写一个贪吃蛇的 html
- User
写一个贪吃蛇的 html
Assistant
好的,这是一个用 HTML、CSS 和 JavaScript 实现的简单贪吃蛇游戏。
你只需要把下面的代码保存为一个
.html文件,然后用浏览器打开它即可。<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>贪吃蛇</title> <style> body { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background-color: #282c34; font-family: 'Press Start 2P', cursive, Arial, sans-serif; /* 假设有像素字体 */ color: #eee; } h1 { color: #61dafb; margin-bottom: 20px; } .game-container { border: 5px solid #61dafb; border-radius: 8px; overflow: hidden; /* 防止内容超出边界 */ box-shadow: 0 0 20px rgba(97, 218, 251, 0.5); position: relative; /* 用于放置游戏结束提示 */ } canvas { background-color: #3a3f4a; display: block; /* 移除 canvas 下方的空白 */ } .score-panel { display: flex; justify-content: space-between; align-items: center; width: 400px; /* 和 canvas 宽度一致 */ margin-top: 15px; padding: 10px 0; background-color: #4a4f59; border-radius: 5px; font-size: 1.2em; color: #a8a8a8; } .score-panel span { color: #f7b731; font-weight: bold; margin: 0 20px; } button { padding: 10px 20px; font-size: 1.2em; background-color: #4CAF50; color: white; border: none; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; margin-top: 20px; } button:hover { background-color: #45a049; } #gameOverScreen { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.7); color: white; display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 1.5em; text-align: center; z-index: 10; display: none; /* 初始隐藏 */ } #gameOverScreen p { margin: 10px 0; } .instructions { margin-top: 20px; font-size: 0.9em; color: #a8a8a8; text-align: center; } </style> </head> <body> <h1>贪吃蛇</h1> <div class="game-container"> <canvas id="gameCanvas" width="400" height="400"></canvas> <div id="gameOverScreen"> <p>游戏结束!</p> <p id="finalScore"></p> <p>按 "开始游戏" 重新开始</p> </div> </div> <div class="score-panel"> <span>分数: <span id="score">0</span></span> <span>最高分: <span id="highScore">0</span></span> </div> <button id="startButton">开始游戏</button> <div class="instructions"> <p>使用方向键 (↑ ↓ ← →) 控制蛇的移动。</p> <p>吃到食物会变长,撞墙或撞到自己都会游戏结束。</p> </div> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const scoreDisplay = document.getElementById('score'); const highScoreDisplay = document.getElementById('highScore'); const startButton = document.getElementById('startButton'); const gameOverScreen = document.getElementById('gameOverScreen'); const finalScoreDisplay = document.getElementById('finalScore'); const GRID_SIZE = 20; // 每个方块的大小 const CANVAS_WIDTH = canvas.width; const CANVAS_HEIGHT = canvas.height; const GRID_COUNT_X = CANVAS_WIDTH / GRID_SIZE; const GRID_COUNT_Y = CANVAS_HEIGHT / GRID_SIZE; let snake = []; let food = {}; let direction = 'right'; let score = 0; let gameInterval; let gameSpeed = 150; // 游戏速度 (毫秒), 越小越快 let isGameOver = false; let isGameRunning = false; let changingDirection = false; // 防止快速按键导致180度转身 // 从 localStorage 加载最高分 let highScore = localStorage.getItem('snakeHighScore') ? parseInt(localStorage.getItem('snakeHighScore')) : 0; highScoreDisplay.textContent = highScore; function initializeGame() { snake = [ { x: 10 * GRID_SIZE, y: 10 * GRID_SIZE }, // 蛇头 { x: 9 * GRID_SIZE, y: 10 * GRID_SIZE }, { x: 8 * GRID_SIZE, y: 10 * GRID_SIZE } ]; direction = 'right'; score = 0; scoreDisplay.textContent = score; isGameOver = false; changingDirection = false; gameOverScreen.style.display = 'none'; generateFood(); draw(); } function generateFood() { let newFoodX, newFoodY; let collisionWithSnake; do { newFoodX = Math.floor(Math.random() * GRID_COUNT_X) * GRID_SIZE; newFoodY = Math.floor(Math.random() * GRID_COUNT_Y) * GRID_SIZE; collisionWithSnake = false; for (let i = 0; i < snake.length; i++) { if (snake[i].x === newFoodX && snake[i].y === newFoodY) { collisionWithSnake = true; break; } } } while (collisionWithSnake); food = { x: newFoodX, y: newFoodY }; } function drawRect(x, y, color) { ctx.fillStyle = color; ctx.fillRect(x, y, GRID_SIZE, GRID_SIZE); ctx.strokeStyle = '#333'; // 方块边框 ctx.strokeRect(x, y, GRID_SIZE, GRID_SIZE); } function draw() { ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); // 清空画布 // 绘制食物 drawRect(food.x, food.y, '#f7b731'); // 绘制蛇 for (let i = 0; i < snake.length; i++) { drawRect(snake[i].x, snake[i].y, i === 0 ? '#4CAF50' : '#45a049'); // 蛇头绿色,身体深绿色 } } function moveSnake() { if (isGameOver) return; const head = { x: snake[0].x, y: snake[0].y }; switch (direction) { case 'up': head.y -= GRID_SIZE; break; case 'down': head.y += GRID_SIZE; break; case 'left': head.x -= GRID_SIZE; break; case 'right': head.x += GRID_SIZE; break; } // 检查碰撞 if (checkCollision(head)) { endGame(); return; } snake.unshift(head); // 添加新蛇头 // 检查是否吃到食物 if (head.x === food.x && head.y === food.y) { score++; scoreDisplay.textContent = score; generateFood(); // 吃到食物可以稍微加速,但不要太快 // gameSpeed = Math.max(50, gameSpeed - 5); // 最小速度50ms // clearInterval(gameInterval); // gameInterval = setInterval(gameLoop, gameSpeed); } else { snake.pop(); // 没吃到食物就移除蛇尾 } draw(); changingDirection = false; // 允许下次方向改变 } function checkCollision(head) { // 撞墙 if (head.x < 0 || head.x >= CANVAS_WIDTH || head.y < 0 || head.y >= CANVAS_HEIGHT) { return true; } // 撞到自己 for (let i = 1; i < snake.length; i++) { if (head.x === snake[i].x && head.y === snake[i].y) { return true; } } return false; } function endGame() { isGameOver = true; isGameRunning = false; clearInterval(gameInterval); finalScoreDisplay.textContent = `你的分数: ${score}`; gameOverScreen.style.display = 'flex'; // 更新最高分 if (score > highScore) { highScore = score; localStorage.setItem('snakeHighScore', highScore); highScoreDisplay.textContent = highScore; } } function changeDirection(event) { if (changingDirection || !isGameRunning) return; // 游戏未开始或正在改变方向时,不允许操作 const keyPressed = event.keyCode; const LEFT_KEY = 37; const UP_KEY = 38; const RIGHT_KEY = 39; const DOWN_KEY = 40; const goingUp = direction === 'up'; const goingDown = direction === 'down'; const goingLeft = direction === 'left'; const goingRight = direction === 'right'; if (keyPressed === LEFT_KEY && !goingRight) { direction = 'left'; changingDirection = true; } else if (keyPressed === UP_KEY && !goingDown) { direction = 'up'; changingDirection = true; } else if (keyPressed === RIGHT_KEY && !goingLeft) { direction = 'right'; changingDirection = true; } else if (keyPressed === DOWN_KEY && !goingUp) { direction = 'down'; changingDirection = true; } } function startGame() { if (!isGameRunning) { initializeGame(); isGameRunning = true; gameInterval = setInterval(moveSnake, gameSpeed); } } // 事件监听 document.addEventListener('keydown', changeDirection); startButton.addEventListener('click', startGame); // 首次加载页面时绘制初始状态 initializeGame(); // 绘制初始蛇和食物 draw(); // 确保食物和蛇在游戏开始前可见 </script> </body> </html>代码说明:
-
HTML 结构 (
<body>):<h1>: 游戏标题。<div class="game-container">: 包含canvas的容器,用于居中和显示游戏结束 overlay。<canvas id="gameCanvas">: 游戏的绘图区域,所有的蛇、食物等都画在这里。<div id="gameOverScreen">: 游戏结束时显示的半透明覆盖层,初始是隐藏的。<div class="score-panel">: 显示当前分数和最高分。<button id="startButton">: 开始游戏的按钮。<div class="instructions">: 游戏操作说明。
-
CSS 样式 (
<style>):- 设置页面居中,背景色,字体等。
game-container: 添加边框和阴影,让游戏区域更突出。canvas: 设置背景色,并使用display: block移除默认的底部空白。score-panel: 样式化分数显示。button: 样式化开始按钮。#gameOverScreen: 关键部分,使用position: absolute和display: none来实现覆盖层和初始隐藏。当游戏结束时,通过 JavaScript 将display设置为flex来显示。
-
JavaScript 逻辑 (
<script>):- 获取 DOM 元素: 获取
canvas、上下文ctx、分数显示元素、按钮等。 - 常量定义:
GRID_SIZE(每个方块的大小),CANVAS_WIDTH,CANVAS_HEIGHT等,用于计算位置和大小。 - 游戏变量:
snake: 存储蛇身体所有部分的坐标数组,每个部分是一个{x, y}对象。food: 食物的坐标对象。direction: 蛇当前移动的方向('up', 'down', 'left', 'right')。score: 当前分数。gameInterval: 用于控制游戏循环的setInterval句柄。gameSpeed: 游戏更新速度(毫秒),数值越小,蛇移动越快。isGameOver,isGameRunning: 游戏状态标志。changingDirection: 一个防止玩家在极短时间内连续按方向键导致蛇 180 度反转的辅助标志。highScore: 最高分,从localStorage读取和保存。
initializeGame(): 重置所有游戏变量到初始状态,为新游戏做准备。generateFood(): 随机生成食物的位置,确保它不在蛇的身体上。drawRect(x, y, color): 绘制单个方块的辅助函数。draw(): 清空画布并绘制蛇和食物。moveSnake(): 游戏的核心逻辑:- 根据当前
direction计算蛇头的新位置。 checkCollision(): 检查是否撞墙或撞到自己。snake.unshift(head): 将新蛇头添加到蛇数组的开头。- 如果吃到食物:增加分数,生成新食物,蛇身变长(不移除尾部)。
- 如果没吃到食物:
snake.pop()移除蛇尾,保持蛇的长度不变。
- 根据当前
checkCollision(head): 判断蛇头是否与边界或蛇身其他部分碰撞。endGame(): 游戏结束时调用,停止游戏循环,显示“游戏结束”屏幕,并更新最高分。changeDirection(event): 监听键盘事件(方向键),根据按下的键改变蛇的移动方向。它会阻止蛇立即 180 度转向(例如,向右移动时不能立即按左)。startGame(): 开始游戏,设置gameInterval循环调用moveSnake()。- 事件监听器:
document.addEventListener('keydown', changeDirection): 监听键盘输入。startButton.addEventListener('click', startGame): 监听开始按钮点击。
- 最高分 (
localStorage): 使用localStorage在浏览器中保存和读取最高分,即使关闭浏览器也会记住。
- 获取 DOM 元素: 获取
如何使用:
- 将上述所有代码复制粘贴到一个文本编辑器(如记事本、VS Code、Sublime Text)中。
- 将文件保存为
snake_game.html(文件名可以随意,但扩展名必须是.html)。 - 用你的网页浏览器(Chrome, Firefox, Edge 等)打开这个文件。
- 点击 "开始游戏" 按钮,然后使用键盘上的 方向键 (↑ ↓ ← →) 来控制贪吃蛇。
享受游戏吧!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.