帮我写一个 贪吃蛇游戏
xiao9469
2023/03/16 21:44:12
- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>璐悆铔囨父鎴</title> <style> body { background: #f9f9f9; font-family: sans-serif; color: #333; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; padding: 0; } h1 { font-size: 3rem; margin: 0; padding: 0; margin-bottom: 1rem; } canvas { border: 1px solid #ddd; } </style> </head> <body> <h1>璐悆铔囨父鎴</h1> <canvas id="snake" width="400" height="400"></canvas> <script src="snake.js"></script> </body> </html>
JavaScript 浠g爜锛- // 瀹氫箟鍙橀噺 var canvas = document.getElementById("snake"); var ctx = canvas.getContext("2d"); var snakeSize = 10; var w = 400; var h = 400; var score = 0; var snake; var food; var interval; // 鍒濆鍖 function init() { snake = { body: [{x: 40, y: 40}, {x: 30, y: 40}, {x: 20, y: 40}], direction: "right" }; createFood(); } // 鍒涘缓椋熺墿 function createFood() { food = { x: Math.floor(Math.random() * (w / snakeSize)) * snakeSize, y: Math.floor(Math.random() * (h / snakeSize)) * snakeSize }; } // 绉诲姩铔 function moveSnake() { var head = {x: snake.body[0].x, y: snake.body[0].y}; // 鏍规嵁鏂瑰悜鏀瑰彉澶撮儴鍧愭爣 if (snake.direction === "right") { head.x += snakeSize; } else if (snake.direction === "left") { head.x -= snakeSize; } else if (snake.direction === "up") { head.y -= snakeSize; } else if (snake.direction === "down") { head.y += snakeSize; } // 妫娴嬬鎾 if (head.x < 0 || head.x >= w || head.y < 0 || head.y >= h) { gameOver(); return; } for (var i = 0; i < snake.body.length; i++) { if (head.x === snake.body[i].x && head.y === snake.body[i].y) { gameOver(); return; } } // 濡傛灉鍚冨埌椋熺墿 if (head.x === food.x && head.y === food.y) { snake.body.unshift(head); score++; createFood(); } else { snake.body.pop(); snake.body.unshift(head); } // 娓叉煋铔囧拰椋熺墿 ctx.clearRect(0, 0, w,