Abudula 2012-07-05
$(document).ready(function(){
//Canvasstuff
varcanvas=$("#canvas")[0];
varctx=canvas.getContext("2d");
varw=$("#canvas").width();
varh=$("#canvas").height();
//Letssavethecellwidthinavariableforeasycontrol
varcw=10;
vard;
varfood;
varscore;
//Letscreatethesnakenow
varsnake_array;//anarrayofcellstomakeupthesnake
varisgameover;
functioninit()
{
d="right";//defaultdirection
create_snake();
create_food();//Nowwecanseethefoodparticle
//finallyletsdisplaythescore
score=0;
//Letsmovethesnakenowusingatimerwhichwilltriggerthepaintfunction
//every60ms
if(typeofgame_loop!="undefined")clearInterval(game_loop);
game_loop=setInterval(paint,60);
isgameover=false;
}
init();
functioncreate_snake()
{
varlength=5;//Lengthofthesnake
snake_array=[];//Emptyarraytostartwith
for(vari=length-1;i>=0;i--)
{
//Thiswillcreateahorizontalsnakestartingfromthetopleft
snake_array.push({x:i,y:0});
}
}
//Letscreatethefoodnow
functioncreate_food()
{
food={
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw),
};
//Thiswillcreateacellwithx/ybetween0-44
//Becausethereare45(450/10)positionsaccrosstherowsandcolumns
}
functionpaint_gameover(){
ctx.fillStyle='red';
//ctx.fillText("GameOver",50,h-200);
ctx.font="bold50pxsans-serif";
ctx.strokeText("GameOver",w/2-70,h/2);
ctx.font="bold20pxsans-serif";
ctx.fillText("replay",w/2,h/2+20);
isgameover=true;
}
//Letspaintthesnakenow
functionpaint()
{
//ToavoidthesnaketrailweneedtopainttheBGoneveryframe
//Letspaintthecanvasnow
ctx.fillstyle="white";
ctx.fillRect(0,0,w,h);
ctx.strokestyle="black";
ctx.strokeRect(0,0,w,h);
isgameover=false;
//Themovementcodeforthesnaketocomehere.
//Thelogicissimple
//Popoutthetailcellandplaceitinfrontoftheheadcell
varnx=snake_array[0].x;
varny=snake_array[0].y;
//Thesewerethepositionoftheheadcell.
//Wewillincrementittogetthenewheadposition
//Letsaddproperdirectionbasedmovementnow
if(d=="right")nx++;
elseif(d=="left")nx--;
elseif(d=="up")ny--;
elseif(d=="down")ny++;
//Letsaddthegameoverclausesnow
//Thiswillrestartthegameifthesnakehitsthewall
//Letsaddthecodeforbodycollision
//Nowiftheheadofthesnakebumpsintoitsbody,thegamewillrestart
if(nx==-1||nx==w/cw||ny==-1||ny==h/cw||check_collision(nx,ny,snake_array))
{
paint_gameover();
//restartgame
//Letsorganizethecodeabitnow.
return;
}
//Letswritethecodetomakethesnakeeatthefood
//Thelogicissimple
//Ifthenewheadpositionmatcheswiththatofthefood,
//Createanewheadinsteadofmovingthetail
if(nx==food.x&&ny==food.y)
{
vartail={x:nx,y:ny};
score++;
//Createnewfood
create_food();
}
else
{
vartail=snake_array.pop();//popsoutthelastcell
tail.x=nx;tail.y=ny;
}
//Thesnakecannoweatthefood.
snake_array.unshift(tail);//putsbackthetailasthefirstcell
for(vari=0;i<snake_array.length;i++)
{
varc=snake_array[i];
//Letspaint10pxwidecells
paint_cell(c.x,c.y);
}
//Letspaintthefood
paint_cell(food.x,food.y);
//Letspaintthescore
varscore_text="Score:"+score;
ctx.fillText(score_text,5,h-5);
}
//Letsfirstcreateagenericfunctiontopaintcells
functionpaint_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);
}
functioncheck_collision(x,y,array)
{
//Thisfunctionwillcheckiftheprovidedx/ycoordinatesexist
//inanarrayofcellsornot
for(vari=0;i<array.length;i++)
{
if(array[i].x==x&&array[i].y==y)
returntrue;
}
returnfalse;
}
//Letsaddthekeyboardcontrolsnow
$(document).keydown(function(e){
if(isgameover)return;
varkey=e.which;
//Wewilladdanotherclausetopreventreversegear
if(key=="37"&&d!="right")d="left";
elseif(key=="38"&&d!="down")d="up";
elseif(key=="39"&&d!="left")d="right";
elseif(key=="40"&&d!="up")d="down";
//Thesnakeisnowkeyboardcontrollable
})
$("#canvas").click(function(){
if(isgameover){
init();
}
})
})