flow

package
v0.4.0-rc.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 18 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Index

Examples

Constants

View Source
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.

View Source
const CommandsSnapshotVersion = 1

CommandsSnapshotVersion is the CommandsSnapshot schema version written by Commands.Snapshot and read by Commands.Restore.

View Source
const DefaultHistoryLimit = 32

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

View Source
const EventSnapshotVersion = 1

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

View Source
const MachineSnapshotVersion = 1

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

View Source
const MapEventSchemaURL = "https://nsgo.games/schemas/mapevent.v1.json"

MapEventSchemaURL is where the JSON Schema of version 1 map-event files is published.

View Source
const MapEventVersion = 1

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

View Source
const VarsFileName = "vars.yaml"

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

View Source
const VarsFormatVersion = 1

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

View Source
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.

View Source
const VarsSnapshotVersion = 1

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

Variables

View Source
var (
	// ErrUnknownCommand reports calling a command name not present in a [CommandRegistry].
	ErrUnknownCommand = errors.New("flow: unknown command")
	// ErrInvalidCommand reports a malformed command registration, argument, or runtime execution error.
	ErrInvalidCommand = errors.New("flow: invalid command")
	// ErrNoPendingWait reports calling Continue, Choose, or Complete* when the interpreter is not paused on that wait kind.
	ErrNoPendingWait = errors.New("flow: no pending wait")
	// ErrInvalidChoice reports an out-of-range index passed to [Commands.Choose].
	ErrInvalidChoice = errors.New("flow: invalid choice")
	// ErrCallDepthExceeded reports nested run/if/choose command frames exceeding maxCallDepth.
	ErrCallDepthExceeded = errors.New("flow: command call depth exceeded")
)
View Source
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")
)
View Source
var ErrInvalidEventSnapshot = errors.New("flow: invalid event snapshot")

ErrInvalidEventSnapshot is wrapped by every error EventRunner.Restore returns.

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

ErrInvalidMapEvent is wrapped by every map-event validation error.

View Source
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 EncodeCommands

func EncodeCommands(doc CommandListDoc) ([]byte, error)

EncodeCommands validates doc and encodes it in canonical deterministic YAML form.

func EncodeEvent

func EncodeEvent(d *MapEventDoc) ([]byte, error)

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

func EncodeMapEvent

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

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

func Enqueue[T any](b *Bus, event T)

Enqueue buffers event on b to be delivered in FIFO order on the next Flush.

func EvaluateConditions

func EvaluateConditions(cond EventConditions, ctx EventPageContext) (bool, error)

EvaluateConditions evaluates cond against ctx. All specified self, switches, variables, items, and expr conditions must hold.

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

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

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

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 ValidateCommands

func ValidateCommands(cmds []EventCommand, reg *CommandRegistry) error

ValidateCommands checks a command list against the schema and optionally against reg.

func ValidateMapEvent

func ValidateMapEvent(doc MapEventDoc) error

ValidateMapEvent checks doc against the map-event schema without requiring a CommandRegistry. Errors are *loaderr.Error values wrapping ErrInvalidMapEvent.

func ValidateMapEventWith

func ValidateMapEventWith(doc MapEventDoc, reg *CommandRegistry) error

ValidateMapEventWith checks doc against the map-event schema, validating any call commands against reg when non-nil. Errors are *loaderr.Error values wrapping ErrInvalidMapEvent.

func ValidateVars

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.

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

func (*Bus) Clear

func (b *Bus) Clear()

Clear removes all subscribers and discards all buffered events from b.

func (*Bus) Flush

func (b *Bus) Flush()

Flush delivers all events buffered by Enqueue in FIFO order, including any events enqueued by handlers during Flush.

type CallCommand

type CallCommand struct {
	Name string         `yaml:"name" schema:"required,minLength=1"`
	Args map[string]any `yaml:"args,omitempty"`
}

CallCommand invokes a game-registered command with typed scalar arguments checked against a CommandRegistry.

type ChoiceInfo

