diff --git a/lib/items.ts b/lib/items.ts index b459d69..d57b100 100644 --- a/lib/items.ts +++ b/lib/items.ts @@ -10,29 +10,34 @@ export function getRandomItem(deck: Item[], played: Item[]): Item { const [fromYear, toYear] = periods[Math.floor(Math.random() * periods.length)]; const avoidPeople = Math.random() > 0.5; + const candidates = deck.filter((candidate) => { - if (avoidPeople && candidate.instance_of.includes("human")) { - return false; - } - if (candidate.year < fromYear || candidate.year > toYear) { - return false; - } - if (tooClose(candidate, played)) { - return false; - } + if (avoidPeople && candidate.instance_of.includes("human")) return false; + if (candidate.year <= fromYear || candidate.year >= toYear) return false; + if (played.some((p) => p.year === candidate.year)) return false; return true; }); + const betterCandidates = candidates.filter( + (candidate) => !tooClose(candidate, played) + ); + + if (betterCandidates.length > 0) { + return betterCandidates[ + Math.floor(Math.random() * betterCandidates.length) + ]; + } + if (candidates.length > 0) { return candidates[Math.floor(Math.random() * candidates.length)]; } + return deck[Math.floor(Math.random() * deck.length)]; } function tooClose(item: Item, played: Item[]) { - let distance = (played.length < 40) ? 5 : 1; - if (played.length < 11) - distance = 110 - 10 * played.length; + let distance = played.length < 40 ? 5 : 1; + if (played.length < 11) distance = 55 - 5 * played.length; return played.some((p) => Math.abs(item.year - p.year) < distance); }