JavaScript游戏高分无法持久化求助:如何实现本地永久存储?
问题描述
我开发了一款小型JavaScript游戏,希望实现前10名高分的持久保存,但目前分数仅在游戏加载状态下有效,刷新浏览器后就会被清除。作为JavaScript新手,我尝试了以下代码但仍未解决问题,现求助如何实现分数永久保存,仅当出现更高分时才替换旧分数:
function loadHighScores() { const highScoresJSON = localStorage.getItem("highScores"); if (highScoresJSON !== null) { highScores = JSON.parse(highScoresJSON); } else { highScores = []; } } function displayHighScores() { topScores.sort((a, b) => b.score - a.score); const scoreListHTML = topScores .map((entry, index) => `${index + 1}. ${entry.initials} - ${entry.score}`) .join("<br>"); scoreList.innerHTML = scoreListHTML; } function saveScore() { const initials = initialsElement.value.toUpperCase(); if (initials.length === 3) { topScores.push({ initials, score }); topScores.sort((a, b) => b.score - a.score); topScores.splice(10); displayHighScores(); resetGame(); showStartScreen(); initialsElement.value = ""; // Save the high scores to local storage. localStorage.setItem("highScores", JSON.stringify(topScores)); } }
解决方案
你的代码核心问题是变量名不统一,以及缺少页面加载时的初始化逻辑,以下是修复后的完整实现:
关键修改说明
- 统一全局变量名:加载、显示、保存操作都使用同一个数组
topScores - 页面加载时自动读取本地存储的高分数据
- 添加分数资格校验:仅当当前分数能进入前10时才允许保存
- 调整保存与显示的顺序,确保数据持久化后再更新界面
修复后的完整代码
// 全局变量存储高分列表 let topScores = []; // 假设这是你已有的DOM元素引用(根据实际ID调整) const initialsElement = document.getElementById('initials'); const scoreList = document.getElementById('scoreList'); // 页面加载完成后立即加载并显示高分 window.addEventListener('DOMContentLoaded', loadHighScores); function loadHighScores() { const highScoresJSON = localStorage.getItem("highScores"); topScores = highScoresJSON ? JSON.parse(highScoresJSON) : []; displayHighScores(); } function displayHighScores() { // 按分数降序排序 topScores.sort((a, b) => b.score - a.score); // 生成高分列表HTML const scoreListHTML = topScores .map((entry, index) => `${index + 1}. ${entry.initials} - ${entry.score}`) .join("<br>"); scoreList.innerHTML = scoreListHTML; } function saveScore() { // 先判断当前分数是否有资格进入前10 const canEnterTop10 = topScores.length < 10 || score > (topScores[9]?.score || 0); if (!canEnterTop10) { alert('分数未进入前10,无需保存'); resetGame(); showStartScreen(); return; } const initials = initialsElement.value.toUpperCase(); if (initials.length === 3) { // 添加新分数条目 topScores.push({ initials, score }); // 重新排序并保留前10名 topScores.sort((a, b) => b.score - a.score); topScores.splice(10); // 持久化到本地存储 localStorage.setItem("highScores", JSON.stringify(topScores)); // 更新页面显示 displayHighScores(); // 重置游戏状态 resetGame(); showStartScreen(); initialsElement.value = ""; } else { alert('请输入3个大写字母的初始s'); } } // 以下是假设你已有的游戏逻辑函数,根据实际情况调整 function resetGame() { // 你的游戏重置逻辑 } function showStartScreen() { // 显示开始界面的逻辑 }
内容的提问来源于stack exchange,提问作者Evan Sorrell
相关产品推荐
相关产品推荐

