I'm making a Javascript minimax algorithm for a Tic-tac-toe game, but the IA is letting me win and also sometimes she doesn't win when she could. I tried to test to find where is the problem but i don't know how because take so many steps to follow in the process.
Here is my code, the game is set in an array like this: [" ", " ", " ", " ", " ", " ", " ", " ", " "]
The checkGameOver is returning "o", "x", "tie" or undefined.
const minimax = function (array, index, isMaximizing, testMark) {
let result = gameFlow.checkGameOver(array, index, testMark);
let scores = {
"o": 1,
"x": -1,
"tie": 0
}
if (result) {
return scores[result];
}
if (isMaximizing) {
let bestScore = -2;
array.forEach( (item, index, array) => {
if (item === " ") {
array[index] = "o";
let score = minimax(array, index, false, "o");
if (score > bestScore) {
bestScore = score;
}
array[index] = " ";
}
})
return bestScore
} else {
let bestScore = 2;
array.forEach( (item, index, array) => {
if (item === " ") {
array[index] = "x";
let score = minimax(array, index, true, "x");
if (score < bestScore) {
bestScore = score;
}
array[index] = " ";
}
})
return bestScore
}
}
const minimaxPlay = function (array) {
let bestScore = -2;
let bestMove;
array.forEach( (item, index, array) => {
if (item === " ") {
array[index] = "o";
let score = minimax(array, index, false, "o");
if (score > bestScore) {
bestScore = score;
bestMove = index
}
array[index] = " ";
}
})
array[bestMove] = "o";
gameFlow.changeCurrentPlayer();
gameBoard.renderPlays();
}