好吧,所以我制作了一个JavaScript蛇游戏,我想添加选项“得分”,以显示前10名球员的姓名和得分。想法是,当游戏结束时,制作一个包含名称和分数的对象,并将其存储到数组中,然后将该数组存储在localStorage中。它只打印出1个播放器,它与变量“ dead”有关,并且因为每次都需要重新加载页面。有什么建议吗?
var players = [];
function igrac(ime,bodovi){
this.ime=ime;
this.bodovi=bodovi;
}
// game over
if ( snakeX < box || snakeX>17*box || snakeY<3*box || snakeY>17*box || collision(newHead,snake)){
dead.play();
clearInterval(game);
var dead= new igrac(prompt("Unesite ime da zapamtite skor:","Vase ime"),score);
players.unshift(dead);
localStorage.setItem("niz",JSON.stringify(players));
window.location.href="menu.html";
}
var nesto=localStorage.getItem("niz");
var players2=JSON.parse(nesto);
players2.sort(function(a,b){
return b.bodovi-a.bodovi;
})
for( var i in players2){
document.write(players2[i].ime + "--------------" + players2[i].bodovi);
}
答案 0 :(得分:2)
您正在保存到localStorage
,但没有从中读取内容。您在页面加载时设置了var players = [];
,但您需要阅读以前的分数:
var players = JSON.parse(localStorage.getItem("niz"));