演示如下:
实现代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#Canvas{
background-color:#F0DB98;
margin: auto;
padding: 0;
display: block;
}
</style>
</head>
<body>
<canvas id="Canvas" width="400" height="400"></canvas>
<script type="text/javascript">
var canvas=document.getElementById("Canvas");
var cxt=canvas.getContext("2d");
var x=32;
var y=32; // 定义蛇的初始位置
var a;
var t=1; //记录蛇的长度
var map=[];
var size=8;
var d=2;
function produceFood(){ //产生食物
a=Math.ceil(Math.random()*50);
cxt.beginPath();
cxt.fillStyle="#00B100";
cxt.fillRect(8*a,8*a,8,8);
cxt.closePath();
}
produceFood();
document.οnkeydοwn=function(e){
var code=e.keyCode-37;
switch(code){
case 1:d=1;break;
case 2:d=2;break;
case 3:d=3;break;
case 0:d=0;break;
}
}
function m(){
map.push({'x':x,'y':y}); //绘制蛇头
cxt.fillStyle="#00B100";
cxt.strokeStyle="#00B100";
cxt.fillRect(x,y,size,size);
switch(d){ //移动方向
case 1:y=y-size;break;
case 2:x=x+size;break;
case 0:x=x-size;break;
case 3:y=y+size;break;
}
if(map.length>t){ //前进一格
var c1=map.shift();
cxt.clearRect(c1['x'],c1['y'],size,size);
}
if(x>400||y>400||x<0||y<0){ //判断是否撞墙
if(x>400)
{alert("撞墙了");window.location.reload();}
if(y>400)
{alert("撞墙了");window.location.reload();}
if(x<0)
{alert("撞墙了");window.location.reload();}
if(y<0)
{alert("撞墙了");window.location.reload();}
}
for(var i=0;i<map.length;i++){ //判断是否咬到自己
if(parseInt(map[i].x)==x&&parseInt(map[i].y)==y){
alert("咬到自己");
window.location.reload();
}
}
if((8*a)==x&&(8*a)==y){ //判断是否吃到食物
t++;
produceFood();
}
}
setInterval(m,300); //每0.3秒移动一次
</script>
</body>
</html>