summaryrefslogtreecommitdiff
path: root/web/test
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-16 22:19:39 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-16 22:19:39 +0100
commit94e2850fb73005f3fb30af8489905e5cdfb6fac5 (patch)
tree1aea8e7e6683af770f0c57c0fb654003778c9f16 /web/test
parent4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (diff)
Phase 4: cards and decks (M4)
Full card play in the browser: ability-line rendering, monster ability decks, the full modifier-deck (AMD) suite, and the loot deck — all server commands, faithful to the reference flows and layout. Web (Svelte 5): - Line renderer + in-game translations: $lib/game/line/ renders the reference line_builder output (emphasis, range markers, element styling); gameI18n.ts loads the /i18n/ in-game ability-text tables (the client-side TranslationService equivalent) - Card components: stat cards, monster ability cards (OG + FH styles, rendered lines, element/flying tokens), modifier cards (gfx resolver incl. P<n> perk graphics), loot cards (party-size value rules, owner, enhancements) - Monster ability decks: AbilityCardSlot in each monster row (front of the current card while active in playTurns, else the back with the draw-pile count); AbilityCardsMenu (reveal top cards, draw extra, extra shuffle, activate/inactivate, drag-reorder, remove); card zoom - Modifier decks: ModifierDeckWidget (tap to draw, face-up revealed top card, empty-box class icon for the current character's own deck, discard stack); ModifierDeckHeader (bad omen, corrosive spew, ±1/−2/+0, imbue 1/2, reveal with the Cassandra 8-button cap, save/don't-save revealed cards, removed count, Hail perk, CS sanctuary/party cards, faction icons, bless/curse and the empower/enfeeble counters); ModifierDeckMenu (draw-pile drag-reorder + send-to-bottom/shuffle/remove, discard remove/return-top, removed pile with return, faction grid with gray-out, perks menu with the Frosthaven opt-in); card zoom - Loot deck: LootDeckWidget (player-gated draw, current-character icon, discard stack, hidden when both piles empty); LootCardsMenu (set owner, per-character loot totals, add card, enhance with the reference material/herb/coin splits, special cards 1418/1419, return top/bottom) - Bottom DeckArea: loot deck left; the Character Decks toggle with the reference open-state cycling (oneOpen/allOpen/noOpen per round state; one-deck view for the current character during playTurns); ally deck behind shouldShowAlliesDeck; global deck - Pure helper modules ported from the reference: rules.ts (FH card styling, inactive-for-rule, ally-deck gate, deck resolution), modifierDeck.ts (pile derivations, faction cards), perks.ts (active perk set, card-text tokens, descriptions, add/remove gating), cards/lootCard.ts (values + per-character totals) - App wiring: campaign data loaded on currentCampaign change (guarded against out-of-order fetches); ability/AMD/loot menus and zooms driven by live-derived state so open menus track pile changes; Escape closes every dialog Server: - /i18n/ static mount: the in-game ability-text translation files the card renderer resolves (the reference TranslationService data) - Loot deck JSON gains pools (pool card ids per pool — the client derives card gfx from pool key + index and reads the enhancements map; ids only, since pool cards are the same live instances that mutate in the piles) - Modifier deck JSON gains removables (the counter totals the header reads) plus load-time round-trip for saves written before the field existed Docs: - PLAN.md: Phase 3 and Phase 4 marked complete (corrected the 'character ability decks' mislabel — ability decks are monster-only), progress log entries for M3 and M4 svelte-check 0 errors; web tests 177/177; build OK; dart analyze 0 errors; dart test 592/592; scripts/ci.sh green.
Diffstat (limited to 'web/test')
-rw-r--r--web/test/deckHelpers.test.ts486
-rw-r--r--web/test/fixtures.ts96
-rw-r--r--web/test/gameDataClient.test.ts10
-rw-r--r--web/test/gameLogic.test.ts26
-rw-r--r--web/test/line/frosthavenConverter.test.ts156
-rw-r--r--web/test/line/lineParser.test.ts169
-rw-r--r--web/test/line/statApplier.test.ts100
-rw-r--r--web/test/line/statCalculator.test.ts41
-rw-r--r--web/test/playerStore.test.ts27
-rw-r--r--web/test/state.test.ts27
10 files changed, 1080 insertions, 58 deletions
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(