sokko-g/services/cards/mirror-service.js
Shinuwa 8c0771f06f
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 23m32s
Validate and deploy Sokko G / deploy (push) Successful in 16s
Rework the Broken Mirror screens and the Guild quest board
The mirror page opens on two illustrated cards, Normal and Hard, painted
with Codex, with three small rule reminders; a card opens or starts its
game. The five companions of the daily team show as tiles: one click uses
a help, two per game, with no selection step. Helps are renamed after
what they do (swap anywhere, show a piece's place, double the rewards,
undo the last move, see the model again), use the shared tooltip and
keep the same height. Selecting a piece no longer waits for the server,
and showing a place aims at the selected piece. Under 960 px of
dashboard, like the section menu, the board goes on top and the moves
panel keeps only the count. Stardust is always written in full.

The Guild board shows four tiles per row on full screen, aligned with
subgrids, solo quests first. Status lines give way to a wooden "Fait"
sign on finished quests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:25:35 +01:00

310 lines
18 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 : 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, HELPERS_PER_GAME, helpsOf, isSolved, MODEL_PEEK_MS, mirrorCandidates, mirrorImage, mirrorReward, MIRROR_MODE_IDS, MIRROR_MODES,
MIRROR_REPEAT_DAYS, pieceAt, placedCells, placedCount, scramble, solve, swapCells, swapLimit, TREASURE_FACTOR
} 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,
// Coups de main donnés (compagnon → coup de main) et ceux qui restent, chez les compagnons de son choix.
used: state.used, helpsLeft: Math.max(0, HELPERS_PER_GAME - Object.keys(state.used).length), freeSwap: state.free, treasure: Boolean(state.treasure), hint: state.hint,
// Modèle visible : jusqu'au premier mouvement, pendant un « Voir le modèle » (instant de fin donné), puis à la fin.
modelOpen: finished || state.moves === 0, peekUntil: state.peekUntil ?? 0,
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,
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];
// Le modèle ne se voit librement que jusqu'au premier mouvement ; ensuite, grâce à l'Équilibré, ou à la fin.
const { state } = game;
if (model && game.status === "playing" && state.moves > 0 && this.cards.now() > (state.peekUntil ?? 0) + 1_000) fail(403, "MIRROR_MODEL_HIDDEN", "Le modèle n’est plus visible.");
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], used: {}, extra: 0, free: false, double: 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) * (state.treasure ? TREASURE_FACTOR : 1) : 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];
});
}
// Coup de main d'un compagnon de l'Équipe du jour, au choix du joueur et quand il veut : HELPERS_PER_GAME par partie, un par
// compagnon. Une double spécialité dit lequel de ses deux coups de main ; l'Orientation dit aussi sur quel morceau (`cell`).
useHelp(playerId, { day, mode, cardId, help, moves, cell } = {}) {
if (typeof cardId !== "string" || typeof help !== "string" || !Number.isInteger(moves)) fail(400, "MIRROR_INVALID", "Demande invalide.");
if (help === "orientation" && !(Number.isInteger(cell) && cell >= 0 && cell < (validMode(mode) ? cellCount(mode) : 0))) fail(400, "MIRROR_INVALID", "Demande invalide.");
return this.change(playerId, { day, mode, moves }, (state) => {
const helper = this.teamHelpers(playerId).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.");
if (Object.keys(state.used).length >= HELPERS_PER_GAME) fail(409, "MIRROR_HELPS_EXHAUSTED", "Vous avez déjà reçu vos deux coups de main.");
state.lastMove = null;
if (help === "bravoure") state.free = true;
// Où va ce morceau ? La case choisie et la vraie case du morceau qui s'y trouve.
if (help === "orientation") state.hint = [cell, pieceAt(state.pos)[cell]];
if (help === "fortune") state.treasure = true;
if (help === BALANCED_HELP) state.peekUntil = this.cards.now() + MODEL_PEEK_MS;
if (help === "endurance") {
const last = state.history.pop();
if (!last) fail(409, "MIRROR_NOTHING_TO_UNDO", "Aucun mouvement à 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);
}
}