【发布时间】:2020-06-20 15:34:07
【问题描述】:
我刚刚用 Python 写了一个“石头、剪刀、纸”游戏,但它似乎无法正常运行。
我一直在搜索互联网,发现了许多不同的、更好的代码编写方法。尽管如此,我想知道为什么我的代码没有根据计算机生成的随机选择检查用户输入的原因。每次用户输入一个选项(只要它是有效的),结果就是平局。
我认为这与 while 循环有关,但我不知道是什么。
import random
def correct_format(x):
x = x.upper()
if x == "ROCK" or x == "PAPER" or x == "SCISSORS":
return True
else:
return False
def pc_choice():
number = random.randint(1,3)
if number == 1:
return "ROCK"
elif number == 2:
return "PAPER"
else:
return "SCISSORS"
def game():
your_choice = input("Rock, paper, or scissors? ")
pc_random = pc_choice()
print("The PC has chosen " + pc_random.lower())
print("You chose " + your_choice.lower())
while not correct_format(your_choice):
your_choice = input("Enter a valid option: ")
else:
if your_choice == "ROCK":
if pc_random == "SCISSORS":
print("You win!")
elif pc_random == "PAPER":
print("You loose")
elif your_choice == "SCISSORS":
if pc_random == "PAPER":
print("You win!")
elif pc_random == "ROCK":
print("You loose")
elif your_choice == "PAPER":
if pc_random == "ROCK":
print("You win!")
elif pc_random == "SCISSORS":
print("You loose")
else:
print("It's a tie!")
game()
【问题讨论】:
-
欢迎来到 StackOverflow!请阅读Why is "Can someone help me" not an actual question
-
您的代码接受小写作为有效输入,然后在 ifs 中与大写进行比较。示例输入将有助于澄清这一点。
标签: python