我就不简述了,基本都写在备注里了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas</title>
<script type="application/javascript">
window.onload = function () {
//alert("aaa");
var canvas = document.getElementById("m_canvas"); //相当于画布
var context = canvas.getContext("2d"); //相当于画笔,同时指定实在2D平面绘制
var kc = 37; //给蛇一个初始方向,一个方向键的keyCode 和啊似科码差不多
document.onkeydown = function (key) {
if(Math.abs(key.keyCode-kc)!=2){
//判断小蛇不能倒退,相反的位置keycode相差为2
kc = key.keyCode;
}
}
var array = [{x: 200, y: 150}, {x: 200, y: 155}]; //用于储存最初的蛇身的点
var bean = null;
function draw() {
if (bean == null) {
var x = Math.floor(Math.random() * 79) * 5; //floor 向下取整,random得到的为0~1之间的数
var y = Math.floor(Math.random() * 59) * 5;
bean = {x: x, y: y};
}
context.fillStyle = "black";
context.fillRect(0, 0, 400, 300);
context.fillStyle="blue";
context.fillRect(0,0,5,300);
context.fillRect(0,0,400,5);
context.fillRect(395,0,5,300);
context.fillRect(0,295,400,5);
context.fillStyle = "green";
context.fillRect(bean.x, bean.y, 5, 5);
context.fillStyle = "red";
for (var i = 0; i < array.length; i++) {
context.fillRect(array[i].x, array[i].y, 5, 5);
}
var point = {x: array[0].x, y: array[0].y};
switch (kc) {
case 37:
point.x = point.x - 5; //左
break;
case 38:
point.y = point.y - 5; //上
break;
case 39:
point.x = point.x + 5; //右
break;
case 40:
point.y = point.y + 5; //下
break;
}
for (var i = array.length; i >= 0; i--) {
if (i==array.length){
//其实数组应该是从length-1开始遍历,array.length本来是数组越界的(虽然js没有越界),添加在for循环的第一次,用于判断死亡情况,简化代码
if (point.x==bean.x&&point.y==bean.y){
array[i]=array[i-1];
bean=null;
}
if (point.x>=395||point.x<=0||point.y<=0||point.y>=295){
alert("小蛇死掉了~~");
return 0;
}
for (var i = 0; i < array.length; i++) {
if (point.x==array[i].x&&point.y==array[i].y){
alert("小蛇自杀了~");
return 0;
}
}
} else if (i > 0) {
array[i] = array[i - 1]; //在不吃豆子的时候将蛇身上的每一个点往后移位,相当于蛇移动
} else {
array[0] = point; //把一个新的点赋值给蛇头位置,即数组0号位置
}
}
setTimeout(draw, 100); //递归调用,设置绘制的延时,控制小蛇的速度
}
setTimeout(draw, 100); //第一次调用,以后进入递归
}
</script>
</head>
<body>
<canvas id="m_canvas" width="400" height="300">你的浏览器不支持canvas</canvas>
<p>控制 ↑↓← →,不能撞墙和撞自身</p>
</body>
</html>