编写cod的一种更高效的python方法

2024-04-29 20:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

游戏规则:

如您所见,共有5个选项(X→Y表示X战胜Y):

  1. 石头→蜥蜴和剪刀
  2. 纸张→Rock&Spock
  3. 剪刀→布和蜥蜴
  4. 蜥蜴→斯波克纸
  5. 斯波克→剪刀和石头

主代码:

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系统:

^{pr2}$

有什么想法吗?在


Tags: 代码cominputgetscoreplayerprint石头
3条回答

给获胜者另一个选择:

def give_winner(first_selection, second_selection):
    rules = {
        1: lambda x: x in (3, 4),
        2: lambda x: x in (1, 5),
        3: lambda x: x in (2, 4),
        4: lambda x: x in (2, 5),
        5: lambda x: x in (3, 1)
    }
    return rules[first_selection](second_selection)

你可以用字典。在

dictionary = {
    1: [3, 4],
    2: [1, 5],
    3: [2, 4],
    4: [2, 5],
    5: [3, 1]
}

def give_winner(first_selection, second_selection):
    if dictionary.has_key(first_selection):
        if second_selection in dictionary[first_selection]:
            return True
    return False

您可以使用(first, second)元组的列表或字典,而不是一系列复杂的if语句

a = [(1,3), (1,4), (2,1), (2,5) ...]

def give_winner(first_selection, second_selection):
    return (first_selection, second_selection) in a

您还可以使用frozenset来提高性能。在

相关问题 更多 >