A statement is one entry of a label in your script: a line of text like 'show scene forest', or an object like { 'Choice': { … } }. An action is the class that runs one kind of statement. 'show scene forest' is run by the Scene action, { 'Choice': { … } } by the Choice action, and a line of dialog by the Dialog action.

You can add actions of your own to give your script new words. This page writes a first one, explains how the engine matches statements to actions, and how to register and replace them. The next pages go deeper:

  • Action Life Cycle: every method the engine calls on an action, waiting for the player, and reporting mistakes.
  • Going Back and Saving: actions that leave something on screen, and how they undo it when the player goes back and rebuild it when a save is loaded.

How the engine picks an action

Each time the game reaches a statement, the engine asks its registered actions, in order, whether they handle it, and runs the first one that says yes:

flowchart LR statement["A statement<br/>'flash 200'"] --> match{"The first action whose<br/>matchString() or matchObject()<br/>returns true"} match --> instance["new Flash(['flash', '200'])"] instance --> run["willApply() → apply() → didApply()"] run -->|"{ advance: true }"| next(["The next statement runs"]) run -->|"{ advance: false }"| wait(["The game waits for the player"])

The Dialog action is last in the list and takes every string statement no other action claimed. That’s why a line your actions don’t recognize shows up as dialog. A function in the script matches no action: the engine calls it itself (see JavaScript Functions).

Write your first action

This action makes the game screen flash white for a moment. In the script it’s written 'flash', or 'flash 500' for a flash that lasts 500 milliseconds.

Add it to js/main.js, above the $_ready(…) call (see Where your code goes):

class Flash extends Monogatari.Action {
  static id = 'Flash';

  // A string statement arrives split at its spaces: 'flash 500' is ['flash', '500'].
  static matchString([keyword]) {
    return keyword === 'flash';
  }

  // The constructor gets the same words. Read what you need into fields.
  constructor([keyword, duration]) {
    super();
    this.duration = parseInt(duration, 10) || 300;
  }

  async apply() {
    const gameScreen = this.engine.element().find('[data-screen="game"]');

    gameScreen.style('filter', 'brightness(3)');

    await new Promise((resolve) => {
      setTimeout(resolve, this.duration);
    });

    gameScreen.style('filter', '');
  }

  // Go on to the next statement once the flash is over.
  async didApply() {
    return { advance: true };
  }

  // When the player goes back past this statement, keep going back.
  async didRevert() {
    return { advance: true, step: true };
  }
}

monogatari.registerAction(Flash);

Then use it in js/script.js:

monogatari.script({
  'Start': [
    'show scene nightLight',
    'The lights flicker.',
    'flash 200',
    'What was that?',
    'end',
  ],
});

Start the game and click past “The lights flicker.”: the game screen flashes white for a fifth of a second, then “What was that?” appears. Press Back in the quick menu and “The lights flicker.” shows again, without a second flash.

The Palacio de Bellas Artes at night, washed out almost to white, with the text box brightened behind the line "The lights flicker."
The game screen in the middle of a 'flash 1500'

Two methods decide how the game moves through the statement:

  • didApply() returns { advance: true }, so the next statement runs as soon as the flash is over. An action that should stop and wait for a click, as dialog does, returns { advance: false }, which is also what it gets if it leaves didApply() out.
  • didRevert() returns { advance: true, step: true }, so going back passes over the flash and stops at the line before it. Without it, the first press of Back lands on the flash statement itself, nothing on screen changes, and the player has to press Back a second time. Going Back and Saving explains both values.

The flash is over before the player can save or go back, so this action needs nothing more. An action that leaves something on screen, like a badge or an image, also has to remove it when the player goes back and show it again when a save is loaded: that’s Going Back and Saving.

Matching statements

An action says which statements it runs with two static methods. The engine calls matchString() for string statements and matchObject() for object statements; the base class’s versions of both return false.

Method It receives Return
static matchString(words) A string statement split into words at its spaces, after its {{variables}} were replaced by their values: 'flash {{time}}' arrives as ['flash', '200'] when the time variable is 200. true when the action runs it.
static matchObject(statement) An object statement, as written in the script. true when the action runs it.

One class can have both. This version of the Flash action also runs { 'Flash': { 'Duration': 500 } }:

class Flash extends Monogatari.Action {
  static id = 'Flash';

  static matchString([keyword]) {
    return keyword === 'flash';
  }

  static matchObject(statement) {
    return typeof statement.Flash !== 'undefined';
  }

  // The words of a string statement, or the object of an object statement.
  constructor(statement) {
    super();

    const duration = Array.isArray(statement) ? statement[1] : statement.Flash.Duration;

    this.duration = parseInt(duration, 10) || 300;
  }

  // apply(), didApply() and didRevert() as before
}

WARNING

