Thứ Ba, 6 tháng 9, 2016

HTML5 game tutorial - Make a snake game using HTML5 canvas and Jquery

HTML5 game tutorial - Make a snake game using HTML5 canvas and Jquery

View code Play Walkthrough

Description

Learn to make a simple snake game using HTML5 canvas and Jquery.
X
Add New Comment

53 Comments

(close)
matt

matt

you forgot to make sure that the food does not collide with the snake body on creation
anon

anon

If you press down and left very quickly (perhaps other combinations are also possible) the game is over.
Phil

Phil

Wow, this reminds me so much of Pygame, the game framework for Python. Glad I found this to show me how similar (and easy) they are.
Daniel

Daniel

Rockstar <3
html5coder

html5coder

Looks pretty nice but it won’t work, what should i be doing wrong?
Liucw

Liucw

so good,programmer of ideas so clearly!
SonicTheBlueBlur2

SonicTheBlueBlur2

html5coder, you have to left-click inside the game box to play, just like with Flash.
SonicTheBlueBlur2

SonicTheBlueBlur2

html5coder, you have to left-click inside the game box to play, just like with Flash.
Emilio Gu

Emilio Gu

Thanks! I don’t understand some parts but, I try to execute and it don’t work! I’ve created the snake.html and the snake.js (the snake.css seems not necesary now), I click in the html but it don’t work. I see there’s no link between snake.html and snake.js, I mean, the html did not include the js to work the game…
swarnika

swarnika

very nice…….
Etienne

Etienne

Nice game, but jQuery is useless !
Carlos

Carlos

Emilio Gu,
Just add this line of code to the HTML file:
Antoine Dahan

Antoine Dahan

Hey Emilio Gu,
in your html file just put the line:
(assuming snake.js is the name of the js file. Also make sure they are in same directory.
Antoine Dahan

Antoine Dahan



riz

riz

brilliant tutorial. You can get rid of jquery dependency by doing this for key presses
document.onkeydown = function(evt)
{
if(evt.keyCode == 37 && d != “right”) d = “left”;
else if(evt.keyCode == 38 && d != “down”) d = “up”;
else if(evt.keyCode == 39 && d != “left”) d = “right”;
else if(evt.keyCode == 40 && d != “up”) d = “down”;
}
//and for dimensions
var w = canvas.getAttribute(“width”);
var h = canvas.getAttribute(“height”);
wazzup

wazzup

There is no need for jquery here really…
annoyedude

annoyedude

The anti-jquery police people are annoying. Sure you don’t strictly *have* to use jquery for this, but it makes a few of the lines easier, a lot of professionals and non-professionals use it by default anyway, isn’t that difficult to add and it warned on the title. well it was his choice to do use that anyway. you can always look at non-jquery html5 game tutorials if that is your preference, but that doesn’t mean every tutorial has to be non-jquery! geez.
killhindoodooos

killhindoodooos

What I did to get it to work was just include a line that says
I don’t know why the original version here works.
Susannah

Susannah

Hmm is anyone else encountering problems with the images on this blog loading?
I’m trying to find out if its a problem on my end or if it’s the blog.
Any feedback would be greatly appreciated.
shrawan

shrawan

thanks ! good walk through !
daffes

daffes

Here’s a fix for:
“If you press down and left very quickly (perhaps other combinations are also possible) the game is over.”
http://pastebin.com/SGxB3H6c
It queues up the keystrokes and only changes the direction once the paint() function is called.
OJ

OJ

I don’t quite see why you need to play around with the tail variable in the snake moving part.
What would be the shortcoming of the following replacement?
if(nx == food.x && ny == food.y)
{
score++;
//Create new food
create_food();
}
else
{
snake_array.pop(); //pops out the last cell
}
var newhead = {x: nx, y: ny};
snake_array.unshift(newhead); //adds the new head as the first cell
This would seem much more easy to follow to me, but perhaps I’m missing something.
Shan

Shan

Nice tutorial!
Was very useful!
Can you suggest some other good html5 game tuts that you know?
Felix

Felix

Hi, excellent tutorial.
Any version for smartphone or tablets?
Thanks
Dominik

Dominik

Where is the definition of “game_loop”?
The game cannot work if game_loop doesnt work, yet its not defined anywhere…
Dominik

Dominik

I see now… nevermind
Prajjwal

Prajjwal

wow, dude you are a master of HTML you are a great person keep hardwork
Melek Jlassi

Melek Jlassi

please how i can do it im new in the css3 and html5 languages im new in all languages how i can do this i copy then all and put them in notepad and save them to .html or what ?
Jan

Jan

can someone explain all parts of code pls ?
Jan

Jan

no need, i understand now.
Mohamed Alaa

Mohamed Alaa

I’ve always been wondering about snake game’s logic and now you finally explained it to me, Thank you very much :)
boom beach diamonds hack

