Documentation
¶
Overview ¶
Package battle is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package battle resolves deterministic, presentation-independent turn-based battles between a party and a troop.
Turns and gauge mode ¶
New copies the party's and the troop's Fighters into a Runner. In turn mode (Rules.TurnMode == "" or ModeTurn), each call to Resolve is one round: the game supplies a Command per acting fighter from either side (or calls ResolveParty to plan enemy AI actions automatically), and the Runner orders them by priority, then effective Agility (highest first), breaking ties by side (party before troop) and fighter index. Commands whose actor is out of range or already defeated, including one defeated earlier in the same turn, are skipped.
In time-progress mode (Rules.TurnMode == ModeGauge), Step(dt) advances each living fighter's ATB gauge on the fixed loop until GaugeMax, and Act (or Resolve) executes ready fighters one turn at a time.
Actions, formulas and scopes ¶
An Action's Scope picks its targets relative to the actor's side (self, one_enemy, all_enemies, random_enemies, one_ally, all_allies, one_dead_ally, all_dead_allies). Hostile actions evaluate pkg/expr formulas over a.* and b.* (or Power + Attack - Defense, at least 1), roll hit/evasion, element multipliers, damage variance, critical hits, drain/recover damage types, and rpgdata.SkillEffect entries (heal, add_state, remove_state, stat_change).
States, AI, troop events and rewards ¶
Status effects can be authored in versioned YAML (ParseStates/EncodeStates) or constructed as State values, supporting turn durations, stacking, per-turn HP/MP ticks, action restrictions (cannot_act, attack_enemy, attack_anyone, attack_ally), removal on damage chance or at battle end, and stats.Sheet modifiers.
Enemy AI actions (rpgdata.EnemyAction), troop battle events executing pkg/flow.Commands scripts, escape attempts, and end-of-battle rewards (experience through rpgdata.Progression, gold, and loot.Roller drops) all run deterministically on the Runner's random.Stream.
Determinism and snapshots ¶
Every roll is drawn from the Runner's random.Stream, so a seed and the same commands replay the same events on every platform. Snapshot captures fighters, turn state, gauges, active states, fired troop events, flow command state, loot pity state, and the stream's state; Restore puts them back for mid-battle saves and rollback.
Index ¶
- Constants
- func EncodeRules(r *Rules) ([]byte, error)
- func EncodeStates(f *StatesFile) ([]byte, error)
- func EvaluateFormula(formula string, a, b Fighter) (int, error)
- type Action
- type Command
- type Event
- type EventKind
- type Fighter
- type LevelUp
- type Ref
- type Restriction
- type Rewards
- type Rules
- type Runner
- func (r *Runner) Act(cmd Command) []Event
- func (r *Runner) CheckTroopEvents() []Event
- func (r *Runner) ClaimRewards() (Rewards, error)
- func (r *Runner) Done() bool
- func (r *Runner) Order(commands []Command) []Command
- func (r *Runner) PlanEnemyCommand(troopIndex int) (Command, bool)
- func (r *Runner) PlanTroopCommands() []Command
- func (r *Runner) Ready() []Ref
- func (r *Runner) Resolve(commands []Command) []Event
- func (r *Runner) ResolveParty(partyCommands []Command) []Event
- func (r *Runner) Restore(s Snapshot) error
- func (r *Runner) Snapshot() Snapshot
- func (r *Runner) Step(dt time.Duration) []Ref
- func (r *Runner) TryEscape() []Event
- func (r *Runner) ValidateCommand(cmd Command) error
- type Scope
- type Side
- type Snapshot
- type StatBuff
- type State
- type StateDef
- type StatesFile
- type TurnMode
Examples ¶
Constants ¶
const RulesSchemaComment = "# yaml-language-server: $schema=" + RulesSchemaURL
RulesSchemaComment is the optional yaml-language-server schema directive for battle rules YAML files.
const RulesSchemaURL = "https://nsgo.games/schemas/battle-rules.v1.json"
RulesSchemaURL is where the JSON Schema of version 1 battle rules files is published.
const RulesVersion = 1
RulesVersion is the schema version ParseRules reads and EncodeRules writes.
const SnapshotVersion = 1
SnapshotVersion is the schema version written by Runner.Snapshot and accepted by Runner.Restore.
const StatesSchemaComment = "# yaml-language-server: $schema=" + StatesSchemaURL
StatesSchemaComment is the optional yaml-language-server schema directive for battle states YAML files.
const StatesSchemaURL = "https://nsgo.games/schemas/battle-states.v1.json"
StatesSchemaURL is where the JSON Schema of version 1 battle states files is published.
const StatesVersion = 1
StatesVersion is the schema version ParseStates reads and EncodeStates writes.
Variables ¶
This section is empty.
Functions ¶
func EncodeRules ¶
EncodeRules validates r and encodes it deterministically as 2-space YAML with RulesSchemaComment on its first line.
func EncodeStates ¶
func EncodeStates(f *StatesFile) ([]byte, error)
EncodeStates validates f and encodes it deterministically as 2-space YAML with StatesSchemaComment on its first line.
func EvaluateFormula ¶
EvaluateFormula evaluates a deterministic pkg/expr battle formula against attacker a and defender b, truncating the result toward zero. It binds a.<stat> and b.<stat> for Fighter fields (hp, maxhp, max_hp, mp, maxmp, max_mp, tp, attack, defense, agility, hit_rate, evasion, crit_rate), Fighter.Stats entries, and Fighter.Sheet stats. It returns an error for an unknown value, a syntax error, a division by zero, or a result that is not a finite number in the int32 range.
Example ¶
EvaluateFormula computes an Action's Formula against attacker a and defender b, truncating the result to an int.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/battle"
)
func main() {
a := battle.Fighter{ID: "hero", Attack: 5}
b := battle.Fighter{ID: "slime", Defense: 1}
for _, formula := range []string{"a.attack * 2 - b.defense", "(a.attack + 1) / 4", "a.speed"} {
v, err := battle.EvaluateFormula(formula, a, b)
fmt.Println(formula, "=", v, err != nil)
}
}
Output: a.attack * 2 - b.defense = 9 false (a.attack + 1) / 4 = 1 false a.speed = 0 true
Types ¶
type Action ¶
type Action struct {
// ID identifies the action to the game.
ID string
// Scope picks the action's targets.
Scope Scope
// TargetCount is how many random enemies RandomEnemies hits (0 defaults to 1).
TargetCount int
// Priority raises or lowers the command's turn order ahead of Agility sorting.
Priority int
// Power is the action's base damage for hostile scopes and its healing otherwise.
Power int
// Cost is the MP the actor spends to use the action.
Cost int
// Costs holds multi-resource costs (such as mp, tp, hp) reusing pkg/ability.Cost.
Costs []ability.Cost
// Accuracy is the chance in (0, 1] that a hostile action hits each target; 0 means it always hits (unless HitType/HitFormula overrides).
Accuracy float64
// HitType is "certain", "physical", or "magical"; empty uses Accuracy/HitFormula directly.
HitType string
// DamageType is "", "none", "hp_damage", "mp_damage", "hp_recover", "mp_recover", "hp_drain", or "mp_drain".
DamageType string
// Element names the action's elemental affinity (e.g. "fire", "ice").
Element string
// Variance is the percentage damage/heal variance in [0, 100].
Variance int
// NoCrit disables critical hit rolls for this action even when Rules.CriticalChance > 0.
NoCrit bool
// CritFormula is an optional pkg/expr bool or probability [0, 1] formula over a.* and b.* that decides this action's critical hits, overriding Rules.CritFormula and Rules.CriticalChance.
CritFormula string
// HitFormula optionally overrides hit probability with a pkg/expr expression over a.* and b.*.
HitFormula string
// AddState applies a copy of this state to each living target after a successful hit.
AddState *State
// Formula optionally replaces Power for damage or healing using pkg/expr over a.<stat> and b.<stat>.
Formula string
// Effects are structured skill effects (heal, add_state, remove_state, stat_change) from pkg/rpgdata.
Effects []rpgdata.SkillEffect
// ItemID, when non-empty, consumes 1 unit of this item from Runner.Bag before resolving.
ItemID string
// Escape, when true, attempts to flee the battle for the party. Only a party fighter can escape: ValidateCommand refuses an escape command from a troop fighter, and Resolve and Act skip one.
Escape bool
// Guard, when true, applies a 1-turn "guard" state halving incoming HP damage until next turn.
Guard bool
}
Action is a skill, an attack, a guard, an escape attempt or an item use.
func ActionFromItem ¶
ActionFromItem builds a battle Action that consumes one unit of item from Runner.Bag. When scope is empty, it defaults to OneEnemy for damage items, OneDeadAlly for revive items, and OneAlly for healing or recovery items.
func ActionFromSkill ¶
ActionFromSkill builds a battle Action from an rpgdata.Skill record.
func EscapeAction ¶
func EscapeAction() Action
EscapeAction returns an Action that attempts to flee the battle.
func GuardAction ¶
func GuardAction() Action
GuardAction returns the standard defensive Action that halves incoming HP damage for one turn.
type Command ¶
type Command struct {
// Actor is the fighter using the action.
Actor Ref
// Action is the action used.
Action Action
// Target is the index of the target on the side the scope selects, for OneEnemy, OneAlly, and OneDeadAlly; other scopes ignore it.
Target int
// Priority optionally adjusts this command's turn order priority.
Priority int
}
Command is one fighter's choice for a turn.
type Event ¶
type Event struct {
// Kind is what happened.
Kind EventKind
// Actor is the fighter whose command caused the event; it is the zero Ref for Won, Lost, Escaped, and TroopEventTriggered.
Actor Ref
// Target is the fighter affected; it is the zero Ref for NoMP, Won, Lost, and Escaped.
Target Ref
// Action names the Action.ID for Acted events.
Action string
// Amount is the HP/MP lost or gained, for Damaged, Healed, Revived, and StateDamage.
Amount int
// Resource names the resource affected ("hp", "mp", "tp") when non-default.
Resource string
// Element names the element of a Damaged event, if any.
Element string
// Critical reports whether a Damaged event was a critical hit.
Critical bool
// State names the state involved in a state event.
State string
// Stat names the stat changed in a StatChanged event.
Stat string
// EventID and Script identify a triggered TroopEvent for TroopEventTriggered and TroopEventFailed events.
EventID string
Script string
// Error is the script error of a TroopEventFailed event.
Error string
}
Event is one thing that happened while a turn resolved.
type EventKind ¶
type EventKind string
EventKind names what happened in an Event.
const ( // Acted is emitted when a fighter begins executing an action (when Rules.EmitActionEvents is true). Acted EventKind = "acted" // Hit is emitted when an action connects with a target (when Rules.EmitActionEvents is true). Hit EventKind = "hit" // Missed is a hostile action missing or being evaded by its target. Missed EventKind = "missed" // Damaged is a target losing Amount HP (or MP when Resource is "mp"); Critical marks a critical hit. Damaged EventKind = "damaged" // Healed is a target gaining Amount HP (or MP when Resource is "mp"). Healed EventKind = "healed" // Revived is a defeated fighter returning to life with HP > 0. Revived EventKind = "revived" // Defeated is a target falling to 0 HP. Defeated EventKind = "defeated" // NoMP is an actor lacking the MP or resource its action costs; the action does nothing. NoMP EventKind = "no_mp" // NoItem is an actor lacking the required item in Runner.Bag. NoItem EventKind = "no_item" // StateDamage is damage applied by a state at turn start. StateDamage EventKind = "state_damage" // StateAdded reports a state applied by an action or effect. StateAdded EventKind = "state_added" // StateRemoved reports a state removed by a skill, damage chance, or battle end. StateRemoved EventKind = "state_removed" // StateExpired reports a state whose turns reached zero. StateExpired EventKind = "state_expired" // StateBlocked reports a living actor that could not act because of a state. StateBlocked EventKind = "state_blocked" // StatChanged reports a turn-based stat buff or debuff applied to a target. StatChanged EventKind = "stat_changed" // TroopEventTriggered reports a troop battle event matching and running its script. TroopEventTriggered EventKind = "troop_event" // TroopEventFailed reports a matched troop event whose script could not be started on Runner.FlowCommands or failed on its first update; Event.Error holds the error. TroopEventFailed EventKind = "troop_event_failed" // Escaped reports the party successfully fleeing the battle. Escaped EventKind = "escaped" // EscapeFailed reports a failed attempt to flee the battle. EscapeFailed EventKind = "escape_failed" // Won is the last living troop member falling. Won EventKind = "won" // Lost is the last living party member falling. Lost EventKind = "lost" )
type Fighter ¶
type Fighter struct {
// ID identifies the fighter to the game.
ID string `json:"id"`
// Name is the fighter's display name.
Name string `json:"name,omitempty"`
// HP is the fighter's current hit points; a fighter starts the battle alive when HP is above 0.
HP int `json:"hp"`
// MaxHP caps healing; 0 means healing is not capped.
MaxHP int `json:"max_hp,omitempty"`
// MP is the fighter's current magic points, spent by an Action's Cost.
MP int `json:"mp,omitempty"`
// MaxMP caps MP recovery; 0 means MP recovery is not capped.
MaxMP int `json:"max_mp,omitempty"`
// TP is the fighter's tactical points, spent by ability.Cost entries with resource "tp".
TP int `json:"tp,omitempty"`
// MaxTP caps TP; 0 defaults to 100 when TP is gained.
MaxTP int `json:"max_tp,omitempty"`
// Attack is added to the Power of the fighter's hostile actions.
Attack int `json:"attack,omitempty"`
// Defense is subtracted from the damage the fighter takes.
Defense int `json:"defense,omitempty"`
// Agility orders the fighter's command within a turn (highest first) and drives gauge fill rate.
Agility int `json:"agility,omitempty"`
// Alive reports whether the fighter can still act and be targeted.
Alive bool `json:"alive"`
// States are the ordered status effects currently affecting the fighter.
States []State `json:"states,omitempty"`
// Stats holds additional named stats (such as "magic", "luck") available in pkg/expr formulas.
Stats map[string]float64 `json:"stats,omitempty"`
// Elements maps elemental names (such as "fire", "ice") to damage multipliers (e.g. 2.0 weakness, 0.5 resist, 0.0 immune).
Elements map[string]float64 `json:"elements,omitempty"`
// HitRate is the fighter's base hit probability for physical/magical actions; 0 defaults to 1.0.
HitRate float64 `json:"hit_rate,omitempty"`
// Evasion is the fighter's evasion probability in [0, 1] against physical/magical actions.
Evasion float64 `json:"evasion,omitempty"`
// CritRate is added to Rules.CriticalChance for this fighter's attacks.
CritRate float64 `json:"crit_rate,omitempty"`
// Gauge is the current ATB gauge value in ModeGauge.
Gauge float64 `json:"gauge,omitempty"`
// GaugeReady reports whether Gauge reached GaugeMax in ModeGauge and the fighter is ready to act.
GaugeReady bool `json:"gauge_ready,omitempty"`
// Experience is the EXP reward granted when this enemy fighter is defeated.
Experience int `json:"experience,omitempty"`
// Gold is the gold reward granted when this enemy fighter is defeated.
Gold int `json:"gold,omitempty"`
// Drops names a loot table ID in a pkg/loot Library.
Drops string `json:"drops,omitempty"`
// AI holds weighted conditional actions for enemy fighters.
AI []rpgdata.EnemyAction `json:"ai,omitempty"`
// SkillIDs lists the skill IDs known by this fighter.
SkillIDs []string `json:"skill_ids,omitempty"`
// StatBuffs holds active turn-based stat modifiers applied by skill effects.
StatBuffs []StatBuff `json:"stat_buffs,omitempty"`
// Sheet optionally links a live pkg/stats.Sheet for base stats, traits, and state effect modifiers.
Sheet *stats.Sheet `json:"-"`
// Progression optionally links a pkg/rpgdata.Progression for awarding EXP and level-ups on victory.
Progression *rpgdata.Progression `json:"-"`
}
Fighter is one battler's stats, runtime pools, gauge, traits, AI and active status effects.
func FighterFromActor ¶
func FighterFromActor(db *rpgdata.Database, actorID string, prog *rpgdata.Progression, sheet *stats.Sheet) (Fighter, error)
FighterFromActor constructs a battle Fighter for actorID in db using prog (or a new actor Progression when nil) and optional live stats.Sheet.
func FighterFromEnemy ¶
FighterFromEnemy constructs a battle Fighter from an rpgdata.Enemy record.
func TroopFromRecord ¶
TroopFromRecord constructs the troop Fighter slice and cloned TroopEvent slice for troopID in db.
type LevelUp ¶
type LevelUp struct {
// Fighter names the party member that leveled up.
Fighter Ref
// FighterID is the fighter's ID.
FighterID string
// FromLevel is the level immediately before this level-up.
FromLevel int
// Level is the new level reached.
Level int
// SkillsLearned are the skill IDs learned at Level.
SkillsLearned []string
// Stats are the class base stat values at Level.
Stats map[string]int
}
LevelUp reports one party member gaining a level from battle experience.
type Ref ¶
type Ref struct {
// Side is the fighter's side.
Side Side
// Index is the fighter's index in its side's slice.
Index int
}
Ref names one fighter by side and index.
type Restriction ¶
type Restriction string
Restriction constrains or overrides what a fighter afflicted by a state does on its turn.
const ( // RestrictNone imposes no action restriction. RestrictNone Restriction = "none" // RestrictCannotAct prevents the fighter from acting on its turn (emitting StateBlocked). RestrictCannotAct Restriction = "cannot_act" // RestrictAttackEnemy forces the fighter to use a basic attack against a random living opponent. RestrictAttackEnemy Restriction = "attack_enemy" // RestrictAttackAnyone forces the fighter to use a basic attack against a random living battler on either side. RestrictAttackAnyone Restriction = "attack_anyone" // RestrictAttackAlly forces the fighter to use a basic attack against a random living ally. RestrictAttackAlly Restriction = "attack_ally" )
func (Restriction) Valid ¶
func (r Restriction) Valid() bool
Valid reports whether r is a known state restriction (empty means no restriction).
type Rewards ¶
type Rewards struct {
// Experience is the total EXP awarded by defeated troop members.
Experience int
// Gold is the total gold awarded by defeated troop members.
Gold int
// Drops are the items rolled from defeated troop members' Drops tables.
Drops []loot.Drop
// LevelUps lists each level gained by party members with an attached Progression.
LevelUps []LevelUp
}
Rewards summarizes the experience, gold, item drops, and level-ups granted by a won battle.
type Rules ¶
type Rules struct {
// Version is the schema version (RulesVersion = 1) when stored in YAML; zero in Go code defaults cleanly.
Version int `yaml:"version" json:"version,omitempty" schema:"required"`
// TurnMode selects "turn" (round-based agility order, default) or "gauge" (time progress stepped on the fixed loop).
TurnMode TurnMode `yaml:"turnMode,omitempty" json:"turn_mode,omitempty" schema:"enum=|turn|gauge"`
// GaugeMax is the gauge threshold at which a battler is ready to act in "gauge" mode; 0 defaults to 100.
GaugeMax float64 `yaml:"gaugeMax,omitempty" json:"gauge_max,omitempty" schema:"minimum=0"`
// GaugeBaseSpeed is added to agility when computing gauge fill rate per second in "gauge" mode; 0 defaults to 10.
GaugeBaseSpeed float64 `yaml:"gaugeBaseSpeed,omitempty" json:"gauge_base_speed,omitempty" schema:"minimum=0"`
// GaugeSpeedScale scales (agility + GaugeBaseSpeed) per second in "gauge" mode; 0 defaults to 1.
GaugeSpeedScale float64 `yaml:"gaugeSpeedScale,omitempty" json:"gauge_speed_scale,omitempty" schema:"minimum=0"`
// CriticalChance is the chance in [0, 1] that a hit is critical.
CriticalChance float64 `yaml:"criticalChance,omitempty" json:"critical_chance,omitempty" schema:"minimum=0,maximum=1"`
// CriticalMultiplier scales damage on a critical hit; 0 defaults to 2.
CriticalMultiplier float64 `yaml:"criticalMultiplier,omitempty" json:"critical_multiplier,omitempty" schema:"minimum=0"`
// HitFormula is an optional pkg/expr bool or probability [0, 1] formula over a.* and b.* for physical/magical hits.
HitFormula string `yaml:"hitFormula,omitempty" json:"hit_formula,omitempty"`
// EvasionFormula is an optional pkg/expr bool or probability [0, 1] formula over a.* and b.* for target evasion.
EvasionFormula string `yaml:"evasionFormula,omitempty" json:"evasion_formula,omitempty"`
// CritFormula is an optional pkg/expr bool or probability [0, 1] formula over a.* and b.* for critical hits.
CritFormula string `yaml:"critFormula,omitempty" json:"crit_formula,omitempty"`
// DisableEscape forbids fleeing from battle when true.
DisableEscape bool `yaml:"disableEscape,omitempty" json:"disable_escape,omitempty"`
// EscapeChance is the probability in [0, 1] that an escape attempt succeeds when EscapeFormula is empty; 0 defaults to 0.5.
EscapeChance float64 `yaml:"escapeChance,omitempty" json:"escape_chance,omitempty" schema:"minimum=0,maximum=1"`
// EscapeFormula is an optional pkg/expr bool or probability [0, 1] formula using party.agility, troop.agility, party.hp, troop.hp, party.count, troop.count, and turn.
EscapeFormula string `yaml:"escapeFormula,omitempty" json:"escape_formula,omitempty"`
// ElementChart maps attacker element -> target element -> damage multiplier (for example fire -> ice -> 1.5).
ElementChart map[string]map[string]float64 `yaml:"elementChart,omitempty" json:"element_chart,omitempty"`
// EmitActionEvents, when true, emits Acted and Hit lifecycle events in addition to Damaged/Healed/Missed.
EmitActionEvents bool `yaml:"emitActionEvents,omitempty" json:"emit_action_events,omitempty"`
}
Rules are the battle-wide tuning values and optional YAML-authored battle configuration.
func ParseRules ¶
ParseRules decodes and validates a battle rules YAML file. It refuses empty input, unknown fields, trailing documents, unsupported versions, invalid expressions and out-of-range numbers, returning a *loaderr.Error pointing at the field and line.
type Runner ¶
type Runner struct {
// Party is the player's fighters.
Party []Fighter
// Troop is the enemy fighters.
Troop []Fighter
// Rules are the battle's tuning values.
Rules Rules
// RNG is the stream every roll is drawn from.
RNG *random.Stream
// Turn counts the turns resolved so far.
Turn int
// Elapsed tracks accumulated simulation time in ModeGauge.
Elapsed time.Duration
// Won reports whether the troop has been defeated.
Won bool
// Lost reports whether the party has been defeated.
Lost bool
// Escaped reports whether the party successfully fled the battle.
Escaped bool
// StateCatalog optionally resolves state IDs referenced by skill effects.
StateCatalog *StatesFile
// StatsFile optionally resolves stats.Effect names referenced by StateDef.Effect.
StatsFile *stats.File
// Database optionally provides skill and enemy records for AI planning and helpers.
Database *rpgdata.Database
// TroopEvents lists conditional battle scripts checked during combat.
TroopEvents []rpgdata.TroopEvent
// FiredTroopEvents records IDs of troop events that have already fired.
FiredTroopEvents map[string]bool
// FlowCommands optionally runs troop event command lists from pkg/flow.
FlowCommands *flow.Commands
// OnTroopEvent is optionally called whenever a troop event fires.
OnTroopEvent func(rpgdata.TroopEvent)
// Bag optionally provides party inventory for item actions.
Bag *inventory.Container
// LootRoller optionally rolls enemy Drops tables when claiming victory rewards.
LootRoller *loot.Roller
// LootLibrary optionally supplies drop tables if LootRoller is nil.
LootLibrary *loot.Library
// RewardsClaimed tracks whether ClaimRewards has already granted victory rewards.
RewardsClaimed bool
// contains filtered or unexported fields
}
Runner holds a battle's state and resolves its turns.
func New ¶
New returns a Runner over copies of party and troop, marking each fighter alive when its HP is above 0. A nil rng is replaced with random.New(0).
func (*Runner) Act ¶
Act executes one ready fighter's command in ModeGauge, ticking only that fighter's states and resetting its gauge. Returns nil if the battle has ended, the actor does not exist, is defeated, or is not ready.
func (*Runner) CheckTroopEvents ¶
CheckTroopEvents evaluates Runner.TroopEvents against the current turn, troop HP ratio, and active troop states, and returns a TroopEventTriggered event for each newly matched event. Each matching event fires at most once per turn (and at most once per battle when Once is true), starts its named command list on Runner.FlowCommands when present, and invokes Runner.OnTroopEvent.
Runner.FlowCommands runs one list at a time: while a list is running (including one paused on a say or a choice), a matching event that has a script is left unfired and is checked again on a later call, so it never cancels the running list. When its list cannot be started (for example, an unknown list name), the event is marked as fired and reported as a TroopEventFailed event carrying the error instead of TroopEventTriggered, and OnTroopEvent is not called; when the list starts but its first update fails, a TroopEventFailed event follows the TroopEventTriggered one.
func (*Runner) ClaimRewards ¶
ClaimRewards computes and grants victory rewards once when Runner.Won is true. It sums Experience and Gold across defeated troop members, rolls each enemy's Drops table via Runner.LootRoller (or a temporary loot.Roller over Runner.LootLibrary and Runner.RNG), and awards Experience to living party members that have an attached Progression. Subsequent calls after RewardsClaimed becomes true return zero Rewards and nil error.
ClaimRewards is all or nothing: it checks every Drops table name before rolling, and when awarding experience fails for any member it rolls back the members already awarded (progression, sheet and learned skills) and the loot stream and pity counters, so on an error nothing has changed and the call can be retried.
func (*Runner) Order ¶
Order returns the commands whose actor exists, sorted into the order Resolve runs them: highest priority (Command.Priority + Action.Priority) first, then highest effective Agility, then PartySide before TroopSide, then lowest fighter index.
func (*Runner) PlanEnemyCommand ¶
PlanEnemyCommand chooses a deterministic command for the living troop member at troopIndex using its AI action list, Runner.Database skill definitions, and Runner.RNG. When no AI action is eligible or affordable, it falls back to a basic attack against a random living party member. It returns false when the battle has ended, troopIndex is invalid/defeated, or no valid target exists.
func (*Runner) PlanTroopCommands ¶
PlanTroopCommands plans deterministic AI commands for every living troop member in index order.
func (*Runner) Ready ¶
Ready returns all living fighters whose ATB gauge is currently ready, ordered by Agility, side, and index.
func (*Runner) Resolve ¶
Resolve runs one turn of commands and returns its events. In ModeGauge it executes commands for ready fighters. It returns nil once the battle is won, lost, or escaped.
Example ¶
Resolve runs one turn: the faster hero acts first whatever the order of the commands, and the turn stops as soon as the troop falls.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/battle"
"github.com/nsgo-dev/game/pkg/random"
)
// newDuel returns a hero against a slime. Accuracy 0 always hits and a CriticalChance of 0 never crits, so the fight draws no random numbers.
func newDuel() (*battle.Runner, []battle.Command) {
party := []battle.Fighter{{ID: "hero", HP: 30, MaxHP: 30, Attack: 5, Agility: 10}}
troop := []battle.Fighter{{ID: "slime", HP: 12, Attack: 2, Defense: 1, Agility: 3}}
r := battle.New(party, troop, battle.Rules{}, random.New(42))
attack := battle.Action{ID: "attack", Scope: battle.OneEnemy, Power: 4}
commands := []battle.Command{
{Actor: battle.Ref{Side: battle.TroopSide}, Action: attack},
{Actor: battle.Ref{Side: battle.PartySide}, Action: attack},
}
return r, commands
}
func main() {
r, commands := newDuel()
for !r.Won && !r.Lost {
for _, e := range r.Resolve(commands) {
fmt.Println("turn", r.Turn, e.Kind, e.Amount)
}
}
fmt.Println("hero hp", r.Party[0].HP, "won", r.Won)
}
Output: turn 1 damaged 8 turn 1 damaged 6 turn 2 damaged 4 turn 2 defeated 0 turn 2 won 0 hero hp 24 won true
func (*Runner) ResolveParty ¶
ResolveParty executes partyCommands while automatically planning AI commands for living troop members that do not already have a command in partyCommands. In ModeGauge it acts for ready fighters.
func (*Runner) Restore ¶
Restore replaces r's mutable state with a copy of s. It returns an error for a nil Runner, a Runner without a stream, or an unsupported snapshot version.
func (*Runner) Snapshot ¶
Snapshot returns a copy of r's mutable state.
Example ¶
Snapshot copies a battle mid-fight and Restore rolls it back, random stream included.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/battle"
"github.com/nsgo-dev/game/pkg/random"
)
// newDuel returns a hero against a slime. Accuracy 0 always hits and a CriticalChance of 0 never crits, so the fight draws no random numbers.
func newDuel() (*battle.Runner, []battle.Command) {
party := []battle.Fighter{{ID: "hero", HP: 30, MaxHP: 30, Attack: 5, Agility: 10}}
troop := []battle.Fighter{{ID: "slime", HP: 12, Attack: 2, Defense: 1, Agility: 3}}
r := battle.New(party, troop, battle.Rules{}, random.New(42))
attack := battle.Action{ID: "attack", Scope: battle.OneEnemy, Power: 4}
commands := []battle.Command{
{Actor: battle.Ref{Side: battle.TroopSide}, Action: attack},
{Actor: battle.Ref{Side: battle.PartySide}, Action: attack},
}
return r, commands
}
func main() {
r, commands := newDuel()
snap := r.Snapshot()
r.Resolve(commands)
fmt.Println("after turn", r.Turn, "slime hp", r.Troop[0].HP)
if err := r.Restore(snap); err != nil {
fmt.Println(err)
return
}
fmt.Println("restored turn", r.Turn, "slime hp", r.Troop[0].HP)
}
Output: after turn 1 slime hp 4 restored turn 0 slime hp 12
func (*Runner) Step ¶
Step advances ATB gauges by dt in ModeGauge and returns the refs of newly ready fighters in deterministic order. Returns nil when the battle is done or Rules.TurnMode is not ModeGauge.
func (*Runner) TryEscape ¶
TryEscape attempts to flee the battle. On success, Escaped is set to true, battle-end states are cleared, and Escaped is emitted.
func (*Runner) ValidateCommand ¶
ValidateCommand checks that cmd's actor exists and can target according to cmd.Action.Scope.
type Scope ¶
type Scope string
Scope is which fighters an Action affects, relative to its actor's side.
const ( // Self targets the actor. Self Scope = "self" // OneEnemy targets the living opponent at Command.Target. OneEnemy Scope = "one_enemy" // AllEnemies targets every living opponent. AllEnemies Scope = "all_enemies" // RandomEnemies targets Action.TargetCount randomly chosen living opponents. RandomEnemies Scope = "random_enemies" // OneAlly targets the living ally at Command.Target, which may be the actor. OneAlly Scope = "one_ally" // AllAllies targets every living ally, the actor included. AllAllies Scope = "all_allies" // OneDeadAlly targets the defeated ally at Command.Target (for revive skills/items). OneDeadAlly Scope = "one_dead_ally" // AllDeadAllies targets every defeated ally. AllDeadAllies Scope = "all_dead_allies" )
type Snapshot ¶
type Snapshot struct {
// Version is SnapshotVersion (1).
Version int `json:"version,omitempty" yaml:"version,omitempty"`
// Party is the party's fighters.
Party []Fighter `json:"party" yaml:"party"`
// Troop is the troop's fighters.
Troop []Fighter `json:"troop" yaml:"troop"`
// Turn is the number of turns resolved.
Turn int `json:"turn" yaml:"turn"`
// Elapsed is the accumulated ATB time in ModeGauge.
Elapsed time.Duration `json:"elapsed,omitempty" yaml:"elapsed,omitempty"`
// Won reports whether the battle was won.
Won bool `json:"won,omitempty" yaml:"won,omitempty"`
// Lost reports whether the battle was lost.
Lost bool `json:"lost,omitempty" yaml:"lost,omitempty"`
// Escaped reports whether the party escaped.
Escaped bool `json:"escaped,omitempty" yaml:"escaped,omitempty"`
// RewardsClaimed reports whether victory rewards have been claimed.
RewardsClaimed bool `json:"rewards_claimed,omitempty" yaml:"rewards_claimed,omitempty"`
// FiredTroopEvents lists IDs of fired troop events in sorted order.
FiredTroopEvents []string `json:"fired_troop_events,omitempty" yaml:"fired_troop_events,omitempty"`
// LastTroopEventTurn records the most recent turn number each troop event fired.
LastTroopEventTurn map[string]int `json:"last_troop_event_turn,omitempty" yaml:"last_troop_event_turn,omitempty"`
// PartySheets captures stats.Sheet state for party members that have a Sheet attached.
PartySheets []stats.Snapshot `json:"party_sheets,omitempty" yaml:"party_sheets,omitempty"`
// TroopSheets captures stats.Sheet state for troop members that have a Sheet attached.
TroopSheets []stats.Snapshot `json:"troop_sheets,omitempty" yaml:"troop_sheets,omitempty"`
// PartyProgressions captures rpgdata.Progression state for party members that have Progression attached.
PartyProgressions []rpgdata.ProgressionSnapshot `json:"party_progressions,omitempty" yaml:"party_progressions,omitempty"`
// Commands captures FlowCommands state when an attached command list is running.
Commands *flow.CommandsSnapshot `json:"commands,omitempty" yaml:"commands,omitempty"`
// LootState captures LootRoller pity counters when a LootRoller is attached.
LootState *loot.State `json:"loot_state,omitempty" yaml:"loot_state,omitempty"`
// RNG is the state of the battle's stream.
RNG random.State `json:"rng" yaml:"rng"`
}
Snapshot is a copy of a battle's mutable state, from Runner.Snapshot.
type StatBuff ¶
type StatBuff struct {
Stat string `json:"stat"`
Amount float64 `json:"amount,omitempty"`
Ratio float64 `json:"ratio,omitempty"`
Turns int `json:"turns"`
}
StatBuff is a temporary turn-based stat modifier applied by a skill effect.
type State ¶
type State struct {
ID string `json:"id"`
Turns int `json:"turns"`
Damage int `json:"damage,omitempty"`
CannotAct bool `json:"cannot_act,omitempty"`
Permanent bool `json:"permanent,omitempty"`
Restriction Restriction `json:"restriction,omitempty"`
Priority int `json:"priority,omitempty"`
Stacks int `json:"stacks,omitempty"`
MaxStacks int `json:"max_stacks,omitempty"`
HPTick int `json:"hp_tick,omitempty"`
MPTick int `json:"mp_tick,omitempty"`
HPRatioTick float64 `json:"hp_ratio_tick,omitempty"`
MPRatioTick float64 `json:"mp_ratio_tick,omitempty"`
RemoveOnDamageChance float64 `json:"remove_on_damage_chance,omitempty"`
RemoveAtBattleEnd bool `json:"remove_at_battle_end,omitempty"`
Effect string `json:"effect,omitempty"`
Modifiers []stats.Modifier `json:"modifiers,omitempty"`
}
State is a deterministic status effect instance on a Fighter. Turns counts remaining turns (unless Permanent is true), Damage/HPTick/MPTick apply each turn, and Restriction or CannotAct governs turn actions.
type StateDef ¶
type StateDef struct {
// ID uniquely identifies this state within the catalog.
ID string `yaml:"id" schema:"required"`
// Name is the display name or localization key.
Name string `yaml:"name,omitempty"`
// Restriction constrains or overrides what an affected battler does on its turn.
Restriction Restriction `yaml:"restriction,omitempty" schema:"enum=|none|cannot_act|attack_enemy|attack_anyone|attack_ally"`
// Priority resolves which active state's restriction wins when several apply (higher wins).
Priority int `yaml:"priority,omitempty"`
// Turns is the default duration in turns when applied; 0 means permanent until explicitly removed.
Turns int `yaml:"turns,omitempty" schema:"minimum=0"`
// MaxStacks is the maximum stack count on one battler; 0 or 1 means non-stacking (reapplying refreshes duration).
MaxStacks int `yaml:"maxStacks,omitempty" schema:"minimum=0"`
// HPTick is the flat HP change per turn (negative deals damage, positive heals).
HPTick int `yaml:"hpTick,omitempty"`
// MPTick is the flat MP change per turn (negative drains MP, positive restores MP).
MPTick int `yaml:"mpTick,omitempty"`
// HPRatioTick is a fractional change of MaxHP per turn (in [-1, 1], negative deals damage).
HPRatioTick float64 `yaml:"hpRatioTick,omitempty" schema:"minimum=-1,maximum=1"`
// MPRatioTick is a fractional change of MaxMP per turn (in [-1, 1], negative drains MP).
MPRatioTick float64 `yaml:"mpRatioTick,omitempty" schema:"minimum=-1,maximum=1"`
// RemoveOnDamageChance is the probability in [0, 1] that taking HP damage removes this state.
RemoveOnDamageChance float64 `yaml:"removeOnDamageChance,omitempty" schema:"minimum=0,maximum=1"`
// RemoveAtBattleEnd removes this state when the battle finishes.
RemoveAtBattleEnd bool `yaml:"removeAtBattleEnd,omitempty"`
// Effect names a gameplay effect in a stats.File applied to the battler's stats.Sheet while active.
Effect string `yaml:"effect,omitempty"`
// Modifiers are inline stat modifiers applied to the battler's stats.Sheet while this state is active.
Modifiers []stats.Modifier `yaml:"modifiers,omitempty"`
}
StateDef defines one status effect in YAML: its action restriction, duration, stacking limit, per-turn HP/MP ticks, removal rules and stats effects.
type StatesFile ¶
type StatesFile struct {
// Version is the schema version; it must equal StatesVersion (1).
Version int `yaml:"version" schema:"required"`
// States are the defined status effects.
States []StateDef `yaml:"states,omitempty"`
}
StatesFile is a versioned YAML catalog of status effect definitions read by ParseStates and written by EncodeStates.
func ParseStates ¶
func ParseStates(data []byte) (*StatesFile, error)
ParseStates decodes and validates a battle states YAML file. It refuses empty input, unknown fields, trailing documents and invalid state definitions, returning a *loaderr.Error pointing at the field and line.
func (*StatesFile) State ¶
func (f *StatesFile) State(id string) *StateDef
State returns the StateDef with id, or nil if not found.
func (*StatesFile) Validate ¶
func (f *StatesFile) Validate() error
Validate checks f's version and every state definition.
func (*StatesFile) ValidateRefs ¶
func (f *StatesFile) ValidateRefs(sf *stats.File) error
ValidateRefs checks that every state Effect name exists in sf when sf is non-nil.