From 94e2850fb73005f3fb30af8489905e5cdfb6fac5 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Mon, 16 Nov 2026 22:19:39 +0100 Subject: Phase 4: cards and decks (M4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 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. --- web/src/lib/data/gameData.ts | 170 +++++- web/src/lib/game/cards/lootCard.ts | 71 +++ web/src/lib/game/cards/modifierCardGfx.ts | 142 +++++ web/src/lib/game/line/buildAbility.ts | 87 ++++ web/src/lib/game/line/frosthavenConverter.ts | 199 +++++++ web/src/lib/game/line/images.ts | 20 + web/src/lib/game/line/lineParser.ts | 389 ++++++++++++++ web/src/lib/game/line/lineStyle.ts | 52 ++ web/src/lib/game/line/statApplier.ts | 350 +++++++++++++ web/src/lib/game/line/statCalculator.ts | 140 +++++ web/src/lib/game/line/tokens.ts | 95 ++++ web/src/lib/game/line/types.ts | 155 ++++++ web/src/lib/game/modifierDeck.ts | 119 +++++ web/src/lib/game/perks.ts | 213 ++++++++ web/src/lib/game/rules.ts | 178 +++++++ web/src/lib/game/stats.ts | 20 +- web/src/lib/i18n/en.ts | 72 ++- web/src/lib/i18n/gameI18n.ts | 75 +++ web/src/lib/i18n/index.ts | 20 +- web/src/lib/protocol/types.ts | 155 +++++- web/src/lib/ui/CounterButton.svelte | 115 +++++ web/src/lib/ui/MainList.svelte | 19 +- web/src/lib/ui/MonsterRow.svelte | 44 +- web/src/lib/ui/StatusMenu.svelte | 16 +- web/src/lib/ui/cards/AbilityCardBack.svelte | 60 +++ web/src/lib/ui/cards/AbilityText.svelte | 200 ++++++++ web/src/lib/ui/cards/LootCard.svelte | 114 +++++ web/src/lib/ui/cards/ModifierCard.svelte | 124 +++++ web/src/lib/ui/cards/MonsterAbilityCard.svelte | 157 ++++++ web/src/lib/ui/decks/AbilityCardSlot.svelte | 121 +++++ web/src/lib/ui/decks/AbilityCardZoom.svelte | 71 +++ web/src/lib/ui/decks/AbilityCardsMenu.svelte | 307 +++++++++++ web/src/lib/ui/decks/DeckArea.svelte | 222 ++++++++ web/src/lib/ui/decks/LootCardsMenu.svelte | 492 ++++++++++++++++++ web/src/lib/ui/decks/LootDeckWidget.svelte | 163 ++++++ web/src/lib/ui/decks/LootEnhancementCounter.svelte | 77 +++ web/src/lib/ui/decks/ModifierCardZoom.svelte | 56 ++ web/src/lib/ui/decks/ModifierDeckHeader.svelte | 460 +++++++++++++++++ web/src/lib/ui/decks/ModifierDeckMenu.svelte | 570 +++++++++++++++++++++ web/src/lib/ui/decks/ModifierDeckWidget.svelte | 185 +++++++ 40 files changed, 6249 insertions(+), 46 deletions(-) create mode 100644 web/src/lib/game/cards/lootCard.ts create mode 100644 web/src/lib/game/cards/modifierCardGfx.ts create mode 100644 web/src/lib/game/line/buildAbility.ts create mode 100644 web/src/lib/game/line/frosthavenConverter.ts create mode 100644 web/src/lib/game/line/images.ts create mode 100644 web/src/lib/game/line/lineParser.ts create mode 100644 web/src/lib/game/line/lineStyle.ts create mode 100644 web/src/lib/game/line/statApplier.ts create mode 100644 web/src/lib/game/line/statCalculator.ts create mode 100644 web/src/lib/game/line/tokens.ts create mode 100644 web/src/lib/game/line/types.ts create mode 100644 web/src/lib/game/modifierDeck.ts create mode 100644 web/src/lib/game/perks.ts create mode 100644 web/src/lib/game/rules.ts create mode 100644 web/src/lib/i18n/gameI18n.ts create mode 100644 web/src/lib/ui/CounterButton.svelte create mode 100644 web/src/lib/ui/cards/AbilityCardBack.svelte create mode 100644 web/src/lib/ui/cards/AbilityText.svelte create mode 100644 web/src/lib/ui/cards/LootCard.svelte create mode 100644 web/src/lib/ui/cards/ModifierCard.svelte create mode 100644 web/src/lib/ui/cards/MonsterAbilityCard.svelte create mode 100644 web/src/lib/ui/decks/AbilityCardSlot.svelte create mode 100644 web/src/lib/ui/decks/AbilityCardZoom.svelte create mode 100644 web/src/lib/ui/decks/AbilityCardsMenu.svelte create mode 100644 web/src/lib/ui/decks/DeckArea.svelte create mode 100644 web/src/lib/ui/decks/LootCardsMenu.svelte create mode 100644 web/src/lib/ui/decks/LootDeckWidget.svelte create mode 100644 web/src/lib/ui/decks/LootEnhancementCounter.svelte create mode 100644 web/src/lib/ui/decks/ModifierCardZoom.svelte create mode 100644 web/src/lib/ui/decks/ModifierDeckHeader.svelte create mode 100644 web/src/lib/ui/decks/ModifierDeckMenu.svelte create mode 100644 web/src/lib/ui/decks/ModifierDeckWidget.svelte (limited to 'web/src/lib') diff --git a/web/src/lib/data/gameData.ts b/web/src/lib/data/gameData.ts index 2511022..10e1c60 100644 --- a/web/src/lib/data/gameData.ts +++ b/web/src/lib/data/gameData.ts @@ -5,6 +5,11 @@ * server is the single source and the client fetches on demand and caches. */ +import type { + GraphicPositional, + MonsterAbilityCard +} from '../protocol/types'; + // --- Raw JSON shapes (the subset the UI needs) ---------------------------- interface RawClass { @@ -14,6 +19,9 @@ interface RawClass { hidden?: boolean; color: string | string[]; colorSecondary?: string | string[]; + /** `adds`/`removes` per perk slot (the reference `PerkModel`). */ + perks?: { text?: string; adds?: string[]; removes?: string[] }[]; + perksFH?: { text?: string; adds?: string[]; removes?: string[] }[]; } interface RawMonsterStats { @@ -46,6 +54,14 @@ interface RawEdition { classes: RawClass[]; monsters: Record; scenarios: Record; + /** Monster ability-card decks (the reference `MonsterAbilityDeckModel`). */ + monsterAbilities?: RawMonsterAbilityDeck[]; +} + +interface RawMonsterAbilityDeck { + name: string; + edition: string; + cards: unknown[]; } // --- UI-facing types ------------------------------------------------------- @@ -60,6 +76,19 @@ export interface ClassData { colorSecondary: string; /** `/images/class-icons/.png` */ icon: string; + /** The `adds` graphic list per perk slot (the reference `perks`). */ + perks: string[][]; + perksFH: string[][]; + /** The full perk-slot data (text + adds + removes) for the perks menu. */ + perkDetails: PerkDetail[]; + perkDetailsFH: PerkDetail[]; +} + +/** One perk slot (the reference `PerkModel`). */ +export interface PerkDetail { + text: string; + adds: string[]; + removes: string[]; } export interface MonsterData { @@ -90,6 +119,12 @@ export interface CampaignData { monsters: MonsterData[]; /** Scenario names in file order. */ scenarios: ScenarioData[]; + /** + * Monster ability-card decks, keyed by deck name (the reference + * `MonsterAbilityDeckModel`). The client reconstructs full cards from + * these when state references a card by `{nr, deck}`. + */ + abilityDecks: Record; } export function firstColor(value: string | string[] | undefined, fallback = '000000') { @@ -101,12 +136,54 @@ function escapePathSegment(value: string): string { return encodeURIComponent(value); } +/** + * Parse one ability-card raw entry into a full {@link MonsterAbilityCard}. + * Mirrors the reference `MonsterAbilityDeckModel.fromJson`: the card is a + * JSON array of `[optionalTitle, nr, shuffle, initiative, optionalGraphics, + * ...lines]` where the title (a leading string) and the graphics list (at + * index 3, a list of `{gfx,x,y,scale?,angle?}`) are both optional. + */ +function parseAbilityCard(raw: unknown[], deckName: string): MonsterAbilityCard { + let title = deckName; + let arr = raw; + if (typeof arr[0] === 'string') { + title = arr[0] as string; + arr = arr.slice(1); + } + const nr = arr[0] as number; + const shuffle = arr[1] as boolean; + const initiative = arr[2] as number; + let rest = arr.slice(3); + let graphics: GraphicPositional[] = []; + if (Array.isArray(rest[0])) { + graphics = (rest[0] as Array>).map((g) => ({ + gfx: g.gfx as string, + x: g.x as number, + y: g.y as number, + scale: (g.scale as number | undefined) ?? 1, + angle: (g.angle as number | undefined) ?? 0 + })); + rest = rest.slice(1); + } + return { + title, + nr, + shuffle, + initiative, + lines: rest as string[], + deck: deckName, + graphics + }; +} + // --- The loader ------------------------------------------------------------ export class GameDataClient { private campaignsPromise: Promise | null = null; private campaignsCache: string[] | null = null; private readonly cache = new Map>(); + /** Resolved campaign data (populated as each fetch lands) for sync lookups. */ + private readonly loaded = new Map(); private readonly roomsCache = new Map[]> | null>>(); constructor(private readonly base = '/data') {} @@ -135,21 +212,65 @@ export class GameDataClient { if (!r.ok) throw new Error(`failed to load campaign ${campaign}`); return r.json(); }) - .then((raw: RawEdition) => ({ - edition: raw.edition, - classes: raw.classes.map((c) => this.toClass(c)), - monsters: Object.entries(raw.monsters).map(([name, m]) => - this.toMonster(name, m, raw.edition) - ), - scenarios: Object.entries(raw.scenarios).map(([name, s]) => ({ - name, - monsters: s.monsters ?? [] - })) - })); + .then((raw: RawEdition) => { + const abilityDecks: Record = {}; + for (const deck of raw.monsterAbilities ?? []) { + abilityDecks[deck.name] = deck.cards.map((c) => + parseAbilityCard(c as unknown[], deck.name) + ); + } + const data: CampaignData = { + edition: raw.edition, + classes: raw.classes.map((c) => this.toClass(c)), + monsters: Object.entries(raw.monsters).map(([name, m]) => + this.toMonster(name, m, raw.edition) + ), + scenarios: Object.entries(raw.scenarios).map(([name, s]) => ({ + name, + monsters: s.monsters ?? [] + })), + abilityDecks + }; + this.loaded.set(campaign, data); + return data; + }); this.cache.set(campaign, promise); return promise; } + /** + * The monster model for [name] in [campaign] (by name or display name), + * or null when the campaign data is not yet loaded. Used to resolve a + * state monster (keyed by model name) to its stats, deck, and art. + */ + findMonster(campaign: string, name: string): MonsterData | null { + const data = this.loaded.get(campaign); + if (!data) return null; + return ( + data.monsters.find((m) => m.name === name || m.display === name) ?? null + ); + } + + /** The ability cards for a monster-ability [deck] in [campaign]. */ + abilityCards(campaign: string, deck: string): MonsterAbilityCard[] { + return this.loaded.get(campaign)?.abilityDecks[deck] ?? []; + } + + /** + * The full ability card for a state reference `{deck, nr}` in [campaign] — + * the client reconstructs it from the edition data (state carries only the + * reference). Null when the campaign is not loaded or the card is unknown. + */ + abilityCard( + campaign: string, + deck: string, + nr: number + ): MonsterAbilityCard | null { + const cards = this.loaded.get(campaign)?.abilityDecks[deck]; + if (!cards) return null; + return cards.find((c) => c.nr === nr) ?? null; + } + /** * The addable section names for a scenario, mirroring the server's * `ScenarioModel`: the rooms file is keyed by the scenario number (the @@ -190,6 +311,14 @@ export class GameDataClient { private toClass(c: RawClass): ClassData { const name = c.name; + const toDetails = ( + perks: RawClass['perks'] + ): PerkDetail[] => + (perks ?? []).map((p) => ({ + text: p.text ?? '', + adds: p.adds ?? [], + removes: p.removes ?? [] + })); return { id: name, name, @@ -198,10 +327,27 @@ export class GameDataClient { health: c.health, color: firstColor(c.color), colorSecondary: firstColor(c.colorSecondary, firstColor(c.color)), - icon: `/images/class-icons/${escapePathSegment(name)}.png` + icon: `/images/class-icons/${escapePathSegment(name)}.png`, + perks: (c.perks ?? []).map((p) => p.adds ?? []), + perksFH: (c.perksFH ?? []).map((p) => p.adds ?? []), + perkDetails: toDetails(c.perks), + perkDetailsFH: toDetails(c.perksFH) }; } + /** + * The character class for [name] in [campaign] (by name or display + * name), or null when the campaign data is not yet loaded. Used by the + * modifier-card gfx resolver for perk (`P`) graphics. + */ + classByName(campaign: string, name: string): ClassData | null { + const data = this.loaded.get(campaign); + if (!data) return null; + return ( + data.classes.find((c) => c.name === name || c.id === name) ?? null + ); + } + private toMonster(name: string, m: RawMonster, edition: string): MonsterData { const display = m.display ?? name; const gfx = m.gfx ?? display; diff --git a/web/src/lib/game/cards/lootCard.ts b/web/src/lib/game/cards/lootCard.ts new file mode 100644 index 0000000..802c92f --- /dev/null +++ b/web/src/lib/game/cards/lootCard.ts @@ -0,0 +1,71 @@ +/** + * Loot-card value (Phase 4 §6(e)): the port of the server's + * `LootCard.getValue()` — the client recomputes it for display because the + * value also depends on the current party size (which is in the state). + */ + +import type { LootCard, LootPoolKey } from '$lib/protocol/types'; + +const HIGH_CHAR_COUNT = 4; +const LOW_CHAR_COUNT = 2; + +// The pool card layout (mirrors the server's `_initPools`): the pool ids cross +// the wire in id order, so the gfx of a pool card is derivable from its key +// and index. Coin 1: ids 1-12, coin 2: 13-18, coin 3: 19-20; materials/herbs +// use their key as the gfx. +const COIN_1_COUNT = 12; +const COIN_2_COUNT = 6; + +/** The `gfx` of the pool card at [key][index] (the `resourceType` arg). */ +export function poolCardGfx(key: LootPoolKey, index: number): string { + if (key === 'coin') { + if (index < COIN_1_COUNT) return 'coin 1'; + if (index < COIN_1_COUNT + COIN_2_COUNT) return 'coin 2'; + return 'coin 3'; + } + return key; +} + +/** + * The per-character loot total for [ownerId] of [lootName] (the reference + * `_LootListTile._getLootAmount`): coins count 1/2/3 by their gfx suffix + * plus enhancement; other loot uses its card value. + */ +export function characterLootTotal( + discardPile: LootCard[], + ownerId: string, + lootName: string, + characterCount: number +): number { + let value = 0; + for (const item of discardPile) { + if (item.owner === ownerId && item.gfx.includes(lootName)) { + if (lootName === 'coin') { + if (item.gfx.endsWith('3')) value += 3; + else if (item.gfx.endsWith('2')) value += 2; + else value += 1; + value += item.enhanced; + } else { + const itemValue = lootValue(item, characterCount); + if (itemValue !== null) value += itemValue; + } + } + } + return value; +} + +/** The displayed value, or null when the card shows no number. */ +export function lootValue(card: LootCard, characterCount: number): number | null { + let value = 1; + if (card.lootType === 1) { + return card.enhanced > 0 ? card.enhanced : null; + } + if (card.enhanced > 0) value += card.enhanced; + if (characterCount >= HIGH_CHAR_COUNT) return value; + if (card.baseValue === 1) { + value++; + } else if (characterCount <= LOW_CHAR_COUNT && card.baseValue === 2) { + value++; + } + return value; +} diff --git a/web/src/lib/game/cards/modifierCardGfx.ts b/web/src/lib/game/cards/modifierCardGfx.ts new file mode 100644 index 0000000..b27a693 --- /dev/null +++ b/web/src/lib/game/cards/modifierCardGfx.ts @@ -0,0 +1,142 @@ +/** + * Modifier-card graphics (Phase 4 §6(d)): the pure port of the reference + * `ModifierCardFrontViewModel` gfx logic. A modifier card carries only a + * `gfx` key; the image URL it renders is derived from that key plus the + * deck's `name` ("" = the shared party deck, "allies", or a character-class + * name): + * + * - `imbue-` → the perk's image under `attack/perks/` (plus an + * `imbue.png` corner marker); `imbue2-` gets `advancedImbue.png`. + * - `Demons-` / `Merchant-Guild-` / `Military-` prefixes are stripped and a + * faction marker is shown. + * - `P` resolves against the owning character's perk slot: `P5` → the + * first `adds` graphic of perk 5, `P5-2` → the last one. + * - A character deck shows the class icon as its corner marker; "allies" + * shows the allies icon. + * + * The served image root is `/images/` (the reference's `assets/images/`). + */ + +/** The deck-name value of the shared party deck. */ +export const GLOBAL_DECK = ''; +/** The deck-name value of the ally deck (Gloomhaven 2nd Edition). */ +export const ALLIES_DECK = 'allies'; + +const ATTACK = '/images/attack/'; + +export interface ModifierGfxInput { + gfx: string; +} + +/** The corner marker of the card rear (or empty when none). */ +export interface RearMarker { + has: boolean; + /** `/images/...` icon URL. */ + gfx: string; +} + +function isAllies(name: string): boolean { + return name === ALLIES_DECK; +} + +function isCharacter(name: string): boolean { + return name.length > 0 && !isAllies(name); +} + +/** Whether the front shows a corner marker (the reference `hasExtra`). */ +export function hasExtra(card: ModifierGfxInput, name: string): boolean { + return ( + card.gfx.startsWith('P') || + isAllies(name) || + card.gfx.includes('imbue') || + card.gfx.startsWith('Demons') || + card.gfx.startsWith('Merchant-Guild') || + card.gfx.startsWith('Military') + ); +} + +/** + * The front image URL (the reference `gfx` getter). `perks` is the owning + * character's `adds`-per-slot list (the caller chooses FH vs. regular); + * pass null for non-character decks. + */ +export function gfxUrl( + card: ModifierGfxInput, + name: string, + perks: string[][] | null = null +): string { + const isImbue = card.gfx.includes('imbue'); + const isImbue2 = card.gfx.includes('imbue2'); + let g = card.gfx; + + if (isImbue) { + g = g.replaceAll('imbue-', ''); + if (isImbue2) g = g.replaceAll('imbue2-', ''); + if (g !== 'plus1') g = `perks/${g}`; + } + + if (card.gfx.startsWith('Demons')) { + g = g.replaceAll('Demons-', ''); + } else if (card.gfx.startsWith('Merchant-Guild')) { + g = g.replaceAll('Merchant-Guild-', ''); + } else if (card.gfx.startsWith('Military')) { + g = g.replaceAll('Military-', ''); + } + + if (g.startsWith('P')) { + const list = perks; + if (list) { + g = g.substring(1); + if (g.endsWith('-2')) { + g = g.substring(0, g.length - 2); + const index = parseInt(g, 10); + if ( + Number.isInteger(index) && + index >= 0 && + index < list.length && + list[index].length > 0 + ) { + g = list[index][list[index].length - 1]; + } + } else { + const index = parseInt(g, 10); + if ( + Number.isInteger(index) && + index >= 0 && + index < list.length && + list[index].length > 0 + ) { + g = list[index][0]; + } + } + } + } + + return `${ATTACK}${g}.png`; +} + +/** The front corner-marker icon (the reference `extraGfx`); '' when none. */ +export function extraGfxUrl(card: ModifierGfxInput, name: string): string { + if (card.gfx.includes('imbue2')) return `${ATTACK}advancedImbue.png`; + if (card.gfx.includes('imbue')) return `${ATTACK}imbue.png`; + if (isAllies(name)) return `${ATTACK}allies.png`; + if (card.gfx.startsWith('Demons')) return '/images/demons.png'; + if (card.gfx.startsWith('Merchant-Guild')) + return '/images/merchant-guild.png'; + if (card.gfx.startsWith('Military')) return '/images/military.png'; + if (isCharacter(name)) + return `/images/class-icons/${encodeURIComponent(name)}.png`; + return ''; +} + +/** The rear corner marker (the reference `ModifierCardRear`). */ +export function rearMarker(name: string): RearMarker { + if (isAllies(name)) + return { has: true, gfx: `${ATTACK}allies.png` }; + if (isCharacter(name)) + return { + has: true, + gfx: `/images/class-icons/${encodeURIComponent(name)}.png` + }; + return { has: false, gfx: '' }; +} diff --git a/web/src/lib/game/line/buildAbility.ts b/web/src/lib/game/line/buildAbility.ts new file mode 100644 index 0000000..45c6e7a --- /dev/null +++ b/web/src/lib/game/line/buildAbility.ts @@ -0,0 +1,87 @@ +/** + * The ability-card rendering pipeline (PORTING.md §8b): pre-translate the + * card's lines with the in-game `t()`, run them through {@link parseLines} + * (expand → convert → per-line stat application → layout), and return the + * structured tree the Svelte renderer walks. Also builds the {@link + * StatMonster} the stat applier needs from the monster model + live standees. + */ + +import { gt } from '$lib/i18n/gameI18n'; +import { parseLines } from './lineParser'; +import type { MonsterAbilityCard, MonsterType } from '$lib/protocol/types'; +import type { MonsterData } from '$lib/data/gameData'; +import type { ColumnNode } from './types'; +import type { StatBlock, StatLevel, StatMonster } from './statApplier'; + +export interface AbilityRenderOptions { + /** Frosthaven style (icon-only tokens, sub-line boxes). */ + fh: boolean; + /** Left-aligned boss stat card layout. */ + left?: boolean; + /** Resolve stats per line (the reference's `!noCalculation`). */ + applyStats?: boolean; + /** Force the elite/normal split (the reference's `calculateAll`). */ + applyAll?: boolean; + scale?: number; + /** The monster is a flyer (move token → flying graphic). */ + flying?: boolean; +} + +type StatSource = { + health?: number | string; + move?: number | string; + attack?: number | string; + range?: number; + attributes?: string[]; +}; + +function toBlock(source: StatSource | undefined): StatBlock | undefined { + if (!source) return undefined; + return { + health: source.health, + move: source.move, + attack: source.attack, + range: source.range, + attributes: source.attributes + }; +} + +/** + * The stat-applier view of a monster at [level], for the standees currently + * in play. Built from the edition's level stats + the live standee types. + */ +export function statMonsterFor( + monster: MonsterData, + level: number, + standeeTypes: MonsterType[], + isActive: boolean +): StatMonster { + const raw = monster.levels.find((l) => l.level === level) ?? monster.levels[0]; + const statLevel: StatLevel = { + normal: toBlock(raw?.normal as StatSource | undefined), + elite: toBlock(raw?.elite as StatSource | undefined), + boss: toBlock(raw?.boss as StatSource | undefined) + }; + return { level: statLevel, standeeTypes, isActive }; +} + +/** The full ability-card line tree (lines pre-translated, then parsed). */ +export function buildAbilityCardTree( + card: MonsterAbilityCard, + stat: StatMonster | null, + opts: AbilityRenderOptions +): ColumnNode { + const lines = card.lines.map(gt); + return parseLines(lines, { + left: opts.left ?? false, + applyStats: opts.applyStats ?? false, + applyAll: opts.applyAll ?? false, + align: opts.left ? 'left' : 'center', + frosthavenStyle: opts.fh, + scale: opts.scale ?? 1, + monster: stat, + flying: opts.flying ?? false, + bossStatCard: opts.left ?? false, + translate: gt + }); +} diff --git a/web/src/lib/game/line/frosthavenConverter.ts b/web/src/lib/game/line/frosthavenConverter.ts new file mode 100644 index 0000000..534efd9 --- /dev/null +++ b/web/src/lib/game/line/frosthavenConverter.ts @@ -0,0 +1,199 @@ +/** + * Frosthaven-style line conversion (client port of the reference + * `FrosthavenConverter`, PORTING.md §8b). Pure string → string: expands + * embedded newlines, rewrites keywords into token/line markers, and tracks the + * sub-line / conditional / element-use state so the line parser can lay lines + * out as the reference does (sub-lines boxed, element-use blocks, …). + */ + +const LOOKBACK = 2; + +/** Split lines containing `\n`, propagating the `^` / `^^` prefix. */ +export function expandEmbeddedNewlines(lines: string[]): string[] { + const result: string[] = []; + for (const line of lines) { + if (!line.includes('\n')) { + result.push(line); + continue; + } + const parts = line.split('\n'); + result.push(parts[0]); + const outerPrefix = parts[0].startsWith('^^') + ? '^^' + : parts[0].startsWith('^') + ? '^' + : ''; + for (let i = 1; i < parts.length; i++) result.push(outerPrefix + parts[i]); + } + return result; +} + +/** The keyword → token/line-marker rewrite + sub-line state machine. */ +export function convertLinesToFH(lines: string[], applyStats: boolean): string[] { + const retVal: string[] = []; + let isSubLine = false; + let isReallySubLine = false; + let isConditional = false; + let isElementUse = false; + + for (let i = 0; i < lines.length; i++) { + let startOfConditional = false; + let line = lines[i]; + + if (line === '[newLine]') line = ''; + + if ( + (line === '[r]' || line === '[s]') && + lines[i + 1]?.includes('%use') + ) { + isElementUse = true; + isConditional = true; + startOfConditional = true; + } + if ((line === '[/r]' || line === '[/s]') && isConditional) { + isConditional = false; + isElementUse = false; + } + + if (i > 0 && lines[i - 1].includes('%use')) startOfConditional = true; + if ( + i > 1 && + lines[i - LOOKBACK].includes('%use') && + (lines[i - 1] === '[r]' || lines[i - 1] === '[s]' || lines[i - 1] === '[c]') + ) { + startOfConditional = true; + } + + line = line.replaceAll('Affect', 'Target'); + line = line.replaceAll('damage', '%damage%'); + line = line.replaceAll('%damage%d', 'damaged'); + if (!applyStats) { + line = line.replaceAll(' - ', '-'); + line = line.replaceAll(' + ', '+'); + } + line = line.replaceAll('% ', '%'); + + if (line.startsWith('*')) { + if (isReallySubLine) retVal.push('[subLineEnd]'); + isReallySubLine = false; + isSubLine = false; + isConditional = false; + isElementUse = false; + } + + const isSubLineCandidate = + line.startsWith('^') && + (line[1] === '%' || + line.startsWith('^Self') || + line.startsWith('^-') || + line.startsWith('^+') || + line.startsWith('^Advantage') || + line.startsWith('^Target') || + line.startsWith('^%target%') || + line.startsWith('^Normal') || + line.startsWith('^all') || + (line.startsWith('^All') && + !line.startsWith('^All attacks') && + !line.startsWith('^All targets'))); + + if (line.startsWith('^') && isSubLine && !startOfConditional) { + if (isSubLineCandidate) { + if ( + !isReallySubLine && + (!isConditional || + (isElementUse && + !line.startsWith('^Perform') && + !line.startsWith('^^for each'))) + ) { + retVal.push('[subLineStart]'); + isReallySubLine = true; + } + + if ( + isElementUse && + (lines[i - 1]?.includes('use') || + (lines[i - LOOKBACK]?.includes('use') && + lines[i - 1]?.includes('[c]'))) && + !line.startsWith('^Target') && + !line.startsWith('^all') && + !line.startsWith('^All') && + !line.includes('instead') + ) { + line = line.substring(1); + if (retVal[retVal.length - 1] === '[subLineStart]') { + retVal.pop(); + } + isReallySubLine = false; + } + line = '!' + line; + line = line.replace(/Self/, 'self').replace(/All/, 'all'); + + if (retVal[retVal.length - 1] === '[subLineStart]') { + retVal[retVal.length - 1] = '![subLineStart]'; + } + } else { + isSubLine = false; + } + } + + if (line.startsWith('^') && isReallySubLine) { + if (retVal[retVal.length - 1] !== '[subLineStart]') { + retVal.push('!^[lineBreak]'); + } + line = '!' + line; + } else if ( + !line.startsWith('!') && + !line.startsWith('*') && + !line.startsWith('^') + ) { + if (!isSubLine && !line.includes('%use%')) { + isSubLine = true; + } else if (isReallySubLine) { + retVal.push('[subLineEnd]'); + isReallySubLine = false; + isSubLine = false; + } + } + + // Use iconography instead of words (applied to every line, last). + line = line.replaceAll('Target', '%target%'); + retVal.push(line); + } + + if (isReallySubLine && (!isConditional || isElementUse)) { + retVal.push('[subLineEnd]'); + } + return retVal; +} + +/** Whether the token's graphic should overflow its line (FH condition icons). */ +export function shouldOverflow(frosthavenStyle: boolean, iconToken: string): boolean { + if (!frosthavenStyle) return false; + const exact = [ + 'pierce', + 'brittle', + 'curse', + 'enfeeble', + 'bless', + 'invisible', + 'strengthen', + 'bane', + 'push', + 'pull', + 'poison', + 'wound', + 'infect', + 'chill', + 'disarm', + 'immobilize', + 'stun', + 'impair', + 'safeguard', + 'muddle' + ]; + return ( + exact.includes(iconToken) || + iconToken.includes('poison') || + iconToken.includes('wound') + ); +} diff --git a/web/src/lib/game/line/images.ts b/web/src/lib/game/line/images.ts new file mode 100644 index 0000000..78c10ac --- /dev/null +++ b/web/src/lib/game/line/images.ts @@ -0,0 +1,20 @@ +/** + * Ability-icon image URLs. The Dart server serves the reference app's + * `assets/images/abilities/` under `/images/abilities/`. In Frosthaven style a + * token's graphic gets the `_fh` suffix when the base token has a + * Gloomhaven/Frosthaven variant pair (the reference's `hasGHVersion`); the + * decision uses the base token, not the `_black`-suffixed filename. + */ + +import { hasGHVersion } from './tokens'; + +/** The icon URL for [gfx] (already resolved to its base / `_black` / flyer form). */ +export function abilityImage(gfx: string, baseToken: string, frosthavenStyle: boolean): string { + const suffix = frosthavenStyle && hasGHVersion(baseToken) ? '_fh' : ''; + return `/images/abilities/${gfx}${suffix}.png`; +} + +/** The divider graphic (`divider_fh.png`, or the boss variant for left cards). */ +export function dividerImage(boss: boolean): string { + return boss ? '/images/abilities/divider_boss_fh.png' : '/images/abilities/divider_fh.png'; +} diff --git a/web/src/lib/game/line/lineParser.ts b/web/src/lib/game/line/lineParser.ts new file mode 100644 index 0000000..ecd694f --- /dev/null +++ b/web/src/lib/game/line/lineParser.ts @@ -0,0 +1,389 @@ +/** + * The ability-line parser (client port of the reference + * `LineBuilder.createLines`, PORTING.md §8b). Takes the (already in-game + * translated) ability lines and produces the structured {@link ColumnNode} + * tree the Svelte renderer walks. It runs the reference's pipeline in order — + * expand embedded newlines → Frosthaven conversion (sub-line / conditional + * markers) → per-line monster-stat application → layout — mirroring the + * reference's container directives (`[c]`/`[r]`/`[s]`), the `!` + * right-part-of-last-line attach, the gray sub-line boxes, the dotted + * conditional boxes, element images and dividers. + * + * The tree is theme-free: the renderer decides font sizes, colors and which + * image assets to load (the `_fh` suffix, `_black` variants, dividers, …). + */ + +import { + applyMonsterStats, + type StatMonster +} from './statApplier'; +import { + convertLinesToFH, + expandEmbeddedNewlines, + shouldOverflow +} from './frosthavenConverter'; +import { TOKENS, hasGHVersion, isElement } from './tokens'; +import type { + Align, + ColumnNode, + ConditionalNode, + LineBuildOptions, + LineStyle, + Node, + RowNode, + SubLineNode +} from './types'; + +// --- Whole-tree text / image helpers (the reference's getAllTextInWidget / +// getAllImagesInWidget) ------------------------------------------------- + +function allText(node: Node): string { + switch (node.kind) { + case 'text': + return node.text; + // The element-use colon is a separate text segment; the element icon + // itself carries no text (matches the reference's getAllTextInWidget). + case 'elementUse': + case 'token': + return ''; + case 'row': + case 'rowgroup': + case 'column': + case 'subline': + case 'conditional': + return node.children.reduce((acc, c) => acc + allText(c), ''); + default: + return ''; + } +} + +function allImages(node: Node): string[] { + switch (node.kind) { + case 'token': + return [node.gfx]; + case 'elementUse': + return [node.element, 'use']; + case 'image': + return [node.gfx]; + case 'divider': + return ['divider']; + case 'row': + case 'rowgroup': + case 'column': + case 'subline': + case 'conditional': + return node.children.flatMap(allImages); + default: + return []; + } +} + +/** A fresh empty row. */ +function newRow(align: Align, children: Node[] = []): RowNode { + return { kind: 'row', align, children }; +} + +export function parseLines(lines: string[], opts: LineBuildOptions): ColumnNode { + const { + left, + applyStats, + applyAll, + align, + frosthavenStyle, + monster, + flying = false, + bossStatCard = false, + translate = (s) => s + } = opts; + + const rowMainAlign: Align = + align === 'left' ? 'left' : align === 'right' ? 'right' : 'center'; + + let strings = expandEmbeddedNewlines([...lines]); + if (frosthavenStyle) { + strings = convertLinesToFH(strings, applyStats); + } else { + strings = strings.filter((s) => s !== '[newLine]' && s !== '[subLineEnd]'); + } + + // Containers (the reference's specialized-layout stacks). + const top: Node[] = []; + const inColumn: Node[] = []; + const inRow: Node[] = []; + const inInnerRow: Node[] = []; + let isInColumn = false; + let isInRow = false; + let isColumnInRow = false; + let hasInnerRow = false; + + /** The container a freshly built row / image / divider is added to. */ + function target(): Node[] { + if (hasInnerRow) return inInnerRow; + if (isInColumn && (!isInRow || isColumnInRow)) return inColumn; + if (isInRow && !isInColumn) return inRow; + return top; + } + + /** The most recent row, for `!` attach + sub-line background building. */ + let lastRow: RowNode | null = null; + + // The reference's buildFHStyleBackgrounds: split the last row at the + // `[subLineStart]` marker, grouping the following segments into sub-line + // rows on `[lineBreak]`. + function buildSubLineBackgrounds() { + if (!lastRow) return; + const parts = lastRow.children; + let startIdx = -1; + for (let i = 0; i < parts.length; i++) { + const p = parts[i]; + if (p.kind === 'text' && p.text.includes('[subLineStart]')) { + startIdx = i; + break; + } + } + if (startIdx < 0) return; + + const mainParts = parts.slice(0, startIdx); + const groups: Node[][] = []; + let current: Node[] = []; + for (let j = startIdx + 1; j < parts.length; j++) { + const p = parts[j]; + if (p.kind === 'text' && p.text.includes('[lineBreak]')) { + groups.push(current); + current = []; + } else { + current.push(p); + } + } + groups.push(current); + + const subLine: SubLineNode = { + kind: 'subline', + boss: bossStatCard, + conditional: false, + children: groups.map((g) => newRow(rowMainAlign, g)) + }; + lastRow.children = [newRow(rowMainAlign, mainParts), subLine]; + } + + for (let i = 0; i < strings.length; i++) { + let line = strings[i]; + let sizeToken = ''; + let isRightPart = false; + let styleToUse: LineStyle = 'normal'; + const textParts: Node[] = []; + + // Sub-line background (the gray box) — closes the open sub-line. + if (line.includes('[subLineEnd]')) { + buildSubLineBackgrounds(); + continue; + } + + // Layout directives. + if (line === '[c]') { + isInColumn = true; + if (isInRow) isColumnInRow = true; + continue; + } + if (line === '[/c]') { + isInColumn = false; + const column: ColumnNode = { kind: 'column', align, children: [...inColumn] }; + inColumn.length = 0; + if (isColumnInRow) inRow.push(column); + else top.push(column); + continue; + } + if (line === '[r]') { + isInRow = true; + continue; + } + if (line === '[s]') { + hasInnerRow = true; + continue; + } + if (line === '[/s]' || line === '[/r]') { + const isInner = line === '[/s]'; + if (isInner) hasInnerRow = false; + else isInRow = false; + + const src = isInner ? inInnerRow : inRow; + const texts = src.map(allText).join(''); + const elementUse = texts.includes(' :'); + const conditional = elementUse; + const columnHack = + texts.lastIndexOf(' :') !== texts.indexOf(' :'); + const rowChildren = columnHack ? src.slice(1) : [...src]; + src.length = 0; + + const row = newRow(rowMainAlign, rowChildren); + + if (frosthavenStyle && conditional) { + const outer = isInner ? inColumn : top; + const belongs = computeBelongs(outer, row); + const cond: ConditionalNode = { + kind: 'conditional', + elementUse, + belongs, + boss: bossStatCard, + children: [row] + }; + outer.push(cond); + } else if (isInner) { + inColumn.push(row); + } else { + top.push(row); + } + continue; + } + + // Element image (¤). + if (line.startsWith('¤')) { + const element = line.substring(1); + const node: Node = { kind: 'image', gfx: element, element: isElement(element) }; + target().push(node); + continue; + } + + // Right-part-of-last-line attach. + if (line.startsWith('!')) { + isRightPart = true; + line = line.substring(1); + } + // Small / divider. + if (line.startsWith('*')) { + sizeToken = '*'; + styleToUse = 'small'; + line = line.substring(1); + if (line.startsWith('....')) { + styleToUse = 'divider'; + if (line.startsWith('*')) { + line = line.substring(1); + styleToUse = 'dividerThin'; + } + // In FH (or left-aligned) the divider is a picture. + if (frosthavenStyle || align === 'left') { + const node: Node = { kind: 'divider', thin: styleToUse === 'dividerThin', boss: align === 'left' }; + target().push(node); + continue; + } + } + } + // Mid / mid-squished. + if (line.startsWith('^')) { + sizeToken = '^'; + styleToUse = 'mid'; + line = line.substring(1); + if (line.startsWith('^')) { + styleToUse = 'midSquished'; + line = line.substring(1); + } + } + // Granted line (no stat application) vs. stat application. + if (line.startsWith('>')) { + line = line.substring(1); + } else if (applyStats && monster) { + const statLines = applyMonsterStats(line, sizeToken, monster, applyAll); + line = statLines.shift() ?? ''; + if (statLines.length > 0) strings.splice(i + 1, 0, ...statLines); + } + + // Parse the line into segments (%, £, Å). + let partStart = 0; + let isIconPart = false; + let addText = true; + for (let ci = 0; ci < line.length; ci++) { + const ch = line[ci]; + if (ch === '|') addText = false; + if (ch === '%') { + if (isIconPart) { + const iconToken = line.substring(partStart, ci); + let iconGfx = iconToken; + if (monster && iconToken === 'move' && flying) iconGfx = 'flying'; + if (left) { + const tokenVal = TOKENS[iconToken]; + if (tokenVal && /[a-z]/.test(tokenVal)) iconGfx += '_black'; + } + if (iconToken === 'use') { + // Element-use: consume the previous element icon, overlay "use". + const prev = textParts.pop(); + const element = + prev && prev.kind === 'token' ? prev.token : iconToken; + textParts.push({ kind: 'elementUse', element, style: styleToUse }); + textParts.push({ + kind: 'text', + text: frosthavenStyle ? ' :' : ' : ', + style: 'normal' + }); + } else { + const rawLabel = TOKENS[iconToken] ?? null; + const label = + frosthavenStyle || rawLabel == null + ? null + : translate(rawLabel); + if (addText && label) { + textParts.push({ kind: 'text', text: label, style: styleToUse }); + } + textParts.push({ + kind: 'token', + token: iconToken, + gfx: iconGfx, + overflow: shouldOverflow(frosthavenStyle, iconGfx), + isElement: isElement(iconToken), + style: styleToUse + }); + } + isIconPart = false; + addText = true; + } else { + if (ci > 0 && partStart < ci) { + let textPart = line.substring(partStart, ci); + if (line[ci - 1] === '|') + textPart = line.substring(partStart, ci - 1); + textParts.push({ kind: 'text', text: textPart, style: styleToUse }); + } + isIconPart = true; + } + partStart = ci + 1; + } + if (ch === '£') { + partStart = ci + 1; + if (styleToUse === 'normal') styleToUse = 'elite'; + else if (styleToUse === 'small') styleToUse = 'eliteSmall'; + else if (styleToUse === 'mid') styleToUse = 'eliteMid'; + } + if (ch === 'Å') styleToUse = 'special'; + } + if (partStart < line.length) { + textParts.push({ kind: 'text', text: line.substring(partStart), style: styleToUse }); + } + + // Attach to the previous row, or add a fresh one. + if (isRightPart && lastRow) { + lastRow.children.push(...textParts); + } else { + const row = newRow(rowMainAlign, textParts); + target().push(row); + lastRow = row; + } + } + + return { kind: 'column', align, children: top }; +} + +/** Whether the conditional box draws the top "element" banner. */ +function computeBelongs(outer: Node[], row: Node): boolean { + let belongs = true; + if (outer.length === 0) { + belongs = false; + } else { + const last = outer[outer.length - 1]; + if (last.kind === 'divider') belongs = false; + } + const graphics = allImages(row); + if (graphics.length === 2 && isElement(graphics[0]) && isElement(graphics[1])) + belongs = false; + return belongs; +} + +// Re-export for convenience in tests / the renderer. +export { hasGHVersion }; diff --git a/web/src/lib/game/line/lineStyle.ts b/web/src/lib/game/line/lineStyle.ts new file mode 100644 index 0000000..6d10482 --- /dev/null +++ b/web/src/lib/game/line/lineStyle.ts @@ -0,0 +1,52 @@ +/** + * Resolved font metrics for an ability-line segment (the reference `LineStyles`, + * PORTING.md §8b). The web card is centre-aligned and non-left, matching the + * reference's ability-card `createLines` call; only the Frosthaven/Gloomhaven + * split and the elite color vary. Sizes are in px at `scale` 1 — the renderer + * multiplies by the card's `scale`. + */ + +import type { LineStyle } from './types'; + +export interface ResolvedLine { + /** Font size in px at scale 1. */ + size: number; + /** Unitless line-height. */ + height: number; + color: string; +} + +const WHITE = '#ffffff'; +const BLACK = '#000000'; +const ELITE = '#ffe600'; // Colors.yellow + +export function resolveStyle( + style: LineStyle, + frosthavenStyle: boolean, + left: boolean +): ResolvedLine { + const color = left ? BLACK : WHITE; + switch (style) { + case 'normal': + return { size: frosthavenStyle ? 13.1 : 12.56, height: frosthavenStyle ? 0.84 : 0.85, color }; + case 'mid': + return { size: frosthavenStyle ? 9.52 : 8.8, height: frosthavenStyle ? 1.0 : 0.85, color }; + case 'midSquished': + return { size: frosthavenStyle ? 9.52 : 8.8, height: 0.8, color }; + case 'small': + return { size: 8.0, height: 0.8, color }; + case 'elite': + return { size: frosthavenStyle ? 13.1 : 12.56, height: frosthavenStyle ? 0.84 : 0.85, color: ELITE }; + case 'eliteSmall': + return { size: 8.0, height: 1.0, color: ELITE }; + case 'eliteMid': + return { size: frosthavenStyle ? 9.52 : 8.8, height: frosthavenStyle ? 1.0 : 0.85, color: ELITE }; + case 'divider': + return { size: 6.4, height: 0.7, color }; + case 'dividerThin': + return { size: 4.8, height: 0.1, color }; + case 'special': + // The reference renders this as transparent Majalla text (a spacer). + return { size: 8.8, height: 1.0, color: 'transparent' }; + } +} 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 { + const map: Record = {}; + 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 { + 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, + eliteTokens: Record, + 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]; +} diff --git a/web/src/lib/game/line/statCalculator.ts b/web/src/lib/game/line/statCalculator.ts new file mode 100644 index 0000000..1f7887b --- /dev/null +++ b/web/src/lib/game/line/statCalculator.ts @@ -0,0 +1,140 @@ +/** + * Formula evaluation (client port of the reference `StatCalculator`, PORTING.md + * §8b). The engine keeps its own Dart copy for its internal use; the client + * needs the same substitution + arithmetic to resolve `%attack% - 1` style + * lines while rendering ability cards. + * + * Substitutes `C` (current character count, clamped to ≥ 2) and `L` (level), + * then evaluates with the reference parser: integer arithmetic where `/` + * rounds up (ceil) and `d` rounds down (floor), and `<` / `>` / `=` produce + * 1 / 0. + */ + +export interface FormulaContext { + /** Current number of characters (clamped to a minimum of 2). */ + characterCount?: number; + /** Current game level. */ + level?: number; +} + +/** The sentinel used past the end of the string (matches no real character). */ +const END = '\u0000'; + +class FormulaParser { + private pos = -1; + private ch = END; + + constructor(private readonly str: string) {} + + /** Run the grammar and return the value, or null when unparseable. */ + parse(): number | null { + try { + this.nextChar(); + const result = this.parseCondition(); + if (this.pos < this.str.length) return null; + return result; + } catch { + return null; + } + } + + private nextChar(): void { + this.pos += 1; + this.ch = this.pos < this.str.length ? this.str.charAt(this.pos) : END; + } + + private eat(charToEat: string): boolean { + while (this.ch === ' ') this.nextChar(); + if (this.ch === charToEat) { + this.nextChar(); + return true; + } + return false; + } + + // Grammar (the reference StatCalculator): + // condition = expression | expression (<|>|=) expression + // expression = term | expression (+|-) term + // term = factor | term (*|x) factor | term (/) factor | term (d) factor + // factor = +factor | -factor | ( expression ) | number + // + // `*` and `x` both multiply; `/` rounds up, `d` rounds down; the + // comparison operators yield 1 (true) or 0 (false). + + private parseCondition(): number { + let result = this.parseExpression(); + for (;;) { + if (this.eat('<')) result = result < this.parseExpression() ? 1 : 0; + else if (this.eat('>')) result = result > this.parseExpression() ? 1 : 0; + else if (this.eat('=')) result = result === this.parseExpression() ? 1 : 0; + else return result; + } + } + + private parseExpression(): number { + let result = this.parseTerm(); + for (;;) { + if (this.eat('+')) result += this.parseTerm(); + else if (this.eat('-')) result -= this.parseTerm(); + else return result; + } + } + + private parseTerm(): number { + let result = this.parseFactor(); + for (;;) { + if (this.eat('*')) result *= this.parseFactor(); + else if (this.eat('x')) result *= this.parseFactor(); + else if (this.eat('/')) result = Math.ceil(result / this.parseFactor()); + else if (this.eat('d')) result = Math.floor(result / this.parseFactor()); + else return result; + } + } + + private parseFactor(): number { + if (this.eat('+')) return this.parseFactor(); + if (this.eat('-')) return -this.parseFactor(); + + if (this.eat('(')) { + const result = this.parseExpression(); + if (!this.eat(')')) throw new Error("missing ')'"); + return result; + } + + const first = this.ch.codePointAt(0) ?? 0; + if (first >= 48 && first <= 57) { + const startPos = this.pos; + while ( + this.ch !== END && + this.ch.codePointAt(0)! >= 48 && + this.ch.codePointAt(0)! <= 57 + ) { + this.nextChar(); + } + return parseInt(this.str.substring(startPos, this.pos), 10); + } + + throw new Error(`unexpected: ${this.ch}`); + } +} + +/** Evaluate a formula string (no C / L substitution). Null when malformed. */ +export function evalFormula(str: string): number | null { + return new FormulaParser(str).parse(); +} + +/** + * Substitute C / L from [ctx] (defaulting C=2, L=1) then evaluate. Mirrors the + * reference `StatCalculator.calculateFormula`; returns null when the result is + * not an integer. + */ +export function calculateFormula( + str: string, + ctx: FormulaContext = {} +): number | null { + const C = Math.max(2, ctx.characterCount ?? 2); + const L = ctx.level ?? 1; + const formula = str.replaceAll('C', String(C)).replaceAll('L', String(L)); + const result = evalFormula(formula); + return typeof result === 'number' ? result : null; +} diff --git a/web/src/lib/game/line/tokens.ts b/web/src/lib/game/line/tokens.ts new file mode 100644 index 0000000..ed070ba --- /dev/null +++ b/web/src/lib/game/line/tokens.ts @@ -0,0 +1,95 @@ +/** + * The ability-line token table and element check (the reference `LineBuilder`'s + * `tokens` map + `isElement`, PORTING.md §8b). Token keys are the `%token%` + * names used in card lines; values are the display labels (translated by the + * in-game `t()` at render time, so the English label is the key's translation). + */ + +export const TOKENS: Record = { + attack: 'Attack', + move: 'Move', + teleport: 'Teleport', + range: 'Range', + heal: 'Heal', + target: 'Target', + shield: 'Shield', + loot: 'Loot', + retaliate: 'Retaliate', + jump: 'Jump', + stun: 'STUN', + wound: 'WOUND', + disarm: 'DISARM', + immobilize: 'IMMOBILIZE', + poison: 'POISON', + invisible: 'INVISIBLE', + strengthen: 'STRENGTHEN', + muddle: 'MUDDLE', + regenerate: 'REGENERATE', + ward: 'WARD', + impair: 'IMPAIR', + bane: 'BANE', + brittle: 'BRITTLE', + chill: 'CHILL', + infect: 'INFECT', + rupture: 'RUPTURE', + push: 'PUSH', + pull: 'PULL', + pierce: 'PIERCE', + curse: 'CURSE', + enfeeble: 'ENFEEBLE', + empower: 'EMPOWER', + bless: 'BLESS', + safeguard: 'SAFEGUARD', + flip: 'ROLLING', + damage: 'damage', + and: 'and' +}; + +/** True when [name] is one of the five elements (or "any"). */ +export function isElement(name: string): boolean { + return ( + name.includes('air') || + name.includes('earth') || + name.includes('fire') || + name.includes('ice') || + name.includes('dark') || + name.includes('light') || + name === 'any' + ); +} + +/** + * Tokens whose graphic has both a Gloomhaven and a Frosthaven variant + * (the reference `hasGHVersion` / `_ghVersionSet`). Only these get the `_fh` + * image suffix when the card renders in Frosthaven style; the rest reuse the + * single graphic. + */ +const GH_VERSION_SET = new Set([ + 'attack', + 'damage', + 'disarm', + 'flying', + 'heal', + 'immobilize', + 'invisible', + 'jump', + 'loot', + 'move', + 'pierce', + 'poison', + 'push', + 'pull', + 'stun', + 'target', + 'range', + 'retaliate', + 'shield', + 'strengthen', + 'teleport', + 'use', + 'wound' +]); + +export function hasGHVersion(name: string): boolean { + return GH_VERSION_SET.has(name); +} diff --git a/web/src/lib/game/line/types.ts b/web/src/lib/game/line/types.ts new file mode 100644 index 0000000..bf1c14f --- /dev/null +++ b/web/src/lib/game/line/types.ts @@ -0,0 +1,155 @@ +/** + * The structured tree produced by {@link parseLines} (the client port of the + * reference `LineBuilder.createLines`, PORTING.md §8b). The tree mirrors the + * reference's Flutter widget layout — a vertical stack of rows, each holding + * text / icon / element-use segments, with sub-line boxes, conditional (dotted) + * boxes, columns, row-groups, element images and dividers nested as the + * reference lays them out. The Svelte renderer walks this tree; it carries no + * theme-specific image paths so the renderer can pick the right assets. + */ + +export type Align = 'left' | 'center' | 'right'; + +/** The font-size / color treatment for a segment (the reference `LineStyles`). */ +export type LineStyle = + | 'normal' + | 'small' + | 'mid' + | 'midSquished' + | 'elite' + | 'eliteSmall' + | 'eliteMid' + | 'divider' + | 'dividerThin' + | 'special'; + +// --- Leaf segments --------------------------------------------------------- + +/** A run of plain text (a card line's words). */ +export interface TextSeg { + kind: 'text'; + text: string; + style: LineStyle; +} + +/** An ability token (a `%token%` icon). `label` is the English display name + * (the renderer translates it via the in-game `t()`); `null` in Frosthaven + * style, where tokens render icon-only. */ +export interface TokenSeg { + kind: 'token'; + /** The raw token key (e.g. `attack`, `poison`, `use`). */ + token: string; + /** Resolved graphic key (e.g. `move` → `flying` for a flyer). */ + gfx: string; + /** True when the graphic should overflow its line (FH condition icons). */ + overflow: boolean; + /** True for the five elements (affects icon sizing). */ + isElement: boolean; + style: LineStyle; +} + +/** A "use element" overlay: an element icon with the `use` graphic + a colon. */ +export interface ElementUseSeg { + kind: 'elementUse'; + element: string; + style: LineStyle; +} + +// --- Structural nodes ------------------------------------------------------ + +/** A vertical stack (the card body, or a `[c]…[/c]` column). */ +export interface ColumnNode { + kind: 'column'; + align: Align; + children: Node[]; +} + +/** A single laid-out line. Children are segments plus any trailing sub-line / + * conditional / column / row-group the line carries. */ +export interface RowNode { + kind: 'row'; + align: Align; + children: Node[]; +} + +/** A horizontal group of side-by-side content (an `[r]…[/r]` row-group). */ +export interface RowGroupNode { + kind: 'rowgroup'; + align: Align; + children: Node[]; +} + +/** A gray rounded box holding sub-line rows (the FH sub-line background). */ +export interface SubLineNode { + kind: 'subline'; + /** True when the card is a boss stat card (darker box). */ + boss: boolean; + /** True when the box wraps a conditional (element-use) effect. */ + conditional: boolean; + children: Node[]; +} + +/** A dotted-border box (the FH conditional / element-use graphic). */ +export interface ConditionalNode { + kind: 'conditional'; + elementUse: boolean; + /** Whether the top "element" banner is drawn (the reference `belongs`). */ + belongs: boolean; + boss: boolean; + children: Node[]; +} + +/** A standalone element image (a `¤ element` line). */ +export interface ImageNode { + kind: 'image'; + gfx: string; + element: boolean; +} + +/** A horizontal divider (`*....` line). */ +export interface DividerNode { + kind: 'divider'; + thin: boolean; + boss: boolean; +} + +export type Node = + | TextSeg + | TokenSeg + | ElementUseSeg + | ColumnNode + | RowNode + | RowGroupNode + | SubLineNode + | ConditionalNode + | ImageNode + | DividerNode; + +// --- Parser inputs --------------------------------------------------------- + +export interface LineBuildOptions { + /** Left-aligned (boss stat card) layout. */ + left: boolean; + /** Resolve `%attack% - 1` against the monster's stats (per line). */ + applyStats: boolean; + /** Force the elite/normal split even with no standees. */ + applyAll: boolean; + align: Align; + /** True for Frosthaven-styled editions. */ + frosthavenStyle: boolean; + /** The user's card scale factor (the reference `scale`). */ + scale: number; + /** The monster, for stat application + the flyer `move`→`flying` swap. */ + monster?: import('./statApplier').StatMonster | null; + /** True when the monster type is a flyer (move token → flying graphic). */ + flying?: boolean; + /** True for a boss stat card (darker boxes, left dividers). */ + bossStatCard?: boolean; + /** + * In-game translation for token display names (the reference translates + * them at parse time). The card's own lines are pre-translated by the + * caller before `parseLines` is called, so only the token labels need + * translating here. Defaults to the identity. + */ + translate?: (s: string) => string; +} diff --git a/web/src/lib/game/modifierDeck.ts b/web/src/lib/game/modifierDeck.ts new file mode 100644 index 0000000..e561451 --- /dev/null +++ b/web/src/lib/game/modifierDeck.ts @@ -0,0 +1,119 @@ +/** + * Modifier (AMD) deck view helpers (Phase 4 §6(d)): the pure read-only + * derivations the deck widget and its menu compute from the wire deck — + * the reference `ModifierDeck` accessors the header/view-model used. + */ + +import type { ModifierCard, ModifierDeck } from '$lib/protocol/types'; + +/** The draw pile, top-first (the reference reverses `drawPileContents`). */ +export function drawPileTopFirst(deck: ModifierDeck): ModifierCard[] { + return [...deck.drawPile].reverse(); +} + +/** The discard pile, bottom-first (draw order). */ +export function discardPile(deck: ModifierDeck): ModifierCard[] { + return deck.discardPile; +} + +/** Whether [gfx] is in the draw or discard pile (the reference `hasCard`). */ +export function deckHasCard(deck: ModifierDeck, gfx: string): boolean { + return ( + deck.drawPile.some((c) => c.gfx === gfx) || + deck.discardPile.some((c) => c.gfx === gfx) + ); +} + +/** A `-1` card is available (in the draw or discard pile). */ +export function deckHasMinus1(deck: ModifierDeck): boolean { + return deckHasCard(deck, 'minus1'); +} + +/** + * The `-2` is "not removed" (the reference `hasMinus2` is true when the + * removed pile has no `minus2` — i.e. the card can still be removed). + */ +export function deckMinus2Present(deck: ModifierDeck): boolean { + return !deck.removedPile.some((c) => c.gfx === 'minus2'); +} + +/** A `+0` card is in the deck. */ +export function deckHasPlus0(deck: ModifierDeck): boolean { + return deckHasCard(deck, 'plus0'); +} + +/** The removable-counter total for [gfx] (0 when unset). */ +export function removableTotal(deck: ModifierDeck, gfx: string): number { + return deck.removables[gfx] ?? 0; +} + +/** The top `count` draw-pile cards (top-first) are revealed. */ +export function revealedCards( + deck: ModifierDeck, + count: number +): ModifierCard[] { + const reversed = drawPileTopFirst(deck); + return reversed.slice(0, Math.max(0, Math.min(count, reversed.length))); +} + +/** + * The Gloomhaven 2nd Edition faction cards (the reference + * `GameMethods.getFactionCards`): four addable cards per faction, or empty + * for an unknown faction. + */ +export function factionCards(faction: string): string[] { + if (faction === 'Demons') { + return [ + 'Demons-perks/plus1any', + 'Demons-perks/plus1retaliate1flip', + 'Demons-perks/plus0wardallyflip', + 'Demons-perks/unique/fuck3' + ]; + } + if (faction === 'Merchant-Guild') { + return [ + 'Merchant-Guild-perks/plus1curse', + 'Merchant-Guild-perks/plus1wound', + 'Merchant-Guild-perks/plus0heal2flip', + 'Merchant-Guild-perks/unique/fuck2' + ]; + } + if (faction === 'Military') { + return [ + 'Military-perks/plus1strengthenally', + 'Military-perks/plus1shield1flip', + 'Military-perks/plus1push2flip', + 'Military-perks/unique/fuck1' + ]; + } + return []; +} + +/** + * Whether [gfx] is in any character's personal deck (the reference + * `GameMethods.isCardInAnyCharacterDeck`) — the faction menu grays out + * cards another character already has. + */ +export function factionCardInAnyCharacterDeck( + deckNames: { name: string; deck: ModifierDeck }[], + gfx: string +): boolean { + return deckNames.some(({ deck }) => + deck.drawPile.some((c) => c.gfx === gfx) || + deck.discardPile.some((c) => c.gfx === gfx) + ); +} + +/** The sanctuary/party-card flag on a deck (gfx prefix, the reference `hasCSSanctuary`/`hasPartyCard`). */ +export function deckHasSanctuaryCard(deck: ModifierDeck): boolean { + return deckPileHasPrefix(deck, 'sanctuary'); +} +export function deckHasPartyCard(deck: ModifierDeck): boolean { + return deckPileHasPrefix(deck, 'party'); +} +function deckPileHasPrefix(deck: ModifierDeck, prefix: string): boolean { + return ( + deck.drawPile.some((c) => c.gfx.startsWith(prefix)) || + deck.discardPile.some((c) => c.gfx.startsWith(prefix)) + ); +} diff --git a/web/src/lib/game/perks.ts b/web/src/lib/game/perks.ts new file mode 100644 index 0000000..9f0d237 --- /dev/null +++ b/web/src/lib/game/perks.ts @@ -0,0 +1,213 @@ +/** + * Character-perk view helpers (Phase 4 §6(d), the reference + * `PerkListTileViewModel` + `GameMethods.canAddPerk`/`canRemovePerk`). The + * perks menu renders the class's perk slots against the character's + * `perkList`/`useFHPerks` and its personal AMD deck. + */ + +import type { + CharacterState, + ModifierDeck +} from '$lib/protocol/types'; +import type { ClassData, PerkDetail } from '$lib/data/gameData'; + +const PERK_PAIR_COUNT = 2; + +/** The perk set in use (Frosthaven set when opted in, else the original). */ +export function activePerks( + classData: ClassData, + state: CharacterState +): PerkDetail[] { + const perksFH = classData.perkDetailsFH; + return state.useFHPerks && perksFH.length > 0 + ? perksFH + : classData.perkDetails; +} + +/** The number word for 1-4 cards ("one ", "two ", …). */ +function nrText(digit: number): string { + if (digit === 1) return 'one '; + if (digit === 2) return 'two '; + if (digit === 3) return 'three '; + if (digit === 4) return 'four '; + return ''; +} + +/** + * A modifier gfx ("perks/minus2flip", "plus1", …) → its display token + * (the reference `_cardText`): `+2%flip%`, `-1 range 2`, `+1 %target%2, self`… + */ +export function cardText(gfx: string): string { + if (gfx.startsWith('perks/')) { + gfx = gfx.slice('perks/'.length); + } + const negative = gfx.startsWith('minus'); + let retVal = '+'; + if (negative) { + retVal = '-'; + gfx = gfx.slice('minus'.length); + } else { + gfx = gfx.slice('plus'.length); + } + retVal += gfx[0]; + if (gfx.length > 1) { + gfx = gfx.slice(1); + let flip = ''; + let range = ''; + let target = ''; + let ally = ''; + if (gfx.endsWith('flip')) { + flip = '%flip%'; + gfx = gfx.slice(0, gfx.length - 'flip'.length); + } + if (gfx.includes('range')) { + range = ` %range% ${gfx.slice(-1)}`; + gfx = gfx.slice(0, gfx.length - 'range'.length - 1); + } + if (gfx.includes('ally')) { + ally = ', %target%1 ally'; + gfx = gfx.slice(0, gfx.length - 'ally'.length); + } + if (gfx.includes('target')) { + target = ` %target% ${gfx.slice(-1)}`; + gfx = gfx.slice(0, gfx.length - 'target'.length - 1); + } + let mainMod = ''; + let maybeNr = ''; + if (gfx.length > 1) { + maybeNr = gfx.slice(-1); + const nr = parseInt(maybeNr, 10); + if (Number.isNaN(nr)) { + maybeNr = ''; + } else { + gfx = gfx.slice(0, gfx.length - 1); + } + mainMod = `%${gfx}%`; + } + + const positiveMod = + gfx === 'invisible' || + gfx === 'heal' || + gfx === 'strengthen' || + gfx === 'regenerate' || + gfx === 'bless' || + gfx === 'ward' || + gfx === 'safeguard' || + gfx === 'dodge'; + if (ally === '' && positiveMod && range === '') ally = ', self'; + + let quotes = ''; + let initialQuoteSpace = ''; + if ( + mainMod !== '' && + (ally !== '' || maybeNr !== '' || range !== '') + ) { + quotes = '"'; + initialQuoteSpace = ' '; + } + + if (mainMod === '' && target !== '') { + target = `+ ${target.slice(-1)}%target%`; + } + + return `${retVal}${initialQuoteSpace}${quotes}${mainMod}${maybeNr}${range}${target}${ally}${quotes}${flip}`; + } + return retVal; +} + +/** The perk-slot description (the reference `description` getter). */ +export function perkDescription(perk: PerkDetail): string { + if (perk.text.length > 0) return perk.text; + + const adds = perk.adds; + const removes = perk.removes; + const removeAmount = removes.length; + const addsAmount = adds.length; + + if (adds.length > 0 && removes.length === 0) { + let d = 'Add '; + d += nrText(addsAmount); + d += `${cardText(adds[0])} card`; + if (addsAmount > 1) d += 's'; + return d; + } else if (adds.length === 0 && removes.length > 0) { + let d = 'Remove '; + d += nrText(removeAmount); + d += `${cardText(removes[0])} card`; + if (removeAmount > 1) d += 's'; + return d; + } else if (adds.length > 0 && removes.length > 0) { + let d = 'Replace '; + d += nrText(removes.length); + d += `${cardText(removes[0])} card`; + if (adds.length > 1) d += 's'; + d += ' with '; + const addsAmount2 = adds.length; + d += nrText(addsAmount2); + d += `${cardText(adds[0])} card`; + if (addsAmount2 > 1) d += 's'; + return d; + } + return ''; +} + +/** Whether the perk can be added (the reference `canAddPerk`). */ +export function canAddPerk( + deck: ModifierDeck, + perks: PerkDetail[], + perkList: boolean[], + index: number +): boolean { + const perk = perks[index]; + for (const item of perk.removes) { + if (!deckHasCard(deck, item)) { + // Check whether another active perk added the same card. + let otherPerkCardAdded = 0; + for (let i = 0; i < perks.length; i++) { + if (perkList[i]) { + for (const card of perks[i].adds) { + if (card === item) otherPerkCardAdded++; + } + // Specific perk cards are tracked by removal too. + if (item.startsWith('perks/')) { + for (const card of perks[i].removes) { + if (card === item) otherPerkCardAdded--; + } + } + } + } + return otherPerkCardAdded > 0; + } + } + return true; +} + +/** Whether the perk can be removed (the reference `canRemovePerk`). */ +export function canRemovePerk( + deck: ModifierDeck, + perks: PerkDetail[], + index: number +): boolean { + const perk = perks[index]; + for (const item of perk.adds) { + if (item.startsWith('perks/')) { + let id = `P${index}`; + if (perk.adds.length >= PERK_PAIR_COUNT && item === perk.adds[perk.adds.length - 1]) { + id += '-2'; + } + if (deckHasCard(deck, id)) return true; + } + if (!deckHasCard(deck, item)) { + return false; + } + } + return true; +} + +/** A card (by gfx id) in the deck's draw or discard pile. */ +function deckHasCard(deck: ModifierDeck, gfx: string): boolean { + return ( + deck.drawPile.some((c) => c.gfx === gfx) || + deck.discardPile.some((c) => c.gfx === gfx) + ); +} diff --git a/web/src/lib/game/rules.ts b/web/src/lib/game/rules.ts new file mode 100644 index 0000000..dad59d6 --- /dev/null +++ b/web/src/lib/game/rules.ts @@ -0,0 +1,178 @@ +/** + * Game-rule helpers the deck UI needs (Phase 4 §6): the port of the reference + * `GameMethods` predicates that gate ability-card display and styling. The + * server owns the rules; these are pure read-only views of the state the + * client already receives. + */ + +import type { + GameState, + ListItem, + ModifierDeck +} from '$lib/protocol/types'; +import { isCharacter, isMonster } from '$lib/protocol/types'; + +const MAX_OG_SOLO_SCENARIO = 100; + +/** The editions whose cards always render in the Frosthaven (icon) style. */ +export function isFrosthavenStyledEdition( + edition: string, + scenario: string +): boolean { + if (edition === 'Solo') { + if (scenario.includes('#19 ')) return false; // Forgotten Circles + // #100+ are the OG solo scenarios. + for (let i = 1; i <= MAX_OG_SOLO_SCENARIO; i++) { + if (scenario.includes(`#${i} `)) return true; + } + return false; + } + return ( + edition === 'Frosthaven' || + edition === 'Buttons and Bugs' || + edition === 'Gloomhaven 2nd Edition' || + edition === 'Skulls in the Snow' || + edition === 'Mercenary Packs' + ); +} + +/** + * Whether a monster's ability cards render in the Frosthaven style (the + * reference `GameMethods.isFrosthavenStyle`). `styleTheme` is the client's + * 'frosthaven' | 'gloomhaven' | 'original' setting. + */ +export function isFrosthavenStyleForMonster( + monsterEdition: string, + state: GameState, + styleTheme: 'frosthaven' | 'gloomhaven' | 'original' +): boolean { + const monsterFh = isFrosthavenStyledEdition( + monsterEdition, + state.scenario + ); + if (monsterFh) return true; + if (styleTheme !== 'frosthaven' && !monsterFh) return false; + return ( + styleTheme === 'frosthaven' || + (styleTheme === 'original' && + isFrosthavenStyledEdition(state.currentCampaign, state.scenario)) + ); +} + +/** + * Whether a monster is inactive for the current round under the scenario's + * "inactive monster" special rule (the reference `isInactiveForRule`). + */ +export function isInactiveForRule( + state: GameState, + monsterId: string +): boolean { + const rule = state.scenarioSpecialRules.find( + (r) => r.type === 'InactiveMonster' && r.name === monsterId + ); + if (rule != null && rule.list.includes(state.round)) return true; + return false; +} + +/** The campaign is one of the custom (Crimson Scales / Trail of Ashes / CCUG). */ +export function isCustomCampaign(campaign: string): boolean { + return ( + campaign === 'Crimson Scales' || + campaign === 'Trail of Ashes' || + campaign === 'CCUG' + ); +} + +/** + * The campaign is Crimson Scales or Trail of Ashes (the reference + * `isCSCampaign` — CCUG has no sanctuary/party-card handling). + */ +export function isCSCampaign(campaign: string): boolean { + return campaign === 'Crimson Scales' || campaign === 'Trail of Ashes'; +} + +/** The character items in the current list. */ +export function charactersIn(list: ListItem[]): ListItem[] { + return list.filter((item) => isCharacter(item)); +} + +/** The party size (character count) — loot values depend on it. */ +export function characterCount(state: GameState): number { + return charactersIn(state.currentList).length; +} + +/** A character id → its class name, for deck `name` resolution. */ +export function characterClassOf( + state: GameState, + id: string +): string | null { + const item = state.currentList.find( + (i) => isCharacter(i) && i.id === id + ); + return item && isCharacter(item) ? item.characterClass : null; +} + +/** The ally-deck monster id, when the ally deck is in play. */ +export function allyDeckOwnerId(state: GameState): string | null { + const item = state.currentList.find((i) => isMonster(i) && i.isAlly); + return item && isMonster(item) ? item.id : null; +} + +/** The id of the character whose turn it is (turnState === current). */ +export function currentCharacterId(state: GameState): string | null { + const item = state.currentList.find( + (i) => isCharacter(i) && i.turnState === 1 + ); + return item && isCharacter(item) ? item.id : null; +} + +/** A figure (character or monster) by id — the reference `getFigure`. */ +export function figureById( + state: GameState, + id: string +): ListItem | null { + return state.currentList.find((i) => i.id === id) ?? null; +} + +/** + * The modifier deck for a deck [name] — "" is the party (monster) deck, + * "allies" the ally deck, a character id its personal deck (the reference + * `GameMethods.getModifierDeck`). + */ +export function modifierDeckByName( + state: GameState, + name: string +): ModifierDeck { + if (name === 'allies') return state.modifierDeckAllies; + if (name === '') return state.modifierDeck; + const item = state.currentList.find((i) => isCharacter(i) && i.id === name); + return item && isCharacter(item) + ? item.characterState.modifierDeck + : state.modifierDeck; +} + +/** Whether a character of [className] is in the game (reference `getFigure`). */ +export function hasCharacterClass( + state: GameState, + className: string +): boolean { + return state.currentList.some( + (i) => isCharacter(i) && i.characterClass === className + ); +} + +/** The campaign is an OG-Gloomhaven (non-Frosthaven-styled) edition. */ +export function isOgGloomEdition(state: GameState): boolean { + return !isFrosthavenStyledEdition(state.currentCampaign, state.scenario); +} + +/** + * Whether the ally deck should be shown (the reference + * `GameMethods.shouldShowAlliesDeck`; the web settings always show the AMD + * deck, so the `showAmdDeck` gate is dropped). + */ +export function shouldShowAlliesDeck(state: GameState): boolean { + if (state.showAllyDeck) return true; + if (!state.allyDeckInOGGloom && isOgGloomEdition(state)) return false; + return state.currentList.some((i) => isMonster(i) && i.isAlly); +} diff --git a/web/src/lib/game/stats.ts b/web/src/lib/game/stats.ts index d842159..b5c41ed 100644 --- a/web/src/lib/game/stats.ts +++ b/web/src/lib/game/stats.ts @@ -9,20 +9,10 @@ import type { CharacterItem, + ModifierDeck, MonsterInstance } from '$lib/protocol/types'; -export interface ModifierCard { - gfx: string; -} - -export interface ModifierDeckJson { - drawPile: ModifierCard[]; - discardPile: ModifierCard[]; - removedPile?: ModifierCard[]; - [ key: string ]: unknown; -} - /** * The wire `figureId` for a standee (a monster instance or a summon): the * reference app builds it as `name + gfx + standeeNr`. @@ -33,7 +23,7 @@ export function standeeFigureId(standee: MonsterInstance): string { /** Count modifier cards matching [predicate] in the draw pile. */ function countCards( - deck: ModifierDeckJson | undefined, + deck: ModifierDeck | undefined, predicate: (gfx: string) => boolean ): number { if (!deck?.drawPile) return 0; @@ -52,9 +42,7 @@ export function characterStatCounters( empower: number; enfeeble: number; } { - const deck = character.characterState.modifierDeck as - | ModifierDeckJson - | undefined; + const deck = character.characterState.modifierDeck; return { bless: countCards(deck, (g) => g === 'bless'), curse: countCards(deck, (g) => g === 'curse'), @@ -65,7 +53,7 @@ export function characterStatCounters( /** The stat counters for a standee (its owner's modifier deck). */ export function standeeStatCounters( - deck: ModifierDeckJson | undefined + deck: ModifierDeck | undefined ): { bless: number; curse: number; diff --git a/web/src/lib/i18n/en.ts b/web/src/lib/i18n/en.ts index b7037a7..536e2c2 100644 --- a/web/src/lib/i18n/en.ts +++ b/web/src/lib/i18n/en.ts @@ -134,5 +134,75 @@ export const en: Record = { 'web:noScenario': 'No scenario set', 'web:round': 'Round', 'web:level': 'Level', - 'web:difficulty': 'Difficulty' + 'web:difficulty': 'Difficulty', + + // Ability cards (monster rows) + 'revealCards': 'Reveal\ncards:', + 'revealAll': 'All', + 'drawExtraCard': 'Draw extra card', + 'extraShuffle': 'Extra Shuffle', + 'activateMonster': 'Activate\nMonster', + 'inactivateMonster': 'Inactivate\nMonster', + 'removeCardQuestion': 'Remove card?', + 'shuffleUndrawnCards': 'Shuffle un-drawn Cards', + + // Modifier decks + 'characterDecks': 'Character Decks', + 'sendToBottom': 'Send to Bottom', + 'returnTopCard': 'Return top card', + 'returnToDiscardPile': 'Return card to discard pile', + 'returnToDrawPile': 'Return card to draw pile', + 'tapCardToAddToDeck': 'Tap Card to add to your deck', + 'removeCardFromDeckQuestion': 'Remove card from your deck?', + 'badOmen': 'Bad Omen', + 'badOmensLeft': 'Bad Omens Left: {count}', + 'corrosiveSpew': 'Corrosive Spew', + 'empowersOnTop': 'Empowers on top', + 'removeMinusOneCard': 'Remove -1 card', + 'removeMinusTwoCard': 'Remove -2 card', + 'minusTwoCardRemoved': '-2 card removed', + 'removePlusZeroCard': 'Remove +0 card', + 'plusZeroCardRemoved': '+0 card removed', + 'addHailPerk': 'Add Hail Perk', + 'removeHailPerk': 'Remove Hail Perk', + 'addCassandraPerk': 'Add\nCassandra Perk', + 'removeCassandraPerk': 'Remove\nCassandra Perk', + 'saveRevealedCards': 'Save\nRevealed Cards', + 'dontSaveRevealedCards': "Don't Save\nRevealed Cards", + 'removedCountLabel': 'Removed: {count}', + 'donateSanctuary': 'Donate to\nSanctuary', + 'removeDonation': 'Remove\nDonation', + 'addPartyCard': 'Add Party\nCard:', + 'removePartyCard': 'Remove\nParty Card:', + 'perks': 'Perks', + 'addPerks': 'Add Perks', + 'useFrosthavenPerks': 'Use Frosthaven Perks', + // Reference addMinusOneCard: two-state button (ICU select in the .arb). + 'addMinusOneCardAdded': 'Add -1 card (added: {count})', + 'addMinusOneCardRemoved': 'Add -1 card (removed: {count})', + + // Loot deck + 'characterLoot': 'Character loot', + 'characterLootTitle': "{name}'s loot:", + 'addSpecialCard': 'Add card {nr}', + 'removeSpecialCard': 'Remove card {nr}', + 'enhanceCards': 'Enhance cards', + 'addLootCard': 'Add Card', + 'addExtraLootCard': 'Add Extra Loot Card', + 'returnToTop': 'Return to Top', + 'returnToBottom': 'Return to Bottom', + 'lootCardEnhancements': 'Loot Card Enhancements', + 'lootAmount2For2': '2 for 2', + 'lootAmount2For23': '2 for 2-3', + 'addedCount': 'added: {count}', + 'lootNameCoin': 'coin', + 'lootNameHide': 'hide', + 'lootNameLumber': 'lumber', + 'lootNameMetal': 'metal', + 'lootNameArrowvine': 'arrowvine', + 'lootNameAxenut': 'axenut', + 'lootNameCorpsecap': 'corpsecap', + 'lootNameFlamefruit': 'flamefruit', + 'lootNameRockroot': 'rockroot', + 'lootNameSnowthistle': 'snowthistle' }; diff --git a/web/src/lib/i18n/gameI18n.ts b/web/src/lib/i18n/gameI18n.ts new file mode 100644 index 0000000..95b9d81 --- /dev/null +++ b/web/src/lib/i18n/gameI18n.ts @@ -0,0 +1,75 @@ +/** + * In-game translation (Phase 4: the reference app's `TranslationService`). + * + * Unlike the UI strings in `./index` (generated from `.arb`), the in-game + * strings live in the campaign JSON: ability-card lines, monster stat + * attributes, token names, and display names. The server serves the locale + * tables at `/i18n/.json` (the reference's `assets/i18n/`). Each file + * is a map of sections → `key → string`; we flatten it the same way the + * reference does (top-level string keys map to themselves, top-level objects + * flatten their string inner keys). English is the key itself, so for `en` + * the table is empty and every lookup returns its key. + * + * `gt()` is the in-game analogue of the UI `t()`. Card lines are translated + * *before* the line pipeline runs (the reference maps `card.lines` through + * `t` first); token display names are translated at render time. + */ + +import { get, writable, type Writable } from 'svelte/store'; + +import { locale, type Locale } from './index'; + +type GameTable = Record; + +/** The flattened in-game table for the active locale (empty for `en`). */ +export const gameTable: Writable = writable({}); + +/** Translate an in-game key with the active locale, falling back to the key. */ +export function gt(key: string): string { + return get(gameTable)[key] ?? key; +} + +const cache = new Map(); + +function flatten(data: Record): GameTable { + const flat: GameTable = {}; + for (const [key, value] of Object.entries(data)) { + if (typeof value === 'string') { + flat[key] = value; + } else if (value && typeof value === 'object' && !Array.isArray(value)) { + for (const [inner, innerValue] of Object.entries(value)) { + if (typeof innerValue === 'string') flat[inner] = innerValue; + } + } + } + return flat; +} + +async function loadGameTable(loc: Locale): Promise { + if (loc === 'en') { + gameTable.set({}); + return; + } + const cached = cache.get(loc); + if (cached) { + gameTable.set(cached); + return; + } + try { + const res = await fetch(`/i18n/${loc}.json`); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const data = (await res.json()) as Record; + const flat = flatten(data); + cache.set(loc, flat); + // Drop stale completions after a locale switch. + if (get(locale) === loc) gameTable.set(flat); + } catch (error) { + console.warn(`in-game i18n: failed to load ${loc}`, error); + if (get(locale) === loc) gameTable.set({}); + } +} + +// Load the current locale on startup and on every locale change. +locale.subscribe((loc) => { + void loadGameTable(loc); +}); diff --git a/web/src/lib/i18n/index.ts b/web/src/lib/i18n/index.ts index 9634712..5792835 100644 --- a/web/src/lib/i18n/index.ts +++ b/web/src/lib/i18n/index.ts @@ -48,8 +48,24 @@ locale.subscribe((value) => { } }); -/** The locales currently available in the client (for the settings picker). */ -export const availableLocales = Object.keys(tables); +/** + * The locales offered in the settings picker. In-game card text, token names, + * and display names are translated for every one of these (the `/i18n/` files); + * the UI strings themselves fall back to English for any locale beyond `en` + * (only the English UI table is ported — Phase 6 ports the rest). + */ +export const availableLocales: Locale[] = [ + 'en', + 'de', + 'es', + 'fr', + 'ko', + 'pl', + 'ru', + 'th', + 'zh', + 'zh_Hant' +]; /** * Translate a key with the active locale, falling back to English. Returns diff --git a/web/src/lib/protocol/types.ts b/web/src/lib/protocol/types.ts index b8ced78..2042692 100644 --- a/web/src/lib/protocol/types.ts +++ b/web/src/lib/protocol/types.ts @@ -37,7 +37,8 @@ export interface CharacterState extends FigureState { initiative: number | null; xp: number; display: string; - modifierDeck: unknown; + /** This character's personal modifier (AMD) deck. */ + modifierDeck: ModifierDeck; summonList: MonsterInstance[]; useFHPerks: boolean; perkList: boolean[]; @@ -56,6 +57,145 @@ export interface MonsterInstance extends FigureState { plague: number; } +// --- Decks & cards (Phase 4) ----------------------------------------------- +// +// These mirror the server's deck `toJson()` shapes exactly (PLAN.md +// section 3.1). The server is the source of truth; the fields below are the +// wire format the client receives in `state`. + +/** + * A modifier card. The server serialises only the graphic key; the card + * kind (add / multiply / remove) and the effect label are derived from the + * gfx on the client (see `modifierCardKind`). + */ +export interface ModifierCard { + gfx: string; +} + +/** + * A modifier (AMD) deck: the shared global deck, the ally deck, and each + * character's personal deck all have this shape. `revealed` is the count of + * draw-pile cards the owner has flipped face-up (Cassandra's special). + */ +export interface ModifierDeck { + addedMinusOnes: number; + /** 0 = none, 1 = imbue level 1, 2 = imbue level 2. */ + imbuement: number; + badOmen: number; + corrosiveSpew: boolean; + revealed: number; + cassandra: boolean; + /** + * Removable-card counter totals, keyed by gfx ("bless", "curse", + * "in-enfeeble", "vi-empower", …) — the deck-header counters. + */ + removables: Record; + /** Bottom → top. The last element is the next card to be drawn. */ + drawPile: ModifierCard[]; + removedPile: ModifierCard[]; + discardPile: ModifierCard[]; +} + +/** `LootType` index: 0 = materiel, 1 = other. */ +export type LootType = 0 | 1; +/** `LootBaseValue` index: 0 = one, 1 = oneIf4twoIfNot, 2 = oneIf3or4twoIfNot. */ +export type LootBaseValue = 0 | 1 | 2; + +export interface LootCard { + gfx: string; + /** Owning character id ("" until drawn). */ + owner: string; + id: number; + /** Enhancement amount added to the card's value. */ + enhanced: number; + baseValue: LootBaseValue; + lootType: LootType; +} + +/** + * The scenario loot deck. `addedCards` (9 entries) counts how many extra + * cards of each material type have been added; `enhancements` maps card id → + * enhancement. The `1418` / `1419` booleans track the two special cards. + */ +/** The resource pool keys, in enhancement-menu order. */ +export const LOOT_POOL_KEYS = [ + 'hide', + 'lumber', + 'metal', + 'arrowvine', + 'axenut', + 'corpsecap', + 'flamefruit', + 'rockroot', + 'snowthistle', + 'coin' +] as const; +export type LootPoolKey = (typeof LOOT_POOL_KEYS)[number]; + +export interface LootDeck { + drawPile: LootCard[]; + discardPile: LootCard[]; + addedCards: number[]; + enhancements: Record; + '1418': boolean; + '1419': boolean; + /** + * The card pools, keyed by resource name, as stable card **ids** (in + * pool order). The pool shares live instances with the draw/discard + * piles, so only ids cross the wire; the enhancement level per id is in + * the `enhancements` map. The enhancement menu renders one counter per + * id. + */ + pools: Record; +} + +/** The Crimson Scales sanctuary deck (two 16-card piles). */ +export interface SanctuaryDeck { + multPile: ModifierCard[]; + flipPile: ModifierCard[]; +} + +/** A positioned graphic on an ability card (the reference `GraphicPositional`). */ +export interface GraphicPositional { + gfx: string; + x: number; + y: number; + scale: number; + angle: number; +} + +/** + * The serialised form of a monster ability card — only `{nr, deck}`. The full + * card (title, initiative, lines, graphics) is reconstructed on the client + * from the deck name + nr against the edition's `monsterAbilities` data. + */ +export interface MonsterAbilityCardRef { + nr: number; + deck: string; +} + +/** The full reconstructed monster ability card (data + serialised ref). */ +export interface MonsterAbilityCard { + title: string; + nr: number; + shuffle: boolean; + initiative: number; + lines: string[]; + deck: string; + graphics: GraphicPositional[]; +} + +/** One monster's ability-card deck (a `currentAbilityDecks` entry). */ +export interface MonsterAbilityState { + /** The deck name (= the monster's `type.deck`). */ + name: string; + /** Bottom → top; the last element is the next card to be drawn. */ + drawPile: MonsterAbilityCardRef[]; + discardPile: MonsterAbilityCardRef[]; + /** The total round number when the deck last auto-drew (0 = not yet). */ + lastRoundDrawn: number; +} + // --- Current-list items ---------------------------------------------------- export interface CharacterItem { @@ -129,11 +269,14 @@ export interface GameState { scenarioSectionsAdded: string[]; currentCampaign: string; currentList: ListItem[]; - currentAbilityDecks: unknown[]; - sanctuaryDeck: unknown; - modifierDeck: unknown; - modifierDeckAllies: unknown; - lootDeck: unknown; + /** One entry per monster currently in the game. */ + currentAbilityDecks: MonsterAbilityState[]; + sanctuaryDeck: SanctuaryDeck; + /** The shared (party) modifier deck. */ + modifierDeck: ModifierDeck; + /** The ally modifier deck (Gloomhaven 2nd Edition). */ + modifierDeckAllies: ModifierDeck; + lootDeck: LootDeck; unlockedClasses: string[]; showAllyDeck: boolean; allyDeckInOGGloom: boolean; diff --git a/web/src/lib/ui/CounterButton.svelte b/web/src/lib/ui/CounterButton.svelte new file mode 100644 index 0000000..8024b0e --- /dev/null +++ b/web/src/lib/ui/CounterButton.svelte @@ -0,0 +1,115 @@ + + + +
+ + +
+ + {#if extraImage} + + {/if} + {#if showTotal} + {total} + {/if} +
+ + +
+ + diff --git a/web/src/lib/ui/MainList.svelte b/web/src/lib/ui/MainList.svelte index cb5ad49..f594778 100644 --- a/web/src/lib/ui/MainList.svelte +++ b/web/src/lib/ui/MainList.svelte @@ -7,6 +7,8 @@
@@ -106,4 +136,16 @@ {/each}
{/if} + + {#if $gameState} + onOpenAbility(item)} + onZoom={() => onZoomAbility(item)} + /> + {/if} diff --git a/web/src/lib/ui/StatusMenu.svelte b/web/src/lib/ui/StatusMenu.svelte index 4563c07..46f6325 100644 --- a/web/src/lib/ui/StatusMenu.svelte +++ b/web/src/lib/ui/StatusMenu.svelte @@ -7,12 +7,16 @@ --> + +
+ + {#if size >= 0} +
{size}
+ {/if} +
+ + diff --git a/web/src/lib/ui/cards/AbilityText.svelte b/web/src/lib/ui/cards/AbilityText.svelte new file mode 100644 index 0000000..51fe672 --- /dev/null +++ b/web/src/lib/ui/cards/AbilityText.svelte @@ -0,0 +1,200 @@ + + + +{#if node.kind === 'column'} +
+ {#each node.children as child} + + {/each} +
+{:else if node.kind === 'row' || node.kind === 'rowgroup'} +
+ {#each node.children as child} + + {/each} +
+{:else if node.kind === 'subline'} +
+ {#each node.children as child} + + {/each} +
+{:else if node.kind === 'conditional'} +
+ {#if node.belongs} + + {/if} +
+ {#each node.children as child} + + {/each} +
+
+{:else if node.kind === 'text'} + {@const m = r(node.style)} + {#if m.color !== 'transparent'} + {node.text} + {:else} + + {/if} +{:else if node.kind === 'token'} + {@const h = r(node.style).size * scale} + {node.token} +{:else if node.kind === 'elementUse'} + {@const h = r(node.style).size * scale} + + {node.element} + use + +{:else if node.kind === 'image'} + {@const h = r('normal').size * scale * (node.element ? 0.6 : 1)} + {node.gfx} +{:else if node.kind === 'divider'} + +{/if} + + diff --git a/web/src/lib/ui/cards/LootCard.svelte b/web/src/lib/ui/cards/LootCard.svelte new file mode 100644 index 0000000..49ddb2b --- /dev/null +++ b/web/src/lib/ui/cards/LootCard.svelte @@ -0,0 +1,114 @@ + + + +
+ {card.gfx} + {#if value !== null} +
+{value}
+ {/if} + {#if special} +
{special}
+ {/if} + {#if revealed && card.enhanced > 0} +
+ {t('enhancedLevel', { level: card.enhanced })} +
+ {/if} + {#if showOwner} + {ownerName} + {/if} +
+ + diff --git a/web/src/lib/ui/cards/ModifierCard.svelte b/web/src/lib/ui/cards/ModifierCard.svelte new file mode 100644 index 0000000..e5e7bf7 --- /dev/null +++ b/web/src/lib/ui/cards/ModifierCard.svelte @@ -0,0 +1,124 @@ + + + +
+ {#if revealed} + {card.gfx} + {#if showExtra} + + + {/if} + {:else} + + {#if rear.has} + + + {/if} + {/if} +
+ + diff --git a/web/src/lib/ui/cards/MonsterAbilityCard.svelte b/web/src/lib/ui/cards/MonsterAbilityCard.svelte new file mode 100644 index 0000000..5310874 --- /dev/null +++ b/web/src/lib/ui/cards/MonsterAbilityCard.svelte @@ -0,0 +1,157 @@ + + + +
+ + + {#each card.graphics.slice(0, 4) as g} + + {/each} + +
+ {gt(card.title)} +
+
+ {initText} +
+
{card.nr}
+ + {#if card.shuffle} + shuffle + {/if} + +
+ +
+
+ + diff --git a/web/src/lib/ui/decks/AbilityCardSlot.svelte b/web/src/lib/ui/decks/AbilityCardSlot.svelte new file mode 100644 index 0000000..8b5250c --- /dev/null +++ b/web/src/lib/ui/decks/AbilityCardSlot.svelte @@ -0,0 +1,121 @@ + + + +
{ + if (showFront) onZoom(); + }} + onkeydown={onKeydown} +> + {#if showFront && card != null} + + {:else} + + {/if} +
+ + diff --git a/web/src/lib/ui/decks/AbilityCardZoom.svelte b/web/src/lib/ui/decks/AbilityCardZoom.svelte new file mode 100644 index 0000000..dc5e258 --- /dev/null +++ b/web/src/lib/ui/decks/AbilityCardZoom.svelte @@ -0,0 +1,71 @@ + + + +{#if open} + +{/if} + + diff --git a/web/src/lib/ui/decks/AbilityCardsMenu.svelte b/web/src/lib/ui/decks/AbilityCardsMenu.svelte new file mode 100644 index 0000000..0cf416c --- /dev/null +++ b/web/src/lib/ui/decks/AbilityCardsMenu.svelte @@ -0,0 +1,307 @@ + + + + + {#if $gameState && $player} +
+ {t('revealCards')} + {#each Array(revealButtons) as _, i} + + {/each} + + + +
+ +
+
(dragIndex = null)} ondrop={onDrop}> + {#each drawTopFirst as ref, i} + {@const c = fullCard(ref)} +
onDragStart(i)} + ondragover={(e) => onDragOver(e, i)} + onclick={() => (removeTarget = ref)} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + removeTarget = ref; + }} + > + {#if c != null && i < revealedCount} + + {:else} + + {/if} +
+ {/each} +
+ +
+ {#each discardList as ref} + {@const c = fullCard(ref)} + {#if c != null} +
(removeTarget = ref)} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + removeTarget = ref; + }} + > + +
+ {/if} + {/each} +
+
+ {:else if $gameState} +

{t('web:spectator')}

+ {/if} + + {#if removeTarget} + {@const rt = removeTarget} + {@const card = fullCard(rt)} + + {/if} +
+ + diff --git a/web/src/lib/ui/decks/DeckArea.svelte b/web/src/lib/ui/decks/DeckArea.svelte new file mode 100644 index 0000000..6e32dea --- /dev/null +++ b/web/src/lib/ui/decks/DeckArea.svelte @@ -0,0 +1,222 @@ + + + +
+
+ {#if $gameState} + + {/if} +
+ +
+ {#if showAmds} + + {#if visible !== 'noOpen'} + {#if visible === 'oneOpen' && canShowOneDeck && currentCharacter} + onOpenAmd(currentCharacter.id)} + onZoom={() => onZoom(currentCharacter.id, currentCharacter)} + /> + {:else} + {#each charsWithPerks as char (char.id)} + onOpenAmd(char.id)} + onZoom={() => onZoom(char.id, char)} + /> + {/each} + {/if} + {/if} + {/if} + + {#if $gameState && shouldShowAlliesDeck($gameState)} + onOpenAmd('allies')} + onZoom={() => onZoom('allies', null)} + /> + {/if} + + {#if $gameState} + onOpenAmd('')} + onZoom={() => onZoom('', null)} + /> + {/if} +
+
+ + diff --git a/web/src/lib/ui/decks/LootCardsMenu.svelte b/web/src/lib/ui/decks/LootCardsMenu.svelte new file mode 100644 index 0000000..638fd0c --- /dev/null +++ b/web/src/lib/ui/decks/LootCardsMenu.svelte @@ -0,0 +1,492 @@ + + + + + {#if $gameState} +
+ + + + + + {#if deck.discardPile.length > 0} + + + {/if} +
+ +
+ {#each discardDisplay as card} + + {/each} +
+ {/if} + + + {#if sub && sub.kind === 'owner'} + {@const s = sub} + + {/if} + + + {#if sub?.kind === 'charLoot'} +
+ {#each characters as char} +
+
+ {char.id} + {t('characterLootTitle', { name: char.characterState.display })} +
+ {#each charLootRows(char.id) as row} + {#if row.amount > 0} +
+ {row.name} + {lootName(row.name)} + {row.amount} +
+ {/if} + {/each} + {/each} +
+ {/if} + + + {#if sub?.kind === 'addLoot'} +
+
{t('addExtraLootCard')}
+ {#each ADD_LOOT_NAMES as name, i} + + {/each} +
+ {/if} + + + {#if sub?.kind === 'enhance'} +
+
{t('lootCardEnhancements')}
+ {#each enhSections as section} +
+ {section.key} + {section.label} +
+ {#each section.rows as row} +
+ {#each row as idx} + {@const c = counter(section.key, idx)} + + {/each} +
+ {/each} +
+ {/each} +
+ {/if} +
+ + diff --git a/web/src/lib/ui/decks/LootDeckWidget.svelte b/web/src/lib/ui/decks/LootDeckWidget.svelte new file mode 100644 index 0000000..369a6c2 --- /dev/null +++ b/web/src/lib/ui/decks/LootDeckWidget.svelte @@ -0,0 +1,163 @@ + + + +{#if !hidden} +
+
{ + if (e.key === 'Enter' || e.key === ' ') draw(); + }} + > + {#if deck.drawPile.length > 0} + + {:else} +
+ {/if} + {deck.drawPile.length} + {#if currentCharacterName != null && deck.drawPile.length > 0} + {currentCharacterName} + {/if} +
+ +
{ + if (e.key === 'Enter' || e.key === ' ') onOpenMenu(); + }} + > + {#each discardStack as entry} +
+ +
+ {/each} +
+
+{/if} + + diff --git a/web/src/lib/ui/decks/LootEnhancementCounter.svelte b/web/src/lib/ui/decks/LootEnhancementCounter.svelte new file mode 100644 index 0000000..7139222 --- /dev/null +++ b/web/src/lib/ui/decks/LootEnhancementCounter.svelte @@ -0,0 +1,77 @@ + + + +
+ + {value} + +
+ + diff --git a/web/src/lib/ui/decks/ModifierCardZoom.svelte b/web/src/lib/ui/decks/ModifierCardZoom.svelte new file mode 100644 index 0000000..68cb150 --- /dev/null +++ b/web/src/lib/ui/decks/ModifierCardZoom.svelte @@ -0,0 +1,56 @@ + + + +{#if open} + +{/if} + + diff --git a/web/src/lib/ui/decks/ModifierDeckHeader.svelte b/web/src/lib/ui/decks/ModifierDeckHeader.svelte new file mode 100644 index 0000000..0f7ae9d --- /dev/null +++ b/web/src/lib/ui/decks/ModifierDeckHeader.svelte @@ -0,0 +1,460 @@ + + + +
+ {#if hasDiviner && !isCharacter} + {#if deck.badOmen === 0} + + {:else} + {t('badOmensLeft', { count: deck.badOmen })} + {/if} + {/if} + + {#if name === 'Ruinmaw' && !deck.corrosiveSpew} + + {/if} + {#if deck.corrosiveSpew} + {t('empowersOnTop')} + {/if} + + + + + + {#if !isCharacter} + + {/if} + + {#if isCharacter && hasPlus0Card} + + {/if} + + {#if monsterDeck} + + {#if deck.imbuement !== 2} + + {/if} + {/if} + + {#if name === '' && hail != null} + + {/if} + + {#if hasCassandraPerk} + + {/if} + + {#if deck.removedPile.length > 0} + + {/if} + + {#if isCSCampaign(state.currentCampaign) && isCharacter} + {#if deck.drawPile.some((c) => c.gfx.startsWith('sanctuary')) || deck.discardPile.some((c) => c.gfx.startsWith('sanctuary'))} + + {:else} + + {/if} + + {#if deck.drawPile.some((c) => c.gfx.startsWith('party')) || deck.discardPile.some((c) => c.gfx.startsWith('party'))} + + {:else} + {t('addPartyCard')} + {#each Array(PARTY_BUTTON_COUNT) as _, i} + + {/each} + {/if} + {/if} + + {#if isCharacter} + {#each factionUnlocked as faction} + + {/each} + {/if} + + changeBless(-1)} + onIncrement={() => changeBless(1)} + /> + changeCurse(-1)} + onIncrement={() => changeCurse(1)} + /> + + {#if hasIncarnate && !isCharacter} + changeEnfeeble('in-enfeeble', -1)} + onIncrement={() => changeEnfeeble('in-enfeeble', 1)} + /> + {/if} + {#if (isCharacter || name === 'allies') && hasIncarnate} + changeEmpower('in-empower', -1)} + onIncrement={() => changeEmpower('in-empower', 1)} + /> + {/if} + {#if name === 'Ruinmaw'} + changeEmpower('rm-empower', -1)} + onIncrement={() => changeEmpower('rm-empower', 1)} + /> + {/if} + {#if (isCharacter || name === 'allies') && hasVimthreader} + changeEmpower('vi-empower', -1)} + onIncrement={() => changeEmpower('vi-empower', 1)} + /> + changeEmpower('vi-gr-empower', -1)} + onIncrement={() => changeEmpower('vi-gr-empower', 1)} + /> + {/if} + {#if !isCharacter && hasVimthreader} + changeEnfeeble('vi-enfeeble', -1)} + onIncrement={() => changeEnfeeble('vi-enfeeble', 1)} + /> + changeEnfeeble('vi-gr-enfeeble', -1)} + onIncrement={() => changeEnfeeble('vi-gr-enfeeble', 1)} + /> + {/if} + {#if (!isCharacter || name === 'Lifespeaker') && hasLifespeaker} + changeEnfeeble('li-enfeeble', -1)} + onIncrement={() => changeEnfeeble('li-enfeeble', 1)} + /> + {/if} + + {#if isCharacter && characterClassData && characterClassData.perkDetails.length > 0} + + {/if} + + {t('revealCards')} + {#each Array(revealCount) as _, i} + + {/each} +
+ + diff --git a/web/src/lib/ui/decks/ModifierDeckMenu.svelte b/web/src/lib/ui/decks/ModifierDeckMenu.svelte new file mode 100644 index 0000000..2cfac21 --- /dev/null +++ b/web/src/lib/ui/decks/ModifierDeckMenu.svelte @@ -0,0 +1,570 @@ + + + + + {#if $gameState} + (sub = { kind: 'removed' })} + onOpenPerks={() => (sub = { kind: 'perks' })} + onOpenFaction={(faction) => (sub = { kind: 'faction', faction })} + /> + +
+
(dragIndex = null)} ondrop={onDrop}> + {#each drawTopFirst as card, i} + {@const pileIndex = deck.drawPile.length - 1 - i} +
onDragStart(i)} + ondragover={(e) => onDragOver(e, i)} + onclick={() => + (sub = { kind: 'sendToBottom', displayIndex: i })} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + sub = { kind: 'sendToBottom', displayIndex: i }; + }} + > + +
+ {/each} +
+ +
+ {#each discardDisplay as card, i} + {@const pileIndex = deck.discardPile.length - 1 - i} +
(sub = { kind: 'removeAmd', pileIndex })} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + sub = { kind: 'removeAmd', pileIndex }; + }} + > + +
+ {/each} +
+
+ {/if} + + + {#if sub?.kind === 'sendToBottom'} + {@const pileIndex = deck.drawPile.length - 1 - sub.displayIndex} + {@const card = deck.drawPile[pileIndex]} + + {/if} + + + {#if sub && sub.kind === 'removeAmd'} + {@const s = sub} + {@const card = deck.discardPile[s.pileIndex]} + + {/if} + + + {#if sub?.kind === 'removed'} +
+
Removed cards
+
+ {#each removedDisplay as card, i} + {@const pileIndex = deck.removedPile.length - 1 - i} +
(sub = { kind: 'returnAmd', pileIndex })} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + sub = { kind: 'returnAmd', pileIndex }; + }} + > + +
+ {/each} +
+
+ {/if} + + + {#if sub && sub.kind === 'returnAmd'} + {@const s = sub} + {@const card = deck.removedPile[s.pileIndex]} + + {/if} + + + {#if sub?.kind === 'faction'} +
+
+ {#each factionGfxs as gfx} + + {/each} +
+
+ {#if factionAdded == null} + {t('tapCardToAddToDeck')} + {:else} + + {/if} +
+
+ {/if} + + + {#if sub?.kind === 'perks' && character && characterClassData} +
+
{t('addPerks')}
+ {#if characterClassData.perkDetailsFH.length > 0} + + {/if} + {#each perks as perk, i} + {@const added = character.characterState.perkList[i] ?? false} + {@const enabled = added + ? canRemovePerk( + character.characterState.modifierDeck, + perks, + i + ) + : canAddPerk( + character.characterState.modifierDeck, + perks, + character.characterState.perkList, + i + )} +
+ + {/each} +
+ {/if} +
+ + diff --git a/web/src/lib/ui/decks/ModifierDeckWidget.svelte b/web/src/lib/ui/decks/ModifierDeckWidget.svelte new file mode 100644 index 0000000..a79bf50 --- /dev/null +++ b/web/src/lib/ui/decks/ModifierDeckWidget.svelte @@ -0,0 +1,185 @@ + + + +
+
{ + if (e.key === 'Enter' || e.key === ' ') draw(); + }} + > + {#if drawTop != null} + 0} + {perks} + /> + {:else} +
+ {#if className} + {className} + {/if} + Shuffle & Draw +
+ {/if} + {deck.drawPile.length} +
+ +
{ + if (e.key === 'Enter' || e.key === ' ') onOpenMenu(); + }} + > + {#each discardStack as entry} +
+ +
+ {/each} +
+
+ + -- cgit v1.3.1