An action that leaves something on screen, like a badge, an image or a sound that keeps playing, has three more jobs than the Flash action:

  • Undo it when the player presses Back.
  • Show it again when the player loads a save.
  • Take it away when the game ends.

Monogatari 2 doesn’t keep a copy of the screen for any of these. Each action undoes its own statements and rebuilds its own things, from what it wrote down in the game’s state and histories. This page explains where an action keeps that, what the engine does when the player goes back, and builds an action that does all three jobs.

Where an action keeps its data

Store What goes in it Saved When the player goes back When a game ends
monogatari.state() The game’s position (label, step) and what is on screen now: the scene, the characters, the images, the music. Yes The engine moves step back; every other key is put back by the action that owns it, in its revert(). step and label go back to the start; each action’s reset() puts its own keys back.
monogatari.history('name') Lists each action keeps of what it did, so it can undo it: history('image'), history('jump')… Yes Each action removes its own entries. Emptied.
monogatari.storage() The game’s variables, like {{player.name}}. Yes Not undone. Only a statement that undoes its own change puts a value back (see Storage and going back). Put back to the starting values from js/storage.js.
monogatari.global('name') Things that aren’t part of the story: timers, flags, elements to remember. No Not touched. Not touched.
  • this.engine.state({ location: '' }) merges the object into the state. this.engine.state('location') reads one key.
  • this.engine.history('location') returns that history’s array, creating an empty one the first time. Change it in place with push() and pop().
  • this.engine.global('name', value) writes a global; this.engine.global('name') reads it.

A save holds the state, every history and the storage, as they are when the player saves.

What happens when the player goes back

When the player presses Back, the engine works backwards from the statement on screen. It takes the statement before it, creates its action, and runs that instance’s three revert methods:

  1. willRevert(): checks. Throw or reject when the statement can’t be undone.
  2. revert(): undo what apply() did.
  3. didRevert(): return { advance, step }, which says what the engine does next.
didRevert() returns The engine Use it for
{ advance: true, step: true } Moves the position back to this statement, then undoes the one before it too. A statement that moved on by itself: show scene, play music, the Flash action.
{ advance: false, step: true } Moves the position back to this statement and stops there. A statement the player stops at, which revert() shows again: a line of dialog, a message, the Continue button. This is what the base class returns.
step: false Leaves the position where revert() put it. Statements that set the position themselves; the Jump action uses it.

So going back from a line of dialog undoes, one by one, every statement that ran by itself after the line before, until it reaches that line, which shows itself again and stops:

flowchart LR back(["Back pressed on<br/>'The park next door is quiet.'"]) --> location["Undo 'location Alameda Central'<br/>{ advance: true, step: true }"] location --> dialog["Undo 'The path to the palace<br/>is busy this afternoon.':<br/>it shows itself again<br/>{ advance: false, step: true }"] dialog --> stop(["The game waits on<br/>'The path to the palace<br/>is busy this afternoon.'"])

When a statement’s willRevert() refuses, or the engine reaches the first statement of the game, it stops undoing and runs the statement at the current position again: the player ends up where they were. A function written straight into the script can’t be undone either, so going back stops at it; the { 'Function': { 'Apply': …, 'Revert': … } } form can (see JavaScript Functions). At the first statement of a label the game reached with jump, going back returns to the jump.

Keep what is on screen in the state

This action shows where the scene takes place in a badge at the top of the game screen. 'location Palacio de Bellas Artes' shows or changes the badge, and 'location' on its own takes it away. Add it to js/main.js:

class ShowLocation extends Monogatari.Action {
  static id = 'Location';

  static async setup() {
    // The statement that showed the badge on screen now. The game's
    // state goes into every save, so a load can show it again.
    this.engine.state({ location: '' });

    // The badges shown before it, so going back can show them again.
    this.engine.history('location');
  }

  // A game ends (quit, or the end statement) or a save is about to load.
  static async reset() {
    this.engine.element().find('.location-badge').remove();
    this.engine.state({ location: '' });
  }

  // A save was loaded: show the badge it had on screen.
  static async onLoad() {
    const statement = this.engine.state('location');

    if (statement !== '') {
      const action = this.engine.prepareAction(statement, { cycle: 'Application' });

      await action.apply();
    }
  }

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

  constructor([keyword, ...name]) {
    super();
    this.name = name.join(' ');
  }

