JS: Show choices inside a Loop

So im trying to to use show choices inside a Loop, but it isnt quite working
For example i want these 3 Choices (Attack, Use item, Flee) and i want the player to click them again and again until the fight is over or he uses Flee to escape.

My code looks like this

While (true) {
$gameMessage.setChoices(
[
"Attack",
"Use Item",
"Flee"
],
0,
-1
);
// etc...
If Attack then code
If Use Item then code
If Flee then exit function
}


This document is telling me that i should use
Game_Interpreter.setWaitMode("message");
interpreter.setWaitMode("message");
but its not working.

Does anybody know what i need to do?


Edit: Also tried recursion, by calling the main function inside the if statements, but it seems it gets ignored.
Your problem is that a game loop is not the same as a programming loop.
your structure will never work that way, because it is missing too many other things that have to happen inside a loop like that - for example updating the display, allowing the enemy to act (instead of only the actor getting something to do) and so on.

You need to take a step back and explain us what it really is that you want to do before we can help - do you want to program your own battle system? If yes then you need to make a logic structure of what is all needed before even starting to program.
Your problem is that a game loop is not the same as a programming loop.
your structure will never work that way, because it is missing too many other things that have to happen inside a loop like that - for example updating the display, allowing the enemy to act (instead of only the actor getting something to do) and so on.

You need to take a step back and explain us what it really is that you want to do before we can help - do you want to program your own battle system? If yes then you need to make a logic structure of what is all needed before even starting to program.
Yeah i figured that they are not the same.

I basically want to recreate exactly this
1688421387102.png
I basically want to recreate exactly this
And that is still too deep into the logic.
When I wrote "take a step back" then I didn't mean one tiny step above that, I meant step back to the beginning.

What use is the structure you displayed in the event screenshot? where and when would that event be processed? That is what is needed as explanation here.
And that is still too deep into the logic.
When I wrote "take a step back" then I didn't mean one tiny step above that, I meant step back to the beginning.

What use is the structure you displayed in the event screenshot? where and when would that event be processed? That is what is needed as explanation here.
I dont know what you want from me.
And that is still too deep into the logic.
When I wrote "take a step back" then I didn't mean one tiny step above that, I meant step back to the beginning.

What use is the structure you displayed in the event screenshot? where and when would that event be processed? That is what is needed as explanation here.
I just want the js equivalent of the screenshot and i think i can take it from there
I just want the js equivalent of the screenshot and i think i can take it from there
no, you can't.

because "show choices" is an event command, NOT A JAVASCRIPT CODE.
The function calls you get from the list you linked in your first posts are calls for event commands that are executed in the event interpreter, they CANNOT be executed outside the event interpreter.

They NEVER work outside their context - that is another reason why they didn't work for you.

you'll need different code depending on the context where and when the player is supposed to answer your questions, and that is why I asked where and when you want to ask the player something.
no, you can't.

because "show choices" is an event command, NOT A JAVASCRIPT CODE.
The function calls you get from the list you linked in your first posts are calls for event commands that are executed in the event interpreter, they CANNOT be executed outside the event interpreter.

They NEVER work outside their context - that is another reason why they didn't work for you.

you'll need different code depending on the context where and when the player is supposed to answer your questions, and that is why I asked where and when you want to ask the player something.
Ah now i understand. Well its simple. You go to an Npc and the Plugin starts, if thats what you wanted to know. And i know that show choices is not JS code, but i wanted to know how to make it work inside a loop, or how the event loop works in js, so i can combine these two things together, like i can in an Event.
You say the plugin starts when you go to an NPC but your first post sounds like you want to bring up a choice loop inside a battle.
For example i want these 3 Choices (Attack, Use item, Flee) and i want the player to click them again and again until the fight is over or he uses Flee to escape.
It sounds like you could do what you want by just calling a common event from the NPC. Could you explain why that isn't an option?
Spoiler: technical
Show Choices is an event command. To make it work as usual, you need an event interpreter, i.e. an instance of Game_Interpreter. The core scripts handle 2 main interpreters (map and troop) and 1 additional map interpreter per active Parallel event. Also, when using a Plugin Command, you can reference the calling interpreter as this (assuming the command has been bound to a "full" function rather than an arrow function).

When an event interpreter gets updated (typically every frame), it processes each command in series until it reaches the end of the list or needs to wait, e.g. from the Wait command, or from Show Text/Choices (wait for message), etc.

