更好地替代大量的IF语句?价值表

Jas*_*son 7 python algorithm dictionary if-statement

我有一个移动表来决定玩家是否根据他们对AI的选择而获胜.Think Rock,Paper,Scissors有很多动作.我最终将用Python编写它,但在开始之前,我想知道是否有更好的方法来做这个而不是很多和很多IF语句?

该表如下所示:

在此输入图像描述

我认为这些动作需要分配数字,或类似的东西?我不知道从哪里开始......

小智 8

你可以用dict吗?像这样的东西:

#dict of winning outcomes, the first layer represents the AI moves, and the inner 
#layer represent the player move and the outcome
ai = {
    'punch' : {
        'punch' : 'tie',
        'kick' : 'wins',
    },
    'stab' : {
        'punch' : 'loses',
        'kick' : 'loses'
    }
}

ai_move = 'punch'
player_move = 'kick'
print ai[ai_move][player_move] #output: wins


ai_move = 'stab'
player_move = 'punch'
print ai[ai_move][player_move] #output: loses
Run Code Online (Sandbox Code Playgroud)

我没有绘制出所有的动作,但你得到了主旨


Jør*_*n R 5

您可以像这样创建类似于上表的攻击地图

map = [
    [0,-1,-1,1,1,-1],
    [1,0,-1,-1,1,-1],
    [1,1,0,-1,-1,1],
    [-1,1,1,0,-1,1],
    [-1,-1,1,1,0,-1],
    [1,1,-1,-1,1,0]
]
Run Code Online (Sandbox Code Playgroud)

这里,0是平局,1是胜利,-1是亏损.

现在创建一系列攻击,其中攻击的位置与上面的地图相对应.

attacks = ["Punch", "Kick", "Stab", "Throw", "Fling", "Uppercut"]
Run Code Online (Sandbox Code Playgroud)

现在你可以很容易地发现一次攻击是否胜过另一次攻击

map[attacks.index("Stab")][attacks.index("Punch")]

>>> 1
Run Code Online (Sandbox Code Playgroud)

Stab赢得了胜利