I can not work with localStorage

1

I have the following javascript code:

const player1 = "X";
const player2 = "O";
var playTime = player1;
var gameOver = false;
var pontuacaoX = 0;
var pontuacaoO = 0;
var chaveX = 'scoreX';
var chaveO = 'scoreO';
var valAcumuladoX = 0;

atualizaMostrador();
inicializarEspacos();

function atualizaMostrador(){
    if(gameOver) {return;}

    if(playTime == player1) {
        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/x.png");
    } else {

        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/o.png");    
    }
}

function inicializarEspacos(){
    var espacos = document.getElementsByClassName("espaco");
    for(var i = 0; i < espacos.length; i++){

        espacos[i].addEventListener("click", function(){
            if(gameOver) {return;}

            if(this.getElementsByTagName("img").length == 0){
                if(playTime == player1){

                    this.innerHTML = "<img src='_img/x.png' width='60px;' height='60px;'>";
                    this.setAttribute("jogada", player1);
                    playTime = player2;

                } else{

                    this.innerHTML = "<img src='_img/o.png' width='60px;' height='60px;'>";
                    this.setAttribute("jogada", player2);
                    playTime = player1;
                }
                atualizaMostrador();
                verificarVencedor();
            }
        });
    }
}

async function verificarVencedor(){

    var a1 = document.getElementById("a1").getAttribute("jogada");
    var a2 = document.getElementById("a2").getAttribute("jogada");
    var a3 = document.getElementById("a3").getAttribute("jogada");

    var b1 = document.getElementById("b1").getAttribute("jogada");
    var b2 = document.getElementById("b2").getAttribute("jogada");
    var b3 = document.getElementById("b3").getAttribute("jogada");

    var c1 = document.getElementById("c1").getAttribute("jogada");
    var c2 = document.getElementById("c2").getAttribute("jogada");
    var c3 = document.getElementById("c3").getAttribute("jogada");

    var vencedor = "";

    if((a1 == b1 && a1 == c1 && a1 != "") || (a1 == a2 && a1 == a3 && a1 != "") || (a1 == b2 && a1 == c3 && a1 != "")){
        vencedor = a1;   
    }else if((b2 == b1 && b2 == b3 && b2 != "") || (b2 == a2 && b2 == c2 && b2 != "") || (b2 == a3 && b2 == c1 && b2 != ""))
    {
        vencedor = b2;
    }else if(((c3 == c2 && c3 == c1) || (c3 == a3 && c3 == b3)) && c3 != "")
    {
        vencedor = c3;    
    }


    if(vencedor != ""){
        gameOver = true;

    if(vencedor == "X"){
        pontuacaoX = valAcumuladoX + 1;
        localStorage.setItem(chaveX, pontuacaoX);

    }else {
        pontuacaoO += 1;
        localStorage.setItem(chaveO, pontuacaoO);
    }
        await sleep(50);

    valAcumuladoX = localStorage.getItem(chaveX);

        alert("O Player: '" + vencedor + "' foi o(a) vencedor(a) da partida! \n Player X " + pontuacaoX + " vs " + pontuacaoO + " Player O. Clique em OK! e em \n PLAY 

AGAIN para jogar novamente!");


    document.getElementById('butao').style.display = "block";


    } else if(a1 != '' && a2 != '' && a3 != '' && b1 != '' && b2 != '' && b3 != '' && c1 != '' && c2 != '' && c3 != ''){

    await sleep(50);

    alert("Velha!");

    document.getElementById('butao').style.display = "block";


      }
}

function sleep(ms){
    return new Promise(resolve => setTimeout(resolve, ms));
}
/*
var resultadoScore = localStorage.getItem(chaveX);
alert(resultadoScore);
*/

I'm trying to save the score of player1 , which is the X player in the case. After play again I did not want to lose this value, so I've been trying to unsuccessfully use localStorage .

P.S.: I did not send the HTML and CSS tags, since I do not know if I can upload the images I'm using.

    
asked by anonymous 22.08.2018 / 19:29

2 answers

1

To work with localStorage (LS) you need to do two things:

  • Verify that it exists and assign the value to the variable that will use it whenever the page is reloaded or in the process.
  • As the value of LS is a string, to make sums you must convert to number , where you can use parseInt() . Otherwise it will only concatenate instead of add.

In your case, the variable valAcumuladoX should use the value saved in LS

// atribuo o valor do LS a uma variável:
var LS_x = localStorage.getItem('scoreX');

// uso um operador curto para atribuir o valor a variável
// se LS_x for verdadeiro, o valor será o guardado no LS,
// caso contrário, será 0
var valAcumuladoX = LS_x || 0;

And where you will add +1 , use parseInt() :

pontuacaoX = parseInt(valAcumuladoX) + 1;

So the whole code should look like this:

const player1 = "X";
const player2 = "O";
var playTime = player1;
var gameOver = false;
var pontuacaoX = 0;
var pontuacaoO = 0;
var chaveX = 'scoreX';
var chaveO = 'scoreO';

var LS_x = localStorage.getItem('scoreX');
var valAcumuladoX = LS_x || 0;

atualizaMostrador();
inicializarEspacos();

function atualizaMostrador(){
    if(gameOver) {return;}

    if(playTime == player1) {
        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/x.png");
    } else {

        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/o.png");    
    }
}

function inicializarEspacos(){
    var espacos = document.getElementsByClassName("espaco");
    for(var i = 0; i < espacos.length; i++){

        espacos[i].addEventListener("click", function(){
            if(gameOver) {return;}

            if(this.getElementsByTagName("img").length == 0){
                if(playTime == player1){

                    this.innerHTML = "<img src='_img/x.png' width='60px;' height='60px;'>";
                    this.setAttribute("jogada", player1);
                    playTime = player2;

                } else{

                    this.innerHTML = "<img src='_img/o.png' width='60px;' height='60px;'>";
                    this.setAttribute("jogada", player2);
                    playTime = player1;
                }
                atualizaMostrador();
                verificarVencedor();
            }
        });
    }
}

async function verificarVencedor(){

    var a1 = document.getElementById("a1").getAttribute("jogada");
    var a2 = document.getElementById("a2").getAttribute("jogada");
    var a3 = document.getElementById("a3").getAttribute("jogada");

    var b1 = document.getElementById("b1").getAttribute("jogada");
    var b2 = document.getElementById("b2").getAttribute("jogada");
    var b3 = document.getElementById("b3").getAttribute("jogada");

    var c1 = document.getElementById("c1").getAttribute("jogada");
    var c2 = document.getElementById("c2").getAttribute("jogada");
    var c3 = document.getElementById("c3").getAttribute("jogada");

    var vencedor = "";

    if((a1 == b1 && a1 == c1 && a1 != "") || (a1 == a2 && a1 == a3 && a1 != "") || (a1 == b2 && a1 == c3 && a1 != "")){
        vencedor = a1;   
    }else if((b2 == b1 && b2 == b3 && b2 != "") || (b2 == a2 && b2 == c2 && b2 != "") || (b2 == a3 && b2 == c1 && b2 != ""))
    {
        vencedor = b2;
    }else if(((c3 == c2 && c3 == c1) || (c3 == a3 && c3 == b3)) && c3 != "")
    {
        vencedor = c3;    
    }


    if(vencedor != ""){
        gameOver = true;

    if(vencedor == "X"){
        pontuacaoX = parseInt(valAcumuladoX) + 1;
        localStorage.setItem(chaveX, pontuacaoX);

    }else {
        pontuacaoO += 1;
        localStorage.setItem(chaveO, pontuacaoO);
    }
        await sleep(50);

    valAcumuladoX = localStorage.getItem(chaveX);

        alert("O Player: '" + vencedor + "' foi o(a) vencedor(a) da partida! \n Player X " + pontuacaoX + " vs " + pontuacaoO + " Player O. Clique em OK! e em \n PLAY 

AGAIN para jogar novamente!");


    document.getElementById('butao').style.display = "block";


    } else if(a1 != '' && a2 != '' && a3 != '' && b1 != '' && b2 != '' && b3 != '' && c1 != '' && c2 != '' && c3 != ''){

    await sleep(50);

    alert("Velha!");

    document.getElementById('butao').style.display = "block";


      }
}

function sleep(ms){
    return new Promise(resolve => setTimeout(resolve, ms));
}
/*
var resultadoScore = localStorage.getItem(chaveX);
alert(resultadoScore);
*/
    
23.08.2018 / 19:09
-1

I made it work, take a look at the code below:

Note that I changed to popular input fields, but only to test.

The X score is written correctly through the local codeStorage.setItem (keyX, scoreX) was being saved, it was not being used through the variable valAcumulateX.

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <label id="placarX">0</label> x <label id="placarO">0</label><br>
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="a1">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="a2">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="a3">
  <br>
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="b1">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="b2">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="b3">
  <br>
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="c1">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="c2">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="c3">
  <br>
  <input id="butao" type="button" value="PLAY AGAIN" onclick="javascript:this.style.display='none';zeracampos();" style="display: none;">
</body>
<script>
  const player1 = "X";
  const player2 = "O";
  var playTime = player1;
  var gameOver = false;
  var pontuacaoX = 0;
  var pontuacaoO = 0;
  var chaveX = 'scoreX';
  var chaveO = 'scoreO';

  function zeracampos() {
    document.getElementById("a1").value = "";
    document.getElementById("a2").value = "";
    document.getElementById("a3").value = "";
    document.getElementById("b1").value = "";
    document.getElementById("b2").value = "";
    document.getElementById("b3").value = "";
    document.getElementById("c1").value = "";
    document.getElementById("c2").value = "";
    document.getElementById("c3").value = "";
  }

  function clicou(obj) {
    if (playTime == player1) {
      obj.value = player1;
      playTime = player2;
    } else {
      obj.value = player2;
      playTime = player1;
    }

  }

  atualizaMostrador();
  inicializarEspacos();

  function atualizaMostrador() {
    if (gameOver) {
      return;
    }

    if (playTime == player1) {
      var player = document.querySelectorAll("div#mostrador img")[0];
      //player.setAttribute("src", "_img/x.png");
    } else {

      var player = document.querySelectorAll("div#mostrador img")[0];
      //player.setAttribute("src", "_img/o.png");    
    }
  }

  function inicializarEspacos() {
    valAcumuladoO = 0;
    valAcumuladoX = 0;
    var espacos = document.getElementsByClassName("espaco");
    for (var i = 0; i < espacos.length; i++) {

      espacos[i].addEventListener("click", function() {

        atualizaMostrador();
        verificarVencedor();

      });
    }
  }

  async function verificarVencedor() {

    var a1 = document.getElementById("a1").value;
    var a2 = document.getElementById("a2").value;
    var a3 = document.getElementById("a3").value;

    var b1 = document.getElementById("b1").value;
    var b2 = document.getElementById("b2").value;
    var b3 = document.getElementById("b3").value;

    var c1 = document.getElementById("c1").value;
    var c2 = document.getElementById("c2").value;
    var c3 = document.getElementById("c3").value;

    var vencedor = "";

    if ((a1 == b1 && a1 == c1 && a1 != "") || (a1 == a2 && a1 == a3 && a1 != "") || (a1 == b2 && a1 == c3 && a1 != "")) {
      vencedor = a1;
    } else if ((b2 == b1 && b2 == b3 && b2 != "") || (b2 == a2 && b2 == c2 && b2 != "") || (b2 == a3 && b2 == c1 && b2 != "")) {
      vencedor = b2;
    } else if (((c3 == c2 && c3 == c1) || (c3 == a3 && c3 == b3)) && c3 != "") {
      vencedor = c3;
    }


    if (vencedor != "") {
      gameOver = true;

      if (vencedor == "X") {
        pontuacaoX = parseInt(valAcumuladoX) + 1;
        localStorage.setItem(chaveX, pontuacaoX);
        valAcumuladoX = localStorage.getItem(chaveX);
        document.getElementById("placarX").innerHTML = valAcumuladoX;

      } else {
        pontuacaoO = parseInt(valAcumuladoO) + 1;
        localStorage.setItem(chaveO, pontuacaoO);
        valAcumuladoO = localStorage.getItem(chaveO);
        document.getElementById("placarO").innerHTML = valAcumuladoO;
      }
      await sleep(50);

      alert("O Player: '" + vencedor + "' foi o(a) vencedor(a) da partida! \n Player X " + pontuacaoX + " vs " + pontuacaoO + " Player O. Clique em OK! e em \n PLAY AGAIN para jogar novamente!");

      document.getElementById('butao').style.display = "block";

    } else if (a1 != '' && a2 != '' && a3 != '' && b1 != '' && b2 != '' && b3 != '' && c1 != '' && c2 != '' && c3 != '') {

      await sleep(50);

      alert("Velha!");

      document.getElementById('butao').style.display = "block";

    }
  }

  function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
  /*
  var resultadoScore = localStorage.getItem(chaveX);
  alert(resultadoScore);
  */
</script>

</html>
    
22.08.2018 / 20:02