using browser storage for Game save - jackdarker/TwineTest GitHub Wiki

Snowman does not come with an fully fledged solution to sore/restore a save-game.
It has some functions to extract the game-data as compressed json and restore this game-data from it.
But we have to take care:

  • to provide a GUI for the user
  • write the json to a file or another storage location
  • read the json from a storage
  • maybe run some additional logic, f.e. to fix a save-game created in a previous version

Attention

Snowman save-game consist of (compressed) json. And by default this means we can only store simple datatypes like numbers, strings and arrays of those. See here for more detailed description and how to work around that.

For now lets just assume you have defined some simple variables in window.story.state.

Part1

The functions we need to use are:

  • var hash= window.story.save()
  • window.story.restore(hash) The hash contains everything inside window.story.state and also history and checkpoint-data.

I created a window.storage-object with the following functions (please note that the exampel has a slightly different implementation now). Those functions use the browser storage.
saveBrowser: function(slot) {
//var hash= window.story.save(); this call somehow messes up html and I had to copy the following from snowman script
var hash = LZString.compressToBase64(JSON.stringify({state:window.story.state,
history:window.story.history,checkpointName:window.story.checkpointName}));
var info=window.story.state.player.location +' - '+ new Date().toString();
window.localStorage.setItem(slot.concat('info'),info);
window.localStorage.setItem(slot,hash);
return(info);
},
loadBrowser: function(slot) {
var hash,info;
if(window.storage.ok()) {
hash=window.localStorage.getItem(slot);
info=window.storage.getSaveInfo(slot);
window.storage.rebuildFromSave(hash,true);
} return(info);
},
rebuildFromSave: function(hash,compressed){
if(!compressed) hash=LZString.compressToBase64(hash);
//copied from window.story.restore() because reviver ;
var save = JSON.parse(LZString.decompressFromBase64(hash));
window.story.state = save.state;
window.story.history = save.history;
window.story.checkpointName = save.checkpointName;
window.gm.rebuildObjects(); // this is for handling version-upgrades
window.story.show(window.story.history[window.story.history.length - 1], true);
}