概述
//定义画蛇的函数
snake.draw=function()
{
for(var i=0;i<this.body.length;i++)
{
this.body[i].draw();
}
};
snake.move = function()
{
var head = this.body[0];
if(snake.direction==“right”)
{
var newhead=new Block(head.col+1,head.row,head.size)
}
if(snake.direction ==“left”)
{
var newhead = new Block(head.col-1,head.row,head.size);
}
if(snake.direction==“up”)
{
var newhead=new Block(head.col,head.row-1,head.size)
}
if(snake.direction==“down”)
{
var newhead=new Block(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(var i=0;i<this.body.length;i++)
{
if(this.body[i].colnewhead.col &&this.body[i].rownewhead.row)
{
clearInterval(intervalId);
gameover();
}
}
this.body.unshift(newhead);
if(newhead.colapple.posX &&newhead.rowapple.posY)
{
score=score+100;
while(true)
{
var checkApple =false;
apple.posX=Math.floor(Math.random()*40);
apple.posY=Math.floor(Math.random()40);
for(var i=0; i<this.body.length;i++)
{
if(this.body[i].colapple.posX &&this.body[i].rowapple.posY)
checkApple=true;
}
if(!checkApple)
break;
}
}
else{
this.body.pop();
}
};
//创建苹果对象
var apple={
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.posX10+5,this.posY10+5,5,0,Math.PI2,false);
ctx.fill();
ctx.fillStyle=“Black”;
};
//结束
var gameover=function()
{
ctx.font=“60px Comic Sans MS”;
ctx.textAlign=“center”;
ctx.textBaseline=“middle”;
ctx.fillText(“GAME OVER!”,200,200)
};
//定时功能
var intervalId=setInterval (function ()
{
ctx.clearRect(0,0,400,400);
ctx.font=“20px Arial”;
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.keyCode37 &&snake.direction!=“right”)
{
snake.direction=“left”;
}
if(event.keyCode38 &&snake.direction!=“down”)
{
snake.direction=“up”;
}
if(event.keyCode39 &&snake.direction!=“left”)
{
snake.direction=“right”;
}
if(event.keyCode40 &&snake.direction!=“up”)
{
snake.direction=“down”;
}
}
);
最后
以上就是壮观柜子为你收集整理的js贪吃蛇小游戏的全部内容,希望文章能够帮你解决js贪吃蛇小游戏所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复