Python n维Tictatcoe对角棋盘(预测谁只需一步就能赢)

Python n维Tictatcoe对角棋盘(预测谁只需一步就能赢),python,tic-tac-toe,Python,Tic Tac Toe,我被赋予了一种抽签游戏的状态。这是一个n*n的游戏,赢家是一个人,他可以拥有多个连续的X或操作系统,其中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)

我被赋予了一种抽签游戏的状态。这是一个n*n的游戏,赢家是一个人,他可以拥有多个连续的X或操作系统,其中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

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

考虑这个替代解决方案

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

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"

那么检查是否有玩家可以玩的空位呢?代码会检查玩家是否可以在下一步中获胜。如果没有更多的动作,这只会表明它无法获胜。否则,只需检查线路板数组中是否没有零。我们可以不使用numpy库编写它吗?我想您可以使用嵌套列表或python数组。但使用numpy要容易得多。