首頁  >  文章  >  web前端  >  如何用js開發實作簡單貪吃蛇遊戲

如何用js開發實作簡單貪吃蛇遊戲

一个新手
一个新手原創
2017-09-26 10:23:561864瀏覽

曾經諾基亞的貪吃蛇風靡一時,在遊戲匱乏的年代,用java實現太難,現在網頁製作20行程式碼就做成一個簡單的demo了,時代在進步啊


  1. #
    <!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開發實作簡單貪吃蛇遊戲

這是遊戲結束:

如何用js開發實作簡單貪吃蛇遊戲

以上是如何用js開發實作簡單貪吃蛇遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn