代码如下
<canvas id="hb" width="600" height="600">
#hb{
background: #33cc99;
margin-left: 200px;
margin-top: 100px;
}
window.onload=function () {
var h=document.getElementById('hb');
//取工具
var tools= h.getContext('2d');
var num=0;
//取线 moveTO(x,y) 起点坐标 lineto(x,y) 终点坐标
tools.strokeStyle='white';
var x= Math.floor( Math.random()* 20) * 30;
var y= Math.floor( Math.random()* 20) * 30;
var dx=1;
var dy=0;
var gameover;
//定义食物没有被吃掉
var iseate=false;
var snake=[{x:3,y:0},{x:2,y:0},{x:1,y:0}];
document.addEventListener('keydown',function (event) {
if (event.keyCode === 38) {
console.log('上');
dx=0;
dy=-1;
}else if(event.keyCode === 40){
console.log('下');
dx=0;
dy=1;
}else if(event.keyCode === 37){
dx=-1;
dy=0;
}else if(event.keyCode === 39){
dx=1;
dy=0;
}
});
setInterval(function () {
//擦除画布
if (gameover) {
return
}
tools.clearRect(0,0,600,600);
//随机生成食物 math.floor向下取整19.9-19 18.2-18
if (iseate) {
x= Math.floor( Math.random()* 20) * 30;
y= Math.floor( Math.random()* 20) * 30;
}
//绘制食物 食物的范围为0.19
tools.fillStyle='red';
tools.fillRect(x,y,30,30);//绘制一个矩形
//绘制蛇:贪吃蛇随着擦除会动起来
if(snake[0].x *30 === x && snake[0].y *30 === y ){
iseate=true;
}else {
iseate=false;
snake.pop();
}
var oldhead=snake[0];
//新的
var newhead={
x:oldhead.x+dx,
y:oldhead.y+dy
};
//游戏结束的判定
if (newhead.y<0 || newhead.x<0 || newhead.x *30>=600 || newhead.y *30>=600) {
gameover=true;
alert("你撞墙,已经死了");
}else {
snake.unshift(newhead);
}
//舌头
/* tools.fillStyle='blue';
tools.fillRect(snake[0].x*30,snake[0].y*30,30,30);
tools.fillStyle='#333399';
tools.fillRect(snake[1].x*30,snake[1].y*30,30,30);
tools.fillRect(snake[2].x*30,snake[2].y*30,30,30);*/
for (var i=0;i<snake.length;i++) {
if (i === 0){
tools.fillStyle='blue';
} else {
tools.fillStyle='#333399';
}
tools.fillRect(snake[i].x*30,snake[i].y*30,30,30);
}
for(var i=1;i<20;i++){
tools.moveTo(0,30 * i+0.5);
tools.lineTo(600,30 * i +0.5);
tools.moveTo(30 * i+0.5,0);
tools.lineTo(30 * i+0.5,600);
}
tools.stroke();
},1000/3);
}
都是通过画布画图做的,画布一遍一遍的擦掉和覆盖