[英]How do I make my basic Rock/Paper/Scissors game with fewer lines of code?
I built this simple rock/paper/scissor game by watching some tutorials.我通过观看一些教程构建了这个简单的石头/纸/剪刀游戏。 Everything is working fine.
一切正常。 The issue is that I want to implement something where if the user and the computer choose the same word, then it should say something like "draw."
问题是我想实现一些东西,如果用户和计算机选择同一个词,那么它应该说像“画”这样的东西。
I could go ahead and add a bunch of "if" and "else" statements, but I don't want that.我可以继续添加一堆“if”和“else”语句,但我不希望这样。 Can you guys think of any other way to implement that with fewer lines of code?
你们能想到用更少的代码行来实现它的任何其他方法吗?
#Simple rock, paper and scissor game
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
if user_pick.lower() == "q":
print("You quit.")
break
elif user_pick not in options:
print("Please enter a valid input.")
continue
random_number = random.randint(0, 2)
computer_pick = options[random_number]
print("The computer picked", computer_pick)
if computer_pick == "rock" and user_pick == "scissors":
print("You lost!")
computer_wins += 1
elif computer_pick == "paper" and user_pick == "rock":
print("You lost!")
computer_wins += 1
elif computer_pick == "scissors" and user_pick == "paper":
print("You lost!")
computer_wins += 1
else:
print('You win!')
user_wins += 1
You could use a dictionary to map which choices beat each other.您可以使用字典来映射哪些选择相互竞争。 This will enable to you make the conditional part of the code, which determines who wins, more concise.
这将使您使决定谁获胜的代码的条件部分更加简洁。 It is also more easily expanded to rock-paper-scissors variants with more options, without the need for many more conditional statements.
它也更容易扩展到具有更多选项的石头剪刀布变体,而不需要更多的条件语句。
#Simple rock, paper and scissor game
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
beaten_by = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
while True:
user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
if user_pick.lower() == "q":
print("You quit.")
break
elif user_pick not in options:
print("Please enter a valid input.")
continue
random_number = random.randint(0, 2)
computer_pick = options[random_number]
print("The computer picked", computer_pick)
if user_pick == computer_pick:
print("Draw!")
elif user_pick == beaten_by[computer_pick]:
print("You lost!")
computer_wins += 1
else:
print("You win!")
user_wins += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.