如何使我的Rock,Paper和剪刀游戏的代码不那么多余?

问题描述 投票:3回答:4

我必须在摇滚,纸张和剪刀游戏上做一个项目,到目前为止我的代码是游戏的完整代码,但我的教授不喜欢它,因为它太冗余了。反正有没有缩短它或使它更简单?

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()

有时当我输入纸张作为我的输入时,我没有得到输出,代码只是循环回到开头,有没有人知道为什么会发生这种情况?

示例:选择Rock,Paper和Scissors或-1退出:

岩石

你赢了!我选择了剪刀,你选择了摇滚乐,摇滚乐剪刀!

选择Rock,Paper和Scissors或-1退出:

我们并列!我选择纸张而你选择纸张

选择Rock,Paper和Scissors或-1退出:

选择Rock,Paper和Scissors或-1退出:^无输出

剪刀

你输了!我选择了摇滚,你选择了剪刀,Rock beats剪刀

选择Rock,Paper和Scissors或-1退出:

选择Rock,Paper和Scissors或-1退出:

^ theres没有输出

python redundancy
4个回答
1
投票

我建议使用模数运算符并枚举您的选择。 (rock(0)=>论文(1)=>剪刀(2))

获胜条件是user_choice - 机器人选择%3 == 1。


1
投票

如何使我的Rock,Paper和剪刀游戏的代码不那么多余?

首先,我们只能枚举用户赢或抽的选项,并让用户输掉的情况隐含。例如

if user_choice == bot:
    result = "draw"
elif (user_choice == "rock") and (bot == "scissors"):
    result = "win";
elif (user_choice == "paper") and (bot == "rock"):
    result = "win";
elif (user_choice == "scissors") and (bot == "paper"):
    result = "win";
else:
    result = "lose";

其次,由于所有的消息都是基于论坛的 - 在选择中替换我们可以将消息生成与逻辑分开。我没有为此编写代码,因为我没有为你做所有的工作。

第三,我们可以使用字典来表示给定用户选择的胜利条件。就像是。

if user_choice == bot:
    result = "draw"
elif wincondition[user_choice] == bot:
    result = "win";
else:
    result = "lose";

有时当我输入纸张作为我的输入时,我没有得到输出,代码只是循环回到开头,有没有人知道为什么会发生这种情况?

您的代码elif bot == "scissors:":中有一个迷路冒号


0
投票

一种可以减少冗余的方法是,不是使用所有if else语句,而是创建一个函数,该函数将响应发送给谁,而不是为每个组合输入每个方案。


0
投票

您可以参数化打印文本:

player_wins = "You win! I chose {bot_choice} and you chose {player_choice}. {player_choice} beats {bot_choice}!"
player_looses = "You lose! I chose {bot_choice} and you chose {player_choice}. {bot_choice} beats {player_choice}!"

print(player_wins.format(bot_choice="Paper", player_choice="scissors")

你也可以缩短if-else条款。我只是给你一个提示,但如果你把选择“摇滚”,“纸”,“剪刀”看作0,1和2,并总结机器人和玩家的选择,你会发现一个模式。模运算符起作用。

© www.soinside.com 2019 - 2024. All rights reserved.