如何使用python在此代码中循环Rock,Paper,Scissors?

时间:2013-01-01 20:23:49

标签: python python-3.x

这是代码......

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退出。

4 个答案:

答案 0 :(得分:3)

使用循环可以控制游戏何时结束。

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

在循环结束时,它会检查游戏是否结束。如果是,则循环退出并运行循环后的任何代码。程序就存在了。

答案 1 :(得分: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:
     ...

答案 2 :(得分:1)

它应该像这样的循环一样简单。

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

答案 3 :(得分:0)

使用defs和类重写代码。这会容易得多。你需要循环。

我从头开始为你编写完整的游戏。 这里:http://codepad.org/Iy6YFW0H

阅读代码并了解其工作原理。随意使用它。顺便说一句,它在Python 2.x中(对不起,我不使用Python 3)。