上一篇
html游戏demo
- 行业动态
- 2025-04-30
- 2
HTML游戏Demo是基于HTML5技术,结合Canvas动画与JS交互,实现点击、碰撞检测等基础游戏逻辑的轻量级网页示例
本案例为一个简单的HTML贪吃蛇游戏Demo,通过HTML、CSS和JavaScript实现基础的游戏逻辑,玩家使用键盘方向键控制蛇的移动,吃掉随机生成的食物后蛇身增长,游戏结束条件为蛇撞到边界或自身。
准备工作
- 工具:任意文本编辑器(如VS Code)、浏览器(建议Chrome或Firefox)。
- 技术栈:HTML(结构)、CSS(样式)、JavaScript(逻辑)。
- 核心功能:
- 蛇的移动与方向控制
- 食物随机生成
- 碰撞检测(边界、自身)
- 得分系统
HTML结构
代码片段 | 功能说明 |
---|---|
<canvas id="gameCanvas" width="400" height="400"></canvas> | 绘制游戏的画布区域 |
<div id="score">Score: 0</div> | 显示当前得分 |
<button id="startBtn">Start Game</button> | 开始游戏按钮 |
CSS样式
代码片段 | 功能说明 |
---|---|
#gameCanvas { border: 1px solid #000; display: block; margin: 20px auto; } | 画布边框与居中显示 |
#score { text-align: center; font-size: 20px; margin-top: 10px; } | 得分文字样式 |
button { margin: 0 auto; display: block; padding: 10px; } | 按钮样式 |
JavaScript逻辑
初始化变量
const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); let snake = [{x: 10, y: 10}]; // 蛇的初始位置 let food = {x: 20, y: 20}; // 食物的初始位置 let direction = 'Right'; // 初始移动方向 let score = 0; let gameInterval;
绘制蛇与食物
function drawSnake() { ctx.fillStyle = 'green'; snake.forEach(segment => { ctx.fillRect(segment.x 20, segment.y 20, 20, 20); }); } function drawFood() { ctx.fillStyle = 'red'; ctx.fillRect(food.x 20, food.y 20, 20, 20); }
键盘事件控制方向
document.addEventListener('keydown', e => { if (e.key === 'ArrowUp' && direction !== 'Down') direction = 'Up'; if (e.key === 'ArrowDown' && direction !== 'Up') direction = 'Down'; if (e.key === 'ArrowLeft' && direction !== 'Right') direction = 'Left'; if (e.key === 'ArrowRight' && direction !== 'Left') direction = 'Right'; });
游戏主循环
function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布 drawSnake(); drawFood(); // 更新蛇头位置 const head = {...snake[0]}; switch (direction) { case 'Up': head.y -= 1; break; case 'Down': head.y += 1; break; case 'Left': head.x -= 1; break; case 'Right': head.x += 1; break; } // 碰撞检测 if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20 || snake.some(segment => segment.x === head.x && segment.y === head.y)) { clearInterval(gameInterval); alert('Game Over!'); return; } // 吃食物逻辑 if (head.x === food.x && head.y === food.y) { score++; document.getElementById('score').textContent = `Score: ${score}`; food = {x: Math.floor(Math.random() 20), y: Math.floor(Math.random() 20)}; } else { snake.pop(); // 未吃到食物时移除尾部 } snake.unshift(head); // 添加新头部 }
启动游戏
document.getElementById('startBtn').addEventListener('click', () => { score = 0; document.getElementById('score').textContent = `Score: ${score}`; snake = [{x: 10, y: 10}]; direction = 'Right'; gameInterval = setInterval(gameLoop, 200); // 每200ms刷新一次 });
测试与优化
- 测试:在浏览器中打开HTML文件,点击“Start Game”按钮,使用键盘方向键控制蛇移动。
- 优化:
- 增加游戏速度随得分提升的逻辑。
- 添加暂停功能。
- 优化碰撞检测算法。
问题与解答
问题1:如何控制蛇的移动方向?
解答:通过监听keydown
事件,根据按键(上下左右箭头)更新direction
变量,需防止蛇直接反向移动(如向右时不能直接向左)。
问题2:食物如何随机生成?
解答:使用Math.random()
生成0到19之间的整数,作为食物的x
和y
坐标,`food.x = Math.floor(Math.random