sokko-g/tests/nebula-cards-expeditions.test.mjs
Shinuwa e0ffccd1c8 Let Sokko TCG players level up cards for Expeditions with Éclats or duplicates
- Each owned rare or better edition keeps a level and field experience; a level costs Éclats by current power, so every rarity reaches the same cap and a rare pays the longer road.
- A duplicate of the same edition gives a whole level; every claimed expedition grants field experience to the cards it sent.
- A one-way bridge turns stardust into Éclats at an admin-tuned rate.
- The card sheet shows level, power, stats and experience with upgrade buttons; expeditions use the upgraded power.
- Administration › Guilde tunes the cost formula, duplicate levels, field experience and the bridge rate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:52:44 +01:00

241 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 { loadExpeditionDestinations, validateExpeditionDestinations } from "../services/cards/expedition-content.js";
import {
applyHazards, cardPower, drawExpeditionDay, editionExpeditionData, efficiency, evaluateTeam, expectedLoot, maxLevel,
requirementsFor, resolveDayEntry, rollLoot, roundStochastic, scoreExpedition, soloRoles, splitPower, STAT_IDS, teamStats, upgradeCost, gainProgress
} from "../services/cards/expedition-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 });
test("every catalog card carries expedition tags and every collection a profile", () => {
const tagIds = new Set(rawCatalog.expeditionTags.map((tag) => tag.id));
assert.ok(rawCatalog.cards.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(rawCatalog.cards.flatMap((card) => card.expedition.tags));
assert.deepEqual(rawCatalog.expeditionTags.filter((tag) => !used.has(tag.id)), []);
});
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 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/);
});
test("destinations order the four stats and stay satisfiable by rare or better cards", () => {
assert.equal(destinations.length, 12);
// Une destination par couple (stat principale, seconde stat) : chaque paire de rôles du solo existe.
assert.equal(new Set(destinations.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("solo.minStars", 5), 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, roles double a stat, hazards and conditions weigh on the score", () => {
const destination = destinations.find((item) => item.id === "light-currents");
const roles = soloRoles(destination, 2);
assert.deepEqual(roles, ["orientation", "bravoure"]);
assert.deepEqual(requirementsFor(destination, 2, roles, settings), [
{ stat: "orientation", main: true, value: 33 },
{ stat: "bravoure", main: false, value: 30 }
]);
// Une place sans rôle (Veilleur de la Guilde) n'ajoute que sa part.
assert.equal(requirementsFor(destination, 1, ["orientation", null, null, null], settings)[0].value, 45);
const slot = { stats: { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }, tags: [], collectionId: "primordial-nebula" };
assert.deepEqual(teamStats([{ ...slot, role: "orientation" }, { ...slot, role: null }], settings), { bravoure: 20, endurance: 20, fortune: 20, orientation: 30 });
// 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 }, role: destination.stats[0], tags: [], collectionId: "primordial-nebula" },
{ stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, role: destination.stats[1], 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("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, packs: 5 }, settings, () => 0), { eclats: 2, stardust: 1, packs: 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, soloCards: 2, busyEditions: [] };
assert.equal(expeditionsPending(summary, now), true);
assert.equal(expeditionsPending({ ...summary, launchedToday: true }, now), false);
assert.equal(expeditionsPending({ ...summary, eligible: 1 }, 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 });
});