Home  >  Article  >  Web Front-end  >  How to develop and implement a simple snake game using js

How to develop and implement a simple snake game using js

一个新手
一个新手Original
2017-09-26 10:23:561912browse

In the past, Nokia’s Snake was all the rage. In an era when games were scarce, it was too difficult to implement using Java. Now, you can create a simple demo with just 20 lines of code to create a web page. Times are progressing


  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>

This is the start of the game:

How to develop and implement a simple snake game using js

This is the end of the game:

How to develop and implement a simple snake game using js

The above is the detailed content of How to develop and implement a simple snake game using js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn