I’m not getting to work with localStorage

Asked

Viewed 204 times

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 keep score from player1, which is player X in the case. After the play Again I didn’t want to lose that value, so I was trying to use without success some localStorage.

P.S.: I didn’t send the code HTML and the CSS, because I don’t know if there’s any way to upload the images I’m using.

  • 2

    And what’s the problem? Does it give an error? Already checked the browser compatibility? localstorage compatibility

  • Try adding/printing this line to your code "localStorage" in window. It will check if your browser is compatible with localstorage. If true, try it below window.localStorage to see all the contents of localStorage

  • @Ricardopunctual no error appears in the console, the problem is that I want to save the player’s point and go assigning + 1 point every time that same player wins. There in the example I am trying to implement the logic for player1(player X), then I will apply the same logic in the other condition(Else if), of player2(player O). I’ve tried it on Chrome and Firefox.

  • @lazyFox I will try here

  • Dear, you said it shows no error, so what would be the value shown when you call localStorage?

  • @sam Application: Key=scoreX, Value=1

  • So the LS is working. What wouldn’t be working?

  • @sam every time player1 win he should add +1 point. Ex: won three consecutive times, pontuacaoX should be shown on alert(pontuacaoX) // 3

Show 3 more comments

2 answers

1


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

  • Check if it exists and assign the value to the variable that will use it whenever the page is reloaded or during the process.
  • Since the value of LS is a string, to perform sums you need to convert to type number, where you can use parseInt(). Otherwise it will only concatenate instead of adding.

In your case, the variable valAcumuladoX should use the value stored 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 will you add +1, use the 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);
*/
  • see if I understand. Here var valAcumuladoX = LS_x || 0; I am checking if the localStorage there is, right? as I’ve got it right up here var LS_x = localStorage.getItem('scoreX'); he will be true and then valAcumuladoX will receive the Key, which allows me to access the points stored, like a query in the comic book? something else, this check is only given at the beginning, or every new game it is held, believe to be the second, but I’m not sure and I think I said shit above, the access is given through the key key key correct?

  • The value will be saved in the browser even if you close it. var valAcumuladoX = LS_x || 0; check if it exists, if it does not exist, it will be 0.

-1

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

Note that I switched to popular input fields, but only for testing.

The score of X is recorded correctly via the local codeStorage.setItem(chaveX, pointoX) was being saved, only it was not being used through the variable valAcumuladoX.

<!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>

  • I couldn’t understand your line of reasoning. pointX gets valAcumuladoX.

  • My error there in my message, I change the text as soon as I find the answer, ok? I am testing your code, soon return.

  • @Luckasfujimoto would like to ask if you tested my example after I changed my answer, if yes and it was correct, could change your vote to positive?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.