Snake Game using HTML, CSS, and JavaScript

Snake Game

A snake game is a traditional programming exercise that can help you improve your programming and problem-solving abilities. The game may be created using HTML, CSS, and JavaScript in a web browser.

You control a snake that moves across a board in the google snake game. As you acquire food, the snake grows in size. The game will end if you collide with your tail or walls.

How to Create the UI for the Canvas

Add a canvas for the snake to move around by using HTML and CSS. If you need to review any fundamental topics, there are numerous additional HTML and CSS projects you can work on.

The complete source code is available on this project’s GitHub site.

  1. Make a new file named “index.html.”
  2. Open the file with any text editor, such as Visual Code or Atom. Add the following HTML code structure:
    <!doctype html>
    <html lang="en-US">
      <head>
        <title>Snake Game</title>
      </head>
      <body>
    
      </body>
    </html>
  3. Add a canvas within the body tag to simulate the snake’s game board.
    <h2>Snake Game</h2>
    <div id="game">
      <canvas id="snake"></canvas>
    </div>
  4. Next, create a new file titled “styles.css” in the same folder as your HTML document.
  5. For the overall web page, add some CSS within. Other essential CSS techniques and tactics can also be used to lay out your website.
    #game {
      width:400px;
      height:400px;
      margin:0 auto;
      background-color:#eee;
    }
    h2 {
      text-align:center;
      font-family:Arial;
      font-size:36px;
    } 
    
  6. Add a link to the CSS in the head tag of your HTML file as follows:
    <link rel="stylesheet" type="text/css" href="styles.css">
  7. Then, open the “index.html” file in your web browser to see the canvas.
    Snake Game

How to Draw the Snake

The snake game google is represented by the black line in the following example:

Snake Game

The snake is made up of many squares or “segments.” The number of squares increases as the snake grows. The snake’s length is one piece at the start of the game.

  1. At the base of the body tag in your HTML file, count a link to a new JavaScript file:
    <body>
      <!-- Your code here -->
      <script src="script.js"></script>
    </body>
  2. Create script.js and begin by obtaining the canvas’s DOM element:
    var canvas = document.getElementById("snake");
  3. Set the canvas HTML element’s context. You want the game to render a 2D canvas in this situation. You can now draw several shapes or pictures onto the HTML element.
    var canvas2d = canvas.getContext("2d");
  4. Set other in-game variables, such as whether the game has ended and the canvas’s height and width:
    var gameEnded = false;
    canvas.width = 400;
    canvas.height = 400;
  5. Create a variable named “snakeSegments.” This will keep trace of the number of “squares” the snake will occupy. You can also create a variable to track the length of the snake:
    var snakeSegments = [];
    var snakeLength = 1;
    
  6. Declare the snake’s starting X and Y positions:
    var snakeX = 0;
    var snakeY = 0;
  7. Make a brand-new function. Inside, add the first snake game mods to the snake segments array, along with its X and Y coordinates:
    function moveSnake() {
      snakeSegments.unshift({ x: snakeX, y: snakeY });
    }
  8. Make a brand-new function. The fill style should be set to the black inside. It will use the following color to draw the snake:
    function drawSnake() {
      canvas2d.fillStyle = "black"; 
    }
  9. Draw a square with a width and height of 10 pixels for every segment that makes up the snake’s size:
      for (var i = 0; i < snakeSegments.length; i++) {
        canvas2d.fillRect(snakeSegments[i].x, snakeSegments[i].y, 10, 10);
      }
  10. Make a game loop that repeats every 100 milliseconds. This will force the game to repeatedly draw the snake in its new position, which will be crucial when the snake begins to move:
    function gameLoop() {
      moveSnake();
     drawSnake();
  11. Spread the “index.html” file in a web browser to observe the snake’s beginning position at its smallest size.

How to Make the Snake Move

Add some logic to move the snake differently based on which button on the keyboard the player presses.

  1. Declare the snake’s starting direction at the top of the file:
    var directionX = 10;
    var directionY = 0;
    
  2. When the player touches a key, add an event handler that fires:
    document.onkeydown = function(event) {
    
    };
  3. Change the snake’s movement direction dependent on the key hit inside the event handler:
    switch (event.keyCode) {
      case 37: // Left arrow
        directionX = -10;
        directionY = 0;
        break;
      case 38: // Up arrow
        directionX = 0;
        directionY = -10;
        break;
      case 39: // Right arrow
        directionX = 10;
        directionY = 0;
        break;
      case 40: // Down arrow
        directionX = 0;
        directionY = 10;
        break;
    }
  4. Use the direction to update the snake’s X and Y coordinates in the moveSnake() function. For example, if the snake needs to move to the left, the X direction will be “-10.” For each frame of the game, this will update the X coordinate to subtract 10 pixels:
    function moveSnake() {
      snakeSegments.unshift({ x: snakeX, y: snakeY });
      snakeX += directionX;
      snakeY += directionY;
    }
  5. While the snake is moving, the game does not eliminate earlier parts. This will make the snake appear like this:

 

6. To fix this, at the start of the drawSnake() function, clean the canvas before drawing the new snake in each frame:

canvas2d.clearRect(0, 0, canvas.width, canvas.height);

7. Additionally, inside the move Snake () function, you must remove the final element of the snakeSegments array:

while (snakeSegments.length > snakeLength) {
  snakeSegments.pop();
}

8. To move the snake, open the “index.html” file and press the left, right, up, or down arrow keys.

How to Add Food Onto the Canvas

Add dots to the board game to symbolize food bits for the snake.

  1. At the top of the file, declare a new variable to hold an array of food pieces:
    var dots = [];
  2. Make a brand-new function. Generate random X and Y coordinates for the dots inside. You can also limit the number of dots on the board to ten at any given time:
    function spawnDots() {
      if(dots.length < 10) {
        var dotX = Math.floor(Math.random() * canvas.width);
        var dotY = Math.floor(Math.random() * canvas.height);
        dots.push({ x: dotX, y: dotY });
      }
    }
  3. After you’ve generated the X and Y coordinates for the food, draw them into the canvas in red:
    for (var i = 0; i < dots.length; i++) {
      canvas2d.fillStyle = "red";
      canvas2d.fillRect(dots[i].x, dots[i].y, 10, 10);
    }
  4. Inside the game loop, execute the new spawnDots() function:
    function gameLoop() {
      moveSnake();
      drawSnake();
      spawnDots();
      if(!gameEnded) {
        setTimeout(gameLoop, 100);
      }
    }
  5. To see the food on the game board, open the “index.html” file.
    Snake Game

How to Make the Snake Grow

When the snake collides with a food dot, you can make it expand in length.

  1. Make a brand-new function. Within it, loop through all of the elements in the dots array:
    function checkCollision() {
      for (var i = 0; i < dots.length; i++) {
            
      }
    }
  2. If the snake’s position matches the coordinates of any dots, the snake’s length is increased, and the dot is deleted:
    if (snakeX < dots[i].x + 10 && 
      snakeX + 10 > dots[i].x && 
      snakeY < dots[i].y + 10 && 
      snakeY + 10 > dots[i].y) {
        snakeLength++;
        dots.splice(i, 1);
    }
  3. In the game loop, call the new check collision() function:
    function gameLoop() {
      moveSnake();
      drawSnake();
      spawnDots();
      checkCollision();
      if(!gameEnded) {
        setTimeout(gameLoop, 100);
      }
    }
  4. In a web browser, open the “index.html” file. Then, move the snake around using the keyboard to collect food and grow the snake.
    Snake Game

How to End the Game

Check to see if the snake’s tail or any barriers caused the game to end.

  1. Make a new function that prints a “Game Over” message.
    function gameOver() {
      setTimeout(function() {
        alert("Game over!");
      }, 500); 
      gameEnded = true
    }
  2. Check whether the snake landed on any of the canvas’s walls inside the checkCollision() function. If this is the case, call the game over() function:
    if (snakeX < -10 || 
      snakeY < -10 || 
      snakeX > canvas.width+10 ||
      snakeY > canvas.height+10) {
        gameOver();
    }
  3. Loop through each section of the snake to check if the head of the snake collided with any of the tail segments:
    for (var i = 1; i < snakeSegments.length; i++) {
    
    }
  4. Check if the snake’s head matches the tail segments inside the for-loop. If this is the case, it signifies the head collided with a tail; hence the game should be ended:
    if (snakeX === snakeSegments[i].x && snakeY === snakeSegments[i].y) {
      gameOver();
    }
  5. In a web browser, open the “index.html” file. Then, to end the game, try to hit a wall or your tail.
    Snake Game

Learning JavaScript Concepts Through Games

Making games is an excellent approach to making your learning experience more enjoyable. So continue to create more games to hone your JavaScript skills.

You May Also Like