Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to reproduce a randomly generated level in Python?

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.


2 Answers

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

like image 178
John La Rooy Avatar answered Sep 08 '25 17:09

John La Rooy


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.

like image 30
Justin Smith Avatar answered Sep 08 '25 17:09

Justin Smith