2013-01-01 45 views
-2

這裏是代碼...如何在Python代碼中循環使用此代碼中的Rock,Paper,Scissors?

import random 
Rock = '1' 
Paper = '2' 
Scissors = '3' 
print('Welcome to Rock, Paper Scissors! The game of all kids to decide on something. \nIn this game you will have to beat the computer once. \n(Psst if it\'s a draw the start the program again! ;D)\nSo how to play. Well, it\'s simple. Pick 1 for Rock, 2 for Paper and 3 for Scissors. \nSo Rock beats Scissors. Scissors cuts Paper and Paper covers Rock. Got it Lets play') 
player=int(input('Please enter number 1 = Rock, 2 = Paper, 3 = Scissors: ')) 
if player<1 or player>3 except player==9: 
    player=int(input('Invalid number. Please enter number 1 = Rock, 2 = Paper, 3 = Scissors: ')) 
    if player<1 or player>3: 
     print('Well, now you can\'t play this game because you are mucking around. Next time DON\'T!') 
elif player==9: 
    exit() 
else: 
    computer=random.randint(1, 3) 
    print(player,computer) 
    print('Remember Rock = 1, Paper = 2 and Scissors = 3') 
    if player==1 and computer==1 or player==2 and computer==2 or player==3 and computer==3: 
     print('It\'s a draw. =l Restart the game if you want to.') 
    if player==1 and computer==2 or player==2 and computer==3 or player==3 and computer==1: 
     print('Computer wins! You lose. Sorry. =(') 
    if player==1 and computer==3 or player==2 and computer==1 or player==3 and computer==2: 
     print('You have won. Well done. =D') 

我需要循環這樣,當用戶輸入一個錯誤的號碼則然後再次詢問,直到用戶已經適當回答的問題。此外,我需要循環播放該程序,直到用戶按9退出。

+0

如果你知道什麼是循環,在這裏我給你python的'while/for';尋找他們中的任何一個,嘗試編寫循環,然後尋求有關出錯的幫助 – Rubens

+0

你看過http://stackoverflow.com/questions/743164/do-while-loop-in-python ? – Carlos

回答

3

使用循環可以控制遊戲何時結束。

game_over = False 
while not game_over: 
    do_stuff() 
    if some_condition: 
     game_over = True 

在循環結束時,它檢查遊戲是否結束。如果是,則循環退出,循環後的任何代碼運行。然後該程序存在。

1

你可以做的最小的改變,讓這個循環是隻添加while True聲明,並將其餘的遊戲嵌套在它下面。我也會修復你的測試退出案例像這樣...

... 
print('Welcome to Rock, Paper Scissors! ...') 
while True: # loop forever 
    player=int(input('Please enter number 1 = Rock, 2 = Paper, 3 = Scissors: ')) 
    if player==9: # but exit if 9 
     exit() 
    elif player<1 or player>3: 
    ... 
    else: 
    ... 
1

它應該像這樣的循環一樣簡單。

while True: 
    while player not in (1,2,3,9): 
    keep_asking_for_input() 
    if player == 9: 
    break 
    pass 
+0

'end'不是一個有效的關鍵字嗎? – jdi

+0

它不是。對不起,Python/Ruby在那裏混淆了一秒鐘。 – Hbcdev

0

用defs和classes重寫你的代碼。這會容易很多。你需要你while循環。

我已經爲你從頭開始編寫完整的遊戲。 Here:http://codepad.org/Iy6YFW0H

閱讀代碼並理解它是如何工作的。隨意使用它。順便說一句,它在Python 2.x(對不起,我不使用Python 3)。