我这里有一些用 Python 3.x 制作的基本游戏的代码。正如您所看到的,局部变量“code1”在我的值之间创建一个随机的两位数,作为我的金库解锁代码的第一部分(稍后在游戏中)。我想要做的是以某种方式存储随机整数,这样如果重新访问特定房间,它将显示该函数第一个输出的随机数,并且不会继续更改,因为这会破坏线索收集的对象。
def corridorOptions():
code1 = random.randint(30,60)
corridorChoice = input('> ')
if corridorChoice == "loose":
delayedPrint("You lift the loose floorboard up out its place." + '\n')
delayedPrint("It shifts with hardly any resistance." + '\n')
delayedPrint("There is a number etched. It reads " + "'" + str(code1) + "'")
干杯,伙计们。
最佳答案
我建议您向 corridorOptions
函数添加一个属性,该属性仅在首次调用该函数时创建一次初始化
from random import randint
def corridorOptions():
if not hasattr(corridorOptions, 'code'):
corridorOptions.code = randint(30, 60)
print("There is a number etched. It reads '{0:02d}'".format(corridorOptions.code))
corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()
输出
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'
关于python - 如何在 Python 中的局部变量中存储随机整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26005274/