Signup/Sign In

How to Build a Snake Game in JavaScript [2023]

Posted in Programming   LAST UPDATED: APRIL 28, 2023

    We all have played the 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 Build a Snake Game in 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 the snake, etc.

    Prerequisites

    • Basic HTML knowledge.
    • Basic JavaScript knowledge.

    Snake Game in Javascript

    How to Make a Snake Game in Javascript

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

    HTML Code

    <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 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.

    Javascript startGame(), pauseGame(), and endGame() function

    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.

    The draw() Function

    In the startGame() method, we call the draw() method continuously 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.

    Also Visit: Top 15 HTML Projects [Updated 2023]

    The keyDownEvent() Function

    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 Below Image to start the game and enjoy playing it.

    Conclusion:

    I hope you like this simple tutorial in which we have built a Snake game in 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.

    If you want to practice your javascript programming skills by developing projects in HTML & JavaScript, check out these -

    Frequently Asked Questions(FAQs)

    1. Can I make a snake game with JavaScript?

    Yes, you can make a snake game with JavaScript.

    2. How to make snake game coding?

    To make a snake game with JavaScript, you need to use HTML5 canvas and create the game's logic using JavaScript. Check the above code to make a snake game in JavaScript.

    3. Can you build a game using JavaScript?

    Yes, you can build games using JavaScript.

    4. How to make snake game using HTML CSS and JavaScript?

    To make a snake game using HTML, CSS, and JavaScript, you need to use HTML5 canvas to draw the game board, use CSS for styling, and use JavaScript to create the game's logic.

    5. Can JavaScript be used like Python?

    JavaScript and Python are both programming languages, but they have different syntax and are used for different purposes. While Python is often used for data science, machine learning, and scripting, JavaScript is commonly used for web development and creating interactive web applications.

    You may also like:

    About the author:
    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    Tags:HTMLJavaScript
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS