2013-03-08 18 views
1

現在我從這個網站做教程「龍之王國」 http://inventwithpython.com/chapter6.html如何使用2個迴路,如果是假的,重複的程序indefinetely

我明白這一切都稍微做什麼,但不是我的問題。最後,我想添加一些代碼,如果玩家說不,它說,因爲我目前擁有它,「太差了*!」並回到程序的開始。我已經做到了這一點,但一旦它經歷了第二次,我得到了是否要再次嘗試的輸入,無論你是否輸入yes或no,它只是結束程序。我嘗試了while,if/else,while的多種組合,而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() 
+1

不需要粗口語言 – 2013-03-08 20:51:45

+0

請將代碼減少到問題的根本部分。 – Trinimon 2013-03-08 21:12:40

+0

對不起,我張貼了我的代碼,但指出,雖然你的審查制度更多地冒犯了我。 – 2013-03-08 21:51:10

回答

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在詢問輸入時將顯示字符串參數。

+0

是的,這工作謝謝你! – 2013-03-08 22:09:19

相關問題