diff options
Diffstat (limited to 'web')
51 files changed, 7570 insertions, 109 deletions
diff --git a/web/src/App.svelte b/web/src/App.svelte index d694ee4..2ed1ec8 100644 --- a/web/src/App.svelte +++ b/web/src/App.svelte @@ -13,9 +13,30 @@ import { onMount, onDestroy } from 'svelte'; import { GameSession } from '$lib/state/session'; import { styleTheme } from '$lib/settings'; + import { gameData, type CampaignData, type MonsterData } from '$lib/data/gameData'; + import { + isMonster, + type ModifierCard, + type MonsterAbilityCard, + type MonsterAbilityState, + type MonsterItem + } from '$lib/protocol/types'; + import { + isFrosthavenStyleForMonster, + isInactiveForRule, + modifierDeckByName + } from '$lib/game/rules'; + import { statMonsterFor } from '$lib/game/line/buildAbility'; + import type { StatMonster } from '$lib/game/line/statApplier'; import TopBar from '$lib/ui/TopBar.svelte'; import MainList from '$lib/ui/MainList.svelte'; import BottomBar from '$lib/ui/BottomBar.svelte'; + import DeckArea from '$lib/ui/decks/DeckArea.svelte'; + import AbilityCardsMenu from '$lib/ui/decks/AbilityCardsMenu.svelte'; + import AbilityCardZoom from '$lib/ui/decks/AbilityCardZoom.svelte'; + import ModifierDeckMenu from '$lib/ui/decks/ModifierDeckMenu.svelte'; + import ModifierCardZoom from '$lib/ui/decks/ModifierCardZoom.svelte'; + import LootCardsMenu from '$lib/ui/decks/LootCardsMenu.svelte'; import MainMenu, { type MenuName } from '$lib/ui/MainMenu.svelte'; import StatusMenu, { type FigureRef } from '$lib/ui/StatusMenu.svelte'; import ConnectionBanner from '$lib/ui/ConnectionBanner.svelte'; @@ -36,6 +57,10 @@ onMount(() => session.connect()); onDestroy(() => session.disconnect()); + const gameState = session.state; + const error = session.lastError; + const status = session.status; + // The style theme (client-only) styles <html> via app.css [data-style]. $effect(() => { document.documentElement.dataset.style = $styleTheme; @@ -59,6 +84,154 @@ figureOpen = true; } + // --- Campaign data (classes, monsters, ability-card decks) --------------- + + let campaignData = $state<CampaignData | null>(null); + let lastCampaign = $state(''); + + $effect(() => { + const c = $gameState?.currentCampaign ?? ''; + if (!c || c === lastCampaign) return; + lastCampaign = c; + campaignData = null; + gameData + .loadCampaign(c) + .then((d) => { + if (lastCampaign === c) campaignData = d; + }) + .catch(() => {}); + }); + + /** The monster model for a state monster (by name or display name). */ + function modelFor(item: MonsterItem): MonsterData | null { + return ( + campaignData?.monsters.find( + (m) => m.name === item.type || m.display === item.type + ) ?? null + ); + } + + // --- Monster ability-card deck menu + zoom ------------------------------- + + let abilityItemId = $state<string | null>(null); + let abilityOpen = $state(false); + + function openAbility(item: MonsterItem) { + const gs = $gameState; + const model = modelFor(item); + if (gs == null || model == null) return; + if (gs.currentAbilityDecks.find((d) => d.name === model.deck) == null) + return; + abilityItemId = item.id; + abilityOpen = true; + } + + const abilityItem = $derived.by((): MonsterItem | null => { + if (abilityItemId == null) return null; + return ( + $gameState?.currentList.find( + (i): i is MonsterItem => isMonster(i) && i.id === abilityItemId + ) ?? null + ); + }); + + const abilityDeck = $derived.by((): MonsterAbilityState | null => { + const gs = $gameState; + if (gs == null || abilityItem == null) return null; + const model = modelFor(abilityItem); + if (model == null) return null; + return gs.currentAbilityDecks.find((d) => d.name === model.deck) ?? null; + }); + + const abilityFh = $derived.by((): boolean => { + const gs = $gameState; + if (gs == null || abilityItem == null) return false; + const model = modelFor(abilityItem); + if (model == null) return false; + return isFrosthavenStyleForMonster(model.edition, gs, $styleTheme); + }); + + let abilityZoom = $state<{ + card: MonsterAbilityCard; + stat: StatMonster | null; + fh: boolean; + flying: boolean; + } | null>(null); + let abilityZoomOpen = $state(false); + + function zoomAbility(item: MonsterItem) { + const gs = $gameState; + if (gs == null) return; + if (gs.roundState !== 1 || !item.isActive || isInactiveForRule(gs, item.type)) + return; + const model = modelFor(item); + if (model == null) return; + const deck = gs.currentAbilityDecks.find((d) => d.name === model.deck); + if (deck == null || deck.discardPile.length === 0) return; + const ref = deck.discardPile[deck.discardPile.length - 1]; + const card = campaignData?.abilityDecks[ref.deck]?.find( + (c) => c.nr === ref.nr + ); + if (card == null) return; + abilityZoom = { + card, + stat: statMonsterFor( + model, + item.level, + item.monsterInstances.map((s) => s.type), + item.isActive + ), + fh: isFrosthavenStyleForMonster(model.edition, gs, $styleTheme), + flying: model.flying + }; + abilityZoomOpen = true; + } + + // --- Modifier (AMD) deck menu + zoom -------------------------------------- + + let amdName = $state<string | null>(null); + let amdOpen = $state(false); + + function openAmd(name: string) { + amdName = name; + amdOpen = true; + } + + const amdDeck = $derived.by(() => { + const gs = $gameState; + if (gs == null || amdName == null) return null; + return modifierDeckByName(gs, amdName); + }); + + const amdClassData = $derived.by(() => { + if (amdName == null || amdName === '' || amdName === 'allies') return null; + return ( + campaignData?.classes.find( + (c) => c.name === amdName || c.id === amdName + ) ?? null + ); + }); + + let amdZoom = $state<{ + card: ModifierCard; + name: string; + perks: string[][] | null; + } | null>(null); + let amdZoomOpen = $state(false); + + function openAmdZoom( + card: ModifierCard, + name: string, + perks: string[][] | null + ) { + amdZoom = { card, name, perks }; + amdZoomOpen = true; + } + + // --- Loot cards menu ------------------------------------------------------ + + let lootMenuOpen = $state(false); + // --- Action log (the last 20 command descriptions) ---------------------- let log = $state<string[]>([]); @@ -83,10 +256,6 @@ }, 3500); } - const gameState = session.state; - const error = session.lastError; - const status = session.status; - $effect(() => { const e = $error; if (e) { @@ -112,6 +281,11 @@ drawerOpen = false; menuOpen = false; figureOpen = false; + abilityOpen = false; + abilityZoomOpen = false; + amdOpen = false; + amdZoomOpen = false; + lootMenuOpen = false; } }} /> @@ -119,9 +293,25 @@ <TopBar {session} onMenu={() => (drawerOpen = true)} /> <div class="app__list"> - <MainList {session} onOpenMenu={openFigure} /> + <MainList + {session} + onOpenMenu={openFigure} + {campaignData} + onOpenAbility={openAbility} + onZoomAbility={zoomAbility} + /> </div> + {#if $gameState} + <DeckArea + {session} + {campaignData} + onOpenAmd={openAmd} + onAmdZoom={openAmdZoom} + onOpenLoot={() => (lootMenuOpen = true)} + /> + {/if} + <BottomBar {session} onOpenSetLevel={() => openMenu('setLevel')} /> </div> @@ -164,3 +354,49 @@ {#if figure} <StatusMenu {session} {figure} bind:open={figureOpen} /> {/if} + +{#if abilityItem != null && abilityDeck != null} + <AbilityCardsMenu + {session} + item={abilityItem} + deck={abilityDeck} + {campaignData} + fh={abilityFh} + bind:open={abilityOpen} + /> +{/if} + +{#if abilityZoom} + {@const z = abilityZoom} + <AbilityCardZoom + card={z.card} + stat={z.stat} + fh={z.fh} + flying={z.flying} + bind:open={abilityZoomOpen} + /> +{/if} + +{#if amdName != null && amdDeck} + <ModifierDeckMenu + {session} + deck={amdDeck} + name={amdName} + characterClassData={amdClassData} + bind:open={amdOpen} + /> +{/if} + +{#if amdZoom} + {@const z = amdZoom} + <ModifierCardZoom + card={z.card} + name={z.name} + perks={z.perks} + bind:open={amdZoomOpen} + /> +{/if} + +{#if $gameState} + <LootCardsMenu {session} deck={$gameState.lootDeck} bind:open={lootMenuOpen} /> +{/if} 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<string, RawMonster>; scenarios: Record<string, RawScenario>; + /** 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/<name>.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<string, MonsterAbilityCard[]>; } 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<Record<string, unknown>>).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<string[]> | null = null; private campaignsCache: string[] | null = null; private readonly cache = new Map<string, Promise<CampaignData>>(); + /** Resolved campaign data (populated as each fetch lands) for sync lookups. */ + private readonly loaded = new Map<string, CampaignData>(); private readonly roomsCache = new Map<string, Promise<Record<string, Record<string, unknown>[]> | null>>(); constructor(private readonly base = '/data') {} @@ -135,22 +212,66 @@ 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<string, MonsterAbilityCard[]> = {}; + 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 * `#` and name stripped — `"#0 Howling in the Snow"` → `"0"`); the first @@ -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<n>`) 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-<perk>` → the perk's image under `attack/perks/` (plus an + * `imbue.png` corner marker); `imbue2-<perk>` gets `advancedImbue.png`. + * - `Demons-` / `Merchant-Guild-` / `Military-` prefixes are stripped and a + * faction marker is shown. + * - `P<n>` 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<string, number> { + const map: Record<string, number> = {}; + for (let item of attributes ?? []) { + const sizeMod = item.charAt(0); + if (sizeMod === '^' || (sizeMod === '*' && item.length > 1)) { + item = item.substring(1); + } + if (item.charAt(0) === '%') { + for (let i = 1; i < item.length; i++) { + if (item.charAt(i) === '%') { + const token = item.substring(1, i); + let number = 0; + if (i !== item.length - 1) { + for (let j = i + 2; j < item.length; j++) { + if (item.charAt(j) === ' ' || j === item.length - 1) { + const nr = item.substring(i + 1, j + 1); + const res = calculateFormula(nr, ctx); + if (res != null) number = res; + break; + } + } + } + if (token === 'target' && number === 0) continue; + map[token] = number; + break; // only one token per attribute line + } + } + } + } + return map; +} + +/** The token values for the monster's normal or elite stats. */ +function getStatTokens( + monster: StatMonster, + isElite: boolean, + ctx: StatApplierContext +): Record<string, number> { + const { normal, elite, boss } = monster.level; + if (boss != null) { + if (isElite) return {}; + return parseTokens(boss.attributes, ctx); + } + const data = isElite ? elite : normal; + if (data == null) return {}; + return parseTokens(data.attributes, ctx); +} + +/** The condition tokens appended after an attack line (all but the stats). */ +const nonConditionStat = (item: string): boolean => + /[a-z]/.test(item) && + item !== 'shield' && + item !== 'retaliate' && + item !== 'range' && + item !== 'heal' && + item !== 'jump'; + +function applyStatForToken( + formula: string, + line: string, + sizeModifier: string, + startIndex: number, + endIndex: number, + monster: StatMonster, + showNormal: boolean, + showElite: boolean, + lastToken: string, + normalTokens: Record<string, number>, + eliteTokens: Record<string, number>, + ctx: StatApplierContext +): string[] { + if (!showElite && !showNormal) return [line]; + + const retVal: string[] = []; + const tokens: string[] = []; + const eTokens: string[] = []; + let normalValue = 0; + let eliteValue = 0; + let skipCalculation = false; + const normalBlock = monster.level.boss ?? monster.level.normal; + const eliteBlock = monster.level.elite; + + if (lastToken === 'attack') { + if (normalBlock == null) return []; + const calc = calcStat(normalBlock.attack, ctx); + if (calc != null) normalValue = calc; + else skipCalculation = true; + if (eliteBlock != null) { + const ec = calcStat(eliteBlock.attack, ctx); + if (ec != null) eliteValue = ec; + } + for (const item of Object.keys(normalTokens)) { + if (nonConditionStat(item)) tokens.push(`%${item}%`); + } + for (const item of Object.keys(eliteTokens)) { + if (nonConditionStat(item)) eTokens.push(`%${item}%`); + } + } else if (lastToken === 'range') { + if ((normalBlock?.range ?? 0) !== 0) { + normalValue = normalBlock?.range ?? 0; + if (eliteBlock != null) eliteValue = eliteBlock.range ?? 0; + } + } else if (lastToken === 'move') { + normalValue = calcStat(normalBlock?.move, ctx) ?? 0; + if (eliteBlock != null) eliteValue = calcStat(eliteBlock.move, ctx) ?? 0; + } else if (lastToken === 'shield') { + if (eliteBlock != null && eliteTokens.shield != null) eliteValue = eliteTokens.shield; + if (normalBlock != null && normalTokens.shield != null) normalValue = normalTokens.shield; + } else if (lastToken === 'retaliate') { + if (eliteBlock != null && eliteTokens.retaliate != null) eliteValue = eliteTokens.retaliate; + if (normalBlock != null && normalTokens.retaliate != null) + normalValue = normalTokens.retaliate; + } + + let normalResult = formula; + if (!skipCalculation) { + const res = calculateFormula(`${formula}+${normalValue}`, ctx); + if (res != null) normalResult = (res < 0 ? 0 : res).toString(); + else skipCalculation = true; + } + + let newStartOfLine = line.substring(0, startIndex); + if (showNormal) { + newStartOfLine += normalResult; + if (!skipCalculation) { + for (const item of tokens) { + newStartOfLine += `|${item}`; + const key = item.substring(1, item.length - 1); + const value = normalTokens[key] ?? 0; + if (value > 0) newStartOfLine += String(value); + } + } + } + + // Special case: uncalculable and only elites ("heed the pigs"). + if (eliteBlock != null && skipCalculation && showElite && !showNormal) { + newStartOfLine += normalResult; + } + + if (eliteBlock != null && !skipCalculation && showElite) { + if (showNormal) newStartOfLine += '/'; + retVal.push(newStartOfLine); + const eliteResult = + calculateFormula(`${formula}+${eliteValue}`, ctx) ?? 0; + const clamped = eliteResult < 0 ? 0 : eliteResult; + let eliteString = `!${sizeModifier}£${clamped}`; + for (const item of eTokens) { + eliteString += `|${item}`; + const key = item.substring(1, item.length - 1); + const value = eliteTokens[key]!; + if (value > 0) eliteString += String(value); + } + retVal.push(eliteString); + } else { + retVal.push(newStartOfLine); + } + + if (endIndex < line.length) { + const leftOver = `!${sizeModifier}${line.substring(endIndex + 1, line.length)}`; + retVal.push(leftOver); + } + return retVal; +} + +/** + * Apply the monster's stats to a line. Returns the list of display strings + * (usually one; more when an elite/normal split or trailing text is produced). + */ +export function applyMonsterStats( + lineInput: string, + sizeToken: string, + monster: StatMonster, + forceShowAll: boolean, + ctx: StatApplierContext = {} +): string[] { + let showElite = false; + const noStandees = ctx.noStandees ?? false; + if ((noStandees && monster.isActive) || monster.standeeTypes.includes(ELITE)) { + showElite = true; + } + let showNormal = false; + if ( + (noStandees && monster.isActive) || + monster.standeeTypes.some((t) => t !== ELITE) + ) { + showNormal = true; + } + if (forceShowAll) { + showElite = true; + showNormal = true; + } + + let line = lineInput; + let retVal: string[] = []; + + const normalTokens = getStatTokens(monster, false, ctx); + const eliteTokens = getStatTokens(monster, true, ctx); + + let lastToken = ''; + let isInToken = false; + let tokenStartIndex = 0; + + for (let i = 0; i < line.length; i++) { + if (line.charAt(i) === '%') { + if (!isInToken) { + isInToken = true; + tokenStartIndex = i + 1; + } else { + isInToken = false; + lastToken = line.substring(tokenStartIndex, i); + } + } + + const isStart = + (!isInToken && + (line.charAt(i) === '+' || + line.charAt(i) === '-' || + line.charAt(i) === 'C' || + line.charAt(i) === 'L')) || + line.charAt(i) === 'X' || + ((numberish(line.charAt(i)) && lastToken === '') && + (i === 0 || line.charAt(i - 1) === ' ')); + + if (isStart) { + let formula = line.charAt(i); + const startIndex = i; + let endIndex = i; + + for (let j = i + 1; j < lineInput.length; j++) { + const val = lineInput.charAt(j); + if (numberish(val) || val === 'd') { + if (val !== ' ') formula += val; + endIndex = j; + } else { + i = j; + if (lineInput.charAt(i - 1) === ' ') { + i = j - 1; + endIndex -= 1; + } + if (i > 0 && lineInput.charAt(i - 1) === '(') { + i = j - 1; + endIndex -= 1; + formula = formula.substring(0, formula.length - 1); + if (i > 1 && lineInput.charAt(i - 2) === ' ') { + i = j - 1; + endIndex -= 1; + } + } + break; + } + } + + if ( + (formula.length > 1 && lastToken !== '') || + formula.length > 2 + ) { + if (lastToken !== '') { + retVal = applyStatForToken( + formula, + line, + sizeToken, + startIndex, + endIndex, + monster, + showNormal, + showElite, + lastToken, + normalTokens, + eliteTokens, + ctx + ); + lastToken = ''; + if (retVal.length > 0) return retVal; + } else { + const result = calculateFormula(formula, ctx); + if (result != null) { + const r = result < 0 ? 0 : result; + line = line.slice(0, startIndex) + String(r) + line.slice(endIndex + 1); + } + } + } + } + } + + return [line]; +} 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<string, string> = { + 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<string, string> = { '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/<locale>.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<string, string>; + +/** The flattened in-game table for the active locale (empty for `en`). */ +export const gameTable: Writable<GameTable> = writable<GameTable>({}); + +/** 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<Locale, GameTable>(); + +function flatten(data: Record<string, unknown>): 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<void> { + 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<string, unknown>; + 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<string, number>; + /** 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<string, number>; + '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<LootPoolKey, number[]>; +} + +/** 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 @@ +<!-- + One [−] icon [total] [+] counter (the reference `CounterButton`): the + deck-header removable counters (bless/curse/empower/enfeeble) send + changeBless/Curse/Empower/Enfeeble with `change` ±1 through it. +--> +<script lang="ts"> + let { + image, + total, + maxValue, + showTotal = true, + extraImage = null, + onIncrement, + onDecrement + }: { + /** The counter icon, e.g. `/images/abilities/bless.png`. */ + image: string; + /** The current total (the deck's removable counter). */ + total: number; + /** The reference `maxValue` — the plus is disabled at/above it. */ + maxValue: number; + /** Show the total next to the icon (deck headers do). */ + showTotal?: boolean; + /** An optional second icon overprinted (two enfeeble owners, …). */ + extraImage?: string | null; + onIncrement: () => void; + onDecrement: () => void; + } = $props(); +</script> + +<div class="counter" role="group" aria-label={image}> + <button + class="counter__btn" + aria-label="decrease" + disabled={total <= 0} + onclick={onDecrement} + > + <img src="/images/psd/sub.png" alt="−" /> + </button> + + <div class="counter__icon"> + <img src={image} alt="" /> + {#if extraImage} + <img class="counter__extra" src={extraImage} alt="" /> + {/if} + {#if showTotal} + <span class="counter__total">{total}</span> + {/if} + </div> + + <button + class="counter__btn" + aria-label="increase" + disabled={total >= maxValue} + onclick={onIncrement} + > + <img src="/images/psd/add.png" alt="+" /> + </button> +</div> + +<style> + .counter { + display: flex; + align-items: center; + gap: 2px; + } + .counter__btn { + width: 32px; + height: 32px; + padding: 2px; + background: transparent; + border: none; + border-radius: 4px; + cursor: pointer; + } + .counter__btn:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.15); + } + .counter__btn:disabled { + opacity: 0.35; + cursor: default; + } + .counter__btn img { + width: 100%; + height: 100%; + filter: brightness(0) invert(1); + } + .counter__icon { + position: relative; + width: 32px; + height: 32px; + } + .counter__icon > img { + width: 100%; + height: 100%; + object-fit: contain; + } + .counter__extra { + position: absolute; + inset: 0; + opacity: 0.55; + } + .counter__total { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + font-weight: 700; + color: #fff; + text-shadow: 1px 1px 1px #000; + pointer-events: none; + } +</style> 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 @@ <script lang="ts"> import type { GameSession } from '$lib/state/session'; import { isCharacter, isMonster, isNoteRow } from '$lib/protocol/types'; + import type { MonsterItem } from '$lib/protocol/types'; + import type { CampaignData } from '$lib/data/gameData'; import type { FigureRef } from './StatusMenu.svelte'; import CharacterRow from './CharacterRow.svelte'; import MonsterRow from './MonsterRow.svelte'; @@ -14,10 +16,16 @@ let { session, - onOpenMenu + onOpenMenu, + campaignData, + onOpenAbility, + onZoomAbility }: { session: GameSession; onOpenMenu: (figure: FigureRef) => void; + campaignData: CampaignData | null; + onOpenAbility: (item: MonsterItem) => void; + onZoomAbility: (item: MonsterItem) => void; } = $props(); const gameState = session.state; @@ -29,7 +37,14 @@ {#if isCharacter(item)} <CharacterRow {session} {item} {onOpenMenu} /> {:else if isMonster(item)} - <MonsterRow {session} {item} {onOpenMenu} /> + <MonsterRow + {session} + {item} + {onOpenMenu} + {campaignData} + {onOpenAbility} + {onZoomAbility} + /> {:else if isNoteRow(item)} <NoteRow {session} {item} /> {/if} diff --git a/web/src/lib/ui/MonsterRow.svelte b/web/src/lib/ui/MonsterRow.svelte index 3f3442b..e2a4383 100644 --- a/web/src/lib/ui/MonsterRow.svelte +++ b/web/src/lib/ui/MonsterRow.svelte @@ -7,18 +7,28 @@ <script lang="ts"> import type { GameSession } from '$lib/state/session'; import type { MonsterItem } from '$lib/protocol/types'; + import type { CampaignData } from '$lib/data/gameData'; import { monsterImage } from '$lib/game/art'; import { standeeFigureId } from '$lib/game/stats'; + import { isFrosthavenStyleForMonster } from '$lib/game/rules'; + import { styleTheme } from '$lib/settings'; import type { FigureRef } from './StatusMenu.svelte'; + import AbilityCardSlot from './decks/AbilityCardSlot.svelte'; let { session, item, - onOpenMenu + onOpenMenu, + campaignData, + onOpenAbility, + onZoomAbility }: { session: GameSession; item: MonsterItem; onOpenMenu: (figure: FigureRef) => void; + campaignData: CampaignData | null; + onOpenAbility: (item: MonsterItem) => void; + onZoomAbility: (item: MonsterItem) => void; } = $props(); const player = session.player; @@ -50,6 +60,26 @@ if (roundState !== 1 || !item.isActive || !$player) return; session.command('turnDone', { id: item.id }); } + + // --- ability cards (the reference `MonsterAbilityCardWidget`) ----------- + + const model = $derived( + campaignData?.monsters.find( + (m) => m.name === item.type || m.display === item.type + ) ?? null + ); + + const abilityDeck = $derived.by(() => { + const gs = $gameState; + if (gs == null || model == null) return null; + return gs.currentAbilityDecks.find((d) => d.name === model.deck) ?? null; + }); + + const fh = $derived.by((): boolean => { + const gs = $gameState; + if (gs == null || model == null) return false; + return isFrosthavenStyleForMonster(model.edition, gs, $styleTheme); + }); </script> <div class="row row--monster" class:row--current={currentTurn} class:row--done={gray}> @@ -106,4 +136,16 @@ {/each} </div> {/if} + + {#if $gameState} + <AbilityCardSlot + state={$gameState} + {item} + deck={abilityDeck} + {campaignData} + {fh} + onOpen={() => onOpenAbility(item)} + onZoom={() => onZoomAbility(item)} + /> + {/if} </div> 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 @@ --> <script lang="ts"> import type { GameSession } from '$lib/state/session'; - import type { CharacterItem, MonsterInstance, MonsterItem } from '$lib/protocol/types'; + import type { + CharacterItem, + ModifierDeck, + MonsterInstance, + MonsterItem + } from '$lib/protocol/types'; import { characterStatCounters, standeeFigureId, - standeeStatCounters, - type ModifierDeckJson + standeeStatCounters } from '$lib/game/stats'; import { isObjectiveOrEscort } from '$lib/data/classInfo'; import { CONDITIONS } from '$lib/game/conditions'; @@ -100,9 +104,9 @@ } const owner = liveOwner; if (!owner) return null; - const deck = 'characterState' in owner - ? (owner.characterState.modifierDeck as ModifierDeckJson | undefined) - : ($gameState?.modifierDeck as ModifierDeckJson | undefined); + const deck: ModifierDeck | undefined = 'characterState' in owner + ? owner.characterState.modifierDeck + : $gameState?.modifierDeck; return deck ? standeeStatCounters(deck) : null; }); diff --git a/web/src/lib/ui/cards/AbilityCardBack.svelte b/web/src/lib/ui/cards/AbilityCardBack.svelte new file mode 100644 index 0000000..362ced1 --- /dev/null +++ b/web/src/lib/ui/cards/AbilityCardBack.svelte @@ -0,0 +1,60 @@ +<!-- + The back of a monster ability card (the reference + `MonsterAbilityCardRear`): the card artwork with the draw-pile size in + the bottom-right corner (hidden when `size` is negative). +--> +<script lang="ts"> + let { + fh = true, + size = -1, + scale = 1 + }: { + fh?: boolean; + /** The draw-pile count shown bottom-right; negative hides it. */ + size?: number; + scale?: number; + } = $props(); + + const width = 142.4 * scale; + const height = 94.4 * scale; +</script> + +<div + class="acback" + style="width: {width}px; height: {height}px" +> + <img + class="acback__bg" + src={fh ? '/images/psd/MonsterAbility-back_fh.png' : '/images/psd/MonsterAbility-back.png'} + alt="" + draggable="false" + /> + {#if size >= 0} + <div class="acback__size" style="font-size: {12.8 * scale}px">{size}</div> + {/if} +</div> + +<style> + .acback { + position: relative; + border-radius: 4px; + flex-shrink: 0; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); + } + .acback__bg { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + border-radius: 4px; + object-fit: fill; + } + .acback__size { + position: absolute; + right: 4.8px; + bottom: 0; + font-family: system-ui, sans-serif; + color: #fff; + text-shadow: 0.8px 0.8px 1px #000; + } +</style> 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 @@ +<!-- + The ability-line renderer (the web counterpart of the reference + `LineBuilder.createLines` output, PORTING.md §8b). Walks the structured + tree produced by `parseLines` and renders it: rows of text / icons / + element-use, gray sub-line boxes, dotted conditional boxes, columns, + row-groups, element images and dividers. Font metrics come from + `resolveStyle` (the reference `LineStyles`); icons come from the served + `/images/abilities/` assets. +--> +<script lang="ts"> + import type { LineStyle, Node } from '$lib/game/line/types'; + import { resolveStyle } from '$lib/game/line/lineStyle'; + import { abilityImage, dividerImage } from '$lib/game/line/images'; + + let { + node, + fh = true, + left = false, + scale = 1 + }: { + node: Node; + fh?: boolean; + left?: boolean; + scale?: number; + } = $props(); + + /** The resolved font metrics for a style. */ + function r(style: LineStyle) { + return resolveStyle(style, fh, left); + } +</script> + +{#if node.kind === 'column'} + <div class="at-col" style="align-items: {node.align === 'left' ? 'flex-start' : node.align === 'right' ? 'flex-end' : 'center'}"> + {#each node.children as child} + <svelte:self node={child} {fh} {left} {scale} /> + {/each} + </div> +{:else if node.kind === 'row' || node.kind === 'rowgroup'} + <div + class="at-row" + class:at-row--group={node.kind === 'rowgroup'} + style="justify-content: {node.align === 'left' ? 'flex-start' : node.align === 'right' ? 'flex-end' : 'center'}" + > + {#each node.children as child} + <svelte:self node={child} {fh} {left} {scale} /> + {/each} + </div> +{:else if node.kind === 'subline'} + <div class="at-subline" class:at-subline--boss={node.boss}> + {#each node.children as child} + <svelte:self node={child} {fh} {left} {scale} /> + {/each} + </div> +{:else if node.kind === 'conditional'} + <div class="at-conditional" class:at-conditional--boss={node.boss} class:at-conditional--banner={node.belongs}> + {#if node.belongs} + <img class="at-conditional__banner" src="/images/abilities/element_top.png" alt="" /> + {/if} + <div class="at-conditional__inner"> + {#each node.children as child} + <svelte:self node={child} {fh} {left} {scale} /> + {/each} + </div> + </div> +{:else if node.kind === 'text'} + {@const m = r(node.style)} + {#if m.color !== 'transparent'} + <span + class="at-text" + style="font-size: {m.size * scale}px; line-height: {m.height}; color: {m.color}" + >{node.text}</span> + {:else} + <span style="display: inline-block; width: {m.size * scale}px"></span> + {/if} +{:else if node.kind === 'token'} + {@const h = r(node.style).size * scale} + <img + class="at-token" + src={abilityImage(node.gfx, node.token, fh)} + alt={node.token} + style="height: {h}px; width: {h}px" + draggable="false" + /> +{:else if node.kind === 'elementUse'} + {@const h = r(node.style).size * scale} + <span class="at-use" style="height: {h}px; width: {h}px"> + <img src={abilityImage(node.element, node.element, fh)} alt={node.element} style="height: {h}px; width: {h}px" draggable="false" /> + <img + class="at-use__use" + src={abilityImage('use', 'use', fh)} + alt="use" + style="height: {h * 0.5}px" + draggable="false" + /> + </span> +{:else if node.kind === 'image'} + {@const h = r('normal').size * scale * (node.element ? 0.6 : 1)} + <img + class="at-image" + src={abilityImage(node.gfx, node.gfx, fh)} + alt={node.gfx} + style="height: {h}px" + draggable="false" + /> +{:else if node.kind === 'divider'} + <img + class="at-divider" + src={dividerImage(node.boss)} + alt="" + style="height: {node.thin ? 2 * scale : 6 * scale}px; width: {55 * scale}px" + draggable="false" + /> +{/if} + +<style> + .at-col { + display: flex; + flex-direction: column; + justify-content: center; + width: 100%; + } + .at-row { + display: flex; + flex-direction: row; + align-items: center; + width: 100%; + } + .at-row--group { + gap: 2px; + } + .at-text { + font-family: 'Markazi', 'Majalla', system-ui, sans-serif; + white-space: pre-wrap; + text-shadow: 0.4px 0.4px 1px rgba(0, 0, 0, 0.87); + } + .at-token { + display: inline-block; + vertical-align: middle; + flex-shrink: 0; + } + .at-image { + display: block; + margin: 0 auto; + } + .at-divider { + display: block; + margin: 0 auto; + opacity: 0.9; + } + .at-use { + position: relative; + display: inline-block; + vertical-align: middle; + flex-shrink: 0; + } + .at-use__use { + position: absolute; + bottom: 0; + left: 20%; + } + .at-subline { + display: flex; + flex-direction: column; + background: rgba(128, 128, 128, 0.6); + border-radius: 6px; + padding: 0.5px 2.5px 0.3px 2px; + margin: 0 2px; + } + .at-subline--boss { + background: rgba(210, 210, 210, 0.27); + } + .at-subline .at-row { + justify-content: flex-start; + } + .at-conditional { + position: relative; + display: inline-block; + margin: 2px; + } + .at-conditional__inner { + display: flex; + flex-direction: column; + background: rgba(128, 128, 128, 0.6); + border: 1.5px dotted rgba(255, 255, 255, 0.85); + border-radius: 10px; + padding: 2px 2px 0.5px 2px; + } + .at-conditional--boss .at-conditional__inner { + background: rgba(210, 210, 210, 0.27); + } + .at-conditional__banner { + position: absolute; + top: -3px; + left: 50%; + transform: translateX(-50%); + width: 20px; + z-index: 1; + } +</style> 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 @@ +<!-- + One loot card (the reference `LootCardFront` / `LootCardRear`): the loot + `gfx` image with its value (`+n`), the 1418/1419 special text, the + enhancement level, and the owning character's class icon. +--> +<script lang="ts"> + import type { LootCard as Card } from '$lib/protocol/types'; + import { lootValue } from '$lib/game/cards/lootCard'; + import { t } from '$lib/i18n'; + + let { + card, + revealed, + ownerName = '', + characterCount = 4, + scale = 1 + }: { + card: Card; + revealed: boolean; + /** The owning character's class name (for the corner icon). */ + ownerName?: string; + /** Party size (the value table depends on it). */ + characterCount?: number; + scale?: number; + } = $props(); + + const width = 39 * scale; + const height = 58.6666 * scale; + + const value = $derived(revealed ? lootValue(card, characterCount) : null); + const special = $derived( + revealed + ? card.gfx.includes('1418') + ? '1418' + : card.gfx.includes('1419') + ? '1419' + : '' + : '' + ); + const showOwner = $derived(revealed && card.owner.length > 0); +</script> + +<div class="lootcard" style="width: {width}px; height: {height}px"> + <img + class="lootcard__bg" + src={revealed ? `/images/loot/${card.gfx}.png` : '/images/loot/back.png'} + alt={card.gfx} + draggable="false" + /> + {#if value !== null} + <div class="lootcard__value" style="font-size: {30 * scale}px">+{value}</div> + {/if} + {#if special} + <div class="lootcard__value" style="font-size: {25 * scale}px">{special}</div> + {/if} + {#if revealed && card.enhanced > 0} + <div class="lootcard__enhanced" style="font-size: {9 * scale}px"> + {t('enhancedLevel', { level: card.enhanced })} + </div> + {/if} + {#if showOwner} + <img + class="lootcard__owner" + src="/images/class-icons/{ownerName}.png" + alt={ownerName} + style="width: {15 * scale}px; height: {15 * scale}px" + draggable="false" + /> + {/if} +</div> + +<style> + .lootcard { + position: relative; + border-radius: 4px; + flex-shrink: 0; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); + } + .lootcard__bg { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + border-radius: 4px; + object-fit: fill; + } + .lootcard__value { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + font-family: system-ui, sans-serif; + font-weight: 700; + color: #fff; + text-shadow: 0.6px 0.6px 1px rgba(0, 0, 0, 0.87); + pointer-events: none; + } + .lootcard__enhanced { + position: absolute; + bottom: 5px; + left: 0; + right: 0; + text-align: center; + color: #fff; + text-shadow: 0.3px 0.3px 0.8px rgba(0, 0, 0, 0.87); + pointer-events: none; + } + .lootcard__owner { + position: absolute; + top: 2px; + right: 2px; + filter: brightness(0) invert(1); + } +</style> 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 @@ +<!-- + One modifier (AMD) card (the reference `ModifierCardFront` / + `ModifierCardRear`): the `gfx` image with an optional corner marker + (imbue / faction / perk / class icon). `name` is the owning deck — the + shared party deck (""), "allies", or a character-class name. Pass + `perks` for a character deck so `P<n>` graphics resolve. +--> +<script lang="ts"> + import type { ModifierCard as Card } from '$lib/protocol/types'; + import { + extraGfxUrl, + gfxUrl, + hasExtra, + rearMarker + } from '$lib/game/cards/modifierCardGfx'; + + let { + card, + name, + revealed, + perks = null, + scale = 1 + }: { + card: Card; + name: string; + revealed: boolean; + perks?: string[][] | null; + scale?: number; + } = $props(); + + const width = 58.6666 * scale; + const height = 39 * scale; + + const frontGfx = $derived(gfxUrl(card, name, perks)); + const frontExtra = $derived(extraGfxUrl(card, name)); + const showExtra = $derived(hasExtra(card, name)); + const rear = $derived(rearMarker(name)); +</script> + +<div + class="modcard" + style="width: {width}px; height: {height}px; --scale: {scale}" +> + {#if revealed} + <img + class="modcard__bg" + src={frontGfx} + alt={card.gfx} + draggable="false" + /> + {#if showExtra} + <img + class="modcard__marker-bg" + src="/images/attack/class-marker-background.png" + alt="" + draggable="false" + /> + <img class="modcard__marker-icon" src={frontExtra} alt="" draggable="false" /> + {/if} + {:else} + <img + class="modcard__bg" + src="/images/attack/back.png" + alt="" + draggable="false" + /> + {#if rear.has} + <img + class="modcard__rear-bg" + src="/images/attack/class-marker-background.png" + alt="" + draggable="false" + /> + <img class="modcard__rear-icon" src={rear.gfx} alt="" draggable="false" /> + {/if} + {/if} +</div> + +<style> + .modcard { + position: relative; + border-radius: 4px; + flex-shrink: 0; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); + } + .modcard__bg { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + border-radius: 4px; + object-fit: fill; + } + .modcard__marker-bg { + position: absolute; + top: calc(26.5 * var(--scale) * 1px); + left: calc(3 * var(--scale) * 1px); + width: calc(10 * var(--scale) * 1px); + height: calc(10 * var(--scale) * 1px); + } + .modcard__marker-icon { + position: absolute; + top: calc(27.75 * var(--scale) * 1px); + left: calc(4.2 * var(--scale) * 1px); + width: calc(7.5 * var(--scale) * 1px); + height: calc(7.5 * var(--scale) * 1px); + filter: brightness(0) invert(1); + } + .modcard__rear-bg { + position: absolute; + top: calc(5.5 * var(--scale) * 1px); + left: calc(15.7 * var(--scale) * 1px); + width: calc(27 * var(--scale) * 1px); + height: calc(27 * var(--scale) * 1px); + } + .modcard__rear-icon { + position: absolute; + top: calc(9 * var(--scale) * 1px); + left: calc(19 * var(--scale) * 1px); + width: calc(20 * var(--scale) * 1px); + height: calc(20 * var(--scale) * 1px); + filter: brightness(0) invert(1); + } +</style> 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 @@ +<!-- + A monster ability card (the reference `MonsterAbilityCardFront`): the card + back with title, initiative, card number, shuffle badge, positioned + graphics, and the ability lines rendered by {@link AbilityText} from the + `parseLines` tree. +--> +<script lang="ts"> + import type { MonsterAbilityCard } from '$lib/protocol/types'; + import type { StatMonster } from '$lib/game/line/statApplier'; + import type { ColumnNode } from '$lib/game/line/types'; + import { buildAbilityCardTree } from '$lib/game/line/buildAbility'; + import { gt, gameTable } from '$lib/i18n/gameI18n'; + import { isElement } from '$lib/game/line/tokens'; + import AbilityText from './AbilityText.svelte'; + + let { + card, + stat, + fh = true, + flying = false, + scale = 1, + applyStats = true, + applyAll = false + }: { + card: MonsterAbilityCard; + stat: StatMonster | null; + fh?: boolean; + flying?: boolean; + scale?: number; + applyStats?: boolean; + applyAll?: boolean; + } = $props(); + + // The tree re-resolves when the in-game locale table changes. + const tree = $derived.by(() => { + void $gameTable; + return buildAbilityCardTree(card, stat, { + fh, + flying, + scale, + applyStats, + applyAll + }) as ColumnNode; + }); + + const width = 142.4 * scale; + const height = 94.4 * scale; + + const initText = $derived( + card.initiative.toString().length === 1 + ? `0${card.initiative}` + : card.initiative.toString() + ); +</script> + +<div + class="mac" + style="width: {width}px; height: {height}px; --scale: {scale}" +> + <img + class="mac__bg" + src={fh ? '/images/psd/monsterAbility-front_fh.png' : '/images/psd/monsterAbility-front.png'} + alt="" + draggable="false" + /> + + {#each card.graphics.slice(0, 4) as g} + <img + class="mac__gfx" + src={`/images/abilities/${g.gfx}.png`} + alt="" + draggable="false" + style="left: {g.x * width}px; top: {g.y * height}px; transform: rotate({g.angle}deg) scale({g.scale * scale * (isElement(g.gfx) ? 0.264 : 0.44)}); transform-origin: top left" + /> + {/each} + + <div class="mac__title" style="font-size: {fh ? 10 * scale : 11.2 * scale}px"> + {gt(card.title)} + </div> + <div class="mac__init" style="font-size: {fh ? 15 * scale : 16 * scale}px"> + {initText} + </div> + <div class="mac__nr" style="font-size: {6.4 * scale}px">{card.nr}</div> + + {#if card.shuffle} + <img class="mac__shuffle" src="/images/abilities/shuffle.png" alt="shuffle" draggable="false" style="height: {12.8 * scale}px" /> + {/if} + + <div class="mac__lines"> + <AbilityText node={tree} {fh} {scale} /> + </div> +</div> + +<style> + .mac { + position: relative; + border-radius: 8px; + flex-shrink: 0; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); + } + .mac__bg { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + border-radius: 8px; + object-fit: fill; + } + .mac__gfx { + position: absolute; + } + .mac__title { + position: absolute; + top: 2px; + left: 0; + right: 0; + text-align: center; + font-family: 'Markazi', 'Majalla', system-ui, sans-serif; + color: #fff; + text-shadow: 0.6px 0.6px 1px rgba(0, 0, 0, 0.87); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .mac__init { + position: absolute; + left: 4px; + top: 12.8px; + font-family: 'Markazi', 'Majalla', system-ui, sans-serif; + color: #fff; + text-shadow: 0.6px 0.6px 1px rgba(0, 0, 0, 0.87); + } + .mac__nr { + position: absolute; + left: 4.8px; + bottom: 0.4px; + font-family: system-ui, sans-serif; + color: #fff; + text-shadow: 0.6px 0.6px 1px rgba(0, 0, 0, 0.87); + } + .mac__shuffle { + position: absolute; + right: 6px; + bottom: 3.2px; + } + .mac__lines { + position: absolute; + top: 11px; + left: 0; + right: 0; + bottom: 0; + display: flex; + align-items: center; + justify-content: center; + padding: 0 4px; + } +</style> 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 @@ +<!-- + One monster's ability card in its row (the reference + `MonsterAbilityCardWidget`): the front of the current (top discard) + card while the round is playing turns and the monster is active, + else the card back with the draw-pile size. Tap opens the deck + menu; double-tap (front only) zooms the card. +--> +<script lang="ts"> + import type { + GameState, + MonsterAbilityCard as AbilityCard, + MonsterAbilityState, + MonsterItem + } from '$lib/protocol/types'; + import type { CampaignData } from '$lib/data/gameData'; + import type { StatMonster } from '$lib/game/line/statApplier'; + import { statMonsterFor } from '$lib/game/line/buildAbility'; + import { isInactiveForRule } from '$lib/game/rules'; + import MonsterAbilityCard from '../cards/MonsterAbilityCard.svelte'; + import AbilityCardBack from '../cards/AbilityCardBack.svelte'; + + const ROW_CARD_SCALE = 0.72; + + let { + state, + item, + deck, + campaignData, + fh, + onOpen, + onZoom + }: { + state: GameState; + item: MonsterItem; + /** This monster's ability deck (matched by model deck name), if any. */ + deck: MonsterAbilityState | null; + campaignData: CampaignData | null; + fh: boolean; + onOpen: () => void; + onZoom: () => void; + } = $props(); + + const model = $derived( + campaignData?.monsters.find( + (m) => m.name === item.type || m.display === item.type + ) ?? null + ); + + const showFront = $derived( + state.roundState === 1 && + item.isActive && + !isInactiveForRule(state, item.type) && + deck != null && + deck.discardPile.length > 0 + ); + + const cardRef = $derived( + showFront && deck != null + ? deck.discardPile[deck.discardPile.length - 1] + : null + ); + const card = $derived.by((): AbilityCard | null => { + if (cardRef == null) return null; + const list = campaignData?.abilityDecks[cardRef.deck] ?? []; + return list.find((c) => c.nr === cardRef.nr) ?? null; + }); + + const stat = $derived.by((): StatMonster | null => { + if (model == null) return null; + return statMonsterFor( + model, + item.level, + item.monsterInstances.map((s) => s.type), + item.isActive + ); + }); + + function onKeydown(e: KeyboardEvent) { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + onOpen(); + } + } +</script> + +<div + class="slot" + role="button" + tabindex="0" + aria-label="ability cards" + onclick={onOpen} + ondblclick={() => { + if (showFront) onZoom(); + }} + onkeydown={onKeydown} +> + {#if showFront && card != null} + <MonsterAbilityCard + {card} + {stat} + {fh} + flying={model?.flying ?? false} + scale={ROW_CARD_SCALE} + applyStats={false} + /> + {:else} + <AbilityCardBack + {fh} + size={deck ? deck.drawPile.length : -1} + scale={ROW_CARD_SCALE} + /> + {/if} +</div> + +<style> + .slot { + flex-shrink: 0; + margin-left: 4px; + cursor: pointer; + } +</style> 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 @@ +<!-- + The ability-card zoom (the reference `AbilityCardZoom`): the current + card at ~2.5x scale, tap (or Escape) to close. +--> +<script lang="ts"> + import type { MonsterAbilityCard as AbilityCard } from '$lib/protocol/types'; + import type { StatMonster } from '$lib/game/line/statApplier'; + import MonsterAbilityCard from '../cards/MonsterAbilityCard.svelte'; + + const DEFAULT_ZOOM = 2.5; + + let { + card, + stat, + fh, + flying = false, + open = $bindable(true) + }: { + card: AbilityCard; + stat: StatMonster | null; + fh: boolean; + flying?: boolean; + open?: boolean; + } = $props(); + + // Fit the card into the viewport (the reference shrinks the zoom to fit). + function scaleFor(): number { + if (typeof window === 'undefined') return DEFAULT_ZOOM; + const w = window.innerWidth; + const h = window.innerHeight; + let zoom = Math.min( + DEFAULT_ZOOM, + (w - 80) / 142.4, + (h - 120) / 94.4 + ); + return Math.max(zoom, 0.5); + } + const scale = $state(scaleFor()); +</script> + +{#if open} + <div + class="zoom" + role="dialog" + aria-modal="true" + onclick={() => (open = false)} + onkeydown={(e) => e.key === 'Escape' && (open = false)} + > + <MonsterAbilityCard + {card} + {stat} + {fh} + {flying} + scale={scale} + applyStats={false} + /> + </div> +{/if} + +<style> + .zoom { + position: fixed; + inset: 0; + z-index: 40; + display: flex; + align-items: center; + justify-content: center; + background: rgba(0, 0, 0, 0.75); + cursor: pointer; + } +</style> 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 @@ +<!-- + The monster ability-card deck menu (the reference `AbilityCardsMenu`): + "Reveal cards:" buttons (local flip of the top draw-pile cards, 1-8 / + All), Draw extra card, Extra Shuffle, Activate/Inactivate Monster, then + the two card columns — the draw pile (face down unless revealed, + drag-reorderable, tap to remove) and the discard pile (face up, tap to + remove). +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + import type { + MonsterAbilityCard as AbilityCard, + MonsterAbilityCardRef, + MonsterAbilityState, + MonsterItem + } from '$lib/protocol/types'; + import type { CampaignData } from '$lib/data/gameData'; + import { t } from '$lib/i18n'; + import MonsterAbilityCard from '../cards/MonsterAbilityCard.svelte'; + import AbilityCardBack from '../cards/AbilityCardBack.svelte'; + import Menu from '../Menu.svelte'; + + const LIST_CARD_SCALE = 0.55; + const MAX_REVEAL_BUTTONS = 8; + + let { + session, + item, + deck, + campaignData, + fh, + open = $bindable(true) + }: { + session: GameSession; + item: MonsterItem; + deck: MonsterAbilityState; + campaignData: CampaignData | null; + fh: boolean; + open?: boolean; + } = $props(); + + const gameState = session.state; + const player = session.player; + + const model = $derived( + campaignData?.monsters.find( + (m) => m.name === item.type || m.display === item.type + ) ?? null + ); + + // Top-first lists (the reference reverses the bottom-first draw pile). + const drawTopFirst = $derived([...deck.drawPile].reverse()); + const discardList = $derived(deck.discardPile); + + // The locally-revealed top cards (menu-only, not a deck command). + let revealedCount = $state(0); + // Reset the local reveal whenever the draw pile changes. + const drawSignature = $derived( + deck.drawPile.map((c) => `${c.nr}`).join(',') + ); + $effect(() => { + void drawSignature; + revealedCount = 0; + }); + + const revealButtons = $derived( + Math.min(drawTopFirst.length, MAX_REVEAL_BUTTONS) + ); + + function fullCard(ref: MonsterAbilityCardRef): AbilityCard | null { + const list = campaignData?.abilityDecks[ref.deck] ?? []; + return list.find((c) => c.nr === ref.nr) ?? null; + } + + function cmd(name: string, args: Record<string, unknown> = {}) { + if ($player) session.command(name, args); + } + + // --- remove-card confirmation ------------------------------------------- + + let removeTarget = $state<MonsterAbilityCardRef | null>(null); + + // --- draw-pile reordering (HTML5 drag & drop) ---------------------------- + + let dragIndex = $state<number | null>(null); + let dropIndex = $state<number | null>(null); + + function onDragStart(i: number) { + dragIndex = i; + } + function onDragOver(e: DragEvent, i: number) { + e.preventDefault(); + dropIndex = i; + } + function onDrop() { + if (dragIndex != null && dropIndex != null && dragIndex !== dropIndex) { + // The list is top-first; the wire pile is bottom-first. + const n = deck.drawPile.length; + const oldIndex = n - 1 - dragIndex; + const newIndex = n - 1 - dropIndex; + cmd('reorderAbilityList', { + deck: deck.name, + oldIndex, + newIndex + }); + } + dragIndex = null; + dropIndex = null; + } +</script> + +<Menu {open} title={item.id}> + {#if $gameState && $player} + <div class="bar"> + <span class="bar__label">{t('revealCards')}</span> + {#each Array(revealButtons) as _, i} + <button + class="pill" + class:pill--wide={i + 1 >= drawTopFirst.length} + onclick={() => (revealedCount = i + 1 >= drawTopFirst.length ? drawTopFirst.length : i + 1)} + > + {i + 1 >= drawTopFirst.length ? t('revealAll') : i + 1} + </button> + {/each} + <button class="pill pill--text" onclick={() => cmd('drawAbilityCard', { ownerId: item.type })}> + {t('drawExtraCard')} + </button> + <button + class="pill pill--text" + onclick={() => { + revealedCount = 0; + cmd('shuffleAbilityCard', { ownerId: item.type }); + }} + > + {t('extraShuffle')} + </button> + <button + class="pill pill--text" + onclick={() => + cmd('activateMonsterType', { + name: item.type, + activate: !item.isActive + })} + > + {item.isActive ? t('inactivateMonster') : t('activateMonster')} + </button> + </div> + + <div class="columns"> + <div class="col" ondragend={() => (dragIndex = null)} ondrop={onDrop}> + {#each drawTopFirst as ref, i} + {@const c = fullCard(ref)} + <div + class="cardwrap" + draggable + ondragstart={() => 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} + <MonsterAbilityCard + card={c} + stat={null} + {fh} + scale={LIST_CARD_SCALE} + applyAll + /> + {:else} + <AbilityCardBack {fh} scale={LIST_CARD_SCALE} /> + {/if} + </div> + {/each} + </div> + + <div class="col"> + {#each discardList as ref} + {@const c = fullCard(ref)} + {#if c != null} + <div + class="cardwrap" + onclick={() => (removeTarget = ref)} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + removeTarget = ref; + }} + > + <MonsterAbilityCard + card={c} + stat={null} + {fh} + scale={LIST_CARD_SCALE} + applyAll + /> + </div> + {/if} + {/each} + </div> + </div> + {:else if $gameState} + <p class="spectate">{t('web:spectator')}</p> + {/if} + + {#if removeTarget} + {@const rt = removeTarget} + {@const card = fullCard(rt)} + <div class="confirm" role="dialog" aria-modal="true"> + {#if card != null} + <MonsterAbilityCard + card={card} + stat={null} + {fh} + scale={0.8} + applyAll + /> + {/if} + <div class="confirm__btns"> + <button + class="pill pill--text" + onclick={() => { + cmd('removeCard', { deck: rt.deck, nr: rt.nr }); + removeTarget = null; + }} + > + {t('removeCardQuestion')} + </button> + </div> + </div> + {/if} +</Menu> + +<style> + .bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + margin-bottom: 10px; + } + .bar__label { + font-size: 13px; + font-weight: 600; + white-space: pre; + } + .pill { + min-width: 32px; + padding: 4px 8px; + font-size: 13px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.12); + color: inherit; + cursor: pointer; + white-space: pre; + } + .pill:hover { + background: rgba(255, 255, 255, 0.25); + } + .pill--text { + min-width: 0; + } + .columns { + display: flex; + gap: 12px; + align-items: flex-start; + } + .col { + flex: 1; + display: flex; + flex-direction: column; + gap: 6px; + max-height: 60vh; + overflow-y: auto; + } + .cardwrap { + cursor: pointer; + border-radius: 6px; + } + .cardwrap:focus-visible { + outline: 2px solid #7ec8ff; + } + .confirm { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + margin-top: 10px; + padding: 10px; + border-radius: 8px; + background: rgba(0, 0, 0, 0.35); + } + .confirm__btns { + display: flex; + gap: 8px; + } + .spectate { + font-size: 13px; + opacity: 0.7; + } +</style> 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 @@ +<!-- + The bottom deck area (the reference `main_scaffold` bottom row): the loot + deck on the left, and on the right the character AMD decks (behind the + "Character Decks" toggle, the reference `CharacterAmdsWidget` open-state + cycling), the ally deck (when `shouldShowAlliesDeck`), and the global + deck. Tapping a deck opens its menu; double-tapping zooms its top + discard card. +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + import type { + CharacterItem, + ModifierCard as Card + } from '$lib/protocol/types'; + import { isCharacter } from '$lib/protocol/types'; + import type { CampaignData, ClassData } from '$lib/data/gameData'; + import { t } from '$lib/i18n'; + import { + currentCharacterId, + modifierDeckByName, + shouldShowAlliesDeck + } from '$lib/game/rules'; + import LootDeckWidget from './LootDeckWidget.svelte'; + import ModifierDeckWidget from './ModifierDeckWidget.svelte'; + + type OpenState = 'noOpen' | 'oneOpen' | 'allOpen'; + + let { + session, + campaignData, + onOpenAmd, + onAmdZoom, + onOpenLoot + }: { + session: GameSession; + campaignData: CampaignData | null; + onOpenAmd: (name: string) => void; + onAmdZoom: (card: Card, name: string, perks: string[][] | null) => void; + onOpenLoot: () => void; + } = $props(); + + const gameState = session.state; + + // The class data for a character item (null until the campaign loads). + function classFor(char: CharacterItem): ClassData | null { + return ( + campaignData?.classes.find( + (c) => c.name === char.characterClass || c.id === char.characterClass + ) ?? null + ); + } + + // Characters whose class has perks (the reference `charsWithPerks`). + const charsWithPerks = $derived.by((): CharacterItem[] => { + const gs = $gameState; + if (!gs || campaignData == null) return []; + return gs.currentList + .filter((i): i is CharacterItem => isCharacter(i)) + .filter((c) => (classFor(c)?.perkDetails.length ?? 0) > 0); + }); + + const currentCharacter = $derived.by((): CharacterItem | null => { + const gs = $gameState; + if (!gs) return null; + const id = currentCharacterId(gs); + if (id == null) return null; + return ( + gs.currentList.find((i): i is CharacterItem => isCharacter(i) && i.id === id) ?? + null + ); + }); + + const canShowOneDeck = $derived( + ($gameState?.roundState ?? 0) === 1 && + currentCharacter != null && + charsWithPerks.some((c) => c.id === currentCharacter.id) + ); + + // The reference keeps the user intent per round state; the toggle cycles + // between them (chooseInitiative: noOpen <-> allOpen; playTurns: + // oneOpen <-> allOpen when the current character can show one deck). + let playTurnsIntent = $state<OpenState>('oneOpen'); + let chooseInitIntent = $state<OpenState>('allOpen'); + + const visible = $derived.by((): OpenState => { + const roundState = $gameState?.roundState ?? 0; + if (roundState !== 1) return chooseInitIntent; + if (playTurnsIntent === 'oneOpen' && canShowOneDeck) return 'oneOpen'; + return playTurnsIntent; + }); + + function toggle() { + const roundState = $gameState?.roundState ?? 0; + if (roundState !== 1) { + chooseInitIntent = chooseInitIntent === 'noOpen' ? 'allOpen' : 'noOpen'; + return; + } + if (canShowOneDeck) { + playTurnsIntent = + playTurnsIntent === 'oneOpen' + ? 'allOpen' + : playTurnsIntent === 'allOpen' + ? 'oneOpen' + : 'oneOpen'; + } else { + playTurnsIntent = + playTurnsIntent === 'noOpen' + ? 'allOpen' + : playTurnsIntent === 'allOpen' + ? 'oneOpen' + : 'allOpen'; + } + } + + function perksFor(char: CharacterItem): string[][] | null { + return classFor(char)?.perkDetails.map((p) => p.adds) ?? null; + } + + function onZoom(name: string, char: CharacterItem | null) { + const gs = $gameState; + if (!gs) return; + const deck = modifierDeckByName(gs, name); + if (!deck || deck.discardPile.length === 0) return; + const card = deck.discardPile[deck.discardPile.length - 1]; + onAmdZoom(card, name, char ? perksFor(char) : null); + } + + const showAmds = $derived(campaignData != null && charsWithPerks.length > 0); +</script> + +<div class="deckarea"> + <div class="deckarea__loot"> + {#if $gameState} + <LootDeckWidget {session} deck={$gameState.lootDeck} onOpenMenu={onOpenLoot} /> + {/if} + </div> + + <div class="deckarea__decks"> + {#if showAmds} + <button class="toggle" onclick={toggle}>{t('characterDecks')}</button> + {#if visible !== 'noOpen'} + {#if visible === 'oneOpen' && canShowOneDeck && currentCharacter} + <ModifierDeckWidget + {session} + deck={currentCharacter.characterState.modifierDeck} + name={currentCharacter.id} + className={currentCharacter.characterClass} + perks={perksFor(currentCharacter)} + onOpenMenu={() => onOpenAmd(currentCharacter.id)} + onZoom={() => onZoom(currentCharacter.id, currentCharacter)} + /> + {:else} + {#each charsWithPerks as char (char.id)} + <ModifierDeckWidget + {session} + deck={char.characterState.modifierDeck} + name={char.id} + className={char.characterClass} + perks={perksFor(char)} + onOpenMenu={() => onOpenAmd(char.id)} + onZoom={() => onZoom(char.id, char)} + /> + {/each} + {/if} + {/if} + {/if} + + {#if $gameState && shouldShowAlliesDeck($gameState)} + <ModifierDeckWidget + {session} + deck={$gameState.modifierDeckAllies} + name="allies" + className={null} + onOpenMenu={() => onOpenAmd('allies')} + onZoom={() => onZoom('allies', null)} + /> + {/if} + + {#if $gameState} + <ModifierDeckWidget + {session} + deck={$gameState.modifierDeck} + name="" + className={null} + onOpenMenu={() => onOpenAmd('')} + onZoom={() => onZoom('', null)} + /> + {/if} + </div> +</div> + +<style> + .deckarea { + display: flex; + justify-content: center; + align-items: center; + gap: 24px; + padding: 4px 8px; + } + .deckarea__loot { + display: flex; + align-items: center; + } + .deckarea__decks { + display: flex; + flex-direction: column; + gap: 4px; + align-items: flex-end; + } + .toggle { + padding: 2px 10px; + font-size: 12px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.15); + color: inherit; + cursor: pointer; + } + .toggle:hover { + background: rgba(255, 255, 255, 0.3); + } +</style> 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 @@ +<!-- + The loot-cards menu (the reference `LootCardsMenu`): the button bar — + Character loot, add/remove special cards 1418/1419, Enhance cards, + Add Card, Return to Top/Bottom — above the discard grid (tap a card → + Set Loot Owner). The other buttons open nested submenus (the + reference's CharacterLootMenu / AddLootCardMenu / + LootCardEnhancementMenu dialogs). +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + import type { LootCard as Card, LootPoolKey } from '$lib/protocol/types'; + import { isCharacter } from '$lib/protocol/types'; + import { t } from '$lib/i18n'; + import { + characterLootTotal, + poolCardGfx + } from '$lib/game/cards/lootCard'; + import LootCard from '../cards/LootCard.svelte'; + import LootEnhancementCounter from './LootEnhancementCounter.svelte'; + import Menu from '../Menu.svelte'; + + const CARD_1418 = 1418; + const CARD_1419 = 1419; + const GRID_COLUMNS = 4; + + // Enhancement sections, in the reference order: materials (8 cards: + // 2× "1", 3× "2 for 2", 3× "2 for 2-3"), herbs (2 cards), coin + // (12× "1", 6× "2", 2× "3" in rows of 3). + const MATERIAL_KEYS: LootPoolKey[] = ['hide', 'lumber', 'metal']; + // Per material: 2× value-1, 3× "2 for 2", 3× "2 for 2-3". + const MATERIAL_SPLIT = [2, 3, 3]; + const HERB_KEYS: LootPoolKey[] = [ + 'arrowvine', + 'axenut', + 'corpsecap', + 'flamefruit', + 'rockroot', + 'snowthistle' + ]; + // Coin pool: 12× "1", 6× "2", 2× "3", shown in rows of 3. + const COIN_SPLIT = [12, 6, 2]; + const COIN_ROW_SIZE = 3; + + // AddLootCardMenu names (in `addedCards` order). + const ADD_LOOT_NAMES = [ + 'hide', + 'lumber', + 'metal', + 'arrowvine', + 'axenut', + 'corpsecap', + 'flamefruit', + 'rockroot', + 'snowthistle' + ]; + + // CharacterLootMenu rows (coin first). + const LOOT_ROWS = [ + 'coin', + 'hide', + 'lumber', + 'metal', + 'arrowvine', + 'axenut', + 'corpsecap', + 'flamefruit', + 'rockroot', + 'snowthistle' + ]; + + let { + session, + deck, + open = $bindable(true) + }: { + session: GameSession; + deck: import('$lib/protocol/types').LootDeck; + open?: boolean; + } = $props(); + + const gameState = session.state; + const player = session.player; + + // The discard pile displays most-recently-drawn first (the reference + // reverses the pile list). + const discardDisplay = $derived([...deck.discardPile].reverse()); + + const characters = $derived( + ($gameState?.currentList ?? []).filter(isCharacter) + ); + + function cmd(command: string, args: Record<string, unknown> = {}) { + if ($player) session.command(command, args); + } + + function lootName(label: string): string { + return t(`lootName${label.charAt(0).toUpperCase()}${label.slice(1)}`); + } + + /** A character's display name by id ("" until found). */ + function characterDisplay(charId: string): string { + for (const c of $gameState?.currentList ?? []) { + if (isCharacter(c) && c.id === charId) return c.characterState.display; + } + return ''; + } + + // --- submenus (nested overlays, the reference's dialog stack) ------------ + + type Sub = + | { kind: 'owner'; card: Card } + | { kind: 'charLoot' } + | { kind: 'addLoot' } + | { kind: 'enhance' }; + + let sub = $state<Sub | null>(null); + + // One enhancement counter per pool card. + function counter(key: LootPoolKey, index: number) { + const pool = deck.pools[key] ?? []; + const id = pool[index] ?? -1; + return { + id, + gfx: poolCardGfx(key, index), + value: id >= 0 ? deck.enhancements[String(id)] ?? 0 : 0 + }; + } + + // The enhancement sections, in the reference order (the + // `LootCardEnhancementMenu` column): materials, herbs, coin. + type EnhSection = { key: LootPoolKey; label: string; rows: number[][] }; + const enhSections = $derived.by<EnhSection[]>(() => { + const sections: EnhSection[] = []; + MATERIAL_KEYS.forEach((key) => { + let start = 0; + [ + '1', + t('lootAmount2For2'), + t('lootAmount2For23') + ].forEach((label, i) => { + const count = MATERIAL_SPLIT[i]; + sections.push({ + key, + label: `${lootName(key)} ${label}`, + rows: rowsFor(start, count, count) + }); + start += count; + }); + }); + HERB_KEYS.forEach((key) => { + sections.push({ + key, + label: lootName(key), + rows: rowsFor(0, 2, 2) + }); + }); + let coinStart = 0; + ['1', '2', '3'].forEach((label, i) => { + const count = COIN_SPLIT[i]; + sections.push({ + key: 'coin', + label: `${lootName('coin')} ${label}`, + rows: rowsFor(coinStart, count, COIN_ROW_SIZE) + }); + coinStart += count; + }); + return sections; + }); + + // `count` cards, `rowSize` per row, starting at pool [start]. + function rowsFor(start: number, count: number, rowSize: number): number[][] { + const rows: number[][] = []; + for (let s = start; s < start + count; s += rowSize) { + rows.push(Array.from({ length: Math.min(rowSize, start + count - s) }, (_, j) => s + j)); + } + return rows; + } + + // Character loot totals per row (the reference `_getLootAmount`). + function charLootRows(charId: string) { + const characterCount = characters.length; + return LOOT_ROWS.map((name) => ({ + name, + amount: characterLootTotal( + deck.discardPile, + charId, + name, + characterCount + ) + })); + } +</script> + +<Menu {open} title="Loot Cards"> + {#if $gameState} + <div class="bar"> + <button class="pill pill--text" onclick={() => (sub = { kind: 'charLoot' })}> + {t('characterLoot')} + </button> + <button + class="pill pill--text" + disabled={!player} + onclick={() => + cmd(deck['1418'] ? 'removeSpecialLootCard' : 'addSpecialLootCard', { + nr: CARD_1418 + })} + > + {deck['1418'] + ? t('removeSpecialCard', { nr: CARD_1418 }) + : t('addSpecialCard', { nr: CARD_1418 })} + </button> + <button + class="pill pill--text" + disabled={!player} + onclick={() => + cmd(deck['1419'] ? 'removeSpecialLootCard' : 'addSpecialLootCard', { + nr: CARD_1419 + })} + > + {deck['1419'] + ? t('removeSpecialCard', { nr: CARD_1419 }) + : t('addSpecialCard', { nr: CARD_1419 })} + </button> + <button class="pill pill--text" onclick={() => (sub = { kind: 'enhance' })}> + {t('enhanceCards')} + </button> + <button class="pill pill--text" onclick={() => (sub = { kind: 'addLoot' })}> + {t('addLootCard')} + </button> + {#if deck.discardPile.length > 0} + <button class="pill pill--text" disabled={!player} onclick={() => cmd('returnLootCard', { top: true })}> + {t('returnToTop')} + </button> + <button class="pill pill--text" disabled={!player} onclick={() => cmd('returnLootCard', { top: false })}> + {t('returnToBottom')} + </button> + {/if} + </div> + + <div class="grid" style="grid-template-columns: repeat({GRID_COLUMNS}, 1fr)"> + {#each discardDisplay as card} + <button + class="grid__cell" + onclick={() => (sub = { kind: 'owner', card })} + role="button" + tabindex="0" + aria-label="loot card {card.id}" + > + <LootCard + {card} + revealed + ownerName={characterDisplay(card.owner)} + characterCount={characters.length} + scale={0.6} + /> + </button> + {/each} + </div> + {/if} + + <!-- set loot owner --> + {#if sub && sub.kind === 'owner'} + {@const s = sub} + <div class="sub" role="dialog" aria-modal="true"> + <div class="sub__title">{t('setLootOwner')}</div> + {#each characters as char} + <button + class="ownerrow" + disabled={!player} + onclick={() => { + cmd('setLootOwner', { ownerId: char.id, cardId: s.card.id }); + sub = null; + }} + > + <img src="/images/class-icons/{char.id}.png" alt={char.id} /> + <span>{char.characterState.display}</span> + </button> + {/each} + </div> + {/if} + + <!-- character loot totals --> + {#if sub?.kind === 'charLoot'} + <div class="sub sub--scroll"> + {#each characters as char} + <div class="divider"></div> + <div class="charrow"> + <img src="/images/class-icons/{char.id}.png" alt={char.id} /> + <span>{t('characterLootTitle', { name: char.characterState.display })}</span> + </div> + {#each charLootRows(char.id) as row} + {#if row.amount > 0} + <div class="lootrow"> + <img src="/images/loot/{row.name}_icon.png" alt={row.name} /> + <span>{lootName(row.name)}</span> + <span class="lootrow__amount">{row.amount}</span> + </div> + {/if} + {/each} + {/each} + </div> + {/if} + + <!-- add an extra loot card --> + {#if sub?.kind === 'addLoot'} + <div class="sub sub--scroll"> + <div class="sub__title">{t('addExtraLootCard')}</div> + {#each ADD_LOOT_NAMES as name, i} + <button + class="lootrow" + disabled={!player} + onclick={() => cmd('addLootCard', { resourceType: name })} + > + <img src="/images/loot/{name}_icon.png" alt={name} /> + <span>{lootName(name)}</span> + <span class="lootrow__amount"> + {t('addedCount', { count: deck.addedCards[i] ?? 0 })} + </span> + </button> + {/each} + </div> + {/if} + + <!-- enhancements --> + {#if sub?.kind === 'enhance'} + <div class="sub sub--scroll"> + <div class="sub__title">{t('lootCardEnhancements')}</div> + {#each enhSections as section} + <div class="secheader"> + <img src="/images/loot/{section.key}_icon.png" alt={section.key} /> + <span>{section.label}</span> + </div> + {#each section.rows as row} + <div class="coinrow"> + {#each row as idx} + {@const c = counter(section.key, idx)} + <LootEnhancementCounter {session} {...c} /> + {/each} + </div> + {/each} + <div class="divider"></div> + {/each} + </div> + {/if} +</Menu> + +<style> + .bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + margin-bottom: 10px; + } + .pill { + padding: 4px 8px; + font-size: 13px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.12); + color: inherit; + cursor: pointer; + white-space: pre; + } + .pill:hover { + background: rgba(255, 255, 255, 0.25); + } + .pill:disabled { + opacity: 0.35; + cursor: default; + } + .pill--text { + min-width: 0; + } + .grid { + display: grid; + gap: 2px; + max-height: 55vh; + overflow-y: auto; + } + .grid__cell { + padding: 0; + background: none; + border: none; + cursor: pointer; + aspect-ratio: 0.72; + } + .grid__cell:focus-visible { + outline: 2px solid #7ec8ff; + } + .sub { + display: flex; + flex-direction: column; + gap: 6px; + margin-top: 10px; + padding: 10px; + border-radius: 8px; + background: rgba(0, 0, 0, 0.35); + } + .sub--scroll { + max-height: 60vh; + overflow-y: auto; + } + .sub__title { + font-size: 14px; + font-weight: 600; + } + .ownerrow { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 8px; + font-size: 14px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.12); + color: inherit; + cursor: pointer; + } + .ownerrow:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.25); + } + .ownerrow:disabled { + opacity: 0.35; + cursor: default; + } + .ownerrow img { + width: 24px; + height: 24px; + object-fit: contain; + } + .charrow { + display: flex; + align-items: flex-end; + justify-content: center; + gap: 10px; + font-size: 14px; + font-weight: 600; + } + .charrow img { + width: 24px; + height: 24px; + object-fit: contain; + } + .lootrow { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 8px; + font-size: 13px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.08); + color: inherit; + } + .lootrow:not(:disabled) { + cursor: pointer; + } + .lootrow:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.2); + } + .lootrow img { + width: 24px; + height: 24px; + object-fit: contain; + } + .lootrow__amount { + margin-left: auto; + font-weight: 700; + } + .divider { + height: 1px; + background: rgba(255, 255, 255, 0.2); + } + .secheader { + display: flex; + align-items: center; + gap: 6px; + font-size: 13px; + font-weight: 600; + } + .secheader img { + width: 24px; + height: 24px; + object-fit: contain; + } + .coinrow { + display: flex; + justify-content: space-evenly; + gap: 4px; + } +</style> 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 @@ +<!-- + The loot deck (the reference `LootDeckWidget`): the draw pile (tap to + draw, current-character class icon above it) beside the discard box + (tap to open the loot cards menu). Hidden while both piles are empty + (the reference `shouldHide`). +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + import type { LootDeck as Deck } from '$lib/protocol/types'; + import { currentCharacterId } from '$lib/game/rules'; + import LootCard from '../cards/LootCard.svelte'; + + const CARD_W = 40; + const CARD_ROT = 15; + + let { + session, + deck, + onOpenMenu + }: { + session: GameSession; + deck: Deck; + onOpenMenu: () => void; + } = $props(); + + const gameState = session.state; + const player = session.player; + + // Hidden while the deck is empty (the reference `shouldHide`). + const hidden = $derived(deck.drawPile.length === 0 && deck.discardPile.length === 0); + + const currentCharacterName = $derived( + $gameState ? currentCharacterId($gameState) : null + ); + + // The top three discard cards, bottom-most first (for the stack offsets). + const discardStack = $derived( + deck.discardPile.slice(-3).map((card, i, arr) => ({ + card, + depth: arr.length - 1 - i + })) + ); + + function draw() { + if ($player && deck.drawPile.length > 0) { + session.command('drawLootCard', {}); + } + } +</script> + +{#if !hidden} + <div class="deck"> + <div + class="drawpile" + role="button" + tabindex="0" + aria-label="draw pile" + onclick={draw} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') draw(); + }} + > + {#if deck.drawPile.length > 0} + <LootCard card={deck.drawPile[deck.drawPile.length - 1]} revealed={false} /> + {:else} + <div class="empty"></div> + {/if} + <span class="count">{deck.drawPile.length}</span> + {#if currentCharacterName != null && deck.drawPile.length > 0} + <img + class="icon" + src="/images/class-icons/{currentCharacterName}.png" + alt={currentCharacterName} + /> + {/if} + </div> + + <div + class="discard" + role="button" + tabindex="0" + aria-label="discard pile" + onclick={onOpenMenu} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenMenu(); + }} + > + {#each discardStack as entry} + <div + class="discard__card" + style="left: {4 + entry.depth * 13}px; transform: rotate({entry.depth === 0 ? 0 : CARD_ROT}deg)" + > + <LootCard card={entry.card} revealed /> + </div> + {/each} + </div> + </div> +{/if} + +<style> + .deck { + display: flex; + align-items: center; + gap: 4px; + width: 94px; + height: 39px; + } + .drawpile { + position: relative; + width: 40px; + height: 39px; + cursor: pointer; + } + .drawpile:focus-visible { + outline: 2px solid #7ec8ff; + border-radius: 4px; + } + .empty { + width: 40px; + height: 39px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.48); + } + .count { + position: absolute; + right: 3px; + bottom: 0; + font-size: 13px; + font-weight: 700; + color: #fff; + text-shadow: 1px 1px 1px #000; + pointer-events: none; + } + .icon { + position: absolute; + top: 12px; + left: 4px; + width: 35px; + height: 35px; + object-fit: contain; + filter: brightness(0) invert(1) drop-shadow(2px 2px 1.5px rgba(0, 0, 0, 0.54)); + pointer-events: none; + } + .discard { + position: relative; + width: 39px; + height: 57.6666px; + border-radius: 5px; + border: 1px solid rgba(255, 255, 255, 0.7); + background: rgba(0, 0, 0, 0.48); + cursor: pointer; + overflow: visible; + } + .discard:focus-visible { + outline: 2px solid #7ec8ff; + } + .discard__card { + position: absolute; + top: 0; + left: 4px; + transition: left 0.2s ease, transform 0.2s ease; + } +</style> 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 @@ +<!-- + One loot-card enhancement counter (the reference + `EnhancementCounterButton`): [−] <value> [+], the minus only enabled + while the card is enhanced. `value` is the card's `enhanced` amount. +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + + let { + session, + id, + gfx, + value + }: { + session: GameSession; + id: number; + /** The card's `gfx` (the wire `resourceType`). */ + gfx: string; + value: number; + } = $props(); + + const player = session.player; + + function cmd(delta: number) { + if ($player) { + session.command('enhanceLootCard', { + id, + value: value + delta, + resourceType: gfx + }); + } + } +</script> + +<div class="counters"> + <button class="cbtn" disabled={!player || value <= 0} onclick={() => cmd(-1)}>−</button> + <span class="cval">{value}</span> + <button class="cbtn" disabled={!player} onclick={() => cmd(1)}>+</button> +</div> + +<style> + .counters { + display: flex; + align-items: center; + justify-content: center; + gap: 6px; + padding: 3px; + } + .cbtn { + width: 24px; + height: 24px; + font-size: 16px; + line-height: 1; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.15); + color: inherit; + cursor: pointer; + } + .cbtn:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.3); + } + .cbtn:disabled { + opacity: 0.35; + cursor: default; + } + .cval { + min-width: 24px; + padding: 2px 6px; + text-align: center; + font-size: 13px; + font-weight: 700; + border-radius: 2px; + background: #fff; + color: #000; + } +</style> 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 @@ +<!-- + The modifier-card zoom (the reference `ModifierCardZoom`): the top card + at ~3x scale (shrunk to fit the screen width), tap (or Escape) to close. +--> +<script lang="ts"> + import type { ModifierCard as Card } from '$lib/protocol/types'; + import ModifierCard from '../cards/ModifierCard.svelte'; + + const DEFAULT_ZOOM = 3.0; + const CARD_WIDTH = 58.6666; + + let { + card, + name, + perks = null, + open = $bindable(true) + }: { + card: Card; + /** The deck name ("" party, "allies", or a character id). */ + name: string; + perks?: string[][] | null; + open?: boolean; + } = $props(); + + // Fit the card into the viewport (the reference shrinks the zoom to fit). + function scaleFor(): number { + if (typeof window === 'undefined') return DEFAULT_ZOOM; + return Math.min(DEFAULT_ZOOM, window.innerWidth / (CARD_WIDTH + 80)); + } + const scale = $state(scaleFor()); +</script> + +{#if open} + <div + class="zoom" + role="dialog" + aria-modal="true" + onclick={() => (open = false)} + onkeydown={(e) => e.key === 'Escape' && (open = false)} + > + <ModifierCard {card} {name} revealed {perks} {scale} /> + </div> +{/if} + +<style> + .zoom { + position: fixed; + inset: 0; + z-index: 40; + display: flex; + align-items: center; + justify-content: center; + background: rgba(0, 0, 0, 0.75); + cursor: pointer; + } +</style> 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 @@ +<!-- + The modifier-deck menu header (the reference `ModifierDeckHeader`): the + wrap of deck commands — Bad Omen, Corrosive Spew, ±1/-2/+0 removal, + Imbue/Advanced Imbue, Hail/Cassandra perk toggles, Cassandra save, + removed-card count, Crimson Scales sanctuary/party card, faction + menus, the bless/curse/empower/enfeeble counters, and the reveal + buttons (0..n / All). +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + import type { GameState, ModifierDeck as Deck } from '$lib/protocol/types'; + import type { ClassData } from '$lib/data/gameData'; + import { t } from '$lib/i18n'; + import { + deckHasMinus1, + deckHasPlus0, + deckMinus2Present, + drawPileTopFirst, + removableTotal + } from '$lib/game/modifierDeck'; + import { hasCharacterClass, isCSCampaign } from '$lib/game/rules'; + import CounterButton from '../CounterButton.svelte'; + + const MAX_BLESS_CURSE = 10; + const MAX_RUINMAW_EMPOWER = 12; + const MAX_VIMTHREADER_GR_EMPOWER = 5; + const MAX_LIFESPEAKER_ENFEEBLE = 15; + const MAX_REVEAL_BUTTONS = 6; + const MAX_REVEAL_BUTTONS_CASSANDRA = 8; + const HAIL_PERK_INDEX = 17; + const CASSANDRA_PERK_INDEX = 15; + const PARTY_BUTTON_COUNT = 4; + + let { + session, + state, + deck, + name, + characterClassData = null, + onOpenRemoved, + onOpenPerks, + onOpenFaction + }: { + session: GameSession; + state: GameState; + deck: Deck; + /** "" party deck, "allies", or a character id. */ + name: string; + /** The owning character's class data (character decks only). */ + characterClassData?: ClassData | null; + onOpenRemoved: () => void; + onOpenPerks: () => void; + onOpenFaction: (faction: string) => void; + } = $props(); + + const player = session.player; + + const isCharacter = $derived(name !== '' && name !== 'allies'); + const monsterDeck = $derived(name === ''); + + const hasDiviner = $derived(hasCharacterClass(state, 'Diviner')); + const hasIncarnate = $derived(hasCharacterClass(state, 'Incarnate')); + const hasVimthreader = $derived(hasCharacterClass(state, 'Vimthreader')); + const hasLifespeaker = $derived(hasCharacterClass(state, 'Lifespeaker')); + const hasCassandra = $derived(hasCharacterClass(state, 'Cassandra')); + + const hail = $derived( + state.currentList.find( + (i) => 'characterClass' in i && i.characterClass === 'Hail' + ) + ); + const hasHailPerk = $derived( + hail != null && 'characterState' in hail + ? (hail.characterState.perkList[HAIL_PERK_INDEX] ?? false) + : false + ); + const cassandra = $derived( + state.currentList.find( + (i) => 'characterClass' in i && i.characterClass === 'Cassandra' + ) + ); + const hasCassandraPerk = $derived( + cassandra != null && 'characterState' in cassandra + ? (cassandra.characterState.perkList[CASSANDRA_PERK_INDEX] ?? false) + : false + ); + + const nrOfEnfeebles = $derived( + (hasVimthreader ? 1 : 0) + (hasLifespeaker ? 1 : 0) + (hasIncarnate ? 1 : 0) + ); + const nrOfEmpowers = $derived( + (hasVimthreader ? 1 : 0) + (hasIncarnate ? 1 : 0) + ); + const moreThanOneEnfeeble = $derived(monsterDeck && nrOfEnfeebles > 1); + const moreThanOneEmpower = $derived( + ((isCharacter || name === 'allies') && nrOfEmpowers > 1) || + (isCharacter && name === 'Ruinmaw' && nrOfEmpowers > 0) + ); + + const drawPile = $derived(drawPileTopFirst(deck)); + // 8 reveal buttons when the party has a Cassandra (the reference + // `vm.hasCassandra` — her revealed-card special needs the extra). + const maxRevealButtons = $derived( + hasCassandra + ? MAX_REVEAL_BUTTONS_CASSANDRA + : MAX_REVEAL_BUTTONS + ); + // Reveal button count: 0..min(drawPile, max) + the All button. + const revealCount = $derived( + Math.min(drawPile.length + 1, maxRevealButtons + 1) + ); + + const hasPlus0Card = $derived(deckHasPlus0(deck)); + + const factionUnlocked = $derived( + (['Demons', 'Merchant-Guild', 'Military'] as const).filter( + (f) => state.unlockedClasses.includes(f) + ) + ); + + function cmd(name: string, args: Record<string, unknown> = {}) { + if (player) session.command(name, args); + } + + /** The deck counter's ownerId (party deck → "" resolves to the party). */ + const ownerId = $derived(name === '' ? '' : name); + + function changeBless(delta: number) { + cmd('changeBless', { change: delta, figureId: '', ownerId }); + } + function changeCurse(delta: number) { + cmd('changeCurse', { change: delta, figureId: '', ownerId }); + } + function changeEmpower(gfx: string, delta: number) { + cmd('changeEmpower', { change: delta, gfx, figureId: '', ownerId }); + } + function changeEnfeeble(gfx: string, delta: number) { + cmd('changeEnfeeble', { change: delta, gfx, figureId: '', ownerId }); + } +</script> + +<div class="hdr"> + {#if hasDiviner && !isCharacter} + {#if deck.badOmen === 0} + <button class="btn" disabled={!player} onclick={() => cmd('badOmen', { allies: name === 'allies' })}> + {t('badOmen')} + </button> + {:else} + <span class="label">{t('badOmensLeft', { count: deck.badOmen })}</span> + {/if} + {/if} + + {#if name === 'Ruinmaw' && !deck.corrosiveSpew} + <button class="btn" disabled={!player} onclick={() => cmd('corrosiveSpew')}> + {t('corrosiveSpew')} + </button> + {/if} + {#if deck.corrosiveSpew} + <span class="label">{t('empowersOnTop')}</span> + {/if} + + <button + class="btn" + disabled={!player} + onclick={() => cmd('amdAddMinusOne', { name })} + > + {deck.addedMinusOnes < 0 + ? t('addMinusOneCardRemoved', { count: Math.abs(deck.addedMinusOnes) }) + : t('addMinusOneCardAdded', { count: Math.abs(deck.addedMinusOnes) })} + </button> + + <button + class="btn" + disabled={!player || !deckHasMinus1(deck)} + onclick={() => cmd('amdRemoveMinus1', { name })} + > + {t('removeMinusOneCard')} + </button> + + {#if !isCharacter} + <button class="btn" disabled={!player} onclick={() => cmd('amdRemoveMinus2', { allies: name === 'allies' })}> + {deckMinus2Present(deck) + ? t('removeMinusTwoCard') + : t('minusTwoCardRemoved')} + </button> + {/if} + + {#if isCharacter && hasPlus0Card} + <button + class="btn" + disabled={!player} + onclick={() => cmd('amdRemovePlus0', { name, remove: hasPlus0Card })} + > + {hasPlus0Card ? t('removePlusZeroCard') : t('plusZeroCardRemoved')} + </button> + {/if} + + {#if monsterDeck} + <button + class="btn" + disabled={!player} + onclick={() => + cmd(deck.imbuement > 0 ? 'amdRemoveImbue' : 'amdImbue1')} + > + {deck.imbuement > 0 ? t('removeImbue') : t('imbue')} + </button> + {#if deck.imbuement !== 2} + <button class="btn" disabled={!player} onclick={() => cmd('amdImbue2')}> + {t('advancedImbue')} + </button> + {/if} + {/if} + + {#if name === '' && hail != null} + <button + class="btn" + disabled={!player} + onclick={() => cmd('addPerk', { characterId: 'Hail', index: HAIL_PERK_INDEX })} + > + {hasHailPerk ? t('removeHailPerk') : t('addHailPerk')} + </button> + {/if} + + {#if hasCassandraPerk} + <button + class="btn" + disabled={!player} + onclick={() => + cmd('amdCassandraSpecial', { deckId: name, on: !deck.cassandra })} + > + {deck.cassandra + ? t('dontSaveRevealedCards') + : t('saveRevealedCards')} + </button> + {/if} + + {#if deck.removedPile.length > 0} + <button class="btn" disabled={!player} onclick={onOpenRemoved}> + {t('removedCountLabel', { count: deck.removedPile.length })} + </button> + {/if} + + {#if isCSCampaign(state.currentCampaign) && isCharacter} + {#if deck.drawPile.some((c) => c.gfx.startsWith('sanctuary')) || deck.discardPile.some((c) => c.gfx.startsWith('sanctuary'))} + <button + class="btn" + disabled={!player} + onclick={() => + cmd('removeCSSanctuaryDonation', { characterId: name })} + > + {t('removeDonation')} + </button> + {:else} + <button + class="btn" + disabled={!player} + onclick={() => cmd('donateCSSanctuary', { characterId: name })} + > + {t('donateSanctuary')} + </button> + {/if} + + {#if deck.drawPile.some((c) => c.gfx.startsWith('party')) || deck.discardPile.some((c) => c.gfx.startsWith('party'))} + <button + class="btn" + disabled={!player} + onclick={() => cmd('removeCSPartyCard', { characterId: name })} + > + {t('removePartyCard')} + </button> + {:else} + <span class="label">{t('addPartyCard')}</span> + {#each Array(PARTY_BUTTON_COUNT) as _, i} + <button + class="btn btn--num" + disabled={!player} + onclick={() => + cmd('addCSPartyCard', { characterId: name, type: 1 })} + > + {i + 1} + </button> + {/each} + {/if} + {/if} + + {#if isCharacter} + {#each factionUnlocked as faction} + <button + class="btn btn--icon" + disabled={!player} + aria-label={faction} + onclick={() => onOpenFaction(faction)} + > + <img + src={ + faction === 'Demons' + ? '/images/demons.png' + : faction === 'Merchant-Guild' + ? '/images/merchant-guild.png' + : '/images/military.png' + } + alt={faction} + /> + </button> + {/each} + {/if} + + <CounterButton + image="/images/abilities/bless.png" + total={removableTotal(deck, 'bless')} + maxValue={MAX_BLESS_CURSE} + onDecrement={() => changeBless(-1)} + onIncrement={() => changeBless(1)} + /> + <CounterButton + image="/images/abilities/curse.png" + total={removableTotal(deck, 'curse')} + maxValue={MAX_BLESS_CURSE} + onDecrement={() => changeCurse(-1)} + onIncrement={() => changeCurse(1)} + /> + + {#if hasIncarnate && !isCharacter} + <CounterButton + image="/images/abilities/enfeeble_old.png" + total={removableTotal(deck, 'in-enfeeble')} + maxValue={MAX_BLESS_CURSE} + extraImage={moreThanOneEnfeeble ? '/images/class-icons/Incarnate.png' : null} + onDecrement={() => changeEnfeeble('in-enfeeble', -1)} + onIncrement={() => changeEnfeeble('in-enfeeble', 1)} + /> + {/if} + {#if (isCharacter || name === 'allies') && hasIncarnate} + <CounterButton + image="/images/abilities/empower_old.png" + total={removableTotal(deck, 'in-empower')} + maxValue={MAX_BLESS_CURSE} + extraImage={moreThanOneEmpower ? '/images/class-icons/Incarnate.png' : null} + onDecrement={() => changeEmpower('in-empower', -1)} + onIncrement={() => changeEmpower('in-empower', 1)} + /> + {/if} + {#if name === 'Ruinmaw'} + <CounterButton + image="/images/abilities/empower_old.png" + total={removableTotal(deck, 'rm-empower')} + maxValue={MAX_RUINMAW_EMPOWER} + extraImage={moreThanOneEmpower ? '/images/class-icons/Ruinmaw.png' : null} + onDecrement={() => changeEmpower('rm-empower', -1)} + onIncrement={() => changeEmpower('rm-empower', 1)} + /> + {/if} + {#if (isCharacter || name === 'allies') && hasVimthreader} + <CounterButton + image="/images/abilities/empower.png" + total={removableTotal(deck, 'vi-empower')} + maxValue={MAX_BLESS_CURSE} + extraImage={moreThanOneEmpower ? '/images/class-icons/Vimthreader.png' : null} + onDecrement={() => changeEmpower('vi-empower', -1)} + onIncrement={() => changeEmpower('vi-empower', 1)} + /> + <CounterButton + image="/images/abilities/greater-empower.png" + total={removableTotal(deck, 'vi-gr-empower')} + maxValue={MAX_VIMTHREADER_GR_EMPOWER} + onDecrement={() => changeEmpower('vi-gr-empower', -1)} + onIncrement={() => changeEmpower('vi-gr-empower', 1)} + /> + {/if} + {#if !isCharacter && hasVimthreader} + <CounterButton + image="/images/abilities/enfeeble.png" + total={removableTotal(deck, 'vi-enfeeble')} + maxValue={MAX_BLESS_CURSE} + extraImage={moreThanOneEnfeeble ? '/images/class-icons/Vimthreader.png' : null} + onDecrement={() => changeEnfeeble('vi-enfeeble', -1)} + onIncrement={() => changeEnfeeble('vi-enfeeble', 1)} + /> + <CounterButton + image="/images/abilities/greater-enfeeble.png" + total={removableTotal(deck, 'vi-gr-enfeeble')} + maxValue={MAX_BLESS_CURSE} + onDecrement={() => changeEnfeeble('vi-gr-enfeeble', -1)} + onIncrement={() => changeEnfeeble('vi-gr-enfeeble', 1)} + /> + {/if} + {#if (!isCharacter || name === 'Lifespeaker') && hasLifespeaker} + <CounterButton + image="/images/abilities/enfeeble.png" + total={removableTotal(deck, 'li-enfeeble')} + maxValue={MAX_LIFESPEAKER_ENFEEBLE} + extraImage={moreThanOneEnfeeble ? '/images/class-icons/Lifespeaker.png' : null} + onDecrement={() => changeEnfeeble('li-enfeeble', -1)} + onIncrement={() => changeEnfeeble('li-enfeeble', 1)} + /> + {/if} + + {#if isCharacter && characterClassData && characterClassData.perkDetails.length > 0} + <button class="btn" disabled={!player} onclick={onOpenPerks}> + {t('perks')} + </button> + {/if} + + <span class="label">{t('revealCards')}</span> + {#each Array(revealCount) as _, i} + <button + class="btn btn--num" + disabled={!player} + onclick={() => cmd('amdReveal', { amount: i, name })} + > + {i >= drawPile.length ? t('revealAll') : i} + </button> + {/each} +</div> + +<style> + .hdr { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + margin-bottom: 10px; + } + .btn { + padding: 4px 8px; + font-size: 12px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.12); + color: inherit; + cursor: pointer; + white-space: pre; + } + .btn:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.25); + } + .btn:disabled { + opacity: 0.35; + cursor: default; + } + .btn--num { + min-width: 30px; + padding: 4px 6px; + } + .btn--icon { + width: 34px; + height: 34px; + padding: 3px; + } + .btn--icon img { + width: 100%; + height: 100%; + object-fit: contain; + } + .label { + font-size: 12px; + opacity: 0.85; + white-space: pre; + } +</style> 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 @@ +<!-- + The modifier-deck menu (the reference `ModifierDeckMenu`): the header + command bar above two card columns — the draw pile (top-first, + drag-reorderable, tap → "send to bottom / shuffle / remove") and the + discard pile (face up, tap → "remove / return top card"). The header's + "Removed", faction, and Perks buttons open nested submenus (the + reference's RemovedModifierCardMenu / GH2eFactionAMDCardMenu / + PerksMenu dialogs). +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + import type { ModifierDeck as Deck } from '$lib/protocol/types'; + import { isCharacter } from '$lib/protocol/types'; + import type { ClassData } from '$lib/data/gameData'; + import { t } from '$lib/i18n'; + import { + drawPileTopFirst, + factionCards, + factionCardInAnyCharacterDeck + } from '$lib/game/modifierDeck'; + import { + activePerks, + canAddPerk, + canRemovePerk, + perkDescription + } from '$lib/game/perks'; + import ModifierCard from '../cards/ModifierCard.svelte'; + import ModifierDeckHeader from './ModifierDeckHeader.svelte'; + import Menu from '../Menu.svelte'; + + const LIST_CARD_SCALE = 0.8; + // Submenu card preview (the reference zooms at 6x, clamped to width). + const PREVIEW_SCALE = 3.0; + + let { + session, + deck, + name, + characterClassData = null, + open = $bindable(true) + }: { + session: GameSession; + deck: Deck; + /** "" party deck, "allies", or a character id. */ + name: string; + /** The owning character's class data (character decks only). */ + characterClassData?: ClassData | null; + open?: boolean; + } = $props(); + + const gameState = session.state; + const player = session.player; + + const isCharacterDeck = $derived(name !== '' && name !== 'allies'); + + const drawTopFirst = $derived(drawPileTopFirst(deck)); + // The discard pile displays most-recently-drawn first (the reference + // reverses the pile list); taps map back to pile indices. + const discardDisplay = $derived([...deck.discardPile].reverse()); + const removedDisplay = $derived([...deck.removedPile].reverse()); + + // The top `deck.revealed` draw cards are face up (Cassandra's special). + function isDrawRevealed(pileIndex: number): boolean { + const topFirst = drawPileTopFirst(deck); + return topFirst.length - 1 - pileIndex < deck.revealed; + } + + function cmd(command: string, args: Record<string, unknown> = {}) { + if ($player) session.command(command, args); + } + + // --- draw-pile reordering (HTML5 drag & drop) ---------------------------- + + let dragIndex = $state<number | null>(null); + let dropIndex = $state<number | null>(null); + + function onDragStart(i: number) { + dragIndex = i; + } + function onDragOver(e: DragEvent, i: number) { + e.preventDefault(); + dropIndex = i; + } + function onDrop() { + if (dragIndex != null && dropIndex != null && dragIndex !== dropIndex) { + // The list is top-first; the wire pile is bottom-first. + const n = deck.drawPile.length; + cmd('reorderModifierList', { + newIndex: n - 1 - dropIndex, + oldIndex: n - 1 - dragIndex, + name + }); + } + dragIndex = null; + dropIndex = null; + } + + // --- submenus (nested overlays, the reference's dialog stack) ------------ + + type Sub = + | { kind: 'sendToBottom'; displayIndex: number } + | { kind: 'removeAmd'; pileIndex: number } + | { kind: 'removed' } + | { kind: 'returnAmd'; pileIndex: number } + | { kind: 'faction'; faction: string } + | { kind: 'perks' }; + + let sub = $state<Sub | null>(null); + + // Close a stale discard-pile submenu when the pile shrinks (the reference + // pops when `index >= discardPileSize`). + $effect(() => { + if ( + sub?.kind === 'removeAmd' && + sub.pileIndex >= deck.discardPile.length + ) { + sub = null; + } + }); + + // The character (for the perks submenu). + const character = $derived( + ($gameState?.currentList ?? []).find( + (i): i is import('$lib/protocol/types').CharacterItem => + isCharacter(i) && i.id === name + ) ?? null + ); + + // The faction-cards submenu state (which card this deck has added). + const factionGfxs = $derived( + sub?.kind === 'faction' ? factionCards(sub.faction) : [] + ); + const factionAdded = $derived( + sub?.kind === 'faction' + ? factionGfxs.find((g) => + deck.drawPile.some((c) => c.gfx === g) || + deck.discardPile.some((c) => c.gfx === g) + ) ?? null + : null + ); + + /** Every character's personal deck (the faction gray-out check). */ + const characterDecks = $derived( + ($gameState?.currentList ?? []).filter(isCharacter).map((c) => ({ + name: c.id, + deck: c.characterState.modifierDeck + })) + ); + + function factionGrayed(gfx: string): boolean { + return factionCardInAnyCharacterDeck(characterDecks, gfx); + } + + // Perks submenu state. + const perks = $derived( + isCharacterDeck && character && characterClassData + ? activePerks(characterClassData, character.characterState) + : [] + ); +</script> + +<Menu {open} title={name === '' ? 'Global' : name}> + {#if $gameState} + <ModifierDeckHeader + {session} + state={$gameState} + {deck} + {name} + {characterClassData} + onOpenRemoved={() => (sub = { kind: 'removed' })} + onOpenPerks={() => (sub = { kind: 'perks' })} + onOpenFaction={(faction) => (sub = { kind: 'faction', faction })} + /> + + <div class="columns"> + <div class="col" ondragend={() => (dragIndex = null)} ondrop={onDrop}> + {#each drawTopFirst as card, i} + {@const pileIndex = deck.drawPile.length - 1 - i} + <div + class="cardwrap" + draggable + ondragstart={() => 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 }; + }} + > + <ModifierCard + {card} + {name} + revealed={isDrawRevealed(pileIndex)} + scale={LIST_CARD_SCALE} + /> + </div> + {/each} + </div> + + <div class="col"> + {#each discardDisplay as card, i} + {@const pileIndex = deck.discardPile.length - 1 - i} + <div + class="cardwrap" + onclick={() => (sub = { kind: 'removeAmd', pileIndex })} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + sub = { kind: 'removeAmd', pileIndex }; + }} + > + <ModifierCard {card} {name} revealed scale={LIST_CARD_SCALE} /> + </div> + {/each} + </div> + </div> + {/if} + + <!-- send-to-bottom (draw-pile card) --> + {#if sub?.kind === 'sendToBottom'} + {@const pileIndex = deck.drawPile.length - 1 - sub.displayIndex} + {@const card = deck.drawPile[pileIndex]} + <div class="confirm" role="dialog" aria-modal="true"> + {#if card} + <ModifierCard + {card} + {name} + revealed={isDrawRevealed(pileIndex)} + scale={PREVIEW_SCALE} + /> + {/if} + <div class="confirm__btns"> + <button + class="pill pill--text" + onclick={() => { + cmd('reorderModifierList', { + newIndex: 0, + oldIndex: pileIndex, + name + }); + sub = null; + }} + > + {t('sendToBottom')} + </button> + <button + class="pill pill--text" + onclick={() => { + cmd('shuffleAMDCard', { name }); + sub = null; + }} + > + {t('shuffleUndrawnCards')} + </button> + <button + class="pill pill--text" + onclick={() => { + cmd('removeAMDCard', { index: pileIndex, name, fromDrawPile: true }); + sub = null; + }} + > + {t('removeCardQuestion')} + </button> + </div> + </div> + {/if} + + <!-- remove / return (discard-pile card) --> + {#if sub && sub.kind === 'removeAmd'} + {@const s = sub} + {@const card = deck.discardPile[s.pileIndex]} + <div class="confirm" role="dialog" aria-modal="true"> + {#if card} + <ModifierCard {card} {name} revealed scale={PREVIEW_SCALE} /> + {/if} + <div class="confirm__btns"> + <button + class="pill pill--text" + onclick={() => { + cmd('removeAMDCard', { index: s.pileIndex, name }); + sub = null; + }} + > + {t('removeCardQuestion')} + </button> + <button + class="pill pill--text" + onclick={() => cmd('returnModifierCard', { name })} + > + {t('returnTopCard')} + </button> + </div> + </div> + {/if} + + <!-- removed cards --> + {#if sub?.kind === 'removed'} + <div class="sub"> + <div class="sub__title">Removed cards</div> + <div class="col"> + {#each removedDisplay as card, i} + {@const pileIndex = deck.removedPile.length - 1 - i} + <div + class="cardwrap" + onclick={() => (sub = { kind: 'returnAmd', pileIndex })} + role="button" + tabindex="0" + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') + sub = { kind: 'returnAmd', pileIndex }; + }} + > + <ModifierCard {card} {name} revealed scale={LIST_CARD_SCALE} /> + </div> + {/each} + </div> + </div> + {/if} + + <!-- return a removed card --> + {#if sub && sub.kind === 'returnAmd'} + {@const s = sub} + {@const card = deck.removedPile[s.pileIndex]} + <div class="confirm" role="dialog" aria-modal="true"> + {#if card} + <ModifierCard {card} {name} revealed scale={PREVIEW_SCALE} /> + {/if} + <div class="confirm__btns"> + <button + class="pill pill--text" + onclick={() => { + cmd('returnRemovedAMDCard', { + index: s.pileIndex, + name, + toDrawPile: false + }); + sub = null; + }} + > + {t('returnToDiscardPile')} + </button> + <button + class="pill pill--text" + onclick={() => { + cmd('returnRemovedAMDCard', { + index: s.pileIndex, + name, + toDrawPile: true + }); + sub = null; + }} + > + {t('returnToDrawPile')} + </button> + </div> + </div> + {/if} + + <!-- faction cards --> + {#if sub?.kind === 'faction'} + <div class="sub"> + <div class="grid"> + {#each factionGfxs as gfx} + <button + class="grid__cell" + class:grid__cell--grayed={factionGrayed(gfx)} + disabled={!player} + aria-label={gfx} + onclick={() => { + if (factionAdded == null && !factionGrayed(gfx)) { + cmd('addFactionCard', { + characterId: name, + cardId: gfx, + add: true + }); + } + }} + > + <ModifierCard + card={{ gfx }} + name="" + revealed + scale={PREVIEW_SCALE} + /> + </button> + {/each} + </div> + <div class="confirm__btns"> + {#if factionAdded == null} + <span class="label">{t('tapCardToAddToDeck')}</span> + {:else} + <button + class="pill pill--text" + onclick={() => { + cmd('addFactionCard', { + characterId: name, + cardId: factionAdded, + add: false + }); + }} + > + {t('removeCardFromDeckQuestion')} + </button> + {/if} + </div> + </div> + {/if} + + <!-- perks --> + {#if sub?.kind === 'perks' && character && characterClassData} + <div class="sub sub--perks"> + <div class="sub__title">{t('addPerks')}</div> + {#if characterClassData.perkDetailsFH.length > 0} + <label class="perkrow"> + <input + type="checkbox" + checked={character.characterState.useFHPerks} + disabled={!player} + onchange={() => + cmd('useFHPerks', { characterId: character.id })} + /> + <span>{t('useFrosthavenPerks')}</span> + </label> + {/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 + )} + <div class="divider"></div> + <label class="perkrow" class:perkrow--disabled={!enabled}> + <input + type="checkbox" + checked={added} + disabled={!player || !enabled} + onchange={() => + cmd('addPerk', { characterId: character.id, index: i })} + /> + <span class="perkrow__desc">{perkDescription(perk)}</span> + </label> + {/each} + </div> + {/if} +</Menu> + +<style> + .columns { + display: flex; + gap: 12px; + align-items: flex-start; + } + .col { + flex: 1; + display: flex; + flex-direction: column; + gap: 8px; + max-height: 50vh; + overflow-y: auto; + } + .cardwrap { + cursor: pointer; + border-radius: 6px; + } + .cardwrap:focus-visible { + outline: 2px solid #7ec8ff; + } + .pill { + min-width: 32px; + padding: 4px 8px; + font-size: 13px; + border: none; + border-radius: 4px; + background: rgba(255, 255, 255, 0.12); + color: inherit; + cursor: pointer; + white-space: pre; + } + .pill:hover { + background: rgba(255, 255, 255, 0.25); + } + .pill--text { + min-width: 0; + } + .confirm { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + margin-top: 10px; + padding: 10px; + border-radius: 8px; + background: rgba(0, 0, 0, 0.35); + } + .confirm__btns { + display: flex; + flex-wrap: wrap; + gap: 8px; + justify-content: center; + } + .sub { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + margin-top: 10px; + padding: 10px; + border-radius: 8px; + background: rgba(0, 0, 0, 0.35); + } + .sub__title { + font-size: 14px; + font-weight: 600; + } + .sub--perks { + align-items: stretch; + max-height: 60vh; + overflow-y: auto; + } + .grid { + display: grid; + grid-template-columns: repeat(auto-fit, 60px); + gap: 8px; + justify-content: center; + } + .grid__cell { + padding: 0; + background: none; + border: none; + cursor: pointer; + } + .grid__cell--grayed { + filter: grayscale(1); + opacity: 0.5; + } + .label { + font-size: 13px; + } + .perkrow { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 0; + font-size: 13px; + cursor: pointer; + } + .perkrow--disabled { + opacity: 0.35; + cursor: default; + } + .perkrow__desc { + flex: 1; + } + .divider { + height: 1px; + background: rgba(255, 255, 255, 0.2); + } +</style> 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 @@ +<!-- + One modifier (AMD) deck (the reference `ModifierDeckWidget`): the draw + pile (tap to draw; face-up top card when cards are revealed; a class icon + + "Shuffle & Draw" when empty) beside the discard box (tap to open the + deck menu, double-tap to zoom the top card). +--> +<script lang="ts"> + import type { GameSession } from '$lib/state/session'; + import type { ModifierDeck as Deck } from '$lib/protocol/types'; + import { currentCharacterId } from '$lib/game/rules'; + import ModifierCard from '../cards/ModifierCard.svelte'; + + let { + session, + deck, + name, + className = null, + perks = null, + onOpenMenu, + onZoom + }: { + session: GameSession; + deck: Deck; + /** "" party deck, "allies", or a character id. */ + name: string; + /** The character-class name (deck icon), null for party decks. */ + className?: string | null; + /** The class's perk `adds` lists (for `P<n>` card graphics). */ + perks?: string[][] | null; + onOpenMenu: () => void; + onZoom: () => void; + } = $props(); + + const gameState = session.state; + const player = session.player; + + // The empty-draw-pile icon: the current character, but only when this + // deck is theirs (the reference `currentCharacter`). + const showIcon = $derived( + className != null && $gameState != null && currentCharacterId($gameState) === className + ); + + const drawTop = $derived( + deck.drawPile.length > 0 + ? deck.drawPile[deck.drawPile.length - 1] + : null + ); + // The top three discard cards, bottom-most first (for the stack offsets). + const discardStack = $derived( + deck.discardPile.slice(-3).map((c, i, arr) => ({ + card: c, + depth: arr.length - 1 - i + })) + ); + + function draw() { + if ($player && deck.drawPile.length > 0) { + session.command('drawModifierCard', { name }); + } + } +</script> + +<div class="deck"> + <div + class="drawpile" + role="button" + tabindex={0} + aria-label="draw pile" + onclick={draw} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') draw(); + }} + > + {#if drawTop != null} + <ModifierCard + card={drawTop} + {name} + revealed={deck.revealed > 0} + {perks} + /> + {:else} + <div class="empty"> + {#if className} + <img class="empty__icon" src="/images/class-icons/{className}.png" alt={className} /> + {/if} + <span class="empty__label">Shuffle & Draw</span> + </div> + {/if} + <span class="count">{deck.drawPile.length}</span> + </div> + + <div + class="discard" + role="button" + tabindex={0} + aria-label="discard pile" + onclick={onOpenMenu} + ondblclick={onZoom} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenMenu(); + }} + > + {#each discardStack as entry} + <div + class="discard__card" + style="left: {entry.depth * 11}px; transform: rotate({entry.depth === 0 ? 0 : entry.depth * -7.5}deg)" + > + <ModifierCard card={entry.card} {name} revealed {perks} /> + </div> + {/each} + </div> +</div> + +<style> + .deck { + display: flex; + align-items: center; + gap: 4px; + width: 153px; + height: 39px; + } + .drawpile { + position: relative; + width: 58.6666px; + height: 39px; + cursor: pointer; + } + .drawpile:focus-visible { + outline: 2px solid #7ec8ff; + border-radius: 4px; + } + .empty { + position: relative; + width: 58.6666px; + height: 39px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.48); + display: flex; + align-items: flex-end; + justify-content: center; + } + .empty__icon { + position: absolute; + top: 4px; + left: 12px; + width: 27px; + height: 27px; + filter: brightness(0.6); + } + .empty__label { + font-size: 9px; + color: #fff; + text-shadow: 0.6px 0.6px 1px rgba(0, 0, 0, 0.87); + padding-bottom: 2px; + } + .count { + position: absolute; + right: 3px; + bottom: 0; + font-size: 13px; + font-weight: 700; + color: #fff; + text-shadow: 1px 1px 1px #000; + pointer-events: none; + } + .discard { + position: relative; + width: 66.6666px; + height: 39px; + border-radius: 5px; + border: 1px solid rgba(255, 255, 255, 0.7); + background: rgba(0, 0, 0, 0.48); + cursor: pointer; + overflow: visible; + } + .discard:focus-visible { + outline: 2px solid #7ec8ff; + } + .discard__card { + position: absolute; + top: 0; + left: 4px; + transition: left 0.2s ease, transform 0.2s ease; + } +</style> diff --git a/web/test/deckHelpers.test.ts b/web/test/deckHelpers.test.ts new file mode 100644 index 0000000..8aef385 --- /dev/null +++ b/web/test/deckHelpers.test.ts @@ -0,0 +1,486 @@ +/** + * Phase 4: unit tests for the deck view helpers — the modifier-deck + * derivations (`$lib/game/modifierDeck`), the loot-card value logic + * (`$lib/game/cards/lootCard`), the rule predicates + * (`$lib/game/rules`), and the perk helpers (`$lib/game/perks`). + */ + +import { describe, it, expect } from 'vitest'; +import { + drawPileTopFirst, + deckHasCard, + deckHasMinus1, + deckHasPlus0, + deckMinus2Present, + removableTotal, + revealedCards, + factionCards, + factionCardInAnyCharacterDeck, + deckHasSanctuaryCard, + deckHasPartyCard +} from '$lib/game/modifierDeck'; +import { + poolCardGfx, + lootValue, + characterLootTotal +} from '$lib/game/cards/lootCard'; +import { + isCSCampaign, + isCustomCampaign, + isInactiveForRule, + isFrosthavenStyleForMonster, + modifierDeckByName, + hasCharacterClass, + currentCharacterId, + shouldShowAlliesDeck +} from '$lib/game/rules'; +import { + activePerks, + cardText, + perkDescription, + canAddPerk, + canRemovePerk +} from '$lib/game/perks'; +import type { + CharacterItem, + LootCard, + MonsterItem, + ModifierCard, + ModifierDeck, + SpecialRule +} from '$lib/protocol/types'; +import type { ClassData, PerkDetail } from '$lib/data/gameData'; +import { + emptyModifierDeck, + emptyGameState +} from './fixtures'; + +// --- fixtures ---------------------------------------------------------------- + +function card(gfx: string): ModifierCard { + return { gfx }; +} + +function deck(overrides: Partial<ModifierDeck> = {}): ModifierDeck { + return { ...emptyModifierDeck(), ...overrides }; +} + +function character( + id: string, + overrides: Partial<CharacterItem> = {} +): CharacterItem { + return { + id, + turnState: 0, + note: '', + characterClass: 'Bounty Hunter', + edition: 'Jaws of the Lion', + characterState: { + level: 1, + health: 10, + maxHealth: 10, + chill: 0, + conditions: [], + conditionsAddedThisTurn: [], + conditionsAddedPreviousTurn: [], + initiative: 1, + xp: 0, + display: id, + modifierDeck: emptyModifierDeck(), + summonList: [], + useFHPerks: false, + perkList: [] + }, + ...overrides + }; +} + +function monster(overrides: Partial<MonsterItem> = {}): MonsterItem { + return { + id: 'Worg', + turnState: 0, + note: '', + isActive: true, + type: 'Worg', + monsterInstances: [], + isAlly: false, + v: 1, + level: 1, + ...overrides + }; +} + +function loot(overrides: Partial<LootCard> = {}): LootCard { + return { + gfx: 'hide', + owner: 'c1', + id: 100, + enhanced: 0, + baseValue: 0, + lootType: 0, + ...overrides + }; +} + +function perk(text = '', adds: string[] = [], removes: string[] = []): PerkDetail { + return { text, adds, removes }; +} + +function classData(perks: PerkDetail[], perksFH: PerkDetail[] = []): ClassData { + return { + id: 'Bounty Hunter', + name: 'Bounty Hunter', + edition: 'Jaws of the Lion', + hidden: false, + health: [10], + color: '000000', + colorSecondary: '000000', + icon: '/images/class-icons/Bounty%20Hunter.png', + perks: perks.map((p) => p.adds), + perksFH: perksFH.map((p) => p.adds), + perkDetails: perks, + perkDetailsFH: perksFH + }; +} + +function inactiveRule( + name: string, + list: number[], + overrides: Partial<SpecialRule> = {} +): SpecialRule { + return { + type: 'InactiveMonster', + note: '', + name, + health: '', + condition: '', + init: 0, + level: 0, + startOfRound: false, + list, + ...overrides + }; +} + +// --- modifierDeck ------------------------------------------------------------- + +describe('modifierDeck', () => { + it('drawPileTopFirst reverses the bottom-first wire pile', () => { + const d = deck({ drawPile: [card('a'), card('b'), card('c')] }); + expect(drawPileTopFirst(d).map((c) => c.gfx)).toEqual(['c', 'b', 'a']); + // The original pile is not mutated. + expect(d.drawPile.map((c) => c.gfx)).toEqual(['a', 'b', 'c']); + }); + + it('deckHasCard looks in draw and discard piles only', () => { + const d = deck({ + drawPile: [card('minus1')], + discardPile: [card('plus0')], + removedPile: [card('minus2')] + }); + expect(deckHasCard(d, 'minus1')).toBe(true); + expect(deckHasCard(d, 'plus0')).toBe(true); + expect(deckHasCard(d, 'minus2')).toBe(false); + expect(deckHasMinus1(d)).toBe(true); + expect(deckHasPlus0(d)).toBe(true); + }); + + it('deckMinus2Present is true until the minus2 card is removed', () => { + expect(deckMinus2Present(deck())).toBe(true); + expect( + deckMinus2Present(deck({ removedPile: [card('minus2')] })) + ).toBe(false); + // A minus2 in the draw pile still counts as present. + expect( + deckMinus2Present(deck({ drawPile: [card('minus2')] })) + ).toBe(true); + }); + + it('removableTotal falls back to 0', () => { + const d = deck(); + d.removables['curse'] = 3; + expect(removableTotal(d, 'curse')).toBe(3); + expect(removableTotal(d, 'bless')).toBe(0); + }); + + it('revealedCards returns the top N draw cards, clamped', () => { + const d = deck({ drawPile: [card('a'), card('b'), card('c')] }); + expect(revealedCards(d, 1).map((c) => c.gfx)).toEqual(['c']); + expect(revealedCards(d, 5).map((c) => c.gfx)).toEqual(['c', 'b', 'a']); + expect(revealedCards(d, 0).map((c) => c.gfx)).toEqual([]); + }); + + it('factionCards lists four cards per faction, none for others', () => { + expect(factionCards('Demons')).toEqual([ + 'Demons-perks/plus1any', + 'Demons-perks/plus1retaliate1flip', + 'Demons-perks/plus0wardallyflip', + 'Demons-perks/unique/fuck3' + ]); + expect(factionCards('Merchant-Guild')[0]).toBe( + 'Merchant-Guild-perks/plus1curse' + ); + expect(factionCards('Military').length).toBe(4); + expect(factionCards('Something Else')).toEqual([]); + }); + + it('factionCardInAnyCharacterDeck grays out cards other decks have', () => { + const decks = [ + { name: 'c1', deck: deck({ drawPile: [card('a')] }) }, + { name: 'c2', deck: deck({ discardPile: [card('b')] }) } + ]; + expect(factionCardInAnyCharacterDeck(decks, 'a')).toBe(true); + expect(factionCardInAnyCharacterDeck(decks, 'b')).toBe(true); + expect(factionCardInAnyCharacterDeck(decks, 'c')).toBe(false); + }); + + it('deckHasSanctuaryCard/deckHasPartyCard match gfx prefixes', () => { + expect( + deckHasSanctuaryCard(deck({ drawPile: [card('sanctuary/1')] })) + ).toBe(true); + expect(deckHasSanctuaryCard(deck({ drawPile: [card('party/1')] }))).toBe( + false + ); + expect( + deckHasPartyCard(deck({ discardPile: [card('party/2')] })) + ).toBe(true); + expect(deckHasPartyCard(deck())).toBe(false); + }); +}); + +// --- lootCard ----------------------------------------------------------------- + +describe('lootCard', () => { + it('poolCardGfx derives the coin denomination from the index', () => { + expect(poolCardGfx('coin', 0)).toBe('coin 1'); + expect(poolCardGfx('coin', 11)).toBe('coin 1'); + expect(poolCardGfx('coin', 12)).toBe('coin 2'); + expect(poolCardGfx('coin', 17)).toBe('coin 2'); + expect(poolCardGfx('coin', 18)).toBe('coin 3'); + expect(poolCardGfx('coin', 19)).toBe('coin 3'); + expect(poolCardGfx('hide', 3)).toBe('hide'); + }); + + it('lootValue applies party size to the base value', () => { + const c = loot({ baseValue: 1 }); // one if 4, two if not + expect(lootValue(c, 4)).toBe(1); + expect(lootValue(c, 3)).toBe(2); + const b = loot({ baseValue: 2 }); // one if 3 or 4, two if not + expect(lootValue(b, 4)).toBe(1); + expect(lootValue(b, 3)).toBe(1); + expect(lootValue(b, 2)).toBe(2); + // Enhancements always add. + expect(lootValue(loot({ baseValue: 0, enhanced: 2 }), 2)).toBe(3); + // Non-materiel cards show only the enhancement. + expect(lootValue(loot({ lootType: 1 }), 4)).toBe(null); + expect(lootValue(loot({ lootType: 1, enhanced: 3 }), 4)).toBe(3); + }); + + it('characterLootTotal sums a character’s coins and loot', () => { + const pile = [ + loot({ gfx: 'coin 1', id: 1 }), + loot({ gfx: 'coin 2', id: 2, enhanced: 1 }), + loot({ gfx: 'coin 3', id: 3 }), + loot({ gfx: 'hide', id: 4, baseValue: 1 }), + loot({ gfx: 'hide', id: 5, owner: 'c2' }) // someone else's + ]; + // 4 characters: baseValue-1 hide counts 1. + expect(characterLootTotal(pile, 'c1', 'coin', 4)).toBe(1 + 3 + 3); + expect(characterLootTotal(pile, 'c1', 'hide', 4)).toBe(1); + expect(characterLootTotal(pile, 'c2', 'hide', 4)).toBe(1); + expect(characterLootTotal(pile, 'c1', 'metal', 4)).toBe(0); + }); +}); + +// --- rules -------------------------------------------------------------------- + +describe('rules', () => { + it('campaign predicates', () => { + expect(isCSCampaign('Crimson Scales')).toBe(true); + expect(isCSCampaign('Trail of Ashes')).toBe(true); + expect(isCSCampaign('CCUG')).toBe(false); + expect(isCustomCampaign('CCUG')).toBe(true); + expect(isCustomCampaign('Frosthaven')).toBe(false); + }); + + it('modifierDeckByName resolves party, ally, and character decks', () => { + const gs = emptyGameState(); + const personal = emptyModifierDeck(); + gs.modifierDeck.addedMinusOnes = 1; + gs.modifierDeckAllies.addedMinusOnes = 2; + const c = character('c1'); + c.characterState.modifierDeck.addedMinusOnes = 3; + gs.currentList = [c]; + expect(modifierDeckByName(gs, '')).toBe(gs.modifierDeck); + expect(modifierDeckByName(gs, 'allies')).toBe(gs.modifierDeckAllies); + expect(modifierDeckByName(gs, 'c1').addedMinusOnes).toBe(3); + // Unknown names fall back to the party deck. + expect(modifierDeckByName(gs, 'nobody')).toBe(gs.modifierDeck); + }); + + it('hasCharacterClass / currentCharacterId', () => { + const gs = emptyGameState({ + currentList: [ + character('c1'), + character('c2', { turnState: 1, characterClass: 'Pyromancer' }) + ] + }); + expect(hasCharacterClass(gs, 'Pyromancer')).toBe(true); + expect(hasCharacterClass(gs, 'Cassandra')).toBe(false); + expect(currentCharacterId(gs)).toBe('c2'); + expect(currentCharacterId(emptyGameState())).toBe(null); + }); + + it('shouldShowAlliesDeck follows the reference gates', () => { + const ally = monster({ id: 'Ally', isAlly: true }); + // The explicit setting always wins. + expect( + shouldShowAlliesDeck(emptyGameState({ showAllyDeck: true })) + ).toBe(true); + // OG edition without the setting and without an ally: hidden. + expect( + shouldShowAlliesDeck( + emptyGameState({ allyDeckInOGGloom: false, currentList: [ally] }) + ) + ).toBe(false); + // OG edition with the setting: shown only with an ally. + expect( + shouldShowAlliesDeck( + emptyGameState({ allyDeckInOGGloom: true, currentList: [ally] }) + ) + ).toBe(true); + expect( + shouldShowAlliesDeck( + emptyGameState({ + allyDeckInOGGloom: true, + currentList: [monster()] + }) + ) + ).toBe(false); + // Frosthaven: no OG gate. + const fh = emptyGameState({ currentCampaign: 'Frosthaven' }); + expect(shouldShowAlliesDeck(fh)).toBe(false); + fh.currentList = [ally]; + expect(shouldShowAlliesDeck(fh)).toBe(true); + }); + + it('isInactiveForRule matches the scenario round list', () => { + const gs = emptyGameState({ + round: 2, + scenarioSpecialRules: [inactiveRule('Worg', [1, 3])] + }); + expect(isInactiveForRule(gs, 'Worg')).toBe(false); + gs.round = 1; + expect(isInactiveForRule(gs, 'Worg')).toBe(true); + expect(isInactiveForRule(gs, 'Another')).toBe(false); + expect(isInactiveForRule(emptyGameState(), 'Worg')).toBe(false); + }); + + it('isFrosthavenStyleForMonster keys off edition and theme', () => { + const gs = emptyGameState(); // Jaws of the Lion: OG edition + expect( + isFrosthavenStyleForMonster('Frosthaven', gs, 'gloomhaven') + ).toBe(true); // the monster edition always wins + expect( + isFrosthavenStyleForMonster('Jaws of the Lion', gs, 'frosthaven') + ).toBe(true); // theme override + expect( + isFrosthavenStyleForMonster('Jaws of the Lion', gs, 'gloomhaven') + ).toBe(false); + // Solo: #5 and #100 are OG-styled, #19 and #200 are not. + const solo = emptyGameState({ currentCampaign: 'Solo' }); + expect( + isFrosthavenStyleForMonster('Solo', { ...solo, scenario: '#5 X' }, 'gloomhaven') + ).toBe(true); + expect( + isFrosthavenStyleForMonster('Solo', { ...solo, scenario: '#19 X' }, 'gloomhaven') + ).toBe(false); + expect( + isFrosthavenStyleForMonster('Solo', { ...solo, scenario: '#200 X' }, 'gloomhaven') + ).toBe(false); + }); +}); + +// --- perks -------------------------------------------------------------------- + +describe('perks', () => { + const classFH = classData( + [perk('', ['plus1'])], + [perk('', ['plus2'])] + ); + + function characterState(useFHPerks: boolean, perks?: boolean[]) { + const c = character('c1'); + c.characterState.useFHPerks = useFHPerks; + c.characterState.perkList = perks ?? []; + return c.characterState; + } + + it('activePerks switches on the FH opt-in', () => { + expect(activePerks(classFH, characterState(true)).map((p) => p.adds[0])).toEqual( + ['plus2'] + ); + expect(activePerks(classFH, characterState(false)).map((p) => p.adds[0])).toEqual( + ['plus1'] + ); + // No FH list: the opt-in has nothing to fall back to. + expect( + activePerks(classData([perk('', ['plus1'])]), characterState(true)) + ).toEqual(classFH.perkDetails); + }); + + it('cardText renders modifier tokens', () => { + expect(cardText('plus1')).toBe('+1'); + expect(cardText('minus2')).toBe('-2'); + expect(cardText('minus2flip')).toBe('-2%flip%'); + expect(cardText('perks/minus1flip')).toBe('-1%flip%'); + expect(cardText('plus1range2')).toBe('+1 %range% 2'); + expect(cardText('minus1target2')).toBe('-1+ 2%target%'); + expect(cardText('plus1heal2')).toBe('+1 "%heal%2, self"'); + }); + + it('perkDescription phrases adds/removes', () => { + expect(perkDescription(perk('', ['plus1']))).toBe('Add one +1 card'); + expect(perkDescription(perk('', ['plus1', 'plus2']))).toBe( + 'Add two +1 cards' + ); + expect(perkDescription(perk('', [], ['minus1']))).toBe( + 'Remove one -1 card' + ); + expect( + perkDescription(perk('', [], ['minus1', 'minus2'])) + ).toBe('Remove two -1 cards'); + expect(perkDescription(perk('', ['plus1'], ['minus1']))).toBe( + 'Replace one -1 card with one +1 card' + ); + expect(perkDescription(perk('Special text'))).toBe('Special text'); + }); + + it('canAddPerk needs the removed cards in the deck', () => { + const perks = [perk('', ['plus1'], ['minus1'])]; + const empty = deck(); + const withCard = deck({ drawPile: [card('minus1')] }); + expect(canAddPerk(empty, perks, [false], 0)).toBe(false); + expect(canAddPerk(withCard, perks, [false], 0)).toBe(true); + // Another active perk adding the same card counts as present. + const adder = [perk('', ['minus1']), perk('', [], ['minus1'])]; + expect(canAddPerk(empty, adder, [true, false], 1)).toBe(true); + expect(canAddPerk(empty, adder, [false, false], 1)).toBe(false); + }); + + it('canRemovePerk needs the added cards in the deck', () => { + const perks = [perk('', ['plus1'])]; + expect( + canRemovePerk(deck(), perks, 0) + ).toBe(false); + expect(canRemovePerk(deck({ discardPile: [card('plus1')] }), perks, 0)).toBe( + true + ); + // A perk card is tracked by its P<n> id, not its gfx. + const perkCard = [perk('', ['perks/plus2flip'])]; + expect( + canRemovePerk(deck({ drawPile: [card('P0')] }), perkCard, 0) + ).toBe(true); + expect(canRemovePerk(deck(), perkCard, 0)).toBe(false); + }); +}); diff --git a/web/test/fixtures.ts b/web/test/fixtures.ts new file mode 100644 index 0000000..805634e --- /dev/null +++ b/web/test/fixtures.ts @@ -0,0 +1,96 @@ +/** + * Shared test fixtures (PLAN.md Phase 4): valid empty deck shapes and a full + * {@link GameState} factory so tests don't repeat the (now non-trivial) + * deck field initialisers. + */ + +import type { + GameState, + LootDeck, + ModifierDeck, + SanctuaryDeck +} from '$lib/protocol/types'; +import { LOOT_POOL_KEYS } from '$lib/protocol/types'; + +/** The ten removable-counter gfx keys the server initialises. */ +export function emptyRemovables(): Record<string, number> { + return { + curse: 0, + bless: 0, + 'in-enfeeble': 0, + 'vi-enfeeble': 0, + 'vi-gr-enfeeble': 0, + 'li-enfeeble': 0, + 'in-empower': 0, + 'rm-empower': 0, + 'vi-empower': 0, + 'vi-gr-empower': 0 + }; +} + +export function emptyModifierDeck(): ModifierDeck { + return { + addedMinusOnes: 0, + imbuement: 0, + badOmen: 0, + corrosiveSpew: false, + revealed: 0, + cassandra: false, + removables: emptyRemovables(), + drawPile: [], + removedPile: [], + discardPile: [] + }; +} + +function emptyPools(): Record<(typeof LOOT_POOL_KEYS)[number], number[]> { + const out = {} as Record<(typeof LOOT_POOL_KEYS)[number], number[]>; + for (const key of LOOT_POOL_KEYS) out[key] = []; + return out; +} + +export function emptyLootDeck(): LootDeck { + return { + drawPile: [], + discardPile: [], + addedCards: [], + enhancements: {}, + '1418': false, + '1419': false, + pools: emptyPools() + }; +} + +export function emptySanctuaryDeck(): SanctuaryDeck { + return { multPile: [], flipPile: [] }; +} + +export function emptyGameState( + overrides: Partial<GameState> = {} +): GameState { + return { + level: 1, + solo: false, + autoScenarioLevel: false, + difficulty: 1, + roundState: 0, + round: 1, + totalRounds: 1, + scenario: 'custom', + toastMessage: '', + scenarioSpecialRules: [], + scenarioSectionsAdded: [], + currentCampaign: 'Jaws of the Lion', + currentList: [], + currentAbilityDecks: [], + sanctuaryDeck: emptySanctuaryDeck(), + modifierDeck: emptyModifierDeck(), + modifierDeckAllies: emptyModifierDeck(), + lootDeck: emptyLootDeck(), + unlockedClasses: [], + showAllyDeck: false, + allyDeckInOGGloom: true, + elementState: {}, + ...overrides + }; +} diff --git a/web/test/gameDataClient.test.ts b/web/test/gameDataClient.test.ts index 4249283..d5f0ce2 100644 --- a/web/test/gameDataClient.test.ts +++ b/web/test/gameDataClient.test.ts @@ -70,7 +70,9 @@ describe('GameDataClient.loadCampaign', () => { health: [12, 14], hidden: false, color: 'FF35ACD5', - colorSecondary: 'ff313959' + colorSecondary: 'ff313959', + perks: [{ adds: ['berserker-1'], removes: ['minus1'] }], + perksFH: [{ adds: ['berserker-fh'] }] }, { name: 'Secret', @@ -115,7 +117,11 @@ describe('GameDataClient.loadCampaign', () => { health: [12, 14], color: 'FF35ACD5', colorSecondary: 'ff313959', - icon: '/images/class-icons/Berserker.png' + icon: '/images/class-icons/Berserker.png', + perks: [['berserker-1']], + perksFH: [['berserker-fh']], + perkDetails: [{ text: '', adds: ['berserker-1'], removes: ['minus1'] }], + perkDetailsFH: [{ text: '', adds: ['berserker-fh'], removes: [] }] }, expect.objectContaining({ id: 'Secret', diff --git a/web/test/gameLogic.test.ts b/web/test/gameLogic.test.ts index 263ba14..891aaff 100644 --- a/web/test/gameLogic.test.ts +++ b/web/test/gameLogic.test.ts @@ -10,9 +10,10 @@ import { classColor, classIcon, monsterImage } from '$lib/game/art'; import { characterStatCounters, standeeFigureId, - standeeStatCounters, - type ModifierDeckJson + standeeStatCounters } from '$lib/game/stats'; +import type { ModifierDeck } from '$lib/protocol/types'; +import { emptyModifierDeck } from './fixtures'; import { t, hasLocaleKey, availableLocales } from '$lib/i18n'; describe('elements', () => { @@ -78,8 +79,8 @@ describe('art', () => { }); describe('stat counters', () => { - function deck(cards: { gfx: string }[]): ModifierDeckJson { - return { drawPile: cards, discardPile: [] }; + function deck(cards: { gfx: string }[]): ModifierDeck { + return { ...emptyModifierDeck(), drawPile: cards }; } it('standeeFigureId is name + gfx + standeeNr', () => { @@ -142,8 +143,21 @@ describe('i18n', () => { expect(t('noSuchKey')).toBe('noSuchKey'); }); - it('only English is ported in Phase 3', () => { - expect(availableLocales).toEqual(['en']); + it('offers every in-game locale; only English has a UI table', () => { + // Phase 4: in-game card text is translated for all locales, so the + // picker lists them all; the UI strings fall back to English. + expect(availableLocales).toEqual([ + 'en', + 'de', + 'es', + 'fr', + 'ko', + 'pl', + 'ru', + 'th', + 'zh', + 'zh_Hant' + ]); expect(hasLocaleKey('draw')).toBe(true); }); }); diff --git a/web/test/line/frosthavenConverter.test.ts b/web/test/line/frosthavenConverter.test.ts new file mode 100644 index 0000000..89101b3 --- /dev/null +++ b/web/test/line/frosthavenConverter.test.ts @@ -0,0 +1,156 @@ +import { describe, it, expect } from 'vitest'; +import { + expandEmbeddedNewlines, + convertLinesToFH, + shouldOverflow +} from '$lib/game/line/frosthavenConverter'; + +const conv = (lines: string[], applyStats = false) => + convertLinesToFH(lines, applyStats); + +describe('expandEmbeddedNewlines', () => { + it('passes through lines without a newline', () => + expect(expandEmbeddedNewlines(['Move 3'])).toEqual(['Move 3'])); + it('splits on \\n', () => + expect(expandEmbeddedNewlines(['a\nb'])).toEqual(['a', 'b'])); + it('propagates a ^ prefix to continuation lines', () => + expect(expandEmbeddedNewlines(['^a\nb'])).toEqual(['^a', '^b'])); + it('propagates a ^^ prefix', () => + expect(expandEmbeddedNewlines(['^^a\nb'])).toEqual(['^^a', '^^b'])); +}); + +describe('convertLinesToFH — keyword replacements', () => { + it('"Affect" → "%target%"', () => + expect(conv(['Affect 2'])).toContain('%target% 2')); + it('"damage" → "%damage%"', () => + expect(conv(['Deal damage here'])[0]).toContain('%damage%')); + it('"damaged" is not doubled', () => + expect(conv(['damaged item'])[0]).toBe('damaged item')); + it('"Target" → "%target%"', () => expect(conv(['Target 2'])[0]).toBe('%target% 2')); + it('Affect pipeline leaves no "Affect"', () => { + const result = conv(['Affect all', 'Affect']); + for (const line of result) expect(line).not.toContain('Affect'); + expect(result[0]).toContain('%target%'); + }); + it('collapses "% " to "%"', () => expect(conv(['50% health'])[0]).toBe('50%health')); + it('preserves plain lines', () => expect(conv(['Move 3'])).toContain('Move 3')); +}); + +describe('convertLinesToFH — applyStats flag', () => { + it('applyStats=false collapses " + "', () => expect(conv(['3 + 1'])[0]).toBe('3+1')); + it('applyStats=false collapses " - "', () => expect(conv(['3 - 1'])[0]).toBe('3-1')); + it('applyStats=true preserves " + "', () => + expect(conv(['3 + 1'], true)[0]).toBe('3 + 1')); + it('applyStats=true preserves " - "', () => + expect(conv(['3 - 1'], true)[0]).toBe('3 - 1')); +}); + +describe('convertLinesToFH — [newLine]', () => { + it('converts to an empty string', () => expect(conv(['text', '[newLine]'])).toContain('')); +}); + +describe('convertLinesToFH — * lines', () => { + it('* line passes through', () => + expect(conv(['*Move 3', '^%poison%']).some((l) => l.startsWith('*'))).toBe(true)); + it('* after a real subline adds [subLineEnd]', () => + expect(conv(['Move 3', '^%poison%', '*Attack'])).toContain('[subLineEnd]')); + it('no trailing [subLineEnd] after a leading *', () => + expect(conv(['*Move 3']).at(-1)).not.toBe('[subLineEnd]')); +}); + +describe('convertLinesToFH — subline markers', () => { + it('^%token% after a normal line inserts ![subLineStart]', () => + expect(conv(['Move 3', '^%poison%'])).toContain('![subLineStart]')); + it('trailing [subLineEnd] when open at end', () => + expect(conv(['Move 3', '^%poison%']).at(-1)).toBe('[subLineEnd]')); + it('^ line matching the subline pattern gets a ! prefix', () => + expect(conv(['Move 3', '^%poison%']).some((l) => l.startsWith('!^'))).toBe(true)); + it('^%target% after a normal line triggers a subline', () => + expect(conv(['Attack 3', '^%target% 2'])).toContain('![subLineStart]')); + it('^Self after a normal line triggers a subline', () => + expect(conv(['Heal 2', '^Self'])).toContain('![subLineStart]')); + it('^All attacks does NOT trigger a subline', () => + expect(conv(['Move 3', '^All attacks on you'])).not.toContain('![subLineStart]')); + it('second ^ inside a subline is also prefixed', () => { + const exclam = conv(['Move 3', '^%poison%', '^%wound%']).filter( + (l) => l.startsWith('!') && l.includes('%') + ); + expect(exclam.length).toBeGreaterThanOrEqual(2); + }); + it('empty list returns empty list', () => expect(conv([])).toEqual([])); + it('single non-special line has no markers', () => { + const result = conv(['Move 3']); + expect(result).not.toContain('[subLineStart]'); + expect(result).not.toContain('![subLineStart]'); + expect(result).not.toContain('[subLineEnd]'); + }); +}); + +describe('convertLinesToFH — element use / conditional', () => { + it('[r] before a %use line does not crash', () => + expect(conv(['Attack 2', '[r]', '%use%', '^%poison%', '[/r]'])).not.toEqual([])); + it('[/r] resets the conditional flag', () => + expect( + conv(['[r]', '%use%', '%fire%', '[/r]', 'Move 3', '^%poison%']) + ).toContain('![subLineStart]')); +}); + +describe('convertLinesToFH — advanced subline patterns', () => { + it('^Normal starts a subline', () => + expect(conv(['Attack 3', '^Normal attack'])).toContain('![subLineStart]')); + it('^all starts a subline', () => + expect(conv(['Attack 3', '^all enemies'])).toContain('![subLineStart]')); + it('^All (not "attacks" / "targets") starts a subline', () => + expect(conv(['Attack 3', '^All adjacent enemies'])).toContain('![subLineStart]')); + it('^All targets does not start a subline', () => + expect(conv(['Move 3', '^All targets suffer'])).not.toContain('![subLineStart]')); + it('isSubLine clears after a non-subline ^ line', () => { + const result = conv(['Move 3', '^All attacks on you', 'Attack 2']); + expect(result).not.toContain('![subLineStart]'); + expect(result).not.toContain('[subLineEnd]'); + }); + it('a new main line closes an open subline', () => + expect(conv(['Move 3', '^%poison%', 'Attack 2'])).toContain('[subLineEnd]')); +}); + +describe('shouldOverflow', () => { + const overflowTokens = [ + 'pierce', + 'brittle', + 'curse', + 'enfeeble', + 'bless', + 'invisible', + 'strengthen', + 'bane', + 'push', + 'pull', + 'poison', + 'wound', + 'infect', + 'chill', + 'disarm', + 'immobilize', + 'stun', + 'impair', + 'safeguard', + 'muddle' + ]; + it('returns true for known FH condition tokens', () => { + for (const token of overflowTokens) + expect(shouldOverflow(true, token)).toBe(true); + }); + it('returns false for non-FH style', () => { + for (const token of overflowTokens) + expect(shouldOverflow(false, token)).toBe(false); + }); + it('returns false for non-overflow tokens', () => { + expect(shouldOverflow(true, 'attack')).toBe(false); + expect(shouldOverflow(true, 'move')).toBe(false); + expect(shouldOverflow(true, '')).toBe(false); + }); + it('matches tokens containing poison / wound', () => { + expect(shouldOverflow(true, 'acid-poison')).toBe(true); + expect(shouldOverflow(true, 'wound-infect')).toBe(true); + }); +}); diff --git a/web/test/line/lineParser.test.ts b/web/test/line/lineParser.test.ts new file mode 100644 index 0000000..ad95240 --- /dev/null +++ b/web/test/line/lineParser.test.ts @@ -0,0 +1,169 @@ +import { describe, it, expect } from 'vitest'; +import { parseLines } from '$lib/game/line/lineParser'; +import type { + ColumnNode, + LineBuildOptions, + Node, + RowNode, + SubLineNode +} from '$lib/game/line/types'; +import type { StatMonster } from '$lib/game/line/statApplier'; + +function opts(partial: Partial<LineBuildOptions> = {}): LineBuildOptions { + return { + left: false, + applyStats: false, + applyAll: false, + align: 'center', + frosthavenStyle: false, + scale: 1, + monster: null, + ...partial + }; +} + +/** The single top-level row of a one-line card. */ +function topRow(col: ColumnNode): RowNode { + const first = col.children[0]; + if (!first || first.kind !== 'row') + throw new Error(`expected a top row, got ${first?.kind}`); + return first; +} + +function texts(node: Node): string[] { + if (node.kind === 'text') return [node.text]; + if ('children' in node) return node.children.flatMap(texts); + return []; +} + +const zealot = (standeeTypes: number[] = [1]): StatMonster => ({ + level: { + normal: { attack: 2, move: 2 }, + elite: { attack: 3, move: 2 } + }, + standeeTypes: standeeTypes as never, + isActive: false +}); + +describe('parseLines — plain text', () => { + it('a single line becomes one row of one text segment', () => { + const col = parseLines(['Move 3'], opts()); + expect(col.children).toHaveLength(1); + const row = topRow(col); + expect(row.children.map((n) => n.kind)).toEqual(['text']); + expect((row.children[0] as { text: string }).text).toBe('Move 3'); + }); + it('multiple lines become multiple rows', () => { + const col = parseLines(['Move 3', 'Attack 2'], opts()); + expect(col.children.map((n) => n.kind)).toEqual(['row', 'row']); + }); +}); + +describe('parseLines — tokens', () => { + it('GH style shows the translated label beside the icon', () => { + const row = topRow(parseLines(['%attack% 2'], opts())); + expect(row.children.map((n) => n.kind)).toEqual(['text', 'token', 'text']); + expect((row.children[0] as { text: string }).text).toBe('Attack'); + expect((row.children[1] as { token: string }).token).toBe('attack'); + }); + it('FH style renders the token icon-only (no label)', () => { + const row = topRow(parseLines(['%attack% 2'], opts({ frosthavenStyle: true }))); + expect(row.children.map((n) => n.kind)).toEqual(['token', 'text']); + }); + it('a standalone token yields just the icon', () => { + const row = topRow(parseLines(['%poison%'], opts({ frosthavenStyle: true }))); + expect(row.children.map((n) => n.kind)).toEqual(['token']); + expect((row.children[0] as { overflow: boolean }).overflow).toBe(true); + }); +}); + +describe('parseLines — sub-lines (FH)', () => { + it('boxes a ^%token% sub-line to the right of the main line', () => { + const col = parseLines(['Move 3', '^%poison%'], opts({ frosthavenStyle: true })); + const row = topRow(col); + expect(row.children.map((n) => n.kind)).toEqual(['row', 'subline']); + const sub = row.children[1] as SubLineNode; + expect(sub.children.map((n) => n.kind)).toEqual(['row']); + expect((sub.children[0] as RowNode).children.map((n) => n.kind)).toEqual([ + 'token' + ]); + }); + it('consecutive ^ sub-line tokens share one row (no line break)', () => { + const col = parseLines( + ['Move 3', '^%poison%', '^%wound%'], + opts({ frosthavenStyle: true }) + ); + const row = topRow(col); + const sub = row.children[1] as SubLineNode; + expect(sub.children.map((n) => n.kind)).toEqual(['row']); + expect((sub.children[0] as RowNode).children.map((n) => n.kind)).toEqual([ + 'token', + 'token' + ]); + }); +}); + +describe('parseLines — element images & dividers', () => { + it('a ¤ element line becomes an image node', () => { + const col = parseLines(['¤fire'], opts({ frosthavenStyle: true })); + expect(col.children.map((n) => n.kind)).toEqual(['image']); + expect((col.children[0] as { element: boolean }).element).toBe(true); + }); + it('a *.... line becomes a divider in FH style', () => { + const col = parseLines(['*....'], opts({ frosthavenStyle: true })); + expect(col.children.map((n) => n.kind)).toEqual(['divider']); + expect((col.children[0] as { thin: boolean }).thin).toBe(false); + }); +}); + +describe('parseLines — columns', () => { + it('[c]…[/c] groups its lines into a column node', () => { + const col = parseLines(['[c]', 'A', 'B', '[/c]'], opts()); + expect(col.children.map((n) => n.kind)).toEqual(['column']); + const inner = col.children[0] as { children: Node[] }; + expect(inner.children.map((n) => n.kind)).toEqual(['row', 'row']); + expect(texts(inner.children[0] as Node)).toEqual(['A']); + }); +}); + +describe('parseLines — element use / conditional', () => { + it('an element+%use% block in a row becomes a conditional box', () => { + const col = parseLines( + ['[r]', '%fire%%use%', '[/r]'], + opts({ frosthavenStyle: true }) + ); + expect(col.children.map((n) => n.kind)).toEqual(['conditional']); + const cond = col.children[0] as { + elementUse: boolean; + children: Node[]; + }; + expect(cond.elementUse).toBe(true); + // The [r] group wraps its inner line in a row (faithful to the + // reference's Row(children: widgetsInRow)). + const group = cond.children[0] as RowNode; + const inner = group.children[0] as RowNode; + expect(inner.children.map((n) => n.kind)).toEqual(['elementUse', 'text']); + }); +}); + +describe('parseLines — elite stat split', () => { + it('splits %attack% into a normal and an elite row', () => { + const col = parseLines( + ['%attack% +0'], + opts({ applyStats: true, applyAll: false, monster: zealot([0, 1]) }) + ); + const all = texts(col).join(' '); + // normal (2) and elite (3) values both present. + expect(all).toContain('2'); + expect(all).toContain('3'); + }); + it('a lone elite standee shows only the elite value', () => { + const col = parseLines( + ['%attack% +0'], + opts({ applyStats: true, applyAll: false, monster: zealot([1]) }) + ); + const row = topRow(col); + const styles = row.children.map((n) => (n as { style?: string }).style ?? ''); + expect(styles.some((s) => s.startsWith('elite'))).toBe(true); + }); +}); diff --git a/web/test/line/statApplier.test.ts b/web/test/line/statApplier.test.ts new file mode 100644 index 0000000..087a6f2 --- /dev/null +++ b/web/test/line/statApplier.test.ts @@ -0,0 +1,100 @@ +import { describe, it, expect } from 'vitest'; +import { + applyMonsterStats, + type MonsterType, + type StatMonster +} from '$lib/game/line/statApplier'; + +// Zealot level 1 (the reference test monster): normal attack=2 move=2, +// elite attack=3 move=2, no range, no attributes. +function zealot(standeeTypes: MonsterType[] = []): StatMonster { + return { + level: { + normal: { health: 4, move: 2, attack: 2 }, + elite: { health: 7, move: 2, attack: 3 } + }, + standeeTypes, + isActive: false + }; +} + +// Black Sludge level 1: both normal and elite carry "%shield% 1". +function blackSludge(standeeTypes: MonsterType[] = []): StatMonster { + return { + level: { + normal: { health: 4, move: 1, attack: 2, attributes: ['%shield% 1'] }, + elite: { health: 8, move: 1, attack: 2, attributes: ['%shield% 1'] } + }, + standeeTypes, + isActive: false + }; +} + +const elite = (s: string[]) => s.find((x) => x.startsWith('!')); + +describe('applyMonsterStats — plain text', () => { + it('returns a line with no formula unchanged', () => + expect(applyMonsterStats('Move 3', '', zealot(), false)).toEqual(['Move 3'])); + it('returns a bare token unchanged', () => + expect(applyMonsterStats('%attack%', '', zealot(), false)).toEqual(['%attack%'])); + it('treats a single digit as plain text', () => + expect(applyMonsterStats('3', '', zealot(), false)).toEqual(['3'])); +}); + +describe('applyMonsterStats — no standees, forceShowAll=false', () => { + it('leaves "%attack% +0" unchanged (no standees, no force)', () => + expect(applyMonsterStats('%attack% +0', '', zealot(), false)).toEqual(['%attack% +0'])); + it('leaves "%move% +1" unchanged', () => + expect(applyMonsterStats('%move% +1', '', zealot(), false)).toEqual(['%move% +1'])); +}); + +describe('applyMonsterStats — forceShowAll attack', () => { + it('splits "%attack% +0" into more than one result', () => + expect(applyMonsterStats('%attack% +0', '', zealot(), true).length).toBeGreaterThan(1)); + it('normal result holds the normal attack value', () => + expect(applyMonsterStats('%attack% +0', '', zealot(), true)[0]).toContain('2')); + it('elite result holds the elite attack value', () => + expect(elite(applyMonsterStats('%attack% +0', '', zealot(), true))).toContain('3')); + it('"%attack% +1" adds 1 to both', () => { + const r = applyMonsterStats('%attack% +1', '', zealot(), true); + expect(r[0]).toContain('3'); + expect(elite(r)).toContain('4'); + }); + it('"%attack% -1" subtracts 1 from both', () => { + const r = applyMonsterStats('%attack% -1', '', zealot(), true); + expect(r[0]).toContain('1'); + expect(elite(r)).toContain('2'); + }); +}); + +describe('applyMonsterStats — forceShowAll move', () => { + it('"%move% +0" yields the move value', () => + expect(applyMonsterStats('%move% +0', '', zealot(), true)[0]).toContain('2')); + it('"%move% +2" yields move + 2', () => + expect(applyMonsterStats('%move% +2', '', zealot(), true)[0]).toContain('4')); +}); + +describe('applyMonsterStats — with standees', () => { + it('a normal standee shows only the normal stat', () => { + const r = applyMonsterStats('%attack% +0', '', zealot([0]), false); + expect(r[0]).toContain('2'); + expect(r.every((s) => !s.includes('3'))).toBe(true); + }); + it('an elite standee splits into both stats', () => { + const r = applyMonsterStats('%attack% +0', '', zealot([1]), false); + expect(r.length).toBeGreaterThan(1); + expect(r.some((s) => s.includes('3'))).toBe(true); + }); +}); + +describe('applyMonsterStats — standalone formula', () => { + it('evaluates a C+L formula (level 1, no characters → 3)', () => + expect(applyMonsterStats('C+L health', '', zealot(), false)[0]).toContain('3')); + it('evaluates a 3+ digit plain number in place', () => + expect(applyMonsterStats('100 damage', '', zealot(), false)[0]).toContain('100')); +}); + +describe('applyMonsterStats — shield token', () => { + it('yields the shield value from the attribute', () => + expect(applyMonsterStats('%shield% +0', '', blackSludge(), true)[0]).toContain('1')); +}); diff --git a/web/test/line/statCalculator.test.ts b/web/test/line/statCalculator.test.ts new file mode 100644 index 0000000..022d8df --- /dev/null +++ b/web/test/line/statCalculator.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from 'vitest'; +import { evalFormula, calculateFormula } from '$lib/game/line/statCalculator'; + +describe('evalFormula', () => { + it('parses a plain integer', () => expect(evalFormula('5')).toBe(5)); + it('parses addition', () => expect(evalFormula('3+2')).toBe(5)); + it('parses subtraction', () => expect(evalFormula('7-3')).toBe(4)); + it('multiplies with *', () => expect(evalFormula('3*4')).toBe(12)); + it('multiplies with x', () => expect(evalFormula('3x4')).toBe(12)); + it('divides with / (ceil)', () => expect(evalFormula('7/2')).toBe(4)); + it('divides with d (floor)', () => expect(evalFormula('7d2')).toBe(3)); + it('honours parentheses', () => expect(evalFormula('(2+3)*4')).toBe(20)); + it('handles unary minus', () => expect(evalFormula('0-5')).toBe(-5)); + it('returns null for non-numeric', () => expect(evalFormula('abc')).toBeNull()); + it('returns null for trailing junk', () => + expect(evalFormula('5extra')).toBeNull()); + it('condition less-than true → 1', () => expect(evalFormula('2<3')).toBe(1)); + it('condition less-than false → 0', () => expect(evalFormula('3<2')).toBe(0)); + it('condition greater-than true → 1', () => + expect(evalFormula('5>4')).toBe(1)); + it('condition greater-than false → 0', () => + expect(evalFormula('1>2')).toBe(0)); + it('condition equals true → 1', () => expect(evalFormula('4=4')).toBe(1)); + it('condition equals false → 0', () => expect(evalFormula('4=5')).toBe(0)); + it('exact ceil division', () => expect(evalFormula('6/2')).toBe(3)); + it('exact floor division', () => expect(evalFormula('6d2')).toBe(3)); + it('precedence: * before +', () => expect(evalFormula('2+3*4')).toBe(14)); +}); + +describe('calculateFormula', () => { + it('substitutes C, clamped to a minimum of 2', () => + expect(calculateFormula('C')).toBe(2)); + it('substitutes C with the real count when ≥ 2', () => + expect(calculateFormula('C', { characterCount: 3 })).toBe(3)); + it('substitutes L with the level', () => + expect(calculateFormula('L', { level: 4 })).toBe(4)); + it('combines C and L', () => + expect(calculateFormula('C+L', { level: 3 })).toBe(5)); + it('returns null for an invalid formula', () => + expect(calculateFormula('??')).toBeNull()); +}); diff --git a/web/test/playerStore.test.ts b/web/test/playerStore.test.ts index c3aefe8..ffd4a47 100644 --- a/web/test/playerStore.test.ts +++ b/web/test/playerStore.test.ts @@ -3,33 +3,10 @@ import { get } from 'svelte/store'; import { GameSession } from '$lib/state/session'; import type { GameState } from '$lib/protocol/types'; import { SocketSequence } from './fake-socket'; +import { emptyGameState } from './fixtures'; function makeState(overrides: Partial<GameState> = {}): GameState { - return { - level: 1, - solo: false, - autoScenarioLevel: false, - difficulty: 1, - roundState: 0, - round: 1, - totalRounds: 1, - scenario: 'custom', - toastMessage: '', - scenarioSpecialRules: [], - scenarioSectionsAdded: [], - currentCampaign: 'Jaws of the Lion', - currentList: [], - currentAbilityDecks: [], - sanctuaryDeck: {}, - modifierDeck: {}, - modifierDeckAllies: {}, - lootDeck: {}, - unlockedClasses: [], - showAllyDeck: false, - allyDeckInOGGloom: true, - elementState: {}, - ...overrides - }; + return emptyGameState(overrides); } describe('GameSession.player (reactive player/spectator flag)', () => { diff --git a/web/test/state.test.ts b/web/test/state.test.ts index 3dada4f..c422810 100644 --- a/web/test/state.test.ts +++ b/web/test/state.test.ts @@ -10,33 +10,10 @@ import { get } from 'svelte/store'; import { GameSession, ownedIds } from '$lib/state/session'; import type { GameState } from '$lib/protocol/types'; import { SocketSequence } from './fake-socket'; +import { emptyGameState } from './fixtures'; function makeState(overrides: Partial<GameState> = {}): GameState { - return { - level: 1, - solo: false, - autoScenarioLevel: false, - difficulty: 1, - roundState: 0, - round: 1, - totalRounds: 1, - scenario: 'custom', - toastMessage: '', - scenarioSpecialRules: [], - scenarioSectionsAdded: [], - currentCampaign: 'Jaws of the Lion', - currentList: [], - currentAbilityDecks: [], - sanctuaryDeck: {}, - modifierDeck: {}, - modifierDeckAllies: {}, - lootDeck: {}, - unlockedClasses: [], - showAllyDeck: false, - allyDeckInOGGloom: true, - elementState: {}, - ...overrides - }; + return emptyGameState(overrides); } function welcome( |