Event commands are processed as an array of objects. To fully recreate events via scripting, you could use something along the lines of the example named "Insert Event Commands" in the Events & Interpreters section on the sheet you linked. Another option is to set up a child interpreter like the Common Event command, but either way you still need to figure out the appropriate event command parameters/indents and build an array to populate the chosen interpreter.
Do you mean a Copy Paste Code example to start testing around?
Code:
$gameMessage.setChoices(["Hello", "Test", "RPG Maker"] , 2, -1);
$gameMessage.setChoiceBackground(1);
$gameMessage.setChoicePositionType(2);
$gameMessage.setChoiceCallback(n => {
$gameVariables.setValue(1, n);
});
this.setWaitMode('message');

The Choice is saved into Variable1. Choosen Answer Number starts with 0 not 1;
Answer1 = 0, Answer2 = 1, Answer3 = 2

I hope this helps.
There are quite a few relevant JavaScript concepts that are needed to explain why you can't just do it with a while(true) loop. But in short, if you wanted to wait for player input, you'd at some point need a wait instruction, which would freeze the entire main thread (and the game with it). Instead, you'd probably want to do it with callbacks - functions that get executed after a certain thing happens. For example, continuing the snippet @Bex provided:

JavaScript:
function runLoop(interpreter){
    $gameMessage.setChoices(["Fight", "Use Item", "Flee"] , 2, -1);
    $gameMessage.setChoiceBackground(1);
    $gameMessage.setChoicePositionType(2);
    $gameMessage.setChoiceCallback(result => {
        processResult(result, interpreter);
    });
    interpreter.setWaitMode('message');
}

function processResult(result, interpreter){
    switch(result){
        case 0:
            //Code that handles "fight"
            runLoop(interpreter);
            break;
        case 1:
            //Code that handles "use item"
            runLoop(interpreter);
            break;
        case 2:
            //Code that handles "flee"
    }   
}

To use it, just execute runLoop, making sure to pass a reference to the current Game_Interpreter to it (this keyword if inside an event).
Also note that if you call this code inside an event it will proceed to whatever is after the script in the event the moment waitMode is no longer set to "message", not when it's all done - though if you're already inside an event, using built-in structures like in the screenshot you've shared is a much better idea anyway. Alternatively, have your "flee" code set a switch, and another autorun event with that switch as a condition that handles the continuation.

Of course, that simplification at the start isn't entirely true: the await keyword does exist, though you'd probably need to do a tutorial on Promises before you can use it.
the Plugin starts
but what is the function of the plugin? why does it even start before the player decides what he wants? It should only start after the player answers.

The posts above should have shown you that you cannot make "simple" loops in javascript.

A plugin needs a function or a purpose, and should always NEVER ask the player directly.

What you should do in this example is to have the NPC done as an event, using the event commands directly - and then use different plugin commands to call different parts of the plugin in the event structure itself.

But the show choiuce should never be part of the plugin, that would simply be too complex, too error prone and (in my opinion) too idiotic to do.
But the show choice should never be part of the plugin
I'd disagree - there definitely exist use cases, especially when the available choices are dynamically generated, where this is the simpler way of going about it. I don't know if whatever OP is doing fits that category, but some things definitely do.

An example, somewhat similar to OP's request (though a bit more complicated, since a simpler example wouldn't need a plugin). Consider the case of a book, which is a series of images (pages), displayed one at a time, where the player can freely move "right" and "left" among them. Except it's not a normal book, and they can also move "up" and "down", among a 2d "grid" of images. And of course at any point they can stop. So the options need to be dynamically generated; you can't move "right" if there are no further images this way. In my game, this logic is implemented with the following class:
Spoiler: A fair amount of code
JavaScript:
//===================================== Multi image display =====================================

