2014-09-23 48 views
1

我在这里为我在Python 3.x中制作的基本游戏编写了一些代码。正如你所见,局部变量'code1'在我的值之间创建了一个随机的两位数字,用于我保险箱解锁代码的第一部分(稍后在游戏中)。我想要做的是以某种方式存储随机整数,所以如果特定的房间被重新访问,它将显示从该函数中输出的第一个随机数,并且不会保持变化,因为这会打败线索收集的对象。如何在Python中将随机整数存储在局部变量中?

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) + "'") 

干杯家伙。

回答

3

我建议你的属性添加到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' 
的第一个电话被创建时即只初始化 一次
相关问题