17370845950

JavaScript游戏高分榜的优雅展示与页面切换实现

本文将指导您如何在JavaScript游戏中优雅地展示高分榜。通过利用CSS的`display`属性和JavaScript动态控制DOM元素,您可以在游戏结束后将游戏界面切换为纯粹的高分榜页面,实现流畅的视图转换,而无需重新加载HTML文件,从而提升用户体验。

在现代Web游戏中,提供一个清晰且易于访问的高分榜是提升玩家体验的关键一环。传统方法可能涉及加载一个全新的HTML页面来显示分数,但这会带来视觉上的中断和额外的网络请求。本教程将介绍一种更流畅、更具交互性的方法,即在同一HTML页面内,通过巧妙地利用CSS和JavaScript来切换游戏界面与高分榜的显示。

核心思路:利用CSS display 属性进行视图切换

实现这一目标的核心是使用CSS的display属性来控制不同内容区域的可见性。我们将把游戏区域和高分榜区域分别放置在独立的HTML容器中。在游戏进行时,高分榜容器保持隐藏;当游戏结束需要显示高分榜时,我们通过JavaScript来隐藏游戏容器,同时显示高分榜容器。

HTML 结构准备

首先,我们需要调整HTML结构,确保高分榜有自己的独立容器,并且这个容器可以被方便地控制显示与隐藏。




    
    
    Doodle Jump 高分榜
    


    
        
            
        
    

    
        

高分榜

    在这个结构中:

    • .game-container 将包裹所有游戏相关的元素,如.grid。
    • .high-scores-container 是一个全新的容器,专门用于显示高分榜。它内部包含一个标题和一个用于显示分数的有序列表

      CSS 样式定义

      接下来,我们需要为这两个容器定义初始样式。默认情况下,高分榜容器应该是隐藏的。

      /* ... 现有CSS样式 ... */
      
      .game-container {
          /* 确保游戏容器占据所需空间 */
          width: 400px; /* 与 .grid 宽度保持一致 */
          height: 600px; /* 与 .grid 高度保持一致 */
          margin: 0 auto; /* 居中显示 */
          position: relative; /* 如果游戏内有绝对定位元素,此容器也需要 */
      }
      
      .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: 0 auto;
          text-align: center;
          padding-top: 50px; /* 顶部留白 */
          background-color: #f0f0f0; /* 高分榜背景色 */
          font-family: "Georgia", "Times New Roman", serif;
          color: #333;
          box-sizing: border-box; /* 确保padding不增加总宽度 */
      }
      
      .high-scores-container h1 {
          font-size: 48px;
          margin-bottom: 30px;
          color: #4CAF50; /* 标题颜色 */
      }
      
      #highScores {
          list-style-type: none; /* 移除默认列表点 */
          padding: 0;
          font-size: 30px;
          line-height: 1.6;
      }
      
      #highScores li {
          margin-bottom: 10px;
          color: #555;
      }

      注意,我们将.grid包裹在.game-container中,这样可以更方便地控制整个游戏区域的显示与隐藏。.high-scores-container 初始设置为 display: none;。

      JavaScript 逻辑实现

      现在,我们需要修改JavaScript代码,以便在游戏结束时执行视图切换。

      1. 获取容器引用: 在 DOMContentLoaded 事件监听器中,获取 game-container 和 high-scores-container 的DOM引用。
      2. 修改 gameOver 函数: 在游戏结束时,除了清理游戏状态和计时器,还需要隐藏游戏容器。
      3. 修改 showHighScores 函数: 在显示高分榜之前,先填充数据,然后隐藏游戏容器并显示高分榜容器。
      document.addEventListener('DOMContentLoaded', () => {
        const grid = document.querySelector('.grid');
        const gameContainer = document.querySelector('.game-container'); // 获取游戏容器
        const highScoresContainer = document.querySelector('.high-scores-container'); // 获取高分榜容器
        const doodler = document.createElement('div');
        // ... 其他变量和函数定义 ...
      
        const NO_OF_HIGH_SCORES = 10;
        const HIGH_SCORES = 'highScores';
      
        // ... createDoodler, control, Platform, createPlatforms, movePlatforms, jump, fall, moveLeft, moveRight, moveStraight 函数 ...
      
        function gameOver() {
          console.log('GAME OVER');
          isGameOver = true;
      
          // 清理所有计时器
          clearInterval(upTimerid);
          clearInterval(downTimerId);
          clearInterval(leftTimerId);
          clearInterval(rightTimerId);
      
          // 暂停音乐
          if (context && typeof context.pause === 'function') {
            context.pause();
          }
      
          // 清空游戏网格内容 (如果需要,可以选择保留一些最终得分信息)
          while (grid.firstChild) {
            grid.removeChild(grid.firstChild);
          }
          // grid.innerHTML = `你的分数: ${score}`; // 可以在这里显示最终分数
      
          // 隐藏游戏容器
          gameContainer.style.display = 'none';
      
          // 检查并显示高分榜
          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);
          localStorage.setItem(HIGH_SCORES, JSON.stringify(highScores));
        }
      
        function checkHighScore() {
          const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ?? [];
          // 确保 highScores 是一个数组,即使 localStorage 中没有数据
          const lowestScore = highScores.length < NO_OF_HIGH_SCORES ? 0 : highScores[NO_OF_HIGH_SCORES - 1].score;
      
          if (score > lowestScore) {
            saveHighScore(score, highScores);
          }
          showHighScores(); // 无论是否创造新高,都显示高分榜
        }
      
        function showHighScores() {
          const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ?? [];
          const highScoreList = document.getElementById('highScores');
      
          // 清空旧列表
          highScoreList.innerHTML = '';
      
          // 填充新的高分榜数据
          highScores.forEach((s, index) => {
              const listItem = document.createElement('li');
              listItem.textContent = `${index + 1}. ${s.name} - ${s.score}`;
              highScoreList.appendChild(listItem);
          });
      
          // 隐藏游戏容器,显示高分榜容器
          gameContainer.style.display = 'none';
          highScoresContainer.style.display = 'block'; // 或者 'flex'/'grid' 根据你的布局需求
        }
      
        function start() {
          if (!isGameOver) {
            // 确保在游戏开始时,高分榜容器是隐藏的
            highScoresContainer.style.display = 'none';
            gameContainer.style.display = 'block'; // 确保游戏容器是显示的
      
            createPlatforms();
            createDoodler();
            setInterval(movePlatforms, 30);
            jump();
            document.addEventListener('keyup', control);
          }
        }
      
        // ... 其他事件监听器 ...
      
        // 游戏初始化时调用start
        start();
      });

      注意事项与优化

      1. 恢复游戏: 在高分榜页面,你可能需要添加一个“重新开始”或“返回主菜单”的按钮。点击这些按钮时,需要再次隐藏高分榜容器,显示游戏容器,并重置游戏状态(如分数、玩家位置、平台等),然后调用 start() 函数。
      2. 样式统一: 确保游戏容器和高分榜容器在宽度、高度和居中方式上保持一致,这样切换时视觉效果会更平滑。
      3. 清空游戏元素: 在 gameOver 中,while (grid.firstChild) { grid.removeChild(grid.firstChild); } 这段代码会移除游戏网格内的所有元素。这是为了确保在显示高分榜时,游戏元素不再可见。如果你想在游戏结束时显示一些最终得分信息在游戏网格内,可以在移除元素前或移除部分元素后进行。
      4. 用户体验: 考虑添加一些过渡动画,使容器的显示和隐藏更加平滑,例如使用CSS transition 属性配合 opacity 或 transform。
      5. 健壮性: 在 checkHighScore 和 showHighScores 函数中,使用 ?? [] 操作符确保 localStorage 中没有数据时也能正确处理,避免潜在的错误。

      总结

      通过上述方法,我们成功地在同一个HTML页面内实现了游戏界面与高分榜的无缝切换。这种方法不仅提升了用户体验,避免了页面加载的延迟,也使得整个Web应用更像一个单页应用(SPA)。这种技术广泛应用于各种Web交互式应用中,是前端开发中实现视图管理的基本且高效的策略。