[ol] 贪吃蛇游戏 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; } 贪吃蛇游戏 [/ol]复制代码JavaScript 代码:[ol]// 定义变量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 = w || head.y = h) { gameOver(); return; } for (var i = 0; i 复制代码 贪吃蛇, 游戏