How to Create Snake Game using Javascript?

by Developers for Hire
Snake Game Development
0 0
Read Time:7 Minute, 53 Second

App development is one of the most rewarding and lucrative career choices. That’s the reason why the global IT sector has been seeing a rise in the number of developers. Every year, thousands of students graduate from the university and pursue their careers as app developers, but only a few achieve success, while the others either abandon this field or work as junior developers for their entire lives. The biggest reason behind this is the lack of practical knowledge.

The best way to master any programming language is by doing practical projects. But how? You can start by developing small programs like fun games. You may have surely heard of the popular Snake Game.

You can hone your coding skills practically by developing your first Snake Game using JavaScript and HTML. In this tutorial, we will demonstrate the process of creating a Snake Game using JavaScript and HTML. So, let’s get started!

Step-by-Step Process to Create Snake Game Using JavaScript: 

Step 1: Displaying a Still Snake and a Board

First, we need to show the game board and the snake. Create a file named snakegame.html. This will have all of our code. Then, open the file in your preferred browser.

To create your game, you will need the HTML <canvas>, which can draw graphics with JavaScript.

<canvas id="gameCanvas" width="400" height="400"><canvas>

Right now, the browser will show nothing since the canvas has no background by default. To make our canvas visible, we can add a border by writing some JavaScript code.

To do that, we need to put <script> and </script> tags after the </canvas>.

Make the Canvas

The next step is to create the game board, or the canvas, where our snake will move around. We can access the canvas element by using the id gameCanvas.

Then, we can get the “2d context” of the canvas, which means that we will draw on it in a 2D space.

We will then fill the entire canvas with a white rectangle that has a black border, starting from the top left corner (0, 0). The size of the rectangle will be 400 x 400 pixels.

const snakeboard = document.getElementById(“gameCanvas”);

const snakeboard_ctx = gameCanvas.getContext(“2d”);

Making the snake

We need to give the snake a starting position on the game board by using an array of coordinates to represent the snake’s body parts.

To make a horizontal snake in the center of the game board, at (200, 200), we can use the coordinates of each body part of the snake. The array of coordinates will match the length of the snake.

let snake = [  {x: 200, y: 200},  {x: 190, y: 200},  {x: 180, y: 200},  {x: 170, y: 200},  {x: 160, y: 200},];

To show the snake on the game board, we can write a function that draws a rectangle for each coordinate pair.

function drawSnakePart(snakePart) 

{  

  snakeboard_ctx.fillStyle = 'lightblue';  

  snakeboard_ctx.strokestyle = 'darkblue';

  snakeboard_ctx.fillRect(snakePart.x, snakePart.y, 10, 10);  

  snakeboard_ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);

}

 

/*Function that prints the parts*/

function drawSnake() 

{  

  snake.forEach(drawSnakePart);

}

Step 2: Make the Snake Moving

We have our game board and our snake ready, but we need the snake to move so it can explore the game area in different directions.

So, let’s see how we can make our snake move by itself on the game board.

Horizontal movement 

To move the snake one step (10px) to the right, we can add 10px to the x-coordinate of every part of the snake (dx = +10).

To move the snake to the left, we can subtract 10px from the x-coordinate of every part of the snake (dx = -10).

function move_snake() 

{  

  const head = {x: snake[0].x + dx, y: snake[0].y};

  snake.unshift(head);

  snake.pop();

}

In the function above, we made a new head for the snake. We then put the new head at the start of the snake using snake.unshift and took out the last part of the snake using snake.pop. This way, the rest of the snake parts move into position.

Vertical Movement

To move our snake up and down, we cannot change all the y-coordinates by 10px as that would make the whole snake go up and down. Only the y-coordinate of the head needs to be changed.

Adding 10px to it to move the snake down and subtracting 10px from it to move the snake up will move the snake correctly.

To do this, we have to modify the move_snake method to also add the dy (vertical speed of the snake) to the y-coordinate of the head.

const head = {x: snake[0].x + dx, y: snake[0].y + dy};

Automatic Movement

To move the snake, for example, 50px to the right, we will have to use move_snake(x) 5 times. However, using the method 5 times will make the snake skip to the +50px position, instead of moving gradually towards that point.

setTimeout(function onTick() {  clearCanvas();  move_Snake();  drawSnake();}, 100);

setTimeout(function onTick() {  clearCanvas();  move_Snake();  drawSnake();}, 100);

...

drawSnake();

