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

pName = pName.Substring(0,8); Console.WriteLine("Changing name to {0}", pName);

}else {

pName = value;

}// end if

}// end set

The set() method examines the incoming value and checks whether it is more than eight characters. If it is, the set() method performs string manipulations to shorten the name (after informing the user of this action). If the incoming value is eight characters or fewer, it is assigned directly to the private variable.

In the Real World

The name restrictions in the following example are silly, but the concept holds true in serious programming. I wrote a program to simulate an air traffic control system. The plane object had a property to take a direction. I used a property to enforce that the direction value be between 0 and 360 because these are the legal direction values in degrees.

Also, because many kinds of input come in as strings, I’ve written properties that accept a string value and convert it into the type I need.

Properties enable you to wrap instance variables in a protective filter of the get() and set() methods so that you have more precise control over the input and output of these properties.

The same kind of technique can be used for any kind of filtering. Suppose that you want all your critter names to start with The Honorable or you want to refuse all names that don’t include a q. No problem! Just use the set() method to designate these restrictions.

Making the Critter More Lifelike

You now know all you need to know to make the critter a lot of fun. By adding a few more variables, properties, and methods, you can re−create the critter featured at the beginning of this chapter. Remember that my original algorithm was to have a critter whose moods change according to the way it is treated. I wanted to achieve this effect as easily as possible.

Adding More Private Variables

I added a couple private variables to the critter, but not to make them properties (at least, not yet), because I wanted the user to interact with them indirectly. Here’s the list of private variables and properties for the final Critter class:

class Critter {

private string pName; private int pFull = 10; private int pHappy = 10; private int pAge = 0;

public string Name { get {

return pName;

96

}// end get set{

if (value.Length > 8){

Console.WriteLine("The name can't be more than 8 characters"); pName = value;

pName = pName.Substring(0,8); Console.WriteLine("Changing name to {0}", pName);

}else {

pName = value;

}// end if

}// end set

}// end name property

The name property and its associated private variable, pName, are identical to the version in the preceding section. However, I added a few new private variables. The pFull variable describes how hungry the critter is. If pFull is zero, the critter is hungry. You’ll see how it works when you look at the new methods in the Critter class. The pHappy determines how happy the critter is. As with the pFull variable, a larger value is better. The pAge variable determines the critter’s age.

Adding the Age() Method

To make the program interesting, I wanted to degrade the critter’s situation slightly each time through the loop, so I added an age() method to the Critter class:

public void Age(){

//handles aging the critter pAge++;

pFull−−;

pHappy−−;

if (pFull < 3) {

//if hungry, accelerate unhappiness pHappy−−;

} // end if

}// end age

The effects of aging on a critter are obvious. The age increases by 1, and fullness and happiness decrease by 1. As an added effect, I decided that hunger would accelerate unhappiness (it works that way with my kids, anyway), so if the critter is hungry, it quickly becomes unhappy.

The Age() method will be added to the Main loop so that the critter ages once per turn.

Adding the Eat() Method

The feed() method gives the user the opportunity to feed the critter. The digestive system of a critter takes little code to reproduce.

public void Eat(){ pFull += 4;

} // end eat

This has the effect of stuffing the critter, by incrementing the value of pFull by 4. Recall that pFull += 4 is just like pFull = pFull + 4;.

97

Adding the Play() Method

The play() method is very similar to the Eat() method, but it changes the happiness level rather than the hunger level. For the sake of variety, I decided that the Play() method should not have quite as strong an effect on happiness as the Eat() method has on hunger.

public void Play(){ pHappy += 3;

} // end play

To give your critter a different personality, you can alter the way the variables are changed. For example, the current design of the critter changes only one variable at a time. During one turn, you can play with a critter or feed it, but you can’t do both. Because each attribute is decremented each time through the loop, the critter’s happiness level goes down during the turn in which you feed it. Of course, you can change this by altering the feed() and play() methods.

Modifying the Talk() Method

The talk() method is the critter’s primary feedback mechanism. Only by asking can you find out how the critter is doing. The talk() method provides all the information about the critter. Here’s my version of the talk() method:

public string Talk(){ string message;

message = "The critter says: \n";

if (pHappy >

5)

{

 

message

+=

"

Hi! My name

is " + Name + "\n";

message

+=

"

I feel happy

today! \n";

}else if (pHappy > 2) {

message += " " + Name + " doesn't feel so good...";

}else if (pHappy > 0) {

message += " " + Name + " is MAD...";

}else {

message += " ...nothing at all, but lays in a heap.";

}// end if

return message; } // end talk

I wanted the critter’s behavior to indicate its status indirectly, so I had it give varying responses, based on its happiness variable. Although a direct readout of the critter’s characteristics would have been more informative, no other type of pet makes it this convenient—neither should the critter. (Of course, you can change this if you like.) I didn’t respond directly to hunger because happiness is affected by hunger, but you can make your critter act the way you want.

Making Changes in the Main Class

The improvements in the Critter class make the Main class much easier and more powerful. The menu method itself doesn’t change at all, but you can finally add responses to all the menu items:

class Menu {

static void Main(string[] args) { bool keepGoing = true;

int choice;

Critter myCritter = new Critter(); myCritter.Name = "George";

98

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