The Wild

Snake Game Coding: Step-by-Step Guide

· 5 min read · Reptiles and Amphibians

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to code the classic Snake game from scratch using HTML, CSS, and JavaScript. By the end, you'll have a playable game in your browser where you control a snake that grows when it eats food, and the game ends if it hits the wall or itself. No prior game development experience is needed, but basic familiarity with JavaScript and the DOM will help.

What You'll Need

  • A text editor (like VS Code, Notepad++, or even Notepad)
  • A modern web browser (Chrome, Firefox, Edge, Safari)
  • Basic understanding of HTML, CSS, and JavaScript (variables, functions, loops, and event listeners)

Step-by-Step

  1. Set up the project files. Create a new folder on your computer and inside it create three files: index.html, style.css, and script.js. You can also use a single HTML file with embedded CSS and JS, but separate files are cleaner.
  2. Write the HTML structure. Open index.html and add a basic HTML skeleton. Include a <canvas> element where the game will be drawn, and a <div> or <p> to display the score. Link the CSS and JS files. Example: <canvas id="gameCanvas" width="400" height="400"></canvas> and <div id="score">0</div>.
  3. Style the page with CSS. In style.css, set the canvas border, background color, and center it on the page. Also style the score display. Keep it simple: canvas { border: 1px solid #000; display: block; margin: 20px auto; } and #score { text-align: center; font-size: 24px; }.
  4. Initialize the game variables in JavaScript. In script.js, get the canvas context, set the grid size (e.g., 20x20 cells), and define variables for the snake (an array of coordinates), the food (a random coordinate), the direction, the score, and the game speed (in milliseconds). Example: const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const gridSize = 20; const tileCount = canvas.width / gridSize; let snake = [{x: 10, y: 10}]; let food = {x: 15, y: 15}; let dx = 0; let dy = 0; let score = 0; let gameSpeed = 100;
  5. Draw the game board. Create a function drawGame() that clears the canvas, draws the snake as a series of green squares, and draws the food as a red square. Use ctx.fillStyle and ctx.fillRect() to draw each cell. Call this function once to see the initial state.
  6. Move the snake. Create a function moveSnake() that updates the snake's head position based on the current direction (dx, dy). Add the new head to the front of the snake array, and remove the tail (unless the snake just ate food). Use snake.unshift(newHead) and snake.pop().
  7. Handle keyboard input. Add an event listener for keydown events. When the arrow keys are pressed, update dx and dy accordingly. Make sure to prevent the snake from reversing directly into itself (e.g., if moving right, don't allow left).
  8. Detect collisions. In the move function, check if the snake's head hits the wall (x or y out of bounds) or hits its own body (check if the head coordinates match any other segment). If so, call a gameOver() function.
  9. Handle eating food. When the snake's head lands on the food, increment the score, generate new random food coordinates (make sure it's not on the snake), and do not remove the tail (so the snake grows). Update the score display.
  10. Create the game loop. Use setInterval() to call a gameStep() function every gameSpeed milliseconds. This function should call moveSnake(), check collisions, and then drawGame(). Example: let gameInterval = setInterval(gameStep, gameSpeed);
  11. Add game over and restart. In gameOver(), clear the interval, show an alert or a message on the page, and offer a restart button or prompt. To restart, reset all variables and start the interval again.
  12. Test and refine. Open index.html in your browser and play. Adjust the game speed, grid size, or colors as desired.

Common Mistakes

  • Forgetting to clear the canvas each frame, which causes the snake to leave a trail.
  • Not preventing the snake from reversing direction, which causes instant self-collision.
  • Generating food on top of the snake, making it impossible to eat.
  • Using setInterval without storing the ID, so you can't clear it on game over.
  • Not using Math.floor() when generating random food coordinates, resulting in decimal positions that don't align with the grid.

Tips

  • Start with a small grid (e.g., 15x15) to make testing easier.
  • Use requestAnimationFrame instead of setInterval for smoother movement, but it requires more careful timing.
  • Add a high-score feature using localStorage to save the best score.
  • Make the game speed increase as the score grows to add difficulty.
  • Use different colors for the snake's head and body for a nicer look.

Troubleshooting

  • Snake doesn't move: Check that the setInterval is running and that dx or dy is not 0. Also ensure the keydown listener is attached to document or window.
  • Snake moves too fast or too slow: Adjust the gameSpeed variable (lower = faster). If using requestAnimationFrame, add a time check to control speed.
  • Canvas is blank: Make sure the canvas has a width and height attribute in HTML, and that you're calling drawGame() after setting up the context.
  • Snake goes through walls: Your collision detection for walls is missing or incorrect. Check that you compare the head's x and y to the canvas boundaries (0 to canvas.width).
  • Food appears off-grid: Ensure you're multiplying by gridSize when drawing food, and that the random coordinates are integers between 0 and tileCount - 1.
  • Game doesn't restart: When restarting, make sure to clear the previous interval with clearInterval(gameInterval) before starting a new one.

Frequently Asked Questions

How do I make the snake move continuously?

Use setInterval to call a function that moves the snake one step in the current direction. The interval's delay controls the speed.

How do I detect if the snake hits itself?

After moving, check if the head's coordinates match any of the other segments in the snake array. If they do, trigger game over.

How do I make the snake grow?

When the head lands on the food, don't remove the tail. In code, skip the snake.pop() step for that frame.

Can I use arrow keys and WASD?

Yes, in the keydown listener, check for both sets of key codes (e.g., 37 for left, 65 for A).

How do I add a pause feature?

Keep a boolean variable paused. In the game loop, if paused, skip the move and draw functions. Toggle it with a key press (e.g., Space).

Why does my snake sometimes skip a cell?

This happens if you update the direction multiple times between game steps. To avoid it, only process the latest direction change per step, or use a buffer for direction changes.