# Tic Tac Toe 2: Easy AI

Planning
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
Challenge
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
Step 6

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

Planning
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"
Information
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```

Challenge
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
Step 12

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

Planning
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:

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

Challenge
Step 16
Run the computer's turn after the wait time is over
Step 17

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

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

Account

MVCode Clubs

Created By

Course:

Artificial Intelligence (A.I.)

Access Level