gpt4 book ai didi

javascript - MinMax 算法未按预期工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:34 25 4
gpt4 key购买 nike

我正在构建一个井字游戏(Free Code Camp 上的一个项目),并实现了一个 minmax 算法来决定计算机玩家接下来应该选择哪个方 block 。

在我测试过的所有情况下,它都按预期工作,但以下情况除外:

var userIs = 'o'
var computerIs = 'x'

function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}

function nextMove(board, player) {
var nextPlayer;
if (computerIs !== player) {
nextPlayer = userIs;
} else {
nextPlayer = computerIs;
}
if (isGameOver(board)) {
if (player === userIs) {
return {
"willWin": -1,
"nextMove": -1
};
} else {
return {
"willWin": 1,
"nextMove": -1
};
}
}

var listOfResults = [];

if (countInArray(board, '-') === 0) {
return {
"willWin": 0,
"nextMove": -1,
};
}

var _list = [];//keeping track of avalible moves
for (var i=0; i < board.length; i++) {
if (board[i] === '-') {
_list.push(i);
}
}
for (var j = 0; j < _list.length; j++) {
board[_list[j]] = player;
var nextTry = nextMove(board, nextPlayer);
listOfResults.push(nextTry.willWin);
board[_list[j]] = '-';
}
if (player === computerIs) {
var maxele = Math.max.apply(Math, listOfResults);
return {
"willWin": maxele,
"nextMove": _list[listOfResults.indexOf(maxele)]
};
} else {
var minele = Math.min.apply(Math, listOfResults);
return {
"willWin": minele,
"nextMove": _list[listOfResults.indexOf(minele)]
};
}
}

function isGameOver(board) {
//horizontal wins
var gameOver = false;
var rowOffset = [0,3,6];
rowOffset.forEach(function(row){
if (board[row] === board[row + 1] && board[row + 1] === board[row + 2] && board[row] !== "-") {
gameOver = true;
}
});
//vertical wins
var colOffset = [0,1,2];
colOffset.forEach(function(col){
if (board[col] === board[col + 3] && board[col + 3] === board[col + 6] && board[col] !== "-" ){
gameOver = true;
}
});

///diag wins
if (board[0] === board[4] && board[4] === board[8] && board[8] !== "-" ) {
gameOver = true;
}
if (board[2] === board[4] && board[4] === board[6] && board[6] !== "-" ) {
gameOver = true;
}
return gameOver;
}

nextMove(["x", "x", "o", "o", "x", "-", "-", "-", "o"], computerIs)

它返回的位置:{willWin: 1, nextMove: 5} 当我期望 {willWin: 1, nextMove: 7}

我正在用 Python 编写一个示例实现:https://gist.github.com/SudhagarS/3942029返回预期结果。

你能看到会导致这种行为的东西吗?

最佳答案

我添加了一些日志记录,发现我没有正确地在玩家之间切换。

切换:

 if (computerIs !== player) {
nextPlayer = userIs;
} else {
nextPlayer = computerIs;
}

到:

if (computerIs === player) {
nextPlayer = userIs;
} else {
nextPlayer = computerIs;
}

并反转分数(-111-1)返回给赢家当游戏结束时,似乎已经成功了。

关于javascript - MinMax 算法未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34270337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com