package fighting
import "github.com/nsgo-dev/game/pkg/fighting"Overview
Package fighting buffers per-step fighting-game input and recognizes motion inputs (quarter circles, dragon punches, charges, double taps), button presses and combos from YAML move sets.
Directions use numpad notation: 5 is neutral, 6 is forward, 4 is back, 2 is down and 8 is up, with the diagonals on 1, 3, 7 and 9. A Recognizer samples one step at a time from any Source, such as *input.Actions or a *replay.Player, mirrors the direction when the character faces left, and reports the moves and combos completed on that step.
Index
- Constants
- func Encode(set *MoveSet) ([]byte, error)
- type Buffer
- func NewBuffer(capacity int) *Buffer
- func (b *Buffer) At(step int) (Frame, bool)
- func (b *Buffer) Cap() int
- func (b *Buffer) Latest() (Frame, bool)
- func (b *Buffer) Len() int
- func (b *Buffer) Oldest() int
- func (b *Buffer) Push(raw Direction, held uint32, facing Facing) Frame
- func (b *Buffer) Reset()
- func (b *Buffer) Steps() int
- type Charge
- type Combo
- type Direction
- type Facing
- type Frame
- type Input
- type Match
- type Move
- type MoveSet
- type Recognizer
- func NewRecognizer(set *MoveSet) (*Recognizer, error)
- func (r *Recognizer) AppendState(dst []byte) []byte
- func (r *Recognizer) Buffer() *Buffer
- func (r *Recognizer) Buttons() []string
- func (r *Recognizer) Direction(src Source) Direction
- func (r *Recognizer) Feed(raw Direction, held uint32, facing Facing) Result
- func (r *Recognizer) Held(src Source) uint32
- func (r *Recognizer) LoadState(state []byte) error
- func (r *Recognizer) Reset()
- func (r *Recognizer) Update(src Source, facing Facing) Result
- type Result
- type Source
Constants
const DefaultDeadzone = 0.5DefaultDeadzone is the axis magnitude at or above which an axis counts as pushed when Input.Deadzone is zero.
const FormatVersion = 1FormatVersion is the move set schema version written by Encode and required by Parse.
const MaxButtons = 32MaxButtons is the largest number of distinct button actions a move set may name.
const MaxSteps = 600MaxSteps bounds every step count in a move set (windows, buffers, charge times and combo gaps) to ten seconds at 60 steps per second, so a document cannot make a Recognizer allocate an unbounded history.
Functions
func Encode(set *MoveSet) ([]byte, error)Encode validates set and serializes it as deterministic 2-space YAML with fields in schema order, so Parse followed by Encode reproduces Encode's output byte for byte.
Types
type Buffer struct {
// contains filtered or unexported fields
}Buffer is a fixed-capacity ring of the most recent Frames, one per step.
Push allocates nothing, so a Buffer can sit in a fixed-step update loop. A Buffer is not safe for concurrent use.
func NewBuffer(capacity int) *BufferNewBuffer returns an empty Buffer that keeps the last capacity frames; a capacity below 1 keeps one frame.
func (b *Buffer) At(step int) (Frame, bool)At returns the frame for step and whether it is still held.
func (b *Buffer) Latest() (Frame, bool)Latest returns the most recent frame and whether there is one.
func (b *Buffer) Len() intLen returns how many frames the buffer currently holds.
func (b *Buffer) Oldest() intOldest returns the Step of the oldest frame still held, or Steps() when the buffer is empty.
func (b *Buffer) Push(raw Direction, held uint32, facing Facing) FramePush records the next step's absolute direction, held buttons and facing, derives Dir and Pressed, and returns the stored frame. An invalid direction is recorded as Neutral.
func (b *Buffer) Reset()Reset empties the buffer and restarts step numbering at zero.
func (b *Buffer) Steps() intSteps returns how many frames have been pushed since the buffer was created or last reset; the latest frame's Step is Steps()-1.
type Charge struct {
// Dirs is a string of numpad digits any of which counts as holding the charge, such as "147" for any back direction.
Dirs string `yaml:"dirs"`
// Steps is the least number of consecutive steps the charge must be held.
Steps int `yaml:"steps"`
// Grace is the most steps allowed between the end of the charge and the first motion entry, beyond the step that immediately follows it.
Grace int `yaml:"grace,omitempty"`
}Charge is a direction held for a number of consecutive steps before a motion starts.
type Combo struct {
// Name identifies the combo in results; it must be unique across moves and combos.
Name string `yaml:"name"`
// Sequence lists at least two move names in order.
Sequence []string `yaml:"sequence"`
// Gap is the most steps between consecutive moves of the sequence, at least 1.
Gap int `yaml:"gap"`
}Combo is a sequence of moves where each move follows the previous one within Gap steps.
type Direction uint8Direction is a stick or pad direction in numpad notation, from 1 (down-back) to 9 (up-forward), with 5 for neutral. The zero value is invalid; Neutral is the resting direction.
const (
DownBack Direction = 1
Down Direction = 2
DownForward Direction = 3
Back Direction = 4
Neutral Direction = 5
Forward Direction = 6
UpBack Direction = 7
Up Direction = 8
UpForward Direction = 9
)Numpad directions relative to a character facing right, so Back is left and Forward is right.
func DirectionOf(x, y int) DirectionDirectionOf returns the direction for a horizontal sign x and a vertical sign y, where x > 0 is right, x < 0 is left, y > 0 is up and y < 0 is down; zero is centered on that axis.
func (d Direction) Mirror() DirectionMirror returns d flipped horizontally (4 and 6, 1 and 3, 7 and 9 swap). It converts between absolute directions and directions relative to a character facing left. An invalid direction is returned unchanged.
func (d Direction) String() stringString returns the numpad digit for d, or "?" for an invalid direction.
func (d Direction) Valid() boolValid reports whether d is one of the nine numpad directions.
func (d Direction) X() intX returns -1 when d points back (left), 1 when it points forward (right) and 0 otherwise, including for an invalid direction.
func (d Direction) Y() intY returns -1 when d points down, 1 when it points up and 0 otherwise, including for an invalid direction.
type Facing uint8Facing is the side a character faces. The zero value, FaceRight, leaves directions unchanged; FaceLeft mirrors them so 6 always means toward the opponent.
const (
// FaceRight means forward is right: absolute and relative directions are the same.
FaceRight Facing = iota
// FaceLeft means forward is left: directions are mirrored before matching.
FaceLeft
)func (f Facing) Relative(d Direction) DirectionRelative returns the absolute direction d as seen by a character with facing f.
type Frame struct {
// Step is the zero-based index of the step since the buffer was created or last reset.
Step int
// Raw is the absolute direction, with 4 meaning left and 6 meaning right.
Raw Direction
// Dir is Raw relative to Facing, with 4 meaning back and 6 meaning forward. Moves match against Dir.
Dir Direction
// Facing is the side the character faced on this step.
Facing Facing
// Held has bit i set while button i is held.
Held uint32
// Pressed has bit i set when button i is held on this step but was not held on the previous one.
Pressed uint32
}Frame is the input sampled on one step.
type Input struct {
// Up, Down, Left and Right are digital action names. Pressing both opposite actions cancels that axis (neutral SOCD).
Up string `yaml:"up,omitempty"`
Down string `yaml:"down,omitempty"`
Left string `yaml:"left,omitempty"`
Right string `yaml:"right,omitempty"`
// AxisX is an analog axis name whose positive values point right.
AxisX string `yaml:"axisX,omitempty"`
// AxisY is an analog axis name whose positive values point down, as in screen coordinates and most gamepads; set YUp when positive values point up.
AxisY string `yaml:"axisY,omitempty"`
// YUp makes positive AxisY values point up.
YUp bool `yaml:"yUp,omitempty"`
// Deadzone is the magnitude in (0, 1] at or above which an axis counts as pushed; zero means DefaultDeadzone.
Deadzone float64 `yaml:"deadzone,omitempty"`
}Input names the actions and axes a Recognizer reads to build a direction each step. Actions and axes may be mixed; their contributions are summed per axis before the deadzone applies.
type Match struct {
// Name is the move's or combo's name.
Name string
// Index is the position of the move in MoveSet.Moves, or of the combo in MoveSet.Combos.
Index int
// Start is the step of the earliest input that formed the match: the first motion entry or chord button for a move, the first move's Step for a combo.
Start int
// Step is the step on which the match completed.
Step int
}Match is a move or combo completed on a step.
type Move struct {
// Name identifies the move in results and combos; it must be unique across moves and combos.
Name string `yaml:"name"`
// Motion is the ordered direction sequence. Each entry is a string of one or more distinct numpad digits, any of which satisfies that step, so "23" accepts down or down-forward.
Motion []string `yaml:"motion,omitempty"`
// Window is the most steps allowed from the first to the last motion entry. It must be at least len(Motion)-1, and is refused on a move with fewer than 2 motion entries.
Window int `yaml:"window,omitempty"`
// Charge requires a direction to be held before the motion starts.
Charge *Charge `yaml:"charge,omitempty"`
// Press lists button action names that finish the move. Without PressAll, pressing any one of them on the current step finishes it.
Press []string `yaml:"press,omitempty"`
// PressAll requires every Press button to be pressed within PressWindow steps, one of them on the current step.
PressAll bool `yaml:"pressAll,omitempty"`
// PressWindow is the most steps between the first and last button of a PressAll chord.
PressWindow int `yaml:"pressWindow,omitempty"`
// Buffer is the most steps the finishing press may come after the last motion entry. It needs both Motion and Press; a move without Press finishes on the first step its motion fits.
Buffer int `yaml:"buffer,omitempty"`
// Priority orders moves finished on the same step, highest first; ties keep definition order.
Priority int `yaml:"priority,omitempty"`
}Move is one recognizable input: a motion, a button press, or a motion finished by a button press.
Motion steps are matched on distinct, increasing steps of the facing-relative direction history, so ["6", "5", "6"] is a forward double tap and ["2", "3", "6"] a quarter circle forward. All step counts are inclusive. Inputs that completed a move cannot complete it again: its next completion needs a motion that starts after that step.
type MoveSet struct {
// Version is the schema version; it must equal FormatVersion.
Version int `yaml:"version"`
// Input names the actions and axes that make up the stick or pad.
Input Input `yaml:"input"`
// Moves are the motion inputs and button presses to recognize, in definition order.
Moves []Move `yaml:"moves"`
// Combos are sequences of moves performed with bounded gaps.
Combos []Combo `yaml:"combos,omitempty"`
}MoveSet is the root of a versioned YAML move set: how directions are read, the moves to recognize and the combos built from them.
func LoadFile(path string) (*MoveSet, error)LoadFile reads and parses the YAML move set at path.
func Parse(data []byte) (*MoveSet, error)Parse decodes a YAML move set and validates it. Unknown fields and trailing YAML documents are refused.
func (set *MoveSet) Buttons() []stringButtons returns the distinct button action names the moves press, in order of first appearance. Bit i of Frame.Held and of the held mask passed to Recognizer.Feed is Buttons()[i].
func (set *MoveSet) Lookback() intLookback returns how many past steps, including the current one, a Recognizer must keep to evaluate every move in set.
func (set *MoveSet) Validate() errorValidate checks set against the schema: the version, input names, at least one move, unique non-empty names, well-formed motions and charges, step counts within [0, MaxSteps], at most MaxButtons buttons and combos that reference existing moves.
type Recognizer struct {
// contains filtered or unexported fields
}Recognizer buffers per-step input and recognizes the moves and combos of a MoveSet.
Call Update (or Feed) exactly once per fixed step, after the Source has stepped. Recognition is deterministic: the same frames always give the same Results. For rollback, save the recognizer's state with AppendState alongside the rest of the simulation and restore it with LoadState before re-simulating. Update allocates nothing after construction. A Recognizer is not safe for concurrent use.
func NewRecognizer(set *MoveSet) (*Recognizer, error)NewRecognizer validates set and returns a Recognizer for it whose buffer holds set.Lookback() steps. Later changes to set do not affect the Recognizer.
func (r *Recognizer) AppendState(dst []byte) []byteAppendState appends the recognizer's complete state (the buffered frames, step count and the progress of every move and combo) to dst and returns the extended slice. The bytes are an in-memory snapshot for rollback, meant for LoadState on a Recognizer built from the same move set; they are not a file format.
func (r *Recognizer) Buffer() *BufferBuffer returns the recognizer's input history. Push frames through Feed or Update rather than directly, so combos stay in step.
func (r *Recognizer) Buttons() []stringButtons returns the button action names in bit order, as MoveSet.Buttons does.
func (r *Recognizer) Direction(src Source) DirectionDirection reads the absolute direction from src: digital actions add ±1 to their axis, analog axes add their value, and an axis whose total magnitude reaches the deadzone points that way.
func (r *Recognizer) Feed(raw Direction, held uint32, facing Facing) ResultFeed records one step from an absolute direction and a held button mask (bit i for Buttons()[i]), for inputs that arrive already decoded, such as rollback netcode, and returns what completed on that step.
func (r *Recognizer) Held(src Source) uint32Held reads the held button mask from src, bit i for Buttons()[i].
func (r *Recognizer) LoadState(state []byte) errorLoadState restores state written by AppendState, so the recognizer continues exactly as the one that wrote it would. It refuses state written for a different move set, or malformed state, and then leaves the recognizer unchanged.
func (r *Recognizer) Reset()Reset clears the input history and combo progress and restarts step numbering at zero.
func (r *Recognizer) Update(src Source, facing Facing) ResultUpdate samples src for the current step with the character facing facing and returns what completed on it.
type Result struct {
// Step is the step the result describes.
Step int
// Moves are the moves completed on Step, highest Priority first and in definition order among equal priorities. Moves[0] is the move a game would perform.
Moves []Match
// Combos are the combos whose last move completed on Step, in definition order.
Combos []Match
}Result lists what completed on one step.
Its slices are reused by the next Update, Feed or Reset; copy them to keep them longer.
type Source interface {
Pressed(name string) bool
Axis(name string) float64
}Source supplies the actions and axes a Recognizer reads each step. *input.Actions, *replay.Recorder and *replay.Player all satisfy it.