MV help with script

Hello, first of all I present myself. I'm Zongoyo, I'm a programmer and was looking into RPG Maker MV development for hobby.

I was trying to automatize a conversation, but I'm not being able.
The goal is make a plugin with a random conversation generator, which also includes images, transitions and flashes.

The main difficulty I've found is with transitions and flashes. Text and images work perfectly.

I'd deeply appreciate an example of a plugin with some sentences, and among them some fadeout/wait/fadein and some flashes.
Nothing overly complicated. It's just I can feel I'm not getting the setup or the syntax properly.

I also attach what I've done just in case someone could help me.


JavaScript:
/*:
 * @plugindesc Async dialogue system for RPG Maker MV/MZ
 * @author Zongoyo
 *
 * @help
 * Use morningTalk() in a script call to start the conversation
 * Use beforeDinnerTalk() in a script call to start the conversation
 * Use beforeBedTalk() in a script call to start the conversation
 * Use bedTalk() in a script call to start the conversation
 */

(() => {
    const _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;

    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args);

        if (command === 'morningTalk') {
            morningTalk.call(this);
        } else if (command === 'beforeDinnerTalk') {
            beforeDinnerTalk.call(this);
        } else if (command === 'beforeBedTalk') {
            beforeBedTalk.call(this);
        } else if (command === 'bedTalk') {
            bedTalk.call(this);
        }
    };

    async function morningTalk() {
        console.log('wip');
    };

    async function beforeDinnerTalk() {
        console.log('wip');
    };

    async function beforeBedTalk() {
        console.log('wip');
    };

    async function bedTalk() {
        try {
            await talk('Actor1', ['11111111111', '2222222222', '33333333333', '4444444444']);
            await makeFlash();
            await startTransition();
            await endTransition();
            await talk('Actor2', ['55555555', '666666666', '777777777', '888888888']);
            await showPicture(1, '4');
            await talk('Actor2', ['111', '222', '333', '444']);
            await hidePicture(1);
            await talk('Actor1', ['999', '888', '777', '666']);
        } catch (error) {
            console.error('Error in bedTalk:', error);
        }
    };

    function talk(face, messages) {
        return new Promise((resolve) => {
            $gameMessage.clear();
            $gameMessage.setFaceImage(face, 0);
            $gameMessage.setBackground(0);
            $gameMessage.setPositionType(2);
            messages.forEach(text => {
                if (text !== '') {
                    $gameMessage.add(text);
                }
            });
            const waitInterval = setInterval(() => {
                if (!$gameMessage.isBusy()) {
                    clearInterval(waitInterval);
                    resolve();
                }
            }, 10);
        });
    };

    function showPicture(pictureId, fileName) {
        return new Promise((resolve) => {
            $gameScreen.showPicture(pictureId, fileName, 0, 0, 0, 100, 100, 255, 0);
            setTimeout(() => {
                resolve();
            }, 1000);
        });
    };

    function hidePicture(pictureId) {
        return new Promise((resolve) => {
            $gameScreen.erasePicture(pictureId);
            setTimeout(() => {
                resolve();
            }, 1000);
        });
    };

    function makeFlash() {
        return new Promise((resolve) => {
            $gameScreen.startFlash([255, 255, 255, 255], 30);
            setTimeout(() => {
                resolve();
            }, 1000);
        });
    };

    function startTransition() {
        return new Promise((resolve) => {
            $gameScreen.startFadeOut(60);
            setTimeout(() => {
                resolve();
            }, 1000);
        });
    };

    function endTransition() {
        return new Promise((resolve) => {
            $gameScreen.startFadeIn(60);
            setTimeout(() => {
                resolve();
            }, 1000);
        });
    };
})();

This code is executed from a event page. I attach an image.
What is hapening with this code is: it appears the first message, when I click on the screen so it will continue the script execution, the first of the flashes happens, and then it jumps to the message after the script in the event page.
If I comment everything but talk() functions everything works ok. So I think I should need some method to synchronize the execution.

If someone can help me I'll be deeply thankful.
Have a nice week.

I've moved this thread to Learning JavaScript (from MV Plugin Releases). Thank you.

(The Learning JavaScript board is about learning to use JS in RPG Maker; Plugin Releases is where you can share finished plugins. 👋)