  async apply() {
    this.engine.element().find('.location-badge').remove();

    if (this.name !== '') {
      const badge = document.createElement('div');

      badge.className = 'location-badge';
      badge.textContent = this.name;

      this.engine.element().find('[data-screen="game"]').append(badge);
    }
  }

  async didApply() {
    // Remember what was on screen before, then record this statement.
    this.engine.history('location').push(this.engine.state('location'));
    this.engine.state({ location: this.name !== '' ? this._statement : '' });

    return { advance: true };
  }

  async revert() {
    const previous = this.engine.history('location').pop();

    this.engine.element().find('.location-badge').remove();
    this.engine.state({ location: previous });

    if (previous !== '') {
      const action = this.engine.prepareAction(previous, { cycle: 'Application' });

      await action.apply();
    }
  }

  async didRevert() {
    return { advance: true, step: true };
  }
}

monogatari.registerAction(ShowLocation);

Style the badge in style/main.css:

.location-badge {
  position: absolute;
  top: 1rem;
  left: 1rem;
  z-index: 11;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  background: var(--main-color);
  color: #ffffff;
}

Give the place variable a value in js/storage.js, and use the action in js/script.js:

monogatari.storage({
  player: {
    name: '',
  },
  place: 'Alameda Central',
});
monogatari.script({
  'Start': [
    'show scene afternoon',
    'location Palacio de Bellas Artes',
    'The path to the palace is busy this afternoon.',
    'location {{place}}',
    'The park next door is quiet.',
    'location',
    'Somewhere, nowhere.',
    'end',
  ],
});

Start the game: the badge reads “Palacio de Bellas Artes” with the first line, “Alameda Central” with the second, and is gone with the third.

The Palacio de Bellas Artes in the afternoon, with a badge reading "Palacio de Bellas Artes" in the top left corner and the line "The path to the palace is busy this afternoon." in the text box
The Location action's badge

Undo it when the player goes back

didApply() writes down two things: in the location history, what was on screen before this statement; in the state, the statement that’s on screen now. revert() reads them back:

  • Press Back on “The park next door is quiet.”: revert() takes “location Palacio de Bellas Artes” off the history, shows that badge again and puts it back in the state. didRevert() returns { advance: true, step: true }, so the engine goes on to “The path to the palace is busy this afternoon.”, which shows itself again and stops there.
  • Press Back on “Somewhere, nowhere.”: the history gives back “location {{place}}”, and “Alameda Central” shows again.

The state holds the statement as written, 'location {{place}}', from this._statement. prepareAction() replaces its variables again when it creates the action, so the badge always shows the variable’s current value.

Rebuild it when a save is loaded

Loading a save resets the game, restores the save’s state, histories and storage, and then calls every action’s onLoad(). The Location action’s onLoad() creates an instance of the statement in the state and calls its apply(). It doesn’t call didApply(), which would write the statement into the history a second time.

After every onLoad() has finished, the engine runs the statement the save was made on again. That’s normally a statement the player was stopped at, like a line of dialog, so it shows itself as it did; the statements before it that moved on by themselves, like location, are the ones onLoad() has to rebuild.

Because the save also holds the location history, going back after a load works as it did before the save.

Clean up when the game ends

reset() runs when the player quits, when the game reaches end, and before a save loads. It takes the badge off the screen and puts the state’s location key back to its starting value. The engine empties the histories itself.

Storage and going back

Going back doesn’t put the game’s variables back by itself: a statement that changes one has to undo its own change. In the script, that’s the job of the Revert function of a { 'Function': … } statement:

monogatari.script({
  'Start': [
    'show scene #4a4e69',
    'Line one.',
    { 'Function': {
      'Apply': function() {
        this.storage({ score: this.storage('score') + 1 });
      },
      'Revert': function() {
        this.storage({ score: this.storage('score') - 1 });
      },
    } },
    'Line two.',
    'end',
  ],
});

With score: 0 in js/storage.js, score is 1 on “Line two.”. Press Back and Revert runs: “Line one.” shows again and score is 0. Without the Revert function, score would stay 1. A function written straight into the script, without the { 'Function': … } object around it, can’t be undone at all, so the player can’t go back past it.

An action of yours that changes a variable should undo the change in its revert(), unless the change is meant to outlast going back, like the list of visited labels the RememberingJump action keeps.

Effects outside the game

A timer, an interval or a sound your action starts keeps going until something stops it. Stop it in reset(), so it doesn’t run on into the main menu or into a loaded save, and in willRollback() or revert() when going back should end it too.