Skip to main content

Snake Game

Live

A classic Snake game rebuilt with HTML Canvas and JavaScript featuring smooth WASD controls, progressive difficulty, and persistent leaderboard system.

MediumJavaScriptHTML5 CanvasCSS310-15 min
Loading...

How to Play

  1. 1Click "Start Game" to begin playing
  2. 2Use WASD keys to control the snake direction
  3. 3Eat food (pink squares) to grow longer and score points
  4. 4Avoid hitting walls or your own tail — game over!

Controls

Move UpW
Move DownS
Move LeftA
Move RightD
Start/RestartClick Button

Tips

  • Plan your moves ahead to avoid trapping yourself
  • Use the walls to help navigate tight spaces
  • The snake moves faster as you score more points

What I Learned Building This

This was a significant step up from the clicking game — my first project involving real-time game loops and collision detection.

Technical Concepts Mastered

  • Game Loop Architecture — Using requestAnimationFrame for smooth 60fps gameplay instead of setInterval, which provides better performance and handles tab visibility
  • Collision Detection — Implementing boundary and self-collision checks efficiently by comparing head position against walls and every body segment
  • State Management — Tracking snake position array, direction, score, and game state (START, PLAYING, GAME_OVER) all in sync
  • Keyboard Input Handling — Responding to WASD keys in real-time while preventing direction reversals that would cause instant death
  • Canvas Rendering — Drawing and clearing game elements efficiently with proper timing to avoid visual artifacts

Challenges Overcome

The hardest part was preventing the snake from reversing into itself. I learned that you need to validate direction changes against the current direction before applying them — you can not go left if already going right, for example. I also had to queue direction changes and only apply them on the next game tick to prevent rapid key presses from bypassing the check.

Another challenge was getting the game loop timing right. Using requestAnimationFrame with a timestamp check ensures the snake moves at a consistent speed regardless of frame rate, while still rendering smoothly at 60fps.

Key Takeaway

Games taught me that programming is about managing state over time. Every frame is a chance to update, check, and render — and getting that loop right makes everything else possible. The snake game also showed me the importance of separating game logic timing from render timing.