<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>20 行 JS 代码实现贪吃蛇</title>
</head>
<body>
<canvas id="can" width="400" height="400" style="background:black;"></canvas>
<script>
var sn=[42,41],dz=43,fx=1,n,ctx=document.getElementById("can").getContext("2d");
function draw(t,c){
ctx.fillStyle=c;
ctx.fillRect(t%20*20,~~(t/20)*20,18,18);
}
document.onkeydown=function(e){fx=sn[1]-sn[0]==(n=[-1,-20,1,20][(e||event).keyCode-37]||fx)?fx:n};
!function(){
sn.unshift(n=sn[0]+fx);
if(sn.indexOf(n,1)>0 || n<0||n>399||fx==1&&n%20==0||fx==-1&&n%20==19) return alert("GAME OVER");
draw(n,"Lime");
if(n==dz){
while(sn.indexOf(dz=~~(Math.random()*400))>=0);
draw(dz,"Yellow");
}else
draw(sn.pop(),"Black");
setTimeout(arguments.callee,500);
}();
</script>
</body>
</html>
1
qq292382270 2017-06-14 15:53:18 +08:00
不会前端的人看起来觉得好 NB ...
|
2
580a388da131 2017-06-14 18:06:57 +08:00
|
3
xiaojunjor 2017-06-16 09:58:41 +08:00
这是 csdn 的 jslang 写的吧,很久之前了
|
4
pyufftj 2017-06-17 10:00:39 +08:00
有点注释就更好了。。
|