RPG Maker MV
CXJ Core v1.3.0

This script powers most of the scripts I've written. In most cases, the use of this script is optional, as I'll always try to find a fallback, but it does make things a bit less complicated.

Download (21.49 kB, 13 times downloaded)

Just put this script as high as possible, but preferably below any and all other core scripts, due to the nature of this script. You can also use this library for your own projects.

All functions are accessible through the CXJScripts.CXJCore namespace by default. You can always change this, either by altering the settings, or by essentially set it as the value of a variable in case you're writing your own plugin that's using this as a basis.

Note that certain core scripts might share the same functionality as this script. In such cases, the functionality of these core scripts take precedence.

Plugin parameters

Namespace

This allows you to set a custom namespace for the plugin to load from. This can be especially useful when running certain commands from event scripts and the likes, although they're a lot less useful for custom scripts.

Basic functions

CXJScripts.CXJCore.getParameters(pluginName, defaultParameters)

This retrieves the parameters for the current plugin. It essentially is an extension to the existing PluginManager function. First, it calls PluginManager.parameters to retrieve the parameters in the old-fashioned way. If it can't find the parameters, it falls back to document.currentScript, which essentially gets the current script file name. This does not work on Internet Explorer, so as a final resort it checks all settings for each plugin and compares it to the object given in defaultParameters. If it finds a complete match, it'll return these parameters. Finally, if it still fails to find the plugin settings, it will use the defaultParameters object as the parameters.

Arguments:

pluginNameThe name of the plugin
defaultParametersThe default parameters

Returns: An object containing every parameter, or defaultParameters if it can't find it.


CXJScripts.CXJCore.checkVersion(module, minVersion, maxVersion)

This checks the version of a dependent plugin.

Arguments:

module

The module name as a string
This is essentially the object. For example, for CXJ Core, the value would be CXJScripts.CXJCore. If it can't find the object, it searches inside the Imported object, and takes the version number there.

Normally it would take the version number from the version property of the plugin object, however, if the version number is stored somewhere else, you can directly reference that instead.

minVersionThe minimum version
maxVersionoptional The maximum version

Returns: true if the plugin is the correct version, false otherwise.


CXJScripts.CXJCore.addPluginCommand(command, func)

Adds a plugin command. The command is executed from the Game_Interpreter, meaning that the keyword this will refer to the Game_Interpreter.

Example:

CXJScripts.CXJCore.addPluginCommand("HelloWorld", function(args) {
    console.log("Hello World!");
    console.log(args);
});

Arguments:

commandThe command that's being used
func

The function being executed
The function that's being executed only takes one parameter, args.


CXJScripts.CXJCore.addWaitMode(waitMode, waitFunc)

Adds a wait mode. This is mainly used to pause event execution until the current event command has finished.

Example:

CXJScripts.CXJCore.addWaitMode("HelloWorld", function() {
    return false; // Done waiting
});

Arguments:

waitModeThe wait mode name
waitFunc

The function
It returns a boolean, where true means it needs to wait, and false means it's done executing.


CXJScripts.CXJCore.addMessageCode(code, func)

Adds a message code. Message codes can also contain parameters. Make sure you use square brackets to define parameters.

Example:

CXJScripts.CXJCore.addMessageCode("helloworld[:any]", function() {
    return arguments[1]; // Done waiting
});

Arguments:

codeThe message code
You can also define parameters. To make it simple, you can use :any to match any string, :num to match an integer and :id to match a string consisting of only alphanumeric numbers and underscores.
func

The function
It returns a string to replace the message code with.

Download CXJ Core v1.0.0 (10.07 kB, 10 times downloaded)

Download CXJ Core v1.0.1 (10.57 kB, 10 times downloaded)

Download CXJ Core v1.1.0 (13.71 kB, 9 times downloaded)

Download CXJ Core v1.2.0 (16.36 kB, 10 times downloaded)

Download CXJ Core v1.2.1 (18.58 kB, 3 times downloaded)

