# Add a character with a schedule (https://ifloom.dev/docs/how-to/add-a-character) Use this for someone the player meets around town, such as a neighbour who walks a dog in the park. You need the [cast plugin](https://ifloom.dev/docs/reference/plugins/cast), and for anyone to be here with the player, the [places plugin](https://ifloom.dev/docs/reference/plugins/places) too (see [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin)). Schedules by time of day also need the [calendar](https://ifloom.dev/docs/reference/plugins/calendar). A [character](https://ifloom.dev/docs/reference/glossary#character) is an entity with the `cast/person` trait, and `cast.person()` writes one. ## Declare the character [#declare-the-character] Add the character to `entities` with `cast.person()`, in `src/world/cast.ts`. Give them a `home` location and the scene that talking to them opens: ```ts import type { Content } from '@ifloom/engine' import { cast } from '@ifloom/plugin-cast' export const people: Content = { storylines: [{ id: 'sam', name: 'Sam' }], entities: [ cast.person({ id: 'sam', name: 'Sam', description: 'Neighbour', image: 'art/character/sam.svg', ui: { hue: 200 }, home: 'park', talk: 'sam.hi', storyline: 'sam', }), ], } ``` The `name` shows over their lines, on their card and in refusals such as `Sam is not here.` The `storyline` names their [storyline](https://ifloom.dev/docs/reference/storylines), and while it's closed they won't talk. The React UI colours their lines with `ui.hue`. ## Write the scene they open [#write-the-scene-they-open] Write the talk scene with the character as its `speaker`. A friendship is a stat the game declares on the kind `character`, so each character keeps their own: ```ts import type { Content } from '@ifloom/engine' import { cast } from '@ifloom/plugin-cast' export const sam: Content = { stats: [{ id: 'friendship', label: 'Friendship', of: 'character' }], scenes: [ { id: 'sam.hi', title: 'Sam', speaker: 'sam', body: [{ text: 'Sam is walking a dog that is clearly not theirs. "Dog-sitting," they say. "He’s in charge."' }], choices: [{ id: 'bye', label: 'Pat the dog and go', effects: [{ stat: 'friendship', by: 5, of: cast.character('sam') }, { scene: null }] }], }, ], } ``` While Sam is at the location the player is at, the cast's view lists Sam among the people here, with a Talk button that sends `cast.talk('sam')`. `cast.character('sam')` writes Sam's entity reference, `'character:sam'`. ## Give them a schedule [#give-them-a-schedule] Add `schedule` entries, each a `location` and a `when`. The character is at the location of the first entry whose `when` holds, and at `home` when none does: ```ts fragment schedule: [{ location: 'high-street', when: calendar.period('morning') }], ``` Sam is on the high street every morning and in the park the rest of the day. Put an exception above the rule it breaks, such as a Sunday entry above an every-day one. A character with no `home` and no entry that holds is [`AWAY`](https://ifloom.dev/docs/reference/plugins/cast#away), and a schedule entry can name `AWAY` for time out of town: ```ts import { calendar } from '@ifloom/plugin-calendar' import { AWAY, type Person } from '@ifloom/plugin-cast' export const schedule: Person['schedule'] = [ { location: AWAY, when: calendar.weekday(6) }, { location: 'high-street', when: calendar.period('morning') }, ] ``` ## Change what they say [#change-what-they-say] Give `talk` a list of [talk options](https://ifloom.dev/docs/reference/plugins/cast#talkoption). Talking opens the scene of the first option whose `when` holds, so put the particular ones first. Inside the character's own conditions, `'$'` stands for them. Ava, by the river once she's a friend: ```ts import { places } from '@ifloom/plugin-places' import type { TalkOption } from '@ifloom/plugin-cast' export const talk: TalkOption[] = [ { scene: 'ava.river', when: { all: [places.at('park'), { stat: 'friendship', of: '$', gte: 25 }] }, label: 'Sit with Ava' }, { scene: 'ava.hi' }, ] ``` `label` goes on the Talk button, which reads `Talk` without one. ## Let the player call them [#let-the-player-call-them] Give the character a `call` to make them reachable from anywhere with `cast.call('ava')`. A call opens a scene without moving the player. Ava picks up only in the evening and at night: ```ts fragment call: { scene: 'ava.call', when: calendar.period('evening', 'night'), busy: 'She’s busy at the counter. Try her this evening.' }, ``` While `when` doesn't hold, the call is refused with `busy`. The view adds no call button, so put one where it fits: an action with `command: cast.call('ava')`, or a phone's contacts. `call: {}` makes someone callable at any time, into their talk scene. ## Say when the player has met them [#say-when-the-player-has-met-them] A character counts as met once the player has seen one of their `talk` scenes or their `call.scene`. The view lists only people the player has met. For someone met another way, such as a speaker in another character's scene, give them a `met` condition: ```ts fragment met: { kv: 'introduced', of: '$' }, ``` Read it anywhere with `cast.met('sam')`. ## Let the player name them [#let-the-player-name-them] Ask for the name with an [input](https://ifloom.dev/docs/reference/inputs), and give the character a `name` that prints the input's key, with words after the `|` for before the player has typed: ```ts import type { Content } from '@ifloom/engine' import { cast } from '@ifloom/plugin-cast' export const friend: Content = { inputs: [{ id: 'friendName', label: 'Your oldest friend is called', type: 'text', maxLength: 16 }], entities: [cast.person({ id: 'sam', name: '{{friendName|Your oldest friend}}', home: 'park', talk: 'sam.hi' })], } ``` Once the player types `Robin`, every place that shows Sam's name shows `Robin`. Without the fallback, Sam has no name until then. [Ask the player for a name](https://ifloom.dev/docs/how-to/ask-for-a-name) has the input. ## Check it worked [#check-it-worked] Run `npm run check`. It reports a talk or call scene the game doesn't have, a `home` or schedule location places doesn't know, and a call that opens no scene: ```text content · trait cast/person on character:sam · talk: opens unknown scene "sam.hello" ``` Then play in `npm run dev`. Walk to where the schedule puts the character, and their card shows among the people here with a Talk button. Walk away, and the card goes. To render them in a UI of your own, see [Render the people](https://ifloom.dev/docs/how-to/render/world-plugins#render-the-people). In the showcase, Small Town, Ava and Sam are in [`examples/showcase/src/world/cast.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/world/cast.ts) and their scenes in `src/story/ava.ts` and `src/story/sam.ts`. For more, see: - [Cast](https://ifloom.dev/docs/reference/plugins/cast), with [`PersonDef`](https://ifloom.dev/docs/reference/plugins/cast#persondef), the [`Person`](https://ifloom.dev/docs/reference/plugins/cast#person) trait and the [`cast/talk`](https://ifloom.dev/docs/reference/plugins/cast#casttalk) and [`cast/call`](https://ifloom.dev/docs/reference/plugins/cast#castcall) commands. - [Build a friendship in stages](https://ifloom.dev/docs/how-to/build-friendships-in-stages), to pace what happens between them and the player. - [Locations, characters and vendors are entities](https://ifloom.dev/docs/explanation/entities-and-traits#locations-characters-and-vendors-are-entities). # Add a countdown (https://ifloom.dev/docs/how-to/add-a-countdown) Use this when the story shouldn't wait: the phone rings and stops after ten seconds, or the bus pulls away. A [timer](https://ifloom.dev/docs/reference/glossary#timer) counts down in real time and runs its own effects when it runs out. The steps build the showcase's ringing phone, which becomes a missed call if the player doesn't answer. ## Declare the timer [#declare-the-timer] Add the timer to your content's `timers`, with how long it runs in `ms` and the effects to run when it runs out: ```ts import type { TimerDef } from '@ifloom/engine' export const ring: TimerDef = { id: 'flat.ring', label: 'Ringing', ms: 10_000, effects: [{ scene: null }, { kv: 'missedAva', to: true }, { notify: 'Missed call: Ava', id: 'missed-call', tag: 'phone' }], } ``` Nobody answered, so the scene closes, a kv key remembers, and a [notice](https://ifloom.dev/docs/how-to/show-a-notice) says so. ## Start it with the scene [#start-it-with-the-scene] Open the scene and start the timer in the same effects, so the countdown starts as the scene comes up. In the showcase a [trigger](https://ifloom.dev/docs/reference/triggers) does both when the player is home in the evening: ```ts import type { TriggerDef } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' export const ringing: TriggerDef = { id: 'flat.ring', when: { all: [places.at('flat'), calendar.period('evening')] }, effects: [{ scene: 'flat.ring' }, { timer: 'flat.ring' }], } ``` ## Stop it in every way out [#stop-it-in-every-way-out] Give every choice that leaves the scene `{ timer: 'flat.ring', to: null }`, which stops the timer without running its effects. A timer keeps running after its scene closes, so a way out that forgets would close whatever is open ten seconds later: ```ts import type { DataScene } from '@ifloom/engine' export const phone: DataScene = { id: 'flat.ring', title: 'The phone', speaker: 'ava', body: [ { text: 'Your phone is ringing on the sill. Ava. Answer before it stops.', ui: { timer: 'flat.ring' } }, { text: 'It has rung a long time now.', when: { timer: 'flat.ring', lte: 3000 } }, ], choices: [ { id: 'answer', label: 'Answer it', effects: [{ timer: 'flat.ring', to: null }, { scene: 'ava.call' }] }, { id: 'leave', label: 'Let it ring', effects: [{ timer: 'flat.ring', to: null }, { scene: null }] }, ], } ``` The second line holds while 3 seconds or fewer are left, so it comes in late. The engine checks it again after every tick. To give the player more time, add some with `{ timer: 'flat.ring', by: 5000 }`. A negative `by` takes time away, and `{ timer: 'flat.ring', to: 3000 }` starts it again with three seconds. ## Show the countdown [#show-the-countdown] With the React UI, the `ui: { timer: 'flat.ring' }` hint on the first line does it. `Scene` renders a [`Countdown`](https://ifloom.dev/docs/reference/react/components#countdown) under that line while the timer runs, with its label, a bar that empties and the seconds left. In the last quarter it's marked `data-urgent`, which each preset colours: Paper draws a thin rule, Storybook a fat bar in a card, Studio a bordered strip, and Terminal a text-mode bar. A player who asks for reduced motion sees the seconds only. To show a timer somewhere else, such as the sidebar, put `` in your layout, or `` for every running timer. A timer that nothing shows still runs, for a deadline the player doesn't see coming. The React UI runs the clock itself. In a UI of your own, start [`startClock`](https://ifloom.dev/docs/reference/browser#startclock) beside the runner, as the templates do, and render the countdown as [Render timers](https://ifloom.dev/docs/how-to/render/timers-minigames-panels#render-timers) shows. ## Check it worked [#check-it-worked] Run `npm run check`, which reports a timer the game doesn't declare. Then play to the scene with `npm run dev`, and let it ring. After ten seconds the scene closes and the notice comes. A test sends the ticks itself, so it gets the same result every time. One long tick covers a whole wait, so `{ type: 'tick', ms: 10_000 }` runs the phone out at once: ```ts given import { apply } from '@ifloom/engine' // `state` has the phone ringing: let six seconds pass, then answer. let next = apply(state, game, { type: 'tick', ms: 6000 }).state next = apply(next, game, { type: 'choose', id: 'answer' }).state next.sceneId // 'ava.call' ``` `ifloom playtest` sends no ticks, so it never sees a timer run out. In the showcase, Small Town, the phone rings in [`examples/showcase/src/story/flat.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/flat.ts), and its tests answer the call in time and miss it. For more, see: - [Timers](https://ifloom.dev/docs/reference/timers), the [`timer` effect](https://ifloom.dev/docs/reference/effects#timer) and the [`timer` condition](https://ifloom.dev/docs/reference/conditions#timer). - The [`tick` command](https://ifloom.dev/docs/reference/commands#tick). - [Timers run in real time, not turns](https://ifloom.dev/docs/explanation/turns-and-time#timers-run-in-real-time-not-turns). # Add a location (https://ifloom.dev/docs/how-to/add-a-location) Use this when the player should be able to walk somewhere new, such as a park off the high street. You need the [places plugin](https://ifloom.dev/docs/reference/plugins/places) in the game's `plugins` (see [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin)). A [location](https://ifloom.dev/docs/reference/glossary#location) is an entity with the `places/location` trait, and `places.location()` writes one. ## Declare the location [#declare-the-location] Add the location to `entities` with `places.location()`, in the story file for that part of town, such as `src/story/park.ts`: ```ts import type { Content } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' export const park: Content = { entities: [ places.location({ id: 'park', name: 'Riverside Park', description: 'Small Town', exits: ['high-street'], body: [{ text: 'The river is slow and brown and full of ducks with opinions.' }], }), ], } ``` The `name` is the exit's label, the room's title and the last part of the header. The `description` is the line under the name. The `body` holds the [blocks](https://ifloom.dev/docs/reference/glossary#block) the room shows while no scene is open, the same blocks a scene's body takes. Add `park` to the content list in `src/game.ts`. ## Join it to the map [#join-it-to-the-map] Exits are one-way, so list the way in and the way back. Add `'park'` to the high street's `exits`, as the park already lists `'high-street'`: ```ts fragment exits: ['flat', 'cafe', 'park', 'office'], ``` Give a new game a starting location with `places({ start: 'flat' })`. A game with no `start` begins nowhere, and its first scene puts the player on the map with `places.move('flat')`. ## Give it things to do [#give-it-things-to-do] Add `actions` to the location. The room offers them only while the player is there, before the game's own actions, priced and refused like any [action](https://ifloom.dev/docs/reference/actions#actiondef). This is the showcase café's coffee: ```ts import { places } from '@ifloom/plugin-places' export const cafe = places.location({ id: 'cafe', name: 'The Corner Café', description: 'Café', exits: ['high-street'], body: [{ text: 'Six tables, one of them wobbly.' }], actions: [ { id: 'coffee', label: 'Buy a coffee', cost: { stats: { coins: 3 } }, blocked: [{ when: { kv: 'hadCoffee' }, reason: 'One is enough for today.' }], effects: [{ stat: 'energy', by: 15 }, { kv: 'hadCoffee', to: true }], }, ], }) ``` The coffee's button sends `{ type: 'action', id: 'places/coffee' }`. For an action in the content's own `actions` that belongs at one location, such as a phone on the flat's wall, add `places.onlyAt(['flat'], 'The phone is at home.')` to its `blocked`. The room still shows it elsewhere, greyed out with that reason, and `{ hide: true }` as a third argument leaves it off the screen instead. ## Set opening hours [#set-opening-hours] Give the location `blocked` entries written with the [calendar](https://ifloom.dev/docs/reference/plugins/calendar)'s conditions. The showcase's office opens in the day on weekdays: ```ts import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' export const office = places.location({ id: 'office', name: 'The Office', description: 'Work', exits: ['high-street'], body: [{ text: 'Strip lights, a kettle, a stack of forms that never gets shorter.' }], blocked: [ { when: calendar.weekday(5, 6), reason: 'Shut at weekends.' }, { when: { all: [calendar.weekday(4), { not: calendar.period('morning', 'afternoon') }] }, reason: 'Closed. Back on Monday.' }, { when: { not: calendar.period('morning', 'afternoon') }, reason: 'Closed. Opens tomorrow morning.' }, ], }) ``` The first entry that holds gives the reason, so put the most particular first. On a Friday evening the exit is greyed out with `Closed. Back on Monday.`, and on a Tuesday evening with `Closed. Opens tomorrow morning.` ## Send the player out at closing time [#send-the-player-out-at-closing-time] A `blocked` entry only stops the player walking in. A player who is inside when it starts to hold stays there, so a game that closes the doors on them sends them out with a [trigger](https://ifloom.dev/docs/reference/triggers). It holds while the player is at the location after hours, moves them out with `places.move`, and says why. `once: { per: 'turn' }` lets it fire each time, where a trigger without it fires once in the whole game: ```ts import type { TriggerDef } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' export const closing: TriggerDef = { id: 'office.closing', once: { per: 'turn' }, when: { all: [places.at('office'), { not: calendar.period('morning', 'afternoon') }] }, effects: [places.move('high-street'), { notify: 'The office closes, and you head out onto the high street.' }], } ``` `places.move` puts the player there without walking, so it's never refused and doesn't run the high street's arrival effects. ## Hide a door until it opens [#hide-a-door-until-it-opens] Give a location a `parent` when it's inside another, and a `blocked` entry with `hide: true` to keep its exit off the screen: ```ts import { places } from '@ifloom/plugin-places' export const backRoom = places.location({ id: 'cafe.back', name: 'The back room', description: 'Café', parent: 'cafe', exits: ['cafe'], blocked: [{ when: { not: { kv: 'staff' } }, reason: 'Staff only.', hide: true }], body: [{ text: 'Sacks of flour, a mop, and a radio tuned to the cricket.' }], }) ``` Add `'cafe.back'` to the café's `exits`. The door shows once the `staff` key is set. While the player is in the back room, `places.within('cafe')` holds and `places.at('cafe')` doesn't. ## Run something on the doorstep [#run-something-on-the-doorstep] Give the location an `arrive` to apply effects as the player walks in by an exit. Here the ducks come over on the first visit: ```ts import { places } from '@ifloom/plugin-places' export const firstVisit = places.location({ id: 'park', name: 'Riverside Park', exits: ['high-street'], body: [{ text: 'The river is slow and brown and full of ducks with opinions.' }], arrive: { when: { not: { kv: 'sawPark' } }, effects: [{ kv: 'sawPark', to: true }, { scene: 'park.ducks' }] }, }) ``` `arrive` runs after `places.go` only. For something that should happen however the player got there, a `places.move` included, use a trigger on `places.at('park')`. ## Share a line across locations [#share-a-line-across-locations] The plugin adds no line to every location. Write the shared blocks once, each with a `when`, and spread them into each location's `body`: ```ts import type { Block } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' import { places, type PlaceDef } from '@ifloom/plugin-places' const warnings: Block[] = [ { text: 'Rent is due tomorrow.', when: calendar.weekday(5) }, { text: 'You can barely keep your eyes open.', when: { stat: 'energy', lt: 10 } }, ] export const location = (def: Omit, text: string) => places.location({ ...def, body: [{ text }, ...warnings] }) ``` For a line that varies, put the same `{ variants: 'street.weather' }` block in each body. The room [draws](https://ifloom.dev/docs/reference/glossary#draw) one member per location each turn and shows the same one each time the player looks in that turn. ## Say who is behind an exit [#say-who-is-behind-an-exit] An exit names the location it leads to, not who is there. To tell the player that Ava is in the café before they walk in, add a block per location to the high street's body, with the [cast](https://ifloom.dev/docs/reference/plugins/cast)'s `cast.at`: ```ts import type { Block } from '@ifloom/engine' import { cast } from '@ifloom/plugin-cast' export const whereAva: Block[] = [ { text: 'Through the café window, Ava waves.', when: cast.at('ava', 'cafe') }, { text: 'Ava’s bicycle is chained up by the park gate.', when: cast.at('ava', 'park') }, ] ``` To put the names on the exit buttons instead, join the two plugins in your UI. This helper asks the cast's `cast/where` query for each person the player has met, and groups their names by the location they're at: ```ts import { pluginQuery, type Runner, type View } from '@ifloom/engine' export function whoIsWhere(runner: Runner, view: View): Map { const where = pluginQuery(runner.game, 'cast/where') const found = new Map() for (const person of view.plugins.cast?.people ?? []) { const at = where?.(runner.state, { character: person.id }) if (typeof at === 'string') found.set(at, [...(found.get(at) ?? []), person.name]) } return found } ``` An exit's `id` is the id of the location it leads to, so look each exit up in the map and print the names after its label. [Render the location and its exits](https://ifloom.dev/docs/how-to/render/world-plugins#render-the-location-and-its-exits) renders the exits in each framework. In the React UI, put your version in place of `Exits` with [`components`](https://ifloom.dev/docs/reference/react/components#components). ## Check it worked [#check-it-worked] Run `npm run check`. It reports an exit to a location the game doesn't have, a `parent` that leads back round to the location, and anything the body or an action names that the game lacks: ```text content · trait places/location on location:park · exit to unknown location "lido" ``` Then walk there in `npm run dev`. The room shows the location's name and body, its actions and its exits, and a closed location's exit is greyed out with its reason. To render the location in a UI of your own, see [Render the location and its exits](https://ifloom.dev/docs/how-to/render/world-plugins#render-the-location-and-its-exits). In the showcase, Small Town, each location is in its own file under [`examples/showcase/src/story/`](https://github.com/IFLoom/ifloom/tree/main/examples/showcase/src/story). For more, see: - [Places](https://ifloom.dev/docs/reference/plugins/places), with [`PlaceDef`](https://ifloom.dev/docs/reference/plugins/places#placedef), the [`Place`](https://ifloom.dev/docs/reference/plugins/places#place) trait and [`Arrival`](https://ifloom.dev/docs/reference/plugins/places#arrival). - [Blocked](https://ifloom.dev/docs/reference/actions#blocked) and the calendar's [conditions](https://ifloom.dev/docs/reference/plugins/calendar#conditions). - [Locations, characters and vendors are entities](https://ifloom.dev/docs/explanation/entities-and-traits#locations-characters-and-vendors-are-entities). # Add a plugin (https://ifloom.dev/docs/how-to/add-a-plugin) Use this to add any first-party plugin, such as the calendar, places or quests, to a game you already have. The steps are the same for all seventeen; [First-party plugins](https://ifloom.dev/docs/reference/plugins) lists them, and [How plugins work](https://ifloom.dev/docs/explanation/plugins) explains what one adds. ## Install the package [#install-the-package] Install the plugin's package beside the engine. Every plugin is `@ifloom/plugin-`: ```sh tab="npm" tab-group="package-manager" npm install @ifloom/plugin-quests ``` ```sh tab="pnpm" tab-group="package-manager" pnpm add @ifloom/plugin-quests ``` ```sh tab="yarn" tab-group="package-manager" yarn add @ifloom/plugin-quests ``` ```sh tab="bun" tab-group="package-manager" bun add @ifloom/plugin-quests ``` The package has `@ifloom/engine` as a peer dependency, so it uses the game's copy. Its React UI is in the same package, so there's nothing more to install for it. ## List it in the game's plugins [#list-it-in-the-games-plugins] Call the plugin's factory in the `plugins` of the base you pass to [`loadGame`](https://ifloom.dev/docs/reference/content#loadgame), in `src/game.ts`: ```ts import { loadGame, type Content } from '@ifloom/engine' import { defineGame } from '@ifloom/cli/game' import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' import { quests } from '@ifloom/plugin-quests' declare const town: Content export default defineGame({ build: () => loadGame([town], { id: 'small-town', title: 'Small Town', plugins: [calendar(), places({ start: 'flat' }), quests()] }), }) ``` Order the list with these rules: 1. **List the calendar first.** Plugins' [`onTurn`](https://ifloom.dev/docs/reference/plugin-api#onturn-and-onturndone) hooks run in list order, and the calendar's moves the clock on. Plugins after it see the new day, and plugins before it see the old one. 2. **List places after the calendar.** Plugins' [labels](https://ifloom.dev/docs/reference/plugin-api#label) join in list order, so the header reads `Day 1 · Monday morning · High Street`. 3. **Put the rest in any order.** The cast asks places where the player is by name, so its place in the list changes nothing. A game chooses its plugins when it's built. A mod can bring content for a plugin the game has, but it can't add a plugin. ## Write its content [#write-its-content] Content calls a plugin's conditions, effects and commands by their full name, `/`, with the arguments as an object. The plugin's helpers write them for you, and they are properties of its factory: ```ts import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' const bed = { id: 'bed', label: 'Go to bed', when: places.at('flat'), command: calendar.sleep() } ``` A plugin's lists go under `data.` in your content, such as `data.quests.quests`. A plugin whose content is entities has definers instead, such as `places.location({ … })` and `cast.person({ … })`, written in `entities`. Each plugin's reference page lists its content under `## Content`. ## Show it on screen [#show-it-on-screen] With the [React UI](https://ifloom.dev/docs/reference/react), import the plugin's UI from its `/react` subpath and list it in `mountGame`'s `plugins`. With a UI of your own, render the plugin's view from `view.plugins.`. The quest log, in each framework: ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** The quest log: the active quests, the tracked one first, each with its hint and how far along it is, then the finished ones. */ export function drawQuests(parent: HTMLElement, { view }: RunnerSnapshot): void { const quests = view.plugins.quests if (!quests) return for (const quest of quests.active) { const entry = add(parent, 'section', '', 'quest') if (quest.updated) entry.dataset.updated = '' add(entry, 'h3', `${quest.name} (${quest.stage} of ${quest.stages})`) add(entry, 'p', quest.hint) // Track it, so it comes first; the same button says Untrack once it's tracked. if (quest.track) drawChoices(entry, [quest.track]) } if (quests.done.length) add(parent, 'p', `Done: ${quests.done.map((quest) => quest.name).join(', ')}`, 'done') // Mark all seen, while there is news: it clears the "updated" marks. if (quests.seen) drawChoices(parent, [quests.seen]) } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { questsUi } from '@ifloom/plugin-quests/react' import module from './game.ts' // A Quests section in the side column opens the quest log, with the count of news on its button. mountGame(module.build(), { plugins: [questsUi] }) ``` ```vue tab="Vue" tab-group="framework" ``` The React UI's default layout puts each plugin's parts where its UI says, in the order of the list. [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis) places them in a layout of your own, and the [Render it yourself](https://ifloom.dev/docs/how-to/render/start) pages render every plugin's view. ## Add the plugins it works with [#add-the-plugins-it-works-with] No first-party plugin needs another. Some do more when the game has a partner, such as the shop's opening hours with the calendar, or the cast's people in the room with places. The [`cooperates`](https://ifloom.dev/docs/reference/plugins#cooperates) table lists each partner and what happens without it. ## Check it worked [#check-it-worked] Run `npm run check`. It prints `No problems.` when the game has every plugin its content calls. A call to a plugin the game lacks shows up as a problem: ```text story.ava · scene ava.park · no plugin condition named "quests/done"; the game has no plugin "quests" ``` Add the missing factory to `plugins`, or remove the call. For more, see: - [First-party plugins](https://ifloom.dev/docs/reference/plugins), with a page for each plugin's factory, content and calls. - [`Plugins`](https://ifloom.dev/docs/reference/react/kit#plugins), the component that places plugin UIs. - [How plugins work](https://ifloom.dev/docs/explanation/plugins). # Add a quest (https://ifloom.dev/docs/how-to/add-a-quest) Use this to give the player a goal in steps, such as settling into a new town. You need the [quests plugin](https://ifloom.dev/docs/reference/plugins/quests) (see [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin)). A quest is a list of [stages](https://ifloom.dev/docs/reference/glossary#stage), each done the first time its condition holds, in order. Progress is never taken back. ## Declare the quest [#declare-the-quest] Add the quest to `data.quests.quests`, in the story file it belongs to. Each stage has a `hint`, which the player reads while it's the stage they're on, and a `done` condition. The showcase's first quest, cut down to two stages: ```ts import type { Content } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' export const movingDay: Content = { data: { quests: { quests: [ { id: 'settle', name: 'Settle in', description: 'New town, new flat. Find your feet.', starts: { kv: 'phase', is: ['open'] }, stages: [ { id: 'out', hint: 'Step out onto the high street.', done: places.at('high-street') }, { id: 'ava', hint: 'Somebody runs the café. Say hello.', done: { seen: 'ava.hi' } }, ], }, ], }, }, } ``` Write each `done` for the moment something happens, such as arriving on the high street. A stage stays done when its condition stops holding, and a later stage counts only once the stages before it are done. The quest is done when its last stage is. ## Start it [#start-it] Give the quest a `starts` condition, and it starts the first time that holds after a command. `settle` starts when the intro sets the `phase` key to `open`. Leave `starts` out to start the quest from an effect instead, with `quests.start()`: ```ts import type { ActionDef } from '@ifloom/engine' import { quests } from '@ifloom/plugin-quests' export const collar: ActionDef = { id: 'collar', label: 'Turn up your collar', effects: [quests.start('scarf')] } ``` A quest can start another, as the showcase's `friend` quest does with `starts: quests.active('settle')`. Give a quest `secret: true` to leave it out of the count of quests still to find until it starts. ## Gate content on its progress [#gate-content-on-its-progress] Read a quest's progress with its conditions, anywhere a condition goes: ```ts import type { Choice } from '@ifloom/engine' import { quests } from '@ifloom/plugin-quests' export const river: Choice = { id: 'river', label: 'Walk to the river', when: quests.reached('friend', 'close'), effects: [{ scene: 'ava.river' }] } ``` - **`quests.active('settle')`** holds while the quest is started and not done. - **`quests.reached('friend', 'close')`** holds once that stage is done. - **`quests.done('settle')`** holds once the last stage is done. ## Show a badge for news [#show-a-badge-for-news] A quest has news when it starts, moves on a stage or is done. Print the number of quests with news the player hasn't looked at with `{{quests/updates}}`, such as in a button's label `To do ({{quests/updates}})`. When the player has looked, send `quests.seen()` to mark every quest's news seen, or `quests.seen('settle')` for one. The React UI's quest log shows the count as a badge, with a Mark all seen button that sends `quests.seen()`. ## Track one quest [#track-one-quest] Send `quests.track('scarf')` to track an active quest, which puts it first in the list. The quest log's Track button sends it. `quests.track()` with no quest stops tracking. Tracking a quest that isn't active is refused with `You are not doing that.` ## Check it worked [#check-it-worked] Run `npm run check`. It reports a quest with no stages, two stages with one id, and anything a `done` or `starts` names that the game doesn't have: ```text content · quests settle · stage out: unknown location "lido" ``` Then play in `npm run dev`. Once the quest starts, it shows in the quest log with its first hint, and the hint moves on as each stage is done. To render the log in a UI of your own, see [Render the quest log](https://ifloom.dev/docs/how-to/render/progress-plugins#render-the-quest-log). In the showcase, Small Town, `settle` is in [`examples/showcase/src/story/moving-day.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/moving-day.ts) and `friend` in `src/story/ava.ts`. For more, see: - [Quests](https://ifloom.dev/docs/reference/plugins/quests), with [`QuestDef`](https://ifloom.dev/docs/reference/plugins/quests#questdef), [`QuestStage`](https://ifloom.dev/docs/reference/plugins/quests#queststage) and the [`quests/start`](https://ifloom.dev/docs/reference/plugins/quests#questsstart) effect. - [Build a friendship in stages](https://ifloom.dev/docs/how-to/build-friendships-in-stages), to pace a quest's stages over days. - [Stats, the kv store and storylines](https://ifloom.dev/docs/explanation/entities-and-traits#stats-the-kv-store-and-storylines). # Add a settings page (https://ifloom.dev/docs/how-to/add-a-settings-page) Use this to let the player change things such as hints or the text size. The engine has no settings of its own, so your content declares each one, and their [profile](https://ifloom.dev/docs/reference/profile) keeps the player's choices, so a new game starts with them. ## Declare the settings [#declare-the-settings] List them in your content's `settings`. A [setting](https://ifloom.dev/docs/reference/settings#settingdef) is a `toggle`, a `choice` or a `range`. This declares one of each sort the showcase uses: ```ts import type { Content } from '@ifloom/engine' export const settings: Content = { settings: [ { id: 'hints', label: 'Show hints', type: 'toggle', default: true }, { id: 'textSize', label: 'Text size', type: 'choice', affects: 'ui', options: [ { value: 'normal', label: 'Normal' }, { value: 'large', label: 'Large' }, ], default: 'normal', }, ], } ``` `hints` leaves out `affects`, so it's a play setting, part of the game state and the save. `textSize` has `affects: 'ui'`, so it never enters the game state. It's kept only in the profile, and only your UI reads it. ## Read a play setting in the story [#read-a-play-setting-in-the-story] Read a play setting with the [`{ setting }`](https://ifloom.dev/docs/reference/conditions#setting) condition, as you would a kv key. This high street shows a hint line only while hints are on: ```ts fragment body: [ { text: 'Bunting, a bus stop and the smell of the bakery.' }, { text: 'The café is open in the mornings.', when: { setting: 'hints' } }, ], ``` A change to a play setting goes through the game as a [`setting`](https://ifloom.dev/docs/reference/commands#setting) command, so it applies at once, is logged with the other commands and replays the same. A save keeps the settings it was made with, so loading an old save brings its values back. ## Show the settings page [#show-the-settings-page] In the React UI, turn on `pages`, and the title screen and the player's menu gain a Settings button once the game declares a setting. Its page renders a checkbox for a toggle, radio buttons for a choice and a slider for a range. With a UI of your own, render `view.settings` and send each change with `runner.setSetting`: ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** A settings screen: every setting the game declares, with its value now. A change goes through runner.setSetting. */ export function drawSettings(parent: HTMLElement, { view, settings }: RunnerSnapshot): void { // settings has the values of both kinds: play settings from the state, ui settings from the profile. for (const setting of view.settings) { const label = add(parent, 'label', setting.label) const value = settings[setting.id] ?? setting.default if (setting.type === 'toggle') { const box = add(label, 'input') Object.assign(box, { type: 'checkbox', checked: value === true }) box.onchange = () => runner.setSetting(setting.id, box.checked) } else if (setting.type === 'choice') { const select = add(label, 'select') for (const option of setting.options ?? []) Object.assign(add(select, 'option', option.label), { value: option.value, selected: option.value === value }) select.onchange = () => runner.setSetting(setting.id, select.value) } else { const range = add(label, 'input') Object.assign(range, { type: 'range', min: String(setting.min ?? 0), max: String(setting.max ?? 100), step: String(setting.step ?? 1), value: String(value), }) range.onchange = () => runner.setSetting(setting.id, Number(range.value)) } } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import module from './game.ts' // `pages` opens on a title screen whose Settings page renders every setting the game declares, play and ui alike. mountGame(module.build(), { pages: true }) ``` ```vue tab="Vue" tab-group="framework" ``` Read each value from [`runner.snapshot().settings`](https://ifloom.dev/docs/reference/runner#settings), which holds both sorts, and fall back to the setting's `default`. [Render a settings screen](https://ifloom.dev/docs/how-to/render/saves-and-settings#render-a-settings-screen) says what each `SettingView` holds. ## Apply a ui setting where you render the story [#apply-a-ui-setting-where-you-render-the-story] Read the value where you render the story. The runner calls its listeners when the player changes it, so whatever renders on a change reads the new value. In the React UI, [`useSetting`](https://ifloom.dev/docs/reference/react/components#usesetting) reads it and renders the component again: ```ts fragment tab="Plain JS" tab-group="framework" // src/main.ts, in the vanilla template. In draw(): root.classList.toggle('large', runner.snapshot().settings.textSize === 'large') ``` ```tsx tab="React" tab-group="framework" import type { ReactNode } from 'react' import { useSetting } from '@ifloom/react' export function Story({ children }: { children: ReactNode }) { const size = useSetting('textSize') return
{children}
} ``` ```vue tab="Vue" tab-group="framework" ``` ## Apply it to the whole page [#apply-it-to-the-whole-page] To size every page, the title screen included, put the setting on ``. In the React UI, name the setting in the game's [`ui.settings`](https://ifloom.dev/docs/reference/react/hints#settings) hint. The React UI copies the text size to `data-text-size` on ``, where its styles size the page for `small`, `normal`, `large` or `larger`. It leaves the story's pictures out while the toggle named in `images` is off: ```ts import type { Content } from '@ifloom/engine' export const look: Content = { ui: { settings: { textSize: 'textSize' } }, } ``` With a UI of your own, copy the value to the attribute now and whenever it changes: ```ts given // src/main.ts function showTextSize() { document.documentElement.dataset.textSize = String(runner.snapshot().settings.textSize) } showTextSize() runner.subscribe(showTextSize) ``` Then size the page by it. The React UI sizes everything in `rem`, so a larger root font scales the whole page, and so will your stylesheet if it does the same: ```css /* src/styles.css */ :root[data-text-size="large"] { font-size: 118.75%; } ``` ## Change a setting from code [#change-a-setting-from-code] Call `runner.setSetting` with the setting's id and its new value. It checks the value against the declaration and answers a [`Result`](https://ifloom.dev/docs/reference/common#result): ```ts given const changed = runner.setSetting('textSize', 'large') if (!changed.ok) console.warn(changed.reason) ``` A ui setting is written to the profile, so it needs a runner made with one. `mountGame` and [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner) make one. ## Check it worked [#check-it-worked] Run `npm run check`. It reports a `{ setting }` condition that names a setting the game doesn't declare, or a ui setting, which conditions can't read. [`checkUiHints`](https://ifloom.dev/docs/reference/react/hints#checkuihints), run in a test, reports a `ui.settings` hint that names a setting of the wrong sort. Then play in `npm run dev`, open Settings, and turn hints off: the hint line goes from the high street at once. Reload the page, and the setting is still off. For more, see: - [Settings](https://ifloom.dev/docs/reference/settings), with [`SettingDef`](https://ifloom.dev/docs/reference/settings#settingdef). - [`setSetting`](https://ifloom.dev/docs/reference/runner#setsetting) and the snapshot's [`settings`](https://ifloom.dev/docs/reference/runner#settings). - [The React UI's `settings` hint](https://ifloom.dev/docs/reference/react/hints#settings). - [Add music and sound](https://ifloom.dev/docs/how-to/add-music-and-sound#declare-the-tracks), for volume and mute settings. # Add a title screen (https://ifloom.dev/docs/how-to/add-a-title-screen) Use this to open your game on a title screen rather than straight into the story. The [React UI](https://ifloom.dev/docs/reference/react) has one built in, turned on with an option. With a UI of your own, you render the screen from the [runner](https://ifloom.dev/docs/reference/runner). ## Turn on the title screen [#turn-on-the-title-screen] In the React UI, pass `pages` to [`mountGame`](https://ifloom.dev/docs/reference/react#mountgame). With a UI of your own, render a title screen before the game. This one offers New game, and Continue once there's a save to go on from: ```ts tab="Plain JS" tab-group="framework" // src/title.ts import type { Runner } from '@ifloom/engine' /** New game, and Continue from the newest save once there is one (the autosave counts). `start` renders the game. */ export async function titleScreen(root: HTMLElement, runner: Runner, start: () => void): Promise { root.replaceChildren() root.appendChild(document.createElement('h1')).textContent = runner.view().title const buttons = root.appendChild(document.createElement('div')) buttons.className = 'choices' const fresh = buttons.appendChild(document.createElement('button')) fresh.textContent = 'New game' fresh.onclick = async () => { await runner.newGame() start() } // Newest first; a save that can't be read is never the one to continue. Without storage, there's nothing to continue. const listed = await runner.saves?.list() const newest = listed?.ok ? listed.value.find((save) => !('broken' in save)) : undefined if (newest) { const carryOn = buttons.appendChild(document.createElement('button')) carryOn.textContent = 'Continue' carryOn.onclick = async () => { const loaded = await runner.load(newest.slot) if (loaded.ok) start() } } } ``` ```ts fragment tab="Plain JS" tab-group="framework" // src/main.ts, in the vanilla template: the title screen first, then the game. import { titleScreen } from './title.ts' void titleScreen(root, runner, () => { runner.subscribe(({ view }) => draw(view)) draw(runner.view()) }) ``` ```ts tab="React" tab-group="framework" // src/main.ts import { mountGame } from '@ifloom/react' import module from './game.ts' import { Layout } from './layout.tsx' import './styles.css' mountGame(module.build(), { layout: Layout, pages: { subtitle: 'A new flat, a new town, and a cat with no name.', art: 'art/title.jpg', }, }) ``` ```vue tab="Vue" tab-group="framework" ``` ```vue tab="Vue" tab-group="framework" ``` `pages: true` turns the React UI's title screen on with no subtitle or picture. A missing `art` file takes no space, so you can add the picture later. The credits come from your content's `credits`, which [Credit your team and supporters](https://ifloom.dev/docs/how-to/credit-your-team-and-supporters) adds. Your own title screen reads three things from the runner: - [`runner.saves.list()`](https://ifloom.dev/docs/reference/saves#saves) lists the saves newest first, the autosave among them, then any that can't be read, as `{ slot, broken }`. It answers a [`Result`](https://ifloom.dev/docs/reference/common#result), which fails where the browser refuses storage, so the screen offers only New game then. - [`runner.newGame()`](https://ifloom.dev/docs/reference/runner#newgame) starts afresh with the player's stored settings. - [`runner.load`](https://ifloom.dev/docs/reference/runner#save-load-and-restore) loads a slot. Its `Result` fails with a `reason` when a save can't be read, so show that to the player. ## Know what the React UI's title screen offers [#know-what-the-react-uis-title-screen-offers] The React UI opens on the title screen, with the game's title and a New game button, and the player's menu gains a Title screen button that goes back. Other buttons show once there's something behind them: - **Continue** loads the newest save, once the player has saved or the game has autosaved. - **Load** opens a list of every save. - **Settings** opens the settings page, once your game declares a setting (see [Add a settings page](https://ifloom.dev/docs/how-to/add-a-settings-page)). - **Credits** shows the credits, once your content's [`credits`](https://ifloom.dev/docs/reference/credits) name someone. - **New Game+** starts a new game that keeps a little of the last, once the player has finished the game (see [Offer New Game+](https://ifloom.dev/docs/how-to/offer-new-game-plus)). The title screen keeps settings and the finished mark in the player's [profile](https://ifloom.dev/docs/reference/profile), so the runner needs one. `mountGame` and [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner) make one for you. If you build your runner by hand, give it a profile: ```ts given import { localStorageDriver } from '@ifloom/browser' import { createRunner, profile, saves, startingState } from '@ifloom/engine' const runner = createRunner(game, startingState(game), { saves: saves(game, localStorageDriver()), profile: profile(game, localStorageDriver()), }) ``` Then render [`GameShell`](https://ifloom.dev/docs/reference/react#gameshell) with that runner and the same `pages` prop, as in ``. ## Make it look like your game [#make-it-look-like-your-game] Your own title screen looks however your stylesheet says. In the React UI, each [preset](https://ifloom.dev/docs/how-to/react/theme-the-react-ui) gives the title screen its own look. To change it, style its parts, such as `title-name` for the title and `title-button` for each button: ```css [data-part="title-name"] { font-family: "Georgia", serif; letter-spacing: 0.05em; } [data-part="title-button"] { min-width: 12rem; } ``` [The pages](https://ifloom.dev/docs/reference/react/parts#the-pages) lists every part of the title screen and the pages around it. To replace a page entirely, pass your own `TitlePage`, `SettingsPage`, `LoadPage`, `CreditsPage` or `GatePage` in `components`, as [Rearrange or replace the React UI's parts](https://ifloom.dev/docs/how-to/react/replace-parts) shows. ## Check it worked [#check-it-worked] Run `npm run dev`. The page opens on the title screen. Press New game, then save from the menu, and go back to the title screen with Title screen: Continue now shows and loads that save. For more, see: - [`PagesOptions`](https://ifloom.dev/docs/reference/react/components#pagesoptions) and [`TitlePage`](https://ifloom.dev/docs/reference/react/components#titlepage). - [The runner](https://ifloom.dev/docs/reference/runner) and [Saves](https://ifloom.dev/docs/reference/saves). - [Add pages around the game](https://ifloom.dev/docs/how-to/add-pages-around-the-game), for a notice before the title screen and pages of your own. # Add a transition or reveal lines (https://ifloom.dev/docs/how-to/add-a-transition) Use this to make a scene fade in, the next location slide in from the side, or a paragraph wait a moment before it appears. Content asks for each with a [ui hint](https://ifloom.dev/docs/reference/glossary#ui-hints), a `ui` field the engine carries to the view unchanged. The names on this page, `transition` and `reveal`, are the [React UI's hints](https://ifloom.dev/docs/reference/react/hints). Tests, `ifloom playtest` and replays ignore them. ## Give a scene a transition [#give-a-scene-a-transition] Add `ui.transition` to the scene. A name on its own is used both ways, coming in and going out: ```ts import type { DataScene } from '@ifloom/engine' export const river: DataScene = { id: 'ava.river', title: 'By the river', ui: { transition: 'fade' }, body: [{ text: 'Ava is on the bench with her shoes off, feeding the ducks.' }], choices: [{ id: 'stay', label: 'Sit with her', effects: [{ scene: null }] }], } ``` To say each way separately, give `in` and `out`, and `ms` for how long each takes, 300 if left out: ```ts fragment ui: { transition: { in: 'slide-up', out: 'fade', ms: 500 } } ``` The built-in names are `fade`, `slide-up`, `slide-left`, `zoom` and `none`, listed in [`TransitionName`](https://ifloom.dev/docs/reference/react/hints#transitionname). ## Give a location or the whole game one [#give-a-location-or-the-whole-game-one] A location takes the same hint, for the room while no scene is open, so walking between locations can slide: ```ts import { places } from '@ifloom/plugin-places' export const highStreet = places.location({ id: 'high-street', name: 'High Street', exits: ['flat', 'cafe'], body: [{ text: 'Bunting, a bus stop and the smell of the bakery.' }], ui: { transition: 'slide-left' }, }) ``` Set a default in your content's `ui`. A scene or a location that says nothing uses it, and one that sets only `in` takes `out` and `ms` from it: ```ts import type { Content } from '@ifloom/engine' export const town: Content = { ui: { transition: { in: 'fade', ms: 250 } } } ``` ## Bring the next screen in from a choice [#bring-the-next-screen-in-from-a-choice] Give a choice a `ui.transition` to say how the screen it leads to comes in, whatever that screen declares. The React UI plays it once, whether the player clicked the choice or pressed its number key: ```ts import type { Choice } from '@ifloom/engine' export const unpack: Choice = { id: 'unpack', label: 'Unpack', ui: { transition: { in: 'slide-up', ms: 400 } }, effects: [{ scene: null }] } ``` ## Reveal lines one after another [#reveal-lines-one-after-another] Give a body block `ui.reveal`, and it waits before it appears. `delay` is the wait in milliseconds after the reveal before it, or after the scene comes on, 800 if left out. `as` is how it comes in, `fade` if left out: ```ts import { text, type Block } from '@ifloom/engine' export const intro: Block[] = [ text('The van pulls away and leaves you on the pavement with three boxes, a key and a cat in a basket.'), text('Tomorrow you start learning the town. Tonight you unpack.', { ui: { reveal: { delay: 1200 } } }), text('The cat has opinions about the basket.', { ui: { reveal: { delay: 1500, as: 'slide-up' } } }), ] ``` Put a paragraph that should wait in a block of its own. Every line is in the page from the start for screen readers, and only its look waits. The choices come after the last reveal, and a click on the scene or any key shows the rest at once. ## Restyle them [#restyle-them] Write CSS against the attributes the React UI sets. The new scene carries `data-transition-in`, the copy of the scene going out carries `data-leaving` and `data-transition-out`, and each held-back group of lines carries `data-reveal`. The times are the CSS variables `--ifloom-transition-ms`, `--ifloom-reveal-at` and `--ifloom-reveal-ms`. A slower, softer fade for every reveal: ```css :root { --ifloom-reveal-ms: 900ms; } [data-reveal="fade"] { animation-timing-function: ease-in-out; } ``` Your rules win over the base styles, which sit in a cascade layer. [Parts](https://ifloom.dev/docs/reference/react/parts) lists every part and attribute. ## Add a transition of your own [#add-a-transition-of-your-own] List the name in your content's `ui.transitionNames`, use it like a built-in one, and play it with CSS: ```ts import type { Content } from '@ifloom/engine' export const curtains: Content = { ui: { transitionNames: ['curtain'] } } ``` ```css @keyframes curtain-in { from { clip-path: inset(0 50% 0 50%); } } @keyframes curtain-out { to { clip-path: inset(0 50% 0 50%); } } [data-transition-in="curtain"] { animation-name: curtain-in; } [data-leaving][data-transition-out="curtain"] { animation-name: curtain-out; } [data-reveal="curtain"] { animation-name: curtain-in; } ``` ## Check it worked [#check-it-worked] Run [`checkUiHints`](https://ifloom.dev/docs/reference/react/hints#checkuihints) over the game, as a test does. It reports a transition name that is neither built in nor in `transitionNames`, which catches typos. Then play the scene with `npm run dev`. A player whose system asks for reduced motion sees every scene and line at once, and so does everyone when you pass `motion: false` to `mountGame`. To play the same hints in a UI of your own, see [Play transitions and reveals](https://ifloom.dev/docs/how-to/render/scene#play-transitions-and-reveals). To keep the React UI's timing in a scene component of your own, build it on [`useScene`](https://ifloom.dev/docs/reference/react/components#usescene). In the showcase, Small Town, the moving-day scene fades in and reveals its second paragraph, and its Unpack choice brings the flat in with `slide-up` (`examples/showcase/src/story/moving-day.ts`). For more, see: - [The React UI's hints](https://ifloom.dev/docs/reference/react/hints), with `transition`, `transitionNames` and `reveal`. - [UI hints](https://ifloom.dev/docs/reference/ui-hints), for how the engine carries them. - [Presentation lives in UI packages](https://ifloom.dev/docs/explanation/design#presentation-lives-in-ui-packages). # Add music and sound (https://ifloom.dev/docs/how-to/add-music-and-sound) Use this to give your game music, background sound, one-shot sounds and voiced lines. Your content lists the tracks and says when each plays. The engine works out what should be playing and lists it in `view.audio`, and the [audio player](https://ifloom.dev/docs/reference/browser/audio-player), `@ifloom/audio`, plays it in the browser. ## Put the files in public/audio [#put-the-files-in-publicaudio] Put every sound file in your game's `public/audio/` folder. A track names its file by its path under `audio/`, and a bare name is an `.ogg`: `'music/calm'` is `public/audio/music/calm.ogg`. `ifloom build` copies `public/` beside the page. Ship the `audio/` folder with the game, since `--inline-assets` puts pictures into the page but never sound. ## Declare the tracks [#declare-the-tracks] List each file in your content's `audio.tracks` by id, with the channel it plays on. Declare a volume setting for each channel and a mute box, as `ui` [settings](https://ifloom.dev/docs/reference/settings) the player changes: ```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: 'sfxVolume', label: 'Sounds', affects: 'ui', type: 'range', min: 0, max: 100, default: 90 }, { 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' }, sfx: { mode: 'cue', volume: 'sfxVolume' }, }, mute: 'muted', default: { music: 'calm' }, }, } ``` The game has four channels without declaring any. `music` and `ambience` are background channels, which play one track or playlist until it changes. `sfx` and `voice` are cue channels, which play each sound once. A track with no `channel` plays on `sfx`. `default` is the music that plays when nothing else names a track. ## Change the music [#change-the-music] Name a background track wherever the music should change: - **A scene's `audio`** plays while the scene is open, such as `audio: { music: 'evening' }`. `{ music: null }` is silence, and the music comes back when the scene closes. - **The [`audio` effect](https://ifloom.dev/docs/reference/effects#audio)** puts a track on a channel until another changes it, and the save keeps it: `{ audio: 'music', to: 'radio' }`. - **A location's `audio`**, with the [places plugin](https://ifloom.dev/docs/reference/plugins/places), plays while the player is there. The open scene wins over an `audio` effect, which wins over the location, which wins over `default`. The café has a murmur of its own: ```ts import { places } from '@ifloom/plugin-places' export const cafe = places.location({ id: 'cafe', name: 'The Corner Café', exits: ['high-street'], body: [{ text: 'Six tables, one of them wobbly.' }], audio: { ambience: 'cafe.murmur' }, }) ``` ## Play a sound or a voiced line [#play-a-sound-or-a-voiced-line] Play a one-shot sound with the [`sound` effect](https://ifloom.dev/docs/reference/effects#sound), on a choice or an action: `{ sound: 'knock' }`. In a scene's words, `[[sound:knock]]` plays it while the scene is on screen, and `[[voice:ava.hello]]` after a spoken line voices it: ```ts import type { DataScene } from '@ifloom/engine' export const hello: DataScene = { id: 'ava.hi', speaker: 'ava', body: [{ text: '@ava: "Hi! You must be the new neighbour." [[voice:ava.hello]]' }], choices: [{ id: 'bye', label: 'Leave her to it', effects: [{ scene: null }] }], } ``` Each sound plays once. Entering the scene again plays its sounds again, and loading a save doesn't replay old ones. A voice always goes to the `voice` channel, where each line waits for the one before it. A location's words don't cue sounds, so use its `audio`, or a `sound` effect on the action that brings the player there. ## Start the audio player [#start-the-audio-player] The React UI's `mountGame` starts the player when the game lists any tracks, and its settings page renders the volume and mute settings. With a UI of your own, call [`startAudio`](https://ifloom.dev/docs/reference/browser/audio-player#startaudio) once, beside the runner. The `vanilla` and `vue` templates already do: ```ts tab="Plain JS" tab-group="framework" import { startAudio } from '@ifloom/audio' import { audioSrc, type RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' // Once, beside the runner: plays what view.audio asks for, from the player's first click or key press. // Keep the player it returns to play a file on demand. const player = startAudio(runner) /** A Play again button for each spoken line in the scene that has a voice. */ export function drawVoices(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const beat of view.scene.beats) { if (beat.type !== 'say' || !beat.voice) continue // The voice names a track in the game's audio.tracks: a file, or a playlist, which has no one file to play. const track = runner.game.audio?.tracks[beat.voice] if (track && 'src' in track) add(parent, 'button', 'Play again').onclick = () => player.play(audioSrc(track.src), 'voice', track.volume ?? 1) } } ``` ```tsx tab="React" tab-group="framework" import { useAudio } from '@ifloom/react' // mountGame plays the game's sound, and Scene puts a replay button on each spoken line with a voice. // To give the player options, place useAudio once in your layout: it takes over from mountGame's player. export function SoundLog() { // Each thing the player does, as a line in the console. useAudio({ log: console.debug }) return null } ``` ```vue tab="Vue" tab-group="framework" ``` Nothing plays until the player first clicks or presses a key, because browsers allow no sound sooner. Then the music for where the player is starts. A game with a start button of its own calls the player's `unlock()` from its handler. Start only one player per runner, or everything plays twice. In React, `useAudio` takes over from `mountGame`'s player instead of adding a second. The player reads each channel's volume from the setting its `volume` names, so moving a slider changes the volume at once. It reads a range from its `min` to its `max` as 0 to 1, times the track's own `volume`. For a box ticked for sound, name it in `audio.sound` instead of `mute`. ## Check it worked [#check-it-worked] Run `npm run check`. It lists every track's file that isn't in `public/audio/`, and reports a track, a channel or a setting that content names and the game lacks. Then play in `npm run dev` and pass `{ log: console.debug }` to `startAudio`, or `audio: { log: console.debug }` to `mountGame`. The browser's console shows each thing the player does: ```text 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 ``` A `play refused` line is the browser saying no before the first click. The player tries refused music again on the next click. ## Variations [#variations] **Quieter music under a voice.** Give the music channel a `duck`, `{ mode: 'background', volume: 'musicVolume', duck: { under: ['voice'], to: 0.4 } }`, and it drops to 0.4 while a voiced line plays. **Sound in the opening scene.** The player counts every sound already in the view as heard when it starts, so the first scene's `[[sound:…]]` doesn't play. Start that sound from a choice, or put music on its channel, which plays as soon as sound is unlocked. **No sound in the React UI.** Pass `audio: false` to `mountGame` for a game that plays sound some other way. For more, see: - [Audio](https://ifloom.dev/docs/reference/audio), with [`GameAudio`](https://ifloom.dev/docs/reference/audio#gameaudio), [`TrackDef`](https://ifloom.dev/docs/reference/audio#trackdef), [`PlaylistDef`](https://ifloom.dev/docs/reference/audio#playlistdef) and [`ChannelDef`](https://ifloom.dev/docs/reference/audio#channeldef). - [The audio player](https://ifloom.dev/docs/reference/browser/audio-player). - The [sound and voice markup](https://ifloom.dev/docs/reference/prose#sound-and-voice). - [Render pictures and play sound](https://ifloom.dev/docs/how-to/render/pictures-and-sound#play-sound), with a button that plays a voiced line again. # Add a content notice and pages of your own (https://ifloom.dev/docs/how-to/add-pages-around-the-game) Use this to show a content notice before the title screen, or to add a page of your own beside the title screen, such as a gallery or a list of endings found. Turn the title screen on first, as [Add a title screen](https://ifloom.dev/docs/how-to/add-a-title-screen) shows. Both pages read and write the player's [profile](https://ifloom.dev/docs/reference/profile), which outlives every save. ## Show a notice before the title screen [#show-a-notice-before-the-title-screen] In the React UI, give `pages` a `gate`. With a UI of your own, render the notice before the title screen, and remember in the profile's `ui:gate` that the player has read it: ```ts tab="Plain JS" tab-group="framework" // src/gate.ts import type { Runner } from '@ifloom/engine' /** The notice, unless the player confirmed it before on this device. `next` renders the title screen. */ export async function gate(root: HTMLElement, runner: Runner, next: () => void): Promise { if (await runner.profile?.get('ui:gate')) return next() root.replaceChildren() root.appendChild(document.createElement('h1')).textContent = 'Before you start' root.appendChild(document.createElement('p')).textContent = 'This story mentions a house fire.' root.appendChild(document.createElement('p')).textContent = 'It happens off the page.' const confirm = root.appendChild(document.createElement('button')) confirm.textContent = 'Carry on' confirm.onclick = async () => { await runner.profile?.set('ui:gate', true) next() } Object.assign(root.appendChild(document.createElement('a')), { href: 'https://example.com/', textContent: 'Not today' }) } ``` ```ts tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import module from './game.ts' mountGame(module.build(), { pages: { gate: { title: 'Before you start', text: 'This story mentions a house fire.\n\nIt happens off the page.', confirm: 'Carry on', decline: { label: 'Not today', href: 'https://example.com/' }, }, }, }) ``` ```vue tab="Vue" tab-group="framework" ``` Confirming moves on to the title screen and is remembered on that device, so the notice doesn't show again. Declining follows the link. Every word on the notice is yours. In the React UI's `gate`, a blank line in `text` starts a new paragraph. Without an `href`, the decline button does nothing and the player stays on the notice. ## Add a page of your own [#add-a-page-of-your-own] In the React UI, give `pages.pages` a component for each page, by id, and the title screen gets a button for it. With a UI of your own, show the page from a button on your title screen. This endings page reads `core:finished`, which the runner writes to the profile the first time the game's `finished` condition holds: ```ts tab="Plain JS" tab-group="framework" // src/endings.ts import type { Runner } from '@ifloom/engine' /** The endings page. `back` renders the title screen again. */ export async function endings(root: HTMLElement, runner: Runner, back: () => void): Promise { const finished = await runner.profile?.get<{ at: number }>('core:finished') root.replaceChildren() root.appendChild(document.createElement('h1')).textContent = 'Endings' root.appendChild(document.createElement('p')).textContent = finished ? 'You have reached an ending.' : 'No endings yet.' const button = root.appendChild(document.createElement('button')) button.textContent = 'Back' button.onclick = back } ``` ```tsx tab="React" tab-group="framework" import { mountGame, useProfile, usePage } from '@ifloom/react' import module from './game.ts' function Endings() { const { back } = usePage() const finished = useProfile<{ at: number }>('core:finished') return (

Endings

{finished ? 'You have reached an ending.' : 'No endings yet.'}

) } mountGame(module.build(), { pages: { pages: { endings: { label: 'Endings', component: Endings } } }, }) ``` ```vue tab="Vue" tab-group="framework" ``` In the React UI, the component takes no props and fills the whole page. [`usePage`](https://ifloom.dev/docs/reference/react/components#usepage) moves between pages, and [`useProfile`](https://ifloom.dev/docs/reference/react/components#useprofile) reads what outlives a save. Set `showOnTitle: false` to leave the page's button off the title screen, and open it yourself with `usePage().go('endings')`. A page with the id of one a plugin UI adds, such as `achievements`, replaces it. ## Check it worked [#check-it-worked] Run `npm run dev`. The notice shows before the title screen. Press Carry on, reload the page, and it goes straight to the title screen. To see the notice again, clear the site's storage in the browser. The title screen has an Endings button, and its page says "No endings yet." until you finish the game. For more, see: - [`PagesOptions`](https://ifloom.dev/docs/reference/react/components#pagesoptions), [`GatePage`](https://ifloom.dev/docs/reference/react/components#gatepage) and [`usePage`](https://ifloom.dev/docs/reference/react/components#usepage). - [Profile](https://ifloom.dev/docs/reference/profile), with its `ui:gate` and `core:finished` keys. - [End the game](https://ifloom.dev/docs/how-to/end-the-game#count-it-as-finishing-the-game), for the `finished` condition. # Add pictures and backgrounds (https://ifloom.dev/docs/how-to/add-pictures-and-backgrounds) Use this to put pictures and short clips in your game: in a scene's words, behind a scene, picked from a set by tags, or stacked in layers with a part the player clicks. The engine renders none of them itself. It lists them in the view, and a UI shows them, the React UI with no setup. ## Put the files in public/art [#put-the-files-in-publicart] Put every picture and clip in your game's `public/art/` folder. Content names a file by its path under `art/`, and [`artSrc`](https://ifloom.dev/docs/reference/prose#artsrc) turns that path into the one the page loads: - **A name with an extension** is that file: `'photo/ava.svg'` is `public/art/photo/ava.svg`. - **A bare name** is a `.jpg`, or an `.mp4` where a video is asked for: `'scene/market-morning'` is `public/art/scene/market-morning.jpg`. - **A URL** is used as it is, but a game opened from disk can't fetch one, so keep your files in `art/`. `ifloom build` copies `public/` beside the page, so the paths work from disk and from a static host. ## Show a picture in a scene [#show-a-picture-in-a-scene] Put a `{ media }` block in the scene's body where the picture goes. `size: 'wide'` spans the column, and `at: 'lead'` puts it before the words as an establishing picture: ```ts import type { DataScene } from '@ifloom/engine' export const market: DataScene = { id: 'market.morning', title: 'The market', body: [{ media: { src: 'scene/market-morning', size: 'wide', at: 'lead', alt: 'Stalls going up in the square' } }, { text: 'The bread stall is already half sold.' }], choices: [{ id: 'leave', label: 'Walk on', effects: [{ scene: null }] }], } ``` In words, write the [image markup](https://ifloom.dev/docs/reference/prose#images) as a paragraph of its own: `[[img:scene/market-morning|Stalls going up]]` in the column, or `[[wide:…]]` across it. ## Give a scene a background [#give-a-scene-a-background] Give the scene a [`picture`](https://ifloom.dev/docs/reference/scenes#picture) with one layer. The engine lists it in `view.scene.picture`: ```ts import type { DataScene } from '@ifloom/engine' export const knock: DataScene = { id: 'flat.knock', title: 'A knock at the door', picture: { aspect: '16/9', layers: [{ id: 'hall', src: 'flat/hall' }] }, body: [{ text: 'Someone knocks, three times, not loud.' }], choices: [{ id: 'close', label: 'Close the door', effects: [{ scene: null }] }], } ``` The React UI's `Scene` renders the picture above the words. To put it behind the words instead, set the bottom layer as the background of the box round the scene: ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' /** The scene's picture behind its words: its bottom layer as the story's background, and none for a scene without one. */ export function drawBackground(story: HTMLElement, { view }: RunnerSnapshot): void { const layer = view.scene.picture?.layers[0] // A video layer can't be a CSS background, so it's left to drawPicture. story.style.backgroundImage = layer && !layer.video ? `url("${layer.src}")` : '' story.style.backgroundSize = 'cover' story.style.backgroundPosition = 'center' } ``` ```tsx tab="React" tab-group="framework" import { Scene, useGame } from '@ifloom/react' // The scene's picture behind its words: its bottom layer as the background of a box round the Scene. // Put it in your layout's Story in place of Scene. Scene still renders the picture above the words too. export function SceneBackground() { const { view } = useGame() const layer = view.scene.picture?.layers[0] const backgroundImage = layer && !layer.video ? `url("${layer.src}")` : undefined return (
) } ``` ```vue tab="Vue" tab-group="framework" ``` A video layer can't be a CSS background, so leave it to the code that renders the picture, as [Render the scene's picture](https://ifloom.dev/docs/how-to/render/pictures-and-sound#render-the-scenes-picture) shows. ## Pick a picture from a pool [#pick-a-picture-from-a-pool] Declare a pool in your content's `media.pools`, a named list of files, each with the tags you sort them by: ```ts import type { Content } from '@ifloom/engine' export const doors: Content = { media: { pools: { door: [ { src: 'door/blue-day.jpg', tags: ['blue', 'day'], weight: 4 }, { src: 'door/blue-night.jpg', tags: ['blue', 'night'] }, { src: 'door/red-day.jpg', tags: ['red', 'day'] }, { src: 'door/red-night.jpg', tags: ['red', 'night'] }, ], }, }, } ``` Ask the pool for a file by tags, in a block as `{ media: { pool: 'door', tags: ['red', 'night'], alt: 'The front door' } }`, or in words as `[[img:@door|red,night|The front door]]`. The engine draws among the files with every tag, by `weight`. With none, it drops the last tag and tries again, so put the tag that matters most first. The save keeps each pick, so the same request in the same place shows the same file on every visit. ## Build a layered picture with a hotspot [#build-a-layered-picture-with-a-hotspot] Give a scene's `picture` several layers, bottom first, each shown while its `when` holds. A layer can ask a pool too. A hotspot is a part of the picture the player clicks, placed by its `rect` (left, top, width and height, in percent), and its `choice` chooses one of the scene's choices: ```ts import type { DataScene } from '@ifloom/engine' export const answer: DataScene = { id: 'flat.knock', picture: { aspect: '16/9', layers: [ { id: 'hall', src: 'flat/hall' }, { id: 'rain', pool: 'window', tags: ['rain'], when: { kv: 'raining' } }, ], hotspots: [{ id: 'door', rect: [60, 10, 25, 85], label: 'The front door', choice: 'answer' }], }, body: [{ text: 'Someone knocks, three times, not loud.' }], choices: [ { id: 'answer', label: 'Answer it', effects: [{ scene: 'flat.visitor' }] }, { id: 'ignore', label: 'Pretend you’re out', effects: [{ scene: null }] }, ], } ``` The hotspot is greyed out and hidden exactly when its choice's button is. Give a hotspot `command` instead of `choice` to send any command. ## Give a location a picture [#give-a-location-a-picture] With the [places plugin](https://ifloom.dev/docs/reference/plugins/places), give the location an `image` for one picture, or a `picture` for layers and hotspots. A location's hotspot sends a `command`. The showcase café shows Ava at the counter while she's there, and clicking her talks to her: ```ts import { cast } from '@ifloom/plugin-cast' import { places } from '@ifloom/plugin-places' export const cafe = places.location({ id: 'cafe', name: 'The Corner Café', exits: ['high-street'], picture: { aspect: '16/10', layers: [{ id: 'counter', src: 'photo/ava.svg', when: cast.here('ava') }], hotspots: [{ id: 'ava', rect: [36, 22, 28, 44], label: 'Talk to Ava', command: cast.talk('ava'), layer: 'counter' }], }, body: [{ text: 'Six tables, one of them wobbly.' }], }) ``` `layer: 'counter'` hides the hotspot while that layer isn't shown. ## Add a video [#add-a-video] Name an `.mp4` or `.webm` file wherever a picture goes, or write `[[video:clips/kettle]]` in words. A clip plays by itself, loops, is muted and has no controls, as a GIF does. The [video flags](https://ifloom.dev/docs/reference/prose#videos) change that, in markup or on a `{ media }` block or a layer: ```ts fragment { media: { src: 'clips/high-street.mp4', controls: true, sound: true, poster: 'clips/high-street-still', alt: 'The high street on market day' } } ``` Browsers refuse to start a clip with sound by itself, so give one with `sound` the `controls` flag, and the player presses play. The React UI's clips follow the game's mute and volume settings. ## Check it worked [#check-it-worked] Run `npm run check`. It lists every picture and clip the game names that isn't in `public/art/`, and reports an unknown pool, a tag no file in the pool has, and a hotspot whose choice the scene lacks. Then play in `npm run dev`. In the React UI, clicking a picture or a clip opens it large in the [`MediaViewer`](https://ifloom.dev/docs/reference/react/components#mediaviewer). Pass `viewer: false` to `mountGame` to turn that off. ## Variations [#variations] **A placeholder for art that isn't made yet.** A labelled box is easier to spot than a gap. Replace the picture with one when its file fails to load: ```css .art-placeholder { display: grid; place-items: center; aspect-ratio: 16 / 9; border: 2px dashed #bbb; color: #888; font: 0.85rem monospace; } ``` ```ts tab="Plain JS" tab-group="framework" // src/picture.ts: use it where the vanilla template makes an . export function picture(src: string, alt = ''): HTMLElement { const img = document.createElement('img') img.src = src img.alt = alt img.onerror = () => { const box = document.createElement('div') box.className = 'art-placeholder' box.setAttribute('role', 'img') box.setAttribute('aria-label', alt) box.textContent = alt || src img.replaceWith(box) } return img } ``` ```tsx tab="React" tab-group="framework" // src/components.tsx: pass it to mountGame as `components`. import { useState } from 'react' import type { Components } from '@ifloom/react' export const components: Components = { Picture: function Placeholder({ Default, ...props }) { const [missing, setMissing] = useState() if (props.src && missing === props.src) { return (
{props.alt || props.src}
) } return { setMissing(props.src); props.onError?.(event) }} /> }, } ``` ```vue tab="Vue" tab-group="framework" ``` Every picture the React UI renders is a `Picture`, so the replacement covers scenes, portraits, notices and layered pictures. Render the built-in one through `Default`, since importing `Picture` from `@ifloom/react` inside the replacement gives you the replacement again. **Pictures a player can turn off.** Name a toggle setting in the game's `ui.settings.images` hint, and the React UI leaves the story's pictures and clips out while it's off, as [Add a settings page](https://ifloom.dev/docs/how-to/add-a-settings-page#apply-it-to-the-whole-page) shows. For more, see: - [Media](https://ifloom.dev/docs/reference/media), with [`PictureDef`](https://ifloom.dev/docs/reference/media#picturedef), [`HotspotDef`](https://ifloom.dev/docs/reference/media#hotspotdef) and [`PoolFile`](https://ifloom.dev/docs/reference/media#poolfile). - [`SceneMedia`](https://ifloom.dev/docs/reference/scenes#scenemedia) and the [image markup](https://ifloom.dev/docs/reference/prose#images). - [Render pictures and play sound](https://ifloom.dev/docs/how-to/render/pictures-and-sound), for a UI of your own. # Add IFLoom to an existing project (https://ifloom.dev/docs/how-to/add-to-a-project) Use this to put a game in a project that already has its own build, such as a site or an app. You need Node 20.19 or later, or 22.12 or later. To start a game in a new folder, see [Create a game](https://ifloom.dev/docs/how-to/create-a-game) instead. ## Install the packages [#install-the-packages] Install the engine and the browser helpers, and the CLI as a dev dependency: ```sh tab="npm" tab-group="package-manager" npm install @ifloom/engine @ifloom/browser npm install --save-dev @ifloom/cli ``` ```sh tab="pnpm" tab-group="package-manager" pnpm add @ifloom/engine @ifloom/browser pnpm add --save-dev @ifloom/cli ``` ```sh tab="yarn" tab-group="package-manager" yarn add @ifloom/engine @ifloom/browser yarn add --dev @ifloom/cli ``` ```sh tab="bun" tab-group="package-manager" bun add @ifloom/engine @ifloom/browser bun add --dev @ifloom/cli ``` Add `@ifloom/react` too for the ready-made [React UI](https://ifloom.dev/docs/reference/react), and `@ifloom/audio` for sound with a UI of your own. A plugin is one more package, as [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin) shows. ## Write the game module [#write-the-game-module] Make `src/game.ts`, the game module, whose default export `defineGame` makes. Its `build` returns what [`loadGame`](https://ifloom.dev/docs/reference/content#loadgame) returns, and the page and the CLI both build the game from it: ```ts // src/game.ts import { loadGame, text, type Content } from '@ifloom/engine' import { defineGame } from '@ifloom/cli/game' const opening: Content = { introScene: 'door', scenes: [{ id: 'door', title: 'The door', body: [text('A green door, half open. Someone inside is laughing.')], choices: [] }], } export default defineGame({ build: () => loadGame([opening], { id: 'my-game', title: 'My Game' }), }) ``` `@ifloom/cli/game` imports only the engine, so the page can import this module without bringing the CLI into the browser build. Split the content into files as the game grows (see [Organise your game's files](https://ifloom.dev/docs/how-to/organise-your-files)). ## Render it into the page [#render-it-into-the-page] Render the game into an element on your page, here `
`. The React tab uses the React UI, and the others render the scene and its choices with code of your own: ```ts tab="Plain JS" tab-group="framework" // src/play.ts import { browserRunner } from '@ifloom/browser' import module from './game.ts' const { game } = module.build() const runner = await browserRunner(game) const root = document.querySelector('#game')! function render(): void { const view = runner.view() root.replaceChildren() for (const beat of view.scene.beats) { if (beat.type === 'text') root.append(Object.assign(document.createElement('p'), { textContent: beat.text })) } for (const choice of view.scene.choices) { const button = Object.assign(document.createElement('button'), { textContent: choice.label, disabled: Boolean(choice.disabled) }) button.onclick = () => runner.apply(choice.command) root.append(button) } } runner.subscribe(render) render() ``` ```ts tab="React" tab-group="framework" // src/play.ts import { mountGame } from '@ifloom/react' import '@ifloom/react/styles.min.css' import module from './game.ts' mountGame(module.build(), { root: '#game' }) ``` ```ts tab="Vue" tab-group="framework" // src/runner.ts import { shallowRef } from 'vue' import { browserRunner } from '@ifloom/browser' import module from './game.ts' const { game } = module.build() export const runner = await browserRunner(game) export const view = shallowRef(runner.view()) runner.subscribe((snapshot) => { view.value = snapshot.view }) ``` ```vue tab="Vue" tab-group="framework" ``` [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner) starts a new game with undo, saves in `localStorage` and an autosave each turn. The imports keep their `.ts` extensions, as the templates' do. Drop them if your TypeScript settings don't allow it. [Start your own UI](https://ifloom.dev/docs/how-to/render/start) renders the rest of the game with your own code. ## Add the scripts [#add-the-scripts] Add the CLI's commands to `package.json`: ```json { "scripts": { "check": "ifloom check", "playtest": "ifloom playtest --turns 5 --out playtest/run.txt", "typecheck": "tsc --noEmit" } } ``` A project that builds with Vite can also use `ifloom dev` and `ifloom build`, with the [Vite preset](https://ifloom.dev/docs/reference/cli#the-vite-preset) in its `vite.config.ts`. A project that builds with something else keeps its own build. See [Build with Next.js](https://ifloom.dev/docs/how-to/build-with-next), [Build with webpack](https://ifloom.dev/docs/how-to/build-with-webpack) and [Build with esbuild](https://ifloom.dev/docs/how-to/build-with-esbuild). ## Check it worked [#check-it-worked] Run the checks from the project's folder: ```sh tab="npm" tab-group="package-manager" npm run check npm run typecheck ``` ```sh tab="pnpm" tab-group="package-manager" pnpm check pnpm typecheck ``` ```sh tab="yarn" tab-group="package-manager" yarn run check yarn run typecheck ``` ```sh tab="bun" tab-group="package-manager" bun run check bun run typecheck ``` `check` loads `src/game.ts` and prints `No problems.` when the game loads cleanly. Otherwise it lists each problem with the scene or key it's about. Then open the page: it shows "The door" and its words. For more, see: - [The CLI](https://ifloom.dev/docs/reference/cli), for the game module and every command. - [The runner](https://ifloom.dev/docs/reference/runner) and [the view](https://ifloom.dev/docs/reference/view), for what the page reads. - [How the pieces fit](https://ifloom.dev/docs/explanation/architecture), for the packages a game needs. # Arrange the layout (https://ifloom.dev/docs/how-to/arrange-the-layout) Use this to change how the page is laid out around the story. The layout is one file: in the React UI, `src/layout.tsx`, a component made of regions (`Game`, `Sidebar`, `Story`, `Overlay`) with the parts inside them, passed to `mountGame` as `layout`. The vanilla and vue templates have the same regions in `src/layout.ts` and `src/Layout.vue`. [`DefaultLayout`](https://ifloom.dev/docs/reference/react/components#defaultlayout) is the whole default layout. ## Fold a section [#fold-a-section] Wrap the parts in a [`Section`](https://ifloom.dev/docs/reference/react/components#section) with `collapsible`. The profile keeps the player's choice per `id`, so a folded section stays folded next time. With a UI of your own, use a `
`, which folds with no code: ```ts fragment tab="Plain JS" tab-group="framework" // src/main.ts, with section() from the vanilla template's src/layout.ts import { layout, section } from './layout.ts' function draw(view: View): void { const { sidebar } = layout(root) const stats = add(section(sidebar, 'stats', 'Stats'), 'dl', '', 'stats') for (const stat of view.stats) { add(stats, 'dt', stat.label) add(stats, 'dd', stat.text) } // …the story, as before } ``` ```tsx tab="React" tab-group="framework" // src/layout.tsx import { Game, Scene, Section, Sidebar, StatList, Story, Title } from '@ifloom/react' import { InventoryCard } from '@ifloom/plugin-inventory/react' export function Layout() { return ( <Section id="stats" title="Stats" collapsible open> <StatList /> </Section> {/* Folded until the player opens it. */} <Section id="inventory" title="In your bag" collapsible open={false}> <InventoryCard title={false} /> </Section> </Sidebar> <Story> <Scene /> </Story> </Game> ) } ``` ```vue tab="Vue" tab-group="framework" <!-- src/Layout.vue --> <script setup lang="ts"> import { view } from './runner.ts' </script> <template> <aside class="sidebar"> <details v-if="view.stats.length" class="section" open> <summary>Stats</summary> <dl class="stats"> <template v-for="stat in view.stats" :key="stat.key"> <dt>{{ stat.label }}</dt> <dd>{{ stat.text }}</dd> </template> </dl> </details> </aside> </template> ``` A `Section` hides itself when nothing in it renders anything, so a Quests section in a game without the quests plugin takes no space. The cards inside have titles of their own, so pass them `title={false}`. ## Open a section in a dialog [#open-a-section-in-a-dialog] Give the `Section` `dialog` instead of `collapsible` for something the player looks at now and then, such as the quest log or the people they've met. It becomes a button that opens its children in a dialog, and `badge` puts a count on the button: ```ts fragment tab="Plain JS" tab-group="framework" // A button that opens a <dialog> with the quests' names. const quests = view.plugins.quests if (quests) { const dialog = add(sidebar, 'dialog') for (const quest of quests.active) add(dialog, 'p', quest.name) add(dialog, 'button', 'Close').onclick = () => dialog.close() add(sidebar, 'button', quests.updates ? `Quests (${quests.updates})` : 'Quests').onclick = () => dialog.showModal() } ``` ```tsx tab="React" tab-group="framework" import { Section } from '@ifloom/react' import { QuestLog, useQuests } from '@ifloom/plugin-quests/react' import { Relationships } from '@ifloom/plugin-cast/react' function JournalSections() { const news = useQuests()?.updates return ( <> <Section id="quests" title="Quests" dialog badge={news || null}> <QuestLog title={false} /> </Section> <Section id="people" title="People" dialog> <Relationships /> </Section> </> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed, ref } from 'vue' import { view } from './runner.ts' const quests = computed(() => view.value.plugins.quests) const dialog = ref<HTMLDialogElement | null>(null) </script> <template> <template v-if="quests"> <button @click="dialog?.showModal()">Quests<template v-if="quests.updates"> ({{ quests.updates }})</template></button> <dialog ref="dialog"> <p v-for="quest in quests.active" :key="quest.id">{{ quest.name }}</p> <button @click="dialog?.close()">Close</button> </dialog> </template> </template> ``` A dialog opened from the side column stays open while the player acts inside it. ## Show a part only at some locations [#show-a-part-only-at-some-locations] Give a `Section` a `when`, any [condition](https://ifloom.dev/docs/reference/conditions) content could write, such as a wardrobe shown only at home. [`When`](https://ifloom.dev/docs/reference/react/components#when) does the same for anything else, and [`useHolds`](https://ifloom.dev/docs/reference/react/components#useholds) answers in a hook. They read the state and change nothing, so saves and replays aren't affected. With a UI of your own, ask the engine's [`holds`](https://ifloom.dev/docs/reference/conditions#holds) as you render: ```ts fragment tab="Plain JS" tab-group="framework" import { holds } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' // In draw(), after the stats: if (holds(runner.state, runner.game, places.at('flat'))) { const worn = section(sidebar, 'wardrobe', 'Wearing') // …what the player has on, from view.plugins.wardrobe } ``` ```tsx tab="React" tab-group="framework" import { Section, When } from '@ifloom/react' import { WardrobeCard } from '@ifloom/plugin-wardrobe/react' import { places } from '@ifloom/plugin-places' export function AtHome() { return ( <> <Section id="wardrobe" title="Wearing" collapsible when={places.at('flat')}> <WardrobeCard title={false} /> </Section> <When condition={{ kv: 'raining' }}> <p>Rain runs down the window.</p> </When> </> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { holds } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' import { runner, view } from './runner.ts' // Read `view` so it's worked out again whenever the state changes. const atHome = computed(() => view.value && holds(runner.state, runner.game, places.at('flat'))) </script> <template> <details v-if="atHome" class="section" open> <summary>Wearing</summary> <!-- …what the player has on, from view.plugins.wardrobe --> </details> </template> ``` To decide in plain code instead, read a plugin's view. This lists the exits only outdoors, from the [places](https://ifloom.dev/docs/reference/plugins/places) plugin's view, read in React with [`usePlaces`](https://ifloom.dev/docs/reference/plugins/places#useplaces): ```ts fragment tab="Plain JS" tab-group="framework" const places = view.plugins.places if (places?.location?.tags.includes('outdoors')) { const list = add(story, 'ul') for (const exit of places.exits) add(add(list, 'li'), 'button', exit.label).onclick = () => runner.apply(exit.command) } ``` ```tsx tab="React" tab-group="framework" import { usePlaces } from '@ifloom/plugin-places/react' function StreetMap() { const places = usePlaces() if (!places?.location?.tags.includes('outdoors')) return null return ( <ul> {places.exits.map((exit) => ( <li key={exit.id}> <button onClick={() => places.go(exit.id)}>{exit.label}</button> </li> ))} </ul> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { runner, view } from './runner.ts' const places = computed(() => view.value.plugins.places) </script> <template> <ul v-if="places?.location?.tags.includes('outdoors')"> <li v-for="exit in places.exits" :key="exit.id"> <button @click="runner.apply(exit.command)">{{ exit.label }}</button> </li> </ul> </template> ``` ## Open a panel from the story [#open-a-panel-from-the-story] For something that shouldn't be on screen until the story asks, such as the wardrobe when the player opens the wardrobe door, put the [`panel` effect](https://ifloom.dev/docs/reference/effects#panel) on an action: ```ts import { places } from '@ifloom/plugin-places' const flat = places.location({ id: 'flat', name: 'Your flat', description: 'Home', exits: ['high-street'], body: [{ prose: 'place.flat' }], actions: [{ id: 'wardrobe', label: 'Open the wardrobe', effects: [{ panel: 'wardrobe' }] }], }) ``` The React UI's [`PanelHost`](https://ifloom.dev/docs/reference/react/components#panelhost) renders the built-in panels by name, so keep one in your layout. [Open a shop, a job board or another panel](https://ifloom.dev/docs/how-to/open-a-panel) shows the effect in every kind of content, and [Render a panel](https://ifloom.dev/docs/how-to/render/timers-minigames-panels#render-a-panel) renders `view.panel` in a UI of your own. ## Place the story's text [#place-the-storys-text] The React UI keeps the scene's title, its words, the choices, the inputs, the exits and the people here to a reading column `--width-prose` wide, centred in the story. Pictures, a location's layered picture and panels still use the whole width. To keep the column to the start of the story instead, give [`Story`](https://ifloom.dev/docs/reference/react/components#story) `align="start"`. The vanilla and vue templates keep their text to the start already, and a few lines in `src/styles.css` centre it: ```css tab="Plain JS" tab-group="framework" /* src/styles.css: the story's text in a column in the middle, as the React UI renders it */ .story > h2, .prose, .inputs, .choices { width: 100%; max-width: 70ch; margin-inline: auto; } ``` ```tsx tab="React" tab-group="framework" // src/layout.tsx import { Game, Scene, Story } from '@ifloom/react' export function Layout() { return ( <Game> {/* Centred when align is left out. */} <Story align="start"> <Scene /> </Story> </Game> ) } ``` ```css tab="Vue" tab-group="framework" /* src/styles.css: the story's text in a column in the middle, as the React UI renders it */ .story > h2, .prose, .inputs, .choices { width: 100%; max-width: 70ch; margin-inline: auto; } ``` In the React UI you can also leave the layout alone and set the `--margin-prose` token, the column's `margin-inline`, in a preset or your stylesheet. `auto` centres the column and `0 auto` keeps it to the start. An `align` on `Story` wins over the token: ```css :root { --margin-prose: 0 auto; } ``` ## Style the side column on a phone [#style-the-side-column-on-a-phone] The React UI's `Sidebar` becomes a drawer below 48rem, Tailwind's `md`, with no work from you. A slim top bar holds the title, the clock and a menu button, and the button slides the side column in over the story. Focus stays in it, Escape closes it, and it closes once the player chooses something. Style it with its parts: ```css [data-part="top-bar"] { background: var(--card); } [data-part="drawer"] { width: 20rem; } [data-part="drawer-button"] { border-radius: 999px; } ``` The vanilla and vue templates stack the side column above the story on a phone, with a media query in `src/styles.css`. A section that folds keeps that short. ## Check it worked [#check-it-worked] Play in `npm run dev`. Fold the Stats section and reload: it stays folded. Go home to the flat, and the Wearing section shows. Narrow the window below 48rem, and the side column moves into the drawer behind the menu button. For more, see: - [Layouts](https://ifloom.dev/docs/reference/react/components#layouts), with `Game`, `Sidebar`, `Story`, `Overlay`, `Section` and `When`. - [Parts](https://ifloom.dev/docs/reference/react/parts), for every `data-part` to style. - [Rearrange or replace the React UI's parts](https://ifloom.dev/docs/how-to/react/replace-parts), for a layout of a different shape. - [Build a HUD](https://ifloom.dev/docs/how-to/build-a-hud), for pieces of your own to place in it. # Ask the player for a name (https://ifloom.dev/docs/how-to/ask-for-a-name) Use this when the story needs the player's name, or any other word or number they type, such as a pet's name or the hour they wake. An [input](https://ifloom.dev/docs/reference/inputs) writes what the player enters to a key in the [kv store](https://ifloom.dev/docs/reference/glossary#kv), the game's store of named values. The steps use The Letter, the novel example, whose first page asks for a name. ## Declare the input [#declare-the-input] Add an entry to `inputs` in your content. The input writes to the kv key of its `id`, here `playerName`, unless `key` names another: ```ts import type { Content } from '@ifloom/engine' export const ch1: Content = { inputs: [{ id: 'playerName', label: 'Your name', type: 'text', maxLength: 20, when: { not: { kv: 'playerName' } } }], } ``` `when` keeps the field on screen only until the player has given a name. A `text` input takes 40 characters unless `maxLength` says otherwise, and the engine trims spaces from both ends before it writes the value. ## Hold the story until it's given [#hold-the-story-until-its-given] Give the scene's choices `when: { kv: 'playerName' }`, which holds once the key has a value. Until then the page shows the field and no choices: ```ts import type { DataScene } from '@ifloom/engine' export const mat: DataScene = { id: 'ch1.mat', title: 'Chapter one: the mat', body: [ { text: 'On the mat, under the takeaway menus, is a letter with a name on it that isn’t yours: J. Hart.' }, { text: 'You turn it over, {{playerName}}. The flap is barely stuck.', when: { kv: 'playerName' } }, ], choices: [{ id: 'open', label: 'Open it', when: { kv: 'playerName' }, effects: [{ scene: 'ch2.stairs' }] }], } ``` The token `{{playerName}}` prints the value of the key in any line. The second line has the same `when`, so nobody reads "You turn it over, ." before there's a name. Test the value elsewhere with the [`kv` condition](https://ifloom.dev/docs/reference/conditions#kv), such as `{ kv: 'playerName', is: 'Sam' }`. To stop the player saving a game with no name, add a `saveable` entry to your content: ```ts import type { Content } from '@ifloom/engine' export const noSaveYet: Content = { saveable: [{ when: { not: { kv: 'playerName' } }, reason: 'Type your name first.' }], } ``` ## Name the saves and the player's lines [#name-the-saves-and-the-players-lines] Give the game's [rules](https://ifloom.dev/docs/reference/glossary#rules) a `saveName` that returns the name. The save list shows it, and a spoken line written under `@you` or `@player` shows it as the speaker: ```ts // src/rules.ts import type { GameRules } from '@ifloom/engine' export const rules: GameRules = { saveName: (state) => (typeof state.kv.playerName === 'string' ? state.kv.playerName : undefined), } ``` Pass `rules` in the base of `loadGame` in `src/game.ts`. Without a `saveName`, the player's lines show `You`. ## Check it worked [#check-it-worked] Run `npm run dev`, type a name and press Enter. The field goes, the line with your name shows, and the choices appear. Type a name over 20 characters and the engine refuses it with `Keep it to 20 characters.`, which every UI shows by the field. [Inputs](https://ifloom.dev/docs/reference/inputs#strings) lists each refusal and its strings key. `ifloom playtest` never types, so a story that waits for a name stops there. Start the playtest past the field with the game module's `start`: ```ts import { loadGame, startingState, type Content } from '@ifloom/engine' import { defineGame } from '@ifloom/cli/game' declare const ch1: Content export default defineGame({ build: ({ unlocked }) => loadGame([ch1], { id: 'the-letter', title: 'The Letter' }, { packs: unlocked }), start: (game) => startingState(game, { kv: { playerName: 'Sam' } }), }) ``` ## Variations [#variations] **A number or a choice.** `type: 'number'` takes a number between `min` and `max`, such as `{ id: 'alarm', label: 'Wake at', type: 'number', min: 5, max: 10, key: 'wakeAt' }`. `type: 'choice'` offers `options`, each a `value` and a `label`, such as tea or coffee. **A field outside a scene.** An input whose `when` holds while no scene is open shows under the room. While a scene is open, the React UI shows it between the scene's words and its choices. In the showcase, Small Town, the cat's name is an input in [`examples/showcase/src/story/moving-day.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/moving-day.ts), and The Letter's is in [`examples/novel/src/story/ch1.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/novel/src/story/ch1.ts). For more, see: - [Inputs](https://ifloom.dev/docs/reference/inputs) and the [`input` command](https://ifloom.dev/docs/reference/commands#input). - [Tokens](https://ifloom.dev/docs/reference/prose#tokens), for printing a value in a line. - [Render inputs](https://ifloom.dev/docs/how-to/render/scene#render-inputs), for a UI of your own. - [Triggers, notices and inputs](https://ifloom.dev/docs/explanation/state-and-commands#triggers-notices-and-inputs). # Build a HUD (https://ifloom.dev/docs/how-to/build-a-hud) Use this when the React UI's stat list, notice strip and quest log are too plain for your game. Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. Each piece of a HUD reads the [view](https://ifloom.dev/docs/reference/view), which is the same whatever renders it, so each tab below reads the same fields. The examples use the showcase's stats and plugins. ## Add a stat bar [#add-a-stat-bar] Find the stat in `view.stats`, a list of [`StatView`](https://ifloom.dev/docs/api/engine#statview)s with each one's `value`, `min`, `max` and `text`. This bar takes the stat's id, so one piece renders a bar for any stat: ```ts tab="Plain JS" tab-group="framework" // src/hud.ts import type { View } from '@ifloom/engine' /** A bar for one of the game's stats, by its key: statBar(view, 'energy'). */ export function statBar(view: View, key: string): HTMLElement | null { const stat = view.stats.find((entry) => entry.key === key) if (!stat) return null const range = stat.max - stat.min const share = range > 0 ? (stat.value - stat.min) / range : 0 const meter = document.createElement('div') meter.className = 'meter' meter.setAttribute('role', 'meter') meter.setAttribute('aria-label', stat.label) meter.setAttribute('aria-valuemin', String(stat.min)) meter.setAttribute('aria-valuemax', String(stat.max)) meter.setAttribute('aria-valuenow', String(stat.value)) meter.setAttribute('aria-valuetext', stat.text) const fill = meter.appendChild(document.createElement('div')) fill.style.width = `${share * 100}%` fill.style.background = share < 0.25 ? 'crimson' : 'seagreen' return meter } ``` ```tsx tab="React" tab-group="framework" // src/hud/StatBar.tsx // Each piece reads the view with useGame, and goes in your layout beside the React UI's parts. import { useGame } from '@ifloom/react' /** A bar for one of the game's stats, by its key: <StatBar stat="energy" />. */ export function StatBar({ stat: key }: { stat: string }) { const { view } = useGame() const stat = view.stats.find((entry) => entry.key === key) if (!stat) return null const range = stat.max - stat.min const share = range > 0 ? (stat.value - stat.min) / range : 0 return ( <div role="meter" aria-label={stat.label} aria-valuemin={stat.min} aria-valuemax={stat.max} aria-valuenow={stat.value} aria-valuetext={stat.text} className="h-3 overflow-hidden rounded-full bg-muted" > <div className="h-full transition-[width]" style={{ width: `${share * 100}%`, background: share < 0.25 ? 'crimson' : 'seagreen' }} /> </div> ) } ``` ```vue tab="Vue" tab-group="framework" <!-- src/StatBar.vue --> <script setup lang="ts"> import { computed } from 'vue' import { view } from './runner.ts' // A bar for one of the game's stats, by its key: <StatBar stat="energy" />. const props = defineProps<{ stat: string }>() const stat = computed(() => view.value.stats.find((entry) => entry.key === props.stat)) const share = computed(() => (stat.value && stat.value.max > stat.value.min ? (stat.value.value - stat.value.min) / (stat.value.max - stat.value.min) : 0)) </script> <template> <div v-if="stat" role="meter" :aria-label="stat.label" :aria-valuemin="stat.min" :aria-valuemax="stat.max" :aria-valuenow="stat.value" :aria-valuetext="stat.text" class="meter" > <div :style="{ width: `${share * 100}%`, background: share < 0.25 ? 'crimson' : 'seagreen' }" /> </div> </template> ``` `max` is the stat's ceiling now, so a ceiling that grows during the game is already worked out. `role="meter"` and the values let a screen reader say how full it is. If a plain bar is all you need in the React UI, give the stat the hint [`ui: { display: 'bar' }`](https://ifloom.dev/docs/reference/react/hints#display) or `'pips'`, and the built-in [`StatList`](https://ifloom.dev/docs/reference/react/components#statlist) renders it. `StatList` is plain on purpose, so write your own, as above, for a bar that changes colour. To reword a levelled stat's "Level 2" or its bar's label, set `ui.statLevel` or `ui.statProgress` in your content's [`strings`](https://ifloom.dev/docs/reference/react#strings). ## Add a strip of unread counts [#add-a-strip-of-unread-counts] Read the unseen notices from `view.notices.unseen`, newest first, and a plugin's counts from its part of `view.plugins`. The [messages](https://ifloom.dev/docs/reference/plugins/messages) plugin keeps an `unread` count: ```ts tab="Plain JS" tab-group="framework" // src/hud.ts import type { View } from '@ifloom/engine' let showNotices = false /** The unread counts. The bell shows the notices; `redraw` renders the page again with the list open or shut. */ export function unread(view: View, redraw: () => void): HTMLElement { const strip = document.createElement('div') strip.className = 'unread' const notices = view.notices.unseen const texts = view.plugins.messages?.unread ?? 0 if (notices.length) { const bell = strip.appendChild(document.createElement('button')) bell.textContent = `🔔 ${notices.length}` bell.onclick = () => { showNotices = !showNotices redraw() } } if (texts) strip.appendChild(document.createElement('span')).textContent = `✉ ${texts}` if (showNotices) { const list = strip.appendChild(document.createElement('ul')) for (const notice of notices.slice(0, 10)) list.appendChild(document.createElement('li')).textContent = notice.title } return strip } ``` ```tsx tab="React" tab-group="framework" // src/hud/Unread.tsx import { useState } from 'react' import { Notices, useGame } from '@ifloom/react' import { DeviceDialog, useDevice } from '@ifloom/plugin-devices/react' export function Unread() { const { view } = useGame() const phone = useDevice() const [showNotices, setShowNotices] = useState(false) const notices = view.notices.unseen.length const texts = view.plugins.messages?.unread ?? 0 return ( <div className="flex gap-3 text-sm"> {notices ? <button onClick={() => setShowNotices(!showNotices)}>🔔 {notices}</button> : null} {texts ? <button onClick={() => phone.open('phone')}>✉ {texts}</button> : null} {showNotices ? <Notices limit={10} /> : null} {/* Renders the phone once it's open. Leave it out when `devicesUi` is in `plugins`. */} <DeviceDialog /> </div> ) } ``` ```vue tab="Vue" tab-group="framework" <!-- src/Unread.vue --> <script setup lang="ts"> import { computed, ref } from 'vue' import { view } from './runner.ts' const showNotices = ref(false) const notices = computed(() => view.value.notices.unseen) const texts = computed(() => view.value.plugins.messages?.unread ?? 0) </script> <template> <div class="unread"> <button v-if="notices.length" @click="showNotices = !showNotices">🔔 {{ notices.length }}</button> <span v-if="texts">✉ {{ texts }}</span> <ul v-if="showNotices"> <li v-for="notice in notices.slice(0, 10)" :key="notice.id">{{ notice.title }}</li> </ul> </div> </template> ``` A count of 0 renders nothing. The bell shows the newest notices, and sending `{ type: 'dismiss' }` with `runner.apply` marks them all seen (see [`dismiss`](https://ifloom.dev/docs/reference/commands#dismiss)). In the React tab, the texts button opens the phone with [`useDevice`](https://ifloom.dev/docs/reference/plugins/devices#usedevice) and a [`DeviceDialog`](https://ifloom.dev/docs/reference/plugins/devices#devicedialog), the pair the built-in device buttons use. In the other tabs it's a count, which you can turn into a button that opens your own messages panel. ## Add an objective line [#add-an-objective-line] Read the active quests from `view.plugins.quests.active`, which the [quests](https://ifloom.dev/docs/reference/plugins/quests) plugin lists with the tracked one first. Each has its `name` and the `hint` for the stage the player is on: ```ts tab="Plain JS" tab-group="framework" // src/hud.ts import type { View } from '@ifloom/engine' /** The tracked quest's name and hint, or null when none is tracked. */ export function objective(view: View): HTMLElement | null { const quest = view.plugins.quests?.active.find((entry) => entry.tracked) if (!quest) return null const line = document.createElement('p') line.className = 'objective' line.appendChild(document.createElement('strong')).textContent = quest.name if (quest.hint) line.append(` · ${quest.hint}`) return line } ``` ```tsx tab="React" tab-group="framework" // src/hud/Objective.tsx import { useGame } from '@ifloom/react' export function Objective() { const { view } = useGame() const quest = view.plugins.quests?.active.find((entry) => entry.tracked) if (!quest) return null return ( <p className="text-sm"> <strong>{quest.name}</strong> {quest.hint ? <span className="text-muted-foreground"> · {quest.hint}</span> : null} </p> ) } ``` ```vue tab="Vue" tab-group="framework" <!-- src/Objective.vue --> <script setup lang="ts"> import { computed } from 'vue' import { view } from './runner.ts' const quest = computed(() => view.value.plugins.quests?.active.find((entry) => entry.tracked)) </script> <template> <p v-if="quest" class="objective"> <strong>{{ quest.name }}</strong> <span v-if="quest.hint"> · {{ quest.hint }}</span> </p> </template> ``` The player chooses which quest to track, which sends the quests plugin's `quests/track` command. To show the newest quest when none is tracked, take `active[0]` instead. ## Put it on screen [#put-it-on-screen] Put the three pieces together in a bar over the scene: ```ts fragment tab="Plain JS" tab-group="framework" // src/main.ts, in the vanilla template import { objective, statBar, unread } from './hud.ts' function draw(view: View): void { root.replaceChildren() const hud = add(root, 'div', '', 'hud') hud.append(...[objective(view), unread(view, () => draw(runner.view())), statBar(view, 'energy')].filter((part) => part !== null)) // …then the title, the scene and its choices, as before. } ``` ```tsx tab="React" tab-group="framework" // src/hud/Hud.tsx import { StatBar } from './StatBar.tsx' import { Objective } from './Objective.tsx' import { Unread } from './Unread.tsx' export function Hud() { return ( <div className="flex flex-col gap-2 rounded-lg border p-3"> <div className="flex items-center justify-between gap-4"> <Objective /> <Unread /> </div> <StatBar stat="energy" /> </div> ) } ``` ```vue tab="Vue" tab-group="framework" <!-- src/App.vue, in the vue template --> <script setup lang="ts"> import StatBar from './StatBar.vue' import Objective from './Objective.vue' import Unread from './Unread.vue' </script> <template> <div class="hud"> <Objective /> <Unread /> <StatBar stat="energy" /> </div> <!-- …then the title, the scene and its choices, as before. --> </template> ``` In plain JS, the pieces render again with the rest of the page on every change. In Vue and React, each component renders again when the view changes. In the React UI, your components go anywhere in your [layout](https://ifloom.dev/docs/reference/react/components#defaultlayout) among the built-in parts, inside the game's provider. Put `<Hud />` at the top of the `Story` in the react template's `src/layout.tsx`, and delete its `StatList` from the side column: ```tsx fragment // src/layout.tsx: the react template's, with <Hud /> at the top of the story <Story> <Hud /> <Scene /> <RoomActions /> </Story> ``` For a bar fixed across the top of the window, see [Rearrange or replace the React UI's parts](https://ifloom.dev/docs/how-to/react/replace-parts). ## Check it worked [#check-it-worked] Play in `npm run dev` and work shifts at the café, which cost 25 energy each: the bar shrinks and turns red below a quarter. Meet Ava and sleep, and the strip shows ✉ 1 for her text. Start a quest and track it, and its name and hint show in the objective line. ## Variations [#variations] **What just changed.** Feedback after a choice, such as `+30 coins`, is already worked out in [`view.changes`](https://ifloom.dev/docs/reference/changes), for the stats your content names in `changes.stats`. The React UI's [`Changes`](https://ifloom.dev/docs/reference/react/components#changes) renders it, and the default layout leaves it out, so place it after the scene. [Render what changed](https://ifloom.dev/docs/how-to/render/stats-and-things#render-what-changed) has the same list in plain JS and Vue. For more, see: - [The view](https://ifloom.dev/docs/reference/view) and [`StatView`](https://ifloom.dev/docs/api/engine#statview). - [Render the stats](https://ifloom.dev/docs/how-to/render/stats-and-things#render-the-stats) and [Render notices](https://ifloom.dev/docs/how-to/render/stats-and-things#render-notices). - [Render the quest log](https://ifloom.dev/docs/how-to/render/progress-plugins#render-the-quest-log). - [Arrange the layout](https://ifloom.dev/docs/how-to/arrange-the-layout), for the rest of the page. # Build a minigame (https://ifloom.dev/docs/how-to/build-a-minigame) Use this for a small game inside the story, played with buttons or keys against the clock. A [minigame](https://ifloom.dev/docs/reference/minigames) is data, like a scene. It has states, the inputs each state listens for, timers that move it on, and a few numbers it keeps while it runs. The steps build quick feet from the showcase's park: an arrow appears, and the player has a second and a half to press it. Quick feet has five rounds. Each round picks one of four arrows at random. Pressing the right arrow scores a point, and a wrong one or running out of time scores none. After the fifth round, three or more points wins five coins. ## Write a state for each arrow [#write-a-state-for-each-arrow] Write one state per arrow. Each shows its words, waits 1.5 seconds, and listens for all four inputs: ```ts import type { MinigameStateDef } from '@ifloom/engine' export const ARROWS = ['up', 'down', 'left', 'right'] as const const POINTS: Record<(typeof ARROWS)[number], string> = { up: 'The girl with the whistle points at the sky. Up!', down: 'She points at her shoes. Down!', left: 'She points at the river. Left!', right: 'She points at the swings. Right!', } export const showArrow = (arrow: (typeof ARROWS)[number]): MinigameStateDef => ({ label: POINTS[arrow], after: { ms: 1500, go: 'round' }, on: ARROWS.map((input) => ({ input, go: 'round', ...(input === arrow ? { effects: [{ kv: 'score', of: 'minigame', by: 1 }] } : {}) })), }) ``` `label` is the words the player reads in that state. `after` goes to `round` once 1.5 seconds of ticks have passed. Each `on` entry is what an input does. All four go to `round`, and only the right one adds a point to the minigame's own [kv store](https://ifloom.dev/docs/reference/glossary#kv), `of: 'minigame'`. The input names are yours. Name them `up`, `down`, `left` and `right` where they fit, and the React UI gives them the arrow keys and labelled buttons without being told. ## Write the rounds [#write-the-rounds] Add the states that decide where to go next and show nothing: ```ts continues import type { MinigameDef } from '@ifloom/engine' export const quickFeet: MinigameDef = { id: 'arrows', title: 'Quick feet', start: 'round', kv: { round: 0, arrow: 0, score: 0 }, keys: { up: ['ArrowUp', 'w'], down: ['ArrowDown', 's'], left: ['ArrowLeft', 'a'], right: ['ArrowRight', 'd'] }, states: { round: { always: [ { when: { kv: 'round', of: 'minigame', gte: 5 }, go: 'tally' }, { go: 'pick', effects: [{ kv: 'round', of: 'minigame', by: 1 }, { kv: 'arrow', of: 'minigame', random: [1, 4] }] }, ], }, pick: { always: ARROWS.map((arrow, index) => ({ when: { kv: 'arrow', of: 'minigame', is: index + 1 }, go: arrow })) }, ...Object.fromEntries(ARROWS.map((arrow) => [arrow, showArrow(arrow)])), tally: { always: [{ when: { kv: 'score', of: 'minigame', gte: 3 }, go: 'won' }, { go: 'lost' }] }, won: { final: { effects: [{ stat: 'coins', by: 5 }, { scene: 'park.arrows-won' }] } }, lost: { final: { effects: [{ scene: 'park.arrows-lost' }] } }, }, } ``` Reading it from the top: - **`kv`** declares the minigame's own keys, which start at 0 and go when it ends. - **`keys`** adds W, A, S and D beside the arrow keys. - **`round`** has `always` entries, taken as soon as the state is entered. After five rounds it goes to `tally`. Otherwise it counts the round, draws an arrow from 1 to 4, and goes to `pick`. - **`pick`** turns the number into one of the arrow states. - **`tally`** checks the score and goes to `won` or `lost`. - **`won`** and **`lost`** are final, so entering one ends the minigame and runs its effects. The states and the ways between them, with the four arrows in one box: ```mermaid stateDiagram-v2 state "up, down, left or right" as arrow [*] --> round round --> pick: under 5 rounds,<br/>round + 1 and draw an arrow pick --> arrow: the arrow drawn arrow --> round: an input, or 1.5 s round --> tally: 5 rounds played tally --> won: score 3 or more tally --> lost: otherwise won --> [*]: 5 coins, park.arrows-won lost --> [*]: park.arrows-lost ``` The arrow is drawn from the save's seed, so the same save always gets the same arrows, and undo can't draw them again. ## Start it [#start-it] Add the minigame to your content's `minigames`, with the two scenes it ends in, and start it with the [`minigame` effect](https://ifloom.dev/docs/reference/effects#minigame). In the park, a location's action does it: ```ts continues import type { ActionDef, Content } from '@ifloom/engine' export const play: ActionDef = { id: 'arrows', label: 'Play quick feet with the kids', effects: [{ minigame: 'arrows' }] } export const park: Content = { minigames: [quickFeet], scenes: [ { id: 'park.arrows-won', title: 'Quick feet', body: [{ text: 'Five coins change hands from a jam jar.' }], choices: [{ id: 'leave', effects: [{ scene: null }] }] }, { id: 'park.arrows-lost', title: 'Quick feet', body: [{ text: '"Too slow!"' }], choices: [{ id: 'leave', effects: [{ scene: null }] }] }, ], } ``` A scene can also start one as it opens, with its `minigame` field, and a [flowing scene](https://ifloom.dev/docs/how-to/write-a-flowing-scene#play-a-minigame-or-open-a-panel-where-it-stands) can play one where it stands. ## Play it [#play-it] Every template renders a running minigame. The React UI's `Scene` renders a [`MinigameCard`](https://ifloom.dev/docs/reference/react/components#minigamecard) in place of the scene, with the title, the words, a bar for the 1.5 seconds and a button for each arrow. The arrow keys and W, A, S and D press them too. The `vanilla` and `vue` templates show the words, the timer and a button for each input, and [`startKeys`](https://ifloom.dev/docs/reference/browser#startkeys) maps the keys. The engine keeps no clock. The React UI, or [`startClock`](https://ifloom.dev/docs/reference/browser#startclock) in the other templates, sends a [`tick`](https://ifloom.dev/docs/reference/commands#tick) about ten times a second while a timer runs. While a minigame runs, the engine refuses every other command with `Finish this first.` To render quick feet your own way, see [Render a minigame](https://ifloom.dev/docs/how-to/render/timers-minigames-panels#render-a-minigame). With the React UI, give `mountGame`'s `panels` a component under the minigame's id, `{ arrows: QuickFeet }`, and it renders in place of the `MinigameCard`. ## Check it worked [#check-it-worked] Run `npm run check`, which reports a `go` to a state the minigame doesn't have, a minigame with no final state it can reach, and a key no minigame declares. A test plays the minigame with no browser and no waiting, since ticks are ordinary commands: ```ts given import { apply, view } from '@ifloom/engine' // `state` has the player in the park. let next = apply(state, game, { type: 'action', id: 'places/arrows' }).state const arrow = next.minigame!.state // 'left', say next = apply(next, game, { type: 'tick', ms: 400 }).state next = apply(next, game, { type: 'minigame', input: arrow }).state view(next, game).minigame?.kv.score // 1 ``` One long tick runs out every timer in its way, so `{ type: 'tick', ms: 10_000 }` plays out all five rounds with no presses. ## Variations [#variations] **A quiz with its answers on the buttons.** Give each `on` entry a `label`, the words on that input's button while the minigame is in that state. One set of inputs, `a`, `b` and `c`, then shows different answers for each question: ```ts import type { MinigameDef } from '@ifloom/engine' export const quiz: MinigameDef = { id: 'quiz', title: 'Pub quiz', start: 'q1', kv: { right: 0 }, states: { q1: { label: 'Which street is the café on?', on: [ { input: 'a', label: 'High Street', go: 'done', effects: [{ kv: 'right', of: 'minigame', by: 1 }] }, { input: 'b', label: 'Mill Lane', go: 'done' }, { input: 'c', label: 'Station Road', go: 'done' }, ], }, done: { final: { copy: { right: 'quiz.right' } } }, }, } ``` The final state copies the score to the kv key `quiz.right`, so `{{quiz.right}}` prints it after the minigame ends. In the showcase, Small Town, quick feet is in [`examples/showcase/src/story/park.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/park.ts). Its `tests/showcase.test.ts` plays it with ticks, and `tests/quick-feet.test.tsx` plays it in the React UI with the arrow keys. For more, see: - [Minigames](https://ifloom.dev/docs/reference/minigames), with every field of `MinigameDef` and its states. - The [`minigame` effect](https://ifloom.dev/docs/reference/effects#minigame) and the [`minigame` and `tick` commands](https://ifloom.dev/docs/reference/minigames#commands). - [Timers run in real time, not turns](https://ifloom.dev/docs/explanation/turns-and-time#timers-run-in-real-time-not-turns). # Build a phone (https://ifloom.dev/docs/how-to/build-a-phone) Use this to give the player a phone with texts, a social feed, contacts, a gallery and apps of your own. A phone is three plugins put together by your content: [devices](https://ifloom.dev/docs/reference/plugins/devices) shows a device with apps, [messages](https://ifloom.dev/docs/reference/plugins/messages) keeps the texts and [feed](https://ifloom.dev/docs/reference/plugins/feed) keeps the posts. None of them knows about the others. Contacts come from the [cast](https://ifloom.dev/docs/reference/plugins/cast). In the showcase, Small Town, the whole phone is in [`examples/showcase/src/world/phone.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/world/phone.ts). ## Add the plugins [#add-the-plugins] Install `@ifloom/plugin-devices`, `@ifloom/plugin-messages` and `@ifloom/plugin-feed` as [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin#install-the-package) shows, then list them in the game's `plugins`. Put the calendar first, so the phone's plugins see a new day when one begins: ```ts import { loadGame } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' import { cast } from '@ifloom/plugin-cast' import { devices } from '@ifloom/plugin-devices' import { messages } from '@ifloom/plugin-messages' import { feed } from '@ifloom/plugin-feed' import { phone } from './world/phone.ts' import { town } from './world/town.ts' export const { game } = loadGame([phone, ...town], { id: 'small-town', title: 'Small Town', plugins: [calendar(), places({ start: 'flat' }), cast(), devices(), messages(), feed()], }) ``` None of the three takes options. Everything about the phone is content in `data`. ## Put the phone in your content [#put-the-phone-in-your-content] Write the phone as one `Content` of its own, first in your content list, so its apps come first on the home screen. Declare the device, the channel for texts and the feed: ```ts import type { AppDef, DeviceDef } from '@ifloom/plugin-devices' import type { Channel } from '@ifloom/plugin-messages' import type { FeedDef } from '@ifloom/plugin-feed' const device: DeviceDef = { id: 'phone', name: 'Phone', frame: 'phone', sidebar: true } const channels: Channel[] = [{ id: 'texts', name: 'Messages' }] const feeds: FeedDef[] = [{ id: 'social', name: 'Social' }] ``` `frame: 'phone'` asks a UI to render it as a phone, and `sidebar: true` offers it from the side column. Give it a `wallpaper` for a picture behind the home screen. Add an app for each channel and each feed. Its badge counts what's unread, and its one section names the plugin whose view it shows: ```ts continues const apps: AppDef[] = [ ...channels.map((channel): AppDef => ({ id: channel.id, name: channel.name, icon: 'messages', on: 'phone', badge: { value: 'messages/unread', with: { channel: channel.id } }, sections: [{ plugin: 'messages', with: { channel: channel.id } }], })), ...feeds.map((entry): AppDef => ({ id: entry.id, name: entry.name, icon: 'feed', on: 'phone', badge: { value: 'feed/unread', with: { feed: entry.id } }, sections: [{ plugin: 'feed', with: { feed: entry.id } }], })), { id: 'contacts', name: 'Contacts', icon: 'contacts', on: 'phone', sections: [{ contacts: true }] }, { id: 'gallery', name: 'Gallery', icon: 'gallery', on: 'phone', sections: [{ things: { of: 'photo' } }] }, ] ``` Contacts lists the cast's people the player has met who have a `call`, each with a Call button. The Gallery lists the `photo` things `'you'` hold, newest first. Then put it all in the content, with the `photo` kind the Gallery lists: ```ts continues import type { Content } from '@ifloom/engine' export const phone: Content = { name: 'phone', kinds: [{ id: 'photo', label: 'Photo', plural: 'Photos', listed: false }], data: { devices: { devices: [device], apps }, messages: { channels }, feed: { feeds }, }, } ``` `listed: false` keeps photos off the town's lists, so only the Gallery shows them. The phone's own badge is every app's count added up. Channels, feeds and apps share one list of ids, so give each its own: a channel and a feed both called `news` would replace one another. ## Send a text with replies [#send-a-text-with-replies] Write each text in `data.messages.messages` with its `channel`, wherever the story needs it. This one is Ava's, the day after the player meets her, with two replies: ```ts import type { MessageDef } from '@ifloom/plugin-messages' import { cast } from '@ifloom/plugin-cast' export const avaText: MessageDef = { id: 'ava.text', channel: 'texts', from: 'ava', when: { all: [{ seen: 'ava.hi' }, { since: 'ava.hi', gte: 1 }] }, body: [{ text: 'Good to meet you yesterday! Coffee’s on me next time 🙂' }], replies: [ { id: 'yes', label: 'Deal!', effects: [{ stat: 'friendship', by: 5, of: cast.character('ava') }] }, { id: 'later', label: 'Maybe later in the week' }, ], } ``` A `from` that names an entity shows its name and picture. The text arrives at the end of the first command after its `when` holds, never on a new game's first screen. The player sends one reply, once, and the others go. To follow up on the reply, give the next text `when: messages.replied('ava.text', 'yes')`. ## Send texts one at a time [#send-texts-one-at-a-time] Give each text after the first an `after` with how long it takes, and a `when` that waits on the one before. The thread shows the sender typing in between: ```ts import { messages, type MessageDef } from '@ifloom/plugin-messages' export const burst: MessageDef[] = [ { id: 'sam.up', channel: 'texts', from: 'sam', when: { kv: 'phase', is: ['evening'] }, body: [{ text: 'Are you up?' }] }, { id: 'sam.radiator', channel: 'texts', from: 'sam', when: messages.arrived('sam.up'), after: { ms: 1500 }, body: [{ text: 'The radiator is knocking again.' }] }, { id: 'sam.never', channel: 'texts', from: 'sam', when: messages.arrived('sam.radiator'), after: { ms: 2500 }, body: [{ text: 'Never mind, it stopped.' }] }, ] ``` The waits run on the engine's [timers](https://ifloom.dev/docs/reference/timers), so a UI's clock has to send `tick` commands. The React UI and [`startClock`](https://ifloom.dev/docs/reference/browser#startclock) do. Each arrival raises a notice, and a newer one in the same thread replaces it while it's unseen, so the player sees one notice with the latest line. Give `typing: false` to a text that shouldn't show anyone typing, such as a delivery update. ## Send a text that comes again [#send-a-text-that-comes-again] Put the texts in a pool with `drawnFrom`, and draw from the pool with `messages.draw`. A [trigger](https://ifloom.dev/docs/reference/triggers) with `once: { per: 'turn' }` draws once a turn: ```ts import type { TriggerDef } from '@ifloom/engine' import { messages, type MessageDef } from '@ifloom/plugin-messages' export const smallTalk: MessageDef[] = ['rain', 'beans', 'river'].map((topic) => ({ id: `ava.chat.${topic}`, channel: 'texts', from: 'ava', drawnFrom: ['ava.chat'], // Not the same line twice within three days. when: { not: messages.since(`ava.chat.${topic}`, { lt: 3 }) }, body: [{ prose: `ava.chat.${topic}` }], })) export const chat: TriggerDef = { id: 'ava.chat', once: { per: 'turn' }, when: messages.replied('ava.text'), effects: [messages.draw('ava.chat')] } ``` Each draw delivers one text whose `when` holds as a new arrival, with its own replies and read mark. The draw is seeded by the save, so a replay or an undo draws the same text. ## Post to the feed [#post-to-the-feed] Write the town's posts in `data.feed.posts` with their `feed`, and a `when` for when each appears: ```ts import type { PostDef } from '@ifloom/plugin-feed' import { calendar } from '@ifloom/plugin-calendar' export const cake: PostDef = { id: 'ava.cake', feed: 'social', from: 'ava', when: calendar.day({ gte: 1 }), body: [{ text: 'Lemon drizzle today. It will not last until noon.' }], likes: 14, } ``` To let the player post, put `feed.post` in an action's effects, and react to it with `feed.react`. This park action passes a period, posts a photo of the river and rolls its likes in a [macro](https://ifloom.dev/docs/reference/glossary#macro) of the game's own: ```ts import type { GameRules } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' import { feed } from '@ifloom/plugin-feed' import { places } from '@ifloom/plugin-places' export const park = places.location({ id: 'park', name: 'Riverside Park', exits: ['high-street'], body: [{ text: 'The river is slow and brown.' }], actions: [{ id: 'photoRiver', label: 'Photograph the river', effects: [calendar.pass(1), feed.post('social', 'river', { text: 'The river at dusk.', image: 'photo/river.svg' }), { 'game/howItDid': true }] }], }) export const rules: GameRules = { macros: { howItDid: (_state, _args, { roll }) => [feed.react('river', { likes: 3 + roll(10, 'river.likes'), from: 'ava', text: 'Lovely!' })], }, } ``` The player's own posts are never unread, and `feed.posted()` holds once they've made one. The showcase's Camera app posts the newest photo with its `game/postLatest` macro in `examples/showcase/src/rules.ts`. ## Take photos for the gallery [#take-photos-for-the-gallery] Make a photo in play with the [`create`](https://ifloom.dev/docs/reference/effects#create) effect and give it to the player. The showcase's Camera app does it from a button that's refused while Ava isn't here: ```ts import type { AppDef } from '@ifloom/plugin-devices' import { cast } from '@ifloom/plugin-cast' export const camera: AppDef = { id: 'camera', name: 'Camera', icon: 'camera', on: 'phone', sections: [ { actions: [ { id: 'photo-ava', label: 'Photograph Ava', blocked: [{ when: { not: cast.here('ava') }, reason: 'She isn’t here.' }], effects: [{ create: 'photo', with: { id: 'ava', name: 'Ava at work', image: 'photo/ava.svg' }, effects: [{ receive: '$', to: 'player' }] }], }, ], }, ], } ``` Add it to the end of `apps`. Opening an app is free and doesn't move the player, so the camera at the café photographs whoever is at the café. An app's button is done as `{ type: 'action', id: 'devices/photo-ava' }`, so give each an id no other app's button has. The [inventory plugin](https://ifloom.dev/docs/reference/plugins/inventory) lists photos too, unless its `data.inventory.kinds` leaves `photo` out. ## Add an app of your own [#add-an-app-of-your-own] Build any app from the same [sections](https://ifloom.dev/docs/reference/plugins/devices#section): `blocks` for words, `actions` for buttons, `things` for a list of what the player holds, and `panel` for a panel of your game's. Refuse an app with `blocked`, keep it off the home screen until its `when` holds, and give it a dot with a badge's `when`: ```ts import type { AppDef } from '@ifloom/plugin-devices' export const bank: AppDef = { id: 'bank', name: 'Bank', icon: 'bank', on: 'phone', blocked: [{ when: { not: { kv: 'bankAccount' } }, reason: 'You have no account yet.' }], sections: [{ blocks: [{ text: 'Your account is in good order.' }] }], } export const mail: AppDef = { id: 'mail', name: 'Mail', icon: 'mail', on: 'phone', when: { kv: 'emailSetUp' }, badge: { when: { kv: 'newMail' } }, sections: [{ panel: 'inbox', with: { unread: 1 } }], } ``` A button in an `actions` section takes a `when` too, so a café app's Order a scarf button can hide once the player has one: `when: { not: { owned: 'clothing:scarf' } }`. ## Shut the phone in some places [#shut-the-phone-in-some-places] Add a [lock](https://ifloom.dev/docs/reference/locks) on `devices/*`. Every app greys out with the lock's reason, and an app left open closes: ```ts import type { Content } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' export const office: Content = { locks: [{ id: 'no-phone', when: places.at('office'), deny: ['devices/*'], reason: 'Not at work.' }], } ``` A lock on `'*'`, such as one that holds through an intro, shuts the phone too, unless its `except` lists `devices/open`. To shut a single app, give it a `blocked` entry. ## Show it on screen [#show-it-on-screen] With the React UI, list `devicesUi`, `messagesUi` and `feedUi` from the three packages' `/react` subpaths in `mountGame`'s `plugins`. `devicesUi` puts a button for the phone in the side column and opens it in a dialog. The texts and the feed inside its apps are rendered by `messagesUi` and `feedUi`, so leave one out and its app opens empty. See [Show it on screen](https://ifloom.dev/docs/how-to/add-a-plugin#show-it-on-screen). With a UI of your own, render `view.plugins.devices`, and a `plugin` section from `view.plugins.messages` or `view.plugins.feed`, as [Render messages, the feed and devices](https://ifloom.dev/docs/how-to/render/phone-plugins#render-a-device-and-its-apps) shows. ## Check it worked [#check-it-worked] Run `npm run check`. It reports what a phone names that the game lacks, such as a badge or a section left behind after you drop the feed plugin, or a Gallery with no `photo` kind. The `name: 'phone'` on the content pins each problem on it: ```text phone · apps social · no plugin value named "feed/unread"; the game has no plugin "feed" phone · apps gallery · unknown kind "photo" ``` Then play in `npm run dev`. Meet Ava, sleep, and open the phone: the Messages app has a badge of 1, and its thread has Deal! and Maybe later in the week. ## Variations [#variations] **Letters on the mat.** A channel doesn't need a device. Add a `letters` channel with no app, and give the flat an action that reads it, `{ id: 'mat', label: 'Pick up the post', command: messages.read({ channel: 'letters' }) }`. Render `view.plugins.messages` wherever the letters should show. **A notice board.** A feed doesn't need one either. Declare a `board` feed in the high street's content, outside the phone's `feeds`, and give the high street an action `{ id: 'board', label: 'Read the notice board', command: feed.seen('board') }`. **An app from a mod.** Apps are merged by id, as scenes are, so a [mod](https://ifloom.dev/docs/reference/mods) adds an app with a new id in `data.devices.apps` and replaces one by using its id. It can add a channel or a feed the same way, in `data.messages.channels` or `data.feed.feeds`. **No feed, gallery or contacts.** Drop the plugin, its apps and its `data` together. In a game without the cast, Contacts is always empty, so drop it there. A device of your own apps, such as a laptop, needs only the devices plugin. For more, see: - [Devices](https://ifloom.dev/docs/reference/plugins/devices), with [`AppDef`](https://ifloom.dev/docs/reference/plugins/devices#appdef) and [`Section`](https://ifloom.dev/docs/reference/plugins/devices#section). - [Messages](https://ifloom.dev/docs/reference/plugins/messages), with [`MessageDef`](https://ifloom.dev/docs/reference/plugins/messages#messagedef) and its [caveats](https://ifloom.dev/docs/reference/plugins/messages#caveats). - [Feed](https://ifloom.dev/docs/reference/plugins/feed), with [`PostDef`](https://ifloom.dev/docs/reference/plugins/feed#postdef). - [How plugins work together](https://ifloom.dev/docs/explanation/plugins). # Build a friendship in stages (https://ifloom.dev/docs/how-to/build-friendships-in-stages) Use this when a friendship or a rivalry should grow over days, not in one afternoon. The player meets someone, gets to know them, and some days later something happens that couldn't have happened on the first visit. The steps use Ava, who runs the café in the showcase. Her storyline is `ava`, and the friendship is a stat on her, `friendship`, declared on the kind `character` (see [Add a character with a schedule](https://ifloom.dev/docs/how-to/add-a-character)). ## Pay once a turn [#pay-once-a-turn] Talking costs no time, so a choice that pays and can be chosen again is an endless farm. Give it [`once`](https://ifloom.dev/docs/reference/actions#once), and it pays once a [turn](https://ifloom.dev/docs/reference/glossary#turn), which is once a day with the [calendar](https://ifloom.dev/docs/reference/plugins/calendar)'s default: ```ts import type { Choice } from '@ifloom/engine' import { cast } from '@ifloom/plugin-cast' export const chat: Choice = { id: 'chat', label: 'Chat', once: { per: 'turn', reason: 'She has a queue.' }, effects: [{ stat: 'friendship', by: 5, of: cast.character('ava') }] } ``` After the player chooses it, the choice stays on screen with its reason and pays nothing until the next turn. An [action](https://ifloom.dev/docs/reference/actions#actiondef) takes the same `once`. ## Count visits [#count-visits] Keep a counter in the storyline's own [kv store](https://ifloom.dev/docs/reference/glossary#kv). Add to it with the [`kv` effect](https://ifloom.dev/docs/reference/effects#kv) and read it with the [`kv` condition](https://ifloom.dev/docs/reference/conditions#kv), both with the storyline in `of`: ```ts import type { Condition, Effect } from '@ifloom/engine' // In the choice that opens her scene. export const visit: Effect[] = [{ kv: 'visits', of: 'storyline:ava', by: 1 }, { scene: 'ava.hi' }] // Anywhere a condition goes: she knows your order. export const regular: Condition = { kv: 'visits', of: 'storyline:ava', gte: 10 } ``` The effect reads the count when it runs, so two of them in one list add up. To count how often a scene was opened, you need no counter: `{ seen: 'ava.hi', gte: 3 }` holds from the third visit (see [`seen`](https://ifloom.dev/docs/reference/conditions#seen)). ## Write a ladder of greetings [#write-a-ladder-of-greetings] Write a line for each stretch of the count, each a block with a `when`, so exactly one shows: ```ts import type { Block } from '@ifloom/engine' export const greeting: Block[] = [ { text: 'Ava nods at you from the till.', when: { seen: 'ava.hi', lt: 2 } }, { text: '"Hello again," says Ava.', when: { seen: 'ava.hi', gte: 2, lt: 5 } }, { text: '"The usual?" Ava is already reaching for a cup.', when: { seen: 'ava.hi', gte: 5, lt: 10 } }, { text: 'Ava waves you round the counter to sit with her.', when: { seen: 'ava.hi', gte: 10 } }, ] ``` Every [range](https://ifloom.dev/docs/reference/common#range) takes `gte`, `gt`, `lte` and `lt` together, so the rungs don't overlap. The top rung has no `lt`, so the ladder stops there. Put the blocks in her scene's `body`. ## Put stages in order, with days between [#put-stages-in-order-with-days-between] The [quests plugin](https://ifloom.dev/docs/reference/plugins/quests) keeps stages in order. A stage is done the first time its `done` holds once the stages before it are done, and it's never taken back. Pace a stage with [`since`](https://ifloom.dev/docs/reference/conditions#since), the whole turns since a scene was first seen, so a high stat alone can't rush it: ```ts import { cast } from '@ifloom/plugin-cast' import { quests, type QuestDef } from '@ifloom/plugin-quests' export const friend: QuestDef = { id: 'friend', name: 'A friend in town', storyline: 'ava', starts: quests.active('settle'), stages: [ { id: 'close', hint: 'Spend time with Ava.', done: { stat: 'friendship', of: cast.character('ava'), gte: 25 } }, // Three days since you met, however often you chat. { id: 'river', hint: 'Find Ava by the river some evening.', done: { all: [{ since: 'ava.hi', gte: 3 }, { seen: 'ava.river' }] } }, ], } ``` Then open the next scene only once the stage before it is done, with [`quests.reached`](https://ifloom.dev/docs/reference/plugins/quests#questsreached): ```ts import type { Choice } from '@ifloom/engine' import { quests } from '@ifloom/plugin-quests' export const river: Choice = { id: 'river', label: 'Walk to the river', when: quests.reached('friend', 'close'), effects: [{ scene: 'ava.river' }] } ``` [Add a quest](https://ifloom.dev/docs/how-to/add-a-quest) declares and starts the quest. ## Pace stages without the quests plugin [#pace-stages-without-the-quests-plugin] Plain conditions give the same order and pace. Record each stage with a key on the storyline when its scene plays, and gate the next one on that key and on `since`: ```ts import type { ActionDef, Choice } from '@ifloom/engine' // The first stage's scene sets its key as it closes. export const bye: Choice = { id: 'bye', label: 'Say goodbye', effects: [{ kv: 'knowsName', of: 'storyline:ava', to: true }, { scene: null }] } // The second waits for the first, three turns after it, and five visits. export const recipe: ActionDef = { id: 'recipe', label: 'Ask Ava for her flapjack recipe', when: { all: [{ kv: 'knowsName', of: 'storyline:ava' }, { since: 'ava.name', gte: 3 }, { seen: 'ava.hi', gte: 5 }, { not: { seen: 'ava.recipe' } }] }, effects: [{ scene: 'ava.recipe' }], } ``` Write each stage's `when` to include the one before it, so the player can't reach a stage by skipping one, however good their numbers are. The `not` hides a stage once its scene has played. ## Check it worked [#check-it-worked] Run `npm run check`, which reports a storyline, scene or stat that a condition names and the game doesn't have. Then play in `npm run dev`. Choose Chat twice in one day, and the second time the choice is greyed out with `She has a queue.` Visit on later days, and the greeting climbs its ladder. A [test](https://ifloom.dev/docs/how-to/test-a-route) can play the days through faster than you can. In the showcase, Small Town, Ava's `chat` choice, her greetings and the `friend` quest are in [`examples/showcase/src/story/ava.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/ava.ts). For more, see: - The [`since`](https://ifloom.dev/docs/reference/conditions#since), [`seen`](https://ifloom.dev/docs/reference/conditions#seen) and [`kv`](https://ifloom.dev/docs/reference/conditions#kv) conditions, and [`Once`](https://ifloom.dev/docs/reference/actions#once). - [Storylines](https://ifloom.dev/docs/reference/storylines) and [Quests](https://ifloom.dev/docs/reference/plugins/quests). - [Stats, the kv store and storylines](https://ifloom.dev/docs/explanation/entities-and-traits#stats-the-kv-store-and-storylines). # Build with esbuild (https://ifloom.dev/docs/how-to/build-with-esbuild) Use esbuild if you want a small build set-up. It compiles TypeScript and JSX itself, so your game needs no loader, and a build script of about twenty lines makes the one `index.html` that opens from disk. `ifloom check` and `ifloom playtest` work beside it. ## Install esbuild [#install-esbuild] Besides the `@ifloom` packages your game uses, add esbuild as a dev dependency: ```sh npm install --save-dev esbuild ``` For the React UI, also add `tailwindcss` and `@tailwindcss/cli`, and `react` and `react-dom` if npm hasn't installed them with `@ifloom/react`. ## Compile TypeScript [#compile-typescript] There's nothing to set up. The @ifloom packages are compiled JavaScript with type declarations, and esbuild compiles your own `.ts` and `.tsx` files itself. Pass `--jsx=automatic` if your own code has JSX, as the `react` template's `src/layout.tsx` does. ## Add the styles [#add-the-styles] esbuild bundles plain CSS you import from your code, so the `vanilla`, `vue` and `svelte` templates' stylesheet needs nothing more. esbuild writes it beside the script as `main.css`. The React UI's stylesheet is written for Tailwind CSS v4, which esbuild doesn't run. Build it with Tailwind's own CLI instead, and don't import it from `main.ts`: ```css /* src/styles.css */ @import "@ifloom/react/styles.css"; ``` ```sh npx tailwindcss -i src/styles.css -o tailwind.css ``` To go without Tailwind, import the prebuilt stylesheet from `main.ts` as plain CSS, with a preset if you like, and leave out the Tailwind steps below. ```ts import '@ifloom/react/styles.min.css' import '@ifloom/react/themes/paper.min.css' ``` ## Set up the page and the dev server [#set-up-the-page-and-the-dev-server] `index.html` points at the files esbuild and Tailwind write: ```html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>My Game
``` With the React UI, the stylesheet is `./tailwind.css` instead. ```json { "scripts": { "dev": "esbuild src/main.ts --bundle --format=esm --jsx=automatic --outdir=. --servedir=. --watch", "dev:css": "tailwindcss -i src/styles.css -o tailwind.css --watch", "build": "tailwindcss -i src/styles.css -o tailwind.css --minify && node build.js", "check": "ifloom check", "playtest": "ifloom playtest --turns 5 --out playtest/run.txt", "typecheck": "tsc --noEmit" } } ``` `npm run dev` serves the folder and builds `main.js` and `main.css` in memory on each change, without writing them to disk. With the React UI, run `npm run dev:css` beside it in a second terminal. Without it, leave out `dev:css` and the Tailwind step of `build`. `--format=esm` keeps the bundle an ES module, because the templates' `main.ts` awaits the runner at the top level. ## Mount the game [#mount-the-game] The entry is the template's `src/main.ts`, unchanged: ```ts tab="Plain JS" tab-group="framework" // src/main.ts: the vanilla template's, cut down import { browserRunner, startClock, startKeys } from '@ifloom/browser' import { startAudio } from '@ifloom/audio' import module from './game.ts' import './styles.css' const { game } = module.build() const runner = await browserRunner(game) startAudio(runner) startClock(runner) startKeys(runner) const root = document.querySelector('#root')! // ...render runner.view() into root, as in "Start your own UI" ``` ```ts tab="React" tab-group="framework" // src/main.ts: the react template's, without the stylesheet, which Tailwind's CLI builds import { mountGame } from '@ifloom/react' import module from './game.ts' import { Layout } from './layout.tsx' mountGame(module.build(), { layout: Layout, pages: true }) ``` ```ts tab="Vue" tab-group="framework" // src/main.ts: the vue template's. The .vue files need an esbuild plugin. import { createApp } from 'vue' import App from './App.vue' import './styles.css' createApp(App).mount('#root') ``` ```ts fragment tab="Svelte" tab-group="framework" // src/main.ts: the svelte template's. The .svelte files need an esbuild plugin. import { mount } from 'svelte' import App from './App.svelte' import './styles.css' mount(App, { target: document.querySelector('#root')! }) ``` esbuild has no Vue or Svelte compiler of its own. Their components need a plugin, such as [esbuild-svelte](https://github.com/EMH333/esbuild-svelte) or one of the [community's Vue plugins](https://github.com/esbuild/community-plugins), run from a build script like the one below. Plain JS and the React UI need nothing more. TypeScript doesn't know what importing a `.css` file gives. Declare it once, in `src/css.d.ts`: ```ts declare module '*.css' ``` ## Build the single offline file [#build-the-single-offline-file] esbuild can make the one `index.html` that opens from disk. Bundle without writing files, then put the script and the styles inside the page: ```js // build.js // One index.html with the game's script and styles inside it, to open from disk. import { build } from 'esbuild' import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { basename } from 'node:path' const { outputFiles } = await build({ entryPoints: ['src/main.ts'], bundle: true, format: 'esm', target: 'es2023', jsx: 'automatic', minify: true, outdir: '.', write: false, }) // What esbuild just made, or else a file on disk, such as Tailwind's output. const built = new Map(outputFiles.map((file) => [basename(file.path), file.text])) const read = (name) => built.get(name) ?? readFileSync(name, 'utf8') const html = readFileSync('index.html', 'utf8') .replace(//g, (_, name) => ``) // `<\/script>/g, (_, name) => ``) mkdirSync('dist', { recursive: true }) writeFileSync('dist/index.html', html) console.log(`dist/index.html ${(html.length / 1024).toFixed(1)} kB`) ``` `npm run build` runs it, and `dist/index.html` plays from disk. A module script inside the page runs from `file://` too, because it loads nothing. Pictures and sound aren't inside it, so copy `public/` beside it, where `ifloom build` would leave them too. To check the folder as `ifloom build` does, call [`checkBuild`](https://ifloom.dev/docs/api/cli#checkbuild) from the same script. ## Check and playtest it [#check-and-playtest-it] `ifloom check` and `ifloom playtest` load `src/game.ts` with the CLI's own Vite, not with esbuild, so they work unchanged. Add `@ifloom/cli` as a dev dependency and keep the game in `src/game.ts`, its [game module](https://ifloom.dev/docs/reference/cli#the-game-module) the default export, made with `defineGame`. The page imports the same module and calls its `build`. Pictures and sound go in `public/`, where `ifloom check` looks for them. `import.meta.env.DEV`, which the docs use to leave the [debug plugin](https://ifloom.dev/docs/how-to/debug-a-game) out of a release, is Vite's. Under esbuild, set your own with `--define:DEV=true` in `dev` and `false` in `build.js` (`define: { DEV: 'false' }`), and declare it in TypeScript with `declare const DEV: boolean`. Run `npm run check`, which prints `No problems.`, then `npm run build` and open `dist/index.html` from disk: the game starts with no server. For more, see: - [The game module](https://ifloom.dev/docs/reference/cli#the-game-module) and [`checkBuild`](https://ifloom.dev/docs/api/cli#checkbuild). - [Ship your game](https://ifloom.dev/docs/how-to/ship-your-game), for saves and what goes in the folder. # Build with Next.js (https://ifloom.dev/docs/how-to/build-with-next) Use this when your game is part of a website: a page of a site you already run on Next, or a game you host on Vercel or Netlify. Next is React, so this page uses React throughout, with the [React UI](https://ifloom.dev/docs/reference/react) or a UI of your own written in React. Next builds a website for a server to host, so it can't make the single `index.html` that opens from disk. Even a static export (`output: 'export'`) loads its scripts in chunks from absolute paths. For a download as well as the site, keep the game in its own package and build it with [`ifloom build`](https://ifloom.dev/docs/reference/cli#ifloom-build), [webpack](https://ifloom.dev/docs/how-to/build-with-webpack) or [esbuild](https://ifloom.dev/docs/how-to/build-with-esbuild), and import the same `src/game.ts` into the site. ## Start from the template [#start-from-the-template] ```sh npm create ifloom@latest my-site -- --template next cd my-site npm install npm run dev ``` The template gives you a Next app (the App Router) with the same two-scene game as the other templates, rendered with the React UI: ``` my-site/ ├── app/ │ ├── layout.tsx the page around everything, which imports src/styles.css │ ├── page.tsx the home page, which renders │ └── Game.tsx a client component that starts the game ├── src/ │ ├── game.ts puts the game together, as in every template │ ├── world/ what the whole game shares, such as stats.ts │ ├── story/ the story, one file per area, starting with opening.ts │ ├── layout.tsx the game's page: the side column, the story and its sections │ └── styles.css the React UI's styles and a theme preset ├── next.config.ts Next's settings, empty to start with ├── postcss.config.mjs Tailwind, for the React UI's stylesheet ├── README.md └── AGENTS.md ``` Its scripts are `dev`, `build` and `start` from Next, `check` and `playtest` from the `ifloom` CLI, and `typecheck`. To add a game to an app you already have, follow the sections below, which set up each part the same way. ## Add the packages [#add-the-packages] The @ifloom packages are compiled JavaScript with their type declarations, so Next uses them like any other package, with no `transpilePackages` or other setting. Add `@ifloom/engine`, `@ifloom/audio`, `@ifloom/browser` and `@ifloom/react` to the app, any plugins your game uses, and `@ifloom/cli` as a dev dependency for `check` and `playtest`, and for `@ifloom/cli/game`, which `src/game.ts` imports `defineGame` from: ```sh tab="npm" tab-group="package-manager" npm install @ifloom/engine @ifloom/audio @ifloom/browser @ifloom/react npm install --save-dev @ifloom/cli ``` ```sh tab="pnpm" tab-group="package-manager" pnpm add @ifloom/engine @ifloom/audio @ifloom/browser @ifloom/react pnpm add --save-dev @ifloom/cli ``` ```sh tab="yarn" tab-group="package-manager" yarn add @ifloom/engine @ifloom/audio @ifloom/browser @ifloom/react yarn add --dev @ifloom/cli ``` ```sh tab="bun" tab-group="package-manager" bun add @ifloom/engine @ifloom/audio @ifloom/browser @ifloom/react bun add --dev @ifloom/cli ``` ## Add the styles [#add-the-styles] The React UI's stylesheet is written for Tailwind CSS v4. Next runs Tailwind through PostCSS, so add `tailwindcss`, `@tailwindcss/postcss` and `postcss` as dev dependencies and a PostCSS config: ```js // postcss.config.mjs export default { plugins: { '@tailwindcss/postcss': {}, }, } ``` Import the UI's stylesheet from a global stylesheet, and that from the root layout: ```css /* src/styles.css */ @import "@ifloom/react/styles.css"; @import "@ifloom/react/themes/paper.css"; ``` ```tsx fragment // app/layout.tsx import type { Metadata } from 'next' import type { ReactNode } from 'react' import '../src/styles.css' export const metadata: Metadata = { title: 'My Game' } export default function RootLayout({ children }: { children: ReactNode }) { return ( {children} ) } ``` `styles.css` brings Tailwind itself, so don't import `tailwindcss` again. If the app already has Tailwind v4 of its own, import `@ifloom/react/theme.css` after your `@import "tailwindcss"` instead (see [Theme the React UI](https://ifloom.dev/docs/how-to/react/theme-the-react-ui)). The second line picks a theme preset, and is optional. To go without Tailwind, import the prebuilt `@ifloom/react/styles.min.css` from the root layout instead, and a preset as `@ifloom/react/themes/paper.min.css`, then leave out the PostCSS config. If you don't use the React UI, you don't need Tailwind at all, and you can style your own UI however the app already does. ## Start the game in a client component [#start-the-game-in-a-client-component] The game runs in the browser only. Its runner reads saves and settings from `localStorage`, which the server doesn't have. So start it in a client component, after the page has loaded, and render nothing until it's ready: ```tsx // app/Game.tsx 'use client' import { useEffect, useState } from 'react' import { browserRunner } from '@ifloom/browser' import type { Runner } from '@ifloom/engine' import { GameShell } from '@ifloom/react' import module from '../src/game.ts' import { Layout } from '../src/layout.tsx' export function Game() { const [runner, setRunner] = useState(null) useEffect(() => { // The game module builds the game, and says what the loader found wrong with it. const { game, problems } = module.build() if (problems.length) console.warn(problems) let live = true void browserRunner(game).then((made) => { if (live) setRunner(made) }) return () => { live = false } }, []) return runner ? : null } function Playing({ runner }: { runner: Runner }) { return } ``` ```tsx // app/page.tsx import { Game } from './Game' export default function Page() { return } ``` `browserRunner` is async, because it reads the player's settings before the first frame, so the effect waits for it. The `live` flag drops a runner that arrives after the component has gone, which happens in development, where React mounts each component twice. This renders [`GameShell`](https://ifloom.dev/docs/reference/react#gameshell) rather than calling [`mountGame`](https://ifloom.dev/docs/reference/react#mountgame). `mountGame` starts a React root of its own in an element, which a React app doesn't need. `GameShell` plays the game's sound and takes the same options as `mountGame`, such as `layout`, `pages`, `audio` and `components`. The page around the game is an ordinary Next page. Put the game on any route, beside the rest of the site. ## Render it with your own UI [#render-it-with-your-own-ui] To render the game with your own React components, read the view with React's `useSyncExternalStore`. Its first two arguments are a subscribe function and a snapshot function, and `runner.subscribe` and `runner.view` are both: ```tsx 'use client' import { useSyncExternalStore } from 'react' import type { Runner } from '@ifloom/engine' function Playing({ runner }: { runner: Runner }) { const view = useSyncExternalStore(runner.subscribe, runner.view, runner.view) return (

{view.scene.title}

{view.scene.beats.map((beat, at) => ('text' in beat ?

{beat.text}

: null))} {view.scene.choices.map((choice) => ( ))}
) } ``` The third argument is the server's snapshot, which `useSyncExternalStore` asks for in a server-rendered app. With your own UI you can drop `@ifloom/react` and Tailwind. Keep `@ifloom/audio` and `@ifloom/browser` for sound, the clock for timers and minigames, and the keys. [Start your own UI](https://ifloom.dev/docs/how-to/render/start) renders the rest of the game. ## Check it worked [#check-it-worked] The CLI's `check` and `playtest` don't use Next. They load `src/game.ts` with the CLI's own Vite, which `@ifloom/cli` brings, so they work in a Next app as they do anywhere: ```json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "check": "ifloom check", "playtest": "ifloom playtest --turns 5 --out playtest/run.txt", "typecheck": "next typegen && tsc --noEmit" } } ``` Keep the game in `src/game.ts`, its [game module](https://ifloom.dev/docs/reference/cli#the-game-module) the default export, made with `defineGame`, or pass its path: `ifloom check app/game/module.ts`. Pictures and sound go in `public/`, as for any Next app, and `ifloom check` looks for them there. In a Next app, use Next's own `dev` and `build` in place of `ifloom dev` and `ifloom build`. Run `npm run check`, which prints `No problems.`, then `npm run dev` and open the page: the game starts on its title screen. For more, see: - [`GameShell`](https://ifloom.dev/docs/reference/react#gameshell) and [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner). - [The game module](https://ifloom.dev/docs/reference/cli#the-game-module). - [Ship your game](https://ifloom.dev/docs/how-to/ship-your-game), for the single offline file. # Build with webpack (https://ifloom.dev/docs/how-to/build-with-webpack) Use webpack if your project already builds with it. The game is the same `src/game.ts` as in any template, and webpack replaces only the `ifloom dev` and `ifloom build` steps. `ifloom check` and `ifloom playtest` still work beside it. ## Install webpack [#install-webpack] Besides the `@ifloom` packages your game uses, add webpack and the loaders as dev dependencies: ```sh npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin esbuild-loader css-loader mini-css-extract-plugin ``` For the React UI, also add `react` and `react-dom`, and Tailwind's PostCSS plugin: `postcss`, `postcss-loader`, `tailwindcss` and `@tailwindcss/postcss`. ## Configure webpack [#configure-webpack] ```js // webpack.config.js import HtmlWebpackPlugin from 'html-webpack-plugin' import MiniCssExtractPlugin from 'mini-css-extract-plugin' export default { entry: './src/main.ts', output: { clean: true }, resolve: { extensions: ['.ts', '.tsx', '.js'] }, module: { rules: [ // Your own TypeScript. The @ifloom packages are JavaScript already. { test: /\.tsx?$/, exclude: /node_modules/, loader: 'esbuild-loader', options: { target: 'es2023', jsx: 'automatic' } }, // Tailwind builds the React UI's stylesheet. { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'] }, ], }, plugins: [new HtmlWebpackPlugin({ template: './index.html' }), new MiniCssExtractPlugin()], } ``` ```js // postcss.config.js export default { plugins: { '@tailwindcss/postcss': {} } } ``` The config is an ES module, so the `package.json` has `"type": "module"`, as every template's does. **TypeScript.** `esbuild-loader` compiles your game's TypeScript and JSX. The @ifloom packages are compiled JavaScript with type declarations, so the rule skips `node_modules` as usual. `ts-loader` or `babel-loader` work too. The engine's code needs ES2023, so don't set an older `target`. **Styles.** The React UI's stylesheet, `@ifloom/react/styles.css`, is written for Tailwind CSS v4. `postcss-loader` runs Tailwind here, so you can use its classes in your own components too. To go without Tailwind, import the prebuilt `@ifloom/react/styles.min.css` instead, and a preset as `@ifloom/react/themes/paper.min.css`, then take `postcss-loader` out of the CSS rule and drop the PostCSS config. Without the React UI you don't need either. `index.html` is the template's, with the ` ``` `add` refuses a file that isn't a mod, one made for another game, and one written for a newer engine, each with a line to show the player. It replaces an installed mod with the same id. ## Show each mod's problems under it [#show-each-mods-problems-under-it] The loader reports every problem against the pack that brought it, and a mod's pack is `mod:`. Loading never throws, so a mod with a broken reference still loads, and the game runs with whatever of it works: ```text mod:compliments · scene ava.hi · goes to unknown scene "ava.compliment" ``` Show each line that starts `mod: ` under that mod, as the managers above do, so the player knows which one to turn off. ## Try it with a mod file [#try-it-with-a-mod-file] A mod file is JSON in the shape of [`ModFile`](https://ifloom.dev/docs/reference/mods#modfile), with the game's `id` in `game` and a pack whose `schema` is the engine's `SCHEMA`. This one adds a scene to the town: ```json { "ifloomMod": 1, "id": "naps", "name": "Afternoon naps", "game": "small-town", "pack": { "id": "naps", "schema": 1, "scenes": [{ "id": "flat.nap", "title": "A nap", "body": [{ "text": "You doze off on the sofa." }], "choices": [{ "id": "wake", "label": "Wake up", "effects": [{ "scene": null }] }] }] } } ``` Add it in the manager. The page reloads, and the store loads its pack as `mod:naps`. ## Load a save made with mods [#load-a-save-made-with-mods] Saves record the ids of the packs the game was loaded with. A save made with a mod that's now off or removed still loads, and its [`LoadedSave`](https://ifloom.dev/docs/reference/saves#loadedsave)'s `missingPacks` names the mod, so tell the player. The React UI's load page does this with its `ui.missingPacks` string. For more, see: - [Mods](https://ifloom.dev/docs/reference/mods), with [`mods`](https://ifloom.dev/docs/reference/mods#mods-1), [`Mods`](https://ifloom.dev/docs/reference/mods#mods) and [`ModFile`](https://ifloom.dev/docs/reference/mods#modfile). - [Content and packs](https://ifloom.dev/docs/explanation/content-and-packs), on why a mod is a pack and how packs merge. - [Translate your game](https://ifloom.dev/docs/how-to/translate-your-game), for a translation shipped as a pack. # Make plugins work together (https://ifloom.dev/docs/how-to/make-plugins-work-together) Use this when your plugin should do more in a game that also has another plugin, such as a loyalty card that only stamps in the café when the game has places. A plugin never imports another. It names its partners in `cooperates`, asks them by name, and does without them when the game lacks them. You need a plugin first, as [Write a plugin](https://ifloom.dev/docs/how-to/write-a-plugin) makes. ## List the partners in cooperates [#list-the-partners-in-cooperates] Put the ids of the plugins yours works with in [`cooperates`](https://ifloom.dev/docs/reference/plugin-queries#cooperates): ```ts import { definePlugin } from '@ifloom/engine/plugin' type Card = { stamps: number; free: number } export const loyalty = definePlugin({ id: 'loyalty', version: 2, cooperates: ['calendar', 'places'], start: () => ({ stamps: 0, free: 0 }), }) ``` Content written for your plugin may then name a partner's conditions, effects and commands even in a game without it. The content checker leaves them alone there, and in play the condition is false, the effect does nothing and the command is refused. A partner nobody lists is reported: ```text content · action coffee · no plugin condition named "calendar/weekend"; the game has no plugin "calendar" ``` ## Ask a partner's query [#ask-a-partners-query] A query is an answer one plugin gives another, such as where the player is or what day it is. Ask it with the context's `query`, and give a fallback after `??` for a game without the partner: ```ts import { definePlugin } from '@ifloom/engine/plugin' export const menu = definePlugin({ id: 'menu', version: 1, cooperates: ['calendar', 'places'], start: () => null, view: (state, { query }) => ({ // The calendar's day, or the turn in a game without one. day: query<{ day: number }>('calendar/now')?.day ?? state.turn, open: (query('places/here') ?? 'cafe') === 'cafe', }), }) ``` Your plugin doesn't import its partner, so it gives each answer's type, `query<{ day: number }>('calendar/now')`, naming only the fields it reads. A game that imports the partner reads the same query typed by the partner's own declaration. Code outside a plugin, such as a test or a tool, asks one with [`pluginQuery`](https://ifloom.dev/docs/reference/plugin-queries#pluginquery). ## Answer a query of your own [#answer-a-query-of-your-own] Add a function to `queries`, worked out with your plugin's own context. Declare its answer in the engine's `QueryRegistry`, so a game that imports your plugin reads it typed: ```ts import { definePlugin } from '@ifloom/engine/plugin' declare module '@ifloom/engine' { interface QueryRegistry { 'loyalty/stampsLeft': () => number } } export const loyalty = definePlugin<{ stamps: number }>({ id: 'loyalty', version: 1, start: () => ({ stamps: 0 }), queries: { stampsLeft: (_state, _args, { slice }) => 5 - slice.stamps }, }) ``` Another plugin that doesn't import yours names the type itself, and does without it: `query('loyalty/stampsLeft') ?? null`. Content can't call a query, so one is for code only. ## Let content call a partner [#let-content-call-a-partner] A plugin's own `content`, or a game's content written for it, can use a partner's conditions and effects once `cooperates` lists it. A weekend brunch that stamps the card twice needs only a `calendar/weekend` in its `when`: ```ts import type { ActionDef } from '@ifloom/engine' export const brunch: ActionDef = { id: 'brunch', label: 'Order the weekend brunch', when: { 'calendar/weekend': true }, effects: [{ 'loyalty/stamp': true }, { 'loyalty/stamp': true }], } ``` Without the calendar, `calendar/weekend` is false, so the room never offers the brunch. ## Test it alone and with each partner [#test-it-alone-and-with-each-partner] Run the same tests in every case with [`partnerCases`](https://ifloom.dev/docs/reference/testing#partnercases). It gives the plugin alone, then with each partner, and `has` says whether a case loads one: ```ts import { describe, expect, it } from 'vitest' import type { Command, Content } from '@ifloom/engine' import { freshState, loadChecked, partnerCases, play } from '@ifloom/engine/testing' import { places } from '@ifloom/plugin-places' import { loyalty } from '../src/loyalty.ts' const cafe: Content = { actions: [{ id: 'coffee', label: 'Buy a coffee', effects: [{ 'loyalty/stamp': true }] }] } const coffee: Command = { type: 'action', id: 'coffee' } for (const { name, plugins, has } of partnerCases(loyalty, [places({ start: 'cafe' })])) { describe(`the loyalty card, ${name}`, () => { it('stamps a coffee', () => { const map: Content = { entities: has('places') ? [places.location({ id: 'cafe', name: 'Café', exits: [], body: [] })] : [] } const game = loadChecked([cafe, map], { id: 'corner-cafe', title: 'The Corner Café', plugins }) expect(loyalty.read(play(freshState(game), game, coffee), game).stamps).toBe(1) }) }) } ``` That makes `the loyalty card, alone` and `the loyalty card, with places`. Give what a partner changes a test block of its own, with the partner set up as that test needs. `partnerCases` throws for a partner missing from `cooperates`. For more, see: - [Plugin queries](https://ifloom.dev/docs/reference/plugin-queries), with [`queries`](https://ifloom.dev/docs/reference/plugin-queries#queries) and [`cooperates`](https://ifloom.dev/docs/reference/plugin-queries#cooperates). - [Testing helpers](https://ifloom.dev/docs/reference/testing), with [`partnerCases`](https://ifloom.dev/docs/reference/testing#partnercases). - [Plugins](https://ifloom.dev/docs/explanation/plugins#plugins-cooperate-by-name), on why plugins cooperate by name. # Move a story from Twine (https://ifloom.dev/docs/how-to/move-from-twine) Use this when you have a story written in Twine's SugarCube or Harlowe and want it in IFLoom. Make a game first, as [Create a game](https://ifloom.dev/docs/how-to/create-a-game) shows. The [Twine phrasebook](https://ifloom.dev/docs/reference/twine-phrasebook) maps each macro and special passage, and this page converts a whole passage. Still deciding whether to move? [IFLoom and Twine](https://ifloom.dev/twine) compares the two, with where Twine is the better choice. ## Decide where each passage goes [#decide-where-each-passage-goes] A Twine story is one file of passages, and an IFLoom game is a few files that each export [`Content`](https://ifloom.dev/docs/reference/content#content). Sort the passages into the layout every template starts with: - **`StoryInit`** and the variables every passage uses go in `src/world/`, a file per kind: `stats.ts`, `things.ts`, and `cast.ts` for the people. - **The passages of one place, chapter or character** go in one file in `src/story/`, such as `story/cafe.ts`, with their words. - **Passages tagged `widget`**, and the Story JavaScript, go in `src/rules.ts` as the game's own code. - **The story's title** goes in `src/game.ts`, the [game module](https://ifloom.dev/docs/reference/cli#the-game-module). The start passage becomes `introScene`, in the content that holds that scene. [Organise your game's files](https://ifloom.dev/docs/how-to/organise-your-files) has the whole layout. ## Convert a passage [#convert-a-passage] This café passage in SugarCube shows a line when the player is short of money, and offers a coffee that costs 3 coins: ```html :: Cafe Ava looks up from the till. "The usual?" <>Your pockets feel light.<> <> <><><><> <> You can't afford a coffee. <> [[Head back out|Street]] ``` Convert it in four steps: 1. Declare each variable that holds a number as a stat in `src/world/stats.ts`, with its start and label. `$coins` becomes the stat `coins`. 2. Make the passage a scene in `src/story/cafe.ts`. Each line of text becomes a `text()` block, and a line inside `<>` takes the condition as its `when`. 3. Make each link a choice. A link inside `<>` becomes a choice with `blocked`, which keeps the button on screen with its reason. Each `<>` becomes an effect, and a true/false variable such as `$hadCoffee` becomes a key in the [kv store](https://ifloom.dev/docs/reference/glossary#kv). 4. Make the link's target the choice's last effect, `{ scene: 'street' }`. The result, kept in one file here to stay short: ```ts import { text, type Content } from '@ifloom/engine' export const cafe: Content = { introScene: 'cafe', stats: [{ id: 'coins', label: 'Coins', start: 5, max: 999, spendable: true, format: '{n} coins' }], scenes: [ { id: 'cafe', title: 'The Corner Café', body: [text('Ava looks up from the till. "The usual?"'), text('Your pockets feel light.', { when: { stat: 'coins', lt: 3 } })], choices: [ { id: 'coffee', label: 'Buy a coffee', blocked: [{ when: { stat: 'coins', lt: 3 }, reason: 'You need 3 coins.' }], effects: [{ stat: 'coins', by: -3 }, { kv: 'hadCoffee', to: true }, { scene: 'street' }], }, { id: 'leave', label: 'Head back out', effects: [{ scene: 'street' }] }, ], }, { id: 'street', title: 'The high street', body: [text('The high street, busy with the market.')], choices: [] }, ], } ``` Leave the price out of the label. `coins` is `spendable`, so the UI works the price out from the choice's effects and shows `Buy a coffee (3 coins)` itself. ## Plan for the differences [#plan-for-the-differences] Four things in a Twine story need a different shape in IFLoom: - **HTML and JavaScript in prose.** Prose is words with a small [markup](https://ifloom.dev/docs/reference/prose#markup) for speech, pictures, video and sound. Move styling to your UI's theme and CSS, and calculations to `rules`. - **Variables that hold objects.** A stat holds a number, and a kv key holds a number, a string or `true`/`false`. The state is the save and must survive being written as JSON, so model a list of things as [entities](https://ifloom.dev/docs/reference/entities). - **Changing text after it shows.** A choice changes the state, and the scene renders again from it. Replace `<>` and similar macros with blocks whose `when` reads the state. - **The Twine editor.** Scenes are objects in `.ts` files, which you edit in a code editor. ## Check it worked [#check-it-worked] Run `npm run check` after each passage you convert. It reports a choice that goes to a scene nobody declared, a stat that doesn't exist, or a misspelt key, with the scene it's in: ```text cafe · scene cafe · goes to unknown scene "stret" ``` It prints `No problems.` once every name resolves. Then run `npm run dev` and play the scene: the coffee button is refused with `You need 3 coins.` while the player has fewer than 3 coins. For more, see: - [The Twine phrasebook](https://ifloom.dev/docs/reference/twine-phrasebook), for every SugarCube and Harlowe macro. - [Scenes](https://ifloom.dev/docs/reference/scenes), [Conditions](https://ifloom.dev/docs/reference/conditions) and [Effects](https://ifloom.dev/docs/reference/effects). - [Differences from Twine, Ink and Ren'Py](https://ifloom.dev/docs/explanation/design#differences-from-twine-ink-and-renpy), for why IFLoom keeps rules out of the prose. # Offer a random scene from a set (https://ifloom.dev/docs/how-to/offer-a-random-scene) Use this for the small things that happen while the player sits in a café or waits at a bus stop. Each one is a [storylet](https://ifloom.dev/docs/reference/glossary#storylet), a scene drawn at random from a named set, and the game keeps no list of them. The steps build the showcase café's "Sit a while". ## Mark the scenes that can come up [#mark-the-scenes-that-can-come-up] Give each scene a `drawnFrom` with the set's name. Add a `weight` to make one more likely, 1 if left out, and a `when` to say when it can come up: ```ts import type { DataScene } from '@ifloom/engine' export const cafeScenes: DataScene[] = [ { id: 'cafe.window', title: 'The window seat', drawnFrom: ['cafe'], weight: 3, when: { not: { seen: 'cafe.window', gte: 2 } }, body: [{ text: 'Rain on the glass, and the high street going by in umbrellas.' }], choices: [{ id: 'leave', effects: [{ scene: null }] }], }, { id: 'cafe.crossword', title: 'Seven down', drawnFrom: ['cafe'], when: { not: { seen: 'cafe.crossword' } }, body: [{ text: '"Seven down. Somewhere to sit and wait, four letters." You try "café".' }], choices: [{ id: 'leave', effects: [{ stat: 'charm', by: 1 }, { scene: null }] }], }, ] ``` A weight of 3 comes up three times as often as a weight of 1, among the scenes whose `when` holds. `when` only limits draws, so a `{ scene: 'cafe.window' }` effect opens the scene whether it holds or not. ## Draw one from an action [#draw-one-from-an-action] Add the [`scene` effect](https://ifloom.dev/docs/reference/storylets#scene) with `from` in place of an id, on an action, a choice or a trigger. Name a scene in `otherwise` for when none can come up: ```ts import type { ActionDef, DataScene } from '@ifloom/engine' export const sit: ActionDef = { id: 'sit', label: 'Sit a while', effects: [{ scene: { from: 'cafe', otherwise: 'cafe.quiet' } }] } export const quiet: DataScene = { id: 'cafe.quiet', title: 'A quiet table', body: [{ text: 'Nothing much happens. The coffee is good.' }], choices: [{ id: 'leave', effects: [{ scene: null }] }], } ``` In the showcase, `sit` is one of the café location's actions. The draw is seeded from the save, so reloading doesn't change what comes up. ## Limit how often each comes up [#limit-how-often-each-comes-up] Write the limit in the scene's `when`: ```ts fragment when: { not: { seen: 'cafe.crossword' } } // once ever when: { not: { seen: 'cafe.window', gte: 2 } } // at most twice when: cast.here('ava') // only while Ava is here when: { stat: 'friendship', of: cast.character('ava'), gte: 25 } // only once you know her ``` For at most once a turn, set a kv key in the scene's choice, list the key in your content's [`resets`](https://ifloom.dev/docs/reference/rules#resets) so it goes back each turn, and test it in `when`. ## Add a cooldown [#add-a-cooldown] Store the turn when the scene was last seen, and test how long ago that was with a condition of the game's own. These go in the game's [rules](https://ifloom.dev/docs/reference/glossary#rules), and content calls them as `game/`: ```ts import type { DataScene, GameRules } from '@ifloom/engine' export const rules: GameRules = { conditions: { cooledDown: (state, args) => { const last = state.kv[String(args.key)] return typeof last !== 'number' || state.turn - last >= Number(args.turns ?? 1) }, }, macros: { stamp: (state, args) => [{ kv: String(args.key), to: state.turn }] }, } export const samAtTheCafe: DataScene = { id: 'cafe.sam', drawnFrom: ['cafe'], when: { 'game/cooledDown': { key: 'cafe.sam.last', turns: 3 } }, body: [{ text: 'Sam waves from the queue with a dog lead in one hand.' }], choices: [{ id: 'leave', effects: [{ 'game/stamp': { key: 'cafe.sam.last' } }, { scene: null }] }], } ``` Sam turns up at most once every three turns. Stamp the key in every way out of the scene, or in the effect that opens it. ## Make an event rare [#make-an-event-rare] Put an ordinary scene in the same set with a bigger weight. With the window seat at weight 1 and a `cafe.ordinary` visit at weight 3, the window seat comes up about one sit in four. For a chance worked out from the state, such as 20% plus 8% per rank, roll it in a [macro](https://ifloom.dev/docs/reference/glossary#macro) with [`chance`](https://ifloom.dev/docs/reference/random#chance), and draw only when it comes up: ```ts import { chance } from '@ifloom/engine' import type { Macro } from '@ifloom/engine/plugin' // in rules.macros, called as { 'game/maybeSomething': { rank: 2 } } export const maybeSomething: Macro = (state, args) => chance(20 + 8 * Number(args.rank ?? 0), 100, state.seed, state.turn, 'cafe.event') ? [{ scene: { from: 'cafe', otherwise: 'cafe.quiet' } }] : [] ``` ## Add to the set from another file or a mod [#add-to-the-set-from-another-file-or-a-mod] Declare another scene with the set in its `drawnFrom`. The set has no list of members, so a later content file or a [mod](https://ifloom.dev/docs/reference/glossary#mod) adds one this way: ```ts import { SCHEMA, type Pack } from '@ifloom/engine' export const rainyDays: Pack = { id: 'mod:rainy-days', schema: SCHEMA, scenes: [ { id: 'cafe.umbrella', drawnFrom: ['cafe'], body: [{ text: 'Someone has left an umbrella hooked over the back of your chair. Nobody comes back for it.' }], choices: [{ id: 'leave', label: 'Leave it where it is', effects: [{ scene: null }] }], }, ], } ``` ## Check it worked [#check-it-worked] Run `npm run check`. It reports a draw from a set no scene is in, such as a set name misspelt in the draw or in `drawnFrom`, and a `weight` or `when` on a scene that is in no set. Then sit a while several times in a row with `npm run dev`. A test can sit down with many seeds and check that each scene comes up, as the showcase's test `draws something to happen when you sit a while at the café, and a quiet table when nothing can` does. In the showcase, Small Town, the `sit` action and the `cafe.*` scenes are in [`examples/showcase/src/story/cafe.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/cafe.ts). For more, see: - [Storylets](https://ifloom.dev/docs/reference/storylets), with the checks and how the draw is seeded. - [The `seen` condition](https://ifloom.dev/docs/reference/conditions#seen) and [`resets`](https://ifloom.dev/docs/reference/rules#resets). - [The same save gives the same draws](https://ifloom.dev/docs/explanation/design#the-same-save-gives-the-same-draws). # Offer New Game+ (https://ifloom.dev/docs/how-to/offer-new-game-plus) Use this to let a player who has finished your game start again with a little of what they had, such as their coins or a memory of the first read. You need an ending first, as [End the game](https://ifloom.dev/docs/how-to/end-the-game) shows. ## Say when the game is finished [#say-when-the-game-is-finished] Give your content a `finished` condition. After each command the runner tests it, and the first time it holds, the runner records the time in the player's [profile](https://ifloom.dev/docs/reference/profile) under `core:finished`. The record outlives every save. The Letter, the novel example, counts either of its two endings: ```ts import type { Content } from '@ifloom/engine' export const endings: Content = { finished: { scene: ['end.kept', 'end.posted'] }, } ``` ## Choose what carries over [#choose-what-carries-over] List player stats and kv keys in your content's `carryOver`, a [`CarryOver`](https://ifloom.dev/docs/reference/state#carryover): ```ts import type { Content } from '@ifloom/engine' export const nextRun: Content = { carryOver: { stats: ['coins'], kv: ['readBefore'] }, } ``` Things the player has belong to the plugin that keeps them, and each plugin carries its own with its [`carry`](https://ifloom.dev/docs/reference/plugin-api#carry). The inventory takes a `carryOver` option, the things to keep or `'all'`: ```ts fragment plugins: [inventory({ carryOver: ['clothing:umbrella'] })] ``` A game that keeps things in kv keys lists those keys in `carryOver.kv` instead. A New Game+ starts like any new game, then copies these from the finished game's state: - **Each stat** in `stats`, held to its range. - **Each kv key** in `kv` that is set. - **What each plugin carries**, such as the things the inventory's `carryOver` lists. A thing made in play, such as a photo, comes with its record. Nothing else comes across. The turn, the scenes seen, the storylines, the entities and the state of every plugin that carries nothing all start fresh. ## Write lines for a second run [#write-lines-for-a-second-run] Set a kv key as the player reaches an ending, carry it over, and read it where the story should know. The Letter sets `readBefore` on each ending's choice, and its first chapter has a line only a second reader sees: ```ts fragment { id: 'post', label: 'Post it back', effects: [{ kv: 'readBefore', to: true }, { scene: 'end.posted' }] } body: [ { text: 'The flat still smells of someone else’s cooking.' }, { text: 'You have the oddest feeling you have stood here before.', when: { kv: 'readBefore' } }, ], ``` ## Offer it to the player [#offer-it-to-the-player] The React UI's title screen shows a New Game+ button once `core:finished` is in the profile and the game has a `carryOver`. Turn the title screen on with `pages`, as [Add a title screen](https://ifloom.dev/docs/how-to/add-a-title-screen) shows. The button carries over from the newest save, or from the game in play if there's no save. On a title screen of your own, offer it once the profile has `core:finished`, and start it with [`runner.newGame({ carry })`](https://ifloom.dev/docs/reference/runner#newgame), where `carry` is the state to carry over from: ```ts given const finished = await runner.profile?.get<{ at: number }>('core:finished') if (finished) { const listed = await runner.saves?.list() const newest = listed?.ok ? listed.value.find((save) => !('broken' in save)) : undefined const save = newest ? await runner.saves?.read(newest.slot) : undefined await runner.newGame({ carry: save?.ok && save.value ? save.value.state : runner.state }) } ``` Carry from the state the player finished on. The profile records only when the game was finished, not the state, so after a reload, read it from the newest save as above. ## Check it worked [#check-it-worked] Run `npm run check`. It reports a stat in `carryOver` the game doesn't declare or that belongs to a kind: ```text content · carryOver · unknown stat "gold" ``` Then play in `npm run dev` to an ending, go back to the title screen, and press New Game+. The line for a second reader shows in the first scene. For more, see: - [`CarryOver`](https://ifloom.dev/docs/reference/state#carryover) and [`newGame`](https://ifloom.dev/docs/reference/runner#newgame). - [Profile](https://ifloom.dev/docs/reference/profile), with its `core:finished` key. - [End the game](https://ifloom.dev/docs/how-to/end-the-game#know-what-a-new-game-keeps), for what a plain new game keeps. # Open a shop, a job board or another panel (https://ifloom.dev/docs/how-to/open-a-panel) Use this to put a shop's counter, a job board or a screen of your own over the story. A [panel](https://ifloom.dev/docs/reference/glossary#panel) never opens because of where the player is. Your content opens it by name with the [`panel` effect](https://ifloom.dev/docs/reference/effects#panel), so it can sit wherever it fits the town. The shop and jobs plugins write the effect for you: ```ts import { shop } from '@ifloom/plugin-shop' import { jobs } from '@ifloom/plugin-jobs' export const counter = shop.open('counter') // { panel: 'shop', with: { vendor: 'counter' } } export const board = jobs.open() // { panel: 'jobs' } export const ads = jobs.open(['dogs']) // { panel: 'jobs', with: { job: ['dogs'] } } ``` Any effect list can hold one. You need the vendor or the jobs declared first, as [Shop](https://ifloom.dev/docs/reference/plugins/shop#vendordef) and [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobdef) describe. ## Open a counter from a location [#open-a-counter-from-a-location] Put the effect on one of the location's [actions](https://ifloom.dev/docs/how-to/add-a-location#give-it-things-to-do), so the room offers it only there. This is the showcase café's counter: ```ts import { places } from '@ifloom/plugin-places' import { shop } from '@ifloom/plugin-shop' export const cafe = places.location({ id: 'cafe', name: 'The Corner Café', description: 'Café', exits: ['high-street'], body: [{ text: 'Six tables, one of them wobbly.' }], actions: [{ id: 'counter', label: 'Go to the counter', effects: [shop.open('counter')] }], }) ``` A town hall's job board is the same, with `jobs.open()` in its action's effects. ## Open the job board from a person [#open-the-job-board-from-a-person] Put the effect in a choice of the person's scene. To close the scene and show the board over the room, do both in one choice: ```ts import type { Choice } from '@ifloom/engine' import { jobs } from '@ifloom/plugin-jobs' export const work: Choice = { id: 'work', label: 'Ask about weekend work', effects: [{ scene: null }, jobs.open()] } ``` The board stays open, because the command that opens a panel never closes it, even when it also closes the scene. ## Open it from a thing the player uses [#open-it-from-a-thing-the-player-uses] With the [inventory plugin](https://ifloom.dev/docs/reference/plugins/inventory), give the thing the `inventory/usable` trait with the effect. Give it `keep: true` so that reading the paper doesn't use it up: ```ts import type { EntityDef } from '@ifloom/engine' import { inventory } from '@ifloom/plugin-inventory' import { jobs } from '@ifloom/plugin-jobs' export const paper: EntityDef = { id: 'paper', of: 'item', name: 'newspaper', description: 'Today’s Small Town Gazette. The back page is job ads.', traits: { ...inventory.at('player'), ...inventory.usable('Read the job ads', [jobs.open(['dogs'])], { keep: true }) }, } ``` `jobs.open(['dogs'])` shows only the dog-walking job, as the paper's ads would. ## Open a shop from a phone or a laptop [#open-a-shop-from-a-phone-or-a-laptop] Put the effect on a button in an app's actions section, from the [devices plugin](https://ifloom.dev/docs/reference/plugins/devices). Opening a counter doesn't move the player, and a vendor with a `places.onlyAt()` entry in its `blocked` refuses to sell anywhere else, so leave that entry out of an online shop: ```ts import type { AppDef } from '@ifloom/plugin-devices' import { shop } from '@ifloom/plugin-shop' export const webshop = shop.vendor({ id: 'webshop', name: 'Pinecone Online', goods: [{ entity: 'clothing:scarf', price: { coins: 10 } }] }) export const pinecone: AppDef = { id: 'pinecone', name: 'Pinecone', icon: 'basket', on: 'laptop', sections: [{ actions: [{ id: 'browse', label: 'Browse the shop', effects: [shop.open('webshop')] }] }], } ``` Add `webshop` to the content's `entities`, and the app to `data.devices.apps`, beside a `laptop` device in `data.devices.devices`. ## Open a panel of your own [#open-a-panel-of-your-own] Name any panel in the effect, with what it needs in `with`: ```ts import type { ActionDef } from '@ifloom/engine' export const noticeboard: ActionDef = { id: 'noticeboard', label: 'Read the noticeboard', effects: [{ panel: 'noticeboard', with: { title: 'Noticeboard' } }] } ``` The engine keeps the panel's name and `with` in `view.panel`, and your UI decides what the name renders. In the React UI, add a component by that name to `mountGame`'s `panels`, as [`PanelHost`](https://ifloom.dev/docs/reference/react/components#panelhost) shows. With a UI of your own, see [Render a panel](https://ifloom.dev/docs/how-to/render/timers-minigames-panels#render-a-panel). To hold a panel open for as long as a scene is on screen, give the scene a [`panel`](https://ifloom.dev/docs/reference/panels#scenepanel) instead, such as `panel: { panel: 'prices', with: { stall: 'bread' } }`. ## Close it [#close-it] The player closes a panel in the UI, which sends the [`closePanel`](https://ifloom.dev/docs/reference/commands#closepanel) command. Content closes it with `{ panel: null }`, and another `panel` effect replaces it. A panel also closes when a later command ends a turn or changes the scene, such as a shift that passes the morning, so the player can buy several things or apply for a job with it open. ## Check it worked [#check-it-worked] Run `npm run check`. It reports a `shop.open` for a vendor the game doesn't have, and a `jobs.open` that lists a job it doesn't have, where the effect is written: ```text content · trait inventory/usable on item:paper · unknown job "circus" ``` Then play in `npm run dev` and press the button. The React UI shows the counter or the board in a dialog when the game lists `shopUi` and `jobsUi` in `plugins` (see [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin#show-it-on-screen)), and closing the dialog closes the panel. To render them in a UI of your own, see [Render a shop counter](https://ifloom.dev/docs/how-to/render/things-plugins#render-a-shop-counter) and [Render a job board](https://ifloom.dev/docs/how-to/render/things-plugins#render-a-job-board). In the showcase, Small Town, the café's counter is in [`examples/showcase/src/story/cafe.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/cafe.ts), Ava's `work` choice in `src/story/ava.ts` and the newspaper in `src/world/things.ts`. For more, see: - [Panels](https://ifloom.dev/docs/reference/panels), with [`OpenPanel`](https://ifloom.dev/docs/reference/panels#openpanel) and [`ScenePanel`](https://ifloom.dev/docs/reference/panels#scenepanel), and the [`panel` effect](https://ifloom.dev/docs/reference/effects#panel). - The [shop](https://ifloom.dev/docs/reference/plugins/shop) and [jobs](https://ifloom.dev/docs/reference/plugins/jobs) plugins. - [Write a flowing scene](https://ifloom.dev/docs/how-to/write-a-flowing-scene#play-a-minigame-or-open-a-panel-where-it-stands), to open a panel in the middle of a scene. # Organise your game's files (https://ifloom.dev/docs/how-to/organise-your-files) Use this when one content file has grown too long to find your way around, or before you start a game with places, people and weeks of story. Every template and example already follows this layout. [Content, packs and the base](https://ifloom.dev/docs/explanation/content-and-packs) explains how `loadGame` merges the files. ``` src/ ├── game.ts assembles the game from the files below ├── rules.ts the game's own code, once it has any ├── world/ what the whole game shares, one file per kind │ ├── stats.ts │ ├── things.ts │ ├── cast.ts │ └── settings.ts └── story/ the story, one file per area ├── opening.ts └── cafe.ts ``` ## Keep game.ts to the list of files [#keep-gamets-to-the-list-of-files] `src/game.ts` holds the game module and the base, and no content. Its default export is the [game module](https://ifloom.dev/docs/reference/cli#the-game-module), made with `defineGame`. The base holds only the game's `id`, `title`, `version`, `plugins` and `rules`. Actions, locks, the scene the game opens on and the rest are [content](https://ifloom.dev/docs/reference/content#content), so they go in a file of their own. ```ts // src/game.ts import { loadGame } from '@ifloom/engine' import { defineGame } from '@ifloom/cli/game' import { stats } from './world/stats.ts' import { opening } from './story/opening.ts' import { cafe } from './story/cafe.ts' export default defineGame({ build: ({ unlocked }) => loadGame([stats, opening, cafe], { id: 'my-game', title: 'My Game' }, { packs: unlocked }), }) ``` `build` receives `unlocked`, the packs in `src/unlocks/` that a player opens with a code (see [Locked content](https://ifloom.dev/docs/reference/cli#locked-content)). A game with no locked content can write `build: () => loadGame([…], base)`. ## Put what the whole game shares in world/ [#put-what-the-whole-game-shares-in-world] Give `src/world/` one file per kind of declaration: `stats.ts`, `things.ts`, `cast.ts` for the people, `settings.ts` for what the player can change. A stat or a character turns up all over the story, so it has no one home there. Each file exports one `Content` object: ```ts // src/world/stats.ts import type { Content } from '@ifloom/engine' export const stats: Content = { stats: [{ id: 'coins', label: 'Coins', start: 12, spendable: true }], } ``` ## Put the story in story/, one file per area [#put-the-story-in-story-one-file-per-area] Give `src/story/` one file per area, with the area's scenes, their words, the actions that open them and its slice of plugin content. A change to the café then touches `story/cafe.ts` and nothing else. Pick the kind of area that matches how you think about the story: - **A place**, with the [places plugin](https://ifloom.dev/docs/reference/plugins/places): the file holds the location, its actions, its scenes, and its vendor or jobs. - **A chapter**, in a linear story: The Letter has `story/ch1.ts`, `ch2.ts` and `ch3.ts`. - **A character's arc**: the showcase's `story/ava.ts` holds Ava's scenes, texts, quest and achievement. A game can mix them, as the showcase mixes places and arcs. Write each scene's words in the scene itself, in its `text()` blocks and its choices' `label`s: ```ts // src/story/cafe.ts import { text, type Content } from '@ifloom/engine' export const cafe: Content = { scenes: [ { id: 'cafe.window', title: 'The window seat', body: [text('You take the stool by the window. A bus goes by, then a man with a ladder.')], choices: [{ id: 'leave', label: 'Finish your cup', effects: [{ scene: null }] }], }, ], actions: [{ id: 'coffee', label: 'Buy a coffee', cost: { stats: { coins: 3 } }, effects: [{ scene: 'cafe.window' }] }], } ``` Lines read by key go in the area's `prose`: [variants](https://ifloom.dev/docs/reference/prose#variantmember), a tooltip's words, or a line several scenes share. When an area has a lot of them, move them to a sibling file named after it, `cafe.prose.ts`, and import them into the area's content as `prose`. ## Split a file when it gets long [#split-a-file-when-it-gets-long] Start with one file in each folder, as the templates do. Split a file when you scroll through it to find things, or when two people edit it at once: 1. Move the declarations into a new file that exports a `Content` object. 2. Import it in `src/game.ts` and add it to the list. 3. Run `npm run check`. `loadGame` merges the files in the order you list them, and lists such as triggers, quests and places keep that order. List `world/` first, then the story in the order the player meets it. The files have no ids, so you can rename, split or merge them at any time, even after release. Saves depend on the ids inside them, so keep scene, entity and storyline ids stable once players have saves. ## Check it worked [#check-it-worked] Each key is declared once across all the files. If two files declare the same scene, `npm run check` fails with a line like this: ```text content · scene "cafe.counter" · declared twice ``` Search for the id and delete the copy you don't want. Give each file's content a `name`, such as `name: 'story.cafe'`, and the problem names both files. `npm run check` prints `No problems.` once every key is declared once. ## Variations [#variations] **Everything by kind.** A management game that is mostly data can keep nearly everything in `world/`. The Corner Café keeps its stats, staff, menu, actions and triggers there, a file each, with only two scenes in `story/` and its sums in `rules.ts`. **One file.** A story of a dozen scenes reads fine as one `Content` object in `src/game.ts`, as [Add IFLoom to an existing project](https://ifloom.dev/docs/how-to/add-to-a-project) shows. Move it into the folders when it grows. The pages this used: - [`Content`](https://ifloom.dev/docs/reference/content#content) and [`loadGame`](https://ifloom.dev/docs/reference/content#loadgame), and the [checks](https://ifloom.dev/docs/reference/content#checks) for a key declared twice. - [The game module](https://ifloom.dev/docs/reference/cli#the-game-module). - [The examples](https://ifloom.dev/docs/reference/examples), which lists each example's files. - [Content, packs and the base](https://ifloom.dev/docs/explanation/content-and-packs). # Playtest and snapshot from the command line (https://ifloom.dev/docs/how-to/playtest-and-snapshot) Use this to check a whole game without playing it yourself: that its content holds together, that a week of play offers nothing it then refuses, and that no scene reads differently from last time without you meaning it. The three commands run from the game's folder, whatever builds it, and read the [game module](https://ifloom.dev/docs/reference/glossary#game-module) in `src/game.ts`. ## Check the content [#check-the-content] Run [`ifloom check`](https://ifloom.dev/docs/reference/cli#ifloom-check): ```sh npx ifloom check ``` It builds the game and prints every problem the [content checker](https://ifloom.dev/docs/reference/checks) found, such as a misspelt scene id or a stat nobody declares, one per line with where it is. It also lists each picture and sound file the game names that isn't in `public/`. It exits with `1` on any problem, so CI fails on a broken id before anybody plays. Warnings, such as a token that may print nothing, follow the problems and don't change the exit code. ## Play a week with playtest [#play-a-week-with-playtest] Run [`ifloom playtest`](https://ifloom.dev/docs/reference/cli#ifloom-playtest). It plays the game for `--turns` turns, seven by default, with a policy choosing each command: ```sh npx ifloom playtest npx ifloom playtest --turns 30 --out playtest/month.txt ``` It writes every screen with the command taken on it to `playtest.txt`, and one row of numbers per turn to `playtest.txt.metrics`: each stat as the turn ended, a count of each listed kind of entity, the scenes entered and the commands refused. Then it prints the numbers and each refusal with its turn and reason. It exits with `1` if any command was refused, since that's a button the game offered and then wouldn't do. ## Read the transcript [#read-the-transcript] Each screen in the transcript is the player's, with the command under it: ```text == Turn 2 · Day 2 · Tuesday morning · High Street # High Street A bakery, a launderette, a bus stop with a bench nobody sits on. [>] Buy a scarf at the market (8 coins) [ ] Go to bed — Too early. [>] Sam: Talk -> The Corner Café > {"type":"custom","name":"cast/talk","with":{"who":"sam"}} ``` The words are as the player reads them, one paragraph a beat: a spoken line under who says it, as `Ava: "Morning."`, and a picture or a video as a `[picture: …]` note. `[>]` is a button the player can press, `[ ]` one that's greyed out with its reason after the dash, and `->` a way out. Run a playtest before and after a change to pacing, such as a price, a reward or a door's hours, and read both. The numbers say when things happened, such as the turn the coins stopped climbing. Only the transcript shows a line that prints on every screen, a variant dealt five days running, or a gate meant for week two that's open on day two. ## Set where it starts and what it chooses [#set-where-it-starts-and-what-it-chooses] Give the game module a `start` and a `policy`. Without them, it starts from `startingState(game)` with the [explorer](https://ifloom.dev/docs/reference/cli#explorer), which presses a button it hasn't tried yet each time: ```ts // src/game.ts import { loadGame, startingState } from '@ifloom/engine' import { defineGame, type Policy } from '@ifloom/cli/game' import { stats } from './world/stats.ts' import { opening } from './story/opening.ts' /** Always knock, then the first button that can be pressed. */ const brave: Policy = (screen) => { const buttons = [...screen.scene.choices, ...screen.actions].filter((button) => !button.disabled) return (buttons.find((button) => button.id === 'knock') ?? buttons[0])?.command ?? null } export default defineGame({ build: () => loadGame([stats, opening], { id: 'my-story', title: 'My Story' }), start: (game) => startingState(game, { kv: { playerName: 'Robin' } }), policy: brave, }) ``` The explorer won't find a route through a story, because it doesn't know your game. Write a [`Policy`](https://ifloom.dev/docs/reference/cli#policy) of your own to reach a scene that needs good choices. A run stops early when the policy returns `null`, goes round in circles, or sends the same refused command twice in a row. It also stops at a running minigame, because neither the explorer nor a policy can play one, so a run through Small Town ends on day 2 at the park's quick feet. ## Snapshot every scene [#snapshot-every-scene] Run [`ifloom snapshot`](https://ifloom.dev/docs/reference/cli#ifloom-snapshot). It renders every scene and every location's body in each probe state, as the player would read it: ```sh npx ifloom snapshot # write snapshots/scenes.txt, or compare with it npx ifloom snapshot --update # write it again, after a change you meant ``` The first run writes the file, so commit it. After that, each run compares and prints `changed: @ ` for each render that reads differently, then exits with `1`. A difference is a bug or a change you meant, so read the diff, then run `--update`. A change to a condition or a line can make a scene read differently without anyone noticing, and the snapshot shows which scene and in which state. ## Choose the probes [#choose-the-probes] Give the game module `probes`, a function that returns the states `ifloom snapshot` reads every scene in. Make each with [`probe`](https://ifloom.dev/docs/reference/cli#probe), by playing commands and effects from the start, so each is a state a player could be in: ```ts // src/game.ts import { loadGame } from '@ifloom/engine' import { defineGame, probe } from '@ifloom/cli/game' import { stats } from './world/stats.ts' import { opening } from './story/opening.ts' export default defineGame({ build: () => loadGame([stats, opening], { id: 'my-story', title: 'My Story' }), probes: (game) => { const knocked = probe('knocked', game, [{ play: { type: 'choose', id: 'knock' } }]) const brave = probe('brave', game, [{ stat: 'courage', to: 5 }], knocked) return [probe('start', game, []), knocked, brave] }, }) ``` A `{ play }` step sends a command as the player would, and `probe` throws if the game refuses it. Any other step is an effect, a plugin's included, such as `{ turn: true }` to end a turn. Pick probes that differ in what the content asks about: the first screen, an ordinary day, and a state well along with keys set and scenes seen. The showcase's three, `moving-day`, `first-morning` and `a-week-in`, are in [`examples/showcase/src/game.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/game.ts). Each scene is rendered as if it were open in each probe, wherever the probe's player stands. Effect steps skip the locks a command would meet, so play commands where you can. ## Run them in tests and CI [#run-them-in-tests-and-ci] The same work is in functions from `@ifloom/cli`, so a test can run it: ```ts import { readFileSync } from 'node:fs' import { expect, it } from 'vitest' import { explorer, playtest, snapshot } from '@ifloom/cli' import { startingState } from '@ifloom/engine' import module from '../src/game.ts' const { game } = module.build() it('plays five turns with nothing refused', () => { expect(playtest(game, startingState(game), explorer(), { turns: 5 }).refusals).toEqual([]) }) it('reads every scene as it did', () => { expect(snapshot(game, module.probes?.(game) ?? [])).toBe(readFileSync(new URL('../snapshots/scenes.txt', import.meta.url), 'utf8')) }) ``` In CI, run your tests, then `ifloom check`, `ifloom playtest` and `ifloom snapshot`. Each exits with `1` on what it finds. For more, see: - [The CLI](https://ifloom.dev/docs/reference/cli), with [`defineGame`](https://ifloom.dev/docs/reference/cli#definegame), [`probe`](https://ifloom.dev/docs/reference/cli#probe), [`Policy`](https://ifloom.dev/docs/reference/cli#policy) and [`explorer`](https://ifloom.dev/docs/reference/cli#explorer). - [Checks](https://ifloom.dev/docs/reference/checks), with every problem the content checker reports. - [Test a route through your game](https://ifloom.dev/docs/how-to/test-a-route). # Put a choice inside a line of text (https://ifloom.dev/docs/how-to/put-a-choice-in-a-line) Use this when a choice reads better as part of the sentence than as a button under it: "Your phone is ringing. Pick it up, or let it ring." The same markup puts a short note on a word, such as who runs the launderette. You need a scene with choices, or a location with actions. ## Put a choice in the line [#put-a-choice-in-the-line] Write `[[act:id|words]]` where the link should go. `id` names one of the scene's choices, and `words` are what the link says: ```ts import type { DataScene } from '@ifloom/engine' import { text } from '@ifloom/engine' export const hall: DataScene = { id: 'hall.phone', title: 'The hall', body: [text('Your phone is ringing on the hall table. [[act:answer|Pick it up]], or let it ring.')], choices: [ { id: 'answer', label: 'Answer the phone', effects: [{ kv: 'answered', to: true }, { scene: 'ava.call' }] }, { id: 'leave', label: 'Go out', effects: [{ scene: null }] }, ], } ``` The link takes the choice's place, so Go out is the only button under the text. It's still a choice. Its `blocked` reasons, its cost, its `once` and the content checker work as they do on a button, and greyed out it shows its reason. `[[act:answer]]` with no words shows the choice's own label. ## Put an action in the room's text [#put-an-action-in-the-rooms-text] While no scene is open, `[[act:id]]` names one of the room's [actions](https://ifloom.dev/docs/reference/glossary#action), a location's or the game's. The showcase's flat links to its "Read your messages" action once Ava's text has come: ```ts import { text, type ActionDef, type Block } from '@ifloom/engine' import { devices } from '@ifloom/plugin-devices' export const line: Block = text('Your phone buzzes on the sill: a message. [[act:read-text|Check it]].', { when: { kv: 'textWaiting' } }) export const readText: ActionDef = { id: 'read-text', label: 'Read your messages', when: { kv: 'textWaiting' }, command: devices.open('texts') } ``` Give the line and the action the same `when`, so the link and the action come and go together. An action can send a command as well as its effects, so a link can do anything a button can. The command runs first, then the effects. While the command would be refused, the link is greyed out with that reason. ## Add a tooltip to a word [#add-a-tooltip-to-a-word] Write `[[tip:key|words]]`. The words show in the line, and the note is the [prose key](https://ifloom.dev/docs/reference/glossary#prose-key) `key` in your content's `prose`: ```ts import { text, type Content } from '@ifloom/engine' export const movingDay: Content = { scenes: [ { id: 'intro', title: 'Moving day', body: [text('The flat is above a [[tip:intro.launderette|launderette]]; it smells of warm cotton.')], choices: [{ id: 'unpack', label: 'Unpack', effects: [{ scene: null }] }], }, ], prose: { 'intro.launderette': 'Sam from flat 2 runs it. Service washes, Monday to Saturday.' }, } ``` The note can hold [tokens](https://ifloom.dev/docs/reference/prose#tokens) such as `{{playerName}}`, and a translation or a mod rewrites it by its key. ## Check it worked [#check-it-worked] Run `npm run check`. The checker reports each of these: - An `[[act:id]]` that names a choice the scene doesn't have, or an action the room doesn't have. - One choice put in the text twice, in one line or in two blocks that can show together. - A `[[tip:key|…]]` whose key has no prose, and a `[[tip:key]]` with no words. - Markup that isn't closed, or has no id. Then play the scene. The link sits in the line, the choice is gone from the list under it, and the tooltip opens on hover, on keyboard focus and on a tap. The React UI renders both with no code from you. To render them in a UI of your own, see [Render inline choices and tooltips](https://ifloom.dev/docs/how-to/render/scene#render-inline-choices-and-tooltips). To open a dialog from a word, see [Show a popup](https://ifloom.dev/docs/how-to/show-a-popup). In the showcase, Small Town, the moving-day scene has a tooltip on "launderette", and the flat's Check it opens the phone's messages (`examples/showcase/src/story/moving-day.ts` and `story/flat.ts`). For more, see: - [Inline actions and tooltips](https://ifloom.dev/docs/reference/prose#inline-actions-and-tooltips) and [`InlineSpan`](https://ifloom.dev/docs/reference/prose#inlinespan). - [Choice](https://ifloom.dev/docs/reference/scenes#choice) and [ActionDef](https://ifloom.dev/docs/reference/actions#actiondef). - [The prose checks](https://ifloom.dev/docs/reference/checks#prose). # Add splash cards (https://ifloom.dev/docs/how-to/react/add-splash-cards) This how-to is for `@ifloom/react`, the optional React UI. To render a game in plain DOM, Vue or React by hand, see [Start your own UI](https://ifloom.dev/docs/how-to/render/start). Use this to show cards as the game opens, before the title screen, such as your studio's logo, a publisher's and the game's own. With `pages` on, a game shows the "Powered by IFLoom" card unless you change it. The fields are on the [`SplashPage`](https://ifloom.dev/docs/reference/react/components#splashpage) reference entry. ## Add your own cards [#add-your-own-cards] List the cards in `pages.splash.cards`, in the order they show. Put [`poweredByIFLoom()`](https://ifloom.dev/docs/reference/react/components#poweredbyifloom) where the IFLoom card should go: ```tsx import { mountGame, poweredByIFLoom } from '@ifloom/react' import module from './game.ts' mountGame(module.build(), { pages: { splash: { cards: [ { id: 'studio', art: 'art/studio-logo.png', title: 'Harbour Games', text: 'presents' }, poweredByIFLoom(), { id: 'logo', art: 'art/logo.png' }, ], }, }, }) ``` A card shows its `art`, `title` and `text`, each optional. A card with a `component` renders that component instead, such as an animated logo or a short video. ## Set each card's time and transition [#set-each-cards-time-and-transition] Give a card `ms` for how long it holds, and `transition` for how it comes in and goes out. The transition names are the ones a scene uses, such as `fade`, `zoom` and `slide-up`: ```tsx import type { SplashCard } from '@ifloom/react' export const logo: SplashCard = { id: 'logo', art: 'art/logo.png', ms: 3000, transition: { in: 'zoom', out: 'fade', ms: 800 } } ``` A card holds for 2000 milliseconds and fades in and out over 600 milliseconds unless you say otherwise. A player who asks for reduced motion sees each card for its `ms` with no transitions. ## Make the cards unskippable [#make-the-cards-unskippable] The player skips a card with a click, Enter or Space, and all of them with Escape or the Skip button. Set `skippable: false` to make every card play out: ```tsx import { mountGame } from '@ifloom/react' import module from './game.ts' mountGame(module.build(), { pages: { splash: { cards: [{ id: 'studio', title: 'Harbour Games' }], skippable: false } } }) ``` ## Turn the cards off [#turn-the-cards-off] Set `splash: false` to open straight on the title screen, or on the [gate](https://ifloom.dev/docs/reference/react/components#gatepage) when there is one: ```tsx import { mountGame } from '@ifloom/react' import module from './game.ts' mountGame(module.build(), { pages: { splash: false } }) ``` A list of cards without `poweredByIFLoom()` also leaves the IFLoom card out. A game mounted without `pages` shows no splash cards. # Add panels, sections, components and hints (https://ifloom.dev/docs/how-to/react/extend-the-react-ui) This how-to is for `@ifloom/react`, the optional React UI. To render a game in plain DOM, Vue or React by hand, see [Start your own UI](https://ifloom.dev/docs/how-to/render/start). Use this when your game has a screen the React UI can't know about, such as a market stall with prices, an app's own screen, your own plugin's view or a hint of your own. You hand the UI a component by name, and it renders it in the right place. To change how a built-in part looks or replace it, see [Rearrange or replace the React UI's parts](https://ifloom.dev/docs/how-to/react/replace-parts). ## Give a scene a panel of its own [#give-a-scene-a-panel-of-its-own] A scene's [panel](https://ifloom.dev/docs/reference/panels#scenepanel) renders in place of its choices, for a stall with prices, a card game or a map. Name the panel in the scene, with what to render it with in `with`: ```ts import type { DataScene } from '@ifloom/engine' export const stall: DataScene = { id: 'market.stall', title: 'The bread stall', panel: { panel: 'prices', with: { loaf: 4 } }, body: [{ text: 'Loaves stacked high, and a chalkboard of prices.' }], choices: [ { id: 'buy', label: 'Buy a loaf', effects: [{ stat: 'coins', by: -4 }, { scene: null }] }, { id: 'leave', label: 'Walk on', effects: [{ scene: null }] }, ], } ``` Write the panel as a [`PanelComponent`](https://ifloom.dev/docs/reference/react/components#panelcomponent), and pass it in `panels` under the same name. It gets the panel's `with` as `data`, and sends the scene's own choices, so what happens stays content the engine checks: ```tsx given import { GameShell, useGame, type PanelComponent } from '@ifloom/react' import { Button, Card, CardContent, CardHeader, CardTitle } from '@ifloom/react/kit' const Prices: PanelComponent = ({ data }) => { const { send } = useGame() const prices = data as { loaf: number } return ( Today's bread ) } const panels = { prices: Prices } export const App = () => ``` The scene's title and body render above the panel as usual. A price that changes in play is better read in the component, from the view or a [value](https://ifloom.dev/docs/reference/custom#values), than written into `with`. The same `panels` render a panel content opens with the [`panel` effect](https://ifloom.dev/docs/reference/effects#panel), in [`PanelHost`](https://ifloom.dev/docs/reference/react/components#panelhost)'s dialog, and yours replace a [built-in panel](https://ifloom.dev/docs/reference/react/components#built-in-panels) or a plugin UI's of the same name. Keep these in mind for every panel: - **A panel with no component is left out**, with no warning. A scene shows its choices instead, and an app's section renders nothing. - **`data` is typed `unknown`.** Cast it to the shape you wrote in `with`. - **The component's own state isn't saved.** `useState` can keep what's in a basket, but finish with a command, which is. - **Define `panels` once**, outside any component. ## Render a panel in an app [#render-a-panel-in-an-app] An app's `{ panel }` [section](https://ifloom.dev/docs/reference/plugins/devices#section) renders the component of that name inside the app, with the section's `with` as `data`. Add it to the same `panels`: ```ts fragment sections: [{ panel: 'inbox', with: { unread: 1 } }] ``` ```tsx import type { PanelComponent } from '@ifloom/react' const Inbox: PanelComponent = ({ data }) =>

{(data as { unread: number }).unread} unread

export const panels = { inbox: Inbox } ``` ## Render a plugin's section in an app [#render-a-plugins-section-in-an-app] An app's `{ plugin }` section asks the UI to render that plugin's view inside the app. The messages and feed UIs bring renderers for their own. For any other plugin, pass a [`PluginSectionComponent`](https://ifloom.dev/docs/reference/react/components#pluginsectioncomponent) in `sections`, keyed by the plugin's id. It gets the plugin's slice of the view as `data`, and the section's `with`. This puts the loyalty card from [Write a plugin](https://ifloom.dev/docs/how-to/write-a-plugin) in an app on the laptop: ```ts fragment // In your content, with devices() in the game's plugins data: { devices: { devices: [{ id: 'laptop', name: 'Laptop', frame: 'laptop', sidebar: true }], apps: [{ id: 'card', name: 'Card', icon: 'card', on: 'laptop', sections: [{ plugin: 'loyalty' }] }], }, } ``` ```tsx given import { GameShell, type PluginSectionComponent } from '@ifloom/react' const LoyaltyCard: PluginSectionComponent = ({ data }) => { const card = data as { stamps: number } | undefined if (!card) return null return

{card.stamps} of 5 stamps

} const sections = { loyalty: LoyaltyCard } export const App = () => ``` Return nothing when `data` is `undefined`, as it is in a game without the plugin. To render messages or a feed your own way, register yours under `messages` or `feed`, and it replaces the plugin UI's. ## Show a plugin's view anywhere [#show-a-plugins-view-anywhere] A plugin's section works only inside an app. To show a plugin's view anywhere else, such as the loyalty card in the side column, read it in a component of your own and put that in your layout. The loyalty plugin declares its view in [`ViewRegistry`](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry), so `view.plugins.loyalty` comes typed: ```tsx import { Sidebar, Title, useGame } from '@ifloom/react' import { Badge } from '@ifloom/react/kit' function StampCount() { const { view } = useGame() const card = view.plugins.loyalty return card ? {card.stamps} stamps : null } export function Side() { return ( <StampCount /> </Sidebar> ) } ``` The component renders nothing in a game without the plugin, so the same layout works in both. ## Make your components part of the system [#make-your-components-part-of-the-system] Give your own elements their parts with [`usePart`](https://ifloom.dev/docs/reference/react/components#usepart), so a game's `classes`, `unstyled` and stylesheet reach them as they reach the built-in ones. Your classes are the defaults, and the game's apply over them: ```tsx import { useGame, usePart } from '@ifloom/react' export function Purse() { const { view } = useGame() const row = usePart('stat', 'flex justify-between text-sm') const value = usePart('stat-value', 'font-medium tabular-nums') return ( <p {...row} data-stat="coins"> In your pocket <span {...value}>{view.statsById.coins.text}</span> </p> ) } ``` The name has to be a [`PartKey`](https://ifloom.dev/docs/reference/react/components#partkey), so choose the built-in part your element is most like. For a kind of element the UI doesn't have, set `data-part` yourself, such as `<div data-part="weather">`, and style it with CSS. To let a game replace your component by name, make it with [`overridable`](https://ifloom.dev/docs/reference/react/components#overridable). It takes a built-in name, so use it for a component that stands in for a built-in one, such as a one-line stats bar you share between games: ```tsx import { useGame, usePart } from '@ifloom/react' import { overridable } from '@ifloom/react/kit' function StatsBarImpl() { const { view } = useGame() const list = usePart('stats', 'flex flex-wrap gap-4 text-sm') const value = usePart('stat-value', 'font-medium tabular-nums') return ( <p {...list}> {view.stats.map((stat) => ( <span key={stat.key} {...value} data-stat={stat.key}> {stat.label} {stat.text} </span> ))} </p> ) } export const StatsBar = overridable('StatList', StatsBarImpl) ``` A game that sets `components.StatList` gets its own component wherever `StatsBar` renders too, with `StatsBarImpl` as its `Default` there. A plugin UI adds names of its own instead, as [Write a plugin's React UI](https://ifloom.dev/docs/how-to/react/write-a-plugins-react-ui) shows. ## Style a section with a hint of your own [#style-a-section-with-a-hint-of-your-own] `Scene` renders the beats of a section with any ui hint in one `group` part, and copies each hint that's a string, a number or `true`/`false` onto it as a `data-*` attribute. A hint of your own is enough to style a whole section as a card. Declare it, so content that uses it is typed: ```ts // src/rules.ts, or any file the game imports declare module '@ifloom/engine' { interface BlockUi { /** Renders the section as a card of this kind. */ card?: 'result' | 'nudge' } } ``` Write it on a section, here the end of a shift at the café: ```ts import { text, type Block } from '@ifloom/engine' export const shiftEnd: Block[] = [ text('The lunch rush comes and goes.'), { blocks: [text('You made 30 coins.'), text('Ava says thanks.')], ui: { card: 'result' } }, ] ``` `Scene` renders the section as `<div data-part="group" data-card="result">` around both beats. Style it in your stylesheet: ```css [data-part="group"][data-card="result"] { border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); padding: 1rem; } ``` Tell [`checkUiHints`](https://ifloom.dev/docs/reference/react/hints#checkuihints) about the hint with `allow`, so it doesn't report a hint the React UI doesn't read: ```ts given import { checkUiHints } from '@ifloom/react' import { expect } from 'vitest' expect(checkUiHints(game, { allow: ['card'] })).toEqual([]) ``` A hint on a single block makes no group, since its beat is one element already. Wrap the block in `{ blocks: [...] }` to give it one. A hint that's an object or a list isn't copied. To render such a section with markup of your own, replace [`BeatGroup`](https://ifloom.dev/docs/reference/react/components#beatgroup) in `components`, which gets the section's hints as `section`. ## Add an inline piece of your own [#add-an-inline-piece-of-your-own] An inline piece is a [UI piece](https://ifloom.dev/docs/reference/prose#ui-pieces) in prose, `[[ui:name|words|arg]]`, which the React UI renders with the component of that name. Declare the name's arguments in `InlineUi`, write the component, and pass it in `inline`. One with a built-in name, such as `modal`, replaces it: ```tsx // src/main.tsx import { useState } from 'react' import { InlineTrigger, mountGame, type InlineComponents, type InlineProps } from '@ifloom/react' import { PartDialog } from '@ifloom/react/kit' import module from './game.ts' declare module '@ifloom/engine' { interface InlineUi { /** `[[ui:map|words|location]]` opens the town map with the location marked. */ map: [location: string] } } function TownMap({ text, args: [location] }: InlineProps<'map'>) { const [open, setOpen] = useState(false) return ( <> <InlineTrigger name="map" open={open} onOpen={() => setOpen(true)}>{text}</InlineTrigger> <PartDialog open={open} onClose={() => setOpen(false)} title="Small Town"> <img src={`art/map/${location}.svg`} alt={`The town map, with ${location} marked`} /> </PartDialog> </> ) } const inline: InlineComponents = { map: TownMap } mountGame(module.build(), { inline }) ``` A line such as `'A sign by the gate shows [[ui:map|where you are|park]].'` now opens the map. A name nothing declares still works, with `args` as text. A name that neither `inline` nor the built-ins have shows its words as plain text. The engine never sees a piece open, so nothing about it goes in a save or the log, and the backlog and a screen reader keep its words. Anything a piece sends with `send` is a command like any other, so write a piece that changes the game as an [inline action](https://ifloom.dev/docs/how-to/put-a-choice-in-a-line) instead. `ifloom build` doesn't check a file that a piece's argument names, so open each piece once in the game. ## Add more shadcn/ui components [#add-more-shadcnui-components] The kit exports the [shadcn/ui primitives](https://ifloom.dev/docs/reference/react/kit#shadcnui-primitives) the UI uses. For anything else shadcn/ui has, such as a slider or a select, add it to your project with shadcn/ui's CLI. Set the CLI up as its [Vite guide](https://ui.shadcn.com/docs/installation/vite) says, with the `@/` path alias and your stylesheet, then run: ```sh npx shadcn@latest add slider ``` This writes `src/components/ui/slider.tsx` and installs the Radix package it needs. It matches the UI with no more work, since `@ifloom/react/styles.css` defines the same CSS variables and maps them to Tailwind colours. Tidy what the CLI writes: - **Delete the variables it adds.** `shadcn init` writes `:root` and `.dark` variables and an `@theme` block into your stylesheet, which the UI's stylesheet already has. Keep only the ones you mean to override, after the import. - **Remove a second `@import "tailwindcss"`.** The UI's stylesheet imports Tailwind already. To keep your own import, use `@ifloom/react/theme.css` in place of `styles.css`, as [Theme the React UI](https://ifloom.dev/docs/how-to/react/theme-the-react-ui#bring-your-own-tailwindcss) shows. - **Use either `cn`.** The CLI's `lib/utils.ts` writes the same function as the kit's [`cn`](https://ifloom.dev/docs/reference/react/kit#cn). ## Check it worked [#check-it-worked] Run `npm run dev`. Open the bread stall, and the prices card renders in place of the choices. Finish a shift at the café, and the takings show in your result card. Choose the map's words in the park's line, and the map opens in a dialog. For more, see: - [Panels](https://ifloom.dev/docs/reference/panels) and [`PanelHost`](https://ifloom.dev/docs/reference/react/components#panelhost). - [Presentation hints](https://ifloom.dev/docs/reference/react/hints) and [`InlineUi`](https://ifloom.dev/docs/reference/react/hints#inlineui). - [Components](https://ifloom.dev/docs/reference/react/components#customising), for `usePart`, `overridable` and `UiProvider`. - [Show a popup](https://ifloom.dev/docs/how-to/show-a-popup), for a modal piece or a panel opened from a line. # Rearrange or replace the React UI's parts (https://ifloom.dev/docs/how-to/react/replace-parts) This how-to is for `@ifloom/react`, the optional React UI. To render a game in plain DOM, Vue or React by hand, see [Start your own UI](https://ifloom.dev/docs/how-to/render/start). Use this when the theme isn't enough and you want to move parts, render one differently, or build the page another way. Each step goes further than the one before. For sections that fold, parts shown only at some locations and the phone's drawer, see [Arrange the layout](https://ifloom.dev/docs/how-to/arrange-the-layout). For colours and CSS, see [Theme the React UI](https://ifloom.dev/docs/how-to/react/theme-the-react-ui). ## Rearrange the parts in layout.tsx [#rearrange-the-parts-in-layouttsx] The page is your layout, `src/layout.tsx`, which the `react` and `next` templates start as a copy of [`DefaultLayout`](https://ifloom.dev/docs/reference/react/components#defaultlayout) and pass to `mountGame` as `layout`. Every part on the page is a component in it, so move parts by editing the JSX. This layout puts the notices at the top of the story and the bag under it, and leaves the quests and the wardrobe out: ```tsx // src/layout.tsx import { Clock, Game, GameMenu, Notices, PanelHost, RoomActions, Scene, Section, Sidebar, StatList, Story, Title } from '@ifloom/react' import { InventoryCard } from '@ifloom/plugin-inventory/react' import { Exits } from '@ifloom/plugin-places/react' import { PeopleHere } from '@ifloom/plugin-cast/react' export function Layout() { return ( <Game> <Sidebar> <Title /> <Clock /> <StatList /> <GameMenu /> </Sidebar> <Story> <Notices /> <Scene /> <Exits /> <RoomActions /> <PeopleHere /> <Section id="inventory" title="In your bag" collapsible open={false}> <InventoryCard title={false} /> </Section> </Story> <PanelHost /> </Game> ) } ``` Keep these in mind as you move things: - **Delete a part where it was.** A component written twice renders twice. - **Keep somewhere for the notices.** With no `Overlay`, nothing floats over the page, so put `Notices` in the story or the side column. - **Keep `PanelHost`** if content opens [panels](https://ifloom.dev/docs/reference/panels). To put the side column on the right, use CSS. The `studio` preset does it with an `order` on the side column and a grid template on `[data-part="page"][data-has-sidebar]`. ## Replace a component everywhere [#replace-a-component-everywhere] Pass your own component in `components`, under the built-in one's name. It renders everywhere the UI renders that component, with the same props plus `Default`, the built-in one, so you can hand back the cases you don't change. This one renders a character's spoken lines and pictures its own way: ```tsx // src/main.tsx import type { SceneBeat } from '@ifloom/engine' import { mountGame, usePart, type Components } from '@ifloom/react' import type { Override } from '@ifloom/react/kit' import module from './game.ts' import './styles.css' const TownBeat: Override<{ beat: SceneBeat }> = ({ beat, Default }) => { const line = usePart('beat', 'border-l-2 border-speech pl-4 leading-prose italic') const picture = usePart('beat', 'mx-auto max-w-md rotate-1 rounded-lg shadow-card') if (beat.type === 'say' && beat.who === 'character') { return <blockquote {...line} data-beat="say" data-who="character">{beat.text}</blockquote> } if (beat.type === 'image') return <img {...picture} data-beat="image" src={beat.src} alt={beat.alt ?? ''} /> return <Default beat={beat} /> } const components: Components = { Beat: TownBeat } mountGame(module.build(), { components }) ``` [`Components`](https://ifloom.dev/docs/reference/react/components#components) lists every name you can replace, and a plugin UI adds its own, such as `ShopCounter`, once you import its `/react`. A replacement applies everywhere. The `Beat` above renders the [backlog](https://ifloom.dev/docs/reference/react/components#backlog)'s beats too, and a replaced `ChoiceButton` renders a scene's choices, the room's actions and the buttons in the plugins' UIs. Follow three rules in a replacement: - **Keep the `data-part`.** Spread [`usePart`](https://ifloom.dev/docs/reference/react/components#usepart)'s result onto your element, so CSS, `classes` and `unstyled` still reach it. Add the [identity attributes](https://ifloom.dev/docs/reference/react/parts#identity-attributes) your CSS uses, such as `data-beat`. - **Render the built-in one through `Default`.** Importing `Beat` from `@ifloom/react` inside your `Beat` gives your replacement again, which calls itself forever. - **Define `components` once**, outside any component. A new object on each render renders everything under the provider again. [`Icon`](https://ifloom.dev/docs/reference/react/components#icon) is the smallest one to replace. It renders every icon the UI uses, so one component swaps the whole set: ```tsx import type { Components } from '@ifloom/react' import type { IconName } from '@ifloom/react/kit' const GLYPHS: Record<IconName, string> = { close: '×', back: '←', warning: '!', voice: '♪', zoom: '+', menu: '≡', chevron: '›' } const components: Components = { Icon: ({ name, label }) => <span aria-label={label} aria-hidden={label ? undefined : true}>{GLYPHS[name]}</span>, } ``` ## Render the scene your own way [#render-the-scene-your-own-way] To restyle the scene's heading, a section with ui hints or a fold, replace [`SceneHeader`](https://ifloom.dev/docs/reference/react/components#sceneheader), [`BeatGroup`](https://ifloom.dev/docs/reference/react/components#beatgroup) or [`Fold`](https://ifloom.dev/docs/reference/react/components#fold). `Scene` times its transitions, reveals and dice around those parts, so the motion stays. For a scene laid out quite differently, write your own `Scene` on [`useScene`](https://ifloom.dev/docs/reference/react/components#usescene), which works out the same timing and renders nothing, and pass it as `components.Scene`: ```tsx import { Beat, ChoiceList, useScene, type Components } from '@ifloom/react' function Chapter() { const { view, transition, groups, pending, skip } = useScene() return ( <article key={transition.key} data-transition-in={transition.in} onClick={pending ? skip : undefined}> <h2 className="font-heading text-scene-title">{view.scene.title}</h2> {groups.map((group, n) => ( <div key={n} data-reveal={group.reveal?.as} style={{ animationDelay: `${group.reveal?.at ?? 0}ms` }}> {group.beats.map(({ beat, index }) => <Beat key={index} beat={beat} />)} </div> ))} {pending ? null : <ChoiceList choices={view.scene.choices} />} </article> ) } const components: Components = { Scene: Chapter } ``` ## Render a minigame your own way [#render-a-minigame-your-own-way] `Scene` renders a running minigame with [`MinigameCard`](https://ifloom.dev/docs/reference/react/components#minigamecard). Replace it in one of two ways: - **For one minigame**, put a component in `panels` under the minigame's id. `Scene` renders it instead, with the [`MinigameView`](https://ifloom.dev/docs/reference/minigames#minigameview) as `data`, and runs the clock for it. Call [`useMinigame`](https://ifloom.dev/docs/reference/react/components#useminigame) in it for `send`. - **For every minigame**, replace `MinigameCard` in `components`. This renders the coconut shy with a component of its own, and every other minigame in a thick frame: ```tsx given import { GameShell, type Components, type PanelComponent } from '@ifloom/react' import { CoconutShy } from './coconut-shy.tsx' const Coconuts: PanelComponent = () => <CoconutShy /> const panels = { coconut: Coconuts } const components: Components = { MinigameCard: ({ Default }) => <div className="rounded-xl border-4 p-4"><Default /></div>, } export const App = () => <GameShell runner={runner} panels={panels} components={components} /> ``` [Build a minigame](https://ifloom.dev/docs/how-to/build-a-minigame) writes a minigame's panel. ## Change the shape of the page [#change-the-shape-of-the-page] The regions are components too. [`Game`](https://ifloom.dev/docs/reference/react/components#game) renders the `page` part, a grid of the side column and the story when it has a `Sidebar`, and one centred column without. Anything inside it renders in order, so a header bar is a `<header>` before the story: ```tsx // src/layout.tsx import { Clock, Game, GameMenu, InputFields, Notices, Overlay, PanelHost, RoomActions, Scene, StatList, Story, Title } from '@ifloom/react' export function Layout() { return ( <Game className="max-w-(--width-reading)"> <header className="flex flex-wrap items-center gap-4 border-b pb-2"> <Title /> <Clock /> <StatList /> <GameMenu /> </header> <Story> <Scene /> <InputFields /> <RoomActions /> </Story> <PanelHost /> <Overlay className="fixed top-4 right-4 bottom-auto"> <Notices /> </Overlay> </Game> ) } ``` Every region takes `className`, merged over its own classes, and `classes` reaches the regions by their parts, `page`, `sidebar`, `story` and `overlay`. Below 48rem, `Sidebar` renders the side column as a drawer behind a menu button. To keep a column on a phone too, leave `Sidebar` out and render your own `<aside>` with the parts in it. ## Write your own root [#write-your-own-root] For a page that isn't a side column and a story at all, pass any component as `layout`. It renders inside the game's provider, with the sound, the text size and the pages as the default layout has them, so [`useGame`](https://ifloom.dev/docs/reference/react/components#usegame), the hooks and every built-in part work in it: ```tsx // src/main.tsx import { InputFields, Notices, Scene, mountGame, useGame, useSaves } from '@ifloom/react' import module from './game.ts' import './styles.css' function TownApp() { const { view, runner } = useGame() const saves = useSaves() return ( <div className="mx-auto flex max-w-2xl flex-col gap-6 p-6"> <h1 className="font-heading text-title">{view.title}</h1> <Scene /> <InputFields /> <footer className="flex gap-3 text-sm"> {saves.available ? <button onClick={() => void saves.save('Quick save')}>Quick save</button> : null} <button disabled={!runner.snapshot().canUndo} onClick={() => runner.undo()}>Undo</button> </footer> <Notices className="fixed right-4 bottom-4 w-80" /> </div> ) } mountGame(module.build(), { layout: TownApp }) ``` `components`, `classes` and `unstyled` still apply to every built-in part you use. Each part reads the view itself, so leave out any part or use one twice. A part with nothing to show renders nothing, such as `Inventory` when the player holds nothing, and a plugin's part renders nothing without its plugin. Keep [`InputFields`](https://ifloom.dev/docs/reference/react/components#inputfields) unless the game has no [inputs](https://ifloom.dev/docs/reference/inputs), since nothing else in the UI takes the value outside a scene. These hooks give the menus' state and actions with no look, so your own screens don't talk to the runner directly: | Key | Meaning | |---|---| | [`useSaves`](https://ifloom.dev/docs/reference/react/components#usesaves) | The save slots, and saving, loading, deleting, exporting and importing them. | | [`useBacklog`](https://ifloom.dev/docs/reference/react/components#usebacklog) | The backlog's entries, kept current. | | [`useMods`](https://ifloom.dev/docs/reference/react/components#usemods) | The player's mods, and adding, turning on and off and removing them. | | [`useWords`](https://ifloom.dev/docs/reference/react/components#usewords) | The UI's words in the game's language. | | [`useDevice`](https://ifloom.dev/docs/reference/plugins/devices#usedevice) | The device that is out, and bringing one out and putting it away. | A button of your own that sends a command should send the `command` a [`ChoiceButton`](https://ifloom.dev/docs/reference/react/components#choicebutton) or the view's `RenderedChoice` carries, rather than one it builds, so a greyed-out button and a refusal never disagree. ## Use the provider without GameShell [#use-the-provider-without-gameshell] `mountGame` and [`GameShell`](https://ifloom.dev/docs/reference/react#gameshell) add the sound, the text size and the pages around the layout. To render the React UI inside a page of your own React app, wrap it in a [`GameProvider`](https://ifloom.dev/docs/reference/react/components#gameprovider) instead, with a [`TooltipProvider`](https://ifloom.dev/docs/reference/react/kit#tooltip) if anything in it uses tooltips: ```tsx given import { createRoot } from 'react-dom/client' import { GameProvider, InputFields, Notices, Scene, StatList } from '@ifloom/react' import { TooltipProvider } from '@ifloom/react/kit' import { questsUi } from '@ifloom/plugin-quests/react' const plugins = [questsUi] createRoot(document.getElementById('root')!).render( <GameProvider runner={runner} plugins={plugins}> <TooltipProvider> <main className="mx-auto grid max-w-5xl gap-6 p-4 md:grid-cols-[1fr_16rem]"> <Scene /> <StatList /> <InputFields /> <Notices className="fixed right-4 bottom-4 w-80" /> </main> </TooltipProvider> </GameProvider>, ) ``` The provider takes the same `plugins`, `panels`, `sections`, `inline` and [`UiOptions`](https://ifloom.dev/docs/reference/react/components#uioptions) as `mountGame`. Make the runner with [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner) to keep saves and settings in the browser. ## Check it worked [#check-it-worked] Run `npm run dev`. The notices show at the top of the story, a character's lines render as your block quotes, and the backlog's lines match them. Open the backlog from the menu to see the same `Beat` there. For more, see: - [Components](https://ifloom.dev/docs/reference/react/components), for every part, hook and region. - [`Components`](https://ifloom.dev/docs/reference/react/components#components), [`Override`](https://ifloom.dev/docs/reference/react/components#override) and [`usePart`](https://ifloom.dev/docs/reference/react/components#usepart). - [Add panels, sections, components and hints](https://ifloom.dev/docs/how-to/react/extend-the-react-ui), to make your own components replaceable. - [Choosing a UI](https://ifloom.dev/docs/explanation/choosing-a-ui), for when to leave the React UI for one of your own. # Set up the React UI (https://ifloom.dev/docs/how-to/react/set-up-the-react-ui) This how-to is for `@ifloom/react`, the optional React UI. To render a game in plain DOM, Vue or React by hand, see [Start your own UI](https://ifloom.dev/docs/how-to/render/start). Use this to render a game with the React UI in a project that doesn't have it yet. A game made from the `react` template has every file below already, as [Create a game](https://ifloom.dev/docs/how-to/create-a-game) shows. You need a [game module](https://ifloom.dev/docs/reference/cli#the-game-module) in `src/game.ts` first, which [Add IFLoom to an existing project](https://ifloom.dev/docs/how-to/add-to-a-project) writes. ## Install the packages [#install-the-packages] Install the UI beside the engine, with React and the tools that build its stylesheet: ```sh tab="npm" tab-group="package-manager" npm install @ifloom/react @ifloom/audio @ifloom/browser react react-dom npm install --save-dev @vitejs/plugin-react @tailwindcss/vite tailwindcss @types/react @types/react-dom ``` ```sh tab="pnpm" tab-group="package-manager" pnpm add @ifloom/react @ifloom/audio @ifloom/browser react react-dom pnpm add -D @vitejs/plugin-react @tailwindcss/vite tailwindcss @types/react @types/react-dom ``` ```sh tab="yarn" tab-group="package-manager" yarn add @ifloom/react @ifloom/audio @ifloom/browser react react-dom yarn add -D @vitejs/plugin-react @tailwindcss/vite tailwindcss @types/react @types/react-dom ``` ```sh tab="bun" tab-group="package-manager" bun add @ifloom/react @ifloom/audio @ifloom/browser react react-dom bun add -d @vitejs/plugin-react @tailwindcss/vite tailwindcss @types/react @types/react-dom ``` The UI needs `@ifloom/audio` and `@ifloom/browser`, React 19, react-dom and Tailwind CSS v4, which are its peer dependencies. npm and pnpm would install the two `@ifloom` packages for you, but Yarn doesn't, so the commands name them. React's types are peers too, and your own `.tsx` files use them. A game that uses the [prebuilt stylesheet](https://ifloom.dev/docs/how-to/react/theme-the-react-ui#use-the-prebuilt-stylesheet) needs neither Tailwind package. Install each plugin your game uses beside it, as [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin) shows. ## Set up TypeScript [#set-up-typescript] Turn on JSX, the DOM and Vite's client types in `tsconfig.json`, beside the settings you have: ```json { "compilerOptions": { "jsx": "react-jsx", "lib": ["ES2023", "DOM", "DOM.Iterable"], "types": ["@ifloom/cli/client"] } } ``` `@ifloom/cli/client` holds Vite's browser types, so TypeScript accepts `import './styles.css'` and `import.meta.env`. ## Add the Vite plugins [#add-the-vite-plugins] List React's and Tailwind's Vite plugins in the [CLI's preset](https://ifloom.dev/docs/reference/cli#the-vite-preset), which builds one HTML file that opens from disk: ```ts // vite.config.ts import tailwindcss from '@tailwindcss/vite' import react from '@vitejs/plugin-react' import { ifloom } from '@ifloom/cli/vite' export default ifloom({ vite: { plugins: [react(), tailwindcss()], resolve: { dedupe: ['react', 'react-dom'] } } }) ``` `dedupe` keeps one copy of React when `@ifloom/react` is linked from a checkout. To build without the CLI, see [Ship your game](https://ifloom.dev/docs/how-to/ship-your-game). ## Write the stylesheet [#write-the-stylesheet] Import the UI's stylesheet, then a theme preset if you want one: ```css /* src/styles.css */ @import "@ifloom/react/styles.css"; @import "@ifloom/react/themes/paper.css"; ``` The UI's stylesheet imports Tailwind and tells it to scan the UI's components, so don't `@import "tailwindcss"` a second time. Tailwind also finds the classes in your own files, so your components can use its utilities. [Theme the React UI](https://ifloom.dev/docs/how-to/react/theme-the-react-ui) lists the presets and everything else you can change. ## Mount the game [#mount-the-game] Call [`mountGame`](https://ifloom.dev/docs/reference/react#mountgame) with what the game module's `build()` returns, in `src/main.ts`: ```ts // src/main.ts import { mountGame } from '@ifloom/react' import module from './game.ts' import { Layout } from './layout.tsx' import './styles.css' mountGame(module.build(), { layout: Layout }) ``` `src/layout.tsx` is the page, a copy of [`DefaultLayout`](https://ifloom.dev/docs/reference/react/components#defaultlayout) for you to change. Copy it from the `react` template, or leave `layout` out to use the default as it is. `mountGame` logs the content checker's problems as warnings, then renders into `#root`. ## Add index.html [#add-indexhtml] Give the page a `#root` element and load the entry: ```html <!-- index.html --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Small Town
``` ## Check it worked [#check-it-worked] Run `npx ifloom dev` and open the address it prints. The game's title is in the side column and the first scene is in the story. Run `npx ifloom build` and open `dist/index.html` from disk: the same page plays with no server. For more, see: - [The React UI](https://ifloom.dev/docs/reference/react) and [`MountOptions`](https://ifloom.dev/docs/reference/react#mountoptions). - [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis), to render your plugins. - [Add a title screen](https://ifloom.dev/docs/how-to/add-a-title-screen), to open on one with the `pages` option. - [Choosing a UI](https://ifloom.dev/docs/explanation/choosing-a-ui), for when to use the React UI. # Show plugins in the React UI (https://ifloom.dev/docs/how-to/react/show-plugin-uis) This how-to is for `@ifloom/react`, the optional React UI. To render a game in plain DOM, Vue or React by hand, see [Start your own UI](https://ifloom.dev/docs/how-to/render/start). Use this to put your game's plugins on screen in the React UI. The UI names no plugin. Each first-party plugin with something for the player ships its React UI in its own `/react` subpath, such as `@ifloom/plugin-shop/react`, and you list the ones you want. You need the plugins in the game first, as [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin) shows. ## List the plugin UIs [#list-the-plugin-uis] Import each plugin's `Ui` from its `/react` subpath and pass them to `mountGame` as `plugins`: ```ts // src/main.ts import { mountGame } from '@ifloom/react' import { placesUi } from '@ifloom/plugin-places/react' import { questsUi } from '@ifloom/plugin-quests/react' import { shopUi } from '@ifloom/plugin-shop/react' import module from './game.ts' import { Layout } from './layout.tsx' import './styles.css' mountGame(module.build(), { layout: Layout, plugins: [placesUi, questsUi, shopUi] }) ``` Each [plugin UI](https://ifloom.dev/docs/reference/react/kit#pluginui) brings its panels, its words, a page or settings if it has them, and the parts the layout places, in the order of the list. [`GameShell`](https://ifloom.dev/docs/reference/react#gameshell) and [`GameProvider`](https://ifloom.dev/docs/reference/react/components#gameprovider) take the same `plugins`. Follow these rules for the list: - **List every plugin UI you want.** The UI finds none by itself, so a plugin UI you leave out never renders. - **List one for a plugin the game lacks if you like.** It renders nothing, so the debug plugin's `debugUi` can stay in the list of a release built without the plugin. - **Define the list once**, outside any component, so it's the same list on every render. Your own `panels`, `sections`, `inline` and `components` win over what a plugin UI brings under the same name. ## Know where the default layout puts them [#know-where-the-default-layout-puts-them] A plugin UI's `layout` names the [spot](https://ifloom.dev/docs/reference/react/kit#pluginspot) each of its parts goes in. [`DefaultLayout`](https://ifloom.dev/docs/reference/react/components#defaultlayout), and the `src/layout.tsx` the templates copy from it, has a [`Plugins`](https://ifloom.dev/docs/reference/react/kit#plugins) at each spot, which renders the listed plugin UIs' parts for it in the order of the list. The quests UI's log goes in the `sidebar` spot, the places UI's exits in `room`, and the cast UI's people here in `story`. A panel, a page, a section in an app and a plugin's settings need no spot. [`PanelHost`](https://ifloom.dev/docs/reference/react/components#panelhost), the pages, the devices' apps and the menu render them by name. ## Place them in a layout of your own [#place-them-in-a-layout-of-your-own] Put a `Plugins` wherever your layout wants a spot's parts, or render a plugin's components yourself, in any order. This side column has the quest log in a section of its own, then the other plugins' side-column parts: ```tsx // src/layout.tsx import { Game, Plugins, Scene, Section, Sidebar, StatList, Story, Title } from '@ifloom/react' import { QuestLog } from '@ifloom/plugin-quests/react' export function Layout() { return ( <StatList /> <Section id="journal" title="Journal" collapsible> <QuestLog title={false} /> </Section> <Plugins at="sidebar" /> </Sidebar> <Story> <Scene /> <Plugins at="room" /> <Plugins at="story" /> </Story> </Game> ) } ``` A component you place by hand still renders once a `Plugins` renders it too, so here the quests UI renders its log twice. List the quests UI without its layout to stop that, as the next step does. The showcase's `examples/showcase/src/layout.tsx` places every plugin's parts by hand. ## Leave out one thing a plugin UI brings [#leave-out-one-thing-a-plugin-ui-brings] A plugin UI is a plain object, so spread it without the field you don't want. This keeps the quests UI's words and panel, with its log only where the layout above puts it: ```ts import { questsUi } from '@ifloom/plugin-quests/react' export const plugins = [{ ...questsUi, layout: undefined }] ``` The same works for `pages`, `panels` or `settings`, such as `{ ...achievementsUi, pages: undefined }` to keep the achievements in a dialog with pages on. [`PluginUi`](https://ifloom.dev/docs/reference/react/kit#pluginui) lists every field. ## Render a plugin yourself [#render-a-plugin-yourself] Leave a plugin's UI out of `plugins`, and the React UI renders nothing for it, so a component of yours can. Each plugin's `/react` exports a hook that gives the plugin's view and its commands with no markup, such as [`useQuests`](https://ifloom.dev/docs/reference/plugins/quests#usequests) and [`useShop`](https://ifloom.dev/docs/reference/plugins/shop#useshop). This line shows the quest the player tracks: ```tsx import { useQuests } from '@ifloom/plugin-quests/react' export function Objective() { const quests = useQuests() const quest = quests?.active[0] if (!quest?.tracked) return null return ( <p className="text-sm"> <strong>{quest.name}</strong> {quest.hint} </p> ) } ``` Put the component in your layout as any other. The hook returns `null` in a game without the plugin, so the component renders nothing there. A component can read `useGame().view.plugins.<id>` instead, typed by the plugin's [`ViewRegistry`](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry) entry once the game imports the plugin. Send the `command` of each `RenderedChoice` the view offers, so your button and the engine agree on what's refused. [Build a HUD](https://ifloom.dev/docs/how-to/build-a-hud) builds more pieces this way. ## Style them with the theme [#style-them-with-the-theme] The presets style the kit's parts that every plugin UI marks its own with, so a plugin UI looks right in every preset with no work from you. To restyle one, write CSS on its `data-part` names, listed under [the plugins' parts](https://ifloom.dev/docs/reference/react/parts#the-plugins-parts), or on `data-kit` to change every plugin's cards at once. Importing a plugin's `/react` adds its parts to `classes` and its components to `components`, typed. [Theme the React UI](https://ifloom.dev/docs/how-to/react/theme-the-react-ui#style-parts-with-css) shows both. ## Check it worked [#check-it-worked] Run `npm run dev`. The quest log is in the Journal section of the side column, the exits are under the scene, and opening the café's counter shows the shop's dialog. For more, see: - [Plugin UIs and the kit](https://ifloom.dev/docs/reference/react/kit), with [`Plugins`](https://ifloom.dev/docs/reference/react/kit#plugins), [`PluginSpot`](https://ifloom.dev/docs/reference/react/kit#pluginspot) and [`PluginUi`](https://ifloom.dev/docs/reference/react/kit#pluginui). - Each plugin's page under [Plugins](https://ifloom.dev/docs/reference/plugins), whose `## React UI` lists its components and hook. - [Write a plugin's React UI](https://ifloom.dev/docs/how-to/react/write-a-plugins-react-ui), for a plugin of your own. - The [Render it yourself](https://ifloom.dev/docs/how-to/render/start) pages, for every plugin's view in any framework. # Theme the React UI (https://ifloom.dev/docs/how-to/react/theme-the-react-ui) This how-to is for `@ifloom/react`, the optional React UI. To render a game in plain DOM, Vue or React by hand, see [Start your own UI](https://ifloom.dev/docs/how-to/render/start). Use this to change how the React UI looks without changing what it renders. The steps go from the smallest change to the biggest, so stop when the game looks right. The first five are CSS in `src/styles.css`. To move parts or replace components, see [Rearrange or replace the React UI's parts](https://ifloom.dev/docs/how-to/react/replace-parts). ## Choose a preset [#choose-a-preset] A preset is a stylesheet that sets the fonts, the sizes, the colours and the shape of the page. Import one after the UI's own stylesheet: ```css /* src/styles.css */ @import "@ifloom/react/styles.css"; @import "@ifloom/react/themes/storybook.css"; ``` | Key | Meaning | |---|---| | `paper` | A printed book. A serif page in one centred column, chapter titles in small caps, choices as underlined lines of text, and the stats as a quiet line at the foot. The Letter (`examples/novel`) uses it. | | `terminal` | A green-screen text adventure. Monospace throughout, light text on black, square corners, choices as a numbered prompt list, and notices as a status line across the top that pushes the page down. | | `studio` | A clean, modern app. Cards on a soft grey page, the side column on the right, bold headings, choices as raised cards, and the reading column kept to the start of the story. The Corner Café (`examples/cafe`) uses it. | | `storybook` | Soft and friendly. Rounded type, a warm tinted page, big pill buttons, and dialogue in speech bubbles. The showcase uses it. | [`ifloom new`](https://ifloom.dev/docs/reference/cli#ifloom-new) writes this import, with the preset you name in `--theme`, or one at random when you name none. With no preset, the UI renders in a system sans-serif, in neutral colours, with the side column on the left. A preset is plain CSS that sets the tokens below and styles a few parts. It styles the UI's own parts and the [kit's parts](https://ifloom.dev/docs/reference/react/kit#kitpart), never a plugin's own by name, so every plugin's UI looks right in every preset. Read yours in `node_modules/@ifloom/react/src/themes/` to see what it changes, or copy it into `src/styles.css` as the start of your own. ## Set tokens and colours [#set-tokens-and-colours] The UI takes every font, size, gap and colour from CSS variables. Set them on `:root`, after the imports: ```css @import "@ifloom/react/styles.css"; @import "@ifloom/react/themes/storybook.css"; :root { --primary: oklch(0.55 0.12 230); --font-heading: Georgia, "Times New Roman", serif; --width-sidebar: 20rem; --gap-beats: 1.25rem; } ``` These are the design tokens, with their defaults: | Key | Meaning | |---|---| | `--font-body` | The font for everything, the system sans-serif by default. | | `--font-heading` | The font of the game's title, scene titles and card headings, `var(--font-body)` by default. | | `--text-title` | The size of the game's title, `1.125rem` by default. | | `--text-scene-title` | The size of a scene's title, `1.5rem` by default. | | `--leading-prose` | The line height of a scene's text, `1.625` by default. | | `--shadow-card` | The shadow under notices, which the presets use for their cards too. | | `--width-prose` | The width of the story's reading column, `70ch` by default. Pictures and panels use the whole story. | | `--margin-prose` | The reading column's `margin-inline`, `auto` by default, which centres it. `0 auto` keeps it to the start, and [`Story`](https://ifloom.dev/docs/reference/react/components#story)'s `align` wins over it. | | `--width-reading` | The page's widest without a side column, `42rem` by default. With one, the page is as wide as the window. | | `--width-sidebar` | The side column's width on a wide screen, `18rem` by default. | | `--width-notice` | The width of the notices in the bottom corner, `20rem` by default. | | `--gap-page` | The space between the side column and the story, and between parts in the story, `1.5rem` by default. | | `--gap-beats` | The space between the paragraphs and lines of a scene, `0.75rem` by default. | The colours are shadcn/ui's, with three of the UI's own at the end: | Key | Meaning | |---|---| | `--background`, `--foreground` | The page and its text. | | `--card`, `--card-foreground` | Cards, notices and letters in a scene. | | `--popover`, `--popover-foreground` | Tooltips and popovers. | | `--primary`, `--primary-foreground` | Primary buttons, badges, and the player's side of a message thread. | | `--secondary`, `--secondary-foreground` | Choice buttons, and the other side of a message thread. | | `--muted`, `--muted-foreground` | Quiet text, such as tags, stat labels and the reason a button is greyed out. | | `--accent`, `--accent-foreground` | Hovered buttons and app icons. | | `--destructive`, `--destructive-foreground` | App badges, errors, and a choice's `irreversible` line. | | `--border`, `--input`, `--ring` | Borders, inputs and the focus ring. | | `--radius` | Corner rounding. The UI works the smaller and larger radii out from it. | | `--speech` | A character's spoken line. | | `--player-speech` | The player's spoken line. | | `--price` | A price on a button. | Each colour and token is a Tailwind class too, so `text-speech`, `bg-primary`, `font-heading` and `shadow-card` work in your own components. ## Add a dark mode [#add-a-dark-mode] The stylesheet has a light set of colours and a dark set. The dark set applies inside an element with the class `dark`, as in shadcn/ui, so put `class="dark"` on `<html>` to turn it on. Set your own dark colours under `.dark`: ```css .dark { --primary: oklch(0.75 0.1 230); } ``` A preset sets its colours on `:root`, and they apply whether `dark` is on or not. `terminal` is dark already. To give another preset a dark version, write your `.dark` colours after its import, so they come later and win. ## Bundle a font [#bundle-a-font] The tokens name fonts already on the player's computer, such as `ui-serif, Georgia, serif`. A built game opens from disk and fetches nothing while it runs, so a font from Google Fonts or another server won't load. Put the font file in `src/` instead, and point an `@font-face` at it with a relative URL. Vite bundles it with the game: ```css @font-face { font-family: "Riverside"; src: url("./fonts/riverside.woff2") format("woff2"); font-display: swap; } :root { --font-heading: "Riverside", Georgia, serif; } ``` Check that the font's licence lets you ship it inside a game. ## Style parts with CSS [#style-parts-with-css] Every element the UI renders carries a `data-part` attribute that names it, such as `scene-title`, `choice` or `stat-value`. Write ordinary CSS against them, with the [identity attributes](https://ifloom.dev/docs/reference/react/parts#identity-attributes) to pick one of several: ```css [data-part="scene-title"] { font-variant: small-caps; letter-spacing: 0.04em; } [data-part="choice"] { border-radius: 0; border-left: 4px solid var(--primary); } /* The player's own lines, set apart */ [data-part="beat"][data-beat="say"][data-who="player"] { font-style: italic; } /* Ava's name in the café's colour */ [data-part="person"][data-person="ava"] [data-part="person-name"] { color: oklch(0.5 0.12 40); } /* Low energy shows in red */ [data-part="stat"][data-stat="energy"] [data-part="stat-value"] { color: var(--destructive); } ``` [React UI parts](https://ifloom.dev/docs/reference/react/parts) lists every part and the attributes each carries. A device's dialog carries `data-frame` and each app icon `data-icon`, so a stylesheet can draw a phone's bezel or map an icon's name to a picture. A plugin UI's part carries `data-kit` too when it's like one of the [kit's parts](https://ifloom.dev/docs/reference/react/kit#kitpart): a vendor's good, a job and an achievement are each a `card`. Style the kit's part to restyle all of them at once, whichever plugin rendered them: ```css [data-kit="card"] { border-radius: 0; border-width: 0 0 1px; } /* An earned achievement, or anything else that's done */ [data-kit="card"][data-state="done"] { background: var(--secondary); } ``` :::warning[Keep your rules out of a layer] Your CSS beats the built-in classes with no `!important`, because Tailwind puts its classes in a [cascade layer](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) called `utilities`, and CSS outside any layer wins over CSS inside one. A rule you put inside an `@layer`, such as `@layer components`, is layered too, and Tailwind's `utilities` layer comes after it and wins. ::: ## Change the built-in classes [#change-the-built-in-classes] Pass `classes` to change the Tailwind classes on a part, keyed by its `data-part` name: ```ts import { mountGame, type Classes } from '@ifloom/react' import module from './game.ts' import './styles.css' const classes: Classes = { // A string is merged with the built-in classes, and yours win where they clash. 'scene-title': 'text-3xl tracking-tight', choice: 'rounded-none', // A function gets the built-in classes and returns the ones to use. stats: () => 'flex flex-wrap gap-x-4 text-xs uppercase', } mountGame(module.build(), { classes }) ``` The UI merges a string with [tailwind-merge](https://github.com/dcastil/tailwind-merge), as [`cn`](https://ifloom.dev/docs/reference/react/kit#cn) does, so `rounded-none` replaces the button's `rounded-md` and every other class stays. A function gets the built-in classes as one string, and its result replaces them. Where several elements share a name, such as `button` or `beat`, the classes go on all of them. ## Start from no classes [#start-from-no-classes] Pass `unstyled: true` to drop every built-in class. The elements, their `data-part`s and their behaviour stay, ready for your CSS or your `classes`: ```ts import { mountGame } from '@ifloom/react' import module from './game.ts' mountGame(module.build(), { unstyled: true, classes: { page: 'mx-auto max-w-prose p-6', choice: 'block w-full py-2 text-left underline-offset-4 hover:underline', }, }) ``` With `unstyled`, a string in `classes` is all the part gets, since nothing is left to merge with. The tokens and colours stay, so the page keeps its background and text colour. A few inner wrappers with no `data-part` of their own keep their layout classes, such as the span around a choice's label, and so do the shadcn/ui primitives inside a part, such as the backlog's scroll area. ## Bring your own `tailwindcss` [#bring-your-own-tailwindcss] When your game has its own Tailwind set-up, import `@ifloom/react/theme.css` in place of `styles.css`. It holds the tokens, the colours, dark mode and the `@source` line that makes Tailwind scan the UI's components, with no `@import "tailwindcss"`: ```css @import "tailwindcss"; @import "@ifloom/react/theme.css"; ``` To leave out Tailwind's preflight, its CSS reset, import its theme and utilities on their own: ```css @layer theme, base, components, utilities; @import "tailwindcss/theme.css" layer(theme); @import "tailwindcss/utilities.css" layer(utilities); @import "@ifloom/react/theme.css"; ``` `theme.css` sets no page background or text colour. Add them yourself: ```css body { background: var(--background); color: var(--foreground); } ``` The first-party plugins' UIs use only classes the UI's own components use, so they need nothing more. A plugin of someone else's that ships a stylesheet says so in its README. Import it after this one. ## Use the prebuilt stylesheet [#use-the-prebuilt-stylesheet] `@ifloom/react/styles.min.css` is `styles.css` already run through Tailwind and minified, and each preset has a prebuilt copy beside it. Import them in `src/main.ts` in place of `src/styles.css`: ```ts // src/main.ts import '@ifloom/react/styles.min.css' import '@ifloom/react/themes/paper.min.css' ``` Then take `tailwindcss()` out of `vite.config.ts`, and `tailwindcss` and `@tailwindcss/vite` out of your dev dependencies. Tokens, presets and rules on `data-part` and `data-kit` work as before, from a stylesheet of your own imported after these. The `classes` option has only the classes the UI already uses, since nothing builds new ones, so restyle with CSS instead. ## Make it look like no other IFLoom game [#make-it-look-like-no-other-ifloom-game] A new colour on the same shapes still looks like the same game. Shape and type make a game look like itself: - **Choose a preset that fits the game**, or copy one into `src/styles.css` and change it. - **Change the fonts.** A serif, a rounded face or a monospace changes the feel more than any colour. Bundle a font file if no system font fits. - **Change the layout.** Move the side column, drop it, put the stats under the scene, or move the notices. [Rearrange or replace the React UI's parts](https://ifloom.dev/docs/how-to/react/replace-parts#change-the-shape-of-the-page) changes the shape of the page. - **Change how choices look.** The player looks at them most. Lines of text, numbered prompts, cards and pills each make a different game. - **Replace one or two components** that matter to your story, such as `Beat` for the way people talk, or `Notice` for news. ## Check it worked [#check-it-worked] Run `npm run dev`. The page takes the preset's fonts and shape, a choice shows your border, and the player's own lines are in italics. Put `class="dark"` on `<html>` in the browser's developer tools, and the page switches to your dark colours. For more, see: - [React UI parts](https://ifloom.dev/docs/reference/react/parts), for every `data-part` and the attributes it carries. - [`Classes`](https://ifloom.dev/docs/reference/react/components#classes) and [`UiOptions`](https://ifloom.dev/docs/reference/react/components#uioptions). - [Kit parts](https://ifloom.dev/docs/reference/react/kit#kit-parts), for the parts the presets style in every plugin UI. - [Arrange the layout](https://ifloom.dev/docs/how-to/arrange-the-layout), for sections, the reading column and the phone's drawer. # Write a plugin's React UI (https://ifloom.dev/docs/how-to/react/write-a-plugins-react-ui) This how-to is for `@ifloom/react`, the optional React UI. To render a game in plain DOM, Vue or React by hand, see [Start your own UI](https://ifloom.dev/docs/how-to/render/start). Use this to ship a React UI with a plugin of your own, so a game lists it in `plugins` as it lists the first-party ones. The UI is optional: a game drawn another way never loads it. You need the plugin's engine side first, as [Write a plugin](https://ifloom.dev/docs/how-to/write-a-plugin) writes. This page builds the UI for a weather plugin that shows the next few days and lets the player mark one as rainy. ## Lay out the package [#lay-out-the-package] The `plugin` template starts the package with its `/react` subpath and a test that renders it, as [Write a plugin](https://ifloom.dev/docs/how-to/write-a-plugin#start-a-package) shows. By hand, give the package these: 1. Put the UI in `src/react/index.tsx`, built to `dist/react/`, and export it as `./react` beside `.` in `package.json`. 2. Make `react`, `react-dom` and `@ifloom/react` optional peers, so a game that renders the plugin another way installs none of them for it. List `@ifloom/react` as a dev dependency too, for your own build and tests. 3. Import only the engine, React, `@ifloom/react`, `@ifloom/react/kit` and your own files. A path inside `@ifloom/react` may move, and another plugin may be missing. ```json fragment "exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" }, "./react": { "types": "./dist/react/index.d.ts", "default": "./dist/react/index.js" } }, "peerDependenciesMeta": { "@ifloom/react": { "optional": true }, "react": { "optional": true }, "react-dom": { "optional": true } } ``` ## Declare the view the UI reads [#declare-the-view-the-ui-reads] The engine side, `src/index.ts`, declares the plugin's view in [`ViewRegistry`](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry), so the UI reads it typed with no cast: ```ts declare module '@ifloom/engine' { interface ViewRegistry { weather: { days: { day: number; label: string; rain: boolean }[] } } } ``` ## Declare the UI once [#declare-the-ui-once] Call [`pluginKit`](https://ifloom.dev/docs/reference/react/kit#pluginkit) with the plugin's id and its words in English. Each component reads the plugin through this one declaration, and the `<id>Ui` spreads it, so the id and the words are written in one place. Prefix the word keys with something of your plugin's, since every plugin UI's keys share the `ui.` namespace a game rewords them in. Then add your components and parts to the React UI's interfaces, so a game's `components` and `classes` take them typed: ```tsx // src/react/index.tsx import type { ComponentProps } from 'react' import { usePart } from '@ifloom/react' import { overridable, pluginKit, useKitPart, usePlugin, type Override, type PluginUi } from '@ifloom/react/kit' import { weather } from '../index.ts' export const WEATHER_WORDS = { weatherTitle: 'Weather', weatherRain: 'Rain later', weatherMark: 'Mark rain' } as const const WEATHER = pluginKit('weather', WEATHER_WORDS) declare module '@ifloom/react' { interface OverridableComponents { Forecast: Override<ComponentProps<typeof Forecast>> } interface PartNames { forecast: true 'forecast-day': true } } ``` ## Write the components [#write-the-components] Read the plugin with [`usePlugin`](https://ifloom.dev/docs/reference/react/kit#useplugin), which gives its view, its words with the game's rewording over them, and a `send` that takes the commands the plugin's helpers write. Make each component with [`overridable`](https://ifloom.dev/docs/reference/react/components#overridable), so a game can replace it by name: ```tsx continues function ForecastImpl({ className }: { className?: string }) { const { view, words, send } = usePlugin(WEATHER) const list = usePart('forecast', 'flex flex-col gap-2 text-sm', className) const day = useKitPart('card', 'forecast-day') if (!view) return null return ( <ul {...list}> {view.days.map((entry) => ( <li key={entry.day} {...day}> {entry.label} {entry.rain ? ` · ${words('weatherRain')}` : <button onClick={() => send(weather.markRain(entry.day))}>{words('weatherMark')}</button>} </li> ))} </ul> ) } export const Forecast = overridable('Forecast', ForecastImpl) ``` `view` is `undefined` in a game without the plugin, so the component renders nothing there. `weather.markRain` is one of the plugin's helpers, so no command is written by hand. For buttons the view already offers as a `RenderedChoice`, send its `command`, or render it with [`ChoiceButton`](https://ifloom.dev/docs/reference/react/components#choicebutton), so the button greys out with the engine's reason. ## Export the plugin UI [#export-the-plugin-ui] Export the `<id>Ui`, a [`PluginUi`](https://ifloom.dev/docs/reference/react/kit#pluginui), with the declaration spread into it and the [spot](https://ifloom.dev/docs/reference/react/kit#pluginspot) each part goes in. Export a hook beside it that gives the view and the plugin's commands with no markup, for a game that renders the plugin its own way: ```tsx continues export function useWeather() { const { view, send } = usePlugin(WEATHER) if (!view) return null return { ...view, markRain: (day: number) => send(weather.markRain(day)) } } export const weatherUi: PluginUi = { ...WEATHER, layout: { sidebar: [Forecast] } } ``` A plugin UI can bring more than layout: `panels` by name, `pages` among the pages around the game, `settings`, renderers for an app's `sections`, `inline` pieces, the `hints` its components read, built-in `components` it replaces, and a `provider` for state it keeps beside the runner. [`PluginUi`](https://ifloom.dev/docs/reference/react/kit#pluginui) describes each field. ## Style it with the kit's parts [#style-it-with-the-kits-parts] The presets style the [kit's parts](https://ifloom.dev/docs/reference/react/kit#kit-parts) and the tokens, never a plugin's own parts by name. A plugin UI looks right in every preset as long as it marks what its parts are like: - **Mark each part with what it's like**, with [`useKitPart`](https://ifloom.dev/docs/reference/react/kit#usekitpart). A vendor's good, a job and an achievement are each a `card`, their names a `title`, a line about them a `note`. Each kit part brings its own look, so `useKitPart('card', 'forecast-day')` is boxed like every other plugin's card with no preset loaded. - **Add only layout.** Put where the part sits over its look, such as `useKitPart('card', 'good', 'sm:flex-row sm:items-start')` for buttons beside the words on a wider screen. Use only the classes in [`KIT_LAYOUT`](https://ifloom.dev/docs/reference/react/kit#kit_layout), with `buttonVariants`, `badgeVariants`, [`PROSE`](https://ifloom.dev/docs/reference/react/kit#prose) and [`useDialogParts`](https://ifloom.dev/docs/reference/react/kit#usedialogparts). - **Use no class of your own.** The prebuilt `styles.min.css` holds only the classes `@ifloom/react`'s own source uses, and a game's Tailwind scans `@ifloom/react` but not your plugin. A class only your plugin uses is missing, and the part renders unstyled. ## Ship a stylesheet when it needs more [#ship-a-stylesheet-when-it-needs-more] If your UI needs classes or rules of its own, publish a stylesheet beside `/react`, as `@ifloom/react` publishes `styles.css` and `styles.min.css`. Ship its Tailwind source with an `@source` line pointing at your `dist/react/`, for a game with Tailwind, and a prebuilt copy for a game without. Say in your README that a game imports yours after the React UI's: ```css /* A game with Tailwind */ @import "@ifloom/react/styles.css"; @import "ifloom-plugin-weather/react.css"; /* A game without */ @import "@ifloom/react/styles.min.css"; @import "ifloom-plugin-weather/react.min.css"; ``` ## Test it [#test-it] Render the UI inside a [`GameProvider`](https://ifloom.dev/docs/reference/react/components#gameprovider) with a runner of a small game that has the plugin, as the template's `tests/react.test.tsx` does. `renderToString` from `react-dom/server` needs no browser: ```tsx import { renderToString } from 'react-dom/server' import { expect, it } from 'vitest' import { createRunner, loadGame } from '@ifloom/engine' import { freshState } from '@ifloom/engine/testing' import { GameProvider } from '@ifloom/react' import { weather } from '../src/index.ts' import { Forecast, weatherUi } from '../src/react/index.tsx' it('lists the days', () => { const { game } = loadGame([], { id: 'weather-town', title: 'Weather town', plugins: [weather()] }) const html = renderToString( <GameProvider runner={createRunner(game, freshState(game))} plugins={[weatherUi]}> <Forecast /> </GameProvider>, ) expect(html).toContain('Mark rain') }) ``` ## Check it worked [#check-it-worked] Run the tests, then list `weatherUi` in a game's `plugins` and run `npm run dev`. The forecast shows in the side column, boxed like the other plugins' cards, and takes the preset's look when you change it. For more, see: - [Plugin UIs and the kit](https://ifloom.dev/docs/reference/react/kit), for `pluginKit`, `usePlugin`, `PluginUi` and the kit's parts. - [`OverridableComponents` and `PartNames`](https://ifloom.dev/docs/reference/react/components#overridablecomponents-and-partnames). - [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis), for how a game lists and places your UI. - [Plugins](https://ifloom.dev/docs/explanation/plugins), for why a plugin's UI ships with the plugin. # Render messages, the feed and devices (https://ifloom.dev/docs/how-to/render/phone-plugins) Render the plugins a phone is made of: the texts from [messages](https://ifloom.dev/docs/reference/plugins/messages), the posts from the [feed](https://ifloom.dev/docs/reference/plugins/feed), and the phone itself with its apps from [devices](https://ifloom.dev/docs/reference/plugins/devices). Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. In the React tabs, each plugin's UI comes from its `/react` subpath and goes in `mountGame`'s `plugins`, as [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis) explains. A game shows its messages and its feed inside an app on a device, so render them inside the open app, as the last section shows. [Build a phone](https://ifloom.dev/docs/how-to/build-a-phone) writes the content. ## Render messages [#render-messages] `view.plugins.messages` holds the texts as a [`MessagesView`](https://ifloom.dev/docs/api/plugin-messages#messagesview), with each channel's threads and their messages, and how many are `unread`. The React UI's `messagesUi` renders a [`MessagesSection`](https://ifloom.dev/docs/api/plugin-messages#messagessection) wherever a device's app shows a messages channel. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner, add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** Each channel's threads, with their messages and the replies on offer, who is typing, and a button that marks a thread read. */ export function drawMessages(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const channel of view.plugins.messages?.channels ?? []) { add(parent, 'h3', channel.unread ? `${channel.name} (${channel.unread})` : channel.name) for (const thread of channel.threads) { const box = add(parent, 'section', '', 'thread') add(box, 'h4', thread.name) for (const message of thread.messages) { const bubble = add(box, 'div', '', 'message') if (!message.read) bubble.dataset.unread = '' add(bubble, 'strong', message.name) add(bubble, 'p', message.text) // A reply is a button like any other; once sent, it's the words of the reply. if (message.replied) add(bubble, 'p', message.replied, 'replied') else drawChoices(bubble, message.replies) } // A message with `after` is on its way. if (thread.typing) add(box, 'p', `${thread.name} is typing…`, 'typing') // Mark read, while anything in the thread is unread. if (thread.read) drawChoices(box, [thread.read]) } } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { messagesUi } from '@ifloom/plugin-messages/react' import module from './game.ts' // A MessagesSection is rendered wherever a device’s app shows a messages channel. mountGame(module.build(), { plugins: [messagesUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // Each channel's threads, with their messages and the replies on offer, who is typing, and a button that marks a thread read. </script> <template> <template v-for="channel in view.plugins.messages?.channels" :key="channel.id"> <h3> {{ channel.name }}<template v-if="channel.unread"> ({{ channel.unread }})</template> </h3> <section v-for="thread in channel.threads" :key="thread.id" class="thread"> <h4>{{ thread.name }}</h4> <div v-for="message in thread.messages" :key="message.key" class="message" :data-unread="message.read ? undefined : ''"> <strong>{{ message.name }}</strong> <p>{{ message.text }}</p> <!-- A reply is a button like any other; once sent, it's the words of the reply. --> <p v-if="message.replied" class="replied">{{ message.replied }}</p> <template v-else> <button v-for="reply in message.replies" :key="reply.id" :disabled="Boolean(reply.disabled)" :title="reply.disabled" @click="runner.apply(reply.command)" > {{ reply.label }} </button> </template> </div> <!-- A message with `after` is on its way. --> <p v-if="thread.typing" class="typing">{{ thread.name }} is typing…</p> <!-- Mark read, while anything in the thread is unread. --> <button v-if="thread.read" @click="runner.apply(thread.read.command)">{{ thread.read.label }}</button> </section> </template> </template> ``` Each thread has its `name`, its sender's `portrait`, its messages oldest first, and its `unread` count. A message's `replies` are ready buttons until the player sends one, and then `replied` holds the reply's words. A thread's `typing` is true while a message with `after` is on its way, which is the moment to show the sender typing. A thread's `read` and a channel's `read` are buttons that mark them read, and each is null while nothing in it is unread. A message's `beats` hold its paragraphs, pictures and videos, rendered as a scene's beats are in [Render the scene and its choices](https://ifloom.dev/docs/how-to/render/scene). [`useMessages`](https://ifloom.dev/docs/api/plugin-messages#usemessages) gives the messages' view to a React component of your own. ## Render a feed [#render-a-feed] `view.plugins.feed` holds the posts as a [`FeedsView`](https://ifloom.dev/docs/api/plugin-feed#feedsview), with each feed's posts, newest first, and how many are new. The React UI's `feedUi` renders a [`FeedSection`](https://ifloom.dev/docs/api/plugin-feed#feedsection) wherever a device's app shows a feed. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** Each feed's posts, newest first, with their likes and comments, and a button that marks the feed seen. */ export function drawFeed(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const feed of view.plugins.feed?.feeds ?? []) { add(parent, 'h3', feed.unread ? `${feed.name} (${feed.unread} new)` : feed.name) for (const post of feed.posts) { const card = add(parent, 'article', '', post.mine ? 'post mine' : 'post') add(card, 'strong', post.name) add(card, 'p', post.text) if (post.image) Object.assign(add(card, 'img'), { src: post.image, alt: '' }) add(card, 'span', `${post.likes} likes`, 'likes') for (const comment of post.comments) add(card, 'p', `${comment.name}: ${comment.text}`, 'comment') } // Mark all seen, while anything in the feed is new. if (feed.seen) drawChoices(parent, [feed.seen]) } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { feedUi } from '@ifloom/plugin-feed/react' import module from './game.ts' // A FeedSection is rendered wherever a device’s app shows a feed. mountGame(module.build(), { plugins: [feedUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // Each feed's posts, newest first, with their likes and comments, and a button that marks the feed seen. </script> <template> <template v-for="feed in view.plugins.feed?.feeds" :key="feed.id"> <h3> {{ feed.name }}<template v-if="feed.unread"> ({{ feed.unread }} new)</template> </h3> <article v-for="post in feed.posts" :key="post.id" :class="['post', { mine: post.mine }]"> <strong>{{ post.name }}</strong> <p>{{ post.text }}</p> <img v-if="post.image" :src="post.image" alt="" /> <span class="likes">{{ post.likes }} likes</span> <p v-for="(comment, at) in post.comments" :key="at" class="comment">{{ comment.name }}: {{ comment.text }}</p> </article> <!-- Mark all seen, while anything in the feed is new. --> <button v-if="feed.seen" @click="runner.apply(feed.seen.command)">{{ feed.seen.label }}</button> </template> </template> ``` Each post has its poster's `name` and `portrait`, its `text`, its `image` and `video`, its `likes` and its `comments`. `mine` is true for the player's own post, which a UI can set apart. A feed's `unread` counts the other people's posts the player hasn't seen, and its `seen` button marks them seen. [`useFeed`](https://ifloom.dev/docs/api/plugin-feed#usefeed) gives the feed's view to a React component of your own. ## Render a device and its apps [#render-a-device-and-its-apps] `view.plugins.devices` holds each device as a [`DevicesView`](https://ifloom.dev/docs/api/plugin-devices#devicesview), with its apps, whether it's out, and the app open on it. The React UI's `devicesUi` puts a button for each device in the side column, opens the device in a dialog, and puts each app with news in the notice strip. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' import type { DeviceView } from '@ifloom/plugin-devices' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** Each device: a button that brings it out, and while it's out, its open app or else its home screen of apps, with Home and Close. */ export function drawDevices(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const device of view.plugins.devices?.devices ?? []) { const screen = add(parent, 'section', '', 'device') screen.dataset.device = device.id add(screen, 'h3', device.badge ? `${device.name} (${device.badge})` : device.name) // Whether it's out, and on what, is the game's state, so every UI shows the same. if (!device.shown) { drawChoices(screen, [{ ...device.home, label: `Take out the ${device.name}` }]) continue } if (device.open) drawApp(screen, device) else drawChoices( screen, device.apps.map((app) => ({ id: app.id, label: app.name, disabled: app.disabled, command: app.command })), ) // Home goes back from an app; Close puts it away. drawChoices(screen, device.open ? [device.home, device.close!] : [device.close!]) } } /** The open app's sections. A `plugin` section is the messages' or the feed's, rendered as their pages show. */ function drawApp(screen: HTMLElement, device: DeviceView): void { for (const section of device.open?.sections ?? []) { if (section.type === 'prose') add(screen, 'p', section.text) else if (section.type === 'actions') drawChoices(add(screen, 'div'), section.actions) else if (section.type === 'list') { for (const entry of section.entries) { const row = add(screen, 'div', '', 'entry') add(row, 'strong', entry.title) add(row, 'p', entry.text) drawChoices(row, entry.actions) } } } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { devicesUi } from '@ifloom/plugin-devices/react' import { feedUi } from '@ifloom/plugin-feed/react' import { messagesUi } from '@ifloom/plugin-messages/react' import module from './game.ts' // A button for each device goes in the side column. An app's messages and feed are rendered by those plugins' UIs, so list them too. mountGame(module.build(), { plugins: [devicesUi, messagesUi, feedUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // Each device: a button that brings it out, and while it's out, its open app or else its home screen of apps, with Home and Close. // Whether it's out, and on what, is the game's state, so every UI shows the same. // A `plugin` section is the messages' or the feed's, rendered as their pages show. </script> <template> <section v-for="device in view.plugins.devices?.devices" :key="device.id" class="device" :data-device="device.id"> <h3> {{ device.name }}<template v-if="device.badge"> ({{ device.badge }})</template> </h3> <button v-if="!device.shown" @click="runner.apply(device.home.command)">Take out the {{ device.name }}</button> <template v-else-if="device.open"> <template v-for="(section, at) in device.open.sections" :key="at"> <p v-if="section.type === 'prose'">{{ section.text }}</p> <div v-else-if="section.type === 'actions'"> <button v-for="action in section.actions" :key="action.id" :disabled="Boolean(action.disabled)" @click="runner.apply(action.command)"> {{ action.label }} </button> </div> <template v-else-if="section.type === 'list'"> <div v-for="entry in section.entries" :key="entry.id" class="entry"> <strong>{{ entry.title }}</strong> <p>{{ entry.text }}</p> <button v-for="action in entry.actions" :key="action.id" :disabled="Boolean(action.disabled)" @click="runner.apply(action.command)"> {{ action.label }} </button> </div> </template> </template> <!-- Home goes back from an app. --> <button @click="runner.apply(device.home.command)">{{ device.home.label }}</button> </template> <template v-else> <button v-for="app in device.apps" :key="app.id" :disabled="Boolean(app.disabled)" :title="app.disabled" @click="runner.apply(app.command)"> {{ app.name }}<template v-if="app.badge"> ({{ app.badge }})</template> </button> </template> <!-- Close puts it away. --> <button v-if="device.close" @click="runner.apply(device.close.command)">{{ device.close.label }}</button> </section> </template> ``` The game's state records whether a device is out and which app is open, so every UI shows the same thing. Render a device only while its `shown` is true. Its `home` button brings it out on its home screen or back from an app, and its `close` button puts it away. Each app has a `badge`, a count or a dot (`true`), and a `command` that opens it, with the reason in `disabled` while it can't open. The open app's `sections` are each a [`SectionView`](https://ifloom.dev/docs/api/plugin-devices#sectionview), told apart by `type`: - **`prose`**: words, with their `beats`. - **`actions`**: buttons, each sending its `command`. - **`list`**: entries, each with a `title`, `text`, `image` and buttons. - **`plugin`**: another plugin's part, named by `plugin`, with `with` naming which, such as `{ channel: 'texts' }`. - **`panel`**: a panel of the game's, rendered as [Render a panel](https://ifloom.dev/docs/how-to/render/timers-minigames-panels#render-a-panel) shows. Render a `plugin` section from that plugin's view. For `messages`, find the channel whose `id` is `with.channel` in `view.plugins.messages.channels` and render it as the messages section does. For `feed`, find the feed whose `id` is `with.feed`. In React, `devicesUi` leaves each `plugin` section to the UI of the plugin it names, so list `messagesUi` and `feedUi` beside it, or those apps open empty. [`useDevices`](https://ifloom.dev/docs/api/plugin-devices#usedevices) gives the devices' view to a React component of your own. For more on what these sections render, see: - [Messages](https://ifloom.dev/docs/reference/plugins/messages), [Feed](https://ifloom.dev/docs/reference/plugins/feed) and [Devices](https://ifloom.dev/docs/reference/plugins/devices). - [The view](https://ifloom.dev/docs/reference/view). - [Build a phone](https://ifloom.dev/docs/how-to/build-a-phone). # Render pictures and play sound (https://ifloom.dev/docs/how-to/render/pictures-and-sound) Render a scene's [picture](https://ifloom.dev/docs/reference/glossary#picture), its layers and hotspots, and play the game's music, sounds and voiced lines. Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. A picture or a clip inside the prose is a beat, which [Render the scene](https://ifloom.dev/docs/how-to/render/scene#render-the-scene) covers. ## Render the scene's picture [#render-the-scenes-picture] `view.scene.picture` holds the scene's layered picture as a [`PictureView`](https://ifloom.dev/docs/api/engine#pictureview), and `view.scene.image` a single picture when the scene has no layers. The React UI's `Scene` renders the picture above the words with [`LayeredPicture`](https://ifloom.dev/docs/api/react#layeredpicture), which you can also place yourself. ```ts tab="Plain JS" tab-group="framework" import type { PictureView, RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** The scene's layered picture, else its image. */ export function drawPicture(parent: HTMLElement, { view }: RunnerSnapshot): void { if (view.scene.picture) drawLayers(parent, view.scene.picture) else if (view.scene.image) Object.assign(add(parent, 'img'), { src: view.scene.image, alt: '' }) } /** Layers stacked bottom first, with each hotspot a button placed by its rect, in percent of the picture. */ function drawLayers(parent: HTMLElement, picture: PictureView): void { const box = add(parent, 'div', '', 'picture') Object.assign(box.style, { position: 'relative', aspectRatio: picture.aspect ?? 'auto' }) for (const layer of picture.layers) { const shown = add(box, layer.video ? 'video' : 'img') Object.assign(shown, { src: layer.src, alt: '' }) Object.assign(shown.style, { position: 'absolute', inset: '0', width: '100%', height: '100%' }) } for (const hotspot of picture.hotspots) { const [left, top, width, height] = hotspot.rect const button = add(box, 'button', '', 'hotspot') button.setAttribute('aria-label', hotspot.label) button.title = hotspot.disabled ?? hotspot.label button.disabled = Boolean(hotspot.disabled) Object.assign(button.style, { position: 'absolute', left: `${left}%`, top: `${top}%`, width: `${width}%`, height: `${height}%` }) button.onclick = () => runner.apply(hotspot.command) } } ``` ```tsx tab="React" tab-group="framework" import { LayeredPicture, Picture, useGame } from '@ifloom/react' // Scene renders the scene's picture above its words. To put it somewhere else, render it from the view yourself: // LayeredPicture stacks the layers and places each hotspot as a button. export function ScenePicture() { const { view } = useGame() if (view.scene.picture) return <LayeredPicture picture={view.scene.picture} /> return view.scene.image ? <Picture src={view.scene.image} alt="" /> : null } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // The scene's layered picture, else its image: layers stacked bottom first, and each hotspot a button placed by its rect, in percent. const fill = { position: 'absolute', inset: '0', width: '100%', height: '100%' } as const const at = ([left, top, width, height]: [number, number, number, number]) => ({ position: 'absolute', left: `${left}%`, top: `${top}%`, width: `${width}%`, height: `${height}%` }) as const </script> <template> <div v-if="view.scene.picture" class="picture" :style="{ position: 'relative', aspectRatio: view.scene.picture.aspect ?? 'auto' }"> <template v-for="(layer, index) in view.scene.picture.layers" :key="index"> <video v-if="layer.video" :src="layer.src" :style="fill" autoplay loop muted /> <img v-else :src="layer.src" alt="" :style="fill" /> </template> <button v-for="hotspot in view.scene.picture.hotspots" :key="hotspot.id" class="hotspot" :aria-label="hotspot.label" :title="hotspot.disabled ?? hotspot.label" :disabled="Boolean(hotspot.disabled)" :style="at(hotspot.rect)" @click="runner.apply(hotspot.command)" /> </div> <img v-else-if="view.scene.image" :src="view.scene.image" alt="" /> </template> ``` Stack the `layers` bottom first. A layer with `video` set is a clip rather than a picture. The engine lists only the layers whose `when` holds and resolves a pool's pick, so render each layer in the list. Put each of the `hotspots` over the layers as a button, placed by its `rect`, the left, top, width and height in percent of the picture. A hotspot is a [`HotspotView`](https://ifloom.dev/docs/api/engine#hotspotview), greyed out with `disabled` like any button, and it sends its `command`. The places plugin gives a location's picture in its own view, and [Render the calendar, locations and people](https://ifloom.dev/docs/how-to/render/world-plugins) renders it the same way. ## Play sound [#play-sound] `view.audio` holds what each channel should play and the sounds that are due, as an [`AudioView`](https://ifloom.dev/docs/api/engine#audioview), and the audio player plays it. The React UI's `mountGame` plays the game's sound itself, and `Scene` puts a replay button on each spoken line with a voice. ```ts tab="Plain JS" tab-group="framework" import { startAudio } from '@ifloom/audio' import { audioSrc, type RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' // Once, beside the runner: plays what view.audio asks for, from the player's first click or key press. // Keep the player it returns to play a file on demand. const player = startAudio(runner) /** A Play again button for each spoken line in the scene that has a voice. */ export function drawVoices(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const beat of view.scene.beats) { if (beat.type !== 'say' || !beat.voice) continue // The voice names a track in the game's audio.tracks: a file, or a playlist, which has no one file to play. const track = runner.game.audio?.tracks[beat.voice] if (track && 'src' in track) add(parent, 'button', 'Play again').onclick = () => player.play(audioSrc(track.src), 'voice', track.volume ?? 1) } } ``` ```tsx tab="React" tab-group="framework" import { useAudio } from '@ifloom/react' // mountGame plays the game's sound, and Scene puts a replay button on each spoken line with a voice. // To give the player options, place useAudio once in your layout: it takes over from mountGame's player. export function SoundLog() { // Each thing the player does, as a line in the console. useAudio({ log: console.debug }) return null } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { audioSrc } from '@ifloom/engine' import { player, runner, view } from './runner.ts' // The vue template's runner.ts starts the player once, beside the runner: `export const player = startAudio(runner)`. // A Play again button for each spoken line in the scene that has a voice. const voices = computed(() => view.value.scene.beats.flatMap((beat) => (beat.type === 'say' && beat.voice ? [beat.voice] : []))) function replay(voice: string) { // The voice names a track in the game's audio.tracks: a file, or a playlist, which has no one file to play. const track = runner.game.audio?.tracks[voice] if (track && 'src' in track) player.play(audioSrc(track.src), 'voice', track.volume ?? 1) } </script> <template> <button v-for="(voice, at) in voices" :key="at" @click="replay(voice)">Play again</button> </template> ``` Start [`startAudio`](https://ifloom.dev/docs/api/audio#startaudio) once, beside the runner, never inside a component that comes and goes. It follows the runner rather than your components, so it plays the same whatever renders the page. Nothing plays until the player first clicks or presses a key, because browsers allow no sound sooner. Pass `{ log: console.debug }` to see each thing the player does in the console. The player sets each channel's volume from the ui setting the game's `audio` names for it, so a volume slider on your settings screen works with no code of yours. A spoken line with a voice is a `say` beat with `voice`, a track id. To play it again, look the track up in the game's `audio.tracks` and call the player's [`play`](https://ifloom.dev/docs/api/audio#audioplayer) with its file, through `audioSrc`. For more on what these sections render, see: - [Media](https://ifloom.dev/docs/reference/media) and [Audio](https://ifloom.dev/docs/reference/audio). - [The audio player](https://ifloom.dev/docs/api/audio). - [Add pictures and backgrounds](https://ifloom.dev/docs/how-to/add-pictures-and-backgrounds) and [Add music and sound](https://ifloom.dev/docs/how-to/add-music-and-sound). # Render cheats, unlocks and debug (https://ifloom.dev/docs/how-to/render/player-tools) Render the tools that sit outside the story: the player's cheats and a box for codes, both from [unlocks](https://ifloom.dev/docs/reference/plugins/unlocks), and a readout for yourself from [debug](https://ifloom.dev/docs/reference/plugins/debug). Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. In the React tabs, each plugin's UI comes from its `/react` subpath and goes in `mountGame`'s `plugins`, as [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis) explains. ## Render the cheats [#render-the-cheats] `view.plugins.unlocks.cheats` holds the cheats the player can see, each a [`CheatView`](https://ifloom.dev/docs/api/plugin-unlocks#cheatview) with its group, how often this save has used it, and a ready `button`. The React UI's `unlocksUi` puts a [`CheatsButton`](https://ifloom.dev/docs/api/plugin-unlocks#cheatsbutton) in the side column that opens the [`CheatPanel`](https://ifloom.dev/docs/api/plugin-unlocks#cheatpanel). ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** The cheats under their groups, each a button that says how often it's been used, greyed out with why when it's refused. */ export function drawCheats(parent: HTMLElement, { view }: RunnerSnapshot): void { const cheats = view.plugins.unlocks?.cheats ?? [] for (const group of new Set(cheats.map((cheat) => cheat.group))) { if (group) add(parent, 'h3', group) for (const cheat of cheats.filter((entry) => entry.group === group)) { const button = add(parent, 'button', cheat.used ? `${cheat.name} (used ${cheat.used})` : cheat.name) button.disabled = Boolean(cheat.button.disabled) button.title = cheat.button.disabled ?? cheat.description button.onclick = () => runner.apply(cheat.button.command) } } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { unlocksUi } from '@ifloom/plugin-unlocks/react' import module from './game.ts' // A Cheats button in the side column opens the CheatPanel. With unlocks, a code box goes on the settings page too. mountGame(module.build(), { plugins: [unlocksUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { runner, view } from './runner.ts' // The cheats under their groups, each a button that says how often it's been used, greyed out with why when it's refused. const cheats = computed(() => view.value.plugins.unlocks?.cheats ?? []) const groups = computed(() => [...new Set(cheats.value.map((cheat) => cheat.group))]) </script> <template> <template v-for="group in groups" :key="group ?? ''"> <h3 v-if="group">{{ group }}</h3> <button v-for="cheat in cheats.filter((entry) => entry.group === group)" :key="cheat.id" :disabled="Boolean(cheat.button.disabled)" :title="cheat.button.disabled ?? cheat.description" @click="runner.apply(cheat.button.command)" > {{ cheat.name }}<template v-if="cheat.used"> (used {{ cheat.used }})</template> </button> </template> </template> ``` Group the cheats by `group`, in the order the game declares them. A cheat's `button` has the reason it's refused in `disabled`, such as a supporter cheat before its code is entered, so render it greyed out with the reason. `used` counts the times this save has used the cheat, and the view's `cheated` counts them all. A cheat runs in any scene and through any lock, so the menu can stay on screen. [`useCheats`](https://ifloom.dev/docs/api/plugin-unlocks#usecheats) gives the cheats to a React component of your own. ## Render a box for codes [#render-a-box-for-codes] `view.plugins.unlocks` holds every unlock as an [`UnlocksView`](https://ifloom.dev/docs/api/plugin-unlocks#unlocksview), each with whether the player has it, and the runner's snapshot holds where entering a code stands at `helpers.unlocks`, an [`UnlockStatus`](https://ifloom.dev/docs/api/plugin-unlocks#unlockstatus). The React UI's `unlocksUi` starts codes on the runner and puts the [`UnlocksPanel`](https://ifloom.dev/docs/api/plugin-unlocks#unlockspanel) on the settings page with pages on, or behind an **Enter a code** button in the menu without them. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' import { enterCode } from '@ifloom/plugin-unlocks' // runner and add, as in the vanilla template's src/main.ts. Start codes there once, beside startClock: startUnlocks(runner). import { add, runner } from './runner.ts' /** A code box while codes have started, with where the last code stands, and the unlocks with which the player has. */ export function drawUnlocks(parent: HTMLElement, { view, helpers }: RunnerSnapshot): void { const unlocks = view.plugins.unlocks if (!unlocks?.total) return // What startUnlocks reports: idle, checking, wrong or unlocked. A new snapshot follows each change. const codes = helpers.unlocks if (codes) { const form = add(parent, 'form') const input = add(form, 'input') input.placeholder = 'Code' const button = add(form, 'button', codes.status === 'checking' ? 'Checking…' : 'Unlock') button.disabled = codes.status === 'checking' form.onsubmit = (event) => { event.preventDefault() void enterCode(runner, input.value) } if (codes.status === 'wrong') add(form, 'p', codes.reason ?? '', 'reason') if (codes.status === 'unlocked') add(form, 'p', `Unlocked: ${codes.entered?.name}.`) } add(parent, 'h3', `Unlocked ${unlocks.unlocked} of ${unlocks.total}`) const list = add(parent, 'ul', '', 'unlocks') for (const unlock of unlocks.unlocks) { const item = add(list, 'li', `${unlock.name}: ${unlock.unlocked ? 'unlocked' : 'locked'}`) item.title = unlock.description } } ``` ```tsx tab="React" tab-group="framework" import { localStorageDriver } from '@ifloom/browser' import { profile } from '@ifloom/engine' import { mountGame } from '@ifloom/react' import { unlockedPacks } from '@ifloom/plugin-unlocks' import { unlocksUiWith } from '@ifloom/plugin-unlocks/react' import module from './game.ts' // What the player's codes opened, from the profile, before the game is built with it. const opened = await unlockedPacks('small-town', profile({ id: 'small-town' }, localStorageDriver())) // A code box on the settings page; a new code builds the game again with what it opened. const unlocks = unlocksUiWith({ problems: opened.problems, onChange: () => location.reload() }) mountGame(module.build({ unlocked: opened.packs }), { pages: true, plugins: [unlocks] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { ref } from 'vue' import { enterCode } from '@ifloom/plugin-unlocks' import { runner, snapshot, view } from './runner.ts' // A code box while codes have started, with where the last code stands, and the unlocks with which the player has. // Start codes once in runner.ts, beside startClock: startUnlocks(runner). It reports idle, checking, wrong or unlocked in the snapshot. const code = ref('') </script> <template> <template v-if="view.plugins.unlocks?.total"> <form v-if="snapshot.helpers.unlocks" @submit.prevent="enterCode(runner, code)"> <input v-model="code" placeholder="Code" /> <button :disabled="snapshot.helpers.unlocks.status === 'checking'"> {{ snapshot.helpers.unlocks.status === 'checking' ? 'Checking…' : 'Unlock' }} </button> <p v-if="snapshot.helpers.unlocks.status === 'wrong'" class="reason">{{ snapshot.helpers.unlocks.reason }}</p> <p v-if="snapshot.helpers.unlocks.status === 'unlocked'">Unlocked: {{ snapshot.helpers.unlocks.entered?.name }}.</p> </form> <h3>Unlocked {{ view.plugins.unlocks.unlocked }} of {{ view.plugins.unlocks.total }}</h3> <ul class="unlocks"> <li v-for="unlock in view.plugins.unlocks.unlocks" :key="unlock.id" :title="unlock.description"> {{ unlock.name }}: {{ unlock.unlocked ? 'unlocked' : 'locked' }} </li> </ul> </template> </template> ``` Entering a code isn't a command, because the plugin checks each code against a slow hash. Set it up in this order: 1. Before you build the game, open the content the player's codes unlock with [`unlockedPacks`](https://ifloom.dev/docs/api/plugin-unlocks#unlockedpacks), from the game's id and its [profile](https://ifloom.dev/docs/reference/profile). Use the same save driver the runner will use, and pass its `packs` to the game module's `build` as `unlocked`. 2. After you make the runner, start taking codes with [`startUnlocks(runner)`](https://ifloom.dev/docs/api/plugin-unlocks#startunlocks), beside `startClock`. It records each remembered unlock in the game and reports in `helpers.unlocks`. 3. Send each code the player enters to [`enterCode(runner, code)`](https://ifloom.dev/docs/api/plugin-unlocks#entercode). When its result's `restart` is true, the code opened content the game in play lacks, so reload the page to build the game again. `helpers.unlocks.status` is `checking` while a code is checked, then `wrong` with its `reason`, or `unlocked` with what it `entered`. Disable the button while it's `checking`, since a check takes a fraction of a second per unlock on a phone. In React, `unlocksUiWith` takes the `problems` `unlockedPacks` returns and an `onChange` that reloads, as the React tab shows. [`useUnlocks`](https://ifloom.dev/docs/api/plugin-unlocks#useunlocks) gives the unlocks' view to a React component of your own. ## Render a debug readout [#render-a-debug-readout] `view.plugins.debug` holds a readout for the developer as a [`DebugView`](https://ifloom.dev/docs/api/plugin-debug#debugview), with the locks that are on, how often each trigger has fired, and the save's seed. The React UI's [`DebugCard`](https://ifloom.dev/docs/api/plugin-debug#debugcard), from `debugUi`, goes at the end of the story. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' import { debug } from '@ifloom/plugin-debug' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** What a debugger wants on screen: the save's seed, the locks that are on, the triggers fired, and a few commands that ignore locks. */ export function drawDebug(parent: HTMLElement, { view }: RunnerSnapshot): void { const shown = view.plugins.debug if (!shown) return add(parent, 'p', `Seed ${shown.seed}`) for (const lock of shown.locks) add(parent, 'p', `Locked: ${lock.reason} (${lock.deny.join(', ')})`, 'lock') add(parent, 'p', `Triggers fired: ${Object.keys(shown.fired).join(', ') || 'none'}`) add(parent, 'button', '100 coins').onclick = () => runner.apply(debug.stat('coins', 100)) add(parent, 'button', 'Close the scene').onclick = () => runner.apply(debug.scene()) } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { debugUi } from '@ifloom/plugin-debug/react' import module from './game.ts' // The DebugCard goes at the end of the story. It does nothing in a build without the plugin. mountGame(module.build(), { plugins: [debugUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { debug } from '@ifloom/plugin-debug' import { runner, view } from './runner.ts' // What a debugger wants on screen: the save's seed, the locks that are on, the triggers fired, and a few commands that ignore locks. </script> <template> <template v-if="view.plugins.debug"> <p>Seed {{ view.plugins.debug.seed }}</p> <p v-for="(lock, at) in view.plugins.debug.locks" :key="at" class="lock">Locked: {{ lock.reason }} ({{ lock.deny.join(', ') }})</p> <p>Triggers fired: {{ Object.keys(view.plugins.debug.fired).join(', ') || 'none' }}</p> <button @click="runner.apply(debug.stat('coins', 100))">100 coins</button> <button @click="runner.apply(debug.scene())">Close the scene</button> </template> </template> ``` The plugin's commands, such as `debug.stat('coins', 100)` and `debug.scene()`, ignore locks, so a button can send them at any time. A release build leaves the plugin out, so `view.plugins.debug` is undefined there and the readout renders nothing. That lets you keep it in your UI for every build, and `DebugCard` does the same. [`useDebug`](https://ifloom.dev/docs/api/plugin-debug#usedebug) gives the debug view to a React component of your own. For more on what these sections render, see: - [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks) and [Debug](https://ifloom.dev/docs/reference/plugins/debug). - [The runner](https://ifloom.dev/docs/reference/runner), for the snapshot's `helpers`. - [Sell supporter content](https://ifloom.dev/docs/how-to/sell-supporter-content) and [Debug a game](https://ifloom.dev/docs/how-to/debug-a-game). # Render quests, achievements and statuses (https://ifloom.dev/docs/how-to/render/progress-plugins) Render how far the player has come and what's affecting them now: the [quests](https://ifloom.dev/docs/reference/plugins/quests) in a log, the [achievements](https://ifloom.dev/docs/reference/plugins/achievements) on a page, and the [statuses](https://ifloom.dev/docs/reference/plugins/statuses) beside the stats. Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. In the React tabs, each plugin's UI comes from its `/react` subpath and goes in `mountGame`'s `plugins`, as [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis) explains. ## Render the quest log [#render-the-quest-log] `view.plugins.quests` holds the quests as a [`QuestsView`](https://ifloom.dev/docs/api/plugin-quests#questsview), with the `active` quests, the tracked one first, and the `done` ones, each a [`QuestEntry`](https://ifloom.dev/docs/api/plugin-quests#questentry). The React UI's `questsUi` puts a Quests section in the side column that opens the [`QuestLog`](https://ifloom.dev/docs/api/plugin-quests#questlog) in a dialog, with the count of news on its button. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** The quest log: the active quests, the tracked one first, each with its hint and how far along it is, then the finished ones. */ export function drawQuests(parent: HTMLElement, { view }: RunnerSnapshot): void { const quests = view.plugins.quests if (!quests) return for (const quest of quests.active) { const entry = add(parent, 'section', '', 'quest') if (quest.updated) entry.dataset.updated = '' add(entry, 'h3', `${quest.name} (${quest.stage} of ${quest.stages})`) add(entry, 'p', quest.hint) // Track it, so it comes first; the same button says Untrack once it's tracked. if (quest.track) drawChoices(entry, [quest.track]) } if (quests.done.length) add(parent, 'p', `Done: ${quests.done.map((quest) => quest.name).join(', ')}`, 'done') // Mark all seen, while there is news: it clears the "updated" marks. if (quests.seen) drawChoices(parent, [quests.seen]) } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { questsUi } from '@ifloom/plugin-quests/react' import module from './game.ts' // A Quests section in the side column opens the quest log, with the count of news on its button. mountGame(module.build(), { plugins: [questsUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { runner, view } from './runner.ts' // The quest log: the active quests, the tracked one first, each with its hint and how far along it is, then the finished ones. const quests = computed(() => view.value.plugins.quests) </script> <template> <template v-if="quests"> <section v-for="quest in quests.active" :key="quest.id" class="quest" :data-updated="quest.updated ? '' : undefined"> <h3>{{ quest.name }} ({{ quest.stage }} of {{ quest.stages }})</h3> <p>{{ quest.hint }}</p> <!-- Track it, so it comes first; the same button says Untrack once it's tracked. --> <button v-if="quest.track" @click="runner.apply(quest.track.command)">{{ quest.track.label }}</button> </section> <p v-if="quests.done.length" class="done">Done: {{ quests.done.map((quest) => quest.name).join(', ') }}</p> <!-- Mark all seen, while there is news: it clears the "updated" marks. --> <button v-if="quests.seen" @click="runner.apply(quests.seen.command)">{{ quests.seen.label }}</button> </template> </template> ``` Each active quest has its `hint`, the count of its `stages` done in `stage`, and `updated` while it has news. Its `track` button tracks it, so it comes first, and the same button untracks it once it's tracked. `updates` counts the quests with news, for a badge, and the view's `seen` button marks them all seen. Both are ready buttons, so send their `command` as you would any other. [`useQuests`](https://ifloom.dev/docs/api/plugin-quests#usequests) gives the quests' view to a React component of your own. ## Render an achievements page [#render-an-achievements-page] `view.plugins.achievements` holds every achievement as an [`AchievementsView`](https://ifloom.dev/docs/api/plugin-achievements#achievementsview), earned or not, with how many are `earned` of the `total`. The React UI's `achievementsUi` puts an [`AchievementsButton`](https://ifloom.dev/docs/api/plugin-achievements#achievementsbutton) in the side column and opens the [`AchievementList`](https://ifloom.dev/docs/api/plugin-achievements#achievementlist) as the `achievements` panel, and the title screen offers an achievements page when pages are on. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** Every achievement, earned or not, with progress towards the ones that count. A secret one reads ??? until it's earned. */ export function drawAchievements(parent: HTMLElement, { view }: RunnerSnapshot): void { const achievements = view.plugins.achievements if (!achievements) return add(parent, 'h3', `Achievements: ${achievements.earned} of ${achievements.total}`) const list = add(parent, 'ul', '', 'achievements') for (const entry of achievements.achievements) { const item = add(list, 'li', entry.name) if (entry.earned) item.dataset.earned = '' if (entry.description) add(item, 'p', entry.description) if (entry.progress) Object.assign(add(item, 'progress'), { max: entry.progress.target, value: entry.progress.value }) } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { achievementsUi } from '@ifloom/plugin-achievements/react' import module from './game.ts' // An Achievements button goes in the side column, and the title screen offers an achievements page when pages are on. mountGame(module.build(), { plugins: [achievementsUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' // Every achievement, earned or not, with progress towards the ones that count. A secret one reads ??? until it's earned. </script> <template> <template v-if="view.plugins.achievements"> <h3>Achievements: {{ view.plugins.achievements.earned }} of {{ view.plugins.achievements.total }}</h3> <ul class="achievements"> <li v-for="entry in view.plugins.achievements.achievements" :key="entry.id" :data-earned="entry.earned ? '' : undefined"> {{ entry.name }} <p v-if="entry.description">{{ entry.description }}</p> <progress v-if="entry.progress" :max="entry.progress.target" :value="entry.progress.value" /> </li> </ul> </template> </template> ``` Render every entry. A secret achievement the player hasn't earned reads `???`, with no description or progress, so the page gives nothing away. An achievement that counts towards a target has `progress`, with its `value` and `target`, for a bar. The view counts an achievement as earned when the player has earned it in any save, from the [profile](https://ifloom.dev/docs/reference/profile) the runner keeps. When the runner records a new one there, it makes a new snapshot, so the page renders again. A view you make yourself with `view(state, game)` has no profile, so it shows only the save's own achievements. The plugin also raises a notice tagged `achievements` when one is earned, which [Render notices](https://ifloom.dev/docs/how-to/render/stats-and-things#render-notices) shows. [`useAchievements`](https://ifloom.dev/docs/api/plugin-achievements#useachievements) gives the achievements' view to a React component of your own. ## Render the statuses [#render-the-statuses] `view.plugins.statuses` holds the statuses in play as a [`StatusesView`](https://ifloom.dev/docs/api/plugin-statuses#statusesview), with each active one in `active`, in the order they were first applied. The React UI's [`StatusList`](https://ifloom.dev/docs/api/plugin-statuses#statuslist), from `statusesUi`, goes under the stats in the side column, and the `statuses` panel renders it too. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** The active statuses, under the stats: each with how many turns it has left. The stats already include what they add. */ export function drawStatuses(parent: HTMLElement, { view }: RunnerSnapshot): void { const active = view.plugins.statuses?.active ?? [] if (!active.length) return const list = add(parent, 'ul', '', 'statuses') for (const status of active) { const item = add(list, 'li', `${status.name} (${status.turnsLeft} left)`) item.title = status.description if (status.stacks > 1) add(item, 'span', ` ×${status.stacks}`) } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { statusesUi } from '@ifloom/plugin-statuses/react' import module from './game.ts' // The StatusList goes under the stats in the side column. mountGame(module.build(), { plugins: [statusesUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' // The active statuses, under the stats: each with how many turns it has left. The stats already include what they add. </script> <template> <ul v-if="view.plugins.statuses?.active.length" class="statuses"> <li v-for="status in view.plugins.statuses.active" :key="status.id" :title="status.description"> {{ status.name }} ({{ status.turnsLeft }} left)<template v-if="status.stacks > 1"> ×{{ status.stacks }}</template> </li> </ul> </template> ``` Each status has its `name`, its `description`, the turns it has left in `turnsLeft`, and its `stacks`. Render them beside the stats, because `view.stats` already includes what each status adds, and the stats a status moves as it starts are listed in `view.changes`. [`useStatuses`](https://ifloom.dev/docs/api/plugin-statuses#usestatuses) gives the statuses' view to a React component of your own. For more on what these sections render, see: - [Quests](https://ifloom.dev/docs/reference/plugins/quests), [Achievements](https://ifloom.dev/docs/reference/plugins/achievements) and [Statuses](https://ifloom.dev/docs/reference/plugins/statuses). - [The view](https://ifloom.dev/docs/reference/view). - [Add a quest](https://ifloom.dev/docs/how-to/add-a-quest). # Render saves, settings and the backlog (https://ifloom.dev/docs/how-to/render/saves-and-settings) Render the screens a player opens from a menu: saves to load, settings to change, and the [backlog](https://ifloom.dev/docs/api/engine#backlogentry) of what was shown, with Undo. Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. These parts read the runner's [snapshot](https://ifloom.dev/docs/reference/glossary#snapshot) as well as its view, because saves, setting values, the backlog and undo belong to the runner rather than to the game state. ## Render a save and load screen [#render-a-save-and-load-screen] `snapshot.saves` lists the saves in the runner's save store, newest first, then any that can't be read. Each is a [`SaveMeta`](https://ifloom.dev/docs/api/engine#savemeta) with its `name`, or `{ slot, broken }` with why it can't be read. The React UI's [`GameMenu`](https://ifloom.dev/docs/api/react#gamemenu) opens its [`SavesMenu`](https://ifloom.dev/docs/api/react#savesmenu), which you can also place yourself, and [`useSaves`](https://ifloom.dev/docs/api/react#usesaves) does everything it does without its look. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' import { nextSlot } from '@ifloom/browser' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** A Save button, greyed out while the game refuses saving, and a row for each save with Load and Delete. */ export function drawSaves(parent: HTMLElement, { view, saves }: RunnerSnapshot): void { const { allowed, reason, visible } = view.saving if (visible) { const save = add(parent, 'button', 'Save') save.disabled = !allowed if (reason) save.title = reason // Each save in a slot of its own, '1', '2', ..., named from view.when, such as "Day 2 · Tuesday morning · The Corner Café". save.onclick = () => void runner.save(nextSlot(saves)) } // The snapshot lists the saves, and the runner hands a new one after every save and delete. const list = add(parent, 'ul', '', 'slots') for (const entry of saves) { const row = add(list, 'li') // A save that can't be read says why, and can only be deleted. add(row, 'span', 'broken' in entry ? entry.broken : entry.name) if (!('broken' in entry)) add(row, 'button', 'Load').onclick = () => void runner.load(entry.slot) add(row, 'button', 'Delete').onclick = () => void runner.saves?.remove(entry.slot) } } ``` ```tsx tab="React" tab-group="framework" import { SavesMenu, Section, useSaves } from '@ifloom/react' // The game menu (GameMenu) opens the saves menu. To place it yourself, in a section that opens a dialog: export function Saves() { return ( <Section id="saves" title="Saves" dialog> <SavesMenu /> </Section> ) } // Or a button of your own, from useSaves. export function QuickSave() { const saves = useSaves() if (!saves.available || !saves.saving.visible) return null return ( <button disabled={!saves.saving.allowed} title={saves.saving.reason ?? undefined} onClick={() => void saves.save('Before the park')}> Quick save </button> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { nextSlot } from '@ifloom/browser' import { runner, snapshot, view } from './runner.ts' // A Save button, greyed out while the game refuses saving, and a row for each save with Load and Delete. // The snapshot lists the saves, and the runner hands a new one after every save and delete. // Each save in a slot of its own, '1', '2', ..., named from view.when, such as "Day 2 · Tuesday morning · The Corner Café". const save = () => runner.save(nextSlot(snapshot.value.saves)) </script> <template> <button v-if="view.saving.visible" :disabled="!view.saving.allowed" :title="view.saving.reason ?? undefined" @click="save">Save</button> <ul class="slots"> <li v-for="entry in snapshot.saves" :key="entry.slot"> <!-- A save that can't be read says why, and can only be deleted. --> <template v-if="'broken' in entry">{{ entry.broken }}</template> <template v-else> {{ entry.name }} <button @click="runner.load(entry.slot)">Load</button> </template> <button @click="runner.saves?.remove(entry.slot)">Delete</button> </li> </ul> </template> ``` Save with `runner.save(slot)`, in a new numbered slot from [`nextSlot`](https://ifloom.dev/docs/api/browser#nextslot), which skips named slots such as `auto`. Load with `runner.load(slot)`, and delete through the store with `runner.saves.remove(slot)`. Each is async and answers a [`Result`](https://ifloom.dev/docs/reference/common#result) rather than throwing, so show its `reason` when it fails. The runner keeps `snapshot.saves` up to date, and a load replaces the game in play and calls your listener, so the screen renders again without code of yours. `view.saving` says whether the game allows saving now, as a [`SavingView`](https://ifloom.dev/docs/api/engine#savingview). Grey Save out while `allowed` is false, with `reason` as its title, and leave it off the screen while `visible` is false. A Continue button loads the first save in the list that isn't broken, the autosave included. [Write a save driver](https://ifloom.dev/docs/how-to/write-a-save-driver) keeps saves somewhere other than `localStorage`. ## Render a settings screen [#render-a-settings-screen] `view.settings` lists every [setting](https://ifloom.dev/docs/reference/settings) the game declares, in order, as a [`SettingView`](https://ifloom.dev/docs/api/engine#settingview) with its `label`, its `type`, its `default`, and the `options` of a choice or the range of a slider. The React UI renders a Settings page when you turn on its `pages`, and [`useSetting`](https://ifloom.dev/docs/api/react#usesetting) reads one setting for a component of your own. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** A settings screen: every setting the game declares, with its value now. A change goes through runner.setSetting. */ export function drawSettings(parent: HTMLElement, { view, settings }: RunnerSnapshot): void { // settings has the values of both kinds: play settings from the state, ui settings from the profile. for (const setting of view.settings) { const label = add(parent, 'label', setting.label) const value = settings[setting.id] ?? setting.default if (setting.type === 'toggle') { const box = add(label, 'input') Object.assign(box, { type: 'checkbox', checked: value === true }) box.onchange = () => runner.setSetting(setting.id, box.checked) } else if (setting.type === 'choice') { const select = add(label, 'select') for (const option of setting.options ?? []) Object.assign(add(select, 'option', option.label), { value: option.value, selected: option.value === value }) select.onchange = () => runner.setSetting(setting.id, select.value) } else { const range = add(label, 'input') Object.assign(range, { type: 'range', min: String(setting.min ?? 0), max: String(setting.max ?? 100), step: String(setting.step ?? 1), value: String(value), }) range.onchange = () => runner.setSetting(setting.id, Number(range.value)) } } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import module from './game.ts' // `pages` opens on a title screen whose Settings page renders every setting the game declares, play and ui alike. mountGame(module.build(), { pages: true }) ``` ```tsx tab="React" tab-group="framework" import type { ReactNode } from 'react' import { useSetting } from '@ifloom/react' // A ui setting does what your UI makes of it: here, Small Town's text size, read with useSetting. export function TextSize({ children }: { children?: ReactNode }) { const size = useSetting('textSize') return <div style={{ fontSize: size === 'large' ? '1.25rem' : undefined }}>{children}</div> } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import type { KvValue } from '@ifloom/engine' import { runner, snapshot, view } from './runner.ts' // A settings screen: every setting the game declares, with its value now. A change goes through runner.setSetting. // snapshot.settings has both kinds: play settings from the state, ui settings from the profile. const valueOf = (id: string, fallback: KvValue) => snapshot.value.settings[id] ?? fallback const set = (id: string, to: KvValue) => runner.setSetting(id, to) </script> <template> <label v-for="setting in view.settings" :key="setting.id"> {{ setting.label }} <input v-if="setting.type === 'toggle'" type="checkbox" :checked="valueOf(setting.id, setting.default) === true" @change="set(setting.id, ($event.target as HTMLInputElement).checked)" /> <select v-else-if="setting.type === 'choice'" :value="valueOf(setting.id, setting.default)" @change="set(setting.id, ($event.target as HTMLSelectElement).value)" > <option v-for="option in setting.options" :key="option.value" :value="option.value">{{ option.label }}</option> </select> <input v-else type="range" :min="setting.min ?? 0" :max="setting.max ?? 100" :step="setting.step ?? 1" :value="valueOf(setting.id, setting.default)" @change="set(setting.id, Number(($event.target as HTMLInputElement).value))" /> </label> </template> ``` Read each setting's value from `snapshot.settings`, which holds both kinds. A `play` setting is part of the game state, and the [profile](https://ifloom.dev/docs/reference/profile) keeps a `ui` setting, never the state. Change either kind with `runner.setSetting(id, to)`, which checks the value against the declaration and answers a `Result`. A `ui` setting does only what your UI makes of it, so copy it where your stylesheet can read it, such as `document.documentElement.dataset.textSize`. The runner calls your listener when a setting changes, so the screen renders again. ## Render the backlog and undo [#render-the-backlog-and-undo] `snapshot.backlog` lists what was shown, oldest first, each a [`BacklogEntry`](https://ifloom.dev/docs/api/engine#backlogentry) with its `title`, its `beats` and the choice the player made. `snapshot.canUndo` and `snapshot.canRedo` say whether `runner.undo()` and `runner.redo()` have a step to take. The React UI's `GameMenu` offers the backlog and Undo when the runner has them, and [`Backlog`](https://ifloom.dev/docs/api/react#backlog) renders the backlog wherever you place it. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. The runner's backlog is on: browserRunner(game, { backlog: true }). import { add, runner } from './runner.ts' /** What was shown, oldest first, each scene's choice after its words, and a button that steps back one command. */ export function drawBacklog(parent: HTMLElement, { backlog, canUndo }: RunnerSnapshot): void { const undo = add(parent, 'button', 'Undo') undo.disabled = !canUndo undo.onclick = () => runner.undo() const list = add(parent, 'ol', '', 'backlog') for (const entry of backlog) { const item = add(list, 'li') add(item, 'h3', entry.title) for (const beat of entry.beats) if (beat.type === 'text' || beat.type === 'say') add(item, 'p', beat.text) if (entry.chose) add(item, 'p', entry.chose, 'chose') } } ``` ```tsx tab="React" tab-group="framework" import { Backlog, Section, useGame, useWords } from '@ifloom/react' import { Button } from '@ifloom/react/kit' // The game menu (GameMenu) offers the backlog and undo when the runner has them. To place them yourself: // a section that opens the backlog in a dialog, and an Undo button. export function History() { const words = useWords() const { runner, snapshot } = useGame() return ( <> <Section id="backlog" title={words('backlog')} dialog> <Backlog /> </Section> <Button variant="outline" disabled={!snapshot.canUndo} onClick={() => runner.undo()}> Undo </Button> </> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, snapshot } from './runner.ts' // What was shown, oldest first, each scene's choice after its words, and a button that steps back one command. // The runner's backlog is on: browserRunner(game, { backlog: true }). </script> <template> <button :disabled="!snapshot.canUndo" @click="runner.undo()">Undo</button> <ol class="backlog"> <li v-for="(entry, at) in snapshot.backlog" :key="at"> <h3>{{ entry.title }}</h3> <template v-for="(beat, index) in entry.beats" :key="index"> <p v-if="beat.type === 'text' || beat.type === 'say'">{{ beat.text }}</p> </template> <p v-if="entry.chose" class="chose">{{ entry.chose }}</p> </li> </ol> </template> ``` The backlog stays empty unless the runner has it on, with `browserRunner(game, { backlog: true })`. The backlog keeps inline actions as plain words, so nothing in it can be pressed. `browserRunner` turns undo on, 50 steps deep, and `runner.offers` says which of the two a menu should offer. For more on what these sections render, see: - [Saves](https://ifloom.dev/docs/reference/saves), [Settings](https://ifloom.dev/docs/reference/settings), [The profile](https://ifloom.dev/docs/reference/profile) and [The runner](https://ifloom.dev/docs/reference/runner). - [Browser helpers](https://ifloom.dev/docs/api/browser), for `browserRunner` and `nextSlot`. - [Add a settings page](https://ifloom.dev/docs/how-to/add-a-settings-page) and [Write a save driver](https://ifloom.dev/docs/how-to/write-a-save-driver). # Render the scene and its choices (https://ifloom.dev/docs/how-to/render/scene) Render the main column of the screen, the open scene or the room while none is open, with everything the player reads and presses there. Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. ## Render the scene [#render-the-scene] `view.scene` holds the open scene, or the [room](https://ifloom.dev/docs/reference/glossary#room) while none is open, with its `title`, its body as `beats` and its `choices` (the `scene` field of [`View`](https://ifloom.dev/docs/api/engine#view)). The React UI's [`Scene`](https://ifloom.dev/docs/api/react#scene) renders all of it, at the top of the story in the default layout. ```ts tab="Plain JS" tab-group="framework" import type { SceneBeat, RunnerSnapshot } from '@ifloom/engine' // runner, add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** The story: the scene's title, its beats and its choices. With no scene open it's the room, whose buttons are view.actions. */ export function drawScene(parent: HTMLElement, { view }: RunnerSnapshot): void { if (view.scene.title) add(parent, 'h2', view.scene.title) const prose = add(parent, 'div', '', 'prose') for (const beat of view.scene.beats) drawBeat(prose, beat) drawChoices(add(parent, 'div', '', 'choices'), view.scene.choices) } /** One paragraph of a scene. A sound beat is heard, not rendered. */ function drawBeat(parent: HTMLElement, beat: SceneBeat): void { switch (beat.type) { case 'text': add(parent, 'p', beat.text) break case 'say': { // Who says it over the words. A quote that answers the line before names no one. const line = add(parent, 'p', '', 'beat-say') line.dataset.who = beat.who if (beat.name) add(line, 'span', beat.name, 'speaker-name') add(line, 'span', beat.text) break } case 'chose': // A pick made earlier in a flowing scene, where the decision was. add(parent, 'p', beat.label, 'beat-chose') break case 'image': Object.assign(add(parent, 'img', '', 'beat-image'), { src: beat.src, alt: beat.alt ?? '' }) break case 'video': Object.assign(add(parent, 'video', '', 'beat-image'), { src: beat.src, autoplay: beat.autoplay, loop: beat.loop, muted: beat.muted, controls: beat.controls, }) break } } ``` ```tsx tab="React" tab-group="framework" import { Game, Scene, Story } from '@ifloom/react' // A layout of your own, for mountGame's `layout`. The default layout has Scene in its Story already. export function Reading() { return ( <Game> <Story> {/* The open scene, or the room: its title, picture, beats and choices. */} <Scene /> </Story> </Game> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // The story: the scene's title, its beats and its choices. With no scene open it's the room, whose buttons are view.actions. // The vue template's Beat.vue renders each beat with its spans; here they're written out. </script> <template> <h2 v-if="view.scene.title">{{ view.scene.title }}</h2> <div class="prose"> <template v-for="(beat, at) in view.scene.beats" :key="at"> <p v-if="beat.type === 'text'">{{ beat.text }}</p> <!-- Who says it over the words. A quote that answers the line before names no one. --> <p v-else-if="beat.type === 'say'" class="beat-say" :data-who="beat.who"> <span v-if="beat.name" class="speaker-name">{{ beat.name }}</span> {{ beat.text }} </p> <!-- A pick made earlier in a flowing scene, where the decision was. --> <p v-else-if="beat.type === 'chose'" class="beat-chose">{{ beat.label }}</p> <img v-else-if="beat.type === 'image'" class="beat-image" :src="beat.src" :alt="beat.alt ?? ''" /> <video v-else-if="beat.type === 'video'" class="beat-image" :src="beat.src" :autoplay="beat.autoplay" :loop="beat.loop" :muted="beat.muted" :controls="beat.controls" /> </template> </div> <div class="choices"> <template v-for="choice in view.scene.choices" :key="choice.id"> <button :disabled="Boolean(choice.disabled)" :title="choice.disabled" @click="runner.apply(choice.command)">{{ choice.label }}</button> <!-- Why it can't be pressed, such as "You need 4 coins." --> <p v-if="choice.disabled" class="reason">{{ choice.disabled }}</p> </template> </div> </template> ``` Render `beats` rather than `body`, which holds the same words as markup text. Each beat is a [`SceneBeat`](https://ifloom.dev/docs/api/engine#scenebeat), told apart by its `type`: - `text` is a paragraph. - `say` is a spoken line. Its `name` is the name to show, the speaker's or the player's, and a bare quote that answers the line before has none. Its `who` is `'player'` on the player's own lines, for the stylesheet. - `image` and `video` are a picture and a clip. - `chose` is a choice the player made earlier in a [flowing scene](#render-a-flowing-scene). - `sound` renders nothing, because the audio player plays it. Each choice is a [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) with its `label`, its `price`, its `command`, and `disabled` set to the reason while it can't be pressed. Send `command` as it is, so your UI never builds a command for a choice. The engine refuses the same command for the same reason, so a greyed-out button and a refusal always agree. `view.scene.speaker` holds who the scene is with, with their `name` and `image`, and `view.scene.image` holds the scene's own picture. ## Render a flowing scene [#render-a-flowing-scene] A [flowing scene](https://ifloom.dev/docs/reference/flows) comes as beats and choices like any other scene, so the section above already renders it. `view.scene.beats` holds everything up to where the flow stopped, with a `chose` beat at each past choice, and `view.scene.fresh` is the index of the first beat the last choice brought. The React UI's `Scene` renders a flowing scene like any other, and each fold as a part the player opens and shuts. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** A flowing scene: everything up to where it stopped, the choices made on the way, a fold's beats together, and the decision it's waiting on. */ export function drawFlow(parent: HTMLElement, { view }: RunnerSnapshot): void { const prose = add(parent, 'div', '', 'prose') // The fold the beats are going into: a <details> the player opens and shuts, under the fold's words. let fold: { label: string; body: HTMLElement } | null = null view.scene.beats.forEach((beat, at) => { const label = beat.section?.fold if (typeof label !== 'string') fold = null else if (fold?.label !== label) { const details = add(prose, 'details') add(details, 'summary', label) fold = { label, body: details } } const into = fold?.body ?? prose const shown = beat.type === 'chose' ? add(into, 'p', beat.label, 'beat-chose') : beat.type === 'text' || beat.type === 'say' ? add(into, 'p', beat.text) : null // What the last choice brought, from `fresh` on, to fade in; what came before stays still. if (shown && at >= view.scene.fresh && view.scene.fresh > 0) shown.classList.add('fresh') }) drawChoices(add(parent, 'div', '', 'choices'), view.scene.choices) } ``` ```tsx tab="React" tab-group="framework" import { Game, Scene, Story } from '@ifloom/react' // A layout of your own, for mountGame's `layout`. The default layout has Scene in its Story already. export function Reading() { return ( <Game> <Story> {/* The open scene, or the room: its title, picture, beats and choices. */} <Scene /> </Story> </Game> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import type { SceneBeat } from '@ifloom/engine' import { runner, view } from './runner.ts' // A flowing scene: everything up to where it stopped, the choices made on the way, a fold's beats together, and the decision it's waiting on. // What the last choice brought, from `fresh` on, gets a class to fade it in; what came before stays still. const fresh = (at: number) => view.value.scene.fresh > 0 && at >= view.value.scene.fresh // The beats in runs: one on its own, or a fold's together, in a <details> the player opens and shuts. const runs = computed(() => { const out: { fold?: string; beats: { beat: SceneBeat; at: number }[] }[] = [] view.value.scene.beats.forEach((beat, at) => { const fold = typeof beat.section?.fold === 'string' ? beat.section.fold : undefined const last = out.at(-1) if (fold !== undefined && last?.fold === fold) last.beats.push({ beat, at }) else out.push({ fold, beats: [{ beat, at }] }) }) return out }) </script> <template> <div class="prose"> <component :is="run.fold === undefined ? 'div' : 'details'" v-for="(run, index) in runs" :key="index"> <summary v-if="run.fold !== undefined">{{ run.fold }}</summary> <template v-for="{ beat, at } in run.beats" :key="at"> <p v-if="beat.type === 'chose'" class="beat-chose" :class="{ fresh: fresh(at) }">{{ beat.label }}</p> <p v-else-if="beat.type === 'text' || beat.type === 'say'" :class="{ fresh: fresh(at) }">{{ beat.text }}</p> </template> </component> </div> <div class="choices"> <button v-for="choice in view.scene.choices" :key="choice.id" :disabled="Boolean(choice.disabled)" :title="choice.disabled" @click="runner.apply(choice.command)" > {{ choice.label }} </button> </div> </template> ``` A beat's `section` holds the ui hints of the section it sits in, so every beat of a `fold()` carries the fold's words in `section.fold`. The examples gather a fold's beats into a `<details>` under those words. `fresh` is 0 before the visit has taken a step, and the examples mark the beats from `fresh` on so the stylesheet can fade them in. While the flow waits on a minigame or a panel, `view.scene.choices` is empty. ## Render the room's actions [#render-the-rooms-actions] `view.actions` holds the buttons on offer besides the scene's choices, each a [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice). The plugins' come first, such as wait, sleep and the ways out, then the game's own [actions](https://ifloom.dev/docs/reference/glossary#action). The React UI's [`RoomActions`](https://ifloom.dev/docs/api/react#roomactions) renders them at the bottom of the story in the default layout, and [`ChoiceList`](https://ifloom.dev/docs/api/react#choicelist) renders any list of buttons the same way. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** The room's buttons, while no scene is open: each with its price, greyed out with why it can't be pressed, or warned. */ export function drawActions(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const action of view.actions) { // The price in a line, such as "2 coins · until evening". const button = add(parent, 'button', action.price ? `${action.label} (${action.price.text})` : action.label) button.disabled = Boolean(action.disabled) button.onclick = () => runner.apply(action.command) // Why it can't be pressed, such as "You need 3 coins.", or a warning that it will be refused. const note = action.disabled ?? action.warning if (note) add(parent, 'p', note, 'reason') } } ``` ```tsx tab="React" tab-group="framework" import { ChoiceList, Game, RoomActions, Scene, Story, useGame } from '@ifloom/react' // A layout of your own, for mountGame's `layout`. The default layout has RoomActions at the bottom of its Story. export function Layout() { return ( <Game> <Story> <Scene /> {/* The room's buttons, with their prices and reasons, while no scene is open. */} <RoomActions /> </Story> </Game> ) } // Or only some of them: ChoiceList renders any list of buttons the same way. export function FreeThings() { const { view } = useGame() return <ChoiceList choices={view.actions.filter((action) => !action.price?.stats?.length)} part="actions" /> } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // The room's buttons, while no scene is open: each with its price in a line, such as "2 coins · until evening", // greyed out with why it can't be pressed, or warned. </script> <template> <div class="bottom choices"> <template v-for="action in view.actions" :key="action.id"> <button :disabled="Boolean(action.disabled)" @click="runner.apply(action.command)"> {{ action.label }}<template v-if="action.price"> ({{ action.price.text }})</template> </button> <!-- Why it can't be pressed, such as "You need 3 coins.", or a warning that it will be refused. --> <p v-if="action.disabled ?? action.warning" class="reason">{{ action.disabled ?? action.warning }}</p> </template> </div> </template> ``` Show the `price` with the label. Its `text` is ready to read, such as "2 coins · until evening". A button with a `warning` can be pressed, but the command will be refused with that line, so show the warning under it. ## Render inline choices and tooltips [#render-inline-choices-and-tooltips] A `text` or `say` beat has `spans` when its line holds bold or italics, an inline action, a tooltip or a UI piece, each an [`InlineSpan`](https://ifloom.dev/docs/api/engine#inlinespan). The React UI's `Scene` renders every span and its own UI pieces `modal` and `image`, and `mountGame`'s `inline` option takes a component for a piece of your own. ```ts tab="Plain JS" tab-group="framework" import type { InlineSpan, RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** The scene's lines with their spans: bold and italics, inline actions, tooltips and UI pieces. */ export function drawProse(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const beat of view.scene.beats) { if (beat.type === 'text' || beat.type === 'say') drawLine(add(parent, 'p'), beat.text, beat.spans) } } /** A line's words. Without spans it's plain text; with them, each span is rendered by its type. */ function drawLine(line: HTMLElement, text: string, spans: InlineSpan[] | undefined): void { if (!spans) { line.textContent = text return } for (const span of spans) { switch (span.type) { case 'text': line.append(span.text) break case 'bold': case 'italic': add(line, span.type === 'bold' ? 'strong' : 'em', span.text) break case 'action': { // An inline action: a button in the line that presses the choice, greyed out with its reason. const button = add(line, 'button', span.text, 'inline-action') button.disabled = Boolean(span.choice.disabled) if (span.choice.disabled) button.title = span.choice.disabled button.onclick = () => runner.apply(span.choice.command) break } case 'tip': // A tooltip: the words, with the note on hover. add(line, 'abbr', span.text, 'tip').title = span.tip break case 'ui': // A UI piece, [[ui:name|words|arg]]: render it by name, or show its words. add(line, 'span', span.text, 'ui').dataset.ui = span.name break } } } ``` ```tsx tab="React" tab-group="framework" import { mountGame, type InlineProps } from '@ifloom/react' import module from './game.ts' // The React UI renders bold, italics, inline actions and tooltips itself, and the UI pieces modal and image. // A piece of your own, [[ui:stamp|Paid|red]], is a component by its name in `inline`. function Stamp({ text, args }: InlineProps) { return <span style={{ color: args[0] ?? 'inherit', border: '2px solid', padding: '0 4px' }}>{text}</span> } mountGame(module.build(), { inline: { stamp: Stamp } }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // The scene's lines with their spans: bold and italics, inline actions, tooltips and UI pieces. // The vue template's Line.vue does the same, with notes that open on a tap. </script> <template> <template v-for="(beat, at) in view.scene.beats" :key="at"> <p v-if="beat.type === 'text' || beat.type === 'say'"> <template v-if="!beat.spans">{{ beat.text }}</template> <template v-for="(span, index) in beat.spans" v-else :key="index"> <template v-if="span.type === 'text'">{{ span.text }}</template> <strong v-else-if="span.type === 'bold'">{{ span.text }}</strong> <em v-else-if="span.type === 'italic'">{{ span.text }}</em> <!-- An inline action: a button in the line that presses the choice, greyed out with its reason. --> <button v-else-if="span.type === 'action'" class="inline-action" :disabled="Boolean(span.choice.disabled)" :title="span.choice.disabled" @click="runner.apply(span.choice.command)" > {{ span.text }} </button> <!-- A tooltip: the words, with the note on hover. --> <abbr v-else-if="span.type === 'tip'" class="tip" :title="span.tip">{{ span.text }}</abbr> <!-- A UI piece, [[ui:name|words|arg]]: render it by name, or show its words. --> <span v-else class="ui" :data-ui="span.name">{{ span.text }}</span> </template> </p> </template> </template> ``` Render a beat without `spans` as its `text`. With them, render each span by its `type`: - `text`, `bold` and `italic` are words, plain or in a `<strong>` or an `<em>`. - `action` is a button inside the line that sends `choice.command`, greyed out with `choice.disabled`. - `tip` is words with a note, `tip`, shown on hover. - `ui` is a [UI piece](https://ifloom.dev/docs/reference/glossary#ui-piece), rendered by its `name`, or as its words when your UI has no piece by that name. The view leaves inline choices out of `view.scene.choices` and `view.actions`, so they never show twice. An inline action whose choice is hidden comes as plain words, and the sentence still reads. [Put a choice inside a line of text](https://ifloom.dev/docs/how-to/put-a-choice-in-a-line) writes them in content. ## Render inputs [#render-inputs] `view.inputs` holds each [input](https://ifloom.dev/docs/reference/inputs) on offer now, in the order the game declares them, as an [`InputView`](https://ifloom.dev/docs/api/engine#inputview). Each has its `label`, its `type` and limits, the `options` of a choice, and its value, read from the [kv](https://ifloom.dev/docs/reference/glossary#kv) key it writes. The React UI's `Scene` renders them between a scene's words and its choices, and [`InputFields`](https://ifloom.dev/docs/api/react#inputfields) renders them under the room in the default layout. ```ts tab="Plain JS" tab-group="framework" import type { InputView, RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** The inputs on offer now, such as the cat's name. What the player enters goes back as an `input` command. */ export function drawInputs(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const input of view.inputs) drawInput(add(parent, 'div', '', 'input'), input) } function drawInput(parent: HTMLElement, input: InputView): void { if (input.type === 'choice') { for (const option of input.options) { add(parent, 'button', option.label).onclick = () => runner.apply({ type: 'input', id: input.id, to: option.value }) } return } const form = add(parent, 'form') const field = add(add(form, 'label', input.label), 'input') field.type = input.type === 'number' ? 'number' : 'text' field.value = input.value === null ? '' : String(input.value) if (input.maxLength !== null) field.maxLength = input.maxLength if (input.min !== null) field.min = String(input.min) if (input.max !== null) field.max = String(input.max) add(form, 'button', 'OK').type = 'submit' form.onsubmit = (event) => { event.preventDefault() // A value that breaks the input's rules is refused with why, such as "Up to 16 letters." const sent = runner.apply({ type: 'input', id: input.id, to: input.type === 'number' ? Number(field.value) : field.value }) if (!sent.ok) add(form, 'p', sent.reason, 'reason') } } ``` ```tsx tab="React" tab-group="framework" import { Game, InputFields, Scene, Story } from '@ifloom/react' // A layout of your own, for mountGame's `layout`. The default layout has InputFields under the Scene. export function Layout() { return ( <Game> <Story> <Scene /> {/* A field for each input on offer, with the reason under it when a value is refused. */} <InputFields /> </Story> </Game> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { ref } from 'vue' import type { InputView } from '@ifloom/engine' import { runner, view } from './runner.ts' // The inputs on offer now, such as the cat's name. What the player enters goes back as an `input` command. // The vue template's InputField.vue renders one; here they're all in one component. const typed = ref<Record<string, string>>({}) const refused = ref<Record<string, string>>({}) function submit(input: InputView) { const entered = typed.value[input.id] ?? (input.value === null ? '' : String(input.value)) // A value that breaks the input's rules is refused with why, such as "Up to 16 letters." const sent = runner.apply({ type: 'input', id: input.id, to: input.type === 'number' ? Number(entered) : entered }) refused.value = { ...refused.value, [input.id]: sent.ok ? '' : sent.reason } } </script> <template> <div v-for="input in view.inputs" :key="input.id" class="input"> <template v-if="input.type === 'choice'"> <button v-for="option in input.options" :key="String(option.value)" @click="runner.apply({ type: 'input', id: input.id, to: option.value })"> {{ option.label }} </button> </template> <form v-else @submit.prevent="submit(input)"> <label> {{ input.label }} <input :value="typed[input.id] ?? input.value ?? ''" :type="input.type === 'number' ? 'number' : 'text'" :maxlength="input.maxLength ?? undefined" :min="input.min ?? undefined" :max="input.max ?? undefined" @input="typed = { ...typed, [input.id]: ($event.target as HTMLInputElement).value }" /> </label> <button type="submit">OK</button> <p v-if="refused[input.id]" class="reason">{{ refused[input.id] }}</p> </form> </div> </template> ``` Send what the player enters as `{ type: 'input', id, to }`. The engine refuses a value that breaks the input's rules with the reason, such as "Up to 16 letters.", so show the reason by the field. Give the field the input's `maxLength`, `min` and `max`, so the browser holds to them too. An input stays in the view while its `when` holds, so a name field goes once the player has given a name. ## Play transitions and reveals [#play-transitions-and-reveals] The engine carries [ui hints](https://ifloom.dev/docs/reference/ui-hints) to the view unchanged. A scene's are in `view.scene.ui`, and a block's are on the first beat it makes, in `beat.ui`. The React UI's `Scene` plays the `transition` and `reveal` hints itself, and [`useScene`](https://ifloom.dev/docs/api/react#usescene) gives a scene component of your own the same timing. The Plain JS and Vue tabs read the two hints with these helpers: ```ts /** * src/hints.ts: reads the React UI's `transition` and `reveal` hints for a UI of your own. The Plain JS and Vue * snippets import it as `../hints.ts`; in a game it sits beside them. */ import type { SceneBeat, View } from '@ifloom/engine' /** The screen in a view, and how it comes in and goes out, from its scene's `ui.transition`. */ export function transitionOf(view: View): { key: string; in: string; out: string; ms: number } { const spec = view.scene.ui?.transition const pair: { in?: string; out?: string; ms?: number } = typeof spec === 'string' ? { in: spec, out: spec } : (spec ?? {}) return { key: view.scene.key, in: pair.in ?? 'none', out: pair.out ?? 'none', ms: pair.ms ?? 300 } } /** The beats to render, each with the reveal it waits for (how and when), or null for those shown with the scene. */ export function withReveals(beats: readonly SceneBeat[]): { beat: SceneBeat; reveal: { as: string; at: number } | null }[] { let at = 0 let reveal: { as: string; at: number } | null = null return beats.map((beat) => { const hint = beat.ui?.reveal if (hint) { at += hint.delay ?? 800 reveal = { as: hint.as ?? 'fade', at } } return { beat, reveal } }) } /** True when the player asks for less motion. There's no matchMedia outside a browser, such as in tests. */ export const reducedMotion = (): boolean => typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches ``` ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot, View } from '@ifloom/engine' import { reducedMotion, transitionOf, withReveals } from '../hints.ts' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** The view whose scene is on the page, and the wait before the next one comes in. */ let shown: View | null = null let timer: ReturnType<typeof setTimeout> | undefined /** The scene's title and words in an <article>, coming in by its transition, each revealed line after its delay. */ function article(view: View, entering: boolean): HTMLElement { const scene = document.createElement('article') const transition = transitionOf(view) scene.style.setProperty('--ms', `${transition.ms}ms`) // Rendered again on the same screen, its reveals have played already. if (entering && !reducedMotion()) scene.dataset.transitionIn = transition.in else scene.dataset.revealed = '' // A click shows every line at once. scene.onclick = () => (scene.dataset.revealed = '') add(scene, 'h2', view.scene.title) for (const { beat, reveal } of withReveals(view.scene.beats)) { if (beat.type !== 'text' && beat.type !== 'say') continue const line = add(scene, 'p', beat.text) if (reveal && !reducedMotion()) { line.dataset.reveal = reveal.as line.style.setProperty('--at', `${reveal.at}ms`) } } return scene } /** The scene, in a box that stays on the page. When the screen changes, the old one goes out by its `out`, then the new one comes in. */ export function drawTransition(box: HTMLElement, { view }: RunnerSnapshot): void { const before = shown shown = view clearTimeout(timer) const old = box.querySelector<HTMLElement>('article') const going = before && transitionOf(before) const changed = going !== null && going.key !== view.scene.key if (going && changed && old && !reducedMotion() && going.out !== 'none') { // The screen before goes out, and can't be pressed or read out meanwhile. old.dataset.transitionOut = going.out old.style.setProperty('--ms', `${going.ms}ms`) old.setAttribute('aria-hidden', 'true') old.inert = true timer = setTimeout(() => box.replaceChildren(article(view, true)), going.ms) return } box.replaceChildren(article(view, before === null || changed)) } ``` ```tsx tab="React" tab-group="framework" import type { CSSProperties } from 'react' import { useScene } from '@ifloom/react' // Scene plays the screen's ui.transition and each block's ui.reveal itself. A scene component of your own keeps the // same timing with useScene: the transition, the beats in runs with each run's reveal, and skip to show them all. export function RevealedLines() { const { transition, groups, motion, pending, skip } = useScene() return ( <article key={transition.key} data-transition-in={motion ? transition.in : undefined} style={{ '--ms': `${transition.ms}ms` } as CSSProperties}> {groups.map((group, at) => ( <div key={at} data-reveal={motion && group.reveal ? group.reveal.as : undefined} style={group.reveal ? ({ '--at': `${group.reveal.at}ms` } as CSSProperties) : undefined} > {group.beats.map(({ beat, index }) => (beat.type === 'text' || beat.type === 'say' ? <p key={index}>{beat.text}</p> : null))} </div> ))} {pending ? <button onClick={skip}>Show all</button> : null} </article> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed, ref, shallowRef, watch } from 'vue' import { reducedMotion, transitionOf, withReveals } from '../hints.ts' import { view } from './runner.ts' // The scene, coming in by its transition, each revealed line after its delay. When the screen changes, // the old one goes out by its `out`, then the new one comes in. A click shows every line at once. const motion = !reducedMotion() // The view whose scene is on the page, and whether it's going out. const shown = shallowRef(view.value) const leaving = ref(false) const revealed = ref(false) const transition = computed(() => transitionOf(shown.value)) let timer: ReturnType<typeof setTimeout> | undefined watch(view, (now) => { clearTimeout(timer) if (now.scene.key === transition.value.key) return void (shown.value = now) const swap = () => { leaving.value = false revealed.value = false shown.value = now } if (!motion || transition.value.out === 'none') return swap() leaving.value = true timer = setTimeout(swap, transition.value.ms) }) </script> <template> <article :key="transition.key" :data-transition-in="motion ? transition.in : undefined" :data-transition-out="leaving ? transition.out : undefined" :data-revealed="revealed ? '' : undefined" :aria-hidden="leaving ? 'true' : undefined" :inert="leaving" :style="{ '--ms': `${transition.ms}ms` }" @click="revealed = true" > <h2>{{ shown.scene.title }}</h2> <template v-for="({ beat, reveal }, at) in withReveals(shown.scene.beats)" :key="at"> <p v-if="beat.type === 'text' || beat.type === 'say'" :data-reveal="motion && reveal ? reveal.as : undefined" :style="reveal ? { '--at': `${reveal.at}ms` } : undefined" > {{ beat.text }} </p> </template> </article> </template> ``` This CSS plays `fade` and `slide-up`, the names the showcase uses. Add rules for the other names your game uses: ```css @keyframes fade-in { from { opacity: 0; } } @keyframes fade-out { to { opacity: 0; } } @keyframes rise-in { from { opacity: 0; transform: translateY(1.25rem); } } [data-transition-in] { animation: fade-in var(--ms) ease-out backwards; } [data-transition-in="slide-up"] { animation-name: rise-in; } [data-transition-in="none"] { animation: none; } [data-transition-out] { animation: fade-out var(--ms) ease-in forwards; pointer-events: none; } [data-transition-out="none"] { animation: none; } [data-reveal] { animation: fade-in 400ms ease-out var(--at) backwards; } [data-reveal="slide-up"] { animation-name: rise-in; } [data-revealed] [data-reveal] { animation: none; } @media (prefers-reduced-motion: reduce) { [data-transition-in], [data-transition-out], [data-reveal] { animation: none; } } ``` Play a transition only when `view.scene.key` changes. A choice that keeps the scene open gives a new view with the same key, and playing the scene's `in` again there looks like a flicker. Keep a revealed line in the page while it waits, rather than hiding it with `display: none`, so a screen reader still reads it. [`startRevealSkip`](https://ifloom.dev/docs/api/browser#startrevealskip) shows every held-back line on a key press, as a click does. A game with `@ifloom/react` gets the two hints typed from there. A game without it declares them itself: ```ts fragment declare module '@ifloom/engine' { interface SceneUi { transition?: { in?: string; out?: string; ms?: number } | string } interface BlockUi { reveal?: { delay?: number; as?: string } } } ``` For more on what these sections render, see: - [Scenes](https://ifloom.dev/docs/reference/scenes), [Flows](https://ifloom.dev/docs/reference/flows), [Prose](https://ifloom.dev/docs/reference/prose) and [Inputs](https://ifloom.dev/docs/reference/inputs). - [The view](https://ifloom.dev/docs/reference/view) and [UI hints](https://ifloom.dev/docs/reference/ui-hints). - [Write a flowing scene](https://ifloom.dev/docs/how-to/write-a-flowing-scene) and [Add a transition or reveal lines](https://ifloom.dev/docs/how-to/add-a-transition). # Start your own UI (https://ifloom.dev/docs/how-to/render/start) Use these pages when you render the game with code of your own, or when you place the React UI's parts in a layout of your own. Start from the template for your framework (`vanilla`, `react` or `vue`), made as [Create a game](https://ifloom.dev/docs/how-to/create-a-game) shows. [Choosing a UI](https://ifloom.dev/docs/explanation/choosing-a-ui) compares the ways to put a game on screen. Every example on these pages comes in three tabs: - **Plain JS** is DOM code on the runner, as in the `vanilla` template's `src/main.ts`. Each part is a function `draw<Thing>(parent, snapshot)` that imports `runner`, `add` and `drawChoices` from `./runner.ts`. - **React** uses the React UI, `@ifloom/react`. It places the ready-made part for the feature in a layout, or builds a component of your own with the React UI's hooks. - **Vue** is a component with no props that reads `view`, `snapshot` and `runner` from `./runner.ts`, as the `vue` template's components do. The site remembers the tab you choose on every page. Every example renders the showcase, Small Town (`examples/showcase`), so it uses the showcase's ids, such as the vendor `counter` and the timer `flat.ring`. ## Start the runner [#start-the-runner] Make the [runner](https://ifloom.dev/docs/reference/runner) once, start the browser helpers beside it, render its snapshot, and render again on every change. The React UI's `mountGame` does all of it in one call. ```ts tab="Plain JS" tab-group="framework" // src/main.ts: the vanilla template's start, cut down to the loop. import type { RenderedChoice, RunnerSnapshot } from '@ifloom/engine' import { startAudio } from '@ifloom/audio' import { browserRunner, startClock, startKeys } from '@ifloom/browser' import module from './game.ts' // The game module builds the game, and lists what the loader found wrong with it. const { game, problems } = module.build() if (problems.length) console.warn(problems) // A new game with a random seed, undo, saves in localStorage and an autosave each turn. const runner = await browserRunner(game) // Each helper follows the runner by itself. startAudio plays view.audio from the first click or key press, // startClock ticks the timers and minigames, and startKeys presses the choices on 1 to 9. startAudio(runner) startClock(runner) startKeys(runner) const root = document.querySelector<HTMLElement>('#root')! /** An element with a class and some text, added to `parent`. The text goes in as textContent, so prose can't add markup. */ function add<K extends keyof HTMLElementTagNameMap>(parent: HTMLElement, tag: K, text = '', className = ''): HTMLElementTagNameMap[K] { const element = parent.appendChild(document.createElement(tag)) if (text) element.textContent = text if (className) element.className = className return element } /** Buttons that send their commands, each greyed out with its reason when it can't be pressed. */ function drawChoices(parent: HTMLElement, choices: RenderedChoice[]): void { for (const choice of choices) { const button = add(parent, 'button', choice.label) button.disabled = Boolean(choice.disabled) if (choice.disabled) button.title = choice.disabled button.onclick = () => runner.apply(choice.command) if (choice.disabled) add(parent, 'p', choice.disabled, 'reason') } } /** The whole screen, rendered again from each snapshot. */ function draw({ view }: RunnerSnapshot): void { root.replaceChildren() add(root, 'h1', view.title) if (view.scene.title) add(root, 'h2', view.scene.title) for (const beat of view.scene.beats) if (beat.type === 'text' || beat.type === 'say') add(root, 'p', beat.text) // The open scene's choices, or the room's actions while no scene is open. drawChoices(add(root, 'div', '', 'choices'), [...view.scene.choices, ...view.actions]) add(root, 'p', view.stats.map((stat) => `${stat.label}: ${stat.text}`).join(' · '), 'stats') } // Render again whenever the runner hands over a new snapshot. runner.subscribe(draw) draw(runner.snapshot()) ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import module from './game.ts' // mountGame makes the runner with browserRunner, plays the sound, runs the clock and maps the keys. // Its default layout renders every part the Render it yourself pages cover. mountGame(module.build()) ``` ```ts tab="Vue" tab-group="framework" // src/runner.ts: the vue template's runner, and its snapshot as Vue state. import { computed, shallowRef } from 'vue' import { startAudio } from '@ifloom/audio' import { browserRunner, startClock, startKeys } from '@ifloom/browser' import module from './game.ts' // The game module builds the game, and lists what the loader found wrong with it. const { game, problems } = module.build() if (problems.length) console.warn(problems) // A new game with a random seed, undo, saves in localStorage and an autosave each turn. export const runner = await browserRunner(game) // The runner hands every listener a new snapshot whenever anything in it changes, so a shallowRef is enough. export const snapshot = shallowRef(runner.snapshot()) runner.subscribe((next) => { snapshot.value = next }) // The view, which is most of what the components render. export const view = computed(() => snapshot.value.view) // Each helper follows the runner by itself. The player plays view.audio from the first click or key press, // and its play() plays a file on demand. startClock ticks the timers and minigames, and startKeys presses the choices on 1 to 9. export const player = startAudio(runner) startClock(runner) startKeys(runner) ``` A UI talks to the engine through three members of the [`Runner`](https://ifloom.dev/docs/api/engine#runner): - `runner.snapshot()` returns the [`RunnerSnapshot`](https://ifloom.dev/docs/api/engine#runnersnapshot), one value with all a UI renders. It holds the view, the settings, the backlog, undo and the saves. - `runner.apply(command)` runs a command, such as the `command` of the button the player pressed. - `runner.subscribe(listener)` calls `listener` with each new snapshot, and returns the function that stops it. The runner makes a new snapshot whenever any part of it changes, and returns the same object until then. A framework that compares values therefore renders again exactly when something is new. React reads it with `useSyncExternalStore(runner.subscribe, runner.snapshot)`, and the Vue tab keeps it in a `shallowRef`. In Vue, `src/main.ts` then mounts the app with `createApp(App).mount('#root')`. [`browserRunner`](https://ifloom.dev/docs/api/browser#browserrunner) gives the runner a random seed, undo 50 steps deep, saves in `localStorage` and an autosave each turn. Pass it any [`RunnerOptions`](https://ifloom.dev/docs/api/engine#runneroptions) to change those, such as `browserRunner(game, { backlog: true })`. Each helper follows the runner on its own, and returns the function that stops it: - [`startAudio`](https://ifloom.dev/docs/api/audio#startaudio) plays the game's music and sounds. Browsers allow no sound before the player clicks or presses a key, so nothing plays until then. - [`startClock`](https://ifloom.dev/docs/api/browser#startclock) sends a `tick` about every 100 ms while a timer or a minigame's timer runs. The engine keeps no clock of its own. - [`startKeys`](https://ifloom.dev/docs/api/browser#startkeys) presses the choices on screen on the keys 1 to 9, and a minigame's inputs on its keys. Each template's `vite.config.ts` already adds its framework's Vite plugin to the [Vite preset](https://ifloom.dev/docs/api/cli-vite), which knows no framework. ## Put the parts together [#put-the-parts-together] Split the screen into parts as it grows, one for each feature the other pages render. Each part reads the snapshot and sends its own commands, so the parts don't depend on each other. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. Each part below imports runner, add and drawChoices from there too. import { add } from './runner.ts' import { drawActions } from './actions.ts' import { drawEntities } from './entities.ts' import { drawInputs } from './inputs.ts' import { drawNotices } from './notices.ts' import { drawPanel } from './panel.ts' import { drawScene } from './scene.ts' import { drawStats } from './stats.ts' /** The screen, put together from the parts on the Render it yourself pages: a side column, the story, the notices and any open panel. */ export function drawLayout(parent: HTMLElement, snapshot: RunnerSnapshot): void { parent.replaceChildren() const side = add(parent, 'aside', '', 'sidebar') add(side, 'h1', snapshot.view.title) drawStats(side, snapshot) drawEntities(side, snapshot) const story = add(parent, 'main', '', 'story') drawScene(story, snapshot) drawInputs(story, snapshot) drawActions(add(story, 'div', '', 'actions'), snapshot) drawNotices(parent, snapshot) drawPanel(parent, snapshot) } ``` ```tsx tab="React" tab-group="framework" import { Game, InputFields, Notices, Overlay, PanelHost, RoomActions, Scene, Section, Sidebar, StatList, Story, Title } from '@ifloom/react' // A layout of your own, for mountGame's `layout`: the React UI's parts, placed as the default layout places them. // Each Render it yourself page names the part for its feature. export function Layout() { return ( <Game> <Sidebar> <Title /> <Section id="stats" title="Stats" collapsible open> <StatList /> </Section> </Sidebar> <Story> <Scene /> <InputFields /> <RoomActions /> </Story> <PanelHost /> <Overlay> <Notices /> </Overlay> </Game> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' import Actions from './Actions.vue' import Entities from './Entities.vue' import Inputs from './Inputs.vue' import Notices from './Notices.vue' import Panel from './Panel.vue' import Scene from './Scene.vue' import Stats from './Stats.vue' // The screen, put together from the parts on the Render it yourself pages: a side column, the story, the notices and any open panel. // Each part imports runner and view from ./runner.ts. </script> <template> <aside class="sidebar"> <h1>{{ view.title }}</h1> <Stats /> <Entities /> </aside> <main class="story"> <Scene /> <Inputs /> <Actions /> </main> <Notices /> <Panel /> </template> ``` In Plain JS, move the runner, `add` and `drawChoices` from `src/main.ts` into `src/runner.ts` and export them. Then call `drawLayout(root, snapshot)` from the listener. In React, pass the layout to `mountGame(module.build(), { layout: Layout })`, and [Arrange the layout](https://ifloom.dev/docs/how-to/arrange-the-layout) moves and folds its sections. In Vue, render `<Layout />` from `src/App.vue`. The other pages render one feature in each section: - [Render the scene and its choices](https://ifloom.dev/docs/how-to/render/scene) covers the scene, flowing scenes, the room's actions, inline choices and tooltips, inputs, and transitions. - [Render stats, things and what changed](https://ifloom.dev/docs/how-to/render/stats-and-things) covers stats, the things the player holds, listed entities, changes, notices and dice rolls. - [Render pictures and play sound](https://ifloom.dev/docs/how-to/render/pictures-and-sound) covers layered pictures with hotspots, and the audio player. - [Render timers, minigames and panels](https://ifloom.dev/docs/how-to/render/timers-minigames-panels) covers countdowns, a running minigame and a panel over the story. - [Render saves, settings and the backlog](https://ifloom.dev/docs/how-to/render/saves-and-settings) covers a load screen, a settings screen, the backlog and undo. Each plugin adds its own part of the view under `view.plugins`, by plugin id, such as the places plugin's ways out at `view.plugins.places.exits`. The plugins' pages in this section render them: [the calendar, locations and people](https://ifloom.dev/docs/how-to/render/world-plugins), [quests, achievements and statuses](https://ifloom.dev/docs/how-to/render/progress-plugins), [the inventory, shop, jobs and wardrobe](https://ifloom.dev/docs/how-to/render/things-plugins), [messages, the feed and devices](https://ifloom.dev/docs/how-to/render/phone-plugins), and [cheats, unlocks and debug](https://ifloom.dev/docs/how-to/render/player-tools). For every field and member, see: - [The view](https://ifloom.dev/docs/reference/view) and [`View`](https://ifloom.dev/docs/api/engine#view). - [The runner](https://ifloom.dev/docs/reference/runner). - [Commands](https://ifloom.dev/docs/reference/commands). - [Browser helpers](https://ifloom.dev/docs/api/browser) and [the audio player](https://ifloom.dev/docs/api/audio). # Render stats, things and what changed (https://ifloom.dev/docs/how-to/render/stats-and-things) Render the numbers and lists around the story: the player's stats, the [things](https://ifloom.dev/docs/reference/glossary#thing) the player holds, what the last command changed, notices and dice. Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. ## Render the stats [#render-the-stats] `view.stats` lists the player's stats that are listed and visible now, in the order the game declares them, each a [`StatView`](https://ifloom.dev/docs/api/engine#statview). The React UI's [`StatList`](https://ifloom.dev/docs/api/react#statlist) renders them in the side column of the default layout, as bars or pips when a stat's `display` hint asks. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** The listed stats: each label and value, a bar from min to max, and how far to the next level. */ export function drawStats(parent: HTMLElement, { view }: RunnerSnapshot): void { const list = add(parent, 'dl', '', 'stats') for (const stat of view.stats) { add(list, 'dt', stat.level ? `${stat.label} (level ${stat.level.level})` : stat.label) const value = add(list, 'dd', stat.text) const bar = add(value, 'meter') Object.assign(bar, { min: stat.min, max: stat.max, value: stat.value }) // Towards the next level, from 0 to 1; there's no next one at the top. if (stat.level?.next != null) Object.assign(add(value, 'progress'), { max: 1, value: stat.level.progress }) } } ``` ```tsx tab="React" tab-group="framework" import { Game, Scene, Section, Sidebar, StatList, Story, useGame, useWords } from '@ifloom/react' // A layout of your own, for mountGame's `layout`, with the stats in the side column as the default layout has them. export function Layout() { const words = useWords() return ( <Game> <Sidebar> <Section id="stats" title={words('stats')} collapsible open> {/* Each listed stat, with a bar or pips by its `display` hint, and its level. */} <StatList /> </Section> <Purse /> </Sidebar> <Story> <Scene /> </Story> </Game> ) } // One stat your own way, from statsById, which has every stat, listed or not. export function Purse() { const { view } = useGame() return <p className="purse">{view.statsById.coins?.text}</p> } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' // The listed stats: each label and value, a bar from min to max, and how far to the next level. </script> <template> <dl class="stats"> <template v-for="stat in view.stats" :key="stat.key"> <dt> {{ stat.label }}<template v-if="stat.level"> (level {{ stat.level.level }})</template> </dt> <dd> {{ stat.text }} <meter :min="stat.min" :max="stat.max" :value="stat.value" /> <!-- Towards the next level, from 0 to 1; there's no next one at the top. --> <progress v-if="stat.level?.next != null" :max="1" :value="stat.level.progress" /> </dd> </template> </dl> </template> ``` Each stat has its `label`, its value written through its `format` as `text`, such as "12 coins", and its `min` and `max` for a bar. A stat with levels has `level`, with its level, the value the next one starts at, and `progress` towards it from 0 to 1. `view.statsById` has every stat by id, listed or not, for one you render your own way, such as a purse in the corner. ## Render what the player holds [#render-what-the-player-holds] The engine keeps no list of what the player holds. A plugin that keeps things puts its own in the view, such as the inventory's `view.plugins.inventory.things`, which [Render things to use and drop](https://ifloom.dev/docs/how-to/render/things-plugins#render-things-to-use-and-drop) renders, and a game that keeps things in kv keys reads them as any key. `view.entities` lists each listed [kind](https://ifloom.dev/docs/reference/glossary#kind) with its entities, as [`EntitiesView`](https://ifloom.dev/docs/api/engine#entitiesview)s, and the React UI's [`EntityTable`](https://ifloom.dev/docs/api/react#entitytable) renders a listed kind as a table wherever you place it. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** Each listed kind, with its entities and the stats the player can see on each. */ export function drawEntities(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const kind of view.entities) { if (!kind.entries.length) continue add(parent, 'h3', kind.plural) const list = add(parent, 'ul', '', 'entities') for (const entity of kind.entries) { const row = add(list, 'li', entity.name) row.dataset.entity = entity.ref // A kind's flags, such as { met: true }, to split or style the list by. for (const [flag, holds] of Object.entries(entity.flags)) if (holds) row.classList.add(flag) for (const stat of entity.stats) add(row, 'span', `${stat.label} ${stat.text}`, 'stat') } } } ``` ```tsx tab="React" tab-group="framework" import { EntityTable, Game, Scene, Section, Sidebar, Story } from '@ifloom/react' // A layout of your own, for mountGame's `layout`. A table of a kind is yours to place. export function Layout() { return ( <Game> <Sidebar> <Section id="people" title="People you know" collapsible> {/* A listed kind's entities and their stats, from view.entities. */} <EntityTable kinds={['character']} /> </Section> </Sidebar> <Story> <Scene /> </Story> </Game> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' // Each listed kind with its entities and the stats the player can see on each. // A kind's flags, such as { met: true }, become classes to split or style the list by. const flagged = (flags: Record<string, boolean>) => Object.keys(flags).filter((flag) => flags[flag]) </script> <template> <template v-for="kind in view.entities" :key="kind.id"> <template v-if="kind.entries.length"> <h3>{{ kind.plural }}</h3> <ul class="entities"> <li v-for="entity in kind.entries" :key="entity.ref" :class="flagged(entity.flags)" :data-entity="entity.ref"> {{ entity.name }} <span v-for="stat in entity.stats" :key="stat.key" class="stat">{{ stat.label }} {{ stat.text }}</span> </li> </ul> </template> </template> </template> ``` Each entity in `view.entities` carries the stats the player can see on it and its kind's [flags](https://ifloom.dev/docs/reference/glossary#flags), such as `{ met: true }`. Split or style the list by its flags, such as the people you've met and the rest. The engine has already left out every entity that isn't listed, so your UI hides nothing more. ## Render what changed [#render-what-changed] `view.changes` lists the stats the last command moved, each a [`ChangeView`](https://ifloom.dev/docs/api/engine#changeview) with its signed `text`, the `name` of what moved, and `by`, which is positive when it went up. The React UI's [`Changes`](https://ifloom.dev/docs/api/react#changes) renders them as pills, and the default layout leaves it out, so the React tab places it after the scene. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** What the last command moved, as pills: `+30 coins`, `-1 Energy`, `+4 Ava`, marked up or down for styling. */ export function drawChanges(parent: HTMLElement, { view }: RunnerSnapshot): void { if (!view.changes.length) return const list = add(parent, 'ul', '', 'changes') for (const change of view.changes) { const pill = add(list, 'li', change.name ? `${change.text} ${change.name}` : change.text, 'change') pill.dataset.stat = change.stat if (change.of) pill.dataset.of = change.of pill.dataset.dir = change.by > 0 ? 'up' : 'down' } } ``` ```tsx tab="React" tab-group="framework" import { Changes, Scene } from '@ifloom/react' // What the last command moved, as pills under the scene: `+30 coins`, `-5%`, `+2 Ava`. // Each pill is a `change` part with data-stat, data-of and data-dir="up" or "down" for your CSS. export function StoryWithChanges() { return ( <> <Scene /> <Changes /> </> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' // What the last command moved, as pills: `+30 coins`, `-1 Energy`, `+4 Ava`, marked up or down for styling. </script> <template> <ul v-if="view.changes.length" class="changes"> <li v-for="change in view.changes" :key="`${change.of ?? 'player'} ${change.stat}`" class="change" :data-stat="change.stat" :data-of="change.of" :data-dir="change.by > 0 ? 'up' : 'down'" > {{ change.text }} {{ change.name }} </li> </ul> </template> ``` The list stays empty until the game names the stats to track in its content's `changes.stats` ([`ChangesDef`](https://ifloom.dev/docs/api/engine#changesdef)). It compares the stats before and after the command, so a stat that went up and back down in one command isn't listed. A change from a plugin's modifier, such as a status starting, is listed too. ## Render notices [#render-notices] `view.notices.unseen` lists every [notice](https://ifloom.dev/docs/reference/notices) the player hasn't dismissed, newest first, each a [`NoticeView`](https://ifloom.dev/docs/api/engine#noticeview) with its `title`, `text`, `image` and `tag`. The React UI's [`Notices`](https://ifloom.dev/docs/api/react#notices) renders them as toasts in a corner, in the default layout's `Overlay`, and [`NoticeStrip`](https://ifloom.dev/docs/api/react#noticestrip) renders them as a strip over the story instead. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' /** The notices not yet dismissed, newest first, each with a button that marks it seen. */ export function drawNotices(parent: HTMLElement, { view }: RunnerSnapshot): void { const toasts = add(parent, 'div', '', 'notices') toasts.setAttribute('role', 'status') for (const notice of view.notices.unseen) { const toast = add(toasts, 'div', '', 'notice') if (notice.tag) toast.dataset.tag = notice.tag add(toast, 'strong', notice.title) if (notice.text) add(toast, 'p', notice.text) add(toast, 'button', 'Dismiss').onclick = () => runner.apply({ type: 'dismiss', id: notice.id }) } } /** A badge with how many are unseen under a tag, such as the post. */ export function drawPostBadge(parent: HTMLElement, { view }: RunnerSnapshot): void { const count = view.notices.byTag.post ?? 0 if (count) add(parent, 'span', String(count), 'badge') } ``` ```tsx tab="React" tab-group="framework" import { Game, NoticeStrip, Notices, Overlay, Scene, Sidebar, Story, useGame } from '@ifloom/react' import { Badge } from '@ifloom/react/kit' // A layout of your own, for mountGame's `layout`. The default layout has Notices in its Overlay. export function Layout() { return ( <Game> <Sidebar> <PostBadge /> </Sidebar> <Story> {/* Or the unseen notices in a strip over the story. */} <NoticeStrip /> <Scene /> </Story> <Overlay> {/* Toasts in a corner, each with a button that dismisses it. */} <Notices /> </Overlay> </Game> ) } // How many are unseen under a tag, from view.notices.byTag. export function PostBadge() { const { view } = useGame() const count = view.notices.byTag.post ?? 0 return count ? <Badge>{count} new</Badge> : null } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // The notices not yet dismissed, newest first, each with a button that marks it seen, and a badge for the post. </script> <template> <span v-if="view.notices.byTag.post" class="badge">{{ view.notices.byTag.post }}</span> <div class="notices" role="status"> <div v-for="notice in view.notices.unseen" :key="notice.id" class="notice" :data-tag="notice.tag ?? undefined"> <strong>{{ notice.title }}</strong> <p v-if="notice.text">{{ notice.text }}</p> <button @click="runner.apply({ type: 'dismiss', id: notice.id })">Dismiss</button> </div> </div> </template> ``` Send `{ type: 'dismiss', id }` when the player has read a notice, or `{ type: 'dismiss' }` to dismiss them all. `view.notices.byTag` counts the unseen notices by tag, for a badge on the post or the phone. ## Render dice rolls [#render-dice-rolls] `view.rolls` lists the rolls the last command made, in order, each a [`Roll`](https://ifloom.dev/docs/api/engine#roll) with its dice, each die's face, what was added, the total and, with a target, whether it passed. The React UI's `Scene` renders a [`DiceRoll`](https://ifloom.dev/docs/api/react#diceroll) above a block whose `dice` hint names the roll, and the other rolls over the scene for a moment. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** The rolls the last command made, as they landed: `2d6: 4 + 5 + 1 = 10 (passed)`. The next command clears them. */ export function drawRolls(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const roll of view.rolls) { const plus = roll.plus ? ` + ${roll.plus}` : '' const outcome = roll.passed === undefined ? '' : roll.passed ? ' (passed)' : ' (failed)' const line = add(parent, 'p', `${roll.dice}: ${roll.faces.join(' + ')}${plus} = ${roll.total}${outcome}`, 'roll') line.dataset.roll = roll.key if (roll.critical) line.dataset.critical = roll.critical } } ``` ```tsx tab="React" tab-group="framework" import { DiceRoll, useScene } from '@ifloom/react' // Scene renders a roll above the block whose `dice` hint names it, and the others over the scene for a moment. // To show them somewhere of your own: the last command's rolls while they're new, so each tumbles once. export function LastRolls() { const { rolls } = useScene() return ( <div key={rolls.at} className="rolls"> {rolls.fresh.map((roll) => ( <DiceRoll key={roll.key} roll={roll} /> ))} </div> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import type { Roll } from '@ifloom/engine' import { view } from './runner.ts' // The rolls the last command made, as they landed: `2d6: 4 + 5 + 1 = 10 (passed)`. The next command clears them. const line = (roll: Roll) => `${roll.dice}: ${roll.faces.join(' + ')}${roll.plus ? ` + ${roll.plus}` : ''} = ${roll.total}${roll.passed === undefined ? '' : roll.passed ? ' (passed)' : ' (failed)'}` </script> <template> <p v-for="(roll, at) in view.rolls" :key="at" class="roll" :data-roll="roll.key" :data-critical="roll.critical">{{ line(roll) }}</p> </template> ``` The next command clears `view.rolls`, so each roll shows once. To put the dice beside the line that tells the outcome, find the beat whose block names the roll in its hint, `beat.ui?.dice`. Put the rolls in an element with `aria-live="polite"`, so a screen reader reads the result. For more on what these sections render, see: - [Stats](https://ifloom.dev/docs/reference/stats), [Entities](https://ifloom.dev/docs/reference/entities), [Changes](https://ifloom.dev/docs/reference/changes), [Notices](https://ifloom.dev/docs/reference/notices) and [Rolls](https://ifloom.dev/docs/reference/rolls). - [The view](https://ifloom.dev/docs/reference/view). - [Give the player things to hold and use](https://ifloom.dev/docs/how-to/give-the-player-things), [Tell the player when something happens](https://ifloom.dev/docs/how-to/show-a-notice) and [Roll dice for a check](https://ifloom.dev/docs/how-to/roll-dice). # Render the inventory, shop, jobs and wardrobe (https://ifloom.dev/docs/how-to/render/things-plugins) Render the plugins that deal in [things](https://ifloom.dev/docs/reference/glossary#thing) and work: what the player can use or drop from the [inventory](https://ifloom.dev/docs/reference/plugins/inventory), a vendor's counter from the [shop](https://ifloom.dev/docs/reference/plugins/shop), a board from [jobs](https://ifloom.dev/docs/reference/plugins/jobs), and what the player wears from the [wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe). Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. In the React tabs, each plugin's UI comes from its `/react` subpath and goes in `mountGame`'s `plugins`, as [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis) explains. The shop's counter, the job board and the wardrobe open as [panels](https://ifloom.dev/docs/reference/glossary#panel), so render each by its name from the panel part that [Render a panel](https://ifloom.dev/docs/how-to/render/timers-minigames-panels#render-a-panel) builds. The Plain JS tabs here are the functions that part calls. ## Render things to use and drop [#render-things-to-use-and-drop] `view.plugins.inventory` holds what you hold as an [`InventoryView`](https://ifloom.dev/docs/api/plugin-inventory#inventoryview), with each thing in `things`, the played protagonist's first and then the player's. The React UI's [`InventoryCard`](https://ifloom.dev/docs/api/plugin-inventory#inventorycard), from `inventoryUi`, renders in place of the React UI's own `Inventory` in the side column. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** What you hold, each thing with a button to use it, when it has a use, and one to drop it. */ export function drawInventory(parent: HTMLElement, { view }: RunnerSnapshot): void { const inventory = view.plugins.inventory if (!inventory) return for (const thing of inventory.things) { const row = add(parent, 'div', '', 'thing') add(row, 'span', thing.count > 1 ? `${thing.name} ×${thing.count}` : thing.name).title = thing.description ?? '' drawChoices(row, thing.use ? [thing.use, thing.drop] : [thing.drop]) } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { inventoryUi } from '@ifloom/plugin-inventory/react' import module from './game.ts' // InventoryCard is rendered in the sidebar and the inventory panel, with a button that uses each usable thing. mountGame(module.build(), { plugins: [inventoryUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // What you hold, each thing with a button to use it, when it has a use, and one to drop it. </script> <template> <div v-for="thing in view.plugins.inventory?.things" :key="`${thing.at}/${thing.ref}`" class="thing"> <span :title="thing.description ?? ''">{{ thing.count > 1 ? `${thing.name} ×${thing.count}` : thing.name }}</span> <button v-for="button in thing.use ? [thing.use, thing.drop] : [thing.drop]" :key="button.id" :disabled="Boolean(button.disabled)" :title="button.disabled" @click="runner.apply(button.command)" > {{ button.label }} </button> </div> </template> ``` Each thing has its `name`, `description`, `image` and `count`, a `drop` button, and a `use` button when it has a use. The plugin's strings word both buttons, and a refused one has its reason in `disabled`. `view.held` lists the same things without the buttons, which [Render what the player holds](https://ifloom.dev/docs/how-to/render/stats-and-things#render-what-the-player-holds) renders. [`useInventory`](https://ifloom.dev/docs/api/plugin-inventory#useinventory) gives the inventory's view to a React component of your own. ## Render a shop counter [#render-a-shop-counter] `view.plugins.shop.panel` holds the vendor whose counter is open as a [`VendorView`](https://ifloom.dev/docs/api/plugin-shop#vendorview), or null while none is. The React UI's `shopUi` renders the `shop` panel as that vendor's [`ShopCounter`](https://ifloom.dev/docs/api/plugin-shop#shopcounter), in a dialog titled with its name. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner, add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** The `shop` panel, from drawPanel: shop.open('counter') opens it with { vendor: 'counter' }. */ export function drawShop(parent: HTMLElement, { view }: RunnerSnapshot): void { // The vendor whose counter the open panel shows; null while it's shut. const vendor = view.plugins.shop?.panel if (!vendor) return add(parent, 'h2', vendor.name) if (vendor.closed) add(parent, 'p', vendor.closed, 'reason') for (const good of vendor.goods) { const row = add(parent, 'div', '', 'good') add(row, 'strong', good.name) if (good.buy.price) add(row, 'span', good.buy.price.text, 'price') if (good.stock !== null) add(row, 'span', `${good.stock} left`, 'stock') // Ready-made buttons, with today's price and why one can't be pressed. drawChoices(row, good.sell ? [good.buy, good.sell] : [good.buy]) } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { shopUi } from '@ifloom/plugin-shop/react' import module from './game.ts' // The shop panel is rendered as the vendor's counter, in a dialog titled with its name. mountGame(module.build(), { plugins: [shopUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { runner, view } from './runner.ts' // The `shop` panel, shown from Panel.vue: shop.open('counter') opens it with { vendor: 'counter' }. // The vendor whose counter the open panel shows; null while it's shut. const vendor = computed(() => view.value.plugins.shop?.panel) </script> <template> <div v-if="vendor" class="shop"> <h2>{{ vendor.name }}</h2> <p v-if="vendor.closed" class="reason">{{ vendor.closed }}</p> <div v-for="good in vendor.goods" :key="good.entity" class="good"> <strong>{{ good.name }}</strong> <span v-if="good.buy.price" class="price">{{ good.buy.price.text }}</span> <span v-if="good.stock !== null" class="stock">{{ good.stock }} left</span> <!-- Ready-made buttons, with today's price and why one can't be pressed. --> <button v-for="button in good.sell ? [good.buy, good.sell] : [good.buy]" :key="button.id" :disabled="Boolean(button.disabled)" :title="button.disabled" @click="runner.apply(button.command)" > {{ button.label }} </button> </div> </div> </template> ``` Nothing about a vendor shows until content opens its counter with `shop.open('counter')`, which sets `view.panel` to `{ panel: 'shop', with: { vendor: 'counter' } }`. Each of the vendor's `goods` is a [`GoodView`](https://ifloom.dev/docs/api/plugin-shop#goodview) with a `buy` button, and a `sell` button when the vendor buys things back. Each button's `price` is today's, discount included, and its `disabled` is the reason it's refused, such as `Sold out.` or `You need 4 coins.`. Render `fullPrice` struck out beside the price, since it's set only on a day the good is marked down. `stock` is null for a good that never runs out. `closed` is the reason the vendor is shut, such as its opening hours, while it is. [`useShop`](https://ifloom.dev/docs/api/plugin-shop#useshop) gives the shop's view to a React component of your own. A shop needs no counter. A location's actions can send `shop.buy` directly, and they come in `view.actions` with their price and reason like any other button. `view.plugins.shop.vendors` lists every vendor, with `here` and `closed` worked out, for a UI that shows a vendor without a panel. ## Render a job board [#render-a-job-board] `view.plugins.jobs.panel` holds the jobs on the open board, each a [`JobView`](https://ifloom.dev/docs/api/plugin-jobs#jobview), or null while the board is shut. The React UI's `jobsUi` renders the `jobs` panel as the [`JobBoard`](https://ifloom.dev/docs/api/plugin-jobs#jobboard), in a dialog. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** The `jobs` panel, from drawPanel: jobs.open() opens it, and jobs.open(['dogs']) with only those. */ export function drawJobs(parent: HTMLElement, { view }: RunnerSnapshot): void { // The jobs on the open board, already filtered by what it was opened with; null while it's shut. for (const job of view.plugins.jobs?.panel ?? []) { const card = add(parent, 'section', '', 'job') add(card, 'h3', job.rank ? `${job.name}: ${job.rank.name}` : job.name) add(card, 'p', job.description) if (job.pay) add(card, 'p', `Pays ${job.pay.text} a shift`) if (job.nextShift) add(card, 'p', job.nextShift.inDays ? `Next shift in ${job.nextShift.inDays} days` : 'A shift today') // Ready-made buttons: Apply while you don't have the job, Work and Quit while you do, each with why it can't be done. drawChoices( card, [job.apply, job.work, job.quit].filter((button) => button !== null), ) } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { jobsUi } from '@ifloom/plugin-jobs/react' import module from './game.ts' // The jobs panel is rendered as the JobBoard, with only the jobs it was opened with if it names any. mountGame(module.build(), { plugins: [jobsUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import type { RenderedChoice } from '@ifloom/engine' import { runner, view } from './runner.ts' // The `jobs` panel, shown from Panel.vue: jobs.open() opens it, and jobs.open(['dogs']) with only those. // The view's panel is the jobs on the open board, already filtered; null while it's shut. const jobs = computed(() => view.value.plugins.jobs?.panel ?? []) const buttons = (...all: (RenderedChoice | null)[]) => all.filter((button) => button !== null) </script> <template> <section v-for="job in jobs" :key="job.id" class="job"> <h3> {{ job.name }}<template v-if="job.rank">: {{ job.rank.name }}</template> </h3> <p>{{ job.description }}</p> <p v-if="job.pay">Pays {{ job.pay.text }} a shift</p> <p v-if="job.nextShift">{{ job.nextShift.inDays ? `Next shift in ${job.nextShift.inDays} days` : 'A shift today' }}</p> <!-- Ready-made buttons: Apply while you don't have the job, Work while you do, each with why it can't be done. --> <button v-for="button in buttons(job.apply, job.work, job.quit)" :key="button.id" :disabled="Boolean(button.disabled)" :title="button.disabled" @click="runner.apply(button.command)" > {{ button.label }} </button> </section> </template> ``` Content opens the board with `jobs.open()`, or `jobs.open(['dogs'])` for only some jobs, and the plugin has already filtered `panel` to those. A job not held has an `apply` button, whose `disabled` is the reason an application is refused. A job held has a `work` button, with the shift's cost as its `price`, and a `quit` button. Each job also has its `pay` for a shift, its `rank` while held, and `nextShift`. `nextShift.inDays` is how many days away the next shift is, 0 for today, and its `day` is the calendar's day, or the turn without a calendar. The plugin raises notices tagged `jobs` for promotions and firing. `view.plugins.jobs.jobs` lists every job, held or not, and [`useJobs`](https://ifloom.dev/docs/api/plugin-jobs#usejobs) gives the jobs' view to a React component of your own. ## Render what the player wears [#render-what-the-player-wears] `view.plugins.wardrobe` holds what whoever you're playing wears as a [`WardrobeView`](https://ifloom.dev/docs/api/plugin-wardrobe#wardrobeview), with each slot in `slots` and the things you could put on in `spare`. The React UI's `wardrobeUi` renders the `wardrobe` panel as the [`WardrobeCard`](https://ifloom.dev/docs/api/plugin-wardrobe#wardrobecard), which a closet location's button opens. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** What you have on, slot by slot, with a button to take each thing off, and what else you could wear. */ export function drawWardrobe(parent: HTMLElement, { view }: RunnerSnapshot): void { const wardrobe = view.plugins.wardrobe if (!wardrobe) return for (const slot of wardrobe.slots) { const row = add(parent, 'div', '', 'slot') add(row, 'span', `${slot.label}: ${slot.name ?? 'nothing'}`) // Ready-made buttons, worded by the plugin's strings: Take off, Wear raincoat. if (slot.takeOff) drawChoices(row, [slot.takeOff]) } drawChoices( parent, wardrobe.spare.map((spare) => spare.wear), ) } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { wardrobeUi } from '@ifloom/plugin-wardrobe/react' import module from './game.ts' // The wardrobe panel renders the WardrobeCard: a place with wardrobe.closet() gets a button that opens it. mountGame(module.build(), { plugins: [wardrobeUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // What you have on, slot by slot, with a button to take each thing off, and what else you could wear. // The buttons are ready-made, worded by the plugin's strings: Take off, Wear raincoat. </script> <template> <template v-if="view.plugins.wardrobe"> <div v-for="slot in view.plugins.wardrobe.slots" :key="slot.id" class="slot"> {{ slot.label }}: {{ slot.name ?? 'nothing' }} <button v-if="slot.takeOff" :disabled="Boolean(slot.takeOff.disabled)" @click="runner.apply(slot.takeOff.command)">{{ slot.takeOff.label }}</button> </div> <button v-for="spare in view.plugins.wardrobe.spare" :key="spare.entity" :disabled="Boolean(spare.wear.disabled)" :title="spare.wear.disabled" @click="runner.apply(spare.wear.command)" > {{ spare.wear.label }} </button> </template> </template> ``` Each slot has its `label`, the `name` of the thing in it or null, and a `takeOff` button while it holds something. Each spare thing has a `wear` button, which the plugin's strings word, such as **Wear raincoat**. `wardrobeUi` adds nothing to the side column, so place [`WardrobeSection`](https://ifloom.dev/docs/api/plugin-wardrobe#wardrobesection) in your layout's `Sidebar` to keep what the player wears on screen. [`useWardrobe`](https://ifloom.dev/docs/api/plugin-wardrobe#usewardrobe) gives the wardrobe's view to a React component of your own. For more on what these sections render, see: - [Inventory](https://ifloom.dev/docs/reference/plugins/inventory), [Shop](https://ifloom.dev/docs/reference/plugins/shop), [Jobs](https://ifloom.dev/docs/reference/plugins/jobs) and [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe). - [Panels](https://ifloom.dev/docs/reference/panels). - [Give the player things to hold and use](https://ifloom.dev/docs/how-to/give-the-player-things), [Open a shop, a job board or another panel](https://ifloom.dev/docs/how-to/open-a-panel) and [Let the player get dressed](https://ifloom.dev/docs/how-to/dress-the-player). # Render timers, minigames and panels (https://ifloom.dev/docs/how-to/render/timers-minigames-panels) Render the countdowns of running timers, a minigame while the player plays it, and a [panel](https://ifloom.dev/docs/reference/glossary#panel) open over the story. Set up the runner first, with `startClock` beside it, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. The engine keeps no clock, so timers and minigames stand still until something sends ticks. ## Render timers [#render-timers] `view.timers` lists each running [timer](https://ifloom.dev/docs/reference/glossary#timer) in the order they started, as a [`TimerView`](https://ifloom.dev/docs/api/engine#timerview) with its `id`, its `label`, and the milliseconds `left` of its `total`. The React UI's `Scene` renders a [`Countdown`](https://ifloom.dev/docs/api/react#countdown) under a block whose `timer` hint names a timer, [`Timers`](https://ifloom.dev/docs/api/react#timers) renders them all, and [`useTimer`](https://ifloom.dev/docs/api/react#usetimer) gives you one to render your own way. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts, which runs startClock(runner) to send the ticks. import { add } from './runner.ts' /** A countdown for each running timer: its label, a bar that empties, and the seconds left. */ export function drawTimers(parent: HTMLElement, { view }: RunnerSnapshot): void { for (const timer of view.timers) { const box = add(parent, 'div', '', 'timer') box.dataset.timer = timer.id // A quarter or less left: render it as urgent. if (timer.left <= timer.total / 4) box.dataset.urgent = '' if (timer.label) add(box, 'span', timer.label, 'timer-label') Object.assign(add(box, 'progress'), { max: timer.total, value: timer.left }) add(box, 'span', `${Math.ceil(timer.left / 1000)}s`, 'timer-left') } } ``` ```tsx tab="React" tab-group="framework" import { Game, Scene, Sidebar, Story, Timers, useTimer } from '@ifloom/react' // Scene renders a Countdown under a block whose `timer` hint names a timer. A layout of your own can put them anywhere. export function Layout() { return ( <Game> <Sidebar> {/* A countdown for every running timer. */} <Timers /> <RingingPhone /> </Sidebar> <Story> <Scene /> </Story> </Game> ) } // One timer your own way: the phone fades as it rings out. export function RingingPhone() { const ringing = useTimer('flat.ring') if (!ringing) return null return <span style={{ opacity: 0.4 + (0.6 * ringing.left) / ringing.total }}>☎</span> } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' // A countdown for each running timer: its label, a bar that empties, and the seconds left. // The vue template's runner.ts runs startClock(runner) to send the ticks. </script> <template> <div v-for="timer in view.timers" :key="timer.id" class="timer" :data-timer="timer.id" :data-urgent="timer.left <= timer.total / 4 ? '' : undefined"> <span v-if="timer.label" class="timer-label">{{ timer.label }}</span> <progress :max="timer.total" :value="timer.left" /> <span class="timer-left">{{ Math.ceil(timer.left / 1000) }}s</span> </div> </template> ``` Render the countdown from `left / total`, and the seconds from `left`. A timer is in the view only while it runs, so its countdown goes when it runs out or the game stops it. To put a countdown under the block that names it, read the block's hint from each beat, `beat.ui?.timer`. A `<progress>` moves in steps with each tick, so for a smooth bar scale a `div` with `transform: scaleX(left / total)` and a 100 ms linear transition. ## Render a minigame [#render-a-minigame] `view.minigame` holds the [minigame](https://ifloom.dev/docs/reference/minigames) being played, as a [`MinigameView`](https://ifloom.dev/docs/api/engine#minigameview), and `view.scene` holds its title and the running state's words. The React UI's `Scene` renders a [`MinigameCard`](https://ifloom.dev/docs/api/react#minigamecard) while one runs, and [`useMinigame`](https://ifloom.dev/docs/api/react#useminigame) reads it for a component of your own. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts, which runs startClock(runner) to send the ticks. import { add, drawChoices } from './runner.ts' /** The minigame being played, under the scene's title and beats (its words): a bar counting down its timer, and a button for each input that does something now. */ export function drawMinigame(parent: HTMLElement, { view }: RunnerSnapshot): void { const minigame = view.minigame if (!minigame) return const box = add(parent, 'section', '', 'minigame') box.dataset.state = minigame.state if (minigame.timeLeft !== null && minigame.timeTotal) { const timer = add(box, 'div', '', 'timer') timer.setAttribute('role', 'progressbar') timer.setAttribute('aria-label', 'Time left') add(timer, 'span').style.transform = `scaleX(${minigame.timeLeft / minigame.timeTotal})` } // Each input is a button like any other, labelled by the game's minigame.<input> strings: Up, Space. drawChoices(add(box, 'div', '', 'choices'), minigame.inputs) } ``` ```tsx tab="React" tab-group="framework" import { useMinigame } from '@ifloom/react' // Scene renders a MinigameCard while one runs, and runs its clock. For one minigame of your own, give mountGame's // `panels` a component under the minigame's id, such as `{ arrows: ArrowPad }`. export function ArrowPad() { // With keys: true, the arrow keys press the inputs too. const { minigame, send } = useMinigame({ keys: true }) if (!minigame) return null return ( <div className="arrows"> <p>{minigame.label}</p> {/* Each input's words come from the game's minigame.<input> strings: Up, Space. */} {minigame.inputs.map((input) => ( <button key={input.id} onClick={() => send(input.id)}> {input.label} </button> ))} </div> ) } ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' // The minigame being played, under the scene's title and beats (its words): a bar counting down its timer, and a // button for each input that does something now. The vue template's runner.ts runs startClock(runner) to send the ticks. </script> <template> <section v-if="view.minigame" class="minigame" :data-state="view.minigame.state"> <div v-if="view.minigame.timeLeft !== null && view.minigame.timeTotal" class="timer" role="progressbar" aria-label="Time left"> <span :style="{ transform: `scaleX(${view.minigame.timeLeft / view.minigame.timeTotal})` }" /> </div> <div class="choices"> <!-- Each input's words come from the game's minigame.<input> strings: Up, Space. --> <button v-for="input in view.minigame.inputs" :key="input.id" @click="runner.apply(input.command)">{{ input.label }}</button> </div> </section> </template> ``` Each of the minigame's `inputs` is a ready button, with its words in `label` and the `{ type: 'minigame', input }` it sends in `command`. Render a bar from `timeLeft` and `timeTotal` while the state has a timer, and read the minigame's own kv store in `kv`, such as a score. [`startKeys`](https://ifloom.dev/docs/api/browser#startkeys) presses the inputs on the minigame's `keys`, or on the arrow keys and space, whatever renders the panel. To render one minigame your own way, check `view.minigame.id`, such as the showcase's `arrows`. In the React UI, give `mountGame`'s `panels` a component under the minigame's id, such as `{ arrows: ArrowPad }`, and it renders in place of the `MinigameCard`. ## Render a panel [#render-a-panel] `view.panel` holds the panel open over the story, as an [`OpenPanel`](https://ifloom.dev/docs/api/engine#openpanel) with its name in `panel` and what content opened it with in `with`, or null. The React UI's [`PanelHost`](https://ifloom.dev/docs/api/react#panelhost) renders the panels it knows over the story in the default layout, and a panel of your own goes in `mountGame`'s `panels` under its name. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // runner and add, as in the vanilla template's src/main.ts. import { add, runner } from './runner.ts' import { drawShop } from './shop.ts' /** The panel open over the story, rendered by its name, with a Close button unless a scene holds it open. */ export function drawPanel(parent: HTMLElement, snapshot: RunnerSnapshot): void { const { view } = snapshot if (!view.panel) return const dialog = add(parent, 'section', '', 'panel') dialog.setAttribute('role', 'dialog') dialog.setAttribute('aria-label', view.panel.panel) const box = add(dialog, 'div') // The shop's counter (see the shop plugin's page); any other panel shows what it was opened with. if (view.panel.panel === 'shop') drawShop(box, snapshot) else add(box, 'pre', JSON.stringify(view.panel.with, null, 2)) if (!view.panel.scene) add(box, 'button', 'Close').onclick = () => runner.apply({ type: 'closePanel' }) } ``` ```tsx tab="React" tab-group="framework" import { mountGame, type PanelComponent } from '@ifloom/react' import { InventoryCard } from '@ifloom/plugin-inventory/react' import module from './game.ts' // PanelHost, in the default layout, renders view.panel by its name. A panel of your own goes in `panels`, over a built-in one: // content opens this one with { panel: 'pockets' }, and it's given what the panel was opened with as `data`. const Pockets: PanelComponent = () => <InventoryCard title="Your pockets" /> mountGame(module.build(), { panels: { pockets: Pockets } }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { runner, view } from './runner.ts' import ShopCounter from './ShopCounter.vue' // The panel open over the story, rendered by its name, with a Close button unless a scene holds it open. // The vue template's App.vue renders <Panel v-if="view.panel" :panel="view.panel" />; this one reads view.panel itself. </script> <template> <section v-if="view.panel" class="panel" role="dialog" :aria-label="view.panel.panel"> <div> <!-- The shop's counter (see the shop plugin's page); any other panel shows what it was opened with. --> <ShopCounter v-if="view.panel.panel === 'shop'" /> <pre v-else>{{ JSON.stringify(view.panel.with, null, 2) }}</pre> <button v-if="!view.panel.scene" @click="runner.apply({ type: 'closePanel' })">Close</button> </div> </section> </template> ``` Render the panel by its name, over everything else. A plugin's panel shows what its own view holds for it, such as the open counter's vendor in `view.plugins.shop.panel`, already filtered by the panel's `with`. Send `{ type: 'closePanel' }` when the player closes it. A scene's own panel has `scene` set and stays while the scene is open, so give it no Close button. The `vanilla` and `vue` templates start with a panel that shows its name and `with`, for you to replace. In the React UI, `PanelHost` renders `inventory` and `stats` itself, and each plugin UI the game lists in `plugins` brings its own, such as `shop` and `jobs`. [Render the inventory, shop, jobs and wardrobe](https://ifloom.dev/docs/how-to/render/things-plugins) renders the shop's and the jobs' panels. For more on what these sections render, see: - [Timers](https://ifloom.dev/docs/reference/timers), [Minigames](https://ifloom.dev/docs/reference/minigames) and [Panels](https://ifloom.dev/docs/reference/panels). - [Browser helpers](https://ifloom.dev/docs/api/browser), for `startClock` and `startKeys`. - [Add a countdown](https://ifloom.dev/docs/how-to/add-a-countdown), [Build a minigame](https://ifloom.dev/docs/how-to/build-a-minigame) and [Open a shop, a job board or another panel](https://ifloom.dev/docs/how-to/open-a-panel). # Render the calendar, locations and people (https://ifloom.dev/docs/how-to/render/world-plugins) Render the world around the story: the time of day from the [calendar](https://ifloom.dev/docs/reference/plugins/calendar), the [location](https://ifloom.dev/docs/reference/glossary#location) the player is at from [places](https://ifloom.dev/docs/reference/plugins/places), and the people from the [cast](https://ifloom.dev/docs/reference/plugins/cast). Set up the runner first, as [Start your own UI](https://ifloom.dev/docs/how-to/render/start) shows. In the React tabs, each plugin's UI comes from its `/react` subpath and goes in `mountGame`'s `plugins`, as [Show plugins in the React UI](https://ifloom.dev/docs/how-to/react/show-plugin-uis) explains. ## Render the clock [#render-the-clock] `view.plugins.calendar` holds the time as a [`CalendarView`](https://ifloom.dev/docs/api/plugin-calendar#calendarview), with the day, the weekday, the period and the whole line in `label`, which is also in `view.when`. The React UI's [`CalendarClock`](https://ifloom.dev/docs/api/plugin-calendar#calendarclock), from `calendarUi`, renders in place of the React UI's own `Clock`, in the side column and in the top bar on a phone. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add, as in the vanilla template's src/main.ts. import { add } from './runner.ts' /** Where the game is in time, with the calendar's pieces on it for a stylesheet, and a nudge at curfew. */ export function drawCalendar(parent: HTMLElement, { view }: RunnerSnapshot): void { const calendar = view.plugins.calendar if (!calendar) return const clock = add(parent, 'p', calendar.label, 'clock') Object.assign(clock.dataset, { day: String(calendar.day), weekday: calendar.weekday, period: calendar.period }) // The last period of the day, with the curfew binding: time for bed. if (calendar.curfew) add(parent, 'p', 'It’s late. Time for bed.', 'curfew') } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { calendarUi } from '@ifloom/plugin-calendar/react' import module from './game.ts' // CalendarClock is rendered wherever the React UI’s own Clock is. mountGame(module.build(), { plugins: [calendarUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { view } from './runner.ts' // Where the game is in time, with the calendar's pieces on it for a stylesheet, and a nudge at curfew. </script> <template> <template v-if="view.plugins.calendar"> <p class="clock" :data-day="view.plugins.calendar.day" :data-weekday="view.plugins.calendar.weekday" :data-period="view.plugins.calendar.period"> {{ view.plugins.calendar.label }} </p> <!-- The last period of the day, with the curfew binding: time for bed. --> <p v-if="view.plugins.calendar.curfew" class="curfew">It’s late. Time for bed.</p> </template> </template> ``` Put the day, the weekday and the period on the clock's element as data attributes, so a stylesheet can colour the night. `curfew` is true in the last period of the day while the curfew binds, which is the moment to send the player to bed. `CalendarClock` sets `data-day`, `data-weekday`, `data-period` and `data-curfew` the same way, and [`useCalendar`](https://ifloom.dev/docs/api/plugin-calendar#usecalendar) gives you the calendar's view in a React component of your own. ## Render the location and its exits [#render-the-location-and-its-exits] `view.plugins.places` holds where the player is as a [`PlacesView`](https://ifloom.dev/docs/api/plugin-places#placesview), with the `location`, its `exits` and the `things` lying there. The React UI's [`LocationCard`](https://ifloom.dev/docs/api/plugin-places#locationcard) and [`Exits`](https://ifloom.dev/docs/api/plugin-places#exits), from `placesUi`, go in the story before the room's actions. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** Where you are: the place's name and picture, the ways out, and what lies here to pick up. */ export function drawPlace(parent: HTMLElement, { view }: RunnerSnapshot): void { const places = view.plugins.places if (!places?.location) return const { location } = places add(parent, 'h3', location.name) if (location.image) Object.assign(add(parent, 'img'), { src: location.image, alt: '' }) // Each exit is a button like any other, greyed out with why it can't be taken. if (places.exits.length) drawChoices(add(parent, 'nav', '', 'exits'), places.exits) for (const thing of places.things) { const row = add(parent, 'div', '', 'lying') add(row, 'span', thing.count > 1 ? `${thing.name} ×${thing.count}` : thing.name) drawChoices(row, [thing.pickUp]) } } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { placesUi } from '@ifloom/plugin-places/react' import module from './game.ts' // The LocationCard and the Exits go in the story, before the room’s actions. mountGame(module.build(), { plugins: [placesUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { runner, view } from './runner.ts' // Where you are: the place's name and picture, the ways out, and what lies here to pick up. const places = computed(() => view.value.plugins.places) </script> <template> <template v-if="places?.location"> <h3>{{ places.location.name }}</h3> <img v-if="places.location.image" :src="places.location.image" alt="" /> <!-- Each exit is a button like any other, greyed out with why it can't be taken. --> <nav class="exits"> <button v-for="exit in places.exits" :key="exit.id" :disabled="Boolean(exit.disabled)" :title="exit.disabled" @click="runner.apply(exit.command)"> {{ exit.label }} </button> </nav> <div v-for="thing in places.things" :key="thing.ref" class="lying"> {{ thing.name }}<template v-if="thing.count > 1"> ×{{ thing.count }}</template> <button :disabled="Boolean(thing.pickUp.disabled)" @click="runner.apply(thing.pickUp.command)">{{ thing.pickUp.label }}</button> </div> </template> </template> ``` Each exit and each thing's `pickUp` is a ready button, a [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice), so render it as any other button and send its `command`. An exit the player can't take has its reason in `disabled`, and an exit a lock hides isn't in the view at all. The location's name and words are also the room scene in `view.scene`, and its own actions are in `view.actions`, which [Render the scene and its choices](https://ifloom.dev/docs/how-to/render/scene) renders. `location` is null while the player is nowhere, so render nothing then. A location with a picture has it in `location.picture`, which [Render pictures and play sound](https://ifloom.dev/docs/how-to/render/pictures-and-sound) renders, and the plugin leaves its hotspots out while a scene is open. [`usePlaces`](https://ifloom.dev/docs/api/plugin-places#useplaces) gives the view with `go` and `pickUp` to a React component of your own. ## Render the people [#render-the-people] `view.plugins.cast` holds the people as a [`CastView`](https://ifloom.dev/docs/api/plugin-cast#castview), with who is here in `present` and everyone in `people`, each a [`PersonView`](https://ifloom.dev/docs/api/plugin-cast#personview). The React UI's `castUi` puts [`PeopleHere`](https://ifloom.dev/docs/api/plugin-cast#peoplehere) after the room's actions, and a People section in the side column that opens [`Relationships`](https://ifloom.dev/docs/api/plugin-cast#relationships) in a dialog. ```ts tab="Plain JS" tab-group="framework" import type { RunnerSnapshot } from '@ifloom/engine' // add and drawChoices, as in the vanilla template's src/main.ts. import { add, drawChoices } from './runner.ts' /** Who's here, each with their face and their Talk button, then everyone you've met. */ export function drawPeople(parent: HTMLElement, { view }: RunnerSnapshot): void { const cast = view.plugins.cast if (!cast) return for (const person of cast.present) { const card = add(parent, 'div', '', 'person') card.dataset.person = person.ref if (person.portrait) Object.assign(add(card, 'img'), { src: person.portrait, alt: '' }) add(card, 'strong', person.name) if (person.description) add(card, 'span', person.description) drawChoices(card, person.actions) } const met = cast.people.filter((person) => person.met) if (!met.length) return add(parent, 'h3', 'People you know') const list = add(parent, 'ul') for (const person of met) add(list, 'li', person.here ? `${person.fullName} (here)` : person.fullName) } ``` ```tsx tab="React" tab-group="framework" import { mountGame } from '@ifloom/react' import { castUi } from '@ifloom/plugin-cast/react' import module from './game.ts' // A People section in the side column opens everyone met, and who’s here goes after the room’s actions. mountGame(module.build(), { plugins: [castUi] }) ``` ```vue tab="Vue" tab-group="framework" <script setup lang="ts"> import { computed } from 'vue' import { runner, view } from './runner.ts' // Who's here, each with their face and their Talk button, then everyone you've met. const cast = computed(() => view.value.plugins.cast) const met = computed(() => cast.value?.people.filter((person) => person.met) ?? []) </script> <template> <div v-for="person in cast?.present" :key="person.ref" class="person" :data-person="person.ref"> <img v-if="person.portrait" :src="person.portrait" alt="" /> <strong>{{ person.name }}</strong> <span v-if="person.description">{{ person.description }}</span> <button v-for="talk in person.actions" :key="talk.id" :disabled="Boolean(talk.disabled)" :title="talk.disabled" @click="runner.apply(talk.command)"> {{ talk.label }} </button> </div> <template v-if="met.length"> <h3>People you know</h3> <ul> <li v-for="person in met" :key="person.ref">{{ person.fullName }}<template v-if="person.here"> (here)</template></li> </ul> </template> </template> ``` Each person has a name, a portrait, a `description` and their buttons in `actions`, such as **Talk**. `met` says whether the player has met them, and `here` whether they're at the player's location. `present` is empty while a scene is open. A character is an [entity](https://ifloom.dev/docs/reference/glossary#entity) of the cast's kind, so the stats the player can see on them, such as friendship, are on their entry in `view.entities` while the game lists the kind. [`usePeople`](https://ifloom.dev/docs/api/plugin-cast#usepeople) gives the cast's view to a React component of your own. For more on what these sections render, see: - [Calendar](https://ifloom.dev/docs/reference/plugins/calendar), [Places](https://ifloom.dev/docs/reference/plugins/places) and [Cast](https://ifloom.dev/docs/reference/plugins/cast). - [The view](https://ifloom.dev/docs/reference/view). - [Set up days and times of day](https://ifloom.dev/docs/how-to/set-up-the-clock), [Add a location](https://ifloom.dev/docs/how-to/add-a-location) and [Add a character with a schedule](https://ifloom.dev/docs/how-to/add-a-character). # Roll dice for a check (https://ifloom.dev/docs/how-to/roll-dice) Use this for a check, a roll against a target, such as two dice for skimming a stone or a d20 plus strength for climbing a wall. The steps build the showcase park's skimming stones. The player clicks a link in the line, the dice land, and the next line says how it went. ## Roll the dice [#roll-the-dice] Give an action the [`roll` effect](https://ifloom.dev/docs/reference/rolls#roll), with the dice and the target. Here a location's action rolls `2d6` against 8: ```ts import type { ActionDef } from '@ifloom/engine' export const skim: ActionDef = { id: 'skim', label: 'Skim a stone', effects: [ { kv: 'skimmed', to: true }, { roll: 'skim', dice: '2d6', against: 8 }, ], } ``` The engine keeps the total in the [kv store](https://ifloom.dev/docs/reference/glossary#kv) under `skim` and records the roll, which passes on 8 or more. Each try rolls afresh, and a replay of the save rolls the same dice. The `skimmed` key marks the day of the throw, for the next step. ## Write a line for each outcome [#write-a-line-for-each-outcome] Give each outcome a block whose `when` reads the roll with the [`roll` condition](https://ifloom.dev/docs/reference/conditions#roll). Add `ui: { dice: 'skim' }` to show the dice directly above that line in the React UI, which holds the line back until they settle: ```ts import { text, type Block, type Condition } from '@ifloom/engine' const skimmed = (when: Condition, words: string): Block => text(words, { when: { all: [{ kv: 'skimmed' }, when] }, ui: { dice: 'skim' } }) export const outcomes: Block[] = [ skimmed({ roll: 'skim', critical: 'max' }, 'Skip after skip, clean to the far bank.'), skimmed({ roll: 'skim', passed: true, critical: false }, 'The stone skips once, twice, again, and sinks most of the way across.'), skimmed({ roll: 'skim', passed: false }, 'Plop. It goes straight in, and the ducks look delighted.'), ] ``` `critical: 'max'` holds when every die showed its top face, a double six here. The engine keeps the latest roll under each key until the next one, so the `skimmed` key keeps these lines to the day of the throw. List it in your content's [`resets`](https://ifloom.dev/docs/reference/rules#resets) as `{ skimmed: false }`, and it goes back each day. ## Put the link in the line [#put-the-link-in-the-line] Link the action from the location's text with `[[act:skim|…]]`, so the player rolls from the sentence: ```ts import { text } from '@ifloom/engine' export const stones = text('Flat stones lie along the water’s edge. [[act:skim|Try to skim a stone]].') ``` Put the outcomes after this line in the location's `body`. [Put a choice inside a line of text](https://ifloom.dev/docs/how-to/put-a-choice-in-a-line) has the markup. ## Add a stat to the roll [#add-a-stat-to-the-roll] Give `plus` an [amount](https://ifloom.dev/docs/reference/glossary#amount), such as the player's stat with its modifiers: ```ts fragment { roll: 'climb', dice: '1d20', plus: { stat: 'strength' }, against: 12 } ``` Notation can carry its own number too, `'2d6+1'`, and `plus` adds to it. A roll with no `against` is a number with no outcome, so branch on the total with `{ kv: 'climb', gte: 15 }`, and print it in a line with `{{climb}}`. ## Roll without a click [#roll-without-a-click] Any effect list can roll, so the game can roll by itself. The showcase counts the ducks as you arrive at the park, with a [trigger](https://ifloom.dev/docs/reference/triggers): ```ts import type { TriggerDef } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' export const ducks: TriggerDef = { id: 'ducks', once: { per: 'turn' }, when: places.at('park'), effects: [{ roll: 'ducks', dice: '1d6+2' }] } ``` A line `{{ducks}} of them paddle over at once.` with `when: { roll: 'ducks' }` prints the count. No block has a `dice` hint for `ducks`, so the React UI shows those dice for a moment over the scene, in its [`DiceOverlay`](https://ifloom.dev/docs/reference/react/components#diceoverlay). ## Check it worked [#check-it-worked] Run `npm run check`, which reports dice notation the engine can't read and a `plus` or `against` that names an unknown stat. Then click the link in `npm run dev`. The dice tumble above the line, settle on the faces rolled with the total and Passed or Failed, and the line for the outcome appears. Each preset draws the dice its own way, such as `[4] [6] = 10` in Terminal. To render rolls in a UI of your own, see [Render dice rolls](https://ifloom.dev/docs/how-to/render/stats-and-things#render-dice-rolls). In the showcase, Small Town, the stones and the ducks are in [`examples/showcase/src/story/park.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/park.ts), and its tests play the check. For more, see: - [Dice rolls](https://ifloom.dev/docs/reference/rolls), with `Dice`, `Roll` and the checks. - The [`roll` condition](https://ifloom.dev/docs/reference/conditions#roll) and the React UI's [`dice` hint](https://ifloom.dev/docs/reference/react/hints#dice). - [The same save gives the same draws](https://ifloom.dev/docs/explanation/design#the-same-save-gives-the-same-draws). # Run a game in code (https://ifloom.dev/docs/how-to/run-a-game-in-code) Use this to play a game from your own code: a script, a tool, a test, or the loop under a UI of your own. Nothing here needs a page, so it runs the same in Node and in a browser. You need a game module, such as the one `npm create ifloom` makes in `src/game.ts`. ## Make a runner [#make-a-runner] A [runner](https://ifloom.dev/docs/reference/runner) holds the game in play, and your code talks only to it. Build the game from its game module, then make the runner with [`createRunner`](https://ifloom.dev/docs/reference/runner#createrunner) and a new game from [`startingState`](https://ifloom.dev/docs/reference/commands#startingstate): ```ts import { createRunner, describeProblem, startingState } from '@ifloom/engine' import module from './game.ts' const { game, problems } = module.build() for (const problem of problems) console.warn(describeProblem(problem)) const runner = createRunner(game, startingState(game)) ``` `createRunner` turns on nothing you don't ask for. Without a `seed`, `startingState` uses one made from the game's id, so every run draws the same variants, which suits a test. A game in front of a player passes its own, `startingState(game, { seed: Math.floor(Math.random() * 2 ** 31) })`. In a browser, [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner) from `@ifloom/browser` makes one with a random seed, 50 steps of undo, saves in `localStorage` and an autosave each turn: `const runner = await browserRunner(game)`. ## Send commands [#send-commands] Everything the player does is a [command](https://ifloom.dev/docs/reference/commands). Every button in the view carries the command it sends, so pass it back to `runner.apply`: ```ts given const knock = runner.view().scene.choices.find((choice) => choice.id === 'knock') if (knock) { const result = runner.apply(knock.command) if (!result.ok) console.warn(result.reason) } ``` `apply` answers with a [`Result`](https://ifloom.dev/docs/reference/glossary#result). A refused command changes nothing, and `reason` says why in words a player can read. A greyed-out button carries the same words in `disabled`, so the screen and the refusal agree. Build the few commands that come from no button yourself: - **`{ type: 'input', id, to }`** sends a value the game asked for, such as a name. See [Ask the player for a name](https://ifloom.dev/docs/how-to/ask-for-a-name). - **`{ type: 'minigame', input }`** presses one of a running minigame's inputs. - **`{ type: 'tick', ms }`** runs timers and a minigame's clock down. In a browser, [`startClock`](https://ifloom.dev/docs/reference/browser#startclock) sends it. - **`{ type: 'dismiss' }`** clears the notices. A plugin's helpers write its commands, such as `places.go('cafe')` from the [places plugin](https://ifloom.dev/docs/reference/plugins/places), and `apply` takes them as they are. ## Read the view [#read-the-view] The [view](https://ifloom.dev/docs/reference/view) is one plain object with everything a screen shows, worded for the player. Read it with `runner.view()`, never from the state: ```ts given const shown = runner.view() shown.scene.title // 'The door' shown.scene.beats // the paragraphs and spoken lines, in order shown.scene.choices.map((choice) => [choice.label, choice.disabled]) // [['Knock', undefined], …] shown.actions // the room's buttons while no scene is open shown.statsById.courage?.text // '1' shown.plugins.places?.exits // each plugin's part, typed, or undefined without it ``` `scene.body` is the same words as one string, paragraphs apart, for a test or a terminal. A UI renders `beats`, which keep spoken lines and pictures apart. [Render the scene and its choices](https://ifloom.dev/docs/how-to/render/scene) walks through each part. ## Follow changes with subscribe [#follow-changes-with-subscribe] `runner.subscribe` hands your listener a new [snapshot](https://ifloom.dev/docs/reference/runner#runnersnapshot) whenever anything changes, and returns the way to stop. Render from it: ```mermaid sequenceDiagram participant UI as Your code participant R as runner UI->>R: subscribe(listener) UI->>R: snapshot() R-->>UI: RunnerSnapshot UI->>R: apply(command) alt the command took R->>UI: listener(the next snapshot) else it was refused R-->>UI: ok false, and the reason end ``` The listener hears undo, redo, a load, a new game, a setting and a save too, so render only from it. `runner.snapshot()` returns the same object until a part of it changes, so a framework that compares values renders exactly when something is new. ## Turn on undo, saves and autosave [#turn-on-undo-saves-and-autosave] Pass the options to `createRunner`. Saves need a [driver](https://ifloom.dev/docs/reference/saves#savedriver) that says where they're kept, and Node has the engine's `memoryDriver`: ```ts import { createRunner, memoryDriver, saves, startingState } from '@ifloom/engine' import module from './game.ts' const { game } = module.build() const runner = createRunner(game, startingState(game), { saves: saves(game, memoryDriver()), history: { depth: 50, stopAtNewTurn: true }, // undo, but never back into the last turn autosave: { every: 'turn' }, // to the slot 'auto' }) runner.apply({ type: 'choose', id: 'knock' }) runner.undo() await runner.save('1', 'At the door') const loaded = await runner.load('1') if (!loaded.ok) console.warn(loaded.reason) ``` `autosave` takes `every: 'command'`, `'scene'` or `'turn'`. A game played mostly in the room, where walking opens no scene, wants `'command'`. Undo can't re-roll a draw, since the same command from the same state draws the same. In a browser, [Write a save driver](https://ifloom.dev/docs/how-to/write-a-save-driver) covers the drivers and your own. ## Play without a runner [#play-without-a-runner] [`apply`](https://ifloom.dev/docs/reference/commands#apply) and [`view`](https://ifloom.dev/docs/reference/view#view-1) work on a state directly, with no undo or saves. Each `apply` returns the next state, or the same one with a reason: ```ts import { apply, startingState, view } from '@ifloom/engine' import module from './game.ts' const { game } = module.build() let state = startingState(game) const tried = apply(state, game, { type: 'choose', id: 'again' }) if (!tried.ok) console.log(tried.reason) // 'That is not on offer.' state = apply(state, game, { type: 'choose', id: 'knock' }).state console.log(view(state, game).scene.title, state.stats.courage) // 'Inside' 2 ``` A state is a plain object, so you can keep one, compare two or write it to a file. A test that wants a whole route played this way uses `play` from [`@ifloom/engine/testing`](https://ifloom.dev/docs/reference/testing#play), which fails on the first refusal. ## Play it from a script [#play-it-from-a-script] This script plays the game `npm create ifloom` makes and prints each screen. Put it at the root of the game and run it with `node play.ts`, since Node 22.18 and later run TypeScript: ```ts // play.ts import { createRunner, startingState, type View } from '@ifloom/engine' import module from './src/game.ts' const { game } = module.build() const runner = createRunner(game, startingState(game)) function print(shown: View): void { console.log(`\n# ${shown.scene.title}`) console.log(shown.scene.body) shown.scene.choices.forEach((choice, at) => console.log(`${at + 1}. ${choice.label}${choice.disabled ? ` (${choice.disabled})` : ''}`)) } runner.subscribe((snapshot) => print(snapshot.view)) print(runner.view()) runner.apply({ type: 'choose', id: 'knock' }) ``` You should see the door, its two choices, then the room inside with its one line about knocking. For more, see: - [The runner](https://ifloom.dev/docs/reference/runner) and [the view](https://ifloom.dev/docs/reference/view). - [Commands](https://ifloom.dev/docs/reference/commands), with [`apply`](https://ifloom.dev/docs/reference/commands#apply) and [`startingState`](https://ifloom.dev/docs/reference/commands#startingstate). - [State and commands](https://ifloom.dev/docs/explanation/state-and-commands), on why a UI reads the view and sends commands. - [Start your own UI](https://ifloom.dev/docs/how-to/render/start), to put the same loop in a page. - [Test a route through your game](https://ifloom.dev/docs/how-to/test-a-route). # Run code at the end of a turn (https://ifloom.dev/docs/how-to/run-code-at-the-end-of-a-turn) Use this when something has to happen as each turn ends that content alone can't say, such as energy coming back overnight, wages on a Friday or a choice of morning scene. You write it in the game's [rules](https://ifloom.dev/docs/reference/glossary#rules), as [`onTurn`](https://ifloom.dev/docs/reference/rules#onturn) or [`onTurnDone`](https://ifloom.dev/docs/reference/rules#onturndone). For a kv key that goes back each turn, content's [`resets`](https://ifloom.dev/docs/reference/rules#resets) is enough. For work once a day, see [Run things each day](https://ifloom.dev/docs/how-to/schedule-daily-work). ## Write an onTurn hook [#write-an-onturn-hook] Add `onTurn` to the rules you pass `loadGame`. It gets the state of the turn that's beginning and returns the next one. Use the context's `apply` to apply effects as content would: ```ts import type { GameRules } from '@ifloom/engine' export const rules: GameRules = { // Energy back to full overnight. onTurn: (_state, { apply }) => apply([{ stat: 'energy', to: 100 }]), } ``` A turn ends each time a [`turn`](https://ifloom.dev/docs/reference/effects#turn) effect applies. With the [calendar](https://ifloom.dev/docs/reference/plugins/calendar), that's going to bed or passing into a new day, unless you set it to end a turn each period or each week. ## Read the turn that ended [#read-the-turn-that-ended] The context's `before` is the state the turn ended on, from before the counter moved on and before `resets` put keys back. Read the day's keys from it: ```ts import type { GameRules } from '@ifloom/engine' export const rules: GameRules = { onTurn: (state, { apply, before }) => apply([ // A late coffee costs a fifth of the night's rest. { stat: 'energy', to: before.kv.lateCoffee ? 80 : 100 }, { kv: 'marketOpen', to: state.turn % 7 === 5 }, ]), } ``` Each `apply` works on the state the hook was handed, unless you pass the state to work on as its second argument. Chain them by passing what the last one returned, as the day's end below does. ## Act after the plugins with onTurnDone [#act-after-the-plugins-with-onturndone] The plugins' own `onTurn` hooks run after yours, and the calendar moves its clock on there. Write `onTurnDone` for code that needs the new day: ```ts import type { GameRules } from '@ifloom/engine' export const rules: GameRules = { onTurnDone: (state, { apply, query }) => (query('calendar/now')?.period === 'morning' ? apply([{ notify: 'A new day.', id: 'morning' }]) : state), } ``` The order at the end of a turn is: the counter and `resets`, the game's `onTurn`, each plugin's `onTurn`, the game's `onTurnDone`, then each plugin's `onTurnDone`. Each gets what the one before it returned. A `turn` effect applied inside any of them does nothing, so one turn's rules never end another. ## Keep state of your own [#keep-state-of-your-own] Keep what isn't a stat, a kv key or an entity in the game's own state. Give the rules a `start` and name its type as `GameRules<S>`. Every function in the rules then reads it as `slice` and writes it with `set`: ```ts import type { GameRules } from '@ifloom/engine' type Days = { lived: number; tired: number } export const rules: GameRules<Days> = { start: () => ({ lived: 0, tired: 0 }), onTurn: (state, { before, slice, set }) => set({ lived: slice.lived + 1, tired: slice.tired + ((before.stats.energy ?? 0) < 20 ? 1 : 0) }), conditions: { worn: (_state, _args, { slice }) => slice.tired >= 3 }, view: (_state, { slice }) => ({ lived: slice.lived }), } ``` The engine keeps it in saves at `state.plugins.game`, and a UI reads the `view` at `view.plugins.game`. Content asks `{ 'game/worn': true }`. ## Write a day's end step by step [#write-a-days-end-step-by-step] A day's end that does several things runs them top to bottom, each `apply` on the state the last left. With the calendar's turn of a day and a game that ends turns only at bed, `state.turn` is the day that's starting: ```ts import type { GameRules } from '@ifloom/engine' const RENT = 30 export const rules: GameRules = { onTurn: (state, { apply, before, roll }) => { const weekday = state.turn % 7 let next = state // Friday night: the week's wages, from a stat each shift adds to. if ((state.turn - 1) % 7 === 4) next = apply([{ stat: 'coins', by: next.stats.owed ?? 0 }, { stat: 'owed', to: 0 }], next) // Sunday morning: the rent, out of what the wages left. const evicted = weekday === 6 && (next.stats.coins ?? 0) < RENT if (weekday === 6 && !evicted) next = apply([{ stat: 'coins', by: -RENT }], next) // Exactly one morning scene, by priority. if (evicted) next = apply([{ scene: 'ending.evicted' }], next) else if (!before.kv.calledAva && roll(3, 'ava.sulk') === 0) next = apply([{ scene: 'ava.sulk' }], next) else next = apply([{ scene: { from: 'morning', otherwise: 'morning.plain' } }], next) return apply([{ stat: 'energy', to: 100 }], next) }, } ``` `roll(3, 'ava.sulk')` draws from the save's seed, the turn and the name, so a replay draws the same. If something else ends turns too, such as a choice's `turn` effect or a calendar that ends one each period, move the steps to `onTurnDone` and read the day from `query('calendar/now')`. ## Check it worked [#check-it-worked] The [content checker](https://ifloom.dev/docs/reference/checks) can't look inside a hook, so a misspelt stat or scene in one isn't reported. Test it by ending a real turn, with the calendar's `calendar.sleep()` or a `turn` effect: ```ts import { expect, it } from 'vitest' import { applyEffects } from '@ifloom/engine' import { freshState } from '@ifloom/engine/testing' import module from '../src/game.ts' const { game } = module.build() it('fills energy overnight', () => { const tired = applyEffects(freshState(game), game, [{ stat: 'energy', to: 10 }]) expect(applyEffects(tired, game, [{ turn: true }]).stats.energy).toBe(100) }) ``` The [debug plugin](https://ifloom.dev/docs/reference/plugins/debug)'s `debug/time` and `debug/turn` set the clock and the counter without running any hook, so set them up with debug commands and then end the turn for real. For more, see: - [Rules](https://ifloom.dev/docs/reference/rules), with [`onTurn`](https://ifloom.dev/docs/reference/rules#onturn), [`onTurnDone`](https://ifloom.dev/docs/reference/rules#onturndone), [`TurnContext`](https://ifloom.dev/docs/reference/rules#turncontext) and [`resets`](https://ifloom.dev/docs/reference/rules#resets). - [Turns and time](https://ifloom.dev/docs/explanation/turns-and-time), on why the turn is the engine's one clock. - [Write your own condition, effect or macro](https://ifloom.dev/docs/how-to/write-your-own-condition-or-effect). # Run things each day: cooldowns, new-day work and pay (https://ifloom.dev/docs/how-to/schedule-daily-work) Use this for the work a life sim does as the days go by, such as the day's weather, a coffee allowed once a day, a scene that rests between visits, or wages paid on a Friday. Each is a few lines on features the engine and the plugins already have. The steps assume the [calendar](https://ifloom.dev/docs/reference/plugins/calendar) with its default turn of a day (see [Set up days and times of day](https://ifloom.dev/docs/how-to/set-up-the-clock)), and say where a turn of a period changes things. ## Put a value back each day [#put-a-value-back-each-day] List the [kv](https://ifloom.dev/docs/reference/glossary#kv) keys that go back at the end of each turn in your content's [`resets`](https://ifloom.dev/docs/reference/rules#resets), with the value each goes back to: ```ts import type { Content } from '@ifloom/engine' export const cafe: Content = { resets: { hadCoffee: false }, } ``` The engine puts them back as each turn ends, before any rule runs. With a turn of a period, that's each period, so use the next step's new-day rule for a key that should last the whole day. ## Allow something once a day [#allow-something-once-a-day] Refuse the action while its key is set, and set the key in its effects. The showcase café's coffee: ```ts import type { ActionDef } from '@ifloom/engine' export const coffee: ActionDef = { id: 'coffee', label: 'Buy a coffee', cost: { stats: { coins: 3 } }, blocked: [{ when: { kv: 'hadCoffee' }, reason: 'One is enough for today.' }], effects: [{ stat: 'energy', by: 15 }, { kv: 'hadCoffee', to: true }], } ``` With `hadCoffee` in `resets`, the button is greyed out with its reason until the next day. A choice or an action that needs no key of its own takes [`once`](https://ifloom.dev/docs/reference/actions#once) instead, `once: { per: 'turn', reason: 'She has a queue.' }`. ## Run something at the start of each day [#run-something-at-the-start-of-each-day] Write the work in the game's [`rules.onTurnDone`](https://ifloom.dev/docs/reference/rules#onturndone), in `src/rules.ts`. It runs as each turn ends, after the calendar has moved on, so it sees the new day. Keep the last day it ran on in the kv store and compare: ```ts import type { GameRules } from '@ifloom/engine' const WEATHER = ['drizzle', 'sun', 'wind'] export const rules: GameRules = { onTurnDone: (state, { apply, query, roll }) => { // The calendar's day, or the turn in a game without one. const day = query('calendar/now')?.day ?? state.turn if (state.kv.lastNewDay === day) return state return apply([ { kv: 'lastNewDay', to: day }, { kv: 'weather', to: WEATHER[roll(WEATHER.length, 'weather')] }, { kv: 'ateToday', to: false }, ]) }, } ``` With a turn of a day this runs every turn. With a turn of a period it runs on the first turn of each day, and the other turns return the state as it was. `roll` draws from the save's seed and the turn, so an undo or a replay gets the same weather. A pass that skips several days runs it once for each turn the pass ends. ## Rest a scene between visits [#rest-a-scene-between-visits] The [`since`](https://ifloom.dev/docs/reference/conditions#since) condition counts whole turns since a scene was seen or a choice was chosen, and `last: true` counts from the latest time. A café [storylet](https://ifloom.dev/docs/reference/glossary#storylet) that rests for three days after it's drawn: ```ts import type { DataScene } from '@ifloom/engine' export const crossword: DataScene = { id: 'cafe.crossword', title: 'Seven down', drawnFrom: ['cafe'], when: { not: { since: 'cafe.crossword', last: true, lt: 3 } }, body: [{ text: 'The man at the next table taps his paper with a pencil.' }], choices: [{ id: 'leave', label: 'Leave him to it', effects: [{ scene: null }] }], } ``` `since` fails for a scene the player hasn't seen, so `not` lets a fresh scene in. For a rest the player can see, put the condition in a `blocked` entry with a reason instead, such as `{ when: { since: 'cafe.counter#chat', last: true, lt: 2 }, reason: 'You only just talked.' }`. A message that comes again rests the same way, with the messages plugin's own [`messages.since`](https://ifloom.dev/docs/reference/plugins/messages#messagessince): `{ not: messages.since('ava.chat.rain', { lt: 3 }) }`. ## Keep part of a day for work [#keep-part-of-a-day-for-work] A [lock](https://ifloom.dev/docs/reference/locks) with `effect: 'calendar/pass'` refuses only the commands that would pass time. On the first morning, the player can buy a coffee but can't go for a jog: ```ts import type { Content } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' export const firstDay: Content = { locks: [ { when: { all: [{ kv: 'phase', is: 'first-day' }, calendar.period('morning')] }, deny: ['action', 'custom'], effect: 'calendar/pass', reason: 'No time for that. Work starts soon.', }, ], } ``` The lock denies `action` and `custom`, the room's actions and plugin commands, rather than `'*'`, because a lock that denies everything empties the room. Add `'choose'` to stop scene choices that pass time too. ## Pay wages once a week [#pay-wages-once-a-week] A [job](https://ifloom.dev/docs/reference/plugins/jobs)'s rank pays at the end of each shift. To pay once a week, pay each shift into a stat the player doesn't spend, and move it into coins as Friday ends. Declare the stat unlisted, so it stays out of the stat list: ```ts import type { StatDef } from '@ifloom/engine' import type { RankDef } from '@ifloom/plugin-jobs' export const owed: StatDef = { id: 'owed', label: 'Wages owed', max: 9999, listed: false } // In the job's ranks: each shift adds to what's owed, not to coins. export const help: RankDef = { id: 'help', name: 'Weekend help', pay: { owed: 12 } } ``` Then pay it out in `rules.onTurnDone`. Its `before` is the state the turn ended on, so the rule can ask whether the day that has just ended was a Friday: ```ts import { holds, type GameRules } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' export const rules: GameRules = { onTurnDone: (state, { apply, before, game }) => { const owed = state.stats.owed ?? 0 const fridayEnded = holds(before, game, calendar.weekday(4)) && !holds(state, game, calendar.weekday(4)) if (owed <= 0 || !fridayEnded) return state return apply([{ stat: 'coins', by: owed }, { stat: 'owed', to: 0 }, { notify: `Payday: ${owed} coins`, id: 'payday', tag: 'money' }]) }, } ``` Weekday 4 is Friday in a seven-day week that starts on a Monday. Missed shifts add nothing to `owed`, so the week's pay is the wage times the shifts worked. No price names `owed`, so the player can't spend it, and a UI shows it by reading `view.statsById.owed`. ## Check it worked [#check-it-worked] Run `npm run check`, which reports a stat, kv store or scene that a lock, a `blocked` entry or a `since` names and the game doesn't have. It can't look inside `rules`, so test them with a [route](https://ifloom.dev/docs/how-to/test-a-route) that plays a week with `calendar.sleep()`. Then play in `npm run dev`. Buy a coffee and the button greys out until morning, and go to bed on a Friday after a shift to see the payday notice. In the showcase, Small Town, the coffee and its reset are in [`examples/showcase/src/story/cafe.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/cafe.ts), and Ava's small talk rests three days per line in `src/story/ava.ts`. For more, see: - [Game rules](https://ifloom.dev/docs/reference/rules), with [`onTurnDone`](https://ifloom.dev/docs/reference/rules#onturndone), [`TurnContext`](https://ifloom.dev/docs/reference/rules#turncontext) and [`resets`](https://ifloom.dev/docs/reference/rules#resets). - The [`since`](https://ifloom.dev/docs/reference/conditions#since) condition and [locks](https://ifloom.dev/docs/reference/locks#lock). - [Turns, scenes and the room](https://ifloom.dev/docs/explanation/turns-and-time). # Sell supporter content (https://ifloom.dev/docs/how-to/sell-supporter-content) Use this to give supporters, such as members on a funding site, a code that opens something extra: cheats, an extra scene, a whole route. The [unlocks plugin](https://ifloom.dev/docs/reference/plugins/unlocks) checks the code and runs the cheats. A supporter enters the code once, and keeps what it opens across saves and new games. ## Decide what to protect [#decide-what-to-protect] Your game ships as files on the player's machine, so anything in the build can be read. Each gate protects a different amount: - **Locked content is protected.** A pack in `src/unlocks/` is encrypted by `ifloom build` under a key made from the code. Without the code, nobody can read it or switch it on by editing the game. - **A gated cheat, choice or button only deters.** `unlocks/has` in its `blocked` keeps honest players out, but the cheat is in the game's code, and someone who edits the code or the save can use it. - **The code is protected if it's long.** Only a slow hash is in the build, and each guess costs 600,000 rounds of hashing. Use random codes of 12 characters or more. No offline game stops a supporter posting the code, or copying out what it unlocked. Give each release new codes, so a shared code opens only what it opened then. [What an offline game can protect](https://ifloom.dev/docs/explanation/design#what-an-offline-game-can-protect) says why. ## Add the plugins [#add-the-plugins] Add `@ifloom/plugin-unlocks` as [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin) shows, and list it in the game. It has the codes and the cheats both. Pass `unlocked` to `loadGame` as its packs, since that's where the locked content comes in: ```ts // src/game.ts import { loadGame } from '@ifloom/engine' import { defineGame } from '@ifloom/cli/game' import { unlocks } from '@ifloom/plugin-unlocks' import { town } from './world/town.ts' export default defineGame({ build: ({ unlocked }) => loadGame([town], { id: 'small-town', title: 'Small Town', plugins: [unlocks()] }, { packs: unlocked }), }) ``` `ifloom check` passes the packs in `src/unlocks/` as `unlocked`, and the page passes the ones the player's codes opened. ## Make a code and its hash [#make-a-code-and-its-hash] Make a random code. This one has 64 random bits, in four groups: ```sh node -e "console.log(require('crypto').randomBytes(8).toString('hex').toUpperCase().match(/.{4}/g).join('-'))" # 7F3A-91C2-0B5D-E468 ``` Put it in `.env.local` in the game's folder, under the unlock's name. Git leaves `.env.local` out, so the code never reaches the repository: ```sh # .env.local IFLOOM_UNLOCK_SUPPORTER=7F3A-91C2-0B5D-E468 ``` Print its hash with [`ifloom unlock-hash`](https://ifloom.dev/docs/reference/cli#ifloom-unlock-hash), and declare the unlock in `data.unlocks.unlocks` with it: ```sh npx ifloom unlock-hash supporter ``` ```ts import type { Content } from '@ifloom/engine' export const supporters: Content = { data: { unlocks: { unlocks: [{ id: 'supporter', name: 'Supporter edition', description: 'A thank-you scene in the café, and the supporter cheats.', hash: '…the 64 hex digits it printed…' }], }, }, } ``` Players type a code in any case, with or without spaces and hyphens, so `7f3a 91c2 0b5d e468` works too. ## Gate the cheats [#gate-the-cheats] Put a supporter cheat in `data.unlocks.cheats` with a `blocked` entry that holds while the player lacks the unlock. [`unlocks.has`](https://ifloom.dev/docs/reference/plugins/unlocks#unlockshas) writes the condition: ```ts import type { Content } from '@ifloom/engine' import { unlocks } from '@ifloom/plugin-unlocks' export const cheats: Content = { data: { unlocks: { cheats: [ { id: 'coins', name: '+20 coins', effects: [{ stat: 'coins', by: 20 }] }, { id: 'gold', name: '+500 coins', group: 'Supporters', blocked: [{ when: { not: unlocks.has('supporter') }, reason: 'For supporters.' }], effects: [{ stat: 'coins', by: 500 }], }, ], }, }, } ``` The cheat shows greyed out with `For supporters.` until the code is entered. Add `hide: true` to the entry to leave it off the panel until then. A cheat can be gated on anything a condition says, such as an achievement or a finished storyline, in the same way. ## Lock the content [#lock-the-content] Put what supporters get in `src/unlocks/supporter.ts`, named after the unlock. It's a [pack](https://ifloom.dev/docs/reference/content#pack), as a mod is, so it holds data only: ```ts // src/unlocks/supporter.ts import { SCHEMA, type Pack } from '@ifloom/engine' import { unlocks } from '@ifloom/plugin-unlocks' const supporter: Pack = { id: 'supporter', schema: SCHEMA, scenes: [ { id: 'cafe.back-room', title: 'The back room', drawnFrom: ['cafe'], weight: 5, when: { all: [unlocks.has('supporter'), { not: { seen: 'cafe.back-room' } }] }, body: [{ text: 'Ava lifts the counter flap and waves you through to the back room.' }], choices: [{ id: 'leave', label: 'Thank her and head back out', effects: [{ scene: null }] }], }, ], } export default supporter ``` Don't import this file anywhere, since `ifloom build` encrypts it into the page and stops if your code imports it. The base game shouldn't name anything in it either, because a player without the code doesn't have it. Reach it from inside, as this storylet does by joining the café's set, or only behind `unlocks/has`. ## Take codes in the game [#take-codes-in-the-game] Entering a code isn't a command, because the plugin checks each code against a slow hash. Set it up at start-up: ```ts // src/runner.ts import { browserRunner, localStorageDriver } from '@ifloom/browser' import { profile } from '@ifloom/engine' import { enterCode, startUnlocks, unlockedPacks } from '@ifloom/plugin-unlocks' import module from './game.ts' // Open what the player's codes unlocked, from the profile browserRunner will use, before the game is built. const opened = await unlockedPacks('small-town', profile({ id: 'small-town' }, localStorageDriver())) export const runner = await browserRunner(module.build({ unlocked: opened.packs }).game) startUnlocks(runner) export async function unlock(code: string): Promise<string> { const result = await enterCode(runner, code) if (result.ok && result.value.restart) location.reload() return result.ok ? `Unlocked: ${result.value.name}.` : result.reason } ``` A code that works records the unlock at once, so the cheat opens. When it has locked content the game in play lacks, `restart` is true, and reloading builds the game with it. [Render a box for codes](https://ifloom.dev/docs/how-to/render/player-tools#render-a-box-for-codes) has the code box in plain JS, React and Vue. In the React UI, list `unlocksUiWith({ problems: opened.problems, onChange: () => location.reload() })` in `plugins`, and the settings page gets an "Enter a code" box. ## Build and check [#build-and-check] Run the check and the build: ```sh npx ifloom check npx ifloom build ``` `check` reads the locked content from source and checks the game with it, and checks the code in `.env.local` against the hash. It also lists what the base game names that only the locked content has, so you can make sure each sits behind `unlocks/has`. `build` encrypts the content, then searches the built folder for the code and every line of the locked prose, and fails if it finds one. Neither prints the code. The build holds each unlock's name, description and hash, every cheat, gated or not, and each unlock's content encrypted in a script in the page's head. Pictures, sound and video that only locked content uses are still plain files in the folder, so keep anything you'd mind being seen out of `public/`. ## Ship a release [#ship-a-release] Each release, with your funding site: 1. Make new codes, one per unlock, and put them in `.env.local` or your build machine's secrets. 2. Run `ifloom unlock-hash` for each unlock, and put the new hashes in the game. 3. Run `ifloom check` and `ifloom build`, and ship the build to everyone. 4. Post the codes where only supporters can see them. Players who entered last release's code see the unlock as locked again until they enter the new one. To let a code carry over, keep it and its hash, and accept that a shared code keeps working. ## Variations [#variations] **Tiers.** Declare an unlock per tier, each with its own code, and give higher tiers every code they're due. A cheat for any supporter asks for either, `{ when: { not: { any: [unlocks.has('supporter'), unlocks.has('patron')] } }, reason: 'For supporters.' }`. The showcase does all of this with a code that's public on purpose, `SMALL-TOWN-SUPPORTER`, in [`examples/showcase/.env`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/.env), with its cheats in `src/world/cheats.ts` and its locked scene in `src/unlocks/supporter.ts`. For more, see: - [Unlocks](https://ifloom.dev/docs/reference/plugins/unlocks), with [`UnlockDef`](https://ifloom.dev/docs/reference/plugins/unlocks#unlockdef), [`unlockedPacks`](https://ifloom.dev/docs/reference/plugins/unlocks#unlockedpacks), [`startUnlocks`](https://ifloom.dev/docs/reference/plugins/unlocks#startunlocks) and [`enterCode`](https://ifloom.dev/docs/reference/plugins/unlocks#entercode). - [Cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatdef), the same plugin's, with [`CheatDef`](https://ifloom.dev/docs/reference/plugins/unlocks#cheatdef). - [Locked content](https://ifloom.dev/docs/reference/cli#locked-content) and [`ifloom unlock-hash`](https://ifloom.dev/docs/reference/cli#ifloom-unlock-hash). # Set up days and times of day (https://ifloom.dev/docs/how-to/set-up-the-clock) Use this when time matters to the story, such as a café that shuts in the evening or a job on weekdays. You need the [calendar plugin](https://ifloom.dev/docs/reference/plugins/calendar) (see [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin)). With no options, a day has five periods, from `morning` to `late`, a week has seven days, a [turn](https://ifloom.dev/docs/reference/glossary#turn) is a day, and the game starts on Monday morning. ## Configure the calendar [#configure-the-calendar] Pass [`CalendarOptions`](https://ifloom.dev/docs/reference/plugins/calendar#calendaroptions) to `calendar()` in `src/game.ts`, and list it first in `plugins` so that every plugin after it sees the new day. The showcase starts on the night the player moves in: ```ts import { loadGame, type Content } from '@ifloom/engine' import { defineGame } from '@ifloom/cli/game' import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' declare const town: Content export const clock = calendar({ start: { day: 0, period: 'night' } }) export default defineGame({ build: () => loadGame([town], { id: 'small-town', title: 'Small Town', plugins: [clock, places({ start: 'flat' })] }), }) ``` Choose the rest of the options for the shape of your game: - **`periods`** names the parts of a day, in order. Give a [`PeriodDef`](https://ifloom.dev/docs/reference/plugins/calendar#perioddef) for a word the player reads that differs from the id: `periods: ['dawn', 'day', { id: 'dusk', label: 'after dark' }]`. - **`turn`** sets how long a turn is: `'period'`, `'day'` or `'week'`. A management game a week at a time uses `'week'`. - **`week`** and **`weekend`** set the days in a week and which of them, counting from `0`, are the weekend. - **`start`** sets the day, from `0`, and the period a new game starts at. The options are code, so a mod can't change them. [Turns, scenes and the room](https://ifloom.dev/docs/explanation/turns-and-time#the-calendar-makes-a-turn-a-period-a-day-or-a-week) explains how the clock and the turn keep step. ## Let actions pass time [#let-actions-pass-time] Put `calendar.pass(n)` in an action's or a choice's effects to move the clock on `n` periods. A shift at the office takes the rest of the day: ```ts import type { ActionDef } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' export const work: ActionDef = { id: 'work', label: 'Do a shift', cost: { stats: { energy: 30 } }, effects: [calendar.pass(2), { stat: 'coins', by: 20 }] } ``` Passing time ends a turn at each boundary it crosses, so with a turn of a day, a pass from the evening into the next morning ends one. The button's price shows where the clock lands, such as `until evening`. An action with no pass takes no time, so buying a coffee leaves the clock where it was. ## Close a week with a button [#close-a-week-with-a-button] In a game whose turn is a week, end the turn with `{ turn: true }` in place of a pass. The clock jumps to the first morning of the next week: ```ts import type { ActionDef } from '@ifloom/engine' export const closeTheWeek: ActionDef = { id: 'closeTheWeek', label: 'Close the week', effects: [{ turn: true }] } ``` The same effect with a turn of a day moves the clock to the next morning, and with a turn of a period to the next period. ## Add a bed [#add-a-bed] Give a location an action that sends `calendar.sleep()`. Bed passes time to the first period of the next day: ```ts import { calendar } from '@ifloom/plugin-calendar' import { places } from '@ifloom/plugin-places' export const flat = places.location({ id: 'flat', name: 'Your flat', description: 'Home', exits: ['high-street'], body: [{ text: 'Boxes, mostly. The radiator knocks when it feels like it.' }], actions: [{ id: 'bed', label: 'Go to bed', command: calendar.sleep() }], }) ``` Bed works from the last three periods, and is refused with `Too early.` before them. Change that with `sleep: { from: ['night', 'late'], wake: 'morning' }`, or leave bed out of the game with `sleep: false`. ## Set a curfew [#set-a-curfew] The curfew stops the player passing time over the end of the day, so the night ends in bed. A button that would run past the last period stays pressable with the warning `That would run past dawn.`, and the engine refuses it with the same line. The curfew always binds unless you give it a [condition](https://ifloom.dev/docs/reference/conditions): ```ts import { calendar } from '@ifloom/plugin-calendar' export const nightOwl = calendar({ curfew: { not: { kv: 'nightOwl' } } }) ``` With `curfew: false` it never binds. An intro whose scenes carry the clock through the night uses a curfew that doesn't hold during the intro, such as `{ not: { kv: 'phase', is: 'arrival' } }`. ## Read the time in content [#read-the-time-in-content] Use the calendar's [conditions](https://ifloom.dev/docs/reference/plugins/calendar#conditions) anywhere a condition goes. They're how a location sets its opening hours and a character keeps a schedule: ```ts import type { Block } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' export const lines: Block[] = [ { text: 'Market day: the square is full of stalls.', when: calendar.weekday(5) }, { text: 'The street lamps flicker on.', when: calendar.period('evening', 'night') }, { text: 'A week in, the boxes are nearly all unpacked.', when: calendar.day({ gte: 6 }) }, ] ``` Weekdays count from `0`, Monday in a seven-day week. `calendar.day()` counts from `0` too, so `{ gte: 6 }` holds from the day the header calls Day 7. To print the time, write `{{calendar/day}}`, `{{calendar/weekday}}` or `{{calendar/period}}` in a line: `Day {{calendar/day}}, a {{calendar/weekday}} {{calendar/period}}.` reads `Day 1, a Monday morning.` on a new game. ## Check it worked [#check-it-worked] Run `npm run check`, which reports a `start` or `sleep` period the calendar doesn't have, and a weekend day outside the week: ```text base · options start · no period called "noon" ``` Then play in `npm run dev`. The header reads `Day 1 · Monday morning`, a button that passes time shows where the clock lands, and bed moves the header on to the next morning. To render the clock in a UI of your own, see [Render the clock](https://ifloom.dev/docs/how-to/render/world-plugins#render-the-clock). In the showcase, Small Town, the calendar is in [`examples/showcase/src/game.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/game.ts) and the office's shift in `src/story/office.ts`. For more, see: - [Calendar](https://ifloom.dev/docs/reference/plugins/calendar), with [`calendar/pass`](https://ifloom.dev/docs/reference/plugins/calendar#calendarpass), [`calendar/sleep`](https://ifloom.dev/docs/reference/plugins/calendar#calendarsleep) and the [strings](https://ifloom.dev/docs/reference/plugins/calendar#strings) that word the header. - [Add a location](https://ifloom.dev/docs/how-to/add-a-location#set-opening-hours) for opening hours, and [Run things each day](https://ifloom.dev/docs/how-to/schedule-daily-work) for work at the start of each day. - [Turns, scenes and the room](https://ifloom.dev/docs/explanation/turns-and-time). # Ship your game (https://ifloom.dev/docs/how-to/ship-your-game) Use this when the game is ready for players, as a folder to zip, upload to itch.io or open by double-clicking `index.html`. A game made with [Create a game](https://ifloom.dev/docs/how-to/create-a-game) has everything it needs. [Why IFLoom works this way](https://ifloom.dev/docs/explanation/design#nothing-loads-at-runtime) explains why a page opened from disk loads nothing at runtime. ## Prepare the game [#prepare-the-game] 1. **Keep the Vite preset.** A new game's `vite.config.ts` has it already. Otherwise add it, with your UI framework's Vite plugin in `vite.plugins`: ```ts // vite.config.ts import { ifloom } from '@ifloom/cli/vite' export default ifloom() ``` The preset builds with `base: './'` and puts the script and the stylesheet inside `index.html`, so the page loads no other file of its own. 2. **Put pictures in `public/art/` and sound in `public/audio/`.** Vite copies `public/` into the build, so they land beside the page. Name them by relative path, `art/cafe.jpg`, never `/art/cafe.jpg`: a leading slash points at the root of the drive, or of the host on itch.io. 3. **Load nothing at runtime.** Import your content statically, and don't call `fetch()` or a dynamic `import()` in your own code. `ifloom build` doesn't search for them, and they fail on a page opened from disk. 4. **Leave the debug plugin out.** Add it only when `import.meta.env.DEV` is `true`, which it isn't under `ifloom build` (see [Debug a game](https://ifloom.dev/docs/how-to/debug-a-game)). 5. **Give the game an id of its own.** `saves` keys every save with the game's `id`, as in `corner-cafe.save.auto`, so two games on one origin don't overwrite each other. Changing the id later loses every player's saves. ## Choose where saves go [#choose-where-saves-go] [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner), which every template uses, keeps saves in `localStorage`. Choose a driver for how the game ships: - **A short game in a browser or on itch.io** keeps `localStorageDriver()`, with about 5MB. - **A long game, or one with big backlogs or mods,** passes `indexedDbDriver()`, which has much more room. - **A desktop wrapper** such as Tauri or Electron passes a driver of its own over the wrapper's files (see [Write a save driver](https://ifloom.dev/docs/how-to/write-a-save-driver)). Pass the driver in the runner's options. With the React UI's `mountGame`, pass them as `runner`: ```ts tab="Plain JS" tab-group="framework" // src/main.ts import { browserRunner, indexedDbDriver } from '@ifloom/browser' import { saves } from '@ifloom/engine' import module from './game.ts' const { game } = module.build() const runner = await browserRunner(game, { saves: saves(game, indexedDbDriver()) }) ``` ```ts tab="React" tab-group="framework" // src/main.ts import { indexedDbDriver } from '@ifloom/browser' import { saves } from '@ifloom/engine' import { mountGame } from '@ifloom/react' import module from './game.ts' const loaded = module.build() mountGame(loaded, { runner: { saves: saves(loaded.game, indexedDbDriver()) } }) ``` ```ts tab="Vue" tab-group="framework" // src/runner.ts import { shallowRef } from 'vue' import { browserRunner, indexedDbDriver } from '@ifloom/browser' import { saves } from '@ifloom/engine' import module from './game.ts' const { game } = module.build() export const runner = await browserRunner(game, { saves: saves(game, indexedDbDriver()) }) export const view = shallowRef(runner.view()) runner.subscribe((snapshot) => (view.value = snapshot.view)) ``` ```ts fragment tab="Svelte" tab-group="framework" // src/runner.ts import { readable } from 'svelte/store' import { browserRunner, indexedDbDriver } from '@ifloom/browser' import { saves } from '@ifloom/engine' import module from './game.ts' const { game } = module.build() export const runner = await browserRunner(game, { saves: saves(game, indexedDbDriver()) }) export const view = readable(runner.view(), (set) => runner.subscribe((snapshot) => set(snapshot.view))) ``` Browser storage goes when the player clears site data. Offer an export and an import with `exportSlot` and `importText` (see [`Saves`](https://ifloom.dev/docs/reference/saves#saves)), so players can keep their saves. ## Build it [#build-it] Check the content, then build: ```sh npm run check npm run build ``` [`ifloom build`](https://ifloom.dev/docs/reference/cli#ifloom-build) builds the game into `dist/`, or the folder `--out` names. It then checks the folder: an `index.html`, every script and stylesheet it loads beside it, and every picture, video and sound the game names. It prints each problem and exits with `1`, so a CI job fails on a build that wouldn't open from disk. ## Check it worked [#check-it-worked] Open `dist/index.html` straight from disk, by double-clicking it. Don't test only through `vite preview`, because a local server isn't `file://` and hides what fails there. Play past the first scene, save, reload the page and load the save. To upload to itch.io, zip the contents of `dist/` and upload the zip as an HTML game. ## Variations [#variations] **One file, pictures and all.** `ifloom build --inline-assets` puts every picture inside `index.html` and removes `art/`, for a game to attach to a message or upload where only one file goes. Sound and video stay beside it, so a game with sound is always a folder. **Without the CLI.** Write the preset out in your own Vite config, with `base: './'` and [`vite-plugin-singlefile`](https://github.com/richardtallent/vite-plugin-singlefile), and build with `vite build`. [`checkBuild`](https://ifloom.dev/docs/api/cli#checkbuild) from `@ifloom/cli` runs the same check from a script of your own. ```ts // vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { viteSingleFile } from 'vite-plugin-singlefile' export default defineConfig({ base: './', plugins: [react(), tailwindcss(), viteSingleFile()], }) ``` **Another bundler.** [Build with esbuild](https://ifloom.dev/docs/how-to/build-with-esbuild#build-the-single-offline-file) and [Build with webpack](https://ifloom.dev/docs/how-to/build-with-webpack#build-the-single-offline-file) make the same single file. [Build with Next.js](https://ifloom.dev/docs/how-to/build-with-next) can't, so a game built with Next is played on its website. For more, see: - [`ifloom build`](https://ifloom.dev/docs/reference/cli#ifloom-build) and [the Vite preset](https://ifloom.dev/docs/reference/cli#the-vite-preset). - [Saves](https://ifloom.dev/docs/reference/saves) and the [save drivers](https://ifloom.dev/docs/reference/browser#save-drivers). - [Nothing loads at runtime](https://ifloom.dev/docs/explanation/design#nothing-loads-at-runtime). # Tell the player when something happens (https://ifloom.dev/docs/how-to/show-a-notice) Use this when something happens outside the story the player is reading, such as a note under the door or the rent going out. A [trigger](https://ifloom.dev/docs/reference/glossary#trigger) runs effects by itself after a command once its condition holds, and a [notice](https://ifloom.dev/docs/reference/notices) tells the player. The steps build the showcase's two triggers. ## Run effects when a condition first holds [#run-effects-when-a-condition-first-holds] Add a trigger to your content's `triggers`, with the condition in `when` and the effects to run. A trigger fires once in the whole game unless it says otherwise: ```ts import type { Content } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' export const movingDay: Content = { kinds: [{ id: 'note', label: 'Note', listed: false }], entities: [{ id: 'welcome', of: 'note', name: 'Welcome note', description: 'Bins go out Thursday. Sam, flat 2' }], triggers: [ { id: 'welcome', when: places.at('high-street'), effects: [{ notify: 'A note under your door', text: 'Welcome to the building! Bins go out Thursday.', tag: 'post' }, { receive: 'note:welcome' }], }, ], } ``` The first command that leaves the player on the high street fires `welcome`. It raises the notice and gives the player the note to keep, through the game's [inventory](https://ifloom.dev/docs/how-to/give-the-player-things). ## Tell the player with a notice [#tell-the-player-with-a-notice] The [`notify` effect](https://ifloom.dev/docs/reference/effects#notify) raises the notice. Its `notify` is the title, and `text` is the longer words, both written in place and both able to hold [tokens](https://ifloom.dev/docs/reference/prose#tokens). `image` adds a picture. `tag` is a word of your own for what the notice is about, such as `'post'` or `'money'`, so a UI can count notices by tag on a badge. ## Repeat it every turn [#repeat-it-every-turn] Give the trigger `once: { per: 'turn' }` to let it fire again, at most once a [turn](https://ifloom.dev/docs/reference/glossary#turn). Give its notice a fixed `id`, so each new one replaces the last instead of stacking: ```ts import type { TriggerDef } from '@ifloom/engine' import { calendar } from '@ifloom/plugin-calendar' export const rent: TriggerDef = { id: 'rent', once: { per: 'turn' }, when: { all: [calendar.weekday(6), calendar.day({ gte: 6 })] }, effects: [ { stat: 'coins', by: -30 }, { notify: 'Rent paid: 30 coins', id: 'rent', tag: 'money' }, ], } ``` A turn is a day in the showcase, so the rent goes out once each Sunday from the first week on. ## Check it worked [#check-it-worked] Play past the condition in `npm run dev`. The React UI shows the notice as a toast in a corner, with [`Notices`](https://ifloom.dev/docs/reference/react/components#notices), until the player dismisses it. A test can check the notice in the view and dismiss it: ```ts given import { apply, view } from '@ifloom/engine' import { places } from '@ifloom/plugin-places' let next = apply(state, game, places.go('high-street')).state view(next, game).notices.unseen[0].title // 'A note under your door' view(next, game).notices.byTag // { post: 1 } next = apply(next, game, { type: 'dismiss' }).state view(next, game).notices.unseen // [] ``` `state.fired` holds the turn each trigger last fired in, such as `{ welcome: 1, rent: 6 }`. ## Variations [#variations] **A notice from a choice or an action.** Put the `notify` effect in the choice's or the action's effects, and it shows after the player presses it. A Pay the rent button would raise the same notice by hand. **A scene instead of a notice.** A trigger can open a scene with `{ scene: 'flat.ring' }`, which interrupts whatever is open. Add `{ not: { scene: [...] } }` to its `when` for the scenes it shouldn't interrupt. In the showcase, Small Town, the `welcome` trigger is in [`examples/showcase/src/story/moving-day.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/moving-day.ts) and `rent` in [`story/flat.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/flat.ts). For more, see: - [Triggers](https://ifloom.dev/docs/reference/triggers), with when they run and their caveats. - [Notices](https://ifloom.dev/docs/reference/notices) and the [`notify` effect](https://ifloom.dev/docs/reference/effects#notify). - [Render notices](https://ifloom.dev/docs/how-to/render/stats-and-things#render-notices), for a UI of your own. - [Triggers, notices and inputs](https://ifloom.dev/docs/explanation/state-and-commands#triggers-notices-and-inputs). # Show a popup (https://ifloom.dev/docs/how-to/show-a-popup) Use this to open a dialog from a word in the text. Choose one of two ways, by whether the dialog changes the game: - **A popup that only shows something**, such as the full text of a note, is a [UI piece](https://ifloom.dev/docs/reference/glossary#ui-piece), `[[ui:modal|words|key]]`. Opening it isn't a command, so the save and the command log never see it. - **A modal that changes the game**, such as a lease to sign, is a [panel](https://ifloom.dev/docs/reference/glossary#panel) opened by an [inline action](https://ifloom.dev/docs/how-to/put-a-choice-in-a-line). Opening it is a command, its buttons send commands, and a replay opens it as play did. ## Write a popup that only shows words [#write-a-popup-that-only-shows-words] Write `[[ui:modal|words|key|title]]` where the link should go. The words show in the line, and the popup shows the [prose key](https://ifloom.dev/docs/reference/glossary#prose-key) `key`. The title is optional, and without one the popup is titled with the words: ```ts import { text, type Block, type Content } from '@ifloom/engine' export const flatLine: Block = text( "Boxes, mostly. The window looks over the high street, and [[ui:modal|the radiator knocks|notice.welcome|Sam's note]] when it feels like it.", ) export const notes: Content = { prose: { 'notice.welcome': 'Welcome to the building! Bins go out Thursday. The radiator knocks; ignore it. Sam, flat 2' }, } ``` The popup's line can have several paragraphs, bold, italics and [tokens](https://ifloom.dev/docs/reference/prose#tokens), and a translation or a mod rewrites it by its key. `[[ui:image|words|path]]` works the same way for a picture, which the words open large. The React UI renders both with no code from you, as [`InlineModal`](https://ifloom.dev/docs/reference/react/components#inlinemodal) and [`InlineImage`](https://ifloom.dev/docs/reference/react/components#inlineimage). ## Render the popup in a UI of your own [#render-the-popup-in-a-ui-of-your-own] The view gives the line's beat a `ui` [span](https://ifloom.dev/docs/reference/prose#inlinespan), `{ type: 'ui', name: 'modal', text, args }`, where `args[0]` is the prose key and `args[1]` the title. Read the line from the game's prose for the current state, and open a native `<dialog>` with `showModal()` when the words are pressed. The `<dialog>` closes on Escape, keeps focus inside while it's open, and returns focus to the link when it closes. Render the line's other spans as [Render inline choices and tooltips](https://ifloom.dev/docs/how-to/render/scene#render-inline-choices-and-tooltips) does, and call this for a `ui` span named `modal`: ```ts tab="Plain JS" tab-group="framework" // src/popup.ts import type { InlineSpan, Runner } from '@ifloom/engine' export function drawPopup(runner: Runner, line: HTMLElement, span: Extract<InlineSpan, { type: 'ui' }>): void { const [key, title] = span.args const text = key ? runner.game.prose?.line(key, runner.state) : undefined // A key with no prose shows as its words, so the line still reads. if (text === undefined) return void line.append(span.text) const button = line.appendChild(document.createElement('button')) Object.assign(button, { type: 'button', className: 'popup-link', textContent: span.text }) button.setAttribute('aria-haspopup', 'dialog') button.onclick = () => { const dialog = document.body.appendChild(document.createElement('dialog')) dialog.appendChild(document.createElement('h2')).textContent = title ?? span.text for (const paragraph of text.split('\n\n')) dialog.appendChild(document.createElement('p')).textContent = paragraph const close = dialog.appendChild(document.createElement('button')) Object.assign(close, { type: 'button', textContent: 'Close', onclick: () => dialog.close() }) dialog.onclose = () => dialog.remove() dialog.showModal() } } ``` ```tsx tab="React" tab-group="framework" // src/Popup.tsx: React with the runner, without @ifloom/react. import { useRef } from 'react' import type { InlineSpan, Runner } from '@ifloom/engine' export function Popup({ runner, span }: { runner: Runner; span: Extract<InlineSpan, { type: 'ui' }> }) { const dialog = useRef<HTMLDialogElement>(null) const [key, title] = span.args const text = key ? runner.game.prose?.line(key, runner.state) : undefined if (text === undefined) return <>{span.text}</> return ( <> <button type="button" className="popup-link" aria-haspopup="dialog" onClick={() => dialog.current?.showModal()}> {span.text} </button> <dialog ref={dialog}> <h2>{title ?? span.text}</h2> {text.split('\n\n').map((paragraph, at) => ( <p key={at}>{paragraph}</p> ))} <button type="button" onClick={() => dialog.current?.close()}> Close </button> </dialog> </> ) } ``` ```vue tab="Vue" tab-group="framework" <!-- src/Popup.vue: <Popup v-if="span.type === 'ui' && span.name === 'modal'" :span="span" /> --> <script setup lang="ts"> import { computed, ref } from 'vue' import type { InlineSpan } from '@ifloom/engine' import { runner, view } from './runner.ts' const props = defineProps<{ span: Extract<InlineSpan, { type: 'ui' }> }>() const dialog = ref<HTMLDialogElement>() // Read again whenever the view changes, so tokens follow the state. const text = computed(() => { void view.value const key = props.span.args[0] return key ? runner.game.prose?.line(key, runner.state) : undefined }) </script> <template> <template v-if="text === undefined">{{ span.text }}</template> <template v-else> <button type="button" class="popup-link" aria-haspopup="dialog" @click="dialog?.showModal()">{{ span.text }}</button> <dialog ref="dialog"> <h2>{{ span.args[1] ?? span.text }}</h2> <p v-for="(paragraph, at) in text.split('\n\n')" :key="at">{{ paragraph }}</p> <button type="button" @click="dialog?.close()">Close</button> </dialog> </template> </template> ``` Give the link a look of its own, so a player can tell it from an inline action, which does something: ```css .popup-link { padding: 0; border: 0; background: none; font: inherit; text-decoration: underline dashed; cursor: pointer; } dialog::backdrop { background: rgb(0 0 0 / 0.5); } ``` ## Write a modal that changes the game [#write-a-modal-that-changes-the-game] Open a [panel](https://ifloom.dev/docs/reference/panels) with the [`panel` effect](https://ifloom.dev/docs/reference/effects#panel), from an action the line links to. Give the panel's button an action with no label, which the panel sends and the room doesn't show: ```ts import { text, type Content } from '@ifloom/engine' export const lease: Content = { actions: [ { id: 'sign-lease', cost: { stats: { coins: 50 }, reasons: { coins: "You can't cover the deposit yet." } }, blocked: [{ when: { kv: 'signed' }, reason: 'You signed it already.' }], effects: [{ kv: 'signed', to: true }, { panel: null }], }, ], prose: { 'lease.text': 'Twelve months, rent on the first. No pets. (Sam says nobody checks.)' }, } // The flat's location gains the line and the action it links to. export const leaseLine = text('The [[act:lease|lease]] is still on the table, unsigned.', { when: { not: { kv: 'signed' } } }) export const readLease = { id: 'lease', label: 'Read the lease', effects: [{ panel: 'lease', with: { title: 'The lease' } }] } ``` The panel stays open while the player reads. It closes when signing closes it with `{ panel: null }`, when the player dismisses it with the [`closePanel`](https://ifloom.dev/docs/reference/commands#closepanel) command, or when the scene changes or the turn ends. Render the panel by its name from `view.panel`. With the React UI, give `mountGame` a `panels` entry, `{ lease: LeasePanel }`, and [`PanelHost`](https://ifloom.dev/docs/reference/react/components#panelhost) renders it in a dialog titled with `with.title`. In a UI of your own, follow [Render a panel](https://ifloom.dev/docs/how-to/render/timers-minigames-panels#render-a-panel), and send `{ type: 'action', id: 'sign-lease' }` from its button. ## Check it worked [#check-it-worked] Run `npm run check`, which reports an `[[act:…]]` that names no action. With the React UI, [`checkUiHints`](https://ifloom.dev/docs/reference/react/hints#checkuihints) also reports a `[[ui:modal|…]]` whose key has no prose. Then press the words in the game. The popup opens over the story and closes on Escape. Signing the lease without 50 coins shows the cost's reason, and with them closes the panel and takes the line away. Don't open a panel from a UI piece. A `[[ui:…]]` link isn't a choice or an action, so the checker, a replay and a UI without that piece don't know it does anything. An inline action does. In the showcase, Small Town, the flat's "the radiator knocks" opens Sam's note, and at the café Ava's name opens her photo (`examples/showcase/src/story/flat.ts` and `story/ava.ts`). For more, see: - [UI pieces](https://ifloom.dev/docs/reference/prose#ui-pieces) and the React UI's [inline pieces](https://ifloom.dev/docs/reference/react/hints#inlineui). - [Panels](https://ifloom.dev/docs/reference/panels) and the [`panel` effect](https://ifloom.dev/docs/reference/effects#panel). - [Presentation lives in UI packages](https://ifloom.dev/docs/explanation/design#presentation-lives-in-ui-packages). # Test a route through your game (https://ifloom.dev/docs/how-to/test-a-route) Use this to check that a route through your game still plays as you meant, every time you change it. The engine runs the same in Node as in a browser, so a test plays commands and checks the state and the view without opening a page. The examples use [Vitest](https://vitest.dev) and the game `npm create ifloom` makes, with its door and its room inside. ## Set up [#set-up] Add Vitest to the game: ```sh tab="npm" tab-group="package-manager" npm install --save-dev vitest ``` ```sh tab="pnpm" tab-group="package-manager" pnpm add --save-dev vitest ``` ```sh tab="yarn" tab-group="package-manager" yarn add --dev vitest ``` ```sh tab="bun" tab-group="package-manager" bun add --dev vitest ``` Then add `"test": "vitest run"` to the scripts in `package.json`. The templates' `tsconfig.json` covers `src` only, so add the tests to its `include`, `"include": ["src", "tests"]`, and `npm run typecheck` checks them too. Any test runner works, since only `describe`, `it` and `expect` come from Vitest. ## Play a route and check the result [#play-a-route-and-check-the-result] Build the game from its game module, play commands with [`play`](https://ifloom.dev/docs/reference/testing#play) from `@ifloom/engine/testing`, and check what came out. `play` fails the test on the first refused command, with its reason: ```ts // tests/game.test.ts import { describe, expect, it } from 'vitest' import { startingState, view } from '@ifloom/engine' import { play } from '@ifloom/engine/testing' import module from '../src/game.ts' const { game, problems } = module.build() const start = startingState(game) describe('the door', () => { it('loads with no problems', () => { expect(problems).toEqual([]) }) it('rewards knocking with courage, and remembers it', () => { const state = play(start, game, { type: 'choose', id: 'knock' }) expect(state.stats.courage).toBe(2) expect(view(state, game).scene.body).toContain('Someone calls out') }) it('says nothing about knocking to a player who waited', () => { const state = play(start, game, { type: 'choose', id: 'wait' }) expect(view(state, game).scene.body).not.toContain('Someone calls out') }) }) ``` Without a `seed`, [`startingState`](https://ifloom.dev/docs/reference/commands#startingstate) uses one made from the game's id, so every run draws the same variants. Check what the player sees through the view and what the game keeps through the state: its [`stats`](https://ifloom.dev/docs/reference/state#stats), the [kv store](https://ifloom.dev/docs/reference/state#kv), [`seen`](https://ifloom.dev/docs/reference/state#seen) and [`chosen`](https://ifloom.dev/docs/reference/state#chosen). `play` takes a plugin helper's command as it is, `play(start, game, places.go('cafe'), jobs.work('cafe'))`. A test that wants undo or saves plays through a runner instead, as [Run a game in code](https://ifloom.dev/docs/how-to/run-a-game-in-code) shows. ## Test a refusal by its reason [#test-a-refusal-by-its-reason] Test a greyed-out choice by its reason, because that's what the player reads. [`apply`](https://ifloom.dev/docs/reference/commands#apply) gives it as `reason`, and the view's button carries the same words in `disabled`: ```ts import { expect, it } from 'vitest' import { apply, startingState, view } from '@ifloom/engine' import module from '../src/game.ts' const { game } = module.build() it('offers no way back before the door', () => { const start = startingState(game) expect(apply(start, game, { type: 'choose', id: 'again' }).reason).toBe('That is not on offer.') expect(view(start, game).scene.choices.map((choice) => choice.id)).toEqual(['knock', 'wait']) }) ``` When a choice is missing and you can't tell why, [Find out why a choice doesn't show](https://ifloom.dev/docs/how-to/troubleshoot-a-missing-choice) lists the causes. ## Check a scene can be reached [#check-a-scene-can-be-reached] A scene nothing leads to is easy to miss. This helper tries every button on screen, then every button after each, until it reaches the scene or runs out of steps, and returns the commands that got there: ```ts import { expect, it } from 'vitest' import { apply, startingState, view, type Command, type Game, type GameState } from '@ifloom/engine' import module from '../src/game.ts' /** The shortest route of presses from `start` to `scene`, or null within `depth` steps. */ function routeTo(game: Game, start: GameState, scene: string, depth = 12): Command[] | null { let frontier = [{ state: start, route: [] as Command[] }] const visited = new Set<string>() for (let step = 0; step < depth && frontier.length; step++) { const next: typeof frontier = [] for (const { state, route } of frontier) { const shown = view(state, game) for (const button of [...shown.scene.choices, ...shown.actions]) { if (button.disabled) continue const out = apply(state, game, button.command) if (!out.ok) continue if (out.state.sceneId === scene) return [...route, button.command] const key = JSON.stringify([out.state.sceneId, out.state.stats, out.state.kv, out.state.turn]) if (!visited.has(key)) next.push({ state: out.state, route: [...route, button.command] }) visited.add(key) } } frontier = next } return null } const { game } = module.build() it('can reach the room inside', () => expect(routeTo(game, startingState(game), 'inside')).toEqual([{ type: 'choose', id: 'knock' }])) ``` The `key` decides when two states count as the same, so the search doesn't go round in circles. Put in it whatever your game's choices depend on, such as `state.plugins` in a game with plugins. `ifloom check` already reports a scene that names a scene that doesn't exist. This search catches a scene that exists but that no choice reaches under the conditions you set. ## Keep a test file per area [#keep-a-test-file-per-area] One content file on its own can't load, since a scene in `story/cafe.ts` names stats from `world/stats.ts`. So test the whole game, with a test file per area that starts where that area does: ```ts // tests/cafe.test.ts import { describe, expect, it } from 'vitest' import { freshState, play } from '@ifloom/engine/testing' import module from '../src/game.ts' const { game } = module.build() describe('the café', () => { it('sells a coffee for 3 coins', () => { const state = play(freshState(game), game, { type: 'action', id: 'coffee' }) expect(state.stats.coins).toBe(9) }) }) ``` [`freshState`](https://ifloom.dev/docs/reference/testing#freshstate) starts a new game with no scene open, so the room's buttons are there. When a test fails, its file names the area, and the area's file is where the fix goes. ## Run them [#run-them] Run `npm test`. In CI, run the tests, then `ifloom check`, `ifloom playtest` and `ifloom snapshot`, as [Playtest and snapshot from the command line](https://ifloom.dev/docs/how-to/playtest-and-snapshot) shows. The showcase's tests in [`examples/showcase/tests/showcase.test.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/tests/showcase.test.ts) play Small Town with every plugin. For more, see: - [Testing helpers](https://ifloom.dev/docs/reference/testing), with [`loadChecked`](https://ifloom.dev/docs/reference/testing#loadchecked), [`freshState`](https://ifloom.dev/docs/reference/testing#freshstate) and [`play`](https://ifloom.dev/docs/reference/testing#play). - [Commands](https://ifloom.dev/docs/reference/commands) and [the view](https://ifloom.dev/docs/reference/view). - [Debug a game](https://ifloom.dev/docs/how-to/debug-a-game), to set up a state with debug commands or replay a player's save. # Translate your game (https://ifloom.dev/docs/how-to/translate-your-game) Use this to make your game readable in another language. A translation is one [pack](https://ifloom.dev/docs/reference/glossary#pack) with three tables. Its `words` give other words to every label, name and line your content writes in place. Its `prose` translates the lines read by key, and its `strings` the engine's and plugins' own lines. You keep writing the game in one language, and the pack lays the other words over it as the game loads. ## List what to translate [#list-what-to-translate] Run [`ifloom words`](https://ifloom.dev/docs/reference/cli#ifloom-words) with `--out` to write every field a player reads as a table to translate from: ```sh npx ifloom words --out words.en.json ``` It builds the game from its game module with no packs, and writes each field's key and its words. For a game with one scene and an action, `words.en.json` reads: ```json { "scene.cafe.counter.title": "The counter", "scene.cafe.counter.text.intro": "Ava looks up from the till.", "scene.cafe.counter.text.4c1f0a": "@ava: \"What can I get you?\"", "scene.cafe.counter.choice.tea.label": "A pot of tea", "scene.cafe.counter.choice.leave.label": "Leave", "action.wait.label": "Wait a while", "entity.character:ava.name": "Ava", "entity.character:ava.description": "Runs the café" } ``` Each key is the path to the field, with each list entry named by its id. [The words table](https://ifloom.dev/docs/reference/words#words) lists every form. A block of words with an `id`, such as `text('Ava looks up from the till.', { id: 'intro' })`, is keyed by it. One without is keyed by six hex digits of a hash of its words, which change when the words do. Give long or often-edited blocks an `id` to keep their key when you fix a typo. ## Translate the words [#translate-the-words] Copy the table into a pack's `words` and translate the values. Keep the keys, the tokens (`{{playerName}}`) and the markup (`@ava:`, `[[act:tea]]`, `**`) as they are: ```ts // src/lang/fr.ts import { SCHEMA, type Pack } from '@ifloom/engine' export const french: Pack = { id: 'lang:fr', schema: SCHEMA, words: { 'scene.cafe.counter.title': 'Le comptoir', 'scene.cafe.counter.text.intro': 'Ava lève les yeux de la caisse.', 'scene.cafe.counter.text.4c1f0a': '@ava: "Je vous sers quoi ?"', 'scene.cafe.counter.choice.tea.label': 'Une théière', 'scene.cafe.counter.choice.leave.label': 'Partir', 'action.wait.label': 'Attendre un peu', 'entity.character:ava.description': 'Tient le café', }, } ``` Leave out anything that reads the same, such as Ava's name. A field the table doesn't name keeps its words. ## Translate the prose and the strings [#translate-the-prose-and-the-strings] Add the two other tables to the same pack: - **`prose`** translates the lines read by key, by the same keys: `{ prose }` blocks, variants, pools, tooltips and the React UI's popups. - **`strings`** translates the engine's and plugins' own lines, such as `Not enough coins.` and the calendar's day names. [Strings](https://ifloom.dev/docs/reference/strings) lists every key, and each plugin's page lists its own under `## Strings`. ```ts import { SCHEMA, type Pack } from '@ifloom/engine' export const french: Pack = { id: 'lang:fr', schema: SCHEMA, prose: { 'place.cafe': 'Six tables, dont une bancale.' }, strings: { finishFirst: 'Finissez ceci d’abord.', 'calendar/period.morning': 'matin' }, } ``` A plugin's line is keyed by the plugin's id, a `/` and the line's name, as in `'calendar/period.morning'`. The React UI's own words, such as its menu, are strings too, under keys that start with `ui.`, listed in [The React UI's strings](https://ifloom.dev/docs/reference/react#strings). ## Load it in the page [#load-it-in-the-page] Choose the language in the page, before the game starts, and pass the pack to the game module's `build`. A game made from a template passes `unlocked` to `loadGame` as its `packs`: ```ts // src/language.ts import type { Pack } from '@ifloom/engine' import { french } from './lang/fr.ts' /** The translation to load over the content, from the browser's language. */ export const translation: Pack[] = navigator.language.startsWith('fr') ? [french] : [] ``` Then build the game with `module.build({ unlocked: translation })` where the page builds it, in `src/main.ts`. Leave the translation out of `build` itself, so `ifloom words` lists the words you write in. The language can also come from a choice on a first page, or from a setting the player changes, followed by a reload. A save records the packs it was made with, so a save made in French names `lang:fr`. It loads in English too, since a translation changes no ids. A translation can also ship as a [mod](https://ifloom.dev/docs/how-to/let-players-add-mods), a mod file whose pack holds the same tables. ## Check it worked [#check-it-worked] `npm run check` builds the game without the translation, so check the pack in a test. [`loadGame`](https://ifloom.dev/docs/reference/content#loadgame) reports every key in the table that names no field: ```ts // tests/french.test.ts import { expect, it } from 'vitest' import module from '../src/game.ts' import { french } from '../src/lang/fr.ts' it('names only fields the game has', () => { expect(module.build({ unlocked: [french] }).problems).toEqual([]) }) ``` A failing key reads `lang:fr · words scene.cafe.counter.text.4c1f0a · names no field the game has`. It's misspelt, or names a line whose words changed since it was translated. List the fields again with `ifloom words` and translate the new line. Then load the page with your browser set to French. A few words stay as they are: - **The player's own words.** A name the player types, or a post they make, is kept as written. - **Calls a plugin doesn't declare as words.** A plugin marks the arguments it translates with [`arg.words()`](https://ifloom.dev/docs/reference/plugin-calls), and a generator's pools aren't in the table. Replace the entry that holds them with a pack of its own. For more, see: - [The words table](https://ifloom.dev/docs/reference/words) and [`translatableFields`](https://ifloom.dev/docs/reference/words#translatablefields). - [Strings](https://ifloom.dev/docs/reference/strings) and [`ifloom words`](https://ifloom.dev/docs/reference/cli#ifloom-words). - [Why a game's files are content and a mod is a pack](https://ifloom.dev/docs/explanation/content-and-packs#why-a-games-files-are-content-and-a-mod-is-a-pack). # Find out why a choice doesn't show (https://ifloom.dev/docs/how-to/troubleshoot-a-missing-choice) Use this when a choice or an action you wrote isn't on screen, or is greyed out when you expect it to work. The engine hides a choice for a few reasons and refuses one for a few more, and it can tell you which. Find your symptom in the tables, then ask the engine to confirm it. ## The choice isn't on screen [#the-choice-isnt-on-screen] A scene's choice or a room's action is left off the screen for one of these reasons: | Problem | Cause | |---|---| | A choice is missing from its scene. | Its `when` doesn't hold. A choice or an action whose `when` fails isn't offered at all, so use a `blocked` entry instead to show it greyed out with a reason. | | A choice or an action is missing while a condition holds. | One of its [`blocked`](https://ifloom.dev/docs/reference/actions#blocked) entries has `hide: true` and its `when` holds. Take `hide` off to grey it out instead. | | A room's action or exit is missing. | A [lock](https://ifloom.dev/docs/reference/locks) with `hide: true` stops its command. A hiding lock covers the room's buttons only, and greys out a scene's choices instead. | | The scene's `choices` are missing below a decision. | A [flowing scene](https://ifloom.dev/docs/how-to/write-a-flowing-scene) offers its `choices` only once the flow reaches the end of the body. While the flow waits at a `decide()`, only that decision's choices show. | | A choice is missing from the buttons but the line has a link. | The prose holds it inline with `[[act:id\|words]]`, so it leaves the list of buttons and shows as a link in the line. See [Put a choice inside a line of text](https://ifloom.dev/docs/how-to/put-a-choice-in-a-line). | | An action is missing while a scene is open. | The room's actions show only while no scene is open. A scene offers its own choices instead. | | A location's action is missing. | The [places plugin](https://ifloom.dev/docs/reference/plugins/places) offers a location's actions only while the player is there. | | An action never shows as a button. | It has no `label`. An action with no label is done only by its command. | | A condition you wrote never holds. | A misspelt kv key reads as unset, and a call to a name nobody declares is false. `ifloom check` reports the call, as `no game condition named "game/marketDy"`. A call with a second key, such as a stray `when`, isn't a call at all. | | A thing is missing from the list of what the player holds. | Its kind isn't [`listed`](https://ifloom.dev/docs/reference/entities#listed), or its `visible` fails. A plugin's kinds aren't listed unless the game says so. | ## The choice is greyed out [#the-choice-is-greyed-out] A greyed-out button carries the reason in `disabled`, and the engine refuses its command with the same words. These are the reasons, in the order [`whyNot`](https://ifloom.dev/docs/reference/actions#whynot) asks: | Problem | Cause | |---|---| | `Finish this first.` on everything. | A [minigame](https://ifloom.dev/docs/reference/minigames) is running, or, on an action, a scene is open. | | A line of your own on many buttons. | A [lock](https://ifloom.dev/docs/reference/locks) in your content's `locks` stops the command while its `when` holds. Its `deny` and `except` say which commands. | | A plugin's line, such as `That would run past dawn.` | A plugin's [guard](https://ifloom.dev/docs/reference/plugin-api#guard) refuses it, such as the calendar's [curfew](https://ifloom.dev/docs/reference/plugins/calendar#calendar). A soft refusal leaves the button pressable with the line as its `warning`. | | `That is not on offer.` | The command names a choice the scene doesn't offer now, or an action whose `when` fails. | | Your `blocked` reason. | The first [`blocked`](https://ifloom.dev/docs/reference/actions#blocked) entry whose `when` holds. | | `Already done.`, or your `once` reason. | Its [`once`](https://ifloom.dev/docs/reference/actions#once) is spent, for the game or until the turn ends. | | `Not enough coins.`, or your `cost.reasons` line. | The player has less of a stat than its [`cost`](https://ifloom.dev/docs/reference/actions#actioncost) asks. Only `cost` refuses: a `stat` effect that takes coins never does. | | The reason of another command. | The choice or action sends a `command`, and that command is refused. | A button shows a choice's own `blocked` and `once` reasons ahead of a lock's. To have a player read one reason before another, such as being too tired before it being too late, put it first in `blocked`. ## Ask the engine why [#ask-the-engine-why] Ask [`whyNot`](https://ifloom.dev/docs/reference/actions#whynot) about the command, and [`explain`](https://ifloom.dev/docs/reference/conditions#explain) about a condition. `explainText` prints the explanation as lines with ✓ or ✗ on each part: ```ts given import { explain, explainText, sceneOf, whyNot } from '@ifloom/engine' whyNot(state, game, { type: 'choose', id: 'coffee' }) // 'Not enough coins.', or undefined when it can be done const coffee = sceneOf(game, 'ava.hi')?.choices?.find((choice) => choice.id === 'coffee') console.log(explainText(explain(state, game, coffee?.when))) // ✗ all of 2: 1 fail // ✓ kv metAva is true; wants set // ✗ stat coins is 3; wants 5 or more ``` A `when` that holds and a `whyNot` that answers `undefined` mean the choice is on offer. A call to the game's own code explains only as the name it called, so test that function on its own. ## See it while you play [#see-it-while-you-play] Add the [debug plugin](https://ifloom.dev/docs/reference/plugins/debug) to development builds, as [Debug a game](https://ifloom.dev/docs/how-to/debug-a-game) shows. The React UI's debug card has a **Why not** tab with the locks on now, what each denies, and every greyed-out choice, action and person's button with its reason. Its forms set a stat, a kv key or the clock, so you can change the state until the choice shows. ## Find it in a playtest [#find-it-in-a-playtest] Run `npx ifloom playtest`. The transcript marks each greyed-out button `[ ]` with its reason after a dash, and lists a choice that's missing by leaving it out of the screen. A button the game offered and then refused is listed after the run, as `turn 3: refused {…}: <reason>`. [Playtest and snapshot from the command line](https://ifloom.dev/docs/how-to/playtest-and-snapshot) covers both. ## Check the content [#check-the-content] Run `npx ifloom check`. It reports a condition that names a stat, a scene, a kv key's call or a plugin the game lacks, a `blocked` reason by key that no strings table has, and a flow whose every choice hides once picked. Fix those first, since each can hide a choice without any error in play. For more, see: - [Actions](https://ifloom.dev/docs/reference/actions), with [`Blocked`](https://ifloom.dev/docs/reference/actions#blocked), [`Once`](https://ifloom.dev/docs/reference/actions#once), [`ActionCost`](https://ifloom.dev/docs/reference/actions#actioncost) and [`whyNot`](https://ifloom.dev/docs/reference/actions#whynot). - [Conditions](https://ifloom.dev/docs/reference/conditions), with [`explain`](https://ifloom.dev/docs/reference/conditions#explain) and [`explainText`](https://ifloom.dev/docs/reference/conditions#explaintext). - [Locks](https://ifloom.dev/docs/reference/locks) and [Choice](https://ifloom.dev/docs/reference/scenes#choice). - [State and commands](https://ifloom.dev/docs/explanation/state-and-commands#locks-and-blocked-reasons), on why the button and the refusal always agree. # Work with a coding agent (https://ifloom.dev/docs/how-to/use-a-coding-agent) Use this when a coding agent, such as Claude Code, Cursor or Codex, writes or changes your game. The agent needs to read the docs and to check what it did, and these steps give it both. ## Give it the docs [#give-it-the-docs] Hand the agent one of the files the docs site publishes for language models: - [`llms-full.txt`](https://ifloom.dev/llms-full.txt) holds every page in one file, about 3 MB. Give it to an agent with room for it in its context. - `llms/<section>.txt` holds one section's pages in one file, such as [`llms/how-to.txt`](https://ifloom.dev/llms/how-to.txt) for the how-to guides or [`llms/reference.txt`](https://ifloom.dev/llms/reference.txt), for an agent with less room. `llms.txt` lists them. - [`llms.txt`](https://ifloom.dev/llms.txt) lists every page with a link and a one-line description. Give it to an agent with a small context, and let it fetch the pages it needs. Each page is also plain Markdown under `https://ifloom.dev/llms.mdx/docs/`. The Copy Markdown button at the top of a page copies it, and the Open menu beside it opens the page in ChatGPT, Claude or Cursor. An agent that works offline in a clone of the [IFLoom repository](https://github.com/IFLoom/ifloom) can read the same pages in `docs/content/docs/`. ## Connect it to the MCP server [#connect-it-to-the-mcp-server] The docs site runs an MCP server at `https://ifloom.dev/api/mcp`, over streamable HTTP, so the agent searches the docs and fetches single pages. Add it to the agent's MCP settings, such as `.mcp.json` for Claude Code or `.cursor/mcp.json` for Cursor: ```json { "mcpServers": { "ifloom": { "url": "https://ifloom.dev/api/mcp" } } } ``` The server has three tools: - `search` finds pages and headings that match a query. - `list_pages` lists every page with its path and description. - `get_page` returns one page as Markdown, given a path such as `/docs/reference/scenes`. ## Let AGENTS.md brief it [#let-agentsmd-brief-it] Every game that `npm create ifloom` makes has an `AGENTS.md`, which agents read when they start work in a folder. It points the agent at the docs, the MCP server and the three examples. It also says where each kind of content goes, as [Organise your game's files](https://ifloom.dev/docs/how-to/organise-your-files) does, and which commands to run after every change. Add your game's own conventions to it, such as how you name scenes, the tone of the prose, and which plugins the game uses. ## Have it check its own work [#have-it-check-its-own-work] Tell the agent to run these after every change: 1. `npm run check` loads the game and lists every problem, such as a scene, prose key or id that content names and nothing declares. It prints `No problems.` and exits with `0` when there are none, and exits with `1` otherwise. 2. `npm run playtest` plays a few turns with nobody at the keyboard and writes every screen and command to a text file. The agent reads it to find a scene that never shows, a choice that's always refused, or a number that never moves. 3. `npm run typecheck` runs TypeScript, so a field the agent misspelt fails. ## Point it at an example [#point-it-at-an-example] Ask the agent to follow one of the repository's three examples, which are whole, working games: - `examples/novel` for a story in chapters. - `examples/cafe` for a management game built on [entities](https://ifloom.dev/docs/reference/entities). - `examples/showcase` for places, characters and a calendar. Ask for content as data, too. Scenes, conditions and effects are plain objects that `check` reads, and a rule written as code is harder for the agent and for `check` to verify. For more, see: - [The CLI](https://ifloom.dev/docs/reference/cli), for `check`, `playtest` and the other commands. - [Playtest and snapshot from the command line](https://ifloom.dev/docs/how-to/playtest-and-snapshot), to put the same checks in CI. - [The examples](https://ifloom.dev/docs/reference/examples), with each example's files. # Run the examples from the repository (https://ifloom.dev/docs/how-to/work-in-the-repository) Use this to try code that hasn't been released yet, such as a fix on the main branch. You need Node 22.18 or later, git and npm, because the checkout's tools run the packages' TypeScript source and Node strips the types itself from 22.18. For a game on the published packages, see [Create a game](https://ifloom.dev/docs/how-to/create-a-game) instead. ## Play the examples [#play-the-examples] 1. Clone the repository and install it: ```sh git clone https://github.com/IFLoom/ifloom.git cd ifloom npm install ``` 2. Run an example's dev server, and open the address Vite prints: ```sh npm run dev -w @ifloom/example-novel # The Letter, a linear novel npm run dev -w @ifloom/example-cafe # The Corner Café, a management game npm run dev -w @ifloom/showcase # Small Town, which uses every feature ``` The showcase has more scripts, each run the same way with `-w @ifloom/showcase`: ```sh npm run build # build dist/index.html npm run check # list any problem in its content npm run playtest # play a week unattended, into playtest/week.txt npm run snapshot # compare every scene with snapshots/scenes.txt npm run build:one-file # build dist-one/index.html, with the pictures inside it ``` Open the built `dist/index.html` straight from disk, with no server. [The examples](https://ifloom.dev/docs/reference/examples) lists each example's files. ## Make a game inside the checkout [#make-a-game-inside-the-checkout] From the root of the checkout: ```sh npm run new -- my-game npm install npm run dev -w my-game ``` `npm run new` runs [`ifloom new`](https://ifloom.dev/docs/reference/cli#ifloom-new), with the same `--template` and `--theme`, and makes the game in `games/my-game`. The `games/` folder is an npm workspace, so `npm install` links the game to the packages. Git ignores `games/`, so your game stays out of IFLoom's history and a pull leaves it alone. Run the game's scripts from the root with `-w`, as in `npm run check -w my-game`. The checkout's workspaces are npm's, so use npm here. A change to a package shows up in the game straight away, because the checkout's tools read each package's source. A `next` game is the exception: run `npm run build` at the root before its `dev` or `build`, and again after you change a package. ## Make a game beside the checkout [#make-a-game-beside-the-checkout] Use this to keep the game in a folder and repository of its own, next to the checkout, on the packages as they'll be published: ``` work/ ├── ifloom/ the IFLoom repository └── my-game/ your game ``` 1. Build and pack every package into `ifloom/packs/`: ```sh cd ifloom npm install npm run pack ``` To write the files elsewhere, give a folder after `--`, relative to the checkout: `npm run pack -- ../my-game/packs`. The `file:` paths below then read `file:./packs/…`. 2. Make the game beside the checkout with `create-ifloom`'s command, straight from the checkout. It takes the same `--template` and `--theme`: ```sh cd .. node ifloom/packages/create-ifloom/bin.js my-game ``` 3. In `my-game/package.json`, point the `@ifloom` dependencies at the packed files: ```json { "dependencies": { "@ifloom/engine": "file:../ifloom/packs/ifloom-engine-0.2.0.tgz", "@ifloom/react": "file:../ifloom/packs/ifloom-react-0.2.0.tgz", "@ifloom/audio": "file:../ifloom/packs/ifloom-audio-0.2.0.tgz", "@ifloom/browser": "file:../ifloom/packs/ifloom-browser-0.2.0.tgz" }, "devDependencies": { "@ifloom/cli": "file:../ifloom/packs/ifloom-cli-0.2.0.tgz" } } ``` List `@ifloom/audio` and `@ifloom/browser` even though they're peers of `@ifloom/react`, or the package manager fetches them from the registry. A package's file is its name without the `@`, with the `/` as a `-`, then its version, so `@ifloom/plugin-jobs` is `ifloom-plugin-jobs-0.2.0.tgz`. Add one for each plugin the game uses. 4. Install and run it: ```sh tab="npm" tab-group="package-manager" cd my-game npm install npm run check npm run dev ``` ```sh tab="pnpm" tab-group="package-manager" cd my-game pnpm install pnpm check pnpm dev ``` ```sh tab="yarn" tab-group="package-manager" cd my-game yarn install yarn run check yarn run dev ``` ```sh tab="bun" tab-group="package-manager" cd my-game bun install bun run check bun run dev ``` Three package managers need one more step: - **bun** looks a package's peers up on the registry even when the game lists them. List the same files under `"overrides"` too. - **yarn 2 and later** need a `.yarnrc.yml` holding `nodeLinker: node-modules`, because Vite doesn't support Plug'n'Play installs. `yarn create ifloom` writes it, but running the command with `node` doesn't. - **npm 10**, which comes with Node 20, stops with `Cannot read properties of null (reading 'edgesOut')` on the packed files. Run `npm install --legacy-peer-deps`, or update npm. A plugin package beside the checkout works the same way. Make it with `--template plugin`, and point its `@ifloom/engine` dev dependency at the packed engine. Leave its peer dependency as it is, since that's the range a game sees once the plugin is on npm. ## Send a change back [#send-a-change-back] A pull request that changes a published package adds a changeset, a small file saying which packages changed and what to tell people, which the release turns into new versions and changelog lines: ```sh npm run changeset ``` Pick the packages and whether each is a patch or a minor (before 1.0, a minor is a breaking change), then write the line for the changelog, starting with `Added:`, `Changed:`, `Removed:` or `Fixed:`. A change to the docs or the examples needs none. [CONTRIBUTING.md](https://github.com/IFLoom/ifloom/blob/main/CONTRIBUTING.md) has the rest: the checks to run and how a release happens. ## Check it worked [#check-it-worked] `npm run check` prints `No problems.` in the new game, and `npm run dev` serves it. After you pull a newer IFLoom, run `npm run pack` in the checkout again, then `npm update` in the game. With another package manager, delete `node_modules` and the lockfile and install again. yarn 1 also keeps the old files in its cache under the same version, so run `yarn cache clean` first. For more, see: - [`ifloom new`](https://ifloom.dev/docs/reference/cli#ifloom-new) and [the CLI's requirements](https://ifloom.dev/docs/reference/cli#requirements). - [Write a plugin](https://ifloom.dev/docs/how-to/write-a-plugin), for a plugin package of your own. # Write a flowing scene (https://ifloom.dev/docs/how-to/write-a-flowing-scene) Write a scene as a [flow](https://ifloom.dev/docs/reference/glossary#flow) when it should carry on after each choice, such as a conversation or a chapter whose text builds as the player decides. Each choice the player makes stays on the page where it was made, followed by the words it brings. You need a game with at least one scene, as [Create a game](https://ifloom.dev/docs/how-to/create-a-game) makes. ## Write the words in place [#write-the-words-in-place] Build the scene's `body` with the builders `@ifloom/engine` exports. `text()` takes a page of words and removes the indentation its lines share, and a blank line starts a new paragraph: ```ts import type { DataScene } from '@ifloom/engine' import { text } from '@ifloom/engine' export const river: DataScene = { id: 'ava.river', title: 'By the river', speaker: 'ava', body: [ text(` Ava is on the bench with her shoes off, feeding the ducks the crusts of the day. "I told you it was the only quiet in town." She shuffles up to make room. `), ], choices: [{ id: 'home', label: 'Say goodnight', effects: [{ scene: null }] }], } ``` A `{ prose: 'ava.river' }` block still works beside the builders, so you can move a scene over one block at a time. ## Stop for a decision [#stop-for-a-decision] Put a `decide()` where the flow should wait for the player to choose. The chosen choice's `then` comes next, then the blocks after the decision: ```ts import { choice, decide, say, text, type Block } from '@ifloom/engine' export const evening: Block[] = [ text(`Ava is on the bench with her shoes off, feeding the ducks.`), decide('evening', [ choice('ducks', 'Ask about the ducks', { then: [say('ava', 'They know my name. I never asked theirs.')] }), choice('stay', 'Sit with her until the light goes', { effects: [{ stat: 'friendship', by: 5, of: 'character:ava' }], then: [text(`The water goes orange, then grey.`)], }), ]), text(`You walk back along the river together, as far as the bridge.`), ] ``` Either choice ends with the walk back, then the scene's own `choices`. To leave instead of rejoining, give the choice a `{ scene: null }` or `{ scene: 'park.dusk' }` effect and no `then`. ## Come back to a question [#come-back-to-a-question] Let the player ask several questions in any order before moving on: 1. Put a `point()` before the decision. 2. Give each question a `jump()` back to it in its `effects`. 3. Hide each question once it's asked, with a `blocked` entry that has `hide: true`. 4. Keep one choice that moves on. ```ts import { choice, decide, jump, point, say, text, type Blocked } from '@ifloom/engine' const asked = (id: string): Blocked[] => [{ when: { chose: `ava.river#${id}` }, reason: 'You asked.', hide: true }] export const questions = [ text(`Ava is on the bench with her shoes off, feeding the ducks.`), point('bench'), decide('evening', [ choice('ducks', 'Ask about the ducks', { blocked: asked('ducks'), then: [say('ava', 'They know my name.')], effects: [jump('bench')] }), choice('bridge', 'Ask about the bridge', { blocked: asked('bridge'), then: [say('ava', 'Older than the town.')], effects: [jump('bench')] }), choice('stay', 'Sit with her until the light goes'), ]), text(`You walk back along the river together.`), ] ``` A jump is only ever a choice's effect, so the flow goes round again only when the player chooses. The checker reports a decision whose every choice hides once chosen, because the flow would stop there with nothing left. ## Skip ahead [#skip-ahead] Put a `point()` inside a choice's `then` or a section, and jump to it from another choice. The flow goes straight there and reads on: ```ts import { choice, decide, jump, point, text } from '@ifloom/engine' export const walk = [ decide('way', [ choice('hill', 'Over the hill', { then: [text(`It's steep. Your legs complain.`), point('gate'), text(`The gate is open.`)] }), choice('lane', 'Down the lane', { then: [text(`The lane is muddy but flat.`)], effects: [jump('gate')] }), ]), text(`The farmhouse is ahead.`), ] ``` Taking the lane reads "The lane is muddy but flat.", then "The gate is open.", then "The farmhouse is ahead." ## Play a minigame or open a panel where it stands [#play-a-minigame-or-open-a-panel-where-it-stands] Put `minigame('skim')` in the body to start a [minigame](https://ifloom.dev/docs/reference/minigames) when the flow gets there. The flow waits until it ends, then reads on. `panel('prices', { stall: 'bread' })` opens a [panel](https://ifloom.dev/docs/reference/panels) the same way and waits until the player closes it: ```ts import { minigame, say, text, when } from '@ifloom/engine' export const stones = [ text(`Ava finds a flat stone and holds it out.`), minigame('skim'), when({ kv: 'skips', gte: 4 }, [say('ava', 'Show-off.')]), text(`The ripples reach the far bank.`), ] ``` ## Fold a part away [#fold-a-part-away] Wrap blocks in `fold()` for a part the player opens and shuts, such as a letter they might not want to read again. A fold keeps no state: ```ts import { fold, text } from '@ifloom/engine' export const postcard = fold('Read the postcard', [text(`Wish you were here. The sea is cold and the chips are good. J.`)]) ``` Make reading it a choice instead when it matters to the story, so the save keeps it and a replay repeats it. ## Check it worked [#check-it-worked] Run `npm run check`. It prints `No problems.` when every jump lands on a point and every decision lets the flow move on. Then play the scene with `npm run dev`. Each choice you make stays on the page where you made it, and the words it brings follow it. The React UI renders all of this with no code from you. To render a flowing scene in a UI of your own, see [Render a flowing scene](https://ifloom.dev/docs/how-to/render/scene#render-a-flowing-scene). In the showcase, Small Town, the evening by the river (`ava.river` in [`examples/showcase/src/story/ava.ts`](https://github.com/IFLoom/ifloom/blob/main/examples/showcase/src/story/ava.ts)) lets you pocket a shell and ask about the ducks before you sit with Ava. For more, see: - [Flows](https://ifloom.dev/docs/reference/flows), with every builder and the checks. - [Scenes](https://ifloom.dev/docs/reference/scenes) and [blocked](https://ifloom.dev/docs/reference/actions#blocked). - [A scene and the room](https://ifloom.dev/docs/explanation/turns-and-time#a-scene-and-the-room). # Write a plugin (https://ifloom.dev/docs/how-to/write-a-plugin) Use this to add a whole system of your own, such as a loyalty card, a sink of dirty dishes or a diary. A [plugin](https://ifloom.dev/docs/reference/glossary#plugin) keeps state in the save and brings the conditions, effects, commands, values, hooks and view that work on it. Content calls them by name with the plugin's id in front, so a mod can use them without shipping code. Write a plugin when the system needs state of its own that saves carry forward, or when more than one game should use it. For code only one game needs, write [the game's own rules](https://ifloom.dev/docs/how-to/write-your-own-condition-or-effect) instead, which can have what a plugin has. ## Start a package [#start-a-package] A plugin can sit in your game's `src/`, as the loyalty card below does. To publish one, start a package of its own from the `plugin` template: ```sh tab="npm" tab-group="package-manager" npm create ifloom@latest ifloom-plugin-loyalty -- --template plugin cd ifloom-plugin-loyalty npm install npm test ``` ```sh tab="pnpm" tab-group="package-manager" pnpm create ifloom ifloom-plugin-loyalty --template plugin cd ifloom-plugin-loyalty pnpm install pnpm test ``` ```sh tab="yarn" tab-group="package-manager" yarn create ifloom ifloom-plugin-loyalty --template plugin cd ifloom-plugin-loyalty yarn install yarn run test ``` ```sh tab="bun" tab-group="package-manager" bun create ifloom ifloom-plugin-loyalty --template plugin cd ifloom-plugin-loyalty bun install bun run test ``` The plugin's id is the package's name without `ifloom-plugin-` or `plugin-` in front, so this makes `loyalty`. The template's files are: - **`src/index.ts`**: the plugin, with a list of entries in `data.loyalty.entries`, a condition, an effect, a command, a view and a check, each marked `TODO`. - **`src/react/`**: its optional React UI, the `/react` subpath. [Write a plugin's React UI](https://ifloom.dev/docs/how-to/react/write-a-plugins-react-ui) covers it. - **`tests/`**: Vitest tests that play the plugin in a small game, alone and with each partner, and a contract test that holds the source to the plugin rules and the README to the exports. - **`package.json`**: the engine as a caret peer dependency, and the scripts `test`, `typecheck` and `build`. ## Write the first plugin [#write-the-first-plugin] Make the plugin with [`definePlugin`](https://ifloom.dev/docs/reference/plugin-api#defineplugin). `start` gives a new game's state, and each function gets the game state, its arguments and a [context](https://ifloom.dev/docs/reference/plugin-api#plugincontext) whose `slice` is the plugin's own state: ```ts // src/loyalty.ts import { definePlugin } from '@ifloom/engine/plugin' type Card = { stamps: number } export const loyalty = definePlugin<Card>({ id: 'loyalty', version: 1, start: () => ({ stamps: 0 }), effects: { stamp: (_state, _args, { slice, set }) => set({ stamps: slice.stamps + 1 }), }, conditions: { full: (_state, _args, { slice }) => slice.stamps >= 5, }, values: { stamps: (_state, _args, { slice }) => slice.stamps, }, }) ``` `set` returns the game state with the plugin's state replaced. An effect returns that state, a condition true or false, and a value a number or a word for prose. ## Call it from content [#call-it-from-content] List the plugin in the game's `plugins`, then call each name with `loyalty/` in front: ```ts import { loadGame, type Content } from '@ifloom/engine' import { loyalty } from './loyalty.ts' const cafe: Content = { actions: [{ id: 'coffee', label: 'Buy a coffee', effects: [{ stat: 'energy', by: 15 }, { 'loyalty/stamp': true }] }], scenes: [ { id: 'counter', body: [{ text: 'Your card has {{loyalty/stamps}} stamps.' }], choices: [ { id: 'free', label: 'Claim a free coffee', when: { 'loyalty/full': true }, effects: [{ scene: null }] }, { id: 'leave', label: 'Not today', effects: [{ scene: null }] }, ], }, ], } export const { game, problems } = loadGame([cafe], { id: 'corner-cafe', title: 'The Corner Café', plugins: [loyalty] }) ``` After five coffees, `loyalty.read(state, game)` is `{ stamps: 5 }` and the counter offers the free coffee. The [content checker](https://ifloom.dev/docs/reference/checks) reports a name the plugin doesn't have, such as `no plugin effect named "loyalty/stomp"`. ## Declare its calls and add a command [#declare-its-calls-and-add-a-command] Declare each call once with [`defineCalls`](https://ifloom.dev/docs/reference/plugin-calls#definecalls), and pass it as `calls`. Each function then gets its arguments typed and read from whatever content wrote. A command the player sends has a `run`, and a `whyNot` that refuses it in the player's words, kept in `strings` so a game can reword them: ```ts import { applyEffects, stringOf } from '@ifloom/engine' import { arg, defineCalls, definePlugin } from '@ifloom/engine/plugin' type Card = { stamps: number; free: number } const CALLS = defineCalls('loyalty', { conditions: { stamps: { atLeast: arg.number().optional(1) }, hasFree: {} }, effects: { stamp: {} }, commands: { redeem: {} }, }) export const loyalty = definePlugin<Card, unknown, typeof CALLS>({ id: 'loyalty', version: 2, calls: CALLS, start: () => ({ stamps: 0, free: 0 }), // A version 1 save kept only stamps. migrations: { 1: (old) => ({ stamps: (old as { stamps: number }).stamps, free: 0 }) }, conditions: { stamps: (_state, { atLeast }, { slice }) => slice.stamps >= atLeast, hasFree: (_state, _args, { slice }) => slice.free > 0, }, effects: { stamp: (_state, _args, { slice, set }) => (slice.stamps === 4 ? set({ stamps: 0, free: slice.free + 1 }) : set({ ...slice, stamps: slice.stamps + 1 })), }, strings: { notFull: 'Your card is not full yet.', onlyAtCafe: 'Only at the café.' }, commands: { redeem: { whyNot: (_state, _args, { slice, game, query }) => slice.free === 0 ? stringOf(game, 'loyalty/notFull') : query('places/here') !== 'cafe' ? stringOf(game, 'loyalty/onlyAtCafe') : undefined, run: (state, _args, { slice, set, game }) => set({ ...slice, free: slice.free - 1 }, applyEffects(state, game, [{ stat: 'energy', by: 15 }])), }, }, view: (_state, { slice }) => ({ stamps: slice.stamps, free: slice.free }), }) ``` The state gained a field, so `version` went up and `migrations` carries a version 1 save forward. `query('places/here')` asks the [places plugin](https://ifloom.dev/docs/reference/plugins/places) where the player is without importing it, and answers `undefined` in a game without it. A button sends the command as `{ 'loyalty/redeem': true }`. Its view greys the button out with the same `whyNot` line, and a game rewords it with `strings: { 'loyalty/notFull': 'Five stamps first.' }`. Give the factory helpers that write each call, named after it, with the declaration's writers (`CALLS.effects.stamp({})`). See [`CallWriter`](https://ifloom.dev/docs/reference/plugin-calls#callwriter). ## Watch other commands [#watch-other-commands] A [guard](https://ifloom.dev/docs/reference/plugin-api#guard) refuses any command, a [price](https://ifloom.dev/docs/reference/plugin-api#price) adds a note to a button's cost, and a [label](https://ifloom.dev/docs/reference/plugin-api#label) adds to the header. Each is handed the effects a command would apply. This sink of dishes refuses cooking once three dishes would pile up: ```ts import { callOf, stringOf, type Effect } from '@ifloom/engine' import { definePlugin } from '@ifloom/engine/plugin' const added = (effects: readonly Effect[]) => effects.reduce((n, effect) => (callOf(effect)?.name === 'dishes/add' ? n + 1 : n), 0) export const dishes = definePlugin<{ dirty: number }>({ id: 'dishes', version: 1, start: () => ({ dirty: 0 }), strings: { piling: 'The dishes would pile up. Wash up first.' }, effects: { add: (_state, _args, { slice, set }) => set({ dirty: slice.dirty + 1 }) }, guard: (_state, { effects }, { slice, game }) => (slice.dirty + added(effects) > 3 ? stringOf(game, 'dishes/piling') : undefined), price: (_state, effects) => (added(effects) ? ['a dish to wash'] : undefined), label: (_state, { slice }) => (slice.dirty ? `${slice.dirty} in the sink` : undefined), }) ``` A guard that returns `{ reason, soft: true }` leaves the button pressable with the line as its `warning`, as the calendar warns before dawn. ## Run code as turns end and commands take [#run-code-as-turns-end-and-commands-take] A [hook](https://ifloom.dev/docs/reference/glossary#hook) runs at an event and returns the next state. `onTurn` and `onTurnDone` run as each turn ends, and `onCommand` after every command that took: ```ts import { definePlugin } from '@ifloom/engine/plugin' type Diary = { days: number; places: string[] } export const diary = definePlugin<Diary>({ id: 'diary', version: 1, start: () => ({ days: 0, places: [] }), onTurn: (_state, { slice, set }) => set({ ...slice, days: slice.days + 1 }), onCommand: (_before, after, { slice, set, query }) => { const here = query('places/here') ?? null return here === null || slice.places.includes(here) ? after : set({ ...slice, places: [...slice.places, here] }) }, }) ``` Return the state you were given when nothing changes. `onCommand` runs only for a command that took, so work out what the first screen needs from the state rather than from it. ## Test it [#test-it] Test the plugin in a small game with [`@ifloom/engine/testing`](https://ifloom.dev/docs/reference/testing). `loadChecked` fails on any content problem, `freshState` starts with no scene open, and `play` fails on the first refused command: ```ts // tests/loyalty.test.ts import { describe, expect, it } from 'vitest' import { apply, type Command, type Content } from '@ifloom/engine' import { freshState, loadChecked, play } from '@ifloom/engine/testing' import { loyalty } from '../src/loyalty.ts' const cafe: Content = { actions: [{ id: 'coffee', label: 'Buy a coffee', effects: [{ 'loyalty/stamp': true }] }] } const game = loadChecked([cafe], { id: 'corner-cafe', title: 'The Corner Café', plugins: [loyalty] }) const coffee: Command = { type: 'action', id: 'coffee' } describe('the loyalty card', () => { it('gives a free coffee after five', () => { const state = play(freshState(game), game, coffee, coffee, coffee, coffee, coffee) expect(loyalty.read(state, game)).toEqual({ stamps: 0, free: 1 }) }) it('refuses to redeem an empty card', () => { expect(apply(freshState(game), game, { type: 'custom', name: 'loyalty/redeem' }).reason).toBe('Your card is not full yet.') }) }) ``` A plugin that works with others runs the same tests alone and with each partner, as [Make plugins work together](https://ifloom.dev/docs/how-to/make-plugins-work-together#test-it-alone-and-with-each-partner) shows. ## Publish it [#publish-it] Run `npm run typecheck` and `npm test`, then `npm publish`, which builds `dist/` with [tsdown](https://tsdown.dev) first. To have it listed on [Community plugins](https://ifloom.dev/docs/reference/plugins/community), meet the criteria the template's README lists. When a release changes what content writes for the plugin, such as an argument's name, bump its `contentVersion` and give it a step in `contentMigrations`, so packs and mods written for the last release still load. A renamed command gets a step in `commandMigrations` too, so old command logs still replay. See [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations). For more, see: - [Plugin API](https://ifloom.dev/docs/reference/plugin-api), with [`Plugin`](https://ifloom.dev/docs/reference/plugin-api#plugin), [`PluginContext`](https://ifloom.dev/docs/reference/plugin-api#plugincontext) and [`definePlugin`](https://ifloom.dev/docs/reference/plugin-api#defineplugin). - [Plugin calls](https://ifloom.dev/docs/reference/plugin-calls), [plugin queries](https://ifloom.dev/docs/reference/plugin-queries) and [plugin views](https://ifloom.dev/docs/reference/plugin-views). - [Plugins](https://ifloom.dev/docs/explanation/plugins), on hooks, providers and why content goes in `data`. - [Add a plugin](https://ifloom.dev/docs/how-to/add-a-plugin), for a game that uses one. # Write a save driver (https://ifloom.dev/docs/how-to/write-a-save-driver) Use this when the browser's storage needs handling the built-in drivers don't do. A save driver is a name and four async functions that store strings by key. The save store, the [profile](https://ifloom.dev/docs/reference/profile) and the [mod store](https://ifloom.dev/docs/reference/mods) all write through the driver you give them, so one driver covers everything your game keeps. Most games need none of their own. Choose one of these first: - **`memoryDriver()`**, from `@ifloom/engine`, keeps saves in a `Map` that goes with the page. Use it for tests and previews. - **`localStorageDriver()`**, from [`@ifloom/browser`](https://ifloom.dev/docs/reference/browser#save-drivers), keeps them in `localStorage`, about 5MB shared by every game on one origin. Use it for short games. [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner) uses it unless told otherwise. - **`indexedDbDriver()`**, from `@ifloom/browser`, keeps them in IndexedDB, up to the browser's own quota. Use it for long games, big backlogs and mods. Write your own for saves that don't fit in `localStorage`, for a browser that refuses storage, or to move players' saves to another driver. The drivers on this page wrap the browser's, so they work from disk and online with nothing to install. Each keeps the rules [`SaveDriver`](https://ifloom.dev/docs/reference/saves#savedriver) lists. ## Compress saves to take less room [#compress-saves-to-take-less-room] In Chromium, every game opened from disk shares one `localStorage`. This driver wraps another and compresses each value with the browser's own `CompressionStream`, storing the bytes as base64: ```ts // compressed.ts import type { SaveDriver } from '@ifloom/engine' // Marks a value this driver compressed, so saves written before you added it still read. const MARK = 'gz:' async function pipe(bytes: Uint8Array<ArrayBuffer>, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> { return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer()) } const toBase64 = (bytes: Uint8Array) => btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')) const fromBase64 = (text: string) => Uint8Array.from(atob(text), (char) => char.charCodeAt(0)) export function compressed(driver: SaveDriver): SaveDriver { return { name: `${driver.name} (compressed)`, async get(key) { const value = await driver.get(key) if (value === null || !value.startsWith(MARK)) return value return new TextDecoder().decode(await pipe(fromBase64(value.slice(MARK.length)), new DecompressionStream('gzip'))) }, async set(key, value) { await driver.set(key, MARK + toBase64(await pipe(new TextEncoder().encode(value), new CompressionStream('gzip')))) }, remove: (key) => driver.remove(key), keys: (prefix) => driver.keys(prefix), } } ``` Use it as `compressed(localStorageDriver())`. A save made mostly of prose, such as one with a long backlog, comes out at half its size or less, and a small save gains almost nothing. The `gz:` mark tells the driver's own values from plain ones, so saves made before you added it still load and are compressed the next time they're written. ## Fall back when the browser refuses storage [#fall-back-when-the-browser-refuses-storage] Some embedded frames, privacy settings and private windows refuse `localStorage` or IndexedDB, and then every save fails. This driver tries the drivers you give it in order, and keeps saves in the first that accepts a test write: ```ts // first-that-works.ts import type { SaveDriver } from '@ifloom/engine' export function firstThatWorks(...drivers: SaveDriver[]): SaveDriver & { chosen: () => Promise<SaveDriver> } { let found: Promise<SaveDriver> | undefined const chosen = () => (found ??= (async () => { for (const driver of drivers) { try { await driver.set('ifloom.probe', '1') await driver.remove('ifloom.probe') return driver } catch { // Refused here: try the next. } } throw new Error('No storage is available for saves.') })()) return { name: drivers.map((driver) => driver.name).join(' or '), chosen, get: async (key) => (await chosen()).get(key), set: async (key, value) => (await chosen()).set(key, value), remove: async (key) => (await chosen()).remove(key), keys: async (prefix) => (await chosen()).keys(prefix), } } ``` `firstThatWorks(indexedDbDriver(), localStorageDriver(), memoryDriver())` keeps saves in IndexedDB where it can, then `localStorage`, then memory. Saves in memory go when the page closes, so tell the player when `(await driver.chosen()).name` is `'memory'`. The save store's [`exportSlot`](https://ifloom.dev/docs/reference/saves#saves) gives them their save as a file to keep, and `importText` reads it back. ## Move saves to a new driver [#move-saves-to-a-new-driver] Changing driver moves nothing, so a switch from `localStorage` to IndexedDB leaves players' saves behind. Copy them across once, before the game starts: ```ts // move-saves.ts import type { SaveDriver } from '@ifloom/engine' // Copies everything one game keeps (saves, profile, mods) from an old driver to a new one. export async function moveSaves(gameId: string, from: SaveDriver, to: SaveDriver): Promise<void> { for (const key of await from.keys(`${gameId}.`)) { if ((await to.get(key)) !== null) continue const value = await from.get(key) if (value !== null) await to.set(key, value) } } ``` It copies only your game's keys and never overwrites one the new driver has, so running it on every start is safe. It leaves the old copies in place, for a player who goes back to an older build. ## Pass the driver to the runner [#pass-the-driver-to-the-runner] Give the driver to the save store and the profile, and pass both to the runner. [`browserRunner`](https://ifloom.dev/docs/reference/browser#browserrunner) uses them in place of its `localStorage` default: ```ts import { browserRunner, indexedDbDriver, localStorageDriver } from '@ifloom/browser' import { memoryDriver, profile, saves } from '@ifloom/engine' import { compressed } from './compressed.ts' import { firstThatWorks } from './first-that-works.ts' import { moveSaves } from './move-saves.ts' import module from './game.ts' const { game } = module.build() const driver = firstThatWorks(indexedDbDriver(), compressed(localStorageDriver()), memoryDriver()) await moveSaves(game.id, localStorageDriver(), driver).catch(() => {}) const runner = await browserRunner(game, { saves: saves(game, driver), profile: profile(game, driver) }) ``` The React UI's [`mountGame`](https://ifloom.dev/docs/reference/react#mountgame) takes the same two in its `runner` option, as [Ship your game](https://ifloom.dev/docs/how-to/ship-your-game#choose-where-saves-go) shows. A game with [mods](https://ifloom.dev/docs/how-to/let-players-add-mods) passes the driver to `mods(game.id, driver)` too. ## Test it [#test-it] Run a new driver through these checks before you trust it with a player's saves. They cover each rule, including a slot name with characters a careless driver would mangle: ```ts import { test } from 'node:test' import assert from 'node:assert/strict' import { memoryDriver, type SaveDriver } from '@ifloom/engine' import { compressed } from '../src/compressed.ts' async function checkDriver(driver: SaveDriver) { assert.equal(await driver.get('test.missing'), null) await driver.set('test.save.1', '{"a":1}') await driver.set('test.save.1', '{"a":2}') assert.equal(await driver.get('test.save.1'), '{"a":2}') await driver.set('test.save.Before the fair: 3/4 *', 'x') await driver.set('other.save.1', 'y') assert.deepEqual((await driver.keys('test.save.')).sort(), ['test.save.1', 'test.save.Before the fair: 3/4 *']) await driver.remove('test.save.1') await driver.remove('test.save.1') assert.deepEqual(await driver.keys('test.save.'), ['test.save.Before the fair: 3/4 *']) } test('the compressed driver keeps the rules', () => checkDriver(compressed(memoryDriver()))) ``` Node has no `localStorage` or IndexedDB, so test a wrapping driver over `memoryDriver()`, or over [`localStorageDriver(storage)`](https://ifloom.dev/docs/reference/browser#localstoragedriver) with a storage object of your own. Then write and read a real save through [`saves`](https://ifloom.dev/docs/reference/saves#saves) with your game, to catch a driver that changes what it stores. ## Variations [#variations] **Files in a desktop app.** A game wrapped with Electron or Tauri can keep saves as files the player can back up. Write the driver over Node's `fs/promises` in Electron's main process, or Tauri's `@tauri-apps/plugin-fs`. Encode each key with `encodeURIComponent` (and `*` as `%2A`, which Windows refuses) to make a file name, and decode the names back in `keys`. Answer `null` from `get` when the file is missing, and let other errors reject. In Electron, expose the four functions to the page through a preload script, and build the `SaveDriver` in the page from them. Windows and macOS treat `Quick.json` and `quick.json` as one file, so lower-case the slot names your game makes. For more, see: - [Saves](https://ifloom.dev/docs/reference/saves), with [`SaveDriver`](https://ifloom.dev/docs/reference/saves#savedriver) and [`memoryDriver`](https://ifloom.dev/docs/reference/saves#memorydriver). - [Save drivers](https://ifloom.dev/docs/reference/browser#save-drivers) in `@ifloom/browser`. - [Ship your game](https://ifloom.dev/docs/how-to/ship-your-game#choose-where-saves-go), to choose a driver for a game in the browser. # Write your own condition, effect or macro (https://ifloom.dev/docs/how-to/write-your-own-condition-or-effect) Use this when content needs something worked out in code, such as whether it's market day or what a loaf costs today. You write the function once in the game's [rules](https://ifloom.dev/docs/reference/glossary#rules), and content calls it by name with `game/` in front. A [plugin](https://ifloom.dev/docs/how-to/write-a-plugin) is the better home when the system needs state of its own or more than one game uses it. ## Put the rules in src/rules.ts [#put-the-rules-in-srcrulests] Write the game's code as a [`GameRules`](https://ifloom.dev/docs/reference/rules#gamerules) object in `src/rules.ts`, and pass it on the base you give `loadGame`: ```ts import { loadGame, type GameRules } from '@ifloom/engine' import { defineGame } from '@ifloom/cli/game' import { stats } from './world/stats.ts' import { cafe } from './story/cafe.ts' export const rules: GameRules = { conditions: { marketDay: (state) => state.turn % 7 === 5 }, } export default defineGame({ build: ({ unlocked }) => loadGame([stats, cafe], { id: 'small-town', title: 'Small Town', rules }, { packs: unlocked }), }) ``` In a real game the rules sit in their own file, and `src/game.ts` imports them. Each step below adds a table to the same object. ## Write a condition [#write-a-condition] Add a function to `conditions` that returns true or false. It gets the state, the arguments content wrote as `args`, and a [context](https://ifloom.dev/docs/reference/custom#customcontext): ```ts import type { Block, GameRules } from '@ifloom/engine' export const rules: GameRules = { conditions: { visitedAtLeast: (state, args) => (state.seen['ava.hi']?.n ?? 0) >= Number(args.times ?? 1), }, } const body: Block[] = [{ text: '"The usual?" Ava is already reaching for a cup.', when: { 'game/visitedAtLeast': { times: 3 } } }] ``` Content calls it anywhere a [condition](https://ifloom.dev/docs/reference/conditions) goes, such as a block's `when`, a choice's `blocked` or a lock. A call that takes no arguments is written `true`, as in `{ 'game/marketDay': true }`. ## Write a macro [#write-a-macro] A [macro](https://ifloom.dev/docs/reference/glossary#macro) is an effect that stands for other effects. Return the effects from the function, and the engine applies them where the macro stands: ```ts import type { Effect, GameRules } from '@ifloom/engine' export const rules: GameRules = { macros: { leaveTip: (state, args) => [{ stat: 'coins', by: -Number(args.by ?? 1) }, { stat: 'charm', by: 1 }], }, } const effects: Effect[] = [{ 'game/leaveTip': { by: 2 } }, { scene: null }] ``` Prefer a macro to an effect. A button's price, a plugin's guard and a lock see the effects it returns before the button is pressed, so the player sees `2c` on the tip. A macro may return a plugin's effect or another macro, and the context's `roll(max, name)` draws a seeded number for one that varies. ## Write an effect [#write-an-effect] An effect returns the next state itself. Use one when the change isn't a list of effects, such as writing the game's own state: ```ts import type { GameRules } from '@ifloom/engine' type Diary = { entries: string[] } export const rules: GameRules<Diary> = { start: () => ({ entries: [] }), effects: { keepDiary: (_state, args, { slice, set }) => set({ entries: [...slice.entries, String(args.text ?? '')] }), }, } ``` Content writes `{ 'game/keepDiary': { text: 'Met Ava at the café.' } }`. Prices, guards and locks can't see inside an effect, so keep to macros where you can. [Run code at the end of a turn](https://ifloom.dev/docs/how-to/run-code-at-the-end-of-a-turn#keep-state-of-your-own) has more on `start`, `slice` and `set`. ## Write a value for prose [#write-a-value-for-prose] A value is a number or a word that prose prints. Add it to `values`: ```ts import type { GameRules } from '@ifloom/engine' export const rules: GameRules = { values: { breadPrice: (state) => (state.kv.marketDay ? 4 : 5), catName: (state) => (typeof state.kv.catName === 'string' ? state.kv.catName : 'The cat'), }, } ``` Prose prints it with no prefix, `A loaf is {{breadPrice}}c today.`, with any arguments as `key=value` after the name. A stat's `max` or an app's badge names it as `{ value: 'game/breadPrice' }`. ## Type the calls [#type-the-calls] Declare what each call takes beside the rules, so content written in TypeScript is checked against it. Add each to the engine's registries: ```ts declare module '@ifloom/engine' { interface ConditionRegistry { 'game/visitedAtLeast': { times?: number } } interface EffectRegistry { 'game/leaveTip': { by?: number } | true 'game/keepDiary': { text: string } } } ``` `{ 'game/leaveTip': { bye: 2 } }` then fails to compile. A call you don't declare still works, and takes any arguments. ## Ask them from code [#ask-them-from-code] A test or a tool asks your functions through the engine, as content does. [`holds`](https://ifloom.dev/docs/reference/conditions#holds) asks a condition, [`amountOf`](https://ifloom.dev/docs/reference/amounts#amountof) a value, and [`applyEffects`](https://ifloom.dev/docs/reference/effects#applyeffects) runs effects: ```ts given import { amountOf, applyEffects, holds } from '@ifloom/engine' holds(state, game, { 'game/visitedAtLeast': { times: 3 } }) // false on a new game amountOf(state, game, { value: 'game/breadPrice' }) // 5 applyEffects(state, game, [{ 'game/leaveTip': { by: 2 } }]).stats.coins ``` ## Check it worked [#check-it-worked] Run `npm run check`. It reports a call to a name the rules don't have, where content writes it: ```text content · scene ava.hi · no game condition named "game/visitedAtleast" ``` A name content writes without `game/` is reported with the fix, and a name in both `effects` and `macros` is reported as both. In play, a condition nobody declares is false and an effect nobody declares does nothing, so a broken call hides content rather than crashing. For more, see: - [Calls by name](https://ifloom.dev/docs/reference/custom), with [`conditions`](https://ifloom.dev/docs/reference/custom#conditions), [`macros`](https://ifloom.dev/docs/reference/custom#macros), [`effects`](https://ifloom.dev/docs/reference/custom#effects) and [`values`](https://ifloom.dev/docs/reference/custom#values). - [Rules](https://ifloom.dev/docs/reference/rules) and the [registries](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry). - [Content and packs](https://ifloom.dev/docs/explanation/content-and-packs#rules-are-the-games-code), on why the game's code stays out of content.