[英]How do I make my basic Rock/Paper/Scissors game with fewer lines of code?
[英]How can I make my code for a game of Rock, Paper, and scissors less redundant?
我必须在摇滚,纸张和剪刀游戏上做一个项目,到目前为止我的代码是游戏的完整代码,但我的教授不喜欢它,因为它太冗余了。 反正有没有缩短它或使它更简单?
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没有输出
我建议使用模数运算符并枚举您的选择。 (rock(0)=>论文(1)=>剪刀(2))
获胜条件是user_choice - 机器人选择%3 == 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:":
一种可以减少冗余的方法是,不是使用所有if else语句,而是创建一个函数,该函数将响应发送给谁,而不是为每个组合键入每个方案。
您可以参数化打印文本:
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,并总结机器人和玩家的选择,你会发现一个模式。 模运算符起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.