31 C
Gujarat
HomeJavascriptsimple snake game in JavaScript

simple snake game in JavaScript

we’re gonna make a quick game. This ones gonna be a snake-like game 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.

simple snake game in js


if you wanna play online

https://simplesnakegameinjs.netlify.app/

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

https://repl.it/@PatelRohan/simple-snake-game-in-JavaScript#index.html

Coding “Snake” in 4 min 30 sec (plain browser JavaScript)

watch the video:https://youtu.be/xGmXxpIj6vs


RELATED ARTICLES

11 COMMENTS

  1. Greetings! This is my first visit to your blog!
    We are a group of volunteers and starting a new project in a community in the same niche.
    Your blog provided us useful information to work on. You have done a extraordinary job!

  2. It’s a shame you don’t have a donate button! I’d certainly
    donate to this fantastic blog! I guess for now i’ll settle
    for bookmarking and adding your RSS feed to my Google account.

    I look forward to fresh updates and will talk about this site with my Facebook group.

    Talk soon!

  3. Do you mind if I quote a few of your articles as long as I provide credit and sources back to your webpage?
    My blog site is in the very same niche as yours and my users would definitely benefit from some of the information you provide here.
    Please let me know if this ok with you. Regards!

  4. Wow, incredible blog layout! How long have you been blogging for? you made blogging glance easy. The overall glance of your website is great, let alone the content material!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

15,000FansLike
5,000FollowersFollow
536FollowersFollow
- Advertisment -spot_img

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Most Popular