rpgdata

package
v0.4.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rpgdata is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package rpgdata reads and writes the versioned YAML database an RPG's records live in: classes with experience and stat curves, learned skills and traits, actors with starting equipment, skills with scopes, costs, formulas and effects, enemies with drops and AI action patterns, and troops with positions and battle events. Records may live in one combined YAML file (Parse/Encode) or one versioned YAML file per category (LoadDir/LoadFS/SaveDir), with every ID and cross-reference checked on load. Progression tracks a character's level and experience, updates a stats.Sheet, reports level-up events and learned skills, and supports Snapshot/Restore.

Index

Examples

Constants

View Source
const (
	ClassesFileName = "classes.yaml"
	ActorsFileName  = "actors.yaml"
	SkillsFileName  = "skills.yaml"
	EnemiesFileName = "enemies.yaml"
	TroopsFileName  = "troops.yaml"
)

Standard filenames for one-file-per-category RPG databases loaded by LoadDir and LoadFS.

View Source
const (
	// ScopeSelf targets the user.
	ScopeSelf = "self"
	// ScopeOneEnemy targets one enemy.
	ScopeOneEnemy = "one_enemy"
	// ScopeAllEnemies targets every living enemy.
	ScopeAllEnemies = "all_enemies"
	// ScopeOneAlly targets one ally.
	ScopeOneAlly = "one_ally"
	// ScopeAllAllies targets every living ally.
	ScopeAllAllies = "all_allies"
	// ScopeRandomEnemies targets a number of random enemies (written as "random_enemies: n" or with TargetCount).
	ScopeRandomEnemies = "random_enemies"
)

Skill target scopes.

View Source
const (
	// HitCertain never misses due to evasion.
	HitCertain = "certain"
	// HitPhysical tests physical hit and evasion.
	HitPhysical = "physical"
	// HitMagical tests magical hit and evasion.
	HitMagical = "magical"
)

Skill hit types.

View Source
const (
	// DamageNone deals no HP or MP damage (effects only).
	DamageNone = "none"
	// DamageHP deals HP damage.
	DamageHP = "hp_damage"
	// DamageMP deals MP damage.
	DamageMP = "mp_damage"
	// DamageHPRecover restores HP.
	DamageHPRecover = "hp_recover"
	// DamageMPRecover restores MP.
	DamageMPRecover = "mp_recover"
	// DamageHPDrain deals HP damage and restores the user's HP.
	DamageHPDrain = "hp_drain"
	// DamageMPDrain deals MP damage and restores the user's MP.
	DamageMPDrain = "mp_drain"
)

Skill damage types.

View Source
const (
	// EffectHeal restores a pool (HP by default, or Stat) by Amount and/or Ratio.
	EffectHeal = "heal"
	// EffectAddState applies State for Turns (0 for permanent/default duration).
	EffectAddState = "add_state"
	// EffectRemoveState clears State from the target.
	EffectRemoveState = "remove_state"
	// EffectStatChange modifies Stat by Amount and/or Ratio for Turns turns.
	EffectStatChange = "stat_change"
)

Skill effect kinds.

View Source
const (
	// ConditionAlways matches on every turn.
	ConditionAlways = "always"
	// ConditionTurn matches turns equal to TurnA + TurnB*k for k >= 0 (or exact TurnA when TurnB is 0).
	ConditionTurn = "turn"
	// ConditionHPRatio matches when current HP / max HP is in [MinRatio, MaxRatio].
	ConditionHPRatio = "hp_ratio"
	// ConditionState matches when State is active on the battler.
	ConditionState = "state"
)

ActionCondition and TroopEvent condition kinds.

View Source
const CurrentVersion = 1

CurrentVersion is the schema version Parse, Encode and the per-category file codecs read and write.

Variables

View Source
var ErrInvalidSnapshot = errors.New("rpgdata: invalid progression snapshot")

ErrInvalidSnapshot reports a ProgressionSnapshot that Progression.Restore refuses.

Functions

func Encode

func Encode(d *Database) ([]byte, error)

Encode validates d and writes it as YAML with 2-space indentation: fields in declaration order, lists in their given order and map keys sorted, so Parse then Encode reproduces an encoded file byte for byte.

