# Thread: Random Numbers in Allegro.

1. ## Random Numbers in Allegro.

I need to generate random numbers for a function in my game. If the number generated is even the player gets an item, if its odd it fails. At the moment my character needs to cut down some wood. I tried this:
Code:
```                 A:
if(key [KEY_ENTER])
{
(srand(static_cast<unsigned>(time(0))));
while(true)
{
rand()%1+1;

if(rand()%2==0)
{
textprintf_ex(backbuffer, font, 3, 450, makecol(255, 255, 255), 0, "You obtain a piece of wood!");
wclvlxp+=10;
}
else if(rand()%2==1)
{
textprintf_ex(backbuffer, font, 3, 450, makecol(255, 255, 255), 0, "You fail cutting the tree.");
goto A;
}
}
}```
but after i go to the tree and click enter, the game freezes. Anyone know how to fix this?

2. Fix things like say the indentation?

Or the poor use of goto to escape a while loop ?

Or what is this!?
> rand()%1+1;

rand() % 2 (on some machines) has been known to alternate 0,1,0,1,0,1,0,1 (ad infinitum)

3. Originally Posted by Salem
Fix things like say the indentation?

Or the poor use of goto to escape a while loop ?

Or what is this!?
> rand()%1+1;

rand() % 2 (on some machines) has been known to alternate 0,1,0,1,0,1,0,1 (ad infinitum)
Thats something I recovered from a text based game I made long ago. The concept is the same.
How can I generate random numbers correctly in Allegro?

4. rand()%1 + 1 isn't very random, being guaranteed to be constantly 1.

Search the FAQ on random numbers.

5. Originally Posted by godly 20
Thats something I recovered from a text based game I made long ago. The concept is the same.
How can I generate random numbers correctly in Allegro?
Try using x = (rand() %10) & 1); Which will give you 0 or 1 but not as an alternating sequence.

Also when doing things like you listed above... generate 1 random number at the top and act on it... otherwise you're likely to get some truly weird stuff going on.

6. Originally Posted by CommonTater
Try using x = (rand() %10) & 1); Which will give you 0 or 1 but not as an alternating sequence.

Also when doing things like you listed above... generate 1 random number at the top and act on it... otherwise you're likely to get some truly weird stuff going on.
I did this:
Code:
```int r;
if(key [KEY_ENTER])
{
r=(rand()%10) & 1);
if(r%2==0){
textprintf_ex(backbuffer, font, 3, 450, makecol(255, 255, 255), 0, "You get some wood!");
wclvlxp+=10;
}```
but it doesn't compile. Help!

7. Sorry, I don't fancy playing a game of "guess the error messages", especially since what you post won't compile.
So you're just going to have to tell us.

8. Simple bracketing mismatch... you should be able to spot these easily...

Code:
`  r=(rand()%10) & 1;`

9. ## .

sort out your naming conventions.. it will save you a lot of pain! wxyyjzkcl = 10 Or whatever you wrote, is a bad idea :-)