Documentation
¶
Overview ¶
Package dialogue runs branching conversations written as Yarn Spinner (.yarn) scripts: ParseYarn reads a Script of titled nodes, and a Runner steps through it line by line and choice by choice, evaluates its variables and conditions, and hands each <<command>> to Options.OnCommand or publishes it as an Event on a flow.Bus.
Nothing in dialogue reads the wall clock, spawns goroutines or keeps package-level state, and a Runner's variables and visit counts save and load as a State, so a conversation replays the same under nsgotest and survives a save game.
Index ¶
- Constants
- Variables
- type Choice
- type Event
- type Line
- type Options
- type Runner
- func (r *Runner) Choose(optionIndex int) (Step, error)
- func (r *Runner) Continue() (Step, error)
- func (r *Runner) CurrentNode() string
- func (r *Runner) LoadState(state State)
- func (r *Runner) SetVar(name string, val any)
- func (r *Runner) Start(node string) (Step, error)
- func (r *Runner) State() State
- func (r *Runner) Var(name string) (any, bool)
- func (r *Runner) Vars() map[string]any
- func (r *Runner) Visited(node string) int
- type Script
- type State
- type Step
- type StepKind
- type StringResolver
Examples ¶
Constants ¶
const DefaultMaxStepsPerContinue = 1024
DefaultMaxStepsPerContinue is the default upper bound on internal statements (assignments, branches, jumps, commands) executed in a single Start, Continue, or Choose call before returning ErrStepLimitExceeded.
Variables ¶
var ( // ErrNilScript is returned when starting a Runner with a nil script. ErrNilScript = errors.New("dialogue: nil script") // ErrUnknownNode is returned when starting or jumping to a node not present in the script. ErrUnknownNode = errors.New("dialogue: unknown node") // ErrInvalidChoice is returned when Choose receives an out-of-range option index. ErrInvalidChoice = errors.New("dialogue: invalid choice index") ErrChoiceUnavailable = errors.New("dialogue: choice is unavailable") // ErrNoPendingChoice is returned when Choose is called while no choice menu is active. ErrNoPendingChoice = errors.New("dialogue: no pending choices") // ErrChoiceRequired is returned when Continue is called while a choice menu is awaiting Choose. ErrChoiceRequired = errors.New("dialogue: waiting for Choose") // ErrStepLimitExceeded is returned when execution exceeds MaxStepsPerContinue without yielding a line, choice, or end. ErrStepLimitExceeded = errors.New("dialogue: step limit exceeded") )
Functions ¶
This section is empty.
Types ¶
type Event ¶
Event is published onto a flow.Bus (via flow.Publish) and/or passed to Options.OnCommand whenever a script executes a game command such as <<give_item key 1>> or <<play_sfx chime>>.
type Options ¶
type Options struct {
// Bus, if non-nil, receives an Event via flow.Publish for every game command.
Bus *flow.Bus
// OnCommand, if non-nil, is invoked for every game command after Bus delivery.
OnCommand func(Event)
// StringResolver, if non-nil, resolves localized text for dialogue lines and choices.
StringResolver StringResolver
// MaxStepsPerContinue caps internal statements per Start, Continue, or Choose call
// to guard against infinite <<jump>> loops. Defaults to DefaultMaxStepsPerContinue.
MaxStepsPerContinue int
}
Options configures a Runner.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner executes a parsed Script step by step.
It maintains variables, node visit counts, and the active execution stack without goroutines or global state. Game commands execute synchronously and publish typed Event values on Options.Bus when configured.
Example ¶
A Runner steps through a script parsed by ParseYarn, returning lines and choices and running game commands.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/dialogue"
)
const shop = `title: Shop
---
<<declare $gold = 15>>
Merchant: You have {$gold} gold.
-> Buy a potion (10 gold) <<if $gold >= 10>>
<<set $gold -= 10>>
<<give_item potion 1>>
Merchant: Here you go.
-> Buy a sword (50 gold) <<if $gold >= 50>>
Merchant: A fine choice.
-> Leave
===
`
// A Runner steps through a script parsed by ParseYarn, returning lines and choices and running game commands.
func main() {
script, err := dialogue.ParseYarn(shop)
if err != nil {
fmt.Println(err)
return
}
r := dialogue.NewRunner(script, dialogue.Options{
OnCommand: func(e dialogue.Event) { fmt.Println("command:", e.Command, e.Args) },
})
step, _ := r.Start("Shop")
fmt.Printf("%s: %s\n", step.Line.Speaker, step.Line.Text)
step, _ = r.Continue()
for _, c := range step.Choices {
fmt.Println(c.Index, c.Text, c.Available)
}
step, _ = r.Choose(0)
fmt.Println(step.Kind, step.Line.Text)
gold, _ := r.Var("gold")
fmt.Println("gold:", gold)
}
Output: Merchant: You have 15 gold. 0 Buy a potion (10 gold) true 1 Buy a sword (50 gold) false 2 Leave true command: give_item [potion 1] line Here you go. gold: 5
func (*Runner) Choose ¶
Choose selects optionIndex from the active StepChoices step and advances to the next line, choice menu, or end of dialogue.
func (*Runner) Continue ¶
Continue advances an active dialogue to the next line, choice menu, or end. Calling Continue while a choice menu is awaiting Choose returns ErrChoiceRequired.
func (*Runner) CurrentNode ¶
CurrentNode returns the title of the currently executing node, or "" when ended.
func (*Runner) LoadState ¶
LoadState restores variables and visit counts from a previously saved State.
func (*Runner) SetVar ¶
SetVar sets a dialogue variable. A leading '$' is optional and normalized away. Numeric Go types are normalized to float64 to match Yarn expression semantics.
func (*Runner) Start ¶
Start begins executing the script at the named node and advances until the first line, choice menu, or end of dialogue.
func (*Runner) State ¶
State returns a serializable snapshot of the runner's variables and visit counts.
func (*Runner) Var ¶
Var returns the current value of name (leading '$' optional) and whether it is set.
type Script ¶
type Script struct {
// contains filtered or unexported fields
}
Script is a parsed Yarn Spinner script containing one or more named nodes. A parsed Script is immutable and safe to share across multiple Runners.
func ParseYarn ¶
ParseYarn parses Yarn Spinner (.yarn) source text into a reusable Script.
Supported syntax:
- Node headers (title: ..., custom key: value) delimited by --- and ===
- Comments starting with //
- Dialogue lines: [Speaker: ]Text [#line:id] [#tag ...] with {expr} interpolation
- Branching choices: -> Option text [<<if cond>>] [#line:id] [#tag ...] with indented bodies
- Conditionals: <<if expr>> / <<elseif expr>> / <<else>> / <<endif>>
- Variables: <<set $var = expr>> (plus to, +=, -=, *=, /=) and <<declare $var = expr>>
- Control flow: <<jump NodeTitle>> and <<stop>>
- Game commands: <<command arg1 "quoted arg" $var {$expr}>>
Its errors are *loaderr.Error values that give the line of the problem and how to fix it; a caller that read src from a file names it with loaderr.WithFile.
func (*Script) NodeHeaders ¶
NodeHeaders returns a copy of the header metadata declared on the named node, or nil if the node does not exist.
type State ¶
type State struct {
Vars map[string]any `json:"vars,omitempty"`
Visited map[string]int `json:"visited,omitempty"`
}
State is a JSON-serializable snapshot of a Runner's variables and node visit counts for save/load persistence.
type StepKind ¶
type StepKind int
StepKind identifies what a Step produced.
const ( // StepEnded indicates the dialogue reached the end of a node, hit <<stop>>, or has not started. StepEnded StepKind = iota // StepLine indicates a single spoken or narrated line is ready to display. StepLine // StepChoices indicates one or more player choices are awaiting Choose. StepChoices )
type StringResolver ¶
StringResolver resolves localized text for a dialogue line or choice.
It receives the #line:<id> identifier (empty if untagged), the raw source text from the Yarn script as fallback, and a snapshot of the runner's variables. Any remaining {expr} placeholders in the returned string are interpolated by the runner using its current variables.