type ChoiceInfo struct {
	Index     int
	Text      string
	OrigIndex int
}

ChoiceInfo describes one available option presented by a paused `choose` command.

type ChoiceOption

type ChoiceOption struct {
	Text     string         `yaml:"text" schema:"required,minLength=1"`
	When     string         `yaml:"when,omitempty"`
	Commands []EventCommand `yaml:"commands,omitempty"`
}

ChoiceOption is one option in a ChooseCommand.

type ChooseCommand

type ChooseCommand struct {
	Prompt  string         `yaml:"prompt,omitempty"`
	Choices []ChoiceOption `yaml:"choices" schema:"required,minItems=1"`
}

ChooseCommand presents player choices and executes the selected option's command list.

type ChoosePrompt

type ChoosePrompt struct {
	Prompt  string
	Choices []ChoiceInfo
}

ChoosePrompt holds the prompt and available options of a paused `choose` command.

type Clock

type Clock uint8

Clock selects which update stream advances a Timer.

const (
	// ClockGame advances a timer through Timers.Update (pausable, scaled game time; the default).
	ClockGame Clock = iota
	// ClockReal advances a timer through Timers.UpdateReal (unscaled display time, independent of Timers.Paused).
	ClockReal
)

func (Clock) String

func (c Clock) String() string

String returns the human-readable name of c.

type CommandContext

type CommandContext struct {
	Vars     *Vars
	ObjectID string
	Self     map[string]bool
}

CommandContext passes runtime stores to a game-registered command handler.

type CommandFrameSnapshot

type CommandFrameSnapshot struct {
	Kind        string `json:"kind" yaml:"kind"`
	List        string `json:"list,omitempty" yaml:"list,omitempty"`
	CmdIndex    int    `json:"cmdIndex,omitempty" yaml:"cmdIndex,omitempty"`
	ChoiceIndex int    `json:"choiceIndex,omitempty" yaml:"choiceIndex,omitempty"`
	Next        int    `json:"next" yaml:"next"`
}

CommandFrameSnapshot saves one frame on a Commands execution stack.

type CommandListDoc

type CommandListDoc struct {
	// Version is the schema version; it must equal MapEventVersion (1).
	Version int `yaml:"version" schema:"required"`
	// Commands are the commands run sequentially by [Commands].
	Commands []EventCommand `yaml:"commands,omitempty"`
}

CommandListDoc is a standalone versioned YAML command list sharing the MapEventVersion command vocabulary.

func ParseCommands

func ParseCommands(data []byte) (CommandListDoc, error)

ParseCommands decodes and validates a standalone versioned command list document.

func ParseCommandsWith

func ParseCommandsWith(data []byte, reg *CommandRegistry) (CommandListDoc, error)

ParseCommandsWith decodes and validates a standalone command list document, checking call commands against reg when reg is non-nil.

type CommandParam

type CommandParam struct {
	Name     string
	Kind     CommandParamKind
	Required bool
	Default  any
	Min      *float64
	Max      *float64
	Enum     []string
	Doc      string
}

CommandParam declares one typed parameter of a game-registered CommandSpec.

type CommandParamKind

type CommandParamKind string

CommandParamKind is the value type of one parameter on a game-registered command.

const (
	ParamBool   CommandParamKind = "bool"
	ParamInt    CommandParamKind = "int"
	ParamFloat  CommandParamKind = "float"
	ParamString CommandParamKind = "string"
)

func (CommandParamKind) Valid

func (k CommandParamKind) Valid() bool

Valid reports whether k is a supported CommandParamKind.

type CommandRegistry

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

CommandRegistry stores game-registered commands and validates `call` commands against their typed parameter schemas.

func NewCommandRegistry

func NewCommandRegistry() *CommandRegistry

NewCommandRegistry returns an empty CommandRegistry.

func (*CommandRegistry) Lookup

func (r *CommandRegistry) Lookup(name string) (CommandSpec, bool)

Lookup returns the registered command spec for name, if any.

func (*CommandRegistry) MustRegister

