提高博弈cod中的循环效率

2024-04-24 15:55:10 发布

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

我正在编写一个连接4的游戏。游戏数组为(6,7),在玩家尚未移动的位置包含0。有两个玩家(玩家1和玩家2)。目前,我是这样检查胜利的

def check_success(game_array):
    assert (np.shape(game_array)==(6,7)), 'Incorrect shape'
    for s_r in range(3):
        for s_c in range(4):
            board=game_array[s_r:s_r+4,s_c:s_c+4]*1
            D = np.einsum('ii->i', board)
            DP = D != 0
            if DP[0] and (D[0] == D).all():
                return True, D[0]
            L = DP & (D == board).all(0)
            I = L.argmax()
            if L[I]:
                return True, D[I]
            L = DP & (D == board.T).all(0)
            I = L.argmax()
            if L[I]:
                return True, D[I]
            D = np.einsum('ii->i', board[::-1])
            if D[0] and (D[0] == D).all():
                return True, D[0]
    return False, 0

有人能想出一种不用for循环(或者至少更少的迭代)的方法来处理这个问题吗?我看了看微小差异并创建一个for循环7,以同时检查行/列(将迭代次数减少7/12)。但我无法实现。你知道吗


Tags: inboardgametrue游戏forreturnif
1条回答
网友
1楼 · 发布于 2024-04-24 15:55:10

基于Checkio - Xs and Os solutionthat answer的解决方案:

def check_success(field):
    rows = field.tolist()
    cols = field.T.tolist()
    diags = [field[::-1,:].diagonal(i)
        for i in range(-field.shape[0] + 1, field.shape[1])]
    diags.extend(field.diagonal(i)
        for i in range(field.shape[1] - 1, -field.shape[0], -1))

    lines = diags + cols + rows
    for line in lines:
        if "2, 2, 2, 2" in repr(line):
            return "2 wins"
        elif "1, 1, 1, 1" in repr(line):
            return "1 wins"
    return "no winner"

它提高了可读性,而不是效率。然而,效率对于6 x 7字段来说并不重要。你知道吗

相关问题 更多 >