我的目标是在我的 TicTacToe 作业中实现极小极大,这样你就可以和它对抗。问题是它似乎没有看到自己正在失败。我不知道为什么它看不到它。当给定一个棋盘时,它只会看到平局或获胜,但不会看到移动可能导致失败。因此,它需要采取行动才能获胜,这很好用,但忽略了对手如果不阻止行动就可能获胜。因此,第一次尝试就很容易获胜。我的代码肯定有问题,但我不知道错误在哪里。
private static Boolean isMovesLeft(char board[][]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
return true;
}
}
}
return false;
}
private static int evaluate(char[][] board) {
for (int row = 0; row < 3; row++)
{
if (board[row][0] == board[row][1] &&
board[row][1] == board[row][2]) {
if (board[row][0] == ai) {
return +10;
} else if (board[row][0] == player) {
return -10;
}
}
}
for (int col = 0; col < 3; col++) {
if (board[0][col] == board[1][col] &&
board[1][col] == board[2][col]) {
if (board[0][col] == ai) {
return +10;
} else if (board[0][col] == player) {
return -10;
}
}
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
if (board[0][0] == ai) {
return +10;
} else if (board[0][0] == player) {
return -10;
}
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
if (board[0][2] == ai) {
return +10;
} else if (board[0][2] == player) {
return -10;
}
}
return 0;
}
private static int minimax(char board[][], int depth, Boolean isMax, int alpha, int beta) {
int score = evaluate(board);
if (score == 10) {
return score - depth;
}
if (score == -10) {
return score + depth;
}
if (!isMovesLeft(board)) {
return 0;
}
if (isMax) {
for (int i = 0; i <= 2; i++) {
for (int j = 0; j <= 2; j++) {
if (board[i][j] == ' ') {
board[i][j] = ai;
score = Math.max(score, minimax(board, depth + 1, !isMax, alpha, beta));
board[i][j] = ' ';
if (score >= beta) {
return beta;
}
if (score > alpha) {
alpha = score;
}
}
}
}
return alpha;
} else
for (int i = 0; i <= 2; i++) {
for (int j = 0; j <= 2; j++) {
if (board[i][j] == ' ') {
board[i][j] = player;
score = Math.min(score, minimax(board, depth + 1, isMax, alpha, beta));
board[i][j] = ' ';
if (score <= alpha) {
return alpha;
}
if (score < beta) {
beta = score;
}
}
}
}
return beta;
}
public List<Integer> findBestMove(char board[][]) {
int bestVal = -1000;
int row = 9, col = 9;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
board[i][j] = ai;
int moveVal = minimax(board, 0, true, -1000, 1000);
board[i][j] = ' ';
System.out.println(moveVal);
if (moveVal > bestVal) {
row = i;
col = j;
bestVal = moveVal;
}
}
}
}
System.out.println(" ");
System.out.println(bestVal);
System.out.println(row + " " + col);
System.out.println(" ");
if (bestVal == 0) {
return Arrays.asList(9, 9);
}
return Arrays.asList(row, col); // TODO: Fix AI
}
我的猜测是分数值提出了一个问题,但我需要使用初始化值,否则我会完全迷失。这是我的最后一根稻草,因为我已经追了好几个小时了,除了重写整个事情之外,我完全一无所知。
我在最后几行添加了这个,破坏了我自己的代码。
if (bestVal == 0) {
return Arrays.asList(9, 9);
}
我对所有读到这篇文章并想提供帮助的人感到抱歉,但我只是愚蠢。对不起。