What is the best method for storing "game progress" in local storage?

I am currently working on coding a simple Risk game where players can click on countries to change their color from red to green, yellow, purple, and back to white.

The game starts with an "all-white" map. I am looking to create different save slots so that players can save the game in one slot and then reload that slot later to continue playing. How can I implement this feature for 4 different save slots? The world map is an SVG file, and I am changing each region's color using event.target.style.fill.

Consider the following code:

HTML

    <svg   width="100%" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                viewBox="0 0 701 300" style="enable-background:new 0 0 701 300;" xml:space="preserve">
    
      <g onclick="changeColor(event)">
       <path class="st1" d="M308.6,112.3l-0.1,0.2l-0.1,0.2l-0.1-0.1h-0.1l-0.1-0.1l0.1-0.1h0.1l0.1-0.1l0.1-0.1L308.6,112.3L308.6,112.3z
            M313.4,111.6v0.2l0.1,0.1l-0.1,0.2v0.1l-0.1,0.1l-0.2,0.1l-0.1,0.1l-0.2-0.1l-0.2-0.2l-0.1-0.1v-0.2l0.2-0.1v-0.2v-0.1h0.2h0.1h0.1
           L313.4,111.6z M309.9,111.8L309.9,111.8l-0.2-0.1l-0.1-0.1v-0.1v-0.1h0.1h0.1l0.2,0.1v0.1L309.9,111.8L309.9,111.8z M312,110.6
           L312,110.6l-0.2,0.2l-0.1,0.2l-0.1,0.1v0.1l-0.1,0.2v0.1l-0.2,0.2v0.1h-0.1l-0.2,0.1l0,0v-0.1l-0.1-0.1v-0.1l-0.1-0.1v-0.1l-0.1-0.2
           l0.2-0.1l0.1,0.1l0.2-0.1h0.1l0.2-0.1l0.2-0.1v-0.1l0.2-0.1h0.2L312,110.6L312,110.6z M315.6,111.6l-0.1,0.1h-0.1h-0.1h-0.1v-0.1
           h0.1l0.2-0.1l0.1-0.1l0.1-0.1v-0.2V111l0.1-0.2l0.1-0.1l0.1-0.2l0.1-0.3l0.1-0.1h0.1l0.1,0.1v0.2v0.2v0.2v0.2l0,0l-0.1,0.2l-0.1,0.1
           H316L315.6,111.6L315.6,111.6z M308.8,110h0.1l0.1,0.1l0.1,0.2l-0.1,0.1v0.1l-0.2,0.3l0,0v-0.1l-0.1-0.3v-0.1v-0.1L308.8,110h0.1
           H308.8z M317.1,109.3L317.1,109.3l-0.1,0.3l-0.2,0.2h-0.2l-0.1,0.2l-0.2-0.1l0,0l0.1-0.1v-0.1l0.1-0.1l0.1-0.1h0.1l0.1-0.1h0.2l0,0
           L317.1,109.3l0.1-0.1l0...

JS

function changeColor(event) { 
    clicks++

    if (clicks == 1)  {
      event.target.style.fill = "#DA4567";
  }
    if (clicks == 2) {
        event.target.style.fill = "#7aeb34";
   }
    if (clicks == 3) {
        event.target.style.fill = "#ffe70a";
}
    if (clicks == 4) {
        event.target.style.fill = "#ba0afa";
}
    if (clicks == 5) {
        event.target.style.fill = "#FFFFFF";
        clicks = 0;
}
}

CSS (INITIAL COLOR = WHITE)

