-2

这是代码...

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

4 回答 4

3

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

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

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

于 2013-01-01T20:32:38.783 回答
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:
     ...
于 2013-01-01T20:34:09.900 回答
1

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

while True:
  while player not in (1,2,3,9):
    keep_asking_for_input()
  if player == 9:
    break
  pass
于 2013-01-01T20:35:31.567 回答
0

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

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

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

于 2013-01-01T21:52:17.343 回答