Workshop › Pac-Man-style Maze Chase › Step 1 of 42

Pac-Man-style Maze Chase: The maze as text

Eat every pellet in the maze while four ghosts hunt you. Smooth tile-to-tile movement, buffered turns, ghost AI with four personalities, scatter and chase modes, and power pellets that turn the hunters into the hunted.

What we are doing

A maze game lives on a grid of tiles. The easiest way to design one is to draw it as text: one string per row, one character per tile. We take the canvas and its 2D context, name the tile size, and write the maze.

```js
const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

const TILE = 24
const TOP = 40 // room for the score and the lives
// # wall, - the ghost house, . pellet, o power pellet, P player start. Row 9 is a tunnel: its ends are open.
const MAZE = [
  '###################',
  '#........#........#',
  '#o##.###.#.###.##o#',
  '#.................#',
  '#.##.#.#####.#.##.#',
  '#....#...#...#....#',
  '####.### # ###.####',
  '   #.#       #.#   ',
  '####.# #---# #.####',
  '    .  #---#  .    ',
  '####.# ##### #.####',
  '   #.#       #.#   ',
  '####.# ##### #.####',
  '#........#........#',
  '#.##.###.#.###.##.#',
  '#o.#.....P.....#.o#',
  '##.#.#.#####.#.#.##',
  '#....#...#...#....#',
  '#.######.#.######.#',
  '#.................#',
  '###################',
]
const ROWS = MAZE.length
const COLS = MAZE[0].length
```

What it means

Your turn

Write the code under the three comment lines. You may copy the MAZE rows; check every row has 19 characters.

Skills: Arrays and objects, Drawing on a canvas

All steps

  1. The maze as text
  2. The game loop
  3. Draw the walls
  4. A set of pellets
  5. Draw the pellets
  6. The player
  7. Where can you walk?
  8. What a mover remembers
  9. One frame of movement
  10. Move every frame
  11. Turns you can press early
  12. Glide between tiles
  13. Turn back at once
  14. Swipes on a phone
  15. Eat the pellets
  16. Show the score
  17. Clear the maze
  18. A red ghost
  19. A ghost never turns back
  20. The ghost walks
  21. The ghost hunts you
  22. Four ghosts in the house
  23. One by one out of the house
  24. Scatter or chase?
  25. Every ghost to its corner
  26. Pink cuts you off
  27. Orange is shy
  28. Cyan works with red
  29. Wait for the first key
  30. Tell the player to start
  31. Three lives
  32. Caught!
  33. Game over
  34. Play again
  35. Frighten the ghosts
  36. Power pellets work
  37. Scared ghosts wander slowly
  38. Eat a scared ghost
  39. Blue, then flashing
  40. Harder levels
  41. A best score that lasts
  42. Build it yourself: the slow tunnel