I’ve been trying to work out the minmax algorithm for my tic tac toe project. I feel like I’m close, but I’m still missing something. The computer just plays the game through to a tie. below is the actual minMax() function, and here is the pen link:
// The rest of the AI logic goes here. Wish me luck.
function minMax(boardState) {
var tempBoard = boardState
var spotsToTry = emptySpots(tempBoard)
console.log(spotsToTry)
if(compTry(tempBoard) === 1 || compTry(tempBoard) === 0){
boardState[spotsToTry[0]] = computer
return boardState
}
else if(compTry(tempBoard) === -1) spotsToTry = spotsToTry.slice(1)
console.log(spotsToTry)
compTry(tempBoard)
function compTry(currentBoard){
var tryArray = spotsToTry
for(var i = 0; i < tryArray.length; i++){
console.log("comp: " + i)
currentBoard[tryArray[i]] = computer
if(winTest(currentBoard) === computer) return 1
else if(winTest(currentBoard) === "Draw") return 0
else return humTry(currentBoard)
}
}
function humTry(currentBoard){
var tryArray = emptySpots(currentBoard)
for(var i = 0; i < tryArray.length; i++){
console.log("hum: " + i)
currentBoard[tryArray[i]] = human
if(winTest(currentBoard) === human) return -1
else if(winTest(currentBoard) === "Draw") return 0
else return minMax(currentBoard)
}
}
}