tangloong
2016-03-23 10:28:28
证
js开发实现简单贪吃蛇游戏(20行代码)
曾经诺基亚的贪吃蛇风靡一时,在游戏匮乏的年代,用java实现太难,现在网页制作20行代码就做成一个简单的demo了,时代在进步啊
代码:
01 | <!doctype html> |
02 | < html > |
03 | < body > |
04 | < canvas id = "can" width = "400" height = "400" style = "background:Black" ></ canvas > |
05 | < script > |
06 | var sn=[42,41],dz=43,fx=1,n,ctx=document.getElementById("can").getContext("2d"); |
07 | function draw(t,c){ |
08 | ctx.fillStyle=c; |
09 | ctx.fillRect(t%20*20+1,~~(t/20)*20+1,18,18); |
10 | } |
11 | document.onkeydown=function(e){fx=sn[1]-sn[0]==(n=[-1,-20,1,20][(e||event).keyCode-37]||fx)?fx:n}; |
12 | !function(){ |
13 | sn.unshift(n=sn[0]+fx); |
14 | if(sn.indexOf(n,1)>0 || n< 0 ||n>399||fx==1&&n%20==0||fx==-1&&n%20==19) return alert("GAME OVER"); |
15 | draw(n,"Lime"); |
16 | if(n==dz){ |
17 | while(sn.indexOf(dz=~~(Math.random()*400))>=0); |
18 | draw(dz,"Yellow"); |
19 | }else |
20 | draw(sn.pop(),"Black"); |
21 | setTimeout(arguments.callee,130); |
22 | }(); |
23 | </ script > |
24 | </ body > |
25 | </ html > |
这是开始游戏:
这是游戏结束:
gif动图
猜你喜欢
请下载代码后再发表评论


jiemomo LV12
2023年10月19日
hhhhhz LV7
2023年6月11日
77329TT LV21
2022年7月10日
喜欢html代码 LV4
2022年2月20日
lianghui LV13
2020年11月5日
shawnlee2020 LV1
2020年6月10日
46545646 LV1
2020年5月21日
2750850265 LV1
2020年4月21日
qiangqq LV2
2020年4月9日
李宇洋 LV2
2020年4月1日