Files
Ustagammon/tests/browser/match-bilan.mjs
T
Pierre MARTINandClaude Opus 5.5 3b0107af1b Bilan du match : page, courbe des chances de gagner le match, listes et accès
Page #/matchs/<id>/bilan (en-tête, courbe continue lue au doigt, partie par
partie, jeu, videau, moment décisif, décision à revoir, export SGF, prompt).
Un match tient en une ligne dans Mes parties et la progression ; le bilan et
l'analyse d'une partie de match y renvoient. Test navigateur d'un match en
5 points remonté de 0–4. ADR 0007 et 0013 amendés, plan clos.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 00:21:24 +01:00

410 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// match-bilan.mjs -- le bilan d'un match entier (étape 1l) : un match en 5
// points joué par l'interface avec des dés imposés, où le joueur est mené
// puis remonte et gagne ; puis la courbe continue des chances de gagner le
// match, le bilan, la courbe touchée, l'analyse d'une partie de match,
// « Mes parties » et l'export SGF (plan 2026-11-12-analyse-du-match.md ;
// charte, ecrans-etape-1.md, « Bilan du match »).
//
// Copyright (C) 2026 les auteurs d'Ustagammon.
// Licence : GPLv3 ou ultérieure (voir LICENSE).
//
// Usage : node match-bilan.mjs <adresse du site> <chromium|firefox> <dossier des captures>
// Lancé par tests/browser.sh. Les dés sont imposés à chaque jet : d'abord
// 2-1 pour le joueur et 6-5 pour l'ordinateur, jusqu'à ce que l'ordinateur
// mène d'au moins deux points ; puis l'inverse, jusqu'à la fin du match.
// Le joueur ne double jamais, passe les doubles de l'ordinateur quand il
// est mené et les prend ensuite, et joue le premier pion jouable vers sa
// première case d'arrivée. Le jet d'ouverture vient d'une graine fixe.
// Captures (Chromium) dans <dossier des captures>/match-bilan/, en 412×915
// et 915×412 : le bilan du match, la courbe touchée, « Mes parties » avec
// le match, et l'en-tête de l'analyse d'une partie du match.
import { mkdirSync, readFileSync } 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 match-bilan.mjs <adresse> <chromium|firefox> <dossier des captures>");
process.exit(2);
}
const full = browserName === "chromium";
const dir = `${shots}/match-bilan`;
mkdirSync(dir, { recursive: true });
const PORTRAIT = { width: 412, height: 915 };
const LANDSCAPE = { width: 915, height: 412 };
const SIZES = [PORTRAIT, LANDSCAPE];
// Les dés : [joueur, ordinateur], selon que l'ordinateur doit mener ou que
// le joueur remonte.
const LEADING = { player: [2, 1], computer: [6, 5] };
const COMEBACK = { player: [6, 5], computer: [2, 1] };
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",
acceptDownloads: true,
});
await context.addInitScript(() => {
// Les dés imposés d'abord (un dé par valeur), puis une graine fixe.
window.__dice = [];
let state = 11;
Math.random = () => {
const die = window.__dice.shift();
if (die !== undefined) {
return (die - 0.5) / 6;
}
state = (state * 1103515245 + 12345) % 2147483648;
return state / 2147483648;
};
window.__csp = [];
document.addEventListener("securitypolicyviolation", (e) =>
window.__csp.push(`${e.effectiveDirective} ${e.blockedURI}`),
);
});
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 = 180_000) {
for (let waited = 0; waited < ms; waited += 100) {
if (await page.evaluate(fn, arg)) {
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 en portrait et en paysage (Chromium
* seulement), après les règles communes. */
async function capture(name, before = async () => {}) {
if (!full) {
return;
}
for (const size of SIZES) {
await page.setViewportSize(size);
await sleep(300);
await before();
const hidden = await hiddenUnderActionBar(page);
check(hidden.length === 0,
`${name} ${size.width}x${size.height} : caché sous la barre d'action : ${hidden.join(", ")}`);
const tall = await tallButtons(page);
check(tall.length === 0, `${name} ${size.width}x${size.height} : boutons étirés : ${tall.join(", ")}`);
await page.screenshot({ path: `${dir}/${name}-${size.width}x${size.height}.png`, fullPage: true });
captures++;
}
await page.setViewportSize(PORTRAIT);
await sleep(300);
}
/** Les dés à imposer : vide la file, puis y met ceux-ci. */
const setDice = (dice) => page.evaluate((d) => {
window.__dice.length = 0;
window.__dice.push(...d);
}, dice);
/** Ajoute les dés du prochain jet de l'ordinateur, s'ils manquent. */
const ensureComputerDice = (dice) => page.evaluate((d) => {
if (window.__dice.length < 2) {
window.__dice.push(...d);
}
}, dice);
/** Le score du match tel que l'écran le montre. */
const score = () => page.evaluate(() => ({
computer: Number(document.querySelector("#strip-computer .match-score")?.textContent ?? "0"),
player: Number(document.querySelector("#strip-player .match-score")?.textContent ?? "0"),
}));
/** Ce que le joueur a à faire (comme tests/browser/match.mjs). */
async function todo() {
for (let i = 0; i < 1200; i++) {
const what = await page.evaluate(() => {
if (document.body.classList.contains("busy")) {
return null;
}
const panel = document.getElementById("panel-veil");
if (!panel.hidden) {
return panel.dataset.kind;
}
if (!document.getElementById("summary-veil").hidden) {
return "over";
}
const usable = (id) => {
const b = document.getElementById(id);
return !b.hidden && !b.disabled;
};
for (const id of ["take", "skip", "confirm", "roll"]) {
if (usable(id)) {
return id;
}
}
return document.querySelector(".hit.can-move") ? "move" : null;
});
if (what !== null) {
return what;
}
await sleep(100);
}
await page.screenshot({ path: `${dir}/${browserName}-bloque.png` }).catch(() => {});
throw new Error(`rien à faire depuis 120 s : « ${await page.textContent("#info")} »`);
}
// ------------------------------------------------- Le match, joué
await page.goto(`${base}#/nouvelle-partie`);
await until("moteur chargé", () => !document.getElementById("new-game-start").disabled);
await page.click("#new-game-match");
await page.click("#new-game-length-5");
await page.click("#new-game-level-beginner");
await page.click("#new-game-start");
await until("match commencé", () => location.hash === "#/" && !document.body.classList.contains("busy"));
let games = 1;
let deepest = { player: 0, computer: 0 };
let dice = LEADING;
let actions = 0;
for (;;) {
check(actions++ < 20000, "le match ne finit pas");
const what = await todo();
if (what === "over") {
await page.evaluate(() => {
window.__dice.length = 0;
});
await until("bilan de la partie prêt", () =>
document.getElementById("summary")?.dataset.ready === "true", null, 300_000);
const primary = await page.textContent("#summary-primary");
const now = await page.evaluate(() => {
const detail = document.getElementById("summary-reading").textContent;
const m = /vous (\d+), l'ordinateur (\d+)/.exec(detail);
return m === null ? null : { player: Number(m[1]), computer: Number(m[2]) };
});
check(now !== null, "score du match absent du bilan de la partie");
log(`partie ${games} : ${await page.textContent("#summary-title")} ; vous ${now.player}, l'ordinateur ${now.computer}`);
// Le bilan d'une partie de match renvoie au bilan du match.
const line = await page.textContent("#summary-match");
check(line.startsWith(`Partie ${games} du match en 5 points · Bilan du match`),
`ligne du match dans le bilan de la partie : « ${line} »`);
if (now.computer - now.player > deepest.computer - deepest.player) {
deepest = now;
}
if (primary === "Bilan du match") {
check(now.player >= 5 && now.computer < 5, `le joueur devait gagner le match : ${JSON.stringify(now)}`);
break;
}
check(primary === "Partie suivante", `fin de partie : « ${primary} »`);
// L'ordinateur mène d'au moins deux points : le joueur remonte.
dice = now.computer - now.player >= 2 ? COMEBACK : LEADING;
await page.click("#summary-primary");
games++;
await until("partie suivante", () => !document.body.classList.contains("busy") &&
document.getElementById("summary-veil").hidden);
continue;
}
if (what === "doubled" || what === "take") {
// Mené, le joueur passe ; ensuite il prend.
if (dice === LEADING) {
await page.click(what === "doubled" ? "#panel-secondary" : "#drop");
} else {
await ensureComputerDice(dice.computer);
await page.click(what === "doubled" ? "#panel-primary" : "#take");
}
} else if (what === "roll") {
await setDice([...dice.player, ...dice.computer]);
await page.click("#roll");
} else if (what === "skip" || what === "confirm") {
await ensureComputerDice(dice.computer);
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");
}
}
}
check(deepest.computer - deepest.player >= 2, `le joueur n'a jamais été mené : ${JSON.stringify(deepest)}`);
log(`match gagné en ${games} parties, après avoir été mené ${deepest.player} à ${deepest.computer} (${actions} actions)`);
// ----------------------------------------------- Le bilan du match
await page.click("#summary-primary");
await until("bilan du match", () => /^#\/matchs\/[a-z0-9-]+\/bilan$/.test(location.hash) &&
document.getElementById("match-title") !== null);
const matchHash = await page.evaluate(() => location.hash);
// Toutes les analyses : la courbe complète, en chances de gagner le match.
await until("courbe complète", () => {
const svg = document.getElementById("match-curve");
const points = svg === null ? [] : JSON.parse(svg.dataset.points ?? "[]");
return document.getElementById("match-summary").dataset.ready === "true" &&
points.length > 0 && points.every((p) => p[2] !== null);
}, null, 900_000);
const bilan = await page.evaluate(() => ({
overline: document.getElementById("match-overline").textContent,
title: document.getElementById("match-title").textContent,
sentence: document.getElementById("match-sentence").textContent,
points: JSON.parse(document.getElementById("match-curve").dataset.points),
lines: document.querySelectorAll("#match-curve polyline").length,
label: document.getElementById("match-curve").getAttribute("aria-label"),
rows: [...document.querySelectorAll("#match-games .match-game-score")].map((e) => e.textContent),
tiles: [...document.querySelectorAll(".match-tile strong")].map((e) => e.textContent),
cube: document.getElementById("match-cube-sentence")?.textContent ?? "",
decisive: document.getElementById("match-decisive-sentence")?.textContent ?? "",
review: document.getElementById("match-to-review") !== null,
exportText: document.getElementById("match-export")?.textContent,
gameIds: [...document.querySelectorAll("#match-games a")].map((a) =>
/^#\/parties\/([a-z0-9-]+)\/bilan$/.exec(a.getAttribute("href"))?.[1]),
}));
log(`bilan : ${bilan.title} ; ${bilan.sentence} ; ${bilan.points.length} points ; videau : ${bilan.cube}`);
check(bilan.overline.startsWith("Fin du match · 5 points · "), `en-tête : « ${bilan.overline} »`);
check(bilan.title === "Vous gagnez le match", `titre : « ${bilan.title} »`);
check(new RegExp(`^5 à \\d, en \\S+ parties?, après avoir été mené ${deepest.player} à ${deepest.computer}\\.$`)
.test(bilan.sentence) || /après avoir été mené \d à \d\.$/.test(bilan.sentence),
`phrase de l'en-tête : « ${bilan.sentence} »`);
// La courbe : une seule ligne, du début du match (50 %) à sa fin (100 %),
// les parties dans l'ordre, chacune à la suite de la précédente.
check(bilan.lines === 1, `${bilan.lines} lignes sur la courbe au lieu d'une`);
check(bilan.points[0][2] === 0.5 && bilan.points.at(-1)[2] === 1,
`courbe : début ${bilan.points[0][2]}, fin ${bilan.points.at(-1)[2]}`);
const order = bilan.points.map((p) => p[0]);
check(order.every((g, i) => i === 0 || g === order[i - 1] || g === order[i - 1] + 1) && order.at(-1) === games,
`courbe : parties dans le désordre ${JSON.stringify(order)}`);
check(bilan.points.every((p) => p[2] >= 0 && p[2] <= 1), "courbe : chances hors de 0 à 100 %");
check(/^Courbe de vos chances de gagner le match : 50\s% au départ/.test(bilan.label),
`libellé de la courbe : « ${bilan.label} »`);
check(bilan.gameIds.length === games && bilan.gameIds.every((id) => id !== undefined),
`liens des parties : ${JSON.stringify(bilan.gameIds)}`);
check(bilan.rows.length === games && bilan.rows.at(-1).startsWith("5–"),
`partie par partie : ${JSON.stringify(bilan.rows)}`);
check(bilan.tiles.length === 3, "tuiles du jeu");
check(/décision|Aucune décision/.test(bilan.cube), `phrase du videau : « ${bilan.cube} »`);
check(/vos chances de gagner le match passent de \d+\s% à \d+\s%\. C'est le plus grand écart du match\.$/
.test(bilan.decisive), `moment décisif : « ${bilan.decisive} »`);
check(bilan.exportText === "Exporter le match (SGF)", "lien d'export");
// En match, les pertes s'écrivent en chances de gagner le match, jamais en
// équité.
const losses = await page.evaluate(() =>
[...document.querySelectorAll("#match-summary .match-loss")].map((e) => e.textContent));
check(losses.every((t) => /^−?\d+,\d\s%( de chances de gagner le match)?$/.test(t)),
`pertes : ${JSON.stringify(losses)}`);
await capture("1-bilan-du-match");
// La courbe touchée : la bulle (partie, coup, score, chances), un lien vers
// la décision.
const touchCurve = async () => {
const box = await page.locator("#match-curve").boundingBox();
await page.mouse.move(box.x + box.width * 0.55, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x + box.width * 0.6, box.y + box.height / 2, { steps: 4 });
await page.mouse.up();
await until("bulle de la courbe", () => document.getElementById("match-bubble") !== null, null, 10_000);
};
await page.locator("#match-curve").scrollIntoViewIfNeeded();
await touchCurve();
const bubble = await page.evaluate(() => ({
href: document.getElementById("match-bubble").getAttribute("href"),
text: document.querySelector("#match-bubble .match-bubble-text").textContent,
}));
check(/^#\/parties\/[a-z0-9-]+\/analyse\/\d+$/.test(bubble.href), `lien de la bulle : ${bubble.href}`);
check(/^Partie \d, coup \d+ · \d–\d · \d+\s%$/.test(bubble.text), `bulle : « ${bubble.text} »`);
await capture("2-courbe-touchee", async () => {
await page.locator("#match-curve").scrollIntoViewIfNeeded();
await touchCurve();
});
// Au clavier aussi : ← → d'une décision à l'autre.
await page.focus("#match-curve");
await page.keyboard.press("ArrowLeft");
check(await page.evaluate(() => document.getElementById("match-bubble") !== null), "bulle au clavier");
// Toucher la bulle ouvre la décision, dans l'analyse de sa partie : en tête,
// la partie dans le match, avec ‹ et ›.
await page.locator("#match-curve").scrollIntoViewIfNeeded();
await touchCurve();
await page.click("#match-bubble");
await until("analyse d'une partie du match", () =>
/^#\/parties\/[a-z0-9-]+\/analyse\/\d+$/.test(location.hash) &&
!document.getElementById("analysis-match").hidden);
const header = await page.textContent("#analysis-match-title");
check(new RegExp(`^Partie \\d sur ${games} · \\d–\\d$`).test(header), `en-tête de l'analyse : « ${header} »`);
await capture("3-analyse-partie-de-match", async () => {
await page.evaluate(() => window.scrollTo(0, 0));
});
// « › » mène à la partie suivante, « ‹ » à la précédente.
const before = await page.evaluate(() => location.hash);
const nextHref = await page.getAttribute("#analysis-next-game", "href");
const previousHref = await page.getAttribute("#analysis-previous-game", "href");
check(nextHref !== null || previousHref !== null, "aucune partie voisine dans l'en-tête de l'analyse");
await page.click(nextHref !== null ? "#analysis-next-game" : "#analysis-previous-game");
await until("autre partie du match", (h) => location.hash !== h &&
/^Partie \d sur/.test(document.getElementById("analysis-match-title").textContent), before);
// « Mes parties » : le match tient en une ligne.
await page.goto(`${base}#/parties`);
await until("Mes parties", () => document.querySelector("#games .games-match") !== null);
const line = await page.evaluate((ids) => {
const item = document.querySelector("#games .games-match");
return {
title: item.querySelector("strong").textContent,
strokes: item.querySelectorAll(".match-stroke").length,
won: item.querySelectorAll(".match-stroke.won").length,
href: item.querySelector("a").getAttribute("href"),
// Les parties du match n'ont plus leur propre ligne.
others: ids.filter((id) => document.querySelector(`#games .games-item[data-id="${id}"]`) !== null)
.length,
};
}, bilan.gameIds);
check(/^Match en 5 points · gagné 5–\d$/.test(line.title), `ligne du match : « ${line.title} »`);
check(line.strokes === games && line.won >= 2, `traits du match : ${JSON.stringify(line)}`);
check(line.href === matchHash, `la ligne du match ouvre ${line.href}`);
check(line.others === 0, `${line.others} parties du match listées à part`);
await capture("4-mes-parties");
// La progression : le match en une ligne aussi.
await page.goto(`${base}#/progression`);
await until("progression", () => document.querySelector("#progression-list .match-line") !== null);
// Retour au bilan du match : export SGF du match entier.
await page.goto(`${base}${matchHash}`);
await until("bilan du match relu", () => document.getElementById("match-export") !== null);
const [download] = await Promise.all([page.waitForEvent("download"), page.click("#match-export")]);
const sgf = readFileSync(await download.path(), "utf8");
const infos = [...sgf.matchAll(/MI\[length:5\]\[game:(\d+)\]/g)].map((m) => Number(m[1]));
check(JSON.stringify(infos) === JSON.stringify([...Array(games).keys()]),
`export SGF : parties ${JSON.stringify(infos)}`);
check(download.suggestedFilename().startsWith("ustagammon-match-"), `nom du fichier : ${download.suggestedFilename()}`);
// « Demander à une IA » : le prompt « Bilan de mon match ».
await page.click("#match-ask-ai");
await until("prompt du match", () => /\/bilan\/ia$/.test(location.hash) &&
(document.getElementById("prompt-text")?.textContent ?? "").includes("match en 5 points"));
const prompt = await page.textContent("#prompt-text");
check(prompt.includes("j'ai gagné le match 5 à") && prompt.includes("Le videau :"), "prompt du match incomplet");
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) {
throw new Error(problems.join("\n"));
}
log(`bilan du match : ${captures} captures dans ${dir}`);