We’re going to make a quick game. This one going to be a snake game in JavaScript and that’s going to be the kind of game. That used to be on cell phones before smartphones. Let’s come to our topic, How to make a simple snake game in JavaScript?. The answer is first, you must have good knowledge of HTML canvas, CSS & JavaScript. Then you can understand this program easily. One thing that HTML5 canvas is great for is creating fun and interactive games.
if you wanna play online:
snakegame.html
First, we need to display the game board and the snake. Start by creating the file snakegame.html. This will contain all of our code. Next, open the file in your preferred browser. To be able to create our game, we have to make use of the HTML <canvas>,which is used to draw graphics with JavaScript.
<canvas id="gc" width="400" height="400"></canvas>
MakingCanvas
Now we can make the canvas, or the game board, for our snake to navigate. First, we get the canvas element using the id gameCanvas (specified earlier). Next, we get the canvas “2d context”, which means that it will be drawn into a 2D space.
We’re going to do canvas equals a document get element by id. It’s most verbose and ugly where we have to be doing a little bit interaction between the HTML. The JavaScript once we get this stuff sorta a setup graphics context or buffer and. Then we’ve got document add event listener. Let’s set up our keyboard hooks key down is all. We really need since this game has momentum like a function called key push. I can spell push correctly let’s go and get that step setup.
canv=document.getElementById("gc");
ctx=canv.getContext("2d");
document.addEventListener("keydown",keyPush);
Start off our game on interval timer to call a game function 15 times every second that’s milliseconds. So, we’re dividing it into it and using flow frame rate since snake works on a very low frame rate. We’re gonna have X velocity and y velocity values for a snake part of the thing about. Snake game right, is that you just push the keys to make the character move and. It keeps on moving with momentum.We’re gonna switch on the keycode some people don’t like switch cases.
The arrow keys and it’s left and then clockwise because you need two concepts on top your head. When you’re walking people through stuff on skype okay. So there’s your input now handled we also want to have our player positions equals P equals. Let start in the middle of the world I’m thinking.
The middle work sitting at 20 by 20 so grid size. And tile count will both be 20 cuz 10 times 20 is 400. And let’s also have an Apple X and an apple Y as our goal. Which will start at 15 15 just to keep things simple. So player X has got a plus equal X velocity. And then player wise got a plus equal Y velocity to implement for those. So if P X’s goes less than 0.let’s also do a context.fill style equals black.
window.onload=function() {
canv=document.getElementById("gc");
ctx=canv.getContext("2d");
document.addEventListener("keydown",keyPush);
setInterval(game,1000/15);
}
px=py=10;
gs=tc=20;
ax=ay=15;
xv=yv=0;
function game() {
px+=xv;
py+=yv;
if(px<0 if="" px="">tc-1) {
px= 0;
}
if(py<0 if="" py="">tc-1) {
py= 0;
}
ctx.fillStyle="black";
ctx.fillRect(0,0,canv.width,canv.height);
<0 if="" px=""><0 if="" py="">
So we’re gonna get a trailer for our trail hold on. You ever need an array for our player because one of things about. A snake game right is it keeps track of all previous positions. Let’s also keep a one called tail to be how long our tails supposed to be trail length.
There are our x and y which were part of mechanics of a snake game. It’s you stepping on your tail you’re in trouble. So we can do it really easily here by doing this. So if it matches on Xand it matches on Y. Then tail is going to go back to come off five speaking outfit matching. We also need to check and see if we step on that Apple, hello no equals five.
If we step on that Apple Then we want to increase our tail length. And as part of the two we want to randomize that. So I’m at the floor so it’s an exact integer. And this is going to be math random which is 0 to1 times tile count on each axis apart.
window.onload=function() {
canv=document.getElementById("gc");
ctx=canv.getContext("2d");
document.addEventListener("keydown",keyPush);
setInterval(game,1000/15);
}
px=py=10;
gs=tc=20;
ax=ay=15;
xv=yv=0;
trail=[];
tail = 5;
function game() {
px+=xv;
py+=yv;
if(px<0 if="" px="">tc-1) {
px= 0;
}
if(py<0 if="" py="">tc-1) {
py= 0;
}
ctx.fillStyle="black";
ctx.fillRect(0,0,canv.width,canv.height);
ctx.fillStyle="lime";
for(var i=0;itail) {
trail.shift();
}
if(ax==px && ay==py) {
tail++;
ax=Math.floor(Math.random()*tc);
ay=Math.floor(Math.random()*tc);
}
ctx.fillStyle="red";
ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
}
function keyPush(evt) {
switch(evt.keyCode) {
case 37:
xv=-1;yv=0;
break;
case 38:
xv=0;yv=-1;
break;
case 39:
xv=1;yv=0;
break;
case 40:
xv=0;yv=1;
break;
}
}
You can add more features like this gameover,pause game and you can also add music
full source code for snake game in JavaScript
Coding “Snake” in 4 min 30 sec (plain browser JavaScript)
watch the video: