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:
parent
5210503922
commit
9cf48ea0d0
36 changed files with 3124 additions and 20 deletions
254
website/src/features/cards/MirrorPanel.jsx
Normal file
254
website/src/features/cards/MirrorPanel.jsx
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
// Rôle : page du Miroir brisé : le Normal puis le Difficile du jour, chacun avec son plateau, le nombre d'échanges restants, les
|
||||
// coups de main de l'Équipe du jour et le résultat (à partager pour le Difficile, le même pour tous). Règles : docs/miroir-brise.md.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Tabs } from "../../components/Tabs.jsx";
|
||||
import { applyMirrorHelp, chooseMirrorHelpers, loadMirror, loadMirrorImage, resetMirror, startMirror, swapMirror } from "./cardsApi.js";
|
||||
import { fillTemplate, formatCountdown } from "./dailyShare.js";
|
||||
import { MirrorBoard } from "./MirrorBoard.jsx";
|
||||
import { mirrorShareText } from "./mirrorFormat.js";
|
||||
import { formatStardust } from "./stardustFormat.js";
|
||||
import { MaskIcon } from "./ExpeditionLabels.jsx";
|
||||
|
||||
const MODES = ["normal", "hard"];
|
||||
const identity = (count) => Array.from({ length: count }, (_, index) => index);
|
||||
const BALANCED_HELP = "balanced";
|
||||
// Spécialités d'un compagnon, en petit : ses coups de main en découlent (l'équilibre a le sien).
|
||||
function Specialties({ helps, teamContent, statLabels }) {
|
||||
return <span className="nebula-mirror-specialties">{helps.map((help) => <span key={help} className="nebula-mirror-specialty" style={{ "--specialty": `var(--color-stat-${help})` }}>
|
||||
<MaskIcon name={help} />{help === BALANCED_HELP ? teamContent.balanced : statLabels[help]}
|
||||
</span>)}</span>;
|
||||
}
|
||||
|
||||
function StartPanel({ mode, mirror, content, busy, onStart }) {
|
||||
const lock = mode === "hard" ? mirror.hardLock : null;
|
||||
const reward = mirror.rewards[mode];
|
||||
return <section className="nds-panel nebula-mirror-start" aria-labelledby={`nebula-mirror-start-${mode}`}>
|
||||
<h3 id={`nebula-mirror-start-${mode}`}>{content.modes[mode].label}</h3>
|
||||
<p>{content.modes[mode].text}</p>
|
||||
<ol className="nebula-mirror-rules">{content.rules.map((rule) => <li key={rule}>{rule}</li>)}</ol>
|
||||
<p className="nebula-mirror-reward">{fillTemplate(content.rewardLine, { base: formatStardust(reward.base), perSwap: reward.perSwap })}</p>
|
||||
{lock && <p className="nds-inline-notice" role="status">{lock === "daily" ? content.dailyFirst : content.hardLocked}</p>}
|
||||
<div className="nds-card-actions"><button className="nds-button" data-variant="primary" type="button" disabled={busy || Boolean(lock)} onClick={onStart}>{content.modes[mode].start}</button></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
// Coups de main : avant le premier échange, le joueur choisit ses compagnons ; ensuite, chacun aide une fois.
|
||||
function MirrorHelpers({ catalog, mirror, game, content, teamContent, statLabels, busy, onChoose, onHelp }) {
|
||||
if (!mirror.team.length) return <section className="nds-panel nebula-mirror-helpers"><h3>{content.helpersTitle}</h3><p className="nebula-mirror-note">{content.helpersNone}</p><a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/team">{content.toTeam}</a></section>;
|
||||
const card = (cardId) => catalog.cards.find((item) => item.id === cardId);
|
||||
const chosen = new Set(game.helpers.map((helper) => helper.cardId));
|
||||
const playing = game.status === "playing";
|
||||
const choosing = playing && !game.helpersLocked;
|
||||
const list = choosing ? mirror.team : game.helpers;
|
||||
const helpButtons = (helper) => helper.helps.map((help) => {
|
||||
const used = game.used[helper.cardId];
|
||||
return <button key={help} className="nds-button nebula-mirror-help" data-size="sm" data-variant="secondary" type="button" style={{ "--specialty": `var(--color-stat-${help})` }}
|
||||
title={content.helps[help].text} disabled={busy || !playing || Boolean(used)} data-used={used === help || undefined} onClick={() => onHelp(helper.cardId, help)}>
|
||||
{content.helps[help].name}
|
||||
</button>;
|
||||
});
|
||||
return <section className="nds-panel nebula-mirror-helpers" aria-labelledby="nebula-mirror-helpers-title">
|
||||
<h3 id="nebula-mirror-helpers-title">{content.helpersTitle}</h3>
|
||||
{choosing && <p className="nebula-mirror-note">{fillTemplate(content.helpersChoose, { count: mirror.helpersPerGame })}</p>}
|
||||
{!list.length && <p className="nebula-mirror-note">{content.helpersNoneChosen}</p>}
|
||||
<ul className="nebula-mirror-helper-list">{list.map((helper) => {
|
||||
const selected = chosen.has(helper.cardId);
|
||||
const name = card(helper.cardId)?.name || teamContent.unknownCard;
|
||||
return <li key={helper.cardId} className="nebula-mirror-helper" data-selected={selected || undefined} data-used={Boolean(game.used[helper.cardId]) || undefined}>
|
||||
{choosing
|
||||
? <button type="button" className="nebula-mirror-helper-pick" aria-pressed={selected} disabled={busy || (!selected && chosen.size >= mirror.helpersPerGame)}
|
||||
onClick={() => onChoose(selected ? [...chosen].filter((id) => id !== helper.cardId) : [...chosen, helper.cardId])}>
|
||||
<img src={card(helper.cardId)?.image} alt="" /><span><strong>{name}</strong><Specialties helps={helper.helps} teamContent={teamContent} statLabels={statLabels} />
|
||||
<small>{helper.helps.map((help) => content.helps[help].name).join(` ${content.or} `)}</small></span>
|
||||
</button>
|
||||
: <div className="nebula-mirror-helper-row"><img src={card(helper.cardId)?.image} alt="" /><span><strong>{name}</strong><Specialties helps={helper.helps} teamContent={teamContent} statLabels={statLabels} /></span>
|
||||
<span className="nebula-mirror-help-actions">{helper.helps.length > 1 && !game.used[helper.cardId] && <small>{content.helpChoice}</small>}{helpButtons(helper)}</span></div>}
|
||||
</li>;
|
||||
})}</ul>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function MirrorResult({ catalog, mirror, game, content, nextAt }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [now] = useState(() => Date.now());
|
||||
const card = catalog.cards.find((item) => item.id === game.cardId);
|
||||
const won = game.status === "won";
|
||||
async function share() {
|
||||
const text = mirrorShareText(mirror, game, { title: content.shareText, modes: content.modes, url: `${window.location.origin}/#/cards/mirror` });
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
} catch {
|
||||
setCopied(false);
|
||||
}
|
||||
}
|
||||
return <section className="nds-panel nebula-mirror-result" data-won={won || undefined} aria-labelledby={`nebula-mirror-result-${game.mode}`}>
|
||||
<h3 id={`nebula-mirror-result-${game.mode}`} tabIndex={-1}>{won ? content.wonTitle : content.lostTitle}</h3>
|
||||
{won ? <p className="nebula-mirror-earned">+{formatStardust(game.reward)}</p> : <p>{fillTemplate(content.lostText, { placed: game.placedCount, total: game.cols * game.rows })}</p>}
|
||||
<p>{fillTemplate(content.resultSwaps, { swaps: game.swaps, par: game.par })}{won && game.swaps < game.par && <> {content.resultBetter}</>}</p>
|
||||
{card && <p className="nebula-mirror-note">{fillTemplate(content.revealed, { card: card.name })}</p>}
|
||||
{game.mode === "hard" && <div className="nds-card-actions"><button className="nds-button" data-variant="primary" type="button" onClick={share}>{copied ? content.shared : content.share}</button></div>}
|
||||
{(game.mode === "hard" || mirror.games.hard) && <p className="nebula-mirror-note">{fillTemplate(content.next, { time: formatCountdown(nextAt - now) })}</p>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function MirrorPanel({ catalog, runMutation, busy, content, teamContent, statLabels }) {
|
||||
const [mirror, setMirror] = useState(null);
|
||||
const [loadError, setLoadError] = useState("");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [notice, setNotice] = useState("");
|
||||
const [mode, setMode] = useState(null);
|
||||
// Par mode : l'image servie, sa version (coups joués quand elle a été rendue) et la place de ses morceaux depuis.
|
||||
const [boards, setBoards] = useState({});
|
||||
// Copie à jour des plateaux, lue au retour du serveur et à l'arrivée d'une image.
|
||||
const boardsRef = useRef({});
|
||||
const [models, setModels] = useState({});
|
||||
const [peeking, setPeeking] = useState(false);
|
||||
const [toast, setToast] = useState("");
|
||||
const urls = useRef([]);
|
||||
// Images en cours de chargement, pour ne pas demander deux fois la même.
|
||||
const pending = useRef(new Set());
|
||||
|
||||
const commitBoards = useCallback((next) => {
|
||||
boardsRef.current = next;
|
||||
setBoards(next);
|
||||
}, []);
|
||||
|
||||
const fetchImage = useCallback(async (gameMode, version, count) => {
|
||||
const key = `${gameMode}:${version}`;
|
||||
if (pending.current.has(key)) return;
|
||||
pending.current.add(key);
|
||||
try {
|
||||
const src = await loadMirrorImage(gameMode, { version });
|
||||
urls.current.push(src);
|
||||
commitBoards({ ...boardsRef.current, [gameMode]: { src, version, applied: version, tiles: identity(count) } });
|
||||
} catch (error) {
|
||||
setNotice(error.message);
|
||||
} finally {
|
||||
pending.current.delete(key);
|
||||
}
|
||||
}, [commitBoards]);
|
||||
|
||||
// Suit la partie à chaque réponse du serveur : un coup de plus (échange, coup de main) se rejoue sur l'image affichée ; tout
|
||||
// autre écart (premier affichage, page restée ouverte) recharge l'image. Le plateau attend pendant ce temps.
|
||||
const applyView = useCallback((next) => {
|
||||
let boardsNext = boardsRef.current;
|
||||
for (const gameMode of MODES) {
|
||||
const current = next.games[gameMode];
|
||||
if (!current) continue;
|
||||
const board = boardsNext[gameMode];
|
||||
if (board && current.moves === board.applied) continue;
|
||||
if (board?.src && current.moves === board.applied + 1) {
|
||||
const tiles = [...board.tiles];
|
||||
if (current.lastMove) {
|
||||
const [x, y] = current.lastMove;
|
||||
[tiles[x], tiles[y]] = [tiles[y], tiles[x]];
|
||||
}
|
||||
boardsNext = { ...boardsNext, [gameMode]: { ...board, tiles, applied: current.moves } };
|
||||
} else fetchImage(gameMode, current.moves, current.cols * current.rows);
|
||||
}
|
||||
if (boardsNext !== boardsRef.current) commitBoards(boardsNext);
|
||||
setMirror(next);
|
||||
}, [commitBoards, fetchImage]);
|
||||
|
||||
useEffect(() => () => urls.current.forEach((url) => URL.revokeObjectURL(url)), []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
loadMirror()
|
||||
.then((result) => { if (active) { applyView(result.mirror); setLoadError(""); } })
|
||||
.catch((error) => { if (active) setLoadError(error.message); });
|
||||
return () => { active = false; };
|
||||
}, [reloadKey, applyView]);
|
||||
|
||||
// Onglet par défaut, à l'arrivée sur la page : le Difficile une fois le Normal terminé. Commencer une partie fixe l'onglet, pour que
|
||||
// son résultat reste affiché.
|
||||
const activeMode = mode || (mirror?.games.normal && mirror.games.normal.status !== "playing" ? "hard" : "normal");
|
||||
const game = mirror?.games[activeMode] || null;
|
||||
|
||||
if (loadError) return <section className="nds-empty-state" role="alert"><h2>{content.title}</h2><p>{loadError}</p><button className="nds-button" data-variant="secondary" type="button" onClick={() => setReloadKey((key) => key + 1)}>{teamContent.retry}</button></section>;
|
||||
if (!mirror) return <section className="nds-empty-state" aria-busy="true"><h2>{content.title}</h2></section>;
|
||||
|
||||
// Les refus propres au Miroir restent dans ce panneau ; runMutation garde le reste (erreurs réseau).
|
||||
async function act(action) {
|
||||
setNotice("");
|
||||
const result = await runMutation(async () => {
|
||||
try {
|
||||
return await action();
|
||||
} catch (error) {
|
||||
if (/^MIRROR_/.test(String(error.code || ""))) return { mirrorError: error };
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
if (result?.mirrorError) {
|
||||
setNotice(result.mirrorError.message);
|
||||
setReloadKey((key) => key + 1);
|
||||
return null;
|
||||
}
|
||||
if (result?.mirror) applyView(result.mirror);
|
||||
return result?.mirror || null;
|
||||
}
|
||||
|
||||
function flash(text) {
|
||||
setToast(text);
|
||||
window.setTimeout(() => setToast((value) => (value === text ? "" : value)), 1800);
|
||||
}
|
||||
|
||||
async function swap(from, to) {
|
||||
const before = game.placed.length;
|
||||
const next = await act(() => swapMirror(mirror.day, activeMode, from, to, game.moves));
|
||||
const after = next?.games[activeMode];
|
||||
if (after && after.status === "playing" && activeMode === "normal" && after.placed.length - before >= 2) flash(content.twoPlaced);
|
||||
}
|
||||
|
||||
async function peek(on) {
|
||||
setPeeking(on);
|
||||
if (!on || models[activeMode]) return;
|
||||
try {
|
||||
const src = await loadMirrorImage(activeMode, { model: true });
|
||||
urls.current.push(src);
|
||||
setModels((current) => ({ ...current, [activeMode]: src }));
|
||||
} catch (error) {
|
||||
setNotice(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
const board = boards[activeMode];
|
||||
const left = game?.left ?? 0;
|
||||
return <section className="nebula-mirror" aria-labelledby="nebula-mirror-title">
|
||||
<div className="nds-section-heading nebula-section-heading">
|
||||
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-mirror-title">{content.title}</h2></div>
|
||||
<div className="nebula-team-heading-actions">
|
||||
{mirror.devReset && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={async () => { commitBoards({}); await act(() => resetMirror()); }}>{content.devReset}</button>}
|
||||
<a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a>
|
||||
</div>
|
||||
</div>
|
||||
{notice && <p className="nds-inline-notice" data-variant="warning" role="status">{notice}</p>}
|
||||
{!mirror.enabled && !mirror.games.normal && !mirror.games.hard
|
||||
? <div className="nds-empty-state"><p>{content.closed}</p></div>
|
||||
: <>
|
||||
<Tabs className="nebula-mirror-tabs" size="md" tabs={MODES.map((id) => ({ id, label: content.modes[id].label }))} activeTab={activeMode} onChange={(id) => { setMode(id); setPeeking(false); }} />
|
||||
{!game && <StartPanel mode={activeMode} mirror={mirror} content={content} busy={busy || !mirror.enabled} onStart={() => { setMode(activeMode); act(() => startMirror(mirror.day, activeMode)); }} />}
|
||||
{game && <div className="nebula-mirror-layout">
|
||||
<div className="nebula-mirror-stage">
|
||||
<MirrorBoard game={game} src={board?.src} modelSrc={peeking ? models[activeMode] : null} tiles={board?.tiles || identity(game.cols * game.rows)} peeking={peeking} disabled={busy || !board?.src || board.applied !== game.moves} content={content} onSwap={swap} />
|
||||
{toast && <p className="nebula-mirror-toast" role="status">{toast}</p>}
|
||||
{game.status === "playing" && <button className="nds-button nebula-mirror-peek" data-size="sm" data-variant="secondary" type="button" onMouseEnter={() => peek(true)} onMouseLeave={() => peek(false)} onFocus={() => peek(true)} onBlur={() => peek(false)}>{content.peek}</button>}
|
||||
</div>
|
||||
<div className="nebula-mirror-side">
|
||||
{game.status === "playing"
|
||||
? <section className="nds-panel nebula-mirror-counter" aria-live="polite">
|
||||
<p className="nebula-mirror-left" data-low={left <= 2 || undefined}><strong>{left}</strong><span>{left > 1 ? content.left.many : content.left.one}</span></p>
|
||||
<p className="nebula-mirror-note">{game.freeSwap ? content.freeHint : content.modes[activeMode].hint}</p>
|
||||
<p className="nebula-mirror-reward">{fillTemplate(content.rewardLine, { base: formatStardust(game.rewards.base), perSwap: game.rewards.perSwap })}</p>
|
||||
</section>
|
||||
: <MirrorResult catalog={catalog} mirror={mirror} game={game} content={content} nextAt={mirror.nextAt} />}
|
||||
{game.status !== "playing" && activeMode === "normal" && !mirror.games.hard && <div className="nds-card-actions"><button className="nds-button" data-variant="primary" type="button" onClick={() => setMode("hard")}>{content.toHard}</button></div>}
|
||||
{(game.status === "playing" || game.helpers.length > 0) && <MirrorHelpers catalog={catalog} mirror={mirror} game={game} content={content} teamContent={teamContent} statLabels={statLabels} busy={busy}
|
||||
onChoose={(cardIds) => act(() => chooseMirrorHelpers(mirror.day, activeMode, cardIds))}
|
||||
onHelp={(cardId, help) => act(() => applyMirrorHelp(mirror.day, activeMode, cardId, help, game.moves))} />}
|
||||
</div>
|
||||
</div>}
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue