Easy Activity Skills Storage (V0.1)

Working on adding my own special skills for a game in RPG Maker, and I thought it may be good to add what ive done for the EXP/Level of special skills (such as mining, woodcutting and smithing; which is also the default). This just stores EXP, as levels are not really needed to be stored and just need a function to properly convert them (later will be updated with the levels functions; so that levels can be calculated and with similar difficulty options as RPG Maker). I am no genius, nor master, at Javascript- so please point out any error or problems.

First thing required in order to run the skills is to initialize it. I left this freely open so that they can be reinitialized at will (clear and reset). Simply call the plugin command
Code:
"playerSkills initialize"
, and it sets it up for you. Skills themselves are setup manually in the Plugins Manager, which are held in a list of a struct. Skills hold only Name, EXP, Level, and LevelRate. level/rate are not used yet, but soon to be. I left the "$gameSystem.playerSkills[]" list to be keyed by the skill's 'name.toLowerCase()" for being easier to grab and hard to mess up (Example:
Code:
$gameSystem.playerSkills["mining"] == String("MiNinG").toLowerCase()

All the base functions are added straight to $gameSystem with a simple numonic of [action][PlayerSkills][Extra], so it will be hard to clash with anything and is simpler to remember. And example is [get][PlayerSkills][EXP], which specifically will return the numerical value of the desired skill- if possible. I don't know if people prefer alerts over console.log or simple gameMessage; but my error reporting is sticking with console.log for now and in the future will return default skill object with the name "error" and "-1" for numerical values. I tried to create a method to grab event id to make it easier to debug, but the attempts failed (still on my first 2 weeks of RPG Maker MV).


update v0.1.3:
  • Added levels and recalculating levels
  • Levels are simple calculations of [baseEXP] x ([level ^ levelRate)]
  • levelRate is added to Skills. This defines how hard of a change there is in required exp per level.
  • levelRate represents how much exp is available for said skill. More abundant resource of exp for said skill should require a much higher levelRate to make skills advance at a more similar or difficult rate. levelRate is suggested, but not required, to be between 1.00 and 2.00
  • added cheap square root function at bottom to make things slightly more easier to read.
  • baseEXP defines the base level of how much exp is required and there is. higher number equals more exp required per level.
Here is the code itself:
PHP:
//=============================================================================
// Extra Player Skills v0.1.3
//=============================================================================

/*~struct~Skill:
 * @param name
 * @type text
 * @default mining
 *
 * @param level
 * @type number
 * @default 1
 *
 * @param exp
 * @type number
 * @default 1
 *
 * @param levelRate
 * @type number
 * @default 1
 *
 * @param baseEXP
 * @type number
 * @default 1000
 */

/*:
 * @plugindesc Background Skill Data
 * @author GrimOfDoom
 * @help Provides extra skill information for any use
 *
 * @param playerSkills
 * @type struct<Skill>[]
 * @desc Player Skills are located here :D
 */

(function() {
    var params = PluginManager.parameters("Skills");
    //====================================================Script Commands, need to be redone to support more features
  
    var PlayerSkills_interpreter = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function(command, args) {
        PlayerSkills_interpreter.call(this, command, args);
        if(command === "playerSkills"){
            switch(args[0]){
                case 'add':
                    $gameSystem.addPlayerSkillEXP(args[1], args[2]);
                    break;
                case 'get':
                    $gameMessage.getPlayerSkillEXP(args[1]);
                    break;
                case 'read':
                    $gameSystem.readPlayerSkillEXP(args[1]);
                    break;
                case 'readLevel':
                    $gameSystem.readPlayerSkillLevel(args[1]);
                    break;
                case 'initialize':
                    $gameSystem.initializePlayerSkills();
                    break;
                case 'recalc':
                    $gameSystem.recalcPlayerSkillLevel(args[1]);
                    break;
                default:
                    console.log(args[1] + " is not a playerSkill command")
                    break;
            }
        }
    };
    //=================================================================Functions used by Commands

    Game_System.prototype.addPlayerSkillEXP = function (skill, exp){
        skill = prepareString(skill);
        exp = Number(exp);
        if (this.playerSkills[skill] === undefined){
            console.log( skill + " cannot be found");
        } else {
            this.playerSkills[skill].exp += exp;
            this.recalcPlayerSkillLevel(skill);
        }
    }

    Game_System.prototype.getPlayerSkill = function(skill){
        skill = prepareString(skill);
        if (this.playerSkills[skill] === undefined){
            console.log( skill + " cannot be found");
        } else {
            return this.playerSkills[skill];
        }
    }

    Game_System.prototype.readPlayerSkillEXP = function(skill){
        $gameMessage.add(skill + " has " + this.getPlayerSkill(skill).exp + " exp");
    }

    Game_System.prototype.getPlayerSkillEXP = function(skill){
        skill = prepareString(skill);
        var fSkill = this.getPlayerSkill(skill);
        return fSkill.exp;
    }

    Game_System.prototype.addPlayerSkillLevel = function(skill, level){
        skill = prepareString(skill);
        level = Number(level);
        if (this.playerSkills[skill] === undefined){
            console.log(skill + " does not exist in playerSkills");
        } else {
            this.playerSkills[skill].level += level;
        }
    }

    Game_System.prototype.getPlayerSkillLevel = function(skill){
        skill = prepareString(skill);
        if (this.playerSkills[skill] === undefined){
            console.log(skill + " does not exist in playerSkills");
        } else {
            return this.playerSkills[skill].level;
        }
    }

    Game_System.prototype.setPlayerSkillLevel = function(skill, level){
        skill = prepareString(skill);
        if (this.playerSkills[skill] === undefined){
            console.log(skill + " does not exist in playerSkills");
        } else {
            this.playerSkills[skill].level = level;
        }
    }

    Game_System.prototype.readPlayerSkillLevel = function (skill){
        skill = prepareString(skill);
        if (this.playerSkills[skill] === undefined){
            console.log(skill + " does not exist in playerSkills");
        } else {
            $gameMessage.add(skill + " is at level " + this.playerSkills[skill].level);
        }
    }

    Game_System.prototype.initializePlayerSkills = function(){
        this.playerSkills = {};
        var skillList = JSON.parse(params["playerSkills"]);
        for (skill in skillList){
            newSkill = JSON.parse(skillList[skill]);
            newSkill.name = prepareString(newSkill.name);
            newSkill.exp = Number(newSkill.exp);
            newSkill.level = Number(newSkill.level);
            newSkill.levelRate = Number(newSkill.levelRate);
            newSkill.baseEXP = Number(newSkill.baseEXP);
            this.playerSkills[newSkill.name] = newSkill;
        }
    }

    Game_System.prototype.recalcPlayerSkillLevel = function (skill){
        var fSkill = this.getPlayerSkill(skill);
        this.setPlayerSkillLevel(skill,Math.round(squirt((fSkill.exp / fSkill.baseEXP), fSkill.levelRate)));
    }

    //====================================================================Side helpful functions

    prepareString = function(message){
        message = String(message)
        message = message.toLowerCase();
        return message;
    }

    squirt = function(g, n) {
        return Math.pow(g, 1/n );
    }
})();

levels are VERY linear. I am not the best at math and could not figure out how to turn the information I gathered into recreated the method that RP Maker uses in Parameter Curves. If you have a suggestion on a change for that, please tell.
First of all, I think it's awesome that you are creating this for yourself.
Even if you're just beginning, doing something like this which is directly for your project (and very satisfying... when it finally works!) will help you learn like crazy. Plus, it's usually better than using someone else's plugin because you can make it exactly what you need and your game is more unique.

Now for advice:
Consider changing your functions to add to an existing prototype rather than be new global functions. If you add the function to the Game_System prototype then you can use it from $gameSystem (the $gameSystem variable inherits properties from the Game_System prototype). This will also allow it to use the "this" keyword in a meaningful way.

Spoiler: Before
Code:
   function initialize_playerSkills(){
       $gameSystem.playerSkills = {};
       var skillList = JSON.parse(params['skillList']);
       for(skill in skillList){
           $gameSystem.playerSkills[skillList[skill]] = 1;
           //$gameMessage.add([skillList[skill]] + ":" + $gameSystem.playerSkills[skillList[skill]] + ";");
       }
   }

Spoiler: After
PHP:
Game_System.prototype.initializePlayerSkills = function() {
    this.playerSkills = {};
    var skillList = JSON.parse(params['skillList']);
    for(skill in skillList){
        this.playerSkills[skillList[skill]] = 1;
    }
};

Then you would change the plugin command part from "initialize_playerSkills()" to "$gameSystem.initializePlayerSkills()"

If the "Smithing" skill is tied to any particular actor, then consider making these functions within Game_Actor instead.
Or if it is associated with the party in general, then you could make it within Game_Party.

(clearly noob here, but I don't even know how I can use this outside of plugin command; for instance, in an event, check if "level"(converted from exp) is high enough to enter house)

You have the gist already, but you need to learn about the return keyword.

Spoiler: Before
Code:
   function read_PlayerSkill(skill){
       skill = String(skill);
       if ($gameSystem.playerSkills[skill] === undefined){
           eventErrorPost(skill + " is not a listed skill")
       } else {
           $gameMessage.add(skill + " has " + $gameSystem.playerSkills[skill] + "EXP" );
       }
   }

Spoiler: After
PHP:
   Game_System.prototype.readPlayerSkill(skill){
       return this.playerSkills[skill];
   };

In an Event Conditional Branch, on the last tab is a 'script' section. Your event could be:
IF: $gameSystem.readPlayerSkill("Smithing") > 100
Let them in the house
ELSE:
Don't let them in the house


Last advice is to think about the data structure from a general perspective. Just do console.log($gameSystem.playerSkills) from the console (press F8 during playtest) and look at it. It will look like this:
{Smithing: 100, Mining: 59, Woodcutting: 30}

That's probably fine for now, but it will get confusing when you want to do levels in addition to exp. You'll have to add more properties to the object to track the level.
{Smithing: 100, SmithingLevel: 4, Mining: 59, MiningLevel: 3, Woodcutting: 30, WoodcuttingLevel: 2}

Alternatively, consider making each skill an object within an array. This will be harder at first to learn how to access the data but will likely be better in the future if you scale up or add more features.
PHP:
[
{name: "Smithing", exp: 100, level: 4}
{name: "Mining", exp: 59, level: 3}
{name: "Woodcutting", exp: 30, level: 2}
]
I originally did not start with using objects (and item list instead) because I just did not yet understand the struct type for parameters yet. I do have to look into it still; I do not necessarily want to add level to the struct, but it will make it easier in the production later on for being able to manipulate that before loading into the game. I don't want to add "level" because it just does a load more time calculating the level every time exp is added than just grabbing it whenever level is needed (very minor, I know, but ive seen some limits on Javascript first hand and don't want to hit them).

Thanks for the information on making the functions of the "Game_System" rather than their own.
well, trying to switch the process over to Game_System, however parsing the parameter struct (that I finally figured out) causes an unexpected error. I don't know if the method I am using, which is the same for everything else, is wrong- but I seam to be incapable of finding anything(or much) on google about parameter structs in the first place.

Code:
//=============================================================================
// Extra Player Skills v0.1
//=============================================================================

/*~struct~Skill:
 * @param name
 * @type text
 * @default mining
 *
 * @param Level
 * @type number
 * @default 1
 *
 * @param exp
 * @type number
 * @default 0
 */

/*:
 * @plugindesc Background Skill Data
 * @author GrimOfDoom
 * @help Provides extra skill information and skill saving
 *
 * @param skillList
 * @type text[]
 * @desc Skills List
 * @default ["Mining","Smithing","Woodcutting"]
 *
 * @param playerSkills
 * @type struct<Skill>[]
 * @desc Struct Test with Skill
 */


