如何使用lz-string在JavaScript中实现游戏存档的导入导出?
使用lz-string实现网页游戏存档的导入/导出
一、引入lz-string库
从lz-string官方仓库下载压缩后的JS文件,放到你的游戏项目目录中,通过script标签引入:
<script src="./lz-string.min.js"></script>
二、修改存档导出逻辑
把原本仅存到localStorage的逻辑,改成生成可复制的压缩字符串,供用户导出存档:
// 生成导出用的存档字符串 function exportGameSave() { // 收集游戏数据,逻辑和你原代码一致 const gameSave = { stars: Game.stars, totalStarsEarned: Game.totalStarsEarned, buildings: buildings, upgrades: upgrades, achievements: achievements }; // 转JSON字符串后用lz-string压缩为URI安全的字符串 const jsonStr = JSON.stringify(gameSave); const compressedSave = LZString.compressToEncodedURIComponent(jsonStr); // 可将此字符串显示到页面输入框供用户复制,比如: // document.getElementById('saveCode').value = compressedSave; return compressedSave; } // 若需保留localStorage存储,更新原saveGame函数 function saveGame() { const compressedSave = exportGameSave(); localStorage.setItem("gameSave", compressedSave); }
三、实现存档导入功能
新增导入函数,解析用户输入的压缩字符串并加载游戏状态:
// 导入存档,参数为用户输入的压缩字符串 function importGameSave(compressedSave) { try { // 解压字符串 const jsonStr = LZString.decompressFromEncodedURIComponent(compressedSave); if (!jsonStr) throw new Error("无效的存档字符串"); const savedGame = JSON.parse(jsonStr); // 加载数据,逻辑和你原代码一致 if (typeof savedGame.stars !== "undefined") Game.stars = savedGame.stars; if (typeof savedGame.totalStarsEarned !== "undefined") Game.totalStarsEarned = savedGame.totalStarsEarned; if (typeof savedGame.buildings !== "undefined") buildings = savedGame.buildings; if (typeof savedGame.upgrades !== "undefined") upgrades = savedGame.upgrades; if (typeof savedGame.achievements !== "undefined") achievements = savedGame.achievements; // 同时将存档存入localStorage localStorage.setItem("gameSave", compressedSave); } catch (err) { console.error("导入存档失败:", err); // 此处可添加用户错误提示逻辑 } } // 更新原loadGame函数,从localStorage加载压缩存档 function loadGame() { const compressedSave = localStorage.getItem("gameSave"); if (compressedSave) importGameSave(compressedSave); }
补充说明
你提供的eyJ2ZXJzaW9uIjoxLjMsImZlYXR1cmVzIjp7ImxvY2F0aW9uIjp7InJvb是一段lz-string压缩后的存档片段,完整的压缩存档可通过exportGameSave()生成,用户复制后即可在其他会话或设备中通过importGameSave()导入。
内容的提问来源于stack exchange,提问作者A Person
相关产品推荐
相关产品推荐

