Documentation
¶
Overview ¶
Package ability is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package ability runs gameplay abilities with costs, cooldowns, charges, cast and channel times, tag queries (requires, blockedBy, cancels), and gameplay effects applied to self or targets, activated by input actions and advanced one fixed game.Loop step at a time.
Ability Sets ¶
A Set is a versioned YAML file (version 1 or 2) 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. Version 1 uses string conditions; version 2 replaces conditions with gameplay tag queries (requires, blockedBy, cancels), ability tags, and declared stats effects.
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), version 1 conditions through a Condition function, version 2 tag queries through Caster.Sheet and Caster.Tags, and declared effects are applied through Caster.TryActivateOn and Caster.Effects when a cast completes.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/ability"
)
func main() {
fmt.Println(ability.CurrentVersion)
}
Output: 2
Index ¶
- Constants
- func Encode(set *Set) ([]byte, error)
- func Validate(set *Set) error
- type AbilityState
- type Actions
- type ActiveState
- type Caster
- func (c *Caster) Active() (id string, phase Phase, elapsed int, ok bool)
- func (c *Caster) ActiveCues(target string) []cues.Active
- func (c *Caster) CanActivate(id string) Reason
- func (c *Caster) Cancel() bool
- func (c *Caster) CueEvents(e Event, target string) []cues.Event
- func (c *Caster) Cues(id string) []string
- 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) SavePart() save.Part
- func (c *Caster) SetTarget(target *stats.Sheet)
- 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) TryActivateOn(id string, target *stats.Sheet) Reason
- func (c *Caster) Update(in Actions)
- type Cost
- type Def
- type EffectRef
- type EffectTarget
- type Event
- type EventKind
- type Phase
- type Pool
- type Reason
- type Resources
- type Set
- type State
- type Status
- type Trigger
Examples ¶
Constants ¶
const ( // MinVersion is the oldest ability set schema version this package reads and writes. MinVersion = 1 // CurrentVersion is the newest ability set schema version this package reads and writes. // Version 2 replaces string conditions with tag queries (requires, blockedBy, cancels), // adds ability tags, and lets abilities declare stats effects applied to self or target. CurrentVersion = 2 )
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 MaxRate = 1_000_000
MaxRate is the highest step rate NewCaster accepts, in steps a second.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AbilityState ¶
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 ¶
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 ¶
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 ¶
type Caster struct {
// Resources pays ability costs. When nil, an ability with costs cannot be activated.
Resources Resources
// Condition reports whether a version 1 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
// Sheet is the caster's own stats.Sheet. Version 2 tag queries (Requires, BlockedBy) read
// active tags from Sheet, and effects with to: self are applied to Sheet on activation.
Sheet *stats.Sheet
// Tags is an optional standalone tag container read alongside Sheet for version 2 tag queries.
Tags *tags.Container
// Effects is the stats.File holding named effects applied when a version 2 ability activates.
Effects *stats.File
// Source identifies this caster as the source passed to stats.Sheet.Apply (for stacking by: source).
// When empty, "ability:" + abilityID is used.
Source string
// OnEvent, when set, receives every Event in the order it happened. It may call the Caster's methods, including TryActivate, TryActivateOn 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)
// OnEffectApplied, when set, is called after each declared EffectRef of an activated ability is applied to its target sheet.
OnEffectApplied func(abilityID string, ref EffectRef, target *stats.Sheet, handle stats.EffectHandle, err error)
// 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 ¶
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 (*Caster) Active ¶
Active returns the ID, phase and elapsed steps of the ability casting or channeling now, or ok false when none is.
func (*Caster) ActiveCues ¶
ActiveCues returns the while-active cues of the ability currently casting or channeling on c, sorted deterministically by tag for cues.Player.Reconcile after rollback.
func (*Caster) CanActivate ¶
CanActivate 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, ReasonBlocked, ReasonCondition, ReasonCost. It changes nothing.
func (*Caster) Cancel ¶
Cancel 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 (*Caster) CueEvents ¶
CueEvents translates an ability Event emitted by c into deterministic cues.Event values for target.
Instant abilities fire EventExecuted on EventActivated; cast-time and channeling abilities also emit EventAdded while active and EventRemoved when they end, cancel or are interrupted; channel ticks emit EventExecuted keyed by (ability, tick, step) so rollback re-simulation does not double them.
func (*Caster) Cues ¶
Cues returns a copy of the gameplay cue tags declared on ability id, or nil if id is unknown or declares no cues.
func (*Caster) Duration ¶
Duration 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 (*Caster) Reset ¶
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 (*Caster) Restore ¶
Restore 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 (*Caster) SavePart ¶
SavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores c through save.Game. Loading validates the snapshot before mutating c, and resets charges, cooldowns and active casts to their initial state when loading an older slot that omits it.
func (*Caster) SetTarget ¶
SetTarget sets or updates the target stats.Sheet for the currently active ability cast (for example when restoring a mid-cast State during rollback).
func (*Caster) Snapshot ¶
Snapshot 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 (*Caster) Status ¶
Status returns the state of the ability id, or ok false when the set has no such ability.
func (*Caster) Steps ¶
Steps returns d in the Caster's whole steps, rounded up, as it counts every duration in its Set.
func (*Caster) TryActivate ¶
TryActivate 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, starting its cooldown and applying any to: self effects.
func (*Caster) TryActivateOn ¶
TryActivateOn activates the ability id targeting target (for effects with to: target) if CanActivate allows it, and returns the reason it did not otherwise. If another ability is active and id's Cancels query matches the active ability's Tags, the active ability is canceled first.
func (*Caster) Update ¶
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 blockedBy matches or a condition/requires 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 ¶
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 ¶
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 or TryActivateOn.
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 (version 1 only) 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. Version 2 replaces Conditions with Requires and BlockedBy tag queries.
Conditions []string `yaml:"conditions,omitempty,flow"`
// Tags (version 2) are gameplay tags describing this ability while it is active, matched by other abilities' BlockedBy and Cancels queries.
Tags []string `yaml:"tags,omitempty,flow"`
// Requires (version 2) is a tag query that must match the caster's tags to activate and keep casting or channeling this ability.
Requires *tags.QueryDoc `yaml:"requires,omitempty"`
// BlockedBy (version 2) is a tag query that blocks activation (and interrupts an active cast or channel) when it matches the caster's tags (or an active ability's tags).
BlockedBy *tags.QueryDoc `yaml:"blockedBy,omitempty"`
// Cancels (version 2) is a tag query matched against another active ability's Tags; when it matches and this ability is otherwise allowed, activating this ability cancels the active one.
Cancels *tags.QueryDoc `yaml:"cancels,omitempty"`
// Effects (version 2) are named stats effects applied to self or target when the ability completes its cast.
Effects []EffectRef `yaml:"effects,omitempty"`
// Cues (version 2) are gameplay cue tags (such as "cue.hit.fire") fired when this ability activates or while it casts or channels.
Cues []string `yaml:"cues,omitempty,flow"`
}
Def defines one ability: what using it costs, how often it can be used, how long it takes, when it is allowed and what gameplay effects it applies.
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 (*Def) EffectiveTrigger ¶
EffectiveTrigger returns Trigger, or TriggerPress when Trigger is empty.
func (*Def) MaxChargesOrOne ¶
MaxChargesOrOne returns Charges, or 1 when Charges is 0.
type EffectRef ¶
type EffectRef struct {
// Effect names the effect in Caster.Effects.
Effect string `yaml:"effect"`
// To is TargetSelf ("self") or TargetOther ("target").
To EffectTarget `yaml:"to"`
}
EffectRef names a stats.Effect that an ability applies when its cast completes.
type EffectTarget ¶
type EffectTarget string
EffectTarget says which stats.Sheet an ability applies an effect to when it activates.
const ( // TargetSelf applies the effect to the Caster's own stats.Sheet. TargetSelf EffectTarget = "self" // TargetOther applies the effect to the target stats.Sheet passed to Caster.TryActivateOn. TargetOther EffectTarget = "target" )
func (EffectTarget) Valid ¶
func (t EffectTarget) Valid() bool
Valid reports whether t is TargetSelf or TargetOther.
type Event ¶
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 ¶
type EventKind uint8
EventKind 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, its cooldown starts and its declared stats effects are applied. 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, a TriggerHold ability's action is released, or another ability's Cancels query cancels it. EventCanceled // EventInterrupted is sent when a cast or channel stops because a condition/requires no longer holds (ReasonCondition), blockedBy matched (ReasonBlocked), 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 )
type Phase ¶
type Phase string
Phase 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 ¶
Pool is a Resources kept in a map from resource name to amount. A missing resource has 0.
type Reason ¶
type Reason uint8
Reason 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 version 1 conditions or version 2 requires tag query does not hold. ReasonCondition // ReasonCost means a resource the ability costs is short. ReasonCost // ReasonBlocked means the ability's blockedBy tag query matched the caster's or active ability's tags. ReasonBlocked )
type Resources ¶
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 ¶
type Set struct {
// Version is the schema version, from MinVersion (1) to CurrentVersion (2).
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.
type State ¶
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 ¶
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.
type Trigger ¶
type Trigger string
Trigger 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" )