Posted on

Scratch Coding – Pacman

Today we are going to build a Pacman game. If you have never seen Pacman before, well you’re in for a real treat. The goal of the game is to move the yellow Pacman around the screen and eat all of the food pellets. We must also make sure that we avoid the ghosts!

We already have a nice backdrop with a Pacman style maze:

We also have a few sprites that we can use to develop our game:

You might notice that the Pacman has a little black dot in front of him, we are going to use that dot to detect if a maze part is in front of us.

Pacman

Let’s start by moving Pacman around the maze.

We want to always be checking to see if the player has pressed an arrow key, if we always want to be doing something, then we should consider using a forever block.

The next item to check is if the player has pressed an arrow key:

Repeat this for the up / down & right keys.

Test our game. Does Pacman move around the Maze? Does he stop at the maze walls?

Moving Animation

One of the cool things that Pacman does as he moves, is he opens and closes his mouth, we can use another green flag hat block and check for the arrow key presses.

If either the left / right or up / down are pressed we can switch to the next costume in the Pacman sprite. We can add a small delay so that it looks like Pacman is eating at a normal rate.

Crossing the Screen

If we move to the edge of the screen, we expect Pacman to cross over to the other side of the screen. Let’s add some code to always check where Pacman is.

This code checks to see if Pacman has gone past the boundary of our backdrop, which is located at 165, and -165. (not the normal 240 and -240)

Ghost Movement

Our ghosts should move around the screen, we are going to make them move in two different directions:

Up/Down

Moving the Y position up and down depending on if the ghost hits a maze colour. After each touch we add a little bit of movement in the opposite direction, this prevents the ghost getting stuck on the maze wall. Only add one of these to each type of ghost, so pick a ghost that moves up and one that moves down.

You will be able to duplicate the ghosts later to make your game harder.

Left/Right

Moving the Ghost left to right has us changing the X position. We follow the same pattern as moving up and down.

Food Pellets

Finally, we can add food pellets to the game and have them hide when they are touched by Pacman. We can duplicate more of these items and place them in other locations on our screen.

Extra Challenges

  • Add a scoring system
  • Add code to make Pacman die if he touches a ghost