Tic Tac Toe 2: Easy AI

Step 1
We will be making the Tic Tac Toe game into a one player game!

Make sure you did the previous lesson "Tic Tac Toe" which focused on making the two player game.

Step 2
Create a new boolean variable to indicate if it will be a one player game
Step 3
Create a new function named "endTurn" that will end a player's turn and update the board

Cut and paste the code from the mousePressed function and then call the new function like so:

Step 4
Now create an if-else if statement to check if the game is in one player mode when the mouse is clicked
Step 5
If it is player 1 turn and the grid square is empty, then place an "X" in the square and end the player's turn
Check Your Work
Step 6
Save and run your code

Click on the screen to check if the "X" is placed and the turn is switched to Player 2.

Step 7
The computer will be choosing a random number for its move

In case you forgot, the grid is an array that starts at 0 and ends at 8

Step 8
Create a new function named "computerTurn"
Step 9
The pseudocode for a computer's turn will be:

1) Assign index to a random number
2) Until index is an empty square, assign index to another random number
3) Put a "O" in that square
4) End the computer's turn

Step 10
Code the computer's turn logic inside the computerTurn function

Use the step above for hints!

Step 11
Inside the mousePressed function, run the computer's turn after Player 1's turn if the game has not ended
Check Your Work
Step 12
Save and run your code

The computer should now instantly play a move after the player does his turn!

Step 13
Next we will be adding a pause between the player 1's turn and the computer's turn

That way it seems more realistic in reaction speed.

Step 14
Create a variable to track how many milliseconds to wait for the computer to complete its turn

I used 500 to indicate half a second but feel free to change it to whatever you desire:

Step 15
The "setTimeout" function allows us to call a certain function after a certain amount of time

Here's a website with more information: https://www.w3schools.com/jsref/met_win_settimeout.asp

Step 16
Run the computer's turn after the wait time is over
Check Your Work
Step 17
Run and save your code

The computer's turn should now wait half a second after the player's turn.

Step 18
(OPTIONAL) Add an if statement to the setup function so the computer can also move first if desired
Step 19
(OPTIONAL) Make it 50-50 chance whether the player or computer starts

The code random(0, 1) < 0.5 is basically a coin flip because it has 50% chance to return true or false

Check Your Work
Step 20
The lesson is now complete!
Tic Tac Toe 2: Easy AI Info


MVCode Clubs

Created By



Artificial Intelligence (A.I.)

Access Level


For Teachers and Schools

Teach coding to your students with MVCode Teach

MVCode offers an integrated product designed to teach coding to students.

Learn more about MVCode Teach