«

js 实现贪吃蛇游戏

时间:2021-12-13     作者:想美好的未来     分类: 开发相关


play: https://www.ccgxk.com/46.html

源码:

<canvas id="can" width="400" height="400" style="background:Black"></canvas>
<script>
    var sn = [42, 41]
     var dz = 43
     var fx = 1
     var n
     var  ctx = document.getElementById("can").getContext("2d")

    function draw(t, c) {
        ctx.fillStyle = c;
        ctx.fillRect(t % 20 * 20 + 1, Math.floor(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.floor(Math.random() * 400)) >= 0);
            draw(dz, "Yellow");
        } else {
            draw(sn.pop(), "Black");
        }
        setTimeout(arguments.callee, 130);
    }();
</script>

顺便测试一下我的文字

abcdefghijklmnopqrstuvwxyz