GitHubComeçar

A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.

package flow

import "github.com/nsgo-dev/game/pkg/flow"

Visão geral

Package flow holds gameplay flow primitives driven by a game.Loop's fixed steps: game-clock timers, finite and hierarchical state machines, step sequences, strict YAML map events and a typed event bus. Branching dialogue lives in the dialogue package, which publishes its commands on a Bus.

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.

Índice

Constantes

const (
	TriggerAction   = "action"
	TriggerTouch    = "touch"
	TriggerAutorun  = "autorun"
	TriggerParallel = "parallel"
)

Map-event page triggers. The game decides when a trigger fires (the action button facing the event, the player stepping on it, every step for autorun and parallel) and then calls EventRunner.Start with the page MapEventDoc.ActivePage picks.

const DefaultHistoryLimit = 32

DefaultHistoryLimit is the default maximum number of transitions retained by a Machine.

const EventSnapshotVersion = 1

EventSnapshotVersion is the EventSnapshot schema version written by EventRunner.Snapshot and read by EventRunner.Restore.

const MachineSnapshotVersion = 1

MachineSnapshotVersion is the MachineSnapshot schema version written and read by Machine.Snapshot and Machine.Restore.

const MapEventVersion = 1

MapEventVersion is the map-event YAML schema version ParseMapEvent reads and EncodeMapEvent writes.

const VarsFileName = "vars.yaml"

VarsFileName is the conventional name of a project's shared variable declaration file.

const VarsFormatVersion = 1

VarsFormatVersion is the schema version of vars.yaml that ParseVars reads and EncodeVars writes.

const VarsSchemaURL = "https://nsgo.games/schemas/vars.v1.json"

VarsSchemaURL is where the JSON Schema of version 1 variable declaration files (vars.yaml) is published.

const VarsSnapshotVersion = 1

VarsSnapshotVersion is the VarsSnapshot schema version written and read by Vars.Snapshot and Vars.Restore.

Variáveis

var (
	// ErrInvalidVars reports that a vars.yaml document breaks the schema: a wrong version,
	// a missing or duplicate name, an invalid kind, a mismatched default, or invalid bounds.
	ErrInvalidVars = errors.New("flow: invalid vars")
	// ErrUnknownVar reports accessing or mutating a variable name that was not declared.
	ErrUnknownVar = errors.New("flow: unknown variable")
	// ErrVarTypeMismatch reports reading or writing a variable with a Go type that does not match its declared VarKind.
	ErrVarTypeMismatch = errors.New("flow: variable type mismatch")
	// ErrVarOutOfRange reports setting a numeric variable outside its declared [Min, Max] bounds.
	ErrVarOutOfRange = errors.New("flow: variable out of range")
	// ErrUndeclaredVar reports a dialogue script <<declare>> or <<set>> naming a variable absent from the dialogue.Options.Vars store, or a [Vars.SetFromExpr] call naming an undeclared variable.
	ErrUndeclaredVar = errors.New("flow: undeclared variable")
)
var ErrInvalidEventSnapshot = errors.New("flow: invalid event snapshot")

ErrInvalidEventSnapshot is wrapped by every error EventRunner.Restore returns.

var ErrInvalidMapEvent = errors.New("flow: invalid map event")

ErrInvalidMapEvent is wrapped by every map-event validation error.

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.

Funções

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 EncodeEvent(d *MapEventDoc) ([]byte, error)

EncodeEvent is EncodeMapEvent for a document held by pointer; a nil document is an error.

func EncodeMapEvent(doc MapEventDoc) ([]byte, error)

EncodeMapEvent validates doc and writes it in canonical YAML form: 2-space indentation, fields in declaration order, map keys sorted and every page's trigger written.

func EncodeVars(doc *VarsDoc) ([]byte, error)

EncodeVars validates doc and writes it in canonical deterministic YAML form: 2-space indentation, fields in declaration order, zero defaults and empty lists omitted.

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) string

FormatMachineInspection 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.

func ValidateMapEvent(doc MapEventDoc) error

ValidateMapEvent checks doc against the map-event schema: the version, at least one page, a known trigger on every page, exactly one command per list entry, named set and self commands, and finite non-negative waits. Errors are *loaderr.Error values wrapping ErrInvalidMapEvent.

func ValidateVars(doc *VarsDoc) error

ValidateVars checks doc against the vars.yaml schema: version, unique valid identifier names, valid kinds, defaults matching their declared kind, valid numeric bounds, and defaults within bounds. Errors are *loaderr.Error values wrapping ErrInvalidVars.

Tipos

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 EventCommand struct {
	Say  *SayCommand  `yaml:"say,omitempty"`
	Wait *WaitCommand `yaml:"wait,omitempty"`
	Set  *SetCommand  `yaml:"set,omitempty"`
	Self *SelfCommand `yaml:"self,omitempty"`
}

EventCommand is one command of a page; exactly one field is set.

type EventConditions struct {
	Self      map[string]bool `yaml:"self,omitempty"`
	Switches  map[string]bool `yaml:"switches,omitempty"`
	Variables map[string]int  `yaml:"variables,omitempty"`
}

EventConditions must all hold for a page to be eligible: each self switch and switch equals its value, and each variable is at least its value. No conditions always hold.

type EventPage struct {
	When     EventConditions `yaml:"when,omitempty"`
	Trigger  string          `yaml:"trigger"`
	Sprite   string          `yaml:"sprite,omitempty"`
	Commands []EventCommand  `yaml:"commands,omitempty"`
}

EventPage is one page of a map event: the conditions that make it eligible, the trigger that starts it and the commands it runs. An empty trigger in a file reads as TriggerAction.

type EventRunner struct {
	Self      map[string]bool
	Variables map[string]int
	Say       func(string)
	// contains filtered or unexported fields
}

EventRunner runs one page of a map event on the loop's fixed steps without blocking it: a wait returns from EventRunner.Update and resumes on a later step. Self and Variables hold what self and set commands write; Say receives say commands.

func NewEventRunner(doc MapEventDoc) *EventRunner

NewEventRunner returns an idle runner for doc; call EventRunner.Start to run a page.

func (r *EventRunner) Restore(s EventSnapshot) error

Restore replaces the runner's state with s, which must fit the runner's document; on error the runner is unchanged.

func (r *EventRunner) Running() bool

Running reports whether a page is in progress.

func (r *EventRunner) Snapshot() EventSnapshot

Snapshot returns the runner's state for a save slot.

func (r *EventRunner) Start(page int) error

Start runs page from its first command, replacing any page in progress.

func (r *EventRunner) Update(dt time.Duration) bool

Update advances the running page by dt, running commands until one waits or the page ends, and reports whether the runner is idle afterwards. Time left over when a wait ends carries into the commands after it.

type EventSnapshot struct {
	Version   int             `json:"version" yaml:"version"`
	Page      int             `json:"page" yaml:"page"`
	Command   int             `json:"command" yaml:"command"`
	Waiting   time.Duration   `json:"waiting,omitempty" yaml:"waiting,omitempty"`
	Self      map[string]bool `json:"self,omitempty" yaml:"self,omitempty"`
	Variables map[string]int  `json:"variables,omitempty" yaml:"variables,omitempty"`
}

EventSnapshot is a text save point of an EventRunner: the running page (-1 when idle), the index of the next command, the time left on a wait, and the runner's self switches and variables.

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() []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 (m *HSM[S]) History() bool

History reports whether shallow history is enabled on m.

func (m *HSM[S]) In(state S) bool

In reports whether state is currently active anywhere along m's active path.

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 (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 (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.Duration

TimeIn 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.Duration

TimeInState 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:

  1. Starts the machine if needed.
  2. Processes queued events (sent before this Update via Send or BindBus) once in FIFO send order, checking active states from innermost to outermost.
  3. If no event triggered a transition, evaluates polled transitions from innermost to outermost in declaration order, taking at most one.
  4. 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() bool

Done 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() S

Current returns the machine's current state.

func (m *Machine[S]) FormatState() string

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 (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() int

HistoryLimit returns the maximum number of transitions retained in m's ring buffer. Before SetHistoryLimit is called, HistoryLimit returns DefaultHistoryLimit.

func (m *Machine[S]) Inspect() MachineInspection

Inspect returns a type-erased read-only snapshot of m's current state and transition history.

func (m *Machine[S]) Previous() S

Previous returns the state before the last transition, or the zero value of S before any transition.

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 (m *Machine[S]) SavePart() save.Part

SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores m through save.Game. Loading validates the snapshot before mutating m, and resets m to its unstarted initial state when loading an older save slot that omits this part.

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() bool

Started reports whether the machine has been started (either via Machine.Start, Machine.SetState, Machine.Update, or Machine.Restore).

func (m *Machine[S]) Step() uint64

Step returns the number of Update steps executed by m.

func (m *Machine[S]) TimeInState() time.Duration

TimeInState 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 MapEventDoc struct {
	Version int         `yaml:"version"`
	Pages   []EventPage `yaml:"pages"`
}

MapEventDoc is a strict YAML map event: an ordered list of pages, of which the last whose conditions hold is active.

func ParseEvent(data []byte) (*MapEventDoc, error)

ParseEvent is ParseMapEvent returning a pointer, for callers that keep the document by reference.

func ParseMapEvent(data []byte) (MapEventDoc, error)

ParseMapEvent decodes and validates a versioned map-event document. Unknown fields and commands, duplicate keys, missing or unsupported versions and trailing YAML documents are refused. Every error is a *loaderr.Error pointing to the offending field and line with a fix.

func (d MapEventDoc) ActivePage(self, switches map[string]bool, variables map[string]int) int

ActivePage returns the index of the last page whose conditions hold against the event's self switches, the game's switches and variables, or -1 when none does. Missing names read as false and 0.

func (d *MapEventDoc) SelectPage(self map[string]bool) (EventPage, bool)

SelectPage returns the page MapEventDoc.ActivePage picks from the event's self switches alone, with no game switches or variables set, and whether any page's conditions hold.

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) Clear()

Clear cancels every active Handle on the Runner.

func (r *Runner) Start(step Step) *Handle

Start 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 SayCommand struct {
	Text string `yaml:"text"`
}

SayCommand passes Text, usually a localization key, to EventRunner.Say.

type SelfCommand struct {
	Name  string `yaml:"name"`
	Value bool   `yaml:"value"`
}

SelfCommand sets the runner's self switch Name to Value.

type SelfVars struct {
	// contains filtered or unexported fields
}

SelfVars is a view of the per-object self variables belonging to one scene object ID inside a Vars store. Self variables model per-instance state such as "this chest was opened" without cluttering global declarations.

func (s *SelfVars) Bool(key string) bool

Bool returns the boolean value of key on this object, or false when unset or non-bool.

func (s *SelfVars) Clear()

Clear removes all self variables on this object.

func (s *SelfVars) Delete(key string)

Delete removes key from this object's self variables.

func (s *SelfVars) Float(key string) float64

Float returns the float64 value of key on this object, or 0 when unset or non-numeric.

func (s *SelfVars) Get(key string) (any, bool)

Get returns the value stored for key on this object and whether it is set.

func (s *SelfVars) Has(key string) bool

Has reports whether key is set on this object.

func (s *SelfVars) Int(key string) int

Int returns the integer value of key on this object, or 0 when unset or non-integer.

func (s *SelfVars) Keys() []string

Keys returns the sorted list of self variable keys set on this object.

func (s *SelfVars) Map() map[string]any

Map returns a shallow copy of this object's self variables.

func (s *SelfVars) ObjectID() string

ObjectID returns the scene object ID this view is scoped to.

func (s *SelfVars) Set(key string, val any) error

Set stores a scalar value (bool, int, finite float64, or string) under key on this object.

func (s *SelfVars) SetBool(key string, val bool)

SetBool sets a boolean self switch on this object.

func (s *SelfVars) SetFloat(key string, val float64) error

SetFloat sets a finite float64 self variable on this object.

func (s *SelfVars) SetInt(key string, val int)

SetInt sets an integer self variable on this object.

func (s *SelfVars) SetString(key string, val string)

SetString sets a string self variable on this object.

func (s *SelfVars) String(key string) string

String returns the string value of key on this object, or "" when unset or non-string.

type SetCommand struct {
	Name  string `yaml:"name"`
	Value int    `yaml:"value"`
}

SetCommand sets the runner's integer variable Name to Value.

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()) Step

Do returns a Step that calls fn once and completes immediately, passing all remaining dt to the next step.

func Loop(makeStep func() Step) Step

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(steps ...Step) Step

Parallel returns a Step that updates every branch on each step until all branches have completed.

func Race(steps ...Step) Step

Race 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) Step

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(steps ...Step) Step

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.

func Wait(d time.Duration) Step

Wait returns a Step that completes after d of game time has elapsed.

func WaitUntil(cond func() bool) Step

WaitUntil 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)) Step

While returns a Step that runs update(dt) on each step while cond returns true, completing as soon as cond returns false.

type Timer struct {
	// contains filtered or unexported fields
}

Timer is a handle to a callback scheduled on a Timers scheduler.

func (t *Timer) Active() bool

Active 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.Duration

Remaining 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()) *Timer

After 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) Clear()

Clear cancels all scheduled timers.

func (ts *Timers) Every(d time.Duration, fn func()) *Timer

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.

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.

type VarChange struct {
	Name string
	Old  any
	New  any
}

VarChange describes one global variable mutation delivered to Vars.OnChange listeners.

type VarDecl struct {
	// Name uniquely identifies the variable; it must start with a letter or '_' followed by letters, digits, or '_'.
	Name string `yaml:"name" schema:"required"`
	// Kind is the variable's declared type: "bool", "int", "float", or "string".
	Kind VarKind `yaml:"kind" schema:"required,enum=bool|int|float|string"`
	// Default is the variable's initial value when omitted or reset; nil uses the zero value for Kind (false, 0, 0.0, or "").
	Default any `yaml:"default,omitempty"`
	// Min is an optional inclusive lower bound for "int" and "float" variables.
	Min *float64 `yaml:"min,omitempty"`
	// Max is an optional inclusive upper bound for "int" and "float" variables.
	Max *float64 `yaml:"max,omitempty"`
	// Doc is an optional description for editors, inspectors, and designers.
	Doc string `yaml:"doc,omitempty"`
}

VarDecl declares one project-wide game variable or switch.

func (d VarDecl) DefaultValue() any

DefaultValue returns the typed initial value of d (bool, int, float64, or string), filling in the zero value for d.Kind when d.Default is nil.

type VarInfo struct {
	Name    string
	Kind    VarKind
	Value   any
	Default any
	Min     *float64
	Max     *float64
	Doc     string
}

VarInfo describes one declared variable's metadata alongside its current runtime value, used by inspectors, debuggers, and MCP tools.

type VarKind string

VarKind is the declared value type of a project-wide game variable or switch.

const (
	// VarBool is a boolean switch (default false).
	VarBool VarKind = "bool"
	// VarInt is a signed integer variable (default 0).
	VarInt VarKind = "int"
	// VarFloat is a finite float64 variable (default 0).
	VarFloat VarKind = "float"
	// VarString is a string variable (default "").
	VarString VarKind = "string"
)
func (k VarKind) Valid() bool

Valid reports whether k is one of VarBool, VarInt, VarFloat, or VarString.

type Vars struct {
	// contains filtered or unexported fields
}

Vars holds project-wide declared game variables and switches alongside scoped per-object self variables, with typed accessors, range enforcement, deterministic change notifications, and save/restore snapshots.

Nothing in Vars reads the wall clock, spawns goroutines, or holds package-level state.

func NewVars(doc *VarsDoc) (*Vars, error)

NewVars creates a runtime variable store initialized to the defaults declared in doc. Passing nil creates an empty store with no global declarations (self variables still work).

func (v *Vars) Bool(name string) (bool, error)

Bool returns the current value of a VarBool variable.

func (v *Vars) ClearSelf(objectID string)

ClearSelf removes all self variables recorded for objectID.

func (v *Vars) Decl(name string) (VarDecl, bool)

Decl returns a copy of the declaration for name (optional leading '$' ignored).

func (v *Vars) Decls() []VarDecl

Decls returns copies of all declarations in declaration order.

func (v *Vars) Float(name string) (float64, error)

Float returns the current value of a VarFloat variable.

func (v *Vars) Get(name string) (any, bool)

Get returns the current typed value (bool, int, float64, or string) of name and whether it is declared. A leading '$' is optional and normalized away.

func (v *Vars) Has(name string) bool

Has reports whether name (optional leading '$' ignored) is declared in v.

func (v *Vars) Info(name string) (VarInfo, bool)

Info returns the current value and declaration metadata for name (optional leading '$' ignored).

func (v *Vars) Int(name string) (int, error)

Int returns the current value of a VarInt variable.

func (v *Vars) List() []VarInfo

List returns Info for every declared variable in declaration order.

func (v *Vars) Lookup(name string) (any, bool)

Lookup returns the current value of name for expression evaluators and condition hooks. It is equivalent to Get and accepts an optional leading '$'.

func (v *Vars) Map() map[string]any

Map returns a shallow copy of all declared variables and their current values.

func (v *Vars) Names() []string

Names returns all declared variable names in declaration order.

func (v *Vars) OnChange(name string, fn func(VarChange)) func()

OnChange subscribes fn to changes of the named global variable (optional leading '$' ignored), or to every global variable change when name is "". Listeners are invoked synchronously in registration order. Unsubscribing or subscribing inside a callback never skips remaining listeners for the change in flight. The returned function unsubscribes fn and is safe to call more than once.

