Tips for storing and retrieving high scores in a JavaScript game

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

Answer №1

Instead of just saving data to localStorage, make sure you also read from it. You initialized var players = []; on page load, but remember to retrieve the previous scores as well:

var players = JSON.parse(localStorage.getItem("niz"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

Updating a Vue ref does not result in the component reflecting the changes made

My Vue3 form has three text inputs and a group of checkboxes. To implement this, I am using the bootstrap-vue form along with its checkbox-group component. After calling an API to fetch default values for the form, I update the ref as shown below. Interes ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

Deliver an index.html file upon server creation

My goal is to have the server load a file called index.html when it is created. Currently, when I run the server.js file using node, it responds with text using res.end("text"). However, I want the index.html file to be displayed instead. I attempted to a ...

Is there a way to ensure that both new Date() and new Date("yyyy-mm-dd hh:mm:ss") are initialized with the same timezone?

When utilizing both constructors, I noticed that they generate with different timezones. Ideally, they should be in the same timezone to ensure accurate calculations between them. I attempted to manually parse today's date and time, but this feels li ...

Sluggish Performance of Material UI Table

Hey there! I've been working with Material-UI for a large data table, but I've noticed it's quite slow. Before reaching out on Github, I wanted to see if other users have any tips or workarounds to help improve performance. Here is the code ...

Jumping Iframe Anchor Link in Src

I'm facing a challenge with an iframe positioned in the center of a webpage. I want to show content from another page within the iframe, but not starting at the very top. To achieve this, I inserted an anchor into the src of my iframe, linked to an a ...

What could be causing the TypeError in my pg-query result?

In the process of creating a node function to add a user to a PostgreSQL database, I am utilizing node.js, pg, and pg-query for communication between the application and the database. Prior to inserting a new record, I am attempting to verify that the ema ...

Retrieve information dynamically from a JSON file using the get JSON function and iterate through the data

I possess a JSON file that I wish to utilize in creating dynamic HTML elements with the JSON content. Below is the provided JSON data: { "india": [ { "position": "left", "imgurl":"3.jpg" }, { ...

Converting HTML Form Data into CSV with Multiple Rows

I currently have a form that generates a CSV file with data from select elements in the HTML form. The columns in the CSV correspond to the selected options in the form, but I need to extend this functionality to populate multiple rows in the CSV. Expecte ...

Creating a personalized instance function in Angular's $resource

When working with AngularJS, all actions for a $resource are added as $customAction methods to the Resource. This allows me to easily invoke them as methods on resource instances. For example: var User = $resource('/user/:userId', {userId:' ...

Deactivate form fields when entering data into a set of interconnected fields

I need help with the following functionality using jQuery on the form below: 1/ If any character is entered in 'filter_loan_id', 'filter_fname', 'filter_lname', or 'filter_postcode' fields, then disable the 'fi ...

Creating a pop-up effect for a div in the center of a table cell using HTML and CSS

I am currently working with Angular and facing a challenge where I need to display a div like a popup in a table cell when clicked. Despite having the click event logic in place, I am unsure of how to achieve this without using external libraries such as B ...

Choose from the select2 multiselect options and lock certain selected choices from being altered

I have coded a select dropdown with preselected options, some of which I want to keep fixed so that users cannot change them. To achieve this, I implemented the following code: <select id="select2-multiple" name="users" multiple="multiple" style="width ...

Utilizing Next.js to create dynamic routes and static builds incorporating unique ID values within the URL paths

Is there a way to create a page in Next.js where I can extract the ID from the URL in a dynamic route and use it for a static build without having to predefine all possible values of the ID in getStaticProps()? For example, the URL is as follows: localhost ...

Find out the first word in a text block in Swift by comparing it to an array of strings

Among a collection of strings composed of words and phrases in various orders, I am trying to identify the first occurrence of a word or phrase from the array. Here is an example: searchWords = ["December", "Wednesday", "beginning ...

The issue of CSS not being applied to HTML content after being inserted via AJAX has been encountered

I've successfully implemented AJAX to retrieve specific page content from a database, but now I'm facing an issue: When it comes to the 'Contact' page, the form retrieved from the database (as HTML) is not applying the CSS styles I hav ...

What is the purpose of the 'onClassExtended' function in Extjs 6 for class definition?

Ext.define('Algorithm.data.Simulated', { needs: [ //.... ], onClassExtended: function(obj, info) { // .... } }) I came across this code snippet but couldn't locate any official documentation for it on Sencha ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

Quick and easy way to access json data with jquery

Need help with reading data from JSON format using jQuery. I've attempted the code below, but I'm having trouble retrieving the exact data I need. $.ajax({ url: '@Url.HttpRouteUrl("GetDistrictList", new { })', ...