lundi 27 avril 2015

Reset a random number generator with same seed (C#)

Here's my situation:

I'm making a game in C# which randomizes the positions of all the objects on the screen everytime you begin a new level. To do this I've just declared a

random r = new Random();

I then decided that even though I want to randomize whenever a new level is begun, I want each level to be the same every time.. In other words, the positions of the things on level 1 will always be the same, every time you start the game, and so on for all the other levels.

To do this, I added a seed to the generator:

random r = new Random(mySeed);

This works perfectly - when I exit the game and start it up again, the random positions in level 1 will be the same every time.

However, here's the problem: I understand that when you give the Random object a seed, it uses that seed to generate its list of numbers, which is obviously why all my r.Next()s are the same no matter how many times I re-open the program. BUT, it seems I have to COMPLETELY restart the entire program in order to reset it and get back to the first item in the list again...

In other words, If the player dies during level 1, you go back to the main menu.. But then when it calls r.Next(), it's of course not going to give me the correct level 1 positions.

I tried to solve this by simply re-constructing the object when you die, for example:

//other death code in here
r = new Random(mySeed);
//back to main menu

But that doesn't seem to make a difference - it'll still continue on with the sequence from where it was before..

So does anyone have a clue how I can point back to the beginning of the random list WITHOUT having to restart the whole program?

Thanks!




Aucun commentaire:

Enregistrer un commentaire