Need help with rand(). :'(

This has been driving me nuts the past few days, I am supposed to spawn random monsters in a text based game (Win32 App) and have them randomly move one unit (x or y co-ordinate) each time the user moves, however each monster seems to be assigned the exact same x and y co ordinates despite me using the rand()%4 function.

Here is just the relevant code. Am I missing something completely obvious? Any help will be greatly appreciated :)

 
//CODE HIDDEN 
Last edited on
Did you call srand at the beginning of your program?

You always, always set your int var's;

Change
1
2
	int rand_x=1; // monsters random x co-ord
	int rand_y=1; // monsters random y co-ord 


and

rand_MOVE, always = 1 so it always goes to else if (rand_MOVE==1)
Last edited on
SamuelAdams - I've private messaged you.

I also forgot to show the main() code so I've just put that in there.
changing the rand_x and rand_y as well as rand_MOVE to 1 didnt seem to work, I think the problem actually lies in the main() code where I've put rand_x=rand()%11; // Random spawn
rand_y=rand()%11; // co-ordinates
this is what seems to assign ALL monsters the same x and y values
To get a different sequence of random numbers from rand() you have to call srand with a different seed each time you run the program. A good seed is the current time.

srand(time(0));

Call srand once in your program and before the first call to rand(). At the beginning of main is a good place.
Last edited on
Thanks for the reply Peter, however I just tried this and it didn't seem to work.
The 3 monsters I have created in the main all still have the exact same x and y start co ords and move together rather than being 'random'
Last edited on
That's because you set rand_x and rand_y before the loop. The value of rand_x and rand_y never change inside the loop so you always pass the same values to the Hero and the three Monster constructor calls.

I don't know if you should actually be creating the hero and the monsters inside the loop. I mean, do you really want a new hero and new monsters each iteration of the loop.

You are not updating the monsters that you have created. If you want monsterMOVE to change the position of a monster you should be using a Monster object inside that function instead of changing rand_x and rand_y which has nothing to do with any monster.
ok got it working, couldn't really understand at first but after going over it that does make sense, thanks a lot.
Topic archived. No new replies allowed.