2017-02-24 21 views
0
def playAgain(): 
    b = input('Do you want to play again? y/n') 
    if b == ('y'): 
     def startGame(): 
      startGame() 
    else: 
     print('Goodbye!') 
     time.sleep(1) 
     sys.exit() 
import random 
import time 
import sys 

global shots 
shots = 0 


while shots <=5: 
    chanceofDeath =random.randint(1,6) 
    input('press enter to play Russian roulette.') 
    if chanceofDeath ==1: 
     shots = shots + 1 
     print (shots) 
     print('You died.') 
     time.sleep(1) 
     playAgain() 
    else: 
     shots = shots + 1 
     print (shots) 
     print ('click') 


    if shots == 5: 
     print('You won without dying!') 
     time.sleep(1) 
     playAgain() 

當我運行該程序時,當它要求再次播放或不播放時,如果您選擇yes,它將起作用,但會從最後一次拍攝開始。例如,如果您在第二次拍攝時死亡並再次播放,而不是重新開始,那麼它將立即從3開始。我如何使照片每次都重置?如何使每次都重置全局值?

回答

0

爲什麼它從最後一槍繼續的原因是因爲你從來沒有真正把「槍」到0這段代碼:

import random 
import time 
import sys 

global shots 
shots = 0 

是隻跑了一次,這意味着鏡頭從未分配回0。


你想要的是,如果用戶選擇再次上場,「出手」變量應重新設置爲0。您可以編輯您的playAgain()函數,如果用戶想再次發揮返回TRUE。例如:

def playAgain(): 
    b = input('Do you want to play again? y/n') 
    if b == ('y'): 
     return True 
    else: 
     print('Goodbye!') 
     time.sleep(1) 
     sys.exit() 

這使您可以檢查用戶是否想要在主while循環,並設置「鏡頭」再次發揮到0這樣的:

if playAgain(): 
    shots = 0 

另外,作爲拍攝聲明除了任何函數外,while循環是唯一使用它的東西,它不需要被定義爲全局變量。

修訂的計劃

def playAgain(): 
    b = input('Do you want to play again? y/n') 
    if b == ('y'): 
     return True 
    else: 
     print('Goodbye!') 
     time.sleep(1) 
     sys.exit() 

import random 
import time 
import sys 

shots = 0 


while shots <=5: 
    chanceofDeath =random.randint(1,6) 
    input('press enter to play Russian roulette.') 
    if chanceofDeath ==1: 
     shots = shots + 1 
     print (shots) 
     print('You died.') 
     time.sleep(1) 

     if playAgain(): 
      shots = 0 

    else: 
     shots = shots + 1 
     print (shots) 
     print ('click') 

    if shots == 5: 
     print('You won without dying!') 
     time.sleep(1) 

     if playAgain(): 
      shots = 0 

而且我不確定你想你的代碼做以下:

def startGame(): 
    startGame() 

希望這有助於

相關問題