我已经坐在这里好几个小时试图将这个Minimax算法应用到我的井字游戏中,虽然我正在取得进步,但我遇到的这个错误非常令人沮丧,而且我已经#39 ;希望有人能指出我朝着正确的方向前进。
问题在于,当我开始游戏时,计算机没有做出正确的动作,我可以相当轻松地击败它。
这是我的Minimax代码:
function minimax(currentBoard, player, depth) {
var emptySquares = currentBoard.filter(square => !isNaN(square));
if (checkForWin(currentBoard, playerO)) {
return 10 - depth;
}
else if (checkForWin(currentBoard, playerX)) {
return depth - 10;
}
else if (emptySquares.length == 0) {
return 0;
}
var moves = [];
var scores = [];
for (var i = 0; i < emptySquares.length; i++) {
let copyBoard = currentBoard.slice();
copyBoard[emptySquares[i]] = player;
player = (player == playerX ? playerO : playerX);
let result = minimax(copyBoard, player, depth++)
scores.push(result);
moves.push(emptySquares[i]);
}
let bestMove;
if (player == playerO) {
let bestScore = -10000;
for (let i = 0; i < scores.length; i++) {
if (scores[i] > bestScore) {
bestScore = scores[i];
bestMove = moves[i];
}
}
return bestMove;
}
else {
let bestScore = 10000;
for (let i = 0; i < scores.length; i++) {
if (scores[i] < bestScore) {
bestScore = scores[i];
bestMove = moves[i];
}
}
return bestMove;
}
}
以下是检查胜利的代码:
function checkForWin(currentBoard, player) {
for (let i = 0; i < wins.length; i++) {
let counter = 0;
for (let j = 0; j < wins[i].length; j++) {
if (currentBoard[wins[i][j]] === player) {
counter++;
if (counter === 3) {
return true;
}
}
else {
break;
}
}
}
return false;
}
让我感到困扰的是,我被困了这么长时间,似乎无法找到解决方案,我希望有人可以提供帮助。提前感谢您的时间。