Estoy haciendo un algoritmo minimax de Javascript para un juego de tres en raya, pero la IA me deja ganar y, a veces, no gana cuando podía. Traté de probar para encontrar dónde está el problema, pero no sé cómo, porque tomo muchos pasos a seguir en el proceso.
Aquí está mi código, el juego está configurado en una matriz como esta: [" ", " ", " ", " ", " ", " ", " ", " ", " "]
El checkGameOver está devolviendo "o", "x", "tie" o indefinido.
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(); }