Link to home
Start Free TrialLog in
Avatar of SileNcer
SileNcer

asked on

Random numbers

I'm writting a simple game in which the user has to touch an item that ramdomly moves to a different place on the screen each time it is touched.  Right now the game is incredibly too easy because the object always comes back into the game in a spot very close to the place it was already at.  Here is the code I used:
//begin code
#include <time.h>
time_t seconds;

time(&seconds);
srand((unsigned int) seconds);

xposition = rand() % (HIGH - LOW + 1) + LOW;
yposition = rand() % (HIGH - LOW + 1) + LOW;
//end code
Does anyone know a better way to get a random number that isn't always close to the number it was before?
ASKER CERTIFIED SOLUTION
Avatar of viktornet
viktornet
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SileNcer
SileNcer

ASKER

That made the code look better, but the object is still being ramdomized in a spot close to where it was before.  I was trying to make a Nibbles game (your a worm and you have to eat little blocks.)
I think the problem is that when the worm eats the block, the randomizing seed is too close to the previous in the split second the process occurs. Maybe you can help me now?
Okay, I fixed it!!!  It seems that the x value wasn't really ramdomizing so I just did this:

xposition = rand() % (WIDTH);
yposition = rand() % (HEIGHT);
xposition = rand() % (WIDTH);

By putting in the ramdom x value twice, it worked :) don't know why.  Thanks a lot for your help!!!
Avatar of ozo
Are you doing the srand every time you get a new position?
If so, that's probably the problem.
You should call srand just once at the start, then just repeatedly call rand() without reseeding it again.
That worked!  Yeah, I guess I didn't need that in the function.  Thanks for helping me.