I was building a simple example of a class that represents a "dice".
At this point i have: Dice.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <cstdlib>
#ifndef DICE_H
#define DICE_H
class Dice{
public:
Dice(){
faceup = ThrowDice();
}
int getFace(){
return faceup;
}
int ThrowDice(){
faceup = rand()%6+1;
return faceup;
}
private:
int faceup;
};
#endif
And i tested it with ... game.cpp
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <ctime>
#include "Dice.h"
usingnamespace std;
int main(){
int i;
Dice A, B;
for(i=0; i<10; i++){
A.ThrowDice();
cout << A.getFace() << endl;
}
}
The problem is that i get always the same numbers.
How can i make the number generation more random without complicating too mush (because that is not the main subject here)?
It is recommended that the RNG be seeded only once to generate "better" RNGs.
The above works, though I still would advocate moving the srand() to main() because now only Dice can call srand() in the entire application (which might not be a problem for the above application, but then consider a larger application that has a Coin class and a Flip() method -- now does Dice init the RNG, or does Coin, or both, or neither?). I don't think it should be Dice's responsibility to do that. In a truly object oriented, flexible architecture I would allow the user to construct a Dice with a random number generator function (using rand() as the default) along the same lines as the random_shuffle() standard algorithm.
I will use srand() in main, because otherwise i will be running away from my initial idea.
One of this days, with a little more time, i will try adding a "shuffle" method to the class so that who decides to use the class as not to worry about about the way random numbers are generated.