MZ Please help scripting dice-roll of "traits" for actors

Hi,

I'm experimenting with "dice-rolling" like D&D. As a result of the dice rolling, I want it to affect the "traits" for getting percentage multipliers on ATK, DEF, MAT, MDF, SPD and LUK. So for example if you were to roll 3d6 (three six-sided dice) for stats, this will result in a 30% to 180% multiplier for each of the stat.

The protagonist (actor 1) already has traits for each of the parameters set, at 100%. So after staring at the script call reference, I thought that the following might work:

$dataActors[1].traits[0].value1 = ((Math.randomInt(6)+1) + (Math.randomInt(6)+1) + (Math.randomInt(6)+1)) / 3;
(the idea being that it results in a value between 0.3 and 1.8);

It doesn't... or, more precisely, it does update the values because console.log shows the results of the dice rolls for $dataActors[1].traits[0].value1 ~ $dataActors[1].traits[5].value1... it just isn't the traits I was thinking. Any idea how the numbering of the traits is done internally?
First, note that this sort of thing should be implemented as a plugin. If you do it via script call, then you'll have problems, because the changes:
  • Will reset when the session ends (i.e. when the game app/page is closed);
  • Won't automatically reset on new/load game;
  • Won't be included in save data.
Also, since this topic is kind of technical code-wise:

I've moved this thread to Learning JavaScript (from MZ Support). Thank you.

$dataActors[1].traits is an array of trait data objects already present on the actor. One type of trait may have different properties from another type.

You're assuming that actor ID 1 has at least 6 traits, and you are scaling the first 6 traits of that actor. It may be simpler to just add the traits instead, e.g. by patching the traitObjects method of Game_Actor to add a new "param scale" trait source.

By default the Param Rate traits are combined as follows (rmmz_objects.js):
Spoiler: rmmz_objects.js - paramRate
JavaScript:
Game_BattlerBase.prototype.traitsPi = function(code, id) {
    return this.traitsWithId(code, id).reduce((r, trait) => r * trait.value, 1);
};

Game_BattlerBase.prototype.paramRate = function(paramId) {
    return this.traitsPi(Game_BattlerBase.TRAIT_PARAM, paramId);
};
So we see that the property is named value in this case, not value1.

(Personally for stat rolls I would consider an additive bonus rather than a multiplier, but it's your game.)
Hi,

Thank as always, much appreciated. I got it to work with the following:

JavaScript:
$dataActors[1].traits[0].value = ((Math.randomInt(6)+1) + (Math.randomInt(6)+1) + (Math.randomInt(6)+1))/10;
//through to
$dataActors[1].traits[5].value = ((Math.randomInt(6)+1) + (Math.randomInt(6)+1) + (Math.randomInt(6)+1))/10;

First, note that this sort of thing should be implemented as a plugin. If you do it via script call, then you'll have problems, because the changes:
  • Will reset when the session ends (i.e. when the game app/page is closed);
  • Won't automatically reset on new/load game;
  • Won't be included in save data.
I can't reproduce the "won't be included in save data" part. It seems to overwrite the values afaict. Closing the app and reloading the save (made after the dice rolls) retains the rolls.
1687134888430.png


(Personally for stat rolls I would consider an additive bonus rather than a multiplier, but it's your game.)
I have the damage calculations and stuff as divisions (like a.atk/b.def *10) with HP and MP fixed at 100 regardless of level, hence the choice for multipliers. It's mostly out of academic interest if this would "work" as a game mechanic.
I can't reproduce the "won't be included in save data" part. It seems to overwrite the values afaict. Closing the app and reloading the save (made after the dice rolls) retains the rolls.
Strange. I cannot reproduce that behaviour with script calls in a project with no plugins. By default the database loads from file once, on game boot (Scene_Boot#create). Therefore any changes get reset when starting a new play session, which happens even on "soft" refresh (F5 from dev tools, as opposed to F5 from the game window). And, as mentioned, they remain if starting a new game or loading a different save during the same session.

I notice there's an input hint box at the top of your menu, so you're using at least one plugin (VisuStella?). Perhaps you have a plugin for instanced database objects, and that is somehow facilitating this result.

Or maybe you're accidentally reapplying the changes every frame, or have it set up to re-run the script call on load? Odds are that'd change the values, though, and I imagine you'd notice that.

If it works then I guess it's OK, I just thought I'd let you know that it is not normal behaviour. 👋
I can confirm that the behavior without plugins is as you describe! But I don't see anything in the plugin parameters of VS Core and Battlecore that might have "fixed" this.

In any case I've put the dice rolling part into my first ever plugin. Hello World sensation yay!

JavaScript:
function rollDice(NumberOfDice,SidesOnDice){
let DiceV = 0;
for (let i = 0; i < NumberOfDice; i++) {
DiceV += Math.randomInt(SidesOnDice)+1;
}
return DiceV;
}
Yay! In case it helps: you can remove the "may not be written for MZ" warning in the Plugin Manager by adding a @target MZ directive in a header section, e.g.
JavaScript:
/*:
 * @target MZ
 * @plugindesc description!
 * @author me!
 * @url https://forums.rpgmakerweb.com/threads/158453/
 * @help rollDice(NumberOfDice, SidesOnDice)
 */
Happy scripting~
Okay, so coming back on the stats resetting... I can confirm it happening in my project with VS BattleCore when I tested today! The weird thing is that the save file from yesterday STILL DOES contain the roll results from yesterday.

It might very well be that the traits revert back when you gain a level. Will have to do some more research, but it is in any case unstable, and as you suggested earlier will require some plumbing to permanently fix (storing the roles in $gameVariables and applying during load or after each level up might work, but feels extremely patchy...).
I'll just leave this here~
Spoiler: plugin code
JavaScript:
// ================================================== //
// ExtraTraits.js
// ================================================== //

/*:
 * @target MZ
 * @plugindesc Extra trait source: random basic param rates.
 * @author Caethyril
 * @url https://forums.rpgmakerweb.com/threads/158453/
 * @help Free to use and/or modify for any project, no credit required.
 *
 * @command Randomise Param Rates
 * @desc Rerolls random param modifiers for given actor.
 *
 * @arg Actor
 * @type actor
 * @desc Which actor to affect.
 *
 * @command Clear Random Param Rates
 * @desc Clears existing random param modifiers for given actor.
 *
 * @arg Actor
 * @type actor
 * @desc Which actor to affect.
 */
;void (() => {  // IIFE for local scope (confines "consts" & strict mode).
'use strict';
    const PLUGIN_NAME = "ExtraTraits";  // for registering plugin command/params
    const SAVE_NAME = PLUGIN_NAME;      // for storing data in save files

    // Define plugin namespace.
    const $ = globalThis[PLUGIN_NAME] ??= {};

    /**
     * @typedef {object} ParamRateTrait
     * @property {number} code `TRAIT_PARAM`
     * @property {number} dataId param ID
     * @property {number} value multiplier (`1 = 100%`)
     */

    // Trait-making function(s).
    $.makeTrait = {
        /**
         * @param {number} paramId basic parameter ID
         * @param {number} value rate value (`1 = 100%`)
         * @returns {ParamRateTrait} trait in engine format
         */
        paramRate: function(paramId, value) {
            return {
                code: Game_BattlerBase.TRAIT_PARAM,
                dataId: paramId,
                value: value
            }
        }
    };

    /** Initialises plugin data on new game. */
    $.initData = function() {
        // Include this data in saves.
        $.data = {
            /** @type {{[actorId:number]: ParamRateTrait[]}} traits for random param rates. */
            randomParamRates: {}
        };
    };

    /**
     * @param {number} faces die face count
     * @param {number} [count=1] number of dice to roll
     * @returns {number} sum of `count` rolls of a fair die numbered `1` to `faces` inclusive.
     */
    $.rollDice = function(faces = 6, count = 1) {
        let res = 0;
        for (let n = count; n--;)
            res += 1 + Math.randomInt(faces);
        return res;
    };

    // Define plugin command(s).
    $.command = new Map();
    $.command.set("Randomise Param Rates", function(args) {
        const actorId = parseInt(args.Actor, 10);
        const D = $.data.randomParamRates[actorId] = [];
        for (let n = 6; n--;)
            D[n] = $.makeTrait.paramRate(n + 2, $.rollDice(6, 3) / 10);
        $gameActors.actor(actorId)?.refresh();  // VisuStella cache compatibility
    });
    $.command.set("Clear Random Param Rates", function(args) {
        const actorId = parseInt(args.Actor, 10);
        delete $.data.randomParamRates[actorId];
        $gameActors.actor(actorId)?.refresh();  // VisuStella cache compatibility
    });

    // Register those plugin command(s).
    for (const [k, f] of $.command.entries())
        PluginManager.registerCommand(PLUGIN_NAME, k, f);

    // Sub-namespace for storing pre-patch methods.
    $.alias ??= {};

    // Include random param rate traits when appropriate.
    void (alias => {
        Game_Actor.prototype.traitObjects = function() {
            const res = alias.apply(this, arguments);
            const extra = $.data.randomParamRates[this.actorId()];
            if (extra)
                res.push({ traits: extra, note: "" });
            return res;
        };
    })($.alias.Game_Actor_traitObjects = Game_Actor.prototype.traitObjects);

    // Initialise plugin data on new/load game.
    void (alias => {
        DataManager.createGameObjects = function() {
            alias.apply(this, arguments);
            $.initData();
        };
    })($.alias.DataManager_createGameObjects = DataManager.createGameObjects);

    // Include plugin data in save files.
    void (alias => {
        DataManager.makeSaveContents = function() {
            const res = alias.apply(this, arguments);
            res[SAVE_NAME] = $.data;
            return res;
        };
    })($.alias.DataManager_makeSaveContents = DataManager.makeSaveContents);

    // Read plugin data from save files, when present.
    void (alias => {
        DataManager.extractSaveContents = function(contents) {
            alias.apply(this, arguments);
            if (contents[SAVE_NAME])
                $.data = contents[SAVE_NAME];
        };
    })($.alias.DataManager_extractSaveContents = DataManager.extractSaveContents);

})();
[Edit: added VisuStella compatibility fixes from later posts - battler refresh and trait object note field.]
What the... wow... thanks! I'm speechless! Will test it out tonight after kids have been knocked unconscious!

There are many things that are alien to me, so will need to study to understand fully what's going on ("globalThis" sounds very... mighty) but... just out of curiosity... how much time did it take for you to brew this?

EDIT: Hmmm... I'm getting a TypeError upon looking up the status screen of the character, after the roll.

Spoiler: F12 Console
Code:
rmmz_managers.js:2032 TypeError: Cannot read property 'match' of undefined
    at _0x342cce (VisuMZ_0_CoreEngine.js:8881)
    at Array.reduce (<anonymous>)
    at Game_Actor.Game_BattlerBase.<computed> [as paramPlus] (VisuMZ_0_CoreEngine.js:8881)
    at Game_Actor.paramPlus (rmmz_objects.js:4479)
    at Game_Actor.eval (eval at VisuMZ.ConvertParams (VisuMZ_0_CoreEngine.js:1), <anonymous>:6:17)
    at Game_Actor.Game_BattlerBase.<computed>.<computed> [as param] (VisuMZ_0_CoreEngine.js:8881)
    at Game_Actor.Game_BattlerBase.<computed>.<computed> [as paramValueByName] (VisuMZ_0_CoreEngine.js:8881)
    at Window_StatusParams.<computed>.<computed> [as drawItem] (VisuMZ_0_CoreEngine.js:8881)
    at Window_StatusParams.Window_Selectable.drawAllItems (rmmz_windows.js:1360)
    at Window_StatusParams.Window_Selectable.paint (rmmz_windows.js:1411)

EDIT2: Sorry, forgot to disable my own plugin. The rolls doesn't seem to be affecting stats though... will do some more dabbling.
It took me less than half an hour, but most of that (as usual) was comments and typo-correction. As I mentioned earlier, the overall design is pretty straightforward, i.e. add a new trait source and include those traits in save data. Of course, that's not easy to translate into a plugin if you're unfamiliar with the codebase!

globalThis is just a modern keyword for referencing the global object:
Could probably use window here instead with no ill effects.

I did some quick tests without any other plugins active before posting it, and it seemed OK for me. It doesn't automatically apply the randomness, though: you need to use Plugin Command -> Randomise Param Rates.

Also, as written, the plugin file should be named ExtraTraits.js; alternatively, the PLUGIN_NAME variable should be changed to match the filename. If not, then the plugin commands (and parameters, but this plugin doesn't have any of those) will not register correctly.

(Just like with everyday writing, every coder tends to have their own style. Almost none of my programming knowledge is from formal education, so I might have more strange habits than average. Hopefully the comments can demystify things a bit, though.)
Thanks! Half an hour... just wow.

I'll do some testing to figure out why exactly it's not working. I did notice the plugin command, but it still wouldn't reflect the results in the stats. Is the idea that you start out with a actor that already has traits, or one with a clean slate?

Going to test now with a clean plugin-less project.

EDIT: it's working perfectly with a plugin-free project. As mentioned there does seem to be some discrepancy in the way VS battlecore (and core?) have changed the traits saving: sometimes it is saved, at other times it is not. I think I'll first try to reproduce the resetting with the VS plugins in place.


Spoiler: SCREENSHOTS
1687350623095.png
1687350684600.png

The changes are retained upon level up...
1687351205956.png

After saving, closing app and loading it seems to be retained, but after walking around and picking up an item, it's... gone... (reverts back to the default trait settings)
1687351536995.png

Okay, so I still have no idea what exactly the trigger is for reverting... in vanilla RPGmaker, the reversion is immediate upon loading. With the VS plugins, it seems... delayed.

EDIT AGAIN: Ah, so trying to nose through the VS CoreEngine is pretty futile if you're not Lt.Cmdr data lol.
Yea, VisuStella's plugins are obfuscated, i.e. deliberately difficult to read. 😴

Maybe check out the help links on their itch page?
Will try, thanks. They don't seem that enthusiastic about solving compatibility issues with non-VS plugins, but I can always try.

I'm dependent on VS for the animated sideview enemies...

Edit: submitted. I am at their mercy now.
Just so you're aware, I think there are other plugins that support animated SV enemies, e.g.
Good luck!
Thanks, that one might actually be a little easier to combine with the 8D character generator (expensive but cool).

There recently was a thread about the game freezing upon running away when an actor change (aka summon) had occurred. Reading through the thread had me thinking the optional stats added with the VS plug-in might have something to do with it… but alas, the VS PLUG-IN is unreadable…
Yea, VisuStella's plugins are obfuscated, i.e. deliberately difficult to read. 😴

Maybe check out the help links on their itch page?
Hooray! I actually got a response! Any idea what this means?
Hello,

The report you're sending a bug report for is not a VisuStella MZ plugin. We are not responsible for plugins outside of the VisuStella MZ library.

However, all we can do is tell you the reason why: you are using parameters that are randomized. Meanwhile, the Core Engine and Battle Core caches parameter values until refreshed. There are conflicts with these two methods and the plugin you're using needs to be updated with a battler.refresh() in order to clear the cache.

This is all the help we can provide for this.

Thank you for understanding,
VisuStella
Oh, nice! That'll be worth bearing in mind when I'm writing other plugins, too, since many people use VisuStella.

Caching is generally implemented to prevent unnecessary repetition of expensive operations, like loading from files or searching/filtering arrays. The core scripts recalculate most things on-demand.

Sounds like VisuStella cache traits etc, updating the cache when the battler is refreshed. The plugin I wrote only updates the random traits via its plugin commands, so you could try adding a couple of lines to those, e.g.
JavaScript:
    $.command.set("Randomise Param Rates", function(args) {
        const actorId = parseInt(args.Actor, 10);
        const D = $.data.randomParamRates[actorId] = [];
        for (let n = 6; n--;)
            D[n] = $.makeTrait.paramRate(n + 2, $.rollDice(6, 3) / 10);
        $gameActors.actor(actorId)?.refresh();  // added (VisuStella compatibility)
    });
    $.command.set("Clear Random Param Rates", function(args) {
        const actorId = parseInt(args.Actor, 10);
        delete $.data.randomParamRates[actorId];
        $gameActors.actor(actorId)?.refresh();  // added (VisuStella compatibility)
    });
I haven't tested, but I'm assuming the refresh calls will force VisuStella to call the (patched) traitObjects method and update the associated cache. 👋
Thanks! It's now throwing the error upon running the event with the plugin parameter.
rmmz_managers.js:2032 TypeError: Cannot read property 'match' of undefined
at _0x342cce (VisuMZ_0_CoreEngine.js:8881)
at Array.reduce (<anonymous>)
at Game_Actor.Game_BattlerBase.<computed> [as paramPlus] (VisuMZ_0_CoreEngine.js:8881)
at Game_Actor.paramPlus (rmmz_objects.js:4479)
at Game_Actor.eval (eval at VisuMZ.ConvertParams (VisuMZ_0_CoreEngine.js:1), <anonymous>:6:17)
at Game_Actor.Game_BattlerBase.<computed>.<computed> [as param] (VisuMZ_0_CoreEngine.js:8881)
at Game_Actor.get (rmmz_objects.js:2443)
at Game_Actor.Game_BattlerBase.refresh (rmmz_objects.js:3052)
at Game_Actor.Game_BattlerBase.<computed>.refresh (VisuMZ_0_CoreEngine.js:8881)
at Game_Actor.Game_BattlerBase.<computed> [as refresh] (VisuMZ_1_BattleCore.js:19457)
The plugin command, right? And you started a new game? Hmm...

Oh, hang on, I think I see it. match is commonly a string-matching method, e.g. extracting tags from a note field. But I just give a trait object with one property, traits (no note). So you could try editing this part as well:
JavaScript:
    void (alias => {
        Game_Actor.prototype.traitObjects = function() {
            const res = alias.apply(this, arguments);
            const extra = $.data.randomParamRates[this.actorId()];
            if (extra)
                res.push({ traits: extra, note: "" });  // added blank note
            return res;
        };
    })($.alias.Game_Actor_traitObjects = Game_Actor.prototype.traitObjects);
Might end up needing some more properties in there. 😴
Yay, it works now! Many thanks! Also of note is that it has to be postitioned BELOW VS CoreEngine (between Core and Battlecore and after Battlecore work, just from quick testing).

The funny thing is that it doesn't seem to pick up the traits with the below:

JavaScript:
let CharParam = ["Str","Con","Int","Wis","Dex","Cha"];
let textMessage = "";
for (let k = 0; k < 6; k++) {
textMessage += CharParam[k] + ":" + $dataActors[1].traits[k].value * 10 + " ";
(k == 2) ? (textMessage += "\n"):(textMessage += "");
}
$gameMessage.add(textMessage);
this.setWaitMode('message');

1688170850849.png

Original thread: https://forums.rpgmakerweb.com/threads/please-help-scripting-dice-roll-of-traits-for-actors.158453/