簡體   English   中英

為Snake游戲添加高分

[英]Add a high score to Snake game

我試圖通過使用 localStorage 在我的 Snake 游戲中設置一個高分,但我無法讓它工作。 我能得到一些建議嗎?

這是在 Cloud9 上使用 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;
}

我希望高分會保留在 localStorage 中,但由於某種原因,它不是。

如果分數大於 highscore,則將分數設置為本地存儲

if (score > highscore) {
   highscore = score;
   localStorage.setItem("highscore", highscore);
}

您可以使用 cookie 來存儲高分

IE

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 "";
  }

我是這樣解決的:你的最高分被保存到 localstorege 並且總是在游戲結束后更新並從 localstorege 加載到你的 HTML 代碼中。

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

if (highscore < score) {
    highscore = score
    localStorage.setItem("highscore", highscore);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM