我要做一个石头剪刀布游戏的项目,目前我的代码是游戏的完整代码,但我的教授不喜欢它,因为它太冗余了。有没有办法缩短它或使其更简单?
import random
while True:
bot = random.choice(["Rock", "Paper", "Scissors"]).lower()
user_choice = input("Choose between Rock, Paper, and Scissors or -1 to exit: \n ").lower()
if user_choice == bot:
print("We tied! I chose", bot," and you chose", user_choice)
elif user_choice == "rock":
if bot == "paper":
print("You lose! I chose", bot," and you chose", user_choice , ", Paper beats rock!")
elif bot == "scissors":
print("You win! I chose", bot," and you chose", user_choice , ", Rock beat scissors!")
elif user_choice == "paper":
if bot == "rock":
print("You win! I chose",bot," and you chose", user_choice , ", Paper beats rock!")
elif bot == "scissors:":
print("You lose! I chose", bot," and you chose", user_choice , ", Scissors beats paper")
elif user_choice == "scissors":
if bot == "paper":
print("You win! I chose", bot," and you chose",user_choice, ", Scissors beats paper")
elif bot == "rock":
print("You Lose! I chose", bot," and you chose", user_choice , ", Rock beats scissors")
else:
print("Invalid Entry, you typed:", user_choice, ", Please try again: ")
if user_choice == '-1':
print("You selected -1 to exit, Goodbye!")
exit()
有时当我输入 paper 作为输入时,我没有得到输出,代码只是循环回到开头,有人知道为什么会这样吗?
例子: 选择剪刀石头布或 -1 退出:
摇滚
你赢了!我选剪刀,你选石头,石头打剪刀!
选择剪刀石头布或 -1 退出:
纸
我们打成平手了!我选纸你选纸
选择剪刀石头布或 -1 退出:
纸
选择剪刀石头布或 -1 退出: ^无输出
剪刀
你输了!我选石头你选剪刀,石头打剪刀
选择剪刀石头布或 -1 退出:
纸
选择剪刀石头布或 -1 退出:
^ 没有输出
最佳答案
我建议使用取模运算符并枚举您的选择。 (石头(0)=> 布(1)=> 剪刀(2))
获胜条件是 user_choice - bot 选择 %3 == 1。
关于python - 如何让剪刀石头布游戏的代码不那么冗余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54914207/