所以,我用 python 制作这个游戏。问题是,剪刀、布和石头可以有不同的组合,比如石头和布、石头和剪刀等等。那么我该如何在不执行大量 elif 语句的情况下做到这一点。
import random
random_choice = ["Scissors", "Paper", "Rock"][random.randint(0, 2)]
player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in ["Scissors", "Paper", "Rock"]:
print("Not valid choice")
raw_input()
exit()
if player_input == random_choice:
print("You both choose %s" % random_choice)
elif player_input == "Rock" and random_choice == "Scissors":
print("You picked Rock and the bot picked Scissors, you win!")
raw_input()
#And so on making heaps of elif's for all the combinations there can be.
那么我们如何制作这个游戏,而不必执行这么多 elif 语句或键入更少的代码。当然必须有一个更好的编程顺序来处理这些类型的事情?
最佳答案
如果你想避免elif
树,你可以使用一个集合来存储所有获胜组合:
import random
# random.choice is a convenient method
possible_choices = ["Scissors", "Paper", "Rock"]
random_choice = random.choice(possible_choices)
# set notation, valid since Python 2.7+ and 3.1+ (thanks Nick T)
winning = {("Scissors", "Paper"), ("Paper", "Rock"), ("Rock", "Scissors")}
player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in possible_choices:
print("Not valid choice.")
raw_input()
if player_input == random_choice:
print("You both choose %s" % random_choice)
elif (player_input, random_choice) in winning:
print("You picked %s and the bot picked %s, you win!" % (player_input, random_choice))
else:
print("You picked %s and the bot picked %s, you lose!" % (player_input, random_choice))
raw_input()
关于Python - 石头剪刀布游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272627/