Save/load not working

Question:
The save and loading functions aren’t working in my game
Repl link:
https://replit.com/@JohnnySuriano/Cycle-Clicker#script.js


Save code

function saveGame() {
  let gameSave = {
    score: score,
    clickingPower: clickingPower,
    cursorCost: cursorCost,
    cursors: cursors,
    noobCoderCost: noobCoderCost,
    noobCoders: noobCoders,
    themeCost: themeCost,
    themes: themes,
    pannelCost: pannelCost,
    pannels: pannels
  };
  localStorage.setItem('gameSave', JSON.stringify(gameSave));
}

Load Code

window.onload = function() {
  loadGame();
  updateScorePerSecond()
  document.getElementById('score').innerHTML = score;
  document.getElementById('pannelcost').innerHTML = pannelCost;
  document.getElementById('pannels').innerHTML = pannels;
  document.getElementById('themecost').innerHTML = themeCost;
  document.getElementById('themes').innerHTML = themes;
  document.getElementById('noobcodercost').innerHTML = noobCoderCost;
  document.getElementById('noobcoders').innerHTML = noobCoders;
  document.getElementById('cursorcost').innerHTML = cursorCost;
  document.getElementById('cursors').innerHTML = cursors;
};

Save every 30 seconds

setInterval(function() {
  saveGame();
}, 30000); //30000ms = 30 seconds

Could you explain more clearly what errors you are getting and what issue you are facing.
Your code looks fine to me so far

1 Like

It should save the progress every 30 seconds but after 30 seconds when I refresh the page all the stats reset to their default values

1 Like

Change your load function to ensure that there is a saved game to load.

For example here:

function loadGame() {
  let savedGame = JSON.parse(localStorage.getItem('gameSave'));
  if (typeof savedGame.score !== 'undefined') score = savedGame.score;

Add a check for savedGame:

function loadGame() {
  let savedGame = JSON.parse(localStorage.getItem('gameSave'));
  
  if (savedGame) { // add a check to see if savedGame exists
    if (typeof savedGame.score !== 'undefined') score = savedGame.score;
3 Likes
function loadGame() {
 if (savedGame) {
   let savedGame = JSON.parse(localStorage.getItem('gameSave'));
   if (typeof savedGame.score !== 'undefined') score = savedGame.score;
   if (typeof savedGame.score !== 'undefined') clickingPower = savedGame.clickingPower;
   if (typeof savedGame.score !== 'undefined') cursors = savedGame.cursors;
   //etc
 }
}

So would this code work?

If you’re doing that, might as well use one bigger check:

function loadGame() {
 if (savedGame) {
   let savedGame = JSON.parse(localStorage.getItem('gameSave'));
   if (!!savedGame.score) { //If it's set, and not undefined
    score = savedGame.score;
    clickingPower = savedGame.clickingPower;
    cursors = savedGame.cursors;
   //etc
  }
 }
}
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.