webdevpuneet.com

Snake Game with Levels – Free HTML, CSS & JS Canvas Snippet

Classic Snake Game · Games · Plain HTML, CSS & JS · Live preview

CategoryGames

About this UI Snippet

Snake Game with Levels — Wall Mazes, Lives, Combos, Bonus Pickups & Swipe Controls

Screenshot of the Classic Snake Game snippet rendered live

Snake is the archetypal grid game: a growing line of segments crosses a fixed grid, eating food while avoiding walls and its own body. This version turns that simple loop into a full run: eight unlockable levels with wall layouts, three lives, a combo multiplier, bonus pickups, sound and swipe controls, all in plain canvas code with no libraries or audio files.

Grid state, not pixels

The snake is an array of { x, y } cell coordinates (index 0 is the head) on a 20x20 grid, and walls are stored as a Set of "x,y" keys built from the [x, y, width, height] rectangles in each level's definition. Collision tests are therefore plain lookups, and draw() is the only place where cells are converted to pixels. The canvas buffer is scaled by devicePixelRatio, so the board stays sharp on retina screens.

Eight levels defined as data

The LEVELS array holds everything about a level: its name, how many apples clear it (goal), its starting move interval (tick), a wall tint (hue) and its wall rectangles. Levels run from an open Meadow through Pillars, Crossroads, Corridors, a Fortress with four gates, a Zigzag and a Maze to a dense Inferno. Adding a level is one more object in the array. Every apple eaten also shortens the move interval a little, so each level speeds up while you play it.

Fixed-step loop with a tick accumulator

Gameplay is discrete (one cell per step), but animation is not. A requestAnimationFrame loop adds the elapsed time to an accumulator and calls tick() each time it reaches the current move interval, while particles, floating text, the pulsing food and the screen shake update every frame. The loop also drives pause (Space or P, and automatically when the tab is hidden) and the 1.6x slowdown from the slow-mo pickup.

A direction buffer that never loses a quick turn

steer() compares a new direction with the last buffered one, not only with the current direction. Two quick key presses (for example up and then left) both count, because up is compared with the current direction and left with up. A reversal is ignored, so a mistimed key can never turn the snake into its own neck. The buffer holds at most two turns. The same function is used by the keyboard, by swipes on touch screens (a short drag on the canvas) and by a tap, which starts the snake moving.

Lives, combos and bonus pickups

A crash costs a life and puts the snake back at the start of the same level with your apple progress kept, so a mistake hurts without wiping a whole level. Eating apples within 3.5 seconds of each other raises a combo multiplier up to x5, which multiplies the 10 points per apple. After an apple, a golden coin (worth 50 points times your combo, with two extra segments of growth) or a blue slow-mo pickup can appear for a few seconds with a shrinking ring that shows its remaining time. Clearing a level gives a bonus of 100 points plus 50 per life left, and restores one life.

Progress, sound and sandbox safety

The highest unlocked level and the best score are saved to localStorage inside try/catch helpers, so the game also runs in sandboxed iframes where storage is blocked, it just does not remember progress there. Sound is a tiny Web Audio synth (an oscillator and a gain node per note) whose apple pitch rises with the combo, and a mute button turns it off. The AudioContext is only created inside the Start click, which is what browsers require.

What's included

Features

Eight levels defined as data: name, apple goal, start speed, wall tint and wall rectangles in one array
Levels unlock one by one and the highest unlocked level is saved to localStorage inside try/catch
Three lives: a crash restarts the level's snake but keeps your apple progress, and clearing a level restores a life
Combo multiplier up to x5 for apples eaten within 3.5 seconds of each other, with a countdown bar on the board
Bonus pickups: golden coin for extra points and growth, slow-mo pickup that slows the snake, both on a visible timer ring
Speed rises with every apple eaten, from level 1 at 150ms per move down to a floor of 55ms
Two-turn direction buffer with a reversal guard, so quick turns are never lost and the snake never reverses into itself
Fixed-step tick accumulator inside requestAnimationFrame, so animation stays smooth while movement stays on the grid
Keyboard, WASD and touch controls: swipe to steer, tap to start, Space or P to pause, auto-pause on a hidden tab
Neon canvas look: retina-sharp, glowing head with eyes, particles, floating score text, screen shake and a Web Audio synth with mute

Step by step