func EncodeActors

func EncodeActors(f *ActorsFile) ([]byte, error)

EncodeActors validates f and encodes it deterministically as 2-space YAML.

func EncodeClasses

func EncodeClasses(f *ClassesFile) ([]byte, error)

EncodeClasses validates f and encodes it deterministically as 2-space YAML.

func EncodeEnemies

func EncodeEnemies(f *EnemiesFile) ([]byte, error)

EncodeEnemies validates f and encodes it deterministically as 2-space YAML.

func EncodeSkills

func EncodeSkills(f *SkillsFile) ([]byte, error)

EncodeSkills validates f and encodes it deterministically as 2-space YAML.

func EncodeTroops

func EncodeTroops(f *TroopsFile) ([]byte, error)

EncodeTroops validates f and encodes it deterministically as 2-space YAML.

func EvalFormulaMap

func EvalFormulaMap(formula string, a, b map[string]float64) (float64, error)

EvalFormulaMap evaluates a skill formula using pkg/expr with a.<stat> bound from map a and b.<stat> bound from map b.

func SaveDir

func SaveDir(dir string, d *Database) error

SaveDir validates d and writes deterministic per-category YAML files into dir for every non-empty category (classes.yaml, actors.yaml, skills.yaml, enemies.yaml, troops.yaml), creating dir if needed.

Types

type ActionCondition

type ActionCondition struct {
	// Kind is "always", "turn", "hp_ratio" or "state".
	Kind string `yaml:"kind"`
	// TurnA and TurnB match turn == TurnA + TurnB*k (k >= 0) for Kind "turn". TurnA is 1 or more; TurnB is 0 for an exact turn or positive for a repeating period.
	TurnA int `yaml:"turnA,omitempty"`
	TurnB int `yaml:"turnB,omitempty"`
	// MinRatio and MaxRatio define the inclusive HP ratio range [MinRatio, MaxRatio] in [0, 1] for Kind "hp_ratio".
	MinRatio float64 `yaml:"minRatio,omitempty"`
	MaxRatio float64 `yaml:"maxRatio,omitempty"`
	// State names the status state that must be active for Kind "state".
	State string `yaml:"state,omitempty"`
}

ActionCondition restricts when an enemy action or troop battle event is eligible.

func (*ActionCondition) Matches

func (c *ActionCondition) Matches(turn int, hpRatio float64, hasState func(string) bool) bool

Matches reports whether c holds for the given 1-based turn number, HP ratio in [0, 1], and active state predicate. A nil condition always matches.

type Actor

type Actor struct {
	// ID identifies the actor among the database's actors.
	ID string `yaml:"id"`
	// Name is the display name or its localization key.
	Name string `yaml:"name"`
	// Class names the actor's class.
	Class string `yaml:"class"`
	// Level is the initial level, 1 when 0, and at most the actor's effective max level when capped.
	Level int `yaml:"level,omitempty"`
	// MaxLevel optionally overrides the class's level cap, 0 to inherit the class's MaxLevel. When the class has a MaxLevel, an actor's MaxLevel may not exceed it.
	MaxLevel int `yaml:"maxLevel,omitempty"`
	// Equipment maps an inventory equipment slot name to an inventory item ID for the actor's starting gear.
	Equipment map[string]string `yaml:"equipment,omitempty"`
}

Actor is a playable character.

func (Actor) EffectiveMaxLevel

func (a Actor) EffectiveMaxLevel(c *Class) int

EffectiveMaxLevel returns the actor's MaxLevel if positive, otherwise c's MaxLevel (or 0 if uncapped).

type ActorsFile

type ActorsFile struct {
	Version int     `yaml:"version"`
	Actors  []Actor `yaml:"actors,omitempty"`
}

ActorsFile is the per-category YAML file holding actors (actors.yaml).

func ParseActors

func ParseActors(data []byte) (*ActorsFile, error)

ParseActors decodes and validates a standalone actors.yaml file. Cross-references to classes are checked when combined in a Database.

func (*ActorsFile) Validate

func (f *ActorsFile) Validate() error

Validate checks the version and actor-local rules of f.

type Class