(function() {
    var params = PluginManager.parameters("Skills");
    //====================================================Script Commands
   

    var PlayerSkills_interpreter = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function(command, args) {
        PlayerSkills_interpreter.call(this, command, args);
        if(command === "playerSkills"){
            switch(args[0]){
                case 'add':
                    playerSkills_addEXP(args[1], args[2]);
                    break;
                case 'read':
                    read_PlayerSkill(args[1]);
                    break;
                case 'initialize':
                    $gameSystem.initializePlayerSkills();
                    break;
                case 'grab':
                    return grab_PlayerSkillsEXP(args[1]);
                    break;
                default:
                    eventErrorPost("The command '" + command + "' is not a playerSkills command");
                    break;
            }
        }
    };






    //=================================================================Functions used by Commands

    function playerSkills_addEXP(skill, exp){
        skill = String(skill);
        exp = Number(exp);
        if ($gameSystem.playerSkills[skill] === undefined){
            eventErrorPost(skill + " could not be found in playerSkills");
        } else {
            $gameSystem.playerSkills[skill] += exp;
        }
    }

    function initialize_playerSkills(){
        $gameSystem.playerSkills = {};
        var skillList = JSON.parse(params['skillList']);
        for(skill in skillList){
            $gameSystem.playerSkills[skillList[skill]] = 1;
            $gameMessage.add([skillList[skill]] + ":" + $gameSystem.playerSkills[skillList[skill]] + ";");
        }
    }

    function read_PlayerSkill(skill){
        skill = String(skill);
        if ($gameSystem.playerSkills[skill] === undefined){
            eventErrorPost(skill + " is not a listed skill")
        } else {
            $gameMessage.add(skill + " has " + $gameSystem.playerSkills[skill] + "EXP" );
        }
    }

    function grab_PlayerSkillsEXP(skill){
        skill = String(skill);
        if ($gameSystem.playerSkills[skill] === undefined){
            eventErrorPost(skill + " is not a listed skill");
        } else {
            return $gameSystem.playerSkills[skill];
        }
    }

    Game_System.prototype.initializePlayerSkills = function(){
        this.playerSkills = {};
        var skillList = JSON.parse(params["playerSkills"]);
        for (skill in skillList){
            skillList[skill].name = skillList[skill].name.toLowerCase();
            this.playerSkills[skillList[skill].name] = skill;
        }
    }




    //====================================================================Side helpful functions

    function eventErrorPost(errorMessage){
        //this._eventId gives "undefined". FIX THIS LATER!!!!
        $gameMessage.add("[" + this._eventId + "] " + errorMessage);
    }
})();
OK, so you created the Plugin Parameter playerSkills , which is an array of objects because of the type you added:
@type struct<Skill>[] <-- array of objects

Here is a good reference on the plugin parameters, but it doesn't directly answer the question that you have here.

You have to use JSON.parse twice to totally de-stringify the plugin parameter in this case.
  1. It starts as a big long messy string - use JSON.parse to get a
  2. Array of individual messy strings, then use JSON.parse (on each one) to get a
  3. Array of structured objects
