Code For Snake Game In Html

8 min read

Code for Snake Game in HTML

Introduction

Learn how to create a fully functional snake game using only HTML, CSS, and JavaScript. This article provides the complete code for snake game in html, step‑by‑step instructions, and clear explanations so you can build, understand, and modify the game yourself. By following the guide you will have a playable snake that runs in any modern browser, making it an excellent project for beginners and a solid foundation for further web development experiments.

Getting Started

Prerequisites

Before you begin, make sure you have a text editor (such as VS Code, Sublime Text, or Notepad++) and a web browser that supports HTML5 canvas (Chrome, Firefox, Edge, or Safari). No additional libraries are required; the code for snake game in html relies solely on native web technologies Small thing, real impact..

Setting Up the HTML Structure

Create a new file named index.html and start with the basic skeleton:




    
    Snake Game
    


    
    


The <canvas> element will serve as the game board. The script.js file will contain all JavaScript logic Still holds up..

Building the Game Board

Creating the Canvas

The canvas element is defined in the HTML with an id of gameCanvas. Its width and height attributes set the drawing area to 400 × 400 pixels, which is a comfortable size for a classic snake experience But it adds up..

Styling with CSS

Create a style.css file and add the following rules:

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

canvas {
    border: 2px solid #333;
    background-color: #fff;
}

The CSS centers the canvas on the page and gives it a subtle border. You can adjust colors and sizes to match your preferences Easy to understand, harder to ignore..

Implementing Game Logic with JavaScript

Initializing Variables

In script.js, start by grabbing the canvas context and defining key constants:

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

const gridSize = 20;               // size of each cell
const tileCount = canvas.width / gridSize;

let snake = [{x: 9, y: 9}];        // initial snake segments
let food = {x: 5, y: 5};           // initial food position
let dx = 0;                       // current direction
let dy = 0;                       // current direction
let score = 0;
let gameInterval;

Important points:

  • The snake is stored as an array of coordinate objects.
  • dx and dy represent the direction of movement (changes by ±1).
  • score tracks how many foods the snake has eaten.

Drawing the Snake

Create a function to render the snake on the canvas:

function drawSnake() {
    ctx.fillStyle = 'green';
    snake.forEach(segment => {
        ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
    });
}

The function iterates over each segment, multiplying its grid coordinates by gridSize to convert to pixel values, then fills a square Worth keeping that in mind..

Handling User Input

Listen for arrow key presses to change direction, ensuring the snake cannot reverse onto itself:

document.addEventListener('keydown', event => {
    switch (event.key) {
        case 'ArrowUp':    if (dy !== 1) { dx = 0; dy = -1; } break;
        case 'ArrowDown':  if (dy !== -1) { dx = 0; dy = 1; } break;
        case 'ArrowLeft':  if (dx !== 1) { dx = -1; dy = 0; } break;
        case 'ArrowRight': if (dx !== -1) { dx = 1; dy = 0; } break;
    }
});

Italic note: the conditionals prevent the snake from moving directly opposite, which would cause an immediate self‑collision Not complicated — just consistent. Simple as that..

Game Loop

Use setInterval to update the game state at a fixed interval (e.g., 150 ms). Inside the loop, move the snake, check for collisions, and redraw:

function gameLoop() {
    setTimeout(() => {
        update();
        draw();
        gameInterval = setTimeout(gameLoop, 150);
    }, 0);
}