Your action is asked before every built-in action, Dialog included. A matchString() that only checks the first word takes every line that starts with it: with the Flash action above, the narration line 'flash floods are common here' flashes the screen instead of showing. Pick a first word that won’t start a sentence in your script, or match more strictly. And never match a word a built-in action uses, like show or play, unless you mean to take its statements over.

A stricter matcher, for 'flash' and 'flash 500' but nothing else:

static matchString([keyword, duration, ...rest]) {
  return keyword === 'flash' && rest.length === 0 && (typeof duration === 'undefined' || /^\d+$/.test(duration));
}

The constructor

When an action matches, the engine creates an instance with the statement as its argument: a string statement’s words, or the object statement. Read what you need into fields.

  • this.engine, this._statement and this._cycle already work in the constructor. this._extras doesn’t: the engine sets it right after the constructor returns.
  • The engine creates an instance both to run a statement and to undo it when the player goes back, so the constructor runs in both cases. Keep it to reading the statement: leave changes to the page for apply(), and report problems with the statement in willApply(), which only runs when the statement is played. A dialog opened from the constructor would open again every time the player goes back over the statement.

Registering an action

monogatari.registerAction(Flash);

Register your actions before monogatari.init() runs: in js/main.js above $_ready(…), or in a file index.html loads before js/main.js. monogatari.init() runs the mounting methods (setup(), bind(), init()) of every action registered by then. An action registered later still matches statements, but its mounting methods never run.

registerAction() puts the action at the front of the list, ahead of every built-in action and of the actions you registered before it. So among your own actions, the one registered last is asked first.

It takes a second argument, true, which puts the action at the end of the list instead, behind the Dialog action. Don’t use it for an action with string statements: the Dialog action takes every string statement first, so 'flash 200' shows up as a line of dialog. An action that only matches object statements still works there.

Finding and removing actions

Every action needs a static id of its own. An action without one keeps the base class’s id, 'Action'.

Call What it does
monogatari.action('Flash') The registered action class with that id, in any letter case, or undefined.
monogatari.actions() Every registered action, in the order the engine asks them.
monogatari.unregisterAction('Flash') Removes the action with that id, in any letter case. Do it before monogatari.init(), so its mounting methods don’t run.

Changing a built-in action

monogatari.action() gives you a built-in action’s class, so you can extend it and register your version in its place. This version of the Jump action also records, in the game’s storage, every label the player has jumped to, for a chapter list or an achievement:

const Jump = monogatari.action('Jump');

class RememberingJump extends Jump {
  async apply() {
    const visited = this.engine.storage('visited');

    if (!visited.includes(this.label)) {
      this.engine.storage({ visited: [...visited, this.label] });
    }

    await super.apply();
  }
}

monogatari.unregisterAction('Jump');
monogatari.registerAction(RememberingJump);

Give the variable its starting value in js/storage.js, next to the ones already there:

monogatari.storage({
  player: {
    name: '',
  },
  visited: [],
});

After 'jump Library' runs, monogatari.storage('visited') is ['Library'], and the game is in the Library label as before.

  • RememberingJump inherits everything it doesn’t write: the id 'Jump', the matcher, the constructor, and the methods that undo a jump.
  • this.label comes from the Jump action’s constructor. Read the built-in action’s source (src/actions/Jump.ts in the engine’s code) before you extend it, to know the fields and methods it has.
  • unregisterAction('Jump') takes the built-in one out, so the game doesn’t have two actions with the same id.

Reference

Static properties

Property Type Default What it’s for
id string 'Action' The action’s unique id, for monogatari.action() and monogatari.unregisterAction().
blocking boolean false A flag for your own shouldProceed() to read while the action waits for the player. The engine itself never reads it. See Waiting for the player.
loadingOrder number 0 When the action’s onLoad() runs after a save is loaded: in groups of equal loadingOrder, each group once the one before it finished, lower numbers first. Before 2.9.0 the engine sorted them as text, so 10 came before 2.
_experimental boolean false When true, the engine leaves the action out of monogatari.actions(), and so never runs it, unless the ExperimentalFeatures setting is true.
_configuration object {} Settings for the action, read and written with configuration(). Declare static _configuration = {}; in your class so it doesn’t share the base class’s object.
engine engine The engine, set by registerAction(). Inside a static method it’s this.engine.

Static methods

Method What it does
configuration(object) Merges object into the action’s settings.
configuration('key') Returns the setting key.
configuration() Returns every setting.

The game-event methods (setup(), shouldProceed(), onLoad() and the others) are on Action Life Cycle.

Instance properties

Property What it holds
this.engine The engine, the same as the class’s engine.
this._statement The statement exactly as written in the script, before its {{variables}} were replaced: 'flash {{time}}'. Already set in the constructor.
this._cycle 'Application' while the statement runs, 'Revert' while it’s undone.
this._extras Extra information the code that created the instance passed along; an empty object for statements the engine runs.
this.context The engine. Deprecated: use this.engine.