Skip to main content
 首页 » 编程设计

python之石头剪刀布游戏,无限循环

2024年09月07日8zhoujg

import random 
 
options = ['Rock','Paper', 'Scissor'] 
npc = random.choice(options) 
 
print('Hello') 
print('We are about to play Rock,Paper,Scissors.') 
 
while True: 
  npc = random.choice(options) 
  player = str(input('Please declare your weapon: ')).capitalize() 
  if (player == npc): 
    print('Your choice: ', player) 
    print('npc choice: ', npc) 
    print('Oopsie looks like we have a tie!') 
    print('Lets Try again!') 
    continue 
  if (player != 'Rock') or (player != 'Paper') or (player != 'Scissor'): 
    print('Poo Poo, that is not a valid option! Please try again!') 
    continue 
  if ((player == 'Rock') and (npc == 'Scissor')) or ((player == 'Scissor') and (npc == 'Paper')) or ((player == 'Paper') and (npc == 'Rock')): 
    print('Your choice: ', player) 
    print('npc choice: ', npc) 
    print('You win!') 
    break 
  if ((player == 'Rock') and (npc == 'Paper')) or ((player == 'Scissor') and (npc == 'Rock')) or ((player == 'Paper') and (npc == 'Scissor')): 
    print('Your choice: ', player) 
    print('npc choice: ', npc) 
    print('You lose!') 
    break 

它一直打印出 it's a Tie 并且不会显示任何其他结果。我刚刚开始编程。任何输入将不胜感激!

编辑:循环已解决。

这是根据请求的示例输出:

   Output: Hello 
           We are about to play Rock,Paper,Scissors. 
           Please declare your weapon: rock 
           Your choice:  Rock 
           npc choice:  Paper 
           You lose! 

请您参考如下方法:

这一行

if (player != 'Rock') or (player != 'Paper') or (player != 'Scissor'): 
如果没有领带,

将始终为 True。改成

if player not in options: 

改进代码的一些建议

您可以删除所有 if 中的 ()。这个

if (player == npc): 

与

相同
if player == npc: 

您还应该使用 if/elif/else 而不是仅使用 if。这将使 continue 的使用变得不必要。

编辑:改进版本:

import random 
 
options = ['Rock','Paper', 'Scissor'] 
npc = random.choice(options) 
 
print('Hello') 
print('We are about to play Rock,Paper,Scissors.') 
 
while True: 
  npc = random.choice(options) 
  player = str(input('Please declare your weapon: ')).capitalize() 
  if player == npc: 
    print('Your choice: ', player) 
    print('npc choice: ', npc) 
    print('Oopsie looks like we have a tie!') 
    print('Lets Try again!') 
  elif player not in options: 
    print('Poo Poo, that is not a valid option! Please try again!') 
  elif (player == 'Rock' and npc == 'Scissor') or (player == 'Scissor' and npc == 'Paper') or (player == 'Paper' and npc == 'Rock'): 
    print('Your choice: ', player) 
    print('npc choice: ', npc) 
    print('You win!') 
    break 
  else: 
    print('Your choice: ', player) 
    print('npc choice: ', npc) 
    print('You lose!') 
    break