For those who are struggling with Tic-Tac-Toe

For those who are struggling with Tic-Tac-Toe
0

#1

For those who are struggling with Tic-Tac-Toe, here is a simple but effective implementation of the MiniMax algorithm:

If you look carefully in the javascript, a board is basically an array made up of objects, and individual cells are those objects.

That means that whatever happens to the board in the miniMax function, gets passed back to the calling function, in this case, the makeMove function, because objects are passed to functions by reference, not by value.

Within the minimax function, when it iterates through each possible move, it creates a new board, called simBoard (simulated Board) and passes that to the recursive miniMax function. When the script is finished recursing, the original board makes it’s move based on the maximum score each empty move could possibly produce. If it’s the player’s turn, it uses the minimum possible score each empty move could possible produce.

Any questions or further explaination needed, please feel free to reach out!

Thanks,
James


#2

I found one way to beat the AI everytime:

  1. Bottom right
  2. Bottom left
  3. Bottom middle

#3

Goodness gracious! You’re right! Might be a flaw in the win logic, when I was developing this, the “check diagonal” was off as well, and I was scratching my head as to why it would just “let” me win so easily.

Thank you for the feedback!


#4

As far as I played, it is the only way to beat it :slight_smile:

Good job


#5

Here’s the original code:

if (board[i][0].value == board[i][1].value && board[i][0].value == board[i][2].value){
  return board[i][0].value;
}

Here’s the modified code:

if (board[i][0].value == board[i][1].value && board[i][0].value == board[i][2].value && board[i][0].value !== ''){
  return board[i][0].value;
}

Without that 3rd check in the conditional, if the board has 3 blanks in the first row, it won’t make it to the last row because of the return statment.

Great catch @Flopet17! Now try to beat it :wink: