Signup/Sign In

Snake Game in HTML and Javascript

Posted in Programming   LAST UPDATED: AUGUST 13, 2021

    We all have played Snake game once in our life. It is a simple game with few rules and unlimited fun. If you are learning Javascript, then it would be a good start for you to develop the simple Snake game in HTML and Javascript.

    In this tutorial, we will use the HTML canvas tag for developing this game, with Javascript code controlling the gameplay and the visuals of the game like the snake and the apple, growing of snake, etc.

    Snake game in HTML and Javascript

    Following is the HTML code where we have used the <canvas> tag to setup the game UI:

    <div class="game-box"><canvas id="canvas" width="400" height="400"></canvas></div>
    <div class="game-info">
        <h2>Snake Game</h2>
        <p id="game-status"></p>
        <p id="game-score"></p>
    </div>

    In the canvas defined above, which is of 400px by 400px, we will create a grid of 20px by 20px in which we will create the snake and the apple.

    var gridSize = (tileSize = 20); // 20 x 20 = 400
    var nextX = (nextY = 0);
    
    // snake
    var defaultTailSize = 3;
    var tailSize = defaultTailSize;
    var snakeTrail = [];
    var snakeX = (snakeY = 10);
    
    // apple
    var appleX = (appleY = 15);

    We initialize the apple and the snake with an initial length of 3 blocks, which will grow as the snake will eat more apples.

    We have defined the functions, startGame(), pauseGame() and endGame() to control the gameplay.

    /* function to start the game */
          function startGame(x) {
              // setting gameActive flag to true
              gameActive = true;
              document.getElementById("game-status").innerHTML = "<small>Game Started</small>";
              document.getElementById("game-score").innerHTML = "";
              return setInterval(draw, 1000 / x);
          }
          
          function pauseGame() {
              // setting gameActive flag to false
              clearInterval(gameControl);
              gameActive = false;
              document.getElementById("game-status").innerHTML = "<small>Game Paused</small>";
          }
          
          function endGame(x) {
              // setting gameActive flag to false
              clearInterval(gameControl);
              gameActive = false;
              document.getElementById("game-status").innerHTML = "<small>Game Over</small>";
              document.getElementById("game-score").innerHTML = "<h1>Score: " + x + "</h1>";
          }

    When the game ends, we will show the score of the player.

    In the startGame() method we call the draw() method continuosly using the setInterval() method. Here is the draw() method which is used for running the game.

    function draw() {
            // move snake in next pos
            snakeX += nextX;
            snakeY += nextY;
    
            // snake over game world?
            if (snakeX < 0) {
              snakeX = gridSize - 1;
            }
            if (snakeX > gridSize - 1) {
              snakeX = 0;
            }
    
            if (snakeY < 0) {
              snakeY = gridSize - 1;
            }
            if (snakeY > gridSize - 1) {
              snakeY = 0;
            }
    
            //snake bite apple?
            if (snakeX == appleX && snakeY == appleY) {
              tailSize++;
    
              appleX = Math.floor(Math.random() * gridSize);
              appleY = Math.floor(Math.random() * gridSize);
            }
    
            //  Select the colour to fill the canvas
          ctx.fillStyle = CANVAS_BACKGROUND_COLOUR;
          //  Select the colour for the border of the canvas
          ctx.strokestyle = CANVAS_BORDER_COLOUR;
    
          // Draw a "filled" rectangle to cover the entire canvas
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          // Draw a "border" around the entire canvas
          ctx.strokeRect(0, 0, canvas.width, canvas.height);
    
            // paint snake
            ctx.fillStyle = SNAKE_COLOUR;
            ctx.strokestyle = SNAKE_BORDER_COLOUR;
            for (var i = 0; i < snakeTrail.length; i++) {
              ctx.fillRect(
                snakeTrail[i].x * tileSize,
                snakeTrail[i].y * tileSize,
                tileSize,
                tileSize
              );
              
              ctx.strokeRect(snakeTrail[i].x * tileSize , snakeTrail[i].y* tileSize, tileSize, tileSize);
    
              //snake bites it's tail?
              if (snakeTrail[i].x == snakeX && snakeTrail[i].y == snakeY) {
                if(tailSize > 3) {
                    endGame(tailSize);
                }
                tailSize = defaultTailSize;  
              }
            }
    
            // paint apple
            ctx.fillStyle = "red";
            ctx.fillRect(appleX * tileSize, appleY * tileSize, tileSize, tileSize);
    
            //set snake trail
            snakeTrail.push({ x: snakeX, y: snakeY });
            while (snakeTrail.length > tailSize) {
              snakeTrail.shift();
            }
          }

    For controlling the game, we have the gameController() function, to enable the user to play the game using the up, down, left and right keys and spacebar to pause/play the game.

    function keyDownEvent(e) {
            switch (e.keyCode) {
              case 37:
                nextX = -1;
                nextY = 0;
                break;
              case 38:
                nextX = 0;
                nextY = -1;
                break;
              case 39:
                nextX = 1;
                nextY = 0;
                break;
              case 40:
                nextX = 0;
                nextY = 1;
                break;
              case 32:
                if(gameActive == true) {
                    pauseGame();
                }
                else {
                    gameControl = startGame(x);
                }
                break;
            }
          }

    Below you will find the live game. Click on the Run button to start the game and enjoy playing it.

    Conclusion:

    I hope you like this simple tutorial in which we have created a simple Snake game using HTML and Javascript. If you have any doubts related to the code, feel free to post in the comment section below and we will help you in understanding the code.

    You may also like:

    Published by: iamabhishek
    Tags:JavascriptHTMLGame DevelopmentHowTo
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS