简体   繁体   中英

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.

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.

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 . ;)

当您想要另一个级别时,您应该首先创建另一个 levelRandom 对象,并将该对象提供给级别生成器以生成级别(如果您正在使用)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM