1

现在我正在从这个网站http://inventwithpython.com/chapter6.html做教程“Dragon Realm”

我明白这一切都在做什么,但这不是我的问题。最后我想添加一些代码,如果玩家说不,它会说,正如我目前所拥有的那样,“太糟糕了*!” 并回到程序的开头。我已经让它这样做了,但是一旦它通过第二次,我就会输入你是否想再试一次,无论你输入的是还是否,它都会结束程序。我尝试了 while、if/else、while True 和 False 的多种组合,但我没有得到我想要的结果。我不明白你是怎么坚持下去的?这可能真的很简单,但我无法弄清楚。

这是程序的代码。

import random
import time
def displayIntro():
    print('You are in a land full of dragons. In front of you,')
    print('you see two caves. In one cave, the dragon is friendly')
    print('and will share his treasure with you. The other dragon')
    print('is greedy and hungry, and will eat you on sight.')
    print()
def chooseCave():
    cave = ''
    while cave != '1' and cave != '2':
        print('Which cave will you go into? (1 or 2)')
        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, 2)
    if chosenCave == str(friendlyCave):
        print('Gives you his treasure!')
    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()
4

1 回答 1

1

您可以简单地添加,

if 'n' in playAgain:
    print "too bad"
    playAgain = 'yes'

最后(在你的while循环内)

顺便说一句,这两行可以合并:

print('Do you want to play again? (yes or no)')
playAgain = input()

简单地说:

playAgain = input('Do you want to play again? (yes or no)')

因为input在请求输入时会显示字符串参数。

于 2013-03-08T20:51:34.603 回答