龙游戏不工作,说定义变量是undefined
问题描述:
我正在制作一个游戏,你可以从三个洞穴中选择一个,每个洞穴都有一条龙。当我运行这个程序时,它拒绝运行,并且说potatocave没有定义。我正在使用python 3.我需要知道为什么它不接受potatocave的定义,我做错了什么,以及是否有更简单的方法。龙游戏不工作,说定义变量是undefined
编辑:我再次运行它,它说selectedCave是未定义的。 回溯错误说:
Traceback (most recent call last):
File "C:\Python33\Projects\Dragon.py", line 32, in <module>
if chosenCave == str(friendlyCave):
NameError: name 'chosenCave' is not defined
import random
import time
time.sleep (3)
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see three caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. Another dragon')
print('is greedy and hungry, and will eat you on sight.')
print('The last dragon is a Potarian and gives free potatoes.')
def chooseCave():
cave = ''
while cave != '1' and cave != '2' and cave != '3':
print('Which cave will you go into? (1, 2 or 3)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 3)
potatocave = random.randint(1, 3)
while potatocave == friendlyCave:
potatocave = random.randint(1, 3)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
elif chosenCave == str(potatocave):
print ('Millions of potatoes rain from the sky.')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
P.S这不是最终版本,我只是用一个土豆洞穴作为占位符弄清楚三个洞穴,而不是我原来的两个概念。
答
那么,错误消息说,这一切:你还没有您要比较它str(friendlyCave)
的那一刻,即行32
定义chosenCave
试想一下,你的解释和从一开始就通过你的脚本工作。你的行动方针是:
import random
,import time
,sleep for 3 seconds
; 作为结果,random
和time
现在是公认的名称。定义函数
displayIntro
,chooseCave
,checkCave
;那些现在也称为相关功能的已知名称。指定
friendlyCave
和potatocave
。在循环中重新分配后者。比较
chosenCave
到str(friendlyCave)
...等等,什么chosenCave
?
但是,随着DSM笔记,如果线28-37被缩进作为checkCave
功能的身体的一部分,一切都只是正常工作:
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 3)
potatocave = random.randint(1, 3)
while potatocave == friendlyCave:
potatocave = random.randint(1, 3)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
elif chosenCave == str(potatocave):
print ('Millions of potatoes rain from the sky.')
else:
print('Gobbles you down in one bite!')
如果你仍然有错误发布回溯太:)以便我们可以看到它说的是这样的行:) – 2013-04-27 16:11:52
您的缩进看起来不对。这真的是它在代码中的外观吗? – DSM 2013-04-27 16:27:39