Add the Snake to the Board
Explore how to add a snake to the game board by creating a snake object with properties like length, color, and direction. Understand how to initialize the snake's position using arrays and draw it on the canvas with rectangles. This lesson guides you through setting up the board and rendering the snake to build a functional Snake game.
We'll cover the following...
Implement: Add the snake to the board
First, let's create the board and the snake. To do this, we will follow the steps below:
Create a canvas in HTML and set a background image for the snake game.
Create a snake object. A snake will be drawn as continuous rectangles. Each rectangle will denote one block of the snake. We will set the initial values to create a snake on the board (background image). We will set the initial length, the color, the initial direction in which the snake moves, and all the positions of the continuous rectangles denoting the snake. We will use arrays and objects to perform this operation. The snake object is shown below:
We will also add two methods inside the snake object that will create (initialize) a snake and then draw the snake on the HTML canvas. The logic behind the two methods is discussed below:
createSnake(): This method will generate the position coordinates of each rectangle that makes up a snake of sizelength.drawSnake(): This method will use thepenobject to create rectangles. The number of rectangles is initially going to be equal tolength, which is set to 2. We will use thefillRect()method to draw rectangles. We will also add a short margin to separate each rectangle from its adjacent ones.
Now let's have a look at the code.
Explanation:
Lines 2–27: We create an object that contains the properties of the snake.
Lines 3–6: We create variables to store the snake's length (number of blocks), the color of the snake, an array to store the coordinates of each block of the snake, and the default direction in which the snake is going to move.
Lines 9–15: We create a
createSnakefunction to initialize the snake for a length of2(the value of thelengthvariable is set to be2). Inside this function, we execute aforloop starting fromlengthand going to0, which means that we are storing the coordinates of the rightmost block (head) of the snake first in the array. Also, we want the snake to start from the first row; hence, all the y-values are set to 0. We are executing the loop fromlengthto0because when we move the snake in any direction, we need to access the rightmost part of the snake (which is the snake's head) and remove the leftmost block of the snake (which is the snake's tail). Removal of the leftmost block of the snake is easiest = if the leftmost coordinate is kept at the last index of the array (so we could just use thepop()method on the array). Then we access the rightmost coordinate by accessing the first element from thecellsarray.Lines 18–27: We create another function to draw the snake with the coordinates present in the
cellsarray. Inside the method, we draw the snake's rectangle (or the block), which stores each block's size. Note that to separate each block from the adjacent block, we add a margin of 3 by subtracting 3 from theblockSizevariable, which stores each block's size.
Merge all the functionalities
Now let's move ahead and create the board by merging some of the concepts discussed so far in this course. Then we will add the snake to the board and draw it as discussed in the above steps.
// The first step in the game loop
function init(){
canvas = document.getElementById('snake-game');
H = canvas.height = 500;
W = canvas.width = 1000;
pen = canvas.getContext('2d');
blockSize = 66;
snake = {
length: 2, // number of rectangles making up the snake
color: "blue", // the color of the snake
cells: [], // the positions of each of the rectangles
direction: "right", // the direction in which the rectangle moves
// Create the snake by initializing the coordinates
createSnake:function(){
for(let i = this.length ; i > 0; i--)
// Add the (x, 0) coordinates to the cells array
this.cells.push({x: i, y: 0});
},
// Draw the snake on the HTML canvas
drawSnake:function(){
for(let i = 0; i < this.cells.length; i++){
// Set the color of the snake
pen.fillStyle = this.color;
// Draw rectangle by a margin of 3 so that each rectangle is separated from its adjacent one
pen.fillRect(this.cells[i].x * blockSize,this.cells[i].y * blockSize, blockSize - 3, blockSize - 3);
}
}
}
// Create the Snake
snake.createSnake();
}
// The second step in the game loop
function draw(){
snake.drawSnake();
}
// The game loop function
function gameloop(){
draw();
}
// Call the init() method to initialize the game
init();
// Execute the game loop at an interval of 100 milliseconds
var f = setInterval(gameloop, 200);Explanation:
In the
game_logic.jsfile:Lines 2–39: We create the
init()method to initialize the game. This is the very first step in the game loop.Line 3: We access the canvas HTML element using the
getElementById()method.Lines 4–5: We set the width and height of the canvas using JavaScript.
Line 6: We create the context object for the canvas to draw the graphics.
Line 7: We set the width of the rectangles that will be a part of the snake.
Lines 9–34: We add the snake object we created in the previous code block.
Line 37: We call the
createSnake()method to initialize the snake withlengthequal to2rectangles.
Lines 42–45: We create the
draw()method that will later be used in a loop. Inside this method, we call thedrawSnake()method to draw the initial snake of length 5.Lines 47–50: We create the
gameloop()method. This method will call thedraw()method at every fixed interval.Line 53: We call the
init()method to initialize the game.Line 56: We use the
setInterval()method to execute thegameloop()method at an interval of 100 milliseconds.
In the
index.htmlfile (the code is pretty much simple HTML code):Line 7: We add a background image to the canvas element, which will depict the board for the game.
Line 8: We add a border to the canvas element to make the game look better.
Line 7: We add a canvas element with an
idofsnake-game.