type Class struct {
	// ID identifies the class among the database's classes.
	ID string `yaml:"id"`
	// Name is the display name or its localization key.
	Name string `yaml:"name,omitempty"`
	// MaxLevel is the highest level, or 0 for no cap.
	MaxLevel int `yaml:"maxLevel,omitempty"`
	// LevelXP scales the linear experience rule: going from level n to n+1 takes n × LevelXP experience. 0 means the class never levels up from experience unless ExpCurve is set.
	LevelXP int `yaml:"levelXP,omitempty"`
	// ExpCurve optionally replaces the linear LevelXP rule with a lookup table or a pkg/expr formula over "level". Mutually exclusive with LevelXP.
	ExpCurve *ExpCurve `yaml:"expCurve,omitempty"`
	// Stats maps a stat name to its base value at each level, the first entry being level 1; levels past the end keep the last value.
	Stats map[string][]int `yaml:"stats,omitempty"`
	// StatCurves maps a stat name to a numeric pkg/expr formula over "level" producing the stat's base value. A stat may not appear in both Stats and StatCurves.
	StatCurves map[string]string `yaml:"statCurves,omitempty"`
	// Skills are the skills the class learns and the level each is learned at.
	Skills []LearnedSkill `yaml:"skills,omitempty"`
	// Traits are names of passive effects defined in a stats.File.
	Traits []string `yaml:"traits,omitempty"`
}

Class is a class: its level cap, experience rule, stat curves, learned skills and passive traits.

func (Class) ExperienceForNext

func (c Class) ExperienceForNext(level int) int

ExperienceForNext returns the experience required to advance from level to level+1 according to c.ExpCurve (table or formula) or c.LevelXP, or 0 if capped or no experience rule is configured.

func (Class) SkillsLearnedAt

func (c Class) SkillsLearnedAt(level int) []string

SkillsLearnedAt returns the IDs of the skills the class learns on reaching level, in the order the class lists them.

func (Class) StatAt

func (c Class) StatAt(name string, level int) int

StatAt returns the class's value of the named stat at level: for Stats, the table entry for that level (clamped to [1, len]); for StatCurves, the evaluated pkg/expr formula rounded to the nearest integer (with level clamped to at least 1); and 0 for a stat the class has no curve for.

func (Class) StatNames

func (c Class) StatNames() []string

StatNames returns the sorted names of every stat defined in c.Stats and c.StatCurves.

func (Class) TotalExperienceFor

func (c Class) TotalExperienceFor(level int) int

TotalExperienceFor returns the cumulative experience required to reach level from level 1 (0 for level <= 1).

type ClassesFile

type ClassesFile struct {
	Version int     `yaml:"version"`
	Classes []Class `yaml:"classes,omitempty"`
}

ClassesFile is the per-category YAML file holding classes (classes.yaml).

func ParseClasses

func ParseClasses(data []byte) (*ClassesFile, error)

ParseClasses decodes and validates a standalone classes.yaml file. Cross-references to skills are checked when combined in a Database via LoadDir/LoadFS or Database.Validate.

func (*ClassesFile) Validate

func (f *ClassesFile) Validate() error

Validate checks the version and class-local rules of f.

type Database

type Database struct {
	// Version is the schema version, CurrentVersion.
	Version int `yaml:"version"`
	// Classes are the classes actors belong to.
	Classes []Class `yaml:"classes,omitempty"`
	// Actors are the playable characters.
	Actors []Actor `yaml:"actors,omitempty"`
	// Skills are the skills classes teach and enemies use.
	Skills []Skill `yaml:"skills,omitempty"`
	// Enemies are the foes troops are made of.
	Enemies []Enemy `yaml:"enemies,omitempty"`
	// Troops are the groups of enemies a battle starts with.
	Troops []Troop `yaml:"troops,omitempty"`
}

Database is one RPG database, either from a single file or combined from per-category files. IDs are unique within each category, and every reference names a record of the category it points at.

func LoadDir

func LoadDir(dir string) (*Database, error)

LoadDir reads per-category YAML files (classes.yaml, actors.yaml, skills.yaml, enemies.yaml, troops.yaml) from dir, merges them into a Database and validates all cross-references. Missing category files are treated as empty, but at least one category file must exist. Any error is returned as a *loaderr.Error pointing to the offending file, field path and line.

