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

If you want to see what’s going on in your code, you can step through it one line at a time. While you are in the IDE (Integrated Debugging Environment), press F11 to run one line of code. You will see the current line of code highlighted in yellow.

Keep pressing the F11 key to see how the computer walks through your code and how it skips over elements. This is a great way to see how branching structures work.

Creating a Random Number

In most game situations, the computer plays the opponent or simulates an unpredictable situation. The key to game programming is the idea of random number generation. You can ask the computer to come up with a random number, which you can use to determine how the computer should proceed.

In the Real World

Random number generation is not only for games! You can also use this technique any time you want to simulate uncertainty. Business simulations and testing programs (software designed to test other software) are two types of applications that rely heavily on random number generation. Random numbers also play a key role in a class of programs called neural nets which can often provide answers to otherwise unsolvable problems.

Most programming languages have some sort of built−in random number generation routine. Usually, this is a command or function that returns back a random double value between 0 and 1.

Trap You should know that the numbers aren’t truly random. Instead, they are generated by a complex formula that tries to create numbers as close to purely random as possible. The results are close enough for the purposes of this book.

C# uses a unique but powerful approach to random number generation. It provides a special object named the (surprise!) Random class. This class has the capability to create several kinds of random values, but you will focus on extracting a double value because you can create any other kind you might need from a double.

Introducing the Die Roller

As usual, I’ll show you a program to illustrate what I mean. The DieRoller program featured in Figure 2.9 illustrates a common problem. I want the computer to simulate rolling a six−sided die.

47

Figure 2.9: The program “rolls up” two six−sided dice.

The random object returns a decimal value between 0 and 1, but a standard die has integer values from 1 to 6. The program illustrates how you can go from a 0–1 value to whatever kind of random number you want.

Exploring the Random Object

The random object is different from the objects you have seen so far (the console object and the convert object). In those cases, the objects were already available simply because you are in the System namespace. The random object is also available in the System namespace, but you can’t use it directly. Instead, it must be created as a variable in order to use it. To create a random object named generator (that seems like a good name to me), I used this line of code inside the Main() method:

Random generator = new Random();

The generator is a variable, but it isn’t a string or integer you’ve seen before. Instead, it is a reference to a random object. It is created much like any other variable, but you use the new keyword to specify that the computer will be making an object instead of a simple variable. It’s okay if this confuses you right now. It will make much more sense when you start making objects of your own in Chapter 4, "Objects and Encapsulation: The Critter Program."

Trick Remember, I learned about the random object and its methods by digging around in the online help and the .NET documentation. These are always good ways to learn about new objects that can help you solve problems.

Creating a Random Double with the .NextDouble() Method

After you set up the generator, you can get a double value easily. Use the NextDouble() method to get a double value from the generator. Here’s some code that will create a random object named generator, get a random double value from it, and store that value in a variable named myDouble:

double myDouble;

Random generator = new Random(); myDouble = generator.NextDouble(); Console.WriteLine(myDouble);

The resulting value will be a number from 0 to 1 with a lot of decimal values. This number is nice,

48

but the goal is to simulate a die, which has a value from 1 to 6.

Getting the Values of Dice

The basic problem of random number generation in computer programs is that computers usually create 0–1 numbers, and you almost always need them in another format. Take a look at the code for the Roller program, and you will see how I solved that problem:

using System;

namespace Roller

{

///<summary>

///Demonstrates creation of a random number

///Andy Harris, 11/10/01

///</summary>

class Class1

{

static void Main(string[] args)

{

double raw; double big; double bigger; int die;

Random generator = new Random();

raw = generator.NextDouble(); Console.WriteLine("raw: {0}", raw);

big = raw * 6; Console.WriteLine("big: {0}", big);

bigger = big + 1; Console.WriteLine("bigger: {0}", bigger);

die = (int)big; Console.WriteLine("die: {0}", die);

//do it all in one step

die = (int)(generator.NextDouble() * 6) + 1; Console.WriteLine("another die: {0}", die);

Console.WriteLine();

Console.WriteLine();

Console.WriteLine("Please press enter key to quit");

Console.ReadLine();

} // end main } // end class

}// end namespace

Getting the desired number is not difficult, but it takes some thought. I did it in several steps in the Roller program so that you can follow the process. First, the variable raw simply gets a value from the generator. This number will contain a 0–1 value. In the next step, I multiply raw by 6 to get a variable named big. If raw is 0 (which will almost never happen), 0 multiplied by 6 will be 0. If raw is 1, (which will almost never happen, either), raw multiplied by 6 will be 6. Most of the time (close enough to all the time), the result of raw multiplied by 6 will be larger than 0 and smaller than 6.

For example, if raw is 0.341061992729577, big will be this value multiplied by 6, or 2.04637195637746. If you convert this number to an integer, you will be close to the desired results

49

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