function update() {
    // Move snake head
    const newHead = {x: snake[0].x + dx, y: snake[0].y + dy};

    // Check wall collision
    if (newHead.Practically speaking, x >= tileCount || newHead. Which means x < 0 || newHead. y < 0 || newHead.

### Game Loop (continued)
```javascript
    // Check self-collision
    if (snake.some(segment => segment.x === newHead.x && segment.y === newHead.y)) {
        endGame();
        return;
    }

    // Add new head
    snake.unshift(newHead);

    // Check food consumption
    if (newHead.y === food.Which means x === food. In real terms, x && newHead. y) {
        score += 1;
        generateFood();
    } else {
        // Remove tail if no food eaten
        snake.

function draw() {
    // Clear canvas
    ctx.In practice, fillStyle = 'black';
    ctx. Here's the thing — fillRect(0, 0, canvas. width, canvas.

    drawSnake();
    drawFood();
}

function drawFood() {
    ctx.fillStyle = 'red';
    ctx.Practically speaking, fillRect(food. x * gridSize, food.

function generateFood() {
    // Generate new food position that isn't on the snake
    let newFood;
    do {
        newFood = {
            x: Math.floor(Math.Even so, random() * tileCount),
            y: Math. Which means floor(Math. random() * tileCount)
        };
    } while (snake.some(segment => segment.And x === newFood. Which means x && segment. y === newFood.

Not the most exciting part, but easily the most useful.

function endGame() {
    clearInterval(gameInterval);
    ctx.textAlign = 'center';
    ctx.fillStyle = 'white';
    ctx.Score: ${score}`, canvas.font = '30px Arial';
    ctx.That said, fillText(`Game Over! width / 2, canvas.

// Start the game
gameInterval = setInterval(gameLoop, 150);

Key Enhancements

  • Self-Collision Check: The update function now checks if the new head position overlaps any existing snake segment, triggering endGame() if true.
  • Food Generation: The generateFood function ensures new food doesn't appear on the snake by looping until a valid position is found.
  • Game Over Screen: The endGame function clears the interval and displays the final score centered on the canvas.

Conclusion

This implementation provides a complete, playable Snake game with core mechanics: directional movement, collision detection, scoring, and a clean game-over state. The code is structured for clarity, with separate functions for each responsibility, making it easy to extend with features like sound effects, difficulty levels, or mobile controls.

Potential Enhancements

While the core game is functional, several features could elevate the player experience and code robustness:

  • Score Persistence: Implement localStorage to save the high score between sessions, giving players a long-term goal.
  • Difficulty Scaling: Decrease the gameLoop interval (increase speed) every 5–10 points to ramp up the challenge dynamically.
  • Pause/Resume Functionality: Add an event listener for the Escape or Space key to toggle a isPaused boolean, halting the gameInterval without destroying the game state.
  • Mobile Touch Controls: Attach touchstart and touchmove listeners to the canvas to calculate swipe direction (comparing clientX/clientY deltas), enabling play on touchscreens.
  • Visual Polish: Replace rectangle rendering with sprite sheets or canvas drawing paths (rounded corners for snake segments, animated food) for a more professional aesthetic.
  • Grid Visuals: Optionally draw a faint grid background (ctx.strokeRect) to help players judge distances.

Final Thoughts

Building Snake from scratch using vanilla JavaScript and the HTML5 Canvas API is an excellent exercise in game development fundamentals: the game loop, state management, coordinate systems, and input handling. The modular structure adopted here—separating logic (update), rendering (draw), and utilities (generateFood)—creates a solid foundation that scales well. Whether you stop here with a polished portfolio piece or continue expanding it into a full-featured arcade clone, the patterns learned here apply directly to more complex 2D game architectures. Happy coding

Common Pitfalls and Debugging

Even a game this compact has a few classic traps worth calling out, since they teach transferable debugging instincts.

The 180° Reversal Bug: The most frequent issue in Snake implementations is allowing the snake to reverse directly into itself. If the snake is moving right and the player presses left, the head immediately collides with the neck segment, ending the game unfairly. The fix is to reject any direction change that is the direct opposite of the current heading:

function changeDirection(newDir) {
  const opposites = { up: 'down', down: 'up', left: 'right', right: 'left' };
  if (opposites[newDir] !== direction) {
    direction = newDir;
  }
}

A subtler variant of this bug appears when a player presses two keys within a single tick (e.g.Still, , up then left while moving right). Buffering the next direction and applying it only at the start of update prevents the snake from folding back on itself within one frame That's the part that actually makes a difference. Worth knowing..

Off-by-One Grid Errors: Because the canvas uses pixel coordinates while the game logic uses grid cells, forgetting to multiply grid positions by the cell size (or dividing when you should multiply) produces a snake that renders offset from where collisions are actually detected. Keep a single cellSize constant and derive everything from it to avoid drift between the visual and logical layers.

Stale Food Position: If generateFood runs before the snake array is initialized, or if it doesn't re-check occupancy after the snake grows, food can spawn underneath the snake and become instantly "eaten" or unreachable. Always generate food after the snake state is settled, and validate against the current segment list.

Interval Drift: setInterval does not guarantee precise timing under heavy load, and it keeps queuing callbacks if the browser tab is backgrounded. For smoother, frame-rate-independent movement, consider requestAnimationFrame with a time accumulator, which also pauses naturally when the tab loses focus.

A Note on Architecture

The separation of update, draw, and utility functions mirrors the pattern used in far larger game engines, where the game loop is split into distinct phases: input handling, state mutation, and rendering. In real terms, keeping rendering pure—reading state without mutating it—means you can later swap the canvas renderer for WebGL, or add a headless test harness that runs update thousands of times without drawing a single pixel. This discipline pays off the moment the project grows beyond a single file Simple, but easy to overlook..

Conclusion

What began as a few hundred lines of JavaScript has produced a genuinely complete arcade experience: responsive directional input, reliable collision detection against both walls and the snake's own body, fair food placement, live scoring, and a clean end state. More importantly, the exercise reinforces the foundational pillars of 2D game development—the loop that drives everything, the state that everything reads from, and the coordinate system that binds logic to pixels And that's really what it comes down to..

The enhancements outlined above—persistence, difficulty scaling, pause states, touch controls, and visual polish—are each small, self-contained additions precisely because the core was built with clear boundaries between responsibilities. But master these patterns on a project this size, and the same architecture scales to platformers, puzzle games, and beyond. Here's the thing — that modularity is the real takeaway. Take the foundation here, make it your own, and enjoy the process of building Small thing, real impact..

Latest Batch

Latest Additions

Explore a Little Wider

More Reads You'll Like

Thank you for reading about Code For Snake Game In Html. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home