I've just finished creating a JavaScript snake game and now I'd like to add a "scores" option that displays the top 10 players along with their names and scores. My initial plan was to create an object containing the player's name and score upon game over, then store it in an array which would be saved in localStorage. However, when trying this out, only one player is being displayed at a time, likely due to some issue with the variable "dead" and the need to reload the page after each game. Any suggestions on how to fix this?
var players = [];
function Player(name, points){
this.name = name;
this.points = points;
}
// Game Over
if (snakeX < box || snakeX>17*box || snakeY<3*box || snakeY>17*box || collision(newHead, snake)){
dead.play();
clearInterval(game);
var deadPlayer = new Player(prompt("Enter your name to save your score:", "Your Name"), score);
players.unshift(deadPlayer);
localStorage.setItem("playerArray", JSON.stringify(players));
window.location.href = "menu.html";
}
var dataFromStorage = localStorage.getItem("playerArray");
var storedPlayers = JSON.parse(dataFromStorage);
storedPlayers.sort(function(a,b){
return b.points - a.points;
})
for(var i in storedPlayers){
document.write(storedPlayers[i].name + "--------------" + storedPlayers[i].points);
}