Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

motion forward or back, or perhaps building a snowball. However, if the robot player is out of snowballs, it should immediately make one. If there are snowballs, I used the roller to generate a 0–5 integer. I used a switch statement to determine what the robot player will do. If the robot rolls a 0, it will move closer to the human. If it rolls a 1, it will back away. If it rolls a 2, it will build another snowball. Any other roll will result in a throw.

If the robot successfully hits the player, it modifies the player’s strength parameter.

The easiest way to change the game is to modify the logic in this method. This very simple logic provides an interesting opponent, but one that is easy to beat. To make the program more interesting, you might want to tweak the logic. I suggest some improvements in the challenges at the end of the chapter.

Creating the Main Menu Class

The main menu of the Snowball Fight program handles the overall game logic but passes most of the details to the two fighter classes. It handles most of the actual interaction between the user and the game.

Creating Instance Variables and Main() Method

The setup of the main menu is straightforward. Instance variables in a container class like the main menu generally hold information that your entire program will need.

{

///<summary>

///A snowball fight against a robot opponent

///demonstrates object−oriented programming

///Andy Harris, 12/23/01

///</summary>

class MainMenu

 

{

 

int range;

//distance between fighters

Fighter player;

//human player

RoboFighter opponent;

//robot opponent

bool keepGoing = true;

//controls main loop

static void Main(string[] args)

{

MainMenu mm = new MainMenu();

}

The range variable holds the distance between the adversaries. This value belongs to the menu because it is common to all three classes in the program. I sent the range as a parameter to the throwSnow()and choosePlay() methods.

Creating the Menu’s Constructor

The menu class constructor has two main parts. The first part sets up a few variables and initializes the two opponents, and the second part manages the interactions with the user. First, take a look at the part that initializes all the other objects:

public MainMenu(){ int choice; string name;

122

//set up the contestants Console.Write("What is your name? "); name = Console.ReadLine();

player = new Fighter(name); Console.Write("What's your opponent's name? "); name = Console.ReadLine();

opponent = new RoboFighter(player, name); range = 10;

Choice will hold the human player’s most recent menu selection. The string variable name will be used to get names from the user for the human− and robot−controlled fighters. Because both the fighter classes require a name as part of the constructor call, I had to get name values from the user before instantiating the classes. I set the initial range to 10, which means that neither player will be able to hit the other without moving closer.

Managing the Responses

The main logic of the program consists of analyzing input from the menu. A while loop continues as long as the keepGoing variable remains true. The menu itself will be drawn in the displayMenu() method (described next.) After displaying the menu, the program uses a switch statement to determine what action the player wants to take.

while(keepGoing){

choice = displayMenu(); switch (choice){

case 0: //quit

Console.WriteLine("quitting"); keepGoing = false;

break; case 1:

//make a snowball player.snowballs++; break;

case 2: range−−;

if (range < 0) { range = 0;

} // end if break;

case 3: range++; break;

case 4:

if (player.throwSnow(range)){ Console.WriteLine("You hit {0}", opponent.name); opponent.strength−−;

}else {

Console.WriteLine("You missed {0}", opponent.name);

}// end if

break;

default:

Console.WriteLine("you said {0}", choice); break;

} // end switch

range = opponent.choosePlay(range); checkWinner();

} // end while loop

}// end constructor

123

The displayMenu() method will return back an integer indicating what kind of action the human player wants to make. I used a switch statement to respond to the various options.

Choice 0 on the menu is quit, so if the user wants to exit, I let him or her do so by setting the keepGoing value to false. The next time through the while loop, the program will end.

Choice 1 corresponds with making a snowball, so all I need to do is increment the snowball property by 1. Notice that you can use the special increment and decrement operators (such as ++, −−, and +=) on properties just as you can on more traditional variables.

Choices 2 and 3 deal with changing the range. They are very similar, except that if you move closer, the range will decrease, and if you move farther away, the range will increase. I decided to check for a lower bound when range was decremented because it doesn’t make sense for the range to be less than 0. I wasn’t worried about checking an upper bound because the player cannot win if he or she is too far away to hit.

Hint Whenever you increment or decrement a variable, think about whether you need to implement a boundary−checking routine. It isn’t always necessary, but if you forget it and need it, your code will end up crashing at some inopportune time.

Choice 4 involves throwing the snowball. Most of the snowball−throwing logic lives inside the Fighter class, but I still needed some logic here. The throwSnow() method returns back a Boolean value of true if the snowball hits the mark. If the player hits the robot, the program responds and decrements the robot player’s strength property.

These are the only choices on the menu, but users will be users—they will enter odd things into your program. The default clause should check all these strange inputs. The game design adds a built−in penalty for mistaken input because the human player forfeits the opportunity to move, throw, or make a snowball during the turn. However, the computer opponent can still make a play.

After allowing the human player to make a selection, the robot player has a turn. All the code for managing the robot player’s turn is in its choosePlay() method. Notice that I passed the current range to the choosePlay() method, and it returns the new range after determining what the robot player does.

Checking for a Winner

After both players have an opportunity to slug each other with frozen slush, it is necessary to see whether somebody has won the game. This is done with a call to the custom checkWinner() method. Actually, it checks whether a player has lost and indicates which player has won. It’s easy to figure out:

public void checkWinner(){

if (opponent.strength <= 0){ Console.WriteLine("You win!"); keepGoing = false; Console.ReadLine();

}else if (player.strength <= 0){ Console.WriteLine("You have been defeated"); keepGoing = false;

Console.ReadLine();

}// end if

}// end checkWinner

124

Соседние файлы в предмете Программирование на C++