Stupid Randomization...

I made a black jack SDL game just for a quick revision.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void Games::hit()
{
	/* initialize random seed: */
	srand ( time(NULL) );

	int val = rand() % 13 + 1;
	int s = rand() % 4 + 1;

	Card *temp = top;

	if (temp == NULL)
	{
		top = new Card(val,s,NULL);
	}
	else
	{
		while(temp->getlink() != NULL)
			temp = temp->getlink();
		temp->setlink(new Card(val,s,NULL));
	}

	count();
}


I recognized that : If I click hit fast, same card appeared !
Also the value increase for an interval... like you click and get 4 H then you get 7 H after a short interval and re-click.
This is the most common mistake with random numbers in C++.

Only call srand once at the beginning of the program.

The reason for this is that if you call srand with the same input you will get the same sequence of numbers from rand(); time(NULL) returns the time in seconds so if you call srand(time(NULL)); more than once in the same second you always pass the same number to srand and therefore you get the same random numbers.
Last edited on
Topic archived. No new replies allowed.