0

I was trying to set a high score in my Snake game by using localStorage, but I can't get it to work. Could I get some advice?

This is on Cloud9 using Javascript.

<div id = "highscore">High Score: 0</div>

var highscore = 0;
var localStorage = localStorage;
localStorage.setItem("highscore", highscore);
var storage = localStorage.getItem("highscore");
highscore.innerHTML = storage;
if (score > highscore) {
    highscore = score;
}

I was hoping that the high score would be retained in localStorage, but for some reason it isn't.

Fei
  • 1,906
  • 20
  • 36
Sensei Zhu
  • 11
  • 2
  • You have to update the value in localStorage any time it changes if you want to retain that change. – ray May 25 '19 at 01:33

3 Answers3

1

set the score to local storage if the score is greater than highscore

if (score > highscore) {
   highscore = score;
   localStorage.setItem("highscore", highscore);
}
Tenusha Guruge
  • 2,147
  • 3
  • 18
  • 38
0

You could use a cookie to storage the high score

i.e.

var highscore =  parseInt(getCookie("high_score"));

if (score > highscore) {

    document.cookie = "high_score="+ score + ";";

}


  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }
0

Here's how I solved it: Your highest score is saved to localstorege and is always updated and loaded into your HTML code from localstorege after the end of the game.

var highscore = localStorage.getItem("highscore");
document.getElementById('highscore').innerHTML = localStorage.getItem("highscore");

if (highscore < score) {
    highscore = score
    localStorage.setItem("highscore", highscore);
}
adammaly004
  • 211
  • 2
  • 3