Documentation
¶
Overview ¶
Package stats is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package stats holds gameplay stats and deterministic gameplay effects: named base values changed by additive, multiplicative and override modifiers, instant and periodic base mutations, stacking rules, granted tags, immunity, ongoing suppression and chance rolls counted in fixed steps.
A Sheet keeps one entity's stats. Every change to a base value, modifier or effect recomputes the stats it touches at once, reports each value that changed through Sheet.OnChange, and leaves Sheet.Value a cached read. A stat's value is
clamp((base + sum of add values) * product of mul values)
or, while any override modifier is present, clamp(the override with the highest priority, the latest added among equal priorities). Adds and muls are applied in the order they were added; with float64 arithmetic that order can change the last digits of a result (0.1 + 0.2 + 0.3 is not exactly 0.3 + 0.1 + 0.2). A sum or product that overflows float64 saturates at the largest finite value of its sign, so values are always finite and within their bounds.
Gameplay effects are applied with Sheet.Apply, which returns a deterministic EffectHandle and checks immunity, require, stacking limits and chance in order (drawing from Sheet.Random only after non-random checks pass). Instant effects and periodic ticks modify stat base values; non-periodic timed and infinite effects add modifiers scaled by stack count, so removing them restores the stat exactly. Sheet.Step advances effects in one documented order per step: expire (firing a due tick on the expiry step), evaluate ongoing queries (suppressing or resuming), tick periods, and recompute. Everything is counted in whole steps and round-trips through Sheet.Snapshot and Sheet.Restore.
Stat definitions and named effects are written in a versioned YAML file (version 1 or 2) read with Parse and written with Encode.
Nothing in stats reads the wall clock, spawns goroutines or keeps package-level state, so sheets are deterministic and replay alike.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/stats"
)
func main() {
fmt.Println(stats.CurrentVersion)
}
Output: 2
Index ¶
- Constants
- Variables
- func Encode(f *File) ([]byte, error)
- func Float(v float64) *float64
- func SchemaComment(version int) string
- func SchemaForVersion(version int, opts jsonschema.Options) (*jsonschema.Schema, error)
- func SchemaURL(version int) string
- func Validate(f *File) error
- type Active
- type ActiveEffect
- type BaseState
- type Change
- type Def
- type Effect
- type EffectEvent
- type EffectEventKind
- type EffectHandle
- type EffectHook
- type EffectKind
- type EffectState
- type File
- type ID
- type Modifier
- type ModifierState
- type Op
- type RefuseReason
- type Sheet
- func (s *Sheet) ActiveCues(target string) []cues.Active
- func (s *Sheet) ActiveEffects() []ActiveEffect
- func (s *Sheet) ActiveTags() []string
- func (s *Sheet) Add(source string, m Modifier) (ID, error)
- func (s *Sheet) AddTag(tag string)
- func (s *Sheet) AddTimed(source string, m Modifier, steps int) (ID, error)
- func (s *Sheet) Apply(source string, e Effect) (EffectHandle, error)
- func (s *Sheet) Base(name string) float64
- func (s *Sheet) Clear()
- func (s *Sheet) Define(d Def) error
- func (s *Sheet) EffectStatus(h EffectHandle) (ActiveEffect, bool)
- func (s *Sheet) Has(name string) bool
- func (s *Sheet) HasTag(tag string) bool
- func (s *Sheet) Lookup(name string) (float64, bool)
- func (s *Sheet) Modifiers() []Active
- func (s *Sheet) Refresh(source string, e Effect) (EffectHandle, error)
- func (s *Sheet) Remaining(id ID) (int, bool)
- func (s *Sheet) Remove(id ID) bool
- func (s *Sheet) RemoveEffect(h EffectHandle) bool
- func (s *Sheet) RemoveEffectsByTag(tag string) int
- func (s *Sheet) RemoveSource(source string) int
- func (s *Sheet) RemoveTag(tag string)
- func (s *Sheet) Restore(snap Snapshot) error
- func (s *Sheet) SavePart() save.Part
- func (s *Sheet) SetBase(name string, base float64) error
- func (s *Sheet) SetEffectHook(effectName string, hook EffectHook)
- func (s *Sheet) Snapshot() Snapshot
- func (s *Sheet) Stats() []string
- func (s *Sheet) Step()
- func (s *Sheet) Steps() uint64
- func (s *Sheet) Value(name string) float64
- type Snapshot
- type StackBy
- type StackExpire
- type StackPeriod
- type StackReapply
- type Stacking
- type TagState
Examples ¶
Constants ¶
const ( // MinVersion is the oldest stats file schema version this package reads and writes. MinVersion = 1 // CurrentVersion is the newest stats file schema version this package reads and writes. // Version 2 adds full gameplay effect runtime rules: instant/timed/infinite kinds, periodic ticks // with tickOnApply, stacking policies, tag queries for require/ongoing/immuneTo, effect tags, and chance. CurrentVersion = 2 )
const SchemaURLV1 = "https://nsgo.games/schemas/stats.v1.json"
SchemaURLV1 is where the JSON Schema of version 1 stats files is published. Encode names it in a yaml-language-server comment on a version 1 file's first line, so editors and AI tools validate and complete the file as it is written.
const SchemaURLV2 = "https://nsgo.games/schemas/stats.v2.json"
SchemaURLV2 is where the JSON Schema of version 2 stats files, which add gameplay effect fields such as tags, requirement queries and stacking, is published. Encode names it in a yaml-language-server comment on a version 2 file's first line.
Variables ¶
var ( // ErrUnknownStat is returned when a stat name is not defined on the sheet or in the file. ErrUnknownStat = errors.New("stats: unknown stat") // ErrDuplicateStat is returned when a stat is defined twice. ErrDuplicateStat = errors.New("stats: duplicate stat") // ErrInvalidOp is returned for an Op other than OpAdd, OpMul and OpOverride. ErrInvalidOp = errors.New("stats: invalid modifier op") // ErrInvalidValue is returned for a NaN or infinite number. ErrInvalidValue = errors.New("stats: value is not finite") // ErrInvalidSteps is returned for a negative step count. ErrInvalidSteps = errors.New("stats: negative steps") // ErrNoRandomStream is returned when applying an effect with 0 < Chance < 1 on a Sheet with a nil Random stream. ErrNoRandomStream = errors.New("stats: effect chance requires Sheet.Random") )
var ErrInvalidSnapshot = errors.New("stats: invalid snapshot")
ErrInvalidSnapshot reports a Snapshot that Sheet.Restore refuses because a stat is unknown, a value is non-finite, an op is invalid, or modifier/effect IDs or remaining steps are invalid.
Functions ¶
func Encode ¶
Encode validates f and writes it as deterministic YAML, SchemaComment for its version on the first line, with 2-space indentation: fields in declaration order and lists in their given order, so Parse then Encode reproduces an encoded file byte for byte.
func SchemaComment ¶
SchemaComment returns the first line Encode writes for a file of the given version: a YAML comment that points a YAML language server at SchemaURL. Parse ignores it like any other comment.
func SchemaForVersion ¶
func SchemaForVersion(version int, opts jsonschema.Options) (*jsonschema.Schema, error)
SchemaForVersion returns the draft-07 JSON Schema of a stats file of the given version, the format Encode writes and Parse reads for that version. Version 1 reflects the package's version 1 wire type, whose immuneTo is a flat tag list and which has none of the version 2 effect fields; version 2 reflects File.
func SchemaURL ¶
SchemaURL returns the schema URL of a stats file of the given version, SchemaURLV1 for version 1 and SchemaURLV2 for version 2.
Types ¶
type Active ¶
type Active struct {
// ID is the modifier's handle for Sheet.Remove.
ID ID
// Source is the tag the modifier was added with, such as "equip:weapon" or "buff:haste".
Source string
// Modifier is the modifier itself.
Modifier Modifier
// Remaining is how many more calls of Sheet.Step the modifier lasts, 0 for a modifier without a time limit.
Remaining int
}
Active describes a modifier currently on a sheet.
type ActiveEffect ¶
type ActiveEffect struct {
Handle EffectHandle
Name string
Source string
Kind EffectKind
Stacks int
Remaining int
Period int
PeriodLeft int
Ticks int
Suppressed bool
Cue string
GrantTags []string
}
ActiveEffect describes one gameplay effect currently active on a Sheet.
type BaseState ¶
type BaseState struct {
// Stat is the stat's name.
Stat string `json:"stat" yaml:"stat"`
// Base is the stat's base value before modifiers.
Base float64 `json:"base" yaml:"base"`
}
BaseState is one stat's base value in a Snapshot.
type Change ¶
type Change struct {
// Stat is the stat's name.
Stat string
// Old and New are its value before and after the change.
Old, New float64
}
Change reports a stat whose value changed.
type Def ¶
type Def struct {
// Name identifies the stat within a sheet; it must be non-empty and unique.
Name string `json:"name" yaml:"name" schema:"required"`
// Base is the stat's value before modifiers.
Base float64 `json:"base" yaml:"base" schema:"required"`
// Min, when set, is the lowest value the stat takes after modifiers.
Min *float64 `json:"min,omitempty" yaml:"min,omitempty"`
// Max, when set, is the highest value the stat takes after modifiers; it must not be below Min.
Max *float64 `json:"max,omitempty" yaml:"max,omitempty"`
}
Def defines one stat: its name, base value and optional bounds.
type Effect ¶
type Effect struct {
// Name identifies the effect within a file; it must be non-empty and unique.
Name string `json:"name" yaml:"name" schema:"required"`
// Kind is instant, timed or infinite. When empty, Steps > 0 behaves as timed and Steps == 0 as infinite.
Kind EffectKind `json:"kind,omitempty" yaml:"kind,omitempty"`
// Steps is how many fixed steps a timed effect lasts; 0 for instant and infinite effects.
Steps int `json:"steps,omitempty" yaml:"steps,omitempty"`
// Period is the interval in fixed steps between periodic ticks. When > 0, each tick applies Modifiers to stat base values.
Period int `json:"period,omitempty" yaml:"period,omitempty"`
// TickOnApply, when true on a periodic effect, runs one tick immediately on application (if not initially suppressed).
TickOnApply bool `json:"tickOnApply,omitempty" yaml:"tickOnApply,omitempty"`
// Chance, when set (in [0, 1]), is the probability the effect applies, drawn from Sheet.Random after immunity, require and stacking checks pass.
Chance *float64 `json:"chance,omitempty" yaml:"chance,omitempty"`
// Cue (version 2) names a gameplay cue tag (such as "cue.status.burning") fired while this effect is active or when it triggers.
Cue string `json:"cue,omitempty" yaml:"cue,omitempty"`
// Tags identify the effect itself (for example for immunity matching on instant effects and cue dispatch).
Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"`
// GrantTags are gameplay tags granted to the target Sheet while the effect is active and not suppressed.
GrantTags []string `json:"grantTags,omitempty" yaml:"grantTags,omitempty"`
// Require is a tag query checked once against the target Sheet on application; if false, the effect is refused.
Require *tags.QueryDoc `json:"require,omitempty" yaml:"require,omitempty"`
// Ongoing is a tag query evaluated every step; while false, the effect stays on the sheet and counts down its duration, but its modifiers, granted tags, immunity and period ticks are suppressed.
Ongoing *tags.QueryDoc `json:"ongoing,omitempty" yaml:"ongoing,omitempty"`
// ImmuneTo is a tag query matched against incoming effects' Tags and GrantTags while this effect is active and not suppressed.
ImmuneTo *tags.QueryDoc `json:"immuneTo,omitempty" yaml:"immuneTo,omitempty"`
// Stacking configures stack limits, grouping (by target or source), reapply duration/period handling, and expiry behavior.
Stacking *Stacking `json:"stacking,omitempty" yaml:"stacking,omitempty"`
// Modifiers are the effect's stat changes, applied in order.
Modifiers []Modifier `json:"modifiers,omitempty" yaml:"modifiers,omitempty"`
}
Effect is a named gameplay effect applied from one source, such as instant damage, an item's bonuses, a stacking buff, a periodic poison, or an immunity ward.
func (Effect) Clone ¶
Clone returns a deep copy of e so caller mutations do not affect an active sheet.
func (Effect) EffectiveKind ¶
func (e Effect) EffectiveKind() EffectKind
EffectiveKind returns Kind, or EffectTimed when Kind is empty and Steps > 0, or EffectInfinite otherwise.
type EffectEvent ¶
type EffectEvent struct {
// Kind is what happened.
Kind EffectEventKind
// Handle identifies the effect application (0 for EventEffectRefused).
Handle EffectHandle
// Effect is the effect's Name.
Effect string
// Source is the source string passed to Apply or Refresh.
Source string
// Step is the Sheet's step count when the event occurred.
Step uint64
// Stacks is the effect's stack count after the event (0 when removed/refused).
Stacks int
// Tick is the 1-based periodic tick count for EventEffectTicked, and 0 otherwise.
Tick int
// Reason is why EventEffectRefused happened, and RefuseNone otherwise.
Reason RefuseReason
// Instant reports whether the effect's kind is EffectInstant.
Instant bool
// Cue holds the effect's declared cue tag (such as "cue.status.burning"), when set.
Cue string
// Tags holds the effect's combined Tags and GrantTags for cue dispatch.
Tags []string
}
EffectEvent reports one lifecycle change of a gameplay effect on a Sheet, for UI, hooks and cues.
type EffectEventKind ¶
type EffectEventKind uint8
EffectEventKind identifies a gameplay effect lifecycle event on a Sheet.
const ( // EventEffectApplied is sent when an effect is applied (including instant effects). EventEffectApplied EffectEventKind = iota + 1 // EventEffectTicked is sent on each periodic tick of an active effect (including TickOnApply and a tick on the expiry step). EventEffectTicked // EventEffectStacked is sent when reapplying an effect merges into an existing active instance. EventEffectStacked // EventEffectSuppressed is sent when an active effect's Ongoing query evaluates to false. EventEffectSuppressed // EventEffectResumed is sent when a suppressed effect's Ongoing query evaluates to true again. EventEffectResumed // EventEffectExpired is sent when an effect's duration ends or it is removed. // Stacks is 0 when the effect leaves the sheet, or > 0 when Stacking.OnExpire == ExpireOne dropped one stack. EventEffectExpired // EventEffectRefused is sent when an effect application is refused by immunity, require, stack limit or chance. EventEffectRefused )
func (EffectEventKind) String ¶
func (k EffectEventKind) String() string
String returns a short lower-case name for k.
type EffectHandle ¶
type EffectHandle uint64
EffectHandle identifies one gameplay effect application on a Sheet. Handles start at 1 and are never reused by the same sheet; 0 means no effect was applied (such as a refused application).
type EffectHook ¶
type EffectHook func(s *Sheet, ev EffectEvent)
EffectHook is a custom Go callback keyed by effect name on a Sheet.
type EffectKind ¶
type EffectKind string
EffectKind is an effect's duration policy.
const ( // EffectInstant applies its modifiers once directly to stat base values and does not stay on the sheet. EffectInstant EffectKind = "instant" // EffectTimed stays on the sheet for Steps fixed steps, applying modifiers (or periodic base changes) and granting tags while active. EffectTimed EffectKind = "timed" // EffectInfinite stays on the sheet until explicitly removed, applying modifiers (or periodic base changes) and granting tags while active. EffectInfinite EffectKind = "infinite" )
func (EffectKind) Valid ¶
func (k EffectKind) Valid() bool
Valid reports whether k is EffectInstant, EffectTimed or EffectInfinite.
type EffectState ¶
type EffectState struct {
// Handle is the effect's unique handle on the sheet.
Handle EffectHandle `json:"handle" yaml:"handle"`
// Source is the source tag the effect was applied with.
Source string `json:"source,omitempty" yaml:"source,omitempty"`
// Effect is the full effect definition.
Effect Effect `json:"effect" yaml:"effect"`
// Stacks is the current stack count (>= 1).
Stacks int `json:"stacks" yaml:"stacks"`
// Remaining is how many Step calls the effect lasts (0 for infinite).
Remaining int `json:"remaining,omitempty" yaml:"remaining,omitempty"`
// PeriodLeft is how many Step calls remain until the next periodic tick.
PeriodLeft int `json:"periodLeft,omitempty" yaml:"periodLeft,omitempty"`
// Ticks is how many periodic ticks the effect has already fired.
Ticks int `json:"ticks,omitempty" yaml:"ticks,omitempty"`
// Suppressed reports whether the effect's Ongoing query is currently false.
Suppressed bool `json:"suppressed,omitempty" yaml:"suppressed,omitempty"`
// ModIDs preserves the modifier IDs of attached non-periodic modifiers so override tie-breaking and Sheet.Modifiers remain identical across Restore.
ModIDs []ID `json:"modIds,omitempty" yaml:"modIds,omitempty"`
}
EffectState is one active gameplay effect in a Snapshot.
type File ¶
type File struct {
// Version is the schema version, from MinVersion (1) to CurrentVersion (2).
Version int `yaml:"version" schema:"required"`
// Stats are the stat definitions, in the order a sheet built from the file reports changes.
Stats []Def `yaml:"stats" schema:"required"`
// Effects are named gameplay effects on those stats.
Effects []Effect `yaml:"effects,omitempty"`
}
File is the root of a versioned YAML stats file: stat definitions and the effects that modify them.
func Parse ¶
Parse decodes a YAML stats file (version 1 or 2) and validates it. Unknown fields and trailing YAML documents are refused.
type ID ¶
type ID uint64
ID identifies one modifier on a sheet. IDs start at 1 and are never reused by the same sheet, so the zero ID names no modifier.
type Modifier ¶
type Modifier struct {
// Stat names the stat the modifier changes.
Stat string `json:"stat" yaml:"stat" schema:"required"`
// Op is how the modifier changes it.
Op Op `json:"op" yaml:"op" schema:"required"`
// Value is the amount added, the factor multiplied by, or the value an override sets; it must be finite.
Value float64 `json:"value" yaml:"value" schema:"required"`
// Priority orders override modifiers on the same stat: the highest wins. Add and mul modifiers ignore it.
Priority int `json:"priority,omitempty" yaml:"priority,omitempty"`
}
Modifier changes one stat.
type ModifierState ¶
type ModifierState struct {
// ID is the modifier's handle.
ID ID `json:"id" yaml:"id"`
// Source is the modifier's source tag.
Source string `json:"source,omitempty" yaml:"source,omitempty"`
// Stat is the target stat name.
Stat string `json:"stat" yaml:"stat"`
// Op is OpAdd, OpMul or OpOverride.
Op Op `json:"op" yaml:"op"`
// Value is the modifier's numeric operand.
Value float64 `json:"value" yaml:"value"`
// Priority orders override modifiers.
Priority int `json:"priority,omitempty" yaml:"priority,omitempty"`
// Remaining is how many Step calls the modifier lasts (0 for permanent).
Remaining int `json:"remaining,omitempty" yaml:"remaining,omitempty"`
}
ModifierState is one active standalone modifier in a Snapshot.
type Op ¶
type Op string
Op is how a modifier changes a stat. Its YAML form is the constant's string.
const ( // OpAdd adds the modifier's value to the stat's base, before any multiplication. OpAdd Op = "add" // OpMul multiplies the stat by the modifier's value after all additions; several multiply together. OpMul Op = "mul" // OpOverride replaces the computed value with the modifier's value, ignoring every add and mul; among several, the highest Priority wins and the latest added breaks ties. OpOverride Op = "override" )
type RefuseReason ¶
type RefuseReason uint8
RefuseReason says why a Sheet refused an effect application.
const ( // RefuseNone means the event is not a refusal. RefuseNone RefuseReason = iota // RefuseImmune means an active non-suppressed effect's ImmuneTo query matched the incoming effect. RefuseImmune // RefuseRequirement means the incoming effect's Require query did not match the target sheet's tags. RefuseRequirement // RefuseStackLimit means the effect already reached its Stacking.Limit. RefuseStackLimit // RefuseChance means the deterministic random roll against Effect.Chance did not succeed. RefuseChance )
func (RefuseReason) String ¶
func (r RefuseReason) String() string
String returns a short lower-case name for r.
type Sheet ¶
type Sheet struct {
// OnChange, when set, is called with each stat whose value changed.
OnChange func(Change)
// OnEffect, when set, receives every gameplay effect lifecycle event in deterministic order.
OnEffect func(EffectEvent)
// Tags, when set, is a shared gameplay tag container bound to a tags.Registry. Tags added to
// the sheet and GrantTags of active non-suppressed effects are mirrored into Tags, and tag
// queries evaluate against both the sheet's own tags and any tags held in Tags.
Tags *tags.Container
// Random is the deterministic random stream used to roll Effect.Chance.
Random *random.Stream
// contains filtered or unexported fields
}
Sheet holds one entity's stats, modifiers, active gameplay effects and tags.
Every method that changes a base value, modifier or effect recomputes the stats it touched before returning and calls OnChange once for each one whose value changed, in definition order. OnChange and OnEffect may themselves change the sheet; those changes are recomputed and reported before the outer call returns. A Sheet is not safe for concurrent use.
func NewSheet ¶
NewSheet returns a sheet holding the given stats at their base values, in the given order.
func (*Sheet) ActiveCues ¶
ActiveCues returns the active while-active cues for target from s's active non-suppressed effects, sorted deterministically by tag for cues.Player.Reconcile after rollback.
func (*Sheet) ActiveEffects ¶
func (s *Sheet) ActiveEffects() []ActiveEffect
ActiveEffects returns all gameplay effects currently active on s, in application order.
func (*Sheet) ActiveTags ¶
ActiveTags returns the sorted, deduplicated list of tag names currently active on s.
func (*Sheet) Add ¶
Add adds a modifier from source that lasts until it is removed, and returns its ID.
func (*Sheet) AddTag ¶
AddTag increments the reference count of tag on s (and mirrors it into Sheet.Tags when bound).
func (*Sheet) AddTimed ¶
AddTimed adds a modifier from source that lasts steps calls of Step and is removed by the last of them; 0 steps lasts until it is removed. It returns the modifier's ID.
func (*Sheet) Apply ¶
func (s *Sheet) Apply(source string, e Effect) (EffectHandle, error)
Apply evaluates and applies gameplay effect e from source to s.
Checks run in deterministic order: validation, immunity, require, stacking limit, and chance. A refused application draws no random number (except when refused by chance itself), emits EventEffectRefused, and returns (0, nil).
Instant effects modify stat base values immediately and return a unique EffectHandle for cue deduplication. Timed and infinite effects stay on the sheet, tracking stacks, duration, ongoing suppression, granted tags, immunity and periodic ticks on Sheet.Step.
func (*Sheet) Clear ¶
func (s *Sheet) Clear()
Clear removes every modifier and active gameplay effect, leaving the stats at their base values.
func (*Sheet) Define ¶
Define adds a stat at its base value after the stats already defined. Defining a name twice returns ErrDuplicateStat.
func (*Sheet) EffectStatus ¶
func (s *Sheet) EffectStatus(h EffectHandle) (ActiveEffect, bool)
EffectStatus returns the status of the active effect handle h, or false if h is not active on s.
func (*Sheet) HasTag ¶
HasTag reports whether s holds tag or any descendant under tag (from explicit tags, active non-suppressed effects' GrantTags, or Sheet.Tags).
func (*Sheet) Modifiers ¶
Modifiers returns the modifiers on the sheet in the order they were added.
func (*Sheet) Refresh ¶
func (s *Sheet) Refresh(source string, e Effect) (EffectHandle, error)
Refresh removes every modifier and active gameplay effect from source and applies e from source in their place as one recompute: OnChange reports only the net change. When e is invalid it changes nothing.
func (*Sheet) Remaining ¶
Remaining returns how many more calls of Step the modifier lasts (0 for one without a time limit) and whether it is on the sheet.
func (*Sheet) Remove ¶
Remove removes the modifier with the given ID and reports whether it was on the sheet.
func (*Sheet) RemoveEffect ¶
func (s *Sheet) RemoveEffect(h EffectHandle) bool
RemoveEffect removes the active gameplay effect identified by h, detaching its modifiers and granted tags, and reports whether h was active.
func (*Sheet) RemoveEffectsByTag ¶
RemoveEffectsByTag removes every active gameplay effect whose Tags or GrantTags match tag under gameplay-tag hierarchy, and returns how many effects were removed.
func (*Sheet) RemoveSource ¶
RemoveSource removes every modifier and active gameplay effect added from source, such as all of an unequipped item's bonuses, and returns how many modifiers it removed.
func (*Sheet) RemoveTag ¶
RemoveTag decrements the reference count of tag on s (and mirrors it into Sheet.Tags when bound).
func (*Sheet) Restore ¶
Restore validates snap against s's defined stats and replaces s's base values, active modifiers, active gameplay effects, tags, random stream state and counters without firing OnChange or OnEffect. On error s is left unchanged.
func (*Sheet) SavePart ¶
SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores s through save.Game. Loading validates every stat, modifier and effect before mutating s, and resets s to its initial base values with no modifiers or effects when loading an older slot that omits it.
func (*Sheet) SetEffectHook ¶
func (s *Sheet) SetEffectHook(effectName string, hook EffectHook)
SetEffectHook registers a Go hook invoked whenever an effect with the given name emits an event. Passing a nil hook removes any previously registered hook for effectName.
func (*Sheet) Snapshot ¶
Snapshot returns s's runtime state as plain data. It shares no memory with s.
func (*Sheet) Step ¶
func (s *Sheet) Step()
Step advances timed modifiers and active gameplay effects by one fixed step. Call it once from each game.Loop Update.
Each step runs in one deterministic order:
- Expire: decrement remaining steps; a periodic tick due on the expiry step fires before the effect expires (or drops one stack for Stacking.OnExpire == ExpireOne).
- Evaluate ongoing: suppress effects whose Ongoing query became false (holding their period) and resume suppressed effects whose Ongoing query became true (setting next tick a full period away).
- Tick periods: advance active non-suppressed periodic effects and apply scaled modifiers to base values.
- Recompute: flush dirty stats in definition order (calling OnChange) and deliver queued effect hooks/events.
type Snapshot ¶
type Snapshot struct {
// Bases lists each defined stat's base value in definition order.
Bases []BaseState `json:"bases,omitempty" yaml:"bases,omitempty"`
// Modifiers lists every standalone active modifier in the order it was added.
Modifiers []ModifierState `json:"modifiers,omitempty" yaml:"modifiers,omitempty"`
// Effects lists every active gameplay effect in the order it was applied.
Effects []EffectState `json:"effects,omitempty" yaml:"effects,omitempty"`
// Tags lists explicit sheet tags (added via Sheet.AddTag) in sorted order.
Tags []TagState `json:"tags,omitempty" yaml:"tags,omitempty"`
// NextID is the last issued modifier ID so newly added modifiers never reuse an ID.
NextID ID `json:"nextId,omitempty" yaml:"nextId,omitempty"`
// NextEffectHandle is the last issued effect handle so newly applied effects never reuse a handle.
NextEffectHandle EffectHandle `json:"nextEffectHandle,omitempty" yaml:"nextEffectHandle,omitempty"`
// Steps is the number of Step calls completed.
Steps uint64 `json:"steps,omitempty" yaml:"steps,omitempty"`
// Random captures Sheet.Random's generator state when Sheet.Random is non-nil.
Random *random.State `json:"random,omitempty" yaml:"random,omitempty"`
}
Snapshot is a deterministic, JSON- and YAML-serializable snapshot of a Sheet's base values, active modifiers, active gameplay effects, explicit tags, counters and optional random stream state.
type StackBy ¶
type StackBy string
StackBy says whether stacks of an effect are grouped per target or per source.
type StackExpire ¶
type StackExpire string
StackExpire says what happens when a timed stacked effect's duration reaches zero.
const ( // ExpireAll removes all stacks and expires the effect at once. ExpireAll StackExpire = "all" // ExpireOne removes one stack and resets the remaining duration to Steps, removing the effect when the last stack expires. ExpireOne StackExpire = "one" )
func (StackExpire) Valid ¶
func (e StackExpire) Valid() bool
Valid reports whether e is ExpireAll or ExpireOne.
type StackPeriod ¶
type StackPeriod string
StackPeriod says how reapplying a periodic effect affects its period countdown.
const ( // PeriodKeep keeps the active effect's current countdown to the next tick unchanged. PeriodKeep StackPeriod = "keep" // PeriodReset resets the countdown to a full Period steps. PeriodReset StackPeriod = "reset" )
func (StackPeriod) Valid ¶
func (p StackPeriod) Valid() bool
Valid reports whether p is PeriodKeep or PeriodReset.
type StackReapply ¶
type StackReapply string
StackReapply says how reapplying a stacked effect handles duration or instance creation.
const ( // ReapplyRefresh resets the active effect's remaining duration to a full Steps count. ReapplyRefresh StackReapply = "refresh" // ReapplyExtend adds Steps to the active effect's remaining duration. ReapplyExtend StackReapply = "extend" // ReapplyKeep leaves the active effect's remaining duration unchanged. ReapplyKeep StackReapply = "keep" // ReapplySeparate creates a separate independent instance up to Stacking.Limit instead of merging stacks. ReapplySeparate StackReapply = "separate" )
func (StackReapply) Valid ¶
func (r StackReapply) Valid() bool
Valid reports whether r is a known reapply policy.
type Stacking ¶
type Stacking struct {
// Limit is the maximum number of stacks (or separate instances for ReapplySeparate). Must be >= 1.
Limit int `json:"limit" yaml:"limit" schema:"required"`
// By groups stacks by target (default) or by source.
By StackBy `json:"by,omitempty" yaml:"by,omitempty"`
// OnReapply controls duration handling or separate instances on reapply: refresh (default), extend, keep or separate.
OnReapply StackReapply `json:"onReapply,omitempty" yaml:"onReapply,omitempty"`
// Period controls a periodic effect's period timer on merged reapply: keep (default) or reset.
Period StackPeriod `json:"period,omitempty" yaml:"period,omitempty"`
// OnExpire controls expiry of a timed stacked effect: all (default) or one.
OnExpire StackExpire `json:"onExpire,omitempty" yaml:"onExpire,omitempty"`
}
Stacking configures how repeated applications of an effect combine on a Sheet.
func (*Stacking) EffectiveBy ¶
EffectiveBy returns By, or StackByTarget when empty.
func (*Stacking) EffectiveOnExpire ¶
func (s *Stacking) EffectiveOnExpire() StackExpire
EffectiveOnExpire returns OnExpire, or ExpireAll when empty.
func (*Stacking) EffectiveOnReapply ¶
func (s *Stacking) EffectiveOnReapply() StackReapply
EffectiveOnReapply returns OnReapply, or ReapplyRefresh when empty.
func (*Stacking) EffectivePeriod ¶
func (s *Stacking) EffectivePeriod() StackPeriod
EffectivePeriod returns Period, or PeriodKeep when empty.