<!DOCTYPEhtml>
<html>
<head><title>贪吃蛇</title>
</head>
<body>
<canvasid="canvas"width="400"height="400"></canvas>
<scriptsrc="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
varcanv=document.getElementById("canvas");
varctx=canv.getContext("2d");
varscore=0;
//定义一个方块的构造函数
varBlock=function(col,row,size)
{
this.col=col;
this.row=row;
this.size=size;
};
//定义Block函数的原型方法draw;
Block.prototype.draw=function()
{
ctx.fillRect(this.col*this.size,this.row*this.size,this.size,this.size)
}
//定义对象蛇
varsnake={
body:[
newBlock(20,20,10),
newBlock(20,21,10),
newBlock(20,22,10)
],
direction:"right",
};
//定义画蛇的函数
snake.draw=function()
{
for(vari=0;i<this.body.length;i++)
{
this.body[i].draw();
}
};
snake.move=function()
{
varhead=this.body[0];
if(snake.direction=="right")
{
varnewhead=newBlock(head.col+1,head.row,head.size)
}
if(snake.direction=="left")
{
varnewhead=newBlock(head.col-1,head.row,head.size);
}
if(snake.direction=="up")
{
varnewhead=newBlock(head.col,head.row-1,head.size)
}
if(snake.direction=="down")
{
varnewhead=newBlock(head.col,head.row+1,head.size)
}
if(newhead.col<0||newhead.col>39)
{
clearInterval(intervalId);
gameover();
}
if(newhead.row<0||newhead.row>39)
{
clearInterval(intervalId);
gameover();
}
for(vari=0;i<this.body.length;i++)
{
if(this.body[i].col==newhead.col&&this.body[i].row==newhead.row)
{
clearInterval(intervalId);
gameover();
}
}
this.body.unshift(newhead);
if(newhead.col==apple.posX&&newhead.row==apple.posY)
{
score=score+100;
while(true)
{
varcheckApple=false;
apple.posX=Math.floor(Math.random()*40);
apple.posY=Math.floor(Math.random()*40);
for(vari=0;i<this.body.length;i++)
{
if(this.body[i].col==apple.posX&&this.body[i].row==apple.posY)
checkApple=true;
}
if(!checkApple)
break;
}
}
else{
this.body.pop();
}
};
//创建苹果对象
varapple={
posX:Math.floor(Math.random()*40),
posY:Math.floor(Math.random()*40),
sizeR:5
}
//画苹果函数
apple.draw=function()
{
ctx.fillStyle="Green";
ctx.beginPath();
ctx.arc(this.posX*10+5,this.posY*10+5,5,0,Math.PI*2,false);
ctx.fill();
ctx.fillStyle="Black";
};
//结束
vargameover=function()
{
ctx.font="60pxComicSansMS";
ctx.textAlign="center";
ctx.textBaseline="middle";
ctx.fillText("GAMEOVER!",200,200)
};
//定时功能
varintervalId=setInterval(function()
{
ctx.clearRect(0,0,400,400);
ctx.font="20pxArial";
ctx.fillText("Score:"+score,5,15);
snake.draw();
snake.move();
apple.draw();
ctx.strokeRect(0,0,400,400);
},200);
//贪吃蛇的按键控制
$("body").keydown(function(event)
{
console.log(event.keyCode);
if(event.keyCode==37&&snake.direction!="right")
{
snake.direction="left";
}
if(event.keyCode==38&&snake.direction!="down")
{
snake.direction="up";
}
if(event.keyCode==39&&snake.direction!="left")
{
snake.direction="right";
}
if(event.keyCode==40&&snake.direction!="up")
{
snake.direction="down";
}
}
);
</script>
</body>
</html>
|