What is hapening with this code is: it appears the first message, when I click on the screen so it will continue the script execution, the first of the flashes happens, and then it jumps to the message after the script in the event page.
The event interpreter needs to be told to wait, e.g. using a wait mode (cf Game_Interpreter#setWaitMode, rpg_objects.js).

I notice you're using setTimeout, rather than patching relevant core script methods to integrate with the game's core update loop. If you want an effect to be "asynchronous", in RM that is usually relative to the event interpreter, i.e. "continue to the next command without waiting for this one to finish". But as you've seen, you get that for free! Once you've identified a suitable core script method to patch (maybe Game_Message#update), all you need is a function to update your process, e.g. count frames until complete then tidy up when done.

Also, I haven't thoroughly checked your code, but core MZ skips frame updates (including rendering) while the game is not in focus; core MV doesn't do this. This "skip" (based on rmmz_managers.js, SceneManager.isGameActive) will have no effect on setTimeout. Something to bear in mind when testing~
Moved to: Learning JavaScript (from MV Plugin Releases) (The Learning JavaScript board is about learning to use JS in RPG Maker; Plugin Releases is where you can share finished plugins. 👋)


The event interpreter needs to be told to wait, e.g. using a wait mode (cf Game_Interpreter#setWaitMode, rpg_objects.js).

I notice you're using setTimeout, rather than patching relevant core script methods to integrate with the game's core update loop. If you want an effect to be "asynchronous", in RM that is usually relative to the event interpreter, i.e. "continue to the next command without waiting for this one to finish". But as you've seen, you get that for free! Once you've identified a suitable core script method to patch (maybe Game_Message#update), all you need is a function to update your process, e.g. count frames until complete then tidy up when done.

Also, I haven't thoroughly checked your code, but core MZ skips frame updates (including rendering) while the game is not in focus; core MV doesn't do this. This "skip" (based on rmmz_managers.js, SceneManager.isGameActive) will have no effect on setTimeout. Something to bear in mind when testing~
Hello! First of all thank you for moving the post to it's right place 🙂

I've made it work. Now it's doing what I need.
I used this solution:

But as you say, I'm not patching relevant core methods, I'm afraid of I could break something.
If someone can tell me a more right way of doing this I'll be glad to listen.

In the meanwhile, here is the working code (using it together with the solution in the post I paste)

Code:
/*:
 * @plugindesc Async dialogue system for RPG Maker MV/MZ
 * @author Zongoyo
 *
 * @help
 * Use morningTalk() in a script call to start the conversation
 * Use beforeDinnerTalk() in a script call to start the conversation
 * Use beforeBedTalk() in a script call to start the conversation
 * Use bedTalk() in a script call to start the conversation
 */

(() => {
    const _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;

    Game_Interpreter.prototype.pluginCommand = function (command, args) {
        _Game_Interpreter_pluginCommand.call(this, command, args);

        if (command === 'morningTalk') {
            morningTalk.call(this);
        } else if (command === 'beforeDinnerTalk') {
            beforeDinnerTalk.call(this);
        } else if (command === 'beforeBedTalk') {
            beforeBedTalk.call(this);
        } else if (command === 'bedTalk') {
            bedTalk.call(this);
        }
    };

    async function morningTalk() {
        $gameVariables.setValue(83, 0);   //-> this is the variable I run a loop while it's zero with in the event page
        console.log('wip');
        $gameVariables.setValue(83, 1);    //-> after doing what is needed, I put it to 1 and the event page continues running through the loop
    };

    async function beforeDinnerTalk() {
        $gameVariables.setValue(83, 0);******
        console.log('wip');
        $gameVariables.setValue(83, 1);*****
    };

    async function beforeBedTalk() {
        $gameVariables.setValue(83, 0);********
        console.log('wip');
        $gameVariables.setValue(83, 1);********
    };

    async function bedTalk() {
        try {
            $gameVariables.setValue(83, 0);***********
            await talk('Actor1', ['11111111111', '2222222222', '33333333333', '4444444444']);
            await startTransition();
            await endTransition();
            await talk('Actor2', ['55555555', '666666666', '777777777', '888888888']);
            await makeFlash();
            await showPicture(1, '4');
            await talk('Actor2', ['111', '222', '333', '444']);
            await hidePicture(1);
            await makeFlash();
            await makeFlash();
            await makeFlash();
            await talk('Actor1', ['999', '888', '777', '666']);
        } catch (error) {
            console.error('Error in bedTalk:', error);
        }
        $gameVariables.setValue(83, 1);********
    };

    function talk(face, messages) {
        return new Promise((resolve) => {
            $gameMessage.clear();
            $gameMessage.setFaceImage(face, 0);
            $gameMessage.setBackground(0);
            $gameMessage.setPositionType(2);
            messages.forEach(text => {
                if (text !== '') {
                    $gameMessage.add(text);
                }
            });
            const waitInterval = setInterval(() => {
                if (!$gameMessage.isBusy()) {
                    clearInterval(waitInterval);
                    resolve();
                }
            }, 1);
        });
    };

    function showPicture(pictureId, fileName) {
        return new Promise((resolve) => {
            $gameScreen.showPicture(pictureId, fileName, 0, 0, 0, 100, 100, 255, 0);
            setTimeout(() => {
                resolve();
            }, 1);
        });
    };

    function hidePicture(pictureId) {
        return new Promise((resolve) => {
            $gameScreen.erasePicture(pictureId);
            setTimeout(() => {
                resolve();
            }, 1);
        });
    };

    function makeFlash() {
        return new Promise((resolve) => {
            $gameScreen.startFlash([255, 255, 255, 255], 30);
            setTimeout(() => {
                resolve();
            }, 500);
        });
    };

    function startTransition() {
        return new Promise((resolve) => {
            $gameScreen.startFadeOut(60);
            setTimeout(() => {
                resolve();
            }, 1000);
        });
    };

    function endTransition() {
        return new Promise((resolve) => {
            $gameScreen.startFadeIn(60);
            setTimeout(() => {
                resolve();
            }, 1000);
        });
    };
})();

thanks!
Just to throw it out there...this seems to be a good example of coding stuff that doesn't need to be coded.

At quick glance, everything you're doing here could be done more easily with common events.
another thing: "this.pluginCommand("bedTalk, []")" might not work (can be wrong).
but there is a plugin command option on tab 3 on the bottom below/above scriptcall.
using plugin command there with just "bedTalk" (without qoutes) will work as that is
the command you set without any arguments.
another thing: "this.pluginCommand("bedTalk, []")" might not work
It should, but it's similar to my post above - it's using code for no reason instead of the included event commands.

The entire point of coding in plugin commands is to call them using the appropriate event command; if you're going to just call it via script like that, there's no reason to make plugin commands. Simply write it like a normal function and call that.
Just to throw it out there...this seems to be a good example of coding stuff that doesn't need to be coded.

At quick glance, everything you're doing here could be done more easily with common events.
Hi! yeah, what I've done there is easy with the event editor, I know.
This was just the base for a much more complex stuff. I just needed the basic action I wanted to use to work sequencially.

But thanks for the comment!

another thing: "this.pluginCommand("bedTalk, []")" might not work (can be wrong).
but there is a plugin command option on tab 3 on the bottom below/above scriptcall.
using plugin command there with just "bedTalk" (without qoutes) will work as that is
the command you set without any arguments.
Hi!
It works, no worry. But I'll also try as you say, for make it easier.
Thanks!
Yea, I skim-read the OP initially but Turan is right: as provided this code would be much simpler as a common event.

The core scripts have many examples of wait modes. You can search your project's js/rpg_objects.js core script file for:
  • setWaitMode - used to tell the interpreter "wait for (specific thing) to end"; and
  • updateWaitMode - used to routinely check the wait mode and reset it when appropriate.
E.g. the Show Text command, Game_Interpreter#command101, calls this.setWaitMode('message') at the end. This causes the interpreter to pause until updateWaitMode returns true, which for this mode happens when the message is no longer busy.
Spoiler: a more complicated example
The balloon wait mode is effectively updated via the balloon sprite, which is a child of its character's sprite (rpg_sprites.js). The balloon sprite's update method is called every frame, ticking down its duration each time. When the duration hits zero, the balloon sprite gets removed, which prompts Sprite_Character#updateAnimation to call endBalloon on the character, signalling that the interpreter can stop waiting.
Notice how all of this makes use of the existing loop: everything updates on a 1-frame interval. Also, 1 frame is not always 1/60 second due to the fluid timestep algorithm, which exists to reduce sudden jumps in framerate (SceneManager.updateMain, rpg_managers.js). [Edit: or, more to the point, due to system resources not being able to sustain 60 fps, temporarily or otherwise.]

Using the message is actually a poor choice of placeholder for a "background" feature, because by default there's only 1 message window for all events to share, and normal player input responses are suppressed while it is busy (rpg_objects.js):
JavaScript:
Game_Player.prototype.canMove = function() {
    if ($gameMap.isEventRunning() || $gameMessage.isBusy()) {
        return false;
    }
If you want a "parallel message" kind of thing, you'd want to add a new display object (window, or sprite) for that, along with suitable structure to start/stop it when appropriate.
Yea, I skim-read the OP initially but Turan is right: as provided this code would be much simpler as a common event.

The core scripts have many examples of wait modes. You can search your project's js/rpg_objects.js core script file for:
  • setWaitMode - used to tell the interpreter "wait for (specific thing) to end"; and
  • updateWaitMode - used to routinely check the wait mode and reset it when appropriate.
E.g. the Show Text command, Game_Interpreter#command101, calls this.setWaitMode('message') at the end. This causes the interpreter to pause until updateWaitMode returns true, which for this mode happens when the message is no longer busy.
Spoiler: a more complicated example
The balloon wait mode is effectively updated via the balloon sprite, which is a child of its character's sprite (rpg_sprites.js). The balloon sprite's update method is called every frame, ticking down its duration each time. When the duration hits zero, the balloon sprite gets removed, which prompts Sprite_Character#updateAnimation to call endBalloon on the character, signalling that the interpreter can stop waiting.
Notice how all of this makes use of the existing loop: everything updates on a 1-frame interval. Also, 1 frame is not always 1/60 second due to the fluid timestep algorithm, which exists to reduce sudden jumps in framerate (SceneManager.updateMain, rpg_managers.js). [Edit: or, more to the point, due to system resources not being able to sustain 60 fps, temporarily or otherwise.]

Using the message is actually a poor choice of placeholder for a "background" feature, because by default there's only 1 message window for all events to share, and normal player input responses are suppressed while it is busy (rpg_objects.js):
JavaScript:
Game_Player.prototype.canMove = function() {
    if ($gameMap.isEventRunning() || $gameMessage.isBusy()) {
        return false;
    }
If you want a "parallel message" kind of thing, you'd want to add a new display object (window, or sprite) for that, along with suitable structure to start/stop it when appropriate.
Hello and thanks for your detailed reply.

Before making this post to do my questions I was trying different kinds of approaches and looking for info.
setWaitMode didn't work at all, but I suppose that it is because I'm not using it properly.
I didn't found any place where it stated how to use it right. Also updateWaitMode isn't clear at all, first notice I've got it exists haha.
Those commands (command101, etc.) haven't found any information about them, but I've seen something in some posts, but again, nothing clear.
I just found a google doc with a table with the commands I've ended up using.

What I need is a way of adding events made by me (with random selections from lists to archieve a more vivid conversation, which random changes each time) to set them between the events in the event pages events.
For example, a new day starts, so I put some common events, but then, I add this script inside(because doing what I'm doing with page events is not possible because I need complex conditions inside the IFs, and the use of Random, and arrays)

Also in my search I didn't found a clear way of using this scripts without a plugin, all the info I found is messy and different in each place, anyway, I'm using a lot of constants for the common states, so having everything inside one single text file seems easier for my requirements, so I'll keep the plugin set up, unless you tell me a clear situation in which it if clearly harmful.

Thanks for all the help! ^__^
Another approach I'd recommend is creating the events with code and running those. I've explained more about how it works in this thread.
RPG Maker's event pcode is not really designed to be human-readable: it's short-form data created by the editor to be interpreted by the game's scripts. That means working with it is usually quite awkward, as seen in the thread Mac linked.

But...
(because doing what I'm doing with page events is not possible because I need complex conditions inside the IFs, and the use of Random, and arrays)
I'm not sure I see how this requires you to create chains of event commands using scripting?
  • Complex conditions: you can nest branches, or use the Script field of Conditional Branch.
  • Randomness: you can use Control Variables -> Set -> Random to store a random integer, then branch based on that.
  • Arrays: if this is for choosing dialogue, you could put each conversation in its own branch and roll a random value to select one.
Just mentioning this stuff in case it turns out that there's an easier way to achieve your goal~
Hello, thanks for your answer.
Without detailed documentation on those commands, the easier way if what I'm already doing.
But thanks! 🙂
Haha, that's standard programming/javascript terminology. There's plenty of documentation if you look up any of those terms
the easier way if what I'm already doing.
sometimes, the easiest way can break stuff, it's more how it will run in the long run.
as it mostly works in the start, in the long run it can break.

better coding and better structure provides more stability so it can work in the long run 🙂

I love easy ways, but it breaks in the long run (sometimes) depending on the plugin and function.

Original thread: https://forums.rpgmakerweb.com/threads/help-with-script.173321/