func (r *CommandRegistry) MustRegister(spec CommandSpec)

MustRegister calls Register and panics on error.

func (*CommandRegistry) Names

func (r *CommandRegistry) Names() []string

Names returns all registered command names in sorted order.

func (*CommandRegistry) Register

func (r *CommandRegistry) Register(spec CommandSpec) error

Register adds spec to r, validating parameter names, kinds, defaults, bounds, and enums.

type CommandResult

type CommandResult struct {
	// Step, if non-nil, pauses the interpreter until Step.Update returns done=true.
	Step Step
	// Wait, when true with Step == nil, pauses in WaitCall until [Commands.CompleteCall] is called.
	Wait bool
}

CommandResult reports whether a game-registered command finished immediately or returned a Step to drive until done.

type CommandSpec

type CommandSpec struct {
	Name   string
	Doc    string
	Params []CommandParam
	Run    func(ctx *CommandContext, args map[string]any) (CommandResult, error)
}

CommandSpec defines a game-registered command callable via `call: {name, args}` and checked at load time.

type CommandWaitKind

type CommandWaitKind string

CommandWaitKind identifies why a Commands interpreter is currently paused.

const (
	WaitNone     CommandWaitKind = ""
	WaitTime     CommandWaitKind = "time"
	WaitSay      CommandWaitKind = "say"
	WaitChoice   CommandWaitKind = "choice"
	WaitMove     CommandWaitKind = "move"
	WaitDialogue CommandWaitKind = "dialogue"
	WaitCall     CommandWaitKind = "call"
)

type Commands

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

Commands is a resumable, non-blocking interpreter of EventCommand lists. Commands that pause (wait, choose, interactive say, move with wait, dialogue, async call) return from Update and resume on later steps, and Snapshot captures the full call stack and wait state.

func NewCommands

func NewCommands(opts CommandsOptions) *Commands

NewCommands returns an idle Commands interpreter configured with opts.

func (*Commands) Choose

func (c *Commands) Choose(index int) error

Choose selects an available option index from Commands.PendingChoices and pushes its commands.

func (*Commands) CompleteCall

func (c *Commands) CompleteCall() error

CompleteCall resumes execution when paused on an async `call` command.

func (*Commands) CompleteDialogue

func (c *Commands) CompleteDialogue() error

CompleteDialogue resumes execution when paused on a `run: {dialogue}` command.

func (*Commands) CompleteMove

func (c *Commands) CompleteMove() error

CompleteMove resumes execution when paused on an externally driven `move` command.

func (*Commands) Continue

func (c *Commands) Continue() error

Continue resumes execution after a paused `say` command.

func (*Commands) PendingChoices

func (c *Commands) PendingChoices() (ChoosePrompt, bool)

PendingChoices returns the prompt and available choices when paused on `choose`.

func (*Commands) PendingSay

func (c *Commands) PendingSay() (SayCommand, bool)

PendingSay returns the say command awaiting Commands.Continue, if any.

func (*Commands) Restore

func (c *Commands) Restore(snap CommandsSnapshot, rootCmds []EventCommand) error

Restore validates snap against rootCmds (and configured Lists) and atomically restores interpreter state.

func (*Commands) Running

func (c *Commands) Running() bool

Running reports whether a command list is currently active (running or paused).

func (*Commands) SetActiveStep

func (c *Commands) SetActiveStep(st Step)

SetActiveStep attaches an externally restored Step to an active WaitMove, WaitDialogue, or WaitCall pause.

func (*Commands) SetOptions

func (c *Commands) SetOptions(opts CommandsOptions)

SetOptions updates the interpreter's stores, registries, and callbacks.

func (*Commands) Snapshot

func (c *Commands) Snapshot() CommandsSnapshot

Snapshot returns a deterministic YAML/JSON snapshot of the interpreter state.

func (*Commands) Start

func (c *Commands) Start(cmds []EventCommand) error

Start begins executing cmds from index 0, replacing any running execution.

func (*Commands) StartList

