我確實定義了字典,但它一直說字典「房間」沒有定義。如何在課堂上使用字典?它顯示字典沒有定義
首先,我認爲這是因爲字典是在課外,但是當我把它放在課堂上時,它仍然顯示相同的信息。
那麼我想知道如何在課堂上參考一本字典? 感謝第一個答案,我已經試過self.ROOMS,它的工作。但是如果我有很多字母,我必須把它們全部放在方法init ??但推薦在「學習python的難題」中,我們最好不要把這麼多的東西放在init
代碼附在這裏,而不相關的部分已經最小化了。
from sys import exit
from random import randint
class Game(object):
def __init__ (self, start):
self.quips = ['You died.you kinda suck at this.', 'Nice job, you died...jackass.',
"Such a luser.",
'I have a small puppy that\'s bettr at this.']
self.start = start
def play (self):
next = self.start
while True:
print "\n--------"
room = ROOMS[next]
next = room()
def death(self):
print self.quips[randint(0,len(quips)-1)]
exit(1)
def central_corridor(self):
action = raw_input(">")
if action == "shoot!":
return 'death'
elif action == "dodge!":
return 'death'
elif action == "tell a joke":
return 'laser_weapon_armory'
else :
print "DOES NOT COMPUTE!"
return 'central_corridor'
def laser_weapon_armory(self):
code = "%d%d%d" %(randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("[keypad]>")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]>")
if guess == code:
return 'the_bridge'
else:
return 'death'
def the_bridge(self):
action = raw_input("> ")
if action == "throw the bomb":
return 'death'
elif action == "slowly place the bomb":
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
def escape_pod(self):
good_pod = randint(1,5)
guess = raw_input("[pod#]> ")
if int(guess) != good_pod:
return 'death'
else:
exit(0)
ROOMS = {
'death' : death,
'central_corridor' : central_corridor,
'laser_weapon_armory' : laser_weapon_armory,
'the_bridge' : the_bridge,
'escape_pod' : escape_pod
}
a_game = Game("central_corridor")
a_game.play()
也許'自我。 ROOMS'? – akonsu
如果您將ROOMS字典移動到頂部,那麼會發生什麼?就在您的init方法下並將其稱爲'self.rooms'? – souldeux
@akonsu'self.ROOMS'因爲它不是一個實例變量而不起作用,所以OP需要做'Game.ROOMS'來代替。 –