API 參考取自原始碼中的 Go 文件註解,以英文撰寫。
package stats
import "github.com/nsgo-dev/game/pkg/stats"概覽
Package stats is experimental: its API and documented formats may change in a minor release. See the API stability policy. holds gameplay stats: named base values changed by additive, multiplicative and override modifiers that come from sources such as equipment and buffs, with timed modifiers counted in fixed steps.
A Sheet keeps one entity's stats. Every change to a base value or a modifier 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. Sheet.Refresh replaces a source's modifiers in a single change. Timed modifiers count calls of Sheet.Step, which a game makes once per fixed step of its game.Loop, so a modifier that lasts n steps is removed by exactly the n-th Step after it was added.
Stat definitions and named effects (groups of modifiers, such as an item's bonuses or a buff) are written in a versioned YAML file 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.
索引
- 常數
- 變數
- func Encode(f *File) ([]byte, error)
- func Float(v float64) *float64
- func Validate(f *File) error
- type Active
- type BaseState
- type Change
- type Def
- type Effect
- type File
- type ID
- type Modifier
- type ModifierState
- type Op
- type Sheet
- func NewSheet(defs ...Def) (*Sheet, error)
- func (s *Sheet) Add(source string, m Modifier) (ID, error)
- func (s *Sheet) AddTimed(source string, m Modifier, steps int) (ID, error)
- func (s *Sheet) Apply(source string, e Effect) ([]ID, error)
- func (s *Sheet) Base(name string) float64
- func (s *Sheet) Clear()
- func (s *Sheet) Define(d Def) error
- func (s *Sheet) Has(name string) bool
- func (s *Sheet) Lookup(name string) (float64, bool)
- func (s *Sheet) Modifiers() []Active
- func (s *Sheet) Refresh(source string, e Effect) ([]ID, error)
- func (s *Sheet) Remaining(id ID) (int, bool)
- func (s *Sheet) Remove(id ID) bool
- func (s *Sheet) RemoveSource(source string) int
- 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) 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
常數
const CurrentVersion = 1CurrentVersion is the version of the stats file schema this package reads and writes.
變數
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")
)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 IDs or remaining steps are invalid.
函式
func Encode(f *File) ([]byte, error)Encode validates f and writes it as deterministic YAML 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 Float(v float64) *float64Float returns a pointer to v, for Def's optional Min and Max.
func Validate(f *File) errorValidate checks f against the version 1 schema: the version, unique non-empty names, finite numbers, Min not above Max, non-negative Steps, known ops, and modifiers that name defined stats.
型別
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 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 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 struct {
// Name identifies the stat within a sheet; it must be non-empty and unique.
Name string `yaml:"name"`
// Base is the stat's value before modifiers.
Base float64 `yaml:"base"`
// Min, when set, is the lowest value the stat takes after modifiers.
Min *float64 `yaml:"min,omitempty"`
// Max, when set, is the highest value the stat takes after modifiers; it must not be below Min.
Max *float64 `yaml:"max,omitempty"`
}Def defines one stat: its name, base value and optional bounds.
type Effect struct {
// Name identifies the effect within a file; it must be non-empty and unique.
Name string `yaml:"name"`
// Kind, optional, is instant, timed or infinite. Validate requires Steps above 0 for timed and Steps 0 for instant and infinite, and no Period for instant. Sheet.Apply does not read it: a game uses it to decide how to apply the effect.
Kind string `yaml:"kind,omitempty"`
// Period, optional, is the interval in fixed steps at which the game runs the effect's periodic hook. Sheet does not read it.
Period int `yaml:"period,omitempty"`
// GrantTags, optional, are gameplay tags the game grants while the effect is active, each once. Sheet does not read them.
GrantTags []string `yaml:"grantTags,omitempty"`
// ImmuneTo, optional, are gameplay tags whose effects the game refuses while this effect is active, each once. Sheet does not read them.
ImmuneTo []string `yaml:"immuneTo,omitempty"`
// Steps is how many fixed steps the effect's modifiers last once applied; 0 keeps them until they are removed.
Steps int `yaml:"steps,omitempty"`
// Modifiers are the effect's modifiers, applied in order.
Modifiers []Modifier `yaml:"modifiers"`
}Effect is a named group of modifiers applied together from one source, such as an item's bonuses or a buff.
type File struct {
// Version is the schema version; it must equal CurrentVersion.
Version int `yaml:"version"`
// Stats are the stat definitions, in the order a sheet built from the file reports changes.
Stats []Def `yaml:"stats"`
// Effects are named groups of modifiers 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(data []byte) (*File, error)Parse decodes a YAML stats file and validates it. Unknown fields and trailing YAML documents are refused.
func (f *File) Effect(name string) (Effect, bool)Effect returns the effect with the given name.
func (f *File) NewSheet() (*Sheet, error)NewSheet returns a sheet holding the file's stats at their base values, with no modifiers.
type ID uint64ID 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 struct {
// Stat names the stat the modifier changes.
Stat string `yaml:"stat"`
// Op is how the modifier changes it.
Op Op `yaml:"op"`
// Value is the amount added, the factor multiplied by, or the value an override sets; it must be finite.
Value float64 `yaml:"value"`
// Priority orders override modifiers on the same stat: the highest wins. Add and mul modifiers ignore it.
Priority int `yaml:"priority,omitempty"`
}Modifier changes one stat.
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 modifier in a Snapshot.
type Op stringOp 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 Sheet struct {
// OnChange, when set, is called with each stat whose value changed.
OnChange func(Change)
// contains filtered or unexported fields
}Sheet holds one entity's stats and the modifiers on them.
Every method that changes a base value or a modifier recomputes the stats it touched before returning and calls OnChange once for each one whose value changed, in definition order. OnChange may itself change the sheet; those changes are recomputed and reported before the outer call returns. A Sheet is not safe for concurrent use.
func NewSheet(defs ...Def) (*Sheet, error)NewSheet returns a sheet holding the given stats at their base values, in the given order.
func (s *Sheet) Add(source string, m Modifier) (ID, error)Add adds a modifier from source that lasts until it is removed, and returns its ID.
func (s *Sheet) AddTimed(source string, m Modifier, steps int) (ID, error)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 (s *Sheet) Apply(source string, e Effect) ([]ID, error)Apply adds every modifier of e from source, lasting e.Steps, and returns their IDs in the effect's order. It adds none of them when any is invalid.
Applying an effect again stacks a second copy; to refresh a buff instead, use Refresh.
func (s *Sheet) Base(name string) float64Base returns the named stat's base value, or 0 when it is not defined.
func (s *Sheet) Clear()Clear removes every modifier, leaving the stats at their base values.
func (s *Sheet) Define(d Def) errorDefine adds a stat at its base value after the stats already defined. Defining a name twice returns ErrDuplicateStat.
func (s *Sheet) Has(name string) boolHas reports whether the sheet defines the named stat.
func (s *Sheet) Lookup(name string) (float64, bool)Lookup returns the named stat's current value and whether it is defined.
func (s *Sheet) Modifiers() []ActiveModifiers returns the modifiers on the sheet in the order they were added.
func (s *Sheet) Refresh(source string, e Effect) ([]ID, error)Refresh removes every modifier added from source and applies e from source in their place, as one change: OnChange reports only each stat's value before the old modifiers left and after the new ones arrived, never the value in between. It returns the new modifiers' IDs in the effect's order. When any of e's modifiers is invalid it changes nothing.
Refresh restarts a buff's duration without the listeners seeing the buff end and begin again.
func (s *Sheet) Remaining(id ID) (int, bool)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 (s *Sheet) Remove(id ID) boolRemove removes the modifier with the given ID and reports whether it was on the sheet.
func (s *Sheet) RemoveSource(source string) intRemoveSource removes every modifier added from source, such as all of an unequipped item's bonuses, and returns how many it removed.
func (s *Sheet) Restore(snap Snapshot) errorRestore validates snap against s's defined stats and replaces s's base values, active modifiers and counters without firing OnChange. On error s is left unchanged.
func (s *Sheet) SavePart() save.PartSavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores s through save.Game. Loading validates every stat and modifier before mutating s, and resets s to its initial base values with no modifiers when loading an older slot that omits it.
func (s *Sheet) SetBase(name string, base float64) errorSetBase sets the named stat's base value and recomputes it.
func (s *Sheet) Snapshot() SnapshotSnapshot returns s's runtime state as plain data. It shares no memory with s.
func (s *Sheet) Stats() []stringStats returns the sheet's stat names in definition order.
func (s *Sheet) Step()Step advances timed modifiers by one fixed step and removes those whose last step this was. Call it once from each game.Loop Update.
func (s *Sheet) Steps() uint64Steps returns how many times Step has been called.
func (s *Sheet) Value(name string) float64Value returns the named stat's current value, or 0 when it is not defined.
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 active modifier in the order it was added.
Modifiers []ModifierState `json:"modifiers,omitempty" yaml:"modifiers,omitempty"`
// NextID is the last issued modifier ID so newly added modifiers never reuse an ID.
NextID ID `json:"nextId,omitempty" yaml:"nextId,omitempty"`
// Steps is the number of Step calls completed.
Steps uint64 `json:"steps,omitempty" yaml:"steps,omitempty"`
}Snapshot is a deterministic, JSON-serializable snapshot of a Sheet's base values, active modifiers, modifier ID counter and step counter.