Step 3: Assigning Allow Keys to Change Snake’s Direction

Now that we have a snake that can move, our next goal is to make the snake change direction when one of the arrow keys is pressed.

Changing the Snake Direction

Let’s write the function turn_snake. This will check if the pressed key is one of the arrow keys. If it is, we will change the horizontal and vertical speed. Look at the function below.

function change_direction(event) 

{  

   const LEFT_KEY = 37;

   const RIGHT_KEY = 39;

   const UP_KEY = 38;

   const DOWN_KEY = 40;

 

   const keyPressed = event.keyCode;

   const goingUp = dy === -10;

   const goingDown = dy === 10;

   const goingRight = dx === 10;  

   const goingLeft = dx === -10;

 

     if (keyPressed === LEFT_KEY && !goingRight)

     {    

          dx = -10;

          dy = 0;  

     }

 

     if (keyPressed === UP_KEY && !goingDown)

     {    

          dx = 0;

          dy = -10;

     }

 

     if (keyPressed === RIGHT_KEY && !goingLeft)

     {    

          dx = 10;

          dy = 0;

     }

 

     if (keyPressed === DOWN_KEY && !goingUp)

     {    

          dx = 0;

          dy = 10;

     }

}

Adding Boundary Condition

To ensure our snake doesn’t move infinitely, we have to create a boundary condition. Let’s start with creating the function has_game_ended.

There are two conditions in which the game can end:

  • If the head of the snake collides with its body.
  • If the head of the snake collides with the boundary.

Both these conditions are included in the code below:

function has_game_ended()

{  

  for (let i = 4; i < snake.length; i++)

  {    

    const has_collided = snake[i].x === snake[0].x && snake[i].y === snake[0].y

    if (has_collided) 

      return true

  }

  const hitLeftWall = snake[0].x < 0;  

  const hitRightWall = snake[0].x > snakeboard.width - 10;

  const hitToptWall = snake[0].y &lt; 0;

  const hitBottomWall = snake[0].y > snakeboard.height - 10;

 

  return hitLeftWall ||  hitRightWall || hitToptWall || hitBottomWall

}

Step 4: Including Food and Score

Now that we have worked on all the other elements of the game, the last step is to incorporate the food and score elements.

Food

We will create a random array of coordinates for the food that our snake will eat. You can make the function random_food to create an x-coordinate and a y-coordinate for the food’s positions.

To generate the new food location for a snake, use the function:

function random_food(min, max)

{  

   return Math.round((Math.random() * (max-min) + min) / 10) * 10;

}

 

function gen_food() 

{  

   food_x = random_food(0, snakeboard.width - 10);

   food_y = random_food(0, snakeboard.height - 10);

   snake.forEach(function has_snake_eaten_food(part) {

        const has_eaten = part.x == food_x && part.y == food_y;

        if (has_eaten) gen_food();

      });

}

Growing the snake

As soon as the snake eats the food, it will grow in size. Instead of adding a body part every time, we can skip removing it using the move_snake function.

function move_snake() {

      // Create the new Snake's head

      const head = {x: snake[0].x + dx, y: snake[0].y + dy};

      // Add the new head to the beginning of snake body

      snake.unshift(head);

      const has_eaten_food = snake[0].x === food_x && snake[0].y === food_y;

      if (has_eaten_food) {

        // Generate new food location

        gen_food();

      } else {

        // Remove the last part of snake body

        snake.pop();

      }

    }

Score

Adding a score element is quite straightforward. We have to initialize a score increment whenever it eats the food. For score display, we need a new div prior to the canvas.

function move_snake()

 {

      // Create the new Snake's head

      const head = {x: snake[0].x + dx, y: snake[0].y + dy};

      // Add the new head to the beginning of snake body

      snake.unshift(head);

      const has_eaten_food = snake[0].x === foodX && snake[0].y === foodY;

      if (has_eaten_Food) {

        // Increase score

        score += 10;

        // Display score on screen

        document.getElementById('score').innerHTML = score;

        // Generate new food location

        gen_food();

      } else {

        // Remove the last part of snake body

        snake.pop();

      }

}

Conclusion

Congratulations! You have successfully created a fun and interactive snake game using JavaScript and HTML. This was a great way to practice your JavaScript skills, showcase your work, and have fun at the same time. Games development projects are perfect for learning JavaScript, building your portfolio, and gaining confidence in your abilities.

 

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

You may also like

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *