可以帮我写一个贪吃蛇游戏的前端页面吗
- User
可以帮我写一个贪吃蛇游戏的前端页面吗
Assistant
当然可以!下面是一个完整的、独立的贪吃蛇游戏前端页面。
你只需要将下面的所有代码复制到一个文件中,将其命名为
snake.html,然后用浏览器(如Chrome, Firefox)打开它,就可以开始玩了。这个实现包含了:
- HTML:用于创建游戏画布和显示分数。
- CSS:用于美化页面,将游戏居中显示。
- JavaScript:实现了所有的游戏逻辑,包括蛇的移动、吃食物、碰撞检测和键盘控制。
贪吃蛇游戏代码 (
snake.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 { background-color: #f0f0f0; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } h1 { color: #333; } #gameCanvas { background-color: #ffffff; border: 2px solid #333; box-shadow: 0 4px 8px rgba(0,0,0,0.1); } #scoreBoard { margin-top: 20px; font-size: 24px; font-weight: bold; color: #555; } #controls { margin-top: 10px; color: #666; } </style> </head> <body> <h1>经典贪吃蛇</h1> <canvas id="gameCanvas" width="400" height="400"></canvas> <div id="scoreBoard">分数: 0</div> <div id="controls">使用方向键 (↑ ↓ ← →) 或 W A S D 键控制</div> <script> // --- 游戏设置 --- const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const scoreBoard = document.getElementById('scoreBoard'); const GRID_SIZE = 20; // 每个格子的尺寸 const CANVAS_WIDTH = canvas.width; const CANVAS_HEIGHT = canvas.height; const SNAKE_COLOR = 'green'; const FOOD_COLOR = 'red'; // --- 游戏状态 --- let 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 } ]; let food = {}; let score = 0; let dx = GRID_SIZE; // 水平速度 let dy = 0; // 垂直速度 let changingDirection = false; // 防止蛇在一次移动中快速反向 let gameOver = false; // --- 主函数 - 游戏循环 --- function main() { if (gameOver) { drawGameOver(); return; } // 使用setTimeout代替setInterval,可以更好地控制帧率 setTimeout(function onTick() { changingDirection = false; clearCanvas(); drawFood(); moveSnake(); drawSnake(); main(); // 递归调用,形成游戏循环 }, 100); // 游戏速度,数字越小越快 } // --- 游戏逻辑函数 --- // 清空画布 function clearCanvas() { ctx.fillStyle = 'white'; ctx.strokeStyle = '#eee'; ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); // 绘制网格线(可选) for (let x = 0; x < CANVAS_WIDTH; x += GRID_SIZE) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, CANVAS_HEIGHT); ctx.stroke(); } for (let y = 0; y < CANVAS_HEIGHT; y += GRID_SIZE) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(CANVAS_WIDTH, y); ctx.stroke(); } } // 绘制蛇的单个部分 function drawSnakePart(snakePart) { ctx.fillStyle = SNAKE_COLOR; ctx.strokeStyle = 'darkgreen'; ctx.fillRect(snakePart.x, snakePart.y, GRID_SIZE, GRID_SIZE); ctx.strokeRect(snakePart.x, snakePart.y, GRID_SIZE, GRID_SIZE); } // 绘制整条蛇 function drawSnake() { snake.forEach(drawSnakePart); } // 移动蛇 function moveSnake() { // 创建新的蛇头 const head = { x: snake[0].x + dx, y: snake[0].y + dy }; // 将新蛇头添加到蛇的数组最前面 snake.unshift(head); // 检查是否吃到食物 const hasEatenFood = snake[0].x === food.x && snake[0].y === food.y; if (hasEatenFood) { score += 10; scoreBoard.textContent = '分数: ' + score; createFood(); // 创建新食物 } else { // 如果没吃到,就移除蛇尾,实现移动效果 snake.pop(); } checkCollision(); } // 碰撞检测 function checkCollision() { // 检查是否撞到自己 for (let i = 4; i < snake.length; i++) { if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) { gameOver = true; return; } } // 检查是否撞墙 const hitLeftWall = snake[0].x < 0; const hitRightWall = snake[0].x > CANVAS_WIDTH - GRID_SIZE; const hitTopWall = snake[0].y < 0; const hitBottomWall = snake[0].y > CANVAS_HEIGHT - GRID_SIZE; if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) { gameOver = true; } } // 在随机位置创建食物 function createFood() { function randomFood(min, max) { return Math.round((Math.random() * (max - min) + min) / GRID_SIZE) * GRID_SIZE; } food.x = randomFood(0, CANVAS_WIDTH - GRID_SIZE); food.y = randomFood(0, CANVAS_HEIGHT - GRID_SIZE); // 确保食物不出现在蛇身上 snake.forEach(function isFoodOnSnake(part) { if (part.x === food.x && part.y === food.y) { createFood(); } }); } // 绘制食物 function drawFood() { ctx.fillStyle = FOOD_COLOR; ctx.strokeStyle = 'darkred'; ctx.fillRect(food.x, food.y, GRID_SIZE, GRID_SIZE); ctx.strokeRect(food.x, food.y, GRID_SIZE, GRID_SIZE); } // 监听键盘事件,改变蛇的方向 function changeDirection(event) { if (changingDirection) return; changingDirection = true; const keyPressed = event.key; const goingUp = dy === -GRID_SIZE; const goingDown = dy === GRID_SIZE; const goingRight = dx === GRID_SIZE; const goingLeft = dx === -GRID_SIZE; // 根据按键和当前方向,改变蛇的移动方向 // 不允许蛇直接反向移动 if ((keyPressed === "ArrowLeft" || keyPressed.toLowerCase() === "a") && !goingRight) { dx = -GRID_SIZE; dy = 0; } if ((keyPressed === "ArrowUp" || keyPressed.toLowerCase() === "w") && !goingDown) { dx = 0; dy = -GRID_SIZE; } if ((keyPressed === "ArrowRight" || keyPressed.toLowerCase() === "d") && !goingLeft) { dx = GRID_SIZE; dy = 0; } if ((keyPressed === "ArrowDown" || keyPressed.toLowerCase() === "s") && !goingUp) { dx = 0; dy = GRID_SIZE; } } // 显示游戏结束画面 function drawGameOver() { ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'; ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); ctx.fillStyle = 'white'; ctx.font = '40px Arial'; ctx.textAlign = 'center'; ctx.fillText('游戏结束', CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2 - 20); ctx.font = '20px Arial'; ctx.fillText('刷新页面重新开始', CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2 + 20); } // --- 启动游戏 --- document.addEventListener('keydown', changeDirection); createFood(); // 第一次创建食物 main(); // 开始游戏循环 </script> </body> </html>如何玩游戏
- 保存文件:将上面的代码完整复制,粘贴到一个新的文本文件中,并将其保存为
snake.html。 - 打开文件:在你的文件管理器中找到
snake.html,双击它,或者右键选择“用浏览器打开”。 - 开始游戏:
- 游戏会自动开始。
- 使用键盘上的 方向键 (↑ ↓ ← →) 或者 W, A, S, D 键来控制蛇的移动方向。
- 你的目标是吃掉红色的方块(食物),每吃一个,蛇的身体就会变长,分数也会增加。
- 注意不要撞到墙壁或自己的身体,否则游戏结束。
- 重新开始:如果游戏结束,刷新页面 (按
F5或Ctrl+R) 即可重新开始。
祝你玩得愉快!
- User
我想让贪吃蛇的样子更加精美一些
Assistant
好的,这是一个非常棒的想法!我们可以通过一些视觉上的改进,让贪吃蛇游戏看起来更现代、更精致。
我将对之前的代码进行以下升级:
- 圆角和渐变:蛇的身体不再是生硬的方块,而是带有圆角和渐变色的平滑块,看起来更有质感。
- 动态眼睛:为蛇头加上眼睛,并且眼睛会根据移动方向“看”,增加趣味性。
- 动态食物:食物不再是静态的红色方块,而是一个会轻微“呼吸”或“脉动”的红色圆点,让它看起来更诱人。
- 更友好的结束画面:游戏结束时提供一个更清晰的提示,并允许按“回车键”直接重新开始,而不是刷新页面。
- 优化的背景:使用更柔和的网格线,让视觉焦点集中在蛇和食物上。
下面是升级后的完整代码。同样,你只需要复制所有代码到一个
snake_deluxe.html文件中,然后用浏览器打开即可。
精美版贪吃蛇代码 (
snake_deluxe.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 { background-color: #2c3e50; /* 深色背景 */ display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #ecf0f1; } h1 { color: #ecf0f1; text-shadow: 2px 2px 4px rgba(0,0,0,0.2); } #gameCanvas { background-color: #34495e; /* 稍亮的画布背景 */ border: 2px solid #ecf0f1; box-shadow: 0 10px 20px rgba(0,0,0,0.3); border-radius: 8px; /* 画布圆角 */ } #scoreBoard { margin-top: 20px; font-size: 24px; font-weight: bold; } #controls { margin-top: 10px; color: #bdc3c7; } </style> </head> <body> <h1>精美版贪吃蛇</h1> <canvas id="gameCanvas" width="400" height="400"></canvas> <div id="scoreBoard">分数: 0</div> <div id="controls">使用方向键 (↑ ↓ ← →) 或 W A S D 键控制</div> <script> // --- 游戏设置 --- const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const scoreBoard = document.getElementById('scoreBoard'); const GRID_SIZE = 20; const CANVAS_WIDTH = canvas.width; const CANVAS_HEIGHT = canvas.height; const SNAKE_BODY_COLOR = '#2ecc71'; const SNAKE_HEAD_COLOR = '#27ae60'; const FOOD_COLOR = '#e74c3c'; // --- 游戏状态 --- let snake; let food; let score; let dx; let dy; let changingDirection; let gameOver; let frameCount = 0; // 新增:用于动画计数 // --- 初始化游戏状态函数 --- function initGame() { 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 } ]; score = 0; dx = GRID_SIZE; dy = 0; changingDirection = false; gameOver = false; scoreBoard.textContent = '分数: ' + score; createFood(); } // --- 主函数 - 游戏循环 --- function main() { if (gameOver) { drawGameOver(); return; } setTimeout(function onTick() { frameCount++; changingDirection = false; clearCanvas(); drawFood(); moveSnake(); drawSnake(); main(); }, 100); } // --- 绘图函数 --- // 清空画布并绘制柔和网格 function clearCanvas() { ctx.fillStyle = '#34495e'; ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); ctx.strokeStyle = 'rgba(236, 240, 241, 0.1)'; // 淡化网格线 for (let x = 0; x < CANVAS_WIDTH; x += GRID_SIZE) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, CANVAS_HEIGHT); ctx.stroke(); } for (let y = 0; y < CANVAS_HEIGHT; y += GRID_SIZE) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(CANVAS_WIDTH, y); ctx.stroke(); } } // 新增:绘制带圆角的矩形 (我们的核心美化工具) function drawRoundRect(x, y, width, height, radius, color) { ctx.fillStyle = color; ctx.beginPath(); ctx.moveTo(x + radius, y); ctx.lineTo(x + width - radius, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius); ctx.lineTo(x + width, y + height - radius); ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); ctx.lineTo(x + radius, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - radius); ctx.lineTo(x, y + radius); ctx.quadraticCurveTo(x, y, x + radius, y); ctx.closePath(); ctx.fill(); } // 绘制整条蛇 function drawSnake() { // 绘制蛇身体 for (let i = 1; i < snake.length; i++) { const part = snake[i]; // 创建渐变效果 const gradient = ctx.createLinearGradient(part.x, part.y, part.x + GRID_SIZE, part.y + GRID_SIZE); gradient.addColorStop(0, SNAKE_BODY_COLOR); gradient.addColorStop(1, SNAKE_HEAD_COLOR); // 渐变到头部颜色,更融合 drawRoundRect(part.x, part.y, GRID_SIZE, GRID_SIZE, 5, gradient); } // 单独绘制蛇头 const head = snake[0]; drawRoundRect(head.x, head.y, GRID_SIZE, GRID_SIZE, 7, SNAKE_HEAD_COLOR); // 绘制眼睛 drawEyes(head); } // 新增:绘制眼睛 function drawEyes(head) { const eyeRadius = 3; const pupilRadius = 1.5; let eye1_x, eye1_y, eye2_x, eye2_y; // 根据方向确定眼睛位置 if (dx > 0) { // 向右 eye1_x = head.x + GRID_SIZE * 0.7; eye1_y = head.y + GRID_SIZE * 0.3; eye2_x = head.x + GRID_SIZE * 0.7; eye2_y = head.y + GRID_SIZE * 0.7; } else if (dx < 0) { // 向左 eye1_x = head.x + GRID_SIZE * 0.3; eye1_y = head.y + GRID_SIZE * 0.3; eye2_x = head.x + GRID_SIZE * 0.3; eye2_y = head.y + GRID_SIZE * 0.7; } else if (dy > 0) { // 向下 eye1_x = head.x + GRID_SIZE * 0.3; eye1_y = head.y + GRID_SIZE * 0.7; eye2_x = head.x + GRID_SIZE * 0.7; eye2_y = head.y + GRID_SIZE * 0.7; } else { // 向上 eye1_x = head.x + GRID_SIZE * 0.3; eye1_y = head.y + GRID_SIZE * 0.3; eye2_x = head.x + GRID_SIZE * 0.7; eye2_y = head.y + GRID_SIZE * 0.3; } // 绘制眼白 ctx.fillStyle = 'white'; ctx.beginPath(); ctx.arc(eye1_x, eye1_y, eyeRadius, 0, 2 * Math.PI); ctx.arc(eye2_x, eye2_y, eyeRadius, 0, 2 * Math.PI); ctx.fill(); // 绘制瞳孔 ctx.fillStyle = 'black'; ctx.beginPath(); ctx.arc(eye1_x, eye1_y, pupilRadius, 0, 2 * Math.PI); ctx.arc(eye2_x, eye2_y, pupilRadius, 0, 2 * Math.PI); ctx.fill(); } // 绘制脉动的食物 function drawFood() { const pulse = Math.abs(Math.sin(frameCount * 0.1)) * 2; // 计算脉动幅度 const foodRadius = GRID_SIZE / 2 - 2 + pulse; ctx.fillStyle = FOOD_COLOR; ctx.shadowColor = 'rgba(231, 76, 60, 0.7)'; // 添加发光效果 ctx.shadowBlur = 15; ctx.beginPath(); ctx.arc(food.x + GRID_SIZE / 2, food.y + GRID_SIZE / 2, foodRadius, 0, 2 * Math.PI); ctx.fill(); // 重置阴影,避免影响其他绘制 ctx.shadowBlur = 0; } // --- 游戏逻辑 --- function moveSnake() { const head = { x: snake[0].x + dx, y: snake[0].y + dy }; snake.unshift(head); if (snake[0].x === food.x && snake[0].y === food.y) { score += 10; scoreBoard.textContent = '分数: ' + score; createFood(); } else { snake.pop(); } checkCollision(); } function checkCollision() { for (let i = 4; i < snake.length; i++) { if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) { gameOver = true; return; } } const hitLeftWall = snake[0].x < 0; const hitRightWall = snake[0].x > CANVAS_WIDTH - GRID_SIZE; const hitTopWall = snake[0].y < 0; const hitBottomWall = snake[0].y > CANVAS_HEIGHT - GRID_SIZE; if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) { gameOver = true; } } function createFood() { function randomFoodPos(min, max) { return Math.round((Math.random() * (max - min) + min) / GRID_SIZE) * GRID_SIZE; } food = { x: randomFoodPos(0, CANVAS_WIDTH - GRID_SIZE), y: randomFoodPos(0, CANVAS_HEIGHT - GRID_SIZE) }; snake.forEach(part => { if (part.x === food.x && part.y === food.y) createFood(); }); } function changeDirection(event) { // 新增:游戏结束后按回车重新开始 if (gameOver && event.key === 'Enter') { initGame(); main(); return; } if (changingDirection) return; changingDirection = true; const keyPressed = event.key; const goingUp = dy === -GRID_SIZE, goingDown = dy === GRID_SIZE; const goingRight = dx === GRID_SIZE, goingLeft = dx === -GRID_SIZE; if ((keyPressed === "ArrowLeft" || keyPressed.toLowerCase() === "a") && !goingRight) { dx = -GRID_SIZE; dy = 0; } if ((keyPressed === "ArrowUp" || keyPressed.toLowerCase() === "w") && !goingDown) { dx = 0; dy = -GRID_SIZE; } if ((keyPressed === "ArrowRight" || keyPressed.toLowerCase() === "d") && !goingLeft) { dx = GRID_SIZE; dy = 0; } if ((keyPressed === "ArrowDown" || keyPressed.toLowerCase() === "s") && !goingUp) { dx = 0; dy = GRID_SIZE; } } // 升级版游戏结束画面 function drawGameOver() { ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'; ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); ctx.fillStyle = 'white'; ctx.font = 'bold 40px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('游戏结束', CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2 - 40); ctx.font = '24px Arial'; ctx.fillText(`最终得分: ${score}`, CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2); ctx.font = '18px Arial'; ctx.fillText('按 [Enter] 键重新开始', CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2 + 40); } // --- 启动游戏 --- document.addEventListener('keydown', changeDirection); initGame(); // 使用初始化函数 main(); // 开始游戏循环 </script> </body> </html>主要改动亮点:
drawRoundRect()函数:这是实现圆角效果的核心,一个非常实用的 Canvas 绘图函数。drawSnake()的重构:现在它会区分蛇头和身体,并为身体部分应用了漂亮的线性渐变。drawEyes()函数:通过判断蛇的移动方向 (dx,dy),智能地调整眼睛和瞳孔的位置,让蛇“活”了起来。drawFood()的升级:利用frameCount和Math.sin()创建了一个平滑的脉动效果,同时用shadowBlur属性给食物加上了光晕,使其更醒目。initGame()和Enter重启:将游戏初始化逻辑封装成一个函数,使得重置游戏状态变得非常简单。现在游戏结束后,只需按一下回车键,就能无缝开始新的一局。- CSS 美化:整体页面采用了深色主题,让游戏画面更突出,视觉上更舒适。
现在打开这个新版本的游戏看看吧,相信你会喜欢这个更精致、更有趣的贪吃蛇!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.