Each core file of services/cards now says where it sits, its entry points, who calls it and what to watch for: admin checks living in the service, the methods added to ExpeditionService and TeamService by Object.assign, the InTx suffix, settings defaults that do not change an existing database, and rules shared with the browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
341 lines
20 KiB
JavaScript
341 lines
20 KiB
JavaScript
/**
|
||
* @file Miroir brisé de Sokko TCG côté serveur : illustration commune du Difficile du jour, parties Facile,
|
||
* Normal et Difficile, échanges de morceaux, coups de main de l'Équipe du jour, gains et réglages.
|
||
*
|
||
* Contexte : sous-service créé par CardsService (`service.mirror`), qui lui fournit base, horloge, hasard et
|
||
* audit (`this.cards`) ; il lit l'équipe active par `this.cards.team`.
|
||
* Points d'entrée : `view(playerId)`, `start`, `swap`, `useHelp`, `image` (servie par mirror-image.js),
|
||
* `summary`, `updateSettings`, `forgetPlayer`.
|
||
* Utilisé par : service.js ; api.js par `service.mirror`.
|
||
* Dépend de : mirror-rules.js, mirror-settings.js, team-rules.js, content/mirror-illustrations.json (mesures
|
||
* produites par scripts/mirror-illustrations.mjs).
|
||
* Attention :
|
||
* - Le serveur garde la place des morceaux : le navigateur ne reçoit que des cases et l'image déjà mélangée.
|
||
* - `resetForTests` n'est exposée par api.js qu'au serveur de développement (`devPerks`).
|
||
* @see docs/miroir-brise.md
|
||
*/
|
||
|
||
import { readFileSync } from "node:fs";
|
||
import { dailyDayKey, isDayKey, nextDailyAt, shiftDayKey } from "./daily.js";
|
||
import {
|
||
aligned, BALANCED_HELP, cellCount, drawIllustration, HELPERS_PER_GAME, helpsOf, isSolved, EXTRA_MOVES, mirrorCandidates, mirrorImage, mirrorReward, MIRROR_MODE_IDS, MIRROR_MODES,
|
||
MIRROR_REPEAT_DAYS, minSwaps, pieceAt, placedCells, placedCount, previousMode, 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;
|
||
}
|
||
|
||
// Verrou d'un mode : le mode précédent pas encore terminé (Facile → Normal → Difficile) ; le Difficile attend aussi la fin de la
|
||
// Carte du jour s'il en montre la réponse. null : le mode peut se jouer.
|
||
lockOf(playerId, day, mode) {
|
||
const previous = previousMode(mode);
|
||
if (previous) {
|
||
const game = this.gameRow(playerId, day, previous);
|
||
if (!game || game.status === "playing") return previous;
|
||
}
|
||
if (mode === "hard") {
|
||
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;
|
||
}
|
||
|
||
locks(playerId, day) {
|
||
return Object.fromEntries(MIRROR_MODE_IDS.map((mode) => [mode, this.lockOf(playerId, day, mode)]));
|
||
}
|
||
|
||
// 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, placedOnHover } = 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 : les cases dont le morceau est à sa place ; en Difficile, il ne se voit qu'au survol du morceau.
|
||
placed: placedCells(state.pos), placedOnHover: Boolean(placedOnHover),
|
||
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: Boolean(MIRROR_MODES[game.mode].freeSwaps), treasure: Boolean(state.treasure), hint: state.hint,
|
||
// Modèle visible : jusqu'au premier mouvement, puis à la fin.
|
||
modelOpen: finished || state.moves === 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, locks: this.locks(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, ...Object.fromEntries(MIRROR_MODE_IDS.map((mode) => [mode, status(mode)])), locks: this.locks(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 que jusqu'au premier mouvement, puis à la fin.
|
||
if (model && game.status === "playing" && game.state.moves > 0) 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.lockOf(playerId, today, mode);
|
||
if (lock === "daily") fail(409, "MIRROR_DAILY_FIRST", "Trouvez d’abord votre Carte du jour.");
|
||
if (lock) fail(409, "MIRROR_LOCKED", lock === "easy" ? "Terminez d’abord le Facile du jour." : "Terminez d’abord le Normal du jour.");
|
||
if (mode !== "hard") {
|
||
const recent = new Set(this.db.prepare("SELECT card_id FROM mirror_games WHERE player_id = ? AND mode = ? AND day >= ?").all(playerId, mode, 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, ni qu'une autre partie du jour.
|
||
recent.add(this.ensureHardDay(today).cardId);
|
||
for (const row of this.db.prepare("SELECT card_id FROM mirror_games WHERE player_id = ? AND day = ?").all(playerId, today)) recent.add(row.card_id);
|
||
cardId = drawIllustration(this.candidates(mode), recent, this.random);
|
||
if (!cardId) fail(409, "MIRROR_UNAVAILABLE", "Aucune illustration ne peut être tirée aujourd’hui.");
|
||
start = scramble(cellCount(mode), this.random);
|
||
// Le Facile se compare au minimum d'échanges libres ; le Normal au meilleur résultat de l'ordinateur en rangée ou colonne.
|
||
par = MIRROR_MODES[mode].freeSwaps ? minSwaps(start) : solve(start, MIRROR_MODES[mode].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, 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 (!MIRROR_MODES[mode].freeSwaps && !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.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 tous vos coups de main.");
|
||
state.lastMove = null;
|
||
// Bravoure : un morceau mal placé, tiré au hasard, va à sa place sans compter de mouvement.
|
||
if (help === "bravoure") {
|
||
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;
|
||
}
|
||
// 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;
|
||
// Équilibré : quelques mouvements de plus ; restants à la fin, ils rapportent comme les autres.
|
||
if (help === BALANCED_HELP) state.extra += EXTRA_MOVES;
|
||
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);
|
||
}
|
||
}
|