Trying to do a minmax without copying (Tic Tac Toe Zipline)

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)
        }
      }
    }

Hey Chad,

I see it’s been over two weeks since you posted this. I hope you’ve figured it out, but if not, I have a couple of suggestions. Your logic to check for winning conditions has the draw as default, so if it’s playing through to a draw, the error is probably not in your mimiax algorithm, but that endgame check. Check the if/else clauses you set up against the game state. However, this is extremely difficult to debug through the console (as you’ve likely concluded yourself), so my ultimate suggestion is to write up the interface first and work on the AI last. This way you can get the endgame check to work simply by clicking in your X’s and O’s on the screen - much easier to see!

1 Like

Thanks. I actually decided to give it a break and go on to something else, but when I come back to it, I’ll take a look at your suggestions. I didn’t paste it in the post, And I may have removed them since then, but I actually have some testing things built in so I can simulate the board in the console.