Near the top of your code, add the following console.log lines and I think you will be able to figure out what is happening.
Code:
(function() {
   var params = PluginManager.parameters("Skills");
    console.log(params);   // <-- This will show all of the plugin parameters
    console.log(params["playerSkills"]);  // <-- This is totally messy! It's just a big string. We can't do anything with this yet.
    var arrayOfMessyStrings = JSON.parse(params["playerSkills"]);
    console.log(arrayOfMessyStrings); //  <-- Better, at least it is an array now. But each element is still just a string with no structure.
    var arrayOfObjects = [];
    for (var i = 0; i < arrayOfMessyStrings.length; i++) {
        arrayOfObjects.push(JSON.parse(arrayOfMessyStrings[i]));
    }
    console.log(arrayOfObjects); //  <-- Ahh, that's nice. Now we can do stuff with this!
   //====================================================Script Commands

Now we can simplify the initializing function too.
Code:
Game_System.prototype.initializePlayerSkills = function(){
    this.playerSkills = arrayOfObjects;
    console.log("Successfully initialized skills");
};


Here's an example of how you can access the data now!

Code:
Game_System.prototype.tellMeTheExpOfThisSkill = function(skillName) {
    for (var i = 0; i < this.playerSkills.length; i++) {
        if(this.playerSkills[i].name === skillName) return this.playerSkills[i].exp;
    }
};

In the console, you can try something like this:
$gameSystem.tellMeTheExpOfThisSkill("smithing");


Obviously you can rename the functions and variables.
The thing is, the initial parse doesn't even work. It fails with an unexpected token (which I realize is not what I wrote, which I though I did). Eventually, after a load of searching; I found out that 'n' error meant that there weren't quotes around the string- turns out, the parameters I originally set didn't even exist anymore (must not have hit apply in the plugin manager). I did not know that I needed to parse for each object; I figured the basic "one and done" is all it needed.

With some editing and fixing to that, I was able to come up with this for initialization. Although I think I will stick with my system of "grab by key" instead of looping the list to find what is needed. I have no idea if your method is more professional than mine (all my skills in programming are in C# and C++ with unreal and unity), but is it just what I think would work best personally.


Code:
    Game_System.prototype.initializePlayerSkills = function(){
        this.playerSkills = {};
        var skillList = JSON.parse(params["playerSkills"]);
        for (skill in skillList){
            newSkill = JSON.parse(skillList[skill]);
            newSkill.name = newSkill.name.toLowerCase();
            this.playerSkills[newSkill.name] = newSkill;
        }
    }

once I update the old bits out to fit this newer format of 'struct' over simple array, ill update it at the top.
I have no idea if your method is more professional than mine (all my skills in programming are in C# and C++ with unreal and unity), but is it just what I think would work best personally.
Fair enough, the best code is code that works. I doubt there is any performance difference in either method.

Another idea to hold the skill data is nested objects, for example:
PHP:
{
"smithing"    : {"exp": 1, "level": 1},
"mining"      : {"exp": 200, "level": 4},
"woodcutting" : {"exp": 50, "level": 2}
}
Then to get the mining experience, it is just:
$gameSystem.playerSkills.mining.exp

If you create the structures as Plugin Parameters, you would still have to parse it recursively because of how the editor saves the Plugin Parameters. This is if you want to set the starting exp and level of each skill in the Plugin Parameters.

Alternatively, if you can always assume that the starting exp and level of all skills are the same (for example, starting exp = 0 and starting level = 1), then no parsing needed:

Code:
Game_System.prototype.initializePlayerSkills = function() {
    var listOfSkillNames = ["smithing", "mining", "woodworking"];  //Could make this a Plugin Parameter, @type text[]
    var initialExp = 0;
    var initialLevel = 1;
    this.playerSkills = {};
    for (var i = 0; i < listOfSkillNames.length; i++){
        this.playerSkills[listOfSkillNames[i]] = {};
        this.playerSkills[listOfSkillNames[i]].exp = initialExp;
        this.playerSkills[listOfSkillNames[i]].level = initialLevel;
    }
};
I did think of nesting more, but I was a bit lazy and just went with what works for now. As for all the starting stuff, I left it as is so that I can set them myself for development purposes. Also, the var1 = Number(var1) was because some things were reading as string even though they were set as Number in parameter and initialization; just makes things work a little better I guess?
The Plugin Parameters always are read as strings initially, no matter what type they are. Even boolean like true and false are read like "true" and "false". As the plugin developer, you have to convert them yourself. The Plugin Parameter type is only for convenience inside the editor itself.

Original thread: https://forums.rpgmakerweb.com/threads/easy-activity-skills-storage-v0-1.89475/