// 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) ; // - le dé injouable (deux pions sur la barre, un seul dé rentre) : estompé, // barré, son libellé et la consigne qui dit pourquoi ; // - 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. */ /** La pastille de la bande, en paysage : sa police (en unités et en px à * l'écran), et si elle tient dans la bande sans chevaucher de pion. */ async function bandMeasure() { return page.evaluate(() => { const svg = document.getElementById("board"); const text = document.getElementById("band-text"); const pill = svg.querySelector(".band-pill"); if (text === null || pill === null) { return null; } const box = svg.getBoundingClientRect(); const vb = svg.viewBox.baseVal; const scale = Math.min(box.width / vb.width, box.height / vb.height); const p = pill.getBBox(); const t = text.getBBox(); const overlaps = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; const checkers = [...svg.querySelectorAll("[data-checker]")].filter((c) => overlaps(p, c.getBBox())); return { text: text.textContent, font: Number(text.getAttribute("font-size")), px: Number(text.getAttribute("font-size")) * scale, lines: text.querySelectorAll("tspan").length, fits: t.width <= p.width - 16 && t.y >= p.y && t.y + t.height <= p.y + p.height, overlaps: checkers.length, }; }); } // La police de la consigne ordinaire, mesurée en paysage (« À vous : lancez // les dés. ») : celle de toute pastille, jamais sous 12 px. let normalBandFont = null; async function flagShown(size) { if (size.width > size.height) { const band = await bandMeasure(); check(band !== null && band.px >= 12 && band.overlaps === 0, `consigne ordinaire : ${JSON.stringify(band)}`); normalBandFont = band.font; } 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 s'il n'espère pas mieux en continuant. 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 : il espère gagner 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é // Après le refus (règle de gnubg, fResignationDeclined) : la partie simple // est grisée, « déjà refusé », et le gammon présélectionné. await page.click("#resign"); await until("feuille d'abandon", () => !document.getElementById("resign-veil").hidden); s = await resignState(); const declined = await page.evaluate(() => document.querySelector('#resign-choices [data-kind="single"]').disabled); check(declined && JSON.stringify(s.choices.map((c) => [c.kind, c.text, c.checked])) === JSON.stringify([ ["single", "Une partie simpledéjà refusé", "false"], ["gammon", "Un gammon4 points", "true"], ["backgammon", "Un backgammon6 points", "false"], ]), `feuille après le refus : ${JSON.stringify(s.choices)}`); await capture("3b-feuille-apres-refus", async () => { check((await resignState()).sheet, "la feuille s'est fermée en changeant de taille"); }); await page.click("#resign-confirm"); // Le bilan, une page, arrive après le plateau final (étape 1m). await until("fin de partie", (title) => !document.getElementById("summary").hidden && document.getElementById("summary-title")?.textContent === title, "Perdue par abandon, gammon, 4 points"); check(await page.isHidden("#resign"), "drapeau après la fin"); // Le bilan, une fois l'analyse prête : aucun coup, une seule phrase. await until("bilan prêt", () => !document.getElementById("summary").hidden && document.getElementById("summary")?.dataset.ready === "true", null, 120_000); const bilan = await page.evaluate(() => ({ title: document.getElementById("summary-title")?.textContent, reading: document.getElementById("summary-detail")?.textContent, counts: document.getElementById("summary-counts") !== null, gauges: document.querySelector("#summary .summary-gauges") !== null, })); check(bilan.title === "Perdue par abandon, gammon, 4 points" && bilan.reading === "Aucun coup joué : rien à analyser." && !bilan.counts && !bilan.gauges, `bilan sans coup : ${JSON.stringify(bilan)}`); // Pas d'analyse vide à voir : « Rejouer » et « Changer les réglages » seuls. const bilanActions = await page.evaluate(() => ({ analysis: document.getElementById("summary-analysis") !== null, primary: document.getElementById("summary-primary")?.textContent, settings: document.getElementById("summary-settings")?.textContent, })); check(!bilanActions.analysis && bilanActions.primary === "Rejouer" && bilanActions.settings === "Changer les réglages", `actions du bilan sans coup : ${JSON.stringify(bilanActions)}`); await capture("5-bilan-abandon"); // Le retour du téléphone ramène à la partie finie : une seule phrase, celle // du maître, dans le style de l'état de la partie. await page.goBack(); await until("partie finie à l'écran", () => location.hash === "#/" && document.getElementById("summary").hidden && document.getElementById("prompt").textContent === "L'ordinateur accepte : vous perdez un gammon, 4 points."); const ending = await page.evaluate(() => ({ neutral: document.getElementById("prompt").classList.contains("neutral"), info: document.getElementById("info").textContent, })); check(!ending.neutral && !ending.info.includes("accepte"), `fin par abandon, une seule phrase : ${JSON.stringify(ending)}`); await capture("4-abandon-accepte"); // ------------------------- Partie libre, videau au centre : Jacoby await startFrom(ATTACKED); // « Doubler », à côté du drapeau : une zone de toucher d'au moins 44 px de // haut, un libellé jamais coupé (recette, 412 px de large). const doubleButton = await page.evaluate(() => { const b = document.getElementById("double"); const r = b.getBoundingClientRect(); return { shown: !b.hidden, height: r.height, clipped: b.scrollWidth > b.clientWidth + 0.5 }; }); check(doubleButton.shown && doubleButton.height >= 44 && !doubleButton.clipped, `« Doubler » à côté du drapeau : ${JSON.stringify(doubleButton)}`); 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, c.checked])) === JSON.stringify([["single", "Une partie simple1 point", true, "true"]]), `Jacoby : la partie simple seule, présélectionnée : ${JSON.stringify(s.choices)}`); const note = await page.evaluate(() => { const n = document.getElementById("resign-note"); return n.hidden ? null : n.textContent; }); check(note === "Le videau n'a pas été doublé : gammon et backgammon ne comptent pas (règle Jacoby).", `Jacoby : la note « ${note} »`); 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)}`); // ------------------------------------------- Dé injouable (retour de Pierre) // Deux pions sur la barre ; l'ordinateur tient vos flèches 20 à 24 : seul un // 6 rentre. Les dés sont tirés au hasard (graine fixe) : on recommence la // partie jusqu'à un jet avec un seul 6. const ONE_ENTRY = "2zY+AADg/wMAYA"; let other = null; for (let tries = 0; tries < 40 && other === null; tries++) { await startFrom(ONE_ENTRY); await page.click("#roll"); await until("dés lancés", () => !document.body.classList.contains("busy") && document.getElementById("roll").hidden); const dice = await page.evaluate(() => [...document.querySelectorAll("#board .die")].map((d) => Number(d.dataset.value))); if (dice.length === 2 && dice.filter((d) => d === 6).length === 1) { other = dice.find((d) => d !== 6); } } check(other !== null, "aucun jet avec un seul 6 en 40 essais"); const point = 25 - other; const blockedDie = () => page.evaluate(() => ({ labels: [...document.querySelectorAll("#board .die-blocked")].map((d) => d.getAttribute("aria-label")), strikes: document.querySelectorAll("#board .die-blocked .die-strike").length, prompt: document.getElementById("prompt").textContent, hint: document.getElementById("move-hint").hidden ? null : document.getElementById("move-hint").textContent, })); /** Paysage : la bande montre les deux phrases, dans sa pastille. */ const bandFits = (expected) => async (size) => { if (size.width <= size.height) { return; } const band = await bandMeasure(); // Même police que la consigne ordinaire (12 px au moins), sur deux // lignes s'il le faut, dans la pastille, sans chevaucher de pion. check(band !== null && band.text === expected && band.fits && band.overlaps === 0 && band.font === normalBandFont && band.px >= 12, `bande du dé injouable : ${JSON.stringify(band)} (police ordinaire ${normalBandFont})`); }; // Dès le lancer, le dé qui ne rentre pas est barré (il n'apparaît dans aucun // coup légal du moteur). let blocked = await blockedDie(); check(JSON.stringify(blocked.labels) === JSON.stringify([`${other} : ne peut pas être joué`]) && blocked.strikes === 1, `dé injouable dès le lancer : ${JSON.stringify(blocked)}`); // La consigne entière, en portrait ; rien dans la barre d'actions (Annuler // seul). check(blocked.prompt === `Le ${other} ne peut pas se jouer : la flèche ${point} est fermée. ` + "Rentrez un pion avec le 6." && blocked.hint === null, `consigne du dé injouable, au lancer : ${JSON.stringify(blocked)}`); await capture("8-de-injouable", bandFits(`Le ${other} ne se joue pas : flèche ${point} fermée. Rentrez un pion avec le 6.`)); await page.click('.hit.can-move[data-place="bar-player"]'); if ((await page.locator(".hit.can-land").count()) > 0) { await page.click(".hit.can-land"); } await until("pion rentré", () => !document.body.classList.contains("busy") && !document.getElementById("confirm").hidden); blocked = await blockedDie(); check(blocked.labels.length === 1 && blocked.prompt === `Le ${other} ne peut pas se jouer : la flèche ${point} ` + "est fermée. Jouez votre coup.", `consigne du dé injouable, après le 6 : « ${blocked.prompt} »`); await capture("8b-de-injouable-apres", bandFits(`Le ${other} ne se joue pas : flèche ${point} fermée. Jouez votre coup.`)); // --------------------------------------------- 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/` : ""}`);