tangloong的gravatar头像
tangloong 2016-03-23 10:28:28

js开发实现简单贪吃蛇游戏(20行代码)

曾经诺基亚的贪吃蛇风靡一时,在游戏匮乏的年代,用java实现太难,现在网页制作20行代码就做成一个简单的demo了,时代在进步啊

代码:

<!doctype html>
<html>
<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+1,~~(t/20)*20+1,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,130);
    }();
</script>
</body>
</html>

这是开始游戏:

js开发实现简单贪吃蛇游戏(20行代码)

这是游戏结束:

js开发实现简单贪吃蛇游戏(20行代码)

gif动图


打赏

文件名:snakeat.zip,文件大小:0.599K 下载
  • /
    • /snakeat.html
最代码最近下载分享源代码列表最近下载
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日
最代码最近浏览分享源代码列表最近浏览
小学生波波  LV19 1月10日
jacky_non  LV2 2023年12月26日
jiemomo  LV12 2023年10月19日
HTMLSW 2023年7月6日
暂无贡献等级
hhhhhz  LV7 2023年6月11日
ikun1232  LV1 2023年4月9日
张旭冬  LV1 2022年11月30日
157226747  LV16 2022年11月25日
舒舒不吃葱花  LV2 2022年11月18日
李宜昌  LV5 2022年7月7日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友