diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-16 22:19:39 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-16 22:19:39 +0100 |
| commit | 94e2850fb73005f3fb30af8489905e5cdfb6fac5 (patch) | |
| tree | 1aea8e7e6683af770f0c57c0fb654003778c9f16 /web/src/lib/game/line/statApplier.ts | |
| parent | 4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (diff) | |
Phase 4: cards and decks (M4)
Full card play in the browser: ability-line rendering, monster ability
decks, the full modifier-deck (AMD) suite, and the loot deck — all
server commands, faithful to the reference flows and layout.
Web (Svelte 5):
- Line renderer + in-game translations: $lib/game/line/ renders the
reference line_builder output (emphasis, range markers, element
styling); gameI18n.ts loads the /i18n/ in-game ability-text tables
(the client-side TranslationService equivalent)
- Card components: stat cards, monster ability cards (OG + FH styles,
rendered lines, element/flying tokens), modifier cards (gfx resolver
incl. P<n> perk graphics), loot cards (party-size value rules,
owner, enhancements)
- Monster ability decks: AbilityCardSlot in each monster row (front of
the current card while active in playTurns, else the back with the
draw-pile count); AbilityCardsMenu (reveal top cards, draw extra,
extra shuffle, activate/inactivate, drag-reorder, remove); card zoom
- Modifier decks: ModifierDeckWidget (tap to draw, face-up revealed top
card, empty-box class icon for the current character's own deck,
discard stack); ModifierDeckHeader (bad omen, corrosive spew,
±1/−2/+0, imbue 1/2, reveal with the Cassandra 8-button cap,
save/don't-save revealed cards, removed count, Hail perk, CS
sanctuary/party cards, faction icons, bless/curse and the
empower/enfeeble counters); ModifierDeckMenu (draw-pile
drag-reorder + send-to-bottom/shuffle/remove, discard
remove/return-top, removed pile with return, faction grid with
gray-out, perks menu with the Frosthaven opt-in); card zoom
- Loot deck: LootDeckWidget (player-gated draw, current-character
icon, discard stack, hidden when both piles empty); LootCardsMenu
(set owner, per-character loot totals, add card, enhance with the
reference material/herb/coin splits, special cards 1418/1419,
return top/bottom)
- Bottom DeckArea: loot deck left; the Character Decks toggle with the
reference open-state cycling (oneOpen/allOpen/noOpen per round
state; one-deck view for the current character during playTurns);
ally deck behind shouldShowAlliesDeck; global deck
- Pure helper modules ported from the reference: rules.ts (FH card
styling, inactive-for-rule, ally-deck gate, deck resolution),
modifierDeck.ts (pile derivations, faction cards), perks.ts (active
perk set, card-text tokens, descriptions, add/remove gating),
cards/lootCard.ts (values + per-character totals)
- App wiring: campaign data loaded on currentCampaign change (guarded
against out-of-order fetches); ability/AMD/loot menus and zooms
driven by live-derived state so open menus track pile changes;
Escape closes every dialog
Server:
- /i18n/ static mount: the in-game ability-text translation files the
card renderer resolves (the reference TranslationService data)
- Loot deck JSON gains pools (pool card ids per pool — the client
derives card gfx from pool key + index and reads the enhancements
map; ids only, since pool cards are the same live instances that
mutate in the piles)
- Modifier deck JSON gains removables (the counter totals the header
reads) plus load-time round-trip for saves written before the field
existed
Docs:
- PLAN.md: Phase 3 and Phase 4 marked complete (corrected the
'character ability decks' mislabel — ability decks are monster-only),
progress log entries for M3 and M4
svelte-check 0 errors; web tests 177/177; build OK; dart analyze
0 errors; dart test 592/592; scripts/ci.sh green.
Diffstat (limited to 'web/src/lib/game/line/statApplier.ts')
| -rw-r--r-- | web/src/lib/game/line/statApplier.ts | 350 |
1 files changed, 350 insertions, 0 deletions
diff --git a/web/src/lib/game/line/statApplier.ts b/web/src/lib/game/line/statApplier.ts new file mode 100644 index 0000000..1ce05dd --- /dev/null +++ b/web/src/lib/game/line/statApplier.ts @@ -0,0 +1,350 @@ +/** + * Monster-stat substitution (client port of the reference `StatApplier`, + * PORTING.md §8b). Resolves `%attack% - 1` style lines against a monster's + * actual stats, producing the display strings the ability-card lines need: + * a normal value, an elite value (prefixed `!£` when both are shown), and any + * leftover line text (prefixed `!`). Stand-alone formulas (e.g. `C+L`) are + * evaluated in place. + * + * The engine keeps its own Dart copy; the client needs it to render ability + * cards faithfully. It operates on the monster's level stats (from `/data/`) + * and the standee types present, not on live state. + */ + +import { calculateFormula } from './statCalculator'; + +/** MonsterType index: 0 normal, 1 elite, 2 boss, 3 summon. */ +export type MonsterType = 0 | 1 | 2 | 3; +const ELITE: MonsterType = 1; + +/** One stat block (`normal` / `elite` / a boss level's inline stats). */ +export interface StatBlock { + health?: number | string; + move?: number | string; + attack?: number | string; + range?: number; + attributes?: string[]; +} + +/** The monster's stats for its current level (already level-resolved). */ +export interface StatLevel { + normal?: StatBlock; + elite?: StatBlock; + /** Present when the level is a boss (its stats live inline on the level). */ + boss?: StatBlock; +} + +/** The data the applier needs about a monster. */ +export interface StatMonster { + level: StatLevel; + /** The `MonsterType` of each standee present. */ + standeeTypes: MonsterType[]; + /** Whether the monster row is the active one. */ + isActive: boolean; +} + +/** Formula + display context. */ +export interface StatApplierContext { + characterCount?: number; + level?: number; + /** The "no standees" setting (shows both stats when the monster is active). */ + noStandees?: boolean; +} + +/** Resolve a stat to a number, or null when a formula cannot be evaluated. */ +function calcStat(value: number | string | undefined, ctx: StatApplierContext): number | null { + if (value == null) return null; + if (typeof value === 'number') return value; + return calculateFormula(value, ctx); +} + +/** The single characters the formula scanner treats as formula content. */ +const numberish = (ch: string): boolean => /^[\d ()xCL/*+-]+$/.test(ch); + +/** Pull the `{token: nr}` pairs out of a stat block's display attributes. */ +function parseTokens(attributes: string[] | undefined, ctx: StatApplierContext): Record<string, number> { + const map: Record<string, number> = {}; + for (let item of attributes ?? []) { + const sizeMod = item.charAt(0); + if (sizeMod === '^' || (sizeMod === '*' && item.length > 1)) { + item = item.substring(1); + } + if (item.charAt(0) === '%') { + for (let i = 1; i < item.length; i++) { + if (item.charAt(i) === '%') { + const token = item.substring(1, i); + let number = 0; + if (i !== item.length - 1) { + for (let j = i + 2; j < item.length; j++) { + if (item.charAt(j) === ' ' || j === item.length - 1) { + const nr = item.substring(i + 1, j + 1); + const res = calculateFormula(nr, ctx); + if (res != null) number = res; + break; + } + } + } + if (token === 'target' && number === 0) continue; + map[token] = number; + break; // only one token per attribute line + } + } + } + } + return map; +} + +/** The token values for the monster's normal or elite stats. */ +function getStatTokens( + monster: StatMonster, + isElite: boolean, + ctx: StatApplierContext +): Record<string, number> { + const { normal, elite, boss } = monster.level; + if (boss != null) { + if (isElite) return {}; + return parseTokens(boss.attributes, ctx); + } + const data = isElite ? elite : normal; + if (data == null) return {}; + return parseTokens(data.attributes, ctx); +} + +/** The condition tokens appended after an attack line (all but the stats). */ +const nonConditionStat = (item: string): boolean => + /[a-z]/.test(item) && + item !== 'shield' && + item !== 'retaliate' && + item !== 'range' && + item !== 'heal' && + item !== 'jump'; + +function applyStatForToken( + formula: string, + line: string, + sizeModifier: string, + startIndex: number, + endIndex: number, + monster: StatMonster, + showNormal: boolean, + showElite: boolean, + lastToken: string, + normalTokens: Record<string, number>, + eliteTokens: Record<string, number>, + ctx: StatApplierContext +): string[] { + if (!showElite && !showNormal) return [line]; + + const retVal: string[] = []; + const tokens: string[] = []; + const eTokens: string[] = []; + let normalValue = 0; + let eliteValue = 0; + let skipCalculation = false; + const normalBlock = monster.level.boss ?? monster.level.normal; + const eliteBlock = monster.level.elite; + + if (lastToken === 'attack') { + if (normalBlock == null) return []; + const calc = calcStat(normalBlock.attack, ctx); + if (calc != null) normalValue = calc; + else skipCalculation = true; + if (eliteBlock != null) { + const ec = calcStat(eliteBlock.attack, ctx); + if (ec != null) eliteValue = ec; + } + for (const item of Object.keys(normalTokens)) { + if (nonConditionStat(item)) tokens.push(`%${item}%`); + } + for (const item of Object.keys(eliteTokens)) { + if (nonConditionStat(item)) eTokens.push(`%${item}%`); + } + } else if (lastToken === 'range') { + if ((normalBlock?.range ?? 0) !== 0) { + normalValue = normalBlock?.range ?? 0; + if (eliteBlock != null) eliteValue = eliteBlock.range ?? 0; + } + } else if (lastToken === 'move') { + normalValue = calcStat(normalBlock?.move, ctx) ?? 0; + if (eliteBlock != null) eliteValue = calcStat(eliteBlock.move, ctx) ?? 0; + } else if (lastToken === 'shield') { + if (eliteBlock != null && eliteTokens.shield != null) eliteValue = eliteTokens.shield; + if (normalBlock != null && normalTokens.shield != null) normalValue = normalTokens.shield; + } else if (lastToken === 'retaliate') { + if (eliteBlock != null && eliteTokens.retaliate != null) eliteValue = eliteTokens.retaliate; + if (normalBlock != null && normalTokens.retaliate != null) + normalValue = normalTokens.retaliate; + } + + let normalResult = formula; + if (!skipCalculation) { + const res = calculateFormula(`${formula}+${normalValue}`, ctx); + if (res != null) normalResult = (res < 0 ? 0 : res).toString(); + else skipCalculation = true; + } + + let newStartOfLine = line.substring(0, startIndex); + if (showNormal) { + newStartOfLine += normalResult; + if (!skipCalculation) { + for (const item of tokens) { + newStartOfLine += `|${item}`; + const key = item.substring(1, item.length - 1); + const value = normalTokens[key] ?? 0; + if (value > 0) newStartOfLine += String(value); + } + } + } + + // Special case: uncalculable and only elites ("heed the pigs"). + if (eliteBlock != null && skipCalculation && showElite && !showNormal) { + newStartOfLine += normalResult; + } + + if (eliteBlock != null && !skipCalculation && showElite) { + if (showNormal) newStartOfLine += '/'; + retVal.push(newStartOfLine); + const eliteResult = + calculateFormula(`${formula}+${eliteValue}`, ctx) ?? 0; + const clamped = eliteResult < 0 ? 0 : eliteResult; + let eliteString = `!${sizeModifier}£${clamped}`; + for (const item of eTokens) { + eliteString += `|${item}`; + const key = item.substring(1, item.length - 1); + const value = eliteTokens[key]!; + if (value > 0) eliteString += String(value); + } + retVal.push(eliteString); + } else { + retVal.push(newStartOfLine); + } + + if (endIndex < line.length) { + const leftOver = `!${sizeModifier}${line.substring(endIndex + 1, line.length)}`; + retVal.push(leftOver); + } + return retVal; +} + +/** + * Apply the monster's stats to a line. Returns the list of display strings + * (usually one; more when an elite/normal split or trailing text is produced). + */ +export function applyMonsterStats( + lineInput: string, + sizeToken: string, + monster: StatMonster, + forceShowAll: boolean, + ctx: StatApplierContext = {} +): string[] { + let showElite = false; + const noStandees = ctx.noStandees ?? false; + if ((noStandees && monster.isActive) || monster.standeeTypes.includes(ELITE)) { + showElite = true; + } + let showNormal = false; + if ( + (noStandees && monster.isActive) || + monster.standeeTypes.some((t) => t !== ELITE) + ) { + showNormal = true; + } + if (forceShowAll) { + showElite = true; + showNormal = true; + } + + let line = lineInput; + let retVal: string[] = []; + + const normalTokens = getStatTokens(monster, false, ctx); + const eliteTokens = getStatTokens(monster, true, ctx); + + let lastToken = ''; + let isInToken = false; + let tokenStartIndex = 0; + + for (let i = 0; i < line.length; i++) { + if (line.charAt(i) === '%') { + if (!isInToken) { + isInToken = true; + tokenStartIndex = i + 1; + } else { + isInToken = false; + lastToken = line.substring(tokenStartIndex, i); + } + } + + const isStart = + (!isInToken && + (line.charAt(i) === '+' || + line.charAt(i) === '-' || + line.charAt(i) === 'C' || + line.charAt(i) === 'L')) || + line.charAt(i) === 'X' || + ((numberish(line.charAt(i)) && lastToken === '') && + (i === 0 || line.charAt(i - 1) === ' ')); + + if (isStart) { + let formula = line.charAt(i); + const startIndex = i; + let endIndex = i; + + for (let j = i + 1; j < lineInput.length; j++) { + const val = lineInput.charAt(j); + if (numberish(val) || val === 'd') { + if (val !== ' ') formula += val; + endIndex = j; + } else { + i = j; + if (lineInput.charAt(i - 1) === ' ') { + i = j - 1; + endIndex -= 1; + } + if (i > 0 && lineInput.charAt(i - 1) === '(') { + i = j - 1; + endIndex -= 1; + formula = formula.substring(0, formula.length - 1); + if (i > 1 && lineInput.charAt(i - 2) === ' ') { + i = j - 1; + endIndex -= 1; + } + } + break; + } + } + + if ( + (formula.length > 1 && lastToken !== '') || + formula.length > 2 + ) { + if (lastToken !== '') { + retVal = applyStatForToken( + formula, + line, + sizeToken, + startIndex, + endIndex, + monster, + showNormal, + showElite, + lastToken, + normalTokens, + eliteTokens, + ctx + ); + lastToken = ''; + if (retVal.length > 0) return retVal; + } else { + const result = calculateFormula(formula, ctx); + if (result != null) { + const r = result < 0 ? 0 : result; + line = line.slice(0, startIndex) + String(r) + line.slice(endIndex + 1); + } + } + } + } + } + + return [line]; +} |
