Ask coding questions

← Back to all posts
Save and Restore Button
WilliamXing (46)

On this game, I want there to be a save and restore button. When you click save, it will save all progress, including spc and cps. When you click restore, it restores your progress. How can I do this?

Comments
hotnewtop
19wintersp (1120)

You can use LocalStorage for this. LocalStorage saves data in on the user's computer, and keeps it between sessions. To save an object to LocalStorage, serialize it as JSON with JSON.stringify and put it in the localStorage object:

var myObjectToSave = {
  foo: "bar",
  baz: "qux"
};

localStorage.savedData = JSON.stringify(myObjectToSave);

The same process can be reversed (with JSON.parse) on the loading end:

var mySavedObject = JSON.parse(localStorage.savedData);

console.log(mySavedObject); // { foo: "bar", baz: "qux" }
GatewayDuckYT (53)

Ok Sir You would use cookies
if you would invite me i would be happy to help set it up

GatewayDuckYT (53)

@GatewayDuckYT at show u how to do it your self

SameeraMurthy (110)

@GatewayDuckYT i think localStorage will be better

WilliamXing (46)

Pls send code and explanation
@GatewayDuckYT

GatewayDuckYT (53)

@WilliamXing can we get on a repl please its easyer there it can be a blank one but after u invite me give me a link

WilliamXing (46)

Restore doesn’t work. It just gives me one score @GatewayDuckYT

Whacko (320)
function save() {
  localStorage.saved = JSON.stringify({
    spc: spc,
    cps: cps
  });
}

function load() {
  if (localStorage.saved) {
    try {
      let saved = JSON.parse(localStorage.saved);
      spc = saved.spc;
      cps = saved.cps;
    } catch(err) {
      console.error(err);
      alert("Failed to load data!");
    }
  } else {
    alert("You need to save, first!");
  }
}
WilliamXing (46)

This doesn't really help @Whacko

Whacko (320)

@WilliamXing Tell me exactly what you want the game to look like.

WilliamXing (46)

Well, I copyed your code into my project, as you should be able to see. But, when I save, then I run it again, I click restore. But, it doesn't [email protected]