This commit is contained in:
Forrest 2026-09-28 01:56:25 -04:00
parent 746d218eda
commit e590baf28d
44 changed files with 8308 additions and 0 deletions

57
sim/src/deck.ts Normal file
View file

@ -0,0 +1,57 @@
import type { CardDef, CardKind, CardPool } from './cards.ts';
import { shuffle, type Rng } from './rng.ts';
import type { RulesConfig } from './rules.ts';
export interface DeckList {
avatars: string[];
servers: string[];
/** Executions, Hardware and Programs. */
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'], rules.deck.avatars);
part('Servers', deck.servers, ['server'], rules.deck.servers);
part('Deck', deck.main, MAIN_KINDS, rules.deck.main);
const copies = new Map<string, number>();
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<string>(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);
};
return {
avatars: sample(['avatar'], rules.deck.avatars),
servers: sample(['server'], rules.deck.servers),
main: sample(MAIN_KINDS, rules.deck.main),
};
}