summaryrefslogtreecommitdiff
path: root/web/test/deckHelpers.test.ts
blob: 8aef3859837480bc3d9763bc552aa9c54947b6d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
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);
	});
});