简体   繁体   English

将分数保存到本地存储

[英]Saving scores to local storage

I'm implementing a dice game, which will store the results of the 2 players.我正在实现一个骰子游戏,它将存储 2 个玩家的结果。 I'm having an issue saving the scores, when I console.log I get the new scores only.我在保存分数时遇到问题,当我 console.log 我只得到新分数时。 What is the issue here?这里有什么问题?

window.onload = (event) => {
  throw_dice();
};
var scores = { player1: 0, player2: 0 };

function throw_dice() {
  let x = Math.floor(Math.random() * 6) + 1;
  let img1 = document.getElementById("img1");
  let y = Math.floor(Math.random() * 6) + 1;
  let img2 = document.getElementById("img2");
  img1.src = "./images/dice" + x + ".png";
  img2.src = "./images/dice" + y + ".png";

  if (x > y) {
    document.getElementById("title").innerHTML = "PLAYER 1 WINS";
    scores.player1 = scores.player1 + 1;
  } else if (x == y) {
    document.getElementById("title").innerHTML = "DRAW";
  } else {
    document.getElementById("title").innerHTML = "PLAYER 2 WINS";
    scores.player2 = scores.player2 + 1;
  }

  saveScores();
  getScores();
}

function saveScores() {
  localStorage.setItem("score", JSON.stringify(scores));
}
function getScores() {
    var x = localStorage.getItem('score');

    console.log('x', JSON.parse(x));
}

On pageload, you're doing在页面加载时,你正在做

var scores = { player1: 0, player2: 0 };

and then updating that object inside throw_dice and saving to storage.然后在throw_dice中更新该对象并保存到存储中。 On that line, you need to retrieve the object from local storage on pageload instead, otherwise you'll be never reading (and thereby overwriting) the existing scores in storage in saveScores .在那条线上,您需要在页面加载时从本地存储中检索对象,否则您将永远不会读取(从而覆盖) saveScores中存储中的现有分数。

var scores = JSON.parse(
  localStorage.getItem('score') || '{ "player1": 0, "player2": 0 }')
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM