我试图从网上调试一些演示代码,以便了解如何存储电路板状态以及minMax如何工作。随附的HTML没有问题(为简洁起见,此处省略)。
通过递归调用minMax函数,可以成功检查gameState,并在内部生成电路板的副本并成功填充(根据控制台)。
但是,永远不会生成名为value
的返回值。事实上,尽管递归发生,我试图推入values
数组的对象永远不会在那里。因此,抛出以下错误:TypeError: Cannot read property 'cost' of undefined
。
有什么想法?
$(document).ready(function () {
const PLAYER = 'O';
const HAL = 'X';
let board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
];
function minMax(newBoard, depth, player) {
let gameState = gameWon(newBoard);
let boardCopy = _.cloneDeep(newBoard);
if (gameState === false) {
let values = [];
for (let k = 0; k < 3; k++) {
for (let l = 0; l < 3; l++) {
if (boardCopy[k][l] !== ' ') {
continue;
}
boardCopy[k][l] = player;
// value that is not logged
let value = minMax(boardCopy, depth + 1, (player === PLAYER) ? HAL : PLAYER);
values.push({
cost: value,
cell: {
i: k,
j: l
}
});
}
}
if (player === HAL) {
// error thrown
let max = _.maxBy(values, (v) => {
return v.cost;
});
if (depth === 0) {
return max.cell;
} else {
return max.cost;
}
} else {
let min = _.minBy(values, (v) => {
return v.cost;
});
if (depth === 0) {
return min.cell;
} else {
return min.cost;
}
}
} else if (gameState === null) {
return 0;
} else if (gameState === PLAYER) {
return depth - 10;
} else if (gameState === HAL) {
return 10 - depth;
}
}
function hal() {
return minMax(board, 0, HAL);
}
});