API 參考取自原始碼中的 Go 文件註解,以英文撰寫。
package ability
import "github.com/nsgo-dev/game/pkg/ability"概覽
Package ability runs gameplay abilities with costs, cooldowns, charges, cast and channel times and conditions, activated by input actions and advanced one fixed game.Loop step at a time.
Ability Sets
A Set is a versioned YAML file listing abilities. Parse decodes and validates one, refusing unknown fields, duplicate IDs and out-of-range values; Encode writes deterministic YAML that Parse reads back to an equal Set.
Casters
A Caster runs one character's abilities. NewCaster turns every duration in a Set into whole steps at the loop's rate, rounding up, and Caster.Update advances cooldowns, recharges and the active cast or channel by exactly one step, then activates abilities whose input actions were pressed. Because every timer counts whole steps, the same inputs on the same steps give the same events on the same steps on every machine, and Snapshot and Restore carry that state through save slots, rollback and replays.
Costs are paid through a Resources (a Pool, or an adapter over the game's own stats), conditions through a Condition function, and a game applies an ability's effect when it receives EventActivated through OnEvent.
索引
- 常數
- func Encode(set *Set) ([]byte, error)
- func Validate(set *Set) error
- type AbilityState
- type Actions
- type ActiveState
- type Caster
- func NewCaster(set *Set, rate int) (*Caster, error)
- func (c *Caster) Active() (id string, phase Phase, elapsed int, ok bool)
- func (c *Caster) CanActivate(id string) Reason
- func (c *Caster) Cancel() bool
- func (c *Caster) Duration(steps int) time.Duration
- func (c *Caster) Rate() int
- func (c *Caster) Reset()
- func (c *Caster) Restore(st *State) error
- func (c *Caster) Snapshot() State
- func (c *Caster) Status(id string) (st Status, ok bool)
- func (c *Caster) Step() uint64
- func (c *Caster) Steps(d time.Duration) int
- func (c *Caster) TryActivate(id string) Reason
- func (c *Caster) Update(in Actions)
- type Cost
- type Def
- type Event
- type EventKind
- type Phase
- type Pool
- type Reason
- type Resources
- type Set
- type State
- type Status
- type Trigger
常數
const (
// MaxAbilities is the most abilities one Set holds.
MaxAbilities = 1024
// MaxCharges is the largest Def.Charges.
MaxCharges = 99
// MaxDuration is the longest cooldown, recharge, cast, channel or tick interval.
MaxDuration = 24 * time.Hour
// MaxNameLength is the longest ability ID, action, resource or condition name, in bytes.
MaxNameLength = 64
)Limits on an ability set, checked by Validate so a crafted file cannot make a Caster allocate or loop without bound.
const CurrentVersion = 1CurrentVersion is the ability set schema version this package reads and writes.
函式
func Encode(set *Set) ([]byte, error)Encode validates set and writes it as deterministic 2-space YAML: fields in a fixed order, abilities in set order, durations as Go duration strings. Parse reads the result back to an equal Set.
func Validate(set *Set) errorValidate checks set against the version 1 schema rules and the package limits.
型別
type AbilityState struct {
// ID is the ability's ID.
ID string `json:"id" yaml:"id"`
// Charges is how many uses are stored.
Charges int `json:"charges" yaml:"charges"`
// Cooldown is how many steps of cooldown are left.
Cooldown int `json:"cooldown,omitempty" yaml:"cooldown,omitempty"`
// Recharge is how many steps are left until the next charge comes back.
Recharge int `json:"recharge,omitempty" yaml:"recharge,omitempty"`
}AbilityState is one ability's charges and timers in a State.
type Actions interface {
// Pressed reports whether the action is held on this step.
Pressed(name string) bool
// JustPressed reports whether the action became held on this step.
JustPressed(name string) bool
}Actions is the input a Caster reads each step: the named actions an input.Actions samples once per fixed game.Loop step. *input.Actions satisfies it, and so can a replay or network input source.
type ActiveState struct {
// Ability is the ability's ID.
Ability string `json:"ability" yaml:"ability"`
// Phase is PhaseCasting or PhaseChanneling.
Phase Phase `json:"phase" yaml:"phase"`
// Elapsed is how many steps of Phase have run.
Elapsed int `json:"elapsed" yaml:"elapsed"`
}ActiveState is the ability casting or channeling in a State.
type Caster struct {
// Resources pays ability costs. When nil, an ability with costs cannot be activated.
Resources Resources
// Condition reports whether a named condition holds, such as "grounded" or "stunned". When nil, every condition is false, so an ability that needs one cannot be activated and an ability that needs "!name" can.
Condition func(name string) bool
// OnEvent, when set, receives every Event in the order it happened. It may call the Caster's methods, including TryActivate and Cancel; events those cause follow the current one. Events that happened before a Reset or Restore called from OnEvent are still delivered, and when that call is made during Update, Update goes on to read input against the reset or restored state.
OnEvent func(Event)
// contains filtered or unexported fields
}Caster runs one character's abilities, one fixed step at a time.
Every duration in its Set becomes a whole number of steps at its rate, rounded up, and every timer counts whole steps, so the same inputs on the same steps produce the same events on the same steps on any machine. Call Update once per game.Loop step, after stepping the input.Actions it reads.
At most one ability casts or channels at a time. Its methods, and OnEvent, run on the goroutine that calls Update, as Loop.Update does.
func NewCaster(set *Set, rate int) (*Caster, error)NewCaster returns a Caster for set at rate steps a second, with every ability idle, charged and off cooldown. A rate of 0 or less means 60, as game.Loop's Rate does. The Caster keeps its own copy of set.
func (c *Caster) Active() (id string, phase Phase, elapsed int, ok bool)Active returns the ID, phase and elapsed steps of the ability casting or channeling now, or ok false when none is.
func (c *Caster) CanActivate(id string) ReasonCanActivate reports whether TryActivate(id) would activate the ability now, and if not, the first reason it would not, checked in this order: ReasonUnknown, ReasonBusy, ReasonCooldown, ReasonNoCharges, ReasonCondition, ReasonCost. It changes nothing.
func (c *Caster) Cancel() boolCancel stops the active cast or channel and sends EventCanceled. A canceled cast spends nothing; a canceled channel keeps what its cast spent. It reports whether an ability was active.
func (c *Caster) Duration(steps int) time.DurationDuration returns how much game time steps of the Caster's fixed step last, rounded down to a nanosecond, for showing a cooldown or cast bar. A negative step count gives 0, and a count longer than the largest time.Duration gives that largest Duration.
func (c *Caster) Reset()Reset returns every ability to idle, fully charged and off cooldown, without sending events. The step count is kept. Called from OnEvent, it still delivers the events that happened before it, after the current one.
func (c *Caster) Restore(st *State) errorRestore replaces the Caster's state with st, without sending events. It refuses, and changes nothing, when st's rate or abilities differ from the Caster's or a value is out of the range a Caster could reach. Called from OnEvent, it still delivers the events that happened before it, after the current one.
func (c *Caster) Snapshot() StateSnapshot returns the Caster's state. Restoring it into a Caster made from the same Set at the same rate, and giving both the same inputs, produces the same events on the same steps.
func (c *Caster) Status(id string) (st Status, ok bool)Status returns the state of the ability id, or ok false when the set has no such ability.
func (c *Caster) Steps(d time.Duration) intSteps returns d in the Caster's whole steps, rounded up, as it counts every duration in its Set.
func (c *Caster) TryActivate(id string) ReasonTryActivate activates the ability id if CanActivate allows it, and returns the reason it did not otherwise. An activated ability starts casting; one with no cast time takes effect at once, before TryActivate returns, spending its costs and a charge and starting its cooldown.
func (c *Caster) Update(in Actions)Update advances the Caster by one fixed step.
In order, it: counts the step; advances every ability's cooldown and recharge, in set order; advances the active cast or channel, interrupting it if a condition no longer holds, canceling a TriggerHold ability whose action is no longer held, and completing a cast or ending a channel whose time is up; then, when in is not nil, tries each ability whose action was just pressed (TriggerPress) or is held (TriggerHold), in set order, activating at most one ability per action. So an ability whose cooldown ends on a step can be activated again on that same step.
type Cost struct {
// Resource names the resource, such as "mana" or "stamina".
Resource string `yaml:"resource"`
// Amount is how much of Resource one use spends; it must be finite and positive.
Amount float64 `yaml:"amount"`
}Cost is one resource an ability spends.
type Def struct {
// ID uniquely names the ability within its Set. It is 1 to MaxNameLength bytes of ASCII letters, digits, '_', '-' and '.'.
ID string `yaml:"id"`
// Name is an optional display name or localization key.
Name string `yaml:"name,omitempty"`
// Action is the input action that activates the ability, as bound on an input.Actions. Empty means only code activates it, through Caster.TryActivate.
Action string `yaml:"action,omitempty"`
// Trigger is TriggerPress or TriggerHold; empty means TriggerPress. TriggerHold needs an Action.
Trigger Trigger `yaml:"trigger,omitempty"`
// Costs are the resources one use spends, each resource at most once. They are checked when activation starts and spent when the cast completes.
Costs []Cost `yaml:"costs,omitempty"`
// Cooldown is the shortest time between two uses, counted from the step a use completes its cast. It applies even while charges remain.
Cooldown time.Duration `yaml:"cooldown,omitempty"`
// Charges is how many uses the ability stores, 0 meaning 1. More than one charge needs a Recharge.
Charges int `yaml:"charges,omitempty"`
// Recharge is how long one spent charge takes to come back. Spent charges come back one after another, not all at once. Zero means a use never spends a charge.
Recharge time.Duration `yaml:"recharge,omitempty"`
// CastTime is how long the ability casts before it takes effect. Zero takes effect on the step it is activated.
CastTime time.Duration `yaml:"castTime,omitempty"`
// ChannelTime is how long the ability channels after it takes effect. Zero means it does not channel.
ChannelTime time.Duration `yaml:"channelTime,omitempty"`
// TickInterval is how often a channel ticks. Zero means the channel does not tick; otherwise it needs a ChannelTime and must not exceed it.
TickInterval time.Duration `yaml:"tickInterval,omitempty"`
// Conditions are names that must all hold to start the ability and to keep casting or channeling it. A leading '!' means the named condition must not hold, such as "!stunned". Each condition appears at most once.
Conditions []string `yaml:"conditions,omitempty,flow"`
}Def defines one ability: what using it costs, how often it can be used, how long it takes and when it is allowed.
Durations are written as Go duration strings such as "500ms" or "1m30s". A Caster turns each into a whole number of its fixed steps, rounding up, so a duration that is not a multiple of the step still waits at least that long.
func (d *Def) EffectiveTrigger() TriggerEffectiveTrigger returns Trigger, or TriggerPress when Trigger is empty.
func (d *Def) MaxChargesOrOne() intMaxChargesOrOne returns Charges, or 1 when Charges is 0.
type Event struct {
// Kind is what happened.
Kind EventKind
// Ability is the ability's ID.
Ability string
// Step is the Caster's step count when it happened: the number of Update calls so far, including the one running.
Step uint64
// Reason is why an EventInterrupted happened, and ReasonOK for every other kind.
Reason Reason
// Tick counts an EventChannelTick's ticks within its channel, from 1; it is 0 for every other kind.
Tick int
}Event reports one change to an ability's state.
type EventKind uint8EventKind says what happened to an ability.
const (
// EventStarted is sent when an ability is activated and starts casting. An ability with no cast time sends it on the same step as EventActivated.
EventStarted EventKind = iota + 1
// EventActivated is sent when an ability's cast completes and it takes effect: its costs are spent, a charge is used and its cooldown starts. This is where a game applies the ability's effect.
EventActivated
// EventChannelTick is sent each TickInterval of a channel; Event.Tick counts the ticks from 1.
EventChannelTick
// EventChannelEnded is sent when a channel runs its full ChannelTime.
EventChannelEnded
// EventCanceled is sent when Caster.Cancel stops a cast or channel, or a TriggerHold ability's action is released.
EventCanceled
// EventInterrupted is sent when a cast or channel stops because a condition no longer holds (Event.Reason is ReasonCondition) or a cost is no longer affordable when the cast completes (ReasonCost).
EventInterrupted
// EventCooldownEnded is sent on the step an ability's cooldown reaches zero.
EventCooldownEnded
// EventChargeRestored is sent on the step a spent charge comes back.
EventChargeRestored
)func (k EventKind) String() stringString returns a short lower-case name for k.
type Phase stringPhase is what an ability is doing.
const (
// PhaseIdle is an ability that is neither casting nor channeling.
PhaseIdle Phase = "idle"
// PhaseCasting is an ability counting down its cast time; nothing is spent yet.
PhaseCasting Phase = "casting"
// PhaseChanneling is an ability that took effect and is channeling.
PhaseChanneling Phase = "channeling"
)type Pool map[string]float64Pool is a Resources kept in a map from resource name to amount. A missing resource has 0.
func (p Pool) Spend(resource string, amount float64)Spend subtracts amount from p[resource].
type Reason uint8Reason says why an ability could not be activated or why its cast stopped. ReasonOK means it could.
const (
// ReasonOK means the ability was (or can be) activated.
ReasonOK Reason = iota
// ReasonUnknown means no ability in the set has the ID.
ReasonUnknown
// ReasonBusy means an ability is already casting or channeling.
ReasonBusy
// ReasonCooldown means the ability's cooldown is running.
ReasonCooldown
// ReasonNoCharges means every charge of the ability is spent.
ReasonNoCharges
// ReasonCondition means one of the ability's conditions does not hold.
ReasonCondition
// ReasonCost means a resource the ability costs is short.
ReasonCost
)type Resources interface {
// Amount returns how much of resource is available.
Amount(resource string) float64
// Spend takes amount of resource away.
Spend(resource string, amount float64)
}Resources holds what abilities spend. A Caster checks Amount before it starts an ability and again before it spends, and calls Spend only after every cost of the use is affordable.
type Set struct {
// Version is the schema version; it must equal CurrentVersion (1).
Version int `yaml:"version"`
// Abilities are the set's abilities. Their order is the order a Caster advances them in, and the order it tries abilities that share an action.
Abilities []Def `yaml:"abilities"`
}Set is the root of a versioned YAML ability set: the abilities one kind of character, unit or item can use.
func Parse(data []byte) (*Set, error)Parse decodes a YAML ability set and validates it. Unknown fields, duplicate keys and trailing YAML documents are refused.
type State struct {
// Rate is the Caster's steps a second.
Rate int `json:"rate" yaml:"rate"`
// Step is the Caster's step count.
Step uint64 `json:"step" yaml:"step"`
// Abilities holds each ability's charges and timers, in set order.
Abilities []AbilityState `json:"abilities" yaml:"abilities"`
// Active is the ability casting or channeling, or nil when none is.
Active *ActiveState `json:"active,omitempty" yaml:"active,omitempty"`
}State is a Caster's runtime state at the end of a step, for save slots, rollback netcode and replays. It holds step counts, not durations, so a restored Caster continues on exactly the same steps.
It encodes as JSON or YAML with the field names below. Restore refuses a State taken from a Caster with a different rate or ability set.
type Status struct {
// Charges is how many uses are stored now, and MaxCharges the most it stores.
Charges, MaxCharges int
// Cooldown is how many steps of cooldown are left, out of CooldownTotal for a full cooldown.
Cooldown, CooldownTotal int
// Recharge is how many steps are left until the next charge comes back, out of RechargeTotal for one charge; 0 when no charge is spent.
Recharge, RechargeTotal int
// Phase is PhaseCasting or PhaseChanneling while the ability is the active one, and PhaseIdle otherwise.
Phase Phase
// Elapsed is how many steps of Phase have run, out of PhaseTotal; both are 0 while idle.
Elapsed, PhaseTotal int
}Status is an ability's state at the current step. Times are in the Caster's steps; Caster.Duration turns them into game time for display.
func (s Status) Ready() boolReady reports whether the ability is idle with a charge and no cooldown. It does not check conditions, costs or whether another ability is busy; Caster.CanActivate does.
type Trigger stringTrigger says which input edge of an ability's action tries to activate it.
const (
// TriggerPress tries to activate the ability on the step its action is first pressed. It is the default when Def.Trigger is empty.
TriggerPress Trigger = "press"
// TriggerHold tries to activate the ability on every step its action is held, and cancels its cast or channel on the step the action is no longer held.
TriggerHold Trigger = "hold"
)