I have a program that rolls two die. The die are objects created from the Dice class. The Dice class contains a method that returns a random number between 1 and the number of sides that the dice contains. Like so:
class Dice
{
//field
private int sides;
private Random rand = new Random();
//Constructor omitted for brevity
//public method to roll the dice.
public int rollDie()
{
return rand.Next(sides) + 1;
}
}
This works just fine for one dice. However, when I create two die and run both of their rollDie methods at the same time, I always receive the same number between the two die objects. For example:
Dice dice1 = new Dice(6); //created two die with 6 sides each.
Dice dice2 = new Dice(6);
dice1.rollDie(); //problem functions
dice2.rollDie();
those two functions will always return the same number, i.e. (1,1), (2,2), etc... never parting from this pattern.
From my research, I have concluded that the random object is creating a random number from the system's time and because the two methods are performed at nearly the same exact moment, they are returning a random number from the same seed. This is obviously a problem because it is far from reality.
The only solution I have tried so far, and the only one I can think of, was to define my own seed for each Dice object to be used in my Random object, but that seems to return the same number each time the rollDie method is called between each time the program is run (i.e. it will return (2, 5), (1, 3) every time the program is run with a seed of 1 and 2, respectively).
The question I have is if there is any way to prevent the two objects from returning the same number as the other?