I've been learning RPG Maker MV scripting and I must say the power of bind and async/await cannot be overstated.
I should note that none of the code below is well tested; it's only for example purposes. I have reason to believe it works, as it was taken from working code and variable and function names were adapted to clarify their purposes as examples, but keep in mind this code is provided only to demonstrate the principles behind it, and is not intended as an out-of-the-box solution. Maybe I'll develop it more and turn it into a plugin one day, but today is not that day. For now, these are just my thoughts in code form.
Bind
The following code demonstrates the usefulness of bind.
This greatly simplifies monkey-patching methods. You know that thing plugins always do that looks like this?
Dedicated monkeyPatch and protoPatch methods can simplify that code to this:
Async/await
A recent MV JS engine upgrade incidentally introduced async/await support. If you're like me, you were somewhat disappointed that the move from Ruby to JS saw MV do away with Fiber.yield, in favor of Game_Interpreter's much less powerful wait mode feature, that can only make Game_Interpreter itself wait, and cannot induce a wait in the already-eval'd script that you're making Game_Interpreter wait from. Well, async/await basically brings Fiber.yield back.
First we need to introduce a new manually controlled wait mode that will make Game_Interpreter wait indefinitely until setWaitMode is called again from an external source.
Add simple async utility methods...
... for waiting for a number of ticks:
... for waiting for an arbitrary condition:
... for waiting on async code from an event page context:
Add some methods for doing simple eventing from within a script or plugin, such as...
... displaying messages:
... displaying menus:
... setting move routes:
And now we have magic!
I should note that none of the code below is well tested; it's only for example purposes. I have reason to believe it works, as it was taken from working code and variable and function names were adapted to clarify their purposes as examples, but keep in mind this code is provided only to demonstrate the principles behind it, and is not intended as an out-of-the-box solution. Maybe I'll develop it more and turn it into a plugin one day, but today is not that day. For now, these are just my thoughts in code form.
Bind
The following code demonstrates the usefulness of bind.
Code:
var MP = {}; // stands for MyPlugin
// (but conveniently also stands for monkeyPatch)
// [EDIT: Fixed this method; persistently binding newImplementation to object was not a good idea.]
MP.monkeyPatch = function (object, methodName, newImplementation) {
let oldImplementation = object[methodName];
object[methodName] = function () {
return newImplementation.bind(this, oldImplementation.bind(this)).apply(this, arguments);
}
};
MP.protoPatch = function (klass, methodName, newImplementation) {
MP.monkeyPatch(klass.prototype, methodName, newImplementation);
};
This greatly simplifies monkey-patching methods. You know that thing plugins always do that looks like this?
Code:
// example of how it's usually done
MP.Game_Actor_foo = Game_Actor.prototype.foo;
Game_Actor.prototype.foo = function (bar, baz) {
MP.Game_Actor_foo.call(this, bar, baz);
// insert override-specific code here
};
Dedicated monkeyPatch and protoPatch methods can simplify that code to this:
Code:
MP.protoPatch(Game_Actor, 'foo', function (oldFoo, bar, baz) {
oldFoo(bar, baz); // don't need .call(this)
// insert override-specific code here
});
Async/await
A recent MV JS engine upgrade incidentally introduced async/await support. If you're like me, you were somewhat disappointed that the move from Ruby to JS saw MV do away with Fiber.yield, in favor of Game_Interpreter's much less powerful wait mode feature, that can only make Game_Interpreter itself wait, and cannot induce a wait in the already-eval'd script that you're making Game_Interpreter wait from. Well, async/await basically brings Fiber.yield back.
First we need to introduce a new manually controlled wait mode that will make Game_Interpreter wait indefinitely until setWaitMode is called again from an external source.
Code:
MP.protoPatch(
Game_Interpreter, 'updateWaitMode',
function (old) {
return this._waitMode == 'manual' || old();
}
);
Add simple async utility methods...
... for waiting for a number of ticks:
Code:
MP.wait = function (n) {
return new Promise((x) => setTimeout(x, n*1000/60));
};
... for waiting for an arbitrary condition:
Code:
MP.waitFor = async function (f, n = 1) {
while (!f()) {
await MP.wait(n);
}
};
... for waiting on async code from an event page context:
Code:
Game_Interpreter.prototype.await = async function (p) {
this.setWaitMode('manual');
await p;
this.setWaitMode('');
};
Add some methods for doing simple eventing from within a script or plugin, such as...
... displaying messages:
Code:
MP.msg = async function (text) {
// allow text or array of text
if (text instanceof Array) {
text = text.join("\n");
} else {
// remove indentation from multiline strings
text = text.split("\n").map((s) => s.trim()).join("\n");
}
// show it
$gameMessage.add(text);
// THE CRUCIAL PIECE:
// IF CALLED WITH AWAIT,
// do not return UNTIL the message is dismissed
await MP.waitFor(() => !$gameMessage.isBusy());
};
... displaying menus:
Code:
MP.menu = async function (choices) {
// 0: put cursor on first option
// -2: branch on cancel
$gameMessage.setChoices(choices, 0, -2);
// return the option chosen
return choices[
// THE CRUCIAL PIECE:
// IF CALLED WITH AWAIT,
// do not return the option chosen
// UNTIL the option is chosen
await new Promise(
(x) => $gameMessage.setChoiceCallback(x)
)
] || false; // false will be returned on cancel
};
... setting move routes:
Code:
MP.setMoveRoute = async function (e, route) {
// allow text or array of text
if (!(route instanceof Array)) {
route = route.split("\n");
}
// convert array of command strings
// into array of actual commands
let wait = true; // wait for move completion (default yes)
let skip = false; // skip if cannot move (default no)
route = route.concat(['end']).map((command) => {
// extract params if there are any
command = command.split(':');
command = {
code: command[0],
params: command[1] || ''
};
// convert the command code to underscores + all caps
command.code = command.code
.split(' ').filter((s) => !!s).join('_').toUpperCase();
// identify commands that are actually move route flags
if (command.code == "[DON'T_WAIT]") {
wait = false;
return null;
} else if (command.code == "[SKIP]") {
skip = true;
return null;
}
// lookup the command code
command.code = Game_Character['ROUTE_' + command.code];
// skip invalid commands
if (command.code === undefined) {
return null;
}
// split and eval params
command.params = command.params
.split(' ').filter((s) => !!s).map(eval);
// finally force move route
e.forceMoveRoute({
list: route,
wait: wait,
repeat: false,
skippable: skip
});
// THE CRUCIAL PIECE:
// IF CALLED WITH AWAIT,
// do not return UNTIL the character is finished
// executing the move route
if (wait) {
await MP.waitFor(() => !e.isMoveRouteForcing());
}
}).filter((command) => !!command);
};
And now we have magic!
Code:
MP.myComplexEventSequence = function (interpreter) {
// ^ call from an event page with MP.myComplexEventSequence(this)
let thisEvent = $gameMap.event(interpreter._eventId);
interpreter.await(async () => {
await MP.message("I will wait for 60 frames after saying this");
await MP.wait(60);
let choice;
do {
await MP.message("How should I move?");
choice = await MP.menu([
"Go in a circle",
"Go in a different circle",
"Let's dance"
]);
if (choice == "Go in a circle") {
await MP.setMoveRoute(thisEvent, `
through on
move up
move left
move down
move right
through off
turn toward
`);
} else if (choice == "Go in a different circle") {
await MP.setMoveRoute(thisEvent, `
through on
move up
move right
move down
move left
through off
turn toward
`);
} else if (choice == "Let's dance") {
await MP.setMoveRoute($gamePlayer, `
through on
move forward
move right
move down
turn left
`);
await MP.setMoveRoute(thisEvent, `
turn right
`);
await MP.wait(30);
await MP.setMoveRoute($gamePlayer, `
[don't wait]
dir fix on
move up
dir fix off
turn down
dir fix on
move left
dir fix off
turn right
dir fix on
move down
dir fix off
turn up
dir fix on
move right
dir fix off
turn left
`);
await MP.setMoveRoute(thisEvent, `
dir fix on
move down
dir fix off
turn up
dir fix on
move right
dir fix off
turn left
dir fix on
move up
dir fix off
turn down
dir fix on
move left
dir fix off
turn right
`);
await MP.setMoveRoute($gamePlayer, `
move up
move left
through off
`);
await MP.msg(
"Now we are stacked on top of each other."
);
await MP.msg(
`There was not a more convenient way
to make sure you didn't wind up
stuck on an impassable tile.`
);
await MP.msg(
`From the context it kinda looks
like we're kissing lol`
);
break;
}
} while (choice);
});
};