func LoadDirWithRefs

func LoadDirWithRefs(dir string, refs ExternalRefs) (*Database, error)

LoadDirWithRefs behaves like LoadDir and also checks cross-references against refs (stats traits, inventory items/slots, loot tables), locating errors to the originating category file and line.

func LoadFS

func LoadFS(fsys fs.FS, dir string) (*Database, error)

LoadFS reads per-category YAML files (classes.yaml, actors.yaml, skills.yaml, enemies.yaml, troops.yaml) from dir within fsys, merges them into a Database and validates all cross-references.

func LoadFSWithRefs

func LoadFSWithRefs(fsys fs.FS, dir string, refs ExternalRefs) (*Database, error)

LoadFSWithRefs behaves like LoadFS and also checks cross-references against refs, locating errors to the originating category file and line.

func Parse

func Parse(data []byte) (*Database, error)

Parse decodes and validates one database document. It refuses unknown fields, a version other than CurrentVersion, a trailing document and any record Validate refuses, returning a *loaderr.Error with the field and line of the problem.

Example

Parse checks every ID and cross-reference; an actor then levels up from the experience an enemy gives, learning its class's skills.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/rpgdata"
)

// meadow is a small database: one class with a level curve and two skills, an actor of that class and a troop of one enemy.
const meadow = `version: 1
classes:
  - id: warrior
    name: Warrior
    maxLevel: 5
    levelXP: 10
    stats:
      attack: [5, 7, 9]
    skills:
      - id: slash
        level: 1
      - id: power_strike
        level: 3
actors:
  - id: aria
    name: Aria
    class: warrior
skills:
  - id: slash
    name: Slash
    scope: one_enemy
    formula: a.attack * 2 - b.defense
  - id: power_strike
    name: Power Strike
    scope: one_enemy
    formula: a.attack * 3 - b.defense
    cost: 4
enemies:
  - id: slime
    name: Slime
    hp: 12
    experience: 35
troops:
  - id: slimes
    members:
      - enemy: slime
        x: 0
        y: 0
`

func main() {
	db, err := rpgdata.Parse([]byte(meadow))
	if err != nil {
		fmt.Println(err)
		return
	}
	actor := db.Actors[0]
	class := db.Class(actor.Class)
	p := rpgdata.NewProgression(actor.Level, class.MaxLevel, class.LevelXP)
	fmt.Println(actor.Name, "level", p.Level, "attack", class.StatAt("attack", p.Level), "skills", class.SkillsLearnedAt(1))
	for _, level := range p.AddExperience(db.Enemy("slime").Experience) {
		fmt.Println("reached level", level, "attack", class.StatAt("attack", level), "learned", class.SkillsLearnedAt(level))
	}
	fmt.Println("experience", p.Experience, "of", p.NeedForNext())
}
Output:
Aria level 1 attack 5 skills [slash]
reached level 2 attack 7 learned []
reached level 3 attack 9 learned [power_strike]
experience 5 of 30
Example (UnknownReference)

Parse refuses a database whose references name records that do not exist.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/rpgdata"
)

func main() {
	_, err := rpgdata.Parse([]byte("version: 1\nenemies:\n  - id: slime\n    name: Slime\n    hp: 12\ntroops:\n  - id: pair\n    members:\n      - enemy: bat\n        x: 0\n        y: 0\n"))
	fmt.Println("refused:", err != nil)
}
Output:
refused: true

func (*Database) Actor

func (d *Database) Actor(id string) *Actor

Actor returns the actor with the id, or nil when d has none. The pointer points into d.Actors and is invalidated when d.Actors changes.

func (*Database) Class

func (d *Database) Class(id string) *Class

Class returns the class with the id, or nil when d has none. The pointer points into d.Classes and is invalidated when d.Classes changes.

func (*Database) Enemy

func (d *Database) Enemy(id string) *Enemy

Enemy returns the enemy with the id, or nil when d has none. The pointer points into d.Enemies and is invalidated when d.Enemies changes.

func (*Database) Skill

func (d *Database) Skill(id string) *Skill

Skill returns the skill with the id, or nil when d has none. The pointer points into d.Skills and is invalidated when d.Skills changes.

