当前位置: 首页 > news >正文

贪吃蛇游戏(纯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 {margin: 0;padding: 20px;font-family: 'Arial', sans-serif;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);min-height: 100vh;display: flex;align-items: center;justify-content: center;}.game-container {background: rgba(255, 255, 255, 0.1);backdrop-filter: blur(10px);border-radius: 20px;padding: 25px;box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);border: 1px solid rgba(255, 255, 255, 0.2);text-align: center;max-width: 900px;width: 100%;}.game-title {color: white;font-size: 2.8em;margin-bottom: 15px;text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1);-webkit-background-clip: text;-webkit-text-fill-color: transparent;background-clip: text;}.game-header {display: flex;justify-content: space-between;align-items: center;margin-bottom: 20px;flex-wrap: wrap;gap: 15px;}.game-info {display: flex;gap: 20px;background: rgba(0, 0, 0, 0.2);padding: 12px 20px;border-radius: 15px;color: white;font-weight: bold;font-size: 1.1em;}.info-item {display: flex;align-items: center;gap: 5px;}.grid-container {display: flex;justify-content: center;margin: 20px 0;}.grid {display: grid;grid-template-columns: repeat(20, 25px);grid-template-rows: repeat(15, 25px);gap: 1px;background-color: rgba(0, 0, 0, 0.3);border-radius: 10px;padding: 15px;box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);}.cell {width: 25px;height: 25px;display: flex;align-items: center;justify-content: center;font-size: 14px;border-radius: 4px;background-color: rgba(0, 0, 0, 0.2);transition: all 0.1s ease;}.snake-head {background: linear-gradient(135deg, #4ade80, #22c55e);color: white;font-weight: bold;box-shadow: 0 0 10px rgba(74, 222, 128, 0.5);}.snake-body {background: linear-gradient(135deg, #22c55e, #16a34a);color: white;}.food {background: linear-gradient(135deg, #ef4444, #dc2626);color: white;animation: pulse 1s infinite;}.power-up {background: linear-gradient(135deg, #f59e0b, #d97706);color: white;animation: spin 2s infinite linear;}.special-food {background: linear-gradient(135deg, #fbbf24, #f59e0b);color: white;animation: bounce 1s infinite;}@keyframes pulse {0%, 100% { transform: scale(1); }50% { transform: scale(1.1); }}@keyframes spin {from { transform: rotate(0deg); }to { transform: rotate(360deg); }}@keyframes bounce {0%, 100% { transform: translateY(0); }50% { transform: translateY(-5px); }}.controls {margin: 25px 0;display: flex;justify-content: center;gap: 15px;flex-wrap: wrap;}button {padding: 12px 25px;border: none;border-radius: 25px;background: rgba(255, 255, 255, 0.2);color: white;font-weight: bold;cursor: pointer;transition: all 0.3s;backdrop-filter: blur(5px);box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);font-size: 1em;}button:hover {background: rgba(255, 255, 255, 0.3);transform: translateY(-2px);}.instructions {color: white;margin: 20px 0;font-size: 0.95em;line-height: 1.6;background: rgba(0, 0, 0, 0.2);padding: 20px;border-radius: 15px;}.rules-section {margin: 15px 0;}.rules-section h3 {margin-top: 0;margin-bottom: 10px;color: #4ecdc4;}.power-ups-list, .special-foods-list {display: flex;justify-content: center;gap: 15px;margin: 10px 0;flex-wrap: wrap;}.item {display: flex;align-items: center;gap: 5px;background: rgba(255, 255, 255, 0.1);padding: 8px 15px;border-radius: 20px;font-size: 0.85em;}.game-over {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);background: rgba(0, 0, 0, 0.9);color: white;padding: 40px;border-radius: 20px;text-align: center;z-index: 1000;box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);max-width: 400px;width: 90%;}.pause-screen {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);background: rgba(0, 0, 0, 0.8);color: white;padding: 40px;border-radius: 20px;text-align: center;z-index: 1000;}.combo-display {background: rgba(255, 215, 0, 0.3);color: gold;padding: 8px 15px;border-radius: 20px;font-weight: bold;margin: 5px 0;animation: glow 0.5s infinite alternate;}@keyframes glow {from { box-shadow: 0 0 5px gold; }to { box-shadow: 0 0 20px gold; }}.active-power {animation: pulse 0.5s infinite;}@media (max-width: 768px) {.game-container {padding: 15px;}.game-title {font-size: 2em;}.game-info {flex-direction: column;gap: 10px;}.grid {grid-template-columns: repeat(20, 20px);grid-template-rows: repeat(15, 20px);padding: 10px;}.cell {width: 20px;height: 20px;font-size: 12px;}.controls {flex-direction: column;align-items: center;}button {width: 100%;max-width: 200px;}}</style>
</head>
<body><div class="game-container"><h1 class="game-title">🎮 离谱贪吃蛇 🎮</h1><div class="game-header"><div class="game-info"><div class="info-item"><span>🏆</span><span>分数: <span id="score">0</span></span></div><div class="info-item"><span>❤️</span><span>生命: <span id="lives">3</span></span></div><div class="info-item"><span></span><span>等级: <span id="level">1</span></span></div><div class="info-item"><span>🔥</span><span>连击: <span id="combo" class="combo-display">0</span></span></div></div></div><div class="grid-container"><div id="game-grid" class="grid"></div></div><div class="controls"><button id="start-btn">▶️ 开始游戏</button><button id="pause-btn">⏸️ 暂停</button><button id="reset-btn">🔄 重置游戏</button></div><div class="instructions"><div class="rules-section"><h3>🎮 游戏规则:</h3><p>🎯 目标:吃到食物获得分数,避开自身碰撞</p><p>⚡ 特殊道具:⚡❄️🌱🔻🌀✨ - 每个都有独特效果</p><p>🌟 特殊食物:⭐❤️💎☁️ - 获得额外奖励</p><p>💥 连击系统:连续吃到5个食物获得额外50分奖励!</p></div><div class="rules-section"><h3>⚡ 道具效果:</h3><div class="power-ups-list"><div class="item">⚡ 速度加速 (5秒) - 快速移动</div><div class="item">❄️ 减速道具 - 慢速移动</div><div class="item">🌱 增长道具 - 蛇身增长</div><div class="item">🔻 缩小道具 - 蛇身缩短</div><div class="item">🌀 传送道具 - 随机传送</div><div class="item">✨ 无敌道具 - 5秒无敌</div></div></div><div class="rules-section"><h3>🌟 特殊食物效果:</h3><div class="special-foods-list"><div class="item">⭐ 超级星星 (+50分) - 大量分数</div><div class="item">❤️ 爱心生命 (+1生命) - 生命恢复</div><div class="item">💎 钻石宝石 (+50分) - 高分奖励</div><div class="item">☁️ 云朵祝福 (+50分) - 额外分数</div></div></div><div class="rules-section"><h3>🎮 操作说明:</h3><p>🎮 方向键控制方向 | ⚡ 空格键暂停 | 🔄 R键重置</p></div></div></div><script>// 游戏变量let snake = [{x: 10, y: 10}];let direction = {x: 0, y: -1};let food = {x: 15, y: 15};let powerUps = [];let specialFoods = [];let gameRunning = false;let gameOver = false;let score = 0;let level = 1;let lives = 3;let activePowerUps = [];let gameSpeed = 150;let gameLoop;let combo = 0;let isPaused = false;let invincible = false;// DOM元素const gameGrid = document.getElementById('game-grid');const scoreElement = document.getElementById('score');const livesElement = document.getElementById('lives');const levelElement = document.getElementById('level');const comboElement = document.getElementById('combo');const startBtn = document.getElementById('start-btn');const pauseBtn = document.getElementById('pause-btn');const resetBtn = document.getElementById('reset-btn');// 生成随机位置function generateRandomPosition() {return {x: Math.floor(Math.random() * 20),y: Math.floor(Math.random() * 15)};}// 检查碰撞function checkCollision(head, snakeBody) {if (invincible) return false;return snakeBody.slice(1).some(segment => segment.x === head.x && segment.y === head.y);}// 生成食物function generateFood() {let newFood;let valid = false;while (!valid) {newFood = generateRandomPosition();valid = !snake.some(segment => segment.x === newFood.x && segment.y === newFood.y) &&!powerUps.some(power => power.x === newFood.x && power.y === newFood.y) &&!specialFoods.some(food => food.x === newFood.x && food.y === newFood.y);}return newFood;}// 生成道具function generatePowerUp() {const types = ['speed', 'slow', 'grow', 'shrink', 'teleport', 'invincible'];const type = types[Math.floor(Math.random() * types.length)];return {...generateRandomPosition(),type: type,id: Date.now() + Math.random()};}// 生成特殊食物function generateSpecialFood() {const types = ['star', 'heart', 'diamond', 'cloud'];const type = types[Math.floor(Math.random() * types.length)];return {...generateRandomPosition(),type: type,id: Date.now() + Math.random()};}// 渲染游戏网格function renderGrid() {gameGrid.innerHTML = '';for (let y = 0; y < 15; y++) {for (let x = 0; x < 20; x++) {const cell = document.createElement('div');cell.className = 'cell';const isSnakeHead = snake[0].x === x && snake[0].y === y;const isSnakeBody = snake.slice(1).some(segment => segment.x === x && segment.y === y);const isFood = food.x === x && food.y === y;const isPowerUp = powerUps.some(power => power.x === x && power.y === y);const isSpecialFood = specialFoods.some(food => food.x === x && food.y === y);if (isSnakeHead) {cell.classList.add('snake-head');cell.textContent = '🐍';} else if (isSnakeBody) {cell.classList.add('snake-body');cell.textContent = '🟢';} else if (isFood) {cell.classList.add('food');cell.textContent = '🍎';} else if (isPowerUp) {cell.classList.add('power-up');const icons = {'speed': '⚡', 'slow': '❄️', 'grow': '🌱', 'shrink': '🔻', 'teleport': '🌀', 'invincible': '✨'};cell.textContent = icons[powerUps.find(p => p.x === x && p.y === y).type];} else if (isSpecialFood) {cell.classList.add('special-food');const icons = {'star': '⭐', 'heart': '❤️', 'diamond': '💎', 'cloud': '☁️'};cell.textContent = icons[specialFoods.find(f => f.x === x && f.y === y).type];}gameGrid.appendChild(cell);}}}// 更新游戏状态function updateGame() {if (!gameRunning || gameOver || isPaused) return;// 移动蛇const newSnake = [...snake];const head = {...newSnake[0]};head.x += direction.x;head.y += direction.y;// 边界处理(可穿越)if (head.x < 0) head.x = 19;if (head.x > 19) head.x = 0;if (head.y < 0) head.y = 14;if (head.y > 14) head.y = 0;// 检查碰撞if (checkCollision(head, newSnake)) {lives--;livesElement.textContent = lives;if (lives <= 0) {gameOver = true;gameRunning = false;showGameOver();return;}// 重置蛇的位置snake = [{x: 10, y: 10}];direction = {x: 0, y: -1};invincible = false;return;}newSnake.unshift(head);// 检查是否吃到食物if (head.x === food.x && head.y === food.y) {score += 10;combo++;comboElement.textContent = combo;scoreElement.textContent = score;if (combo >= 5) {score += 50;scoreElement.textContent = score;combo = 0;comboElement.textContent = combo;comboElement.style.animation = 'glow 0.5s infinite alternate';setTimeout(() => comboElement.style.animation = '', 2000);}food = generateFood();} else {newSnake.pop();}// 检查是否吃到道具powerUps = powerUps.filter(power => {if (power.x === head.x && power.y === head.y) {// 应用道具效果switch (power.type) {case 'speed':gameSpeed = 100;setTimeout(() => gameSpeed = 150, 5000);break;case 'grow':newSnake.push(...Array(2).fill().map(() => ({...newSnake[newSnake.length - 1]})));break;case 'shrink':if (newSnake.length > 3) {newSnake.splice(-2, 2);}break;case 'teleport':const teleportPos = generateRandomPosition();head.x = teleportPos.x;head.y = teleportPos.y;break;case 'invincible':invincible = true;setTimeout(() => invincible = false, 3000);break;}return false; // 移除道具}return true;});// 检查是否吃到特殊食物specialFoods = specialFoods.filter(foodItem => {if (foodItem.x === head.x && foodItem.y === head.y) {switch (foodItem.type) {case 'star':score += 50;scoreElement.textContent = score;break;case 'heart':lives++;livesElement.textContent = lives;break;case 'diamond':score += 50;scoreElement.textContent = score;break;case 'cloud':score += 50;scoreElement.textContent = score;break;}return false; // 移除食物}return true;});snake = newSnake;// 随机生成道具和特殊食物if (Math.random() < 0.02) {powerUps.push(generatePowerUp());}if (Math.random() < 0.01) {specialFoods.push(generateSpecialFood());}renderGrid();}// 显示游戏结束function showGameOver() {const gameOverDiv = document.createElement('div');gameOverDiv.className = 'game-over';gameOverDiv.innerHTML = `<h2>🎮 游戏结束! 🎮</h2><p>最终得分: ${score}</p><p>最高连击: ${Math.max(combo, 5)}</p><button onclick="this.parentElement.remove(); resetGame()" style="margin-top: 15px; padding: 12px 25px; background: #ff6b6b; border: none; border-radius: 25px; color: white; font-weight: bold; cursor: pointer;">再玩一次!</button>`;document.body.appendChild(gameOverDiv);}// 显示暂停界面function showPauseScreen() {const pauseDiv = document.createElement('div');pauseDiv.className = 'pause-screen';pauseDiv.innerHTML = `<h2>⏸️ 暂停中 ⏸️</h2><p>按空格键继续游戏</p>`;document.body.appendChild(pauseDiv);return pauseDiv;}// 开始游戏function startGame() {if (gameRunning) return;gameRunning = true;gameOver = false;isPaused = false;score = 0;lives = 3;level = 1;combo = 0;snake = [{x: 10, y: 10}];direction = {x: 0, y: -1};food = generateFood();powerUps = [];specialFoods = [];gameSpeed = 150;invincible = false;scoreElement.textContent = score;livesElement.textContent = lives;levelElement.textContent = level;comboElement.textContent = combo;renderGrid();if (gameLoop) clearInterval(gameLoop);gameLoop = setInterval(updateGame, gameSpeed);}// 暂停游戏function togglePause() {if (!gameRunning || gameOver) return;isPaused = !isPaused;pauseBtn.textContent = isPaused ? '▶️ 继续' : '⏸️ 暂停';if (isPaused) {showPauseScreen();} else {const pauseDiv = document.querySelector('.pause-screen');if (pauseDiv) pauseDiv.remove();}}// 重置游戏function resetGame() {if (gameLoop) clearInterval(gameLoop);gameRunning = false;gameOver = false;isPaused = false;const pauseDiv = document.querySelector('.pause-screen');if (pauseDiv) pauseDiv.remove();startGame();}// 键盘控制document.addEventListener('keydown', (e) => {if (!gameRunning || gameOver) return;switch (e.key) {case 'ArrowUp':if (direction.y === 0) direction = {x: 0, y: -1};break;case 'ArrowDown':if (direction.y === 0) direction = {x: 0, y: 1};break;case 'ArrowLeft':if (direction.x === 0) direction = {x: -1, y: 0};break;case 'ArrowRight':if (direction.x === 0) direction = {x: 1, y: 0};break;case ' ':togglePause();break;}});// 按钮事件startBtn.addEventListener('click', startGame);pauseBtn.addEventListener('click', togglePause);resetBtn.addEventListener('click', resetGame);// 初始化游戏renderGrid();</script>
</body>
</html>
http://www.dtcms.com/a/342791.html

相关文章:

  • 服务发现与负载均衡:Kubernetes Service核心机制深度解析
  • Vue数据的变更操作与表单数据的收集【6】
  • 动漫短剧小程序系统开发|动漫短剧小程序搭建|动漫短剧源码交付
  • 后浪来袭:NIST 轻量级密码标准化决赛圈算法剖析(ASCON、SPARKLE 等)
  • AI翻唱实战:用[灵龙AI API]玩转AI翻唱 – 第6篇
  • RocketMQ 消息消费 单个消费和批量消费配置实现对比(Springboot),完整实现示例对比
  • TCP连接
  • 华为开发者空间训练营-优秀作品公布
  • PyTorch深度学习遥感影像地物分类与目标检测、分割及遥感影像问题深度学习优化——CNN原理、Faster RCNN/YOLO检测到U-Net分割等
  • 13、按键输入检测
  • ES_索引模板
  • flutter_rust_bridge的前世今生
  • Mysql InnoDB 底层架构设计、功能、原理、源码系列合集【一、InnoDB 架构先导。主讲模块划分,各模块功能、源码位置、关键结构体/函数】
  • 无人机长距离高速传输技术解析
  • cuda之sass分析
  • 机器人组装MES系统:破解行业痛点,打造数字化智能工厂
  • 对象存储解决方案:MinIO 的架构与代码实战
  • week3-[字符数组]元音
  • 电脑芯片其实更偏向MPU不是CPU,GPU CPU NPU MPU MCU的区别
  • 电商项目_微服务_架构
  • Shader开发(十六)UV 坐标介绍
  • 【python】windows下使用pyenv+uv进行python版本及环境变量管理
  • K 均值聚类(K-Means)演示,通过生成笑脸和爱心两种形状的模拟数据,展示了无监督学习中聚类算法的效果。以下是详细讲解:
  • 微服务02-Spring Cloud入门:构建微服务生态系统
  • 灵活使用UE5 Modeling中的UV编辑功能
  • RabbitMQ死信队列、延时队列分别是什么
  • 常德二院全栈国产化信创项目:开启医疗新质生产力的“头雁”之旅
  • 【STM32】HAL库中的实现(九):SPI(串行外设接口)
  • 如何在阿里云OSS之间进行数据迁移呢?
  • Pytorch安装详细步骤