1

I created a game with a score. Every time that there's a collision, it ads 10 points and when the user has made 16 collisions, the game ends, and the score gets stored in localstorage so it can be displayed on a scoreboard.

  //everytime there's a collision, contador++
  // when contador reaches 16, there's a pop up and the score is saved in local storage.

  if (contador == 16)  {

  localStorage.setItem("pontosSalvos", pontos);

  var pop = document.getElementById ( "alerta_ajuda");
  pop.style.display = 'inline';
  contador = 0;

          }

Then, there's a page for the scoreboard with the following code:

    //the score gets displayed on a span called mensagem

    function mostraPontos() {
    var pontos = localStorage.getItem ("pontosSalvos");
    var span = document.getElementById ("mensagem_pontos");

    span.innerHTML = pontos; 
}

What I wanted to know is this: With the code like this, whenever there's a new score, it replaces the previous score in the scoreboard and it only shows the new score. Is there a way to store/display multiple scores without replacing the old ones? Thank you!

  • You are aware that after making it save multiple scores if you use a different device you will only see the scores created via that device and browser... Also the client can edit the score since they have full access to the cookie. – NewToJS Jun 04 '17 at 16:04
  • @guest271314 So wrong. As long as people can see where the variables are defined most don't care for the choice of name and also wouldn't vote to close for that reason. – NewToJS Jun 04 '17 at 16:14
  • @NewToJS Possibly, though am skeptical of the rationality of "most don't care" for good reason – guest271314 Jun 04 '17 at 16:15
  • 1
    Well multiple have to agree for vote to close. It isn't something I would do as I don't see that as being a good enough reason. As long as I can see where the variables are defined then it makes no difference to what that variables name is set to as I know what sort of value it hold to understand the rest of the source. – NewToJS Jun 04 '17 at 16:20

2 Answers2

1

The localStorage can only store strings. You can store arrays in it using numerous formats. I would recommend JSON to do this. Have some array with the scores, and when reading from localStorage, JSON.parse it, and when writing, JSON.stringify. You probably want to change the span to an ordered list.

if (contador == 16)  {
    var pontosArr = JSON.parse(localStorage.pontosSalvos || '[]');
    pontosArr.push(+pontos);
    // Sorts highest to lowest
    pontosArr.sort(function(a, b) { return b - a; });
    localStorage.pontosSalvos = JSON.stringify(pontosArr);

    var pop = document.getElementById ( "alerta_ajuda");
    pop.style.display = 'inline';
    contador = 0;

}
function mostraPontos() {
    // pontos is an empty array if nothing has been stored yet.
    var pontos = JSON.parse(localStorage.pontosSalvos || '[]');
    var ol = document.getElementById("mensagem_pontos");
    ol.innerHTML = '';
    // Appends all the scores as list elements
    for (var i = 0; i < pontos.length; i++) {
        var li = document.createElement('li');
        li.textContent = pontos[i];
        ol.appendChild(li);
    }
}
Artyer
  • 31,034
  • 3
  • 47
  • 75
0

You can push the scores to an array and save its stringified version to localStorage instead of storing a single value.

To display them in HTML, you should parse the stringified value coming back from localStorage to obtain an array again and map its values to an HTML element of your choice.

Something like this:

const board = document.getElementById('board');

// Load saved scores:

const fakeLocalStorage = {};

let scores = [];

try {
  scores = JSON.parse(fakeLocalStorage.scores);
} catch(err) {}

// Add new scores and save them:

document.getElementById('push').onclick = function() {  
  scores.push(Math.floor(Math.random() * 17));
  
  fakeLocalStorage.scores = JSON.stringify(scores);
  
  board.innerHTML = scores.map(score => `<li>${ score }</li>`).join('');
};

// Clear all scores and delete them from localStorage:

document.getElementById('clear').onclick = function() {
  scores = [];
  
  delete fakeLocalStorage.scores;
  
  board.innerHTML = '';
};
<button id="push">ADD SCORE</button>
<button id="clear">CLEAR SCORES</button>

<ul id="board"></ul>

Note localStorage is not allowed in StackOverflow snippets, so I just use a normal object fakeLocalStorage in this example. You can just swap it for localStorage in your code and it should still be working as expected.

Danziger
  • 19,628
  • 4
  • 53
  • 83
  • 2
    Don't you think giving an example of doing that would make this more suitable for an answer rather than a comment... – NewToJS Jun 04 '17 at 16:02
  • Then I suggest you write it before submitting. It isn't who gets the first post that wins the accepted answer. If anything you put yourself at risk of being down voted by doing that if you don't have the relevant information in your answer/solution. – NewToJS Jun 04 '17 at 16:22
  • 1
    I disagree the initial answer didn't have the relevant information to answer the question. In short, the answer is just, "push the scores into an array and store that in localStorage". If additional help is needed in order to know how to persist an array to localStorage, there are other questions in SO addressing that. – Danziger Jun 04 '17 at 16:35
  • 1
    Moreover, I think adding working code, specially for simple questions/answers, just provides and effortless copy-pasteable solution and encourages newcomers to write questions like "This is my code. It doesn't work. Please help", as they would also expect to get their code fixed instead of directions on how to address the underlaying issue. – Danziger Jun 04 '17 at 16:38
  • Well if the question is a duplicate then you flag the question as a duplicate rather than copy/pasting the solution.... Leave a recommendation as your answer did before "use an array and push new scores into it" and then give the link to the duplicate question. It's the reason for having flags on questions... – NewToJS Jun 04 '17 at 16:40
  • 1
    I don't consider the question a duplicate, at least of the question I'm referring to: https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage, because the OP's question was about a specific use case and not about the generic functionality. Therefore, the code I provided is not a copy/paste of anything, but rather a specific solution for that use case. If I decided to add it instead of leaving the initial answer is because after checking the existing questions/answers, I thought due to the differences from those examples, this may be more clarifying. – Danziger Jun 04 '17 at 17:02