func (*Database) Troop

func (d *Database) Troop(id string) *Troop

Troop returns the troop with the id, or nil when d has none. The pointer points into d.Troops and is invalidated when d.Troops changes.

func (*Database) Validate

func (d *Database) Validate() error

Validate checks the version, that IDs are non-empty and unique within each category, that numbers, scopes, curves, formulas and conditions are valid, and that every class skill, actor class, enemy action skill and troop member names a record that exists. Its errors are *loaderr.Error values naming the field at fault.

func (*Database) ValidateRefs

func (d *Database) ValidateRefs(refs ExternalRefs) error

ValidateRefs checks cross-file references from d to external catalogs in refs (stats traits, inventory starting equipment, and loot drop tables). Nil fields in refs are skipped.

type EnemiesFile

type EnemiesFile struct {
	Version int     `yaml:"version"`
	Enemies []Enemy `yaml:"enemies,omitempty"`
}

EnemiesFile is the per-category YAML file holding enemies (enemies.yaml).

func ParseEnemies

func ParseEnemies(data []byte) (*EnemiesFile, error)

ParseEnemies decodes and validates a standalone enemies.yaml file. Cross-references to skills are checked when combined in a Database.

func (*EnemiesFile) Validate

func (f *EnemiesFile) Validate() error

Validate checks the version and enemy-local rules of f.

type Enemy

type Enemy struct {
	// ID identifies the enemy among the database's enemies.
	ID string `yaml:"id"`
	// Name is the display name or its localization key.
	Name string `yaml:"name"`
	// HP is the enemy's hit points, 1 or more.
	HP int `yaml:"hp"`
	// Attack is the enemy's attack stat, 0 or more.
	Attack int `yaml:"attack,omitempty"`
	// Defense is the enemy's defense stat, 0 or more.
	Defense int `yaml:"defense,omitempty"`
	// Stats holds additional named enemy stats (such as "mp", "agility", "magic").
	Stats map[string]int `yaml:"stats,omitempty"`
	// Experience is the experience defeating it gives, 0 or more.
	Experience int `yaml:"experience,omitempty"`
	// Gold is the gold defeating it gives, 0 or more.
	Gold int `yaml:"gold,omitempty"`
	// Drops names a loot table ID in a pkg/loot Library.
	Drops string `yaml:"drops,omitempty"`
	// Traits are names of passive effects defined in a stats.File.
	Traits []string `yaml:"traits,omitempty"`
	// Actions are the enemy's battle AI action pattern entries, chosen by condition and weight.
	Actions []EnemyAction `yaml:"actions,omitempty"`
}

Enemy is a foe's record.

func (Enemy) Stat

func (e Enemy) Stat(name string) int

Stat returns the enemy's value for name, checking Stats first and falling back to the shorthand fields ("hp", "attack", "defense").

type EnemyAction

type EnemyAction struct {
	// Skill names a skill of the database.
	Skill string `yaml:"skill"`
	// Weight is the relative selection weight / rating, 1 or more.
	Weight int `yaml:"weight"`
	// Condition optionally restricts when this action is eligible. Nil means always eligible.
	Condition *ActionCondition `yaml:"condition,omitempty"`
}

EnemyAction is one weighted entry in an enemy's battle action pattern.

type ExpCurve

type ExpCurve struct {
	// Table lists the experience needed to go from level 1 to 2, level 2 to 3, and so on. Each entry must be 1 or more; levels past the end repeat the last entry.
	Table []int `yaml:"table,omitempty"`
	// Formula is a numeric pkg/expr expression over "level" (the current level n >= 1) returning the experience needed to reach level n+1.
	Formula string `yaml:"formula,omitempty"`
}

ExpCurve defines how much experience advancing from level n to n+1 requires, either as an explicit table or as a pkg/expr formula over "level".

type ExternalRefs

type ExternalRefs struct {
	// Stats, when non-nil, is checked for every class and enemy trait effect name.
	Stats *stats.File
	// Items, when non-nil, is checked for every actor starting equipment item ID.
	Items *inventory.Catalog
	// EquipSlots, when non-empty alongside Items, checks that every actor starting equipment slot name exists and matches the item's Equip kind.
	EquipSlots []inventory.EquipSlot
	// Loot, when non-nil, is checked for every enemy drops loot table ID.
	Loot *loot.Library
}

