views:

183

answers:

3

I'm making a game which uses procedurally generated levels, and when I'm testing I'll often want to reproduce a level. Right now I haven't made any way to save the levels, but I thought a simpler solution would be to just reuse the seed used by Python's random module. However I've tried using both random.seed() and random.setstate() and neither seem to reliably reproduce results. Oddly, I'll sometimes get the same level a few times in a row if I reuse a seed, but it's never completely 100% reliable. Should I just save the level normally (as a file containing its information)?

Edit:

Thanks for the help everyone. It turns out that my problem came from the fact that I was randomly selecting sprites from groups in Pygame, which are retrieved in unordered dictionary views. I altered my code to avoid using Pygame's sprite groups for that part and it works perfectly now.

+6  A: 

random.seed should work ok, but remember that it is not thread safe - if random numbers are being used elsewhere at the same time you may get different results between runs.

In that case you should use an instance of random.Random() to get a private random number generator

>>> import random
>>> seed=1234
>>> n=10
>>> random.Random(seed).sample(range(1000),n)
[966, 440, 7, 910, 939, 582, 671, 83, 766, 236]
>>> 

Will always return the same result for a given seed

gnibbler
+1  A: 

Best would be to create a levelRandom class with a data slot for every randomly produced result when generating a level. Then separate the random-generation code from the level-construction code. When you want a new level, first generate a new levelRandom object, then hand that object to the level-generator to produce your level. Later, to get the same level again, you can just reuse the levelRandom instance.

Justin Smith
+1  A: 

The numbers generated by a random function are deterministic. Thus, seed with known value and save it. Create a level from the following random numbers. To load the level, simply seed again with the same known value and use the "random" numbers again, which will be reoccurring in the same sequence. This is language agnostic but for Python do mind threading as pointed out by gnibbler.

This exact technique was actually used to create the humongous world of the legendary game Elite. If you are brave, just go check how Ian Bell did it. ;)

mizipzor