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

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

I found one way to beat the AI everytime:

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

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!

1 Like

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

Good job

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

1 Like