Skip to content
Projects

Snake

You (blue) vs AI (red) — use arrow keys to play

Snake vs AI

Control your snake with arrow keys. Eat apples to grow — your opponent shrinks. Last snake standing wins.

You
AI
Apple

Behind the Build

Building Snake: Competing Against Your Own Code

How a classic arcade game became an exercise in game architecture, AI design, and the joy of losing to something you built.

I grew up playing Snake on old Nokia phones. If you were a kid in the early 2000s, you know the one — that tiny pixelated line on a green-gray screen, growing longer every time you ate a dot, with nothing but your own tail to kill you. No levels, no boss fights, just you and the ever-shrinking space you had to navigate. I played it everywhere: in the car, at the dinner table, in the back of classrooms where I definitely should have been paying attention.

When I started looking for my next project after Wordle, that nostalgia hit hard. But I didn’t want to just recreate the solo experience — I’d done that a hundred times on that Nokia. I wanted to add a competitive edge: what if you weren’t alone on the board? What if there was an AI opponent hunting the same apples, and every apple you ate didn’t just grow you — it shrank your opponent? Starve them to zero and you win. Crash into anything and you lose. That twist turned a simple nostalgia project into something with real design challenges.

Processing: The Right Tool for the Job

I built the original in Processing (Python mode) — a creative coding environment designed for visual, interactive sketches. Processing gives you a setup() function that runs once and a draw() loop that runs every frame. It’s the perfect mental model for a game: initialize your state, then update and render 60 times a second.

What makes Processing great for a project like this is that the rendering primitives are dead simple. Drawing a snake segment is just square(x, y, size) and ellipse(x, y, w, h). No sprite sheets, no texture loading — just shapes and colors. That simplicity let me focus on what I actually cared about: the game architecture and the AI.

Architecture: Classes All the Way Down

The project is structured around clear object-oriented design. The GameController owns the board state — it tracks “deadly points” (any occupied cell that will kill you on contact), manages the apple, and handles end-game conditions. Each Snake is composed of SnakeSquare objects and delegates its movement input to a SnakeController.

That controller abstraction is the key design decision. The human snake and the AI snake are the exact same class — they differ only in who’s sending the directional inputs. The human’s controller reads keyboard events. The AI’s controller calculates the best move. The snake itself doesn’t know or care which one it is.

controller pattern
# Both snakes are identical — only their controller differs
human_snake = Snake(gc, 'Human', gui_controls)  # keyboard input
ai_snake    = Snake(gc, 'AI',    ai_control)     # calculated moves

# The Snake class just calls:
#   controls.set_snake(self)
# Then the controller sends directions whenever it decides to.
# The snake doesn't know if a human or algorithm is driving it.

The AI: Simple But Effective

The AI isn’t a neural network or anything exotic. It’s a scoring function that evaluates each of the four possible directions every frame and picks the highest-scoring one. Two factors drive the score:

  • Clearance score — how many of the neighboring cells around the target position are unoccupied. This keeps the AI from boxing itself into corners.
  • Apple distance — the minimum distance to the apple, accounting for the board’s wrap-around edges (the shortest path might be going off one side and appearing on the other).
ai._choose_dir()
def _choose_dir(self):
    scores = {UP: 0, DOWN: 0, LEFT: 0, RIGHT: 0}

    for direction in scores.keys():
        coordinates = self._get_neighbor_coord(direction)
        # Will I crash? How open is the space around me?
        neighb_score = self._clear_score(coordinates)
        # How far am I from the apple (with wrap-around)?
        appl_dist_score = self._apple_distance(coordinates)
        scores[direction] = neighb_score + appl_dist_score

    return max(scores, key=scores.get)

It’s the kind of AI that’s beatable but not stupid. It won’t walk into walls, it actively chases the apple, and it tries to keep its options open. Sometimes it outplays you. Sometimes it corners itself because it can’t see more than one move ahead. That imperfection is what makes it fun — you’re playing against something that feels like it’s trying, not something that’s omniscient.

Bringing It to the Browser

Processing has a JavaScript counterpart called p5.js — same API, same mental model, runs in a canvas element. The port was almost mechanical: every fill(), stroke(), and ellipse() call translates directly. The biggest change was shifting from Processing’s normalized color mode (0.0–1.0) to p5’s default RGB (0–255), and restructuring from Python’s flat files into TypeScript classes.

The game you played above (or are about to) is running the same logic as the original Processing sketch. Same grid size, same speed control, same AI scoring function. It’s a direct port — not a reimagining, not a “web version inspired by.” The architecture mapped one-to-one.

What I Learned

This project taught me more about software design than most things ten times its size. The controller pattern — making the snake agnostic about who’s driving it — is the kind of abstraction that textbooks love to explain and codebases rarely bother to implement. Here, it wasn’t theoretical. It was the reason I could add an AI opponent without changing a single line of the Snake class.

The “deadly points” set is another lesson in choosing the right data structure. Every cell occupied by either snake is tracked in a single set. Collision detection is an O(1) lookup instead of iterating through every body segment. When a tail moves, its old position gets removed. When a head moves, its new position gets added. Simple bookkeeping, huge performance win.

If you want to dig into the full implementation — the original Processing Python and the TypeScript port — it’s all on GitHub. And if the AI beat you, don’t feel bad. It beats me too.

IP

Ivan Pedroza

Software Engineer — Seattle, WA

View on GitHub