6

I'm working on Pong in C# w/ XNA.

I want to use a random number (within a range) to determine things such as whether or not the ball rebounds straight, or at an angle, and how fast the ball moves when it hits a paddle.

I want to know how to implement it.

Slateboard
  • 1,031
  • 6
  • 15
  • 31
  • 10
    Shouldn't the angle and speed be determined by how the ball hits the paddle? If you make it random, it seems your users would have a hard time anticipating where the ball is going. – Esteban Araya Jul 10 '10 at 03:12
  • 1
    @Esteban Not if it's Xtreme Pong! – Grokodile Jul 10 '10 at 06:19
  • 1
    In it's present state, the ball rebounds depending on whether or not the paddle is moving when it hits. But if neither paddle moved, the ball would go straight with no variation. I wanted to use a random number to change the angle. – Slateboard Jul 10 '10 at 06:58

6 Answers6

15

Use the Random class. For example:

Random r = new Random();
int nextValue = r.Next(0, 100); // Returns a random number from 0-99
Quartermeister
  • 57,579
  • 7
  • 124
  • 111
  • 4
    It's worth noting that you should only create a *single instance* of Random (per thread). For simple, single-threaded games, making it a `public static readonly` member of the derived Game class is what I usually do. See also Jon Skeet's answer: http://stackoverflow.com/questions/3217651/how-do-i-use-random-numbers-in-c/3218084#3218084 – Andrew Russell Jul 10 '10 at 13:01
8

Unless you need cryptographically secure numbers, Random should be fine for you... but there are two gotchas to be aware of:

  • You shouldn't create a new instance every time you need one. If you create an instance without specifying a seed, it will use the current time as the seed - which means if you create several instances in quick succession, many of them will produce the same sequence of numbers. Typically you create a long-lasting instance of Random and reuse it.
  • It's not thread-safe. If you need to generate random numbers from multiple threads, you should think about having one instance per thread. Read this blog post for more information - but make sure you read the comments as well, as they have very useful information.
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1. Excellent tips; I've seen people get bitten by those time and time again. My favorite is mistake w/ Random is when people instantiate it inside a tight loop and seed it w/ `DateTime.Now` hoping that that will fix the problem. :) – Esteban Araya Jul 10 '10 at 14:14
1
Random rnd = new Random();
rnd.Next(minValue, maxValue);

i.e.

rnd.Next(1,10);
Marko
  • 71,361
  • 28
  • 124
  • 158
1

Use the Random object's Next method that takes a min and max and returns a value in that range:

var random = new Random();    
int randomNum = random.Next(min, max);
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

While you can use the Random class like all the other are suggesting, the Random class only uses psuedo-random number generation. The RandomNumberGenerator, which can be found in the System.Security.Cryptography namespace, creates actual random numbers.

How To Use:

RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] rand = new byte[25]; //Set the length of this array to
                           // the number of random numbers you want
rng.GetBytes(rand);

More Info: http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator(v=VS.80).aspx

Adam P
  • 4,603
  • 6
  • 31
  • 40
  • RandomNumberGenerator is an abstract class. :) Use the RNGCryptoServiceProvider which derives from this class. Nevertheless it still produces "cryptographically strong" random numbers, which is still pseudo random. And according to http://stackoverflow.com/questions/418817/pros-and-cons-of-rngcryptoserviceprovider, RNGCryptoServiceProvider is slower and overkill for this matter. – Ranhiru Jude Cooray Jul 10 '10 at 05:29
  • This will be more random but may have a performance hit, so balance accordingly. You may not need this amount of randomness and it also might not be quite as easy to use as Random – TJB Jul 10 '10 at 05:39
  • I thought I'd just through it out there as an option. To be honest, I probably just use Random as well. – Adam P Jul 10 '10 at 05:57
  • 1
    `RandomNumberGenerator` doesn't generate "actual" random numbers; it's still a PRNG. The numbers generated by `Random` are fine if all you need is stochastic randomness. A cryptographic PRNG just generates numbers that are far harder to predict. – Will Vousden Jul 10 '10 at 06:30
0

Here is my random generator

 private static Random rnd = new Random(Environment.TickCount);

 private int RandomNum(int Lower, int Upper)
{

 return rnd.Next(Lower, Upper);//MyRandomNumber;

}
Smith
  • 5,765
  • 17
  • 102
  • 161