有没有更好的方法来挑选石头剪刀的获胜者



随意学习python,并决定尝试一下石头剪刀作为一个快速项目。进行得很顺利,但我真的陷入了试图缩短用于比较结果的代码的过程中。

def check_results(ai, self):
if ai == self:
return 'tralf'
if self == 'rock':
if ai == 'paper':
return False
else:
return True
if self == 'scissors':
if ai == 'rock':
return False
else:
return True
if self == 'paper':
if ai == 'scissors':
return False
else:
return True

ai和self,正如你可能猜到的,是电脑选择的,而玩家选择的只是被传进来的。

必须硬编码的一些事情让我非常非常不满意,我花了大约20分钟的时间拒绝这样做,只是尝试随机的东西,看看是否可以缩短它。

我尝试的一件事是,从一个列表中获得两个玩家选择的索引,并通过在一个单独的列表中运行来进行比较。无法让它发挥作用,或者至少无法让它以一种比硬编码更好的方式发挥作用,所以我放弃了,用无聊的方式来做。如有任何帮助,我们将不胜感激。

以可读性和错误检查为代价,可能会出现以下情况:

def did_player_win(player_choice, computer_choice):
choices = ['scissors', 'paper', 'rock']
# The order in which the strings appear in the list is important.
# scissors beats paper
# paper beats rock
# rock beats scissors (wraps around)
return choices[(choices.index(player_choice) + 1) % len(choices)] == computer_choice
player_choice = 'paper'
computer_choice = 'rock'
print(did_player_win(player_choice, computer_choice))

但这并不能成为优秀的源代码。冗长并不可耻(未来的自己会感谢你:(

def did_player_win(player_choice, computer_choice):
choices = {
'rock': 'scissors',
'paper': 'rock',
'scissors': 'paper'
}
return choices[player_choice] == computer_choice

以下是使用python 3.10的匹配情况(模式匹配(的解决方案:

def check_results(ai, self):
if ai == self:
return 'tralf'
match (ai, self):
case ('scissor', 'paper') | ('paper', 'rock') | ('rock', 'scissor'):  # cases where you lose
return False
case ('scissor', 'rock') | ('paper', 'scissor') | ('rock', 'paper'):  # cases where you win
return True

print(check_results('rock', 'rock'))
print(check_results('rock', 'paper'))
print(check_results('paper', 'rock'))
print(check_results('rock', 'scissor'))

结果:

tralf
True
False
False

最新更新