Jump to content

[SOLVED] JS Game save and load


xRa7eN
 Share

Recommended Posts

Hi, I've been working on my game project clicker (helps me learn JS and other languages). So it is going smooth so far. Thought it might be a good idea implement a save/load feature now.

The following has no errors, but loading it has no effect.

INITIAL VARS

var player = {
	name:"",
	level:0,
	gold: 190,// CHANGE BACK TO 0 AFTER TESTING
	artifact: 0,
	weaponId:0,
	weaponLevel:0,
	spellId:0,
        spellLevel:0,
	goldPerClick:5,
	goldPerSec:0,
        currentTrainer:0,
};

SAVE STATE

/* SETUP A SAVE STATE */
function save() {

        // TRY TO SAVE THE GAME
        try {
                localStorage.setItem('copperSave',JSON.stringify(player));
        }catch(err) {
                console.log('Cannot access localStorage - browser may be old or storage may be corrupt')
        }
        console.log('Game saved successfully');

}// FUNCTION: SAVE GAME

LOAD STATE

/* LOAD PREVIOUS game */
function loadGame() {
        var gameLoad = JSON.parse(localStorage.getItem("copperSave"));

        player= gameLoad.player;
        console.log(player); // this shows the starting vars NOT the saved var from getItem!
}

SOME MISC VARS TO HELP DEBUG

initGame();

var answer = confirm('Continue from previous saves?\nWarning, "Cancel" creates a new game wiping previous saves');
if ( answer ) {
        loadGame();
}
console.log('here after load query');

// GAME LOOP FOLLOWS BELOW....

It looks right, can anyone suggest why it might not be loading correctly. It just gives the starting variable, not the saved variables.

 

Link to comment
Share on other sites

ok went the cookie approach. I heard this is not usually the best way, but it works. I set the date way in the future, so should not be an issue - hopefully.


/* SETUP A SAVE STATE */
function save() {
        // Using cookie method. problems with localstorage.
        var d = new Date; // other possible future date:
        d.setTime(d.getTime() + 10 * 365 * 24 * 60 * 60); // 2038 :-)
        document.cookie = "copperSave" + "=" + JSON.stringify(player) + ";path=/;expires" + d.toGMTString();
}// FUNCTION: SAVE GAME

/* LOAD PREVIOUS game */
function loadGame() {
        // Split cookie string and get all individual name=value pairs in an array
        var cookieArr = document.cookie.split(";");

        // Loop through the array elements
        for(var i = 0; i < cookieArr.length; i++) {
                var cookiePair = cookieArr[i].split("=");

                /* Removing whitespace at the beginning of the cookie name
                and compare it with the given string */
                if("copperSave" == cookiePair[0].trim()) {
                    // Decode the cookie value and return
                    player =  JSON.parse(cookiePair[1]);

                }

        }
        console.log(player.gold);
}




initGame();
var answer = confirm('Continue from previous saves?\nWarning, "Cancel" creates a new game wiping previous saves');
if ( answer ) {
        loadGame();
}

 

Link to comment
Share on other sites

Notice you are saving a stringified version of "player"

10 hours ago, xRa7eN said:

SAVE STATE


/* SETUP A SAVE STATE */
function save() {

        // TRY TO SAVE THE GAME
        try {
                localStorage.setItem('copperSave',JSON.stringify(player));
        }catch(err) {
                console.log('Cannot access localStorage - browser may be old or storage may be corrupt')
        }
        console.log('Game saved successfully');

}// FUNCTION: SAVE GAME

 

But then requesting a "player" from within that parsed object when you load.  player = gameLoad.player

10 hours ago, xRa7eN said:

LOAD STATE


/* LOAD PREVIOUS game */
function loadGame() {
        var gameLoad = JSON.parse(localStorage.getItem("copperSave"));

        player= gameLoad.player;
        console.log(player); // this shows the starting vars NOT the saved var from getItem!
}

The two are not equal, this is the equivalent of asking for "player.player" - which should be undefined.

The fact that console.log(player) does not return "undefined" suggests you've previously pushed a value in there (e.g. from a failed run beforehand), and are now repeatedly viewing the same mistake?  And that's a problem with state persistence generally - mistakes linger and are hard to understand or replicate.

Your cookie approach might work but is just wrong - generally client-side cookies are transferred on every http request (within the headers) on every matching resource, and I doubt the server ever needs to know any of it?  LocalStorage is the correct API, fix the typos and reset your cache / store.

 

 

 

Link to comment
Share on other sites

Hi b10b!

Trust me, the nightmare is worse LOL

The log actually shows player correctly - just the original initgame () values. weird huh.

With cookies, there is no fail. works perfect.

So should I just use "player = gameLoad?  at the moment, back to dealing with the math of the incremental. I just put this part on hold, and stuck with cookies, and I am currently developing it, but later will pursue what is going on with the localstorage - probably something weird.

player = JSON.parse(localStorage.getItem("copperSave"));

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...