// Rôle : vérifie les données, les réglages et les règles pures des Expéditions Sokko TCG. import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { test } from "node:test"; import { prepareVersionedCatalog } from "../services/cards/catalog.js"; import { DESTINATION_SPECIALTIES, loadExpeditionDestinations, validateExpeditionDestinations } from "../services/cards/expedition-content.js"; import { applyHazards, cardPower, drawExpeditionDay, editionExpeditionData, efficiency, evaluateTeam, expectedLoot, maxLevel, requirementsFor, resolveDayEntry, rollLoot, roundStochastic, scoreExpedition, splitPower, STAT_IDS, teamStats, upgradeCost, gainProgress, equipmentBonus, LINEAGES, resonancesOf, teamSynergy, unlockedSlots, bonusLootPct, pickItems, HIDDEN_ITEMS, teamPowers, travelHours, rollRequirementFactor, bonusSlotLevel, levelCount, starsForLevel, planStats, vocationProfile, clampAllocation, allocationError, levelPoints, maxStatPoints, expertiseOf } from "../services/cards/expedition-rules.js"; import { drawCollectionCard } from "../services/cards/game-rules.js"; import { DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, readPath, validateExpeditionSettings } from "../services/cards/expedition-settings.js"; import { EXPEDITION_SETTING_GROUPS, expeditionSettingLabel } from "../website/src/features/cards/admin/expeditionSettingFields.js"; import { expeditionsPending, guildQuests } from "../website/src/features/cards/guildQuests.js"; const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")); const catalog = prepareVersionedCatalog(rawCatalog); const destinationsPath = "services/cards/content/expedition-destinations.json"; const destinations = loadExpeditionDestinations(destinationsPath, catalog); const destinationIds = destinations.map((destination) => destination.id); const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinationIds); const profile = (bravoure, endurance, fortune, orientation) => ({ bravoure, endurance, fortune, orientation }); // La Collection affiche les cartes dans l'ordre du catalogue : chaque collection va de la plus rare à la plus commune. test("every collection lists its cards from the rarest to the most common", () => { const rank = new Map(rawCatalog.rarities.map((rarity, index) => [rarity.id, index])); const rarityOf = new Map(rawCatalog.editions.map((edition) => [edition.cardId, edition.rarity])); for (const collection of rawCatalog.collections) { const ranks = rawCatalog.cards.filter((card) => card.collectionId === collection.id).map((card) => rank.get(rarityOf.get(card.id))); assert.ok(ranks.every((value, index) => index === 0 || value <= ranks[index - 1]), `${collection.id} : cartes de la plus rare à la plus commune`); } }); test("every catalog card carries expedition tags and every collection a profile", () => { const tagIds = new Set(rawCatalog.expeditionTags.map((tag) => tag.id)); const teamCards = rawCatalog.cards.filter((card) => card.kind !== "destination"); assert.ok(teamCards.every((card) => card.expedition.tags.length >= 1 && card.expedition.tags.every((tag) => tagIds.has(tag)))); assert.ok(rawCatalog.collections.every((collection) => STAT_IDS.reduce((sum, stat) => sum + collection.expedition.profile[stat], 0) === 100)); // Aucune étiquette inutilisée : le vocabulaire reste celui des cartes. const used = new Set(teamCards.flatMap((card) => card.expedition.tags)); assert.deepEqual(rawCatalog.expeditionTags.filter((tag) => !used.has(tag.id)), []); }); // Carte de destination : rare, sans données d'expédition, liée à une destination existante ; elle ne part jamais en équipe. test("a destination card is a rare that unlocks a destination and never joins a team", () => { // Les Courants de Lumière perdent leur carte du catalogue, remplacée par celle du test. const freeDestination = "light-currents"; const withCard = (card, rarity = "rare") => { const copy = structuredClone(rawCatalog); copy.cards = copy.cards.filter((item) => item.destinationId !== freeDestination); copy.editions = copy.editions.filter((edition) => copy.cards.some((item) => item.id === edition.cardId)); copy.cards.push({ id: "card-light-currents", collectionId: "watchers-logbooks", name: "Une destination", description: "Une destination.", kind: "destination", destinationId: freeDestination, ...card }); copy.editions.push({ id: "card-light-currents-standard", cardId: "card-light-currents", rarity, finishIds: ["standard"], promotional: false }); return copy; }; const prepared = prepareVersionedCatalog(withCard({})); assert.equal(editionExpeditionData(prepared, "card-light-currents-standard", 0, settings), null); assert.ok(validateExpeditionDestinations(JSON.parse(JSON.stringify(destinations.map(({ ...item }) => item))), prepared)); assert.throws(() => prepareVersionedCatalog(withCard({}, "epic")), /must be rare/); assert.throws(() => prepareVersionedCatalog(withCard({ expedition: { tags: ["theme:voyage"] } })), /never joins a team/); assert.throws(() => prepareVersionedCatalog(withCard({ destinationId: undefined })), /needs a destinationId/); assert.throws(() => validateExpeditionDestinations(destinations, prepareVersionedCatalog(withCard({ destinationId: "nowhere" }))), /unknown destination nowhere/); }); test("catalog validation refuses broken expedition data", () => { const unknownTag = structuredClone(rawCatalog); unknownTag.cards[0].expedition.tags = ["theme:inconnu"]; assert.throws(() => prepareVersionedCatalog(unknownTag), /unknown expedition tag theme:inconnu/); const noTags = structuredClone(rawCatalog); delete noTags.cards[0].expedition; assert.throws(() => prepareVersionedCatalog(noTags), /needs 1 to 8 expedition tags/); const repeated = structuredClone(rawCatalog); repeated.cards[0].expedition.tags = ["theme:voyage", "theme:voyage"]; assert.throws(() => prepareVersionedCatalog(repeated), /repeats an expedition tag/); const badProfile = structuredClone(rawCatalog); badProfile.cards[0].expedition.profile = profile(50, 50, 10, 0); assert.throws(() => prepareVersionedCatalog(badProfile), /summing to 100/); const lopsided = structuredClone(rawCatalog); lopsided.cards[0].expedition.profile = profile(60, 20, 10, 10); assert.throws(() => prepareVersionedCatalog(lopsided), /at most 50 each/); const noCollectionProfile = structuredClone(rawCatalog); delete noCollectionProfile.collections[0].expedition; assert.throws(() => prepareVersionedCatalog(noCollectionProfile), /needs an expedition profile/); const badTagId = structuredClone(rawCatalog); badTagId.expeditionTags.push({ id: "Voyage", label: "Voyage" }); assert.throws(() => prepareVersionedCatalog(badTagId), /family:name id/); // Stat de synergie : obligatoire à égalité et pour un objet à pouvoir, et toujours une stat que l'objet apporte. const common = (cards, id) => cards.find((card) => card.id === id); const tie = structuredClone(rawCatalog); delete common(tie.cards, "void-scale").expedition.equipment.synergyStat; assert.throws(() => prepareVersionedCatalog(tie), /ties on its best stat and needs a synergyStat/); const elsewhere = structuredClone(rawCatalog); common(elsewhere.cards, "void-scale").expedition.equipment.synergyStat = "fortune"; assert.throws(() => prepareVersionedCatalog(elsewhere), /a stat its equipment raises/); const power = structuredClone(rawCatalog); delete common(power.cards, "mad-compass").expedition.equipment.synergyStat; assert.throws(() => prepareVersionedCatalog(power), /power equipment needs a synergyStat/); }); test("destinations order the four stats and stay satisfiable by rare or better cards", () => { const visible = destinations.filter((destination) => !destination.hidden); assert.equal(visible.length, 15); assert.deepEqual(destinations.filter((destination) => destination.hidden).map((destination) => destination.id), ["crimson-passage", "lost-observatory"]); // Chaque couple (stat principale, seconde stat) a au moins une destination : les profils restent variés. assert.equal(new Set(visible.map((destination) => destination.stats.slice(0, 2).join("+"))).size, 12); const broken = (change) => { const copy = structuredClone(destinations); change(copy[0]); return () => validateExpeditionDestinations(copy, catalog); }; assert.throws(broken((destination) => { destination.stats = ["bravoure", "bravoure", "fortune", "orientation"]; }), /order the four stats/); assert.throws(broken((destination) => { destination.conditions = [{ type: "tag", tag: "personnage:ours" }]; }), /fewer than 3/); assert.throws(broken((destination) => { destination.dangers[0].unlessTags = ["theme:inconnu"]; }), /known counter tags/); assert.throws(broken((destination) => { destination.coverCardId = "missing"; }), /unknown cover card/); assert.throws(() => validateExpeditionDestinations(destinations.map((destination) => ({ ...destination, hidden: true })), catalog), /visible destination/); }); test("expedition settings merge stored values with defaults and validate bounds and cross rules", () => { assert.equal(validateExpeditionSettings(settings, destinationIds), null); assert.equal(settings.enabled, false); assert.deepEqual(settings.destinations[destinationIds[0]], { active: true, weight: 1 }); // Champ manquant ou invalide : valeur par défaut, signalée ; clé inconnue : supprimée. const invalid = []; const merged = mergeExpeditionSettings({ power: { rare: 45, cap: "x" }, extra: 1, destinations: { [destinationIds[0]]: { active: false, weight: 3 }, gone: { active: true, weight: 1 } } }, destinationIds, (path) => invalid.push(path)); assert.equal(merged.power.rare, 45); assert.equal(merged.power.cap, 100); assert.deepEqual(invalid, ["power.cap"]); assert.equal("extra" in merged, false); assert.equal("gone" in merged.destinations, false); assert.deepEqual(merged.destinations[destinationIds[0]], { active: false, weight: 3 }); // Chaque champ du schéma a une valeur par défaut valide. for (const field of EXPEDITION_SETTINGS_SCHEMA) assert.notEqual(readPath(DEFAULT_EXPEDITION_SETTINGS, field.path), undefined, field.path); const withChange = (path, value) => { const copy = structuredClone(settings); const keys = path.split("."); keys.slice(0, -1).reduce((node, key) => node[key], copy)[keys.at(-1)] = value; return copy; }; assert.match(validateExpeditionSettings(withChange("day.destinationsPerDay", 0), destinationIds), /day\.destinationsPerDay/); assert.match(validateExpeditionSettings(withChange("durations.hours", [6, 2, 12]), destinationIds), /croissantes/); assert.match(validateExpeditionSettings(withChange("requirements.star3", [1, 2]), destinationIds), /3 entiers/); assert.match(validateExpeditionSettings(withChange("score.successPct", 130), destinationIds), /Réussite < Triomphe/); assert.match(validateExpeditionSettings(withChange("stars", { min: 4, max: 2 }), destinationIds), /étoile minimale/); assert.match(validateExpeditionSettings(withChange("power.rare", 120), destinationIds), /plafond/); assert.match(validateExpeditionSettings(withChange("destinations", { unknown: { active: true, weight: 1 } }), destinationIds), /inconnue/); const next = withChange("loot.eclatsPerHourCents", 300); next.destinations[destinationIds[1]].weight = 4; assert.deepEqual(diffExpeditionSettings(settings, next), [ { path: "loot.eclatsPerHourCents", previous: 200, next: 300 }, { path: `destinations.${destinationIds[1]}.weight`, previous: 1, next: 4 } ]); }); test("power grows with levels up to the shared cap and splits exactly by profile", () => { assert.equal(cardPower("rare", 0, settings), 40); assert.equal(cardPower("rare", 4, settings), 60); assert.equal(cardPower("rare", 99, settings), 100); assert.equal(cardPower("common", 3, settings), 0); assert.deepEqual(["rare", "epic", "legendary", "mythic"].map((rarity) => maxLevel(rarity, settings)), [12, 9, 6, 3]); assert.deepEqual(splitPower(40, profile(25, 25, 20, 30)), { bravoure: 10, endurance: 10, fortune: 8, orientation: 12 }); const odd = splitPower(55, profile(33, 33, 17, 17)); assert.equal(Object.values(odd).reduce((sum, value) => sum + value, 0), 55); // Une mythique garde sa propre rareté, mais le profil et les étiquettes de sa carte. const legendary = editionExpeditionData(catalog, "starvoid-dragon-standard", 0, settings); assert.equal(legendary.power, 70); assert.deepEqual(legendary.tags, ["personnage:dragon", "lieu:nebuleuse", "lieu:soleil"]); assert.equal(editionExpeditionData(catalog, "dragon-constellation-standard", 0, settings), null); }); test("requirements scale per slot, cards add their stats, hazards and conditions weigh on the score", () => { const destination = destinations.find((item) => item.id === "light-currents"); // Une carte seule : la part d'une place ; un groupe : une part par place, chaque joueur en plus relevant celle-ci de 10 %. assert.deepEqual(requirementsFor(destination, 2, 1, settings), [ { stat: "orientation", main: true, soloValue: 11, value: 11 }, { stat: "bravoure", main: false, soloValue: 10, value: 10 } ]); assert.deepEqual(requirementsFor(destination, 2, 4, settings).map((item) => item.value), [57, 52]); // Pas de rôle : chaque carte apporte ses stats telles quelles. const slot = { stats: { bravoure: 10, endurance: 10, fortune: 10, orientation: 12 }, tags: [], collectionId: "primordial-nebula" }; assert.deepEqual(teamStats([slot, slot]), { bravoure: 20, endurance: 20, fortune: 20, orientation: 24 }); // 12 h sans Endurance : −15 % ; Endurance suffisante : aucun malus. Danger non paré : −20 %, moins le bouclier. assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 0.85); assert.equal(applyHazards({ bravoure: 10, endurance: 24, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 1); const danger = { id: "d", label: "D", stat: "bravoure", unlessTags: ["theme:hiver"] }; assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 8); assert.equal(applyHazards({ bravoure: 10, endurance: 28, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 9); assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: true }] }, settings).stats.bravoure, 10); assert.equal(efficiency(0.5, settings), 0.5); assert.equal(efficiency(1.5, settings), 1.25); assert.equal(efficiency(3, settings), 1.5); const requirements = [{ stat: "bravoure", main: true, value: 10 }, { stat: "fortune", main: false, value: 10 }]; const full = scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 } }, settings); assert.equal(full.scorePct, 100); assert.equal(full.tier, "success"); assert.equal(scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 }, conditionMet: false }, settings).scorePct, 75); assert.equal(scoreExpedition({ requirements, stats: { bravoure: 40, fortune: 40 } }, settings).tier, "triumph"); assert.equal(scoreExpedition({ requirements, stats: { bravoure: 5, fortune: 5 } }, settings).tier, "struggle"); }); test("one more star never raises the score of the same team", () => { const destination = destinations[0]; const entry = { condition: destination.conditions[0], dangers: destination.dangers }; // Équipe faible sur la stat principale, forte sur la seconde : sans la règle, 2 ★ ferait mieux que 1 ★. const slots = [ { stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, tags: [], collectionId: "primordial-nebula" }, { stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, tags: [], collectionId: "primordial-nebula" } ]; const scores = [1, 2, 3, 4].map((stars) => evaluateTeam({ destination, entry, stars, durationIndex: 0, slots }, settings)); for (let index = 1; index < scores.length; index += 1) assert.ok(scores[index].scorePct <= scores[index - 1].scorePct); assert.equal(scores[1].limitedByStars, 1); }); test("experts are different cards that each cover a required stat for two places on their own", () => { const destination = { stats: ["bravoure", "orientation", "fortune", "endurance"] }; const card = (stats, cardId) => ({ cardId, stats: { bravoure: 0, endurance: 0, fortune: 0, orientation: 0, ...stats }, tags: [], collectionId: "primordial-nebula" }); // Duo en 4 ★ : l'Expertise se mesure sur l'exigence d'un solo, 25 en Bravoure (donc 50) et 23 en Orientation (donc 46), même si // le groupe relève l'exigence de chaque place. const requirements = requirementsFor(destination, 4, 2, settings); assert.deepEqual(requirements.map((item) => [item.soloValue, item.value]), [[25, 55], [23, 51], [18, 40]]); const brave = card({ bravoure: 55, orientation: 60 }, "brave"); const guide = card({ orientation: 51 }, "guide"); // Une carte forte partout n'est experte que d'une stat : avec un guide, les deux stats sont tenues. assert.deepEqual(expertiseOf([brave, guide], requirements, settings), [ { stat: "bravoure", slotIndex: 0, cardId: "brave" }, { stat: "orientation", slotIndex: 1, cardId: "guide" } ]); assert.deepEqual(expertiseOf([brave, card({ orientation: 45 }, "short")], requirements, settings).map((item) => item.stat), ["bravoure"]); // Deux spécialistes de la même stat n'en tiennent qu'une. assert.equal(expertiseOf([card({ bravoure: 60 }, "a"), card({ bravoure: 60 }, "b")], requirements, settings).length, 1); // Le bonus s'ajoute hors du plafond des synergies : 8 % par stat tenue. const entry = { condition: null, dangers: [] }; const input = { destination, entry, stars: 2, durationIndex: 0, slots: [card({ bravoure: 22, orientation: 4 }, "x")], synergyPct: 10 }; const expert = evaluateTeam(input, settings); const without = evaluateTeam(input, { ...settings, expertise: { ...settings.expertise, scorePct: 0 } }); assert.deepEqual(expert.expertise.map((item) => item.stat), ["bravoure"]); assert.equal(expert.expertisePct, 8); assert.equal(without.synergyPct, 10); assert.ok(Math.abs(expert.scorePct / without.scorePct - 1.08) < 1e-9); }); test("a mythic spreads as many level points as its legendary, from a higher start", () => { assert.equal(levelPoints("legendary", 0, settings), 0); assert.equal(levelPoints("mythic", 0, settings), 15); assert.equal(levelPoints("mythic", maxLevel("mythic", settings), settings), levelPoints("legendary", maxLevel("legendary", settings), settings)); assert.equal(levelPoints("rare", maxLevel("rare", settings), settings), 60); }); test("loot is proportional to the chosen duration and rounds without changing its average", () => { const short = expectedLoot({ hours: 2, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings); const long = expectedLoot({ hours: 12, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings); assert.equal(long.eclats / 12, short.eclats / 2); assert.equal(short.eclats, 5.2); // Fortune : +2 % par point moyen par place, plafonné ; destinations bonus : multiplicateur propre. assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 20, slotCount: 2 }, settings).fortuneBonusPct, 20); assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 200, slotCount: 2 }, settings).fortuneBonusPct, 50); assert.equal(expectedLoot({ hours: 4, stars: 1, tier: "success", fortune: 0, slotCount: 2, bonusSlot: 6 }, settings).eclats, 10); assert.equal(roundStochastic(2.3, () => 0), 3); assert.equal(roundStochastic(2.3, (max) => max - 1), 2); assert.equal(roundStochastic(4, () => 0), 4); assert.deepEqual(rollLoot({ eclats: 1.5, stardust: 0.2, cards: 5 }, settings, () => 0), { eclats: 2, stardust: 1, cards: settings.loot.maxCards }); }); // Paysage d'une destination : facultatif, toujours un WebP du dossier des destinations, et présent sur le disque. test("destination landscapes point to existing images of their folder", async () => { for (const destination of destinations.filter((item) => item.image)) await readFile(`website/public${destination.image}`); await readFile("website/public/static/img/expeditions/brush-mask.webp"); const raw = JSON.parse(await readFile(destinationsPath, "utf8")); assert.throws(() => validateExpeditionDestinations([{ ...raw[0], image: "/static/img/cards/other.webp" }, ...raw.slice(1)], catalog), /image must be/); const linked = raw.findIndex((destination) => destination.rewardCollectionId); const withSpecialty = raw.map((destination, index) => (index === linked ? { ...destination, specialty: ["eclats", "cards"] } : destination)); assert.throws(() => validateExpeditionDestinations(withSpecialty, catalog), /cannot have a specialty/); const free = raw.findIndex((destination) => !destination.rewardCollectionId && !destination.hidden); for (const specialty of ["eclats", [], ["eclats", "eclats"], ["eclats", "gold"], ["eclats", "stardust", "cards"]]) { assert.throws(() => validateExpeditionDestinations(raw.map((destination, index) => (index === free ? { ...destination, specialty } : destination)), catalog), /one or two different values/); } // Une destination liée par collection : celle de sa carte de destination des paquets. assert.deepEqual(raw.filter((destination) => destination.rewardCollectionId).map((destination) => [destination.id, destination.rewardCollectionId]).sort(), [["cosmic-cloud-heart", "primordial-nebula"], ["grand-astral-hall", "astral-genesis"], ["level-isles", "dream-arcade"], ["reunited-isles-feast", "long-night"]]); const crater = raw.findIndex((destination) => destination.id === "scale-crater"); assert.throws(() => validateExpeditionDestinations(raw.map((destination, index) => (index === crater ? { ...destination, specialty: undefined, rewardCollectionId: "long-night" } : destination)), catalog), /collection of the destination card/); // Destinations non liées : chaque profil de butin possible une fois et une seule (chaque spécialité simple, chaque paire, une neutre). const unlinked = raw.filter((destination) => !destination.hidden && !destination.rewardCollectionId); const profiles = unlinked.map((destination) => (destination.specialty ? [...destination.specialty].sort().join("+") : "neutre")).sort(); const kinds = [...DESTINATION_SPECIALTIES].sort(); const pairs = kinds.flatMap((kind, index) => kinds.slice(index + 1).map((other) => `${kind}+${other}`)); assert.deepEqual(profiles, [...kinds, ...pairs, "neutre"].sort()); }); // Spécialités de butin : une récompense favorisée ×boostPct (les autres ×otherPct), ou deux ×pairBoostPct (les deux autres // ×pairOtherPct), cartes de collection comprises ; rien sans spécialité. Une carte de collection suit les taux de rareté, puis // favorise les manquantes. test("destination specialties raise one or two rewards and lower the others", () => { const loot = (specialty) => expectedLoot({ hours: 6, stars: 2, tier: "success", fortune: 0, slotCount: 2, specialty }, settings); const neutral = loot(null); const { boostPct, otherPct, pairBoostPct, pairOtherPct } = settings.specialty; const ratio = (value, reference, pct) => Math.abs(value - reference * pct / 100) < 1e-9; const single = loot(["eclats"]); assert.ok(ratio(single.eclats, neutral.eclats, boostPct) && ratio(single.stardust, neutral.stardust, otherPct)); assert.ok(ratio(single.cards, neutral.cards, otherPct) && ratio(single.objects, neutral.objects, otherPct)); const pair = loot(["cards", "items"]); assert.ok(ratio(pair.cards, neutral.cards, pairBoostPct) && ratio(pair.objects, neutral.objects, pairBoostPct)); assert.ok(ratio(pair.eclats, neutral.eclats, pairOtherPct) && ratio(pair.stardust, neutral.stardust, pairOtherPct)); // Une rareté tirée avec les taux de la collection, puis une carte pondérée : la manquante (b) pèse 200, la possédée (a) 100. const mini = { collections: [{ id: "c", active: true, dropWeights: { rare: 1 } }], cards: [{ id: "a", collectionId: "c" }, { id: "b", collectionId: "c" }], editions: [{ id: "a1", cardId: "a", rarity: "rare" }, { id: "b1", cardId: "b", rarity: "rare" }] }; const weightOf = (edition) => (edition.id === "a1" ? 100 : 200); assert.equal(drawCollectionCard(mini, "c", (max) => (max === 300 ? 99 : 0), { weightOf }), "a1"); assert.equal(drawCollectionCard(mini, "c", (max) => (max === 300 ? 100 : 0), { weightOf }), "b1"); assert.equal(drawCollectionCard({ ...mini, collections: [{ ...mini.collections[0], active: false }] }, "c", () => 0), null); }); // La difficulté se tire avec les destinations : un niveau de chaque, puis la suite recommence. Un niveau donne les mêmes étoiles, // qu'on parte seul ou en groupe. test("each daily destination draws a difficulty level, one of each", () => { assert.equal(levelCount(settings), 5); assert.deepEqual([0, 1, 2, 3, 4].map((level) => starsForLevel(level, settings)), [1, 2, 3, 4, 5]); assert.equal(starsForLevel(9, settings), settings.stars.max); for (const random of [() => 0, (max) => max - 1, (max) => Math.floor(max / 2)]) { assert.deepEqual(drawExpeditionDay(destinations, settings, [], random).map((entry) => entry.level).sort(), [0, 1, 2, 3]); } // Limité aux destinations débloquées : avec deux destinations, seulement les deux premiers niveaux. const two = drawExpeditionDay(destinations, settings, [], (max) => max - 1, new Set(["light-currents", "great-void"])); assert.deepEqual(two.map((entry) => entry.destinationId).sort(), ["great-void", "light-currents"]); assert.deepEqual(two.map((entry) => entry.level).sort(), [0, 1]); assert.deepEqual(drawExpeditionDay(destinations, settings, [], () => 0, new Set()), []); const six = drawExpeditionDay(destinations, { ...settings, day: { ...settings.day, destinationsPerDay: 6 } }, [], () => 0).map((entry) => entry.level); assert.deepEqual(six.slice(0, 5).sort(), [0, 1, 2, 3, 4]); assert.deepEqual(six.slice(5), six.slice(0, 1)); // Destinations bonus : la Carte céleste au plus haut niveau du jour du joueur, l'Étoile guide juste en dessous (jamais sous le // premier), la destination cachée au plus haut du jeu ; un tirage d'avant les niveaux prend celui de sa place. assert.deepEqual(["5", "6", "hidden"].map((slot) => bonusSlotLevel(slot, settings, 3)), [2, 3, 4]); assert.deepEqual(["5", "6", "hidden"].map((slot) => bonusSlotLevel(slot, settings, 1)), [0, 1, 4]); assert.deepEqual(["5", "6"].map((slot) => bonusSlotLevel(slot, settings, 0)), [0, 0]); assert.equal(bonusSlotLevel("6", settings, 9), 4); assert.equal(resolveDayEntry(destinations, { destinationId: destinations[0].id, conditionIndex: 0, dangerIndexes: [0, 0] }, 2).level, 2); }); test("the day draw picks active visible destinations and avoids yesterday's when it can", () => { const draw = drawExpeditionDay(destinations, settings, [], () => 0); assert.equal(draw.length, 4); assert.equal(new Set(draw.map((entry) => entry.destinationId)).size, 4); const recent = draw.map((entry) => entry.destinationId); const next = drawExpeditionDay(destinations, settings, recent, () => 0); assert.ok(next.every((entry) => !recent.includes(entry.destinationId))); // Destinations retirées ou de poids nul : jamais tirées. const closed = structuredClone(settings); for (const id of destinationIds.slice(1)) closed.destinations[id].active = false; assert.deepEqual(drawExpeditionDay(destinations, closed, [destinationIds[0]], () => 0).map((entry) => entry.destinationId), [destinationIds[0]]); // Le second danger diffère du premier quand la destination en a deux. assert.ok(draw.every((entry) => entry.dangerIndexes[0] !== entry.dangerIndexes[1])); const resolved = resolveDayEntry(destinations, draw[0]); assert.equal(resolved.entry.dangers.length, 2); assert.equal(resolveDayEntry(destinations, { destinationId: "missing", conditionIndex: 0, dangerIndexes: [0, 0] }), null); }); test("every server setting has its label in the administration, and nothing else", () => { const labelled = EXPEDITION_SETTING_GROUPS.flatMap((group) => group.fields.map((field) => field.path)); assert.deepEqual([...labelled].sort(), EXPEDITION_SETTINGS_SCHEMA.map((field) => field.path).sort()); assert.equal(expeditionSettingLabel(`destinations.${destinations[0].id}.weight`, destinations), `${destinations[0].name} · poids`); }); test("the guild shows expeditions when open and flags them once a day or when one is back", () => { const now = Date.parse("2026-11-15T10:00:00Z"); const summary = { enabled: true, running: 0, returned: 0, nextReturnAt: null, launchedToday: false, eligible: 3, busyEditions: [] }; assert.equal(expeditionsPending(summary, now), true); assert.equal(expeditionsPending({ ...summary, launchedToday: true }, now), false); // Une carte jouable suffit pour partir. assert.equal(expeditionsPending({ ...summary, eligible: 1 }, now), true); assert.equal(expeditionsPending({ ...summary, eligible: 0 }, now), false); assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now + 1000 }, now), false); assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now - 1000 }, now), true); // Un groupe à rejoindre attend le joueur ; son propre groupe en formation ne déclenche pas le rappel quotidien. assert.equal(expeditionsPending({ ...summary, launchedToday: true, joinableGroups: 1 }, now), true); assert.equal(expeditionsPending({ ...summary, forming: 1 }, now), false); // Fermées : la tuile disparaît, sauf tant qu'une expédition du joueur n'est pas terminée. assert.deepEqual(guildQuests({ expeditions: { ...summary, enabled: false } }, now), []); assert.equal(guildQuests({ expeditions: { ...summary, enabled: false, returned: 1 } }, now)[0].pending, true); }); test("a level costs Éclats by current power, so a rare pays the longer road to the same cap", () => { const total = (rarity) => { let sum = 0; for (let level = 0; upgradeCost(rarity, level, settings) != null; level += 1) sum += upgradeCost(rarity, level, settings); return sum; }; assert.equal(upgradeCost("rare", 0, settings), 10); assert.equal(upgradeCost("mythic", 0, settings), 100); assert.equal(upgradeCost("rare", 12, settings), null); assert.deepEqual(["rare", "epic", "legendary", "mythic"].map(total), [780, 720, 570, 330]); // Expérience de terrain : 10 % par retour, un niveau tous les 100 %, rien au-delà du plafond. assert.deepEqual(gainProgress({ level: 0, fieldXp: 95 }, "rare", { xpPct: 10 }, settings), { level: 1, fieldXp: 5 }); assert.deepEqual(gainProgress({ level: 2, fieldXp: 50 }, "mythic", { levels: 1, xpPct: 60 }, settings), { level: 3, fieldXp: 0 }); assert.deepEqual(gainProgress({ level: 11, fieldXp: 0 }, "rare", { levels: 5 }, settings), { level: 12, fieldXp: 0 }); }); test("commons carry equipment spread over a fixed budget, and every card has synergy partners", () => { const commons = rawCatalog.cards.filter((card) => card.expedition?.equipment?.stats); assert.equal(commons.length, 65); for (const card of commons) assert.equal(Object.values(card.expedition.equipment.stats).reduce((sum, value) => sum + value, 0), 6, card.id); // Les communes des Carnets des Veilleurs portent chacune un pouvoir, et aucune stat ; l'Adaptation est portée par une commune de // trois autres collections. const powered = rawCatalog.cards.filter((card) => card.expedition?.equipment?.power); assert.deepEqual(powered.filter((card) => card.collectionId === "watchers-logbooks").map((card) => card.expedition.equipment.power).sort(), ["fogBell", "longsight", "madCompass", "rations", "starNet", "stormLantern", "talisman", "treasureMap"]); assert.deepEqual(powered.filter((card) => card.expedition.equipment.power === "attunement").map((card) => card.collectionId).sort(), ["dream-arcade", "long-night", "primordial-nebula"]); assert.throws(() => prepareVersionedCatalog({ ...structuredClone(rawCatalog), cards: rawCatalog.cards.map((card) => (card.id === "mad-compass" ? { ...card, expedition: { ...card.expedition, equipment: { power: "flying" } } } : card)) }), /known power/); const broken = (change) => { const copy = structuredClone(rawCatalog); change(copy); return () => prepareVersionedCatalog(copy); }; const common = (copy) => copy.cards.find((card) => card.id === "star-compass"); assert.throws(broken((copy) => { common(copy).expedition.equipment.stats = { orientation: 7 }; }), /must spread 6 points/); assert.throws(broken((copy) => { common(copy).expedition.equipment.stats = { orientation: 4, fortune: 2 }; }), /must spread 6 points/); assert.throws(broken((copy) => { delete common(copy).expedition.equipment; }), /needs equipment stats/); assert.throws(broken((copy) => { copy.cards[0].expedition.equipment = { stats: { bravoure: 6 } }; }), /cannot be equipment/); assert.throws(broken((copy) => { copy.cards.find((card) => card.id === "cosmic-water-axolotl").expedition.tags = ["personnage:axolotl"]; }), /shares a tag with only/); // Lignées : chaque étiquette citée existe dans le vocabulaire. const tagIds = new Set(rawCatalog.expeditionTags.map((tag) => tag.id)); for (const [primordial, tags] of Object.entries(LINEAGES)) for (const tag of [primordial, ...tags]) assert.ok(tagIds.has(tag), tag); assert.ok(destinations.every((destination) => destination.themeTags.length > 0)); }); test("equipment opens with power, shared tags add synergy points, and teams earn affinity and resonances", () => { assert.deepEqual([40, 70, 99, 100].map((power) => unlockedSlots(power, settings)), [1, 2, 2, 3]); const bonus = equipmentBonus([ { stats: { orientation: 4, fortune: 2 }, tags: ["theme:voyage"] }, { stats: { bravoure: 8, endurance: -2 }, tags: ["theme:fete"] } ], ["theme:voyage", "personnage:loup"], settings); assert.deepEqual(bonus.stats, { bravoure: 8, endurance: -2, fortune: 2, orientation: 6 }); assert.deepEqual(bonus.pairs, ["theme:voyage", null]); // À égalité, la synergie va à la stat déclarée par l'objet, pas à la première dans l'ordre ; un objet à pouvoir a la sienne. const declared = equipmentBonus([ { stats: { bravoure: 3, orientation: 3 }, synergyStat: "orientation", tags: ["theme:voyage"] }, { stats: {}, synergyStat: "endurance", tags: ["theme:voyage"] } ], ["theme:voyage"], settings); assert.deepEqual(declared.stats, { bravoure: 3, endurance: 2, fortune: 0, orientation: 5 }); assert.deepEqual(declared.synergies.map((item) => item.stat), ["orientation", "endurance"]); const card = (cardId, collectionId, tags) => ({ cardId, collectionId, tags }); // Écho : le même personnage dans deux collections ; Lignée : un Primordial et une carte de son thème ; Thème partagé : deux cartes d'un thème. assert.deepEqual(resonancesOf([card("a", "primordial-nebula", ["personnage:hamster"]), card("b", "dream-arcade", ["personnage:hamster"])], settings), [{ type: "echo", key: "personnage:hamster" }]); assert.deepEqual(resonancesOf([card("a", "primordial-nebula", ["personnage:loup"]), card("b", "primordial-nebula", ["theme:aurores"])], settings), [{ type: "lineage", key: "personnage:loup" }]); assert.deepEqual(resonancesOf([card("a", "x", ["theme:hiver"]), card("b", "x", ["theme:hiver"])], settings), [{ type: "sisters", key: "theme:hiver" }]); // Une même carte ne forme pas seule une Lignée ; deux Résonances au plus. assert.deepEqual(resonancesOf([card("a", "x", ["personnage:loup", "theme:aurores"]), card("b", "y", ["theme:nuit"])], settings), []); // Une même paire de cartes ne forme qu'une Résonance, même si elle est liée de plusieurs façons. const pair = [card("a", "primordial-nebula", ["personnage:loup", "theme:hiver"]), card("b", "dream-arcade", ["personnage:loup", "theme:aurores", "theme:hiver"])]; assert.deepEqual(resonancesOf(pair, settings).map((item) => item.type), ["echo"]); // Avec une troisième carte, une autre paire peut former une seconde Résonance. const all = [...pair, card("c", "long-night", ["theme:aurores"])]; assert.deepEqual(resonancesOf(all, settings).map((item) => item.type), ["echo", "lineage"]); const destination = { themeTags: ["theme:hiver"] }; const synergy = teamSynergy({ destination, slots: all, cohesionPct: 10 }, settings); assert.equal(synergy.affinity, "theme:hiver"); // Affinité 10 + deux Résonances 20 + cohésion 10 = 40, plafonné à 25 ; la somme avant plafond reste visible. assert.equal(synergy.totalPct, 25); assert.equal(synergy.rawPct, 40); assert.equal(teamSynergy({ destination: { themeTags: ["lieu:vide"] }, slots: [card("a", "x", ["theme:nuit"])] }, settings).totalPct, 0); }); test("objects come by weight, hidden ones only with enough Orientation, and bonus destinations multiply the loot", () => { const counts = (orientationPerSlot, excluded = []) => { const seen = new Set(); let step = 0; // Hasard parcourant tout l'intervalle : chaque objet permis finit par sortir. for (let index = 0; index < 200; index += 1) pickItems(1, { orientationPerSlot, excluded }, settings, (max) => (step++ * 7) % max).forEach((id) => seen.add(id)); return seen; }; const closed = counts(0); assert.ok(HIDDEN_ITEMS.every((id) => !closed.has(id))); assert.ok(["anchor", "guideStar", "skyChart"].every((id) => closed.has(id))); const open = counts(15, ["plan"]); assert.ok(open.has("fragment") && open.has("engraving") && !open.has("plan")); assert.deepEqual([null, "5", "6", "hidden"].map((slot) => bonusLootPct(slot, settings)), [100, 100, 125, 150]); assert.equal(expectedLoot({ hours: 4, stars: 1, tier: "success", fortune: 0, slotCount: 2, bonusSlot: "hidden" }, settings).eclats, 12); assert.equal(expectedLoot({ hours: 10, stars: 1, tier: "success", fortune: 0, slotCount: 2 }, settings).objects, 0.5); }); test("powers trade an advantage for a cost and count once per team", () => { const destination = destinations[0]; const entry = { condition: destination.conditions[0], dangers: destination.dangers }; const slot = (powers = []) => ({ stats: { bravoure: 30, endurance: 30, fortune: 30, orientation: 30 }, tags: [], collectionId: "x", cardId: `c${powers.join()}`, powers }); assert.deepEqual(teamPowers([slot(["talisman"]), slot(["talisman", "starNet"])]), ["talisman", "starNet"]); const evaluate = (powers, stats) => evaluateTeam({ destination, entry, stars: 2, durationIndex: 0, slots: [{ ...slot(), stats }, { ...slot(), stats }], powers }, settings); const weak = { bravoure: 1, endurance: 1, fortune: 1, orientation: 1 }; const strong = { bravoure: 90, endurance: 90, fortune: 90, orientation: 90 }; // Talisman : un Retour difficile de justesse (score d'au moins 60 %) devient une Réussite, un échec net le reste ; jamais de Triomphe. const close = { bravoure: 8, endurance: 8, fortune: 8, orientation: 8 }; assert.ok(evaluate([], close).scorePct >= settings.powers.talismanFloorPct && evaluate([], close).tier === "struggle"); assert.equal(evaluate(["talisman"], close).tier, "success"); assert.equal(evaluate([], weak).tier, "struggle"); assert.equal(evaluate(["talisman"], weak).tier, "struggle"); assert.equal(evaluate(["talisman"], strong).tier, "success"); // Adaptation : +4 sur la stat exigée la plus faible de la carte qui le porte, choisie pour la destination. const attuned = evaluateTeam({ destination, entry, stars: 2, durationIndex: 0, slots: [{ ...slot(["attunement"]), stats: { bravoure: 10, endurance: 10, fortune: 10, orientation: 10, [destination.stats[1]]: 6 } }] }, settings); assert.deepEqual(attuned.attunement.map((item) => item.stat), [destination.stats[1]]); assert.equal(attuned.baseStats[destination.stats[1]], 10); // Carte au trésor : une part du score en moins ; Filet : un peu de Fortune en moins. const plain = evaluate([], { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }); assert.ok(Math.abs(evaluate(["treasureMap"], { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }).scorePct - plain.scorePct * 0.9) < 1e-9); // Filet : chaque place perd 2 de Fortune (deux places ici). assert.equal(evaluate(["starNet"], { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }).stats.fortune, plain.stats.fortune - 4); // Butin et trajet : la Boussole folle et les Provisions changent le butin, la Longue-vue et les Provisions le temps de trajet. const loot = (powers) => expectedLoot({ hours: 10, stars: 1, tier: "success", fortune: 0, slotCount: 2, powers }, settings); assert.equal(loot(["madCompass"]).eclats, loot([]).eclats * 1.3); // Coup de folie : les exigences réelles sont tirées entre 80 % et 130 % de celles affichées ; sans lui, elles ne changent pas. assert.equal(rollRequirementFactor([], settings, () => 0), 100); assert.deepEqual([rollRequirementFactor(["madCompass"], settings, () => 0), rollRequirementFactor(["madCompass"], settings, (max) => max - 1)], [80, 130]); const tenStats = { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }; const scaled = (pct) => evaluateTeam({ destination, entry, stars: 2, durationIndex: 0, slots: [{ ...slot(), stats: tenStats }], requirementFactorPct: pct }, settings).perRequirement.map((item) => item.value); const shown = requirementsFor(destination, 2, 1, settings).map((item) => item.value); assert.deepEqual(scaled(100), shown); assert.deepEqual(scaled(130), shown.map((value) => Math.round(value * 1.3))); // Provisions : un quart du trajet et un quart du butin en moins, donc le même butin par heure réelle. assert.equal(loot(["rations"]).eclats, loot([]).eclats * 0.75); // Longue-vue : +40 % de chance de carte et une carte de plus au plafond, pour un trajet un quart plus long. assert.ok(Math.abs(loot(["longsight"]).cards - loot([]).cards * 1.4) < 1e-9); assert.equal(loot(["longsight"]).cardCap, loot([]).cardCap + 1); assert.deepEqual([travelHours(6, [], settings), travelHours(6, ["longsight"], settings), travelHours(8, ["rations"], settings), travelHours(10, ["stormLantern"], settings)], [6, 7.5, 6, 11]); // Plafonds de butin : une tranche par 6 h choisies, au moins une. const capped = (hours) => expectedLoot({ hours, stars: 5, tier: "triumph", fortune: 100, slotCount: 1, multiplierPct: 1000 }, settings); assert.deepEqual([2, 6, 12].map((hours) => capped(hours).cards), [1, 1, 2]); assert.deepEqual([2, 6, 12].map((hours) => capped(hours).objects), [2, 2, 4]); // Lanterne de tempête : un danger subi pèse moitié moins, mais le trajet dure 10 % de plus. const exposed = { bravoure: 10, endurance: 0, fortune: 10, orientation: 10 }; const danger = { id: "storm", stat: "bravoure", countered: false }; const struck = applyHazards(exposed, { slotCount: 2, durationIndex: 0, dangers: [danger] }, settings).dangers[0]; const sheltered = applyHazards(exposed, { slotCount: 2, durationIndex: 0, dangers: [danger], dangerReliefPct: settings.powers.stormLanternDangerPct }, settings).dangers[0]; assert.ok(struck.factor < 1); assert.ok(Math.abs((1 - sheltered.factor) - (1 - struck.factor) * 0.5) < 1e-9); const stars5 = (powers) => evaluateTeam({ destination, entry, stars: 5, durationIndex: 0, slots: [{ ...slot(), stats: exposed }, { ...slot(), stats: exposed }], powers }, settings); assert.ok(stars5(["stormLantern"]).scorePct >= stars5([]).scorePct); assert.ok(Math.abs(travelHours(6, ["stormLantern"], settings) - 6.6) < 1e-9); // Cloche de brume : du butin en moins en solo, rien en groupe ; en groupe, un bonus de synergie. assert.ok(Math.abs(loot(["fogBell"]).eclats - loot([]).eclats * 0.8) < 1e-9); const groupLoot = (powers) => expectedLoot({ hours: 10, stars: 1, tier: "success", fortune: 0, slotCount: 2, powers, group: true }, settings); assert.equal(groupLoot(["fogBell"]).eclats, groupLoot([]).eclats); // En groupe, son bonus s'ajoute hors du plafond des synergies, comme l'Expertise. const rally = (rallyPct) => evaluateTeam({ destination, entry, stars: 2, durationIndex: 0, slots: [{ ...slot(), stats: tenStats }, { ...slot(), stats: tenStats }], synergyPct: settings.score.synergyCapPct, rallyPct }, settings).scorePct; assert.ok(Math.abs(rally(settings.powers.fogBellSynergyPct) / rally(0) - 1.1) < 1e-9); }); test("progression plans: the default keeps today's stats, vocations reach the cap and free points stay within the rules", () => { const profile = { bravoure: 25, endurance: 25, fortune: 20, orientation: 30 }; for (const level of [0, 3, 12]) assert.deepEqual(planStats("rare", level, profile, null, settings), splitPower(cardPower("rare", level, settings), profile)); assert.deepEqual([levelPoints("rare", 4, settings), levelPoints("legendary", 6, settings), levelPoints("legendary", 9, settings), maxStatPoints(25, settings)], [20, 30, 30, 15]); assert.deepEqual(vocationProfile("navigator", settings), { bravoure: 0, endurance: 20, fortune: 20, orientation: 60 }); assert.deepEqual(vocationProfile("leader", { ...settings, plans: { maxStatPct: 45 } }), { bravoure: 45, endurance: 28, fortune: 0, orientation: 27 }); // Rare de niveau 4 : base 40 selon le profil, puis 20 points en vocation de Gardien (12 en Endurance, 4 en Bravoure et en Fortune). assert.deepEqual(planStats("rare", 4, profile, { plan: "guardian" }, settings), { bravoure: 14, endurance: 22, fortune: 12, orientation: 12 }); assert.deepEqual(planStats("rare", 4, profile, { plan: "free", allocation: { fortune: 7 } }, settings), { bravoure: 10, endurance: 10, fortune: 15, orientation: 12 }); // Une répartition qui ne respecte plus les règles (réglage abaissé) est ramenée dedans, sans erreur. assert.deepEqual(clampAllocation({ bravoure: 20, endurance: 9 }, 20, settings), { bravoure: 11, endurance: 9, fortune: 0, orientation: 0 }); assert.equal(allocationError({ bravoure: 12, fortune: 8 }, 20, settings), null); assert.match(allocationError({ bravoure: 13 }, 20, settings), /12 points/); assert.match(allocationError({ bravoure: 10, fortune: 11 }, 20, settings), /20 points/); assert.ok(allocationError({ magic: 1 }, 20, settings)); });