g.MultiDisplay = function (rows, columns, wrap, filename, description, text) {
    let self = this;
    text = text || s.displayNavigation;
    let x = 0;
    let y = 0;
    let imageTexts = {};
    $gv[3] = 0; //Clear player choice

    this.moveUp = function (amount = 1) {
        if (y + amount < columns && y + amount >= 0) y += amount;
        else if (wrap) y = (y + amount) % columns;
        else console.error("Invalid operation at MultiDisplay");
    };
    this.moveDown = (amount = 1) => self.moveUp(-amount);
    this.moveRight = function (amount = 1) {
        if (x + amount < rows && x + amount >= 0) x += amount;
        else if (wrap) x = (x + amount) % rows;
        else console.error("Invalid operation at MultiDisplay");
    };
    this.moveLeft = (amount = 1) => self.moveRight(-amount);

    this.showChoices = function (inp) {
        let choices = [];

        if (wrap || y < columns - 1) choices.push(2); //Up
        if (wrap || x > 0) choices.push(0); //Left
        if (wrap || x < rows - 1) choices.push(1); //Right
        if (wrap || y > 0) choices.push(3); //Down

        textOptions = choices.map(n => text[n]);

        if (imageTexts[x + "-" + y]) {
            textOptions.push(s.copy);
            choices.push(-1);
        }

        textOptions.push(text[text.length - 1]);
        choices.push(-2); //The cancel option

        let startingOption = choices.indexOf($gv[3]); //If previously chosen option is available, it will start selected
        if (startingOption < 0) startingOption = 0; //Otherwise use the first option

        $gameMessage.setChoices(textOptions, startingOption, choices.length - 1);
        $gameMessage.setChoiceBackground(0);
        $gameMessage.setChoicePositionType(2);
        $gameMessage.setChoiceCallback(n => $gv[3] = choices[n]);
        if (description) $gameMessage.add(description);
        inp.setWaitMode('message');
    };

    this.processResponse = function (inp) {
        let choice = $gv[3];
        switch (choice) {
            case -2: break;
            case -1:
                copyTextToClipboard(imageTexts[x + "-" + y]);
                g.showMessage(inp, s.clipboardMessage);
                break;
            case 0: self.moveLeft(); break;
            case 1: self.moveRight(); break;
            case 2: self.moveUp(); break;
            case 3: self.moveDown(); break;
            default: console.error("Invalid player input for MultiDisplay: ", choice);
        }
    };

    this.showImage = function (size = 100) {
        $gameScreen.erasePicture(1);
        $gameScreen.showPicture(1, `${filename}/${filename}-${x}-${y}`, 1, 960, 375, size, size, 255, 0);
    }

    this.getCoords = () => console.log(x, y);

    this.setOptions = function (options) { text = options; };
    this.setDescription = function (desc) { description = "\\>" + desc.replaceAll('\n', '\n\\>'); };

    this.addImageText = function (x, y, text) {
        imageTexts[x + "-" + y] = text;
    }
}

And its associated common event:
Spoiler: Screenshot
RPGMV_2023-07-04_16-19-52.png

The loop is handled by an event (because that's just simpler to do), but showing choices is handled entirely with code because, again, that's just simpler to do. Somehow passing all this data upwards to the calling event (including available options and the choice that's selected at the start) would have been a lot more complicated.

I don't know what OP's actual goal is - I'm assuming they're just asking for a simple example, and want to use it to build something more complicated. So this may or may not be the right solution for them. But I'd avoid stating that something should "never be part of a plugin". In the infinite set of possibilities that are things you can do with RPG Maker there's always bound to be something which proves such statement wrong.
but what is the function of the plugin? why does it even start before the player decides what he wants? It should only start after the player answers.

The posts above should have shown you that you cannot make "simple" loops in javascript.

A plugin needs a function or a purpose, and should always NEVER ask the player directly.

What you should do in this example is to have the NPC done as an event, using the event commands directly - and then use different plugin commands to call different parts of the plugin in the event structure itself.

But the show choiuce should never be part of the plugin, that would simply be too complex, too error prone and (in my opinion) too idiotic to do.
I usually agree with you on pretty much everything, but one of the commercial games I develop for has a plugin that creates dynamic choices programmatically. 😛
Do you mean a Copy Paste Code example to start testing around?
Code:
$gameMessage.setChoices(["Hello", "Test", "RPG Maker"] , 2, -1);
$gameMessage.setChoiceBackground(1);
$gameMessage.setChoicePositionType(2);
$gameMessage.setChoiceCallback(n => {
$gameVariables.setValue(1, n);
});
this.setWaitMode('message');

The Choice is saved into Variable1. Choosen Answer Number starts with 0 not 1;
Answer1 = 0, Answer2 = 1, Answer3 = 2

I hope this helps.
Well its not like i didnt try this before. Sadly somehow this doesnt work. It always saiys, that it is not a function.

I am currently trying to use the loop inside a common Event and calling my plugin inside the loop and i think that should be good enough.
Well its not like i didnt try this before. Sadly somehow this doesnt work. It always saiys, that it is not a function.
Most likely because you called it in a context where this doesn't refer to the interpreter. In that case you'd need to replace this with a working reference to the interpreter.

I am currently trying to use the loop inside a common Event and calling my plugin inside the loop and i think that should be good enough.
That's probably the most reasonable way to do it in most cases imho.
The Snippet i posted is used in the Eventcommand - Script - It's on Page3 of the Eventcommands.
I dont know how to write it so its usable as Script Plugin.
The Snippet i posted is used in the Eventcommand - Script - It's on Page3 of the Eventcommands.
I dont know how to write it so its usable as Script Plugin.
I got it working now. Thank you all for your help.
Would be nice if you share the Syntax for that.

Original thread: https://forums.rpgmakerweb.com/threads/js-show-choices-inside-a-loop.158929/