| Symptom | First action | Planning use |
|---|---|---|
| Snake lands between cells or looks misaligned | Keep all game state in cell coordinates and convert to pixels only when drawing. | Food, wall and body checks become plain comparisons of cell positions. |
| Snake moves too fast or too slow | Run the update on a fixed timer. One tutorial calls setInterval with a 200 ms delay. | The tick length is your difficulty setting. |
| Snake never grows, or grows on every move | Add a new head each move and drop the tail only when no food was eaten. | Length changes only when the head reaches food. |
| Food appears under the snake | Re-pick a random cell until it is not on the snake. | Placement stays fair at any snake length. |
| Game over fires at once or never fires | Compare the head with body cells after index 0, and check the border. | Decide early whether walls kill or wrap. |
| Snake flips back onto itself | Ignore a direction that opposes the current movement. | Reversal is blocked at input time, not treated as a crash. |
The rules in this table come from Sam Clarke’s JavaScript snake tutorial and a 3D snake tutorial on DEV Community.
Here is how to make snake game in JavaScript: store the snake as an array of grid cells, advance it on a timer tick by adding a new head and dropping the tail, then check walls, body and food.
This project is a compact entry point into the wider topic of how to make a browser game, so it is a good place to learn the loop, drawing and input pieces that larger games reuse.
What you are building
You will build a playable Snake on an HTML canvas. It needs basic JavaScript, a page with a canvas element, a text editor and a browser. The finished game has a grid, a snake that grows when it eats, food that appears in empty cells and a game-over rule.
The design choice that makes this simple is discrete movement. Sam Clarke’s tutorial explains it directly: “Since snake is a grid based game, I decided to make a basic grid object to handle drawing the cells.” The snake does not glide across pixels. It jumps a whole cell on every tick of a timer, and every rule in the game reads from cell coordinates.
Setting up the canvas and grid
Start with a canvas element and ask it for a drawing surface. The Canvas API gives you that through canvas.getContext(“2d”), which is how Sam Clarke obtains his context. From there, wrap cell drawing in one small grid helper so the rest of the game never multiplies by pixel sizes.
Choosing grid dimensions
Tutorials use a range of sizes. A straker gist notes that its 400×400 canvas is a 25×25 grid. Another walkthrough on alexjpaz.github.io uses a 200×200 px board with 10 px cells, giving 20 cells per side.
For a first build, a small square grid is easiest to reason about and to debug. Define the cell size and the cell counts as constants, and derive the canvas width and height from them. Changing the grid later then means editing two numbers.
- Symptom: the snake looks stretched or blurry. Fix the canvas size to cell count times cell size, and avoid stretching it with CSS.
- Symptom: nothing is drawn. Check that the context was requested from the canvas element you actually added to the page.
Representing the snake in code
The snake is an Array of cell coordinates. The alexjpaz tutorial states the choice plainly: “I chose to keep the track of how long to draw the tail by having an array of tail coordinates.” Each entry holds an x and a y in cell units, and the head is the entry the other rules compare against.

Because the body is just a list, drawing is a loop that fills one cell for each entry, and length is the array’s length. Food is a single cell with the same x and y shape, which lets you reuse one equality helper for every comparison in the game.

- Symptom: the snake seems to teleport or draw in the wrong place. You are probably mixing pixel and cell units. Store cells, convert at draw time.
- Symptom: the snake shows only a head. The body array is not being drawn in full. Loop over every entry, not just the first.
Moving the snake on a tick
Movement is a tick-based update. On each tick, copy the head, shift it one cell in the current direction and put it at the front of the array. Sam Clarke’s code does this with snake.unshift(head). Then remove the last entry, unless the new head landed on food, in which case you keep it and the snake grows.
Timing the tick
The simplest driver is setInterval. The DEV Community tutorial runs its update with setInterval and a 200 ms delay, with the comment that the snake moves forward every 200ms. A game loop can also be slowed instead: the straker gist drops its loop from 60 to 15 updates per second, which means running the update once every 4 frames.
Treat the interval as a tuning knob. A longer delay suits beginners and touch-pad play, while a shorter delay raises difficulty. Keep drawing and logic in the same tick so the picture never shows a state the rules have not processed.
- Symptom: the snake speeds up after restarting. A new timer was started without clearing the old one, so two updates run per tick period. Keep the timer handle and clear it on game over.
- Symptom: the snake grows forever. The tail removal is running only in the food branch. It should run on every move that did not eat.
Placing food in an empty cell
Pick a random cell, then reject it if the snake occupies it. Sam Clarke’s version repeats the pick in a loop that continues while snake.some finds a segment equal to the random cell. The DEV Community tutorial states the same rule: food should not coincide with the previous position or the current snake body.

The retry loop is the right default. It is short, it reuses the cell-equality helper and it stays quick while the snake is small relative to the grid. If the snake could ever fill most of the board, a list of free cells would be a sturdier choice, but a beginner build does not need it.
- Symptom: food appears off the grid edge. Your random range includes the grid width or height itself. Cells run from zero up to, but not including, the count.
- Symptom: food spawns on the snake and vanishes. The retry check is missing or compares the wrong fields.
Detecting collisions and steering
Collision detection in Snake is three small checks run after each new head is computed: the wall, the body and the direction input.
Walls
You have two valid designs. The DEV Community tutorial ends the game when the snake reaches the border or touches its body. Sam Clarke’s version instead wraps: when the head’s x reaches the grid width, it is set back to 0, and the same idea applies on the other edges.
Choose a killing wall for a classic, tense game and a wrapping wall for a relaxed one. Whichever you pick, test the edge cells explicitly, because off-by-one mistakes show up there first.

Body
Self-collision compares the new head with every other cell. Sam Clarke returns snake.slice(1).some with a cell-equality test, so index 0 is excluded and the head is never compared with itself. The alexjpaz tutorial describes the same end state: the player runs into a section of its own tail.
Reversing into itself
Block reversal when handling input, before the tick uses the new direction. Sam Clarke’s handler simply ignores a key press when it tries to go back on self. The straker gist does it by checking the current axis, so a horizontal mover cannot take a horizontal reverse and a vertical mover cannot take a vertical one.
Without this guard the head would step straight onto the segment behind it, and the self-collision check would end the game on a key press instead of a real mistake.
Next project
Once Snake runs, how to make pong in javascript is a natural second build to compare against, and it lets you practise the same canvas drawing on a different game.
Frequently asked questions
| Question | Answer |
|---|---|
| How do I generate a random whole number for the food position? | Use Math.random scaled to a range and floored. For an inclusive maximum, the alexjpaz tutorial returns Math.floor(Math.random() * (max – min + 1) + min). For an exclusive maximum, Sam Clarke’s version returns Math.floor(Math.random() * (max – min)) + min, which suits a cell count. |
| Does the grid have to be square? | No. Sam Clarke’s tutorial creates a 40 x 25 grid of 15 px cells, while the other tutorials mentioned above use square grids. |
| Do I need a framework? | No. The Canvas 2D context from getContext(“2d”) is enough to draw cells. If you want one later, try this phaser tutorial for beginners. |



