MrJazsohanisharma

Create the Snake Game Using JavaScript

Create the Snake Game Using JavaScript

DOWNLOAD: SNAKE GAME WITH JAVASCRIPT - SOURCE CODE


In general, to create a JavaScript game, you'll need two things, the first is the HTML5 canvas, and the second is JavaScript.

You first go and create the canvas element, inside your HTML file :

<canvas id="snake" width="200" height="200"></canvas>
view raw code5.js hosted with ❤ by GitHub
then before the closing body tag "</body>", you add your JavaScript code.

<script src="snake.js"></script>
view raw code4.js hosted with ❤ by GitHub
Now we need to write our code, inside snake.js file, the first thing that we will do, is to select our canvas, and getContext('2d') of our canvas :

const cvs = document.getElementById('snake');
const ctx = cvs.getContext('2d');
view raw code3.js hosted with ❤ by GitHub

getContext('2d') method, has properties and methods that allow us to draw and DO different things on the canvas.

I will use box = 32 pixels, box here is like a unit, why? because our snake is a square, it's width and height both equal to 32px by default.

Also, we will have to move our snake in any direction, by one box at a time.

And the food position is given using our box unit.

PS : if your don't understand what I am talking about, watch the video below.  WATCH TUTORIAL

Now let's create some variables and constants :
// create the unit
const box = 32;
// create the snake
let snake = [];
snake[0] = {
x : 9 * box,
y : 10 * box
};
// create the food random position
let food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
// create the score var
let score = 0;
//control the snake
let d;
view raw code2.js hosted with ❤ by GitHub
To control our snake we will need to add an eventListener  to our document. WATCH TUTORIAL

document.addEventListener("keydown",direction);
view raw code1.js hosted with ❤ by GitHub
direction here, is a function, whenever the player, press a key on the keyboard, it will fire up.

function direction(event){
let key = event.keyCode;
if( key == 37 && d != "RIGHT"){
d = "LEFT";
}else if(key == 38 && d != "DOWN"){
d = "UP";
}else if(key == 39 && d != "LEFT"){
d = "RIGHT";
}else if(key == 40 && d != "UP"){
d = "DOWN";
}
}
view raw code10.js hosted with ❤ by GitHub
Remember, every key on the keyboard has a code :

the Left key code is : 37.
the Up key code is : 38.
the Right key code is : 39.
the Down key code is : 40.

Above before we move the snake to the right per example, we need to make sure, that our snake isn't going to the left, also before moving the snake to the bottom, we must first check if the snake isn't going to the top.

Now let's draw our snake and the food to the canvas.

function draw(){
for( let i = 0; i < snake.length ; i++){
ctx.fillStyle = ( i == 0 )? "green" : "white";
ctx.fillRect(snake[i].x,snake[i].y,box,box);
ctx.strokeStyle = "red";
ctx.strokeRect(snake[i].x,snake[i].y,box,box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x,food.y,box,box);
}
view raw code.js hosted with ❤ by GitHub
We loop over the snake array, and draw every square. using the fillRect() method. and the same for the food.

Now let's talk about the logic behind moving the snake.

To move the snake, is simple, we get the head's position, let snakeX = snake[0].x; let snakeY = snake[0].y; , we remove the tail, we change snakeX and snakeY based on the direction, (left, right ... ), then we create a new head, in the new position.

before doing this, we need to check, if the snake didn't eat the food, cause if so, we don't need to remove the tail, we just add a new head.

The javascript code we look like this :

function draw(){
for( let i = 0; i < snake.length ; i++){
ctx.fillStyle = ( i == 0 )? "green" : "white";
ctx.fillRect(snake[i].x,snake[i].y,box,box);
ctx.strokeStyle = "red";
ctx.strokeRect(snake[i].x,snake[i].y,box,box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x,food.y,box,box);
// old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// which direction
if( d == "LEFT") snakeX -= box;
if( d == "UP") snakeY -= box;
if( d == "RIGHT") snakeX += box;
if( d == "DOWN") snakeY += box;
// if the snake eats the food
if(snakeX == food.x && snakeY == food.y){
score++;
eat.play();
food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
// we don't remove the tail
}else{
// remove the tail
snake.pop();
}
// add new Head
let newHead = {
x : snakeX,
y : snakeY
}
snake.unshift(newHead);
}
// call draw function every 100 ms
let game = setInterval(draw,100);
view raw code6.js hosted with ❤ by GitHub
Now we need to check if there is no collision, the cases where there is a collision are : if the snake hits one of the walls, or if it hits itself. to check if the snake hits itself or not, we need to check if all the squares from the snake array (except the head), doesn't have the same coordinates as the head.
function collision(head,array){
for(let i = 0; i < array.length; i++){
if(head.x == array[i].x && head.y == array[i].y){
return true;
}
}
return false;
}
view raw code7.js hosted with ❤ by GitHub
We need now to add this code, inside our draw() function :
function draw(){
for( let i = 0; i < snake.length ; i++){
ctx.fillStyle = ( i == 0 )? "green" : "white";
ctx.fillRect(snake[i].x,snake[i].y,box,box);
ctx.strokeStyle = "red";
ctx.strokeRect(snake[i].x,snake[i].y,box,box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x,food.y,box,box);
// old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// which direction
if( d == "LEFT") snakeX -= box;
if( d == "UP") snakeY -= box;
if( d == "RIGHT") snakeX += box;
if( d == "DOWN") snakeY += box;
// if the snake eats the food
if(snakeX == food.x && snakeY == food.y){
score++;
eat.play();
food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
// we don't remove the tail
}else{
// remove the tail
snake.pop();
}
// add new Head
let newHead = {
x : snakeX,
y : snakeY
}
// game over
if(snakeX < box || snakeX > 17 * box || snakeY < 3*box || snakeY > 17*box || collision(newHead,snake)){
clearInterval(game);
}
snake.unshift(newHead);
}
// call draw function every 100 ms
let game = setInterval(draw,100);
view raw code8.js hosted with ❤ by GitHub
one last thing to add inside our draw() function, is the code to draw the player's score.
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score,2*box,1.6*box);
view raw code9.js hosted with ❤ by GitHub
You can watch our tutorial about creating the snake game using JavaScript The tutorial has two parts:
1st part : we understand everything about the game, we discuss things before we code.
2nd part : Type in the Code.

Download the starter template from gitHub, so you can follow the tutorial step by step :

The Game files link : Code Explained Repo





Other Tutorials for games created using JavaScript :

Create the Tetris Game Using Javascript

Create the Flappy Bird Game Using Javascript

8 Comments

You're welcome to share your ideas with us in comments.

  1. why do you do this --> Math.floor(Math.random()*17+1) * box

    ReplyDelete
  2. The Math.floor() function returns the largest integer less than or equal to a given number.

    The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

    ReplyDelete
  3. Where does the 9 and the 10 come from when you are creating the variables and constants in the first step?

    ReplyDelete
  4. https://subeshbhandari.com/blog/games/build-a-snake-game

    ReplyDelete
  5. it keeps saying: Uncaught TypeError: Cannot read property 'getContext' of null

    ReplyDelete
Previous Post Next Post