Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers for dice game [duplicate]

Possible Duplicate:
random string generation - two generated one after another give same results

I am writing a simple dice game for windows phone 7, that involves rolling two dice at the same time. Here is my Dice Roll Code:

 private int DiceRoll()
    {
        int result;
        Random rnd = new Random();

        result = rnd.Next(1, 7);
        return result;
    }

I then have this code that rolls the dice when a button is clicked:

   private void roll_Click(object sender, RoutedEventArgs e)
    {
        roll1 = DiceRoll();
        roll2 = DiceRoll();}

My problem is that both die get the same result.

Any idea how I can get a rolling algorithm that will usually return different results, but occasionally return the same?

like image 915
BigPete Avatar asked Dec 01 '22 03:12

BigPete


1 Answers

The default seed for Random is based on the current time. To quote the documentation,

As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.

That is exactly what you should do: create one instance of Random and use it to generate all your random numbers.

like image 94
Anomie Avatar answered Dec 03 '22 18:12

Anomie