GameSession

Copyright(c) 2012 Stefano Balietti MIT Licensed

Addon to save and load the nodeGame session in the browser

@see node.store


(function (node) {
  

Global scope

  
  var JSUS = node.JSUS,
    NDDB = node.NDDB,
    store = node.store;

  var prefix = 'nodegame_';

node.session

Loads a nodeGame session

If no parameter is passed it will return the current session. Else, it will try to load a session with the given id.

This method interact with the node.store object that provides lower level capabilities to write to a persistent support (e.g. the browser localStorate).

Params
sid number Optional. The session id to load
Returns
object The session object @see node.store
  node.session = function (sid) {
        

Returns the current session

    if (!sid) {
      var session = {
          id:   node.gsc.session,
          player: node.player,
          memory: node.game.memory,
          state:  node.game.state,
          game:   node.game.name,
          history: undefined
      };
      

If we saved the emitted events, add them to the session object

      if (node.events.history || node.events.history.length) {
        session.history = node.events.history.fetch();
      }
      
      return session;
    }
    
    if (!node.session.isEnabled()) {
      return false;
    }
    

Tries to return a stored session

    return node.store(prefix + sid);
  };

node.session.isEnabled

TRUE, if the session can be saved to a persistent support

  node.session.isEnabled = function() {
    return (node.store) ? node.store.isPersistent() : false;
  };
  

node.session.store

Stores the current session to a persistent medium

Returns
boolean TRUE, if session saving was successful
  node.session.store = function() {
    if (!node.session.isEnabled()) {
      node.log('Could not save the session');
      return false;
    }
    
    var session = node.session();
    var sid = session.id;
    node.store(prefix + sid, session);
    node.log('Session saved with id ' + sid);
    return true;
  }
  

Closure

})('undefined' != typeof node ? node : module.parent.exports);