一种更高效的 Python 代码编写方式

use*_*984 0 python if-statement

我必须编写一个类似于剪刀石头布的程序游戏,但有五个选项而不是三个。我能够使用 ifs 系统编写代码,但我想知道是否有更好的方法来编写代码。

\n\n

游戏规则:

\n\n

可以看到,一共有5个选项(X \xe2\x86\x92 Y 表示X战胜Y):

\n\n
    \n
  1. 岩石 \xe2\x86\x92 蜥蜴和剪刀
  2. \n
  3. 纸 \xe2\x86\x92 摇滚与史波克
  4. \n
  5. 剪刀\xe2\x86\x92 纸和蜥蜴
  6. \n
  7. 蜥蜴 \xe2\x86\x92 斯波克和纸
  8. \n
  9. 斯波克 \xe2\x86\x92 剪刀与石头
  10. \n
\n\n

主要代码:

\n\n
import 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\n
Run Code Online (Sandbox Code Playgroud)\n\n

IFS系统:

\n\n
def 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\n
Run Code Online (Sandbox Code Playgroud)\n\n

有任何想法吗?

\n

jba*_*100 5

if您可以拥有一个元组列表或字典,而不是一系列复杂的(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来提高性能。