Как сохранить игровой счет в локальном хранилище

#javascript #html #local-storage

Вопрос:

Я хочу сохранить результат игры в локальном хранилище. Я пытался

 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); 

Комментарии:

1. ваш getitem неверен

Ответ №1:

Ключ "score" не в том myScore

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