【问题标题】:How to save game score in local storage如何将游戏分数保存在本地存储中
【发布时间】:2021-09-08 23:01:12
【问题描述】:

我想将游戏分数保存在本地存储中。 我试过了

localStorage.setItem("score", myScore);

var score = localStorage.getItem(myScore);

保存游戏分数但它不起作用。我做错了吗?我该怎么办?

function updateGameArea() {
        var x, height, gap, minHeight, maxHeight, minGap, maxGap;
        for (i = 0; i < myObstacles.length; i += 1) {
            if (myGamePiece.crashWith(myObstacles[i])) {
                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();
    }
    
    localStorage.setItem("score", myScore);
    var score = localStorage.getItem(myScore);

【问题讨论】:

  • 您的 getitem 错误

标签: javascript html local-storage


【解决方案1】:

密钥是"score" 而不是myScore

localStorage.setItem("score", myScore);
let score = localStorage.getItem("score"); // <--- key is "score", not myScore

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多