import type { CardDef, CardKind, CardPool } from './cards.ts'; import { shuffle, type Rng } from './rng.ts'; import { avatarsOutside, type RulesConfig } from './rules.ts'; export interface DeckList { avatars: string[]; servers: string[]; /** Executions, Hardware and Programs (and Avatars, when recruiting). */ main: string[]; } const MAIN_KINDS: CardKind[] = ['program', 'hardware', 'execution']; /** Problems with a deck list; empty when it's legal. */ export function validateDeck(pool: CardPool, deck: DeckList, rules: RulesConfig): string[] { const errors: string[] = []; const part = (label: string, names: string[], kinds: CardKind[], size: number) => { if (names.length !== size) errors.push(`${label}: ${names.length} cards, needs ${size}`); for (const name of names) { const card = pool.byName.get(name); if (!card) errors.push(`${label}: unknown card "${name}"`); else if (!kinds.includes(card.kind)) errors.push(`${label}: "${name}" is a ${card.kind}`); } }; part('Avatars', deck.avatars, ['avatar'], avatarsOutside(rules)); part('Servers', deck.servers, ['server'], rules.deck.servers); part('Deck', deck.main, rules.recruit.on ? [...MAIN_KINDS, 'avatar'] : MAIN_KINDS, rules.deck.main); const copies = new Map(); for (const name of [...deck.avatars, ...deck.servers, ...deck.main]) { copies.set(name, (copies.get(name) ?? 0) + 1); } for (const [name, n] of copies) { if (n > rules.deck.maxCopies) errors.push(`${n} copies of "${name}", max ${rules.deck.maxCopies}`); } return errors; } /** A random legal deck: every card in the pool is equally likely, up to the copy limit. */ export function randomDeck( pool: CardPool, rng: Rng, rules: RulesConfig, include: (card: CardDef) => boolean = () => true, ): DeckList { const sample = (kinds: CardKind[], size: number): string[] => { const names = pool.all .filter((c) => kinds.includes(c.kind) && include(c)) .flatMap((c) => Array(rules.deck.maxCopies).fill(c.name)); if (names.length < size) throw new Error(`Not enough ${kinds.join('/')} cards for a deck`); return shuffle(rng, names).slice(0, size); }; if (rules.recruit.on) { const k = rules.recruit.avatarsInDeck; const avatars = sample(['avatar'], 1 + k); const servers = sample(['server'], rules.deck.servers); return { avatars: avatars.slice(0, 1), servers, main: shuffle(rng, [...avatars.slice(1), ...sample(MAIN_KINDS, rules.deck.main - k)]) }; } return { avatars: sample(['avatar'], rules.deck.avatars), servers: sample(['server'], rules.deck.servers), main: sample(MAIN_KINDS, rules.deck.main), }; }