Tic Tac Toe AI not working properly?

It’s almost finished, but I have two more problems I can’t figure out. The computer doesn’t ALWAYS go after me and I can’t figure out why or how to up any difficulty at all. Also, how do I center the X’s and O’s in the cells? Thanks a lot for dealing with a newbie!

I would do several refactorings. You have variable names that don’t mean anything, and others that have very similar names (what’s the difference between turns and turn?). Remember you write code for yourself and others, not for the machine. The machine does not care if your variable is called a or isBoardComplete or currentActivePlayer.

After that, make sure you go step by step on your code and check the status of the variables. If you don’t have (or don’t know how to use) a debugger, just place Console.log() for key variables on places you believe are key in the computer skipping their turn.

As example, I would place a console.log(“Entered CPU turn”) at the start of the computerTurn function. Another one to check the state variables before entering the while loop. Maybe another one inside the loop to see if the computer just attempted to make a play in an invalid spot of the board (non existent, taken, etc…)

It has happened to me a lot, putting moves in array[19] in a 3x3 board, or getting 53 as result of 5+3 xD

I honestly can’t understand any other way other than let taken = false; while(taken === false && count !==5)

I made this change to your code

  if(move === ""){
        console.log("Trying to place move at position " + computersMove)
        $("#" + computersMove).text(computersTurn);

After a couple of turns it logged:
"Trying to place move at position 10"

So I guess you can already figure out what can be wrong from here :slight_smile:


You are doing Math.Random()*10, this returns a number from 0 to 10. Your board has slots from 0 to 8 so your computer does not miss turns, it just place its turns in two places that are outside of the board

Why when I try to console log the same thing to see what you are talking about I get nothing going on in the console?

EDIT: Oops, never mind!

Also, fuck yes you are my hero and thank you for making me understand. How do I center the X’s and O’s in the spaces or maybe how do I get cool icons for them?

I use FontAwesome for the icons. I believe it’s in some of the FCC curriculum, otherwise just google for a bit, they’re very easy to use and nice and tidy.

Easy to use I’m sure, but not so much to have it hidden. I now have the problem of still not being able to center and now the typed X’s and O’s just override the FA icon. A lot ahead of me I’m sure >.<

1 Like