Rolando Andrade
Back to projects

Built in 2019

Snake

HTML Canvas Snake Game

Snake preview

Snake HTML Canvas video-game. It was refactored in 2021 migrating to TypeScript and using Vite.

Browser games feel like magic when you learn to code. A few lines of JavaScript, and shapes move on the screen. No compiling. No setup. You open a file and it runs.

The magic fades fast. Messy code piles up. Every new feature hurts. What started as fun turns into a mess.

I wanted a browser game that stayed easy to change. It needed a clear structure that I could extend later. Snake was a good fit. The rules are simple, everyone knows how it plays, and there is always something to polish.

Eat, grow, survive

The game draws on an HTML Canvas element. You steer a cyan snake on a dark gray board with the arrow keys or WASD. The goal is the classic one. Eat the red food, grow longer, and do not hit your own tail.

The snake starts with four segments and moves at a steady pace. Each piece of food adds one segment. Your score shows in the corner. Hit a wall or your own body, and the game ends.

Press Enter or Space to play again. The game is simple on purpose. I wanted the focus on clean code, not flashy features.

Shapes that draw themselves

All drawing uses the Canvas 2D API on one canvas element. Each frame, the game clears the background and draws everything again.

Every shape is an object with a position, a size and a color. A base shape knows how to draw a rectangle on the canvas. Game elements extend that base and add their own behavior.

This inheritance keeps drawing code apart from game code. The snake does not need to know about the canvas. It only tracks where it is.

A loop every 100 milliseconds

At the center is a loop that runs every 100 milliseconds. This fixed timestep makes the game play the same on a fast or slow browser.

Each pass runs the same steps:

  1. Draw the background
  2. Move the snake
  3. Check for food
  4. Update the score
  5. Draw all elements
  6. Check if the snake died

The loop stops when the snake dies. A game over screen tells you how to restart. Enter resets the state and starts a new game.

The body follows the head

The snake body is an array of segments. Each segment has a position and a velocity. The head leads and the rest follow.

Movement is a chain reaction. First the head moves with its current velocity. Then each segment moves to the old position of the segment in front of it. That makes the snake trail.

Turning only changes the head. Press an arrow key, and the head’s velocity changes. The body takes the new direction as it follows.

A guard blocks illegal moves. You cannot turn back into yourself. Pressing left while you move right does nothing. That small check prevents annoying instant deaths.

Walls, tail and food

The game checks two kinds of collisions. For walls, it compares the head position with the edges of the grid. For the body, it searches the segment array for a matching position.

The grid uses one unit per cell. To get the pixel position on the canvas, the game multiplies the grid position by the cell size. Keeping grid and pixels apart makes the collision math simpler.

Food uses the same grid. When the head lands on the food, the snake grows. The food then jumps to a random empty cell.

Food never spawns inside

Food has to appear in a free cell. Spawning inside the snake would be unfair.

The algorithm makes a list of every cell on the grid. It removes the cells the snake covers. Then it picks one of the rest at random. The food always lands in a valid cell.

On a 20x20 grid with a short snake, this is fast. A very long snake on a bigger board could slow it down. For normal play, it works well.

One manager for keys

One central manager turns key presses into game actions. It listens for keydown events and calls the callbacks that registered for them.

Several keys can trigger one action. Arrow keys and WASD both steer. Enter and Space both restart. Players can use whichever keys they like.

With callbacks, each part of the game reacts to input on its own. The snake registers the direction handlers. The game manager registers the restart handlers. Neither one needs to know about the other.

TypeScript two years later

I first wrote the game in JavaScript in 2019. It worked, but without types every change was risky. In 2021, I rewrote all of it in TypeScript.

Now there are types everywhere. Interfaces describe the shape of each game object. The compiler catches mistakes before the game runs. Jumping around the code in an editor got much easier.

I also swapped the old build setup for Vite. Hot module replacement reloads only the code you changed, so development is faster. The production build is tiny. One script deploys it to GitHub Pages.

One job per module

The hardest part was keeping the code organized. A game has many systems that talk to each other: input, drawing, physics and scoring. Without discipline, they blur together.

I drew clear lines between them. Each module has one job. The snake handles movement and growth. The food handles spawning. The game manager coordinates everything.

TypeScript inheritance fit these relationships. Shapes draw themselves. Game elements are shapes with extra behavior. The hierarchy came straight from the problem.

Old code, new eyes

Browser games do not need frameworks. The Canvas API is enough for 2D games, and plain JavaScript lets you control every pixel.

The rewrite showed me why old code is worth a second look. What seemed fine in 2019 looked amateur in 2021. With more experience, the rewrite came out better than the original could have been.

Simple games are great for learning. Everyone knows the rules and the scope stays small. You can spend all your attention on how you build, not on what you build.

Interested in working together? Check out my services and pricing to see how we can collaborate on your next project. Let's Build