我正在尝试为tic tac toe游戏编写一个minimax算法。我创建了一个递归函数,它应该遍历电路板数组中的可用空间,改变它们以获得所有可能的结果,并用分数对任何最终电路板状态进行加权。它现在创建了一个无限循环。我接近这样做了吗?
这就是我所拥有的:
//boardstate updated with 1's for human choice 2's for cpu, representative of a tic tac toe board
var boardState = [0,0,0,0,0,0,0,0,0];
//gets index of best move playerNum === 1 = human turn, 2 = cpu turn
function minMax (newBoard, playerNum) {
var openSpaces = getOpenSpaces(newBoard);
//checks for win condition gives score of -10 if human win 10 if cpu win 0 if stalemate
if (checkWinState(newBoard, 1)){
return -10;
} else if (checkWinState(newBoard, 2)){
return 10;
} else if (openSpaces.length === 0){
return 0;
}
var moves = [];
//iterates through board array changing values to get all possible outcomes
for (var i = 0; i < openSpaces.length; i++){
var move = {};
move.index = openSpaces[i];
newBoard[openSpaces[i]] = playerNum;
if(playerNum === 1){
var result = minMax(newBoard, 2);
move.score = result;
} else if(playerNum === 2){
var result = minMax(newBoard, 1);
move.score = result;
}
newBoard[openSpaces[i]] = 0;
moves.push(move);
}
var bestMove;
if (playerNum === 2){
var bestScore = -1000;
for(var i = 0; i < moves.length; i++){
if (moves[i].score > bestScore){
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
var bestScore = 1000;
for (var i = 0; i < moves.length; i++){
if(moves[i].score < bestScore){
bestScore = moves[i].score;
bestMove = i;
}
}
}
return bestMove;
}
//gets index of open spaces
function getOpenSpaces(board){
var openSpaceIndexes = [];
for(var i = 0; i < board.length; i++){
if (board[i] === 0){
openSpaceIndexes.push(i);
}
}
return openSpaceIndexes;
}