func (v *Vars) Reset()

Reset restores every declared variable to its declared default and clears all per-object self variables. Global variables whose value actually changed notify their OnChange listeners in declaration order.

func (v *Vars) Restore(snap VarsSnapshot) error

Restore validates snap against v's declarations and replaces v's values and self variables atomically without invoking OnChange listeners.

The zero VarsSnapshot (Version 0 with empty Vars and Self) resets every variable to its declared default and clears all self variables, matching a save slot written before variables were saved. Variables declared in v but absent from snap keep their declared defaults so new variables added in a game update load older saves cleanly. Unknown variable names, type mismatches, out-of-range values, or unsupported versions return an error wrapping ErrInvalidSnapshot without modifying v.

func (v *Vars) Self(objectID string) *SelfVars

Self returns a scoped self-variable view for objectID inside v. Calling Self allocates no map entry until a key is set.

func (v *Vars) SelfObjects() []string

SelfObjects returns the sorted list of object IDs that currently have at least one self variable set.

func (v *Vars) Set(name string, val any) error

Set updates the declared variable name to val, enforcing its declared VarKind and optional [Min, Max] bounds. If the value changes, registered OnChange listeners are called synchronously in registration order.

func (v *Vars) SetBool(name string, val bool) error

SetBool updates a VarBool variable.

func (v *Vars) SetClamped(name string, val any) (oldVal, newVal any, clamped bool, err error)

SetClamped updates the declared variable name to val like Set, but clamps out-of-range numeric values into [Min, Max] instead of returning ErrVarOutOfRange.

func (v *Vars) SetFloat(name string, val float64) error

SetFloat updates a VarFloat variable, refusing NaN/Inf and enforcing any declared [Min, Max] range.

func (v *Vars) SetFromExpr(name string, val any) error

SetFromExpr updates a declared variable from an expression language's value, such as a Yarn dialogue script's, where every number is a float64: an integral float64 is accepted for a VarInt variable. A leading '$' on name is optional. An undeclared name returns an error wrapping ErrUndeclaredVar; kinds and declared ranges are enforced as by Vars.Set.

func (v *Vars) SetInt(name string, val int) error

SetInt updates a VarInt variable, enforcing any declared [Min, Max] range.

func (v *Vars) SetString(name string, val string) error

SetString updates a VarString variable.

func (v *Vars) Snapshot() VarsSnapshot

Snapshot returns a deterministic deep copy of v's global variables and per-object self variables. It shares no memory with v and encodes cleanly to JSON or YAML for save slots.

func (v *Vars) String(name string) (string, error)

String returns the current value of a VarString variable.

type VarsDoc struct {
	// Version is the schema version; it must equal VarsFormatVersion (1).
	Version int `yaml:"version" schema:"required"`
	// Vars declares the project's shared game variables and switches in declaration order.
	Vars []VarDecl `yaml:"vars,omitempty"`
}

VarsDoc is the root of a versioned vars.yaml declaration file.

func LoadVarsFS(fsys fs.FS, name string) (*VarsDoc, error)

LoadVarsFS reads, decodes, and validates the vars.yaml file at name in fsys. Errors are *loaderr.Error values naming name.

func ParseVars(data []byte) (*VarsDoc, error)

ParseVars decodes and validates a versioned vars.yaml document. Unknown fields, duplicate keys, missing or unsupported versions, and trailing YAML documents are refused. Every error is a *loaderr.Error pointing to the offending field and line with a fix; a caller that read data from a file names it with loaderr.WithFile.

func (d *VarsDoc) Has(name string) bool

Has reports whether d declares a variable named name (optional leading '$' ignored).

func (d *VarsDoc) Var(name string) (VarDecl, bool)

Var returns a copy of the declaration for name (optional leading '$' ignored), if declared.

type VarsSnapshot struct {
	// Version is VarsSnapshotVersion (1).
	Version int `json:"version" yaml:"version"`
	// Vars maps declared global variable names to their saved values.
	Vars map[string]any `json:"vars,omitempty" yaml:"vars,omitempty"`
	// Self maps scene object IDs to their saved per-object self variables.
	Self map[string]map[string]any `json:"self,omitempty" yaml:"self,omitempty"`
}

VarsSnapshot is a plain JSON/YAML-serializable snapshot of a Vars store's global variables and per-object self variables for save slots and deterministic state restore.

type WaitCommand struct {
	Seconds float64 `yaml:"seconds"`
}

WaitCommand pauses the page for Seconds of game time.