我正在尝试理解我收到的错误消息(问题主题行)。我怀疑它可能与范围和嵌套逻辑有关。
以下是相关代码块:
class Smaug(Scene):
def enter(self):
print "Smaug is a terrifying huge fire breathing dragon, but you must get the Arkenstone from him for Thorin"
print "In Smaug's cave, the Lonely Mountain, Smaug notices your presence and challenges you to a game"
print "He says \"Guess a number between 1 and 3\""
smaugNum = random.randint(1, 3)
guesses = 0
def guess():
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
guess()
print "Too many failed guesses, you lose!"
return 'death'
这段代码使用引擎运行,引擎是一个类:
class GameEngine(object):
def __init__(self):
self.scenes = {'TheTrolls':TheTrolls(), 'MistyMountainsAndGollum':MistyMountainsAndGollum(), 'Smaug':Smaug(), 'death':death()}
def run(self):
next = 'TheTrolls'
while True:
if next == 'finished':
print "Well done! You won!"
exit(1)
next = self.scenes.get(next).enter()
GameEngine().run()
“游戏”(这是我正在完成的教程)在将guess()函数添加到Smaug()之前确实有效。
但这是输出:
Traceback (most recent call last): File "ex45.py", line 21, in
<module>
GameEngine().run() File "ex45.py", line 18, in run
next = self.scenes.get(next).enter() AttributeError: 'NoneType' object has no attribute 'enter'
我的想法是,在while循环中return 'finished'
可能不是父块的返回?还是我离开了?我是学习者。
答案 0 :(得分:1)
您的问题是代码形式:
if next not in scenes:
scenes.get(next) == None
因此错误:正如消息告诉您的那样,None
没有enter
属性!尝试
next = scenes.get(next)
if next is not None:
next.enter()
else:
print("No more scenes")
break # leave the loop
答案 1 :(得分:0)
您可以从错误中看到self.scenes.get(next)
导致None
。可能有很多原因,但我想这是death()
调用返回无。