boom beach diamonds hack

Communication is often stunted, and scammers seem too populate the sites as much
as actual shoppers. For instance, your chat operators can trabsfer chats, handle multiple
chats simultaneously and even generate chat transcripts all from the comfort of their palm.
You can hire any dedicated programmer who can work dedicatedly and who is able to deliver
your appropriate work on time with the supreme expertise and highly advanced techniques and technologies such as Objective C, Cocoa,
Xcode, interface builder and many more.
thanh

thanh

simple but very great
Abdul

Abdul

Is there a way to make the game not start automatically, like to start the game the user has to click on the canvas, similarly when the game is over.
badlyneeded

badlyneeded

how to put background picture and change the snake to image as well as the food to fruit?
a.h

a.h

Carlos, Antoine, what line should Emilio add?
I am having the same issue.
Also, to remove all JS dependencies, how can we replace these lines:
//first line
$(document).ready(function(){
//canvas
var canvas = $(“#canvas”)[0];
Jordan Lane

Jordan Lane

This is a fun little project!
I’ve created an object oriented version without the jQuery dependency and couple more features like food spawning collision and double movement blocking. Here it is for anyone interested: https://github.com/JJCLane/Snake
Robert

Robert

Very nice tutorial, keep it up!
Thank you. :)
Brian

Brian

This game is bad piggies
miha

miha

Nice, congrats for simplicity.
Free pokemon games

Free pokemon games

Usually I do not learn article on blogs, however I wish to say that this write-up very forced me to
take a look at and do so! Your writing style has been surprised
me. Thank you, very great article.
http://Durl.me/Apyqeg

http://Durl.me/Apyqeg

Good answer back in return of this matter with genuine arguments and telling everything on the topic
of that.
woodworking

woodworking

CNC equipment aids in keeping overhead low while
profiding the most optimal environment for boosted productivity.
The size of the project in its raw stage is also something to
think about. To make it even easy to understand iit could include detailed
drawings to ggo with each stage showing the progress off youur project.
Skill level is also an important component in all types oof woodwork and home projects.
Homes

Homes

Dobra komunikacja z centrum miasta oraz dojazd do obwodnicy są jednym z głowach atutów tej okolicy.
Elouise

Elouise

Dodge headligghts are available in verry reasonable rice on the stores.
This kit iis vwry useful ass it offers a wide range of clours
according to colour temperatures; you can pick the one that matches well with your car.
You shoujld be able too nail the first easily
(and almost automatically) as you round the corner.
A GPS unit can be a great idea for a teens vehicle.
Unless someone has plenty off ready cash, they are unlikely to be able to
regularly change their car, particularly if they like driving new
vehicles.
scarymazegames

scarymazegames

Appreciating the time and energy you put into your blog and
in depth information you offer. It’s good to come across a blog
every once in a while that isn’t the same outdated rehashed material.
Fantastic read! I’ve saved your site and I’m adding your RSS feeds to my Google account.
 
<!-- Lets make a simple snake game -->
<canvas id="canvas" width="450" height="450"></canvas>
 
<!-- Jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
 
$(document).ready(function(){
    //Canvas stuff
    var canvas = $("#canvas")[0];
    var ctx = canvas.getContext("2d");
    var w = $("#canvas").width();
    var h = $("#canvas").height();
    
    //Lets save the cell width in a variable for easy control
    var cw = 10;
    var d;
    var food;
    var score;
    
    //Lets create the snake now
    var snake_array; //an array of cells to make up the snake
    
    function init()
    {
        d = "right"; //default direction
        create_snake();
        create_food(); //Now we can see the food particle
        //finally lets display the score
        score = 0;
        
        //Lets move the snake now using a timer which will trigger the paint function
        //every 60ms
        if(typeof game_loop != "undefined") clearInterval(game_loop);
        game_loop = setInterval(paint, 60);
    }
    init();
    
    function create_snake()
    {
        var length = 5; //Length of the snake
        snake_array = []; //Empty array to start with
        for(var i = length-1; i>=0; i--)
        {
            //This will create a horizontal snake starting from the top left
            snake_array.push({x: i, y:0});
        }
    }
    
    //Lets create the food now
    function create_food()
    {
        food = {
            x: Math.round(Math.random()*(w-cw)/cw), 
            y: Math.round(Math.random()*(h-cw)/cw), 
        };
        //This will create a cell with x/y between 0-44
        //Because there are 45(450/10) positions accross the rows and columns
    }
    
    //Lets paint the snake now
    function paint()
    {
        //To avoid the snake trail we need to paint the BG on every frame
        //Lets paint the canvas now
        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, w, h);
        ctx.strokeStyle = "black";
        ctx.strokeRect(0, 0, w, h);
        
        //The movement code for the snake to come here.
        //The logic is simple
        //Pop out the tail cell and place it infront of the head cell
        var nx = snake_array[0].x;
        var ny = snake_array[0].y;
        //These were the position of the head cell.
        //We will increment it to get the new head position
        //Lets add proper direction based movement now
        if(d == "right") nx++;
        else if(d == "left") nx--;
        else if(d == "up") ny--;
        else if(d == "down") ny++;
        
        //Lets add the game over clauses now
        //This will restart the game if the snake hits the wall
        //Lets add the code for body collision
        //Now if the head of the snake bumps into its body, the game will restart
        if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw || check_collision(nx, ny, snake_array))
        {
            //restart game
            init();
            //Lets organize the code a bit now.
            return;
        }
        
        //Lets write the code to make the snake eat the food
        //The logic is simple
        //If the new head position matches with that of the food,
        //Create a new head instead of moving the tail
        if(nx == food.x && ny == food.y)
        {
            var tail = {x: nx, y: ny};
            score++;
            //Create new food
            create_food();
        }
        else
        {
            var tail = snake_array.pop(); //pops out the last cell
            tail.x = nx; tail.y = ny;
        }
        //The snake can now eat the food.
        
        snake_array.unshift(tail); //puts back the tail as the first cell
        
        for(var i = 0; i < snake_array.length; i++)
        {
            var c = snake_array[i];
            //Lets paint 10px wide cells
            paint_cell(c.x, c.y);
        }
        
        //Lets paint the food
        paint_cell(food.x, food.y);
        //Lets paint the score
        var score_text = "Score: " + score;
        ctx.fillText(score_text, 5, h-5);
    }
    
    //Lets first create a generic function to paint cells
    function paint_cell(x, y)
    {
        ctx.fillStyle = "blue";
        ctx.fillRect(x*cw, y*cw, cw, cw);
        ctx.strokeStyle = "white";
        ctx.strokeRect(x*cw, y*cw, cw, cw);
    }
    
    function check_collision(x, y, array)
    {
        //This function will check if the provided x/y coordinates exist
        //in an array of cells or not
        for(var i = 0; i < array.length; i++)
        {
            if(array[i].x == x && array[i].y == y)
             return true;
5x 10x 15x 20x
53 Comments
Description

Không có nhận xét nào:

Đăng nhận xét