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 :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas id="snake" width="200" height="200"></canvas> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="snake.js"></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cvs = document.getElementById('snake'); | |
const ctx = cvs.getContext('2d'); |
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 :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener("keydown",direction); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
} | |
} |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
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 :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ctx.fillStyle = "white"; | |
ctx.font = "45px Changa one"; | |
ctx.fillText(score,2*box,1.6*box); |
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
Tags:
JavaScript
why do you do this --> Math.floor(Math.random()*17+1) * box
ReplyDeleteThe Math.floor() function returns the largest integer less than or equal to a given number.
ReplyDeleteThe 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.
nuice
ReplyDeletedont work for me
ReplyDeleteWhere does the 9 and the 10 come from when you are creating the variables and constants in the first step?
ReplyDeletehttps://subeshbhandari.com/blog/games/build-a-snake-game
ReplyDeletenice thanks
Deleteit keeps saying: Uncaught TypeError: Cannot read property 'getContext' of null
ReplyDelete