Recommended Posts

I know how to use rand() I thought.. but I have a little game AI that has some randomness to its logic I''m using rand() and it works fine I do a srand( time(NULL)) so I can get diffrent each time the game runs but here is the problem.
the AI is in a class and I have three of these monsters loaded but all three are behaving exactly the same for this code.

but for all the AIs they run that secion of code with the same random numbers for each pass. When I trace through the code with debug for each AI this secion gets diffrent random number like I want. The only thing I am think is that rand() depends on the time passed between the last time it was used and all three objects are running this code too close togeter??
HELP

it generates much more random output than rand() and is much faster. the rand() function is used to throw very platform dependand random numbers... e.g. on a pentium3 90% of the numbers generated by rand() are greater than 0x80000000 and a multiple of 2, what might be your problem,,,

Share this post

Link to post

Share on other sites

quote:Original post by Zul Gotcha. In that case, perhaps rand() keeps using the same baseline to generate each "random" number. Check into using srand to change the seed values for rand: srand

That's not his problem.

I think I know what it is. You have three instances of CRomer, right? One for each monster. The problem is that static variable state. A static variable is going to be the same for all instances of the class. So walking through your program, when if (GetTickCount() - ThinkTime > ...) is true, state is assigned a new random number and ThinkTime is reset. However, when Patrol is called for the other monsters, they are going to use the value for the last time state = rand()% 7 was called, regardless of which monster's class it was called in. Here's a short program to demonstrate what I'm talking about:

#include <iostream>#include <string>#include <time.h>

class Class{public: Class() { srand(time(NULL)); } ~Class(){ }

void Print() { std::cout << i_ << std::endl; }

void GetNewRandom(bool b) { static int i = 2;

if (b) i = rand() % 7;

i_ = i; }

private: int i_;};

int main(void){ Class A, B;

std::string s;

do { A.GetNewRandom(true); B.GetNewRandom(false);

A.Print(); B.Print();

std::cin >> s; } while (s != "q");

return 0;}

You see how the same value is always printed out, even thoughclass B should be printing out 2 everytime?

Now to fix it. Just make 'state' a private member variable, init it to 2 in the constructor, and reset it like you already are. Hopefully that is what your problem is and what will fix it.