首页 > 解决方案 > n 维井字棋对角线检查器(预测谁将一举获胜)

问题描述

我得到了井字游戏的状态。这是一个*n 游戏,获胜者是可以拥有“a”个连续 X 或 Os(也给出了 a)的人。我应该预测天气 X 或 O 可以在下一场比赛中获胜。例如,如果状态是这样的:

X X O X O
X O X O X
O X O - -
- - - - -
X O X O X

输出是:

O 

我对对角线检查有问题。我写了一个代码。

X = 'X'
O = 'O'
DASH = '-'

def o_left_diagonal_checker_winner(game_board, n, a):
    x_counter = 0
    for j in range(n):
        for i in range(1, n):
            if i - 1 >= 0 and n - i >= 0:
                if game_board[i - 1][n - i] == X:
                    x_counter += 1
                if n - i - 2 >= 0 and i - 2 >= 0 and x_counter == a - 1 and game_board[n - i - 2][i - 2] == DASH:
                    return O
                else:
                    x_counter = 0

这部分代码将从左上到右检查游戏。但它不起作用。如果您有更好的算法,请告诉我,我不能使用库。

标签: pythontic-tac-toe

解决方案


考虑这个替代解决方案。

假设您有一个代表您的游戏板的数组。对于每个位置的不同状态,值为 +1,-1,0。然后取 ad*d 大小的子数组并沿对角线求和。行和列。如果任何值 = -2 或 2,则玩家 +1 或 -1 有机会在下一个状态下获胜。d 将是您的数组的大小。这是一个获胜条件为 3 的 5*5 棋盘示例。因此,简单地用获胜可能性掩盖棋盘将预测下一个获胜者。

import numpy as np
board = np.array([[-1., -1.,  1.,  1., -1.],
                  [-1.,  0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.,  1.],
                  [ 0.,  0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.,  0.]])

win_length = 3


#lets assume +1 = X, -1 = 0 and 0 = nothing
# Also assume that X always starts
# You could also simply replace priority with who is moving next
def who_wins_next(board,a):
    priority = sum(sum(board))

    if priority >0: # If else case to automatically determine who is moving next. Alternatively you can add another input to who is moving next to replace this
        target = 2
        text = "X (1)"
    else:
        target = -2
        text = "O (-1)"


    width,height = board.shape
    for i in range(width-a+1):
        for j in range(height-a+1):
            sub = board[i:i+a,j:j+a]
            diagonal_forward = sum(sub[i][i] for i in range(a))
            diagonal_backward = sum(sub[i][a-i-1] for i in range(a))
            row_sums = np.sum(sub,axis=1) #Using numpy sum with axis to get an array of row sums
            col_sums = np.sum(sub,axis=0) # Likewise for columns
            if diagonal_forward == target or diagonal_backward == target or target in list(row_sums) or target in list(col_sums):
                #Only need to know if win is possible. Not how.
                return text + " can win in next step"
    return text + " cannot win in next step"

推荐阅读