/******************************************************************************
 * CXJ_CXJCore.js                                                             *
 ******************************************************************************
 * CXJ Core v1.3.0                                                            *
 * By G.A.M. Kertopermono, a.k.a. GaryCXJk                                    *
 ******************************************************************************
 * License: ISC                                                               *
 ******************************************************************************
 * Copyright (c) 2017, G.A.M. Kertopermono                                    *
 *                                                                            *
 * Permission to use, copy, modify, and/or distribute this software for any   *
 * purpose with or without fee is hereby granted, provided that the above     *
 * copyright notice and this permission notice appear in all copies.          *
 *                                                                            *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES   *
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF           *
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR    *
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES     *
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN      *
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR *
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.                *
 ******************************************************************************/

/*:
 * @plugindesc The core script that powers most of the other CXJ scripts
 * @author G.A.M. Kertopermono
 *
 * @param Namespace
 * @desc Sets the namespace from which the functions are accessible.
 * @default 
 * 
 * @param Override PluginManager.parameters
 * @desc Override the original parameters function?
 * @type boolean
 * @on Override
 * @off Don't override
 * @default false
 * 
 * @param Modify Game_Interpreter
 * @desc Add functions to Game_Interpreter that manipulate it?
 * @type boolean
 * @on Yes
 * @off No
 * @default false
 *
 * @help
 * ============================================================================
 * = About                                                                    =
 * ============================================================================
 *
 * This script powers most of the scripts I've written. In most cases, the use
 * of this script is optional, as I'll always try to find a fallback, but it
 * does make things a bit less complicated.
 *
 * ============================================================================
 * = Usage                                                                    =
 * ============================================================================
 *
 * Just put this script as high as possible, but preferably below any and all
 * other core scripts, due to the nature of this script. You can also use this
 * library for your own projects.
 *
 * All functions are accessible through the CXJScripts.CXJCore namespace
 * by default. You can always change this, either by altering the settings,
 * or by essentially set it as the value of a variable in case you're writing
 * your own plugin that's using this as a basis.
 * 
 * Note that certain core scripts might share the same functionality as this
 * script. In such cases, the functionality of these core scripts take
 * precedence.
 *
 * ----------------------------------------------------------------------------
 * - Plugin parameters                                                        -
 * ----------------------------------------------------------------------------
 *
 * Namespace
 *
 * This allows you to set a custom namespace for the plugin to load from. This
 * can be especially useful when running certain commands from event scripts
 * and the likes, although they're a lot less useful for custom scripts.
 *
 * ----------------------------------------------------------------------------
 * - Basic functions                                                          -
 * ----------------------------------------------------------------------------
 *
 * CXJScripts.CXJCore.getParameters(pluginName, defaultParameters)
 *
 * This retrieves the parameters for the current plugin. It essentially is an
 * extension to the existing PluginManager function. First, it calls
 * PluginManager.parameters to retrieve the parameters in the old-fashioned
 * way. If it can't find the parameters, it falls back to
 * document.currentScript, which essentially gets the current script file
 * name. This does not work on Internet Explorer, so as a final resort it
 * checks all settings for each plugin and compares it to the object given in
 * defaultParameters. If it finds a complete match, it'll return these
 * parameters. Finally, if it still fails to find the plugin settings, it will
 * use the defaultParameters object as the parameters.
 *
 * Arguments:
 *
 * pluginName        - The name of the plugin
 * defaultParameters - The default parameters
 *
 * Returns:
 *
 * An object containing every parameter, or defaultParameters if it can't find
 * it.
 * 
 * ---
 * 
 * CXJScripts.CXJCore.checkVersion(module, minVersion, maxVersion)
 * 
 * This checks the version of a dependent plugin.
 * 
 * Arguments:
 * 
 * module     - The module name as a string
 *              This is essentially the object. For example, for CXJ Core,
 *              the value would be CXJScripts.CXJCore. If it can't find the
 *              object, it searches inside the Imported object, and takes
 *              the version number there.
 *              
 *              Normally it would take the version number from the version
 *              property of the plugin object, however, if the version number
 *              is stored somewhere else, you can directly reference that
 *              instead.
 * minVersion - The minimum version
 * maxVersion - (optional) The maximum version
 * 
 * Returns:
 *
 * true if the plugin is the correct version, false otherwise.
 * 
 * ---
 * 
 * CXJScripts.CXJCore.addPluginCommand(command, func)
 *
 * Adds a plugin command. The command is executed from the Game_Interpreter,
 * meaning that the keyword this will refer to the Game_Interpereter.
 * 
 * Example:
 * 
 * CXJScripts.CXJCore.addPluginCommand("HelloWorld", function(args) {
 *     console.log("Hello World!");
 *     console.log(args);
 * });
 * 
 * Arguments:
 * 
 * command - The command that's being used
 * func    - The function being executed
 *           The function that's being executed only takes one parameter, args.
 *
 * Will be overridden by:
 * 
 * * WAY_Core
 *
 * ---
 * 
 * CXJScripts.CXJCore.addWaitMode(waitMode, waitFunc)
 * 
 * Adds a wait mode. This is mainly used to pause event execution until the
 * current event command has finished.
 * 
 * Example:
 * 
 * CXJScripts.CXJCore.addWaitMode("HelloWorld", function() {
 *     return false; // Done waiting
 * });
 * 
 * Arguments:
 * 
 * waitMode - The wait mode name
 * waitFunc - The function
 *            It returns a boolean, where true means it needs to wait, and false
 *            means it's done executing.
 *
 * ---
 * 
 * CXJScripts.CXJCore.addMessageCode(code, func)
 * 
 * Adds a message code. Message codes can also contain parameters. Make sure you
 * use square brackets to define parameters.
 * 
 * Example:
 * 
 * CXJScripts.CXJCore.addMessageCode("helloworld[:any]", function() {
 *     return arguments[1]; // Done waiting
 * });
 * 
 * Arguments:
 * code - The message code
 *        You can also define parameters. To make it simple, you can use :any to
 *        match any string, :num to match an integer and :id to match a string
 *        consisting of only alphanumeric numbers and underscores.
 * func - The function
 *        It returns a string to replace the message code with.
 *
 * ============================================================================
 * = Compatibility                                                            =
 * ============================================================================
 * 
 * This plugin does not overwrite default functionality.
 *
 * ============================================================================
 * = Changelog                                                                =
 * ============================================================================
 *
 * 1.3.0 (2017-10-17)
 * 
 * * Adds a function to add message codes
 * * Adds compatibility to WAY_Core
 *
 * 1.2.1 (2017-08-27)
 * 
 * * Adds a function to add wait modes
 *
 * 1.2.0 (2017-08-27)
 * 
 * * Adds a function to add plugin commands
 * 
 * 1.1.0 (2017-08-26)
 * 
 * * Adds a version checker
 * * Fixed Namespace functionality
 * 
 * 1.0.1 (2017-08-26)
 * ------------------
 * 
 * * Adds the option to override PluginManager.parameters
 * 
 * 1.0.0 (2017-07-15)
 * ------------------
 *
 * * Initial release
 *
 * ============================================================================
 * = License                                                                  =
 * ============================================================================
 *
 * Copyright (c) 2017, G.A.M. Kertopermono
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * ============================================================================
 */

