1. <!doctype html>
    2. <html>
    3. <body>
    4. <canvas id="can" width="400" height="400" style="background: Black"></canvas>
    5. <script>
    6. var sn = [ 42, 41 ], dz = 43, fx = 1, n, ctx = document.getElementById("can").getContext("2d");
    7. function draw(t, c) {
    8. ctx.fillStyle = c;
    9. ctx.fillRect(t % 20 * 20 + 1, ~~(t / 20) * 20 + 1, 18, 18);
    10. }
    11. document.onkeydown = function(e) {
    12. fx = sn[1] - sn[0] == (n = [ -1, -20, 1, 20 ][(e || event).keyCode - 37] || fx) ? fx : n
    13. };
    14. !function() {
    15. sn.unshift(n = sn[0] + fx);
    16. if (sn.indexOf(n, 1) > 0 || n<0||n>399 || fx == 1 && n % 20 == 0 || fx == -1 && n % 20 == 19)
    17. return alert("GAME OVER");
    18. draw(n, "Lime");
    19. if (n == dz) {
    20. while (sn.indexOf(dz = ~~(Math.random() * 400)) >= 0);
    21. draw(dz, "Yellow");
    22. } else
    23. draw(sn.pop(), "Black");
    24. setTimeout(arguments.callee, 130);
    25. }();
    26. </script>
    27. </body>
    28. </html>

    注释版

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>贪吃蛇重构</title>
    6. <style>
    7. body {
    8. display: flex;
    9. height: 100vh;
    10. margin: 0;
    11. padding: 0;
    12. justify-content: center;
    13. align-items: center;
    14. }
    15. </style>
    16. </head>
    17. <body>
    18. <canvas id="can" width="400" height="400" style="background-color: black">对不起,您的浏览器不支持canvas</canvas>
    19. <script>
    20. var snake = [41, 40], //snake队列表示蛇身,初始节点存在但不显示
    21. direction = 1, //1表示向右,-1表示向左,20表示向下,-20表示向上
    22. food = 43, //食物的位置
    23. n, //与下次移动的位置有关
    24. box = document.getElementById('can').getContext('2d');
    25. //从0到399表示box里[0~19]*[0~19]的所有节点,每20px一个节点
    26. function draw(seat, color) {
    27. box.fillStyle = color;
    28. box.fillRect(seat % 20 *20 + 1, ~~(seat / 20) * 20 + 1, 19, 19);
    29. //用color填充一个矩形,以前两个参数为x,y坐标,后两个参数为宽和高。
    30. }
    31. document.onkeydown = function(evt) {
    32. //当键盘上下左右键摁下的时候改变direction
    33. direction = snake[1] - snake[0] == (n = [-1, -20, 1, 20][(evt || event).keyCode - 37] || direction) ? direction : n;
    34. };
    35. (function() {
    36. snake.unshift(n = snake[0] + direction);
    37. //此时的n为下次蛇头出现的位置,n进入队列
    38. if(snake.indexOf(n, 1) > 0 || n < 0 || n > 399 || direction == 1 && n % 20 == 0 || direction == -1 && n % 20 == 19) {
    39. //if语句判断贪吃蛇是否撞到自己或者墙壁,碰到时返回,结束程序
    40. return alert("GAME OVER!");
    41. }
    42. draw(n, "lime"); //画出蛇头下次出现的位置
    43. if(n == food) { //如果吃到食物时,产生一个蛇身以外的随机的点,不会去掉蛇尾
    44. while (snake.indexOf(food = ~~(Math.random() * 400)) > 0);
    45. draw(food, "yellow");
    46. } else { //没有吃到食物时正常移动,蛇尾出队列
    47. draw(snake.pop(),"black");
    48. }
    49. setTimeout(arguments.callee, 100);
    50. //每隔0.15秒执行函数一次,可以调节蛇的速度
    51. })();
    52. </script>
    53. </body>
    54. </html>