Score: 0

High Score: 0

Build Your Own Snake Game

Snake and Apple Game

🌟 What You'll Learn

  • Basic game development concepts
  • HTML5 Canvas drawing techniques
  • Keyboard controls implementation
  • Score tracking and collision detection

Game Overview

This classic Snake game features:

How It Works (Simple Explanation)

  1. The game board is drawn using HTML5 Canvas
  2. Arrow keys control the snake's direction
  3. The snake automatically moves forward
  4. Eating food increases score and snake length
  5. Collisions with walls or self end the game

Game Loop Essentials

function drawGame() {
    // Clear canvas
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Move snake
    let newHead = { x: snake[0].x, y: snake[0].y };
    // Update position based on direction
    // Check collisions
    // Draw snake and food
}

This function runs every 100ms to update game state

Snake Movement Code

document.addEventListener("keydown", (event) => {
    switch(event.key) {
        case "ArrowLeft": direction = "LEFT";
        case "ArrowRight": direction = "RIGHT";
        case "ArrowUp": direction = "UP";
        case "ArrowDown": direction = "DOWN";
    }
});

Keyboard controls update the snake's direction

Key Programming Concepts

1. Canvas Rendering

The game uses HTML5 Canvas to draw:

  • Black background
  • Green snake blocks
  • Red food items

2. Game Loop

The heart of the game updates:

  • Snake position
  • Collision detection
  • Score calculation

Food Generation

function generateApple() {
    do {
        x = randomXPosition();
        y = randomYPosition();
    } while (positionOccupiedBySnake());
}

Ensures food never spawns inside the snake

SEO Keywords

How to Use This Code

  1. Copy the HTML structure
  2. Paste the JavaScript code
  3. Add CSS styling
  4. Run in modern web browser

Pro Tip: Try modifying the snake speed or colors to create your own version!