locked
Problems with random numbers

    Question

  • I am experiencing MAJOR problems with random numbers in my game. I am generating map layouts, items and monsters by random, but I get the EXACT same number sequence with each different run of the game. I have tried rand() and srand() as well as the Boost uniform_int_distribution, but nothing works...Please help.

    Thursday, September 4, 2014 6:29 AM

Answers

  • Solved it.

    It seems that srand only seeds rand for the current thread. I had to perform srand in my loader thread as well, since that is where I do all the random generation of map layouts etc.

    Thursday, September 4, 2014 8:23 AM

All replies

  • How are you calling this? It sounds like you're using a constant seed. If you always use the same seed then you'll always get the same sequence. This can be very useful for testing, but generally isn't what you want for production. Typically you'll call srand with the current time to get different sequences on different runs.

    See the example for rand:

       // Seed the random-number generator with the current time so that
       // the numbers will be different every time we run.
       srand( (unsigned)time( NULL ) );

    Thursday, September 4, 2014 6:40 AM
    Owner
  • I am seeding at startup, with time(NULL). Does not seem to make a difference. Should I seed each time I want to generate a number instead?
    Thursday, September 4, 2014 6:52 AM
  • Solved it.

    It seems that srand only seeds rand for the current thread. I had to perform srand in my loader thread as well, since that is where I do all the random generation of map layouts etc.

    Thursday, September 4, 2014 8:23 AM