ExternalRefs holds optional catalogs from sibling packages checked by Database.ValidateRefs, LoadDirWithRefs and LoadFSWithRefs.

type LearnedSkill

type LearnedSkill struct {
	// ID names a skill of the database.
	ID string `yaml:"id"`
	// Level is the level the skill is learned at, 1 or more.
	Level int `yaml:"level"`
}

LearnedSkill is a skill a class learns on reaching a level.

type LevelUpEvent

type LevelUpEvent struct {
	// FromLevel is the level immediately before this level-up.
	FromLevel int
	// Level is the new level reached.
	Level int
	// SkillsLearned are the skill IDs the class learns at Level, in class declaration order.
	SkillsLearned []string
	// Stats are the class's base stat values at Level for every stat defined on the class.
	Stats map[string]int
}

LevelUpEvent reports one level gained during Progression.GainExperience.

type Progression

type Progression struct {
	// Level is the current level, 1 or more.
	Level int `yaml:"level"`
	// Experience is the experience gathered since reaching Level.
	Experience int `yaml:"experience"`
	// MaxLevel is the level cap, or 0 for none.
	MaxLevel int `yaml:"maxLevel"`
	// LevelXP scales the experience each level takes; 0 or less never levels up unless a class ExpCurve is attached.
	LevelXP int `yaml:"levelXP"`
	// contains filtered or unexported fields
}

Progression is a character's level and the experience gathered toward the next one. When created with NewProgression, going from level n to n+1 takes n × LevelXP experience. When created with NewClassProgression or NewActorProgression, it uses the class's ExpCurve (table or pkg/expr formula) or LevelXP, can update a stats.Sheet with class stat curves and traits, and reports LevelUpEvents with learned skills. At MaxLevel, when above 0, experience no longer levels up.

func NewActorProgression

func NewActorProgression(db *Database, actorID string) (*Progression, error)

NewActorProgression returns a Progression for the named actor in db, starting at the actor's initial Level (1 when 0) and capped by the actor's effective max level.

func NewClassProgression

func NewClassProgression(c *Class, level int) (*Progression, error)

NewClassProgression returns a Progression bound to class c at initial level (clamped to [1, c.MaxLevel] when capped). It compiles c.ExpCurve.Formula when present and returns an error if c is nil or its curve is invalid.

func NewProgression

func NewProgression(level, maxLevel, levelXP int) Progression

NewProgression returns a progression at level, raised to 1 and lowered to maxLevel when it has one, with no experience gathered.

func (*Progression) AddExperience

func (p *Progression) AddExperience(xp int) []int

AddExperience adds xp, levels up as many times as it pays for and returns each level reached, in order. Experience left over after the last level up stays toward the next one; at the level cap it keeps accumulating without effect. A nil progression or an xp of 0 or less changes nothing.

Example

At the level cap a Progression stops leveling and keeps the experience it gathers.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/rpgdata"
)

func main() {
	p := rpgdata.NewProgression(4, 5, 10)
	fmt.Println("levels", p.AddExperience(100))
	fmt.Println("level", p.Level, "experience", p.Experience, "need", p.NeedForNext())
}
Output:
levels [5]
level 5 experience 60 need 0

func (*Progression) ApplyToSheet

func (p *Progression) ApplyToSheet(sheet *stats.Sheet) error

ApplyToSheet sets sheet's base value for every stat defined by p's bound class (that also exists on sheet) to its value at p.Level. Stats not defined on sheet are skipped; a nil sheet or unbound progression does nothing.

func (*Progression) ApplyTraits

func (p *Progression) ApplyTraits(sheet *stats.Sheet, sf *stats.File, source string) error

ApplyTraits applies every trait effect named by p's bound class from sf onto sheet under the given source prefix (defaulting to "class:<id>" when source is empty).

func (*Progression) Class

func (p *Progression) Class() *Class

Class returns a copy of the class bound to p, or nil for a standalone progression.

func (*Progression) GainExperience

func (p *Progression) GainExperience(xp int, sheet *stats.Sheet) ([]LevelUpEvent, error)

GainExperience adds xp, levels up as many times as it pays for, updates sheet's base values for every stat the bound class defines (when both sheet and class are non-nil), and returns a LevelUpEvent for each level reached in order.

func (Progression) NeedForNext

func (p Progression) NeedForNext() int

NeedForNext returns the experience the next level takes in total, or 0 when the progression cannot level up any more.

func (*Progression) Restore

func (p *Progression) Restore(snap ProgressionSnapshot) error

Restore validates snap and restores p's level and experience state. On error p is left unchanged.

func (*Progression) RestoreAndApply

func (p *Progression) RestoreAndApply(snap ProgressionSnapshot, sheet *stats.Sheet) error

RestoreAndApply restores snap into p and, when sheet is non-nil and p is bound to a class, applies the restored level's stat base values to sheet.

func (*Progression) SkillsLearned

func (p *Progression) SkillsLearned() []string

SkillsLearned returns every skill ID learned by p's bound class at or below p.Level, in class declaration order without duplicates.

func (*Progression) Snapshot

func (p *Progression) Snapshot() ProgressionSnapshot

Snapshot captures p's runtime level and experience state as plain JSON/YAML-serializable data.

type ProgressionSnapshot

type ProgressionSnapshot struct {
	// ClassID is the ID of the class this progression was bound to, or empty for a standalone progression.
	ClassID string `json:"classId,omitempty" yaml:"classId,omitempty"`
	// Level is the current level, 1 or more.
	Level int `json:"level" yaml:"level"`
	// Experience is the experience gathered since reaching Level, 0 or more.
	Experience int `json:"experience" yaml:"experience"`
	// MaxLevel is the level cap, or 0 for none.
	MaxLevel int `json:"maxLevel,omitempty" yaml:"maxLevel,omitempty"`
	// LevelXP scales the linear experience rule when no ExpCurve is attached.
	LevelXP int `json:"levelXP,omitempty" yaml:"levelXP,omitempty"`
}

ProgressionSnapshot is a JSON- and YAML-serializable snapshot of a Progression's runtime state.

type Skill

type Skill struct {
	// ID identifies the skill among the database's skills.
	ID string `yaml:"id"`
	// Name is the display name or its localization key.
	Name string `yaml:"name"`
	// Scope is who the skill targets: self, one_enemy, all_enemies, one_ally, all_allies, or random_enemies (optionally written "random_enemies: n").
	Scope string `yaml:"scope"`
	// TargetCount is the number of random enemies targeted when Scope is "random_enemies" without an inline ": n" count.
	TargetCount int `yaml:"targetCount,omitempty"`
	// Formula is a numeric pkg/expr damage or healing formula over a.<stat> (user) and b.<stat> (target), such as "a.attack * 2 - b.defense".
	Formula string `yaml:"formula,omitempty"`
	// Cost is a shorthand MP cost, 0 or more. For multi-resource costs reusing ability.Cost, use Costs.
	Cost int `yaml:"cost,omitempty"`
	// Costs are the resources spent on use, reusing ability.Cost (each resource at most once, finite positive amount).
	Costs []ability.Cost `yaml:"costs,omitempty"`
	// HitType is "certain", "physical" or "magical"; empty defaults to game rules.
	HitType string `yaml:"hitType,omitempty"`
	// DamageType is "none", "hp_damage", "mp_damage", "hp_recover", "mp_recover", "hp_drain" or "mp_drain".
	DamageType string `yaml:"damageType,omitempty"`
	// Element names the skill's element, such as "fire" or "ice".
	Element string `yaml:"element,omitempty"`
	// Variance is the percentage damage variance in [0, 100].
	Variance int `yaml:"variance,omitempty"`
	// Critical reports whether the skill can deal a critical hit.
	Critical bool `yaml:"critical,omitempty"`
	// Effects are non-damage effects applied on hit (heal, add_state, remove_state, stat_change).
	Effects []SkillEffect `yaml:"effects,omitempty"`
}

Skill is a skill's record: target scope, resource costs, hit and damage rules, formula over a.* and b.* stats, and additional effects.

func (Skill) EffectiveCosts

func (s Skill) EffectiveCosts() []ability.Cost

