# RPG Forge docs, full text Index: https://rpgforge.ai/llms.txt --- # How a game plays Source: https://rpgforge.ai/docs/how-it-plays.md What every game on RPGForge plays like, whatever its world. Read this before telling anyone what the engine can or can't do. ## Turns The player types what they do in plain words. Each action counts as a turn. The engine resolves rolls, damage, trades, travel, and time, then the narrator writes what happened. Uncertain actions roll a d20 against the situation, with any [skill](/docs/skills) rank added. A failed roll stops what it tried and nothing more; anything worse, like a snapped pick or a guard who heard, is a game rule (an [`onRoll` hook](/docs/hooks)). A turn takes a minute or two of world time, a walk between places ten or twenty minutes by distance. A typical session of play covers an hour or two unless the party rests or travels far. Travel goes between [connected locations](/docs/map), and the trip takes game time by distance. One command can cross several places; anyone hostile waiting where the walk ends may ambush the party. What happens on the road between depends on the game. An [`onBeforeTravel` hook](/docs/hooks) can stop the walk partway, with a reason the narrator tells. When play goes flat, someone nearby or a companion along comes to the party with a proposal; see [When play goes flat](/docs/story). A game runs until an **End game** step wins or loses it (see [Endings](/docs/story#endings)), or a hero falls for good under permadeath. Without either, play goes on. ## What the player sees Every game has the same play screen, built in. Each panel fills itself from the world. A request for one of these is answered by pointing at it and filling what it shows: - **Inventory**: everything the hero carries, what is equipped, and the items they can use. Empty until the hero has starting items or picks some up. - **Abilities**: the hero's abilities and spells, with their costs and cooldowns. - **Character**: portrait, level, health and other meters, stats, trained [skills](/docs/skills) and equipment. - **Journal**: quests, their steps and rewards. - **Party**, **Map** and **Scene** (who and what is here). - The **HUD** bar, the one part an author arranges: which [fields](/docs/fields), item counts and equipped values it shows. ## Combat Combat is **turn-based in rounds**. One command is the player's action for the round; everyone else in the fight acts in the same round in initiative order. Quicker combatants act first. A blow that drops an opponent resolves before that opponent can act. - Attacks roll to hit; damage comes from the weapon and a stat (strength for melee, agility for ranged). - [Abilities](/docs/items-creatures) cost resources and have cooldowns; effects (poison, stun, buffs) tick each round. - Party members, recruited NPCs and summoned companions fight on the player's side. - Anyone can try to flee, opposed by the side they are running from. **No grid and no positions.** A fight happens at one location, and everyone in it can reach everyone else. There is no movement, range or facing inside a scene. A game wanting tactical positioning can approximate it with [fields](/docs/fields) (cover, a high ground flag) instead of a map. ## Multiplayer Every game supports multiplayer without extra setup. The host opens their session to friends, who join with their characters, before the start or mid-game with the host's approval. The engine handles it as one party: - Each player sends an action every turn and the turn resolves them together, once everyone has acted, the host's turn timer runs out, or the host moves it on. - The party shares one location and travels together; it can't split up. - In a fight, each player's action takes its place in the round's initiative order. ## Not part of the engine - A tactical grid or positioning (above). - Splitting the party across locations. - Real-time play: nothing happens between turns. - New screens, panels or minigames beyond the ones above, see [What you can't build](/docs/limits). --- # Translations Source: https://rpgforge.ai/docs/translations.md Players read the site in their language, and the narrator already tells the story in it. What you wrote yourself, the names of people and things, descriptions, quests, stays in the language you wrote it in until you translate it. ## How it works Translations are off until you turn them on: tick **Translations** on Setup's Rules tab (the agent can turn it on too). While it is off, every player sees the game as you wrote it, and the step is hidden. The **Translate** step lists every text a player reads on screen, grouped by what it belongs to, including the game itself, the character sheet (stat, slot and field labels), each character, item, place, creature, ability, effect, quest, world event, region, skill, faction and plugin. Recap lines a rule shows ("Starving") are listed with the asset whose rule shows them. Pick a language, and write each line's translation next to it. - A line is keyed by its exact text. The same words are translated once for every place they appear. - Editing a source text leaves its old translation behind, so that line shows as untranslated again. Saving drops translations whose text the game no longer has. - Names stay the game's names underneath. A translated name is only what players of that language see, on cards and in the narration, so rules, conditions and quests that name it keep working. - A player sees the translation when they play in that language. A language without a translation shows the default text. - A plugin includes translations of its field labels and badges. A line you translate on the Plugins tab is saved into that plugin. It goes wherever the plugin goes, and an installed plugin arrives with its lines filled in. - While **Untranslated only** is ticked, a line you are writing stays in the list until you untick it or change language. ## Asking the agent The agent in the Prompt panel can translate for you, on your credits: ask it to "translate the game into Spanish". It reads the texts with `get_translations` and writes them with `set_translations`, so you can review and edit every line on the Translate step afterwards. ## What is not translated Text only the narrator reads needs no translation: lore entries, habits, what a vendor offers, hints and conditions. Players never read it directly, and the narrator uses it to tell the story in the player's language. The opening is listed only when it is read out word for word. Places, people and quests the world builds during play are written in the game's language for now. --- # Skills Source: https://rpgforge.ai/docs/skills.md A **skill** is narrow, trained competence a character holds in ranks (0 to 10): Lockpicking, Foraging, Healing, Swordsmanship. ## Skills vs stats vs abilities vs plugins - A **stat** is broad biological or mental aptitude (Strength, Agility, Intellect) shared by every roll of its kind. - An **ability** is a named, costed move with a cooldown (Fireball, Shield Bash). - A **skill** is narrow competence (0-10 ranks). It adds to checks of that kind and scales heals and hits. - **Skills are NOT plugins.** Do not create a plugin, custom fields, or hooks to track skills or skill progression. The engine already handles skill progression natively. ## Turning skills on Skills are **off by default**. Tick **Skills** under Setup › Rules to turn them on; that shows the **Skills** step. When off, no rank adds to a roll and nothing scales or trains. Skills you declared stay stored for when you turn it back on. The builder turns it on when it declares skills for you. ## Declaring skills Skills are declared on the game under `settings.skills`. Each skill has: - `name`: Short display name, e.g. "Lockpicking", "Foraging", "Swordsmanship". - `description` - The acts it covers, e.g. "foraging for wild herbs, hunting edible roots, gathering forest sustenance". The adjudicator uses this description to decide which skill applies to a player's action. ## Built-in progression: skills improve with use Characters gain practice automatically whenever they: 1. Make a roll that draws on the skill (harder checks teach more, failure still teaches half). 2. Use an item or weapon tagged with the skill (`item.skill: "Swordsmanship"`). 3. Use an ability tagged with the skill (`ability.skill: "Healing"`). As characters earn practice, their skill ranks increase automatically. You do not need to write hooks or scripts to level them up. ## Tagging items and abilities - An item or weapon can declare `skill: ""`. Wielding or using it trains that skill and benefits from the character's rank. - An ability can declare `skill: ""`. Its damage and healing steps scale with the caster's rank. - Conditions can gate on skill rank, e.g. requiring a certain rank to attempt an action. --- # Damage types Source: https://rpgforge.ai/docs/damage-types.md A **damage type** is a kind of harm the game distinguishes, like Fire, Poison, or Frost. Without declared types, every hit is plain, and nothing resists anything. ## Turning damage types on Damage types are **off by default**. Tick **Damage types** under Setup › Rules to turn them on; that shows the **Damage types** step. With it off every hit is plain and nothing resists anything, whatever weapons and effects name. Declared types stay stored for when you turn it back on. The builder turns it on when it declares damage types for you. ## Declaring damage types Damage types are declared on the game under `settings.damageTypes`. Each has: - `name` - A noun the narrator can say, e.g. "Fire", "Poison". - `description` - What deals it in this world, e.g. "flame, burning oil, dragon breath". ## What deals a type - A **weapon** names one with `damageType`. For example, a flaming sword deals Fire on every blow that lands. - A **creature or NPC** names one with `damageType` next to its `damageDice`. A wyrm's bite deals Fire when striking unarmed. A wielded weapon's type replaces it. - A **damage step** names one: `$.damage({ dice: { count: 2, sides: 6 }, damageType: "Fire" })`. This is how an ability, an item rule, a hook or an effect's tick deals a type. Bare fists and anything left untyped deal plain harm. ## Resisting a type An effect lists `resists`, one entry per type, each saying what harm of that type does to whoever carries it: | `takes` | Means | | -------- | ------------------------------------------ | | `half` | resistance, like a fire ward | | `none` | immunity, like a fire elemental against Fire | | `double` | weakness, like a frost creature against Fire | Two effects on one carrier multiply. A ward and a weakness to the same type cancel out. The effect can be permanent (a creature's nature, through its starting effects), worn (an item's granted effect), or timed (a potion). The resistance applies after armor. A resisted blow still does at least 1; only an immunity takes nothing. The narrator is told how the harm landed in words ("the fire barely takes hold of them") without numbers. ## Checks - A `damageType` or `resists` entry naming a type the game never declared is an unknown name. - A resistance to a type nothing in the game deals is flagged: it can never matter. --- # Expressions Source: https://rpgforge.ai/docs/expressions.md An **expression** is a small piece of JavaScript that reads the game and gives back a value. You'll use them anywhere the editor shows a formula box, such as a quest condition, a damage amount, a field's maximum, or a hook body. ```js $.stat('might') * 2 + 5 ``` That's a complete expression. No `return`, no function wrapper. ## Everything is on `$` `$` is the only thing in scope: ```js $.subject.name // who this rule is about $.subject.health // their current hit points $.player.fields.satiety // a field on the host player $.turn // the turn number $.timed // does this world have a clock? ``` Reads come in two kinds: - **[Values](/docs/reading-values)**: `$.subject.health`, `$.stat()`, `$.field()`, `$.dial()`. - **[Questions](/docs/questions)**: `$.hasItem()`, `$.alive()`, `$.hasPlugin()`. True or false. Reading something that doesn't exist returns `undefined` or `null` instead of throwing an error. That's the number one reason a rule silently never fires. Read [Missing values](/docs/missing-values). ## The sandbox Expressions run in a sandbox with a time budget: - **An infinite loop is stopped**, not hung. The turn continues; your rule doesn't. - **Expressions can't talk to each other.** No variable survives from one rule to the next. If two rules need to share something, put it in a [field](/docs/fields). - **An expression that throws gives nothing back**, and the engine uses its default. So a broken rule looks like a rule that didn't fire instead of showing an error message. ## Dice `$.random()`, `$.rollDie(6)` and `$.pick(weights)` only work in a **rule body** (a hook, an item rule). In a condition or an amount they return `null`. The reason: conditions and amounts are worked out once per turn and reused. A roll there would be the same roll every time it was read. A body runs when things actually happen. A roll there is a real roll. Roll in the body, then act on it: ```js var rows = $.table('affixes') var weights = {} for (var i = 0; i < rows.length; i++) weights[rows[i].key] = rows[i].weight var picked = $.pick(weights) if (picked !== null) { $.setField({ field: 'edge', to: $.row('affixes', picked).power }) } ``` `$.pick` takes a map of key to weight (zero or less is never picked), or a plain array to pick from evenly. A target that needs a random number, like "kill three to seven of them", should roll **once** when the quest opens and store the result. A gate that re-rolled every turn would never be reachable. ## Next [Reading values](/docs/reading-values). If you're writing hook bodies, read [Rule bodies](/docs/rule-bodies) too. --- # Reading values Source: https://rpgforge.ai/docs/reading-values.md These give you a value to compare, add up, or pass to a step. ## Stats: by role, not by name ```js $.stat('might') ``` Stats are read by **role**. A game can call its strength stat "Might", "Brawn" or "Thew", and `$.stat('might')` reads it in all three. Reading by display name (`$.stat('brawn')`) breaks the day someone renames it. `$.stat(key)` answers: - `health` and `playerLevel`; - each stat key the game declares (`strength`, `agility`, or whatever it has); - each role that one of the game's stats claims, from the engine's `might`, `resolve`, `presence`, `speed`, `evasion`, `accuracy` and `insight`, and any role a plugin declares (also by its full id, `engine:speed`). A stat named the same as a role wins that name. So `$.stat('speed')` in a game whose stats are strength and agility reads agility, if agility claims speed. A role no stat claims has no value, and neither does any other name. The formula fails and a gate reading it stays shut (see [Missing values](/docs/missing-values)). The stats editor shows which stat claims each role, and get_plugin lists what every key reads in this game. ```js 5 + $.stat('might') * 1.5 // a heavy weapon that hits harder in strong hands ``` ## Fields A **field** is a value a plugin declared on something: `satiety`, `infection`, `mana`. ```js $.field('satiety') // on the subject $.field('satiety', 'player') // on the host player $.field('infection', 'target') // on whoever was aimed at $.field('corruption', 'location') // on the place itself ``` A field that no entity has reads `null`, **not** `0`. That difference decides whether your rule fires. See [Missing values](/docs/missing-values). ## Carried totals ```js $.carried('weight') ``` Adds up a field across everything the subject holds. This is how encumbrance works. ## Dials: your tuning numbers ```js $.dial('foodDrainPerHour') ``` Reads one of your plugin's dials, the numbers an author can tune in your plugin's panel. Never copy a dial's value into your code as a number. `0.4` works until someone changes the dial, and then two numbers disagree and nothing errors. See [Formulas and dials](/docs/formulas). ## Tables: your plugin's own rows When your plugin owns a **list** (tiers, a roster, a matchup chart), declare a table and read it through `$`: ```js $.table('conditions') // every row, as an array $.row('conditions', 'snow') // the row whose first column is 'snow', or null $.row('conditions', 'snow').tempBand // one cell ``` A misspelled table name reads as an empty table. A loop over it will silently never execute. ### Table or field? - A **field** lives on the entity and is edited on that entity's sheet. A location added later gets it automatically. Use it when the value belongs to the thing. - A **table** lives in your plugin's panel. A location added later is missing from it until someone adds a row. Use it for your system's vocabulary. Whichever you pick, **read from where you wrote.** Filling in a table and then reading `$.location.fields.something` gives you a system that's fully set up but never runs. ## Time ```js $.event.minutes // how long this stretch took $.timed // whether the world has a clock ``` In a game without a clock, `minutes` is the narrator's guess and swings from 3 to 22 for similar turns. Price by the hour only when there's a real clock: ```js $.timed ? $.dial('drainPerHour') * ($.event.minutes / 60) : $.dial('drainPerTurn') ``` See [Minutes are not time](/docs/minutes-are-not-time). ## Everything you can read | Path | Answers | |---|---| | `$.subject` | The entity this rule is about. | | `$.subject.name` | The subject's name. | | `$.subject.kind` | What the subject is: 'player', 'npc', 'creature' or 'object'. | | `$.subject.location` | Where the subject is. | | `$.subject.health` | Current health. | | `$.subject.maxHealth` | Maximum health. | | `$.subject.dead` | Whether the subject is dead. | | `$.subject.level` | The subject's character level. | | `$.subject.fields` | The subject's declared fields, by key. | | `$.subject.bonds` | The subject's NPC bonds. | | `$.subject.home` | An NPC subject's authored home location ('' when they have none); absent on anyone else. | | `$.subject.heading` | Where a creature subject is walking. That is the place `$.headTo` sent it, else its next patrol stop, or '' when neither. Absent on anyone else. | | `$.subject.equipSlots` | Equipment slots an item subject can occupy (empty array for non-equippable items); absent on living entities. | | `$.subject.isWeapon` | Whether an item subject can occupy a weapon slot (by role, even if renamed); absent on living entities. | | `$.subject.isEquipment` | Whether an item subject can be equipped in any slot; absent on living entities. | | `$.source` | Who caused it - attacker, user, emitter. | | `$.source.weapon` | What the source wields, shaped like `$.weapon`. In `onAttack` the subject is the target, so you read an attacker's ammunition here with `$.source.weapon.fields.loaded`. | | `$.player` | The acting player: whoever uses the item or casts, or the subject when it is a player, else the host. Use `$.party` for everyone. | | `$.player.name` | The acting player's name: whoever uses the item or casts, the host when nobody in particular acts. | | `$.player.health` | The acting player's health. | | `$.player.level` | The acting player's character level. | | `$.player.fields` | The acting player's declared fields. | | `$.party` | Every player - host and guests. | | `$.location` | The place this is happening in. Printing it gives the name, so `"at " + $.location` still reads as the place. | | `$.location.name` | The place's name. | | `$.location.fields` | Declared number fields on the current place by key, covering anything with trait "location". Untouched places read empty, not as zero. | | `$.location.tags` | The place's declared text fields, by key. | | `$.world` | World flags. | | `$.here` | What is in the current location. | | `$.exits` | Formatted as `{ name: distance }`, listing everywhere you can reach in one hop. Edges work both ways regardless of how they were drawn. Use `Object.keys($.exits).length === 0` to test for map edges when running generators. Empty if the game has no map. | | `$.items` | All carried items, mapped as name to quantity. Use this when inspecting names dynamically. `Object.keys($.items)` lists them, and `$.items["Rope"]` returns how many there are. | | `$.pack` | Detailed inventory for the subject, with an entry for each carried row: { name, key, fields, tags, quantity }. Use this when specific item instances matter, like finding which magazine holds the most ammo, and target that copy with `item: entry.key`. | | `$.equipped` | What the wearer has in each slot, mapped by the slot names declared in this game. Empty slots return null. If an entity lacks a slot entirely, that key is omitted, so `$.slotEmpty` is easier than checking for null by hand. | | `$.weapon` | The item in the subject's weapon slot, null when unarmed, whatever the game calls that slot. | | `$.weapon.name` | The wielded item's name. | | `$.weapon.fields` | The wielded item's declared number fields. | | `$.weapon.tags` | The wielded item's declared text fields. | | `$.weapon.key` | That one wielded item, as a key a field step can write to: `$.adjustField({ field: "rounds", by: -1, item: $.weapon.key })`. | | `$.weapon.ammoLeft` | How many matching rounds the wielder has, whether loose or in an open container. Returns null for weapons that don't use ammo. | | `$.weapon.roundsPerShot` | How many rounds one shot spends: 1, or more for a burst or automatic weapon. Null when it fires nothing. | | `$.mobs` | Creatures present. | | `$.foes` | Who present can still fight the party: creatures that are not companions and have not stood down, and people who turned on it. | | `$.game` | Every item, character, location, mob, ability and effect in the game, full authored records included, populated only inside a declared action's afterRoll body. Search it by name: $.game.filter(e => e.name === 'Rusty Key')[0]. Each entry has name, kind, description, mechanics (compiled item rules), quests (an NPC's authored steps), costs (an ability's resource costs), refs (every other name this one references - search every OTHER entry's refs for a name to find what points AT it) and here ("seen" when it is in the acting character's place or carried or held by someone there, "hidden" when it is there but out of sight, "" elsewhere). | | `$.turn` | The turn number. | | `$.combat.active` | Whether a fight is running right now. | | `$.combat.round` | Which round the fight is on, counting from 1. Zero when no fight is running. | | `$.combat.allies` | How many on the player's side are still standing. Zero outside a fight. | | `$.combat.enemies` | How many on the enemy side are still standing. Zero outside a fight. | | `$.quests` | Every quest by name. Each entry includes `status` ("inactive", "active", "completed" or "failed"), the current `step` index starting at 0, and total `steps`. Check completion with `status === "completed"`. A finished quest moves `step` one past the last index, to equal `steps`. On an active quest, `step === steps - 1` means they're on the final step. | | `$.visited` | Names of every location the party has visited. Use `$.visited.indexOf($.location) === -1` to check if this is their first visit. | | `$.timeMinutes` | Minutes on the world clock. Advances once per tick. | | `$.minutesPassed` | Minutes on the world clock since the game began. | | `$.minutesPerDay` | Minutes in one day under this world's calendar (Earth: 1440). | | `$.timed` | Whether this world has a clock. Charge per hour when true, or per turn when false. In clockless games, `$.event.minutes` is just the narrator's rough estimate. | | `$.setting` | The game's setting. | | `$.killCount` | Kills so far. | | `$.minted` | What the tool just created, available inside the tool body. Evaluates to `{}` everywhere else, returning undefined without throwing errors. | | `$.minted.name` | The name of the thing just minted. A mint invents the name, so this is the only way a body can place, spawn or grant what it made - `$.spawnItem({ itemExpr: $.minted.name })`. | | `$.event` | The payload from the firing trigger. Evaluates to `{}` outside hooks, returning undefined without throwing errors. | | `$.item` | The item in play. Null outside the item-use path. | | `$.item.name` | The item's name. | | `$.item.state` | The item's state. | | `$.item.fields` | The item's declared fields. | | `$.target` | The aimed-at entity. | | `$.target.name` | The target's name. | | `$.target.state` | The target's state. | | `$.target.fields` | The target's declared fields. | What's on `$.event` depends on the trigger. See [Hooks](/docs/hooks). --- # Asking questions Source: https://rpgforge.ai/docs/questions.md These answer yes or no. [Conditions](/docs/conditions) are built from them. ## Inventory ```js $.hasItem("Rope"); // any at all? $.hasItem("Rope", 3); // at least three? ``` ## People and places ```js $.alive("Ironjaw"); // is this NPC alive? $.at("Ironjaw", "the mill"); // is this NPC here? $.location.name === "the mill"; // is this happening at the mill? ``` A spawn step's [id](/docs/steps#giving-what-you-spawn-an-id) works here too: ```js $.exists("nest-swarm"); // is the thing spawned with this id in the world? $.alive("nest-swarm"); // and not dead? $.hasItem("smugglers-box"); // does the subject carry that one copy? ``` `$.location` is the place the rule is running in: where the player is standing for an item they use, where the event fired for an event. It is a [read](/docs/reading-values) that compares with `===` instead of asking the model. Names are as they appear in your game. A missing name returns `false`. A typo reads as "no" instead of raising an error. Use editor completion. ## Abilities and gear ```js $.hasAbility("secondwind"); $.slotEmpty("offhand"); // false if the body has no offhand at all $.slotHolds("weapon", "Iron Sword"); ``` ## Other plugins ```js $.hasPlugin("hunger"); // is that plugin installed? $.hasField("infection", "target"); // does this entity have that field? ``` Any plugin can read any field, so ask first. Without the check, `$.field('satiety')` in a game without the hunger plugin reads `null`, and your rule acts as if everyone is always starving or never hungry, depending on which way the comparison points. ```js $.hasPlugin("hunger") && $.field("satiety") < 20 ? 2 : 1; // hits harder if also hungry ``` ## Time windows ```js $.timeBetween("20:00", "04:00"); // handles midnight ``` ## An operator chosen at runtime ```js $.compare(actual, op, target); ``` For when the operator comes from data, like a quest that stores `'>='` next to its threshold. ## Every question | Call | Answers | |---|---| | `$.hasItem('rope', 2)` | Whether the subject has at least this many. | | `$.delivered('Raw Copper Ore', 1, 'Foreman Hilda')` | Quest steps only: whether the party has put at least that many in that NPC's hands. They keep them when the step completes. | | `$.carried('weight')` | The total of a field across everything carried. | | `$.stats.luck` | A map of stat names to values for this character, including custom stats alongside the default five. Read this when a rule needs to handle every stat alike. Use $.stat(name) when you want a specific one. Role aliases like `might` and `engine:might` point to whichever stat claims them, so looping over keys can return repeated values. | | `$.stat('might')` | A stat on the subject: health, playerLevel, a stat key this game declares, or a role (might, resolve, presence, speed, evasion, accuracy, insight, or a plugin's) once one of its stats claims it. Prefer the role, which survives a rename. Any other name has no value. The formula fails and a gate stays shut. get_plugin lists what each key reads in this game (statReads). | | `4 + $.skill('Healing') * 3` | A rank in a declared skill, or 0 when untrained. Reads the player's, or the subject's when `who` is "target". Damage and heal steps on tagged abilities or items already scale with rank, so use this if you need a custom formula. | | `$.field('satiety', 'player')` | One declared field, number or text, on the subject or whoever `who` names - "player", "target", "location" for the place this is happening in, or "weapon" for what the subject wields. | | `$.compare(actual, op, target)` | Compare two values with an operator chosen at runtime. | | `$.alive('Ironjaw')` | Whether a named entity is alive. | | `$.exists('hornet-swarm')` | Whether something a spawn step made with this `id` is in the world (an item anywhere, or a creature alive or dead). | | `$.questIs('BORROWED_CARTRIDGE', 'completed')` | Whether the quest with this id stands "active", "completed" or "failed". | | `$.questStep('BORROWED_CARTRIDGE') >= 2` | How many steps of the quest are done: -1 before it is taken, every step once finished. | | `$.at('Ironjaw', 'the mill')` | Whether a named entity is at a location. | | `$.itemAt('House Fire', 'the mill')` | Whether an item is lying at a location - on the ground or fixed in place, not carried. | | `$.mobsAt('the mill').filter(n => n === 'Shambler').length` | The creatures in sight at any place, by name, as `$.mobs` lists them for the place this is happening in. Inside a hook about a creature or NPC somewhere else, `$.mobs` is still where the party is, so read the place they stand in with `$.mobsAt($.subject.location)`. | | `$.positionOf($.subject.location)` | A place's pin as `{ x, y, map }`, where it stands now: x grows east, y grows south, and `map` is the place whose map holds the pin ('' for the top map). Null for a place with no pin. Compare positions only on the same map; `$.directionOf` lifts two places onto one. | | `$.directionOf($.event.from, $.event.to) === 'North'` | The compass direction from one place to another, one of East, South-East, South, South-West, West, North-West, North, North-East, read on the deepest map holding both, as exits are told. '' when they share a spot or have no pins. | | `Object.keys($.exitsOf($.subject.location))` | Every place one hop from any place, as `{ name: distance }`, the shape `$.exits` has for the place this is happening in. Walk it outward to reach places further off. | | `$.timeBetween(from, to)` | Whether the clock now reads between two times. | | `$.hasAbility('secondwind')` | Whether the subject has an ability. | | `$.slotEmpty('offhand')` | Whether a slot exists on this body AND is empty. False for a slot the body does not have, since a missing hand cannot be freed up. | | `$.slotHolds('weapon', 'Iron Sword')` | Whether one named item is worn in a particular slot. | | `$.hasPlugin('hunger')` | Whether another plugin is installed - ask before reading its fields. | | `$.hasField('infection', 'target')` | Whether a field exists. Use it to tell an unset field from a real zero. | | `$.dial('foodDrainPerHour')` | One of your own plugin's dials. Never freeze a dial's value as a literal. | | `$.table('conditions')` | Returns every row in a table as an array, from this plugin or another if you provide its ID. If the table is undeclared or its plugin is off or missing, you get an empty array and loops simply skip. | | `$.row('mechanisms', 'pump', 'firearm-mechanisms')` | One row found by its first column, or null when nothing matches: from your own table, or another plugin's when you name its id. Read a cell off it by column key. | | `$.random() < 0.25` | A random number from 0 up to (but not including) 1. ONLY inside a script body - in a condition or an amount expression it answers null, because those are cached and a cached roll is the same roll every time. Roll in the body and pass the result to a step. | | `$.rollDie(6)` | A whole number from 1 to faces, like one die. Script bodies only, for the reason $.random() gives. Null if faces is not at least 1. | | `$.pick($.row('seasons', 'winter').weights)` | Picks an option at random. With a weights map, each key's chance is its weight over the total, ignoring keys with weights of zero or less. With a plain array, it picks evenly. Returns the chosen key or entry, or null if no valid options exist. Script bodies only. Pull from table rows where entries are validated, so typos won't slip through. | --- # Missing values Source: https://rpgforge.ai/docs/missing-values.md The most common reason a rule that looks right never fires, without an error. ## A missing stat has no value. A field is `null`. ```js $.stat('nonsense') // no value: the formula fails, a gate stays shut $.field('nonsense') // null ``` A formula reading a stat that is not there gives no number at all, and its fallback applies. See [Reading values](/docs/reading-values) for the keys `$.stat` answers. ## `null` loses every comparison ```js null < 5 // false null > 5 // false null == 0 // false ``` So someone without an `infection` field does **not** match `infection < 5`. Usually that's right: it stops a cure rule firing on every healthy person in the world. But if you meant "everyone below 5, including people who've never been infected", your rule matches nobody. ## Why you get no error - A missing path reads as `undefined`. - A condition treats `undefined` as "closed". - An expression that throws gives nothing, and the engine uses its default. Three separate mechanisms, all silent. Editor completion only offers paths that exist, so if you typed a path by hand and completion didn't offer it, that's probably your bug. ## Fixes Count "doesn't have it" as passing: ```js !$.hasField('infection') || $.field('infection') < 5 ``` Treat missing as zero: ```js ($.field('infection') || 0) + 1 ``` Check the plugin that owns it is installed: ```js $.hasPlugin('hunger') && $.field('satiety') < 20 ``` ## Why missing isn't just `0` Because `0` means something. Satiety `0` is *starving*. Satiety `null` is *this game has no hunger*. If missing read as zero, every character in a game without hunger would be starving. --- # Minutes are not time Source: https://rpgforge.ai/docs/minutes-are-not-time.md `onTimePasses` fires in every game, including games without a clock. In a game without a clock, `$.event.minutes` is **the narrator's guess** at how long the turn took. In live sessions, similar turns have ranged from 3 to 22 minutes. Charge an hourly rate against that and a wordy turn costs seven times what a terse one does. Nothing errors. The game just feels random, and no playtest report will tell you the cause is prose length. That's why stamina and mana don't run on the clock. ## Fix 1: charge in the unit the game has ```js $.adjustField({ field: 'satiety', by: -($.timed ? ($.event.minutes / 60) * $.dial('foodDrainPerHour') : $.dial('foodDrainPerTurn')) }) ``` Two dials, an hourly one and a per-turn one, because they really are different numbers and the author needs to tune both. ## Fix 2: use `onTurnEnd` For anything that ticks once per character per turn (regeneration, cooldowns, per-turn drains), use `onTurnEnd`. It fires once per actor per turn in every game and carries no estimate. Don't put the same rule on both triggers. That charges twice. --- # Steps Source: https://rpgforge.ai/docs/steps.md Reading the world is an [expression](/docs/expressions). **Changing** it is a **step**. A rule body is a list of steps. ```js $.adjustField({ field: "satiety", by: -1 }); $.damage({ amount: 3 }); $.narrate("the wound closes over"); ``` Steps take **named** arguments. `$.damage(3)` is refused; write `$.damage({ amount: 3 })`. The few exceptions (`narrate`, `refuse`, `grantXp`, `passTime` and a handful more) take one plain value, as shown below. ## The common ones | Step | Does | | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `$.adjustField({ field, by })` | Move a field **by** an amount | | `$.setField({ field, to })` | Set a field **to** a value (a number or a word) | | `$.adjustStat({ stat, by })` / `$.setStat({ stat, to })` | Same, for stats; `stat: "maxHealth"` grows or shrinks the hit-point ceiling of one NPC or creature | | `$.damage({ amount })` / `$.heal({ amount })` | Hurt or heal | | `$.applyEffect({ effect })` | Apply an effect by name; add `turns`, `minutes` or `permanent: true` to override how long it lasts | | `$.removeEffect({ effect })` | Remove one; leave `effect` out to remove all | | `$.give({ item, quantity })` | Give the player an item; `who` gives it to someone else, such as `"source"` in a hook | | `$.consume({ item })` | Use up one of a carried item; call it again for each one more | | `$.transfer({ item, from, to })` | Move a carried item from one character to another. `from` and `to` are `self`, `target`, `party` or a character's name | | `$.spawnItem({ item })` | Put an item in the world; `at` works as it does for `$.spawn` | | `$.spawnMob({ mob })` | Spawn a creature where the rule happens; `at` names a place, or `"self"` where whoever the rule is about stands; `minutes` is how long it stays | | `$.reveal({ item })` / `$.hide({ item })` | Bring something hidden into sight, or hide something here. Also takes `npc`, `mob` or `path` | | `$.teleport({ to })` | Move whoever it lands on to a place, no walking. A player reached takes the whole party along. See [Taking someone somewhere](#taking-someone-somewhere) | | `$.summon('Ironjaw')` | Bring a named NPC into the room where the rule or world event runs (revealing them if hidden) | | `$.grantAbility({ ability })` | Teach an ability | | `$.grantXp(50)` | Award experience | | `$.setWorld({ key, value, op, scope })` | Set a world flag to a text value; `op` "add" or "subtract" counts instead, `scope` "location" keeps it to this place | | `$.startQuest({ quest })` | Open a quest | | `$.failQuest({ quest })` | Fail a quest for good | | `$.endGame({ outcome, title, epilogue })` | End the game: `outcome` "win" or "lose", `title` the ending's name, `epilogue` what it means. See [Endings](/docs/story#endings) | | `$.startTimer({ id, minutes })` | Fire a timer later | | `$.bond({ bond, by })` | Change how an NPC feels | | `$.remember({ text })` | Give an NPC a memory | | `$.leaveParty({ npc, hostile: true })` | Turn an NPC against the party: they attack it on sight until pacified. Works on anyone, traveling with the party or not | | `$.sound('thunder')` | Play a sound | | `$.passTime(30)` | Advance the clock | | `$.tool({ tool })` | Run a [generator](/docs/generators) | | `$.narrate('...')` | Tell the narrator something happened | | `$.refuse('...')` | Stop the action or plugin event that fired the hook, saying why in a standalone clause ("they are too winded to swing"). The roll card and the narrator show it as written. | The editor's completion lists every step, with its arguments. ## Who it lands on Steps that act on somebody take an optional `targets`: | `targets` | Lands on | | ------------------------ | ------------------------------------------------------------------- | | `'target'` (default) | whoever was aimed at, or the user if none was targeted | | `'self'` | always the user, whatever was aimed at | | `'allies'` / `'enemies'` | the user's side / the other side | | `'buyer'` | whoever paid, inside a [vendor service](/docs/vendor-services) only | `'allies'` and `'enemies'` reach the whole side; add `count` to reach only that many of it, and `count` on `'target'` spreads from the one aimed at across their side. Whoever the player names ("I heal Mira and Tor") is picked first and the rest are drawn at random. Add `random: true` to draw them all at random whoever was named, for chain lightning that leaps where it likes. A ration uses `'self'` so feeding someone else still feeds the eater. A fire bomb uses `targets: 'enemies', count: 3`. `count` is how many **different** targets receive the effect, not total hits. To strike one target three times, write the step three times: ```js $.damage({ dice: { count: 1, sides: 4 } }); $.damage({ dice: { count: 1, sides: 4 } }); $.damage({ dice: { count: 1, sides: 4 } }); ``` A [world event](/docs/story#world-events)'s user is the player whose act set it off (shaking the branches under a hornet nest). A bare step lands on them, `'allies'` on their party and `'enemies'` on everyone else here. When the world sets it off (a timer, an arrival, a chance roll), `'enemies'` is everyone here and every other side, the default included, is the party, as long as the event fires where the party is. To land on one particular character instead, name them with `who`. It beats `targets`, and a name no living character or creature answers to lands on nobody: ```js $.damage({ amount: 5, who: "Ironjaw" }); ``` ## Taking someone somewhere `$.teleport` moves the step's [target](#who-it-lands-on), selected like any other step. Calling `$.teleport("Old Well")` moves the target, or the user when untargeted. That's all a recall spell needs. Moving a player brings the entire party, companions included, through the full arrival. An NPC or creature moved goes alone. A guard's arrest is a cast aimed at the lawbreaker that takes the guard along too: ```js // Ability "Arrest": whoever is aimed at goes to the cell, and the guard goes with them. if ($.subject.kind === "player") { $.setWorld({ key: "JAIL_DOOR", value: "LOCKED" }); } $.teleport("Town Jail"); $.teleport({ to: "Town Jail", targets: "self" }); ``` The ability's description is what an NPC reads to decide when to use it, so state who it is for ("anyone who breaks the peace in front of him") without leaving it ambiguous. Holding them there is a [plugin](/docs/plugins): an `onBeforeTravel` hook that refuses while the flag is set, and an action the player can roll to get out. ```js // Hook onBeforeTravel, gated on JAIL_DOOR = LOCKED if ($.event.from === "Town Jail") { $.refuse("the cell door is locked fast"); } // Action "breakOut", afterRoll if ( $.event.passed && $.world.JAIL_DOOR === "LOCKED" && $.location.name === "Town Jail" ) { $.setWorld({ key: "JAIL_DOOR", value: "OPEN" }); $.narrate("the cell door gives way, and the road out is open"); } ``` Declare `JAIL_DOOR` in the game's starting world state first. An `onTimePasses` hook that opens it after a night's rest lets a player who waits it out go free in the morning. ## `by` vs `to` ```js $.adjustField({ field: "fever", by: 1 }); // one worse than before $.setField({ field: "fever", to: 1 }); // exactly 1, whatever it was ``` Mix these up and you get a fever stuck at 1, or one that never stops climbing. A field on one particular item, such as the rounds in the gun just fired or a torch burning down, takes `item` with that item's key: ```js $.adjustField({ field: "rounds", by: -1, item: $.weapon.key }); // the gun in hand $.adjustField({ field: "fray", by: 1, item: $.event.weaponKey }); // in onAttack: what swung ``` ## What `refuse` stops `refuse` stops what the hook is answering. In a hook on the player's attempt, that is the attempt. Inside a hook on a plugin's action or event (`mechanisms:reload`, `rest:sleep`), it stops that one action or event and nothing else. A reload rejected for lack of a magazine leaves the rest of the turn to run. ## Spawning something that belongs to someone `$.spawnItem` can say more than which item. Each option describes the one copy it makes: | Option | Does | | ----------------------------------------- | ------------------------------------------------------------------------------- | | `at: "self"` | Put it on the ground where whoever the rule is about stands | | `contents: { fromHolder: "self" }` | Move everything they carry into it (it must be a container) | | `tags: { key: "value" }` | Stamp text variables on this copy | | `fields: { key: expression }` | Stamp number variables on this copy, computed as it is made | | `likeness: { of, mark }` | Make this copy **show someone** | | `minutes: 90` | Unmake this copy after that many in-game minutes, running its on destroyed rule | | `minutesExpr: $.dial("bodyDecayMinutes")` | The same lifetime, computed as it is made. 0 or less keeps it forever | A **likeness** gives one copy somebody's picture and titles it after them. `of` is a character, a creature, a player, or `"self"` for whoever the rule is about. `mark` is an optional icon drawn over the picture. The default item picture is used when that someone has none. It is how the Bodies plugin's hook makes a body look like whoever died: ```js $.spawnItem({ item: "Corpse", at: "self", contents: { fromHolder: "self" }, likeness: { of: "self", mark: "rpg:skull-solid" }, }); ``` That body shows up as "Corpse of Skitter" with Skitter's portrait under a skull. The same option makes a statue of a hero, a wanted poster of a bandit, or a painted portrait of a lost queen. The likeness is fixed when the copy is made. It stays accurate even after its subject has moved on. ## Giving what you spawn an id `$.spawnItem` and `$.spawn` take an `id`, a name you pick for the one item or creature they make. Every later step and expression can then point at that exact copy, even when ten others of its kind lie around. ```js $.spawnItem({ item: "Strongbox", id: "smugglers-box", at: "the cellar" }); $.spawnMob({ mob: "Hornet Swarm", side: "enemy", id: "nest-swarm" }); ``` | Use | Does | | --------------------------------------------------------------- | ----------------------------------------------------- | | `$.spawnItem({ item: "Coin", into: "smugglers-box" })` | Makes something inside that container, wherever it is | | `$.transfer({ item: "Key", from: "Ash", to: "smugglers-box" })` | Moves a carried item into it (or `from` it, out) | | `$.itemHealth({ item: "smugglers-box", by: -2 })` | Wears or mends that copy only | | `$.hide({ item: "smugglers-box" })`, `$.reveal(...)` | Hides or reveals that copy, wherever it lies | | `$.drop("smugglers-box")`, `$.consume(...)` | Drops or spends that copy, when the actor has it | | `who: "nest-swarm"` on any step | Lands on that creature | | `$.exists("nest-swarm")` | Whether it is in the world | | `$.alive("nest-swarm")`, `$.hasItem("smugglers-box")` | Whether it lives; whether it is in the subject's pack | **An id makes something once.** While a copy with that id is in the world, a spawn with the same id is skipped. A rule that may run many times, such as a nest that releases its swarm on every blow, writes the spawn plainly and the swarm comes out once: ```js $.spawnMob({ mob: "Hornet Swarm", side: "enemy", id: "nest-swarm" }); ``` Once the creature is despawned, or the item is used up or broken, the id is free and the next spawn makes it again. A creature's body still holds its id. Rules for ids: - An id names one copy. A spawn with an id makes one, whatever `quantity` says, and no stack joins it. - An id is not the name of any character, creature, item or place in your game. The editor flags one that is. - Players never see an id. The narrator hears the item's or creature's name. ## Revealing and hiding A [hidden thing](/docs/locations#hidden-things) is really there, just unseen. `$.reveal` brings it into sight and `$.hide` takes something out of it. Name one item, NPC or creature: ```js $.reveal({ item: "Taped Keycard" }); $.hide({ npc: "Vuk" }); $.reveal({ mob: "Cave Lurker", at: "Sunken Crypt" }); $.reveal({ path: "Smugglers' Cove" }); $.hide({ path: "Old Mill", at: "Village Square" }); ``` An item or creature is looked for where the rule happens, or at `at`. A creature name reveals every one of that kind there. An NPC is found wherever they are. Someone in a fight can't be hidden. To reach one creature out of several that share a name, add `who`. In a hook about a creature, `"self"` is that creature, wherever it stands. A lurker can give itself away while the others stay hidden. `"source"` is whoever caused the event. An aggressive creature a rule reveals beside the party strikes first, the same as one walking in on them. ```js // onTurnEnd: the lurker the party woke shows itself if ($.subject.fields.awake) $.reveal({ mob: "Corpse Lurker", who: "self" }); ``` The item appears in the scene the moment it's revealed, and the narrator is told it was found. A lever that opens a secret panel is a reveal; so is a potion of invisibility that hides whoever drinks it. A `path` is the [road](/docs/map#hidden-roads) between the place the rule happens (or `at`) and the place named. Revealing it opens it and puts it on the map; hiding it closes it and takes it off, even a road the author drew in plain sight. There has to be a road between the two already: a reveal opens a road, it never builds one. The **Reveal / hide** step works this way in the form. ## Narration never gets numbers ```js $.narrate("the fever's grip loosens"); // good $.narrate("fever reduced by 2"); // bad ``` The narrator is never told the mechanics: no numbers, no cooldowns, no turn counts. That's what keeps the prose in voice. Write the sentence you want the player to read. ## Damage is never zero Damage has a floor of 1, so `$.damage({ amount: 0 })` still costs a point. If a dial can be set to zero, check it first: ```js if ($.dial("starvationDamagePerHour") > 0) { $.damage({ amount: $.dial("starvationDamagePerHour") }); } ``` ## Next [Rule bodies](/docs/rule-bodies): what else can go in a body. --- # Rule bodies Source: https://rpgforge.ai/docs/rule-bodies.md A rule body is a list of [steps](/docs/steps), with `if` where you need to branch. ```js if ($.player.fields.satiety <= 0) { if ($.dial('starvationDamagePerHour') > 0) { $.damage({ amount: $.dial('starvationDamagePerHour') }) } } ``` The editor shows this as **visual steps** or as **code**. They're the same rule, and editing either one edits it. ## Plain JavaScript works too Variables, loops and helper logic are fine. The editor keeps them as a block of code and runs them in the sandbox: ```js var starving = [] for (var i = 0; i < $.party.length; i++) { if ($.party[i].fields.satiety <= 0) starving.push($.party[i].name) } if (starving.length > 0) { $.narrate(starving.join(' and ') + ' can barely keep their feet') } ``` There's a trade-off, and it's the one rule on this page to remember: **Inside code, only these steps exist:** - `$.damage(...)` - `$.heal(...)` - `$.adjustField(...)` - `$.setField(...)` - `$.narrate(...)` - `$.recap(...)` - `$.refuse(...)` - `$.give(...)` - `$.consume(...)` - `$.setWorld(...)` - `$.teleport(...)` - `$.passTime(...)` - `$.tool(...)` - `$.adjustCooldown(...)` - `$.reveal(...)` - `$.hide(...)` Plus every read on `$`. Everything else (`$.applyEffect`, `$.spawnItem`, `$.refuse`, `$.startQuest` and the rest) only works as a **visual step**. Once a body drops into code, the rest of that block stays code. A `$.refuse(...)` below a `var` line can't run. The editor rejects the body and shows which line failed. To fix it: - **Put steps like these above any variables or loops**, or - **Avoid the variable.** Write the expression straight into the argument. Amounts (`amount`, `by`, `to`) and names ending in `Expr` (`itemExpr`, `mobExpr`) take expressions and stay steps. A conditional is fine there too: ```js $.adjustField({ field: 'satiety', by: -($.timed ? ($.event.minutes / 60) * $.dial('foodDrainPerHour') : $.dial('foodDrainPerTurn')) }) ``` - **Read in the `if` itself.** An `if` whose condition reads what it needs stays a step, so anything can sit inside it: ```js if ($.field('satiety', 'player') <= $.dial('starvingBelow')) { $.applyEffect({ effect: 'Starving' }) } ``` The same check written as `var s = $.field(...)` and then `if (s <= ...)` is code, and `$.applyEffect` can't run inside it. Inside code, `$.setWorld(key, value)` and `$.give(item, quantity)` also take plain arguments. ## Roll tables A roll table runs one of its entries, picked by weight. Each entry's `run` is a separate body that can hold ifs, chances and other tables: ```js if ($.chance(0.75)) { $.rollTable([ { weight: 60, run: () => { $.give({ item: "Silverfin Trout" }) } }, { weight: 15, run: () => { $.give({ item: "Emerald Glimmerfish" }) } }, ]) } ``` ## Limits - A body can record at most 200 steps. Real rules record one or two. The cap exists to stop a runaway loop. - `return` ends the body early and keeps what it already did. ## Next [Hooks](/docs/hooks): when a body runs. --- # Hooks Source: https://rpgforge.ai/docs/hooks.md A **hook** is a rule that runs when the engine does something anywhere in the world. An item rule, by contrast, runs when a player uses one specific object. A hook has a trigger, an optional [condition](/docs/conditions), and a [body](/docs/rule-bodies). ## Triggers | Trigger | Fires when | `$.event` carries | |---|---|---| | `onSpawnCreature` | a creature enters the world | | | `onSpawnItem` | an item enters the world; **the item is the subject** | | | `onDamage` | hit points actually drop, from any source | `amount` `killed` `abilityName` `weapon` `weaponKey` | | `onHeal` | hit points actually rise | `amount` | | `onDeath` | someone dies (players too), after loot and XP | | | `onCombatStart` | a fight begins; subject is the location | | | `onCombatRoundEnd` | a combat round closes; subject is the location | | | `onEffectApplied` | an effect applies to someone | | | `onAttack` | every swing, **misses included** | `weapon` `weaponKey` `ranged` `ammo` `rounds` `attacking` | | `onLocationEnter` | the party arrives (NPCs moving do not fire it); subject is the new location | | | `onMapEdge` | the party reaches a dead end, every exit already visited | `exits` | | `onItemUse` | an item rule runs | | | `onAbilityUse` | someone uses an ability (players, NPCs and creatures); subject is the caster | `abilityName` `target` `passed` | | `onRoll` | a skill check resolves; **it can't change the roll** | `passed` `total` `dc` `margin` `crit` `botch` `stat` `note` `abilityName` `reason` | | `onTurnStart` | once per actor per turn | | | `onTurnEnd` | once per actor per turn, NPCs off-screen included | `inCombat` `rested` | | `onTimePasses` | in-game time advances during a turn, travel, or sleep | `minutes` `resting` | | `onTravel` | the party covers ground | `distance` | | `onBeforeAction` | someone **tries** something, before it happens: every swing by a player, NPC or creature, and a player's other combat moves and rest | `attack` `weapon` `ranged` `combatAction` `swings` `stat` `note` `actionOrdinal` | | `onBeforeTravel` | before each leg of a walk; subject is where the party stands | `from` `to` `destination` `leg` `legs` `distance` `arriving` | | `onBeforeNpcTravel` | before an NPC on an errand, schedule or patrol steps to the next place, off screen too; subject is the NPC | `from` `to` `distance` | A hook can also answer another plugin's event, written `pluginId:eventKey`, like `rest:sleep`. See [Cooperation](/docs/plugin-cooperation). ## Picking one - **Trying vs hurting.** `onAttack` fires on every swing. `onDamage` fires only when hit points move. Stamina per swing goes on the first; bleeding goes on the second. - **Per turn vs per minute.** For anything that ticks per character per turn, use `onTurnEnd`. `onTimePasses` minutes can be the narrator's guess; see [Minutes are not time](/docs/minutes-are-not-time). - **The creature vs its gear.** A hook writes to its subject. `onSpawnCreature` writes to the bandit; `onSpawnItem` writes to the bandit's sword. A rolled modifier or a curse on an object goes on the second. - **The party vs everyone.** `onLocationEnter`, `onTravel` and `onBeforeTravel` follow the party; `onBeforeNpcTravel` is the NPCs' road. A rule about NPCs wherever they are goes on `onTurnEnd` and reads their state, such as `$.subject.location === $.subject.home`. - **Round vs turn.** A turn is one actor, while a round is everybody. Things that last "a round", like a brace or a mark, expire on `onCombatRoundEnd`. - **Swinging vs swung at.** A plugin's `onAttack` hook runs once per swing, about the target. A character's, creature's or effect's hook runs for whichever side it's on, and `$.event.attacking` says which: true when they swung, false when they were swung at. - **`weapon` vs `weaponKey`.** `weapon` is the item's name. `weaponKey` is that exact object. Wear and tear goes on the key, or it lands on the spare in the pack instead of the blade in hand. - **What hurt them.** On `onDamage`, `abilityName` is the ability cast that dealt the harm, and `weapon` / `weaponKey` the weapon swung or the item whose rule dealt it. Each is empty for harm with no ability or weapon, such as a poison tick, a world event or a bare fist. - **`ammo`** is the round the swing spent, such as `Bodkin Arrow`, and empty when it spent none. `$.spawnItem({ itemExpr: $.event.ammo, at: "self" })` drops the loosed arrow where the target stands. - **`rounds`** is how many rounds the swing spent: 0 for none, 1 for most shots, more for a burst. A magazine counter takes `by: -$.event.rounds`. ## `onBeforeAction` says no It's the trigger for refusing. A [`refuse`](/docs/steps) in it stops the action and says why. ```js if ($.event.attack && $.field('stamina') < 5) { $.refuse('their arms are too heavy to lift the blade again') } ``` `$.event.actionOrdinal` is which action this is in the turn (0 for the first), so `$.event.actionOrdinal > 0` limits a turn to one action. Every swing by a player, an NPC or a creature passes through it before any ammunition is spent. The subject is the one swinging, and `$.weapon` is what they hold. ### A gun with a magazine [Ammunition](/docs/items-creatures#ammunition) draws loose rounds from the pack. For a gun that keeps a count of the rounds loaded in it, with one rifle empty while the spare is full, leave the gun's **fires** empty and give it a number variable such as `mag`. Then a plugin needs two hooks. `onBeforeAction` refuses the shot when that gun is empty: ```js if ($.event.attack && $.event.ranged && $.weapon && $.weapon.fields.mag <= 0) { $.refuse('the magazine is empty') } ``` `onAttack` spends the round from that exact gun. Its subject is the target. The gun is read off `$.source.weapon` and written through `$.event.weaponKey`: ```js if ($.event.ranged && $.source.weapon && $.source.weapon.fields.mag > 0) { $.adjustField({ field: 'mag', by: -1, item: $.event.weaponKey }) } ``` Reloading is a way of using the gun (`reload`) whose rule spends a magazine and refills the count: `$.consume('Rifle Magazine')`, then `$.setField({ field: 'mag', to: 30 })`. NPCs use items too and reload the same way. A gun like this has no ammo kind, and an NPC with an empty one does not switch weapons by itself. The refusal tells them why the shot never comes. ## `onBeforeTravel` decides the road A walk can cross several places in one turn. Before anyone moves, `onBeforeTravel` runs once for each leg, in order, with the place the party stands in as its subject. A [`refuse`](/docs/steps) ends the walk immediately. The party spends the turn in `$.event.from` and the narrator tells the reason. A refusal on the first leg means the party never sets out. | `$.event` | | |---|---| | `from` | where the party stands before this leg | | `to` | the next place | | `destination` | where the walk is headed | | `leg` / `legs` | which leg this is (1 for the first) and how many there are | | `distance` | this leg's length | | `arriving` | true on the leg that ends the walk | It runs before the people present answer, so everything the hook does is already there when they do. A creature it spawns appears in `from`, waiting where the walk stops, and anyone hostile there gets the usual ambush. Some long walks through wild country stop short: ```js if ($.event.legs > 1 && !$.event.arriving && $.random() < $.dial('roadTrouble')) { $.refuse('the road is washed out, and the party has to find a way round') } ``` Bandits on the road out of town: ```js if ($.event.leg === 2 && $.random() < 0.15) { $.spawnMob({ mob: 'Highway Bandit' }) $.refuse('bandits step out onto the road ahead') } ``` When the players are headed for different places that turn, the walk is decided later and this trigger doesn't fire. `onTravel` and `onLocationEnter` still fire for each leg actually walked. ## `onBeforeNpcTravel` is the same gate for NPCs NPCs walk one place per turn on their errands, schedules, patrols and wanderings. Before each step, `onBeforeNpcTravel` runs with the NPC as its subject. A [`refuse`](/docs/steps) keeps them where they are, and they remember why. A gate shut at night, for everyone: ```js if ($.event.to === "Old Town" && $.timeBetween("22:00", "06:00")) { $.refuse("the town gate is barred for the night") } ``` Pair it with the same check in `onBeforeTravel` and the gate holds for the party too. It does not fire for an NPC keeping pace with the party, fleeing a fight, or walking in on the party as part of how the people present answer. ## `onRoll` answers, never rewrites An `onRoll` hook runs once the roll is decided, before the people present answer. It can't change the roll. The roll card always explains its number, but whatever it sets off lands: damage, an effect, an item taken or given, a world flag, a creature, a narrated line. That's how a game gives failures teeth. Add a complication on a bad fail, but not on every fail, and not one that grants what the roll denied: ```js if (!$.event.passed && $.event.margin <= -5 && $.random() < $.dial('mishapChance')) { $.setWorld({ key: 'WATCH_ALERTED', value: 'YES', scope: 'location' }) $.narrate('the clatter carries down the street, and someone shouts for the watch') } ``` It's also how something improves with use: ```js if ($.event.passed && $.event.margin > 5 && $.event.note === 'read') { $.adjustField({ field: 'insight', by: 1 }) } ``` `margin` is total minus DC, negative on a failure. `crit` and `botch` read the natural die, which is a different question from `passed`. ## Example: a fever, in three hooks **`onTimePasses`**: it climbs. ```js if ($.field('fever') > 0) { $.adjustField({ field: 'fever', by: $.timed ? ($.event.minutes / 60) * $.dial('feverPerHour') : $.dial('feverPerTurn') }) } ``` **`onTurnEnd`**: a high fever hurts. ```js if ($.field('fever') >= 10) { $.damage({ amount: 1 }) } ``` **`onBeforeAction`**: too sick to fight. ```js if ($.event.attack && $.field('fever') >= 15) { $.refuse('the fever has taken their balance; the blade will not answer') } ``` ## Next [Conditions](/docs/conditions): gating when a hook may run. --- # Conditions Source: https://rpgforge.ai/docs/conditions.md A **condition** decides whether a rule may fire. Items, abilities, hooks, world events and quests all use the same one, so you only learn it once. It's a list of entries plus a mode: **all** (every entry must hold) or **any** (one is enough). ## Entry types - world flag - has item - character alive / at a location - the party is at a location (a journey, arrival, or return home) - item lying at a location (on the ground or fixed in place, not carried) - creatures killed (quest steps only), optionally only those killed at one place - stat comparison - field comparison - time of day - time since the game began - ability - **expression**: write the gate yourself - **narrative** (quests only): plain English, judged by the model Use the structured entries when they fit; they read better in the editor. Use **expression** for arithmetic or anything the entries can't say: ```js $.field('fever') > $.stat('resolve') * 2 ``` ## Narrative is quests only A **narrative** entry ("the player spoke to the mayor about the tides") is judged by the model. Everything except quests has to decide instantly, so narrative entries are rejected anywhere else. A hook can't stall a turn waiting on a model call. ## Example A door that opens only at night, only with the key, and only after the harbor has closed: - mode: **all** - time of day: `20:00` to `04:00` - has item: Lighthouse Key - world flag: `harbor` is `closed` The first two as one expression entry, with the world flag check left structured: ```js $.timeBetween(1200, 240) && $.hasItem('Lighthouse Key') ``` `$.timeBetween` takes minutes into the day, so `20:00` is `1200`. ## Time since the game began The world clock opens on day one at the game's start hour, not at zero, so comparing `$.timeMinutes` against a small number is true from the first turn. The **time since the game began** entry counts from the first turn instead, and `$.minutesPassed` is the same number in an expression: ```js $.minutesPassed >= 360 // six hours in ``` For "six hours after the alarm was raised", start a timer from the step that raises it (`$.startTimer`, see [Steps](/docs/steps)) and give the event the timer trigger. ## Watch for `null` A field comparison against a field the subject doesn't have **fails**. If "doesn't have it yet" should pass, say so: ```js !$.hasField('infection') || $.field('infection') < 5 ``` See [Missing values](/docs/missing-values). --- # Quests Source: https://rpgforge.ai/docs/quests.md The editor side is on [Quests without code](/docs/quests-no-code). This page covers the fields and the rule-side patterns. A quest is a list of **steps** (stages). Each has an optional [condition](/docs/conditions) and a list of [rule steps](/docs/steps) that run when it completes. - **With a condition**: completes the moment it holds. Exact and cheap. - **Without one**: the model judges it from the story. The `label` is what it judges, so write something observable: "Convince the harbormaster to look the other way". A `hasItem` condition with `handTo` completes when the player hands the item to that NPC, usually the quest-giver, and the item leaves their pack. Without `handTo`, holding it is enough. With the world's coin and a `quantity`, a hand-over to the giver represents a payment, such as a debt, a toll, or a bribe. Never ask for something the player already holds when the quest begins (their starting gear, a gift from the opening scene, or the giver's stock): that step is done before it starts. ## Rewards - Each step's rule steps run as that step completes. - `rewardSteps` on the quest is the final payoff, and the quest-giver names what it grants when they pitch the job. ## When the giver pitches it A giver brings a job up only when the players ask for work, offer help or ask about their trouble, or the story stirs them toward the party. `urgent: true` makes them raise it unasked as soon as they are with the party: for a plea, an emergency, or someone who came looking for the players. Leave it off for most jobs. ## Wiring with world flags Have actions set a world flag, and gate later steps on it: ```js $.setWorld({ key: "harbor", value: "closed" }); ``` Rules read it back through `$.world`: ```js $.world.harbor === "closed"; ``` World flags are visible everywhere. A location, an NPC, and a quest step can all react to the same fact without knowing about each other. Declare a flag under [World flags](/docs/story#world-flags) before a rule names it. ## Forks Steps run in order, unless the quest sets `anyOrder: true`. With that setting, every step is open from the start and completes independently, useful for tasks like paying each person owed. To fork, give each path separate steps and **retire the path not taken** with `skipIf`. When true, this condition marks the step failed and moves on. ```js $.setWorld({ key: "path", value: "mercy" }); // the step that forks writes the choice ``` | Step | `condition` | `skipIf` | | ------------------------------- | ----------------- | ------------------------------- | | Escort him to the checkpoint | `escorted = true` | `path = blood` | | Report the body to the precinct | `reported = true` | `path = mercy` | | Collect your pay | `paid = true` | none: this is where they rejoin | The skipped step shows as **failed** instead of completed. Three-way forks are two skips in a row. ### When the choice is made in play A choice made in conversation (taking one side of a feud, sparing a prisoner) does not use a rule to run `$.setWorld`. Make the step before the fork a **choice**: give it an `outcome` with a key and the ways it can go, and the fork's `skipIf` gates read that key. ```json { "id": "DECIDE", "label": "Decide the courier's fate", "outcome": { "key": "path", "choices": [ { "value": "mercy", "when": "The player let the courier go." }, { "value": "blood", "when": "The player killed the courier." } ] } } ``` While the step is active, the narrator is asked which choice happened. The step then completes with `path` set to one of the listed values. A rule that sets `path` first (using an item, say) completes it the same way. A `condition` on a choice step is what must hold before it is asked, such as being in the right place. For a choice that belongs to no quest, a plugin can [ask the narrator](/docs/plugins#asking-the-narrator) instead. **`optional: true` is not a fork.** It means "not needed to finish". An incomplete optional step still **blocks** the quest, so two optional arms on opposite flags park the quest forever. ### Or branch the outcome When both paths do the same tasks and only the payoff differs, keep one list and branch inside the step's rule steps: ```js if ($.world.path === "mercy") { $.grantXp(50); } else { $.give({ item: "Bounty Purse" }); } ``` ### Or branch the story For a choice that changes everything after it: quest A's `rewardSteps` sets a flag, and two follow-up quests have opposite `introduceCondition`s on it. Only one is ever offered. ## Quests with no NPC A notice-board bounty, a curse that starts in the crypt, the game's main thread: these live on the game in `quests[]`, not on a character. `locationNames` scopes where the quest can be **introduced**. `["Notice Board"]` means only there; empty means anywhere. Once open, the quest travels with the player. Three ways it opens: - **`$.startQuest({ quest: 'HARBOR_BOUNTY' })`** from any rule body, like an item, a location event, or a hook. Safe to run twice. An open or finished quest is left alone. - **`autoIntroduce: true`** opens it the moment `introduceCondition` holds. Good for the main thread ("the plague has started"). - **Judged discovery**: leave `autoIntroduce` off and set an `introduceCondition`. Each turn the condition holds, the narrator is asked whether the player has actually _learned_ of the quest (read the notice, overheard it). The condition is required here: without it the quest would be put to the narrator every turn forever. An ungated quest is never judged. ### Who pays Without a `rewardGiver`, a world quest pays as soon as its last step completes. Set `rewardGiver` to an NPC and the reward waits for the player to go back to them. ## When the giver dies The reward comes from a person. If the person who **pays** dies, the quest fails, even if the work was done. Set `failOnGiverDeath: false` for jobs that outlive the giver, like a letter addressed to someone else. ## Example _The keeper's silence_ 1. **Talk to the keeper.** No condition; judged. 2. **Find the logbook.** Condition: has item Logbook. Rule step: `$.setWorld({ key: 'knows_about_tides', value: 'yes' })` 3. **Confront the harbormaster.** No condition. The narrator knows about the logbook because step 2 set a flag. 4. **Reward:** `$.grantXp(50)` and an item. --- # Plugins Source: https://rpgforge.ai/docs/plugins.md A **plugin** bundles fields, dials, hooks and events into one system you can switch off, edit, share, and add to other games. Hunger, rest, stamina, mana, encumbrance and NPC bonds are all plugins. **None of them are engine code.** Open one in code view for a complete working example. ## The rule **Deleting a plugin must leave a working game.** If your system can't be switched off cleanly, it's engine code in disguise. Design for it from the start. What does a game look like without your plugin? That question matches what happens when someone uninstalls it. ## What a plugin can declare | Part | What it is | |---|---| | [Fields](/docs/fields) | Values stored on things, like a meter with tiers and a HUD bar, or a plain number. | | [Dials](/docs/formulas) | Tuning numbers, editable in the plugin's panel. | | Tables | Lists of records your rules read with `$.table()` and `$.row()`. | | [Hooks](/docs/hooks) | The behavior. | | [Actions](#actions-and-abilities) | Something a player does that the plugin manages, such as probe, forage, or sense. | | [Events](/docs/plugin-cooperation) | Moments you let other plugins refuse. | | Sections | A question the plugin adds to the model's turn, or prose it contributes. | | [Seams](/docs/seams) | Extension points that *replace* an engine calculation instead of adding to it. | | Scene layers | What the plugin draws over the location: particles, fog, a color grade, a wash, a sound. | | [Tools](/docs/generators) | Generators that create new content during play. | ## Actions and abilities An **action** is something a player does that your plugin owns. The model can pick it from the player's words like any built-in act, and when its roll resolves, its **after roll** statements run with `$.event.passed`, `$.event.crit` and `$.event.margin`. Probing and foraging are actions. An ability can perform an action instead. Set the ability's **Performs** to the action's key, and casting it runs that action's after roll on the cast's roll. An ability without a roll counts as passed. Two more values come with it: | Value | What it holds | |---|---| | `$.event.ability` | The ability's name, such as "Detect Magic". | | `$.event.abilityText` | Its description, which says what this use is for. | Mark an action **Ability only** when nobody should do it without the ability. The model is then never offered it alone. That way, a character who lacks Detect Magic can't sense magic just by saying so. **Sensing** is the worked example; open it in code view. Its one action, `sense`, is ability only. On a passed cast it reads `$.game` for everything in the current place that carries rules (an enchanted item lying there or carried by someone there, a power someone there holds, a person with a quest), uncovers what's hidden there with `$.reveal`, and tells the narrator all of it with the ability's description, so Detect Magic tells of the enchanted ring and Smell Poison of the tainted cup. With nothing there, it says plainly the sense finds nothing. Each entry in `$.game` has `here`: `"seen"` when it's in the current place or carried by someone there, `"hidden"` when it's there but out of sight, and `""` elsewhere. ## Drawing on the scene A **scene layer** puts something on screen. It names a world-state key your hooks write and one of your tables. The value at that key picks a row, and the row's presentation columns are what the scene shows: | Column type | What it draws | |---|---| | Particles | Something falling or drifting, tuned against a live preview. | | Grade | How the scene is colored: dimmer, drained, warmer, hazier. | | Wash | Water streaking down the view. | | Fog | Drifting fog, how thick and how much it veils. | A row can also carry `label` and `icon` (shown in the scene's readout), `sound` and `soundVolume` (an ambient loop), and `overcast` (dims the sky). A row leaves out whatever it doesn't draw. Weather has two layers. The sky reads `WEATHER` from its conditions table, and fog reads `WEATHER_FOG` from its fog table. Open it in code view to see them: ```js scene([ { stateKey: "WEATHER", table: "conditions", outdoor: true }, { stateKey: "WEATHER_FOG", table: "fog", outdoor: true } ]) ``` Mark a layer `outdoor` when a roof should keep it out: in a location tagged indoor it isn't drawn, and its sound is heard muffled. A value without a matching row produces no visuals, so "none" needs no row. ## Asking the narrator A **question** (a section, in the plugin panel) adds something to the model's turn. After the turn is narrated, for example, it can ask "did the player accept the bargain?", offer fixed **Choices**, and run statements on the answer as `$.answer.`. Act on the answer with plain branches, one per choice, such as `if ($.answer.choice === 'accepted') { $.setWorld({ key: 'bargain', value: 'accepted' }) }`. Give every question an **Only ask when** gate. An ungated question is asked on every turn of every session and costs tokens everywhere. A gated one is asked only while its gate holds: while a choice is still open, or while the person who offers it is present. ## Your first plugin 1. Open **Plugins** and create one. 2. Declare a field. It shows up on the character sheet. 3. Add a hook that changes it. 4. Add something that changes it back. 5. Play a few turns. Then read [Designing a plugin](/docs/good-plugin). ## Sharing Publish from your library. Other authors add it from the **Assets** step, which makes a **copy**. They can edit freely without affecting you, and name clashes are handled for you. A plugin that uses what another plugin provides (its fields, tables, steps, tools, actions, or the world flags and timers its hooks write) needs that plugin. Saving it to your library lists the plugins it needs as fixed rows, and the saved bundle carries them. Guard a read with `$.hasPlugin` to keep the dependency optional. The editor warns when something a rule uses comes from a plugin that is off or missing, when nothing at all provides it, and when a rule builds a field or table name at run time, since no check can tell which plugin that name needs. Write names out. --- # Designing a plugin Source: https://rpgforge.ai/docs/good-plugin.md A plugin that validates isn't finished. Most broken systems here save cleanly and then never fire, or produce effects that players never notice. This page is about getting past that. ## Start with the decision A system is only interesting if it makes the player **choose** something. Before you declare a field, finish this sentence: > Because of this system, the player has to decide whether to ___. - Hunger: *spend a day foraging, or push on hungry.* - Infection: *treat the wound now with the only medicine, or save it.* - Reputation: *help the smugglers, or stay welcome in town.* If you can't fill that blank, you have a bare number without a real system. ## Rules decide, the model narrates If fields can settle a result, write it as a rule. A modifier that follows from what a character wields and where they stand is a computed field with a `rollTerm`: ```js valueExpr: "$.row('reach', $.field('range', 'weapon'))[$.field('terrain', 'location')]" ``` Add a [question](/docs/plugins) only for what needs judgment. It costs tokens on every turn it asks. ## Every meter needs a way in and a way out For each field, write down: 1. **What raises it.** Time, an action, a place, an enemy. 2. **What lowers it.** An item, a rest, a person, a ritual. 3. **What the fix costs.** A trip, money, a risk, a turn. A meter nothing lowers is a countdown the player can't fight. A meter nothing raises never moves. A fix that costs nothing isn't a decision. Fixes usually belong in the **world** outside the plugin. For example, an herbalist sells the cure, or a shrine clears the curse. A plugin that ships without them is half a system. Say which items, NPCs or places your plugin expects in its description. ## Make it visible The player can't respond to what they can't see. - **Tiers are how the narrator notices.** Write tier prose that shows up in the scene: "his hands have started to shake" beats "infection: moderate". See [Fields](/docs/fields). - **Leave the calm tier silent.** If the lowest band says something, every turn includes a status report. - **Put the important meter on the HUD.** If losing to it ends the run, it belongs on screen. - **Warn before you punish.** Let a tier say "your stomach is hollow" before the damage starts. A penalty without warning feels like a bug. ## Tune with dials, not literals Every number a designer might want to change should be a [dial](/docs/formulas). Rates, thresholds, costs. Then an author can make your plague deadly or mild without opening code. - **Pick defaults by playing.** Play ten turns at the default. If the meter never reaches a tier, the rate is too low. If the player can't do anything else, it's too high. - **Separate per-hour and per-turn rates** if your system uses time. See [Minutes are not time](/docs/minutes-are-not-time). - **Let zero mean off.** An author who sets damage to 0 wants no damage. Check the dial before calling `$.damage`, since damage floors at 1. ## Play nicely with other plugins - **Ask before you read.** Use `$.hasPlugin('hunger') && ...` instead of a bare read of someone else's field. - **Offer events instead of reaching in.** If other systems might want to stop your action, declare an event and let them `refuse` it. - **Don't take a seam unless you must.** Only one plugin can own each [seam](/docs/seams). Taking one locks every other plugin out of it. The test for all of it: delete either plugin in any pair and the other still makes sense. See [Cooperation](/docs/plugin-cooperation). ## Keep it small One plugin, one idea. "Survival" as a single plugin with hunger, thirst, cold and sleep can only be all on or all off. Four small plugins let an author take thirst and leave the cold. Small plugins are also easier to debug. When a system fails to run, reading three hooks is easier than reading thirty. ## When it does nothing Most dead systems are one of these: - **A field that's `null`.** If no character has it, every comparison fails. See [Missing values](/docs/missing-values). - **Reading a different place than you wrote.** Values filled in a table, hook reads `$.location.fields`. - **The wrong trigger.** An `onTimePasses` rule in a game without a clock, or an `onDamage` rule that should have been `onAttack`. - **A frozen number.** A literal where a dial should be, now out of date. The full list is on [Common mistakes](/docs/common-mistakes). ## Checklist - [ ] I can say what decision this system forces. - [ ] Every field has something that raises it and something that lowers it. - [ ] The fix costs the player something. - [ ] Tier prose reads like narration, and the calm tier is silent. - [ ] Every tunable number is a dial. - [ ] Reads of other plugins' fields are guarded with `$.hasPlugin`. - [ ] Deleting the plugin leaves a working game. - [ ] I played ten turns with it on. --- # Fields Source: https://rpgforge.ai/docs/fields.md A **field** is a value your plugin puts on things: `satiety`, `infection`, `mana`. Declaring one is usually the first thing a plugin does. ## What a declaration gives you - a **range** (min and max). Every write is clamped to it. - **tiers**: what the narrator says at each band, and what the HUD badge shows. - **visibility**: a row on the sheet by default, or a HUD bar. - optionally, a **creation question** asked when a player builds their character. ## Tiers are what the narrator sees The narrator **never sees the number**. It sees the tier prose: | Band | Narrator reads | |---|---| | 0-3 | *nothing* | | 4-9 | "he has a fever" | | 10-14 | "veins darkening at the wrist" | | 15+ | "barely lucid, burning to the touch" | Write tiers as something a narrator would say in the scene. `"infection: 12"` isn't a tier. **Leave the resting tier silent.** Otherwise every turn includes a status report. ## Bands: absolute or ratio - **No max:** bands are absolute values. - **With a max:** bands are a fraction of the max. If your tiers look wrong, check whether you meant to set a max. ## Who carries it | Trait | Lands on | |---|---| | `entity` | everything that moves: players, NPCs, creatures, items | | `living` | players, NPCs, creatures | | `carryable` | items | | `player` / `npc` / `creature` | one kind only | | `location` | the place itself | `entity` does **not** include locations. A location field is how a place tracks its state: how corrupted this crypt is, how much game is left in the forest. Read it with `$.location.fields.corruption` or `$.field('corruption', 'location')`. ## A value per copy An item field with `scope: "instance"` lives on one copy, not on the item. A sword rolled `+3 (Blessed)` keeps that value, and the next Iron Sword rolls a new one. The item's **name never changes**. The player sees what sets a copy apart as a tag next to the name in the pack, the items nearby and the item window, the way charges show: | Field | Tag shown | |---|---| | text or enum | the value as written: `+3 (Blessed)`, `Vicious` | | number with tiers | the tier's badge | | number with no tiers | nothing on the card, and the item window shows the number | `visibility: "never"` hides it everywhere. When a player names one copy ("my blessed wand"), the command reader tells the copies apart by these same values. Write a text value the way you want it shown, since it is shown as written. ## Reading ```js $.field('infection') // the subject $.field('infection', 'target') // whoever was aimed at $.field('corruption', 'location') // the place $.field('reach', 'weapon') // what the subject wields, null when unarmed ``` Text and enum fields read like numbers. Missing reads as `null`, not `0`. See [Missing values](/docs/missing-values). ## Derived fields A field with a `valueExpr` is computed when read, not stored, like a carry limit worked out from might. You don't write to it. Because nothing is stored, `$.hasField()` says `false` for it, so branch on its inputs instead. --- # Cooperation Source: https://rpgforge.ai/docs/plugin-cooperation.md **Plugins never call each other.** They meet through shared engine state. That's what makes them removable: if hunger called into rest, deleting rest would break hunger. They meet in three places. ## 1. Shared fields Any plugin can read any field. So **ask before you rely on one**: ```js $.hasPlugin('hunger') && $.field('satiety') < 20 ``` Without the check, a game without the hunger plugin reads `null`, and your rule behaves as if everyone is always starving or never hungry. See [Missing values](/docs/missing-values). ## 2. Engine triggers One plugin's `$.damage()` fires `onDamage`, and another plugin's hook catches it. Neither knows the other exists. ## 3. Plugin events A plugin can declare an **event**: a moment it lets other plugins refuse. The rest plugin declares `rest:sleep`. Hunger answers it: ```js // hook on rest:sleep if ($.party.some(p => p.fields.satiety <= 0)) { $.refuse('they are too hollow with hunger to settle') } ``` A hook on an undeclared event never fires. So hunger works fine in a game without rest. A `refuse` in a hook on an event stops only that event. The rest of the turn still runs. ## The test **Delete either side of any pair, and the other still works.** Hunger without rest still drains and still starves; it just never refuses a sleep. Rest without hunger still restores; it just never gets refused. If deleting one breaks the other, you haven't built two plugins. You've built one in two pieces. --- # Formulas and dials Source: https://rpgforge.ai/docs/formulas.md ## Dials A **dial** is a tuning number your plugin declares with a default. Authors change it in your plugin's panel without touching code. ```js $.dial('foodDrainPerHour') ``` Dials belong to their plugin. Two plugins can each have a `baseRate` with different values. ## The engine's formulas `maxHp`, `travelSpeed`, `xpCurve` and the damage formulas aren't constants. They're **expressions** you can rewrite in Setup. ```js // maxHp as shipped 10 + Math.floor(($.stat('might') + $.stat('resolve') * 3) / 5) + ($.stat('playerLevel') - 1) ``` A game where toughness comes only from resolve: ```js 8 + Math.floor($.stat('resolve') / 2) ``` You're changing the shape of the rule, not just its numbers. ## Never freeze a dial ```js $.damage({ amount: 0.4 }) // wrong $.damage({ amount: $.dial('starvationPerHour') }) // right ``` A copied number is right until someone retunes the dial. Then two numbers disagree, the game behaves inconsistently, and nothing errors. You won't see it at the default setting, because both numbers still match there. ## Two stores: the tuned value wins A dial's value lives in two stores: - the plugin's declared **default**, - the author's **tuned** value from the panel. **The tuned value outranks the default.** If you change a plugin's default in a game where the author already tuned that dial, nothing changes in play. For agents editing plugins: `get_plugin` shows `tunedTo` next to `default` when they differ, so "make it a bit faster" means faster than the tuned number. `set_plugin` clears the tuned value for any dial whose default you actually change, and leaves the rest unchanged. --- # Seams Source: https://rpgforge.ai/docs/seams.md Everything else a plugin declares **adds**. A seam **replaces** an engine calculation. Only one plugin can own a seam. Two plugins both rewriting damage would have no defined result, so the engine doesn't allow it. ## The seams | Seam | Replaces | |---|---| | `variance` | damage spread | | `armor` | what a target subtracts | | `damageFormula` | turning the parts of a blow into a number | | `damageTaken` | what a blow costs the one taking it, after armor | | `weaponAttack` | the whole swing | | `levelUpAward` | what a level grants | | `enemyXpValue` | what a kill is worth | | `simulateNpc` | which NPCs the world thinks about while nobody's watching | | `simulationPriority` | which of those go first when there isn't room for all | ## They stack Replacing `damageFormula` leaves `variance` and `armor` in place; your formula can use them or not. `weaponAttack` exists for games where an attack isn't a roll against a defense at all, like damage decided by matching card suits. ## Big worlds: `simulateNpc` By default the engine considers every NPC every turn. Fine for a village, wasteful for a continent. Narrow it: ```js $.stat('hopsFromParty') <= 2 ``` That's distance from the party on the map as it is right now. `-1` means no route, which fails every `<=` test. Don't write a rule that's true forever. An NPC who's never simulated never finishes anything, so add a floor: ```js $.stat('hopsFromParty') <= 2 || $.stat('turnsSinceSimulated') > 10 ``` `simulationPriority` then ranks whoever is left when the turn can't fit everyone. ## When to use one Use a seam when the engine's calculation is **wrong** for your game, not when it needs tuning. Tougher characters? Edit the `maxHp` [formula](/docs/formulas). Damage from playing cards? Replace `weaponAttack`. If a dial or formula can say it, use that. A seam locks every other plugin out. --- # Generators Source: https://rpgforge.ai/docs/generators.md Everything else a plugin does works on things that already exist. A **generator** (a plugin *tool*) makes new ones during play, in response to what the players did. You describe the job in a sentence: ``` Add one new location further into the mine, connected to where they are standing. Put something in it: something living, something worth taking, or nothing if the place should be empty. Reuse creatures and items this mine already has where they fit, rather than inventing near-duplicates. ``` The model gets an overview of your world and makes everything the task needs in **one call**: places, people, items, creatures, abilities, effects, events, and sketches of what lies further on. ## Where things end up The game puts what was made where the tool fired, unless the model said otherwise: - a new **place** goes on the map next to the one it opens off (where the party is, by default) - a **creature** spawns there - a **person** lives there - an **item** drops on the ground - an **event** happens there So it is all present this turn, and the narrator can describe it. ## When it needs to look first Some jobs read before they decide: "look at what they did to the shrine, then either restore it or let it rot; add three of these; move that camp". Set `"mode": "agent"` for those. The tool then runs as an agent with the editor's tools: it reads the world, edits what exists, and moves things on the map. Anything new uses the normal build step and gets placed the same way. It takes several model calls instead of one, so use it only when one call can't do the job. ## Tell it to reuse A generator that only makes new things produces a list instead of a world. The tenth room gets the tenth new monster and nothing feels like it belongs. Because it reads before it writes, it can put more of the crawlers from four rooms ago here instead. **Say "reuse what fits"**, or it won't. ## Where it writes Everything a generator makes belongs to **that play session** instead of your permanent game. Two groups playing your world get different mines. Your authored game stays exactly as you left it. A generator can also make a session-only version of something you wrote, like your innkeeper in a worse mood. ## Declaring one ```json { "key": "newRoom", "describe": "The task, in your own words.", "context": "'They are ' + ($.player.fields.depth || 0) + ' rooms in.'", "body": "$.grantAbility({ abilityExpr: $.minted.name })", "fallback": "Copper Bit" } ``` - **`describe`**: the task. What to make. Don't explain what an item is; it knows. - **`context`**: an expression giving what's happening right now, as prose. "They're nine rooms deep and just collapsed a tunnel." - **`mode`**: `"build"` (the default, one call) or `"agent"` (reads first; several calls). - **`body`**: optional rule steps to run afterwards, for anything else that should happen. - **`fallback`**: an authored item to use if generation fails. Always set one. ## Firing it **From a rule**, for mechanical triggers like a threshold, a timer, or a reached location. ```js if ($.field('corruption') > 80) { $.tool({ tool: 'spawnBloom' }) } ``` **At the edge of the map**, use the `onMapEdge` [hook](/docs/hooks). It fires when the party arrives somewhere with every exit already visited, which is exactly when a dungeon should grow: ```js // hook: onMapEdge $.tool({ tool: 'newRoom' }) ``` The room is made on arrival, ready to enter next turn. **From the model's judgment**, for questions about the fiction ("did that fight leave salvage?"): add a yes/no field to a section and fire the tool in the section's body when the answer is yes. ```js if ($.answer.leftSalvage) { $.tool({ tool: 'salvage' }) } ``` ## Acting on what it made What was made is already placed. For anything more, like a second copy of the new item at the party's feet, use the body. You can't know the names beforehand, but you can read them here. `$.minted.name` is the first thing made (a new place first), `$.minted.mob` the first creature, `$.minted.item` the first item. ```js $.spawnItem({ itemExpr: $.minted.item }) $.grantAbility({ abilityExpr: $.minted.name }) ``` The `Expr` versions take an expression, while the plain ones take a fixed name. Use one or the other. ## Cost A generator is an extra model call while the player waits: one call, and once more if the first came up empty. In agent mode it's capped (twelve tool calls and six writes, each build counting as one write). A runaway just means a slow turn at worst. It still costs something every time, so **gate it**. A generator with no condition runs every turn. Put it on `background` when the result can wait without delaying the player. Put it on `rollPreprocess` when the narrator has to describe what appeared *this* turn. ## What it can't do - **Edit plugins.** A running game doesn't rewrite its rules. - **Delete things.** A player might be holding or standing in them. - **Change your game.** Only the session. --- # What you can't build Source: https://rpgforge.ai/docs/limits.md Most ideas are buildable. Hunger, infection, reputation, seasons, smithing, a curse that worsens at night: those are [fields](/docs/fields) and [hooks](/docs/hooks). This page lists what isn't, so you don't build something that saves fine and never works. ## Hard edges - **Hooks fire at a fixed set of moments.** The [hook list](/docs/hooks) is closed. If you need "the moment a trade completes", there's nothing to attach to. The nearest workable shape is usually `onTurnEnd` plus a field, which fires near the moment, not at it. - **No real-world time.** Game time only moves forward, on the game's clock. `$.passTime` and `$.startTimer` handle all scheduling. The world pauses between sessions. A garden can't grow overnight while the player is logged out, but it can grow a day's worth when they come back. - **Nothing outside the game.** No network calls, no files, no other sessions, no external APIs. - **No new interface.** No new panels, buttons, screens or minigames. The inventory, abilities, character sheet, journal, party and map panels already exist ([How a game plays](/docs/how-it-plays)). Rules write fields and narration; how the game is displayed isn't authorable beyond fields, tiers and the HUD. - **Narration is prose.** `$.narrate` tells the narrator something happened and it comes back as sentences. It won't show an exact number, a table, or a UI element. - **Generated content stays in the session.** A [generator](/docs/generators) can create locations, items and creatures during play, but only for that session, and it can't edit plugins or delete anything. ## Soft edges: possible, just not how you said it - **"Every N seconds"** → every turn, or every N in-game minutes. - **A new kind of thing** (a rank, a vehicle, a business) → usually a field on something that already exists. - **Replace core maths** → check the [seams](/docs/seams) first. You can't add one, but the one you want may be there. - **A procedural dungeon** → a generator on `onMapEdge`. - **A password, code phrase or command the player says or types** → a plugin [action](/docs/plugins#actions-and-abilities) whose description names the words. ## When it really is past an edge Stop. A near-miss system is worse than none: it costs credits, validates cleanly, and the first sign it never worked is a playthrough where nothing happens. Then bring it to **[Discord](https://discord.gg/uxz74KWfAG)**. The hooks, steps and seams all grew from people asking for something that wasn't there. The most useful request names the moment you needed and what you wanted to happen then. --- # Vendor stock and money Source: https://rpgforge.ai/docs/vendor-stock.md A vendor is a character with a `vendor` block. By default it sells without running out and pays without running dry. Everything below is **opt-in**. A vendor you don't configure behaves as it always did. ## Three modes | Mode | Set by | What runs out | |---|---|---| | Bottomless (default) | nothing | nothing | | Counted | `stock` on a sell entry, `till` on the vendor | the numbers you set, per session | | Pockets | `tradesFromInventory: true` | the character's real items and coin | ### Counted `stock` is a count on one sell entry. It drops as the player buys. At zero, sales of that item stop outright: no partial sale, no payment taken. `restock` refills it: `quantity` every `everyTurns` turns, up to `max` (defaults to the starting stock). `till` works similarly for money, tracking what the vendor can pay out, with optional refilling. The till moves both ways. It drops when they buy from the player and rises when the player buys from them. A vendor you've cleaned out can be funded again by trading with them. ### Pockets `tradesFromInventory: true` drops the counters. What the character carries is the stock; their coin is the till. What they sell is what a pickpocket could lift and what their corpse would drop. Their starting items are the opening stock, and `stock`/`till` are ignored. ## Guarantees - **Unset isn't zero.** No `stock` means untracked, not sold out. - **No false promises.** The narrator is told what's sold out and what the till can't cover before it writes the scene. - **No half trades.** No goods without payment, no payment without goods. A short sale is billed for what was actually handed over. - **The clock runs everywhere.** Every vendor restocks, not just the one in the room, and catches up over the turns that passed. ## Aisles Stock is grouped by each sell row's `category`, the vendor's section for it. It stays flat when grouping says nothing new: fewer than two sections, or one item per section. Rows without a section go under **Other**, last. Two spellings make two aisles. ## Mistakes - **A till without the currency.** A till lists what they can pay *in*. A currency not listed is one they can't pay in at all. - **`stock` on a pocket vendor.** Ignored. Give them starting items instead. - **Counting stock where it doesn't matter.** Players notice counts. Spend them where running out is an event, like the last antidote in a siege or three arrows before the smith reopens. --- # Vendor services Source: https://rpgforge.ai/docs/vendor-services.md A **service** is something a vendor does for the player, like sharpening a blade, giving a blessing, cursing a rival, or clearing out a cellar by filling it with rats first. The player pays, and the service's steps run once. Add one on the character's **Vendor** tab under **Services**. Each has a name, a price in an item, an optional line telling the narrator what the vendor does, and a body of steps edited with the same step editor (and code view) as everything else. Players buy a service the way they buy goods: "sharpen my sword", "bless Bram for me", "how much for the blessing?". Asking only quotes the price. Nothing runs until they pay. ## Three people A service has up to three people in it: | Who | What they are | How a step reaches them | |---|---|---| | **Recipient** | who the service is for (the buyer, or whoever they bought it for) | the default, no `targets` | | **Vendor** | who does the work | `targets: "self"` | | **Buyer** | who paid | `targets: "buyer"` | When the buyer buys it for themselves, the buyer and the recipient are the same person, and a step aimed at either lands on them. Buying for someone else only works when that person is in the scene. If they aren't, the purchase is refused and nothing is paid. `"buyer"` only means something inside a service. Anywhere else it reaches nobody. ```js // Blessing of the Grove $.heal({ amount: 10 }) // whoever it's for $.applyEffect({ effect: "Blessed" }) // whoever it's for $.adjustField({ field: "mana", by: -5, targets: "self" }) // the vendor pays in mana $.bond({ bond: "trust", by: 1, targets: "buyer" }) // whoever paid ``` ## What the body can read The body runs as though the vendor cast it at the recipient, so every step means what it means in an [ability](/docs/steps). Expressions see the three people too: | Read | Is | |---|---| | `$.subject` | the recipient | | `$.equipped` | the recipient's equipped slots | | `$.source` | the vendor | | `$.player`, `$.items` | the buyer and what they carry | That covers "do this to my held item": ```js // Sharpen Blade: works on whatever is in the recipient's weapon slot $.itemHealth({ item: $.equipped.weapon, by: 20 }) $.narrate("The edge sings off the whetstone.") ``` Slot names come from your game, so use the one your layout declares. And anything a step can do to the world: ```js // Rat Problem: sold by a very honest exterminator $.spawnMob("Rat") $.spawnMob("Rat") $.spawnMob("Rat") ``` ## Price and paying The price works like any other vendor price. It can be haggled, it is quoted when asked, and the the player pays before the body runs. That way, the body sees what they have left. A vendor with a [till](/docs/vendor-stock) takes the payment into it. A service is never out of stock and is bought one at a time. It costs the vendor no cooldown or resources unless the body spends them, as the mana example does. ## Good services - **Make the recipient matter.** A service that only ever helps the buyer could be an item. One you can buy *for* a companion, or *against* someone, is something only a person can offer. - **Let the vendor pay a cost.** A healer who tires with every blessing is a character. A `targets: "self"` step is how. - **Write the description for the narrator.** "lays moss on the wound and hums" is what the scene is built from. Leave it empty when the name already says it. --- # Common mistakes Source: https://rpgforge.ai/docs/common-mistakes.md None of these raise an error. All of them give you a rule that looks right but never fires. **Reading a stat by display name.** `$.stat('brawn')` breaks when the stat is renamed, and a missing stat reads `0`, and the rule keeps running on the wrong number. Use the role: `$.stat('might')`. → [Reading values](/docs/reading-values) **Treating a missing field as `0`.** It's `null`, and `null` fails every comparison, `<` included. `infection < 5` matches nobody who lacks the field. → [Missing values](/docs/missing-values) **`$.player` when you meant everyone.** `$.player` is the host only. Use `$.party`. **Charging per hour off `$.event.minutes` in a clockless game.** Those minutes are the narrator's guess; wordy turns cost seven times more. → [Minutes are not time](/docs/minutes-are-not-time) **A dial copied as a number.** Right until someone retunes the dial. → [Formulas and dials](/docs/formulas) **`$.damage` with a zero dial.** Damage floors at 1. Check the dial first. → [Steps](/docs/steps) **Reading a different place than you wrote.** Settings filled into a table, hook reads `$.location.fields`. → [Reading values](/docs/reading-values) **Numbers in narration.** `$.narrate('fever reduced by 2')` breaks the voice. Write the sentence a player should read. → [Steps](/docs/steps) **`optional` used as a fork.** An unfinished optional quest step blocks the quest. Use `skipIf`. → [Quests](/docs/quests) **Rolling dice in a condition.** `$.random()` returns `null` outside a rule body. → [Expressions](/docs/expressions) **Narrating an NPC who walked off.** `$.narrate` never checks who is in the room, so a wandering NPC can be described in an event while standing somewhere else. Gate the event on `$.at("Name", "Place")` or bring them in with `$.summon("Name")` / `$.teleport({ to: "Place", who: "Name" })`. → [Story and world events](/docs/story#world-events)