NPCs: Reactions - ThePix/QuestJS GitHub Wiki

One way to give life to an NPC is to have him react to the world around him. If the player appears wearing a fancy hat, have the NPC react to it.

We can do that through an array attribute called reactions. By default this will be checked each round the NPC is in the same room as the player. If you want it to happen even when not in the same location:

settings.npcReactionsAlways = true

The reactions array

This is an array of dictionaries, with each entry in the array being a different reaction.

Each reaction has a "name", a "test", a "script" and (optionally) an "override". The "test" and "script" attributes should be functions taking a dictionary parameter which will include the NPC as the "char2 attribute (you cannot use this inside the functions as it will refer to the dictionary in the array, not the NPC).

The "override" attribute, if present, should be an array of strings. The "name" attribute is just a string used by the reaction system to identify each reaction. If an NPC has several reactions with the same name, only one will ever get used - this can be useful!

If the NPC is present, Quest will go through each reaction in the dictionary. If the reaction has already been used, it will be skipped. Otherwise, the test is run, and if it returns true, the action will be run and any reactions listed in override will be flagged as completed as well as this one. Only one action will be used per turn per character - the first in the list that returns true from its "test" function.

In this example, two reactions are set. The two "test" functions determine if the reaction will be used, whilst the "script" functions do the work of the reaction. The parameter in "test" and "script" can be omitted when not used, the second "script" uses it to illustrate how to do so.

Note that the "bigHat" reaction takes priority, it overrides "smallHat". If the first reaction fires, it will override the second, so Mary will never comment on the small hat if she sees the player wearing the big hat first. The reaction that takes priority must appear earlier in the list.

  reactions:[
    {
      name:'big_hat',
      test:function() {
        return player.getOuterWearable("head") === w.big_hat
      },
      script:function() { 
        msg("'Wow, what a great hat,' Mary says.") 
      },
      override:["small_hat"],
    },

    {
      name:'small_hat',
      test:function() {
        return player.getOuterWearable("head") === w.small_hat
      },
      script:function(params) {
        msg("'What a lovely hat,' " + lang.getName(params.char) + " says.") 
      },
    },
  ],  

If a reaction has no name, it can be used multiple times. This can be useful too.

If there is a reaction, Quest will call pause() on the NPC to stop him doing anything else this turn. If you do not want that to happen, add noPause:true, to the dictionary.

Reactions use the respond function, and so can be nested.