Iavra

Iavra Self Variables

Nov 20th, 2015 (edited)
785
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*:
  2.  * @plugindesc Adds self variables to the game, that work similar to self switches.
  3.  * <Iavra Self Variables>
  4.  * @author Iavra
  5.  *
  6.  * @param Container Name
  7.  * @desc Name of the self variables container. Default: $gameSelfVariables
  8.  * @default $gameSelfVariables
  9.  *
  10.  * @param Plugin Command
  11.  * @desc Name of the plugin command to manage self variables. Can't control whitespaces. Default: SelfVariable
  12.  * @default SelfVariable
  13.  *
  14.  * @help
  15.  * Adds self variables to the game. These work similar to self switches and are uniquely identifies by a map id, an event id and
  16.  * a key (any string without whitespaces). This documentation assumes, that the plugin parameters "Container Name" and "Plugin
  17.  * Command" are set to their default values.
  18.  *
  19.  * Basic access to self variables is done via script commands:
  20.  *
  21.  * $gameSelfVariables.setValue([mapId, eventId, key], value);
  22.  * $gameSelfVariables.value([mapId, eventId, key]);
  23.  *
  24.  * To access a self variable of the current event, the following script commands can be used:
  25.  *
  26.  * $gameSelfVariables.get(this, key);
  27.  * $gameSelfVariables.set(this, key, value);
  28.  *
  29.  * Self Variables can also be modified via plugin commands. The following operations are available:
  30.  *
  31.  * =   Sets a self variable to a given value.
  32.  * +   Adds a given value to a self variable.
  33.  * -   Subtracts a given value from a self variable.
  34.  * /   Divides a self variable with a given value.
  35.  * *   Multiplies a self variable with a given value.
  36.  * %   Sets a self variable to the remainder when dividing it with a given value (mod).
  37.  *
  38.  * To apply one of these operations, one of the following commands can be used:
  39.  *
  40.  * SelfVariable key operation value             // Invokes an operation with a given value.
  41.  * SelfVariable key operation v[value]          // Invokes an operation with the value contained in a given variable.
  42.  * SelfVariable key operation self[value]       // Invokes an operation with the value contained in a given self variable.
  43.  * SelfVariable key operation (value1 ~ value2) // Invokes an operation with a random integer between 2 values.
  44.  * SelfVariable key operation "value"           // Evaluates the given expression as an integer and invokes the operation with it.
  45.  *
  46.  * Further plugin commands are:
  47.  *
  48.  * SelfVariable key abs                         // Sets a self variable to its absolute value.
  49.  */
  50.  
  51. var Imported = Imported || {};
  52. Imported.iavra_self_variables = true;
  53.  
  54. //=============================================================================
  55. // namespace IAVRA
  56. //=============================================================================
  57.  
  58. (function() {
  59.     "use strict";
  60.    
  61.     /**
  62.      * Plugin parameters are loaded without using the PluginManager, since it relies on the actual filename.
  63.      */
  64.     var _params = $plugins.filter(function(p) { return p.description.contains('<Iavra Self Variables>'); })[0].parameters;
  65.     var _containerName = _params['Container Name'];
  66.     var _pluginCommand = _params['Plugin Command'];
  67.    
  68.     /**
  69.      * Validate plugin parameters.
  70.      */
  71.     if(!_containerName) { throw new Error('container name can\'t be empty'); }
  72.     if(!_pluginCommand || /\s/.test(_pluginCommand)) { throw new Error('plugin command can\'t be empty or contain whitespaces'); }
  73.    
  74.     /**
  75.      * Basic operations, that can be used.
  76.      */
  77.     var _operations = {
  78.         '=': function(cur, val) { return _parseInt(val); },
  79.         '+': function(cur, val) { return cur + _parseInt(val); },
  80.         '-': function(cur, val) { return cur - _parseInt(val); },
  81.         '/': function(cur, val) { return cur / _parseInt(val); },
  82.         '*': function(cur, val) { return cur * _parseInt(val); },
  83.         '%': function(cur, val) { return cur % _parseInt(val); }
  84.     };
  85.    
  86.     /**
  87.      * A list of all operations. "-" is escaped, because otherwise it will be recognized as a special character in regexes.
  88.      */
  89.     var _opKeys = "=+\\-/*%";
  90.    
  91.     /**
  92.      * Regexes matching all plugin commands, that can be used.
  93.      */
  94.     var _regex = {
  95.         // SelfVariable <key> <operation> <value>
  96.         modifyDirect: new RegExp('^([' + _opKeys + ']) ([+-]?\\d+)$'),
  97.         // SelfVariable <key> <operation> v[<variableId>]
  98.         modifyVariable: new RegExp('^([' + _opKeys + ']) [vV]\\[(\\d+)\\]$'),
  99.         // SelfVariable <key> <operation> self[<selfVariableId>]
  100.         modifySelfVariable: new RegExp('^([' + _opKeys + ']) self\\[(.+)\\]$', 'i'),
  101.         // SelfVariable <key> <operation> (<min> ~ <max>)
  102.         modifyRandom: new RegExp('^([' + _opKeys + ']) \\(([+-]?\\d+) ~ ([+-]?\\d+)\\)$'),
  103.         // SelfVariable <key> <operation> "<script>"
  104.         modifyScript: new RegExp('^([' + _opKeys + ']) "(.*)"$'),
  105.         // SelfVariable <key> abs
  106.         abs: /^abs$/i
  107.     };
  108.    
  109.     /**
  110.      * Tests all regexes given above. If one of them matches, the self variable is set to its new value and the function returns.
  111.      */
  112.     var _handleCommand = function(key, cmd) {
  113.         var t = _testWithCallback, o = _operations, g = window[_containerName], c = g.value(key);
  114.         // Modify self variable directly with the given value.
  115.         if(t(cmd, _regex.modifyDirect, function(m) { g.setValue(key, o[m[1]](c, m[2])); })) { return; }
  116.         // Modify self variable with the value of a given game variable.
  117.         if(t(cmd, _regex.modifyVariable, function(m) { g.setValue(key, o[m[1]](c, $gameVariables.value(m[2]))); })) { return; }
  118.         // Modify self variable with the value of a given self variable.
  119.         if(t(cmd, _regex.modifySelfVariable, function(m) { g.setValue(key, o[m[1]](c, g.value([key[0], key[1], m[2]]))); })) { return; }
  120.         // Modify self variable with a random number between 2 given values.
  121.         if(t(cmd, _regex.modifyRandom, function(m) { g.setValue(key, o[m[1]](c, _randomInt(m[2], m[3]))); })) { return; }
  122.         // Modify self variable with the result of a given script.
  123.         if(t(cmd, _regex.modifyScript, function(m) { g.setValue(key, o[m[1]](c, _parseInt(eval(m[2])))); })) { return; }
  124.         // Sets self variable to its absolute value (3 -> 3, -3 -> 3).
  125.         if(t(cmd, _regex.abs, function(m) { g.setValue(key, Math.abs(c)); })) { return; }
  126.     };
  127.    
  128.     /**
  129.      * If the given string matches the given regex, apply the given callback to it (supplying the match as a parameter). Returns
  130.      * true on a match and false if not.
  131.      */
  132.     var _testWithCallback = function(string, regex, callback) {
  133.         var match = regex.exec(string);
  134.         if(!match) { return false; }
  135.         callback(match);
  136.         return true;
  137.     };
  138.    
  139.     /**
  140.      * Returns a random integer between 2 given values (both inclusive).
  141.      */
  142.     var _randomInt = function(min, max) {
  143.         min = _parseInt(min), max = _parseInt(max);
  144.         return Math.floor(Math.random() * (max - min + 1)) + min;
  145.     }
  146.    
  147.     /**
  148.      * A faster alternative to using parseInt(); Performance a bit-wise right shift by zero. Other alternatives would be double
  149.      * bit-wise not (~~value) or implicit conversion (+value), although the last one needs an additional Math.floor().
  150.      */
  151.     var _parseInt = function(value) { return value >> 0; };
  152.    
  153.     /**
  154.      * Creates a key pointing to the current event of the given Game_Interpreter instance and the given variable.
  155.      */
  156.     var _createKey = function(interpreter, key) { return [interpreter._mapId, interpreter._eventId, key]; };
  157.    
  158.     //=============================================================================
  159.     // class Game_SelfVariables
  160.     //=============================================================================    
  161.    
  162.     /**
  163.      * This is basically a copy of Game_SelfSwitches, mixed with Game_Variables for correct value handling.
  164.      */
  165.     function Game_SelfVariables() { this.initialize.apply(this, arguments); };
  166.     (function($) {
  167.        
  168.         $.prototype.initialize = function() { this.clear(); };
  169.        
  170.         $.prototype.clear = function() { this._data = {}; };
  171.        
  172.         $.prototype.value = function(key) { return this._data[key] || 0; };
  173.        
  174.         $.prototype.setValue = function(key, value) { value = _parseInt(value); this._data[key] = value; this.onChange(); };
  175.        
  176.         $.prototype.onChange = function() { $gameMap.requestRefresh(); };
  177.        
  178.         /**
  179.          * Returns a self variable of the current event. Called from a Game_Interpreter as "$gameSelfVariables.get(this, 'A')".
  180.          */
  181.         $.prototype.get = function(interpreter, key) { return this.value(_createKey(interpreter, key)); };
  182.        
  183.         /**
  184.          * Sets a self variable of the current event, Called from a Game_Interpreter as "$gameSelfVariables.set(this, 'A', 1);
  185.          */
  186.         $.prototype.set = function(interpreter, key, value) { this.setValue(_createKey(interpreter, key), value); };
  187.        
  188.     })(Game_SelfVariables);
  189.    
  190.     //=============================================================================
  191.     // class Game_Interpreter
  192.     //=============================================================================
  193.    
  194.     (function($) {
  195.        
  196.         /**
  197.          * Creates a key pointing to the current event and the given variable.
  198.          */
  199.         $.prototype._iavra_selfVariables_createKey = function(key) { return [this._mapId, this._eventId, key]; }
  200.        
  201.         /**
  202.          * When our plugin command matches, extract the first argument as key and join the rest together, so it can be matched. Only
  203.          * call the original function, if our command doesn't match (performance reasons).
  204.          */
  205.         $.prototype._iavra_selfVariables_pluginCommand = $.prototype.pluginCommand;
  206.         $.prototype.pluginCommand = function(command, args) {
  207.             if(command === _pluginCommand) {
  208.                 _handleCommand(_createKey(this, args.shift()), args.join(' '));
  209.                 return;
  210.             }
  211.             this._iavra_selfVariables_pluginCommand(command, args);
  212.         };
  213.        
  214.     })(Game_Interpreter);
  215.    
  216.     //=============================================================================
  217.     // module DataManager
  218.     //=============================================================================
  219.    
  220.     /**
  221.      * Create, save and load our container object together with all other game objects.
  222.      */
  223.     (function($) {
  224.        
  225.         $._iavra_selfVariables_createGameObjects = $.createGameObjects;
  226.         $.createGameObjects = function() {
  227.             this._iavra_selfVariables_createGameObjects();
  228.             window[_containerName] = new Game_SelfVariables();
  229.         };
  230.        
  231.         $._iavra_selfVariables_makeSaveContents = $.makeSaveContents;
  232.         $.makeSaveContents = function() {
  233.             var contents = this._iavra_selfVariables_makeSaveContents();
  234.             contents._iavra_selfVariables = window[_containerName];
  235.             return contents;
  236.         };
  237.        
  238.         $._iavra_selfVariables_extractSaveContents = $.extractSaveContents;
  239.         $.extractSaveContents = function(contents) {
  240.             this._iavra_selfVariables_extractSaveContents(contents);
  241.             window[_containerName] = contents._iavra_selfVariables;
  242.         };
  243.        
  244.     })(DataManager);
  245.    
  246.     //=============================================================================
  247.     // export
  248.     //=============================================================================
  249.    
  250.     /**
  251.      * Export our class, so load/save can work correctly.
  252.      */
  253.     window.Game_SelfVariables = Game_SelfVariables;
  254.    
  255. })();
Add Comment
Please, Sign In to add comment