Le petit dé seul jouable ne se dit plus « la règle impose » : le moteur dit si l'autre dé se jouait seul (coups légaux au double de sa valeur). Avec le drapeau, « Doubler » garde son libellé sur une ligne (marges réduites). Les tests navigateur acceptent la consigne du dé injouable et attendent le titre de la fin par abandon (panneau, puis bilan). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
400 lines
18 KiB
JavaScript
400 lines
18 KiB
JavaScript
// 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 <adresse du site> <chromium|firefox> <dossier des captures>
|
||
// Lancé par tests/browser.sh. Captures (Chromium) dans
|
||
// <dossier des captures>/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 <adresse> <chromium|firefox> <dossier des captures>");
|
||
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");
|
||
// Le panneau de fin, puis le bilan à sa place dès que l'analyse est prête :
|
||
// entre les deux, ni l'un ni l'autre un court instant.
|
||
await until("fin de partie", (title) =>
|
||
(!document.getElementById("panel-veil").hidden &&
|
||
document.getElementById("panel-text").textContent === title) ||
|
||
(!document.getElementById("summary-veil").hidden &&
|
||
document.getElementById("summary-title")?.textContent === title),
|
||
"Perdue par abandon, gammon, 4 points");
|
||
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)}`);
|
||
|
||
// ------------------------------------------- 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");
|
||
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("dé injouable", () => !document.body.classList.contains("busy") &&
|
||
document.querySelector("#board .die-blocked") !== null);
|
||
const blocked = await 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,
|
||
}));
|
||
check(JSON.stringify(blocked.labels) === JSON.stringify([`${other} : ne peut pas être joué`]) &&
|
||
blocked.strikes === 1, `dé injouable : ${JSON.stringify(blocked)}`);
|
||
const point = 25 - other;
|
||
// La forme longue de la consigne (les trois premières parties), ou la courte.
|
||
check(blocked.prompt === `Votre ${other} ne peut pas être joué : la flèche ${point} est fermée, ` +
|
||
"votre pion ne peut pas rentrer. Touchez les dés pour finir votre tour." ||
|
||
blocked.prompt === `Flèche ${point} fermée : touchez les dés.`,
|
||
`consigne du dé injouable : « ${blocked.prompt} »`);
|
||
await capture("8-de-injouable", async (size) => {
|
||
if (size.width > size.height) {
|
||
const band = await page.evaluate(() => document.getElementById("band-text")?.textContent ?? "");
|
||
check(band === `Flèche ${point} fermée : touchez les dés.`, `bande du dé injouable : « ${band} »`);
|
||
}
|
||
});
|
||
|
||
// --------------------------------------------- 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/` : ""}`);
|