The daily team page now opens on a welcome screen with the three steps, and the recruitment keeps the same look: golden steps, the choice in a golden panel with the hidden stars, a team summary of colored mini cards and its strengths, and a reroll badge. One "Your team" block is shared by the Guild, the recruitment and the ready team. The header shows the extra golden stars and the balms; the tips button is gone. On the Guild, team quests carry a "En groupe" sign until the team is ready and the streak badge stays readable. The race gets its own admin tab: its own opening, the day's circuit and results, rewards by place and the watchers' skill. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
664 lines
40 KiB
JavaScript
664 lines
40 KiB
JavaScript
// Rôle : vérifie les règles pures de l'Équipe du jour et de la Course des courants, et mesure leur équilibre par simulation.
|
|
import assert from "node:assert/strict";
|
|
import { readFile } from "node:fs/promises";
|
|
import { resolve } from "node:path";
|
|
import { Readable } from "node:stream";
|
|
import { test } from "node:test";
|
|
import { createCardsApiHandler } from "../services/cards/api.js";
|
|
import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js";
|
|
import { CardsDatabase } from "../services/cards/database.js";
|
|
import { STAT_IDS } from "../services/cards/expedition-rules.js";
|
|
import { applyBoost, autoRun, bestRunner, boostsError, canBoost, drawZones, MAX_RACE_MS, placeOf, RACE_STATS, replayRun, startRun, stepRun, ZONE_COUNT } from "../services/cards/race-rules.js";
|
|
import { CardsService } from "../services/cards/service.js";
|
|
import { canRevealStar, chooseCharacter, companionStats, DEFAULT_TEAM_SETTINGS, drawOffer, hiddenStars, inventTeam, keepCompanion, lentCharacters, MIN_SPECIALISTS, OFFER_SIZE, profileKey, recruitmentFinished, rerollOffer, revealStar, specialtiesOf, startRecruitment, TEAM_SIZE, teamCharacters, teamDay, teamSettingsError, visibleSky, WATCHER_TEAM_LEVELS } from "../services/cards/team-rules.js";
|
|
import { DEFAULT_DAILY_TEAM_SETTINGS, dailyTeamSettingsError, readDailyTeamSettings } from "../services/cards/team-settings.js";
|
|
|
|
const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")));
|
|
const RATES = { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 };
|
|
const published = (active) => buildPublishedCatalog(baseCatalog, { variations: [], collectionStates: baseCatalog.collections.map(({ id }) => ({ collectionId: id, active: active(id) })), dropRates: baseCatalog.collections.map(({ id }) => ({ collectionId: id, rarityWeights: RATES })) });
|
|
const catalog = published(() => true);
|
|
const characters = teamCharacters(catalog);
|
|
const byId = new Map(characters.map((character) => [character.id, character]));
|
|
const allIds = new Set(byId.keys());
|
|
|
|
// Suite pseudo-aléatoire fixe : les mesures ne varient pas d'une exécution à l'autre.
|
|
function seeded(seed) {
|
|
let state = seed >>> 0;
|
|
return (max) => {
|
|
state = (state + 0x6d2b79f5) >>> 0;
|
|
let value = Math.imul(state ^ (state >>> 15), 1 | state);
|
|
value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
|
|
return ((value ^ (value >>> 14)) >>> 0) % max;
|
|
};
|
|
}
|
|
|
|
const profile = (bravoure, endurance, fortune, orientation) => ({ bravoure, endurance, fortune, orientation });
|
|
|
|
test("team characters are the illustrated expedition characters, without commons or destinations", () => {
|
|
assert.ok(characters.length > 100);
|
|
for (const { id } of characters) {
|
|
const card = catalog.cards.find((item) => item.id === id);
|
|
assert.ok(card.image && card.kind !== "destination" && !card.expedition.equipment, id);
|
|
}
|
|
const closed = teamCharacters(published((id) => id === "primordial-nebula"));
|
|
assert.equal(closed.length, characters.length);
|
|
assert.ok(closed.some((character) => character.active) && closed.some((character) => !character.active));
|
|
});
|
|
|
|
test("a profile has one specialty, two when its best stats are equal, none when it is balanced", () => {
|
|
assert.deepEqual(specialtiesOf(profile(45, 15, 10, 30)), ["bravoure"]);
|
|
assert.deepEqual(specialtiesOf(profile(35, 35, 10, 20)), ["bravoure", "endurance"]);
|
|
assert.deepEqual(specialtiesOf(profile(20, 30, 20, 30)), ["endurance", "orientation"]);
|
|
assert.deepEqual(specialtiesOf(profile(25, 25, 20, 30)), []);
|
|
assert.deepEqual(specialtiesOf(profile(25, 25, 25, 25)), []);
|
|
});
|
|
|
|
test("an offer holds three different profiles and never comes back", () => {
|
|
const random = seeded(1);
|
|
for (let round = 0; round < 60; round += 1) {
|
|
let state = startRecruitment(characters, { ownedIds: allIds }, random);
|
|
const seen = new Set();
|
|
while (!recruitmentFinished(state)) {
|
|
assert.equal(state.offer.length, OFFER_SIZE);
|
|
assert.equal(new Set(state.offer.map((id) => profileKey(byId.get(id).profile))).size, OFFER_SIZE);
|
|
for (const id of state.offer) {
|
|
assert.ok(!seen.has(id));
|
|
seen.add(id);
|
|
}
|
|
state = keepCompanion(characters, allIds, chooseCharacter(state, state.offer[0]), random);
|
|
}
|
|
assert.equal(state.team.length, TEAM_SIZE);
|
|
assert.deepEqual(state.offer, []);
|
|
}
|
|
});
|
|
|
|
test("owned characters come first; lent ones only fill missing specialties, from open collections", () => {
|
|
const random = seeded(2);
|
|
assert.deepEqual(lentCharacters(characters, allIds, random), []);
|
|
const lent = lentCharacters(characters, new Set(), random);
|
|
for (const stat of STAT_IDS) assert.ok(lent.filter((id) => specialtiesOf(byId.get(id).profile).includes(stat)).length >= MIN_SPECIALISTS);
|
|
|
|
const owned = new Set(characters.filter((character) => specialtiesOf(character.profile).includes("bravoure")).slice(0, 6).map((character) => character.id));
|
|
const completed = lentCharacters(characters, owned, random);
|
|
assert.ok(completed.every((id) => !owned.has(id)));
|
|
const poolIds = new Set([...owned, ...completed]);
|
|
assert.ok(drawOffer(characters, { poolIds, seenIds: new Set() }, random).every((id) => poolIds.has(id)));
|
|
|
|
const partly = teamCharacters(published((id) => id === "primordial-nebula"));
|
|
const active = new Set(partly.filter((character) => character.active).map((character) => character.id));
|
|
for (let round = 0; round < 20; round += 1) {
|
|
const state = startRecruitment(partly, { ownedIds: new Set() }, random);
|
|
assert.ok([...state.lentIds, ...state.offer].every((id) => active.has(id)));
|
|
}
|
|
});
|
|
|
|
test("gold stars raise the power, a black star drops it and ends the attempts, dust changes nothing", () => {
|
|
const start = startRecruitment(characters, { ownedIds: allIds, goldReserve: 2 }, seeded(3));
|
|
assert.deepEqual(hiddenStars(start), { gold: 10, black: 3, dust: 2 });
|
|
const state = chooseCharacter({ ...start, sky: ["gold", "dust", "gold", "black", "gold", "gold"], revealed: [] }, start.offer[0]);
|
|
assert.equal(state.current.power, 50);
|
|
assert.equal(chooseCharacter(state, start.offer[1]), null);
|
|
|
|
const gold = revealStar(state, 0);
|
|
assert.equal(gold.star, "gold");
|
|
assert.equal(gold.state.current.power, 60);
|
|
assert.equal(revealStar(gold.state, 0), null);
|
|
const dust = revealStar(gold.state, 1);
|
|
assert.equal(dust.state.dust, DEFAULT_TEAM_SETTINGS.dustValue);
|
|
assert.equal(dust.state.current.power, 60);
|
|
const fallen = revealStar(dust.state, 3);
|
|
assert.equal(fallen.state.current.power, 30);
|
|
assert.ok(![2, 4, 5].some((index) => canRevealStar(fallen.state, index)));
|
|
|
|
let top = dust.state;
|
|
for (const index of [2, 4]) top = revealStar(top, index).state;
|
|
assert.equal(top.current.power, 95);
|
|
assert.equal(canRevealStar(top, 5), false);
|
|
|
|
assert.deepEqual(visibleSky(fallen.state).map((item) => item.kind), ["gold", "dust", null, "black", null, null]);
|
|
const kept = keepCompanion(characters, allIds, fallen.state, seeded(4));
|
|
assert.deepEqual(kept.team, [{ cardId: start.offer[0], profile: byId.get(start.offer[0]).profile, power: 30, step: 1, fallen: true, healed: false, lent: false }]);
|
|
assert.deepEqual(kept.revealed, [0, 1, 3]);
|
|
});
|
|
|
|
test("three other characters can be asked for a limited number of times, and owned ones come back before any lent one", () => {
|
|
const random = seeded(12);
|
|
const first = startRecruitment(characters, { ownedIds: allIds }, random);
|
|
const second = rerollOffer(characters, allIds, first, random);
|
|
assert.equal(second.rerolls, first.rerolls - 1);
|
|
assert.ok(second.offer.every((id) => !first.offer.includes(id)));
|
|
assert.deepEqual(second.sky, first.sky);
|
|
const third = rerollOffer(characters, allIds, second, random);
|
|
assert.equal(rerollOffer(characters, allIds, third, random), null);
|
|
assert.equal(rerollOffer(characters, allIds, chooseCharacter(first, first.offer[0]), random), null);
|
|
|
|
// Une petite collection qui couvre les quatre spécialités : jamais de prêt, même en redemandant.
|
|
const owned = new Set(STAT_IDS.flatMap((stat) => {
|
|
const profiles = new Set();
|
|
return characters.filter((character) => specialtiesOf(character.profile).join() === stat && !profiles.has(profileKey(character.profile)) && profiles.add(profileKey(character.profile))).slice(0, 4).map((character) => character.id);
|
|
}));
|
|
for (let round = 0; round < 30; round += 1) {
|
|
let state = startRecruitment(characters, { ownedIds: owned }, random);
|
|
while (!recruitmentFinished(state)) {
|
|
const next = rerollOffer(characters, owned, state, random);
|
|
if (next) {
|
|
assert.ok(next.offer.every((id) => !state.offer.includes(id)));
|
|
state = next;
|
|
}
|
|
assert.ok(state.offer.every((id) => !state.team.some((companion) => companion.cardId === id)));
|
|
state = keepCompanion(characters, owned, chooseCharacter(state, state.offer[0]), random);
|
|
}
|
|
assert.ok(state.team.every((companion) => !companion.lent));
|
|
}
|
|
});
|
|
|
|
test("the gold reserve is capped and a finished recruitment shows every star", () => {
|
|
const random = seeded(5);
|
|
let state = startRecruitment(characters, { ownedIds: new Set(), goldReserve: 9 }, random);
|
|
assert.equal(state.extraGold, 3);
|
|
while (!recruitmentFinished(state)) state = keepCompanion(characters, new Set(), chooseCharacter(state, state.offer[0]), random);
|
|
assert.ok(state.team.every((companion) => companion.lent));
|
|
assert.ok(visibleSky(state).every((star) => star.kind && !star.revealed));
|
|
});
|
|
|
|
test("a team serves three days and its settings must keep a real risk", () => {
|
|
assert.deepEqual(["2026-11-24", "2026-11-25", "2026-11-26", "2026-11-27", "2026-11-28"].map((day) => teamDay("2026-11-25", day)), [0, 1, 2, 3, 0]);
|
|
assert.equal(teamSettingsError(DEFAULT_TEAM_SETTINGS), null);
|
|
for (const change of [{ goldStars: 0 }, { blackStars: -1 }, { dustValue: 1.5 }, { rerolls: -1 }, { powers: [50] }, { powers: [50, 50] }, { fallPower: 50 }]) {
|
|
assert.ok(teamSettingsError({ ...DEFAULT_TEAM_SETTINGS, ...change }), JSON.stringify(change));
|
|
}
|
|
assert.ok(teamSettingsError(null));
|
|
});
|
|
|
|
test("a course has eight zones shared three, two, two and one", () => {
|
|
const random = seeded(6);
|
|
assert.deepEqual([...RACE_STATS], [...STAT_IDS]);
|
|
for (let round = 0; round < 30; round += 1) {
|
|
const zones = drawZones(random);
|
|
assert.equal(zones.length, ZONE_COUNT);
|
|
assert.deepEqual(RACE_STATS.map((stat) => zones.filter((zone) => zone === stat).length).sort(), [1, 2, 2, 3]);
|
|
}
|
|
});
|
|
|
|
test("a replayed race is deterministic and ignores impossible boosts", () => {
|
|
const zones = ["fortune", "bravoure", "bravoure", "endurance", "orientation", "bravoure", "endurance", "fortune"];
|
|
const runner = profile(30, 10, 10, 10);
|
|
const helpers = [profile(40, 5, 5, 5), profile(5, 40, 5, 5)];
|
|
const plain = replayRun({ runner, helpers }, zones);
|
|
const boosts = [{ at: 3_000, helper: 0 }, { at: 12_000, helper: 1 }];
|
|
const boosted = replayRun({ runner, helpers, boosts }, zones);
|
|
assert.ok(boosted.finishedAt < plain.finishedAt && plain.finishedAt <= MAX_RACE_MS);
|
|
assert.equal(replayRun({ runner, helpers, boosts: [...boosts].reverse() }, zones).finishedAt, boosted.finishedAt);
|
|
assert.deepEqual(boosted.boosts.map((boost) => boost.helper), [0, 1]);
|
|
// Un deuxième élan pendant le premier, ou donné après l'arrivée, ne compte pas.
|
|
assert.equal(replayRun({ runner, helpers, boosts: [{ at: 3_000, helper: 0 }, { at: 3_500, helper: 1 }, { at: MAX_RACE_MS, helper: 1 }] }, zones).finishedAt, replayRun({ runner, helpers, boosts: [{ at: 3_000, helper: 0 }] }, zones).finishedAt);
|
|
// Le même équipier vaut plus dans la zone de sa meilleure stat.
|
|
assert.ok(replayRun({ runner, helpers, boosts: [{ at: 4_000, helper: 0 }] }, zones).finishedAt < replayRun({ runner, helpers, boosts: [{ at: 100, helper: 0 }] }, zones).finishedAt);
|
|
|
|
let run = applyBoost(startRun(), helpers, zones, 0);
|
|
assert.equal(canBoost(run, helpers, 1), false);
|
|
while (run.time < run.boostEnd) run = stepRun(run, runner, zones);
|
|
assert.equal(canBoost(run, helpers, 1), true);
|
|
assert.equal(canBoost(run, helpers, 0), false);
|
|
|
|
assert.equal(boostsError(boosts, 2), null);
|
|
for (const invalid of [null, [{ at: 1, helper: 0 }, { at: 2, helper: 0 }], [{ at: -1, helper: 0 }], [{ at: 1.5, helper: 0 }], [{ at: 1, helper: 2 }], [{ at: MAX_RACE_MS + 1, helper: 0 }], [boosts[0], boosts[1], { at: 5, helper: 1 }]]) assert.ok(boostsError(invalid, 2));
|
|
assert.equal(placeOf(100, [100, 90, 120]), 2);
|
|
});
|
|
|
|
// --- Équilibre, par simulation (suites fixes) -------------------------------------------------------------------------------
|
|
|
|
const teamStats = (team) => team.map(({ cardId, power }) => companionStats(byId.get(cardId).profile, power));
|
|
const entrant = (stats, zones, index = bestRunner(stats, zones)) => ({ runner: stats[index], helpers: stats.filter((_, other) => other !== index) });
|
|
|
|
test("simulated races reward a good team, a good runner and good boosts", () => {
|
|
const random = seeded(7);
|
|
const races = 250;
|
|
const wins = { random: 0, runner: 0, boosts: 0 };
|
|
let last = 0;
|
|
for (let race = 0; race < races; race += 1) {
|
|
const zones = drawZones(random);
|
|
const others = Array.from({ length: 3 }, () => autoRun(entrant(teamStats(inventTeam(characters, drawZones(random), WATCHER_TEAM_LEVELS.strong, random)), zones), zones, random(2) === 0, random).finishedAt);
|
|
const stats = teamStats(inventTeam(characters, zones, WATCHER_TEAM_LEVELS.strong, random));
|
|
const place = (index, skilled) => placeOf(autoRun(entrant(stats, zones, index), zones, skilled, random).finishedAt, others);
|
|
const randomPlace = place(random(TEAM_SIZE), false);
|
|
wins.random += randomPlace === 1 ? 1 : 0;
|
|
last += randomPlace === 4 ? 1 : 0;
|
|
wins.runner += place(undefined, false) === 1 ? 1 : 0;
|
|
wins.boosts += place(undefined, true) === 1 ? 1 : 0;
|
|
}
|
|
assert.ok(wins.random < races * 0.2, `coureur et élans au hasard : ${wins.random} victoires`);
|
|
assert.ok(last > races * 0.4, `coureur et élans au hasard : ${last} dernières places`);
|
|
assert.ok(wins.runner > wins.random, `bon coureur : ${wins.runner}`);
|
|
assert.ok(wins.boosts > wins.runner * 2 && wins.boosts > races * 0.3 && wins.boosts < races * 0.7, `bons élans : ${wins.boosts} victoires`);
|
|
});
|
|
|
|
test("the watchers' teams go from weak to strong", () => {
|
|
const random = seeded(8);
|
|
const average = Object.fromEntries(Object.entries(WATCHER_TEAM_LEVELS).map(([level, skill]) => {
|
|
let total = 0;
|
|
for (let round = 0; round < 250; round += 1) {
|
|
const zones = drawZones(random);
|
|
total += autoRun(entrant(teamStats(inventTeam(characters, zones, skill, random)), zones), zones, skill > 50, random).finishedAt;
|
|
}
|
|
return [level, total / 250];
|
|
}));
|
|
assert.ok(average.strong < average.medium && average.medium < average.weak, JSON.stringify(average));
|
|
});
|
|
|
|
test("a small collection is barely worse than a full one", () => {
|
|
const random = seeded(9);
|
|
const score = (size) => {
|
|
let total = 0;
|
|
for (let round = 0; round < 250; round += 1) {
|
|
const owned = new Set();
|
|
while (owned.size < size) owned.add(characters[random(characters.length)].id);
|
|
const needs = drawZones(random);
|
|
let state = startRecruitment(characters, { ownedIds: owned }, random);
|
|
while (!recruitmentFinished(state)) {
|
|
const stat = needs[state.team.length];
|
|
const best = [...state.offer].sort((left, right) => byId.get(right).profile[stat] - byId.get(left).profile[stat])[0];
|
|
total += byId.get(best).profile[stat];
|
|
state = keepCompanion(characters, owned, chooseCharacter(state, best), random);
|
|
}
|
|
}
|
|
return total / 250;
|
|
};
|
|
const [none, some, all] = [0, 40, characters.length].map(score);
|
|
assert.ok(Math.min(none, some) > all * 0.9 && Math.max(none, some) < all * 1.1, `${none} / ${some} / ${all}`);
|
|
});
|
|
|
|
// --- Service et API ---------------------------------------------------------------------------------------------------------
|
|
|
|
const NOON = Date.parse("2026-11-25T11:00:00Z");
|
|
const DAY = "2026-11-25";
|
|
const DAY_MS = 24 * 3_600_000;
|
|
|
|
function game(t, { enabled = true, seed = 11 } = {}) {
|
|
const database = new CardsDatabase(":memory:");
|
|
t.after(() => database.close());
|
|
const clock = { now: NOON };
|
|
const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random: seeded(seed) });
|
|
database.db.prepare("UPDATE collection_states SET active = 1").run();
|
|
service.reloadCatalog();
|
|
const player = service.upsertPlayer({ discordId: "1", displayName: "Léa", avatarUrl: "" });
|
|
const admin = service.upsertPlayer({ discordId: "2", displayName: "Admin", avatarUrl: "", isAdmin: true });
|
|
if (enabled) service.team.updateSettings(admin.id, { ...DEFAULT_DAILY_TEAM_SETTINGS, enabled: true });
|
|
return { database, db: database.db, clock, service, player, admin, team: service.team };
|
|
}
|
|
|
|
const storedState = (db, playerId) => JSON.parse(db.prepare("SELECT state_json FROM player_teams WHERE player_id = ?").get(playerId).state_json);
|
|
const refuses = (code, callback) => assert.throws(callback, (error) => error.code === code);
|
|
|
|
// Recrute sans rien améliorer, jusqu'à l'équipe complète.
|
|
function recruitAll({ team, player }) {
|
|
let view = team.view(player.id);
|
|
while (view.status === "recruiting") {
|
|
const { cardId } = view.recruitment.current ?? view.recruitment.offer[0];
|
|
if (!view.recruitment.current) team.chooseCharacter(player.id, { cardId });
|
|
view = team.keepCompanion(player.id, { cardId }).team;
|
|
}
|
|
return view;
|
|
}
|
|
|
|
test("the daily team is closed by default and only an administrator opens it", (t) => {
|
|
const { team, player, admin, db } = game(t, { enabled: false });
|
|
assert.equal(team.view(player.id).enabled, false);
|
|
assert.equal(team.summary(player.id).status, "none");
|
|
refuses("TEAM_CLOSED", () => team.startRecruitment(player.id, { day: DAY }));
|
|
assert.throws(() => team.updateSettings(player.id, { ...DEFAULT_DAILY_TEAM_SETTINGS, enabled: true }), (error) => error.status === 403);
|
|
refuses("TEAM_SETTINGS_INVALID", () => team.updateSettings(admin.id, { ...DEFAULT_DAILY_TEAM_SETTINGS, raceRewards: [1] }));
|
|
refuses("TEAM_SETTINGS_UNCHANGED", () => team.updateSettings(admin.id, { ...DEFAULT_DAILY_TEAM_SETTINGS }));
|
|
assert.equal(team.updateSettings(admin.id, { ...DEFAULT_DAILY_TEAM_SETTINGS, enabled: true, unknown: 1 }).teamSettings.settings.enabled, true);
|
|
assert.equal(JSON.parse(db.prepare("SELECT settings_json FROM team_settings").get().settings_json).unknown, undefined);
|
|
// Des réglages illisibles gardent l'ouverture et reprennent les valeurs par défaut.
|
|
assert.equal(dailyTeamSettingsError(readDailyTeamSettings({ enabled: true, recruitment: { fallPower: 99 } })), null);
|
|
assert.equal(readDailyTeamSettings({ enabled: true, recruitment: { fallPower: 99 } }).enabled, true);
|
|
});
|
|
|
|
test("a recruitment goes from the first offer to a complete team, once per day", (t) => {
|
|
const { team, player, db, clock } = game(t);
|
|
db.prepare("UPDATE players SET gold_stars = 2 WHERE id = ?").run(player.id);
|
|
const started = team.startRecruitment(player.id, { day: DAY }).team;
|
|
assert.equal(started.status, "recruiting");
|
|
assert.equal(started.goldStars, 0);
|
|
assert.deepEqual(started.recruitment.hidden, { gold: 10, black: 3, dust: 2 });
|
|
assert.equal(started.recruitment.offer.length, 3);
|
|
refuses("TEAM_RECRUITING", () => team.startRecruitment(player.id, { day: DAY }));
|
|
refuses("TEAM_EXPIRED", () => team.startRecruitment(player.id, { day: "2026-11-24" }));
|
|
|
|
// Redemander trois personnages : un double clic, qui renvoie l'ancienne proposition, n'en consomme pas deux.
|
|
const shown = started.recruitment.offer.map((companion) => companion.cardId);
|
|
const rerolled = team.rerollOffer(player.id, { offer: shown }).team.recruitment;
|
|
assert.equal(rerolled.rerolls, started.recruitment.rerolls - 1);
|
|
assert.equal(team.rerollOffer(player.id, { offer: shown }).team.recruitment.rerolls, rerolled.rerolls);
|
|
assert.equal(team.rerollOffer(player.id, { offer: rerolled.offer.map((companion) => companion.cardId) }).team.recruitment.rerolls, 0);
|
|
refuses("TEAM_REROLL_UNAVAILABLE", () => team.rerollOffer(player.id, { offer: team.view(player.id).recruitment.offer.map((companion) => companion.cardId) }));
|
|
|
|
// Recharger la page ne relance aucun tirage.
|
|
const current = team.view(player.id).recruitment;
|
|
assert.deepEqual(team.view(player.id).recruitment, current);
|
|
const [first, second] = current.offer.map((companion) => companion.cardId);
|
|
team.chooseCharacter(player.id, { cardId: first });
|
|
team.chooseCharacter(player.id, { cardId: first });
|
|
refuses("TEAM_CHOICE_INVALID", () => team.chooseCharacter(player.id, { cardId: second }));
|
|
refuses("TEAM_CHOICE_INVALID", () => team.keepCompanion(player.id, { cardId: second }));
|
|
|
|
const ready = recruitAll({ team, player });
|
|
assert.equal(ready.status, "ready");
|
|
assert.equal(ready.teamDay, 1);
|
|
assert.equal(ready.companions.length, TEAM_SIZE);
|
|
assert.ok(ready.companions.every((companion) => companion.lent && Object.values(companion.stats).reduce((sum, value) => sum + value, 0) === companion.power));
|
|
assert.ok(ready.lastSky.every((star) => star.kind));
|
|
assert.equal(ready.canRecruit, false);
|
|
refuses("TEAM_ALREADY_RECRUITED", () => team.startRecruitment(player.id, { day: DAY }));
|
|
refuses("TEAM_NOT_RECRUITING", () => team.revealStar(player.id, { index: 0 }));
|
|
|
|
clock.now += 2 * DAY_MS;
|
|
assert.deepEqual([team.view(player.id).status, team.view(player.id).teamDay, team.view(player.id).canRecruit], ["ready", 3, true]);
|
|
assert.ok(team.activeTeam(player.id));
|
|
clock.now += DAY_MS;
|
|
assert.equal(team.view(player.id).status, "expired");
|
|
assert.equal(team.activeTeam(player.id), null);
|
|
assert.equal(team.startRecruitment(player.id, { day: "2026-11-28" }).team.companions.length, 0);
|
|
});
|
|
|
|
test("revealed stars are paid once, and hidden ones never leave the server", (t) => {
|
|
const { team, player, db, service } = game(t);
|
|
team.startRecruitment(player.id, { day: DAY });
|
|
const { cardId } = team.view(player.id).recruitment.offer[0];
|
|
team.chooseCharacter(player.id, { cardId });
|
|
const { sky } = storedState(db, player.id);
|
|
const [dust, otherDust] = sky.flatMap((kind, index) => (kind === "dust" ? [index] : []));
|
|
const before = service.getState(player.id).wallet.stardust;
|
|
const result = team.revealStar(player.id, { index: dust });
|
|
assert.equal(result.state.wallet.stardust, before + 3);
|
|
assert.equal(team.revealStar(player.id, { index: dust }).state.wallet.stardust, before + 3);
|
|
assert.equal(result.team.recruitment.current.power, 50);
|
|
assert.equal(result.team.recruitment.sky[dust].kind, "dust");
|
|
assert.equal(result.team.recruitment.sky[otherDust].kind, null);
|
|
assert.equal(result.team.recruitment.sky.filter((star) => star.kind).length, 1);
|
|
const sent = JSON.stringify(result);
|
|
assert.ok(!sent.includes("seenIds") && !sent.includes("lentIds"));
|
|
|
|
const fallen = team.revealStar(player.id, { index: sky.indexOf("black") }).team.recruitment;
|
|
assert.deepEqual([fallen.current.power, fallen.current.fallen], [30, true]);
|
|
refuses("TEAM_STAR_INVALID", () => team.revealStar(player.id, { index: sky.indexOf("gold") }));
|
|
for (const index of [-1, 99, 1.5, "0", null]) refuses("TEAM_STAR_INVALID", () => team.revealStar(player.id, { index }));
|
|
const next = team.keepCompanion(player.id, { cardId }).team.recruitment;
|
|
assert.equal(next.sky.filter((star) => star.revealed).length, 2);
|
|
refuses("TEAM_STAR_INVALID", () => team.revealStar(player.id, { index: sky.indexOf("gold") }));
|
|
});
|
|
|
|
test("owned characters are offered first, without those of a pack not revealed yet", (t) => {
|
|
const { team, player, db, service } = game(t);
|
|
const editionOf = (cardId) => service.catalog.editions.find((edition) => edition.cardId === cardId && edition.rarity !== "mythic").id;
|
|
const owned = characters.slice(0, 60).map((character) => character.id);
|
|
for (const cardId of owned) service.addCard(player.id, editionOf(cardId));
|
|
team.startRecruitment(player.id, { day: DAY });
|
|
assert.ok(team.view(player.id).recruitment.offer.every((companion) => owned.includes(companion.cardId) && !companion.lent));
|
|
const hidden = characters.at(-1).id;
|
|
service.insertOpening(player.id, service.index.cards.get(hidden).collectionId, [editionOf(hidden), editionOf(hidden), editionOf(hidden)]);
|
|
assert.equal(team.ownedCardIds(player.id).has(hidden), false);
|
|
assert.ok(db.prepare("SELECT 1 FROM collection_cards WHERE player_id = ? AND edition_id = ?").get(player.id, editionOf(hidden)));
|
|
});
|
|
|
|
test("a recruitment survives a card removed from the catalog, and a deleted account leaves nothing", (t) => {
|
|
const { team, player, db, service } = game(t);
|
|
team.startRecruitment(player.id, { day: DAY });
|
|
const state = storedState(db, player.id);
|
|
db.prepare("UPDATE player_teams SET state_json = ? WHERE player_id = ?").run(JSON.stringify({ ...state, offer: ["missing-card"] }), player.id);
|
|
assert.equal(team.view(player.id).recruitment.offer.length, 3);
|
|
db.prepare("UPDATE player_teams SET state_json = ? WHERE player_id = ?").run(JSON.stringify({ ...state, current: { cardId: "missing-card", step: 0, power: 50, fallen: false } }), player.id);
|
|
const repaired = team.view(player.id).recruitment;
|
|
assert.equal(repaired.current, null);
|
|
assert.deepEqual(storedState(db, player.id).sky, state.sky);
|
|
recruitAll({ team, player });
|
|
assert.equal(service.getState(player.id).team.status, "ready");
|
|
assert.ok(service.getState(player.id).history.some((entry) => entry.type === "team_recruited"));
|
|
db.prepare("UPDATE players SET gold_stars = 3 WHERE id = ?").run(player.id);
|
|
service.deleteAccount(player.id);
|
|
assert.equal(db.prepare("SELECT COUNT(*) AS count FROM player_teams").get().count, 0);
|
|
assert.equal(db.prepare("SELECT gold_stars FROM players WHERE id = ?").get(player.id).gold_stars, 0);
|
|
});
|
|
|
|
test("the course of the day is the same for everyone and changes with the day", (t) => {
|
|
const { team, player, admin, clock } = game(t);
|
|
const { zones } = team.view(player.id);
|
|
assert.deepEqual(team.view(admin.id).zones, zones);
|
|
clock.now += DAY_MS;
|
|
assert.equal(team.view(player.id).zones.length, ZONE_COUNT);
|
|
assert.equal(team.db.prepare("SELECT COUNT(*) AS count FROM team_days").get().count, 2);
|
|
});
|
|
|
|
test("the team API requires a session", async (t) => {
|
|
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
|
|
t.after(() => handler.close?.());
|
|
for (const [method, path] of [["GET", ""], ["POST", "/recruit"], ["POST", "/reroll"], ["POST", "/choose"], ["POST", "/stars"], ["POST", "/heal"], ["POST", "/keep"], ["POST", "/race"], ["POST", "/race/boosts"], ["POST", "/race/finish"]]) {
|
|
const req = Readable.from(method === "POST" ? [Buffer.from("{}")] : []);
|
|
Object.assign(req, { method, url: `/api/cards/team${path}`, headers: { host: "localhost", origin: "http://localhost", "content-type": "application/json" }, socket: { remoteAddress: "127.0.0.1" } });
|
|
let status = 0;
|
|
await handler(req, { setHeader() {}, writeHead(code) { status = code; }, end() {} });
|
|
assert.equal(status, 401, path);
|
|
}
|
|
});
|
|
|
|
// --- Course et récompense de la Carte du jour -------------------------------------------------------------------------------
|
|
|
|
const join = (service, discordId, displayName) => service.upsertPlayer({ discordId, displayName, avatarUrl: "" });
|
|
|
|
function readyTeam(context, player = context.player) {
|
|
context.team.startRecruitment(player.id, { day: context.team.today });
|
|
return recruitAll({ team: context.team, player });
|
|
}
|
|
|
|
test("a race needs a team, runs once a day and is paid once by the server", (t) => {
|
|
const context = game(t);
|
|
const { team, player, service, db } = context;
|
|
refuses("RACE_NO_TEAM", () => team.startRace(player.id, { day: DAY, cardId: "starvoid-dragon" }));
|
|
const { companions } = readyTeam(context);
|
|
refuses("RACE_RUNNER_INVALID", () => team.startRace(player.id, { day: DAY, cardId: "missing-card" }));
|
|
refuses("RACE_NOT_RUNNING", () => team.finishRace(player.id, {}));
|
|
const { race } = team.startRace(player.id, { day: DAY, cardId: companions[0].cardId }).team;
|
|
assert.equal(race.status, "running");
|
|
assert.equal(race.runner.cardId, companions[0].cardId);
|
|
assert.equal(race.helpers.length, TEAM_SIZE - 1);
|
|
assert.equal(race.opponents.length, 3);
|
|
assert.ok(race.opponents.every((opponent) => opponent.watchers && opponent.name === null && opponent.helpers.length === TEAM_SIZE - 1));
|
|
assert.deepEqual(team.view(player.id).race, race);
|
|
refuses("RACE_ALREADY_RUN", () => team.startRace(player.id, { day: DAY, cardId: companions[1].cardId }));
|
|
|
|
const boosts = [{ at: 1_000, helper: 2 }, { at: 4_000, helper: 0 }];
|
|
const before = service.getState(player.id).wallet.stardust;
|
|
const result = team.finishRace(player.id, { boosts });
|
|
const expected = replayRun({ runner: race.runner.stats, helpers: race.helpers.map((helper) => helper.stats), boosts }, race.zones);
|
|
assert.equal(result.team.race.finishedAt, expected.finishedAt);
|
|
assert.equal(result.team.race.place, placeOf(expected.finishedAt, race.opponents.map((opponent) => opponent.finishedAt)));
|
|
assert.equal(result.state.wallet.stardust, before + race.rewards[result.team.race.place - 1]);
|
|
assert.equal(team.finishRace(player.id, { boosts: [] }).state.wallet.stardust, before + result.team.race.reward);
|
|
assert.equal(result.state.team.race, "finished");
|
|
assert.ok(result.state.history.some((entry) => entry.type === "race_finished" && entry.details.place === result.team.race.place));
|
|
assert.equal(db.prepare("SELECT COUNT(*) AS count FROM team_races").get().count, 1);
|
|
});
|
|
|
|
test("the race opens and closes on its own, with its watchers' skill and a daily summary for the administration", (t) => {
|
|
const context = game(t);
|
|
const { team, player, admin } = context;
|
|
const { companions } = readyTeam(context);
|
|
const settings = team.settings;
|
|
assert.deepEqual([settings.raceEnabled, settings.watcherSkill], [true, { strong: 90, medium: 60, weak: 30 }]);
|
|
refuses("TEAM_SETTINGS_INVALID", () => team.updateSettings(admin.id, { ...settings, raceEnabled: "oui" }));
|
|
refuses("TEAM_SETTINGS_INVALID", () => team.updateSettings(admin.id, { ...settings, watcherSkill: { ...settings.watcherSkill, weak: 101 } }));
|
|
// Des réglages enregistrés avant la Course gardent leurs valeurs et prennent celles de la Course par défaut.
|
|
assert.deepEqual(readDailyTeamSettings({ enabled: true, raceRewards: [9, 8, 7, 6] }).watcherSkill, { strong: 90, medium: 60, weak: 30 });
|
|
|
|
team.updateSettings(admin.id, { ...settings, raceEnabled: false });
|
|
assert.deepEqual([team.summary(player.id).raceEnabled, team.view(player.id).raceEnabled, team.summary(player.id).enabled], [false, false, true]);
|
|
refuses("RACE_CLOSED", () => team.startRace(player.id, { day: DAY, cardId: companions[0].cardId }));
|
|
assert.equal(team.adminSettings().race.started, 0);
|
|
|
|
team.updateSettings(admin.id, { ...settings, raceEnabled: true, watcherSkill: { strong: 100, medium: 100, weak: 100 } });
|
|
const { race } = team.startRace(player.id, { day: DAY, cardId: companions[0].cardId }).team;
|
|
const finished = team.finishRace(player.id, { boosts: [] }).team.race;
|
|
const summary = team.adminSettings().race;
|
|
assert.deepEqual(summary.zones, race.zones);
|
|
assert.deepEqual([summary.started, summary.finished, summary.stardust], [1, 1, finished.reward]);
|
|
assert.equal(summary.places[finished.place - 1], 1);
|
|
assert.deepEqual(summary.opponents, { players: 0, watchers: 3 });
|
|
// L'Équipe du jour fermée ferme aussi la Course aux joueurs.
|
|
team.updateSettings(admin.id, { ...team.settings, enabled: false });
|
|
assert.equal(team.summary(player.id).raceEnabled, false);
|
|
});
|
|
|
|
test("boosts already given cannot change, and an abandoned race ends with them", (t) => {
|
|
const context = game(t);
|
|
const { team, player, clock } = context;
|
|
const { companions } = readyTeam(context);
|
|
team.startRace(player.id, { day: DAY, cardId: companions[0].cardId });
|
|
const first = [{ at: 2_000, helper: 1 }];
|
|
team.recordBoosts(player.id, { boosts: first });
|
|
team.recordBoosts(player.id, { boosts: [] });
|
|
assert.deepEqual(team.view(player.id).race.boosts, first);
|
|
refuses("RACE_BOOSTS_CHANGED", () => team.recordBoosts(player.id, { boosts: [{ at: 2_500, helper: 1 }] }));
|
|
refuses("RACE_BOOSTS_CHANGED", () => team.finishRace(player.id, { boosts: [{ at: 500, helper: 3 }, ...first] }));
|
|
refuses("RACE_BOOSTS_INVALID", () => team.recordBoosts(player.id, { boosts: [...first, { at: 1, helper: 9 }] }));
|
|
clock.now += 30_000;
|
|
assert.equal(team.view(player.id).race.status, "running");
|
|
clock.now += 10 * 60_000;
|
|
const { race } = team.view(player.id);
|
|
assert.equal(race.status, "finished");
|
|
assert.deepEqual(race.boosts, first);
|
|
});
|
|
|
|
test("a race started before midnight ends on its day and leaves the next day free", (t) => {
|
|
const context = game(t);
|
|
const { team, player, clock } = context;
|
|
const { companions } = readyTeam(context);
|
|
clock.now = Date.parse("2026-11-25T22:59:50Z");
|
|
team.startRace(player.id, { day: DAY, cardId: companions[0].cardId });
|
|
clock.now += 20_000;
|
|
assert.equal(team.today, "2026-11-26");
|
|
refuses("RACE_RUNNING", () => team.startRace(player.id, { day: "2026-11-26", cardId: companions[0].cardId }));
|
|
team.finishRace(player.id, { boosts: [] });
|
|
assert.equal(team.view(player.id).race, null);
|
|
assert.equal(team.startRace(player.id, { day: "2026-11-26", cardId: companions[1].cardId }).team.race.day, "2026-11-26");
|
|
});
|
|
|
|
test("opponents are other players' usable teams, completed by the watchers, and follow a deleted account", (t) => {
|
|
const context = game(t);
|
|
const { team, player, service, clock } = context;
|
|
const others = [["10", "Ana"], ["11", "Bob"]].map(([id, name]) => join(service, id, name));
|
|
for (const other of others) readyTeam(context, other);
|
|
const late = join(service, "12", "Recrute");
|
|
team.startRecruitment(late.id, { day: DAY });
|
|
const { companions } = readyTeam(context);
|
|
const { race } = team.startRace(player.id, { day: DAY, cardId: companions[0].cardId }).team;
|
|
assert.deepEqual(race.opponents.map((opponent) => opponent.name).filter(Boolean).sort(), ["Ana", "Bob"]);
|
|
assert.equal(race.opponents.filter((opponent) => opponent.watchers).length, 1);
|
|
service.deleteAccount(others[0].id);
|
|
assert.deepEqual(team.view(player.id).race.opponents.map((opponent) => opponent.name).filter(Boolean), ["Bob"]);
|
|
team.finishRace(player.id, {});
|
|
// Trois jours plus tard, les équipes des autres ne courent plus.
|
|
clock.now += 3 * DAY_MS;
|
|
const ready = readyTeam(context);
|
|
assert.ok(team.startRace(player.id, { day: "2026-11-28", cardId: ready.companions[0].cardId }).team.race.opponents.every((opponent) => opponent.watchers));
|
|
service.deleteAccount(player.id);
|
|
assert.equal(context.db.prepare("SELECT COUNT(*) AS count FROM team_races WHERE player_id = ?").get(player.id).count, 0);
|
|
});
|
|
|
|
function winDaily({ service, player, db, team }) {
|
|
service.getDaily(player.id);
|
|
const { card_id: cardId } = db.prepare("SELECT card_id FROM daily_attempts WHERE player_id = ? AND day = ?").get(player.id, team.today);
|
|
return service.guessDaily(player.id, { day: team.today, cardId });
|
|
}
|
|
|
|
test("a daily victory waits for a choice between stardust and a golden star", (t) => {
|
|
const context = game(t);
|
|
const { service, player, db } = context;
|
|
const before = service.getState(player.id).wallet.stardust;
|
|
const won = winDaily(context);
|
|
assert.deepEqual(won.daily.rewardOffer, { stardust: 10, starStardust: 10, starAvailable: true, goldStars: 0, maxGoldStars: 3 });
|
|
assert.equal(won.state.wallet.stardust, before);
|
|
assert.equal(won.state.daily.rewardPending, true);
|
|
refuses("DAILY_REWARD_INVALID", () => service.chooseDailyReward(player.id, { day: DAY, choice: "both" }));
|
|
db.prepare("UPDATE shop_settings SET daily_reward = 999").run();
|
|
const chosen = service.chooseDailyReward(player.id, { day: DAY, choice: "star" });
|
|
assert.equal(chosen.state.wallet.stardust, before + 10);
|
|
assert.equal(chosen.state.team.goldStars, 1);
|
|
assert.deepEqual([chosen.daily.rewardOffer, chosen.daily.earned, chosen.daily.earnedStar], [null, 10, true]);
|
|
assert.equal(service.chooseDailyReward(player.id, { day: DAY, choice: "star" }).state.team.goldStars, 1);
|
|
refuses("DAILY_REWARD_CHOSEN", () => service.chooseDailyReward(player.id, { day: DAY, choice: "stardust" }));
|
|
});
|
|
|
|
test("an unchosen daily reward becomes stardust the next day, at the amount offered", (t) => {
|
|
const context = game(t);
|
|
const { service, player, db, clock } = context;
|
|
winDaily(context);
|
|
db.prepare("UPDATE shop_settings SET daily_reward = 999").run();
|
|
clock.now += DAY_MS;
|
|
refuses("DAILY_EXPIRED", () => service.chooseDailyReward(player.id, { day: DAY, choice: "star" }));
|
|
const state = service.getState(player.id);
|
|
assert.equal(state.wallet.stardust, 10);
|
|
assert.equal(state.team.goldStars, 0);
|
|
assert.equal(service.getState(player.id).wallet.stardust, 10);
|
|
assert.deepEqual(state.history.find((entry) => entry.type === "daily_reward_chosen").details, { stardust: 10, star: false });
|
|
});
|
|
|
|
test("a full reserve or a closed daily team pays the daily card at once", (t) => {
|
|
const full = game(t);
|
|
full.db.prepare("UPDATE players SET gold_stars = 3 WHERE id = ?").run(full.player.id);
|
|
const won = winDaily(full);
|
|
assert.deepEqual([won.daily.rewardOffer, won.daily.earned, won.state.wallet.stardust], [null, 10, 10]);
|
|
|
|
const closed = game(t, { enabled: false });
|
|
assert.deepEqual([winDaily(closed).daily.rewardOffer, closed.service.getState(closed.player.id).wallet.stardust], [null, 10]);
|
|
|
|
// Fermée entre la victoire et le choix : il reste la poussière.
|
|
const between = game(t);
|
|
winDaily(between);
|
|
between.team.updateSettings(between.admin.id, { ...DEFAULT_DAILY_TEAM_SETTINGS });
|
|
assert.equal(between.service.getDaily(between.player.id).rewardOffer.starAvailable, false);
|
|
refuses("DAILY_STAR_UNAVAILABLE", () => between.service.chooseDailyReward(between.player.id, { day: DAY, choice: "star" }));
|
|
assert.equal(between.service.chooseDailyReward(between.player.id, { day: DAY, choice: "stardust" }).state.wallet.stardust, 10);
|
|
});
|
|
|
|
test("only the development server resets a team and its races", (t) => {
|
|
const context = game(t);
|
|
const { team, player, service } = context;
|
|
const { companions } = readyTeam(context);
|
|
team.startRace(player.id, { day: DAY, cardId: companions[0].cardId });
|
|
assert.equal(team.view(player.id).devReset, false);
|
|
refuses("NOT_FOUND", () => team.resetForTests(player.id));
|
|
service.devPerks = true;
|
|
const reset = team.resetForTests(player.id).team;
|
|
assert.deepEqual([reset.devReset, reset.status, reset.race, reset.canRecruit], [true, "none", null, true]);
|
|
});
|
|
|
|
test("a balm brings a weakened companion back to its starting power, once and at once", (t) => {
|
|
const { team, player, db, service } = game(t);
|
|
team.startRecruitment(player.id, { day: DAY });
|
|
const { cardId } = team.view(player.id).recruitment.offer[0];
|
|
team.chooseCharacter(player.id, { cardId });
|
|
refuses("TEAM_HEAL_INVALID", () => team.healCompanion(player.id, { cardId }));
|
|
const { sky } = storedState(db, player.id);
|
|
team.revealStar(player.id, { index: sky.indexOf("gold") });
|
|
team.revealStar(player.id, { index: sky.indexOf("black") });
|
|
refuses("NOT_ENOUGH_ITEMS", () => team.healCompanion(player.id, { cardId }));
|
|
assert.equal(team.view(player.id).recruitment.current.power, 30);
|
|
service.expeditions.addItemsInTx(player.id, ["balm", "balm"]);
|
|
assert.equal(team.view(player.id).recruitment.balms, 2);
|
|
assert.equal(team.view(player.id).balms, 2);
|
|
const healed = team.healCompanion(player.id, { cardId }).team.recruitment;
|
|
assert.deepEqual([healed.current.power, healed.current.healed, healed.balms], [50, true, 1]);
|
|
assert.equal(team.healCompanion(player.id, { cardId }).team.recruitment.balms, 1);
|
|
refuses("TEAM_STAR_INVALID", () => team.revealStar(player.id, { index: sky.lastIndexOf("gold") }));
|
|
const kept = team.keepCompanion(player.id, { cardId }).team;
|
|
assert.deepEqual([kept.companions[0].power, kept.companions[0].healed], [50, true]);
|
|
refuses("TEAM_CHOICE_INVALID", () => team.healCompanion(player.id, { cardId }));
|
|
assert.ok(service.getState(player.id).history.some((entry) => entry.type === "item_used" && entry.details.item === "balm"));
|
|
});
|
|
|
|
test("a balm only comes from expeditions while the daily team is open", (t) => {
|
|
assert.equal(game(t).service.expeditions.excludedItems().includes("balm"), false);
|
|
assert.equal(game(t, { enabled: false }).service.expeditions.excludedItems().includes("balm"), true);
|
|
});
|