Add the Broken Mirror puzzle to the Guild

A daily puzzle: a card illustration cut into pieces, rebuilt by swapping
two pieces of the same row or column within a limited number of swaps.
The normal picture is a square card in 4 x 4, drawn for each player, with
placed pieces outlined in green; the hard one is a 5 x 7 portrait shared
by everyone each day, with a result to copy. The limit is the computer's
best result (beam search) plus a margin, and every swap left adds
stardust. Two companions of the daily team can each give one help, by
specialty; a double specialty picks one when used.

The server keeps the piece positions, sends the picture already shuffled
and checks every swap. Uniform illustrations are left out, from measures
written by scripts/mirror-illustrations.mjs. The Guild gets its quest and
a Codex tile, the administration a tab (opening, rewards, margins, the
day's summary), and migration 30 its tables. New collections must plan at
least one double-specialty character, counted by
scripts/team-specialties.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-28 13:38:46 +01:00
parent 5210503922
commit 9cf48ea0d0
36 changed files with 3124 additions and 20 deletions

View file

@ -4,6 +4,7 @@ import { join, resolve } from "node:path";
import { CardsDatabase } from "./database.js";
import { loadCardsCatalog, publicCatalog } from "./catalog.js";
import { createDailyImageRenderer } from "./daily-image.js";
import { createMirrorImageRenderer } from "./mirror-image.js";
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
import { createDiscordAlertSender, dispatchAlerts } from "./discord-alerts.js";
import { CardsService, DEV_DISCORD_ID } from "./service.js";
@ -143,6 +144,7 @@ export function createCardsApiHandler({
service = new CardsService({ database, catalog, now, random, devPerks, destinations, alerts: { available: Boolean(alertSender), publicOrigin: env.CARDS_PUBLIC_ORIGIN || null } });
}
const renderDailyImage = createDailyImageRenderer(join(projectRoot, "website", "public"));
const renderMirrorImage = createMirrorImageRenderer(join(projectRoot, "website", "public"));
const secureCookies = env.NODE_ENV === "production" || String(env.CARDS_PUBLIC_ORIGIN || "").startsWith("https://");
const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean));
service?.syncAdmins(adminIds, { keepDevAdmin: devAuth });
@ -395,6 +397,50 @@ export function createCardsApiHandler({
json(res, 200, service.team.updateSettings(session.player.id, (await readBody(req)).settings));
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/mirror") {
json(res, 200, { mirror: service.mirror.view(session.player.id) });
return true;
}
// Image mélangée de la partie, dans l'état où elle est (ou en ordre avec `model=1`) ; `v` (nombre de coups) évite seulement de relire une ancienne image.
if (req.method === "GET" && url.pathname === "/api/cards/mirror/image") {
rateLimit(req, "mirror-image", 60);
const image = await renderMirrorImage(service.mirror.image(session.player.id, url.searchParams.get("mode"), { model: url.searchParams.get("model") === "1" }));
res.writeHead(200, { "Content-Type": "image/webp", "Content-Length": image.length, "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" });
res.end(image);
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/mirror/start") {
rateLimit(req, "mirror-start", 30);
const body = await readBody(req);
json(res, 200, service.mirror.start(session.player.id, { day: body.day, mode: body.mode }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/mirror/swap") {
rateLimit(req, "mirror-swap", 240);
const body = await readBody(req);
json(res, 200, service.mirror.swap(session.player.id, { day: body.day, mode: body.mode, from: body.from, to: body.to, moves: body.moves }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/mirror/helpers") {
rateLimit(req, "mirror-helpers", 60);
const body = await readBody(req);
json(res, 200, service.mirror.chooseHelpers(session.player.id, { day: body.day, mode: body.mode, cardIds: body.cardIds }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/mirror/help") {
rateLimit(req, "mirror-help", 60);
const body = await readBody(req);
json(res, 200, service.mirror.useHelp(session.player.id, { day: body.day, mode: body.mode, cardId: body.cardId, help: body.help, moves: body.moves }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/mirror/reset") {
json(res, 200, service.mirror.resetForTests(session.player.id));
return true;
}
if (req.method === "PUT" && url.pathname === "/api/cards/admin/mirror/settings") {
json(res, 200, service.mirror.updateSettings(session.player.id, (await readBody(req)).settings));
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/expeditions") {
json(res, 200, service.expeditions.getExpeditions(session.player.id));
return true;

File diff suppressed because it is too large Load diff

View file

@ -564,6 +564,37 @@ export const MIGRATIONS = [
) STRICT;
ALTER TABLE daily_attempts ADD COLUMN reward_offer_json TEXT CHECK (reward_offer_json IS NULL OR json_valid(reward_offer_json));
ALTER TABLE daily_attempts ADD COLUMN reward_choice TEXT CHECK (reward_choice IS NULL OR reward_choice IN ('pending', 'stardust', 'star'));
`,
// Miroir brisé : ses réglages, l'illustration et le mélange du Difficile (les mêmes pour tous un jour donné), et les parties des
// joueurs (une par mode et par jour), avec leur état complet : le client ne reçoit jamais la solution.
`
CREATE TABLE mirror_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
settings_json TEXT NOT NULL CHECK (json_valid(settings_json)),
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id)
) STRICT;
INSERT INTO mirror_settings(id, settings_json, updated_at, updated_by) VALUES (1, '{}', 0, NULL);
CREATE TABLE mirror_days (
day TEXT PRIMARY KEY,
card_id TEXT NOT NULL,
start_json TEXT NOT NULL CHECK (json_valid(start_json)),
par INTEGER NOT NULL CHECK (par >= 0),
created_at INTEGER NOT NULL
) STRICT;
CREATE TABLE mirror_games (
player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE,
day TEXT NOT NULL,
mode TEXT NOT NULL CHECK (mode IN ('normal', 'hard')),
card_id TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('playing', 'won', 'lost')),
state_json TEXT NOT NULL CHECK (json_valid(state_json)),
reward INTEGER NOT NULL DEFAULT 0 CHECK (reward >= 0),
started_at INTEGER NOT NULL,
finished_at INTEGER,
PRIMARY KEY (player_id, day, mode)
) STRICT;
CREATE INDEX mirror_games_day ON mirror_games(day, mode);
`
];

View file

@ -0,0 +1,40 @@
// Rôle : prépare l'image du Miroir brisé envoyée au joueur : l'illustration déjà mélangée, dans l'ordre où sont les morceaux.
// Le navigateur la découpe pour l'affichage ; il ne reçoit ni l'image en ordre, ni la place des morceaux (seulement des cases).
import { join } from "node:path";
import sharp from "sharp";
// Largeur d'un morceau envoyé : le plateau fait 540 px au plus en Normal et 450 px en Difficile, doublés pour les écrans denses.
const PIECE_SIZE = { square: 270, portrait: 180 };
const CACHE_LIMIT = 64;
export function createMirrorImageRenderer(publicRoot) {
const cache = new Map();
// `at[cell]` : le morceau présent dans chaque case.
return function render({ image, cols, rows, format, at }) {
const key = `${image}|${at.join(",")}`;
const cached = cache.get(key);
if (cached) {
cache.delete(key);
cache.set(key, cached);
return cached;
}
const rendered = (async () => {
const path = join(publicRoot, image);
const { width, height } = await sharp(path).metadata();
const sourceWidth = Math.floor(width / cols), sourceHeight = Math.floor(height / rows);
const size = PIECE_SIZE[format];
const pieceHeight = Math.round(size * sourceHeight / sourceWidth);
const pieces = await Promise.all(Array.from({ length: cols * rows }, (_, piece) => sharp(path)
.extract({ left: (piece % cols) * sourceWidth, top: Math.floor(piece / cols) * sourceHeight, width: sourceWidth, height: sourceHeight })
.resize(size, pieceHeight, { fit: "fill" }).toBuffer()));
return sharp({ create: { width: size * cols, height: pieceHeight * rows, channels: 3, background: "#05070f" } })
.composite(at.map((piece, cell) => ({ input: pieces[piece], left: (cell % cols) * size, top: Math.floor(cell / cols) * pieceHeight })))
.webp({ quality: 84 }).toBuffer();
})();
cache.set(key, rendered);
if (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
// Un échec ne reste pas en cache : le prochain appel réessaie.
rendered.catch(() => cache.delete(key));
return rendered;
};
}

View file

@ -0,0 +1,153 @@
// Rôle : règles pures du Miroir brisé (modes, mélange, échange en rangée ou en colonne, référence de l'ordinateur, coups de main,
// gain, illustrations jouables). Le service les applique avec la base ; aucune fonction ici ne lit la base ni l'horloge.
// Règles et valeurs : docs/miroir-brise.md.
import { randomInt } from "node:crypto";
// Normal : une illustration carrée en 4 × 4, propre à chaque joueur. Difficile : le portrait 5:7 en 5 × 7, le même pour tous.
// Les deux découpes tombent juste : 800 / 4 = 200 px, 1060 / 5 = 1484 / 7 = 212 px.
export const MIRROR_MODES = Object.freeze({
normal: Object.freeze({ cols: 4, rows: 4, format: "square", placedShown: true }),
hard: Object.freeze({ cols: 5, rows: 7, format: "portrait", placedShown: false })
});
export const MIRROR_MODE_IDS = Object.freeze(Object.keys(MIRROR_MODES));
// Au plus deux morceaux déjà à leur place au départ.
export const MAX_FIXED_AT_START = 2;
// Largeur de la recherche de l'ordinateur : au-delà, le résultat ne s'améliore presque plus (moins de 0,1 échange en 4 × 4).
export const SOLVER_WIDTH = 60;
// Coups de main : deux compagnons de l'Équipe du jour, choisis avant le premier échange.
export const HELPERS_PER_GAME = 2;
// Un personnage Équilibré n'a pas de spécialité : son coup de main a sa propre clé.
export const BALANCED_HELP = "balanced";
export const HELP_IDS = Object.freeze(["bravoure", "endurance", "fortune", "orientation", BALANCED_HELP]);
// Échanges ajoutés par l'Endurance (la simulation donnait +2 trop fort face aux autres coups de main, environ +1).
export const ENDURANCE_EXTRA = 1;
// Illustration trop unie (ciel, brume) : plus de 20 % de morceaux presque identiques à un autre. Mesures :
// scripts/mirror-illustrations.mjs, dans services/cards/content/mirror-illustrations.json.
export const MAX_AMBIGUOUS_SHARE = 0.2;
// Une illustration du Difficile ne revient pas avant ce nombre de jours, ni une illustration du Normal pour un même joueur.
export const MIRROR_REPEAT_DAYS = 30;
const defaultRandom = (max) => randomInt(max);
export const cellCount = (mode) => MIRROR_MODES[mode].cols * MIRROR_MODES[mode].rows;
// `pos[p]` : case où se trouve le morceau p ; sa vraie case est p. Mélange de Fisher-Yates ; s'il laisse trop de morceaux en place,
// ceux-là tournent entre eux (aucun ne reste en place). Pas de nouveau tirage : un hasard prévisible (parcours E2E) ne boucle pas.
export function scramble(count, random = defaultRandom) {
const pos = Array.from({ length: count }, (_, index) => index);
for (let index = count - 1; index > 0; index -= 1) {
const other = random(index + 1);
[pos[index], pos[other]] = [pos[other], pos[index]];
}
const fixed = pos.flatMap((cell, piece) => (cell === piece ? [piece] : []));
if (fixed.length > MAX_FIXED_AT_START) fixed.forEach((piece, index) => { pos[piece] = fixed[(index + 1) % fixed.length]; });
return pos;
}
export const isSolved = (pos) => pos.every((cell, piece) => cell === piece);
export const placedCount = (pos) => pos.filter((cell, piece) => cell === piece).length;
export const placedCells = (pos) => pos.flatMap((cell, piece) => (cell === piece ? [cell] : []));
// Morceau présent dans chaque case.
export function pieceAt(pos) {
const at = [];
pos.forEach((cell, piece) => { at[cell] = piece; });
return at;
}
export function aligned(cols, x, y) {
return x !== y && (Math.floor(x / cols) === Math.floor(y / cols) || x % cols === y % cols);
}
export function swapCells(pos, x, y) {
const at = pieceAt(pos);
const next = [...pos];
next[at[x]] = y;
next[at[y]] = x;
return next;
}
// Distance d'un morceau à sa case : 0 en place, 1 dans sa rangée ou sa colonne, 2 sinon (il lui faut un relais).
const weight = (cols, piece, cell) => (cell === piece ? 0 : aligned(cols, cell, piece) ? 1 : 2);
function legalPairs(cols, count) {
const pairs = [];
for (let x = 0; x < count; x += 1) for (let y = x + 1; y < count; y += 1) if (aligned(cols, x, y)) pairs.push([x, y]);
return pairs;
}
// Recherche en faisceau : le meilleur nombre d'échanges trouvé pour finir, et le premier échange de cette solution.
// Déterministe : à égalité, l'ordre des échanges départage. Ne garde que les échanges qui ne font pas reculer.
export function solve(pos, cols, width = SOLVER_WIDTH) {
const count = pos.length;
const pairs = legalPairs(cols, count);
const total = pos.reduce((sum, cell, piece) => sum + weight(cols, piece, cell), 0);
let layer = [{ pos, at: pieceAt(pos), score: total, first: null }];
const seen = new Set([pos.join()]);
for (let depth = 0; depth <= 4 * count; depth += 1) {
const done = layer.find((state) => isSolved(state.pos));
if (done) return { length: depth, first: done.first };
const next = [];
for (const state of layer) {
for (const [x, y] of pairs) {
const a = state.at[x], b = state.at[y];
const delta = weight(cols, a, y) + weight(cols, b, x) - weight(cols, a, x) - weight(cols, b, y);
if (delta > 0) continue;
const nextPos = [...state.pos];
nextPos[a] = y;
nextPos[b] = x;
const key = nextPos.join();
if (seen.has(key)) continue;
seen.add(key);
const at = [...state.at];
at[x] = b;
at[y] = a;
// Poser deux morceaux d'un coup départage deux échanges de même progression.
next.push({ pos: nextPos, at, score: state.score + delta - ((y === a) + (x === b)) * 0.1, first: state.first || [x, y], order: next.length });
}
}
if (!next.length) break;
next.sort((left, right) => left.score - right.score || left.order - right.order);
layer = next.slice(0, width);
}
// Filet : chaque morceau se pose en deux échanges au plus.
return { length: 2 * (count - placedCount(pos)), first: null };
}
// Échanges permis à la limite d'une partie : la référence de l'ordinateur et la marge du mode.
export const swapLimit = (par, margin) => par + margin;
// Gain d'une image reconstituée : la base, plus une part par échange restant.
export const mirrorReward = ({ base, perSwap }, left) => base + perSwap * Math.max(0, left);
// Coups de main d'un compagnon : ses spécialités, ou l'Équilibré s'il n'en a pas.
export const helpsOf = (specialties) => (specialties.length ? [...specialties] : [BALANCED_HELP]);
// --- Illustrations -------------------------------------------------------------------------------------------------------
const imageOf = (card, mode) => (MIRROR_MODES[mode].format === "portrait" ? card.fullImage : card.image);
// Illustrations jouables d'un mode : cartes des collections ouvertes, possédées ou non, avec l'illustration du bon format, et pas
// trop unies. Une carte que le script de mesure n'a pas encore vue n'est pas jouable (le test des données le signale).
export function mirrorCandidates(catalog, measures, mode) {
const active = new Set(catalog.collections.filter((collection) => collection.active).map((collection) => collection.id));
const format = MIRROR_MODES[mode].format;
return catalog.cards.filter((card) => {
if (!active.has(card.collectionId) || !imageOf(card, mode)) return false;
const measure = measures?.[format]?.[card.id];
return Boolean(measure) && measure.ambiguous / measure.pieces <= MAX_AMBIGUOUS_SHARE;
});
}
export function mirrorImage(catalog, cardId, mode) {
const card = catalog.cards.find((item) => item.id === cardId);
return card ? imageOf(card, mode) : null;
}
// `excluded` : cartes récentes ou à ne pas dévoiler (Carte du jour du joueur). Sans autre choix, on les reprend.
export function drawIllustration(candidates, excluded, random = defaultRandom) {
if (!candidates.length) return null;
const fresh = candidates.filter((card) => !excluded.has(card.id));
const pool = fresh.length ? fresh : candidates;
return pool[random(pool.length)].id;
}

View file

@ -0,0 +1,318 @@
// Rôle : applique les règles du Miroir brisé avec la base (Difficile du jour, parties, échanges, coups de main, gains, réglages).
// Branché sur CardsService (`service.mirror`) : il réutilise sa base, son horloge, son hasard, son audit et l'Équipe du jour.
// Le serveur garde la place des morceaux : le client ne reçoit que des cases, et l'image déjà mélangée (mirror-image.js).
import { readFileSync } from "node:fs";
import { dailyDayKey, isDayKey, nextDailyAt, shiftDayKey } from "./daily.js";
import {
aligned, BALANCED_HELP, cellCount, drawIllustration, ENDURANCE_EXTRA, HELPERS_PER_GAME, helpsOf, isSolved, mirrorCandidates, mirrorImage, mirrorReward, MIRROR_MODE_IDS, MIRROR_MODES,
MIRROR_REPEAT_DAYS, pieceAt, placedCells, placedCount, scramble, solve, swapCells, swapLimit
} from "./mirror-rules.js";
import { DEFAULT_MIRROR_SETTINGS, mirrorSettingsError, normalizeMirrorSettings, readMirrorSettings } from "./mirror-settings.js";
import { specialtiesOf } from "./team-rules.js";
export const DEFAULT_MIRROR_MEASURES_PATH = new URL("./content/mirror-illustrations.json", import.meta.url);
export function loadMirrorMeasures(path = DEFAULT_MIRROR_MEASURES_PATH) {
return JSON.parse(readFileSync(path, "utf8"));
}
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
const validMode = (mode) => MIRROR_MODE_IDS.includes(mode);
export class MirrorService {
constructor(cards, measures = loadMirrorMeasures()) {
this.cards = cards;
this.db = cards.db;
this.measures = measures;
this.random = (max) => cards.random(max);
}
get today() {
return dailyDayKey(this.cards.now());
}
// --- Réglages -----------------------------------------------------------------------------------------------------------
get settings() {
const row = this.db.prepare("SELECT settings_json FROM mirror_settings WHERE id = 1").get();
return readMirrorSettings(JSON.parse(row?.settings_json || "{}"), (error) => console.error(`Invalid stored mirror settings, using defaults: ${error}`));
}
// Le jour en cours : l'illustration du Difficile, les parties commencées, gagnées et perdues par mode, la poussière versée.
adminSummary(day = this.today) {
const hard = this.db.prepare("SELECT card_id, par FROM mirror_days WHERE day = ?").get(day);
const rows = this.db.prepare("SELECT mode, status, COUNT(*) AS count, COALESCE(SUM(reward), 0) AS stardust FROM mirror_games WHERE day = ? GROUP BY mode, status").all(day);
const games = Object.fromEntries(MIRROR_MODE_IDS.map((mode) => {
const of = (status) => rows.find((row) => row.mode === mode && row.status === status)?.count ?? 0;
return [mode, { started: of("playing") + of("won") + of("lost"), won: of("won"), lost: of("lost") }];
}));
return { day, hard: hard ? { cardId: hard.card_id, par: hard.par } : null, games, stardust: rows.reduce((sum, row) => sum + row.stardust, 0) };
}
adminSettings() {
return { today: this.adminSummary(), settings: this.settings, defaults: normalizeMirrorSettings(DEFAULT_MIRROR_SETTINGS), updatedAt: this.db.prepare("SELECT updated_at FROM mirror_settings WHERE id = 1").get()?.updated_at ?? 0 };
}
// Une partie commencée garde la limite et les gains de son début.
updateSettings(adminId, settings) {
this.cards.requireAdmin(adminId);
const error = mirrorSettingsError(settings);
if (error) fail(400, "MIRROR_SETTINGS_INVALID", error);
const previous = this.settings;
const next = normalizeMirrorSettings(settings);
if (JSON.stringify(previous) === JSON.stringify(next)) fail(409, "MIRROR_SETTINGS_UNCHANGED", "Ces réglages sont déjà en vigueur.");
this.cards.database.transaction(() => {
this.db.prepare("UPDATE mirror_settings SET settings_json = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(JSON.stringify(next), this.cards.now(), adminId);
this.cards.audit(adminId, "mirror_settings_updated", "mirror", { previous, next });
});
return { mirrorSettings: this.adminSettings() };
}
requireOpen() {
if (!this.settings.enabled) fail(409, "MIRROR_CLOSED", "Le Miroir brisé est fermé pour le moment.");
}
// --- Lectures -----------------------------------------------------------------------------------------------------------
candidates(mode) {
return mirrorCandidates(this.cards.catalog, this.measures, mode);
}
// Difficile du jour, le même pour tous : illustration, mélange et meilleur résultat de l'ordinateur. À appeler dans une transaction.
ensureHardDay(day) {
const read = () => this.db.prepare("SELECT card_id, start_json, par FROM mirror_days WHERE day = ?").get(day);
if (!read()) {
const recent = new Set(this.db.prepare("SELECT card_id FROM mirror_days WHERE day >= ?").all(shiftDayKey(day, -MIRROR_REPEAT_DAYS)).map((row) => row.card_id));
const cardId = drawIllustration(this.candidates("hard"), recent, this.random);
if (!cardId) fail(409, "MIRROR_UNAVAILABLE", "Aucune illustration ne peut être tirée aujourd’hui.");
const start = scramble(cellCount("hard"), this.random);
this.db.prepare("INSERT INTO mirror_days(day, card_id, start_json, par, created_at) VALUES (?, ?, ?, ?, ?)").run(day, cardId, JSON.stringify(start), solve(start, MIRROR_MODES.hard.cols).length, this.cards.now());
}
const row = read();
return { cardId: row.card_id, start: JSON.parse(row.start_json), par: row.par };
}
hardNumber(day) {
return this.db.prepare("SELECT COUNT(*) AS count FROM mirror_days WHERE day <= ?").get(day).count;
}
gameRow(playerId, day, mode) {
const row = this.db.prepare("SELECT card_id, status, state_json, reward, started_at, finished_at FROM mirror_games WHERE player_id = ? AND day = ? AND mode = ?").get(playerId, day, mode);
return row ? { mode, cardId: row.card_id, status: row.status, state: JSON.parse(row.state_json), reward: row.reward, startedAt: row.started_at, finishedAt: row.finished_at } : null;
}
// Carte du jour du joueur encore à trouver : le Miroir ne doit pas la montrer.
pendingDailyCard(playerId, day) {
const row = this.db.prepare("SELECT card_id FROM daily_attempts WHERE player_id = ? AND day = ? AND status = 'playing'").get(playerId, day);
return row?.card_id ?? null;
}
// Le Difficile s'ouvre une fois le Normal terminé ; il attend aussi la fin de la Carte du jour s'il en montre la réponse.
hardLock(playerId, day) {
const normal = this.gameRow(playerId, day, "normal");
if (!normal || normal.status === "playing") return "normal";
const daily = this.pendingDailyCard(playerId, day);
if (daily && daily === this.db.prepare("SELECT card_id FROM mirror_days WHERE day = ?").get(day)?.card_id) return "daily";
return null;
}
// Compagnons de l'Équipe du jour qui peuvent donner un coup de main : il faut une équipe prête et l'Équipe ouverte.
teamHelpers(playerId) {
if (!this.cards.team.settings.enabled) return [];
const team = this.cards.team.activeTeam(playerId);
return team ? team.companions.map((companion) => ({ cardId: companion.cardId, helps: helpsOf(specialtiesOf(companion.profile)) })) : [];
}
gameView(game) {
const { cols, rows, placedShown } = MIRROR_MODES[game.mode];
const { state } = game;
const finished = game.status !== "playing";
return {
mode: game.mode, status: game.status, cols, rows, moves: state.moves, swaps: state.swaps, limit: state.limit + state.extra, left: state.limit + state.extra - state.swaps,
rewards: state.rewards, reward: game.reward,
// Contour vert du Normal : les cases dont le morceau est à sa place. Le Difficile n'en montre aucune avant la fin.
placed: placedShown || finished ? placedCells(state.pos) : [],
placedCount: finished ? placedCount(state.pos) : null,
helpers: state.helpers, used: state.used, helpersLocked: state.swaps > 0 || Object.keys(state.used).length > 0, freeSwap: state.free, hint: state.hint,
lastMove: state.lastMove,
// L'illustration et la référence de l'ordinateur ne se montrent qu'à la fin.
cardId: finished ? game.cardId : null, par: finished ? state.par : null
};
}
view(playerId) {
const day = this.today;
const settings = this.settings;
const games = Object.fromEntries(MIRROR_MODE_IDS.map((mode) => {
const game = this.gameRow(playerId, day, mode);
return [mode, game ? this.gameView(game) : null];
}));
const hardDay = this.db.prepare("SELECT 1 FROM mirror_days WHERE day = ?").get(day);
return {
enabled: settings.enabled, day, nextAt: nextDailyAt(this.cards.now()), number: hardDay ? this.hardNumber(day) : this.hardNumber(day) + 1,
rewards: settings.rewards, games, hardLock: this.hardLock(playerId, day), helpersPerGame: HELPERS_PER_GAME, enduranceExtra: ENDURANCE_EXTRA,
team: this.teamHelpers(playerId),
devReset: Boolean(this.cards.devPerks)
};
}
// Résumé pour la Guilde, sans rien tirer.
summary(playerId) {
const day = this.today;
const status = (mode) => this.db.prepare("SELECT status FROM mirror_games WHERE player_id = ? AND day = ? AND mode = ?").get(playerId, day, mode)?.status ?? "none";
return { enabled: this.settings.enabled, normal: status("normal"), hard: status("hard"), hardLock: this.hardLock(playerId, day) };
}
// Image mélangée de la partie du jour, dans l'état où elle est ; `model` : l'illustration en ordre, pour le modèle au survol.
image(playerId, mode, { model = false } = {}) {
if (!validMode(mode)) fail(400, "MIRROR_INVALID", "Demande invalide.");
const game = this.gameRow(playerId, this.today, mode);
if (!game) fail(404, "MIRROR_NOT_STARTED", "Aucune partie en cours.");
const image = mirrorImage(this.cards.catalog, game.cardId, mode);
if (!image) fail(503, "MIRROR_UNAVAILABLE", "Cette illustration est indisponible.");
const { cols, rows, format } = MIRROR_MODES[mode];
return { image, cols, rows, format, at: model ? game.state.pos.map((_, piece) => piece) : pieceAt(game.state.pos) };
}
// --- Parties ------------------------------------------------------------------------------------------------------------
start(playerId, { day, mode } = {}) {
if (!isDayKey(day) || !validMode(mode)) fail(400, "MIRROR_INVALID", "Demande invalide.");
this.requireOpen();
this.cards.database.transaction(() => {
const today = this.today;
if (day !== today) fail(409, "MIRROR_EXPIRED", "Un nouveau jour a commencé : rechargez la page.");
// Commencer deux fois (double clic, deux onglets) rend simplement la partie.
if (this.gameRow(playerId, today, mode)) return;
let cardId, start, par;
if (mode === "hard") {
({ cardId, start, par } = this.ensureHardDay(today));
const lock = this.hardLock(playerId, today);
if (lock === "normal") fail(409, "MIRROR_HARD_LOCKED", "Terminez d’abord le Normal du jour.");
if (lock === "daily") fail(409, "MIRROR_DAILY_FIRST", "Trouvez d’abord votre Carte du jour.");
} else {
const recent = new Set(this.db.prepare("SELECT card_id FROM mirror_games WHERE player_id = ? AND mode = 'normal' AND day >= ?").all(playerId, shiftDayKey(today, -MIRROR_REPEAT_DAYS)).map((row) => row.card_id));
const daily = this.pendingDailyCard(playerId, today);
if (daily) recent.add(daily);
// Jamais la même illustration que le Difficile du jour.
recent.add(this.ensureHardDay(today).cardId);
cardId = drawIllustration(this.candidates("normal"), recent, this.random);
if (!cardId) fail(409, "MIRROR_UNAVAILABLE", "Aucune illustration ne peut être tirée aujourd’hui.");
start = scramble(cellCount("normal"), this.random);
par = solve(start, MIRROR_MODES.normal.cols).length;
}
const settings = this.settings;
const state = { start, pos: start, swaps: 0, moves: 0, history: [], par, limit: swapLimit(par, settings.margins[mode]), rewards: settings.rewards[mode], helpers: [], used: {}, extra: 0, free: false, hint: null, lastMove: null };
this.db.prepare("INSERT INTO mirror_games(player_id, day, mode, card_id, status, state_json, reward, started_at, finished_at) VALUES (?, ?, ?, ?, 'playing', ?, 0, ?, NULL)")
.run(playerId, today, mode, cardId, JSON.stringify(state), this.cards.now());
});
return this.result(playerId);
}
// Applique `apply(state, game)` à la partie du jour, puis la termine si l'image est reconstituée ou les échanges épuisés.
// `moves` : les coups que le client a vus ; un envoi en double (double clic, deux onglets) ne joue pas deux fois.
change(playerId, { day, mode, moves }, apply) {
if (!isDayKey(day) || !validMode(mode)) fail(400, "MIRROR_INVALID", "Demande invalide.");
this.cards.database.transaction(() => {
const today = this.today;
if (day !== today) fail(409, "MIRROR_EXPIRED", "Un nouveau jour a commencé : rechargez la page.");
const game = this.gameRow(playerId, today, mode);
if (!game) fail(409, "MIRROR_NOT_STARTED", "Aucune partie en cours.");
if (game.status !== "playing") fail(409, "MIRROR_FINISHED", "Cette partie est terminée.");
if (moves !== undefined && moves !== game.state.moves) return;
const state = structuredClone(game.state);
apply(state, game);
this.save(playerId, today, game, state);
});
return this.result(playerId);
}
save(playerId, day, game, state) {
const left = state.limit + state.extra - state.swaps;
const status = isSolved(state.pos) ? "won" : left <= 0 ? "lost" : "playing";
const reward = status === "won" ? mirrorReward(state.rewards, left) : 0;
this.db.prepare("UPDATE mirror_games SET status = ?, state_json = ?, reward = ?, finished_at = ? WHERE player_id = ? AND day = ? AND mode = ? AND status = 'playing'")
.run(status, JSON.stringify(state), reward, status === "playing" ? null : this.cards.now(), playerId, day, game.mode);
if (status === "playing") return;
if (reward) this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(reward, playerId);
const helps = Object.values(state.used);
this.cards.audit(playerId, "mirror_finished", day, { mode: game.mode, won: status === "won", swaps: state.swaps, par: state.par, stardust: reward, cardId: game.cardId, helps });
}
swap(playerId, { day, mode, from, to, moves } = {}) {
const count = validMode(mode) ? cellCount(mode) : 0;
const cell = (value) => Number.isInteger(value) && value >= 0 && value < count;
if (!cell(from) || !cell(to) || from === to || !Number.isInteger(moves)) fail(400, "MIRROR_INVALID", "Demande invalide.");
return this.change(playerId, { day, mode, moves }, (state) => {
if (!state.free && !aligned(MIRROR_MODES[mode].cols, from, to)) fail(409, "MIRROR_SWAP_INVALID", "On n’échange que deux morceaux de la même rangée ou de la même colonne.");
state.pos = swapCells(state.pos, from, to);
state.swaps += 1;
state.moves += 1;
state.history.push([from, to]);
state.free = false;
state.hint = null;
state.lastMove = [from, to];
});
}
// Compagnons choisis pour la partie, jusqu'au premier échange ou au premier coup de main.
chooseHelpers(playerId, { day, mode, cardIds } = {}) {
if (!Array.isArray(cardIds) || cardIds.length > HELPERS_PER_GAME || new Set(cardIds).size !== cardIds.length) fail(400, "MIRROR_INVALID", "Demande invalide.");
return this.change(playerId, { day, mode }, (state) => {
if (state.swaps > 0 || Object.keys(state.used).length) fail(409, "MIRROR_HELPERS_LOCKED", "Les compagnons se choisissent avant le premier échange.");
const team = new Map(this.teamHelpers(playerId).map((helper) => [helper.cardId, helper]));
if (cardIds.some((cardId) => !team.has(cardId))) fail(409, "MIRROR_HELPER_INVALID", "Ce compagnon n’est pas dans votre équipe.");
state.helpers = cardIds.map((cardId) => team.get(cardId));
});
}
// Coup de main d'un compagnon choisi, une fois par partie. Une double spécialité dit lequel de ses deux coups de main.
useHelp(playerId, { day, mode, cardId, help, moves } = {}) {
if (typeof cardId !== "string" || typeof help !== "string" || !Number.isInteger(moves)) fail(400, "MIRROR_INVALID", "Demande invalide.");
return this.change(playerId, { day, mode, moves }, (state) => {
const helper = state.helpers.find((item) => item.cardId === cardId);
if (!helper || !helper.helps.includes(help)) fail(409, "MIRROR_HELPER_INVALID", "Ce coup de main n’est pas disponible.");
if (state.used[cardId]) fail(409, "MIRROR_HELP_USED", "Ce compagnon a déjà donné son coup de main.");
const { cols } = MIRROR_MODES[mode];
state.lastMove = null;
if (help === "endurance") state.extra += ENDURANCE_EXTRA;
if (help === "bravoure") state.free = true;
if (help === "orientation") state.hint = solve(state.pos, cols).first;
if (help === "fortune") {
const misplaced = state.pos.flatMap((cell, piece) => (cell === piece ? [] : [piece]));
const piece = misplaced[this.random(misplaced.length)];
state.lastMove = [state.pos[piece], piece];
state.pos = swapCells(state.pos, state.pos[piece], piece);
state.hint = null;
}
if (help === BALANCED_HELP) {
const last = state.history.pop();
if (!last) fail(409, "MIRROR_NOTHING_TO_UNDO", "Aucun échange à reprendre.");
state.pos = swapCells(state.pos, last[0], last[1]);
state.swaps -= 1;
state.lastMove = last;
state.hint = null;
}
state.used[cardId] = help;
state.moves += 1;
});
}
result(playerId) {
return { mirror: this.view(playerId), state: this.cards.getState(playerId) };
}
// Serveur Vite local (`devPerks`) : efface les parties du jour du joueur, pour rejouer.
resetForTests(playerId) {
if (!this.cards.devPerks) fail(404, "NOT_FOUND", "Remise à zéro indisponible.");
this.db.prepare("DELETE FROM mirror_games WHERE player_id = ?").run(playerId);
return this.result(playerId);
}
forgetPlayer(playerId) {
this.db.prepare("DELETE FROM mirror_games WHERE player_id = ?").run(playerId);
}
}

View file

@ -0,0 +1,47 @@
// Rôle : réglages du Miroir brisé (ouverture, gains, marges d'échanges) : valeurs par défaut, validation et lecture tolérante.
import { MIRROR_MODE_IDS } from "./mirror-rules.js";
const MAX_REWARD = 100_000;
const MAX_MARGIN = 30;
// Gains : base d'une image reconstituée et part par échange restant. Repères : la Carte du jour rapporte 20 en production et la
// Course 20 / 15 / 10 / 5. Marges : échanges permis au-delà du meilleur résultat de l'ordinateur ; en Normal, un joueur attentif
// réussit environ 9 fois sur 10 avec 3 (simulation, docs/miroir-brise.md).
export const DEFAULT_MIRROR_SETTINGS = Object.freeze({
enabled: false,
rewards: Object.freeze({ normal: Object.freeze({ base: 10, perSwap: 1 }), hard: Object.freeze({ base: 20, perSwap: 2 }) }),
margins: Object.freeze({ normal: 3, hard: 6 })
});
export function mirrorSettingsError(settings) {
const integer = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
if (!settings || typeof settings !== "object" || Array.isArray(settings)) return "Réglages du Miroir brisé invalides.";
if (typeof settings.enabled !== "boolean") return "L’ouverture du Miroir brisé doit être vraie ou fausse.";
for (const mode of MIRROR_MODE_IDS) {
const reward = settings.rewards?.[mode];
if (!reward || !integer(reward.base, MAX_REWARD) || !integer(reward.perSwap, MAX_REWARD)) return `Gains du Miroir brisé : des entiers entre 0 et ${MAX_REWARD.toLocaleString("fr-FR")}.`;
if (!integer(settings.margins?.[mode], MAX_MARGIN)) return `Marges d’échanges : des entiers entre 0 et ${MAX_MARGIN}.`;
}
return null;
}
// Garde seulement les champs connus.
export const normalizeMirrorSettings = ({ enabled, rewards, margins }) => ({
enabled,
rewards: Object.fromEntries(MIRROR_MODE_IDS.map((mode) => [mode, { base: rewards[mode].base, perSwap: rewards[mode].perSwap }])),
margins: Object.fromEntries(MIRROR_MODE_IDS.map((mode) => [mode, margins[mode]]))
});
// Réglages enregistrés : des valeurs invalides laissent la place aux valeurs par défaut, pour que le jeu reste jouable.
export function readMirrorSettings(stored, onInvalid = () => {}) {
const defaults = DEFAULT_MIRROR_SETTINGS;
const merged = {
...defaults, ...stored,
rewards: Object.fromEntries(MIRROR_MODE_IDS.map((mode) => [mode, { ...defaults.rewards[mode], ...stored?.rewards?.[mode] }])),
margins: { ...defaults.margins, ...stored?.margins }
};
const error = mirrorSettingsError(merged);
if (!error) return normalizeMirrorSettings(merged);
onInvalid(error);
return normalizeMirrorSettings({ ...defaults, enabled: stored?.enabled === true });
}

View file

@ -10,6 +10,7 @@ import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedit
import { ExpeditionService } from "./expedition-service.js";
import { MAX_GOLD_RESERVE } from "./team-rules.js";
import { TeamService } from "./team-service.js";
import { MirrorService } from "./mirror-service.js";
const TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
@ -42,7 +43,7 @@ const ADMIN_HISTORY_PAGE_SIZE = 50;
const PLAYER_HISTORY_EVENTS = Object.freeze([
"welcome_opening", "pack_opened", "gift_pack_opened", "cards_recycled", "opening_purchased", "campaign_claimed",
"trade_created", "trade_received", "trade_declined", "trade_joined", "trade_completed", "trade_cancelled",
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild", "expedition_dissolved", "card_upgraded", "eclats_converted", "item_used", "destination_starter", "card_plan_changed", "item_bought", "team_recruited", "race_finished", "daily_reward_chosen"
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild", "expedition_dissolved", "card_upgraded", "eclats_converted", "item_used", "destination_starter", "card_plan_changed", "item_bought", "team_recruited", "race_finished", "daily_reward_chosen", "mirror_finished"
]);
const DEV_STARDUST = 1000;
const DELETED_PLAYER_NAME = "Joueur supprimé";
@ -74,7 +75,7 @@ const FLARE_ERROR_MESSAGES = {
export class CardsService {
// `destinations` : destinations des Expéditions validées ; sans elles, celles du dépôt (services/cards/content).
// `alerts` : { available, publicOrigin } pour les alertes Discord des Expéditions (bot configuré, lien des messages).
constructor({ database, catalog, now = Date.now, random, devPerks = false, destinations = null, dailyClues = null, alerts = {} } = {}) {
constructor({ database, catalog, now = Date.now, random, devPerks = false, destinations = null, dailyClues = null, mirrorMeasures = undefined, alerts = {} } = {}) {
// Serveur Vite local uniquement : ressources permanentes du compte de développement pour tester le jeu sans attendre.
this.devPerks = devPerks;
this.database = database;
@ -87,6 +88,7 @@ export class CardsService {
this.dailyClues = dailyClues || loadDailyClues();
this.reloadCatalog();
this.team = new TeamService(this);
this.mirror = new MirrorService(this, mirrorMeasures);
this.expeditions = new ExpeditionService(this, destinations || loadExpeditionDestinations(DEFAULT_DESTINATIONS_PATH, catalog), alerts);
}
@ -675,6 +677,7 @@ export class CardsService {
shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward, stardustPerEclat: this.expeditions.settings.progression.stardustPerEclat, oblivionPrice: this.expeditions.settings.progression.oblivionPrice, windRosePrice: this.expeditions.settings.progression.windRosePrice },
daily: this.dailySummary(playerId),
team: this.team.summary(playerId),
mirror: this.mirror.summary(playerId),
expeditions: this.expeditions.summary(playerId),
cardProgress: this.expeditions.cardProgressView(playerId),
equipment: this.expeditions.equipmentChoices(playerId),
@ -766,6 +769,7 @@ export class CardsService {
daily: this.dailyAdminSummary(),
expeditionSettings: this.expeditions.adminSettings(),
teamSettings: this.team.adminSettings(),
mirrorSettings: this.mirror.adminSettings(),
expeditionsToday: this.expeditions.adminSummary(),
packActivity7d,
campaigns: this.campaignSummaries(),
@ -1221,6 +1225,7 @@ export class CardsService {
this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE player_id = ? AND status = 'pending'").run(this.now(), playerId);
this.expeditions.forgetPlayer(playerId);
this.team.forgetPlayer(playerId);
this.mirror.forgetPlayer(playerId);
this.expeditions.forgetAlertsInTx(playerId);
this.expeditions.forgetItemsInTx(playerId);
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts", "card_progress", "card_equipment"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);