为什么minimax算法在这种情况下会下在阻止O获胜的位置而不是使自己获胜,还有就是它好像看不到几步之后

下面是我的代码



public class TicTacToe {
// 用于表示棋盘的状态,其中玩家的棋子用 1 和 -1 表示,空位用 0 表示
private static final int EMPTY = 0;
private static final int X = 1;
private static final int O = -1;
// 判断游戏是否结束,并返回赢家
private static int evaluate(int[][] board) {
for (int i = 0; i < 3; i++) {
// 检查行和列
if (board[i][0] == board[i][1] && board[i][0] == board[i][2]) {
if (board[i][0] != EMPTY) return board[i][0];
}
if (board[0][i] == board[1][i] && board[0][i] == board[2][i]) {
if (board[0][i] != EMPTY) return board[0][i];
}
}
// 检查对角线
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2]) || (board[0][2] == board[1][1] && board[0][2] == board[2][0])) {
if (board[1][1] != EMPTY) return board[1][1];
}
// 没有赢家返回0
return EMPTY;
}
// 判断棋盘上是否还有空位
private static boolean isMovesLeft(int[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == EMPTY) {
return true;
}
}
}
return false;
}
// Minimax算法实现
private static int minimax(int[][] board, int depth, boolean isMax) {
int score = evaluate(board);
if (score == X) return score - depth; // 减去深度以优先走最快获胜路径
if (score == O) return depth + score; //
if (!isMovesLeft(board)) return 0; // 平局
if (isMax) {
int best = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == EMPTY) {
board[i][j] = X;
best = Math.max(best, minimax(board, depth + 1, false));
board[i][j] = EMPTY;
}
}
}
return best;
} else {
int best = Integer.MAX_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == EMPTY) {
board[i][j] = O;
best = Math.min(best, minimax(board, depth + 1, true));
board[i][j] = EMPTY;
}
}
}
return best;
}
}
// 该方法找到并返回最优的移动
public static int[] findBestMove(int[][] board) {
int bestValue = Integer.MIN_VALUE;
int[] bestMove = new int[]{-1, -1};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == EMPTY) {
board[i][j] = X;
int moveValue = minimax(board, 0, false);
board[i][j] = EMPTY;
if (moveValue > bestValue) {
bestMove[0] = i;
bestMove[1] = j;
bestValue = moveValue;
}
}
}
}
return bestMove; // 返回行列
}
}