By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
Responding to and Tracking Key Presses
How to Work With Responding to and Tracking Key Presses
JavaScript
Passing a JavaScript Value Between HTML Pages
Passing a JavaScript Value Between HTML Pages
JavaScript
Compare Objects in an Array
JavaScript Problem: Compare Objects in an Array
JavaScript
Switching Name Order Using Capturing Groups in Regular Expressions
Switching Name Order Using Capturing Groups in Regular Expressions
JavaScript
Shuffling an Array
JavaScript Problem: How to Perform Shuffling an Array
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > How to Make simple snake game in JavaScript
JavaScript

How to Make simple snake game in JavaScript

Admin
Last updated: 2022/11/23 at 5:25 AM
Admin
Share
7 Min Read

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.

Contents
snakegame.htmlMakingCanvas full source code for snake game in JavaScript
simple snake game in javascript

if you wanna play online:

Demo

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:

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: snake game in javascript
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Admin
Follow:
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article what is a server Server Explained: What is a Server? It’s Working
Next Article What is Linear search in python?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

Responding to and Tracking Key Presses

How to Work With Responding to and Tracking Key Presses

February 5, 2023
Passing a JavaScript Value Between HTML Pages

Passing a JavaScript Value Between HTML Pages

February 3, 2023
Compare Objects in an Array

JavaScript Problem: Compare Objects in an Array

January 30, 2023
Switching Name Order Using Capturing Groups in Regular Expressions

Switching Name Order Using Capturing Groups in Regular Expressions

January 29, 2023
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?