Free

Snake Game

The classic game in about 180 lines of plain JavaScript and a canvas.

  • JavaScript
  • Canvas
  • HTML

About this project

Snake, written to be read. Arrow keys or WASD, a speed slider, a pause, a high score that survives a refresh, and touch controls that only appear on a device without a mouse.

The idea worth taking from it is that the board is a GRID, not pixels. The snake lives at {x: 7, y: 4} — a cell. Pixels appear in exactly one function, where a cell is multiplied by the cell size. Keep that separation and collision detection is comparing two integers; work in pixels instead and it becomes overlapping-rectangle maths that is easy to get subtly wrong.

What you will learn

  • Model a game board as a grid of cells rather than pixels, and see why collision detection becomes trivial
  • Move a snake by adding a head and dropping a tail — two lines that describe all of its motion
  • Queue input so a fast player cannot reverse into themselves between frames
  • Draw to a canvas, and scale it with CSS without blurring the drawing buffer
  • Keep a high score in localStorage

Before you start

  • JavaScript basics — variables, functions, arrays
  • A browser and a text editor. Nothing to install.

New to JavaScript? The free JavaScript course covers everything this project assumes.

Academic integrity notice

These projects are provided for learning, experimentation and reference. Understand the code, modify it for your own requirements, and acknowledge external work according to your institution’s academic policies. Priodemy does not supply work to be submitted as your own.