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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With