use*_*984 0 python if-statement
我必须编写一个类似于剪刀石头布的程序游戏,但有五个选项而不是三个。我能够使用 ifs 系统编写代码,但我想知道是否有更好的方法来编写代码。
\n\n游戏规则:
\n\n可以看到,一共有5个选项(X \xe2\x86\x92 Y 表示X战胜Y):
\n\n主要代码:
\n\nimport random\nfrom ex2_rpsls_helper import get_selection\n\ndef rpsls_game():\n com_score = 0\n player_score = 0\n draws = 0\n while(abs(com_score - player_score) < 2):\n print(" Please enter your selection: 1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock): ")\n selection = int(input())\n # a while loop to make sure input i between 0<x<6\n while(selection <= 0 or selection > 5):\n print( "Please select one of the available options.\\n")\n selection = int(input())\n com_selection = random.randint(1,5)\n print(" Player has selected: "+get_selection(selection)+".")\n print(" Computer has selected: "+get_selection(com_selection)+".")\n\n # A set of else and elseif to determin who is the winner\n if(give_winner(selection, com_selection)):\n print(" The winner for this round is: Player\\n")\n player_score += 1\n elif(give_winner(com_selection,selection)):\n print(" The winner for this round is: Computer\\n")\n com_score += 1\n else:\n print(" This round was drawn\\n")\n draws += 1\n\n print("Game score: Player "+str(player_score)+", Computer "+str(com_score)+", draws "+str(draws))\n if(player_score > com_score):\n return 1\n else:\n return -1\nRun Code Online (Sandbox Code Playgroud)\n\nIFS系统:
\n\ndef give_winner(first_selection, second_selection):\n if(first_selection is 1):\n if(second_selection is 3 or second_selection is 4):\n return True\n elif(first_selection is 2):\n if(second_selection is 1 or second_selection is 5):\n return True\n elif(first_selection is 3):\n if(second_selection is 2 or second_selection is 4):\n return True\n elif(first_selection is 4):\n if(second_selection is 2 or second_selection is 5):\n return True\n elif(first_selection is 5):\n if(second_selection is 3 or second_selection is 1):\n return True\n return False\nRun Code Online (Sandbox Code Playgroud)\n\n有任何想法吗?
\nif您可以拥有一个元组列表或字典,而不是一系列复杂的(first, second)语句,
a = [(1,3), (1,4), (2,1), (2,5) ...]
def give_winner(first_selection, second_selection):
return (first_selection, second_selection) in a
Run Code Online (Sandbox Code Playgroud)
您还可以使用 afrozenset来提高性能。