我已经将极小最大算法应用于这个井字游戏,到目前为止,它在“知道如何取胜”方面表现良好。然而,计算机仍然无法弄清楚如何防止......
我已经将极小最大算法应用于这个井字游戏,到目前为止,它在“知道如何取胜”方面效果很好。但是,计算机仍然无法弄清楚如何阻止我获胜,它看不到我制造的威胁,它只是专注于自己获胜。[例如,在这里,计算机 (X) 试图争取第一行的胜利,我 (O) 将我的第一步放在中心,然后转向棋盘 0][2] 单元格,阻止计算机获胜。现在我离获胜只有一步之遥,但计算机没有阻止我获胜,而是试图争取第一列的胜利。
这也是代码笔
在我的评估函数中,我会返回与每一步相关的值,我为威胁分配了值,以鼓励计算机考虑威胁并在结果中阻止它们。然而,这似乎效果不佳。
// 'X' => +10; 'O' => -10;
function evaluate(board) {
// evaluating rows;
for (let i = 0; i < 3; i++) {
if (
board[i][0] == board[i][1] &&
board[i][1] == board[i][2]
) {
if (board[i][0] == AI) {
return +10;
} else if (board[i][0] == player) {
return -10;
}
};
};
// evaluating columns;
for (let j = 0; j < 3; j++) {
if (
board[0][j] == board[1][j] &&
board[1][j] == board[2][j]
) {
if (board[0][j] == AI) {
return +10;
} else if (board[0][j] == player) {
return -10;
}
}
};
// evaluating the diagonals;
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;
}
}
// detecting row threats;
for (let i = 0; i < 3; i++) {
if (
(board[i][0] == player && board[i][1] == player && board[i][2] == '') ||
(board[i][0] == player && board[i][2] == player && board[i][1] == '') ||
(board[i][1] == player && board[i][2] == player && board[i][0] == '')
) { return -9; }
};
// detection column threats;
for (let j = 0; j < 3; j++) {
if (
(board[0][j] == player && board[1][j] == player && board[2][j] == '') ||
(board[0][j] == player && board[2][j] == player && board[1][j] == '') ||
(board[1][j] == player && board[2][j] == player && board[0][j] == '')
) { return -9; }
};
// detecting diagonal threats;
if ((board[0][0] == player && board[1][1] == player && board[2][2] == '') ||
(board[0][0] == player && board[2][2] == player && board[1][1] == '') ||
(board[1][1] == player && board[2][2] == player && board[0][0] == '')
) { return -9; };
if ((board[0][2] == player && board[1][1] == player && board[2][0] == '') ||
(board[0][2] == player && board[2][0] == player && board[1][1] == '') ||
(board[1][1] == player && board[2][0] == player && board[0][2] == '')
) { return -9; }
// if none then:
return 0;
};