Fusion de main (analyse du match, 1l) ; l'abandon passe en version 4 des événements

La version 3 est celle de main (identifiant de match) ; l'abandon prend la
version 4, avec la migration des versions 1, 2 et 3 testée.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-23 08:03:02 +01:00
co-authored by Claude Opus 5.5
74 changed files with 5232 additions and 156 deletions
+15 -3
View File
@@ -31,9 +31,14 @@
# build/browser-shots/retours-2/ ; la capsule « Crawford » y est capturée
# par match.mjs.
#
# Le bilan d'un match entier (tests/browser/match-bilan.mjs : un match en 5
# points avec dés imposés, où le joueur remonte après avoir été mené ; courbe
# continue, bilan, analyse, « Mes parties », export SGF, prompt), captures
# dans build/browser-shots/match-bilan/.
#
# BROWSERS=chromium et SCRIPTS=accueil (ou play, match, maitre, bilan,
# prompts, nouvelle-partie, retours-joueurs, lecons, progression, plateau,
# retours-2)
# match-bilan, retours-2)
# restreignent le test.
#
# Outils : l'image de Playwright (navigateurs) et le paquet playwright,
@@ -47,7 +52,7 @@ cd "$(dirname "$0")/.."
image="${PLAYWRIGHT_IMAGE:?lancer via make test-browser}"
browsers="${BROWSERS:-chromium firefox}"
# Les scripts à lancer (tests/browser/<nom>.mjs), tous par défaut.
scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression plateau retours-2}"
scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression plateau match-bilan retours-2}"
unset MAKEFLAGS MFLAGS MAKELEVEL
make -s package >/dev/null
@@ -87,7 +92,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 \
tests/browser/retours-2.mjs "$tools/"
tests/browser/retours-2.mjs tests/browser/match-bilan.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
@@ -178,5 +183,12 @@ for browser in $browsers; do
-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
if [[ " $scripts " == *" match-bilan "* ]]; then
# Le bilan d'un match entier (étape 1l) ; captures dans
# build/browser-shots/match-bilan/.
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 match-bilan.mjs "http://localhost:$port/" "$browser" /shots || status=1
fi
done
exit "$status"
+475
View File
@@ -0,0 +1,475 @@
// 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. */
/** Deux images de plus : la mise en page et ce qui se redessine après elle
* (la courbe du match) sont finis. */
const frames = () =>
page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function capture(name, before = async () => {}, after = async () => {}) {
if (!full) {
return;
}
for (const size of SIZES) {
await page.setViewportSize(size);
await sleep(300);
await frames();
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 });
await frames();
await after();
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)}`);
/** Recette : chaque texte de la courbe fait au moins 12 px à l'écran
* (taille de la police, mise à l'échelle du viewBox). */
async function curveTextsReadable(where) {
const small = await page.evaluate(() => {
const svg = document.getElementById("match-curve");
const box = svg.getBoundingClientRect();
const view = svg.viewBox.baseVal;
const scale = Math.min(box.width / view.width, box.height / view.height);
const found = [...svg.querySelectorAll("text")]
.map((t) => ({ text: t.textContent, px: parseFloat(getComputedStyle(t).fontSize) * scale }))
.filter((t) => t.px < 11.95)
.map((t) => `« ${t.text} » ${t.px.toFixed(1)} px`);
// Le tracé remplit la courbe : le viewBox a la taille rendue, sans
// bande vide sous le tracé ni à côté.
if (Math.abs(box.width - view.width) > 2 || Math.abs(box.height - view.height) > 2) {
found.push(`viewBox ${view.width}x${view.height} pour ${Math.round(box.width)}x${Math.round(box.height)} rendus`);
}
return found;
});
check(small.length === 0, `${where} : courbe mal dessinée : ${small.join(", ")}`);
}
await curveTextsReadable("portrait");
// Le moment décisif sur la fin du match : l'anneau or seul, et la légende
// le dit.
// Dans ce match, le moment décisif (le 2-1 de l'ordinateur, jusqu'à
// 100 %) touche le point de fin à l'écran : l'anneau or seul, et la légende
// le dit (charte : deux marques à moins de 16 px n'en font qu'une).
async function mergedMarks(where) {
const legend = await page.evaluate(() => ({
items: [...document.querySelectorAll(".match-legend li")].map((li) => li.textContent),
endDot: document.querySelector("#match-curve .match-mark-end") !== null,
ring: document.querySelector("#match-curve .match-mark-ring") !== null,
}));
check(legend.ring && !legend.endDot &&
JSON.stringify(legend.items) === JSON.stringify(["Moment décisif, fin du match", "Décision à revoir"]),
`${where} : marques et légende de la courbe : ${JSON.stringify(legend)}`);
}
/** La courbe telle qu'elle est rendue : libellés lisibles, marques. */
async function curveChecks(where) {
await curveTextsReadable(where);
await mergedMarks(where);
}
await frames();
await mergedMarks("portrait");
// Les tuiles : le chiffre seul, l'unité en une ligne dessous.
check((await page.textContent("#match-tiles-caption")).startsWith("Taux d'erreur, en millièmes par décision"),
"légende des tuiles");
await capture(
"1-bilan-du-match",
() => curveChecks("avant la capture"),
() => curveChecks("après la capture"),
);
// 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( · Crawford)?$`).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,
caption: item.querySelector(".caption").textContent,
aligned: (() => {
const strong = item.querySelector("strong").getBoundingClientRect();
const caption = item.querySelector(".caption").getBoundingClientRect();
return Math.abs(strong.left - caption.left) < 1;
})(),
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(/· contre Débutant$/.test(line.caption) && line.aligned, `détail de la ligne du match : ${JSON.stringify(line)}`);
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}`);
+3 -1
View File
@@ -346,7 +346,9 @@ for (;;) {
});
check(settingsLink?.text === "Changer les réglages" && settingsLink.href === "#/nouvelle-partie",
`lien « Changer les réglages » : ${JSON.stringify(settingsLink)}`);
if (primary === "Rejouer") {
// À la fin du match, le bilan de la dernière partie mène au bilan
// du match (étape 1l) ; « Rejouer » reste sous le plateau.
if (primary === "Bilan du match") {
check(/gagne(z)? le match$/.test(title) && detail.includes("Score final"),
`fin du match : ${title} ; ${detail}`);
const [, player, computer] = /vous (\d+), l'ordinateur (\d+)/.exec(detail) ?? [];
+16 -3
View File
@@ -245,10 +245,13 @@ gnubg en tire.
- `levels` : `position_id`, `match_id` et `dice` (`null` : décision de
videau) ;
- `resigns` : `position_id` et `match_id` (sans dés) d'une position où le
joueur au trait propose d'abandonner, avant de lancer les dés.
joueur au trait propose d'abandonner, avant de lancer les dés ;
- `chances` (étape 1l) : `match_id` (un match, sans position) et
`equities`, des équités normalisées à convertir en chances de gagner le
match.
Un fichier de résultat reprend le cas, avec `type` (`move`, `cube`,
`level` ou `resign`), `gnubg_commit` et `met`, puis, aux niveaux d'analyse 0 et 2 plis
`level`, `chance` ou `resign`), `gnubg_commit` et `met`, puis, aux niveaux d'analyse 0 et 2 plis
(clés de `plies`, réglages prédéfinis de gnubg sans bruit, filtre
« Normal ») :
@@ -282,7 +285,17 @@ Un fichier de résultat reprend le cas, avec `type` (`move`, `cube`,
abandonne), puis `resignations`, pour `single`, `gammon` et `backgammon` :
la réponse de l'ordinateur de gnubg à la commande « resign » du joueur au
trait (`accepted`) et, s'il accepte, les points qu'il gagne (`points`,
sinon `null`).
sinon `null`) ;
- **chances de gagner le match** (`chance`, sans `plies`) : `at_score`, les
chances du joueur au trait de gagner le match au score du Match ID, avant
la partie, lues dans la table d'équité de match de gnubg (`gnubg.met`,
comme `getMEAtScore` dans `matchequity.c` : table d'après Crawford pour
les parties qui suivent la partie Crawford) ; puis, pour chaque équité de
`equities`, `mwc` (`gnubg.eq2mwc`, avec le videau et le score du Match
ID) et `loss`, la même équité vue comme le coût d'une erreur dans les
statistiques de match de gnubg (`updateStatcontext` dans `analysis.c` :
`eq2mwc(équité) - eq2mwc(0)`). `compare.py` les compare à la commande
`mwc` d'`engine-cli`.
Deux précautions, faute de quoi gnubg donne des valeurs qui dépendent de ce
qu'il a calculé avant :
Binary file not shown.
+56
View File
@@ -323,5 +323,61 @@
"position_id": "sp2DBwDgOfgAaA",
"match_id": "EQHgACAAIAAE"
}
],
"chances": [
{
"id": "chances-5-0-0",
"description": "Match en 5 points à 0-0 : table d'avant Crawford.",
"match_id": "MAGgAAAAAAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-5-0-2",
"description": "Match en 5 points, joueur au trait mené 0-2.",
"match_id": "MAGgAAAAEAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-5-2-4-cube-2",
"description": "Match en 5 points, 2-4, videau à 2 chez l'adversaire.",
"match_id": "EQGgACAAIAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-5-4-3-crawford",
"description": "Match en 5 points, 4-3, partie Crawford.",
"match_id": "sAGgAEAAGAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-5-4-3-post-crawford",
"description": "Match en 5 points, 4-3, après la partie Crawford.",
"match_id": "MAGgAEAAGAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-5-3-4-post-crawford",
"description": "Match en 5 points, 3-4, après la partie Crawford, joueur au trait mené.",
"match_id": "MAGgADAAIAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-7-1-3-cube-4",
"description": "Match en 7 points, 1-3, videau à 4 chez le joueur au trait.",
"match_id": "AgHgABAAGAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-7-other-on-roll",
"description": "Match en 7 points, l'autre joueur au trait (Match ID de match-7-cube).",
"match_id": "cAngAFAAGAAE",
"equities": [-0.25, -0.03, 0.4]
},
{
"id": "chances-5-post-crawford-other-on-roll",
"description": "Match en 5 points après Crawford, l'autre joueur au trait (Match ID de match-post-crawford-cube).",
"match_id": "cAmgAEAAEAAE",
"equities": [-0.25, -0.03, 0.4]
}
]
}
@@ -0,0 +1,26 @@
{
"id": "chances-5-0-0",
"description": "Match en 5 points à 0-0 : table d'avant Crawford.",
"match_id": "MAGgAAAAAAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.48067,
"loss": -0.019329995
},
{
"equity": -0.03,
"mwc": 0.4976804,
"loss": -0.0023196042
},
{
"equity": 0.4,
"mwc": 0.530928,
"loss": 0.030928016
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.5
}
@@ -0,0 +1,26 @@
{
"id": "chances-5-0-2",
"description": "Match en 5 points, joueur au trait mené 0-2.",
"match_id": "MAGgAAAAEAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.32094374,
"loss": -0.021511257
},
{
"equity": -0.03,
"mwc": 0.33987364,
"loss": -0.002581358
},
{
"equity": 0.4,
"mwc": 0.376873,
"loss": 0.034417987
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.35205
}
@@ -0,0 +1,26 @@
{
"id": "chances-5-2-4-cube-2",
"description": "Match en 5 points, 2-4, videau à 2 chez l'adversaire.",
"match_id": "EQGgACAAIAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.1875,
"loss": -0.0625
},
{
"equity": -0.03,
"mwc": 0.2425,
"loss": -0.007499993
},
{
"equity": 0.4,
"mwc": 0.35,
"loss": 0.099999994
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.32264
}
@@ -0,0 +1,26 @@
{
"id": "chances-5-3-4-post-crawford",
"description": "Match en 5 points, 3-4, après la partie Crawford, joueur au trait mené.",
"match_id": "MAGgADAAIAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.1875,
"loss": -0.0625
},
{
"equity": -0.03,
"mwc": 0.2425,
"loss": -0.007499993
},
{
"equity": 0.4,
"mwc": 0.35,
"loss": 0.099999994
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.48803
}
@@ -0,0 +1,26 @@
{
"id": "chances-5-4-3-crawford",
"description": "Match en 5 points, 4-3, partie Crawford.",
"match_id": "sAGgAEAAGAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.6875,
"loss": -0.0625
},
{
"equity": -0.03,
"mwc": 0.7425,
"loss": -0.007499993
},
{
"equity": 0.4,
"mwc": 0.85,
"loss": 0.100000024
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.67736
}
@@ -0,0 +1,26 @@
{
"id": "chances-5-4-3-post-crawford",
"description": "Match en 5 points, 4-3, après la partie Crawford.",
"match_id": "MAGgAEAAGAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.6875,
"loss": -0.0625
},
{
"equity": -0.03,
"mwc": 0.7425,
"loss": -0.007499993
},
{
"equity": 0.4,
"mwc": 0.85,
"loss": 0.100000024
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.51197004
}
@@ -0,0 +1,26 @@
{
"id": "chances-5-post-crawford-other-on-roll",
"description": "Match en 5 points après Crawford, l'autre joueur au trait (Match ID de match-post-crawford-cube).",
"match_id": "cAmgAEAAEAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.18301125,
"loss": -0.061003745
},
{
"equity": -0.03,
"mwc": 0.23669454,
"loss": -0.0073204488
},
{
"equity": 0.4,
"mwc": 0.34162098,
"loss": 0.09760599
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.32264
}
@@ -0,0 +1,26 @@
{
"id": "chances-7-1-3-cube-4",
"description": "Match en 7 points, 1-3, videau à 4 chez le joueur au trait.",
"match_id": "AgHgABAAGAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.2507625,
"loss": -0.0835875
},
{
"equity": -0.03,
"mwc": 0.32431948,
"loss": -0.010030508
},
{
"equity": 0.4,
"mwc": 0.46809,
"loss": 0.13374001
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.35715
}
@@ -0,0 +1,26 @@
{
"id": "chances-7-other-on-roll",
"description": "Match en 7 points, l'autre joueur au trait (Match ID de match-7-cube).",
"match_id": "cAngAFAAGAAE",
"equities": [
{
"equity": -0.25,
"mwc": 0.26622373,
"loss": -0.02686125
},
{
"equity": -0.03,
"mwc": 0.28986162,
"loss": -0.0032233596
},
{
"equity": 0.4,
"mwc": 0.33606297,
"loss": 0.04297799
}
],
"type": "chance",
"gnubg_commit": "14b67984737ded0f6de43d63dcb789f729d9b06b",
"met": "Kazaross-XG2",
"at_score": 0.33130002
}
+12
View File
@@ -255,6 +255,16 @@ def compare_cube_analysis(report, cli, case):
expected["equity_loss"], SKILL_THRESHOLDS)
def compare_chances(report, cli, case):
"""Chances de gagner le match : table au score, conversion d'équités."""
for item in case["equities"]:
actual = run_cli(cli, ["mwc", case["match_id"], repr(item["equity"])])
where = "%s, équité %s" % (case["id"], item["equity"])
report.number(where, "at_score", case["at_score"], actual["at_score"])
report.number(where, "mwc", item["mwc"], actual["mwc"])
report.number(where, "loss", item["loss"], actual["loss"])
def compare_levels(report, cli, case, settings):
for name, expected in sorted(case["levels"].items()):
where = "%s niveau %s" % (case["id"], name)
@@ -306,6 +316,8 @@ def compare_analyses(report, cli, folder):
compare_cube_analysis(report, cli, case)
elif case["type"] == "resign":
compare_resign(report, cli, case)
elif case["type"] == "chance":
compare_chances(report, cli, case)
else:
compare_levels(report, cli, case, settings)
return len(paths)
+51 -2
View File
@@ -426,6 +426,53 @@ def resign_case(case):
}
# --------------------------------------------------------------------------
# Chances de gagner le match (analyses.json, « chances ») : la table d'équité
# de match de gnubg au score du Match ID, et la conversion d'une équité
# normalisée en chances de gagner le match (eq2mwc), avec le coût d'une
# erreur des statistiques de match (updateStatcontext, analysis.c :
# « eq2mwc(rSkill, &ci) - eq2mwc(0.0f, &ci) »).
START_POSITION = "4HPwATDgc/ABMA"
def single(x):
"""x arrondi en simple précision, comme le calcul de gnubg en float."""
return struct.unpack("<f", struct.pack("<f", x))[0]
def met_at_score(ci):
"""getMEAtScore de gnubg (matchequity.c) pour le joueur au trait : une
lecture de la table que gnubg donne (gnubg.met), sans autre calcul.
Avant ou pendant la partie Crawford, la table d'avant Crawford ; après,
la table d'après Crawford du joueur qui mène."""
length = ci["matchto"]
table = gnubg.met(length)
away0 = length - ci["score"][0] - 1
away1 = length - ci["score"][1] - 1
if not ci["crawford"] and (away0 == 0 or away1 == 0):
me0 = single(1.0 - table[2][away1]) if away0 == 0 else table[1][away0]
else:
me0 = table[0][away0][away1]
return me0 if ci["move"] == 0 else single(1.0 - me0)
def match_chances(case):
gnubg.command("set gnubgid %s:%s" % (START_POSITION, case["match_id"]))
if gnubg.matchid() != case["match_id"]:
raise SystemExit("%s : gnubg relit %s" % (case["id"], gnubg.matchid()))
ci = cube_info()
zero = gnubg.eq2mwc(0.0, ci)
return {
"at_score": f32(met_at_score(ci)),
"equities": [
{"equity": equity, "mwc": f32(gnubg.eq2mwc(equity, ci)),
"loss": f32(single(gnubg.eq2mwc(equity, ci) - zero))}
for equity in case["equities"]
],
}
def write_analysis(out_dir, result):
with open(os.path.join(out_dir, result["id"] + ".json"), "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
@@ -443,10 +490,12 @@ def generate_analyses(commit):
gnubg.command("set display off")
gnubg.command("set automatic game off")
gnubg.command("set automatic roll off")
for kind in ("moves", "cubes", "levels"):
for kind in ("moves", "cubes", "levels", "chances"):
for case in cases[kind]:
result = dict(case, type=kind[:-1], gnubg_commit=commit, met=MET)
if kind == "moves":
if kind == "chances":
result.update(match_chances(case))
elif kind == "moves":
result["plies"] = {}
for ply in PLIES:
result["plies"][str(ply)], result["luck"] = analyse_move(case, ply)
+52 -1
View File
@@ -70,10 +70,61 @@ def check(path):
return errors
def check_game_records(records, expected, where):
"""Avance dans la partie courante de gnubg enregistrement par
enregistrement : après chaque coup, sa position doit être celle du
journal."""
gnubg.command("first move")
after = []
for record in records:
gnubg.command("next")
if record["action"] == "move":
after.append(gnubg.positionid())
errors = []
if len(after) != len(expected["after"]):
errors.append("%s%d coups lus, %d attendus" % (where, len(after), len(expected["after"])))
for i, (got, want) in enumerate(zip(after, expected["after"])):
if got != want:
errors.append("%saprès le coup %d : gnubg %s, journal %s" % (where, i + 1, got, want))
break
return errors
def check_match(path):
"""Un match entier (étape 1l) : gnubg charge le fichier (load match),
y trouve la longueur du match, et pour chaque partie, dans l'ordre, le
score avant elle, les positions après chaque coup et le résultat."""
with open(path[:-4] + ".json") as f:
expected = json.load(f)
gnubg.command("load match " + path)
match = gnubg.match(analysis=0, boards=0, statistics=0, verbose=0)
games = match["games"]
errors = []
if match["match-info"].get("match-length") != expected["length"]:
errors.append("longueur : gnubg %s" % match["match-info"])
if len(games) != len(expected["games"]):
return errors + ["%d parties lues, %d attendues" % (len(games), len(expected["games"]))]
gnubg.command("first game")
for index, (game, want) in enumerate(zip(games, expected["games"])):
where = "partie %d : " % (index + 1)
if index > 0:
gnubg.command("next game")
info = game["info"]
score = (info.get("score-X"), info.get("score-O"))
if score != (want["score"]["computer"], want["score"]["player"]):
errors.append("%sscore avant la partie : gnubg %s, journal %s" % (where, score, want["score"]))
errors += check_game_records(list(game["game"]), want, where)
result = want["result"]
winner = "O" if result["winner"] == "player" else "X"
if (info.get("winner"), info.get("points-won")) != (winner, result["points"]):
errors.append("%srésultat : gnubg %s, journal %s" % (where, info, result))
return errors
failures = 0
paths = sorted(glob.glob(os.path.join(FOLDER, "*.sgf")))
for path in paths:
errors = check(path)
errors = check_match(path) if os.path.basename(path).startswith("match-") else check(path)
name = os.path.basename(path)
if errors:
failures += 1
+6 -1
View File
@@ -149,10 +149,15 @@ elif .type == "resign" then
and all(.resignations[]; (.accepted | type) == "boolean"
and (if .accepted then (.points | nombre) else .points == null end))
then empty else "abandon incomplet" end)
elif .type == "chance" then
(if (.match_id | test("^[A-Za-z0-9+/]{12}$")) and (.at_score | nombre)
and .at_score >= 0 and .at_score <= 1 and (.equities | length) > 0
and all(.equities[]; (.equity | nombre) and (.mwc | nombre) and (.loss | nombre))
then empty else "chances de gagner le match incomplètes" end)
else "type inconnu" end
JQ
mapfile -t analyses < <(jq -r '(.moves + .cubes + .levels + .resigns)[].id' analyses.json)
mapfile -t analyses < <(jq -r '(.moves + .cubes + .levels + .chances + .resigns)[].id' analyses.json)
doublons="$(printf '%s\n' "${analyses[@]}" "${ids[@]}" | sort | uniq -d | paste -sd' ' -)"
[ -z "$doublons" ] || signaler "analyses.json : identifiants en double : $doublons"
for id in "${analyses[@]}"; do