gpt4 book ai didi

Python - 剪刀、布和石头游戏

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:23 26 4
gpt4 key购买 nike

所以,我正在用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com