2013-01-01 44 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)。