Add an Easy mirror before Normal and let every companion help
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 23m41s
Validate and deploy Sokko G / deploy (push) Successful in 16s

Easy is a square 4 x 4 picture drawn for each player, with green
outlines, where any two pieces swap; it is scored against the free
minimum and pays 5 plus 1 per move left. The three mirrors open one
after another (Easy, Normal, Hard) and the Guild quest is done with all
three. Migration 31 rebuilds mirror_games to accept the new mode. The
mirror page shows three illustrated cards, Easy painted with Codex.

Bravery now places a misplaced piece for free, since swapping anywhere
means nothing in Easy. Each of the five companions can help once per
game instead of two in all. Mirror styles now win over the global
button hover, so placed pieces keep their green outline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-28 18:27:02 +01:00
parent 4321559831
commit ebb220d532
18 changed files with 276 additions and 146 deletions

View file

@ -595,6 +595,25 @@ export const MIGRATIONS = [
PRIMARY KEY (player_id, day, mode)
) STRICT;
CREATE INDEX mirror_games_day ON mirror_games(day, mode);
`,
// Miroir brisé : le mode Facile (échanges libres) avant le Normal. SQLite ne modifie pas une contrainte : la table est refaite.
`
CREATE TABLE mirror_games_next (
player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE,
day TEXT NOT NULL,
mode TEXT NOT NULL CHECK (mode IN ('easy', '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;
INSERT INTO mirror_games_next SELECT player_id, day, mode, card_id, status, state_json, reward, started_at, finished_at FROM mirror_games;
DROP TABLE mirror_games;
ALTER TABLE mirror_games_next RENAME TO mirror_games;
CREATE INDEX mirror_games_day ON mirror_games(day, mode);
`
];

View file

@ -3,9 +3,11 @@
// 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.
// Facile : une illustration carrée en 4 × 4, propre à chaque joueur, où l'on échange n'importe quels morceaux. Normal : pareil, mais
// seulement dans la même rangée ou la même colonne. Difficile : le portrait 5:7 en 5 × 7, le même pour tous, en rangée ou colonne.
// Les découpes tombent juste : 800 / 4 = 200 px, 1060 / 5 = 1484 / 7 = 212 px. Ordre du jour : chacun s'ouvre après le précédent.
export const MIRROR_MODES = Object.freeze({
easy: Object.freeze({ cols: 4, rows: 4, format: "square", placedShown: true, freeSwaps: true }),
normal: Object.freeze({ cols: 4, rows: 4, format: "square", placedShown: true }),
hard: Object.freeze({ cols: 5, rows: 7, format: "portrait", placedShown: false })
});
@ -14,12 +16,12 @@ export const MIRROR_MODE_IDS = Object.freeze(Object.keys(MIRROR_MODES));
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;
// Coups de main par partie : un par compagnon de l'Équipe du jour, les cinq (décidé le 28 novembre 2026 ; deux rendaient le jeu dur).
export const HELPERS_PER_GAME = 5;
// 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]);
// Coups de main, un par sorte d'aide (docs/miroir-brise.md) : Bravoure, un mouvement libre (hors rangée et colonne) ; Orientation,
// Coups de main, un par sorte d'aide (docs/miroir-brise.md) : Bravoure, un morceau mal placé (au hasard) va à sa place ; Orientation,
// la case d'un morceau choisi ; Fortune, le Trésor (gain multiplié) ; Endurance, reprendre le dernier mouvement ; Équilibré, revoir
// le modèle pendant MODEL_PEEK_MS. Le modèle se voit librement jusqu'au premier mouvement.
export const TREASURE_FACTOR = 2;
@ -47,6 +49,21 @@ export function scramble(count, random = defaultRandom) {
return pos;
}
// Minimum d'échanges libres : morceaux moins cycles de la permutation (la référence du Facile).
export function minSwaps(pos) {
const seen = new Array(pos.length).fill(false);
let cycles = 0;
for (let index = 0; index < pos.length; index += 1) {
if (seen[index]) continue;
cycles += 1;
for (let cell = index; !seen[cell]; cell = pos[cell]) seen[cell] = true;
}
return pos.length - cycles;
}
// Mode qui doit être terminé avant celui-ci (Facile → Normal → Difficile), ou null pour le premier.
export const previousMode = (mode) => MIRROR_MODE_IDS[MIRROR_MODE_IDS.indexOf(mode) - 1] ?? null;
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] : []));

View file

@ -5,7 +5,7 @@ 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
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";
@ -110,15 +110,25 @@ export class MirrorService {
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";
// 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 [];
@ -137,7 +147,7 @@ export class MirrorService {
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,
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, 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,
@ -156,7 +166,7 @@ export class MirrorService {
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,
rewards: settings.rewards, games, locks: this.locks(playerId, day), helpersPerGame: HELPERS_PER_GAME,
team: this.teamHelpers(playerId),
devReset: Boolean(this.cards.devPerks)
};
@ -166,7 +176,7 @@ export class MirrorService {
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) };
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.
@ -194,24 +204,25 @@ export class MirrorService {
// 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));
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.
// Jamais la même illustration que le Difficile du jour, ni qu'une autre partie du jour.
recent.add(this.ensureHardDay(today).cardId);
cardId = drawIllustration(this.candidates("normal"), recent, this.random);
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("normal"), this.random);
par = solve(start, MIRROR_MODES.normal.cols).length;
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, free: false, double: false, hint: null, lastMove: null };
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());
});
@ -253,12 +264,11 @@ export class MirrorService {
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.");
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.free = false;
state.hint = null;
state.lastMove = [from, to];
});
@ -273,9 +283,16 @@ export class MirrorService {
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.");
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;
if (help === "bravoure") state.free = true;
// 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;

View file

@ -5,12 +5,13 @@ 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).
// Course 20 / 15 / 10 / 5 ; le Facile rapporte la moitié du Normal. Marges : échanges permis au-delà de la référence (le minimum
// d'échanges libres en Facile, le meilleur résultat de l'ordinateur sinon) ; 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 })
rewards: Object.freeze({ easy: Object.freeze({ base: 5, perSwap: 1 }), normal: Object.freeze({ base: 10, perSwap: 1 }), hard: Object.freeze({ base: 20, perSwap: 2 }) }),
margins: Object.freeze({ easy: 4, normal: 3, hard: 6 })
});
export function mirrorSettingsError(settings) {