您的位置:首页 > Web前端 > JavaScript

js小游戏----贪吃蛇

2017-09-07 13:56 316 查看
<html xmlns="http://www.w3.org/1999/xhtml

">

<head runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></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 + 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小游戏