.st1{fill:#FFFFFF;stroke:#000000;stroke-linejoin:round;}

You can see a live demo of the game and access the website by clicking on the link below. I have also added a user interface for saving and loading games which can be accessed through the "Load/Save game" button.

Visit the Risk Game Demo here.

Thank you for your support!

Answer №1

If you want to utilize localStorage to save the state of your application, it's essential to create functions similar to the ones outlined below:

function save(slotIndex, clicks) {
  let slots;

  try {
    slots = JSON.parse(localStorage.getItem('slots'));
  } catch (e) {
    console.error(e);
  }

  if (!slots) {
    slots = [0, 0, 0, 0];
  }

  slots[slotIndex] = clicks;

  localStorage.setItem('slots', JSON.stringify(slots));
}

function restore(slotIndex) {
  let slots = [];

  try {
    slots = JSON.parse(localStorage.getItem('slots'));
  } catch (e) {
    alert('no slots found in local storage');
  }

  return slots[slotIndex] || 0;
}

An altered version of your app with my modifications can be accessed here.

It's important to note that the state being saved only includes the number of clicks made, which corresponds to the next color for coloring a country.

If what you truly intend to save are the colors of the countries themselves, a more intricate data structure would be required:

const slots = [
  
  {
    currentColorIndex: 2,
    selectedCountries: [
       { id: 'spain', colorIndex: 3 },
       { id: 'usa', colorIndex: 1 },
    ]
  },
  ... other slots
  
];

This updated data can also be stored in localStorage once stringified (as all localStorage values must be strings). Your application will need to update this structure whenever a color is changed in the SVG, ensuring they remain synchronized.

As applications become more complex, delving into concepts like the MVC (Model View Controller) pattern may prove beneficial in handling such issues effectively.

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

The conversion of the input (ImageButton) to jQuery is not possible

Within my gridview, I have ImageButtons that open an edit form. To determine the ID, I need to access the surrounding element (Row). The issue arises when I try to pass 'this' as a parameter in the onClientClick event which triggers a JavaScript ...

Currently dealing with a script that utilizes AJAX GET to incorporate JSON data into my table

Greetings and thank you for taking the time to read this! Within my HTML, I have implemented a form element that allows inputting data into 5 different fields. This data is then transmitted to a database using my unique API key. Once stored in the database ...

Ways to soften a section of a canvas component?

What is the simplest way to apply a blur effect to a specific portion of my canvas element? I am utilizing the JavaScript 3D Library known as three.js. This library simplifies the use of WebGL. While they offer examples of blur and depth of field effects, ...

What steps are involved in converting .html files to .ejs format via terminal?

I'm currently working on a Node project and I have a bunch of HTML files that I need to convert to .ejs format. Does anyone know of a quick way to change all the .html files in my directory to .ejs using terminal commands? ...

Error retrieving data from Jquery getJSON Query

When making a request for a JSON feed using the standard jQuery getJson function, I ran into an issue. The JSON URL is not hosted on my own domain. $.getJSON('myfeed.json?jsoncallback=?', function(data){ console.log(data); }) After checking F ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

Incorporate a notification into the Windows notification center without it being visibly displayed on the desktop

I am currently developing an Electron application that includes a custom Notification feature. This feature involves html5 divs appearing and disappearing as necessary on a frameless, transparent, always-on-top window. Although the feature works well, I s ...

Error: Attempting to access 'map' property on an undefined object in a ReactJS application

import React, { useEffect, useState } from 'react'; import axios from "axios"; import './List.css'; import { toast } from "react-toastify"; const ListComponent = () => { const url = "http://localhost:4500& ...

Unable to locate the sibling element using CSS Selector with Selenium

When using a CSS Selector to click on the next sibling element in Selenium WebDriver, an InvalidSelectorException is thrown. If we consider my DOM structure: <div class="checkbox-group"> <div> <span class="checkbox">::aft ...

Ensure page is updated after an AJAX request in jQuery Mobile by refreshing the page

My jQueryMobile page structure in index.html looks like this: <div data-role="page"> <div data-role="header">...</div> <div data-role="content">...</div> <div data-role="footer">...</div> </div& ...

Troubleshooting a scenario where making edits to a mongoDB item does not result in any updates

I am struggling with a problem in my nodeJS application involving updating items in a mongoDB database. I have successfully implemented features to add and remove notes, but when attempting to update a note, the changes do not reflect in the database. Desp ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

Unable to execute the new firebase on node server

I'm currently watching this google talk. However, I am facing an issue trying to create a firebase object. Following my package.json file, I initiated with: npm install firebase --save Then proceeded with the following steps: let Firebase = requir ...

There seems to be an issue with the navigation bar

I am currently facing an issue with the navigation bar on my website. It appears to be working fine when viewed at full width, but when I shrink the page, the menu button shows up as expected but does not function properly. I have been trying to identify ...

What is the process for dynamically inserting a new object into an array of data objects in Vue.js?

I am a beginner with vue.js and currently working on a form. I have an add button in my form, so when the user clicks on it, the same form field will be added to the form. Users can add as many times as they want. Here is my initial data: data () { ret ...

Loading JSON models with raycasting and colliding with meshes in three.js

Currently, I am utilizing a raycaster to detect if the mouse (or touch) hits a mesh. The object is slender and I would like to enlarge the size of whatever can be intersected by the Ray. While working with game objects in three.js, is there a way for me to ...

Sizing Children in Ant Design Inline Forms

I'm having trouble making my form inline with a select taking up 60% of the space and a submit button taking up the remaining 40%. Every time I try to do this, the select and button end up sizing themselves incorrectly. The select starts out very smal ...

Making Angular2 Templates More Efficient with Array.prototype.filter()

I have a variable named networkInterface that includes an array called services. My objective is to create a checkbox input that indicates whether a specific service_id exists within the services array of the networkInterface. An illustration of JSON `int ...

What is the behavior of an AngularJS controller when it encounters the res.json(false) value?

In my AngularJS controller, I am sending an HTTP request to an API. The API can respond with either res.json(true) or res.json(false) depending on a certain condition. However, it seems like the controller is not handling this as expected. I am interested ...

What is the secret to keeping a hover effect active?

As I hover over the buttons in my stack, a text box appears on the right side. The intention is for this text box to act as a scroll box, but it disappears when I move my mouse to scroll because it needs to be continuously hovered upon to stay active. To ...