INNER CODE UNIT · JavaScript
chooseWeightedCard
Sisyphe42/ReignsAgent · packages/core/src/index.js:561
function chooseWeightedCard(cards, state, rng) {
const weighted = cards.map((card) => ({
card,
weight: Math.max(0, (card.weight ?? 1) + (state.cardWeights[card.id] ?? 0))
}));
const total = weighted.reduce((sum, entry) => sum + entry.weight, 0);
if (total <= 0) {
return cards[0];
}
let cursor = rng() * total;
for (const entry of weighted) {
cursor -= entry.weight;
if (cursor < 0) {
return entry.card;
}
}