func (c *Commands) StartList(name string) error

StartList begins executing the named list from CommandsOptions.Lists.

func (*Commands) Update

func (c *Commands) Update(dt time.Duration) (bool, error)

Update advances active waits, movement routes, and subsequent commands by dt without blocking. It returns whether the interpreter is idle after the step alongside any runtime error.

func (*Commands) Waiting

func (c *Commands) Waiting() CommandWaitKind

Waiting reports why the interpreter is currently paused, or WaitNone.

type CommandsOptions

type CommandsOptions struct {
	Vars       *Vars
	ObjectID   string
	Self       map[string]bool
	Variables  map[string]int
	Registry   *CommandRegistry
	Lists      map[string][]EventCommand
	Funcs      map[string]expr.Func
	ItemCount  func(item string) int
	OnSay      func(SayCommand) bool
	OnChoose   func(ChoosePrompt)
	OnGive     func(ItemCommand) error
	OnTake     func(ItemCommand) error
	OnMove     func(MoveCommand) Step
	OnTransfer func(TransferCommand) error
	OnSound    func(SoundCommand)
	OnDialogue func(node string) Step
}

CommandsOptions configures a Commands interpreter (or NewEventRunnerWith).

type CommandsSnapshot

type CommandsSnapshot struct {
	Version        int                    `json:"version" yaml:"version"`
	Frames         []CommandFrameSnapshot `json:"frames,omitempty" yaml:"frames,omitempty"`
	WaitKind       CommandWaitKind        `json:"waitKind,omitempty" yaml:"waitKind,omitempty"`
	Waiting        time.Duration          `json:"waiting,omitempty" yaml:"waiting,omitempty"`
	PendingChoices []int                  `json:"pendingChoices,omitempty" yaml:"pendingChoices,omitempty"`
	Self           map[string]bool        `json:"self,omitempty" yaml:"self,omitempty"`
	Variables      map[string]int         `json:"variables,omitempty" yaml:"variables,omitempty"`
	Locals         map[string]any         `json:"locals,omitempty" yaml:"locals,omitempty"`
}

CommandsSnapshot is a deterministic YAML/JSON snapshot of a Commands interpreter.

type EventCommand

type EventCommand struct {
	Say      *SayCommand      `yaml:"say,omitempty"`
	Choose   *ChooseCommand   `yaml:"choose,omitempty"`
	If       *IfCommand       `yaml:"if,omitempty"`
	Wait     *WaitCommand     `yaml:"wait,omitempty"`
	Set      *SetCommand      `yaml:"set,omitempty"`
	Self     *SelfCommand     `yaml:"self,omitempty"`
	Give     *ItemCommand     `yaml:"give,omitempty"`
	Take     *ItemCommand     `yaml:"take,omitempty"`
	Move     *MoveCommand     `yaml:"move,omitempty"`
	Transfer *TransferCommand `yaml:"transfer,omitempty"`
	Sound    *SoundCommand    `yaml:"sound,omitempty"`
	Run      *RunCommand      `yaml:"run,omitempty"`
	Call     *CallCommand     `yaml:"call,omitempty"`
}

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

type EventConditions

type EventConditions struct {
	// Self requires each named per-object self switch to equal its boolean value.
	Self map[string]bool `yaml:"self,omitempty"`
	// Switches requires each named game switch to equal its boolean value.
	Switches map[string]bool `yaml:"switches,omitempty"`
	// Variables requires each named integer game variable to be at least its value.
	Variables map[string]int `yaml:"variables,omitempty"`
	// Items requires the player to hold at least the specified count of each named item.
	Items map[string]int `yaml:"items,omitempty"`
	// Expr is an optional boolean expression evaluated through pkg/expr against game variables and self/item helpers.
	Expr string `yaml:"expr,omitempty"`
}

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

type EventPage

