# Actions (https://ifloom.dev/docs/reference/actions) An action is something the player can do outside a scene's choices, such as buying a coffee, doing a shift or waiting a while. Your content declares the game's own in `actions`, and plugins offer theirs, such as a location's actions in the [places plugin](https://ifloom.dev/docs/reference/plugins/places) and an app's in the [devices plugin](https://ifloom.dev/docs/reference/plugins/devices). [State, commands and the view](https://ifloom.dev/docs/explanation/state-and-commands#locks-and-blocked-reasons) explains how refusals work, and [Give the player things to hold and use](https://ifloom.dev/docs/how-to/give-the-player-things) offers actions in a game. In the showcase: `examples/showcase/src/story/cafe.ts`, whose `coffee` action costs 3 coins and is refused once you've had one today. ```ts import { actionOf, effectsOf, need, whyNot, type ActionCost, type ActionDef, type Blocked, type ButtonDef, type Once, type Reason } from '@ifloom/engine' import { actionReferences } from '@ifloom/engine/plugin' ``` ## ButtonDef [#buttondef] The fields a scene's [`Choice`](https://ifloom.dev/docs/reference/scenes#choice) and an [`ActionDef`](#actiondef) share, so the two are written and read the same way. Every field is in [`ButtonDef`](https://ifloom.dev/docs/api/engine#buttondef). When the player chooses a choice or does an action, the engine runs its `command`, then pays its `cost`, then applies its `effects`. A `label` and its `labels` are words in place, with tokens filled in, and the first entry of `labels` whose `when` holds wins over `label`. `tags` reach the [`RenderedChoice`](https://ifloom.dev/docs/reference/view#renderedchoice) for a UI to style or filter by, and the engine gives them no meaning. `irreversible` is a warning the UI shows, and `ui` holds [presentation hints](https://ifloom.dev/docs/reference/ui-hints). ## ActionDef [#actiondef] An action the game declares in `actions`, or a plugin offers, with a choice's fields. Every field is in [`ActionDef`](https://ifloom.dev/docs/api/engine#actiondef). While no scene is open, each action with a `label` is a button in the room. An action with no label is never rendered, and a choice's `command`, another action or a hotspot does it with `{ type: 'action', id }`. The engine adds no action of its own, so the showcase declares a `wait` action in its content. | Field | Meaning | |---|---| | `id` | The action's id, unique among the game's actions. The view passes it on as the `RenderedChoice`'s `id`, and `[[act:id]]` in a room's prose names it. | | `when` | The condition the action is offered and done under. Without it, the action is always there. | | `command` | A [`CommandRef`](https://ifloom.dev/docs/reference/custom#commandref) the action sends before its cost and effects, any command but `choose` and never the action itself. | | `once` | How often the action can be done, a [`Once`](#once), counted in [`state.chosen`](https://ifloom.dev/docs/reference/state#chosen) under its id. | Doing an action sends one command, which is the one the runner's log keeps. An action with only a `command` sends that command, so a lock on the command stops it. An action with a cost, effects or `once` sends [`{ type: 'action', id }`](https://ifloom.dev/docs/reference/commands#action), which runs its `command` first. A plugin's action is named with the plugin's id in front, such as `{ type: 'action', id: 'places/coffee' }`. The engine asks that plugin for it, through its `action` provider or else the actions it offers in this state, so the café's coffee can be bought only while the café's actions are offered. This is the showcase's coffee, with a [macro](https://ifloom.dev/docs/reference/custom#macros) of the game's own that counts the cups: ```ts import type { ActionDef } from '@ifloom/engine' export const coffee: ActionDef = { id: 'coffee', label: 'Buy a coffee', cost: { stats: { coins: 3 }, reasons: { coins: 'Not even for a small one.' } }, blocked: [{ when: { kv: 'hadCoffee' }, reason: 'One is enough for today.' }], effects: [{ stat: 'energy', by: 15 }, { kv: 'hadCoffee', to: true }, { 'game/countCoffee': true }], } ``` A macro of the game's own in `effects` sees the state before the cost was paid. The [content checker](https://ifloom.dev/docs/reference/checks) checks what an action names, and doesn't look inside the game's code. ## ActionCost [#actioncost] The [stats](https://ifloom.dev/docs/reference/stats) an action spends, by id, with the words for a player who has too little. Every field is in [`ActionCost`](https://ifloom.dev/docs/api/engine#actioncost). The engine refuses the action when the player has less of any stat in `stats` than it costs. The refusal is the entry in `reasons` for that stat, or else the stat's [`lackingLine`](https://ifloom.dev/docs/reference/stats#lackingline). The view shows the cost on the button before it's pressed, as its [`Price`](https://ifloom.dev/docs/reference/view#price), listing the stats in the order `stats` gives them. A negative amount pays the player, so `{ coins: -5 }` adds 5 coins. It isn't checked against what the player has and isn't shown in the price, and [`effectsOf`](#effectsof) lists it as `{ stat: 'coins', by: 5 }`. An amount of 0 does nothing. ```ts fragment cost: { stats: { coins: 3, energy: 10 }, reasons: { coins: 'Not even for a small one.' } } ``` ## Blocked [#blocked] A reason something the player could do is refused for now, while its `when` holds. Every field is in [`Blocked`](https://ifloom.dev/docs/api/engine#blocked). An action, a scene's choice, a location, a device's app and a job each take a `blocked` list. The engine tests the entries in order, and the first whose `when` holds refuses with its `reason`, which is also the button's disabled text. With `hide: true`, the button leaves the screen while `when` holds, in place of being greyed out. The reducer and the view read the same list, so the two can't disagree. ```ts import type { Blocked } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' export const opening: Blocked[] = [ { when: calendar.weekday(6), reason: 'The café is shut on Sundays.' }, { when: { kv: 'barred' }, reason: 'Rosa won’t serve you.', hide: true }, ] ``` A [lock](https://ifloom.dev/docs/reference/locks) in content's `locks` is the other way to refuse things. A lock covers a rule across many commands, such as a stretch of the game that keeps the player at home, and `blocked` covers a reason that belongs to one thing. ## Reason [#reason] The words a player reads when something is refused, written in place or named by key in the [strings table](https://ifloom.dev/docs/reference/strings). Every form is in [`Reason`](https://ifloom.dev/docs/api/engine#reason). A reason written in place, such as `'Too tired.'`, is the game's own words. `{ string: 'shop/closed' }` names a line of the strings table, so a game rewords it once for every place it's used. The helpers that write a `blocked` entry use this form, such as `places.onlyAt()` with `places/notHere` and `shop.hours()` with `shop/closed`. [`reasonOf`](https://ifloom.dev/docs/reference/strings#reasonof) reads one, and the checker reports `no string named "…"` for a key no table has. ## Once [#once] How often something can be done, once in the whole game or once a turn. Every field is in [`Once`](https://ifloom.dev/docs/api/engine#once). A choice, an action and a [cheat](https://ifloom.dev/docs/reference/plugins/unlocks#cheatdef) take one as `once`, and a [trigger](https://ifloom.dev/docs/reference/triggers#triggerdef) takes its `per`. `per: 'game'` is spent once it has been done, and `per: 'turn'` is spent until the turn ends. A spent one is refused with `reason`, which shows on its button, or with the engine's `done` string, `Already done.`, when `reason` is left out. ```ts fragment once: { per: 'turn', reason: 'Once a day is plenty.' } ``` For a wait of more than one turn, leave out `once` and refuse the choice with a `blocked` entry on the [`since`](https://ifloom.dev/docs/reference/conditions#since) condition, counting from the last time it was chosen, as [Rest a scene between visits](https://ifloom.dev/docs/how-to/schedule-daily-work#rest-a-scene-between-visits) shows: ```ts fragment blocked: [{ when: { since: 'cafe.counter#chat', last: true, lt: 3 }, reason: 'You only just talked.' }] ``` ## View [#view] While no scene is open, `view.actions` lists the room's actions, each a [`RenderedChoice`](https://ifloom.dev/docs/reference/view#renderedchoice) made by [`renderAction`](https://ifloom.dev/docs/reference/view#renderaction). It lists the game's own first, then each plugin's, then content's actions with a label. A lock that denies `'*'` empties it (see [`lockedOut`](https://ifloom.dev/docs/reference/locks#lockedout)). The view leaves out an action whose command a lock with `hide` stops, and one whose own `blocked` entry with `hide` holds. A rendered action's `disabled` text is [`whyNot`](#whynot) for the command it sends, the function the reducer refuses with. Its `warning` is the first soft refusal a plugin's guard gives, on a button the player can still press, and its `price` is the action's cost with the notes plugins' prices add. To render the room's actions, see [Render the room's actions](https://ifloom.dev/docs/how-to/render/scene#render-the-rooms-actions). ## Functions [#functions] ### actionOf [#actionof] Returns the action that `{ type: 'action', id }` does in a state, or `undefined`. Its signature is in [`actionOf`](https://ifloom.dev/docs/api/engine#actionof). An id with no plugin in front is one of content's `actions`. An id with a plugin's id in front, such as `'places/coffee'`, is that plugin's, from its `action` provider or else the action of that id it offers now. ```ts given import { actionOf } from '@ifloom/engine' actionOf(state, game, 'wait')?.label // 'Wait a while' ``` ### need [#need] Returns a [`Blocked`](#blocked) entry written the other way round, refused with `reason` unless `when` holds. Its signature is in [`need`](https://ifloom.dev/docs/api/engine#need). `need(reason, when)` is `{ when: { not: when }, reason }`, for a refusal that reads better as what the action needs. ```ts import { need, type Blocked } from '@ifloom/engine' export const scarfNeeded: Blocked[] = [need('You need a scarf for this.', { owned: 'clothing:scarf' })] ``` ### whyNot [#whynot] Returns the line a command is refused with in a state, or `undefined` when it would go ahead. Its signature is in [`whyNot`](https://ifloom.dev/docs/api/engine#whynot). It answers for every command, actions, choices, inputs and plugin commands included. The reducer refuses with this line and the view greys out buttons with it. It tests a [lock](https://ifloom.dev/docs/reference/locks) first, then a plugin's guard or the game's own [`guard`](https://ifloom.dev/docs/reference/rules#gamerules), then what the command itself needs, whose lines are under [Commands](https://ifloom.dev/docs/reference/commands#command). A plugin command that sets `ignoresLocks` skips the first two, and so does the [`setting`](https://ifloom.dev/docs/reference/commands#setting) command. For an action, the engine tests in this order and refuses with the first that fails: 1. A scene is open: `Finish this first.` 2. Its `when` doesn't hold: `That is not on offer.` 3. A lock stops `{ type: 'action', id }`: the lock's `reason`. 4. An entry of `blocked` holds: its `reason`. 5. Its `once` is spent: `once.reason`, or `Already done.` 6. A stat in `cost.stats`, in the order written, is short: `cost.reasons[id]`, or the stat's `lackingLine`. 7. Its `command` would be refused: that command's reason. The engine's own lines come from the [strings table](https://ifloom.dev/docs/reference/strings) (`finishFirst`, `notOnOffer`, `done` and `notEnough`), so a game can reword them. ```ts given import { whyNot } from '@ifloom/engine' import { cast } from '@ifloom/plugin-cast' whyNot(state, game, cast.talk('ava')) // 'Ava is not here.' while she's elsewhere ``` ### effectsOf [#effectsof] Returns the effects a command would apply, worked out before it runs. Its signature is in [`effectsOf`](https://ifloom.dev/docs/api/engine#effectsof). Plugins' guards and prices, and [locks with `effect`](https://ifloom.dev/docs/reference/locks#lock), read it. The game's own macros among the effects are worked out against the state given. | Kind | Meaning | |---|---| | `action` | The effects its `command` would apply, then a `stat` effect of minus the amount for each stat in `cost.stats`, then its `effects`. | | `choose` | The effects of that choice in the open scene, as it renders now. | | `custom` | The plugin command's own `effectsOf`, or none when it has none. | | Any other | None, so `scene` gives none, and an unknown action or choice gives none. | ```ts given import { effectsOf } from '@ifloom/engine' effectsOf(state, game, { type: 'action', id: 'places/work' }) // [{ stat: 'energy', by: -30 }, { 'calendar/pass': { by: 2 } }, { stat: 'coins', by: 20 }] ``` ### actionReferences [#actionreferences] Returns what an action names, for the [content checker](https://ifloom.dev/docs/reference/checks): its conditions, effects, command, reasons and hints. Its signature is in [`actionReferences`](https://ifloom.dev/docs/api/engine-plugin#actionreferences). A plugin whose content holds actions, as a location's or an app's do, returns these from its `references`, so the checker checks them as it checks the game's own. ```ts import { actionReferences } from '@ifloom/engine/plugin' export const named = actionReferences({ id: 'wait', label: 'Wait a while', effects: [{ turn: true }] }) ``` ## Checks [#checks] The [content checker](https://ifloom.dev/docs/reference/checks) checks every action: | Problem | Cause | |---|---| | `no string named "shop/close"` | A `reason` names a key no strings table has. | | `spends unknown stat "gold"` | `cost.stats` names a stat the game doesn't declare. | | `an action's command can't be the action itself; give it the effects` | The action's `command` sends the action, and the engine leaves the command out. | ## Caveats [#caveats] - A plugin guard's soft refusal isn't in the order `whyNot` tests for an action. The button stays pressable with the line as its `warning`, and the engine refuses the command with it. - `effectsOf` lists only the effects the command applies directly. It leaves out what a plugin's effect applies in turn, and what `places/go` and `cast/talk` do, since neither lists effects. - `blocked` comes before `cost`, so a player short of energy reads a `blocked` line first when both hold. A `blocked` entry on the stat itself, ahead of the others, puts the energy line first. # Amounts (https://ifloom.dev/docs/reference/amounts) An amount is a number that content names and the engine works out when it reads it: a plain number, a stat, a kv key, a value, a count of entities, or a formula of them. Range bounds, a `stat` effect's `by` and `to`, a stat's `min` and `max` and a roll's target all take one, so "coins at least the rent" needs no code. [Effects and conditions are data](https://ifloom.dev/docs/explanation/state-and-commands) explains why content stays data. In the showcase: `examples/showcase/src/story/park.ts`, whose skimming roll has a target in `against`. ```ts import { amountOf, type Amount } from '@ifloom/engine' ``` ## Amount [#amount] A number content names that the engine works out when it reads it. Every form is in [`Amount`](https://ifloom.dev/docs/api/engine#amount). | Key | Meaning | |---|---| | `12` | The number as written. | | `'coins'` | The player's stat with that id. | | `{ stat, of? }` | A stat, the player's or with `of` an entity's, read as [`statValue`](https://ifloom.dev/docs/reference/stats#statvalue) reads it. | | `{ kv, of? }` | A key's number in a [kv store](https://ifloom.dev/docs/reference/glossary#kv), the player's or with `of` another's. A value that isn't a number counts as 0. | | `{ value, with? }` | A [value](https://ifloom.dev/docs/reference/custom#values) by name, the game's own (`game/…`) or a plugin's, asked with `with`. Text that reads as a number counts as that number. | | `{ count, where? }` | The number of entities, counted as the [`count`](https://ifloom.dev/docs/reference/conditions#count) condition counts them. | | `{ sum }`, `{ product }`, `{ min }`, `{ max }` | The sum, product, least or greatest of a list of amounts. | | `{ scale, by }` | An amount multiplied by the number `by`, so `{ scale: 'coins', by: -1 }` is minus the player's coins. | | `{ clamp, min?, max? }` | An amount held between two numbers. | `of` names the owner as it does in conditions: an [`EntityRef`](https://ifloom.dev/docs/reference/common#entityref), `'$'` inside an [`each`](https://ifloom.dev/docs/reference/effects#each) or a `where`, and `'storyline:'` or `'minigame'` for a kv key. An amount that doesn't read as a finite number is 0, and so is an owner that isn't there. The engine works an amount out each time it reads it: as an effect applies, as a condition is asked, or as a stat is held to its range. A choice's [price](https://ifloom.dev/docs/reference/view#price) reads its `stat` effect's amount in the state on screen. These fields take an amount: - The bounds of every [`Range`](https://ifloom.dev/docs/reference/common#range), in every condition that takes one, a call's own bounds included. - The [`stat`](https://ifloom.dev/docs/reference/effects#stat) effect's `by` and `to`. - The [`kv`](https://ifloom.dev/docs/reference/effects#kv) effect's `by`, and each end of its `random`. - The [`receive`](https://ifloom.dev/docs/reference/effects#receive) and [`release`](https://ifloom.dev/docs/reference/effects#release) effects' `by`. - A [roll](https://ifloom.dev/docs/reference/rolls)'s `plus` and `against`. - A [stat](https://ifloom.dev/docs/reference/stats#statdef)'s `min` and `max`. - A plugin field the plugin declares to the checker as `{ amount }`, such as an [achievement](https://ifloom.dev/docs/reference/plugins/achievements)'s progress or a [device](https://ifloom.dev/docs/reference/plugins/devices) app's badge. This content caps energy at the player's fitness, and pays each member of staff their own wage: ```ts import type { Content } from '@ifloom/engine' export const week: Content = { stats: [ { id: 'fitness', label: 'Fitness', start: 40 }, { id: 'energy', label: 'Energy', start: 30, max: { stat: 'fitness' } }, ], actions: [ { id: 'payday', label: 'Pay the staff', effects: [{ each: 'staff', effects: [{ stat: 'coins', by: { scale: { stat: 'wage', of: '$' }, by: -1 } }] }], }, ], } ``` ## Functions [#functions] ### amountOf [#amountof] Returns an amount worked out in a state, as the engine reads one. Its signature is in [`amountOf`](https://ifloom.dev/docs/api/engine#amountof). A plugin calls it for a field of its own that takes an amount, and declares the field to the [content checker](https://ifloom.dev/docs/reference/checks) as `{ amount }` in its [references](https://ifloom.dev/docs/reference/plugin-checks). ```ts given import { amountOf } from '@ifloom/engine' amountOf(state, game, { stat: 'coins' }) // 12 amountOf(state, game, { sum: ['coins', { kv: 'tips' }] }) // 15 amountOf(state, game, { count: 'staff' }) // 2 ``` ## Checks [#checks] The [content checker](https://ifloom.dev/docs/reference/checks) reads every amount content writes, and reports these problems: | Problem | Cause | |---|---| | `unknown stat "gold"` | The amount names a stat the game doesn't declare, or one declared on another owner. | | `unknown storyline "nobody"` | A `{ kv, of: 'storyline:…' }` names a storyline the game doesn't declare. | | `no game value named "game/nothing"` | A `{ value }` names a value nobody declares. | | `an amount is a number, a stat id, a formula, { stat }, { kv }, { value } or { count }; this one is [3]` | The amount has none of the shapes above. | ## Caveats [#caveats] - In a `kv` effect, `to` stays a [`KvValue`](https://ifloom.dev/docs/reference/common#kvvalue) as written, since a string there is text and not a stat's id. A `kv` effect changes a key by an amount with `by`. - A stat's `max` or `min` that comes back to the stat itself, such as a derived stat whose ceiling reads it, reads its default (100, or 0) while the engine works it out. - A `max` or `min` naming a value nobody declares, such as one from a plugin the game no longer has, reads its default too. # Audio (https://ifloom.dev/docs/reference/audio) A game's audio is the tracks, playlists and channels it declares in its content's `audio`, which scenes, locations, effects and prose name by id. The engine plays nothing itself. It works out what each channel should play and which one-shot sounds are due, and lists them in `view.audio` for an audio player such as [`@ifloom/audio`](https://ifloom.dev/docs/reference/browser/audio-player) to play. [Add music and sound](https://ifloom.dev/docs/how-to/add-music-and-sound) gives the café music and a doorbell. No example game declares audio, so [Add music and sound](https://ifloom.dev/docs/how-to/add-music-and-sound) is the example. ```ts import { audioSrc, type AudioChannelView, type AudioCue, type AudioState, type AudioView, type ChannelDef, type GameAudio, type PlaylistDef, type TrackDef, } from '@ifloom/engine' ``` ## GameAudio [#gameaudio] The game's audio, declared in its content's `audio`. Every field is in [`GameAudio`](https://ifloom.dev/docs/api/engine#gameaudio). - **`tracks`** holds every [track](#trackdef) and [playlist](#playlistdef) by id. - **`channels`** holds the game's [channels](#channeldef), merged over the four defaults field by field. - **`default`** says what each background channel plays when nothing else names one. - **`mute`** names a `ui` toggle [setting](https://ifloom.dev/docs/reference/settings) that silences everything while it's on. - **`sound`** names a `ui` toggle setting that plays sound only while it's on, so a settings page can offer whichever reads right. With both `mute` and `sound`, either one silences. A game with no `audio` has no tracks, and `view.audio` lists no channels and no cues. [`loadGame`](https://ifloom.dev/docs/reference/content#loadgame) merges the content's and every pack's `audio`. A pack's track replaces one with the same id, a pack's channel is merged field by field, and its `mute`, `sound` and `default` entries win. This content gives the town calm music, a café murmur, a knock and a voiced line, with volume and mute settings: ```ts import type { Content } from '@ifloom/engine' export const sound: Content = { settings: [ { id: 'musicVolume', label: 'Music', affects: 'ui', type: 'range', min: 0, max: 100, default: 70 }, { id: 'muted', label: 'Mute', affects: 'ui', type: 'toggle', default: false }, ], audio: { tracks: { calm: { src: 'music/calm.ogg', channel: 'music' }, evening: { src: 'music/evening.ogg', channel: 'music', volume: 0.8 }, radio: { playlist: ['calm', 'evening'], order: 'shuffle' }, 'cafe.murmur': { src: 'cafe-murmur.ogg', channel: 'ambience' }, knock: { src: 'knock.ogg' }, 'ava.hello': { src: 'voice/ava-hello.ogg', channel: 'voice' }, }, channels: { music: { mode: 'background', volume: 'musicVolume' } }, mute: 'muted', default: { music: 'calm' }, }, } ``` ## TrackDef [#trackdef] One sound file the game ships, in `audio.tracks`. Every field is in [`TrackDef`](https://ifloom.dev/docs/api/engine#trackdef). `src` is the file, relative to the game's `public/audio/` folder, through [`audioSrc`](#audiosrc). A track plays on the `sfx` channel unless `channel` names another, so give music and ambience a `channel`, and the checker reports a track with none that a background placement names. `loop` is `true` unless set, and it matters only on a background channel. `volume` is the track's own, from 0 to 1, and 1 unless set. ## PlaylistDef [#playlistdef] Several background tracks played one after another, in `audio.tracks`, named anywhere a background track can be. Every field is in [`PlaylistDef`](https://ifloom.dev/docs/api/engine#playlistdef). `order` says how the list plays: | Key | Meaning | |---|---| | `'inOrder'` | The list plays once, then the channel is quiet. | | `'loop'` | The list plays over and over. It's the default. | | `'shuffle'` | The list plays over and over in an order drawn from the save's seed, the channel, the playlist's id and the turn it started playing. | A shuffled order stays the same for as long as the playlist plays, and a [replay](https://ifloom.dev/docs/reference/runner#replay) of the same commands draws the same order. In a shuffle, an entry can be `{ track, weight }` instead of a plain id, which weighs 1. The engine draws the order without replacement, the first track by weight from all of them, the next from the ones left, and so on. Every track still plays once in each pass, so weight only changes how early a track tends to come. This playlist puts `calm` first more often than not: ```ts fragment radio: { playlist: [{ track: 'calm', weight: 3 }, 'evening', 'bandstand'], order: 'shuffle' } ``` ## ChannelDef [#channeldef] A channel the game declares in `audio.channels`, which sets whether its sounds replace each other or overlap, and how they fade. Every field is in [`ChannelDef`](https://ifloom.dev/docs/api/engine#channeldef). A `'background'` channel plays one thing until it changes, and a `'cue'` channel plays each sound once, overlapping. `crossfade` is the milliseconds a background channel takes to fade from one track to the next. `volume` names a `ui` range setting for the channel's volume, and nothing has one until the game names it, so a game with no audio settings plays at full volume. `duck` quietens the channel to `to`, from 0 to 1, while any channel in `under` plays. Every game has four channels, and the game's are merged over them field by field: | Key | Meaning | |---|---| | `music` | A background channel with a crossfade of 1000. | | `ambience` | A background channel with a crossfade of 600. | | `sfx` | A cue channel, where a track with no `channel` plays. | | `voice` | A cue channel, where every `[[voice:id]]` plays. | A channel the game adds needs a `mode`, and a new background channel's crossfade is 1000 unless set. This ducks the music under a voice and adds a radio channel: ```ts fragment channels: { music: { mode: 'background', volume: 'musicVolume', duck: { under: ['voice'], to: 0.4 } }, radio: { mode: 'background', crossfade: 200 }, } ``` ## Effects [#effects] ### audio [#audio] Sets a background channel `to` a track or playlist, kept in the save, or silences it with `to: null`. The [`audio` effect](https://ifloom.dev/docs/reference/effects#audio) entry has its rules. ### sound [#sound] Plays a track once on its own channel, kept among the save's last 20 cues. The [`sound` effect](https://ifloom.dev/docs/reference/effects#sound) entry has its rules. ## State [#state] ### AudioState [#audiostate] The music and sounds a save keeps in [`state.audio`](https://ifloom.dev/docs/reference/state#audio). Every field is in [`AudioState`](https://ifloom.dev/docs/api/engine#audiostate). `channels` holds what `audio` effects put on channels, and a channel not listed is left to the location and the default. `cues` holds the last 20 `sound` effects, each numbered by `seq`, the running count of them. `shown` counts every time a scene is entered, and `started` holds what each background channel is playing and the turn it started, which seeds a shuffle. The engine updates `started` after every command. ## View [#view] ### AudioView [#audioview] The game's audio as [`view.audio`](https://ifloom.dev/docs/reference/view#view) lists it, for an audio player to play. Every field is in [`AudioView`](https://ifloom.dev/docs/api/engine#audioview). `channels` holds every channel, background and cue, as an [`AudioChannelView`](#audiochannelview). `cues` holds every kept `sound` effect, oldest first, then the open scene's sound and voice beats in order, each an [`AudioCue`](#audiocue). `muteSetting` is `game.audio.mute` and `soundSetting` is `game.audio.sound`. The engine never reads the [profile](https://ifloom.dev/docs/reference/profile), so the player reads those settings' values there itself. To play it, see [Play sound](https://ifloom.dev/docs/how-to/render/pictures-and-sound#play-sound). ### AudioChannelView [#audiochannelview] One channel as `view.audio.channels` lists it, with what it plays now. Every field is in [`AudioChannelView`](https://ifloom.dev/docs/api/engine#audiochannelview). A background channel plays the first of these that names it: 1. The open scene's [`audio`](https://ifloom.dev/docs/reference/scenes#audio). 2. An [`audio`](https://ifloom.dev/docs/reference/effects#audio) effect, kept in the save. 3. A plugin's `audio` provider, such as the [places plugin](https://ifloom.dev/docs/reference/plugins/places)'s for the location the player is at. 4. The game's `default`. `null` at any of these is silence, and nothing below it is asked, so a scene that sets `{ music: null }` stops the music until it closes. `track` is always `null` on a cue channel. `src` is `null` for silence or an unknown track, and for a playlist it's the first file, with every file, volume and the played order in `playlist`. The player multiplies `volume` by the value of the setting `volumeSetting` names. ### AudioCue [#audiocue] One sound that's due, for a player to play once per `key`. Every field is in [`AudioCue`](https://ifloom.dev/docs/api/engine#audiocue). The engine works each key out from the state, so it's the same across view calls, after a choice that keeps the scene open, and after a save is loaded: | Key | Meaning | |---|---| | `cue::` | A `sound` effect, numbered by its place in the running count. | | `scene::::` | A scene's `[[sound:id]]` or `[[voice:id]]` beat, due while the scene is open. | `` counts every time a scene is entered, so a scene entered again gets new keys and its sounds play again. Rendering the scene the player is already in, after a choice, isn't a new showing. A voice always plays on the `voice` channel. ## Functions [#functions] ### audioSrc [#audiosrc] Returns where a sound file is, relative to the page. Every parameter is in [`audioSrc`](https://ifloom.dev/docs/api/engine#audiosrc). It works as [`artSrc`](https://ifloom.dev/docs/reference/prose#artsrc) does for pictures. The path goes under `audio/`, a leading `/` or `audio/` is dropped, and a name with no extension gets `.ogg`. ```ts import { audioSrc } from '@ifloom/engine' audioSrc('cafe-murmur.ogg') // 'audio/cafe-murmur.ogg' audioSrc('/audio/knock.mp3') // 'audio/knock.mp3' audioSrc('music/calm') // 'audio/music/calm.ogg' ``` ## Checks [#checks] The [content checker](https://ifloom.dev/docs/reference/checks) checks everything content names against `game.audio`. A background placement is a scene's `audio`, a location's `audio`, an `audio` effect or `game.audio.default`. A sound is a `sound` effect, `[[sound:id]]` or `[[voice:id]]`. | Problem | Cause | |---|---| | `unknown track "…"` | A placement, a sound, markup or a playlist names a track that `game.audio.tracks` doesn't have. | | `unknown channel "…"` | A placement names a channel that is neither declared nor one of the four defaults. | | `channel "…" plays sounds, not background audio` | A placement names a cue channel, such as `sfx`. | | `track "…" is a sound on channel "…", not background audio` | A placement or a playlist names a track on a cue channel. A track with no `channel` is on `sfx`. | | `track "…" is background audio on channel "…", not a sound` | A sound names a track on a background channel, such as `music`. | | `"…" is a playlist, not a sound` | A sound names a playlist. | | `on undeclared channel "…"` | A track's `channel` names a channel the game doesn't have. | | `volume is not between 0 and 1` | A track's `volume` is out of range. | | `a playlist with no tracks` | A playlist's list is empty. | | `"…" is a playlist; a playlist holds tracks` | A playlist names another playlist. | | `"…" has a weight of …; a weight must be above 0` | A playlist entry's `weight` is 0 or less. | | `"…" has a weight, but only a shuffled playlist uses weights` | A playlist entry has a `weight` in a playlist that doesn't shuffle. | | `unknown setting "…"` | A channel's `volume`, `game.audio.mute` or `game.audio.sound` names a setting the game doesn't declare. | | `setting "…" is not a ui range setting` | A channel's `volume` names a setting that isn't a `ui` range. | | `setting "…" is not a ui toggle setting` | `game.audio.mute` or `game.audio.sound` names a setting that isn't a `ui` toggle. | | `ducks under unknown channel "…"` | A channel's `duck.under` names a channel the game doesn't have. | | `duck.to is not between 0 and 1` | A channel's `duck.to` is out of range. | | `mode is not "background" or "cue"` | A channel's `mode` is neither. | The checker reports these at `track `, `channel `, `audio` and `audio default`, or where the placement or sound is written. It also lists every track's file in its [`files`](https://ifloom.dev/docs/reference/checks#fileref). ## Caveats [#caveats] - Without a player such as `@ifloom/audio`, `view.audio` is only data, and nothing sounds. - A `sound` effect stays in `state.audio.cues` until 20 newer ones push it out. A player that has just started marks every key it can see as heard, or loading a save would replay old sounds. - `[[sound:id]]` in a location's body becomes a beat but no cue, because only an open scene has showings. Use the location's `audio`, or a `sound` effect on arrival. - A mod that removes a track leaves `track` set and `src` null, so the channel is silent. The checker reports the track first. - `volume`, `mute` and `sound` name `ui` settings, which the [profile](https://ifloom.dev/docs/reference/profile) keeps and the state never does, so they don't change the game. # The audio player (https://ifloom.dev/docs/reference/browser/audio-player) `@ifloom/audio` plays a game's sound in the browser. The engine works out what should be playing in [`view.audio`](https://ifloom.dev/docs/reference/audio#audioview) and plays nothing itself, and the audio player follows a runner and plays it with the browser's own `HTMLAudioElement`. It needs no framework and no build step, and it works from a page opened from disk. [Add music and sound](https://ifloom.dev/docs/how-to/add-music-and-sound) declares the tracks it plays, and [Play sound](https://ifloom.dev/docs/how-to/render/pictures-and-sound#play-sound) starts it in each framework. None of the examples has any sound yet. The `vanilla`, `vue` and `svelte` templates start the player in `src/main.ts` or `src/runner.ts`. ```ts import { startAudio, type AudioLike, type AudioOptions, type AudioPlayer } from '@ifloom/audio' ``` The package imports only `@ifloom/engine`, and `@ifloom/react` takes it as a peer dependency. A track's `src` is read through [`audioSrc`](https://ifloom.dev/docs/reference/audio#audiosrc), so `{ src: 'music/calm.ogg' }` is the file `public/audio/music/calm.ogg`, and [`ifloom check`](https://ifloom.dev/docs/reference/cli#ifloom-check) reports one that's missing. ## startAudio [#startaudio] `startAudio` starts playing a runner's sound and follows the runner until you stop it. Its signature is in [`startAudio`](https://ifloom.dev/docs/api/audio#startaudio). It reads `runner.view().audio` at the start and again after every change of state, and does this with each part: - **Background channels**, such as `music` and `ambience`, play one file each. When the file changes, the old one fades out while the new one fades in, over the channel's `crossfade` in milliseconds. A command that leaves the file as it was doesn't restart it, and a track loops when its `loop` says so. - **Playlists** play their files in the order the view gives, each after the last ends. A `loop` or `shuffle` playlist goes back to the start after the last file, and an `inOrder` playlist stops there. - **Cues**, the one-shot sounds, play once per [`key`](https://ifloom.dev/docs/reference/audio#audiocue). Cues on one channel overlap, except on the `voice` channel, where each line waits for the one before it to finish. - **Volume** is the track's own `volume`, times the channel's volume setting, times 0 while the game is muted. - **Ducking** quietens a channel while a sound plays on another, only on a channel whose [`duck`](https://ifloom.dev/docs/reference/audio#channeldef) the game declares. The channel goes down while that sound plays and comes back up when it ends, over 300 ms each way. ```ts import { browserRunner } from '@ifloom/browser' import { startAudio } from '@ifloom/audio' import module from './game.ts' const runner = await browserRunner(module.build().game) const player = startAudio(runner) ``` The React UI's `GameShell` and `mountGame` start the player when [`game.audio`](https://ifloom.dev/docs/reference/audio#gameaudio) lists any tracks. A UI of your own calls `startAudio` once, after it makes the runner. ### The first click [#the-first-click] Browsers let a page play sound only after the player has done something on it. The audio player starts silent and waits for the first `pointerdown` or `keydown` on `root`. It then plays everything that is due, such as the music for the location the player is at and any cue that came up in the meantime. A game with its own start button, or one inside a frame that gets the click, calls [`unlock`](#audioplayer) from its own handler. When the browser still refuses the music, such as after an `unlock` that no click caused, the player tries it again on the next click or key press. ### Cues played once [#cues-played-once] The player remembers every cue key it has played. At the start it counts each key already in the view as heard, so a reloaded page or a save loaded at the start doesn't replay a knock from three turns ago. It tells play apart from a jump. After one more command, the new cues play. After a load, a new game, an undo or a redo, the `sound` effects kept in the save count as heard, and the sounds and voices of the scene now on screen still play once. ### Volume and mute [#volume-and-mute] The player reads each volume from the ui [setting](https://ifloom.dev/docs/reference/settings) that `game.audio` names for the channel. It reads a range setting from its `min` to its `max` as 0 to 1, so 70 on a 0 to 100 slider is 0.7. It reads the values from [`runner.snapshot().settings`](https://ifloom.dev/docs/reference/runner#settings) and follows the runner, so a slider on the settings screen changes the volume at once. It uses the setting's `default` until the player stores a value, when the stored value no longer fits the setting, and when the runner has no profile. ```ts fragment settings: [ { id: 'musicVolume', label: 'Music', affects: 'ui', type: 'range', min: 0, max: 100, default: 70 }, { id: 'muted', label: 'Mute', affects: 'ui', type: 'toggle', default: false }, ], audio: { tracks: { calm: { src: 'music/calm.ogg', channel: 'music', volume: 0.8 } }, channels: { music: { mode: 'background', volume: 'musicVolume' } }, mute: 'muted', } ``` Here the calm music plays at 0.8 × 0.7. `mute` names a toggle that silences everything while it's on. `sound` names a toggle that reads the other way, silent while it's off. ## AudioOptions [#audiooptions] `AudioOptions` is the settings for `startAudio`, each optional. Every field is in [`AudioOptions`](https://ifloom.dev/docs/api/audio#audiooptions). | Field | Meaning | |---|---| | `createAudio` | The function that makes the element for a file. `new Audio(src)` if left out, and a test passes a fake. | | `log` | A function that receives a line for each decision the player makes. Nothing is logged if left out. | | `root` | The element whose first `pointerdown` or `keydown` unlocks sound. `document` if left out. | `log` shows what the player is doing where nobody can hear it, in a headless browser or a test. With `{ log: console.debug }` the console shows lines such as these: ``` started, 0 cues already heard; waiting for a click or key press unlocked music: play audio/music/calm.ogg sfx: play cue:1234:1 knock music: crossfade to audio/music/evening.ogg over 1000 ms voice: queue scene:1234:3:1:ava.hello ava.hello music: play refused for audio/music/calm.ogg (NotAllowedError) ``` A `play refused` line is the browser refusing to play sound before the page's first click or key press. The player notes it, carries on, and tries refused music again on the next click (`music: try … again`). It logs a file paused before it started, by a quick change of track, as `stopped … before it started`. ## AudioPlayer [#audioplayer] `AudioPlayer` is what `startAudio` returns, a function that stops the player with two methods on it. Every member is in [`AudioPlayer`](https://ifloom.dev/docs/api/audio#audioplayer). | Field | Meaning | |---|---| | `player()` | Stops following the runner and the page's clicks and key presses, and pauses every sound. A stopped player can't start again, so a new one needs a new `startAudio`. | | `unlock()` | Allows sound now, as the first click or key press does, and starts the sounds that are due. | | `play(src, channel?, volume?)` | Plays a file once on a channel, at a volume from 0 to 1. The channel is `'sfx'` and the volume 1 if left out. On `'voice'` it waits its turn as any voice line does. It unlocks sound first. | `play` is for a sound the view doesn't ask for, such as a button that plays a spoken line again. Its `src` is a path from the page, as `audioSrc` returns it. ```ts given import { startAudio } from '@ifloom/audio' import { audioSrc } from '@ifloom/engine' const player = startAudio(runner) player.play(audioSrc('voice/ava-hello.ogg'), 'voice') ``` [Play sound](https://ifloom.dev/docs/how-to/render/pictures-and-sound#play-sound) puts a replay button on each spoken line with a voice. ## AudioLike [#audiolike] `AudioLike` is the part of an `HTMLAudioElement` that the player uses. Every field is in [`AudioLike`](https://ifloom.dev/docs/api/audio#audiolike). A fake for a test needs only these fields, and calls `onended` when its file would have finished. Fades and ducking move in steps on `setTimeout`, so a test with fake timers moves them on with `vi.advanceTimersByTime`. ```ts given import { startAudio, type AudioLike } from '@ifloom/audio' const made: AudioLike[] = [] const player = startAudio(runner, { createAudio: (src) => { const element: AudioLike = { src, volume: 1, loop: false, currentTime: 0, ended: false, onended: null, play: () => Promise.resolve(), pause: () => {} } made.push(element) return element }, root: new EventTarget(), }) player.unlock() made.map((element) => element.src) // ['audio/music/calm.ogg'] ``` ## Caveats [#caveats] - The opening scene's cues don't play, because they're in the view when the player starts and count as heard. Start a scene's cue from a choice, or put music on a background channel, which plays once sound is unlocked. - [`ifloom build --inline-assets`](https://ifloom.dev/docs/reference/cli#ifloom-build) puts pictures into `index.html` but never sound, so a game with sound ships its `audio/` folder beside the page. - Two players on one runner play everything twice. `GameShell` and `mountGame` start one already, and the React UI's `useAudio` replaces it rather than adding a second. # Browser helpers (https://ifloom.dev/docs/reference/browser) `@ifloom/browser` holds the parts of a game that need a web page, which the engine leaves out because it has no DOM. It makes a runner with saves in the browser, keeps saves in `localStorage` or IndexedDB, sends the clock's ticks, and turns key presses into commands. Every helper is plain DOM, so a UI in any framework uses it, and so does the [React UI](https://ifloom.dev/docs/reference/react). [Start your own UI](https://ifloom.dev/docs/how-to/render/start) starts each helper beside the runner, and [Choosing a UI](https://ifloom.dev/docs/explanation/choosing-a-ui) compares the ways to put a game on screen. In the showcase: `examples/showcase/src/main.tsx`, which keeps saves in `localStorage` and mods in IndexedDB. The `vanilla` and `vue` templates' `src/main.ts` and `src/runner.ts` start `browserRunner`, `startClock` and `startKeys`. ```ts import { browserRunner, indexedDbDriver, localStorageDriver, nextSlot, startClock, startKeys, startRevealSkip } from '@ifloom/browser' ``` The package imports only `@ifloom/engine`. Each `start…` function returns the function that stops it. ## browserRunner [#browserrunner] `browserRunner` returns a [runner](https://ifloom.dev/docs/reference/runner) with saves, a profile and an autosave kept in the browser. Its signature is in [`browserRunner`](https://ifloom.dev/docs/api/browser#browserrunner). It calls the engine's [`createRunner`](https://ifloom.dev/docs/reference/runner#createrunner) with these options, and each [`RunnerOptions`](https://ifloom.dev/docs/api/engine#runneroptions) field you pass replaces that field's default whole: | Field | Meaning | |---|---| | `history` | `{ depth: 50 }`, so undo goes 50 steps back. | | `saves` | A [save store](https://ifloom.dev/docs/reference/saves#saves) on [`localStorageDriver`](#localstoragedriver), with keys that start with the game's id. | | `profile` | The [profile](https://ifloom.dev/docs/reference/profile) on the same driver. | | `autosave` | `{ every: 'turn' }`, into the `auto` slot. | The game starts from `start` when you pass it. Otherwise it starts from [`startingState`](https://ifloom.dev/docs/reference/commands#startingstate) with a random seed, so each playthrough draws its own variants, and with the player's stored play [settings](https://ifloom.dev/docs/reference/settings). `browserRunner` is async because it reads the profile first, so [`runner.snapshot().settings`](https://ifloom.dev/docs/reference/runner#settings) holds the player's ui settings from the first frame. A profile that can't be read starts the game with the settings' defaults. ```ts import { browserRunner } from '@ifloom/browser' import module from './game.ts' const { game } = module.build() const runner = await browserRunner(game, { backlog: { limit: 200 } }) ``` [`mountGame`](https://ifloom.dev/docs/reference/react#mountgame) and the `vanilla`, `vue`, `svelte` and `next` templates make their runner with it. [Start your own UI](https://ifloom.dev/docs/how-to/render/start#start-the-runner) renders its snapshot. ## Save drivers [#save-drivers] A [`SaveDriver`](https://ifloom.dev/docs/reference/saves#savedriver) keeps the data of a save store, a profile or a [mod store](https://ifloom.dev/docs/reference/mods). The engine has only [`memoryDriver`](https://ifloom.dev/docs/reference/saves#memorydriver), and these two keep the data in the browser. ### localStorageDriver [#localstoragedriver] `localStorageDriver` returns a save driver on `globalThis.localStorage`, or on the Web Storage you pass. Its signature is in [`localStorageDriver`](https://ifloom.dev/docs/api/browser#localstoragedriver). The driver looks for the storage on its first read or write, not when you make it. Where there's none, such as in Node or a locked-down iframe, that read or write rejects with `localStorage is not available here`. The save store turns the rejection into a reason such as `The game could not be saved.` (see [Strings](https://ifloom.dev/docs/reference/saves#strings)), and the runner passes it to `onSaveError`. Web Storage holds about 5MB per origin. Chromium gives every page opened from disk one origin, so every `file://` game the player has shares those 5MB. ```ts given import { localStorageDriver } from '@ifloom/browser' import { saves } from '@ifloom/engine' const store = saves(game, localStorageDriver(window.sessionStorage)) ``` ### StorageLike [#storagelike] `StorageLike` is the part of the Web Storage API that `localStorageDriver` uses. Both `localStorage` and `sessionStorage` are one. Every field is in [`StorageLike`](https://ifloom.dev/docs/api/browser#storagelike). ### indexedDbDriver [#indexeddbdriver] `indexedDbDriver` returns a save driver on IndexedDB, which holds far more than Web Storage. Every option is in [`indexedDbDriver`](https://ifloom.dev/docs/api/browser#indexeddbdriver). The driver opens one database, `database` (`'ifloom'` if left out), and creates it when it's missing. The database holds one object store of strings by key, `store` (`'saves'` if left out). Every game can share the default database, because each key starts with the game's id. `indexedDB` is `globalThis.indexedDB` if left out, and a test passes another, such as `fake-indexeddb`'s. The driver creates its object store only when it creates the database. An existing database opened with another `store` name has no such store, so every call rejects, and a new store needs a new `database` too. Where IndexedDB is missing, every call rejects with `IndexedDB is not available here`. ```ts import { indexedDbDriver } from '@ifloom/browser' import { mods } from '@ifloom/engine' const modStore = mods('small-town', indexedDbDriver({ database: 'small-town-mods' })) ``` ### IndexedDbLike [#indexeddblike] `IndexedDbLike` is the part of `indexedDB` that `indexedDbDriver` uses, so a test can pass its own. The browser's `indexedDB` is one. Its fields are in [`IndexedDbLike`](https://ifloom.dev/docs/api/browser#indexeddblike). ## startClock [#startclock] `startClock` sends the [`tick`](https://ifloom.dev/docs/reference/commands#tick) commands that run down [timers](https://ifloom.dev/docs/reference/timers) and a [minigame](https://ifloom.dev/docs/reference/minigames)'s timer, since the engine keeps no clock. Its signature is in [`startClock`](https://ifloom.dev/docs/api/browser#startclock). The clock runs only while a timer in `view.timers` or the minigame's timer counts down and the page is visible. It then sends a tick every `every` milliseconds, carrying the real time since the last one. When the player switches to another tab, it sends the time until then and stops, so a timer waits for them. A command that starts a timer, or moves a minigame to a new state, restarts the clock from that command. ```ts import { browserRunner, startClock } from '@ifloom/browser' import module from './game.ts' const runner = await browserRunner(module.build().game) const stopClock = startClock(runner) ``` Start one clock per runner, when the game starts. Two clocks would each send ticks, so the timers would run twice as fast. [Render timers](https://ifloom.dev/docs/how-to/render/timers-minigames-panels) shows the countdowns it drives. ### ClockOptions [#clockoptions] `ClockOptions` is the settings for `startClock`. Its one field, `every`, is the time between ticks in milliseconds, 100 if left out. Each tick carries the real time that passed, so a slower clock keeps time as well and only updates less smoothly. It's in [`ClockOptions`](https://ifloom.dev/docs/api/browser#clockoptions). ## Keyboard shortcuts [#keyboard-shortcuts] These helpers turn key presses into commands. Each one leaves alone a key the player types into a field and a key held with Ctrl, Alt, Meta or Shift. ### startKeys [#startkeys] `startKeys` starts the game's keyboard shortcuts. Its signature is in [`startKeys`](https://ifloom.dev/docs/api/browser#startkeys). It tries the keys in this order: the game's own keys in `map`, then Escape, then the number keys for the choices, then a minigame's keys. A key it uses does nothing else. While a dialog is open (see [`dialogOpen`](#dialogopen)), it leaves every key to the dialog. ```ts given import { startKeys } from '@ifloom/browser' const stopKeys = startKeys(runner, { escape: () => console.log('open the menu'), map: { F5: { type: 'action', id: 'quick-save' } }, }) ``` The templates call `startKeys(runner)` with no options. A game that starts it again with options removes the template's call, or each key is handled twice. With the React UI, pass `keys` to `mountGame` instead. ### KeysOptions [#keysoptions] `KeysOptions` is the settings for `startKeys`. Every field is in [`KeysOptions`](https://ifloom.dev/docs/api/browser#keysoptions). | Field | Meaning | |---|---| | `map` | The game's own keys, by [`KeyboardEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key), each with the command it sends. They come first, so mapping `'1'` or `'Escape'` replaces what that key does. | | `escape` | The function Escape calls. A function that returns `false` did nothing, so the key goes on to the page. | | `choices` | The number keys 1 to 9 choose the choices in [`numberedChoices`](#numberedchoices) order, skipping one that is greyed out. A function takes the key's number and returns whether it chose anything. `true` if left out. | | `minigame` | The keyboard presses a minigame's inputs through [`startMinigameKeys`](#startminigamekeys). `true` if left out. | ### startMinigameKeys [#startminigamekeys] `startMinigameKeys` presses the running minigame's inputs from the keyboard, mapping keys with [`minigameInput`](#minigameinput). Its signature is in [`startMinigameKeys`](https://ifloom.dev/docs/api/browser#startminigamekeys). It listens before other shortcuts, so a minigame's keys win over the number keys. A key that maps to an input never scrolls the page or does anything else, even while that input does nothing. `startKeys` starts it unless you pass `minigame: false`, and the React UI's [`MinigameCard`](https://ifloom.dev/docs/reference/react/components#minigamecard) starts it on its own. ### minigameInput [#minigameinput] `minigameInput` returns the id of the minigame input that a key presses, whether or not the input does anything now, or `undefined` for none. Its signature is in [`minigameInput`](https://ifloom.dev/docs/api/browser#minigameinput). It reads the minigame's own [`keys`](https://ifloom.dev/docs/reference/minigames#minigamedef) first. Without them, the arrow keys and space press the inputs `up`, `down`, `left`, `right` and `space`, and an input with a one-letter id is pressed by that letter in either case. ```ts given import { minigameInput } from '@ifloom/browser' minigameInput(runner.view().minigame!, 'ArrowLeft') // 'left' ``` ### numberedChoices [#numberedchoices] `numberedChoices` returns the choices the number keys choose, in order. They're the open scene's choices, or the room's [actions](https://ifloom.dev/docs/reference/actions) when the scene has none, and key 1 is the first. A UI uses it to show each button's number. Its signature is in [`numberedChoices`](https://ifloom.dev/docs/api/browser#numberedchoices). ### ignoredKey [#ignoredkey] `ignoredKey` returns true for a key press that shortcuts leave alone. That is a key typed into an input, a text area, a select or editable text, a key held with Ctrl, Alt, Meta or Shift, or one another handler has already prevented. A shortcut of your own calls it first. Its signature is in [`ignoredKey`](https://ifloom.dev/docs/api/browser#ignoredkey). ### dialogOpen [#dialogopen] `dialogOpen` returns true while the page shows a dialog, an open `` element or an element with the `dialog` or `alertdialog` role. The shortcuts stand aside while it's open, so the dialog's own keys and Escape reach it. Its signature is in [`dialogOpen`](https://ifloom.dev/docs/api/browser#dialogopen). ## nextSlot [#nextslot] `nextSlot` returns the slot for a new save, one more than the highest numbered slot in a listing of the saves, as a string. Its signature is in [`nextSlot`](https://ifloom.dev/docs/api/browser#nextslot). It returns `'1'` when the listing has no numbered slot. It skips slots with other names, such as `'auto'` and `'quick'`. A save that can't be read still holds its number, so a new save never writes over it. Pass it the snapshot's [`saves`](https://ifloom.dev/docs/reference/runner#saves-1), which the runner keeps up to date, or the result of [`saves.list()`](https://ifloom.dev/docs/reference/saves#saves). ```ts given import { nextSlot } from '@ifloom/browser' const saved = await runner.save(nextSlot(runner.snapshot().saves), 'Before the café') ``` [Render a save and load screen](https://ifloom.dev/docs/how-to/render/saves-and-settings#render-a-save-and-load-screen) uses it. ## Revealed prose [#revealed-prose] A UI decides how and when prose appears, from [ui hints](https://ifloom.dev/docs/reference/ui-hints) such as the React UI's [`reveal`](https://ifloom.dev/docs/reference/react/hints#reveal). This helper does the one part every such UI shares, a key that shows the rest at once. ### startRevealSkip [#startrevealskip] `startRevealSkip` calls `skip` on each key press until it's stopped. `skip` shows everything the scene still holds back. Its signature is in [`startRevealSkip`](https://ifloom.dev/docs/api/browser#startrevealskip). It listens before other shortcuts and stops the key there, so a number key can't choose a choice the player can't see yet. It leaves alone a key typed into a field and a key held with a modifier. Start it while a reveal is pending, and stop it once the scene shows in full. ```ts import { startRevealSkip } from '@ifloom/browser' import { showEverything } from './reveal.ts' const stopSkip = startRevealSkip(() => { showEverything() stopSkip() }) ``` [Add a transition](https://ifloom.dev/docs/how-to/add-a-transition) times a reveal in each framework. ## Caveats [#caveats] - `browserRunner` keeps its saves and profile in `localStorage`, which Node lacks. The runner still starts there, but every save, autosave and profile write fails with `localStorage is not available here`. A test passes `{ saves: saves(game, memoryDriver()), profile: profile(game, memoryDriver()) }`, or calls `createRunner` itself. - A timer runs out whether or not the UI renders it, so start `startClock` when the game starts, not only while a countdown is on screen. # Changes (https://ifloom.dev/docs/reference/changes) After each command the engine compares the stats your content tracks in `changes`, before and after, and lists what moved in `view.changes`. A UI shows it as feedback after a choice, such as `+3 coins` or `+4 Ava`, without working out the difference itself. In the showcase: `examples/showcase/src/world/stats.ts`, which tracks coins, energy, charm and each character's friendship. ```ts import type { Change, ChangesDef, ChangeView } from '@ifloom/engine' ``` ## ChangesDef [#changesdef] The stats whose changes the view lists, the `changes` key of content and packs. Every field is in [`ChangesDef`](https://ifloom.dev/docs/api/engine#changesdef). `stats` lists stat ids. An entity stat's id, one declared with [`of`](https://ifloom.dev/docs/reference/stats#of), covers that stat on every entity, so `friendship` tracks Ava's and Sam's alike. Every content file's and pack's lists are added together, so a mod can track a stat it adds without repeating yours. With no stat named anywhere, `view.changes` is always empty. The engine lists the changes in this way: - The player's stats come first, in the order the game declares them, then each entity's, for every entity with stats in the save before or after the command. - A stat whose [`visible`](https://ifloom.dev/docs/reference/stats#statdef) condition doesn't hold after the command is left out, so the list never gives away a hidden number. - A stat with `listed: false` is still listed here, for a UI that renders that stat its own way. - The comparison runs after the triggers and plugins' hooks, so what they moved in the same command counts. ```ts import type { Content } from '@ifloom/engine' export const stats: Content = { stats: [ { id: 'coins', label: 'Coins', start: 12, max: 999, format: { one: '{n} coin', other: '{n} coins' } }, { id: 'energy', label: 'Energy', start: 80, format: '{n}%' }, { id: 'friendship', label: 'Friendship', of: 'character' }, ], changes: { stats: ['coins', 'energy', 'friendship'] }, } ``` ## State [#state] ### Change [#change] One tracked stat the last command moved, as the save keeps it in [`state.changes`](https://ifloom.dev/docs/reference/state#changes). Every field is in [`Change`](https://ifloom.dev/docs/api/engine#change). `from` and `to` are the stat as [`statValue`](https://ifloom.dev/docs/reference/stats#statvalue) reads it before and after, with derived stats worked out and modifiers and rounding applied. `by` is `to - from`. `text` is the change in the stat's own [`format`](https://ifloom.dev/docs/reference/stats#statwords) with a sign, such as `+3 coins`, `-1 coin` or `-5%`, and the bare signed number when the stat has no format. `of` names the entity for a stat kept on one, and is left out for the player's. Every command replaces the list, with an empty one when it moved no tracked stat. A `tick` that moved nothing keeps the list as it was, so a clock ticking a [timer](https://ifloom.dev/docs/reference/timers) doesn't wipe the feedback from the choice before it. Because the save keeps the list, a loaded save, an undo and a [replay](https://ifloom.dev/docs/reference/runner#replay) show the same feedback. ## View [#view] ### ChangeView [#changeview] A [`Change`](#change) with the words to show after its `text`, as [`view.changes`](https://ifloom.dev/docs/reference/changes#view) lists it. Every field is in [`ChangeView`](https://ifloom.dev/docs/api/engine#changeview). `name` says what moved when `text` doesn't: | Field | Meaning | |---|---| | `name` for an entity's stat | The entity's name, such as `Ava`, as the view names entities for this save. | | `name` for the player's stat | The stat's `label`, such as `Energy`, when its format has no words besides the number, such as `{n}%`, or it has no format. | | no `name` | The stat's format already says it in words, such as `{n} coins`. | So `+3 coins`, `-1 Energy` and `+4 Ava` are each a change's `text` followed by its `name`. The view works out `name` each time it renders, so a translation or a renamed entity shows at once. To render the list, see [Render what changed](https://ifloom.dev/docs/how-to/render/stats-and-things#render-what-changed). ## Checks [#checks] The [content checker](https://ifloom.dev/docs/reference/checks) reports an id in `changes.stats` that is no stat, as `stats names "cions", which is no stat`. ## Caveats [#caveats] - Nothing is listed until content names some stats in `changes.stats`. A UI that renders `view.changes` in a game that tracks nothing shows no pills. - A stat that went up and back down in one command isn't listed, since the engine compares only the before and after. - An entity made or removed by the command has no change listed, because it isn't there on one side. - A stat that a plugin's modifier moves, such as a status starting, is listed, since the list compares what the player reads. # Checking content (https://ifloom.dev/docs/reference/checks) The content checker is `checkGame`, one walk over a game's content that reports each name the game lacks and lists every file it names. [`loadGame`](https://ifloom.dev/docs/reference/content#loadgame) runs it on the game it merges, so a loaded game's problems are in its result already, each pinned on the content or pack it came from. `ifloom check` prints them, and [Playtest and snapshot from the command line](https://ifloom.dev/docs/how-to/playtest-and-snapshot) runs it with probes. In the showcase: `examples/showcase/tests/showcase.test.ts`, whose test `loads with nothing wrong` expects the loaded town to have no problems. ```ts import { checkGame, describeProblem, type Checked, type FileRef, type Probe, type Problem } from '@ifloom/engine' import type { Reference } from '@ifloom/engine/plugin' ``` ## Checked [#checked] The result of [`checkGame`](#checkgame): the problems in a game's content, the warnings, and the files it names. Every field is in [`Checked`](https://ifloom.dev/docs/api/engine#checked). `problems` lists each [`Problem`](#problem) in the order the checker found it, and is empty when nothing is wrong. `warnings` lists what may go wrong in play but isn't a mistake in the content, in the same shape. So far the one warning is a token that may print nothing (see [prose](#prose)). [`ifloom check`](https://ifloom.dev/docs/reference/cli#ifloom-check) prints each warning as `warning: …` and doesn't fail on one. `files` lists every file the game names, each a [`FileRef`](#fileref). ## Probe [#probe] A state to render every scene in, with a name for the problems it finds. Every field is in [`Probe`](https://ifloom.dev/docs/api/engine#probe). For each probe, the checker renders every scene and reports `render threw: …` at `scene ()` when rendering one throws, such as when one of the game's own values throws for that state. Keep `name` short and without spaces. [`probe`](https://ifloom.dev/docs/reference/cli#probe) from `@ifloom/cli/game` makes one by playing commands and effects from the start, and a [game module](https://ifloom.dev/docs/reference/glossary#game-module)'s `probes` can go to `checkGame` as they are. ```ts given import { checkGame, startingState } from '@ifloom/engine' const later = { ...startingState(game), turn: 5 } checkGame(game, { probes: [{ name: 'day-five', state: later }] }) ``` ## Problem [#problem] One problem the checker found: where the thing came from, what it's in and what's wrong. Every field is in [`Problem`](https://ifloom.dev/docs/api/engine#problem). `pack` is `game` for a game built by hand. For a loaded game it's the pack that last declared or patched the thing, else the content's `name` (`content` when it has none), `base` for a key the base can't hold, or a plugin's id for what came from that plugin's own content. `where` names what the problem is in, such as `scene ava.hi`, and `what` says what's wrong. [`describeProblem`](#describeproblem) joins the three into one line. ## FileRef [#fileref] One picture, video or sound file the game names, with where content names it. Every field is in [`FileRef`](https://ifloom.dev/docs/api/engine#fileref). `path` is where the page asks for the file: after [`artSrc`](https://ifloom.dev/docs/reference/prose#artsrc) for a picture or a video, and after [`audioSrc`](https://ifloom.dev/docs/reference/audio#audiosrc) for a sound. So `{ src: 'door' }` is `art/door.jpg`, and a track's `'music/calm'` is `audio/music/calm.ogg`. The list covers these: - Every track in `game.audio.tracks`. A playlist names tracks, not files. - Every file in a [pool](https://ifloom.dev/docs/reference/media#pools). A pool request such as `[[img:@door]]` names no file itself, so its pool's files are listed instead. - A `{ media }` block's `src` and `poster`, and a picture layer's. - The files in picture and video markup in any prose, posters included. - The `image` of a `notify` effect and of an entity, declared or made by a `create` effect. A URL is left out. - Whatever a plugin's [references](#reference) name, such as a post's picture. The same file named in two places is listed once for each place. The CLI finds a game's files from this list alone. [`ifloom check`](https://ifloom.dev/docs/reference/cli#ifloom-check) looks for each one in `public/`, and [`ifloom build`](https://ifloom.dev/docs/reference/cli#ifloom-build) looks in the built folder. ## Reference [#reference] One name a piece of content gives, for the checker to resolve: an id by what it is, a file, or content to look inside. Every form is in [`Reference`](https://ifloom.dev/docs/api/engine-plugin#reference). A plugin builds these in its `references`, a trait's `references`, an argument's `.naming()` and a `CheckTools.problems` call, so the checker checks its content as it checks the engine's ([A plugin's content checks](https://ifloom.dev/docs/reference/plugin-checks)). Each form is checked this way: | Key | Meaning | |---|---| | `{ scene, as }` | A scene that has to exist. `as` words the problem, `gated on…` for a condition, `opens…` for a button and `goes to…`, the default, for an effect. | | `{ choice }` | A `scene#choice` key, checked as `chose` and `since` check it. | | `{ stat, of, writes }` | A stat read, or written with `writes`, on the player or on `of`. | | `{ stat, starts }` | A stat an entity of the kind `starts` is given a value for. | | `{ storyline }`, `{ kind }`, `{ trait }`, `{ action }`, `{ input }`, `{ minigame }`, `{ timer }` | An id the game has to declare. A plugin's action, with a `/`, isn't checked. A timer's `to` and `by` have to be milliseconds. | | `{ someone }` | Someone: `'player'`, `'you'` or a unique entity, checked as [someone](#someone) is. | | `{ protagonist }` | Whom a `you` effect makes the player play, checked as [protagonists](#someone) are. | | `{ receiver }` | A call that needs a plugin that keeps things, or with an id, that plugin, checked as [receivers](#receivers) are. | | `{ like, of }` | An entity a `create` makes a thing like, of the kind it makes. | | `{ minigameKv }` | A key some minigame declares in its `kv`. | | `{ entity }` | An entity by reference, such as `'food:apple'`, that content or a plugin's `entities` declares. `'$'` and `'food:*'` pass once the kind exists. | | `{ setting, is }` | A play setting, and a value it has to be able to take. | | `{ prose }`, `{ variants }` | A prose key that needs words, or a variants list that needs lines. | | `{ words, field, oldKey }` | Words written in place in the field `field`, reported when they are a prose key the game has, since a field of words never reads one. | | `{ outdated }` | Content written in a form the engine no longer reads, reported with the way to write it now. | | `{ value }` | A [value](https://ifloom.dev/docs/reference/custom#values), the game's own (`game/…`) or a plugin's. | | `{ openPanel, with }` | A [panel](https://ifloom.dev/docs/reference/panels) opened by name. Any name passes, and each plugin is asked what its `with` names. | | `{ dice, key, plus, against }`, `{ amount }`, `{ ui }` | A roll that has to be well formed, an [amount](https://ifloom.dev/docs/reference/amounts#checks) the engine has to be able to read, and [presentation hints](https://ifloom.dev/docs/reference/ui-hints#checks) that have to be data. | | `{ channel, track }`, `{ sound }` | A background placement, or a sound played once, checked as [audio](https://ifloom.dev/docs/reference/audio#checks) is. | | `{ pool, tags }` | A pool and the tags asked of it. | | `{ call, name, with }` | A call by name to a plugin's or the game's own condition, effect or command, in the [`CallTable`](https://ifloom.dev/docs/reference/plugin-checks) `call` names. | | `{ entry, plugin, list, noun }` | An entry in a plugin's content, such as a location, reported as `unknown location "…"`. It isn't checked when the game lacks that plugin. | | `{ picture }`, `{ video }`, `{ audio }` | A file, listed in [`files`](#fileref). A URL isn't listed. | | `{ reason }` | A refusal's [`Reason`](https://ifloom.dev/docs/reference/actions#reason), whose key, if it has one, has to name a string. | | `{ problem }` | A plugin's own rule, broken, whose words are reported as they are. | | `{ markup }` | Prose with markup in it. | | `{ actionsIn, offers }` | The `[[act:]]` links in a body or a line of prose, each naming one of `offers`, the choices on offer. | | `{ when }`, `{ effects }`, `{ command }`, `{ blocks }`, `{ media }`, `{ layered }` | Content to look inside, checked as the engine's own is. A layered picture with `choices: null` belongs to no scene, such as a location's. | | `{ within, refs }` | More references, whose problems read `: `, such as `action dig: unknown location "moon"`. | A loyalty-card plugin says what its calls and its cards name this way, with `cardsOf(game)` its list of `data.loyalty.cards` and [`actionReferences`](https://ifloom.dev/docs/reference/actions#actionreferences) for each card's actions: ```ts fragment references: { calls: (_table, name, args) => (name === 'stamp' ? [{ entry: String(args.card), plugin: 'loyalty', list: 'cards', noun: 'card' }] : []), content: (game) => cardsOf(game).map((card) => ({ list: 'cards', id: card.id, refs: [ { blocks: card.body }, { layered: card.picture, choices: null }, ...(card.actions ?? []).map((action) => ({ within: `action ${action.id}`, refs: actionReferences(action) })), ], })), }, ``` The checker reports a problem in an entry as ` `, against the content or pack the entry came from. ## Functions [#functions] ### checkGame [#checkgame] Returns the problems, warnings and files of a game's content, as a [`Checked`](#checked). Every parameter is in [`checkGame`](https://ifloom.dev/docs/api/engine#checkgame). It walks every part of the game that is data: scenes, actions, triggers, inputs, settings, stats, entities, `finished`, `carryOver`, the locks, `saveable`, `introScene`, audio, media pools, all the prose, and every plugin's content. It looks each condition, effect and command up in one table that says what it names, so a condition is checked the same wherever it sits, and then resolves each name against the game. It never throws on bad content. A game built by hand calls it in a test: ```ts import { describe, expect, it } from 'vitest' import { checkGame, startingState } from '@ifloom/engine' import module from '../src/game.ts' const { game } = module.build() describe('the game', () => { it('has nothing wrong with it', () => { expect(checkGame(game, { probes: [{ name: 'start', state: startingState(game) }] }).problems).toEqual([]) }) }) ``` `loadGame` returns only problems, so a test that wants the warnings calls `checkGame(game)` on the loaded game. ### describeProblem [#describeproblem] Returns a problem as one line, its `pack`, `where` and `what` joined with ` · `. Every parameter is in [`describeProblem`](https://ifloom.dev/docs/api/engine#describeproblem). ```text mod:sunday-market · scene market.stall · goes to unknown scene "market.closing" ``` ## Checks [#checks] The checker reports each problem at a `where` that names what the problem is in. The checks on a condition, an effect and a command are the same wherever one sits, and are listed under [Conditions](#conditions), [Effects](#effects) and [Commands](#commands). The rest run where this table says: | Key | Meaning | |---|---| | `scene ` | A data scene: `no prose for "…"` for a `{ prose }` block, `variants "…" has no lines` for a `variants` block and the variants its `image` names, the conditions on its blocks, a `variants` block's `gate`, each choice's `when`, `blocked`, `labels` and `effects`, and `two choices share the id "…"`. A [flowing scene](https://ifloom.dev/docs/reference/flows#checks) adds its own checks. Also its `audio`, its `{ media }` blocks and `picture`, its `panel`, `unknown minigame "…"` for its `minigame`, and the [storylet](https://ifloom.dev/docs/reference/storylets#checks) fields. | | `action ` | Each of the content's [actions](https://ifloom.dev/docs/reference/actions#checks): its `when`, `blocked`, `effects` and `command`, `spends unknown stat "…"` or `spends stat "…", which is derived and never written` for its `cost`, `an action's command can't be a choice`, and `an action's command can't be the action itself; give it the effects`. | | `trigger ` | Its `when` and its `effects`. | | `input ` | Its `when`, `a choice with no options`, and `min is above max`. | | `minigame ` | `starts in unknown state "…"`, `no final state can be reached from its start, so it never ends`, `keys maps input "…", which no state's on uses`, `uses key "…", which is not in its kv` and `copies key "…", which is not in its kv`. See [minigames](https://ifloom.dev/docs/reference/minigames#checks). | | `minigame state ` | Its `label`, `a timer needs ms above 0`, `a final state ends the minigame, so its after, on and always never run`, and for each transition `goes to unknown state "…"`, `to lists no states` and `the weight of "…" must be above 0`. A transition's `when` and `effects` are reported under `… `, and a final state's effects under `… final`. | | `phrase ` | Each problem [phrases](https://ifloom.dev/docs/reference/phrases#checks) lists, and each row's `when` and markup under `phrase row `. | | `changes` | `stats names "…", which is no stat` for an id in [`changes.stats`](https://ifloom.dev/docs/reference/changes#changesdef), and `stats must be a list of stat ids`. | | `timer ` | `a timer needs ms above 0`, `two timers share this id`, and its `effects`. See [timers](https://ifloom.dev/docs/reference/timers#checks). | | `setting ` | `a choice with no options`, `min is above max`, `step must be above 0`, and a `default` the setting can't take, such as `default 9 is not between 0 and 5`. | | `stat ` | `belongs to unknown kind "…"` for its `of`, `no game value named "…"` or `no plugin value named "…"` for a `max: { value }`, its `visible` and its `ui`, and each problem [stats](https://ifloom.dev/docs/reference/stats#checks) lists for a [formula](https://ifloom.dev/docs/reference/stats#formula) and [levels](https://ifloom.dev/docs/reference/stats#statlevels). | | `entity :` | `unknown kind "…"`, `no stat named "…"`, `stat "…" is derived: it is worked out, never written`, `an entity id must not be a whole number`, what its `visible` names, and its `image` file. Where a plugin starts it, such as the inventory's `inventory/at`, is that plugin's trait, checked as [traits](#traits) are. | | `kind ` | What its `listed` and `flags` conditions name, with `'$'` as any one of the kind, and its `ui`. | | `trait ` | `plugin "…" has no trait "…"`, for a trait id whose plugin the game has but doesn't declare it. See [traits](#traits). | | `trait on :` | `unknown entity "…"` for a row of the `traits` table that names an entity nobody declares, and what the plugin's trait finds in the data. | | `finished` | The game's [`finished`](https://ifloom.dev/docs/how-to/offer-new-game-plus) condition. | | `carryOver` | `unknown stat "…"` and `stat "…" belongs to , not the player` in [`carryOver`](https://ifloom.dev/docs/how-to/offer-new-game-plus). | | `receivers` | `"…" is no plugin of the game's that keeps things`, for an id in the game's [`receivers`](https://ifloom.dev/docs/reference/content#gamebase) that isn't a [receiver](https://ifloom.dev/docs/reference/entities#receivers). | | `lock ` | The `when` of each of the content's [locks](https://ifloom.dev/docs/reference/locks#lock), by its `id`, or by its place in the list from 0 for one with none. | | `introScene` | `unknown scene "…"`, when the game opens on a scene it doesn't have. | | `plugin ` | `a plugin id is letters, digits and "-" only`, `two plugins share this id`, `trait "…" must be named "/" and a name` and `two traits share the id "…"`. | | `data ` | `the game has no plugin named ""`, for content for a plugin the game wasn't built with. | | ` ` | What a plugin's content names, from its [references](#reference), and what its own `check` finds. | | `track `, `channel `, `audio`, `audio default` | The game's [audio](https://ifloom.dev/docs/reference/audio#checks). | | `pool ` | A [pool](https://ifloom.dev/docs/reference/media#checks) that is empty, a file with no `src`, or a file's weight. | | `prose ` | The tracks `[[sound:id]]` and `[[voice:id]]` name, and the pools and flags in picture and video markup, in every line of prose. | | `version` | `version must be a whole number, 1 or more`, for the base's [`version`](https://ifloom.dev/docs/reference/content#gamebase). | | `migration ` | `a step is keyed by the version it upgrades from, 1 to …`, for a [migration](https://ifloom.dev/docs/upgrading/migrate-your-saves) step keyed outside 1 to `version - 1`. A game with no `version` has no room for steps, so the checker reports any step. | | ` ` for `scene`, `storyline`, `action`, `stat`, `kind`, `entity`, `trigger`, `input`, `setting`, `minigame` | `two s share this id`. Only a game built without `loadGame` can have these, since `loadGame` merges by id. | `loadGame` adds problems of its own about the content and packs themselves, such as a key declared twice ([`loadGame`'s checks](https://ifloom.dev/docs/reference/content#checks)). A stat is the player's or belongs to a [kind](https://ifloom.dev/docs/reference/entities#kinddef), and every `stat` and `level` condition and `stat` effect has to name it on its owner: | Problem | Cause | |---|---| | `stat "…" belongs to : say whose with "of"` | A kind's stat is named with no `of`, as if it were the player's. | | `stat "…" is the player's, not 's` | The player's stat is named with an `of`. | | `stat "…" belongs to , not ` | A stat is named on an entity of another kind. | A [`Reason`](https://ifloom.dev/docs/reference/actions#reason) written by key, `{ string: 'shop/closed' }`, in a `blocked` entry or a `once`, has to name a line in the game's strings, a plugin's or the engine's, or the checker reports `no string named "…"` where it's written. A call to a plugin the game wasn't built with isn't reported when one of the game's plugins lists that plugin in its [`cooperates`](https://ifloom.dev/docs/reference/plugin-queries). In play the condition is false, the effect does nothing and the command is refused. A call to a plugin nobody cooperates with is reported. ### Conditions [#conditions] The checker walks every condition, inside `all`, `any`, `not` and a `count`'s `where` too. | Problem | Cause | |---|---| | `"…" takes its arguments as an object, …` | A [plugin call](https://ifloom.dev/docs/reference/custom#plugincall) written by its full name whose value is neither an object nor `true`, such as `{ 'places/at': ['cafe'] }`. It's asked with no arguments. An effect or a command written this way gets the same problem. | | `a condition asks one thing, but this one has … keys that each say what it asks: …` | One object has two keys that each say what it asks, such as `{ kv, stat }`. It never holds, and the checker doesn't look inside it. Combine them with `all`. | | `a condition needs one key that says what it asks, such as kv or stat, or a call by name; …` | The object has no such key, such as `{}` or `{ gte: 3 }`. It never holds. | | `unknown storyline "…"` | `storyline`, or a `kv` condition's `of: 'storyline:…'`, names a storyline nobody declares. | | `unknown stat "…"` | `stat` or `level` names a stat nobody declares. | | `unknown kind "…"` | `count`, `entity`, or the `of` of a `stat`, `level` or `kv`, names a kind nobody declares. `'$'`, `'you'`, `'player'`, `'minigame'` and `'storyline:…'` name no kind. | | `plugin "…" has no trait "…"` | A `count`'s [`Select`](https://ifloom.dev/docs/reference/entities#select) names a `trait` its plugin doesn't declare. | | `gated on unknown scene "…"` | `seen`, `since` or `scene` names a scene that doesn't exist. | | `gated on a choice in unknown scene "…"` | A `chose` key, or a `since` naming a `scene#choice`, names a scene that doesn't exist. | | `gated on unknown choice "…"` | A `chose` or `since` key names a choice its data scene doesn't have. | | `no game condition named "…"`, `no plugin condition named "…"` | A call names a condition nobody declares, in the game's `rules` for a `game/` name or else in the plugin its name starts with. It adds `; the game has no plugin "…"` when the game lacks that plugin, and a hint to write `game/` in front for a name with no `/`. | | `minigame key "…" is not in any minigame's kv` | A `kv` condition with `of: 'minigame'` names a key no [minigame](https://ifloom.dev/docs/reference/minigames) declares. | | `unknown timer "…"` | A `timer` condition names a timer the game doesn't declare. | | `unknown setting "…"` | A `setting` condition names a setting the game doesn't declare. | | `setting "…" is a ui setting; conditions read only play settings` | A `setting` condition names a `ui` [setting](https://ifloom.dev/docs/reference/settings), which the state never holds. | | ` for setting "…" is not …` | An `is` the setting can't take: not `true` or `false` for a toggle, not an option of a choice, or outside a range's bounds or steps. | A call to a plugin's condition is also checked for what the plugin's [references](#reference) say it names. Stat owners are checked as [the tables above](#checks) list, and an `owned` condition as [someone](#someone) and [receivers](#receivers) are. ### Effects [#effects] | Problem | Cause | |---|---| | `an effect does one thing, but this one has … keys that each say what it does: …` | One object has two keys that each say what it does, such as `{ stat, kv }`. It does nothing. | | `an effect needs one key that says what it does, such as stat or kv, or a call by name; …` | The object has no such key, such as `{}` or `{ by: 2 }`. It does nothing. | | `no game effect named "…"`, `no plugin effect named "…"` | A call names an effect nobody declares, worded as for a condition. | | `unknown stat "…"` | A `stat` effect, or a `roll`'s `plus: { stat }`, names a stat nobody declares. | | `stat "…" is derived: it is worked out, never written` | A `stat` effect names a stat with a [formula](https://ifloom.dev/docs/reference/stats#formula), or a `create` gives one a value. | | `no stat named "…"` | A `create` gives its entity a stat in `with` that isn't declared `of` its kind. | | `unknown kind "…"` | A `create` or `each` names a kind nobody declares, or a `stat`, `kv`, `entity`, `remove` or `move` effect names an entity of one. | | `unknown entity "…" to be like: name one the game declares` | A `create`'s `like` names an entity nobody declares. | | `like names a , not a ` | A `create`'s `like` is of another kind than the one it creates. | | `plugin "…" has no trait "…"` | An `each`'s `trait`, or a trait in a `create`'s `with.traits`, isn't declared by its plugin. | | `unknown storyline "…"` | A `kv` effect's `of: 'storyline:…'` or a `closeStoryline` effect names a storyline nobody declares. | | `goes to unknown scene "…"` | A `scene` effect, or a [storylet](https://ifloom.dev/docs/reference/storylets) draw's `otherwise`, names a scene that doesn't exist. | | `draws from "…", but no scene is drawn from it` | A storylet draw, `{ scene: { from } }`, names a set no scene's `drawnFrom` includes. | | `unknown minigame "…"` | A `minigame` effect names a minigame the game doesn't declare. | | `minigame key "…" is not in any minigame's kv` | A `kv` effect with `of: 'minigame'` names a key no minigame declares. | | `dice "…" is not dice notation such as "2d6+1", "1d20" or "d100"` | A [`roll`](https://ifloom.dev/docs/reference/rolls) effect's `dice` isn't notation. It rolls nothing. | | `dice have … sides; a die needs at least 2`, `… dice; a roll throws 1 to 100` | A `roll` effect's dice are out of range, in notation or as `{ count, sides }`. | | `roll key "…" must be letters, digits and _, not starting with a digit, so {{key}} can show it` | The kv key a `roll` effect names isn't a plain name. | | `roll plus: …`, `roll against: …` | A `roll` effect's `plus` or `against` isn't an amount the engine can read. | | `an amount is a number, a stat id, a formula, { stat }, { kv }, { value } or { count }; …` | An [`Amount`](https://ifloom.dev/docs/reference/amounts) has a shape the engine can't read. | | `unknown timer "…"` | A `timer` effect names a timer the game doesn't declare. It does nothing. | | `a timer’s to must be a number of milliseconds above 0, or null to stop it`, `a timer’s by must be a number of milliseconds` | A `timer` effect's `to` or `by` is out of range. | | `jumps to point "…", but a jump only works as a choice's effect in the scene that has that point` | A [`point`](https://ifloom.dev/docs/reference/effects#point) effect sits anywhere but a data scene's choice. In a choice, the scene's [flow checks](https://ifloom.dev/docs/reference/flows#checks) read it. | The checker also lists a `notify`'s `image` in [`files`](#fileref), checks an `audio` or `sound` effect as [audio](https://ifloom.dev/docs/reference/audio#checks), a `panel` effect's `with` as each plugin's references say, and a call to a plugin's effect for what its references name. Stat owners are checked as [the tables above](#checks) list. A `receive`'s `to` and a `release`'s `from` are checked as [someone](#someone), the entity a `you` effect names as a protagonist, and every `receive` and `release` as [receivers](#receivers) are, its `via` included. A `create`'s `effects` are checked with `'$'` as one of the kind it makes. Inside an `each`, the checker reads `where` as a condition and `effects` as effects, with `'$'` standing for one of its kind. A problem from inside starts `in each : `, such as `in each staff: stat "quality" belongs to dish, not staff`. ### Commands [#commands] | Problem | Cause | |---|---| | `opens unknown scene "…"` | A `scene` command names a scene that doesn't exist. | | `unknown action "…"` | An `action` command names an action the game's content doesn't declare. A plugin's action, such as `places/coffee`, isn't checked, since the plugin answers for it in play. | | `unknown input "…"` | An `input` command names an input the game doesn't declare. | | `no game command named "…"`, `no plugin command named "…"` | A call names a command nobody declares. The checker then checks what the plugin's references name. | | `unknown command type "…"` | A command's `type` is none the engine has. In play it's refused with `This game does not do that.` | A `setting` command is checked as a `{ setting, is }` condition is. `start`, `newGame`, `choose`, `leave`, `dismiss`, `tick`, `minigame` and `closePanel` name nothing to check. A choice's [`command`](https://ifloom.dev/docs/reference/scenes#choice) is checked as any command is, under `choice :`, and `choice …: a choice's command can't be another choice; put the effects on this one` reports one that is `choose`. ### prose [#prose] The checker reads every line of prose and every block of words for its speakers, its inline actions and tooltips, and its tokens. A spoken line written under an id, `@ava: "…"` in [prose](https://ifloom.dev/docs/reference/prose#speech) or a [`say()`](https://ifloom.dev/docs/reference/flows#say) block's speaker, has to name an entity, and `'you'` and `'player'` always pass: | Problem | Cause | |---|---| | `a spoken line is under "…", which names no entity` | No entity has that id or reference. | | `a spoken line is under "…", which more than one kind has: name it as "kind:…"` | Two kinds share the bare id and neither is `character`. Write the full reference, such as `@staff:jo`. | The checker reads [inline actions and tooltips](https://ifloom.dev/docs/reference/prose#inline-actions-and-tooltips) against the choices of the scene whose body names them, or a location's body against its actions and the game's: | Problem | Cause | |---|---| | `[[act:…]] names no choice or action offered here` | The id is none of the scene's choices or the room's buttons. | | `[[act:…]] is in one line twice; only the first is drawn as an action` | One prose line names the same id twice. | | `[[act:…]] is in two blocks that can show together; only the first is drawn as an action` | Two blocks name the id, and one has no `when`. Members of one variants list are drawn one at a time, so they can each name it. | | `[[act]] needs the id of a choice: [[act:id]] or [[act:id\|words]]` | The markup is `[[act:]]` or `[[act:\|words]]`. | | `[[act:…\|]] has no words; leave out the "\|" to use the choice's label` | The markup has an empty `\|`. | | `[[tip]] needs a prose key: [[tip:key\|words]]` | The markup is `[[tip:\|words]]`. | | `[[tip:…]] needs the words to show: [[tip:…\|words]]` | A tooltip has no words, so it shows as written. | | `[[tip:…]]: no prose for "…"` | The tooltip's key has no prose. | | `[[act:…]] or [[tip:…]] is not closed with "]]", or is missing its ":"` | The checker can't find the markup's end. | | `[[act]] and [[tip]] are shown as written in a "> " line; use them in narration or a spoken line` | A thought holds inline markup. | The checker reads the [tokens](https://ifloom.dev/docs/reference/prose#tokens) in every line of prose, every block of words and every phrase's row, and reports them where the line is: | Problem | Cause | |---|---| | `{{…}} names no phrase, no value in rules.values and no kv key the content starts or sets; is the phrase's name right?` | A bare name with a group in it, such as `{{outfit.verdit}}`, names none of these. A key counts when content starts it, an input writes it, an effect sets it with no `of`, a roll keeps its total under it, or a minigame's final state copies to it. A plain name such as `{{friend}}` isn't checked, since a start command or the game's code may set it. | | `{{…}} names no value "…"` | A plugin's token, `{{plugin/name}}`, names a value no plugin of the game has. | | `mood.word takes who` | A phrase's token leaves out an argument the phrase declares in [`args`](https://ifloom.dev/docs/reference/phrases#args). | | `mood.word takes who, not whom` | A phrase's token passes an argument the phrase doesn't take. A phrase with no `args` gives `weather takes no arguments, not who`. | One token gives a warning instead, in `warnings`. `{{…}} may be unset, and then prints nothing; give it words to show until then, as {{…|…}}` warns about a bare token with no fallback that names a kv key the game's `kv` doesn't start, or a phrase with no row that always fits. A line whose block shows only under a `kv` or `roll` condition on that key, such as `when: { kv: 'playerName' }`, isn't warned about. ### traits [#traits] The checker checks every declared entity's [traits](https://ifloom.dev/docs/reference/entities#traittable) once the kind's default, the entity's own and any table row are combined. The check depends on whose trait it is: - **A trait of a plugin the game has.** The plugin has to declare it, or the checker reports `plugin "laundry" has no trait "laundry/washabel"`. The plugin's `check` reads the data on each entity that has the trait, and the checker resolves what its `references` name, at `trait laundry/washable on clothing:scarf`. - **A trait of a plugin the game doesn't have.** It passes unchecked, as content for a cooperating plugin does. - **The game's own trait**, with no `/` in its id. It isn't checked, since no plugin says what it holds. A row of the `traits` table for an entity nobody declares is reported whoever's trait it is, as `unknown entity "clothing:sock"`. A problem from a row is pinned on the content or pack the row came from, and one from an entity's own data on the content that declares the entity. ### words [#words] The checker reads a translation's [words table](https://ifloom.dev/docs/reference/words) against the fields the game has: | Problem | Cause | |---|---| | `names no field the game has (translatableFields lists every key)` | A pack's key, at `words `, names no field. It's a typo, or a block whose words changed so its hash key moved on. | | `two fields with different words share the words key "…"; give a block of words an id, or rename one` | Two blocks of words in one scene share an `id`, or two ids join into one key. | ### someone [#someone] Someone content names, a `receive`'s `to`, a `release`'s `from`, an `owned`'s `of` or a plugin's `arg.someone()`, has to be `'player'`, `'you'`, `'$'` or an entity of a [unique](https://ifloom.dev/docs/reference/entities#unique) kind. The entity a `you` effect makes the player play has to be `'player'`, `'$'` or an entity of a unique kind, and not `'you'`: | Problem | Cause | |---|---| | `unknown someone "…": name "player", "you" or a unique entity` | The name is no entity reference at all, such as `'pal'`. | | `"…" isn't someone: its kind "…" isn't unique` | The entity's kind stacks, such as `'food:apple'`. | | `"you" is already whoever is played: …` | A `you` effect names `'you'`. | | `unknown protagonist "…": a protagonist is "player" or a unique entity` | A `you` effect names no entity reference, such as `'pal'`. | | `"…" can't be played: its kind "…" isn't unique` | A `you` effect names an entity whose kind stacks. | | `unknown kind "…"` | The entity is of a kind nobody declares. | ### receivers [#receivers] A `receive`, `release` or `owned` needs a plugin that keeps things, a [receiver](https://ifloom.dev/docs/reference/entities#receivers): | Problem | Cause | |---|---| | `no plugin of the game keeps things, so this does nothing: …` | The game has no receiver, so the call would do nothing. A Twine-style game uses [kv keys](https://ifloom.dev/docs/how-to/hand-roll-an-inventory) instead. | | `via names "…", which isn't one of the game's plugins` | `via` names a plugin the game wasn't built with. | | `via names "…", which keeps no things` | `via` names a plugin with no receiver. | | `unknown entity "…"` | The thing isn't declared and isn't `'$'` or `'kind:*'`. | ## Caveats [#caveats] - The checker doesn't run the game's own code. A [macro](https://ifloom.dev/docs/reference/custom#macros) that returns a broken effect, or a `rules.onTurn` that applies one, shows only in play. - A game built by hand has no content files, so `checkGame` can't report a key declared twice or a key content can't hold. Only `loadGame` reports those. - The checker reads only the tokens [prose](#prose) lists. A plain `{{breadPrice}}` that names nothing stays on screen as written, so you see it in play. - A probe renders every scene in its state, even one no route reaches, so a value that throws for an impossible state fails the check. # The CLI (https://ifloom.dev/docs/reference/cli) `@ifloom/cli` is the `ifloom` command, which makes a game, runs it while you write, builds it into a folder that opens from disk, and checks and plays it with nobody at the keyboard. It reads the game from its [game module](#the-game-module) and builds it with the [Vite preset](#the-vite-preset). [Create a game](https://ifloom.dev/docs/how-to/create-a-game) starts one, [Ship your game](https://ifloom.dev/docs/how-to/ship-your-game) builds it, and [Playtest and snapshot](https://ifloom.dev/docs/how-to/playtest-and-snapshot) puts the checks in CI. In the showcase: `examples/showcase/package.json`, whose scripts run each command, and `examples/showcase/src/game.ts`, its game module. `npm create ifloom` runs `ifloom new`. Every other command runs from the game's folder, where the game lists `@ifloom/cli` as a dev dependency. Outside a game, `npx ifloom` runs the latest CLI from the `ifloom` package, which depends on `@ifloom/cli` and runs its command. `ifloom` or `ifloom help` prints every command with its flags and exits with `0`, and an unknown command prints the same and exits with `1`. ## Requirements [#requirements] The `ifloom` command is compiled JavaScript and needs Node 20.19 or later, or 22.12 or later, as Vite does. Node 24 is recommended. Inside a clone of the IFLoom repository it runs the CLI's TypeScript source, which needs Node 22.18 or later (see [Work in the repository](https://ifloom.dev/docs/how-to/work-in-the-repository)). `@ifloom/cli` depends on Vite and `vite-plugin-singlefile`, and names no UI framework. A game lists its framework's Vite plugin as a dependency of its own and adds it in `vite.config.ts`. [Add IFLoom to an existing project](https://ifloom.dev/docs/how-to/add-to-a-project) installs the CLI and its scripts. `@ifloom/cli/game` imports only the engine, so a game's browser code type-checks with it. `@ifloom/cli` itself imports Node's modules, so a file that imports it needs `@types/node` and `"node"` in its `tsconfig.json`'s `types`, or a place outside the browser code's `include`. ## ifloom new [#ifloom-new] `ifloom new` makes a new game, or a plugin package, from a template in a folder named after it. ```sh ifloom new [--template