我正在研究tic tac toe(用戶vs計算機)的AI,並且我正在使用minimax算法實現計算機的最佳移動。我已經看過YouTube上的一些視頻,並閱讀了一些人的代碼。但是,有些部分代碼我仍然對正在做的事感到困惑。以下面的代碼爲例,來自井號最小極小函數。有一個主要的if,else if,else語句和其他所有從那裏得到的。我的主要問題是理解嵌入的for循環,以及後面的2個if。我認爲,我已經對這些東西發表了一些評論。我從這個YouTube視頻中獲取了示例代碼:https://www.youtube.com/watch?v=x_Je9i3aKNk 最小極小函數用於井字遊戲。有人可以解釋minimax tic tac toe算法
//minimax function
function minimax(newGrid, depth, player) {
const gameState = isGameOver(newGrid);
//if the game is not over, evalute best move for computer
if(gameState === false) {
const values = [];
for(var i = 0; i < 3; i++) {
for(var j = 0; j < 3; j++) {
const gridCopy = _.cloneDeep(newGrid);
//if that spot is taken, skip to next loop
if(gridCopy[i][j] !== ' ') continue;
//if spot is player, evaluate
gridCopy[i][j] = player;
//need clarification
const value = minimax(gridCopy, depth+1, (player == PLAYER_TOKEN) ? COMPUTER_TOKEN : PLAYER_TOKEN);
values.push(value);
}
}
//need clarification for computer turn
if(player === COMPUTER_TOKEN) {
const max = _.maxBy(value, (v) => {
return v.cost;
});
if(depth === 0) {
return max.cell;
}
else {
return max.cost;
}
//need clarification for user turn
else {
const min = _.minBy(value, (v) => {
return v.cost;
});
if(depth === 0) {
return v.cell;
}
else {
return v.cost;
}
}
//if game state is null return 0
else if (gameState === null) {
return 0;
}
//if game state is player return negative
else if(gameState === PLAYER_TOKEN) {
return depth - 10;
}
//if game state is computer return positive
else if(gameState === COMPUTER_TOKEN) {
return 10 - depth;
}
}