EffectiveCosts returns s.Costs when non-empty, otherwise a single "mp" cost when s.Cost > 0, or nil when free.

func (Skill) EvalFormula

func (s Skill) EvalFormula(a, b *stats.Sheet) (float64, error)

EvalFormula evaluates s.Formula using pkg/expr with a.<stat> bound from caster a and b.<stat> bound from target b. Returns 0 and nil if s.Formula is empty.

func (Skill) ParseScope

func (s Skill) ParseScope() (kind string, count int, ok bool)

ParseScope parses s.Scope (and s.TargetCount) into its canonical scope kind and target count. For "random_enemies" (written either as "random_enemies: n" / "random_enemies:n" or with TargetCount > 0), it returns (ScopeRandomEnemies, n, true). For other valid scopes it returns (scope, 1, true).

type SkillEffect

type SkillEffect struct {
	// Kind is "heal", "add_state", "remove_state" or "stat_change".
	Kind string `yaml:"kind"`
	// State names the status state for "add_state" and "remove_state".
	State string `yaml:"state,omitempty"`
	// Stat names the stat for "stat_change" or the pool (such as "hp" or "mp") for "heal".
	Stat string `yaml:"stat,omitempty"`
	// Amount is the flat amount healed or stat delta applied.
	Amount float64 `yaml:"amount,omitempty"`
	// Ratio is a fractional heal ratio or stat multiplier.
	Ratio float64 `yaml:"ratio,omitempty"`
	// Chance is the probability in (0, 1] that the effect lands; 0 means always (1.0).
	Chance float64 `yaml:"chance,omitempty"`
	// Turns is how many turns a "stat_change" (1 or more) or "add_state" (0 or more) lasts.
	Turns int `yaml:"turns,omitempty"`
}

SkillEffect is one non-damage effect a skill applies to a target.

type SkillsFile

type SkillsFile struct {
	Version int     `yaml:"version"`
	Skills  []Skill `yaml:"skills,omitempty"`
}

SkillsFile is the per-category YAML file holding skills (skills.yaml).

func ParseSkills

func ParseSkills(data []byte) (*SkillsFile, error)

ParseSkills decodes and validates a standalone skills.yaml file.

func (*SkillsFile) Validate

func (f *SkillsFile) Validate() error

Validate checks the version and skill rules of f.

type Troop

type Troop struct {
	// ID identifies the troop among the database's troops.
	ID string `yaml:"id"`
	// Name is the optional display name or localization key.
	Name string `yaml:"name,omitempty"`
	// Members are the troop's enemies and where they stand; a troop has at least one.
	Members []TroopMember `yaml:"members"`
	// Events are optional conditional battle events triggered during combat.
	Events []TroopEvent `yaml:"events,omitempty"`
}

Troop is a group of enemies a battle starts with, with optional battle events.

type TroopEvent

type TroopEvent struct {
	// ID uniquely identifies the event within its troop.
	ID string `yaml:"id"`
	// Condition determines when the event fires.
	Condition ActionCondition `yaml:"condition"`
	// Script names the cutscene, dialogue node or flow event to run.
	Script string `yaml:"script"`
	// Once restricts the event to firing at most once per battle.
	Once bool `yaml:"once,omitempty"`
}

TroopEvent triggers a named battle script or event when Condition holds during combat.

type TroopMember

type TroopMember struct {
	// Enemy names an enemy of the database.
	Enemy string `yaml:"enemy"`
	// X is the member's horizontal position.
	X int `yaml:"x"`
	// Y is the member's vertical position.
	Y int `yaml:"y"`
}

TroopMember is one enemy in a troop and its position.

type TroopsFile

type TroopsFile struct {
	Version int     `yaml:"version"`
	Troops  []Troop `yaml:"troops,omitempty"`
}

TroopsFile is the per-category YAML file holding troops (troops.yaml).

func ParseTroops

func ParseTroops(data []byte) (*TroopsFile, error)

ParseTroops decodes and validates a standalone troops.yaml file. Cross-references to enemies are checked when combined in a Database.

func (*TroopsFile) Validate

func (f *TroopsFile) Validate() error

Validate checks the version and troop-local rules of f.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL