Loading...

Create the snake game with HTML5 and jQuery

View: 2625    Dowload: 0   Comment: 0   Post by: hanhga   Category: References   Fields: none

Surely you are familiar with the game "Snakes" are often available in applications of mobile phone games and the video games before. Have you ever thought you would manually write applications, or integrate this role into the website or web blog so visitors can have fun and stay longer on your site.
Today I will share with you every step taken to create game "Snake" with just HTML5 Canvas and jQuery.

html5, games snake, jQuery, html5 tips, tao tro choi

HTML

First we will need to declare a canvas element and the jQuery library as follows:

1
2
3
4
5
6
7
8
9
<!-- 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>

jQuery

And this is the whole brain as well as the code will help you create solid game hunting as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<script type="text/javascript">
 
$(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;
 
        }
 
        return false;
 
    }
 
      
 
    //Lets add the keyboard controls now
 
    $(document).keydown(function(e){
 
        var key = e.which;
 
        //We will add another clause to prevent reverse gear
 
        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 snake is now keyboard controllable
 
    })
 
          
 
})
 
</script>

On each annotated code clear and I hope that through this game, the more you will understand in the application of html5 canvas element as well as enhance their code with jQuery.

Create the snake game with HTML5 and jQuery

Surely you are familiar with the game "Snakes" are often available in applications of mobile phone games and the video games before. Have you ever thought you would manually write applications, or integrate this role into the website or web blog so visitors can have fun and stay longer on your site.

Posted on 25-06-2015 

Comment:

To comment you must be logged in members.

Files with category

  • Instructions for installing and configuring Windows Live Mail on Windows 10 simple

    Instructions for installing and configuring Windows Live Mail on Windows 10 simple

    View: 3489    Download: 0   Comment: 0

    Category: References     Fields: Other

    Windows 10 pre-installed Mail application for managing personal email on the device. The latest version of this application but improved a lot and support other email accounts such as Gmail or Yahoo Mail but users almost no "salty" really with this...

  • Step by step instructions to create social networking buttons with CSS3

    Step by step instructions to create social networking buttons with CSS3

    View: 2484    Download: 0   Comment: 0

    Category: References     Fields: Other

    CSS3 help web designers have the ability to create buttons (buttons) very nice, today I will share with you two tips decoration for button in your web becomes radiant beauty that no need to use photoshop.

  • You should understand the CSS Box Shadow

    You should understand the CSS Box Shadow

    View: 2574    Download: 0   Comment: 0

    Category: References     Fields: Other

    Effects his shadow was introduced in the previous article, however, in this article, I will guide more specific about shadow attributes, you try it with anything. First we try to learn css following paragraph:

  • How to do button movement with beautiful CSS3

    How to do button movement with beautiful CSS3

    View: 2235    Download: 0   Comment: 0

    Category: References     Fields: Other

    Previously to create motion effects button, you must draw the button in photoshop, then switched to flash to make it possible to move. But now you need not spend too much time doing it, all because of the emergence of CSS3.

  • Create a dropdown menu with CSS3 effects with beautiful transtions

    Create a dropdown menu with CSS3 effects with beautiful transtions

    View: 2420    Download: 0   Comment: 0

    Category: References     Fields: Other

    More of the dropdown menu you want to introduce to you, this will have the effect menu transitions (converted background of menu background from pale to dark). This menu works well on browsers like FF, Chrome, Safary, but unfortunately did not work...

  • How to hack css for all browsers you should know

    How to hack css for all browsers you should know

    View: 1994    Download: 0   Comment: 0

    Category: References     Fields: Other

    In the process of web design, which makes it the most headaches is how to design web pages that you can run on the browser. Especially when clients use the old as IE6 browser such. However, with this article, you will easily edit interface runs well...

  • Create Accordion with extremely beautiful CSS3

    Create Accordion with extremely beautiful CSS3

    View: 2518    Download: 0   Comment: 0

    Category: References     Fields: Other

    Accordion is a technique that helps you shortened the content that you want displayed on the website. It is often used for the display of submenus. In addition you can also use it for content, images. Before applying this procedure, you have to use...

  • Create the effect Hovercho images with Webkit and CSS3 is great

    Create the effect Hovercho images with Webkit and CSS3 is great

    View: 2159    Download: 0   Comment: 0

    Category: References     Fields: Other

    WebKit is one open source application framework provides the necessary components built one for your web browser. Along with CSS3, cả have contributed to very nice effect những previously only using JavaScript or JQuery thực beige.​

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd