Every project / Games

šŸ Snake

The classic: eat the food, grow longer, don't bite yourself.

Snake running
Language
HTML, CSS & JavaScript
Level
Beginner
Category
Games
ā–¶ Try it & remix

What you'll learn

  • Canvas drawing
  • Arrays
  • Keyboard events
  • Game loops
  • localStorage

How it works

  • The board is a 20Ɨ20 grid. The snake is a list of squares, head first.
  • Every 120 ms, step() adds a new head in the direction you're going. If the snake didn't eat, it drops the tail, which makes it look like it's sliding along.
  • Arrow keys go into a queue, so two quick presses both count, and you can't turn straight back into yourself.
  • Hitting a wall or your own body ends the game. Your best score is saved with localStorage.

Knobs to turn

These settings are near the top of the code. Remix it, change one, and watch what happens. The preview updates as you type.

SettingStarts atFileWhat it does
SIZE20game.jssquares per side
SPEED120game.jsmilliseconds per move (smaller = faster)

Files

FileLines
index.html21the page: what shows up
game.js106what it does
style.css38how it looks

Challenges

Each one is a bit harder than the last. Teachers: these make good assignment instructions.

  1. Change the colors of the snake and the food.
  2. Make the snake speed up a little every time it eats.
  3. Add a golden apple that appears sometimes and is worth 5 points.
  4. Let the snake wrap around to the other side instead of hitting the walls.
  5. Add walls or obstacles in the middle of the board.