Tutorials
Dialogue player
OSF is headless: it describes the story, and your game decides how to show it. In this tutorial you build a dialogue player that runs in the terminal. It is an example implementation, written in JavaScript so it fits on one page, and every step maps directly to C#, GDScript or C++.
It plays the my-story-json/ folder that osf convert wrote in Your first project. osf play does the same in the terminal, so you can compare the two.
Workflow
- Write the story in
.osfand runosf convert. - Your game loads the JSON resources and indexes them by
Kind.id, the same form references use (Character.guard,Dialogue.intro). - The player walks the nodes, from the dialogue’s
startNodethrough eachnext, until a node or option has none.
How a dialogue branches
Every dialogue is made of nodes and options, connected by next:
- Story to Dialogue: the Story’s
startis the first dialogue. Without it, play starts at the first dialogue in file order. - Dialogue to Node: the dialogue’s
startNode. - Node to Node, or Option to Node:
nextwith a node id. - Node or Option to another Dialogue:
next: Dialogue.<id>, which starts at that dialogue’sstartNode. Variables keep their values. - A
nextcan also be a list of branches, each with a targettoand its ownrequires: the first branch whose conditions are met is followed. - Node or Option back to a node’s options:
next: <node>.optionsoffers that node’s options again, without its line or itsset. This is how a question hub returns to its questions. - No
next, or no branch that matches: the play ends.
Variables add state. Each starts at its default. A node’s set is applied when the node is entered, an option’s set when it is chosen; a set either gives a new value or adds to or subtracts from a number. An option is shown only when its requires are met: every condition, or every condition of one of its alternatives. A condition can also check the play history, such as whether a node was played or an option selected. The full rules are in Playing a dialogue.
The player
The player reads the JSON resources with Node’s standard library, so it needs no packages.
// player.mjs: plays an OSF story in the terminal.
// Usage: node player.mjs <folder written by osf convert>
import { readFileSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
import { createInterface } from 'node:readline/promises'
// 1. Load every resource and index it by "Kind.id".
function load(dir, out = {}) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name)
if (entry.isDirectory()) load(path, out)
else if (entry.name.endsWith('.json')) {
const { kind, data } = JSON.parse(readFileSync(path, 'utf8'))
if (data.id) out[`${kind}.${data.id}`] = data
}
}
return out
}
const resources = load(process.argv[2] ?? 'story-json')
const story = Object.entries(resources).find(([key]) => key.startsWith('Story.'))[1]
// 2. Story state: every Variable starts at its default.
const state = {}
const types = {}
for (const [key, data] of Object.entries(resources)) {
if (key.startsWith('Variable.')) {
state[data.id] = data.default
types[data.id] = data.type
}
}
// A value in set is a new value, or { operation: add | subtract, value }.
// An unsignedNumber never goes below 0.
function apply(sets = {}) {
for (const [id, v] of Object.entries(sets)) {
let next = v
if (typeof v === 'object') next = state[id] + (v.operation === 'add' ? v.value : -v.value)
state[id] = types[id] === 'unsignedNumber' ? Math.max(0, next) : next
}
}
// Play history: nodes entered and options chosen, as "dialogue.node" and
// "dialogue.node.option".
const played = new Set()
const selected = new Set()
// <node>.stateData.played or <node>.options.<option>.selected, optionally after
// Dialogue.<id>., is true once that node was entered or that option chosen.
function history(key, dialogueId) {
const parts = key.startsWith('Dialogue.') ? key.split('.').slice(1) : [dialogueId, ...key.split('.')]
const [dlg, node, kind, option] = parts
return kind === 'stateData' ? played.has(`${dlg}.${node}`) : selected.has(`${dlg}.${node}.${option}`)
}
// A condition holds when the value is equal, or { operator, value } is true.
const compare = { '==': (a, b) => a === b, '!=': (a, b) => a !== b, '<': (a, b) => a < b, '<=': (a, b) => a <= b, '>': (a, b) => a > b, '>=': (a, b) => a >= b }
function holds(id, v, dialogueId) {
const value = id.includes('.') ? history(id, dialogueId) : state[id]
return typeof v === 'object' ? compare[v.operator](value, v.value) : value === v
}
// requires is a map whose entries must all hold, or the full form:
// { all: [{ variable, operator, value }] } or { any: [{ all: [...] }, ...] }.
function met(requires = {}, dialogueId) {
if (Array.isArray(requires.any)) return requires.any.some((group) => met(group, dialogueId))
if (Array.isArray(requires.all)) return requires.all.every((c) => holds(c.variable, c, dialogueId))
return Object.entries(requires).every(([id, v]) => holds(id, v, dialogueId))
}
// next is a target, or a list of { to, requires } branches: the first that is met wins.
const follow = (next, dialogueId) =>
Array.isArray(next) ? next.find((b) => met(b.requires, dialogueId))?.to : next
// 3. Fill in {{ Kind.id.field }} references. The field defaults to name;
// variables are read from the current state.
const fill = (text) =>
text.replace(/(?<!\\)\{\{\s*(\w+)\.([\w-]+)(?:\.(\w+))?\s*\}\}/g, (_, kind, id, field = 'name') => {
if (kind === 'Variable') return String(state[id])
const data = resources[`${kind}.${id}`]
return data[field] ?? data.id // a Dialogue without a name shows its id
}).replace(/\\\{\{/g, '{{')
// 4. Walk the nodes, from the Story's start (else the first dialogue).
const rl = createInterface({ input: process.stdin, output: process.stdout })
let dialogue = resources[story.start] ?? Object.entries(resources).find(([key]) => key.startsWith('Dialogue.'))[1]
let nodeId = dialogue.startNode
let again = false // after next: <node>.options, offer the options without the line or set
while (nodeId) {
const node = dialogue.nodes[nodeId]
if (!again) {
played.add(`${dialogue.id}.${nodeId}`)
apply(node.set)
const { speaker, title, text } = node.content
const name = title ?? (speaker ? resources[speaker].name : null)
const line = fill(text).trimEnd()
console.log(name ? `${fill(name)}: ${line}` : line)
}
again = false
let next = node.next
if (node.options) {
const options = Object.entries(node.options).filter(([, o]) => met(o.requires, dialogue.id))
if (!options.length) break // every option is hidden: a dead end
options.forEach(([, o], i) => console.log(` ${i + 1}. ${fill(o.content.text)}`))
const [optionId, choice] = options[Number(await rl.question('> ')) - 1] ?? options[0]
selected.add(`${dialogue.id}.${nodeId}.${optionId}`)
apply(choice.set)
next = choice.next
}
next = follow(next, dialogue.id)
// next is a node in this dialogue, <node>.options to offer its options again,
// Dialogue.<id> for another dialogue, or missing (the end).
if (next?.startsWith('Dialogue.')) {
dialogue = resources[next]
nodeId = dialogue.startNode
} else if (next?.endsWith('.options')) {
nodeId = next.slice(0, -'.options'.length)
again = true
} else {
nodeId = next
}
}
rl.close()Load the resources
Step 1 reads every .json file in the folder and indexes its data by Kind.id. Because references use the same form, resources[node.content.speaker] is the speaker’s Character and resources[story.start] is the first Dialogue.
Keep the state
Step 2 sets every variable to its default. apply handles both forms of set: a plain value, or { operation, value } that adds or subtracts, keeping an unsignedNumber at 0 or more. holds checks one condition: a plain value that must be equal, or { operator, value } that compares. met checks a whole requires: the short map, whose entries must all hold, or the full form, where all is a list of { variable, operator, value } conditions that must all hold and any is a list of all groups of which one is enough. holds also answers the history conditions, <node>.stateData.played and <node>.options.<option>.selected, from two sets the player loop fills in. follow picks the target of a next, whether it is a plain id or a list of branches.
Fill in text references
Text can contain references such as {{ Character.guard }} or {{ Document.old_lighthouse }}. Step 3 replaces them with the resource’s text, or a variable’s current value.
Walk the nodes
Step 4 is the whole player loop: mark the node played, apply its set, print the speaker and text, show the options whose requires are met, mark the chosen option selected and apply its set, and follow next. For next: <node>.options the loop goes back to that node with again set, so it skips the line and the set and only offers the options. A node whose options are all hidden is a dead end, and the play stops.
Run it
$ node player.mjs my-story-json
Guard: Halt! Who goes there?
1. A friend.
2. Nobody. Bye.
> 1
Guard: Then take this key, Guard trusts you.From here, a real game replaces console.log with its dialogue UI, and picks the language from the Locale resources.