srand screwing with me

This is a discussion on srand screwing with me within the C++ Programming forums, part of the General Programming Boards category; i am in the process of making a small game, and one part of the program is that you are ...

  1. #1
    ...
    ... is offline
    Registered User
    Join Date
    Feb 2002
    Posts
    465

    srand screwing with me

    i am in the process of making a small game, and one part of the program is that you are competing with 24 other 'players' (npcs) for the top score. the winning condition of the game is when you reach the top position, so naturally everyone else has to start out ahead of you. as the game progresses, their scores either raise or lower depending on how good they do (of course, they mostly raise. what fun would it be to win without even doing anything :P ).

    anyway, here is my problem: the npcs start out ahead of you, but each with a random score. their scores continue to fluctuate as the game progresses. i wrote out the code to give them all random scores, and to sort them on the score list and all of that. the only problem is, everytime i went to list the code, all of the npcs had the same score.

    i thought this had to be some bug in another part of my code, so i spent hours playing with different formulae and algorithms, but nothing seemed to solve my problem. it was then that it dawned on me.

    i have been taught to create random numbers in the following fashion:

    Code:
    #include <time.h>
    
    //...
    
    srand(time(NULL));
    x = rand() % 10;
    and that would create a random number from 0 to 10.

    my code creates all of the npc's scores at the same time, and is using the seed for the random number as time... that means, since the computer is able to operate at extremely high speeds, the time doesnt change enough for it to get different random numbers!

    i tested this by adding pauses after each random number (small pauses, mind you).

    at first my output was something like this:

    49
    49
    49
    49
    49
    49
    etc...

    after putting the pauses, it was more like:

    49
    49
    49
    51
    51
    51
    51
    54
    54
    etc...

    so it all boils down to this question:

    is there a different seed to use or a different means of creating random numbers when you have to generate them all at once?
    I came up with a cool phrase to put down here, but i forgot it...

  2. #2
    moi
    moi is offline
    Registered User moi's Avatar
    Join Date
    Jul 2002
    Posts
    946
    only use srand() once before all of your calls to rand() (in program startup). then just call rand().
    hello, internet!

  3. #3
    ...
    ... is offline
    Registered User
    Join Date
    Feb 2002
    Posts
    465
    ah, brilliant!
    I came up with a cool phrase to put down here, but i forgot it...

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21