Stuck with Tic Tac Toe AI function


I am having a hard time getting the AI function to work. Here is my dilemma…Every time I run the code, the function sets the computer player to the next sequentially available space. I totally confused. Here is the link to the codepen:

Thanks for any help in advance,


This project was a struggle for a lot of people. There are two tactics you can take:

  1. Keep an array of available spaces and generate a random number of which space to use
  2. Use the max-mind algothrom it’s difficult for new coders to implement but if you’re up for a challenge.

Thank you for the suggestion, however, I have tried to implement the minimax algorithm. It keeps returning the next sequential free space/cell number. I need another pair of eyes to tell me where I went wrong and possibly why I did not code the algorithm correctly.

Thank you.

I have figured it out. I had returned the wrong value back. It took some time to find this, but I fixed the code and now it is running correctly!!!