Documentation
¶
Overview ¶
Package loot is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package loot rolls nested weighted drop tables with guaranteed drops and pity counters, and draws distinct weighted draft offers from versioned pools on the deterministic streams of package random.
Tables ¶
A Document is the versioned YAML text a game's author writes: a list of named tables. Each Table holds weighted Entries, of which it picks Rolls times, and Guaranteed entries it drops every time it is rolled. An Entry drops an item, rolls another table (nesting), or drops nothing. Parse decodes and validates a Document, refusing unknown fields, unsupported versions, unknown or cyclic table references and runaway sizes; Encode writes the same Document back as deterministic YAML that parses to an equal value.
Rolling ¶
New compiles a Document into an immutable Library. A Roller rolls a Library's tables on one random.Stream, so a seed and a sequence of rolls always produce the same drops on every platform. A Library can be shared by many Rollers; each Roller is used by one goroutine.
Pity ¶
A table's Pity rules raise the chance of one of its entries after a run of picks without it. A hard rule (GuaranteeAt) forces the entry on the GuaranteeAt-th pick since it was last picked; a soft rule (SoftFrom, SoftStep) adds SoftStep to the entry's weight for every pick from the SoftFrom-th one on. A Roller keeps a miss counter per rule; State and SetState copy the counters out and back in for save slots, beside the stream's own random.State.
Draft pools ¶
A Pool is a versioned YAML document parsed with ParsePool and written with EncodePool. Each Option declares an ID, relative Weight, optional Rarity, MaxRank, finite shared Copies, Requires prerequisites at a rank, and Excludes. An optional RarityCurve shifts rarity weights across a named progression axis such as level or wave.
NewDrafter compiles a Pool into a Drafter on one random.Stream. Offer(k) draws up to k distinct weighted choices without replacement and reports Offer.Short when fewer than k eligible choices remain. Take, Reroll, Banish, Lock, Unlock and Return manage ranks, finite stock, exclusions and pinned shop slots; State and SetState snapshot the DrafterState (including the stream state, level, ranks, stock, bans, locks and active offer) for saves and replays.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/loot"
)
func main() {
fmt.Println(loot.CurrentVersion)
}
Output: 1
Index ¶
- Constants
- Variables
- func Encode(doc *Document) ([]byte, error)
- func EncodePool(pool *Pool) ([]byte, error)
- func Validate(doc *Document) error
- func ValidatePool(pool *Pool) error
- type Choice
- type Document
- type Drafter
- func (d *Drafter) Banish(id string) error
- func (d *Drafter) CurrentOffer() Offer
- func (d *Drafter) Eligible(id string) bool
- func (d *Drafter) IsBanished(id string) bool
- func (d *Drafter) IsLocked(id string) bool
- func (d *Drafter) Level() int
- func (d *Drafter) LevelName() string
- func (d *Drafter) Lock(id string) error
- func (d *Drafter) Offer(k int) Offer
- func (d *Drafter) Rank(id string) int
- func (d *Drafter) Reroll() Offer
- func (d *Drafter) Return(id string) error
- func (d *Drafter) SetLevel(level int)
- func (d *Drafter) SetState(st DrafterState) error
- func (d *Drafter) State() DrafterState
- func (d *Drafter) Stock(id string) (remaining int, finite bool)
- func (d *Drafter) Stream() *random.Stream
- func (d *Drafter) Take(id string) error
- func (d *Drafter) Unlock(id string) error
- type DrafterState
- type Drop
- type Entry
- type Library
- type Offer
- type Option
- type Pity
- type Pool
- type Range
- type RarityStep
- type Requirement
- type Roller
- func (r *Roller) AppendRoll(dst []Drop, table string) ([]Drop, error)
- func (r *Roller) Library() *Library
- func (r *Roller) Misses(table, rule string) (int, bool)
- func (r *Roller) ResetPity()
- func (r *Roller) Roll(table string) ([]Drop, error)
- func (r *Roller) SetState(st State) error
- func (r *Roller) State() State
- func (r *Roller) Stream() *random.Stream
- type State
- type Table
Examples ¶
Constants ¶
const ( // MaxRolls is the largest number of weighted picks one roll of a table may make. MaxRolls = 1024 // MaxCount is the largest quantity of an item entry, or the largest number of times a table entry rolls its table. MaxCount = 1 << 30 // MaxWeight is the largest entry weight and the largest SoftStep. MaxWeight = 1e15 // MaxGuaranteeAt is the largest GuaranteeAt and SoftFrom of a pity rule. MaxGuaranteeAt = 1 << 20 // MaxRollSteps bounds the work of one Roller.Roll: the worst case of picks, sub-table rolls and drops a table can produce, which Validate computes from Rolls and Count maxima, must not exceed it. A weighted pick counts as many steps as its table has entries and pity rules, because it scans all of them. MaxRollSteps = 1 << 16 )
Limits that keep every roll bounded. Validate refuses documents that exceed them.
const ( // MaxPoolOptions is the largest number of options one Pool may declare. MaxPoolOptions = 4096 // MaxRaritySteps is the largest number of level steps one Pool.RarityCurve may declare. MaxRaritySteps = 1024 )
Limits that keep every draft pool bounded. ValidatePool refuses pools that exceed them.
const CurrentVersion = 1
CurrentVersion is the loot document schema version that Parse accepts and Encode writes.
const MaxMisses = 1 << 30
MaxMisses is the largest value a pity miss counter holds; counting saturates there, and SetState refuses larger values.
const PoolVersion = 1
PoolVersion is the draft pool document schema version that ParsePool accepts and EncodePool writes.
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL
SchemaComment is the first line Encode writes: a YAML comment that points a YAML language server at SchemaURL. Parse ignores it like any other comment.
const SchemaURL = "https://nsgo.games/schemas/loot.v1.json"
SchemaURL is where the JSON Schema of version 1 loot documents is published. Encode names it in a yaml-language-server comment on the document's first line, so editors and AI tools validate and complete loot tables as they are written.
Variables ¶
var ( // ErrUnknownOption is returned when an option ID is not declared in the pool. ErrUnknownOption = errors.New("loot: unknown option") // ErrMaxRank is returned when an option has already reached its MaxRank. ErrMaxRank = errors.New("loot: option at max rank") // ErrOutOfStock is returned when a finite-copies option has no remaining stock. ErrOutOfStock = errors.New("loot: option out of stock") // ErrBanished is returned when an option has been banished from the pool. ErrBanished = errors.New("loot: option banished") // ErrUnmetRequirement is returned when an option's Requires prerequisites are not satisfied. ErrUnmetRequirement = errors.New("loot: option requirement not met") // ErrExcluded is returned when an option is excluded by an already-held option. ErrExcluded = errors.New("loot: option excluded") // ErrStockFull is returned by Return when an option's stock is already at its pool Copies limit or no rank is held for an unlimited option. ErrStockFull = errors.New("loot: option stock is already full") )
Sentinel errors returned by Drafter methods.
var ErrUnknownTable = errors.New("loot: unknown table")
ErrUnknownTable is returned by Roller.Roll for a table name the Library does not hold.
Functions ¶
func Encode ¶
Encode validates doc and writes it as deterministic 2-space YAML, SchemaComment on its first line, that Parse decodes to an equal Document.
func EncodePool ¶
EncodePool validates pool and writes it as deterministic 2-space YAML that ParsePool decodes to an equal Pool.
func Validate ¶
Validate checks doc against the version 1 schema: names, entry kinds, weights, ranges, pity rules, table references without cycles, and the MaxRollSteps bound on every table.
func ValidatePool ¶
ValidatePool checks pool against the version 1 draft pool schema: unique IDs, positive weights, valid ranks and copies, strictly increasing rarity curve thresholds, valid requires/excludes references without requirement cycles, and size limits.
Types ¶
type Choice ¶
type Choice struct {
// ID is the option's identifier.
ID string
// Rarity is the option's rarity label, if any.
Rarity string
// Rank is the option's current held rank before being taken.
Rank int
// NextRank is Rank + 1, the rank the option will reach if taken.
NextRank int
// MaxRank is the option's maximum rank, or 0 if unlimited.
MaxRank int
// Copies is the option's total pool stock, or 0 if unlimited.
Copies int
// Stock is the remaining copies in the pool (0 if depleted or if Copies is 0).
Stock int
// Locked reports whether this choice is pinned by Lock across Reroll and subsequent Offer calls.
Locked bool
}
Choice is one option presented in an Offer.
type Document ¶
type Document struct {
// Version is the schema version; it must equal CurrentVersion (1).
Version int `yaml:"version" schema:"required"`
// Tables are the document's tables. Their names are unique, and entries refer to them by name.
Tables []Table `yaml:"tables" schema:"required"`
}
Document is the root of a versioned YAML loot document.
type Drafter ¶
type Drafter struct {
// contains filtered or unexported fields
}
Drafter draws distinct weighted offers from a compiled Pool on one random.Stream, tracking ranks, finite stock, prerequisites, exclusions, banish, lock and progression level. A Drafter is not safe for concurrent use; give each run or goroutine its own Drafter and stream.
func NewDrafter ¶
NewDrafter validates and compiles pool and returns a Drafter drawing from stream. Later edits to pool do not affect the Drafter.
func (*Drafter) Banish ¶
Banish permanently removes option id from future offers, clears any lock on id, and removes it from the active offer if present. Banishing an already-banished option is a no-op.
func (*Drafter) CurrentOffer ¶
CurrentOffer returns the currently active Offer without drawing from the stream.
func (*Drafter) Eligible ¶
Eligible reports whether id can currently be offered at the current level and state.
func (*Drafter) IsBanished ¶
IsBanished reports whether id has been banished from the pool.
func (*Drafter) Level ¶
Level returns the current progression level used for Pool.RarityCurve lookup.
func (*Drafter) LevelName ¶
LevelName returns the name of the progression axis configured on the pool (defaulting to "level").
func (*Drafter) Lock ¶
Lock pins option id so Reroll and subsequent Offer calls keep it in the offer until it is taken, unlocked, banished, or becomes ineligible. Lock refuses unknown or currently ineligible options.
func (*Drafter) Offer ¶
Offer draws up to k distinct weighted choices from eligible options in the pool and replaces the active offer. Currently locked choices that remain eligible are kept first (up to k), and the remaining slots are sampled without replacement from the remaining eligible options. When fewer than k eligible options exist, Offer returns all available choices with Offer.Short set to true.
func (*Drafter) Rank ¶
Rank returns the current rank held for id, or 0 if id is unknown or has not been taken.
func (*Drafter) Reroll ¶
Reroll redraws the current offer with the same requested size as the last Offer call, keeping any still-eligible locked choices and sampling replacements for all unlocked slots. When no offer is active (OfferSize == 0), Reroll returns an empty Offer without advancing the stream.
func (*Drafter) Return ¶
Return returns one copy of option id back to the pool (such as selling a unit in an auto-battler). For finite-copies options, stock increases by 1 (refused with ErrStockFull if already at full Copies) and rank decreases by 1 if currently positive. For unlimited-copies options, rank decreases by 1 (refused with ErrStockFull if rank is already 0). Any active offer or locked option whose Requires prerequisites become unmet is pruned.
func (*Drafter) SetState ¶
func (d *Drafter) SetState(st DrafterState) error
SetState restores d from a snapshot returned by State, including its random.Stream state. Unknown option IDs in st are ignored so saves outlive edits to the pool file; missing finite-copies options default to full stock. Invalid values (negative or out-of-range ranks, ranks above MaxRank, negative or out-of-range stock, stock above Copies, or negative/out-of-range OfferSize) are refused without modifying d.
func (*Drafter) State ¶
func (d *Drafter) State() DrafterState
State returns a deterministic snapshot of d, including its random.Stream state, level, ranks, remaining stock, banished and locked options, and active offer.
func (*Drafter) Stock ¶
Stock returns the remaining stock for id and whether id has finite copies in the pool. For an unknown option or an option with unlimited copies (Copies == 0), it returns (0, false).
func (*Drafter) Take ¶
Take selects option id, incrementing its rank, decrementing its finite stock (if Copies > 0), clearing any lock on id, and removing id from the active offer if present. It refuses unknown, banished, maxed, out-of-stock, excluded or unmet-requirement options without modifying state.
type DrafterState ¶
type DrafterState struct {
// Stream is the snapshot of the Drafter's random.Stream.
Stream random.State `json:"stream" yaml:"stream"`
// Level is the current progression level used to select the active step of Pool.RarityCurve.
Level int `json:"level,omitempty" yaml:"level,omitempty"`
// Ranks maps each option ID with rank > 0 to its current rank.
Ranks map[string]int `json:"ranks,omitempty" yaml:"ranks,omitempty"`
// Stock maps each finite-copies option ID to its remaining stock in the pool.
Stock map[string]int `json:"stock,omitempty" yaml:"stock,omitempty"`
// Banished lists banished option IDs in pool order.
Banished []string `json:"banished,omitempty" yaml:"banished,omitempty"`
// Locked lists locked option IDs in pool order.
Locked []string `json:"locked,omitempty" yaml:"locked,omitempty"`
// Offer lists the option IDs currently in the active offer, in order.
Offer []string `json:"offer,omitempty" yaml:"offer,omitempty"`
// OfferSize is the requested size (k) of the active offer, used by Reroll.
OfferSize int `json:"offerSize,omitempty" yaml:"offerSize,omitempty"`
}
DrafterState is a JSON- and YAML-marshalable snapshot of a Drafter, including its random.Stream state, progression level, taken ranks, remaining stock, banished and locked options, and active offer, for saves and replays.
type Entry ¶
type Entry struct {
// Item names the item this entry drops.
Item string `yaml:"item,omitempty"`
// Table names another table of the document that this entry rolls.
Table string `yaml:"table,omitempty"`
// Nothing marks an empty pick, which drops nothing; its weight sets the chance of a miss.
Nothing bool `yaml:"nothing,omitempty"`
// Weight is the entry's relative chance among the table's Entries. It must be positive there and 0 in Guaranteed.
Weight float64 `yaml:"weight,omitempty"`
// Count is the item's quantity, or how many times the table entry rolls its table, drawn uniformly from the range; nil means exactly one. A Nothing entry has no Count.
Count *Range `yaml:"count,omitempty"`
}
Entry is one possible drop of a table. Exactly one of Item, Table and Nothing is set.
type Library ¶
type Library struct {
// contains filtered or unexported fields
}
Library is a compiled, immutable set of tables that any number of Rollers can roll concurrently.
func New ¶
New validates doc and compiles it into a Library. The Library does not keep doc, so later changes to doc do not affect it.
func (*Library) Chances ¶
Chances returns the probability of each of the named table's Entries on one pick with no pity ramp applied, in document order. It returns nil for an unknown table or one without entries.
type Offer ¶
type Offer struct {
// Choices are the distinct offered options in presentation order (kept locked choices first, then newly drawn choices in draw order).
Choices []Choice
// Requested is the number of choices requested (k).
Requested int
// Short is true when fewer than Requested eligible options were available.
Short bool
}
Offer is the result of Drafter.Offer, Drafter.Reroll or Drafter.CurrentOffer.
type Option ¶
type Option struct {
// ID uniquely identifies the option within the pool.
ID string `yaml:"id"`
// Weight is the option's positive relative weight (within its rarity when RarityCurve is set, or across the pool otherwise). When Copies is positive, effective weight scales with remaining copies in stock.
Weight float64 `yaml:"weight"`
// Rarity, optional, names the option's rarity tier. It must be set and declared in RarityCurve whenever RarityCurve is non-empty.
Rarity string `yaml:"rarity,omitempty"`
// MaxRank is the maximum number of times the option can be taken; 0 means unlimited.
MaxRank int `yaml:"maxRank,omitempty"`
// Copies is the finite shared stock of the option in the pool; 0 means unlimited stock.
Copies int `yaml:"copies,omitempty"`
// Requires lists other options that must be held at least at the given rank before this option can be offered or taken.
Requires []Requirement `yaml:"requires,omitempty"`
// Excludes lists other option IDs that prevent this option from being offered or taken once any of them is held at rank 1 or higher.
Excludes []string `yaml:"excludes,omitempty"`
}
Option is one draftable choice in a Pool.
type Pity ¶
type Pity struct {
// Name identifies the rule's miss counter in State; it is unique within its table.
Name string `yaml:"name" schema:"required"`
// Item names the target entry by its Item.
Item string `yaml:"item,omitempty"`
// Table names the target entry by its Table.
Table string `yaml:"table,omitempty"`
// GuaranteeAt, when positive, forces the target on the GuaranteeAt-th pick since it was last picked. When several rules of a table force a pick at once, the first one in order wins and the others keep counting.
GuaranteeAt int `yaml:"guaranteeAt,omitempty"`
// SoftFrom, when positive, starts the soft ramp: on the n-th pick since the target was last picked, with n >= SoftFrom, the target's weight grows by (n-SoftFrom+1)*SoftStep. It must be below GuaranteeAt when both are set.
SoftFrom int `yaml:"softFrom,omitempty"`
// SoftStep is the weight the soft ramp adds per pick. It is positive exactly when SoftFrom is.
SoftStep float64 `yaml:"softStep,omitempty"`
}
Pity is a rule that raises the chance of one entry of its table after a run of picks without it. Exactly one of Item and Table names the target entry, and at least one of GuaranteeAt and SoftFrom is set.
type Pool ¶
type Pool struct {
// Version is the schema version; it must equal PoolVersion (1).
Version int `yaml:"version"`
// Name, optional, identifies the pool (such as "upgrades" or "shop").
Name string `yaml:"name,omitempty"`
// LevelName, optional, names the progression axis that RarityCurve thresholds index (such as "level" or "wave"); empty defaults to "level".
LevelName string `yaml:"levelName,omitempty"`
// RarityCurve defines relative rarity weights from each At threshold onward, sorted by strictly increasing At. When empty, options draw by their own weights directly.
RarityCurve []RarityStep `yaml:"rarityCurve,omitempty"`
// Options are the draftable choices in the pool. Their IDs are unique.
Options []Option `yaml:"options"`
}
Pool is the root of a versioned YAML draft pool document.
type Range ¶
Range is an inclusive integer range [Min, Max]. In YAML it is written as a single integer when Min equals Max and as a mapping with min and max otherwise.
func (Range) MarshalYAML ¶
MarshalYAML writes r as an integer when Min equals Max and as a min/max mapping otherwise.
type RarityStep ¶
type RarityStep struct {
// At is the minimum level (or wave, named by Pool.LevelName) at which these weights apply.
At int `yaml:"at"`
// Weights maps each rarity name to its non-negative relative weight at this threshold. At least one weight must be positive.
Weights map[string]float64 `yaml:"weights"`
}
RarityStep sets the relative rarity weights from progression threshold At onward.
type Requirement ¶
type Requirement struct {
// ID names the required option in the same pool.
ID string `yaml:"id"`
// Rank is the minimum rank required (at least 1).
Rank int `yaml:"rank"`
}
Requirement gates an Option on holding another option at a minimum rank.
type Roller ¶
type Roller struct {
// contains filtered or unexported fields
}
Roller rolls a Library's tables on one random.Stream and keeps the pity miss counters of one player or save. A Roller is not safe for concurrent use; give each goroutine its own Roller and stream.
func NewRoller ¶
NewRoller returns a Roller with zero pity counters that rolls lib's tables on stream, typically a stream forked for loot such as streams.Stream("loot"). It panics if lib or stream is nil.
func (*Roller) AppendRoll ¶
AppendRoll is like Roll but appends the drops to dst, so a caller that reuses dst rolls without allocating. On an unknown table it returns dst unchanged and an error wrapping ErrUnknownTable, without drawing from the stream or touching the counters.
func (*Roller) Misses ¶
Misses returns how many picks of table have passed since the target of its pity rule was last picked, and false when the table or rule does not exist. The next pick is pick number Misses+1, which is what GuaranteeAt and SoftFrom count.
func (*Roller) ResetPity ¶
func (r *Roller) ResetPity()
ResetPity sets every pity counter of r back to zero.
func (*Roller) Roll ¶
Roll rolls the named table once and returns its drops in the order they were produced: guaranteed entries first, then each weighted pick, with nested tables expanded in place.
func (*Roller) SetState ¶
SetState replaces r's pity counters with st's. Rules missing from st start at zero, and counters for tables or rules the Library no longer has are ignored, so a save outlives edits to the loot document. It refuses a counter below 0 or above MaxMisses and then leaves r unchanged.
type State ¶
State is a Roller's pity counters as plain data for save slots, keyed by table name and then by pity rule name. Only non-zero counters are listed. Its map keys marshal in sorted order with encoding/json and YAML, so its text is deterministic.
type Table ¶
type Table struct {
// Name identifies the table to Roller.Roll and to entries of other tables.
Name string `yaml:"name" schema:"required"`
// Rolls is how many weighted picks one roll of the table makes, drawn uniformly from the range; nil means exactly one. It must be nil when Entries is empty.
Rolls *Range `yaml:"rolls,omitempty"`
// Guaranteed entries drop every time the table is rolled, before its weighted picks. Their Weight must be 0 and they cannot be Nothing.
Guaranteed []Entry `yaml:"guaranteed,omitempty"`
// Entries are the weighted choices of each pick. Every Weight must be positive, and no two entries may name the same item or the same table.
Entries []Entry `yaml:"entries,omitempty"`
// Pity rules raise the chance of one entry of Entries after a run of picks without it.
Pity []Pity `yaml:"pity,omitempty"`
}
Table is one named drop table.