用html帮我生成一个能在网页上运行的迷宫游戏,要有交互,色彩和功能要多样,动态界面,用键盘控制
- User
用html帮我生成一个能在网页上运行的迷宫游戏,要有交互,色彩和功能要多样,动态界面,用键盘控制
Assistant
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>迷宫游戏</title> <style> body { font-family: 'Arial', sans-serif; background-color: #f0f0f0; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; overflow: hidden; } #game-container { position: relative; margin: 20px; box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); border-radius: 5px; overflow: hidden; } #maze { background-color: #222; position: relative; } .wall { position: absolute; background-color: #3498db; border-radius: 2px; } #player { position: absolute; width: 18px; height: 18px; background-color: #e74c3c; border-radius: 50%; transition: all 0.1s ease; z-index: 10; box-shadow: 0 0 10px rgba(231, 76, 60, 0.7); } #goal { position: absolute; width: 20px; height: 20px; background-color: #2ecc71; border-radius: 50%; animation: pulse 1.5s infinite; z-index: 5; } @keyframes pulse { 0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(46, 204, 113, 0.7); } 70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(46, 204, 113, 0); } 100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(46, 204, 113, 0); } } #game-info { display: flex; justify-content: space-between; width: 100%; margin-bottom: 10px; color: #333; font-weight: bold; } #controls { margin-top: 20px; background-color: #fff; padding: 15px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); text-align: center; max-width: 500px; } button { background-color: #3498db; color: white; border: none; padding: 10px 20px; margin: 5px; border-radius: 5px; cursor: pointer; font-weight: bold; transition: background-color 0.3s; } button:hover { background-color: #2980b9; } #level-select { margin: 10px 0; } #message { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0, 0, 0, 0.8); color: white; padding: 20px 30px; border-radius: 5px; font-size: 24px; z-index: 100; display: none; } #timer, #moves { font-size: 18px; margin: 5px; } .item { position: absolute; width: 15px; height: 15px; border-radius: 50%; z-index: 5; animation: float 2s infinite ease-in-out; } .coin { background-color: gold; box-shadow: 0 0 5px gold; } .key { background-color: #9b59b6; box-shadow: 0 0 5px #9b59b6; } .door { background-color: #8e44ad; box-shadow: 0 0 5px #8e44ad; border-radius: 0; } @keyframes float { 0% { transform: translateY(0px); } 50% { transform: translateY(-5px); } 100% { transform: translateY(0px); } } .trail { position: absolute; width: 6px; height: 6px; background-color: rgba(231, 76, 60, 0.3); border-radius: 50%; z-index: 1; } </style> </head> <body> <div id="game-container"> <div id="game-info"> <div id="timer">时间: 0s</div> <div id="score">得分: 0</div> <div id="moves">移动: 0</div> </div> <canvas id="maze" width="500" height="500"></canvas> <div id="player"></div> <div id="goal"></div> </div> <div id="controls"> <h2>迷宫游戏</h2> <p>使用键盘方向键或WASD移动, 收集金币, 找到钥匙开门, 到达绿色终点。</p> <div id="level-select"> <button onclick="setDifficulty('easy')">简单</button> <button onclick="setDifficulty('medium')">中等</button> <button onclick="setDifficulty('hard')">困难</button> </div> <button onclick="resetGame()">重新开始</button> </div> <div id="message"></div> <script> // 游戏配置 const config = { cellSize: 20, mazeWidth: 25, mazeHeight: 25, difficulty: 'medium', itemCount: { easy: 5, medium: 10, hard: 15 } }; // 游戏状态 let gameState = { playerPosition: { x: 1, y: 1 }, goalPosition: { x: 0, y: 0 }, maze: [], items: [], doors: [], hasKey: false, score: 0, moves: 0, startTime: null, timerInterval: null, gameRunning: false }; // 获取元素 const mazeElement = document.getElementById('maze'); const playerElement = document.getElementById('player'); const goalElement = document.getElementById('goal'); const timerElement = document.getElementById('timer'); const scoreElement = document.getElementById('score'); const movesElement = document.getElementById('moves'); const messageElement = document.getElementById('message'); const ctx = mazeElement.getContext('2d'); // 设置难度 function setDifficulty(level) { config.difficulty = level; switch(level) { case 'easy': config.mazeWidth = 15; config.mazeHeight = 15; break; case 'medium': config.mazeWidth = 25; config.mazeHeight = 25; break; case 'hard': config.mazeWidth = 35; config.mazeHeight = 35; break; } resetGame(); } // 更新游戏大小 function updateGameSize() { const width = config.mazeWidth * config.cellSize; const height = config.mazeHeight * config.cellSize; mazeElement.width = width; mazeElement.height = height; } // 生成迷宫 (使用递归回溯算法) function generateMaze() { // 初始化迷宫,全部为墙 const width = config.mazeWidth; const height = config.mazeHeight; let maze = new Array(height); for (let y = 0; y < height; y++) { maze[y] = new Array(width).fill(1); // 1表示墙 } // 定义递归函数 function carve(x, y) { // 将当前单元格标记为通道 maze[y][x] = 0; // 定义可能的方向: 上、右、下、左 const directions = [ { dx: 0, dy: -2 }, // 上 { dx: 2, dy: 0 }, // 右 { dx: 0, dy: 2 }, // 下 { dx: -2, dy: 0 } // 左 ]; // 随机排序方向 shuffleArray(directions); // 尝试每个方向 for (let dir of directions) { const nx = x + dir.dx; const ny = y + dir.dy; // 检查是否在边界内且是墙 if (nx >= 0 && nx < width && ny >= 0 && ny < height && maze[ny][nx] === 1) { // 打通中间的墙 maze[y + dir.dy / 2][x + dir.dx / 2] = 0; carve(nx, ny); } } } // 从(1,1)开始生成迷宫 carve(1, 1); // 确保入口和出口是通道 maze[1][1] = 0; // 入口 maze[height - 2][width - 2] = 0; // 出口 return maze; } // 辅助函数:随机打乱数组 function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } // 绘制迷宫 function drawMaze() { ctx.clearRect(0, 0, mazeElement.width, mazeElement.height); // 绘制背景 ctx.fillStyle = "#222"; ctx.fillRect(0, 0, mazeElement.width, mazeElement.height); // 绘制墙壁 ctx.fillStyle = "#3498db"; for (let y = 0; y < gameState.maze.length; y++) { for (let x = 0; x < gameState.maze[y].length; x++) { if (gameState.maze[y][x] === 1) { ctx.fillRect( x * config.cellSize, y * config.cellSize, config.cellSize, config.cellSize ); } } } // 绘制道具 gameState.items.forEach(item => { ctx.fillStyle = item.type === 'coin' ? "gold" : "#9b59b6"; ctx.beginPath(); ctx.arc( item.x * config.cellSize + config.cellSize / 2, item.y * config.cellSize + config.cellSize / 2, config.cellSize / 3, 0, Math.PI * 2 ); ctx.fill(); // 绘制光晕效果 ctx.globalAlpha = 0.5; ctx.beginPath(); ctx.arc( item.x * config.cellSize + config.cellSize / 2, item.y * config.cellSize + config.cellSize / 2, config.cellSize / 2, 0, Math.PI * 2 ); ctx.fill(); ctx.globalAlpha = 1.0; }); // 绘制门 gameState.doors.forEach(door => { ctx.fillStyle = "#8e44ad"; ctx.fillRect( door.x * config.cellSize, door.y * config.cellSize, config.cellSize, config.cellSize ); }); } // 放置玩家和目标 function placeElements() { // 放置玩家 gameState.playerPosition = { x: 1, y: 1 }; updatePlayerPosition(); // 放置目标 gameState.goalPosition = { x: config.mazeWidth - 2, y: config.mazeHeight - 2 }; goalElement.style.left = `${gameState.goalPosition.x * config.cellSize}px`; goalElement.style.top = `${gameState.goalPosition.y * config.cellSize}px`; goalElement.style.width = `${config.cellSize}px`; goalElement.style.height = `${config.cellSize}px`; } // 放置游戏道具 function placeItems() { gameState.items = []; gameState.doors = []; gameState.hasKey = false; const itemCount = config.itemCount[config.difficulty]; // 放置金币 for (let i = 0; i < itemCount; i++) { let x, y; do { x = Math.floor(Math.random() * (config.mazeWidth - 2)) + 1; y = Math.floor(Math.random() * (config.mazeHeight - 2)) + 1; } while ( gameState.maze[y][x] !== 0 || (x === 1 && y === 1) || (x === config.mazeWidth - 2 && y === config.mazeHeight - 2) || gameState.items.some(item => item.x === x && item.y === y) ); gameState.items.push({ x: x, y: y, type: 'coin' }); } // 放置钥匙 let kx, ky; do { kx = Math.floor(Math.random() * (config.mazeWidth - 2)) + 1; ky = Math.floor(Math.random() * (config.mazeHeight - 2)) + 1; } while ( gameState.maze[ky][kx] !== 0 || (kx === 1 && ky === 1) || (kx === config.mazeWidth - 2 && ky === config.mazeHeight - 2) || gameState.items.some(item => item.x === kx && item.y === ky) ); gameState.items.push({ x: kx, y: ky, type: 'key' }); // 放置门(在出口附近) const doorX = config.mazeWidth - 3; const doorY = config.mazeHeight - 2; if (gameState.maze[doorY][doorX] === 0) { gameState.doors.push({ x: doorX, y: doorY }); // 将门的位置设为墙 gameState.maze[doorY][doorX] = 2; // 2表示门 } } // 更新玩家位置 function updatePlayerPosition() { playerElement.style.left = `${gameState.playerPosition.x * config.cellSize + 1}px`; playerElement.style.top = `${gameState.playerPosition.y * config.cellSize + 1}px`; playerElement.style.width = `${config.cellSize - 2}px`; playerElement.style.height = `${config.cellSize - 2}px`; // 添加轨迹效果 if (gameState.gameRunning) { const trail = document.createElement('div'); trail.className = 'trail'; trail.style.left = `${gameState.playerPosition.x * config.cellSize + config.cellSize / 2}px`; trail.style.top = `${gameState.playerPosition.y * config.cellSize + config.cellSize / 2}px`; document.getElementById('game-container').appendChild(trail); // 淡出并移除轨迹 setTimeout(() => { trail.style.opacity = '0'; setTimeout(() => { trail.remove(); }, 500); }, 500); } } // 检查碰撞 function checkCollision(x, y) { // 检查是否是墙 if (gameState.maze[y][x] === 1) { return true; } // 检查是否是门 if (gameState.maze[y][x] === 2) { if (gameState.hasKey) { // 有钥匙,打开门 gameState.maze[y][x] = 0; // 移除门的视觉效果 gameState.doors = gameState.doors.filter(door => !(door.x === x && door.y === y)); // 重绘迷宫 drawMaze(); showMessage("门已打开!", 1000); return false; } else { showMessage("需要钥匙才能开门!", 1000); return true; } } return false; } // 检查道具收集 function checkItemCollection() { const px = gameState.playerPosition.x; const py = gameState.playerPosition.y; for (let i = 0; i < gameState.items.length; i++) { const item = gameState.items[i]; if (item.x === px && item.y === py) { // 收集道具 if (item.type === 'coin') { gameState.score += 10; scoreElement.textContent = `得分: ${gameState.score}`; showMessage("+10 分!", 500); } else if (item.type === 'key') { gameState.hasKey = true; showMessage("获得钥匙!", 1000); // 改变玩家颜色以表示有钥匙 playerElement.style.backgroundColor = '#9b59b6'; playerElement.style.boxShadow = '0 0 10px rgba(155, 89, 182, 0.7)'; } // 从数组中移除道具 gameState.items.splice(i, 1); // 重绘迷宫 drawMaze(); break; } } } // 检查是否到达目标 function checkGoal() { const px = gameState.playerPosition.x; const py = gameState.playerPosition.y; if (px === gameState.goalPosition.x && py === gameState.goalPosition.y) { endGame(true); } } // 显示消息 function showMessage(text, duration = 2000) { messageElement.textContent = text; messageElement.style.display = 'block'; setTimeout(() => { messageElement.style.display = 'none'; }, duration); } // 更新计时器 function updateTimer() { if (!gameState.startTime || !gameState.gameRunning) return; const elapsed = Math.floor((Date.now() - gameState.startTime) / 1000); timerElement.textContent = `时间: ${elapsed}s`; } // 开始游戏 function startGame() { gameState.gameRunning = true; gameState.startTime = Date.now(); gameState.timerInterval = setInterval(updateTimer, 1000); } // 结束游戏 function endGame(win = false) { gameState.gameRunning = false; clearInterval(gameState.timerInterval); if (win) { const timeTaken = Math.floor((Date.now() - gameState.startTime) / 1000); const timeBonus = Math.max(0, 300 - timeTaken) * 2; const moveBonus = Math.max(0, 500 - gameState.moves); const totalScore = gameState.score + timeBonus + moveBonus; showMessage(`恭喜!您完成了迷宫!\n总分: ${totalScore}\n时间: ${timeTaken}秒\n移动: ${gameState.moves}步`, 5000); } } // 重置游戏 function resetGame() { // 清除计时器 clearInterval(gameState.timerInterval); // 重置游戏状态 gameState.score = 0; gameState.moves = 0; gameState.hasKey = false; // 更新UI scoreElement.textContent = `得分: 0`; movesElement.textContent = `移动: 0`; timerElement.textContent = `时间: 0s`; // 重置玩家外观 playerElement.style.backgroundColor = '#e74c3c'; playerElement.style.boxShadow = '0 0 10px rgba(231, 76, 60, 0.7)'; // 移除所有轨迹 document.querySelectorAll('.trail').forEach(trail => trail.remove()); // 更新游戏大小 updateGameSize(); // 生成新迷宫 gameState.maze = generateMaze(); // 绘制迷宫 drawMaze(); // 放置玩家和目标 placeElements(); // 放置道具 placeItems(); // 开始游戏 startGame(); } // 键盘控制 document.addEventListener('keydown', (e) => { if (!gameState.gameRunning) return; let newX = gameState.playerPosition.x; let newY = gameState.playerPosition.y; switch (e.key) { case 'ArrowUp': case 'w': case 'W': newY--; break; case 'ArrowRight': case 'd': case 'D': newX++; break; case 'ArrowDown': case 's': case 'S': newY++; break; case 'ArrowLeft': case 'a': case 'A': newX--; break; default: return; // 忽略其他按键 } // 检查碰撞 if (!checkCollision(newX, newY)) { gameState.playerPosition.x = newX; gameState.playerPosition.y = newY; updatePlayerPosition(); gameState.moves++; movesElement.textContent = `移动: ${gameState.moves}`; // 检查道具收集 checkItemCollection(); // 检查是否到达目标 checkGoal(); } }); // 初始化游戏 window.onload = () => { resetGame(); }; </script> </body> </html>你需要解释代码或者对游戏功能有疑问吗?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.