Pre-release
Adventure.js Docs Downloads
Score: 0 Moves: 0
// restoreWorld.js

/*global adventurejs A*/
"use strict";

/**
 * For UNDO and RESTORE.
 * Revert the world to the baseline snapshot
 * and then merge in updates from a partial copy.
 * @method adventurejs.Game#restoreWorld
 * @memberOf adventurejs.Game
 * @param {Object} source
 */
adventurejs.restoreWorld = function Adventurejs_restoreWorld(source) {
  this.game.log(
    "log",
    "high",
    "restoreWorld.js attempting to restore the world.",
    "CopyOperations"
  );
  var starttime = new Date().getTime();

  // we're expecting a string but allowing that we
  // might have received a pre-formed world object
  if ("string" === typeof source) {
    source = JSON.parse(source);
  }

  // Verify a key property to ensure that we're looking at a save.
  if ("undefined" === typeof source._timestamp) {
    alert(
      "The selected json file doesn't appear to be a valid adventurejs save file."
    );
    return false;
  }

  // Verify that save is for this game.
  if (source._titleSerialized !== this.game.titleSerialized) {
    alert("The selected save file doesn't appear to be for this game.");
    return false;
  }

  // Verify that save was made with same version of the game.
  // Holding off on this for now to see how well we can handle version changes.
  //if( source._version !== this.game.version ) {
  //  alert( "The selected save file doesn't appear to be for this game." );
  //  return false;
  //}

  //delete the current world
  delete this.world;

  // restore entire world from baseline
  //this.world = A.cloneWorld.call(this, this.baseline.world);
  this.world = A.clone.call(this, this.baseline.world);
  //@TODO testing clone vs cloneWorld - initial tests are good and much faster

  this.world = A.mergeWorld.call(this, source, this.world);

  // TODO vars, score, other meta info

  source = null;

  // lastly, update the main display
  // TODO this should update entire display set
  this.game.updateDisplayRoom();

  this.game.log(
    "log",
    "high",
    "restoreWorld() took " +
      (new Date().getTime() - starttime) / 1000 +
      " seconds.",
    "CopyOperations"
  );

  return true;
};