0

我正在制作一个游戏,让你从三个洞穴中选择,每个洞穴里都有一条龙。当我运行这个程序时,它拒绝运行,并说potatocave 是未定义的。我正在使用python 3。我需要知道为什么它不接受定义的potatocave,我做错了什么,以及是否有更简单的方法来做到这一点。

编辑:我再次运行它,它说 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()

PS这不是最终版本,我只是用一个土豆洞作为占位符来弄清楚三个洞穴的概念,而不是我原来的两个。

4

1 回答 1

4

chosenCave好吧,错误消息说明了一切:在您尝试将其与 进行比较时,您尚未定义str(friendlyCave),即第 32 行。


想象一下你是解释者,从一开始就完成你的脚本。你的做法是:

  1. import random, import time, sleep for 3 seconds; 因此,random现在time是公认的名字。

  2. 定义函数displayIntro, chooseCave, checkCave; 这些现在也是指代各自功能的已知名称。

  3. 分配friendlyCavepotatocave。在循环中重新分配后者。

  4. 比较……等等,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-27T21:28:13.160 回答