Skip to content

Instantly share code, notes, and snippets.

@jameswomack
Last active August 29, 2015 14:03
Show Gist options
  • Save jameswomack/6e6462f9c6ae5d9b9072 to your computer and use it in GitHub Desktop.
Save jameswomack/6e6462f9c6ae5d9b9072 to your computer and use it in GitHub Desktop.
CircularJSON w/ Type Information
var CircularJSON = require('circular-json');
var jsdom = require("jsdom");
var $ = require("jquery")(jsdom.jsdom().createWindow());
var print = console.log;
var LocalStorage = {
store: {},
setItem: function (key, value) {
this.store[key] = CircularJSON.stringify(value);
},
getItem: function (key, Proto) {
var result = JSON.parse(this.store[key]);
return key === Proto.name.toLowerCase() ? reviveFromJSONResult(result, Proto) : result;
}
};
function Room(name, description){
this.description = description;
this.roomItems = [/*array of items randomly set*/];
this.exits = [/*array of rooms set */];
}
var Player = function Player(startroom){
this.currentRoom = startroom; //this is a room
this.playerItems = [/* An array of Items */];
}
var isPlayer = Player.isPrototypeOf.bind(Player);
var localStorage = Object.create(LocalStorage);
var player = null;
function startGame() {
player = new Player(new Room('Home', 'My favorite place to code at night.'));
player.player = player;
}
function saveGame(){
player.lastsave = new Date().toISOString();
localStorage.setItem('player', player);
}
function loadGame() {
player = localStorage.getItem('player', Player);
}
function reviveFromJSONResult(result, Proto) {
var value = Object.create(Proto);
for (var key in result) {
value[key] = result[key];
}
value[Proto.name.toLowerCase()] && (value[Proto.name.toLowerCase()] = value);
return value;
}
startGame();
saveGame();
player = null
loadGame();
print(player === player.player, isPlayer(player), isPlayer(player.player));
// true true true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment