
本教程将指导您如何在javascript游戏中优雅地展示高分榜,避免直接在游戏区域内显示导致布局混乱。通过利用css的`display`属性和javascript动态控制元素可见性,我们可以在游戏结束后,平滑地将游戏界面切换为独立的高分榜页面,从而提供更清晰、专业的用户体验,无需页面刷新。
在开发基于javaScript的休闲游戏,例如Doodle Jump这类项目时,游戏结束后通常需要展示玩家的得分,并与历史高分进行比较。直接在游戏区域内叠加显示高分榜,往往会导致界面拥挤、信息混乱,影响用户体验。本文将介绍一种简洁有效的方法,通过css和javascript的配合,实现高分榜的“页面级”独立展示效果,让玩家在游戏结束后能在一个清晰的界面上查看自己的成就。
核心思路:利用CSS display 属性切换视图
实现这种“页面切换”效果的关键在于利用CSS的display属性。我们可以创建两个主要的html容器:一个用于承载游戏界面(例如您的.grid),另一个用于承载高分榜。在游戏进行时,高分榜容器设置为隐藏(display: none;);当游戏结束需要显示高分榜时,通过JavaScript将游戏容器设置为隐藏,同时将高分榜容器设置为显示(display: block;或其他适合的布局值)。这种方法无需重新加载页面,即可实现视图的平滑切换。
HTML结构调整
为了更好地管理高分榜的显示,建议将高分榜列表
包裹在一个独立的容器div中。同时,我们可以确保游戏区域和高分榜区域是同级元素,便于独立控制它们的可见性。
<!-- 高分榜容器,初始隐藏 --> <div class="high-scores-container"> <h2>高分榜</h2> <ol id="highScores"></ol> <button id="restartGame">重新开始</button> <!-- 可选:添加重新开始按钮 --> </div> <!-- 游戏区域,初始显示 --> <div class="grid"> <!-- 游戏内容,如doodler、平台等 --> <div class="volumeIcon"></div> </div>
在这个结构中,.high-scores-container将包含高分榜的标题、列表以及可能的交互按钮。.grid则继续作为游戏的主舞台。
立即学习“Java免费学习笔记(深入)”;
css样式定义
接下来,我们需要为这两个容器定义初始样式。关键是让高分榜容器在默认情况下是隐藏的,并且当它显示时,能够占据与游戏区域类似的空间,提供一个清晰的背景。
/* 游戏区域的现有样式 */ .grid { width: 400px; height: 600px; background-color: yellow; position: relative; font-size: 200px; text-align: center; background-image: url(bluesky_level1.gif); background-size: contain; background-repeat: no-repeat; background-size: 400px 600px; margin-right: auto; margin-left: auto; } /* 高分榜容器样式 */ .high-scores-container { display: none; /* 初始状态:隐藏 */ width: 400px; /* 与游戏区域宽度一致 */ height: 600px; /* 与游戏区域高度一致 */ margin-right: auto; /* 居中 */ margin-left: auto; /* 居中 */ background-color: #f0f8ff; /* 浅蓝色背景,与游戏区分 */ color: #333; font-family: "Georgia", "Times New Roman", serif; text-align: center; padding-top: 50px; /* 顶部留白 */ box-sizing: border-box; /* 确保padding包含在宽高内 */ /* 如果需要与grid重叠,可以设置position: absolute; top: 0; left: 0; */ /* 但更推荐让它们并排或通过flex/grid布局来切换 */ } .high-scores-container h2 { font-size: 40px; margin-bottom: 30px; color: #0056b3; } #highScores { list-style: none; /* 移除默认列表点 */ padding: 0; font-size: 24px; line-height: 1.6; max-height: 350px; /* 限制列表高度,防止溢出 */ overflow-y: auto; /* 列表过长时显示滚动条 */ margin-top: 20px; } #highScores li { margin-bottom: 10px; padding: 5px 0; background-color: #e6f2ff; border-radius: 5px; margin: 5px auto; width: 80%; } #restartGame { margin-top: 30px; padding: 10px 20px; font-size: 18px; cursor: pointer; background-color: #28a745; color: white; border: none; border-radius: 5px; transition: background-color 0.3s ease; } #restartGame:hover { background-color: #218838; }
这里我们为.high-scores-container设置了与.grid相同的尺寸和居中方式,并添加了更友好的背景色和字体样式。display: none;是其初始隐藏的关键。
JavaScript逻辑实现
现在,我们需要修改JavaScript代码,以便在游戏结束时执行视图切换逻辑。
- 获取dom元素引用: 在脚本开始时,获取grid和high-scores-container的DOM引用。
- 修改 gameOver() 函数: 在游戏结束逻辑中,清除游戏元素后,将grid的display样式设置为’none’,同时将high-scores-container的display样式设置为’block’。
- 完善 showHighScores() 函数: 确保此函数在更新高分榜内容后,高分榜容器是可见的。
- 添加“重新开始”功能(可选): 为高分榜页面的“重新开始”按钮添加事件监听器,以便玩家可以快速开始新游戏。
document.addEventListener('DOMContentLoaded', () => { const grid = document.querySelector('.grid'); const doodler = document.createElement('div'); // ... 其他游戏变量 ... const highScoresContainer = document.querySelector('.high-scores-container'); // 获取高分榜容器 const restartButton = document.getElementById('restartGame'); // 获取重新开始按钮 // ... 现有游戏逻辑(createDoodler, control, Platform类等) ... function gameOver() { console.log('GAME OVER'); isGameOver = true; // 清理游戏区域的子元素 while (grid.firstChild) { grid.removeChild(grid.firstChild); } // 清除所有定时器,停止游戏循环 clearInterval(upTimerid); clearInterval(downTimerId); clearInterval(leftTimerId); clearInterval(rightTimerId); // 隐藏游戏区域,显示高分榜容器 grid.style.display = 'none'; highScoresContainer.style.display = 'block'; checkHighScore(); // 检查并更新高分榜 } function saveHighScore(score, highScores) { const name = prompt('恭喜您获得高分!请输入您的名字:'); const newScore = { score, name: name || '匿名玩家' // 如果用户未输入,则设为匿名 }; highScores.push(newScore); highScores.sort((a, b) => b.score - a.score); // 降序排序 highScores.splice(NO_OF_HIGH_SCORES); // 只保留前NO_OF_HIGH_SCORES个分数 localStorage.setItem(HIGH_SCORES, jsON.stringify(highScores)); }; function checkHighScore() { const highScores = json.parse(localStorage.getItem(HIGH_SCORES)) ?? []; const lowestScore = highScores[NO_OF_HIGH_SCORES - 1]?.score ?? 0; if (score > lowestScore || highScores.length < NO_OF_HIGH_SCORES) { saveHighScore(score, highScores); } showHighScores(); // 无论是否新高分,都显示高分榜 } function showHighScores() { const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ?? []; const highScoreList = document.getElementById('highScores'); // 渲染高分榜列表,增加排名显示 highScoreList.innerHTML = highScores.map((score, index) => `<li>${index + 1}. ${score.name} - ${score.score}</li>` ).join(''); // 使用join('')避免数组默认的逗号分隔 // 确保高分榜容器可见 (虽然gameOver已设置,但在此处再次确认更稳妥) // highScoresContainer.style.display = 'block'; } function start() { if (!isGameOver) { createPlatforms(); createDoodler(); setInterval(movePlatforms, 30); jump(); document.addEventListener('keyup', control); // 确保游戏开始时高分榜是隐藏的 highScoresContainer.style.display = 'none'; grid.style.display = 'block'; } } // 为“重新开始”按钮添加事件监听器 if (restartButton) { restartButton.addEventListener('click', () => { // 最简单的重新开始方式是重新加载页面,但这会丢失游戏状态 // 如果要保留状态,需要一个resetGame()函数来初始化所有变量 location.reload(); // 或者调用一个 resetGameAndStart() 函数 // resetGameAndStart(); }); } // 确保在游戏开始前,高分榜是隐藏的 highScoresContainer.style.display = 'none'; // 确保游戏开始时grid是可见的 grid.style.display = 'block'; // 游戏开始 start(); // ... 音乐播放事件监听器 ... });
在上述JavaScript代码中,我们做了以下关键改动:
- 在DOMContentLoaded中,获取了新添加的highScoresContainer和restartButton的引用。
- 在gameOver()函数中,清除了游戏区域的所有子元素和所有定时器后,通过修改style.display属性,将grid隐藏,将highScoresContainer显示。
- showHighScores()函数现在将高分榜条目格式化为“排名. 玩家名称 – 分数”,并使用.join(”)来避免列表项之间的逗号。
- 为restartButton添加了一个简单的click事件监听器,通过location.reload()实现重新开始游戏(更复杂的场景可能需要一个专门的