我必须编写一个类似于石头剪刀布的程序游戏,但有五个选项而不是三个选项。我能够使用 ifs 系统编写代码,但我想知道是否有更好的方法来编写代码。
游戏规则:
如您所见,共有 5 个选项(X → Y 表示 X 胜过 Y):
- 摇滚 → 蜥蜴和剪刀
- 纸→摇滚和斯波克
- 剪刀→纸和蜥蜴
- 蜥蜴 → Spock & Paper
- 斯波克 → 剪刀和石头
主要代码:
import random
from ex2_rpsls_helper import get_selection
def rpsls_game():
com_score = 0
player_score = 0
draws = 0
while(abs(com_score - player_score) < 2):
print(" Please enter your selection: 1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock): ")
selection = int(input())
# a while loop to make sure input i between 0<x<6
while(selection <= 0 or selection > 5):
print( "Please select one of the available options.\n")
selection = int(input())
com_selection = random.randint(1,5)
print(" Player has selected: "+get_selection(selection)+".")
print(" Computer has selected: "+get_selection(com_selection)+".")
# A set of else and elseif to determin who is the winner
if(give_winner(selection, com_selection)):
print(" The winner for this round is: Player\n")
player_score += 1
elif(give_winner(com_selection,selection)):
print(" The winner for this round is: Computer\n")
com_score += 1
else:
print(" This round was drawn\n")
draws += 1
print("Game score: Player "+str(player_score)+", Computer "+str(com_score)+", draws "+str(draws))
if(player_score > com_score):
return 1
else:
return -1
IFS系统:
def give_winner(first_selection, second_selection):
if(first_selection is 1):
if(second_selection is 3 or second_selection is 4):
return True
elif(first_selection is 2):
if(second_selection is 1 or second_selection is 5):
return True
elif(first_selection is 3):
if(second_selection is 2 or second_selection is 4):
return True
elif(first_selection is 4):
if(second_selection is 2 or second_selection is 5):
return True
elif(first_selection is 5):
if(second_selection is 3 or second_selection is 1):
return True
return False
有任何想法吗?