1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>贪吃蛇重构</title> <style> body { display: flex; height: 100vh; margin: 0; padding: 0; justify-content: center; align-items: center; } </style> </head> <body> <canvas id="can" width="400" height="400" style="background-color: black">对不起,您的浏览器不支持canvas</canvas> <script> var snake = [41, 40], direction = 1, food = 43, n, box = document.getElementById('can').getContext('2d'); function draw(seat, color) { box.fillStyle = color; box.fillRect(seat % 20 *20 + 1, ~~(seat / 20) * 20 + 1, 19, 19); } document.onkeydown = function(evt) { direction = snake[1] - snake[0] == (n = [-1, -20, 1, 20][(evt || event).keyCode - 37] || direction) ? direction : n; }; (function() { snake.unshift(n = snake[0] + direction); if(snake.indexOf(n, 1) > 0 || n < 0 || n > 399 || direction == 1 && n % 20 == 0 || direction == -1 && n % 20 == 19) { return alert("GAME OVER!"); } draw(n, "lime"); if(n == food) { while (snake.indexOf(food = ~~(Math.random() * 400)) > 0); draw(food, "yellow"); } else { draw(snake.pop(),"black"); } setTimeout(arguments.callee, 100); })(); </script> </body> </html>
|