How to Use

  1. 1
    Pick a level and startOnly level 1 is open at first. Click "Start Game", read the level banner (name and how many apples to eat), then press an arrow key, a WASD key, swipe on the board, or tap to get the snake moving.
  2. 2
    Steer around walls and yourselfUse Arrow keys or WASD, or swipe on a touch screen. Two quick turns are buffered so tight corners work, and a reversal into your own neck is ignored. Space or P pauses.
  3. 3
    Eat apples and build a comboEach apple gives 10 points. Eat the next one within 3.5 seconds to raise the combo multiplier up to x5. The progress bar above the board shows how close you are to clearing the level.
  4. 4
    Grab the bonus pickupsAfter some apples a golden coin ($) or a blue slow-mo (S) pickup appears for a few seconds. Gold is worth 50 points times your combo and adds growth, slow-mo slows the snake for 6 seconds.
  5. 5
    Use your three lives wiselyHitting a wall or your own body costs a life and puts the snake back at the start of the level, keeping your apple count. At zero lives the run ends and you can try again.
  6. 6
    Clear levels to unlock the next onesEating the level's apple goal clears it for a bonus of 100 points plus 50 per life left, restores one life and unlocks the next level. There are 8 levels in total, and your best score is saved.

Real-world uses

Common Use Cases

Retro arcade section on a portfolio or personal site
Snake is instantly recognisable, and eight levels, lives and unlockable progress give visitors a reason to stay and play. It is self-contained canvas code with no dependencies, so it drops into a "fun stuff" page or a 404 page.
Teaching level data, fixed-step loops and input buffering
The snippet shows three ideas in one small file: levels described as plain data, a fixed-step accumulator that separates game speed from frame rate, and an input buffer that makes fast play feel fair. Compare the grid logic with the Matter.js Stacking Tower Game.
Reference for touch and keyboard input on one game
One steer() function serves keys, swipes and taps, including the reversal guard and the buffer. It is a reusable pattern for any grid or lane game that has to work on both desktop and phones.
Coding exercise on grid collision and level design
Walls as a set of coordinate keys, food placed on a random free cell, and a tail that moves out of the way before the self-collision check are all common interview topics. Designing a new wall layout is a good follow-up exercise.
Themed reskin for a branded or seasonal game
Change the level hues, the apple and snake colours and the wall rectangles to build a branded mini-game for a campaign page, for example a collect-the-logos variant with your own level names.
Engagement game behind an empty state or loading screen
The whole game is a few kilobytes and starts on a tap or keypress, so it works as an easter egg behind an offline page, an empty dashboard or a long upload screen.
Related: Matter.js Stacking Tower Game
See the Matter.js Stacking Tower Game for a related games pattern worth pairing with this one.

Got questions?

Frequently Asked Questions

Edit the LEVELS array. Each entry has a name, an apple goal, a starting tick in milliseconds, a hue for the wall colour and a list of [x, y, width, height] wall rectangles on the 20x20 grid. Keep row 10 free for the first five columns, which is where the snake starts, and make sure every open area stays reachable. Then add a matching numbered button in the HTML and update the level count.

steer() compares each new direction with the last buffered turn, or with the current direction if the buffer is empty. A direction equal to or opposite of that is ignored. Up to two turns are buffered, so two quick key presses both count, but a reversal never does.

Snake moves one cell per step, but the glow, particles, floating text, screen shake and pause all need to run every frame. The loop adds the elapsed time to an accumulator and runs tick() whenever it reaches the current move interval. That keeps movement on a steady grid rhythm while rendering stays smooth, and the interval can change on the fly for speed-ups and slow-mo.

You start a run with three lives. A crash costs one life and restarts the snake at the level start while keeping the apples you already ate. Clearing a level restores one life. Apples eaten within 3.5 seconds of each other raise a combo from x1 to x5, which multiplies the 10 points per apple, and the combo drops back to zero when the timer runs out or you crash.

Yes. Swipes on the canvas steer the snake and a tap starts it, and pointer events and touch-action: none keep the page from scrolling. localStorage reads and writes are wrapped in try/catch, so a blocked storage only means that your best score and unlocked levels are not remembered, and every sound call is wrapped too, so a blocked audio device never stops the game.

Copy & paste

Source Code

<div class="sn-wrap">
  <div class="sn-header">
    <h2>Snake</h2>
    <div class="sn-scores">
      <span>Level <strong id="sn-level">1</strong></span>
      <span>Score <strong id="sn-score">0</strong></span>
      <span>Best <strong id="sn-best">0</strong></span>
    </div>
  </div>
  <div class="sn-progress"><div class="sn-progress-bar" id="sn-progress"></div></div>

  <div class="sn-canvas-wrap">
    <canvas id="sn-canvas" width="400" height="400"></canvas>
    <div class="sn-overlay" id="sn-overlay">
      <p class="sn-overlay-title" id="sn-overlay-title">Snake</p>
      <p class="sn-overlay-sub" id="sn-overlay-sub">Eat the apples to clear each level. Walls get trickier and the snake gets faster. You have 3 lives.</p>
      <div class="sn-levels" id="sn-levels" role="group" aria-label="Level">
        <button class="sn-level active" data-level="1" type="button" aria-pressed="true" aria-label="Level 1">1</button>
        <button class="sn-level" data-level="2" type="button" aria-pressed="false" aria-label="Level 2">2</button>
        <button class="sn-level" data-level="3" type="button" aria-pressed="false" aria-label="Level 3">3</button>
        <button class="sn-level" data-level="4" type="button" aria-pressed="false" aria-label="Level 4">4</button>
        <button class="sn-level" data-level="5" type="button" aria-pressed="false" aria-label="Level 5">5</button>
        <button class="sn-level" data-level="6" type="button" aria-pressed="false" aria-label="Level 6">6</button>
        <button class="sn-level" data-level="7" type="button" aria-pressed="false" aria-label="Level 7">7</button>
        <button class="sn-level" data-level="8" type="button" aria-pressed="false" aria-label="Level 8">8</button>
      </div>
      <p class="sn-level-name" id="sn-level-name">Level 1: Meadow</p>
      <button class="sn-new-btn" id="sn-new-btn" type="button">Start Game</button>
    </div>
  </div>

  <div class="sn-footer">
    <span class="sn-lives" id="sn-lives" aria-label="Lives">&#9829; &#9829; &#9829;</span>
    <span class="sn-hint">Arrows / WASD / swipe. Space pauses.</span>
    <button class="sn-mute" id="sn-mute" type="button" aria-pressed="false">Sound on</button>
  </div>
</div>

Extend with AI

Take This Snippet Further With AI

Paste this snippet's HTML, CSS, and JS into an AI coding assistant like Claude and ask it to explain how the tick accumulator in frame() separates move speed from frame rate, how steer() buffers two turns without allowing a reversal, and why tick() leaves the tail out of the self-collision check unless the snake is still growing. It is also a good snippet to extend with AI help: ask for a level editor that saves custom wall layouts, a wrap-around mode where the edges teleport, a second snake controlled by an AI that chases the apples, or a daily challenge with a seeded random apple order. You can also ask it to check every level for unreachable areas with a flood fill.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a Snake game with levels using the HTML5 Canvas API in plain HTML, CSS and JavaScript, with no frameworks and no audio files.

Requirements:
- A 20x20 grid on a 400x400 logical canvas (sharp on retina screens by scaling the buffer with devicePixelRatio). The snake is an array of {x, y} cells and walls are a Set of "x,y" keys built from [x, y, width, height] rectangles.
- Eight levels defined in an array (name, apple goal, starting tick in ms, wall tint hue, wall rectangles), from an open board to dense mazes. Every apple eaten makes the snake slightly faster. Level 1 is open at first, clearing a level unlocks the next, and the highest unlocked level is saved to localStorage inside try/catch. Show a level select on the start screen with locked levels disabled.
- A requestAnimationFrame loop with a time accumulator that calls a tick() function every current move interval, so movement stays on the grid while particles and effects animate every frame.
- Controls: Arrow keys and WASD, swipe on the canvas for touch, a tap to start, Space or P to pause, and auto-pause when the tab is hidden. Buffer up to two turns and ignore any turn that is the same as or the opposite of the last buffered direction.
- Collision with the outer border, a wall or the snake's own body costs a life (three lives per run). The tail should be treated as free on the same tick unless the snake is still growing. After a crash the snake restarts at the level start and waits for input, while the apples eaten so far are kept. At zero lives show a game-over screen with a retry button.
- Apples give 10 points times a combo multiplier (up to x5) when eaten within 3.5 seconds of the previous one. After an apple, sometimes spawn a bonus pickup with a visible timer ring: a golden coin (50 points times the combo plus extra growth) or a slow-mo pickup (the snake moves slower for 6 seconds).
- Clearing a level gives 100 points plus 50 per life left, restores one life (up to the maximum) and shows a "Next Level" button that keeps the score and lives. Beating level 8 shows a win screen. Show a progress bar for the apple goal, the lives, the level, the score and a best score saved to localStorage.
- Game feel: glowing head with eyes that face the direction of travel, particles on eating, floating score text, screen shake on a crash, a level banner before each level, and Web Audio synth sounds (oscillator plus gain node) with a mute button, created inside the Start click.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.