// If it doesn't already exist, create a new CXJScripts object.
var CXJScripts = CXJScripts || {};

// Sets variables for the dependency check
var Imported = Imported || {};

+function(_) {
    // Creates the CXJCore object and attaches it to the main CXJScripts object
    var CXJCore = {};
    _.CXJCore = CXJCore;
    
    CXJCore.version = '1.3.0';

    /* ------------------------------------------------------------------------
     * - PRIVATE FUNCTIONS                                                    -
     * ------------------------------------------------------------------------ 
     */

    /* Checks plugin content */
    var _checkPluginContent = function(parameters) {
        for(var prop in parameters) {
            if(parameters.hasOwnProperty(prop)) {
                return true;
            }
        }
        return false;
    }
    
    /* Function for message codes */
    var _setMessageCode = function(code) {
        code = code.replace(/\[(.+?)\]/, '\[$1\]');
        code = code.replace(/\:any/,'(.+?)');
        code = code.replace(/\:num/,'([0-9]+)');
        code = code.replace(/\:id/,'([0-9a-zA-Z_])');
        return code;
    }
    
    /* ------------------------------------------------------------------------
     * - PRIVATE VARIABLES                                                    -
     * ------------------------------------------------------------------------
     */
    
    var _pluginCommands = {};     // Holds all plugin commands
    var _waitModes = {};          // Holds all wait modes
    var _messageCodeConvert = []; // Holds all message codes on convert
    
    // Object to store which core exists for certain functions
    var _coreExists = {
        pluginCommand: ''
    }
    
    /* ------------------------------------------------------------------------
     * - ALIASES                                                              -
     * ------------------------------------------------------------------------
     */
    
    CXJCore.old = {
        pluginManagerParameters: PluginManager.parameters,
        gameInterpreterPluginCommand: Game_Interpreter.prototype.pluginCommand,
        gameInterpreterUpdateWaitMode: Game_Interpreter.prototype.updateWaitMode,
        windowBaseConvertEscapeCharacters: Window_Base.prototype.convertEscapeCharacters
    }
    
    /**
     * Gets the current script's parameters.
     * When the script's name is renamed, it tries various fallbacks before
     * defaulting to the default parameters given.
     */
    CXJCore.getParameters = function(pluginName, defaultParams) {
        // Use the default RPG Maker MV plugin manager
        var parameters = CXJCore.old.pluginManagerParameters(pluginName);
        
        if(_checkPluginContent(parameters)) {
            return parameters;
        }
        
        // Use currentScript (doesn't work on Internet Explorer)
        if(document.currentScript) {
            var scriptName = document.currentScript.src;
            scriptName = scriptName.substr(scriptName.indexOf('/plugins/') + 9);
            scriptName = scriptName.substr(0, scriptName.lastIndexOf('.js'));
            parameters = CXJCore.old.pluginManagerParameters(scriptName);
            return parameters;
        }
        
        // Iterate through each defined script
        for(var idx = 0; idx < $plugins.length; idx++) {
            var plugin = $plugins[idx];
            var params = plugin.parameters;
            
            // If the description contains the plugin name, this is the guy
            if(plugin.description.indexOf('<' + pluginName + '>') > -1) {
                return params;
            }
            
            /* Check each parameter of the plugin, if all are present in the
               defaultParams parameter, this is the script */
            var hasFound = true;
            var propNames = Object.keys(defaultParams);
            for(var idx = 0; idx < propNames.length; idx++) {
                if(!params.hasOwnProperty(propNames[idx])) {
                    hasFound = false;
                    break;
                }
            }
            if(hasFound) {
                return params;
            }
        }
        
        // Return the default parameters
        return defaultParams;
    }
    
    /**
     * Checks whether the dependent plugin has the correct version
     */
    CXJCore.checkVersion = function(module, minVersion, maxVersion) {
        // If maxVersion is not set, set it to -1 (no limit)
        if(!maxVersion && maxVersion !== 0) {
            maxVersion = -1;
        }
        // Splits the module name into an array
        module = module.split('.');
        
        // The base object to find the module in
        var elem = window;
        var version = null;
        
        // Searches if the element exists
        for(var idx = 0; idx < module.length; idx++) {
            var sub = module[idx];
            if(!elem[sub]) {
                elem = null;
                break;
            }
            elem = elem[sub];
        }
        
        // Sets the version number of the module
        if(!elem) {
            if(Imported[module]) {
                version = (Imported[module] + '').split('.');
            }
        } else if(elem instanceof Object) {
            version = (elem.version + '').split('.');
        } else {
            // In case the version number is stored elsewhere, this can
            // be directly referenced
            version = (elem + '').split('.');
        }
        // Check the version with the minimum and maximum version number
        if(version) {
            if(!Array.isArray(minVersion)) {
                minVersion = (minVersion + '').split('.');
            }
            if(maxVersion !== -1 && !Array.isArray(maxVersion)) {
                maxVersion = (maxVersion + '').split('.');
            }
            for(var idx = 0; idx < version.length; idx++) {
                if(idx >= minVersion.length) {
                    continue;
                }
                if(version[idx] < minVersion[idx]) {
                    return false;
                }
                if(maxVersion !== -1) {
                    if(idx >= maxVersion.length) {
                        continue;
                    }
                    if(version[idx] > maxVersion[idx]) {
                        return false;
                    }
                }
            }
        }
        return false;
    }
    
    /**
     * Easy function to add new plugin commands
     */
    if(Imported['WAY_Core'] && PluginManager.addCommand) {
        CXJCore.addPluginCommand = PluginManager.addCommand;
        _coreExists.pluginCommand = 'WAY_Core';
    } else {
        CXJCore.addPluginCommand = function(command, func) {
            _pluginCommands[command] = func;
        }
    }
    
    /**
     * Easy function to add new wait modes
     */
    CXJCore.addWaitMode = function(waitMode, waitFunc) {
        _waitModes[waitMode] = waitFunc;
    }
    
    /**
     * Easy function to add new message codes
     */
    CXJCore.addMessageCode = function(code, func) {
        var data = [_setMessageCode(code), func];
        _messageCodeConvert.push(data);
    }
    
    // Initialization
    +function() {
        // Default parameters
        var defaultParameters = {
            'Namespace': '',
            'Override PluginManager.parameters': false,
            'Modify Game_Interpreter': false
        };
        
        var parameters = CXJCore.getParameters('CXJ_CXJCore', defaultParameters);
        
        /* Namespace
         * Sets CXJCore to a different namespace.
         */
        if(parameters['Namespace'].trim()) {
            var subNamespaces = parameters['Namespace'].trim().split('.');
            var elem = window;
            for(var idx = 0; idx < subNamespaces.length; idx++) {
                var subNamespace = subNamespaces[idx];
                if(!elem[subNamespace]) {
                    elem[subNamespace] = {};
                }
                elem = elem[subNamespace];
            }
            for(var prop in CXJCore) {
                if(CXJCore.hasOwnProperty(prop)) {
                    elem[prop] = CXJCore[prop];
                }
            }
        }
        
        /* Override PluginManager.parameters
         * Overrides the original PluginManager.parameters function with the
         * CXJCore one.
         */
        if(parameters['Override PluginManager.parameters']) {
            PluginManager.parameters = CXJCore.getParameters;
        }
        
        /* --------------------------------------------------------------------
         * - Game_Interpereter.prototype.pluginCommand (Override)             -
         * --------------------------------------------------------------------
         */
        if(!_coreExists.pluginCommand) {
            Game_Interpreter.prototype.pluginCommand = function(command, args) {
                if(_pluginCommands.hasOwnProperty(command)) {
                    _pluginCommands[command].call(this, args);
                } else {
                    CXJCore.old.gameInterpreterPluginCommand.call(this, command, args);
                }
            }
        }
        
        /* --------------------------------------------------------------------
         * - Game_Interpereter.prototype.updateWaitMode (Override)            -
         * --------------------------------------------------------------------
         */
        
        Game_Interpereter.prototype.updateWaitMode = function() {
            if(_waitModes.hasOwnProperty(this._waitMode)) {
                var waiting = _waitModes[this._waitMode].call(this);
                if(!waiting) {
                    this._waitMode = '';
                }
                return waiting;
            } else {
                return CXJCore.old.gameInterpreterUpdateWaitMode.call(this);
            }
        }
        
        /* --------------------------------------------------------------------
         * - Window_Base.prototype.convertEscapeCharacters (Override)         -
         * --------------------------------------------------------------------
         */
        
        Window_Base.prototype.convertEscapeCharacters = function(text) {
            text = CXJCore.old.windowBaseConvertEscapeCharacters.call(this, text);
            for(var idx = 0; idx < _messageCodeConvert.length; idx++) {
                var data = _messageCodeConvert[idx];
                text = text.replace(new RegExp('\x1b' + data[0], 'gi'), data[1].bind(text));
            }
            return text;
        }
        
        /* --------------------------------------------------------------------
         * - Game_Interpreter.prototype.addPluginCommand (New)                -
         * --------------------------------------------------------------------
         */
        if(parameters['Modify Game_Interpreter']) {
            Game_Interpreter.prototype.addPluginCommand = CXJCore.addPluginCommand;
            Game_Interpreter.prototype.addWaitMode = CXJCore.addWaitMode;
        }
    }();
    
}(CXJScripts);                                

Creator: GaryCXJk

Release date: 2017-07-15

Last updated: 2017-10-17

Downloads: 13

License: ISC License

Optional compatibility: