如何在localStorage中保存游戏分数?现有实现代码运行无效该如何解决?
存在的错误
getItem()参数错误:localStorage.getItem()接收的是存储时的键名字符串,你传入变量myScore是错误的,应该传入你定义的键名"score"- 存储内容错误:你直接存入
myScore对象,localStorage仅支持存储字符串类型,直接存对象会被自动转为"[object Object]",无法拿到实际分数值,应该存储myGameArea.frameNo这个实际的分数数值 - 执行时机错误:你的localStorage读写代码写在全局作用域,页面加载时就会执行,此时游戏还未运行、分数未生成;当前游戏逻辑是碰撞后就终止
updateGameArea执行,应该把存储逻辑放在碰撞判定成功的位置,也就是游戏结束时执行存储 - 类型问题:localStorage存储的所有值都是字符串,取出分数如果要做数值运算(比如对比最高分)需要手动转为数字类型
正确实现
修改后的代码如下:
function updateGameArea() { var x, height, gap, minHeight, maxHeight, minGap, maxGap; for (i = 0; i < myObstacles.length; i += 1) { if (myGamePiece.crashWith(myObstacles[i])) { // 游戏结束时存储当前分数 localStorage.setItem("score", myGameArea.frameNo); // 读取存储的分数 var savedScore = Number(localStorage.getItem("score")); // 可以按需使用savedScore,比如展示历史分数 return; } } myGameArea.clear(); myGameArea.frameNo += 1; if (myGameArea.frameNo == 1 || everyinterval(150)) { x = myGameArea.canvas.width; minHeight = 20; maxHeight = 200; height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight); minGap = 50; maxGap = 200; gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap); myObstacles.push(new component(10, height, "green", x, 0)); myObstacles.push(new component(10, x - height - gap, "green", x, height + gap)); } for (i = 0; i < myObstacles.length; i += 1) { myObstacles[i].x += -1; myObstacles[i].update(); } myScore.text="SCORE: " + myGameArea.frameNo; myScore.update(); myGamePiece.newPos(); myGamePiece.update(); }
如果需要存储历史最高分,可以在存储时增加判断逻辑:
const historyHighest = Number(localStorage.getItem("highestScore") || 0); if (myGameArea.frameNo > historyHighest) { localStorage.setItem("highestScore", myGameArea.frameNo); }
内容的提问来源于stack exchange,提问作者AgChong
相关产品推荐
相关产品推荐

