Documentation
¶
Overview ¶
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.
Index ¶
- Constants
- Variables
- 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 (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 (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 (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
Examples ¶
Constants ¶
const DefaultHistoryLimit = 32
DefaultHistoryLimit is the default maximum number of transitions retained by a Machine.
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.
const MachineSnapshotVersion = 1
MachineSnapshotVersion is the MachineSnapshot schema version written and read by Machine.Snapshot and Machine.Restore.
Variables ¶
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 = errors.New("flow: dialogue choice is unavailable") // 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.
Functions ¶
func BindBus ¶
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 FormatMachineInspection ¶
func FormatMachineInspection(snap MachineInspection) string
FormatMachineInspection renders snap in a deterministic canonical text format suitable for statedump Values and golden-file diffs across runs.
func OnAnyEvent ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
Types ¶
type Bus ¶
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.
Example ¶
A Bus delivers typed events to the handlers subscribed for that type: Publish at once, Enqueue on the next Flush.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/flow"
)
type CoinPicked struct{ Value int }
func main() {
var bus flow.Bus
score := 0
unsubscribe := flow.Subscribe(&bus, func(e CoinPicked) { score += e.Value })
flow.SubscribeOnce(&bus, func(e CoinPicked) { fmt.Println("first coin:", e.Value) })
flow.Publish(&bus, CoinPicked{Value: 5})
flow.Enqueue(&bus, CoinPicked{Value: 10})
fmt.Println("before flush:", score)
bus.Flush()
fmt.Println("after flush:", score)
unsubscribe()
flow.Publish(&bus, CoinPicked{Value: 100})
fmt.Println("unsubscribed:", score)
}
Output: first coin: 5 before flush: 5 after flush: 15 unsubscribed: 15
type DialogueChoice ¶
DialogueChoice holds one option presented at a StepChoices step.
type DialogueEvent ¶
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 ¶
DialogueLine holds a resolved dialogue line produced by a DialogueRunner.
type DialogueOptions ¶
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 ¶
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.
Example ¶
A DialogueRunner 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/flow"
)
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
===
`
func main() {
script, err := flow.ParseYarn(shop)
if err != nil {
fmt.Println(err)
return
}
r := flow.NewDialogueRunner(script, flow.DialogueOptions{
OnCommand: func(e flow.DialogueEvent) { 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 NewDialogueRunner ¶
func NewDialogueRunner(script *DialogueScript, opts DialogueOptions) *DialogueRunner
NewDialogueRunner creates a runner for script with the given options.
func (*DialogueRunner) Choose ¶
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 (*DialogueRunner) Continue ¶
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 (*DialogueRunner) CurrentNode ¶
func (r *DialogueRunner) CurrentNode() string
CurrentNode returns the title of the currently executing node, or "" when ended.
func (*DialogueRunner) LoadState ¶
func (r *DialogueRunner) LoadState(state DialogueState)
LoadState restores variables and visit counts from a previously saved DialogueState.
func (*DialogueRunner) SetVar ¶
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 (*DialogueRunner) Start ¶
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 (*DialogueRunner) State ¶
func (r *DialogueRunner) State() DialogueState
State returns a serializable snapshot of the runner's variables and visit counts.
func (*DialogueRunner) Var ¶
func (r *DialogueRunner) Var(name string) (any, bool)
Var returns the current value of name (leading '$' optional) and whether it is set.
func (*DialogueRunner) Vars ¶
func (r *DialogueRunner) Vars() map[string]any
Vars returns a shallow copy of all currently set dialogue variables (keys without leading '$').
func (*DialogueRunner) Visited ¶
func (r *DialogueRunner) Visited(node string) int
Visited returns how many times the named node has been entered via Start or <<jump>>.
type DialogueScript ¶
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 ¶
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 (*DialogueScript) HasNode ¶
func (s *DialogueScript) HasNode(title string) bool
HasNode reports whether the script contains a node with the given title.
func (*DialogueScript) NodeHeaders ¶
func (s *DialogueScript) NodeHeaders(title string) map[string]string
NodeHeaders returns a copy of the header metadata declared on the named node, or nil if the node does not exist.
func (*DialogueScript) Nodes ¶
func (s *DialogueScript) Nodes() []string
Nodes returns the script's node titles in declaration order.
type DialogueState ¶
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 ¶
type DialogueStep struct {
Kind StepKind
Line DialogueLine
Choices []DialogueChoice
}
DialogueStep is the result of Start, Continue, or Choose on a DialogueRunner.
type HSM ¶
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.
Example ¶
An HSM nests child machines inside parent states so parent transitions apply to every descendant, running Enter outside-in and Exit inside-out.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/flow"
)
func main() {
combat := flow.NewHSM("approach")
combat.SetHistory(true)
combat.AddState("approach", flow.State{
Enter: func() { fmt.Println("enter approach") },
Exit: func() { fmt.Println("exit approach") },
})
combat.AddState("attack", flow.State{
Enter: func() { fmt.Println("enter attack") },
Exit: func() { fmt.Println("exit attack") },
})
combat.AddEventTransition("approach", "attack", "in_range")
enemy := flow.NewHSM("combat")
enemy.AddState("combat", flow.State{
Enter: func() { fmt.Println("enter combat") },
Exit: func() { fmt.Println("exit combat") },
})
enemy.AddChild("combat", combat)
enemy.AddState("stunned", flow.State{
Enter: func() { fmt.Println("enter stunned") },
Exit: func() { fmt.Println("exit stunned") },
})
enemy.AddEventTransition("combat", "stunned", "stun")
enemy.AddEventTransition("stunned", "combat", "recover")
enemy.Start()
enemy.Send("in_range")
enemy.Update(16 * time.Millisecond)
fmt.Println("active:", enemy.Current())
enemy.Send("stun")
enemy.Update(16 * time.Millisecond)
fmt.Println("active:", enemy.Current())
enemy.Send("recover")
enemy.Update(16 * time.Millisecond)
fmt.Println("resumed:", enemy.Current())
}
Output: enter combat enter approach exit approach enter attack active: [combat attack] exit attack exit combat enter stunned active: [stunned] exit stunned enter combat enter attack resumed: [combat attack]
func NewHSM ¶
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 (*HSM[S]) AddAnyEventTransition ¶
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 (*HSM[S]) AddAnyTransition ¶
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 (*HSM[S]) AddChild ¶
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 (*HSM[S]) AddEventTransition ¶
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 (*HSM[S]) AddState ¶
AddState registers the Enter, Update and Exit callbacks for id, replacing any previously registered callbacks for id while preserving any attached child machine.
func (*HSM[S]) AddTransition ¶
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 (*HSM[S]) ClearHistory ¶
func (m *HSM[S]) ClearHistory()
ClearHistory forgets any recorded shallow history on m and all of its nested child machines.
func (*HSM[S]) Current ¶
func (m *HSM[S]) Current() []S
Current 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 (*HSM[S]) Leaf ¶
func (m *HSM[S]) Leaf() S
Leaf returns the innermost active leaf state reachable from m, or the zero value of S if m is an inactive child machine.
func (*HSM[S]) Previous ¶
func (m *HSM[S]) Previous() S
Previous returns the state before the last transition at m's level, or the zero value of S before any transition.
func (*HSM[S]) Send ¶
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 (*HSM[S]) SetHistory ¶
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 (*HSM[S]) SetState ¶
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 (*HSM[S]) Start ¶
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 (*HSM[S]) TimeIn ¶
TimeIn returns the game time spent in state if state is currently active along m's active path, or 0 otherwise.
func (*HSM[S]) TimeInState ¶
TimeInState returns the game time spent in m's current state since entering it.
func (*HSM[S]) Update ¶
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 ¶
type Handle struct {
// contains filtered or unexported fields
}
Handle represents a running Step started on a Runner.
type Machine ¶
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.
Example ¶
A Machine switches states when a transition's condition holds, running each state's Enter and Exit.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/flow"
)
func main() {
type mode string
stamina := 2.0
m := flow.NewMachine[mode]("run")
m.AddState("run", flow.State{
Enter: func() { fmt.Println("enter run") },
Update: func(dt time.Duration) { stamina -= dt.Seconds() },
Exit: func() { fmt.Println("exit run") },
})
m.AddState("rest", flow.State{Enter: func() { fmt.Println("enter rest") }})
m.AddTransition("run", "rest", func() bool { return stamina <= 0 })
m.Start()
for range 3 {
m.Update(time.Second)
}
fmt.Println(m.Current(), m.Previous(), m.TimeInState())
}
Output: enter run exit run enter rest rest run 1s
func NewMachine ¶
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 (*Machine[S]) AddAnyTransition ¶
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 (*Machine[S]) AddNamedAnyTransition ¶
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 (*Machine[S]) AddNamedTransition ¶
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 (*Machine[S]) AddState ¶
AddState registers the callbacks for id, replacing any previously registered for id.
func (*Machine[S]) AddTransition ¶
AddTransition registers a conditional transition from from to to. Transitions are checked in declaration order during Update.
func (*Machine[S]) ClearHistory ¶
func (m *Machine[S]) ClearHistory()
ClearHistory discards all recorded transitions without changing HistoryLimit or Step.
func (*Machine[S]) Current ¶
func (m *Machine[S]) Current() S
Current returns the machine's current state.
func (*Machine[S]) FormatState ¶
FormatState 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 (*Machine[S]) History ¶
func (m *Machine[S]) History() []TransitionRecord[S]
History returns m's retained transitions in chronological order (oldest to newest).
func (*Machine[S]) HistoryInto ¶
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 (*Machine[S]) HistoryLimit ¶
HistoryLimit returns the maximum number of transitions retained in m's ring buffer. Before SetHistoryLimit is called, HistoryLimit returns DefaultHistoryLimit.
func (*Machine[S]) Inspect ¶
func (m *Machine[S]) Inspect() MachineInspection
Inspect returns a type-erased read-only snapshot of m's current state and transition history.
func (*Machine[S]) Previous ¶
func (m *Machine[S]) Previous() S
Previous returns the state before the last transition, or the zero value of S before any transition.
func (*Machine[S]) Restore ¶
func (m *Machine[S]) Restore(snap MachineSnapshot[S]) error
Restore 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 (*Machine[S]) SetHistoryLimit ¶
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 (*Machine[S]) SetState ¶
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 (*Machine[S]) Snapshot ¶
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 (*Machine[S]) Start ¶
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 (*Machine[S]) Started ¶
Started reports whether the machine has been started (either via Machine.Start, Machine.SetState, Machine.Update, or Machine.Restore).
func (*Machine[S]) TimeInState ¶
TimeInState returns the game time spent in the current state since entering it.
type MachineInspection ¶
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 ¶
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 ¶
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 ¶
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.
Example ¶
A Runner plays Steps over game time, like a coroutine: here a cutscene that waits, then does two things at once. Each line shows the game time at the end of the update that ran it.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/flow"
)
func main() {
var r flow.Runner
elapsed := time.Duration(0)
log := func(s string) flow.Step { return flow.Do(func() { fmt.Println(elapsed, s) }) }
h := r.Start(flow.Seq(
log("fade in"),
flow.Wait(time.Second),
flow.Parallel(
flow.Seq(flow.Wait(500*time.Millisecond), log("door opens")),
flow.Repeat(2, func() flow.Step { return flow.Seq(flow.Wait(time.Second), log("footstep")) }),
),
log("done"),
))
for !h.Done() {
elapsed += 250 * time.Millisecond
r.Update(250 * time.Millisecond)
}
}
Output: 250ms fade in 1.5s door opens 2s footstep 3s footstep 3s done
type State ¶
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 ¶
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 ¶
func Do(fn func()) Step
Do returns a Step that calls fn once and completes immediately, passing all remaining dt to the next step.
func Loop ¶
Loop 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 ¶
Parallel returns a Step that updates every branch on each step until all branches have completed.
func Race ¶
Race returns a Step that updates branches in order until the first branch completes, then cancels the remaining branches.
func Repeat ¶
Repeat 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 ¶
Seq 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.
type StepKind ¶
type StepKind int
StepKind 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 )
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.
type Timer ¶
type Timer struct {
// contains filtered or unexported fields
}
Timer is a handle to a callback scheduled on a Timers scheduler.
type Timers ¶
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.
Example ¶
Timers runs callbacks on game time, so pausing the game pauses them too.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/flow"
)
func main() {
var ts flow.Timers
ticks := 0
ts.Every(time.Second, func() { ticks++ })
bomb := ts.After(3*time.Second, func() { fmt.Println("boom") })
ts.Update(2 * time.Second)
ts.SetPaused(true)
ts.Update(10 * time.Second)
fmt.Println(ticks, bomb.Remaining())
ts.SetPaused(false)
ts.Update(time.Second)
fmt.Println(ticks, bomb.Active())
}
Output: 2 1s boom 3 false
func (*Timers) After ¶
After schedules fn to run once after d of game time has elapsed. A non-positive d fires on the next Update step.
func (*Timers) Every ¶
Every 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.
type TransitionRecord ¶
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 ¶
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.