Possible Duplicate:
How often should I call srand() in a C++ application?
I am trying to implement rolling multiple dice but with my code, even if i create 2+ dice, they always seem to roll the same number. Here’s my code:
Dice::Dice() {}
void Dice::roll()
{
srand(time(0));
setFaceValue((rand() % MAX_FACE_VALUE + 1));
}
int Dice::getFaceValue()
{
return currentFaceValue;
}
void Dice::setFaceValue(int value)
{
currentFaceValue = value;
}
If I program this into my driver, i get the same number 3 times.
int main()
{
Dice d1, d2, d3;
d1.roll();
cout << d1.getFaceValue() << endl;
d2.roll();
cout << d2.getFaceValue() << endl;
d3.roll();
cout << d3.getFaceValue() << endl;
}
I suspect your ‘seed’-ing the RNG uses a time scale that changes slower than how soon your objects b1 – b3 are created; i.e. your time(0) call doesn’t change as fast as b1 – b3 are created and call their roll() method.
You can either use, 3 different seed times in the beginning, at object creation time, ensuring a different RNG or use a functions of 1 RNG to make 1-to-1 valued mappings for extracting more RNG numbers.
So in one word go-slow! Adding sleep() calls between the invocations could change things.