type EventPage struct {
	// When holds the conditions that must all hold for this page to be active.
	When EventConditions `yaml:"when,omitempty"`
	// Trigger determines when the page activates: "action", "touch", "autorun", or "parallel".
	Trigger string `yaml:"trigger" schema:"enum=action|touch|autorun|parallel"`
	// Sprite optionally overrides the object's sprite frame while this page is active.
	Sprite string `yaml:"sprite,omitempty"`
	// Commands are the commands run when this page activates.
	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 EventPageContext

type EventPageContext struct {
	Vars      *Vars
	ObjectID  string
	Self      map[string]bool
	Switches  map[string]bool
	Variables map[string]int
	Items     map[string]int
	ItemCount func(item string) int
	Funcs     map[string]expr.Func
}

EventPageContext supplies the state against which EventConditions and MapEventDoc.ActivePageWith evaluate.

type EventRunner

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: waiting commands return from EventRunner.Update and resume on a later step. Self and Variables hold what self and set commands write when no shared Vars store is attached; Say receives say commands.

func NewEventRunner

func NewEventRunner(doc MapEventDoc) *EventRunner

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

func NewEventRunnerWith

func NewEventRunnerWith(doc MapEventDoc, opts CommandsOptions) *EventRunner

NewEventRunnerWith returns an idle runner for doc configured with opts (such as Vars, ObjectID, Registry, Lists, OnSay, OnChoose, OnMove, OnTransfer, OnSound, OnDialogue).

func (*EventRunner) ActivePage

func (r *EventRunner) ActivePage(itemCount func(string) int) int

ActivePage selects the active page of doc against the runner's Vars store, Self switches, and Variables (plus optional item count).

func (*EventRunner) Choose

func (r *EventRunner) Choose(index int) error

Choose picks option index from EventRunner.PendingChoices and pushes its command list.

func (*EventRunner) Continue

func (r *EventRunner) Continue() error

Continue advances past a paused say command.

func (*EventRunner) Err

func (r *EventRunner) Err() error

Err returns the last runtime error encountered during EventRunner.Update, if any.

func (*EventRunner) PendingChoices

func (r *EventRunner) PendingChoices() (ChoosePrompt, bool)

PendingChoices returns the choices currently awaiting EventRunner.Choose, if any.

func (*EventRunner) PendingSay

func (r *EventRunner) PendingSay() (SayCommand, bool)

PendingSay returns the say command currently awaiting EventRunner.Continue, if any.

func (*EventRunner) Restore

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 (*EventRunner) Running

func (r *EventRunner) Running() bool

Running reports whether a page is in progress.

func (*EventRunner) SavePart

func (r *EventRunner) SavePart() save.Part

SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores r through save.Game. Loading validates the snapshot against r's document before mutating r, and resets r to idle with empty self switches and variables when loading an older save slot.

func (*EventRunner) SetActiveStep

func (r *EventRunner) SetActiveStep(st Step)

SetActiveStep attaches an externally restored Step to a restored WaitMove, WaitDialogue, or WaitCall state.

func (*EventRunner) SetOptions

func (r *EventRunner) SetOptions(opts CommandsOptions)

SetOptions updates the runner's callback and store options (preserving any active execution state unless Vars/Self maps changed).

func (*EventRunner) Snapshot

func (r *EventRunner) Snapshot() EventSnapshot

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

func (*EventRunner) Start

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

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

func (*EventRunner) Update

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.

func (*EventRunner) Waiting

func (r *EventRunner) Waiting() CommandWaitKind

Waiting reports what the runner is currently paused on, if anything.

type EventSnapshot

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"`
	Commands  *CommandsSnapshot `json:"commands,omitempty" yaml:"commands,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

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

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 (*HSM[S]) AddAnyTransition

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 (*HSM[S]) AddChild

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 (*HSM[S]) AddEventTransition

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 (*HSM[S]) AddState

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 (*HSM[S]) AddTransition

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 (*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]) History

func (m *HSM[S]) History() bool

History reports whether shallow history is enabled on m.

func (*HSM[S]) In

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

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

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

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 (*HSM[S]) SetHistory

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 (*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

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 (*HSM[S]) TimeInState

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

TimeInState returns the game time spent in m's current state since entering it.

func (*HSM[S]) Update

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

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

Handle represents a running Step started on a Runner.

func (*Handle) Cancel

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 (*Handle) Done

func (h *Handle) Done() bool

Done reports whether the step has finished or been cancelled.

type IfCommand

type IfCommand struct {
	When string         `yaml:"when" schema:"required,minLength=1"`
	Then []EventCommand `yaml:"then,omitempty"`
	Else []EventCommand `yaml:"else,omitempty"`
}

IfCommand branches on a pkg/expr boolean expression.

type ItemCommand

type ItemCommand struct {
	Item  string `yaml:"item" schema:"required,minLength=1"`
	Count int    `yaml:"count,omitempty" schema:"minimum=0"`
}

ItemCommand adds or removes Count (0 means 1) of Item.

func (ItemCommand) Quantity

func (c ItemCommand) Quantity() int

Quantity returns Count, or 1 when Count is 0.

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

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 (*Machine[S]) AddNamedAnyTransition

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 (*Machine[S]) AddNamedTransition

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 (*Machine[S]) AddState

func (m *Machine[S]) AddState(id S, state State)

AddState registers the callbacks for id, replacing any previously registered for id.

func (*Machine[S]) AddTransition

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 (*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

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 (*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

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 (*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]) SavePart

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 (*Machine[S]) SetHistoryLimit

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 (*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

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 (*Machine[S]) Step

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

Step returns the number of Update steps executed by m.

func (*Machine[S]) TimeInState

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

TimeInState returns the game time spent in the current state since entering it.

func (*Machine[S]) Update

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

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 MapEventDoc

type MapEventDoc struct {
	// Version is the schema version; it must equal MapEventVersion (1).
	Version int `yaml:"version" schema:"required"`
	// Pages are the ordered pages of the event; the last page whose when conditions hold is active.
	Pages []EventPage `yaml:"pages" schema:"required,minItems=1"`
}

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

func ParseEvent

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

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

func ParseMapEvent

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 ParseMapEventWith

func ParseMapEventWith(data []byte, reg *CommandRegistry) (MapEventDoc, error)

ParseMapEventWith decodes and validates a map-event document, checking any call commands against reg when reg is non-nil.

func (MapEventDoc) ActivePage

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 (MapEventDoc) ActivePageWith

func (d MapEventDoc) ActivePageWith(ctx EventPageContext) int

ActivePageWith returns the index of the last page whose conditions hold against ctx, or -1 when none does.

func (*MapEventDoc) SelectPage

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 MoveCommand

type MoveCommand struct {
	Target string   `yaml:"target,omitempty"`
	Route  []string `yaml:"route" schema:"required,minItems=1"`
	Wait   bool     `yaml:"wait,omitempty"`
}

MoveCommand executes a tile movement route on Target (defaulting to the event's own object).

type RunCommand

type RunCommand struct {
	List     string `yaml:"list,omitempty"`
	Dialogue string `yaml:"dialogue,omitempty"`
}

RunCommand runs another named command list or starts a Yarn dialogue node.

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

func (*Runner) Clear

func (r *Runner) Clear()

Clear cancels every active Handle on the Runner.

func (*Runner) Start

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 (*Runner) Update

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

type SayCommand struct {
	Text    string `yaml:"text" schema:"required,minLength=1"`
	Speaker string `yaml:"speaker,omitempty"`
}

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

type SelfCommand

type SelfCommand struct {
	Name  string `yaml:"name" schema:"required,minLength=1"`
	Value bool   `yaml:"value"`
}

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

type SelfVars

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 (*SelfVars) Bool

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

func (s *SelfVars) Clear()

Clear removes all self variables on this object.

func (*SelfVars) Delete

func (s *SelfVars) Delete(key string)

Delete removes key from this object's self variables.

func (*SelfVars) Float

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 (*SelfVars) Get

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

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

func (*SelfVars) Has

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

Has reports whether key is set on this object.

func (*SelfVars) Int

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 (*SelfVars) Keys

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

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

func (*SelfVars) Map

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

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

func (*SelfVars) ObjectID

func (s *SelfVars) ObjectID() string

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

func (*SelfVars) Set

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 (*SelfVars) SetBool

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

SetBool sets a boolean self switch on this object.

func (*SelfVars) SetFloat

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

SetFloat sets a finite float64 self variable on this object.

func (*SelfVars) SetInt

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

SetInt sets an integer self variable on this object.

func (*SelfVars) SetString

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

SetString sets a string self variable on this object.

func (*SelfVars) String

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

type SetCommand struct {
	Name  string `yaml:"name" schema:"required,minLength=1"`
	Value int    `yaml:"value,omitempty"`
	Expr  string `yaml:"expr,omitempty"`
	// contains filtered or unexported fields
}

SetCommand sets variable Name to Value (int, bool, finite float64, or string) or to the result of Expr.

func NewSetCommand

func NewSetCommand(name string, value any) (SetCommand, error)

NewSetCommand builds a SetCommand assigning a literal scalar value (bool, int, finite float64, or string) to name.

func (SetCommand) LiteralValue

func (c SetCommand) LiteralValue() any

LiteralValue returns the literal value configured on c when Expr is empty.

func (SetCommand) MarshalYAML

func (c SetCommand) MarshalYAML() (any, error)

MarshalYAML encodes SetCommand in canonical key order, omitting value when Expr is set.

func (*SetCommand) UnmarshalYAML

func (c *SetCommand) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML decodes a set command mapping, accepting bool/int/float/string literals under value or an expression under expr (never both) while refusing unknown or duplicate keys.

type SoundCommand

type SoundCommand struct {
	Cue    string  `yaml:"cue,omitempty"`
	Path   string  `yaml:"path,omitempty"`
	Volume float64 `yaml:"volume,omitempty" schema:"minimum=0,maximum=1"`
}

SoundCommand plays a sound cue or asset path at an optional volume multiplier in [0, 1].

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

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

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

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

func Parallel(steps ...Step) Step

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

func Race

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

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

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

func Wait(d time.Duration) Step

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

func WaitUntil

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

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

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

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

func (*Timer) Active

func (t *Timer) Active() bool

Active reports whether the timer is still scheduled to fire.

func (*Timer) Cancel

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

func (t *Timer) Clock() Clock

Clock returns the clock that advances the timer, or ClockGame for a nil timer.

func (*Timer) Remaining

func (t *Timer) Remaining() time.Duration

Remaining returns the time left on the timer's clock before it next fires, or 0 when inactive.

type Timers

type Timers struct {
	// Paused stops Update from advancing ClockGame timers when true; UpdateReal ignores it.
	Paused bool
	// contains filtered or unexported fields
}

Timers schedules one-shot and repeating callbacks driven by explicit fixed-step updates rather than the wall clock.

Call Update from game.Loop.Update to advance ClockGame timers (paused while the loop or Paused is true and scaled by TimeScale). Call UpdateReal from game.Loop.RealUpdate to advance ClockReal timers on unscaled display time regardless of pause. 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

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

After schedules fn to run once after d of game time (ClockGame) has elapsed. A non-positive d fires on the next Update step.

func (*Timers) AfterOn

func (ts *Timers) AfterOn(c Clock, d time.Duration, fn func()) *Timer

AfterOn schedules fn to run once after d has elapsed on clock c. A non-positive d fires on the next update of clock c.

Example

AfterOn schedules a timer on ClockReal so it advances via UpdateReal even while Timers.Paused is true.

package main

import (
	"fmt"
	"time"

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

func main() {
	var ts flow.Timers
	ts.After(100*time.Millisecond, func() { fmt.Println("game") })
	ts.AfterOn(flow.ClockReal, 100*time.Millisecond, func() { fmt.Println("real") })

	ts.SetPaused(true)
	ts.Update(100 * time.Millisecond)
	ts.UpdateReal(100 * time.Millisecond)
	ts.SetPaused(false)
	ts.Update(100 * time.Millisecond)
}
Output:
real
game

func (*Timers) Clear

func (ts *Timers) Clear()

Clear cancels all scheduled timers on every clock.

func (*Timers) Every

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

Every schedules fn to run each time d of game time (ClockGame) elapses, carrying any overshoot into the next period so repeating timers do not drift. A non-positive d fires once per Update step.

func (*Timers) EveryOn

func (ts *Timers) EveryOn(c Clock, d time.Duration, fn func()) *Timer

EveryOn schedules fn to run each time d elapses on clock c, carrying any overshoot into the next period so repeating timers do not drift. A non-positive d fires once per update of clock c.

func (*Timers) SetPaused

func (ts *Timers) SetPaused(paused bool)

SetPaused sets whether Update advances scheduled ClockGame timers. UpdateReal ignores Paused.

func (*Timers) Update

func (ts *Timers) Update(dt time.Duration)

Update advances all active ClockGame timers by dt and fires expired ones in registration order while Paused is false.

Callbacks may safely cancel existing timers or schedule new ones; newly scheduled timers begin counting on the following update step of their clock.

func (*Timers) UpdateReal

func (ts *Timers) UpdateReal(dt time.Duration)

UpdateReal advances all active ClockReal timers by dt and fires expired ones in registration order, ignoring Paused.

Callbacks may safely cancel existing timers or schedule new ones; newly scheduled timers begin counting on the following update step of their clock.

type TransferCommand

type TransferCommand struct {
	Map    string  `yaml:"map,omitempty"`
	Scene  string  `yaml:"scene,omitempty"`
	At     *[2]int `yaml:"at,omitempty,flow"`
	X      int     `yaml:"x,omitempty"`
	Y      int     `yaml:"y,omitempty"`
	Facing string  `yaml:"facing,omitempty" schema:"enum=up|down|left|right"`
}

TransferCommand moves the player to another map/scene and/or tile coordinates.

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.

type VarChange

type VarChange struct {
	Name string
	Old  any
	New  any
}

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

type VarDecl

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 (VarDecl) DefaultValue

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

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

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 (VarKind) Valid

func (k VarKind) Valid() bool

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

type Vars

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

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 (*Vars) Bool

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

Bool returns the current value of a VarBool variable.

func (*Vars) ClearSelf

func (v *Vars) ClearSelf(objectID string)

ClearSelf removes all self variables recorded for objectID.

func (*Vars) Decl

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

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

func (*Vars) Decls

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

Decls returns copies of all declarations in declaration order.

func (*Vars) Float

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

Float returns the current value of a VarFloat variable.

func (*Vars) Get

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 (*Vars) Has

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

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

func (*Vars) Info

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

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

func (*Vars) Int

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

Int returns the current value of a VarInt variable.

func (*Vars) List

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

List returns Info for every declared variable in declaration order.

func (*Vars) Lookup

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 (*Vars) Map

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

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

func (*Vars) Names

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

Names returns all declared variable names in declaration order.

func (*Vars) OnChange

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 (*Vars) Reset

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 (*Vars) Restore

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 (*Vars) Self

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 (*Vars) SelfObjects

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

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

func (*Vars) 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 (*Vars) SetBool

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

SetBool updates a VarBool variable.

func (*Vars) SetClamped

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 (*Vars) SetFloat

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 (*Vars) SetFromExpr

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 (*Vars) SetInt

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

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

func (*Vars) SetString

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

SetString updates a VarString variable.

func (*Vars) Snapshot

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 (*Vars) String

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

String returns the current value of a VarString variable.

type VarsDoc

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

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

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 (*VarsDoc) Has

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

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

func (*VarsDoc) Var

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

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

type VarsSnapshot

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

type WaitCommand struct {
	Seconds float64 `yaml:"seconds" schema:"minimum=0"`
}

WaitCommand pauses the page for Seconds of game time.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL