And exit Game when snake eat itself.It’s your decision you can exit your game if it hits the Wall.

Now Play around with Jquery:

First thing Logic of the Game.It is simple.

Create an Array of Snake.

Write a function to paint snake array in Canvas.

Write a function for creating food.

Moving of snake:Remove Tail of the snake(Last element in array) and append to the Head(First Element)

Increment the Head.

Trigger the Paint function continuously.

And write exit conditions.

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

functionpaint()

{

YourScore="Your Score is: "+score;

$("p#Score").html(YourScore);

Context.fillStyle="black";

Context.fillRect(0,0,w,h);

Context.strokeStyle="black";

Context.strokeRect(0,0,w,h);

varHeadX=SnakeArray[0].x;

varHeadY=SnakeArray[0].y;

if(direction=="right")HeadX++;

elseif(direction=="left")HeadX--;

elseif(direction=="up")HeadY--;

elseif(direction=="down")HeadY++;

if(HeadX==-1)//If Snake hits Wall then resetting the head position

{//We can write exit conditon here instead of resetting the position.

HeadX=w/cw-1;

}elseif(HeadX==w/cw)

{

HeadX=0;

}

if(HeadY==-1)

{

HeadY=h/cw-1;

}

elseif(HeadY==h/cw)

{

HeadY=0;

}

if(Ouroboros_Check(HeadX,HeadY,SnakeArray))

{

pause();

GamePlay.pause();

if(GameOver.paused)

GameOver.play();

alert("Game Over- Your Score : "+score);

GameStart();

return;

}

if(HeadX==apple.x&&HeadY==apple.y)

{

SnakeEating.play();

vartail={x:HeadX,y:HeadY};

score++;

create_apple();

}

else

{

vartail=SnakeArray.pop();

tail.x=HeadX;tail.y=HeadY;

}

SnakeArray.unshift(tail);

for(vari=0;i<SnakeArray.length;i++)

{

varc=SnakeArray[i];

Draw_pixel(c.x,c.y);

}

Draw_pixel(apple.x,apple.y);

}

Key Board Movements:

Here is the code for key board movements. This function calls when keydown event occurs.Here I am checking one condition “allowPressKeys” this will disable the arrows when game is in pause mode.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

$(document).keydown(function(e){

if(!allowPressKeys){

returnnull;

}

varkey=e.which;

switch(key)

{

case37:

if(direction!="right")direction="left";

break;

case38:

if(direction!="down")direction="up";

break;

case39:

if(direction!="left")direction="right";

break;

case40:

if(direction!="up")direction="down";

break;

default:

break;

}

})

Creating Food and snake:

Creating food is nothing but painting one random pixel within the canvas.Each time generate one random pixel,paint it.For Snake Declare one array.Assign some length initially.Call Paint_cell function.

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

functionPaint_Snake()

{

varlength=3;

SnakeArray=[];

for(vari=length-1;i>=0;i--)

{

SnakeArray.push({x:i,y:0});

}

}

functioncreate_apple()

{

apple={

x:Math.round(Math.random()*(w-cw)/cw),

y:Math.round(Math.random()*(h-cw)/cw),

};

}

functionDraw_pixel(x,y)

{

Context.fillStyle="white";

Context.fillRect(x*cw,y*cw,cw,cw);

Context.strokeStyle="white";

Context.strokeRect(x*cw,y*cw,cw,cw);

}

Checking Exit Conditions:

If snake head meets it’s body then the game will end. Ouroboros_Check take arguments HeadX,HeadY,And SnakeArray,checks whether head meets Snake Body.(The Ouroborosis a symbol representing a Dragan eating own it’s tail.).When game ends we will call Startgame function.

1

2

3

4

5

6

7

8

9

functionOuroboros_Check(x,y,array)

{

for(vari=0;i<array.length;i++)

{

if(array[i].x==x&&array[i].y==y)

returntrue;

}

returnfalse;

}

Play and Pause Game:

The key of the Game is calling Paint function continuously. setInterval is a standard Java Script function,we can call it with a function(or code snippet) to execute it for every period in milliseconds.

The above Code display alert message for every 2 seconds. And For stopping we use clearInterval(AlertMsg) function.

In play method we will call setInterval with Paint() and in Pause we will call clearInterval.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

functionplay()

{

if(typeof Game_Interval!="undefined")clearInterval(Game_Interval);

Game_Interval=setInterval(paint,Speed);

allowPressKeys=true;

$("button#Soundoff").removeAttr('disabled');

$("button#SoundOn").removeAttr('disabled');

}

functionpause()

{

clearInterval(Game_Interval);

allowPressKeys=false;

$("button#Soundoff").attr('disabled','disabled');

$("button#SoundOn").attr('disabled','disabled');

}

Game Sounds And Buttons:

With <audio> tag in HTML5 We can include sounds in Web page.I am used three audio tags for Gameplaying(background music),GameOver(When snake eat itself) and SnakeEatingFood.

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

$("button#pause").click(function(){

$("button#pause").hide();

GamePlay.pause();

pause();

$("button#play").show();

});

$("button#Soundoff").click(function(){

$("button#Soundoff").hide();

GamePlay.play();

$("button#SoundOn").show();

});

$("button#SoundOn").click(function(){

$("button#SoundOn").hide();

GamePlay.pause();

$("button#Soundoff").show();

});

$("button#play").click(function(){

$("button#play").hide();

play();

GamePlay.play();

$("button#pause").show();

});

And I included some text between <audio> and <canvas> tags.

1

2

<canvas>OOps..Upgrade your browser</canvas>

<audio>Your browser does notsupport HTML5 audio.</audio>

If a browser supports canvas and audio tags then it simply ignore the text between the tags.And If not then the browser ignore the tags and displays the text between tags.No need to check canvas and audio support explicitly.

Click here to Play Game now.Turn On Your Speakers,Use Arrows to Move Snake,Use buttons for play pause and sound OFF ON.