I'm trying to make a Tetris game using the SDL-library. When a new shape appears I want it to be random, so therefore I've tried to make a function that takes a takes a random number between 0 to 4, which is later used to decide what shape that will appear. Here's the function so far:
int EventHandler::setShapeType() {
if (m_seeded == false) {
srand(time(NULL) * SDL_GetTicks()); //SDL_GetTicks returns the number of miliseconds since the SDL_library was initialized
m_seeded = true;
}
int shapeType = (int) (((double) rand()/RAND_MAX) * 4.999);
cout << shapeType << endl;
return shapeType;
}
m_seeded is a method variable in EventHandler and is set to false in the constructor, so the first if-statement only runs once.
As you can see the function is not complete yet, and the printing of shapeType is solely there for debugging purposes, but so far it should atleast be able to generate a random number... Which it doesn't seem to do. In my main function I made a 10000 iteration loop in which counted how often every number between 0 to 4 was returned, and afterwards printed out the final result as percentage relative to the maximum number of iterations. Here's the result:
- Zero: 29.8
- One: 23.9
- Two: 19.2
- Three: 14.7
- Four: 12.4
Now, I thought that for 10000 iterations every number would appear around the same number of times, but they don't! With small differences, this is the result I get every time. I know that rand() in fact just takes numbers from a premade list, and that the "randomness" comes from what seed you use, but shoudn't I get more varied results than what I'm getting? Well, I'm lost, I'd love some help on this.
Aucun commentaire:
Enregistrer un commentaire