Random Dice Numbers

Possible duplicate:
random string generation - two generated one after another give identical results

I am writing a simple dice game for Windows Phone 7, which involves rolling two dice simultaneously. Here is my code for the bones:

private int DiceRoll() { int result; Random rnd = new Random(); result = rnd.Next(1, 7); return result; } 

Then I have this code that rolls the dice when the button is pressed:

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

My problem is that both of them get the same result.

Any idea how I can get a rolling algorithm that usually returns different results, but sometimes returns the same?

+4
source share
3 answers

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

As a result, various Random objects created in close sequence by calling the default constructor will have the same initial default values ​​and, therefore, will create the same sets of random numbers. This problem can be avoided by using one random object to generate all random numbers.

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

+11
source

You need to save one Random object and reuse it; every time you create a new Random object, you will effectively reset a sequence of numbers starting in the same place. Store the Random object as a member variable somewhere. You will also want to sow it with a different value each time you run the program - for example, a value based on the system time clock.

+4
source

The overwhelming majority of “random number” tools I've seen do not work well if you select two or more random objects in one application. You allocate a new Random object for each call, and every time they are going to sow something rather weak and, possibly, even identical seeds.

So, generate a single Random object and use it for the duration of your application.

+4
source

Source: https://habr.com/ru/post/1344340/


All Articles