DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

I Built Pac-Man in ~150 Lines of Vanilla JavaScript

Pac-Man looks like it needs serious AI and a physics engine. It needs neither — a maze stored as text, grid movement, and ghosts that just step toward you. About 150 lines of vanilla JavaScript.

🟡 Play it: https://dev48v.infy.uk/game/day11-pacman.html

1. The maze is a grid of text

const MAZE = ["#####","#...#","#.#.#"];  // # = wall, . = pellet
Enter fullscreen mode Exit fullscreen mode

Everything — movement, collision, pellets, ghost moves — is a lookup into this grid. The whole level is data you can edit by typing.

2. Grid movement, blocked by walls

if (MAZE[pac.y+dy][pac.x+dx] !== "#") { pac.x += dx; pac.y += dy; }
Enter fullscreen mode Exit fullscreen mode

That one check IS your collision system. No pixel math.

3. Buffered input feels right

Store a wanted direction separately; switch to it when that way opens. That tiny buffer is the difference between responsive and stiff controls.

4. Eat pellets = change the grid

if (grid[y][x] === ".") { grid[y][x] = " "; score += 10; pellets--; }
Enter fullscreen mode Exit fullscreen mode

When pellets hits 0, the maze is cleared.

5. Ghosts: greedy chase

From a ghost's legal moves, pick the one closest to Pac-Man (plus a little randomness so you can escape). Greedy distance-minimising is surprisingly menacing.

The takeaway

A text maze + grid steps + greedy ghosts = the whole arcade icon. Play it — the "Understand" tab walks each step.

Top comments (0)