I'm trying to implement Minimax to find the best move each turn in tic-tac-toe in js.
However, it always returns the first free spot: 0,0 and when this spot is taken 0,1 and so on. It turns out that the miniMax function always returns 1.
let board = [
['', '', ''],
['', '', ''],
['', '', '']
];
const scores = {
'X': 1,
'O': -1
}
function miniMax(board, isMaximizing, player, turns) {
let winner = checkForWinner(board);
if (winner != null)
return scores[winner];
if (turns > 9)
return 0;
let bestScore = isMaximizing ? -Infinity : Infinity;
let score;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == '') {
board[i][j] = player;
score = miniMax(board, !isMaximizing, isMaximizing ? p2 : p1, turns + 1)[1];
board[i][j] = '';
if (isMaximizing) {
if (score > bestScore) {
bestScore = score;
bestMove = [i, j];
}
}
else {
if (score < bestScore) {
bestScore = score;
bestMove = [i, j];
}
}
}
}
}
return [bestMove, bestScore];
}
I've tried looking at other people's implementation of Minimax for Tic-Tac-Toe, but I couldn't understand what makes mine fail.
What did I do wrong?
EDIT: I've updated my code but now it returns 0,0 then 1,0 then 0,1 then 2,0 then 0,2.