Pre-release
AdventureJS Docs Downloads
Score: 0 Moves: 0
// getAsset.js

(function () {
  /* global AdventureJS A */

  var p = AdventureJS.Game.prototype;

  /**
   * <strong>getAsset</strong> takes a string representing an
   * asset name or id and tries to return an asset object.
   * @memberOf AdventureJS.Game
   * @method AdventureJS.Game#getAsset
   * @param {String} identifier Name or ID of a game object.
   * @param {Object} params Used to check for 'prefer_substance' in cases of looking for substances in containers.
   * @returns {Object} A game asset.
   */
  p.getAsset = function Game_getAsset(
    identifier,
    params = { prefer_substance: false }
  ) {
    // did we get an asset?
    if (identifier && "object" === typeof identifier && identifier.id) {
      return identifier;
    }

    // did we get something other than a string?
    if ("string" !== typeof identifier) {
      this.game.log(
        "L1051",
        "warn",
        "low",
        "Game_getAsset received invalid identifier. ",
        "Game"
      );
      return null;
    }
    identifier = identifier.toLowerCase();

    var object;

    if (identifier.includes(":")) {
      // When parsing asset:aspect:potential:type for substance or fungibles we can
      // set a parsednoun to a string that looks like "fungible:pistachio:in:pouch"
      let [type, potential, aspect, asset] = identifier.split(":"); // type:class:aspect:asset

      if (type && type === "fungible") {
        // @TODO what do we do here with fungibles?
        // at the moment we're going to return the dispenser
        identifier = asset;
      } else if (type && type === "substance") {
        // it's a substance
        if (params.prefer_substance) {
          identifier = potential;
        } else {
          identifier = asset;
        }
      }
    }

    // what other special props might we want to return from here?

    if ("player" === identifier || "_player" === identifier) {
      object = this.getPlayer();
    } else if ("room" === identifier || "_room" === identifier) {
      object = this.getRoom();
    } else {
      object = this.world[A.FX.normalize(identifier)];
    }

    if (typeof object !== "undefined") {
      return object;
    }

    return null;
  };
})();