diff --git a/app/src/ui/analysis-view.ts b/app/src/ui/analysis-view.ts index 3f290fe..8a8aba0 100644 --- a/app/src/ui/analysis-view.ts +++ b/app/src/ui/analysis-view.ts @@ -456,6 +456,8 @@ export function createAnalysisView(options: AnalysisViewOptions): AnalysisView { ); } else if (turn.move !== null && turn.move.halfMoves.length === 0) { phrase.textContent = REVIEW_TEXTS.playerCannotMove; + } else if (turn.end?.resigned === true) { + phrase.textContent = REVIEW_TEXTS.playerResigned; } // Le plateau : le coup joué et, s'il diffère, le meilleur coup. diff --git a/app/src/ui/app.ts b/app/src/ui/app.ts index 6d8de51..d2148b6 100644 --- a/app/src/ui/app.ts +++ b/app/src/ui/app.ts @@ -33,6 +33,7 @@ import { masterLine, masterWords, parsePhrases, + resignationAnswer, } from "../domain/analysis/phrases.js"; import { type FinishedGame, @@ -41,9 +42,9 @@ import { } from "../domain/analysis/progression.js"; import type { Advice } from "../domain/game/advice.js"; import type { Cube } from "../domain/game/cube.js"; -import type { MoveNotation } from "../domain/game/engine.js"; +import type { MoveNotation, ResultKind } from "../domain/game/engine.js"; import type { GameJournal } from "../domain/game/events.js"; -import type { Game, MoveSteps, NewGame, SideBoards } from "../domain/game/game.js"; +import type { Game, MoveSteps, NewGame, ResignChoice, SideBoards } from "../domain/game/game.js"; import { BAR, type HalfMove } from "../domain/game/position.js"; import { type PositionLink, type SharedPosition, setupOf } from "../domain/game/position-link.js"; import type { SavedGameSummary } from "../domain/game/saved-game.js"; @@ -260,6 +261,7 @@ type ActionName = | "confirm" | "skip" | "double" + | "resign" | "take" | "drop" | "undo" @@ -314,6 +316,16 @@ export function startApp(options: AppOptions): void { bubble: byId("pip-bubble"), roll: byId("roll"), double: byId("double"), + resign: byId("resign"), + resignRefusal: byId("resign-refusal"), + menuResign: byId("menu-resign"), + resignVeil: byId("resign-veil"), + resignTitle: byId("resign-title"), + resignClose: byId("resign-close"), + resignLead: byId("resign-lead"), + resignChoices: byId("resign-choices"), + resignCancel: byId("resign-cancel"), + resignConfirm: byId("resign-confirm"), take: byId("take"), drop: byId("drop"), confirm: byId("confirm"), @@ -491,6 +503,15 @@ export function startApp(options: AppOptions): void { ui.moveHint.textContent = TEXTS.moveHint; ui.doubleConfirm.textContent = TEXTS.double; ui.doubleCancel.textContent = TEXTS.cancel; + ui.resign.append(icon("flag")); + ui.resign.setAttribute("aria-label", TEXTS.resign); + ui.resign.title = TEXTS.resign; + label(ui.menuResign, TEXTS.resign, "flag"); + ui.resignTitle.textContent = TEXTS.resign; + ui.resignClose.append(icon("close")); + ui.resignClose.setAttribute("aria-label", TEXTS.close); + ui.resignCancel.textContent = TEXTS.resignContinue; + ui.resignConfirm.textContent = TEXTS.resignPropose; ui.helpBack.textContent = TEXTS.back; ui.helpTabs.setAttribute("aria-label", TEXTS.helpTabs); for (const tab of ui.helpTabs.querySelectorAll("a[data-screen]")) { @@ -568,6 +589,15 @@ export function startApp(options: AppOptions): void { // un pion parti dès le premier toucher). let idleWaiters: (() => void)[] = []; let canDouble = false; + // Les abandons que le joueur peut proposer maintenant (à son tour, + // avant de lancer les dés), le choix de la feuille, et la réponse de + // l'ordinateur attendue. + let resignChoices: ResignChoice[] = []; + let resignKind: ResultKind = "single"; + let resignWaiting = false; + // La partie Crawford dont la capsule est déjà apparue (le fondu ne se + // joue qu'au premier dessin). + let crawfordGame: Game | null = null; // Le joueur a lancé les dés mais ne peut pas jouer : il doit passer. let stuck = false; let busy = true; @@ -699,6 +729,7 @@ export function startApp(options: AppOptions): void { sides = await game.displayedBoard(); targets = moveTargets(await game.nextHalfMoves()); canDouble = await game.canDouble(); + resignChoices = await game.resignOptions(); stuck = await game.cannotMove(); if (selected !== null && !targets.has(selected)) { selected = null; @@ -744,8 +775,8 @@ export function startApp(options: AppOptions): void { if (!animating) { renderBoard(ui.board, g, model, { dice: shownDice(game, stuck), - // Partie Crawford : pas de videau. - cube: state.match?.crawford === true ? null : state.cube, + cube: state.cube, + crawford: crawfordDecor(game), movable: new Set(targets.keys()), selected, targets: new Set(selected === null ? [] : (targets.get(selected)?.keys() ?? [])), @@ -759,7 +790,9 @@ export function startApp(options: AppOptions): void { landscape && !panelShown ? text === null ? TEXTS.gameOver - : bandText(text.short, state.match?.crawford === true) + : refusedResignation(game) !== null + ? TEXTS.resignRefusedBand + : text.short : null, controls: landscape ? controls() : null, advice: landscape && !panelShown ? boardAdvice(shownAdvice()) : null, @@ -803,6 +836,10 @@ export function startApp(options: AppOptions): void { const over = state.phase === "over"; show(ui.roll, rolling); show(ui.double, rolling && canDouble); + show(ui.resign, rolling && resignChoices.length > 0); + ui.menuResign.disabled = + busy || ui.game.hidden !== false || !rolling || resignChoices.length === 0; + renderRefusal(game); show(ui.cancel, moving && !stuck); show(ui.confirm, moving && game.moveComplete); show(ui.moveHint, moving && !stuck && !game.moveComplete); @@ -817,6 +854,7 @@ export function startApp(options: AppOptions): void { for (const button of [ ui.roll, ui.double, + ui.resign, ui.take, ui.drop, ui.confirm, @@ -841,6 +879,154 @@ export function startApp(options: AppOptions): void { reviewFinishedGame(); } + /** La capsule « Crawford » de la partie : « appear » au premier dessin + * de la partie Crawford (fondu), « shown » ensuite, null hors d'elle. */ + function crawfordDecor(g: Game): "shown" | "appear" | null { + if (g.state.match?.crawford !== true) { + return null; + } + if (crawfordGame === g) { + return "shown"; + } + crawfordGame = g; + return "appear"; + } + + /** L'ordinateur a refusé l'abandon : le message du maître au-dessus de + * la barre d'actions (portrait), jusqu'au lancer des dés. Le drapeau, + * la première phrase en gras, puis la raison. */ + function renderRefusal(g: Game): void { + const kind = refusedResignation(g); + const said = phrases; + ui.resignRefusal.hidden = kind === null || said === null; + if (kind === null || said === null) { + ui.resignRefusal.replaceChildren(); + delete ui.resignRefusal.dataset.kind; + return; + } + if (ui.resignRefusal.dataset.kind === kind) { + return; + } + ui.resignRefusal.dataset.kind = kind; + const sentence = resignationAnswer(said, kind, false, 0); + const cut = sentence.indexOf(". "); + const strong = document.createElement("strong"); + strong.textContent = cut < 0 ? sentence : sentence.slice(0, cut + 1); + ui.resignRefusal.replaceChildren( + icon("flag"), + strong, + cut < 0 ? "" : ` ${sentence.slice(cut + 2)}`, + ); + } + + /** La feuille de choix de l'abandon (charte) : un choix unique en + * cartes, le plus petit par défaut ; avec un seul choix, pas de liste. */ + function openResignSheet(g: Game): void { + resignKind = resignChoices[0]?.kind ?? "single"; + const cube = g.state.cube.value; + ui.resignLead.textContent = + cube > 1 ? `${TEXTS.resignLead} ${TEXTS.resignCube(cube)}` : TEXTS.resignLead; + renderResignChoices(); + ui.resignConfirm.textContent = TEXTS.resignPropose; + ui.resignConfirm.disabled = false; + ui.resignCancel.disabled = false; + const first = ui.resignChoices.querySelector("[role=radio]"); + openOverlay(ui.resignVeil, first ?? ui.resignConfirm); + } + + function renderResignChoices(): void { + const single = resignChoices.length === 1; + ui.resignChoices.replaceChildren(); + if (single) { + ui.resignChoices.removeAttribute("role"); + ui.resignChoices.removeAttribute("aria-label"); + } else { + ui.resignChoices.setAttribute("role", "radiogroup"); + ui.resignChoices.setAttribute("aria-label", TEXTS.resignChoicesLabel); + } + for (const choice of resignChoices) { + const card = document.createElement(single ? "div" : "button"); + card.className = "resign-choice"; + card.dataset.kind = choice.kind; + const name = document.createElement("span"); + name.className = "resign-choice-name"; + name.textContent = TEXTS.resignKinds[choice.kind]; + const worth = document.createElement("span"); + worth.className = "resign-choice-points"; + const after = choice.matchAfter; + worth.textContent = + after === null + ? TEXTS.resignPoints(choice.points) + : TEXTS.resignScore(after.score.player, after.score.computer, after.over); + card.append(name, worth); + if (card instanceof HTMLButtonElement) { + card.type = "button"; + card.setAttribute("role", "radio"); + const checked = choice.kind === resignKind; + card.setAttribute("aria-checked", String(checked)); + card.tabIndex = checked ? 0 : -1; + card.onclick = () => { + resignKind = choice.kind; + renderResignChoices(); + ui.resignChoices + .querySelector(`[data-kind="${choice.kind}"]`) + ?.focus(); + }; + } + ui.resignChoices.append(card); + } + } + + // Les flèches parcourent les cartes, comme un groupe de boutons radio. + ui.resignChoices.addEventListener("keydown", (event) => { + const step = + event.key === "ArrowDown" || event.key === "ArrowRight" + ? 1 + : event.key === "ArrowUp" || event.key === "ArrowLeft" + ? -1 + : 0; + if (step === 0 || resignChoices.length < 2) { + return; + } + event.preventDefault(); + const i = resignChoices.findIndex((c) => c.kind === resignKind); + const next = resignChoices[(i + step + resignChoices.length) % resignChoices.length]; + if (next !== undefined) { + resignKind = next.kind; + renderResignChoices(); + ui.resignChoices.querySelector(`[data-kind="${next.kind}"]`)?.focus(); + } + }); + + /** « Proposer » : l'ordinateur répond selon le moteur. Accepté, la + * feuille se ferme sur la fin de partie ; refusé, sur la partie, avec + * le message du maître. */ + async function proposeResignation(): Promise { + const g = canAct(); + if (g === null || resignWaiting) { + return; + } + const kind = resignKind; + resignWaiting = true; + ui.resignConfirm.textContent = TEXTS.resignThinking; + ui.resignConfirm.disabled = true; + ui.resignCancel.disabled = true; + try { + await act(async (g) => { + const accepted = await g.resign(kind); + const result = g.state.result; + info = + accepted && result !== null && phrases !== null + ? resignationAnswer(phrases, kind, true, result.points) + : ""; + }); + } finally { + resignWaiting = false; + closeTransient(); + render(); + } + } + /** Le conseil du maître à montrer : le réglage le permet, ses phrases * sont lues, et l'analyse attendue est prête. */ function shownAdvice(): { @@ -922,9 +1108,12 @@ export function startApp(options: AppOptions): void { ui.info.textContent = info; ui.prompt.textContent = ""; ui.prompt.classList.add("neutral"); + ui.resignRefusal.hidden = true; + ui.menuResign.disabled = true; for (const button of [ ui.roll, ui.double, + ui.resign, ui.take, ui.drop, ui.confirm, @@ -954,9 +1143,15 @@ export function startApp(options: AppOptions): void { game.state.turn === "player" && game.state.phase === "moving" && game.pendingHalfMoves.length > 0; + const state = game?.state; return { back: replay ? "replay" : "undo", backEnabled: !busy && (replay || undoable), + resign: + !busy && + state?.turn === "player" && + state.phase === "rolling" && + resignChoices.length > 0, menuEnabled: true, match: game === null ? null : matchScore(game.state), }; @@ -985,7 +1180,9 @@ export function startApp(options: AppOptions): void { ui.matchLine.removeAttribute("aria-label"); return; } - ui.matchLine.textContent = MATCH_TEXTS.matchLine(score.length, state.match.crawford); + // La partie Crawford se lit sur la barre (charte) : la ligne du + // match n'en parle plus ; le lecteur d'écran, si. + ui.matchLine.textContent = MATCH_TEXTS.matchLine(score.length); ui.matchLine.setAttribute( "aria-label", `${MATCH_TEXTS.scoreSpoken(score.length, score.computer, score.player)}${ @@ -1989,6 +2186,19 @@ export function startApp(options: AppOptions): void { ui.doubleQuestion.textContent = TEXTS.confirmDouble(2 * g.state.cube.value); openOverlay(ui.doubleVeil, ui.doubleConfirm); }, + // Abandonner : la feuille de choix, qui tient lieu de confirmation. + resign: () => { + const g = canAct(); + if ( + g?.state.turn !== "player" || + g.state.phase !== "rolling" || + resignChoices.length === 0 + ) { + return; + } + closeOverlays(); + openResignSheet(g); + }, take: () => { const g = canAct(); if (g?.state.phase === "doubled" && g.state.turn === "computer") { @@ -2052,7 +2262,7 @@ export function startApp(options: AppOptions): void { // (feuille, aide, position), comme le retour du téléphone. close: () => { const route = navigation.route; - if (!ui.doubleVeil.hidden || !ui.bubble.hidden) { + if (!ui.doubleVeil.hidden || !ui.bubble.hidden || !ui.resignVeil.hidden) { closeTransient(); render(); } else if (isSheet(route)) { @@ -2089,8 +2299,13 @@ export function startApp(options: AppOptions): void { /** Ferme la confirmation du double et la bulle, qui n'ont pas * d'adresse ; ne touche jamais à la partie. */ function closeTransient(): void { - const open = !ui.doubleVeil.hidden; + // Pendant la réponse de l'ordinateur, la feuille d'abandon reste. + if (resignWaiting) { + return; + } + const open = !ui.doubleVeil.hidden || !ui.resignVeil.hidden; ui.doubleVeil.hidden = true; + ui.resignVeil.hidden = true; bubbleSide = null; ui.bubble.hidden = true; if (open) { @@ -2957,6 +3172,16 @@ export function startApp(options: AppOptions): void { ui.roll.onclick = actions.roll; ui.skip.onclick = actions.skip; ui.double.onclick = actions.double; + ui.resign.onclick = actions.resign; + ui.menuResign.onclick = actions.resign; + ui.resignClose.onclick = () => closeTransient(); + ui.resignCancel.onclick = () => closeTransient(); + ui.resignConfirm.onclick = () => void proposeResignation(); + ui.resignVeil.addEventListener("click", (event) => { + if (event.target === ui.resignVeil) { + closeTransient(); + } + }); ui.take.onclick = actions.take; ui.drop.onclick = actions.drop; ui.confirm.onclick = actions.confirm; @@ -3119,6 +3344,7 @@ export function startApp(options: AppOptions): void { !ui.game.hidden && ui.menuVeil.hidden && ui.doubleVeil.hidden && + ui.resignVeil.hidden && ui.explainVeil.hidden && g !== null && g.state.turn === "player" && @@ -3438,9 +3664,11 @@ function endParts(game: Game): { title: string; detail: string } { return { title: TEXTS.gameOver, detail: "" }; } const { winner, kind, points } = result; + const resigned = result.resigned === true; const dropped = game.events.some((e) => e.type === "CubeDropped"); const how = dropped ? TEXTS.droppedDouble(winner) : ""; const { match, matchAfter } = game.state; + const endTitle = resigned ? TEXTS.resignedResult(kind, points) : TEXTS.endTitle(winner, kind); if (match !== null && matchAfter !== null) { const { player, computer } = matchAfter.score; const detail = MATCH_TEXTS.matchDetail( @@ -3452,14 +3680,15 @@ function endParts(game: Game): { title: string; detail: string } { matchAfter.over, ); return { - title: matchAfter.over - ? MATCH_TEXTS.matchWonTitle(winner) - : TEXTS.endTitle(winner, kind), + title: matchAfter.over ? MATCH_TEXTS.matchWonTitle(winner) : endTitle, detail: `${how}${matchAfter.crawford ? `${detail} ${MATCH_TEXTS.crawfordNext}` : detail}`, }; } + if (resigned) { + return { title: endTitle, detail: TEXTS.resignedDetail(game.state.cube.value) }; + } return { - title: TEXTS.endTitle(winner, kind), + title: endTitle, detail: `${how}${TEXTS.endDetail(winner, points, game.state.cube.value)}`, }; } @@ -3476,8 +3705,16 @@ function matchScore(state: GameState): MatchScore | null { /** Paysage : la consigne de la bande centrale ; pendant la partie * Crawford, elle le dit d'abord (la ligne du match n'y est pas). */ -function bandText(prompt: string, crawford: boolean): string { - return crawford && prompt !== "" ? MATCH_TEXTS.crawfordPrompt(prompt) : prompt; +/** L'abandon que l'ordinateur vient de refuser (son genre), tant que le + * joueur n'a pas lancé les dés : le dernier événement de la partie est le + * refus ; null sinon. */ +function refusedResignation(game: Game): ResultKind | null { + const line = game.events; + const last = line.at(-1); + const offer = line.at(-2); + return last?.type === "ResignationDeclined" && offer?.type === "ResignationOffered" + ? offer.kind + : null; } /** Le bouton qui suit une partie finie : « Partie suivante » dans un match diff --git a/app/src/ui/board-view.ts b/app/src/ui/board-view.ts index de470be..0a276d8 100644 --- a/app/src/ui/board-view.ts +++ b/app/src/ui/board-view.ts @@ -50,6 +50,9 @@ export interface BoardControls { readonly back: "undo" | "replay"; readonly backEnabled: boolean; readonly menuEnabled: boolean; + /** Le drapeau « Abandonner la partie », au-dessus du bouton du bas + * (absent ou false : pas de drapeau). */ + readonly resign?: boolean; /** Le score du match, sous le menu (null : partie libre). */ readonly match: MatchScore | null; } @@ -64,8 +67,13 @@ export interface MatchScore { /** Ce qui s'ajoute aux pions : dés, videau, mises en évidence. */ export interface BoardDecor { readonly dice: readonly ShownDie[]; - /** null : pas de videau (partie Crawford). */ + /** null : pas de videau. */ readonly cube: Cube | null; + /** Partie Crawford : la capsule « Crawford » sur la barre et le videau + * estompé (charte, « Crawford sur la barre ») ; « appear » : la + * capsule apparaît en fondu (premier dessin de la partie). Absent ou + * null : partie ordinaire. */ + readonly crawford?: "shown" | "appear" | null; /** Les pions que le joueur peut déplacer. */ readonly movable: ReadonlySet; /** Le pion touché, dont on montre les cases d'arrivée. */ @@ -228,6 +236,9 @@ export function renderBoard( } drawDice(svg, g, decor.dice); const cube = decor.cube === null ? null : drawCube(svg, g, decor.cube); + if (cube !== null && decor.crawford != null) { + cube.classList.add("crawford"); + } if (decor.trace !== null) { drawTraceRings(svg, g, board, decor.trace); } @@ -243,7 +254,7 @@ export function renderBoard( addAction(g, hits, decor.diceAction, label, { x, y: g.height / 2 }, width); } } - if (decor.canDouble && cube !== null && decor.cube !== null) { + if (decor.canDouble && cube !== null && decor.cube !== null && decor.crawford == null) { cube.classList.add("can-double"); addAction(g, hits, "double", TEXTS.double, cubeCenter(g, decor.cube), g.target); } @@ -417,6 +428,9 @@ function drawBar( if (g.layout === "landscape") { drawChips(svg, g, board); } + if (decor.crawford != null) { + drawCrawford(svg, g, board, decor.crawford === "appear"); + } addHit(hits, "bar-player", decor, { x: g.barLeft, y: 0, @@ -425,6 +439,56 @@ function drawBar( }); } +/** + * Partie Crawford : le mot « Crawford » à la verticale sur la barre (lu de + * bas en haut), dans une capsule (charte, « Crawford sur la barre »). Dans + * la moitié haute, entre le cadre (ou, en paysage, la pastille du compte + * de l'ordinateur) et les pions frappés, dessinée sous eux ; dans la moitié + * basse, symétriquement, si la moitié haute porte plus de pions frappés. + * Une note pour les lecteurs d'écran, pas une cible. + */ +function drawCrawford(svg: SVGSVGElement, g: Geometry, board: BoardModel, appear: boolean): void { + const font = g.crawfordFont; + const width = font + 6; + // « CRAWFORD » : huit capitales grasses espacées de 0,12 em. + const length = font * 6.6 + 12; + const top = board.bar.player <= board.bar.computer; + // En paysage, sous la pastille du compte (au moins 8 px d'écart). + const margin = g.layout === "landscape" ? g.edge + 4 + g.chipHeight + 14 : g.edge + 6; + const y = top ? margin : g.height - margin - length; + const x = g.barLeft + (g.bar - width) / 2; + const group = add(svg, "g", { + class: appear ? "crawford-capsule appear" : "crawford-capsule", + "data-half": top ? "top" : "bottom", + role: "note", + "aria-label": TEXTS.crawfordNote, + }); + add(group, "rect", { + class: "crawford-frame", + x, + y, + width, + height: length, + rx: width / 2, + }); + const cx = x + width / 2; + const cy = y + length / 2; + add( + group, + "text", + { + class: "crawford-text", + x: cx, + y: cy + font * 0.36, + "font-size": font, + "letter-spacing": `${0.12 * font}`, + transform: `rotate(-90 ${cx} ${cy})`, + "aria-hidden": "true", + }, + "CRAWFORD", + ); +} + /** Paysage : les comptes de points en pastilles aux deux bouts de la barre, * aux couleurs du camp (l'ordinateur en haut, vous en bas). */ function drawChips(svg: SVGSVGElement, g: Geometry, board: BoardModel): void { @@ -724,6 +788,9 @@ function drawControls( if (controls.match !== null) { drawMatchBox(svg, g, x, top + g.target / 2 + 6, controls.match); } + if (controls.resign === true) { + control("flag", "resign", TEXTS.resign, bottom - g.target - 8, true); + } if (controls.back === "replay") { control("replay", "replay", TEXTS.replayTitle, bottom, controls.backEnabled); } else { diff --git a/app/src/ui/games-texts.ts b/app/src/ui/games-texts.ts index d7a4999..0a85ab4 100644 --- a/app/src/ui/games-texts.ts +++ b/app/src/ui/games-texts.ts @@ -42,13 +42,18 @@ export const GAMES_TEXTS = { new Date(ms).toLocaleString("fr-FR", { dateStyle: "medium", timeStyle: "short" }), status: ( - result: { winner: Side; kind: ResultKind; points: number } | null, + result: { winner: Side; kind: ResultKind; points: number; resigned?: true } | null, moveCount: number, ) => { if (result === null) { return `En cours, ${moves(moveCount)}`; } - const who = result.winner === "player" ? "Gagnée" : "Perdue"; + const who = + result.winner === "player" + ? "Gagnée" + : result.resigned === true + ? "Perdue par abandon" + : "Perdue"; return `${who} (${RESULT_KIND[result.kind]}, ${points(result.points)}), ${moves(moveCount)}`; }, branchCount: (n: number) => (n > 1 ? `${n} branches` : ""), diff --git a/app/src/ui/geometry.ts b/app/src/ui/geometry.ts index 6620af0..ec19cc3 100644 --- a/app/src/ui/geometry.ts +++ b/app/src/ui/geometry.ts @@ -55,6 +55,8 @@ export interface Geometry { * haute (13 px au moins à l'écran). */ readonly cube: number; readonly cubeFont: number; + /** Taille du mot « Crawford » sur la barre (11 px au moins). */ + readonly crawfordFont: number; readonly countFont: number; /** Épaisseur des flèches du coup de l'ordinateur : 2,5 px à l'écran. */ readonly arrowWidth: number; @@ -90,6 +92,7 @@ export function boardGeometry(layout: Layout, aspect: number, pxPerUnit: number) const text = atLeast(13.5, pxPerUnit, 17); const sizes = { cubeFont: text, + crawfordFont: atLeast(11, pxPerUnit, 11), cube: Math.max(36, text + 20), countFont: Math.max(18, text), arrowWidth: 2.5 / pxPerUnit, diff --git a/app/src/ui/icons.ts b/app/src/ui/icons.ts index aa11539..42bc698 100644 --- a/app/src/ui/icons.ts +++ b/app/src/ui/icons.ts @@ -13,6 +13,7 @@ export const ICON_PATHS = { fullscreen: "M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5", exitFullscreen: "M9 4v5H4M20 9h-5V4M15 20v-5h5M4 15h5v5", undo: "M9 14L4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3", + flag: "M6 21V4M6 4h11l-2.5 4.5L17 13H6", replay: "M20 12a8 8 0 1 1-2.34-5.66M20 4v5h-5", close: "M6 6l12 12M18 6L6 18", chevron: "M9 6l6 6-6 6", diff --git a/app/src/ui/match-texts.ts b/app/src/ui/match-texts.ts index 5bae1ca..a151839 100644 --- a/app/src/ui/match-texts.ts +++ b/app/src/ui/match-texts.ts @@ -61,11 +61,9 @@ export const MATCH_TEXTS = { kept: "Vos choix sont gardés pour la prochaine fois.", // Score du match sur l'écran de jeu - /** « Match en 5 points », et « · partie Crawford ». */ - matchLine: (length: number, crawford: boolean) => - `Match en ${length} points${crawford ? " · partie Crawford" : ""}`, - /** Paysage : « Partie Crawford · À vous : lancez les dés. ». */ - crawfordPrompt: (prompt: string) => `Partie Crawford · ${prompt}`, + /** « Match en 5 points ». La partie Crawford se lit sur la barre du + * plateau (charte, « Crawford sur la barre »). */ + matchLine: (length: number) => `Match en ${length} points`, /** Ce que lit le lecteur d'écran. */ scoreSpoken: (length: number, computer: number, player: number) => `Match en ${length} points : l'ordinateur ${computer}, vous ${player}`, diff --git a/app/src/ui/progression-texts.ts b/app/src/ui/progression-texts.ts index 249a92f..79043ac 100644 --- a/app/src/ui/progression-texts.ts +++ b/app/src/ui/progression-texts.ts @@ -40,7 +40,13 @@ export const PROGRESSION_TEXTS = { if (result === null) { return "Partie terminée"; } - const parts = [result.winner === "player" ? "Gagnée" : "Perdue"]; + const parts = [ + result.winner === "player" + ? "Gagnée" + : result.resigned === true + ? "Perdue par abandon" + : "Perdue", + ]; if (result.kind !== "single") { parts.push(RESULT_KIND[result.kind]); } diff --git a/app/src/ui/review-texts.ts b/app/src/ui/review-texts.ts index ce4de4b..8d90677 100644 --- a/app/src/ui/review-texts.ts +++ b/app/src/ui/review-texts.ts @@ -66,6 +66,7 @@ export const REVIEW_TEXTS = { computerCannotMove: "L'ordinateur ne pouvait pas jouer.", playerCannotMove: "Vous ne pouviez pas jouer.", computerCube: "L'ordinateur a doublé.", + playerResigned: "Vous avez abandonné ; l'ordinateur a accepté.", chanceAfter: (chance: string) => `Vos chances de gagner après ce coup : ${chance}`, theirMove: "Son coup", masterMove: "Le coup du maître", diff --git a/app/src/ui/texts.ts b/app/src/ui/texts.ts index b5ce55f..420fa16 100644 --- a/app/src/ui/texts.ts +++ b/app/src/ui/texts.ts @@ -111,12 +111,12 @@ export const TEXTS = { short: "À vous : lancez les dés.", }, yourMove: (dice: readonly number[]): PromptText => ({ - long: `Jouez ${roll(dice)} : touchez un pion, puis sa case d'arrivée.`, + long: `Jouez ${roll(dice)} : touchez un pion, puis sa flèche d'arrivée.`, short: `Jouez ${roll(dice)}.`, }), pickTarget: { - long: "Touchez une case d'arrivée en surbrillance, ou un autre pion.", - short: "Choisissez la case.", + long: "Touchez une flèche d'arrivée en surbrillance, ou un autre pion.", + short: "Choisissez la flèche d'arrivée.", }, confirmOrUndo: { long: "Touchez vos dés pour jouer ce coup, ou « Annuler » pour reprendre un pion.", @@ -148,12 +148,47 @@ export const TEXTS = { winner === "player" ? "L'ordinateur a passé votre double : " : "Vous avez passé son double : ", + /** Une partie finie par un abandon accepté (charte, « Abandonner une + * partie ») : « Perdue par abandon, gammon, 2 points » ; la partie + * simple ne se dit pas : « Perdue par abandon, 1 point ». */ + resignedResult: (kind: ResultKind, n: number) => + `Perdue par abandon, ${kind === "single" ? "" : `${kind}, `}${points(n)}`, + /** Le détail d'une partie libre perdue par abandon : le videau, s'il a + * été doublé. */ + resignedDetail: (cube: number) => (cube > 1 ? `Videau à ${cube}.` : ""), /** « 8 points pour lui, videau à 4. » */ endDetail: (winner: "player" | "computer", n: number, cube: number) => `${points(n)} pour ${winner === "player" ? "vous" : "lui"}${ cube > 1 ? `, videau à ${cube}` : "" }.`, + // Partie Crawford (charte, « Crawford sur la barre ») + crawfordNote: "Partie Crawford : le videau ne peut pas être proposé pendant cette partie.", + + // Abandon (charte, « Abandonner une partie »). Les réponses de + // l'ordinateur sont des phrases du maître (docs/maitre/phrases.md, + // sections abandon.…). + resign: "Abandonner la partie", + resignLead: + "Vous proposez de perdre tout de suite. L'ordinateur accepte ou refuse, selon le moteur.", + resignCube: (cube: number) => `Le videau est à ${cube}.`, + resignKinds: { + single: "Une partie simple", + gammon: "Un gammon", + backgammon: "Un backgammon", + } satisfies Record, + resignChoicesLabel: "Ce que vous concédez", + /** Ce que rapporte un choix : les points (videau compris) ; dans un + * match, le score qui en résulterait. */ + resignPoints: (n: number) => points(n), + resignScore: (player: number, computer: number, over: boolean) => + `vous ${player}, l'ordinateur ${computer}${over ? " · fin du match" : ""}`, + resignContinue: "Continuer la partie", + resignPropose: "Proposer", + resignThinking: "L'ordinateur réfléchit…", + /** Paysage : la bande du plateau, après un refus. */ + resignRefusedBand: "L'ordinateur refuse : à vous de lancer.", + // Aide helpTitle: "Aide", helpTabs: "Rubriques de l'aide", diff --git a/docs/adr/0013-position-dans-l-adresse.md b/docs/adr/0013-position-dans-l-adresse.md index 16790d6..96a57a2 100644 --- a/docs/adr/0013-position-dans-l-adresse.md +++ b/docs/adr/0013-position-dans-l-adresse.md @@ -244,3 +244,10 @@ Ajoutées avec l'écran de progression (étape 1h), dans le même schéma : la feuille le dit, jamais une page cassée. - Comme « Mes parties », ces adresses n'ont de sens que sur l'appareil qui a joué les parties : ce ne sont pas des liens à partager. + +### 2026-11-13 — La feuille d'abandon n'a pas d'adresse + +La feuille de choix de l'abandon (étape 1k) tient lieu de confirmation, +comme celle du double : selon la règle de l'amendement du 2026-11-03, elle +n'a pas d'adresse. Échap, la croix, « Continuer la partie » ou un toucher +hors de la feuille la ferment. diff --git a/docs/scenarios/jouer-un-match.feature b/docs/scenarios/jouer-un-match.feature index 9eb3583..538bc1c 100644 --- a/docs/scenarios/jouer-un-match.feature +++ b/docs/scenarios/jouer-un-match.feature @@ -53,7 +53,8 @@ Fonctionnalité: Choisir sa partie et jouer un match Scénario: Qu'est-ce que la partie Crawford ? Dans un match, quand un joueur arrive à un point de la victoire, la partie suivante se joue sans videau : personne ne peut doubler. C'est la - règle de Crawford ; l'écran l'annonce par « partie Crawford ». Dans les + règle de Crawford. Pendant cette partie, « Crawford » est écrit à la + verticale sur la barre du plateau, et le videau est estompé. Dans les parties d'après, celui qui est mené peut de nouveau doubler. Étant donné qu'un match en 3 points commence et que l'ordinateur va gagner un gammon diff --git a/tests/browser.sh b/tests/browser.sh index 55952c8..a4c52cc 100755 --- a/tests/browser.sh +++ b/tests/browser.sh @@ -26,9 +26,14 @@ # captures dans build/browser-shots/progression/. Les gestes du plateau soigné # (tests/browser/plateau.mjs : glisser-déposer, pion lâché hors cible, double # toucher, clavier, filet des pions), captures dans build/browser-shots/plateau/. +# Les retours des joueurs, 2e lot (tests/browser/retours-2.mjs : drapeau, +# feuille d'abandon, refus et acceptation), captures dans +# build/browser-shots/retours-2/ ; la capsule « Crawford » y est capturée +# par match.mjs. # # BROWSERS=chromium et SCRIPTS=accueil (ou play, match, maitre, bilan, -# prompts, nouvelle-partie, retours-joueurs, lecons, progression, plateau) +# prompts, nouvelle-partie, retours-joueurs, lecons, progression, plateau, +# retours-2) # restreignent le test. # # Outils : l'image de Playwright (navigateurs) et le paquet playwright, @@ -42,7 +47,7 @@ cd "$(dirname "$0")/.." image="${PLAYWRIGHT_IMAGE:?lancer via make test-browser}" browsers="${BROWSERS:-chromium firefox}" # Les scripts à lancer (tests/browser/.mjs), tous par défaut. -scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression plateau}" +scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression plateau retours-2}" unset MAKEFLAGS MFLAGS MAKELEVEL make -s package >/dev/null @@ -82,7 +87,7 @@ mkdir -p build/browser-shots cp tests/browser/play.mjs tests/browser/accueil.mjs tests/browser/match.mjs tests/browser/recette.mjs \ tests/browser/maitre.mjs tests/browser/bilan.mjs tests/browser/prompts.mjs tests/browser/nouvelle-partie.mjs \ tests/browser/retours-joueurs.mjs tests/browser/lecons.mjs tests/browser/progression.mjs tests/browser/plateau.mjs \ - "$tools/" + tests/browser/retours-2.mjs "$tools/" status=0 for browser in $browsers; do # Réseau de l'hôte : le site est sur 127.0.0.1. Le service worker @@ -166,5 +171,12 @@ for browser in $browsers; do -v "$PWD/$tools:/tools" -v "$PWD/build/browser-shots:/shots" -w /tools "$image" \ node plateau.mjs "http://localhost:$port/" "$browser" /shots || status=1 fi + if [[ " $scripts " == *" retours-2 "* ]]; then + # Retours des joueurs, 2e lot : abandon (drapeau, feuille, refus, + # acceptation) ; captures dans build/browser-shots/retours-2/. + docker run --rm --init --ipc=host --network host --user "$(id -u):$(id -g)" -e HOME=/tmp \ + -v "$PWD/$tools:/tools" -v "$PWD/build/browser-shots:/shots" -w /tools "$image" \ + node retours-2.mjs "http://localhost:$port/" "$browser" /shots || status=1 + fi done exit "$status" diff --git a/tests/browser/match.mjs b/tests/browser/match.mjs index 9b67b21..fdc6878 100644 --- a/tests/browser/match.mjs +++ b/tests/browser/match.mjs @@ -150,10 +150,54 @@ async function shownMatch() { computer: document.querySelector("#strip-computer .match-score").textContent, player: document.querySelector("#strip-player .match-score").textContent, cube: document.querySelectorAll("#board .cube").length, + cubeDimmed: document.querySelectorAll("#board .cube.crawford").length, + // La partie Crawford se lit sur la barre (étape 1k). + crawford: document.querySelectorAll("#board .crawford-capsule").length === 1, + capsule: document.querySelector("#board .crawford-capsule")?.getAttribute("aria-label") ?? null, double: !document.getElementById("double").hidden, })); } +/** La capsule « Crawford » sur la barre : sur la barre, dans une moitié, + * sans toucher la pastille du compte en paysage, 11 px au moins, et pas + * une cible (charte, « Crawford sur la barre »). */ +async function capsuleProblems() { + return page.evaluate(() => { + const svg = document.getElementById("board"); + const capsule = svg.querySelector(".crawford-capsule"); + const bar = svg.querySelector(".board-bar")?.getBBox(); + if (capsule === null || bar === undefined) { + return ["capsule absente"]; + } + const found = []; + const frame = capsule.querySelector(".crawford-frame").getBBox(); + if (frame.x < bar.x || frame.x + frame.width > bar.x + bar.width) { + found.push("hors de la barre"); + } + const box = svg.getBoundingClientRect(); + const vb = svg.viewBox.baseVal; + const scale = Math.min(box.width / vb.width, box.height / vb.height); + const px = Number(capsule.querySelector(".crawford-text").getAttribute("font-size")) * scale; + if (px < 11) { + found.push(`texte de ${px.toFixed(1)} px`); + } + if (getComputedStyle(capsule).pointerEvents !== "none") { + found.push("cible tactile"); + } + for (const chip of svg.querySelectorAll(".pip-chip")) { + const c = chip.getBBox(); + const gap = Math.max(c.y - (frame.y + frame.height), frame.y - (c.y + c.height)); + if (gap * scale < 8) { + found.push(`à ${(gap * scale).toFixed(1)} px de la pastille`); + } + } + if (capsule.getAttribute("role") !== "note") { + found.push("rôle"); + } + return found; + }); +} + // ---------------------------------------------------- Écran « Nouvelle partie » await page.goto(`${base}#/nouvelle-partie`); @@ -281,9 +325,10 @@ for (;;) { check(actions++ < 20000, "le match ne finit pas"); const what = await todo(); const now = await shownMatch(); - const crawford = now.line.endsWith("· partie Crawford"); + const crawford = now.crawford; if (crawford && what !== "over") { - check(now.cube === 0 && !now.double, `partie Crawford : videau visible ${JSON.stringify(now)}`); + check(now.cube === 1 && now.cubeDimmed === 1 && !now.double, + `partie Crawford : videau estompé, pas de « Doubler » ${JSON.stringify(now)}`); } if (what === "over") { // Le bilan, une fois l'analyse prête, à la place du panneau. @@ -352,13 +397,17 @@ for (;;) { games++; await until("partie suivante", () => !document.body.classList.contains("busy")); const next = await shownMatch(); - if (next.line.endsWith("· partie Crawford")) { + if (next.crawford) { crawfordGames++; - check(next.cube === 0, "partie Crawford : le videau est dessiné"); + check(next.cube === 1 && next.cubeDimmed === 1, "partie Crawford : le videau n'est pas estompé"); + check(next.capsule === "Partie Crawford : le videau ne peut pas être proposé pendant cette partie.", + `partie Crawford : libellé « ${next.capsule} »`); if (!crawfordShot) { crawfordShot = true; - check(next.line === "Match en 3 points · partie Crawford", - `partie Crawford, portrait : « ${next.line} »`); + check(next.line === "Match en 3 points", + `partie Crawford, portrait : la ligne du match « ${next.line} »`); + const portraitProblems = await capsuleProblems(); + check(portraitProblems.length === 0, `capsule, portrait : ${portraitProblems.join(", ")}`); await page.setViewportSize(LANDSCAPE); await sleep(200); const band = await page.evaluate(() => { @@ -370,12 +419,28 @@ for (;;) { text.getBBox().width <= pill.getBBox().width - 16, }; }); - check(band.text.startsWith("Partie Crawford · "), - `partie Crawford, paysage : « ${band.text} »`); + check(!band.text.includes("Crawford"), + `partie Crawford, paysage : le préfixe reste (« ${band.text} »)`); check(band.fits, `partie Crawford, paysage : la consigne déborde (« ${band.text} »)`); + const landscapeProblems = await capsuleProblems(); + check(landscapeProblems.length === 0, `capsule, paysage : ${landscapeProblems.join(", ")}`); await page.setViewportSize(PORTRAIT); await sleep(200); await capture("3-partie-crawford"); + // La recette du 2e lot des retours des joueurs (étape 1k). + if (full) { + mkdirSync(`${shots}/retours-2`, { recursive: true }); + for (const size of [PORTRAIT, LANDSCAPE]) { + await page.setViewportSize(size); + await sleep(200); + await page.screenshot({ + path: `${shots}/retours-2/0-capsule-crawford-${size.width}x${size.height}.png`, + }); + captures++; + } + await page.setViewportSize(PORTRAIT); + await sleep(200); + } } } else if (!scoreShot) { scoreShot = true; diff --git a/tests/browser/retours-2.mjs b/tests/browser/retours-2.mjs new file mode 100644 index 0000000..027b418 --- /dev/null +++ b/tests/browser/retours-2.mjs @@ -0,0 +1,346 @@ +// retours-2.mjs -- les retours des joueurs, 2e lot (étape 1k ; charte, +// ecrans-etape-1.md, « Retours des joueurs, 2e lot »), dans un vrai +// navigateur sans écran (Playwright), sur le site servi par l'image de +// production : +// +// - le drapeau « Abandonner la partie », à votre tour avant le lancer +// seulement, dans la barre d'actions (portrait) et la colonne de +// commandes (paysage), et la ligne du menu ; +// - la feuille de choix : partie libre avec le videau à 2 (trois cartes, +// points videau compris), partie libre au centre (règle de Jacoby : la +// partie simple seule, sans liste), match (le score qui en résulterait) ; +// - l'ordinateur refuse (le message du maître, la partie continue) puis +// accepte (« Perdue par abandon, gammon, 4 points »). +// +// La capsule « Crawford » sur la barre est vérifiée et capturée par +// match.mjs, qui joue un match jusqu'à sa partie Crawford. +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). +// +// Usage : node retours-2.mjs +// Lancé par tests/browser.sh. Captures (Chromium) dans +// /retours-2/, en 412×915 et 915×412. + +import { mkdirSync } from "node:fs"; +import { chromium, firefox } from "playwright"; +import { hiddenUnderActionBar, tallButtons } from "./recette.mjs"; + +const [base, browserName, shots] = process.argv.slice(2); +const browserType = { chromium, firefox }[browserName]; +if (!base || !browserType || !shots) { + console.error("usage : node retours-2.mjs "); + process.exit(2); +} +const full = browserName === "chromium"; +const dir = `${shots}/retours-2`; +mkdirSync(dir, { recursive: true }); +const PORTRAIT = { width: 412, height: 915 }; +const LANDSCAPE = { width: 915, height: 412 }; +// Positions de référence (tests/reference/analyses.json, abandons) : le +// joueur au trait subit une attaque, gammon probable. EQEAAAAAAAAA : partie +// libre, videau à 2 chez l'adversaire. +const ATTACKED = "sp2DBwDgOfgAaA"; +const CUBE_2_COMPUTER = "EQEAAAAAAAAA"; + +const problems = []; +const log = (text) => console.log(`[${browserName}] ${text}`); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +let captures = 0; + +function check(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +const browser = await browserType.launch(); +const context = await browser.newContext({ + viewport: PORTRAIT, + deviceScaleFactor: 1, + locale: "fr-FR", + reducedMotion: "reduce", +}); +await context.addInitScript(() => { + let state = 11; + Math.random = () => { + state = (state * 1103515245 + 12345) % 2147483648; + return state / 2147483648; + }; + window.__csp = []; + document.addEventListener("securitypolicyviolation", (e) => + window.__csp.push(`${e.effectiveDirective} ${e.blockedURI}`), + ); + if (localStorage.getItem("ustagammon.settings") === null) { + localStorage.setItem("ustagammon.settings", JSON.stringify({ tutorialSeen: 1 })); + } +}); +const page = await context.newPage(); +page.on("pageerror", (error) => problems.push(`erreur de la page : ${error.message}`)); +page.on("console", (message) => { + if (message.type() === "error") { + problems.push(`console : ${message.text()}`); + } +}); + +/** Attend une condition dans la page (sans page.waitForFunction, qui passe + * par eval, interdit par la politique de sécurité du site). */ +async function until(what, fn, arg, ms = 60_000) { + for (let waited = 0; waited < ms; waited += 100) { + if (await page.evaluate(fn, arg).catch(() => false)) { + return; + } + await sleep(100); + } + await page.screenshot({ path: `${dir}/${browserName}-bloque.png` }).catch(() => {}); + throw new Error(`attente trop longue : ${what}`); +} + +/** Une capture de la recette dans les deux tailles (Chromium), après les + * règles communes ; check(size) vérifie l'écran dans chaque taille. */ +async function capture(name, checkSize = async () => {}) { + for (const size of [PORTRAIT, LANDSCAPE]) { + await page.setViewportSize(size); + await sleep(250); + await checkSize(size); + if (!full) { + continue; + } + const where = `${name} ${size.width}x${size.height}`; + const hidden = await hiddenUnderActionBar(page); + check(hidden.length === 0, `${where} : caché sous la barre d'action : ${hidden.join(", ")}`); + const tall = await tallButtons(page); + check(tall.length === 0, `${where} : boutons trop hauts : ${tall.join(", ")}`); + await page.screenshot({ path: `${dir}/${name}-${size.width}x${size.height}.png` }); + captures++; + } + await page.setViewportSize(PORTRAIT); + await sleep(200); +} + +/** Une partie à partir d'une position (et d'un Match ID), joueur au trait, + * dés à lancer. */ +async function startFrom(position, matchId) { + const id = matchId === undefined ? "" : `/${encodeURIComponent(matchId)}`; + await page.goto(`${base}#/position/${encodeURIComponent(position)}${id}`); + await until("position lue", () => { + const play = document.getElementById("position-play"); + return !play.hidden && !play.disabled; + }); + await page.click("#position-play"); + await until("partie commencée", () => + location.hash === "#/" && + !document.body.classList.contains("busy") && + !document.getElementById("roll").hidden); + // Le bandeau « Reprendre l'ancienne » (10 s) n'est pas le sujet. + await until("bandeau parti", () => document.getElementById("banner").hidden, null, 15_000); +} + +/** Ce que l'écran montre de l'abandon. */ +async function resignState() { + return page.evaluate(() => { + const flag = document.getElementById("resign"); + const box = flag.getBoundingClientRect(); + return { + flag: !flag.hidden, + flagSize: [Math.round(box.width), Math.round(box.height)], + flagLabel: flag.getAttribute("aria-label"), + boardFlag: document.querySelector('#board [data-action="resign"]') !== null, + menu: !document.getElementById("menu-resign").disabled, + sheet: !document.getElementById("resign-veil").hidden, + choices: [...document.querySelectorAll("#resign-choices .resign-choice")].map((c) => ({ + kind: c.dataset.kind, + text: c.textContent, + radio: c.getAttribute("role") === "radio", + checked: c.getAttribute("aria-checked"), + height: Math.round(c.getBoundingClientRect().height), + })), + lead: document.getElementById("resign-lead").textContent, + confirm: document.getElementById("resign-confirm").textContent, + refusal: document.getElementById("resign-refusal").hidden + ? null + : document.getElementById("resign-refusal").textContent, + band: document.getElementById("band-text")?.textContent ?? "", + roll: !document.getElementById("roll").hidden, + panel: document.getElementById("panel-veil").hidden + ? null + : document.getElementById("panel-text").textContent, + }; + }); +} + +/** Le drapeau : en portrait dans la barre d'actions, en paysage dans la + * colonne de commandes. */ +async function flagShown(size) { + const s = await resignState(); + if (size.width < size.height) { + check(s.flag && s.flagLabel === "Abandonner la partie", `drapeau absent : ${JSON.stringify(s)}`); + check(s.flagSize[0] === 52 && s.flagSize[1] === 52, `drapeau de ${s.flagSize} px`); + } else { + check(s.boardFlag, `paysage : drapeau absent de la colonne : ${JSON.stringify(s)}`); + } +} + +// ------------------------------------- Partie libre, videau à 2 : refus + +await startFrom(ATTACKED, CUBE_2_COMPUTER); +let s = await resignState(); +check(s.flag && s.menu && !s.sheet, `drapeau et menu à votre tour : ${JSON.stringify(s)}`); +await capture("1-drapeau", flagShown); + +await page.click("#resign"); +await until("feuille d'abandon", () => !document.getElementById("resign-veil").hidden); +s = await resignState(); +check(s.lead === "Vous proposez de perdre tout de suite. L'ordinateur accepte ou refuse, selon le moteur. Le videau est à 2.", + `phrase de la feuille : « ${s.lead} »`); +check(JSON.stringify(s.choices.map((c) => [c.kind, c.text, c.radio, c.checked])) === JSON.stringify([ + ["single", "Une partie simple2 points", true, "true"], + ["gammon", "Un gammon4 points", true, "false"], + ["backgammon", "Un backgammon6 points", true, "false"], +]), `choix en partie libre : ${JSON.stringify(s.choices)}`); +check(s.choices.every((c) => c.height >= 56), `cartes de moins de 56 px : ${JSON.stringify(s.choices)}`); +await capture("2-feuille-partie-libre", async () => { + check((await resignState()).sheet, "la feuille s'est fermée en changeant de taille"); +}); + +// La partie simple, choisie par défaut : refusée (gammon probable). +await page.click("#resign-confirm"); +await until("réponse de l'ordinateur", () => + document.getElementById("resign-veil").hidden && !document.body.classList.contains("busy")); +s = await resignState(); +check(s.refusal === "L'ordinateur refuse. D'après le moteur, il peut espérer plus qu'une partie simple en continuant. La partie continue.", + `message du refus : « ${s.refusal} »`); +check(s.roll && s.flag && s.panel === null, `après le refus, la partie continue : ${JSON.stringify(s)}`); +await capture("3-abandon-refuse", async (size) => { + const now = await resignState(); + if (size.width > size.height) { + check(now.band === "L'ordinateur refuse : à vous de lancer.", `bande après le refus : « ${now.band} »`); + } +}); + +// ------------------------------------------ Le gammon : accepté + +await page.click("#resign"); +await until("feuille d'abandon", () => !document.getElementById("resign-veil").hidden); +await page.click('#resign-choices [data-kind="gammon"]'); +s = await resignState(); +check(s.choices.find((c) => c.kind === "gammon")?.checked === "true", `gammon choisi : ${JSON.stringify(s.choices)}`); +await page.click("#resign-confirm"); +await until("fin de partie", () => !document.getElementById("panel-veil").hidden || + !document.getElementById("summary-veil").hidden); +const ended = await page.evaluate(() => ({ + panel: document.getElementById("panel-veil").hidden ? null : document.getElementById("panel-text").textContent, + summary: document.getElementById("summary-veil").hidden + ? null + : document.getElementById("summary-title")?.textContent, + info: document.getElementById("info").textContent, + flag: !document.getElementById("resign").hidden, +})); +check((ended.panel ?? ended.summary) === "Perdue par abandon, gammon, 4 points", + `fin par abandon : ${JSON.stringify(ended)}`); +check(!ended.flag, "drapeau après la fin"); +await capture("4-abandon-accepte"); +// Le bilan, une fois l'analyse prête, dit aussi l'abandon. +await until("bilan prêt", () => !document.getElementById("summary-veil").hidden && + document.getElementById("summary")?.dataset.ready === "true", null, 120_000); +const summaryTitle = await page.textContent("#summary-title"); +check(summaryTitle === "Perdue par abandon, gammon, 4 points", `bilan : « ${summaryTitle} »`); +await capture("5-bilan-abandon"); +await page.click("#summary-close"); + +// ------------------------- Partie libre, videau au centre : Jacoby + +await startFrom(ATTACKED); +await page.click("#resign"); +await until("feuille d'abandon", () => !document.getElementById("resign-veil").hidden); +s = await resignState(); +check(JSON.stringify(s.choices.map((c) => [c.kind, c.text, c.radio])) === + JSON.stringify([["single", "Une partie simple1 point", false]]), + `Jacoby : la partie simple seule, sans liste : ${JSON.stringify(s.choices)}`); +await capture("6-feuille-jacoby"); +await page.click("#resign-cancel"); +await until("feuille fermée", () => document.getElementById("resign-veil").hidden); +// Au lancer, plus de drapeau ; le menu n'a plus la ligne active. +await page.click("#roll"); +await until("dés lancés", () => !document.body.classList.contains("busy") && + document.getElementById("roll").hidden); +s = await resignState(); +check(!s.flag && !s.menu, `drapeau après le lancer : ${JSON.stringify(s)}`); + +// --------------------------------------------- Match en 7 points + +await page.evaluate(() => { + const saved = JSON.parse(localStorage.getItem("ustagammon.settings") ?? "{}"); + localStorage.setItem("ustagammon.settings", + JSON.stringify({ ...saved, gameKind: "match", matchLength: 7, level: "beginner" })); +}); +await page.goto(`${base}#/nouvelle-partie`); +await page.reload(); +await until("écran « Nouvelle partie »", () => !document.getElementById("new-game-start")?.disabled); +await page.click("#new-game-start"); +await until("match commencé", () => location.hash === "#/" && !document.body.classList.contains("busy")); +// Jouer jusqu'à votre tour avant le lancer. +for (let i = 0; i < 200; i++) { + const what = await page.evaluate(() => { + if (document.body.classList.contains("busy")) { + return null; + } + const usable = (id) => { + const b = document.getElementById(id); + return !b.hidden && !b.disabled; + }; + if (usable("roll")) { + return "roll"; + } + for (const id of ["take", "skip", "confirm"]) { + if (usable(id)) { + return id; + } + } + return document.querySelector(".hit.can-move") ? "move" : null; + }); + if (what === "roll") { + break; + } + if (what === "take") { + await page.click("#take"); + } else if (what === "skip" || what === "confirm") { + await page.click(`#${what}`); + } else if (what === "move") { + await page.click(".hit.can-move"); + if ((await page.locator(".hit.can-land").count()) > 0) { + await page.click(".hit.can-land"); + } + } else { + await sleep(100); + } +} +await until("bandeau parti", () => document.getElementById("banner").hidden, null, 15_000); +s = await resignState(); +check(s.flag, `match : drapeau à votre tour : ${JSON.stringify(s)}`); +// Par le menu, cette fois. +await page.click("#menu-button"); +await until("menu", () => !document.getElementById("menu-veil").hidden); +check(!(await page.isDisabled("#menu-resign")), "ligne « Abandonner la partie » du menu inactive"); +await page.click("#menu-resign"); +await until("feuille d'abandon", () => !document.getElementById("resign-veil").hidden && + document.getElementById("menu-veil").hidden); +s = await resignState(); +check(s.choices.length >= 1 && s.choices[0].text.startsWith("Une partie simplevous ") && + s.choices.every((c) => /vous \d+, l'ordinateur \d+/.test(c.text)), + `match : le score qui en résulterait : ${JSON.stringify(s.choices)}`); +await capture("7-feuille-match", async () => { + check((await resignState()).sheet, "la feuille s'est fermée en changeant de taille"); +}); +await page.keyboard.press("Escape"); +await until("feuille fermée", () => document.getElementById("resign-veil").hidden); + +const csp = await page.evaluate(() => window.__csp); +check(csp.length === 0, `violations de la politique de sécurité : ${csp.join(", ")}`); +await browser.close(); +if (problems.length > 0) { + console.error(problems.join("\n")); + process.exit(1); +} +log(`abandon : drapeau, feuille (partie libre, Jacoby, match), refus puis acceptation` + + `${full ? ` ; ${captures} captures dans retours-2/` : ""}`); diff --git a/web/app.css b/web/app.css index aca853f..2a4b800 100644 --- a/web/app.css +++ b/web/app.css @@ -674,9 +674,98 @@ a.notation { .actions .slot { display: flex; + gap: var(--space-2); min-width: 0; } +/* Abandonner : un drapeau au trait dans un bouton rond de 52 px, à gauche + * de la barre d'actions, jamais en brique (charte, « Abandonner une + * partie »). */ +.actions .slot .resign-flag { + flex: none; + width: 52px; + min-width: 52px; + height: 52px; + min-height: 52px; + margin-block: -2px; + padding: 0; + color: var(--text); + border-radius: 50%; +} + +/* L'ordinateur refuse l'abandon : le message du maître, au-dessus de la + * barre d'actions, jusqu'au lancer des dés. */ +.resign-refusal { + display: flex; + flex: none; + gap: var(--space-2); + align-items: flex-start; + margin: 0 0 var(--space-2); + padding: var(--space-2) 12px; + font-size: 15px; + line-height: 21px; + color: var(--text); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); +} + +.resign-refusal[hidden] { + display: none; +} + +.resign-refusal .icon { + flex: none; + width: 20px; + height: 20px; + margin-top: 1px; +} + +.resign-refusal strong { + margin-right: 0.25em; +} + +/* La feuille de choix de l'abandon : des cartes de 56 px, un seul choix. */ +.resign-lead { + margin: 0 0 var(--space-4); + font-size: 17px; + line-height: 25px; +} + +.resign-choices { + display: flex; + flex-direction: column; + gap: var(--space-2); + margin-bottom: var(--space-4); +} + +.resign-choice { + display: flex; + gap: var(--space-3); + align-items: center; + justify-content: space-between; + min-height: 56px; + padding: 0 var(--space-4); + font-weight: 700; + color: var(--text); + white-space: normal; + text-align: left; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius-md); +} + +button.resign-choice[aria-checked="true"] { + background: var(--accent-soft); + border: 2px solid var(--accent); +} + +.resign-choice-points { + font-weight: 400; + color: var(--muted); + text-align: right; +} + .actions .slot button { flex: 1; min-width: 0; @@ -1165,6 +1254,22 @@ a.notation { .cube-face { fill: var(--cube); stroke: var(--checker-player-edge); stroke-width: 2; } +/* Partie Crawford : le videau reste à sa place, estompé (charte). */ +.cube.crawford { opacity: 0.4; } + +/* Partie Crawford : « CRAWFORD » à la verticale sur la barre, dans une + * capsule au contour de 1,5 px, couleur des numéros du cadre. Ce n'est pas + * une cible : les touchers passent au travers. */ +.crawford-capsule { pointer-events: none; } +.crawford-capsule.appear { animation: fade-in var(--duration-fast) var(--easing-standard); } +.crawford-frame { fill: none; stroke: var(--point-number); stroke-width: 1.5; } + +.crawford-text { + fill: var(--point-number); + font-weight: 800; + text-anchor: middle; +} + .cube-value { fill: var(--cube-text); font-weight: 800; diff --git a/web/index.html b/web/index.html index 1aa69ad..1fe30dd 100644 --- a/web/index.html +++ b/web/index.html @@ -74,8 +74,13 @@

+ +
+ + @@ -157,6 +162,7 @@ + @@ -196,6 +202,24 @@
+ + +