Tic Tac Toe With AI — The ultimate beginner guide! (Part 3)

Victor Catalin Torac
4 min readMay 29, 2016

--

Now that we are comfortable with Encapsulation And Inheritance, let’s take it one level up →V0.2←. We will begin implementing an AI to play against. We make that by creating an function(class) caled AI and we add some properties.

In the start() function we use this.plays property so that the AI knows what game we are playing.

.plays is a reference data type to the GameManager object.Any change made by the AI using it’s game variable will reflect on the GameManager.We inform the game too what AI is it playing by updating the GameManager()

Remember this.ai is an reference(alias) data type too

Since GameManager takes one parameter now, we call it after creating aiPlayer.

Next we update the AI function() by adding one more property.

Now we are have all the parts for making the AI take a move, so let’s go on and begin implementing the logic.

Explanation: Every time we click on an empty cell the AI will clicks on an empty cell as well. For now we make it takeABlindMove(), later on we will add the algorithm to the function. We implement the logic inside our advanceTo() method.

we call .advanceTo every time we click on a cell

The first problem we encounter is that we don’t know how many empty cells are on the board, so let’s create an property on the State() that keeps track of our board.

We update isTerminal() too, in case we have a draw.

.isTerminal returns an boolean, that’s why we return true if it’s a draw.

Now we use emptyCells() inside of takeAnBlindMove(), select an random index from it, and then use that index to set the cell.

Until now we set the cell manually , but since we will use it a lot, it’s time to create ourself an helper function that does that for us.

Create an object called ui that encloses all UI related methods and attributes.

Now we use our newly created function.

BEFORE:

AFTER:

ui.insertAt() is just an visual function. it does not take care of updating the board, that’s why we put next.board[indx] = “X”.

Now we complete the takeABlindMove() function.So here we want to chose an random empty cell from the array and put an “O” inside of it.The only problem is that our AI function doesn’t know nothing about the board. Luckily for us we have already attach the AI to the gameManager, so now we will use that reference for getting info about the board.

Et voilà, le jeux sont fait :)

Pro Tip: i encourage you to use console.log every time you have an doubt, console.log is you’re best friend in the world of javascript :)

To check out full code visit my codepen : CodePen V0.3

Next Part: →

--

--