Documentation
¶
Overview ¶
Package combat holds the damage formula and the balance constants it reads.
Damage is a ratio against defence rather than a subtraction:
damage = attack * skillMultiplier * affinityMultiplier * K / (K + defence)
K is DefenseConstant, and the shape of the curve follows from it: a defender whose defence equals K takes half damage, one with no defence takes the full figure, and the curve flattens from there instead of ever reaching zero. Subtraction was rejected because attack - defence produces a breakpoint where a small stat change flips a hit between full damage and none, and that breakpoint moves every time the level cap changes.
Both multipliers are integers in parts per thousand and the whole expression resolves with a single integer division at the end, so truncation happens once and the result is identical on every platform.
The numerator that division reads is built in 128 bits. Five factors multiplied together pass what an int64 holds long before any one of them is an unreasonable number to author, and the obvious repair — dividing earlier — is refused precisely because it would truncate twice. Widening the intermediate is what lets the division stay single; below the point where the narrower arithmetic overflowed, the answer is bit for bit the one it gave.
Index ¶
- Constants
- func Absorb(attempts []Attempt, pool int64) (left int64)
- func AbsorbedBy(attempts []Attempt) int64
- func Count(attempts []Attempt, outcome Outcome) int
- func DamageDealt(attempts []Attempt) int64
- func Gradient(health, maximum int64, atEmpty int) int
- func PickScaling(source ScalingSource, base, current int64) int64
- func Pierced(defense int64, pierce int) int64
- func Repeated(value int64, count int) int64
- func Scaled(value int64, ratio int) int64
- func Swung(power, bonus, share int) int
- type Attempt
- type Hit
- type Outcome
- type Rules
- func (r Rules) Chance(h Hit) int
- func (r Rules) CriticalStrike(h Hit) int64
- func (r Rules) Damage(attack, defense int64, skillMultiplier, affinityMultiplier int) int64
- func (r Rules) DefenseReduction(defense int64) int
- func (r Rules) Expected(h Hit) int64
- func (r Rules) ExpectedStrike(h Hit) int64
- func (r Rules) GrantBlocks(held, granted int) (total, wasted int)
- func (r Rules) Resolve(h Hit) []int64
- func (r Rules) Restore(stat int64, multiplier int) int64
- func (r Rules) Roll(h Hit, blocks int, source *rng.Source) (attempts []Attempt, blocksLeft int)
- func (r Rules) Strike(h Hit) int64
- func (r Rules) Total(h Hit) int64
- func (r Rules) Validate() error
- type ScalingSource
Constants ¶
const PermilleBase = scale.Base
PermilleBase is the denominator every multiplier in this package is expressed against. The element chart's neutral multiplier uses the same base.
Variables ¶
This section is empty.
Functions ¶
func Absorb ¶
Absorb spends a pool of absorbing guard across the strikes that landed, in order, moving what it eats out of Damage and into Absorbed. It returns what is left of the pool.
⚠️ **A pass over the outcomes rather than a branch inside Roll**, and the shape is the design rather than convenience. A block charge is spent *during* the roll because it decides whether a strike happens at all — it cancels the strike, so nothing downstream of it exists. A pool is spent *after*, because it only reduces what already landed, and the critical that decides how big a strike was has to be rolled before there is a figure to eat. Two mechanics, two moments, and the code says so.
It touches no randomness and walks the attempts in the order Roll produced them, so it is a pure function of its arguments — which is what lets a battle still replay from its seed with a barrier on the board.
func AbsorbedBy ¶
AbsorbedBy returns how much of a set of attempts an absorbing guard ate.
func DamageDealt ¶
DamageDealt returns how much damage a set of attempts actually dealt.
func Gradient ¶
Gradient returns the share a hurt caster adds to its own skill's power, in parts per thousand: nought at full health, atEmpty as it approaches nothing, and a straight line between the two.
It is the smooth half of an idea whose stepped half already exists. `self_requires` asks a *threshold* -- at or below forty per cent, take a fixed bonus -- and a threshold is the right shape for a skill that becomes a different skill once a line is crossed. This is the other shape: the move that grows with the wound rather than switching at one, where every point of health lost is worth the same as the last and there is no line for either side to play around.
⚠️ **A multiplier rather than a bonus, and that is the whole reason it is arithmetic here rather than a second Condition in skill.** A bonus is a number added to power and would have to be added to *something* -- the declared power, which is not what a skill lands at once a detonate has amplified it. A share of whatever power the skill arrived at means a caster swinging harder swings harder at the power it actually has, and the two terms compose instead of arguing about which goes first. A Condition could not express it either way, because a Condition answers yes or no and there is no yes or no here.
⚠️ **It returns the share added, not the multiplier**, which is what makes nought mean "nothing happened" — the same shape as Pierce, Refused and Drained, all of which are the share that moved a number and are absent from the log when none did. The caller adds PermilleBase itself, in one place.
A maximum of nought is answered with nought rather than divided by: something with no maximum is not something that is hurt.
⚠️ The `=` half of the full-health guard is redundant with the arithmetic below and always will be — at exactly full health the missing share is nought, so the last line already answers nought — which means mutating it to `>` survives the whole suite. It is kept anyway because the `>` half is *not* redundant: a unit somehow past its own bar would otherwise earn a negative share and hand a hurt skill less power than a healthy one. Written down so the next person to mutate this stops looking for the missing test.
func PickScaling ¶
func PickScaling(source ScalingSource, base, current int64) int64
PickScaling returns whichever version of a stat the source names.
func Pierced ¶
Pierced returns the defence a hit resolves against once a piercing ratio has been taken off it, in parts per thousand of defence ignored.
It is a ratio rather than a switch, and that is the whole design. Measured against a 3100/800 unit and a 4800/400 one, both of which sit at the same joint budget, a ratio walks the armoured unit's edge from 0.98x to 1.55x across its range while a switch jumps straight to the far end — making an armour unit worthless against one skill and unaffected by the next, with nothing in between. A hard cap on a continuous quantity is the shape this engine has rejected everywhere else, which is why buffs saturate.
Only the ignored share is truncated, so full piercing reaches exactly zero defence and no piercing leaves the defence exactly as it was.
func Repeated ¶
Repeated returns a value taken a whole number of times.
The same argument as Scaled, for the two places a per-strike figure is multiplied by a count rather than by a ratio.
func Scaled ¶
Scaled returns a value taken at a ratio in parts per thousand.
⚠️ **It exists because saturating at math.MaxInt64 is only half an answer.** A quotient that will not fit stops at the widest figure the type holds, which is the right thing for the quotient and useless to the next line: every plain `value * ratio / PermilleBase` downstream of a saturated figure wraps, and a wrap is the one answer that comes back SMALLER. So the saturation has to be carried rather than merely produced, and carrying it means the arithmetic that takes it is exact — the same answer this package already gave twice, once for the damage numerator and once for Swung.
It is bit for bit `value * ratio / PermilleBase` for every pair that fits an int64, which is every pair any battle can reach; the widening only changes the answer where the narrow expression had stopped being one.
A ratio of PermilleBase returns the value untouched, for the reason Swung's comment gives: a guard that saturated on the product alone would refuse a figure it was handed and could have returned.
func Swung ¶
Swung is the power a skill lands at once the caster's own terms are in: the bonus a threshold on the caster adds, and the share a gradient multiplies in.
⚠️ **The bonus first and the share second, and the order is a design rather than an accident:** a caster swinging harder swings harder at the power it actually has, so a detonate that arrives at three thousand four hundred is what the wound is a share of. The other order would make the gradient a share of the declared power and quietly worth less on exactly the skills it should be worth most on.
It lives here, beside Gradient, because two callers have to agree on it exactly and neither may own it. The battle resolves a hit through it and the authoring preview measures an unwritten skill through it, so an author reading a figure before a write and the engine landing the blow afterwards are reading one arithmetic rather than two that agree today.
⚠️ **The product is built in 128 bits, for the reason the damage numerator is, and it matters more here.** This figure *becomes* `skillMultiplier` in Rules.damage, so it is upstream of the widening that protects that expression and the widening there cannot reach it. Written in one `int` it passed math.MaxInt64 at a power around 9.2e15 and wrapped, which handed damage a negative multiplier — refused by that function's first line — so an enormous power came back dealing MinimumDamage.
⚠️ **The widening is reused rather than a cheaper overflow check, and the reason is that the divisor is one of the multiplicands' own scale.** A skill with no bonus and no share is `power * 1000 / 1000`, which is `power` for every power the type holds. A guard that saturated whenever the *product* left an int64 would answer math.MaxInt64 to that — refusing a figure it was handed and could have returned untouched, three orders of magnitude below where the quotient stops fitting. Widening answers `power`, so the identity survives and the only inputs that saturate are the ones whose answer genuinely does not fit.
A quotient past the type saturates at math.MaxInt64, which is a bound on the **type** and not on the design, exactly as it is in the numerator — and the two compose: a saturated multiplier hands damage a factor that saturates its own division in turn, so the blow lands at the widest figure an int64 holds against a bar whose largest reachable value is eleven and a half thousand. It kills whatever it touches, which is what a power that large asked for. What it must not do is wrap, because a wrap is the one answer that comes back *smaller*.
⚠️ **The three clamps refuse a negative rather than preserving what one used to produce, and that is the one input whose answer moves.** None is reachable: power is Skill.Power plus a Condition's BonusPower and Validate refuses a negative of either, the bonus is that same field read off the caster, and Gradient cannot return a negative share — its full-health guard exists precisely so a unit somehow past its own bar does not earn one. They are written down anyway, because the arithmetic below is unsigned and a Skill built by hand must not be able to reach it; and there is no answer to preserve, since a negative power, a bonus that is a penalty and a wound that weakens are three things no field expresses.
Types ¶
type Attempt ¶
type Attempt struct {
Outcome Outcome
Damage int64
// Critical says this strike landed critically. It is a flag beside the
// outcome rather than a fourth Outcome, and that is deliberate:
// Count(attempts, Struck) is how the engine counts landings — drains,
// on-hit riders and every tally read it — so a Critted outcome would
// silently change what that counts, and every one of those callers would
// start missing exactly the strikes that hit hardest. A critical strike is
// a strike that landed well, not a different thing from a strike.
Critical bool
// Absorbed is how much of this strike an absorbing guard ate before the rest
// reached health. Damage is what was left over.
//
// A field beside the outcome rather than a fourth Outcome, for exactly the
// reason Critical is one: a strike a pool ate **connected**. It arrived, it
// was paid for, and only where its damage went is different — so the riders
// it carries land, its drains drain what actually reached health, and
// Count(attempts, Struck) counts it. A Blocked strike is the other thing: it
// never happened. Spelling the two the same way would have every on-hit
// tally in the engine start missing the strikes a barrier ate.
//
// So a fully eaten strike is Struck with Damage nought, and that is not the
// minimum-damage floor failing. The floor exists so an attack always does
// something against defence, which is a *reduction*; a pool is a quantity
// that was paid for and can be spent down to nothing, and eating a blow
// whole is the thing it was bought to do.
Absorbed int64
}
Attempt is the outcome of one strike.
type Hit ¶
type Hit struct {
// Scaling is the attacker's scaling stat, already buffed. Most skills
// scale off attack, but a skill may declare a different stat; the layer
// that builds the Hit picks which one, and the multiplier is what
// normalises between stats of different magnitudes.
Scaling int64
// Multiplier is the skill's power for a single strike, in parts per
// thousand.
Multiplier int
// Strikes is how many times the skill lands. Zero and one both mean a
// single strike. A multi-strike skill is expected to divide its power
// across strikes rather than repeat it at full power.
Strikes int
// Affinity is the elemental multiplier, in parts per thousand.
Affinity int
// Defense is the target's defence, already buffed and not yet pierced.
Defense int64
// Convert is the share of this blow that meets no defence at all, in parts
// per thousand, and it belongs to the ATTACKER rather than to the skill.
//
// Pierce is a property of a skill — razor_leaf pierces because that is what
// razor_leaf is — so it is authored on the skill and every carrier gets the
// same ratio. This one is a property of whoever is swinging: a trait that
// says "part of everything I throw goes straight through" applies to the
// whole kit, and there was no way to write that. The battle layer sums it
// across the traits in force and hands it down here.
Convert int
// Pierce is the share of that defence the skill ignores, in parts per
// thousand. Zero is every skill that does not pierce, which is why adding
// the field moved no golden file.
//
// It sits on the hit rather than being folded into Defense by the caller so
// that the figure survives to the event log: a pierced hit that logs like an
// ordinary one leaves the log unable to explain its own numbers, which is
// the same trap a silent passive would set.
Pierce int
// Repeat is the chance, in parts per thousand, that a strike is followed by
// another one, rolled again after each. Zero is a skill whose strike count is
// simply Strikes, which is every skill that shipped before this field.
//
// It is a different shape from Strikes and not a substitute for it. Strikes
// says "this always lands three times, each for a third"; Repeat says "this
// lands once and might keep going", which is a *distribution* rather than a
// number — mostly the floor, occasionally a great deal more. A rating cannot
// use the ceiling (it would price every cast as the best cast) and cannot use
// the floor (it would never see the tail), so ExpectedStrikes is the figure
// everything outside the roll reads.
//
// ⚠️ **The count is rolled once, before the strike loop.** Rolling inside it
// would interleave the count's draws with each strike's own, so a change to
// how a strike resolves would move a figure the count depends on — and the
// replay contract rests on the stream being read in a fixed order.
Repeat int
// MaxStrikes is where a repeating strike stops. It bounds the tail, and a
// repeating skill without one would be a skill that can, however rarely, take
// a whole battle in one turn.
MaxStrikes int
// Crit is the chance each strike lands critically, in parts per thousand,
// and it is the *skill's* own figure. No stat moves it: progression.Values
// is a fixed-size array behind a schema of six required pointers, and a
// seventh kind is not something a stat line may grow — so a skill that crits
// crits at the same rate in every hand that carries it, and how often is the
// thing that distinguishes one skill from the next.
//
// Zero is every skill in the book today, which is why adding it moved no
// battle golden and no saved log: rng.Source.Chance returns without drawing
// at a chance of nought, so the stream is untouched. Pierce used the same
// trick, for the same reason.
Crit int
// SkillAccuracy is the skill's own chance to connect, in parts per
// thousand. Zero means the skill never lands, so it must be set.
SkillAccuracy int
// AccuracyStat is the attacker's accuracy stat, which closes the gap
// between the skill's own accuracy and a certain hit.
AccuracyStat int64
// DodgeStat is the target's dodge stat, which reopens that gap.
DodgeStat int64
}
Hit describes one attack after stats, buffs and the elemental chart have all been settled. It deliberately carries plain numbers rather than references to a unit or a skill, so this package stays free of every layer above it.
func (Hit) ExpectedStrikes ¶
ExpectedStrikes is how many strikes a repeating skill lands on average, in parts per thousand, and it is what every caller outside the roll should read.
A geometric tail cut at MaxStrikes: the floor always lands, and each strike after it lands with probability p^k. Summed rather than approximated by the closed form, because the closed form needs the cut and the sum is six lines of integer arithmetic that cannot drift from the loop it describes.
func (Hit) RollStrikes ¶
RollStrikes is how many times this hit actually lands, which is StrikeCount for an ordinary skill and a rolled count for a repeating one.
⚠️ **It draws nothing when the skill does not repeat**, which is what keeps every log written before repeating strikes existed byte for byte what it was: rng.Source.Chance returns without touching the stream at a chance of nought, the same trick Pierce and Crit each used.
func (Hit) StrikeCount ¶
Strikes returns how many times the hit lands, treating an unset count as one.
type Rules ¶
type Rules struct {
// DefenseConstant is the defence value at which a defender takes half
// damage. Its size sets how long defence keeps mattering: too small and
// defence saturates early, too large and defence scales close to linearly
// and tanks run away with the late game.
DefenseConstant int64 `json:"defense_constant"`
// MinimumDamage is the floor a connecting hit deals, so a heavily
// resisted attack against a heavily armoured target still moves the
// battle forward instead of stalling it.
MinimumDamage int64 `json:"minimum_damage"`
// CriticalMultiplier is what a critical strike multiplies the whole damage
// expression by, in parts per thousand. It is one game-wide constant rather
// than a figure a skill declares: how *often* a skill crits is what makes
// one skill different from the next, and a second per-skill number would
// only let two skills disagree about what the word means.
//
// Validate requires it rather than tolerating an absent one. A missing
// value reads as nought, which drives every critical strike straight to
// MinimumDamage — the mechanic silently inverted, with the book still
// loading and every ordinary hit still correct.
CriticalMultiplier int `json:"critical_multiplier"`
// MinHitChance is the limit dodge drives a hit chance towards without ever
// reaching it, in parts per thousand. Without a floor a dodge-stacked unit
// would eventually be untouchable, which is not a defensive stat but an
// immunity.
MinHitChance int `json:"min_hit_chance"`
// MaxBlockCharges is the most charges a unit may hold at once.
//
// Charges are the one defence in the engine that does not saturate: three
// of them cancel three strikes outright, with no diminishing return, so a
// stack of them can erase a whole round of incoming damage rather than
// reduce it. A hard cap is the right bound for a discrete resource, the same
// reason the affinity scale is clamped rather than saturated.
MaxBlockCharges int `json:"max_block_charges"`
}
Rules holds the tunable constants of the damage formula.
func ParseRules ¶
ParseRules reads a rules declaration. It never touches the filesystem; the caller supplies the bytes.
func (Rules) Chance ¶
Chance returns the probability the hit connects, in parts per thousand.
The skill's own accuracy is where it starts. The attacker's accuracy stat closes the gap towards a certain hit; the target's dodge stat then reopens it towards MinHitChance. Both sides saturate, so neither can be stacked into an absolute: no amount of accuracy makes an unreliable skill certain, and no amount of dodge makes a unit untouchable.
Dodge is applied after accuracy rather than subtracted from it, because a contest of the two raw stats would cancel out and a defender with high dodge would gain nothing at all against an attacker with high accuracy. Applying it second means dodge always bites, even against an attack that was going to land ninety-nine times in a hundred. The cost of that choice is that dodge works against a wider gap than accuracy does and is therefore worth more per point; the dodge ceiling is set lower to pay for it.
A skill that declares full accuracy cannot miss and cannot be dodged. That is the explicit way to write an effect that must land, and it is what gives a block charge its purpose.
func (Rules) CriticalStrike ¶
CriticalStrike returns the damage of a single strike that landed critically.
It is the same expression with the game-wide multiplier folded into it rather than Strike's answer multiplied afterwards. Multiplying afterwards would be a second truncation, so a critical hit would sometimes come to one point less than the formula says — and the shortfall would depend on the defence curve, which is the one thing this package resolves in a single division precisely so nobody has to reason about that.
func (Rules) Damage ¶
Damage returns the damage a hit deals. skillMultiplier and affinityMultiplier are in parts per thousand; a skill multiplier of 1800 is a 1.8x hit and an affinity multiplier of 2250 is a stacked weakness.
A hit that resolves below MinimumDamage is raised to it, but an attack with no power behind it deals nothing at all.
defense is the defence as it applies to this hit, piercing already taken off. Piercing is Pierced's job rather than a fifth parameter here: what this signature refuses is a fifth positional *non-multiplier*. attack and defense are not interchangeable and a mis-ordered pair passes silently at every caller; Hit is the struct that exists precisely to carry an attack whose terms are all settled. A caller that reaches this directly rather than through Strike is asking for the raw curve, and a damage-over-time tick is exactly that — see turn.go.
The private damage below is allowed the fifth argument the public one is not, because a critical multiplier is a *multiplier*: the three of them commute, so a mis-order among them cannot change a figure, and it is unexported so no caller outside this package can mis-order them anyway. It exists so the package resolves through exactly one expression, and so a critical strike truncates once rather than multiplying an already-floored result.
func (Rules) DefenseReduction ¶
DefenseReduction returns the share of damage that gets through a given defence, in parts per thousand. It exists for tuning and for showing the curve; Damage does not call it, because folding it in would introduce a second truncation.
func (Rules) Expected ¶
Expected returns what every strike of a hit is worth before any is rolled.
⚠️ **Through ExpectedStrikes rather than StrikeCount, which is the rule Repeat is declared under and which this was the one place not to follow.** A repeating skill's count is a distribution — mostly the floor, occasionally a great deal more — so a rating cannot use the ceiling (it would price every cast as the best cast) and cannot use the floor either. This was reading the floor, and nothing said so: measured, a seven-hundred-power single beat a six-hundred one landing about five times, and `spark` was priced at two strikes rather than three.
The count comes in parts per thousand, so the division is here and not at the call site — a caller multiplying a per-strike figure by a per-mille count is exactly the second copy of the arithmetic this package exists to prevent.
⚠️ Total is deliberately NOT changed to match: it is the deterministic figure skills.golden's damage column is written from, and a number that moved with an expected value would stop being the thing an author compares two skills by. See its comment. The two answer different questions and both are wanted.
Because ExpectedStrike returns early at a chance of nought and ExpectedStrikes returns the plain count for a skill that does not repeat, this is still bit for bit Total for every shipped skill but the repeating ones.
func (Rules) ExpectedStrike ¶
ExpectedStrike returns what one strike is worth before it is rolled, with the chance of a critical priced in.
It exists so a rating can charge for a critical without drawing one: Suggest may not touch the battle's source, and it may not keep a second copy of the resolving arithmetic either, so this is composed from the same two functions Roll resolves through.
A skill that cannot crit takes the early return rather than the weighting, which is what makes this bit-identical to Strike for every skill in the book today — and therefore why the opponent's choices did not move.
func (Rules) GrantBlocks ¶
GrantBlocks adds charges to what a unit already holds, capped at MaxBlockCharges, and reports how many were wasted on the cap.
Granting goes through here rather than being a plain addition so that a stack of shielding effects cannot quietly push a unit past the cap, and so the effect that overshoots can say so instead of silently doing nothing.
func (Rules) Resolve ¶
Resolve returns the damage of each strike in order.
Every strike is computed and truncated on its own rather than by dividing a single total, because a strike is the unit that on-hit effects and shields react to. The cost is that a multi-strike skill loses up to one point of damage per strike to truncation, which is why splitting power across strikes is very slightly worse than concentrating it.
func (Rules) Restore ¶
Restore returns how much health a multiplier of a stat gives back.
It does not divide by the defence curve, and damage over time does. That asymmetry is the design rather than an oversight: defence turns away what is coming *at* a unit and has nothing to do with what is helping it, so a well-armoured unit is no harder to heal than a bare one. Adding the division for symmetry's sake would make armour quietly reduce its own side's support.
Like everything else here it is integer parts per thousand, truncated once.
func (Rules) Roll ¶
Roll resolves every strike of a hit against its chance to connect, spending the target's block charges on whichever strikes get through. It returns the per-strike outcomes and the charges left over.
Each strike rolls on its own rather than the skill rolling once, so a multi-strike skill can land partially. That is what gives accuracy a different shape on a multi-strike skill than on a single one: the expected damage is the same, but the variance is far lower. An area skill rolls once per target for the same reason, by resolving each target as its own hit.
A charge is only spent on a strike that would otherwise have landed, so a target that dodges wastes none. One charge cancels one strike, which is what makes block the answer to a single heavy hit and multi-strike the answer to block: the same charge that erases a full-power blow is burned by a third of one.
func (Rules) Strike ¶
Strike returns the damage of a single strike, against whatever defence the hit's piercing leaves standing.
func (Rules) Total ¶
Total returns the damage of every strike combined, ignoring the chance of a critical.
⚠️ It stays because its remaining caller is internal/seed's skillReport, which writes skills.golden's damage column, and that column is a *deterministic* figure the design record is read against — a number that moved with an expected value would stop being the thing an author compares two skills by. Anything rating a hypothetical action wants Expected instead. Do not delete this as dead weight: doing so takes the golden column with it.
type ScalingSource ¶
type ScalingSource uint8
ScalingSource selects which version of the attacker's scaling stat a skill reads.
The distinction exists because a stat that feeds both the turn order and the damage would otherwise be worth its square when buffed: a fifty percent speed buff would grant fifty percent more turns each dealing fifty percent more damage. A skill that reads BaseStat lets a buff move the turn economy while leaving the damage term alone, which keeps such a buff worth the same as any other. A skill that reads CurrentStat accepts the compounding on purpose.
const ( // CurrentStat reads the stat after buffs and debuffs. CurrentStat ScalingSource = iota // BaseStat reads the stat before them. BaseStat )
func (ScalingSource) String ¶
func (s ScalingSource) String() string