Lesson 27: Artificial Intelligence

In the last lesson you added a ghost to the game that moved in one direction until it hit the wall. In this lesson, you are going to give the ghost some instructions about how and where to move. This AI (Artificial Intelligence) will determine how well the ghost is at chasing Pacman.

1. Declare a global variable that you will use to keep track of the direction redGhost is moving.

2. Towards the bottom of loop(), replace the code that is moving redGhost, including the hit test that is stopping it from moving through walls, with the following code.

So what is going on here?

You created rgX (x value of red ghost) and rgY (y value of red ghost) to store the coordinates of redGhost. You will use these values later.

You created rgNewDirection to store the new direction of redGhost.

You create rgOppositeDirection and set it equal to the opposite direction of redGhost's current direction.

You randomly select a new direction, and continue to do this until the new direction selected is not opposite the redGhost's current direction.

Ok... so this code is not working just yet, and this ghost will not have the most sophisticated AI. Once we finish the code, redGhost will randomly move about the gameWindow, always looking for a new direction to turn and never reversing into the opposite direction.

3. Now that you know what direction you want to move redGhost in, add the code to do so. After redGhost has been moved, set the current direction (rgDirection) to equal the new direction (rgNewDirection).

This should cause the ghost to continually move in different directions, but not yet within the constraints of the walls.

4. Move the code into a do/while loop that continues to randomly select a new direction and move redGhost every time that the ghost is moved onto a wall.

Notice the top two lines of the do block resets redGhost to it's previous position so that if redGhost does hit a wall, it is moved back to this original position. Once redGhost is moved to a position that is not hitting a wall, then the loop can stop, leaving redGhost in its new position, and the current direction of redGhost can be updated to its new direction.

Now redGhost and pacman can move about the gameWindow until they collide.

Shaking Ghosts?

Make sure the walls are spaced so that the pathways are exactly the same size as the ghost (40px).
Why do the ghosts shake when the pathways are too large?

Because the walls are not stopping the ghosts from changing direction, they do change direction. That is what we programmed them to do: change direction when possible.

Soon you will want to add code to move the other ghosts as well. This is alot of code to stick into the loop() function.

5. To keep the code easily understandable to you and others looking at your code, move the code for moving the red ghost into a separate moveRedGhost function.

6. Then all you need in loop() is the moveRedGhost(); function call.