Tic Tac Toe AI Feedback and Suggestions?

I’ve managed to create a tic tac toe game, but I’m not confident in my AI since it’s quite possible to beat the computer (who only plays defensively at this time). My thought process thus far is as follows: decide who goes first with a coin flip, when it’s computer’s turn computer maps/filters over the grids and figures out both which grids are currently empty and where on the grid player one is located. It then runs through a switch statement to either block player one from winning (quite lengthy with 24 possible combinations since there are only 8 possible win states with 3 permutations for each) or computer will default to choosing a random space on the grid if the computer is not in danger of losing. The result is that the computer plays defensively but still can beat since it only reacts defensively and won’t set itself up to win only block at the moment.

Am I on the right path here? I feel like the switch statement is excessively long (24 cases) and there must be a simpler way to go about this. And I’m aware that the initial ‘random’ grids the computer chooses when not in danger of losing leave room for the human player to strategize against it. I could add a second switch statement for the computer’s ‘free turns’ to check for an available path to victory, but the one I have now already seems like overkill. Thoughts?

Here’s an example of the logic I used (only including the first switch case for brevity)…

function computerResponse(){
  let availGrids = grids.filter(grid=>{
    if(!grid.classList.contains('p1')){
      return grid;
    }
  });
  availGrids = availGrids.filter(grid=>{
    if(!grid.classList.contains('p2')){
      return grid;
    }
  })
  const randomIndex = Math.floor(getRandom(0,availGrids.length));
  console.table(availGrids);
  // get the opponents positions
    const opponentGrids = grids.filter(grid=>{
      if (grid.classList.contains('p1')){
        return grid;
      }
    })

    switch(true){
      case (opponentGrids.includes(document.getElementById('seven')))
        && (opponentGrids.includes(document.getElementById('four'))) :
        if (availGrids.includes(document.getElementById('one'))){
          document.getElementById('one').textContent=player2;
          document.getElementById('one').classList.add('p2');
          break;
        }

tic tac toe project on codepen

Sweet! Thanks for the refactoring tips! :slight_smile: I think with everything simplified now it should be easier to make a ‘smarter’ AI that plays more offensively by leaning on the same computerLogic array to make decisions during free turns where it doesn’t need to block the opponent. Great stuff!