API 參考取自原始碼中的 Go 文件註解,以英文撰寫。
package flow
import "github.com/nsgo-dev/game/pkg/flow"概覽
Package flow holds gameplay flow primitives driven by a game.Loop's fixed steps: game-clock timers, finite and hierarchical state machines, step sequences, a typed event bus and a branching dialogue runtime.
Nothing in flow reads the wall clock, spawns goroutines or keeps package-level state, so every piece pauses with the loop, stays deterministic under nsgotest and isolates cleanly per scene or world.
索引
- 常數
- 變數
- func BindBus[E any, S comparable](m *HSM[S], b *Bus) (unsubscribe func())
- func Enqueue[T any](b *Bus, event T)
- func FormatMachineInspection(snap MachineInspection) string
- func OnAnyEvent[E any, S comparable](m *HSM[S], to S, guard func(E) bool)
- func OnEvent[E any, S comparable](m *HSM[S], from, to S, guard func(E) bool)
- func Publish[T any](b *Bus, event T)
- func Subscribe[T any](b *Bus, fn func(T)) (unsubscribe func())
- func SubscribeOnce[T any](b *Bus, fn func(T)) (unsubscribe func())
- type Bus
- type DialogueChoice
- type DialogueEvent
- type DialogueLine
- type DialogueOptions
- type DialogueRunner
- func NewDialogueRunner(script *DialogueScript, opts DialogueOptions) *DialogueRunner
- func (r *DialogueRunner) Choose(optionIndex int) (DialogueStep, error)
- func (r *DialogueRunner) Continue() (DialogueStep, error)
- func (r *DialogueRunner) CurrentNode() string
- func (r *DialogueRunner) LoadState(state DialogueState)
- func (r *DialogueRunner) SetVar(name string, val any)
- func (r *DialogueRunner) Start(node string) (DialogueStep, error)
- func (r *DialogueRunner) State() DialogueState
- func (r *DialogueRunner) Var(name string) (any, bool)
- func (r *DialogueRunner) Vars() map[string]any
- func (r *DialogueRunner) Visited(node string) int
- type DialogueScript
- type DialogueState
- type DialogueStep
- type HSM
- func NewHSM[S comparable](initial S) *HSM[S]
- func (m *HSM[S]) AddAnyEventTransition(to S, event any, guard ...func() bool)
- func (m *HSM[S]) AddAnyTransition(to S, when func() bool)
- func (m *HSM[S]) AddChild(parent S, child *HSM[S])
- func (m *HSM[S]) AddEventTransition(from, to S, event any, guard ...func() bool)
- func (m *HSM[S]) AddState(id S, state State)
- func (m *HSM[S]) AddTransition(from, to S, when func() bool)
- func (m *HSM[S]) ClearHistory()
- func (m *HSM[S]) Current() []S
- func (m *HSM[S]) History() bool
- func (m *HSM[S]) In(state S) bool
- func (m *HSM[S]) Leaf() S
- func (m *HSM[S]) Previous() S
- func (m *HSM[S]) Send(event any)
- func (m *HSM[S]) SetHistory(enabled bool)
- func (m *HSM[S]) SetState(to S)
- func (m *HSM[S]) Start()
- func (m *HSM[S]) TimeIn(state S) time.Duration
- func (m *HSM[S]) TimeInState() time.Duration
- func (m *HSM[S]) Update(dt time.Duration)
- type Handle
- type Machine
- func NewMachine[S comparable](initial S) *Machine[S]
- func (m *Machine[S]) AddAnyTransition(to S, when func() bool)
- func (m *Machine[S]) AddNamedAnyTransition(name string, to S, when func() bool)
- func (m *Machine[S]) AddNamedTransition(name string, from, to S, when func() bool)
- func (m *Machine[S]) AddState(id S, state State)
- func (m *Machine[S]) AddTransition(from, to S, when func() bool)
- func (m *Machine[S]) ClearHistory()
- func (m *Machine[S]) Current() S
- func (m *Machine[S]) FormatState() string
- func (m *Machine[S]) History() []TransitionRecord[S]
- func (m *Machine[S]) HistoryInto(dst []TransitionRecord[S]) []TransitionRecord[S]
- func (m *Machine[S]) HistoryLimit() int
- func (m *Machine[S]) Inspect() MachineInspection
- func (m *Machine[S]) Previous() S
- func (m *Machine[S]) Restore(snap MachineSnapshot[S]) error
- func (m *Machine[S]) SetHistoryLimit(limit int)
- func (m *Machine[S]) SetState(to S)
- func (m *Machine[S]) Snapshot() MachineSnapshot[S]
- func (m *Machine[S]) Start()
- func (m *Machine[S]) Started() bool
- func (m *Machine[S]) Step() uint64
- func (m *Machine[S]) TimeInState() time.Duration
- func (m *Machine[S]) Update(dt time.Duration)
- type MachineInspection
- type MachineInspector
- type MachineSnapshot
- type Runner
- type State
- type Step
- func Do(fn func()) Step
- func Loop(makeStep func() Step) Step
- func Parallel(steps ...Step) Step
- func Race(steps ...Step) Step
- func Repeat(n int, makeStep func() Step) Step
- func Seq(steps ...Step) Step
- func Wait(d time.Duration) Step
- func WaitUntil(cond func() bool) Step
- func While(cond func() bool, update func(dt time.Duration)) Step
- type StepKind
- type StringResolver
- type Timer
- type Timers
- type TransitionRecord
- type TransitionSnapshot
常數
const DefaultHistoryLimit = 32DefaultHistoryLimit is the default maximum number of transitions retained by a Machine.
const DefaultMaxStepsPerContinue = 1024DefaultMaxStepsPerContinue is the default upper bound on internal statements (assignments, branches, jumps, commands) executed in a single Start, Continue, or Choose call before returning ErrStepLimitExceeded.
const MachineSnapshotVersion = 1MachineSnapshotVersion is the MachineSnapshot schema version written and read by Machine.Snapshot and Machine.Restore.
變數
var (
// ErrNilScript is returned when starting a DialogueRunner with a nil script.
ErrNilScript = errors.New("flow: nil dialogue script")
// ErrUnknownNode is returned when starting or jumping to a node not present in the script.
ErrUnknownNode = errors.New("flow: unknown dialogue node")
// ErrInvalidChoice is returned when Choose receives an out-of-range option index.
ErrInvalidChoice = errors.New("flow: invalid dialogue choice index")
// ErrChoiceUnavailable is returned when Choose selects an option whose <<if>> guard evaluated false.
// ErrNoPendingChoice is returned when Choose is called while no choice menu is active.
ErrNoPendingChoice = errors.New("flow: no pending dialogue choices")
// ErrChoiceRequired is returned when Continue is called while a choice menu is awaiting Choose.
ErrChoiceRequired = errors.New("flow: dialogue is waiting for Choose")
// ErrStepLimitExceeded is returned when execution exceeds MaxStepsPerContinue without yielding a line, choice, or end.
ErrStepLimitExceeded = errors.New("flow: dialogue step limit exceeded")
)var ErrInvalidSnapshot = errors.New("flow: invalid snapshot")ErrInvalidSnapshot reports a snapshot that Machine.Restore refuses because its version, recorded states, or timing do not match the target machine.
函式
func BindBus[E any, S comparable](m *HSM[S], b *Bus) (unsubscribe func())BindBus subscribes m to events of type E on b, forwarding each delivered event to m.Send in delivery order so it is processed on the next Update step. It returns an idempotent unsubscribe function.
func Enqueue[T any](b *Bus, event T)Enqueue buffers event on b to be delivered in FIFO order on the next Flush.
func FormatMachineInspection(snap MachineInspection) stringFormatMachineInspection renders snap in a deterministic canonical text format suitable for statedump Values and golden-file diffs across runs.
func OnAnyEvent[E any, S comparable](m *HSM[S], to S, guard func(E) bool)OnAnyEvent registers a typed wildcard event-triggered transition on m to to from any active state within m (when to is not already active). It matches any queued event of type E when guard is nil or guard(ev) returns true.
func OnEvent[E any, S comparable](m *HSM[S], from, to S, guard func(E) bool)OnEvent registers a typed event-triggered transition on m from from to to. It matches any queued event of type E (including events forwarded from a Bus via BindBus) when guard is nil or guard(ev) returns true.
func Publish[T any](b *Bus, event T)Publish synchronously delivers event to every current subscriber of type T on b in subscription order.
Subscribers added during dispatch do not receive the event in flight; subscribers removed during dispatch are skipped if they have not yet run.
func Subscribe[T any](b *Bus, fn func(T)) (unsubscribe func())Subscribe registers fn to receive events of type T published on b and returns an idempotent unsubscribe function. A nil fn is ignored.
func SubscribeOnce[T any](b *Bus, fn func(T)) (unsubscribe func())SubscribeOnce registers fn to receive the next event of type T published on b, then automatically unsubscribes it before invoking fn. It returns an idempotent unsubscribe function to cancel before it fires.
型別
type Bus struct {
// contains filtered or unexported fields
}Bus is a typed, zero-global-state event bus for communication between objects in a scene or world.
The zero value is ready to use. Handlers run in subscription order; unsubscribing or subscribing inside a handler never skips subsequent subscribers for the event in flight.
func (b *Bus) Clear()Clear removes all subscribers and discards all buffered events from b.
func (b *Bus) Flush()Flush delivers all events buffered by Enqueue in FIFO order, including any events enqueued by handlers during Flush.
type DialogueChoice struct {
Index int
Text string
LineID string
Available bool
Tags []string
}DialogueChoice holds one option presented at a StepChoices step.
type DialogueEvent struct {
Command string
Args []string
Node string
}DialogueEvent is published onto flow.Bus (via Publish) and/or passed to DialogueOptions.OnCommand whenever a script executes a game command such as <<give_item key 1>> or <<play_sfx chime>>.
type DialogueLine struct {
Speaker string
Text string
LineID string
Tags []string
}DialogueLine holds a resolved dialogue line produced by a DialogueRunner.
type DialogueOptions struct {
// Bus, if non-nil, receives a DialogueEvent via Publish for every game command.
Bus *Bus
// OnCommand, if non-nil, is invoked for every game command after Bus delivery.
OnCommand func(DialogueEvent)
// 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
}DialogueOptions configures a DialogueRunner.
type DialogueRunner struct {
// contains filtered or unexported fields
}DialogueRunner executes a parsed DialogueScript 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 DialogueEvent values on DialogueOptions.Bus when configured.
func NewDialogueRunner(script *DialogueScript, opts DialogueOptions) *DialogueRunnerNewDialogueRunner creates a runner for script with the given options.
func (r *DialogueRunner) Choose(optionIndex int) (DialogueStep, error)Choose selects optionIndex from the active StepChoices step and advances to the next line, choice menu, or end of dialogue.
func (r *DialogueRunner) Continue() (DialogueStep, error)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 (r *DialogueRunner) CurrentNode() stringCurrentNode returns the title of the currently executing node, or "" when ended.
func (r *DialogueRunner) LoadState(state DialogueState)LoadState restores variables and visit counts from a previously saved DialogueState.
func (r *DialogueRunner) SetVar(name string, val any)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 (r *DialogueRunner) Start(node string) (DialogueStep, error)Start begins executing the script at the named node and advances until the first line, choice menu, or end of dialogue.
func (r *DialogueRunner) State() DialogueStateState returns a serializable snapshot of the runner's variables and visit counts.
func (r *DialogueRunner) Var(name string) (any, bool)Var returns the current value of name (leading '$' optional) and whether it is set.
func (r *DialogueRunner) Vars() map[string]anyVars returns a shallow copy of all currently set dialogue variables (keys without leading '$').
func (r *DialogueRunner) Visited(node string) intVisited returns how many times the named node has been entered via Start or <<jump>>.
type DialogueScript struct {
// contains filtered or unexported fields
}DialogueScript is a parsed Yarn Spinner script containing one or more named nodes. A parsed DialogueScript is immutable and safe to share across multiple DialogueRunners.
func ParseYarn(src string) (*DialogueScript, error)ParseYarn parses Yarn Spinner (.yarn) source text into a reusable DialogueScript.
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 (s *DialogueScript) HasNode(title string) boolHasNode reports whether the script contains a node with the given title.
func (s *DialogueScript) NodeHeaders(title string) map[string]stringNodeHeaders returns a copy of the header metadata declared on the named node, or nil if the node does not exist.
func (s *DialogueScript) Nodes() []stringNodes returns the script's node titles in declaration order.
type DialogueState struct {
Vars map[string]any `json:"vars,omitempty"`
Visited map[string]int `json:"visited,omitempty"`
}DialogueState is a JSON-serializable snapshot of a DialogueRunner's variables and node visit counts for save/load persistence.
type DialogueStep struct {
Kind StepKind
Line DialogueLine
Choices []DialogueChoice
}DialogueStep is the result of Start, Continue, or Choose on a DialogueRunner.
type HSM[S comparable] struct {
// contains filtered or unexported fields
}HSM is a hierarchical finite state machine keyed by states of type S and stepped by Update on a game.Loop.
Any state may own a nested child *HSM[S] attached via AddChild, with its own initial state and optional shallow history (SetHistory). Enter callbacks run outside-in (parent before child), Exit callbacks run inside-out (child before parent), and transitions between branches exit up to the lowest common ancestor before entering down to the target leaf. Transitions declared on a parent apply while any descendant is active, and the innermost active state is checked first.
Event-triggered transitions (AddEventTransition, AddAnyEventTransition, OnEvent, OnAnyEvent) work alongside polled conditions (AddTransition, AddAnyTransition). Events sent through Send or forwarded from a Bus via BindBus are queued in FIFO send order and processed once per Update step.
func NewHSM[S comparable](initial S) *HSM[S]NewHSM returns a hierarchical state machine whose initial state is initial. Call Start to run initial Enter callbacks before the first Update, or let the first Update start it automatically.
func (m *HSM[S]) AddAnyEventTransition(to S, event any, guard ...func() bool)AddAnyEventTransition registers an event-triggered wildcard transition to to from any active state within m (when to is not already active). It fires when an event equal to event is processed and all non-nil guards return true. A nil event is ignored.
func (m *HSM[S]) AddAnyTransition(to S, when func() bool)AddAnyTransition registers a polled wildcard transition to to from any active state within m. Transitions are evaluated in declaration order during Update, and a wildcard transition does not re-enter to when it is already active.
func (m *HSM[S]) AddChild(parent S, child *HSM[S])AddChild attaches child as the nested state machine owned by state parent in m. Passing nil removes any child attached to parent. AddChild panics if attaching child would create a cycle or if child is already attached to a different parent machine.
func (m *HSM[S]) AddEventTransition(from, to S, event any, guard ...func() bool)AddEventTransition registers an event-triggered transition from from to to that fires when an event equal to event is processed and all non-nil guards return true. A nil event is ignored.
func (m *HSM[S]) AddState(id S, state State)AddState registers the Enter, Update and Exit callbacks for id, replacing any previously registered callbacks for id while preserving any attached child machine.
func (m *HSM[S]) AddTransition(from, to S, when func() bool)AddTransition registers a polled conditional transition from from to to. Transitions are evaluated in declaration order during Update, with innermost active states checked first.
func (m *HSM[S]) ClearHistory()ClearHistory forgets any recorded shallow history on m and all of its nested child machines.
func (m *HSM[S]) Current() []SCurrent returns the active state path from m down to the active leaf state. Before Start is called, Current returns the initial path from m to its initial leaf. For an attached child machine that is not currently active, Current returns nil.
func (m *HSM[S]) History() boolHistory reports whether shallow history is enabled on m.
func (m *HSM[S]) In(state S) boolIn reports whether state is currently active anywhere along m's active path.
func (m *HSM[S]) Leaf() SLeaf returns the innermost active leaf state reachable from m, or the zero value of S if m is an inactive child machine.
func (m *HSM[S]) Previous() SPrevious returns the state before the last transition at m's level, or the zero value of S before any transition.
func (m *HSM[S]) Send(event any)Send queues event onto the root machine in FIFO send order to be processed on the next Update step. Events sent while Update is processing transitions or callbacks are deferred to the following step. A nil event is ignored.
func (m *HSM[S]) SetHistory(enabled bool)SetHistory enables or disables shallow history on m. When enabled, re-entering m as a child machine resumes its last active direct child state instead of its initial state.
func (m *HSM[S]) SetState(to S)SetState immediately switches to to, exiting up to the lowest common ancestor (inside-out) and entering down to the target leaf (outside-in). Switching to the already-active leaf state after Start is a no-op.
func (m *HSM[S]) Start()Start enters the initial state path from root to leaf if the machine has not yet started. Subsequent calls are no-ops.
func (m *HSM[S]) TimeIn(state S) time.DurationTimeIn returns the game time spent in state if state is currently active along m's active path, or 0 otherwise.
func (m *HSM[S]) TimeInState() time.DurationTimeInState returns the game time spent in m's current state since entering it.
func (m *HSM[S]) Update(dt time.Duration)Update advances the root machine by dt:
- Starts the machine if needed.
- Processes queued events (sent before this Update via Send or BindBus) once in FIFO send order, checking active states from innermost to outermost.
- If no event triggered a transition, evaluates polled transitions from innermost to outermost in declaration order, taking at most one.
- Advances TimeInState for every active state (when dt > 0) and runs each active state's Update callback from outside in.
Calling Update on an attached child machine is a no-op; drive the hierarchy from the root machine.
type Handle struct {
// contains filtered or unexported fields
}Handle represents a running Step started on a Runner.
func (h *Handle) Cancel()Cancel stops the step so it will not run further. Cancelling a nil or finished Handle is a no-op.
func (h *Handle) Done() boolDone reports whether the step has finished or been cancelled.
type Machine[S comparable] struct {
// contains filtered or unexported fields
}Machine is a finite state machine keyed by states of type S and stepped by Update on a game.Loop.
func NewMachine[S comparable](initial S) *Machine[S]NewMachine returns a state machine whose initial state is initial. Call Start to run the initial state's Enter callback before the first Update, or let the first Update start it automatically.
func (m *Machine[S]) AddAnyTransition(to S, when func() bool)AddAnyTransition registers a conditional transition to to from any other state. Transitions are checked in declaration order during Update, and a wildcard transition does not re-enter to when already in it.
func (m *Machine[S]) AddNamedAnyTransition(name string, to S, when func() bool)AddNamedAnyTransition registers a labeled wildcard transition to to from any other state. When name is non-empty it is recorded in TransitionRecord.Transition whenever the transition fires; when empty, a default "*->to" label is used.
func (m *Machine[S]) AddNamedTransition(name string, from, to S, when func() bool)AddNamedTransition registers a labeled conditional transition from from to to. When name is non-empty it is recorded in TransitionRecord.Transition whenever the transition fires; when empty, a default "from->to" label is used.
func (m *Machine[S]) AddState(id S, state State)AddState registers the callbacks for id, replacing any previously registered for id.
func (m *Machine[S]) AddTransition(from, to S, when func() bool)AddTransition registers a conditional transition from from to to. Transitions are checked in declaration order during Update.
func (m *Machine[S]) ClearHistory()ClearHistory discards all recorded transitions without changing HistoryLimit or Step.
func (m *Machine[S]) Current() SCurrent returns the machine's current state.
func (m *Machine[S]) FormatState() stringFormatState returns a deterministic, human-readable text summary of m's current state and transition history suitable for statedump Values and diffing AI decisions across runs.
func (m *Machine[S]) History() []TransitionRecord[S]History returns m's retained transitions in chronological order (oldest to newest).
func (m *Machine[S]) HistoryInto(dst []TransitionRecord[S]) []TransitionRecord[S]HistoryInto appends m's retained transitions in chronological order (oldest to newest) into dst[:0], performing zero heap allocations when cap(dst) is sufficient.
func (m *Machine[S]) HistoryLimit() intHistoryLimit returns the maximum number of transitions retained in m's ring buffer. Before SetHistoryLimit is called, HistoryLimit returns DefaultHistoryLimit.
func (m *Machine[S]) Inspect() MachineInspectionInspect returns a type-erased read-only snapshot of m's current state and transition history.
func (m *Machine[S]) Previous() SPrevious returns the state before the last transition, or the zero value of S before any transition.
func (m *Machine[S]) Restore(snap MachineSnapshot[S]) errorRestore validates snap against m's known states and replaces m's runtime state without calling any Exit or Enter callbacks.
Restore refuses snapshots with an unsupported version, unknown Current or non-zero Previous state, negative TimeInState, or non-zero TimeInState/Previous on an unstarted machine, leaving m unchanged and returning an error wrapping ErrInvalidSnapshot.
func (m *Machine[S]) SetHistoryLimit(limit int)SetHistoryLimit sets the maximum number of recent transitions retained by m. Passing 0 or a negative value disables transition history and clears any retained entries. Shrinking the limit preserves the most recent transitions in chronological order.
func (m *Machine[S]) SetState(to S)SetState immediately switches to to, running the current state's Exit and to's Enter callbacks. Switching to the current state after Start is a no-op.
func (m *Machine[S]) Snapshot() MachineSnapshot[S]Snapshot returns m's runtime state as plain data. Restoring it into a fresh Machine with the same states and transitions resumes from the exact state and TimeInState without running Exit or Enter hooks.
func (m *Machine[S]) Start()Start runs the initial state's Enter callback if the machine has not yet started. Subsequent calls are no-ops.
func (m *Machine[S]) Started() boolStarted reports whether the machine has been started (either via Machine.Start, Machine.SetState, Machine.Update, or Machine.Restore).
func (m *Machine[S]) Step() uint64Step returns the number of Update steps executed by m.
func (m *Machine[S]) TimeInState() time.DurationTimeInState returns the game time spent in the current state since entering it.
func (m *Machine[S]) Update(dt time.Duration)Update advances the machine by dt: it starts the machine if needed, increments Step, evaluates transitions in declaration order (taking at most one), adds dt to TimeInState and runs the current state's Update callback.
type MachineInspection struct {
// Current is the formatted current state.
Current string
// Previous is the formatted previous state (empty when HasPrevious is false).
Previous string
// HasPrevious reports whether at least one transition has occurred.
HasPrevious bool
// Step is the total number of Update steps executed.
Step uint64
// TimeInState is the elapsed game time spent in Current.
TimeInState time.Duration
// History lists the retained recent transitions in chronological order (oldest to newest).
History []TransitionSnapshot
}MachineInspection is a type-erased, read-only snapshot of a Machine's current state and transition history.
type MachineInspector interface {
// Inspect returns a type-erased read-only snapshot of the machine's current state and transition history.
Inspect() MachineInspection
// FormatState returns a deterministic text summary of the machine's current state and transition history.
FormatState() string
}MachineInspector is implemented by every *Machine[S] so tools and debug overlays can inspect any Machine regardless of its state type parameter S.
type MachineSnapshot[S comparable] struct {
// Version is MachineSnapshotVersion.
Version int `json:"version" yaml:"version"`
// Current is the machine's active state (or its initial state if not yet started).
Current S `json:"current" yaml:"current"`
// Previous is the state before the last transition, or the zero value of S before any transition.
Previous S `json:"previous,omitempty" yaml:"previous,omitempty"`
// TimeInState is the game time spent in Current since entering it.
TimeInState time.Duration `json:"timeInState,omitempty" yaml:"timeInState,omitempty"`
// Started reports whether the machine has entered its initial state.
Started bool `json:"started,omitempty" yaml:"started,omitempty"`
}MachineSnapshot holds a Machine's runtime state as plain data that marshals deterministically to YAML and JSON, for save slots, rollback netcode, and state dumps.
type Runner struct {
// contains filtered or unexported fields
}Runner drives one or more active Steps on each game step. The zero value is ready to use.
func (r *Runner) Start(step Step) *HandleStart schedules step to run on subsequent Update calls and returns a Handle to observe or cancel it. A nil step returns an already-done Handle.
func (r *Runner) Update(dt time.Duration)Update advances all active steps by dt in start order. Steps started from inside a callback begin on the next Update step.
type State struct {
// Enter runs once when the machine enters the state.
Enter func()
// Update runs on each Machine.Update step while the machine is in the state.
Update func(dt time.Duration)
// Exit runs once when the machine leaves the state.
Exit func()
}State holds the optional callbacks for one state of a Machine.
type Step interface {
Update(dt time.Duration) (leftover time.Duration, done bool)
Cancel()
}Step is one unit of work in a sequence, advanced deterministically by Update without goroutines.
Update advances the step by up to dt and returns any unused time along with whether the step has finished, so a Seq can pass leftover time to the next step on the same tick. Cancel stops an unfinished step cleanly when its Handle or an enclosing Race cancels it.
func Do(fn func()) StepDo returns a Step that calls fn once and completes immediately, passing all remaining dt to the next step.
func Loop(makeStep func() Step) StepLoop returns a Step that repeats the Step returned by makeStep until cancelled. A zero-duration body runs once per Update step rather than spinning indefinitely.
func Parallel(steps ...Step) StepParallel returns a Step that updates every branch on each step until all branches have completed.
func Race(steps ...Step) StepRace returns a Step that updates branches in order until the first branch completes, then cancels the remaining branches.
func Repeat(n int, makeStep func() Step) StepRepeat returns a Step that runs the Step returned by makeStep n times in sequence. A non-positive n or nil makeStep completes immediately.
func Seq(steps ...Step) StepSeq returns a Step that runs steps in order, carrying any leftover dt from a completed step into the next one on the same tick. Nil entries are skipped.
func Wait(d time.Duration) StepWait returns a Step that completes after d of game time has elapsed.
func WaitUntil(cond func() bool) StepWaitUntil returns a Step that completes on the first Update where cond returns true (or immediately if cond is nil).
func While(cond func() bool, update func(dt time.Duration)) StepWhile returns a Step that runs update(dt) on each step while cond returns true, completing as soon as cond returns false.
type StepKind intStepKind identifies what a DialogueStep 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
)func (k StepKind) String() stringString returns a human-readable name for the StepKind.
type StringResolver func(lineID, fallback string, vars map[string]any) stringStringResolver 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.
type Timer struct {
// contains filtered or unexported fields
}Timer is a handle to a callback scheduled on a Timers scheduler.
func (t *Timer) Active() boolActive reports whether the timer is still scheduled to fire.
func (t *Timer) Cancel()Cancel stops the timer so it will not fire again. Cancelling a nil or inactive timer is a no-op.
func (t *Timer) Remaining() time.DurationRemaining returns the game time left before the timer next fires, or 0 when inactive.
type Timers struct {
// Paused stops Update from advancing timers when true.
Paused bool
// contains filtered or unexported fields
}Timers schedules one-shot and repeating callbacks on the game clock rather than the wall clock.
Call Update on each fixed step of a game.Loop; timers pause automatically while the loop is paused or while Paused is true. The zero value is ready to use.
func (ts *Timers) After(d time.Duration, fn func()) *TimerAfter schedules fn to run once after d of game time has elapsed. A non-positive d fires on the next Update step.
func (ts *Timers) Every(d time.Duration, fn func()) *TimerEvery schedules fn to run each time d of game time elapses, carrying any overshoot into the next period so repeating timers do not drift. A non-positive d fires once per Update step.
func (ts *Timers) SetPaused(paused bool)SetPaused sets whether Update advances scheduled timers.
func (ts *Timers) Update(dt time.Duration)Update advances all active timers by dt and fires expired ones in registration order.
Callbacks may safely cancel existing timers or schedule new ones; newly scheduled timers begin counting on the following Update step.
type TransitionRecord[S comparable] struct {
// From is the state the machine left.
From S
// To is the state the machine entered.
To S
// Step is the Update step count on which the transition occurred (0 before the first Update).
Step uint64
// Transition names the transition that fired: the label passed to AddNamedTransition or
// AddNamedAnyTransition, "from->to" / "*->to" for unnamed transitions, or "SetState".
Transition string
}TransitionRecord records one state transition taken by a Machine.
type TransitionSnapshot struct {
// From is the formatted state the machine left.
From string
// To is the formatted state the machine entered.
To string
// Step is the Update step count on which the transition occurred.
Step uint64
// Transition names the transition that fired.
Transition string
}TransitionSnapshot is a type-erased TransitionRecord for inspection and debug overlays.