XNA 101 .Net

Learn how to program in C# while writing games in XNA Game Studio 3.0!
Our upcoming Silverlight book for beginners (includes a great chapter on game development in Silverlight!) Hello! Silverlight 2 with Dave Campbell, available online now!



Pages

Recent posts

Navigation

Archive

Blogroll

    Tampa Divorce Lawyer

    North of Tampa in Lutz, Florida. A Tampa Divorce Lawyer focusing on family, divorce, and real estate law.

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    Lesson 14: Random Thoughts

    Random numbers are very important to game development. This lesson introduces how to use random numbers in your program.

    As usual, we start where the last lesson left off.

    Complete source code for lesson 14: http://www.bluerosegames.com/xna101/lessons/XnaLesson14.zip 

    In most games, the way the game behaves depends on a few factors. Of course one of these is the input from the user who is playing the game via the keyboard, mouse, joystick or game pad. Another is some standard patterns that enemies or other game elements follow based on the situation. However if a game only relied on these factors, the game would get boring quickly since it would always behave in a similar way. A third factor to how a game behaves is randomness. Whether it's the shape of the next piece in a tetris game, or the little unpredictable behaviors of a boss at the end of a Super Mario level, randomness is an important factor in most games.

    The .Net Framework provides a class to C# which generates pseudo random numbers. These numbers are not true random numbers, since the numbers still follow a pattern, but the pattern is so huge and varied that the numbers appear to be random and are uniformly distributed across a range if run through enough iterations. This class, appropriately, is the Random class.

    In our MyFirstGame program, let's use the Random class to control the initial velocity of the bouncing balls.

    First we need to create an object of type Random. Let's do this in the Game1 class, so that it is available to all members of the Game1 class. We don't want to create an instance of the Random class each time we need a random number, both for speed reasons and it could impact how random our numbers are.

    So at the top of the Game1 class definition block with the rest of our Game1 Field definitions, add the following:

    Random rand = new Random();

    Now this statement is a bit different than what we've done in the past. As an alternative to instantiating the Field in the constructor, you can do what is called Field Initialization. In C#, Field Initialization occurs before the constructor is executed. It is simpler to initialize an object this way if certain conditions are met:

    • The Field's constructor must not require any data from any other Fields or any non-constant data.
    • The Field's constructor must not be able to throw an error. This is because there is no way to handle that error properly. If the constructor can throw an error, it is better to instantiate the object in the constructor.

    One of the key parts of the Random class is what is referred to as a seed value. If you initialize a Random object with the same seed value, you will get the same sequence of random numbers every time. If a seed value is not passed in to Random's constructor, the seed value is generated from the system clock, giving a seed value that is going to be different each time unless 2 Random objects are created in the same clock cycle. This can happen on high performance equipment, but since we are only creating one Random object we don't really need to worry about this.

    So now to generate the random numbers. The Random.Next() method has 3 overloads, or 3 different sets of arguments that it can accept. Overloaded methods have the same method name but have different arguments that are passed into the method. They must differ by data type, number of arguments, or both.

    • If Random.Next() is called with no arguments, the result is a non-negative random number greater than or equal to zero, and less than 2,147,483,647.
    • If one argument is passed in, the result is a non-negative random number greater than or equal to 0, and less than the value in the argument.
    • If two arguments are passed in, the result is a random number greater than or equal to the first number, and less than the second.

    Note that for the Random.Next() methods, in the case of the lower bound, or the minimum value returned, the call is inclusive, meaning the value returned can be equal to the lower bound, and in the case of the upper bound, the call is exclusive. The number returned will always be less than, but not equal to, the upper bound. When dealing with ranges, I will often refer to the lower bound and the upper bound. The values equal to and near (slightly larger or smaller than) the lower and upper bounds are called boundary conditions, and are the source of a large percentage of bugs in programs. When building test cases for applications, special attention should be placed on creating test cases for all of the boundary conditions.

    In this particular case, we will use the third overload of Random.Next() with a minimum value of 2, and a maximum value of 11, which will generate numbers between 2 and 10.

    In the Game1.Initialize() method, change the following statement:

    ball2.Velocity = new Vector2(10f, 5f); 

    to:

    ball1.Velocity = new Vector2(rand.Next(2, 11), rand.Next(2, 11)); 
    ball2.Velocity = new Vector2(rand.Next(2, 11), rand.Next(2, 11)); 

    As part of each call to rand.Next(), the seed is updated automatically inside the rand.Next() call so that the next value generated (on the next call to rand.Next()) will be based on that seed. Run the program again a few times and see that each time the balls move at different speeds.

    Posted: Nov 14 2008, 10:52 by Bill Reiss | Comments (3) RSS comment feed |
    • Currently 5/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5
    Filed under:

    Comments

    Add comment


     

      Country flag

    biuquote
    • Comment
    • Preview
    Loading