From f9b8663afbeaff509d9c084ac5b1a68c73838707 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Thu, 12 Nov 2026 23:55:51 +0100 Subject: [PATCH 1/6] Moteur : chances de gagner le match (table de gnubg), export SGF d'un match entier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commande mwc d'engine-cli et engine_match_chances_of : chances au score (getMEAtScore) et conversion d'une équité (eq2mwc), comparées à gnubg de bureau. Export d'un match entier en SGF, relu par gnubg (load match). Co-Authored-By: Claude Opus 5.5 --- app/src/domain/game/engine.ts | 23 ++++++++ app/src/domain/game/sgf.ts | 26 ++++++++- app/src/engine/wasm-engine.ts | 13 +++++ app/tests/game.test.ts | 5 ++ app/tests/tools/sgf-samples.ts | 43 +++++++++++++- engine-cli/main.c | 34 ++++++++++- engine/engine.c | 26 +++++++++ engine/include/engine.h | 26 +++++++++ tests/reference/analyses.json | 56 +++++++++++++++++++ tests/reference/analysis/chances-5-0-0.json | 26 +++++++++ tests/reference/analysis/chances-5-0-2.json | 26 +++++++++ .../analysis/chances-5-2-4-cube-2.json | 26 +++++++++ .../analysis/chances-5-3-4-post-crawford.json | 26 +++++++++ .../analysis/chances-5-4-3-crawford.json | 26 +++++++++ .../analysis/chances-5-4-3-post-crawford.json | 26 +++++++++ ...chances-5-post-crawford-other-on-roll.json | 26 +++++++++ .../analysis/chances-7-1-3-cube-4.json | 26 +++++++++ .../analysis/chances-7-other-on-roll.json | 26 +++++++++ tests/reference/compare.py | 12 ++++ tests/reference/generate.py | 53 +++++++++++++++++- tests/sgf/check.py | 53 +++++++++++++++++- 21 files changed, 596 insertions(+), 8 deletions(-) create mode 100644 tests/reference/analysis/chances-5-0-0.json create mode 100644 tests/reference/analysis/chances-5-0-2.json create mode 100644 tests/reference/analysis/chances-5-2-4-cube-2.json create mode 100644 tests/reference/analysis/chances-5-3-4-post-crawford.json create mode 100644 tests/reference/analysis/chances-5-4-3-crawford.json create mode 100644 tests/reference/analysis/chances-5-4-3-post-crawford.json create mode 100644 tests/reference/analysis/chances-5-post-crawford-other-on-roll.json create mode 100644 tests/reference/analysis/chances-7-1-3-cube-4.json create mode 100644 tests/reference/analysis/chances-7-other-on-roll.json diff --git a/app/src/domain/game/engine.ts b/app/src/domain/game/engine.ts index b667d17..716f84f 100644 --- a/app/src/domain/game/engine.ts +++ b/app/src/domain/game/engine.ts @@ -69,6 +69,12 @@ export interface Engine { points: number, ): Promise; + /** Les chances de gagner le match du joueur au trait (cube.match + * obligatoire), d'après la table d'équité de match du moteur : au + * score, avant la partie, et pour l'équité normalisée equity (une + * évaluation, ou une perte d'équité), avec ce videau et ce score. */ + matchChances(cube: EngineCube, equity: number): Promise; + /** L'analyse du coup joué (played : position après le coup, vue du joueur * qui l'a joué, comme Move.position), au niveau d'analyse ply ; null si * aucun coup n'était possible. */ @@ -129,6 +135,23 @@ export interface MatchDescription { readonly jacoby: boolean; } +/** + * Les chances de gagner le match d'un joueur, selon le moteur (table + * d'équité de match de gnubg, Kazaross-XG2), de 0 à 1. + * + * Glossaire : docs/glossaire/chances-de-gagner-le-match.md + */ +export interface MatchChances { + /** Au score du match, avant la partie (la table elle-même). */ + readonly atScore: number; + /** Pour l'équité demandée (eq2mwc de gnubg). */ + readonly ofEquity: number; + /** L'équité demandée vue comme une perte (ou un gain) : ses chances + * moins celles d'une équité nulle, comme le coût d'une erreur dans + * les statistiques de match de gnubg. */ + readonly ofLoss: number; +} + /** * Niveau de jeu de l'ordinateur : un réglage prédéfini de GNU Backgammon * (aecSettings dans eval.c ; voir engine/include/engine.h). Les quatre diff --git a/app/src/domain/game/sgf.ts b/app/src/domain/game/sgf.ts index 0b2cf71..368ea94 100644 --- a/app/src/domain/game/sgf.ts +++ b/app/src/domain/game/sgf.ts @@ -35,6 +35,9 @@ export interface SgfOptions { readonly computerName: string; /** Date de la partie, AAAA-MM-JJ (DT) ; absente si non fournie. */ readonly date?: string; + /** Dans un match exporté entier, l'indice de la partie (à partir de 0, + * comme MI[game:…] dans gnubg) ; 0 par défaut. */ + readonly gameIndex?: number; } /** Un nœud SGF et les variantes qui le suivent. */ @@ -82,13 +85,14 @@ export async function exportSgf( // sa longueur et le score avant la partie (W, l'ordinateur, est le // joueur 0 de gnubg), et les règles comme gnubg les écrit (sgf.c) : // Crawford, et CrawfordGame pour la partie Crawford. Le numéro de la - // partie dans le match n'est pas gardé : 0. + // partie dans le match : celui que donne l'appelant (exportMatchSgf), + // 0 pour une partie exportée seule. const { result, match } = replay(currentLine(journal)); const root = [ "FF[4]GM[6]CA[UTF-8]AP[Ustagammon]", match === null ? "MI[length:0][game:0][ws:0][bs:0]" - : `MI[length:${match.length}][game:0][ws:${match.score.computer}][bs:${match.score.player}]` + + : `MI[length:${match.length}][game:${options.gameIndex ?? 0}][ws:${match.score.computer}][bs:${match.score.player}]` + `RU[Crawford${match.crawford ? ":CrawfordGame" : ""}]`, `PW[${escapeText(options.computerName)}]PB[${escapeText(options.playerName)}]`, options.date === undefined ? "" : `DT[${escapeText(options.date)}]`, @@ -103,6 +107,24 @@ export async function exportSgf( return `(;${root}${sequence(tree)})\n`; } +/** + * Un match entier au format SGF de GNU Backgammon : ses parties dans + * l'ordre, chacune son arbre (MI porte son numéro et le score avant elle), + * à la suite dans le même fichier, comme gnubg enregistre un match (« save + * match ») et le relit (« load match »). + */ +export async function exportMatchSgf( + engine: Engine, + journals: readonly GameJournal[], + options: Omit, +): Promise { + const games: string[] = []; + for (const [gameIndex, journal] of journals.entries()) { + games.push(await exportSgf(engine, journal, { ...options, gameIndex })); + } + return games.join(""); +} + /** Écrit des nœuds : une suite tant qu'il n'y a qu'une variante, puis * chaque variante entre parenthèses. */ function sequence(nodes: readonly SgfNode[]): string { diff --git a/app/src/engine/wasm-engine.ts b/app/src/engine/wasm-engine.ts index 7712aec..4e15d3d 100644 --- a/app/src/engine/wasm-engine.ts +++ b/app/src/engine/wasm-engine.ts @@ -24,6 +24,7 @@ import type { Level, Luck, LuckRating, + MatchChances, MatchDescription, MatchId, Move, @@ -167,6 +168,18 @@ export function createWasmEngine(run: RunCommand): Engine { }; }, + async matchChances(cube: EngineCube, equity: number): Promise { + if (cube.match === undefined) { + throw new Error("pas de match : pas de chances de gagner le match"); + } + const answer = (await run(["mwc", await matchId(cube), String(equity)])) as { + at_score: number; + mwc: number; + loss: number; + }; + return { atScore: answer.at_score, ofEquity: answer.mwc, ofLoss: answer.loss }; + }, + async analyseMove( position: PositionId, cube: EngineCube, diff --git a/app/tests/game.test.ts b/app/tests/game.test.ts index 901657f..83b31e7 100644 --- a/app/tests/game.test.ts +++ b/app/tests/game.test.ts @@ -72,6 +72,11 @@ function fakeEngine(overrides: Partial = {}): Engine { crawford: score[winner] === match.length - 1, }; }, + matchChances: async (_cube, equity) => ({ + atScore: 0.5, + ofEquity: 0.5 + equity / 4, + ofLoss: equity / 4, + }), analyseMove: async () => null, analyseCube: async () => ({ analysed: false, diff --git a/app/tests/tools/sgf-samples.ts b/app/tests/tools/sgf-samples.ts index 065949e..c3ae8b8 100644 --- a/app/tests/tools/sgf-samples.ts +++ b/app/tests/tools/sgf-samples.ts @@ -15,8 +15,9 @@ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { Game } from "../../src/domain/game/game.js"; -import { exportSgf } from "../../src/domain/game/sgf.js"; +import { Game, type NewGame } from "../../src/domain/game/game.js"; +import { firstGameOf } from "../../src/domain/game/match.js"; +import { exportMatchSgf, exportSgf } from "../../src/domain/game/sgf.js"; import { loadNodeEngine } from "../support/node-engine.js"; import { playMoves, playToTheEnd, seededDice, step } from "../support/play.js"; @@ -133,6 +134,44 @@ async function main(): Promise { } game.goBackTo(original.head as string); } + // Un match entier en 3 points (étape 1l), exporté d'un seul fichier : + // chaque partie à la suite, avec son numéro et le score avant elle. La + // première graine dont le match compte au moins trois parties. + for (let seed = 21; ; seed++) { + const dice = seededDice(seed); + const played: Game[] = []; + let next: Game | null = Game.start(engine, { + dice, + level: "0ply", + match: firstGameOf(3, "exemple"), + }); + while (next !== null) { + await playToTheEnd(next, engine); + played.push(next); + const following: NewGame | null = next.nextGame; + next = following === null ? null : Game.start(engine, { ...following, dice }); + } + if (played.length < 3) { + continue; + } + const sgf = await exportMatchSgf( + engine, + played.map((g) => g.journal), + { playerName: "Vous", computerName: "Ordinateur", date: "2026-11-12" }, + ); + const expected = { + length: 3, + games: played.map((g) => ({ + after: g.events.flatMap((e) => (e.type === "MovePlayed" ? [e.position] : [])), + result: g.state.result, + score: g.state.match?.score, + })), + }; + writeFileSync(join(out, `match-${seed}.sgf`), sgf); + writeFileSync(join(out, `match-${seed}.json`), `${JSON.stringify(expected)}\n`); + files++; + break; + } console.log(`${files} parties exportées dans ${out}`); } diff --git a/engine-cli/main.c b/engine-cli/main.c index 421133e..4ff01dc 100644 --- a/engine-cli/main.c +++ b/engine-cli/main.c @@ -50,6 +50,11 @@ * no_double ou double (joueur au trait), * take ou pass (son adversaire) * luck POSITION_ID MATCH_ID DÉS chance du jet pour le joueur au trait + * mwc MATCH_ID [ÉQUITÉ] chances de gagner le match du joueur + * au trait : au score, avant la + * partie, et pour une équité + * normalisée (0 par défaut), en + * chances et en perte * * --ply : niveau de gnubg, de 0 (défaut) à 4 (meilleur coup comme « hint », * analyses comme l'analyse de partie de gnubg). @@ -83,7 +88,7 @@ /* Liste des commandes, pour les messages d'erreur. */ #define COMMANDS "bestmove, moves, legal, cube, eval, position, halfmoves, matchid, reference, " \ - "levels, analysemove, analysecube, luck, double, take ou aftergame" + "levels, analysemove, analysecube, luck, double, take, aftergame ou mwc" /* Coups gardés dans le classement de la commande reference (comme hint). */ #define REFERENCE_MAX_MOVES 10 @@ -597,6 +602,31 @@ run_after_game_command(const options *opt) return EXIT_SUCCESS; } +/* mwc : chances de gagner le match (voir engine_match_chances_of). */ +static int +run_mwc_command(const options *opt) +{ + engine_match_chances chances; + engine_status status; + float equity = 0.0f; + char *end; + + if (opt->arg_count != 1 && opt->arg_count != 2) + return usage_error("arguments attendus : MATCH_ID [ÉQUITÉ]"); + if (opt->arg_count == 2) { + equity = strtof(opt->args[1], &end); + if (end == opt->args[1] || *end != '\0') + return usage_error("ÉQUITÉ attend un nombre"); + } + status = engine_match_chances_of(opt->args[0], equity, &chances); + if (status != ENGINE_OK) + return print_engine_error(status); + printf("{\"match_id\": \"%s\", \"equity\": " NUMBER ", \"at_score\": " NUMBER + ", \"mwc\": " NUMBER ", \"loss\": " NUMBER "}\n", opt->args[0], equity, + chances.at_score, chances.mwc, chances.loss); + return EXIT_SUCCESS; +} + /* * reference :un niveau d'un fichier de résultat de tests/reference/, de * même structure que plies[""] (voir tests/reference/README.md). @@ -886,6 +916,8 @@ main(int argc, char **argv) result = run_analyse_cube_command(&opt); else if (strcmp(opt.command, "luck") == 0) result = run_luck_command(&opt); + else if (strcmp(opt.command, "mwc") == 0) + result = run_mwc_command(&opt); else result = usage_error("commande inconnue : " COMMANDS); diff --git a/engine/engine.c b/engine/engine.c index b40be99..ec0d743 100644 --- a/engine/engine.c +++ b/engine/engine.c @@ -838,6 +838,32 @@ engine_match_after_game(const char *match_id, int winner, int points, return ENGINE_OK; } +/* --------------------------------------- Chances de gagner le match */ + +engine_status +engine_match_chances_of(const char *match_id, float equity, engine_match_chances *chances) +{ + engine_match m; + cubeinfo cube; + engine_status status; + + if (engine_state != READY) + return ENGINE_ERROR_NOT_INITIALISED; + status = engine_decode_match(match_id, &m); + if (status != ENGINE_OK) + return status; + if (m.match_length == 0 + || SetCubeInfo(&cube, m.cube_value, m.cube_owner, m.player_on_roll, m.match_length, + m.score, m.crawford, m.jacoby, DEFAULT_BEAVERS, VARIATION_STANDARD) != 0) + return ENGINE_ERROR_MATCH_ID; + chances->at_score = getMEAtScore(m.score[0], m.score[1], m.match_length, m.player_on_roll, + m.crawford, aafMET, aafMETPostCrawford); + chances->mwc = eq2mwc(equity, &cube); + /* analysis.c, updateStatcontext : « eq2mwc(rSkill, &ci) - eq2mwc(0.0f, &ci) ». */ + chances->loss = eq2mwc(equity, &cube) - eq2mwc(0.0f, &cube); + return ENGINE_OK; +} + /* -------------------------------------------- Analyse d'une décision de videau */ /* Le plus petit de deux nombres. */ diff --git a/engine/include/engine.h b/engine/include/engine.h index 66197ad..edef11d 100644 --- a/engine/include/engine.h +++ b/engine/include/engine.h @@ -452,6 +452,32 @@ typedef struct { engine_status engine_match_after_game(const char *match_id, int winner, int points, engine_match_after *after); +/* Chances de gagner le match, d'après la table d'équité de match de gnubg + * (Kazaross-XG2, celle de gnubg de bureau par défaut). */ +typedef struct { + float at_score; /* chances du joueur au trait de gagner le match + * au score du Match ID, avant la partie + * (getMEAtScore de gnubg, matchequity.c, + * partie Crawford et suivantes comprises) */ + float mwc; /* l'équité normalisée donnée, pour ce videau et + * ce score, convertie en chances de gagner le + * match du joueur au trait (eq2mwc) */ + float loss; /* la même équité vue comme une perte : eq2mwc + * de l'équité moins eq2mwc de 0, comme le coût + * d'une erreur dans les statistiques de match de + * gnubg (updateStatcontext, analysis.c) */ +} engine_match_chances; + +/* + * Chances de gagner le match : au score du Match ID (avant la partie), et + * pour une équité normalisée (videau, score, joueur au trait et partie + * Crawford du Match ID ; les dés et le propriétaire du videau sont + * ignorés). ENGINE_ERROR_MATCH_ID en partie libre (longueur 0) : il n'y a + * pas de match. + */ +engine_status engine_match_chances_of(const char *match_id, float equity, + engine_match_chances *chances); + /* ------------------------------------------------------------- Analyse */ /* Appréciation de gnubg pour une perte d'équité (0 ou négative). */ diff --git a/tests/reference/analyses.json b/tests/reference/analyses.json index 1eeb7fb..d131b4e 100644 --- a/tests/reference/analyses.json +++ b/tests/reference/analyses.json @@ -279,5 +279,61 @@ "match_id": "cAkAAAAAAAAA", "dice": null } + ], + "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] + } ] } diff --git a/tests/reference/analysis/chances-5-0-0.json b/tests/reference/analysis/chances-5-0-0.json new file mode 100644 index 0000000..7ebabd4 --- /dev/null +++ b/tests/reference/analysis/chances-5-0-0.json @@ -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 +} diff --git a/tests/reference/analysis/chances-5-0-2.json b/tests/reference/analysis/chances-5-0-2.json new file mode 100644 index 0000000..1fbd0fc --- /dev/null +++ b/tests/reference/analysis/chances-5-0-2.json @@ -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 +} diff --git a/tests/reference/analysis/chances-5-2-4-cube-2.json b/tests/reference/analysis/chances-5-2-4-cube-2.json new file mode 100644 index 0000000..2f28d7f --- /dev/null +++ b/tests/reference/analysis/chances-5-2-4-cube-2.json @@ -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 +} diff --git a/tests/reference/analysis/chances-5-3-4-post-crawford.json b/tests/reference/analysis/chances-5-3-4-post-crawford.json new file mode 100644 index 0000000..1db6bdf --- /dev/null +++ b/tests/reference/analysis/chances-5-3-4-post-crawford.json @@ -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 +} diff --git a/tests/reference/analysis/chances-5-4-3-crawford.json b/tests/reference/analysis/chances-5-4-3-crawford.json new file mode 100644 index 0000000..4544390 --- /dev/null +++ b/tests/reference/analysis/chances-5-4-3-crawford.json @@ -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 +} diff --git a/tests/reference/analysis/chances-5-4-3-post-crawford.json b/tests/reference/analysis/chances-5-4-3-post-crawford.json new file mode 100644 index 0000000..ed076a6 --- /dev/null +++ b/tests/reference/analysis/chances-5-4-3-post-crawford.json @@ -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 +} diff --git a/tests/reference/analysis/chances-5-post-crawford-other-on-roll.json b/tests/reference/analysis/chances-5-post-crawford-other-on-roll.json new file mode 100644 index 0000000..0c7f926 --- /dev/null +++ b/tests/reference/analysis/chances-5-post-crawford-other-on-roll.json @@ -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 +} diff --git a/tests/reference/analysis/chances-7-1-3-cube-4.json b/tests/reference/analysis/chances-7-1-3-cube-4.json new file mode 100644 index 0000000..a4216ef --- /dev/null +++ b/tests/reference/analysis/chances-7-1-3-cube-4.json @@ -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 +} diff --git a/tests/reference/analysis/chances-7-other-on-roll.json b/tests/reference/analysis/chances-7-other-on-roll.json new file mode 100644 index 0000000..cbbaf1d --- /dev/null +++ b/tests/reference/analysis/chances-7-other-on-roll.json @@ -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 +} diff --git a/tests/reference/compare.py b/tests/reference/compare.py index 8bdd272..318372e 100644 --- a/tests/reference/compare.py +++ b/tests/reference/compare.py @@ -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) @@ -280,6 +290,8 @@ def compare_analyses(report, cli, folder): compare_move_analysis(report, cli, case) elif case["type"] == "cube": compare_cube_analysis(report, cli, case) + elif case["type"] == "chance": + compare_chances(report, cli, case) else: compare_levels(report, cli, case, settings) return len(paths) diff --git a/tests/reference/generate.py b/tests/reference/generate.py index 2a6b9b6..14ba0a8 100644 --- a/tests/reference/generate.py +++ b/tests/reference/generate.py @@ -391,6 +391,53 @@ def level_cube(case, name): } +# -------------------------------------------------------------------------- +# 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(" 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 From 68664dc3f733dcb6dab66e7b723212a2e1c82804 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Fri, 13 Nov 2026 00:05:46 +0100 Subject: [PATCH 2/6] =?UTF-8?q?Domaine=20:=20identifiant=20de=20match=20(?= =?UTF-8?q?=C3=A9v=C3=A9nements=20v3),=20bilan=20du=20match,=20phrases=20e?= =?UTF-8?q?t=20prompt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Les parties d'un match partagent un identifiant ; les parties d'avant sont rattachées d'après les scores et les dates quand c'est sûr. L'analyse de partie range les chances de gagner le match et les pertes de chaque décision, converties par le moteur. Bilan du match (agrégation, videau, moment décisif, courbe continue), phrases du maître, gabarit « Bilan de mon match », scénario de la remontée de 0–4 à 5–4. Co-Authored-By: Claude Opus 5.5 --- app/src/domain/analysis/game-analysis.ts | 181 +++++- app/src/domain/analysis/match-analysis.ts | 518 ++++++++++++++++++ app/src/domain/analysis/phrases.ts | 70 +++ app/src/domain/game/events.ts | 40 +- app/src/domain/game/match.ts | 31 +- app/src/domain/game/review.ts | 12 + app/src/domain/game/saved-game.ts | 4 + app/src/domain/prompts/prompts.ts | 201 ++++++- app/src/domain/prompts/templates.ts | 7 +- app/src/storage/game-session.ts | 11 +- app/src/ui/help.ts | 1 + app/src/ui/match-summary-texts.ts | 167 ++++++ app/src/ui/prompt-source.ts | 3 +- app/tests/game.test.ts | 4 +- app/tests/match-analysis.test.ts | 401 ++++++++++++++ app/tests/progression.test.ts | 9 +- app/tests/prompts.test.ts | 5 +- app/tests/steps/analyser-mon-match.steps.ts | 237 ++++++++ app/tests/steps/demander-a-une-ia.steps.ts | 1 + .../steps/suivre-ma-progression.steps.ts | 12 +- app/tests/support/match.ts | 98 ++++ app/tests/tools/prompt-sample.ts | 1 + docs/maitre/phrases.md | 69 ++- docs/prompts/README.md | 1 + docs/prompts/match.md | 58 ++ docs/scenarios/README.md | 1 + docs/scenarios/analyser-mon-match.feature | 63 +++ tests/reference/README.md | 23 +- tests/test_reference.sh | 7 +- 29 files changed, 2185 insertions(+), 51 deletions(-) create mode 100644 app/src/domain/analysis/match-analysis.ts create mode 100644 app/src/ui/match-summary-texts.ts create mode 100644 app/tests/match-analysis.test.ts create mode 100644 app/tests/steps/analyser-mon-match.steps.ts create mode 100644 app/tests/support/match.ts create mode 100644 docs/prompts/match.md create mode 100644 docs/scenarios/analyser-mon-match.feature diff --git a/app/src/domain/analysis/game-analysis.ts b/app/src/domain/analysis/game-analysis.ts index 3296204..244241c 100644 --- a/app/src/domain/analysis/game-analysis.ts +++ b/app/src/domain/analysis/game-analysis.ts @@ -28,6 +28,7 @@ import { type Verdict, verdictOf, } from "../game/advice.js"; +import { CENTERED_CUBE } from "../game/cube.js"; import type { Engine, LuckRating } from "../game/engine.js"; import { LUCK_THRESHOLDS } from "../game/engine.js"; import { @@ -43,7 +44,7 @@ import { engineCube } from "../game/game.js"; import { COMPUTER_LEVELS, type ComputerLevel } from "../game/level.js"; import { emptyReview, type GameReview } from "../game/review.js"; import type { Roll } from "../game/roll.js"; -import type { Side } from "../game/side.js"; +import { otherSide, type Side } from "../game/side.js"; import { applyEvent, replay } from "../game/state.js"; import { ANALYSIS_PLY, analyseDecision, decisionsOf } from "./analyse.js"; @@ -132,8 +133,16 @@ export type AnalysisTask = | { readonly kind: "decision"; readonly side: Side; readonly eventId: string } /** La chance d'un jet. */ | { readonly kind: "luck"; readonly eventId: string } - /** Les chances de gagner du joueur après un coup. */ - | { readonly kind: "chance"; readonly eventId: string }; + /** Les chances de gagner du joueur après un coup (et, dans un match, + * ses chances de gagner le match). */ + | { readonly kind: "chance"; readonly eventId: string } + /** Dans un match : les chances du joueur de gagner le match au début + * de la partie (GameStarted), après un coup (MovePlayed) ou après la + * partie (GameEnded). */ + | { readonly kind: "matchChance"; readonly eventId: string } + /** Dans un match : les chances de gagner le match qu'une décision du + * joueur lui a coûtées. */ + | { readonly kind: "matchLoss"; readonly eventId: string }; /** L'analyse de partie du journal, au niveau d'analyse ; vide s'il n'y en * a pas encore (ou à un autre niveau). */ @@ -165,24 +174,68 @@ export function missingAnalyses(journal: GameJournal): AnalysisTask[] { tasks.push({ kind: "luck", eventId: event.id }); } } + // Dans un match (étape 1l) : ce qu'il faut au bilan du match, les + // pertes en chances de gagner le match, puis les deux bouts de la + // courbe du match (sans évaluation : la table au score). + const inMatch = line[0]?.type === "GameStarted" && line[0].match !== undefined; + const matchChances = review.matchChances ?? {}; + if (inMatch) { + const losses = review.matchLosses ?? {}; + for (const event of decisionsOf(line, "player")) { + if (advice[event.id] !== undefined && losses[event.id] === undefined) { + tasks.push({ kind: "matchLoss", eventId: event.id }); + } + } + for (const event of line) { + if ( + (event.type === "GameStarted" || event.type === "GameEnded") && + matchChances[event.id] === undefined + ) { + tasks.push({ kind: "matchChance", eventId: event.id }); + } + } + } for (const event of decisionsOf(line, "computer")) { if (review.computer[event.id] === undefined && !skipped.has(event.id)) { tasks.push({ kind: "decision", side: "computer", eventId: event.id }); } } for (const event of line) { - if (event.type === "MovePlayed" && review.winChances[event.id] === undefined) { + if (event.type !== "MovePlayed") { + continue; + } + if (review.winChances[event.id] === undefined) { + // Dans un match, la même évaluation donne aussi les chances de + // gagner le match. tasks.push({ kind: "chance", eventId: event.id }); + } else if (inMatch && matchChances[event.id] === undefined) { + // Une partie analysée avant l'étape 1l. + tasks.push({ kind: "matchChance", eventId: event.id }); } } return tasks; } +/** Ce qu'il faut au bilan du match pour cette partie : le bilan de la + * partie, et les pertes en chances de gagner le match de ses décisions. */ +export function readyForMatchSummary(journal: GameJournal): boolean { + return missingAnalyses(journal).every( + (task) => + task.kind === "chance" || + task.kind === "matchChance" || + (task.kind === "decision" && task.side === "computer"), + ); +} + /** Ce qu'il faut au bilan : toutes les décisions du joueur et la chance * de tous les jets. */ export function readyForSummary(journal: GameJournal): boolean { return missingAnalyses(journal).every( - (task) => task.kind === "chance" || (task.kind === "decision" && task.side === "computer"), + (task) => + task.kind === "chance" || + task.kind === "matchChance" || + task.kind === "matchLoss" || + (task.kind === "decision" && task.side === "computer"), ); } @@ -252,31 +305,123 @@ export async function runAnalysis( const chance = await chanceAfter(engine, journal, task.eventId); return withReview(journal, { ...review, - winChances: { ...review.winChances, [task.eventId]: chance }, + winChances: { ...review.winChances, [task.eventId]: chance.game }, + ...(chance.match === null + ? {} + : { + matchChances: { + ...review.matchChances, + [task.eventId]: chance.match, + }, + }), + }); + } + case "matchChance": { + const chance = await matchChanceAt(engine, journal, task.eventId); + return withReview(journal, { + ...review, + matchChances: { ...review.matchChances, [task.eventId]: chance }, + }); + } + case "matchLoss": { + const loss = await matchLossOf(engine, journal, task.eventId); + return withReview(journal, { + ...review, + matchLosses: { ...review.matchLosses, [task.eventId]: loss }, }); } } } +/** Les chances du joueur de gagner le match au début de la partie, ou + * après elle (GameEnded) : la table d'équité de match du moteur au score + * (1 ou 0 si le match est fini). Après un coup : voir chanceAfter. */ +async function matchChanceAt( + engine: Engine, + journal: GameJournal, + eventId: string, +): Promise { + const line = currentLine({ ...journal, head: eventId }); + const event = line.at(-1); + const state = replay(line); + const match = state.match; + if (match === null || event === undefined) { + throw new Error(`pas une partie de match : ${eventId}`); + } + if (event.type === "GameStarted") { + return (await engine.matchChances(engineCube(state, "player"), 0)).atScore; + } + if (event.type === "GameEnded") { + const after = event.match; + if (after === undefined) { + throw new Error(`fin de partie sans match : ${eventId}`); + } + if (after.over) { + return event.winner === "player" ? 1 : 0; + } + const next = { cube: CENTERED_CUBE, match: { ...match, ...after } }; + return (await engine.matchChances(engineCube(next, "player"), 0)).atScore; + } + if (event.type === "MovePlayed") { + const chance = await chanceAfter(engine, journal, eventId); + if (chance.match === null) { + throw new Error(`pas une partie de match : ${eventId}`); + } + return chance.match; + } + throw new Error(`ni début, ni coup, ni fin de partie : ${eventId}`); +} + +/** Les chances de gagner le match qu'une décision du joueur lui a + * coûtées : l'équité perdue de son conseil, convertie par le moteur avec + * le videau et le score de la décision, vus de celui qui décide comme dans + * gnubg (pour une prise ou un refus, celui qui a doublé). */ +async function matchLossOf(engine: Engine, journal: GameJournal, eventId: string): Promise { + const advice = journal.advice?.[eventId]; + if (advice === undefined) { + throw new Error(`décision sans conseil : ${eventId}`); + } + const line = currentLine({ ...journal, head: eventId }); + const before = replay(line.slice(0, -1)); + const decider = + advice.kind === "cube" && (advice.action === "take" || advice.action === "pass") + ? otherSide("player") + : "player"; + return (await engine.matchChances(engineCube(before, decider), advice.equityLoss)).ofLoss; +} + /** Les chances de gagner du joueur après le coup moveId : le résultat si * la partie finit là, sinon l'évaluation du moteur, vue de celui qui a * alors la main. */ -async function chanceAfter(engine: Engine, journal: GameJournal, moveId: string): Promise { +async function chanceAfter( + engine: Engine, + journal: GameJournal, + moveId: string, +): Promise<{ readonly game: number; readonly match: number | null }> { const line = currentLine(journal); const index = line.findIndex((e) => e.id === moveId); const upTo = index >= 0 ? line.slice(0, index + 1) : currentLine({ ...journal, head: moveId }); const next = index >= 0 ? line[index + 1] : undefined; - if (next?.type === "GameEnded") { - return next.winner === "player" ? 1 : 0; - } const after = replay(upTo); + if (next?.type === "GameEnded") { + // La partie finit sur ce coup : la courbe du match y prend la + // valeur de la fin de partie. + return { + game: next.winner === "player" ? 1 : 0, + match: after.match === null ? null : await matchChanceAt(engine, journal, next.id), + }; + } const onRoll = after.turn ?? "player"; - const evaluation = await engine.evaluate( - after.position, - engineCube(after, onRoll), - ANALYSIS_PLY, - ); - return onRoll === "player" ? evaluation.win : 1 - evaluation.win; + const cube = engineCube(after, onRoll); + const evaluation = await engine.evaluate(after.position, cube, ANALYSIS_PLY); + const mine = (chance: number) => (onRoll === "player" ? chance : 1 - chance); + if (after.match === null) { + return { game: mine(evaluation.win), match: null }; + } + // L'équité avec videau, normalisée, convertie par le moteur en chances + // de gagner le match du joueur au trait. + const match = await engine.matchChances(cube, evaluation.equity); + return { game: mine(evaluation.win), match: mine(match.ofEquity) }; } // ------------------------------------------------ Les chiffres du bilan @@ -405,7 +550,9 @@ function errorOf(advice: Advice): { error: number; counted: boolean } { return { error, counted: advice.action !== "noDouble" || closeCube(advice) }; } -function errorRateOf(advices: readonly Advice[]): ErrorRate { +/** Le taux d'erreur d'une suite de décisions (updateStatcontext et + * getMWCFromError de gnubg). */ +export function errorRateOf(advices: readonly Advice[]): ErrorRate { let total = 0; let decisions = 0; for (const advice of advices) { diff --git a/app/src/domain/analysis/match-analysis.ts b/app/src/domain/analysis/match-analysis.ts new file mode 100644 index 0000000..6437327 --- /dev/null +++ b/app/src/domain/analysis/match-analysis.ts @@ -0,0 +1,518 @@ +// L'analyse d'un match entier (étape 1l ; charte, ecrans-etape-1.md, +// « Bilan du match ») : les parties d'un même match retrouvées, et le bilan +// du match à partir des analyses déjà rangées dans le journal de chaque +// partie (1e). Fonctions pures, testées sous Node +// (app/tests/match-analysis.test.ts). +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). +// +// Rien n'est recalculé ici, et aucune table d'équité de match n'est lue : +// les chances de gagner le match (après chaque coup, au début et à la fin +// de chaque partie) et les pertes en chances de gagner le match viennent +// du moteur, rangées par l'analyse de chaque partie (review.matchChances, +// review.matchLosses). Le taux d'erreur et la chance s'additionnent sur +// tout le match, comme les statistiques de match de gnubg (analysis.c, +// updateStatcontext, cumulées partie après partie par AddStatcontext). + +import { type Advice, type Verdict, verdictOf } from "../game/advice.js"; +import type { Level } from "../game/engine.js"; +import { currentLine, type GameJournal } from "../game/events.js"; +import type { Match } from "../game/match.js"; +import type { Roll } from "../game/roll.js"; +import type { Side } from "../game/side.js"; +import { type GameResult, type GameState, replay } from "../game/state.js"; +import { decisionsOf } from "./analyse.js"; +import { + type ErrorRate, + errorRateOf, + gameTurns, + type LuckSummary, + luckRatingOf, + readyForMatchSummary, + reviewOf, + summarizeAnalysis, +} from "./game-analysis.js"; + +// ------------------------------------------- Les parties d'un match + +/** Une partie de match enregistrée, telle que le stockage la donne. */ +export interface MatchGame { + readonly id: string; + /** Début de la partie et dernière action, en millisecondes depuis 1970. */ + readonly startedAt: number; + readonly updatedAt: number; + readonly journal: GameJournal; +} + +/** + * Un match joué : ses parties dans l'ordre, et où il en est. + * + * Glossaire : docs/glossaire/match.md + */ +export interface PlayedMatch { + /** L'identifiant du match (version 3 des événements) ; pour un match + * d'avant, celui de sa première partie. */ + readonly id: string; + /** Les parties ont été rattachées d'après leurs scores et leurs dates + * (parties enregistrées avant l'identifiant de match). */ + readonly inferred: boolean; + readonly length: number; + readonly level: Level; + readonly games: readonly MatchGame[]; + readonly startedAt: number; + readonly updatedAt: number; + /** Le score : après la dernière partie si elle est finie, avant elle + * sinon. */ + readonly score: Readonly>; + readonly over: boolean; + /** Le vainqueur du match (null tant qu'il n'est pas fini). */ + readonly winner: Side | null; + /** La dernière partie est finie, le match continue : la partie + * suivante n'est pas encore commencée. */ + readonly waiting: boolean; +} + +/** Délai au plus entre la dernière action d'une partie et le début de la + * suivante, pour rattacher une partie d'avant l'identifiant de match à la + * précédente. Au-delà, on ne devine pas. */ +export const LINK_DELAY_MS = 12 * 60 * 60 * 1000; + +interface Facts { + readonly game: MatchGame; + readonly state: GameState; + readonly match: Match; +} + +/** + * Les matchs que forment des parties enregistrées. Les parties qui portent + * un identifiant de match (version 3 des événements) sont réunies par lui. + * Les autres, enregistrées avant, sont rattachées de proche en proche à + * partir d'une première partie à 0 à 0 : la suivante a la même longueur et + * le même niveau, commence au score où la précédente a fini (Crawford + * compris), après elle et moins de LINK_DELAY_MS après sa dernière action. + * Dès qu'il y a deux candidates, ou qu'une candidate pourrait suivre deux + * parties, la chaîne s'arrête : les parties qui restent ne sont rattachées + * à aucun match (loose) plutôt que mal rattachées. Les parties libres sont + * ignorées. + */ +export function groupMatches(games: readonly MatchGame[]): { + readonly matches: PlayedMatch[]; + readonly loose: MatchGame[]; +} { + const facts: Facts[] = []; + for (const game of games) { + const state = replay(currentLine(game.journal)); + if (state.match !== null) { + facts.push({ game, state, match: state.match }); + } + } + const byStart = (a: Facts, b: Facts) => a.game.startedAt - b.game.startedAt; + const identified = new Map(); + const legacy: Facts[] = []; + for (const f of facts) { + const id = f.match.id; + if (id === undefined) { + legacy.push(f); + } else { + identified.set(id, [...(identified.get(id) ?? []), f]); + } + } + const matches = [...identified].map(([id, list]) => playedMatch(id, list.sort(byStart), false)); + + legacy.sort(byStart); + const used = new Set(); + for (const first of legacy) { + if (used.has(first.game.id) || first.match.score.player + first.match.score.computer > 0) { + continue; + } + const chain = [first]; + used.add(first.game.id); + for (;;) { + const last = chain.at(-1) as Facts; + const next = legacy.filter((f) => !used.has(f.game.id) && follows(last, f)); + const candidate = next[0]; + if ( + next.length !== 1 || + candidate === undefined || + legacy.some((f) => f !== last && follows(f, candidate)) + ) { + break; + } + chain.push(candidate); + used.add(candidate.game.id); + } + matches.push(playedMatch(first.game.id, chain, chain.length > 1)); + } + return { + matches, + loose: legacy.filter((f) => !used.has(f.game.id)).map((f) => f.game), + }; +} + +/** next peut-elle être la partie qui suit previous dans le même match ? */ +function follows(previous: Facts, next: Facts): boolean { + const after = previous.state.matchAfter; + return ( + previous.state.phase === "over" && + after !== null && + !after.over && + next.match.length === previous.match.length && + next.state.level === previous.state.level && + next.match.score.player === after.score.player && + next.match.score.computer === after.score.computer && + next.match.crawford === after.crawford && + next.game.startedAt >= previous.game.startedAt && + next.game.startedAt - previous.game.updatedAt <= LINK_DELAY_MS + ); +} + +function playedMatch(id: string, list: readonly Facts[], inferred: boolean): PlayedMatch { + const first = list[0] as Facts; + const last = list.at(-1) as Facts; + const after = last.state.phase === "over" ? last.state.matchAfter : null; + const over = after?.over ?? false; + return { + id, + inferred, + length: first.match.length, + level: first.state.level, + games: list.map((f) => f.game), + startedAt: first.game.startedAt, + updatedAt: Math.max(...list.map((f) => f.game.updatedAt)), + score: after?.score ?? last.match.score, + over, + winner: over ? (last.state.result?.winner ?? null) : null, + waiting: after !== null && !after.over, + }; +} + +/** Le match dont fait partie la partie gameId (null : aucun). */ +export function matchOfGame( + matches: readonly PlayedMatch[], + gameId: string, +): { readonly match: PlayedMatch; readonly number: number } | null { + for (const match of matches) { + const index = match.games.findIndex((g) => g.id === gameId); + if (index >= 0) { + return { match, number: index + 1 }; + } + } + return null; +} + +// ----------------------------------------------------- Le bilan + +/** Les sortes d'erreurs de videau, dans l'ordre du bilan du match (charte) : + * doubler à tort, ne pas doubler à tort, prendre à tort, passer à tort ; + * les mêmes que les statistiques de gnubg (anCubeWrongDouble…). */ +export type CubeErrorKind = "wrongDouble" | "missedDouble" | "wrongTake" | "wrongPass"; + +export const CUBE_ERROR_KINDS: readonly CubeErrorKind[] = [ + "wrongDouble", + "missedDouble", + "wrongTake", + "wrongPass", +]; + +/** Une décision du joueur dans le match. */ +export interface MatchDecision { + /** Le numéro de la partie dans le match, à partir de 1. */ + readonly game: number; + readonly gameId: string; + /** Le tour de la partie (le « coup » de l'écran d'analyse). */ + readonly turn: number; + /** Le score au début de la partie, celui de la décision. */ + readonly score: Readonly>; + readonly advice: Advice; + /** Les chances de gagner le match qu'elle a coûtées (0 ou négatif), + * selon le moteur ; null tant qu'elles ne sont pas calculées. */ + readonly loss: number | null; +} + +/** Une décision de videau du joueur qui diffère de celle du moteur. */ +export interface CubeError extends MatchDecision { + readonly kind: CubeErrorKind; +} + +/** Une partie du match, pour « Partie par partie ». */ +export interface MatchGameRow { + readonly number: number; + readonly id: string; + readonly scoreBefore: Readonly>; + /** Le score après la partie (null : pas finie). */ + readonly scoreAfter: Readonly> | null; + readonly crawford: boolean; + readonly result: GameResult | null; + /** La valeur du videau à la fin de la partie. */ + readonly cube: number; +} + +/** + * Un point de la courbe des chances de gagner le match : le début du + * match, puis chaque tour de chaque partie. La fin d'une partie est le + * début de la suivante : la courbe est continue d'une partie à l'autre. + * + * Glossaire : docs/glossaire/chances-de-gagner-le-match.md + */ +export interface MatchCurvePoint { + readonly game: number; + readonly gameId: string; + /** Le tour (null : le début du match, avant le premier jet). */ + readonly turn: number | null; + /** Le camp qui avait la main (null au début du match). */ + readonly side: Side | null; + readonly roll: Roll | null; + /** Les chances du joueur de gagner le match après ce tour, de 0 à 1 + * (null : pas encore analysé). */ + readonly chance: number | null; + /** L'appréciation de la décision du joueur la plus coûteuse du tour. */ + readonly verdict: Verdict | null; + /** Le tour finit la partie. */ + readonly ends: boolean; +} + +/** Le moment décisif : le tour qui a fait le plus varier les chances de + * gagner le match. Ce peut être un coup de dés : aucun jugement. */ +export interface DecisiveMoment { + readonly game: number; + readonly gameId: string; + readonly turn: number; + readonly side: Side; + /** Le jet du tour (null : un tour fini sur un double passé). */ + readonly roll: Roll | null; + readonly from: number; + readonly to: number; +} + +/** Le bilan d'un match. */ +export interface MatchSummary { + readonly match: PlayedMatch; + readonly rows: readonly MatchGameRow[]; + /** Toutes les parties ont l'analyse qu'il faut au bilan + * (readyForMatchSummary) ; sinon, les chiffres sont partiels. */ + readonly ready: boolean; + /** Le taux d'erreur sur tout le match, sur les pions, sur le videau. */ + readonly errorRate: ErrorRate; + readonly chequer: ErrorRate; + readonly cube: ErrorRate; + /** La chance de vos dés sur tout le match. */ + readonly luck: LuckSummary; + /** Vos décisions de videau comptées (comme le taux d'erreur du + * videau), et celles qui diffèrent du moteur, dans l'ordre du bilan. */ + readonly cubeDecisions: number; + readonly cubeErrors: readonly CubeError[]; + readonly decisive: DecisiveMoment | null; + /** La décision à revoir : la plus grande perte de chances de gagner le + * match, pions ou videau, parmi les imprécisions et les erreurs. */ + readonly toReview: MatchDecision | null; + readonly curve: readonly MatchCurvePoint[]; + /** Le plus grand retard remonté par le vainqueur du match : le score + * au début de la partie où il était le plus mené (null : jamais + * mené, ou match pas fini). */ + readonly comeback: Readonly> | null; +} + +const CUBE_KIND: Readonly> = { + double: "wrongDouble", + noDouble: "missedDouble", + take: "wrongTake", + pass: "wrongPass", +}; + +/** Le bilan d'un match, avec les analyses déjà rangées. */ +export function summarizeMatch(match: PlayedMatch): MatchSummary { + const rows: MatchGameRow[] = []; + const decisions: MatchDecision[] = []; + const curve: MatchCurvePoint[] = []; + let luckTotal = 0; + let rolls = 0; + let ready = true; + + match.games.forEach((game, index) => { + const number = index + 1; + const journal = game.journal; + const line = currentLine(journal); + const state = replay(line); + const before = state.match?.score ?? { player: 0, computer: 0 }; + rows.push({ + number, + id: game.id, + scoreBefore: before, + scoreAfter: state.phase === "over" ? (state.matchAfter?.score ?? null) : null, + crawford: state.match?.crawford ?? false, + result: state.result, + cube: state.cube.value, + }); + ready &&= readyForMatchSummary(journal); + const summary = summarizeAnalysis(journal); + luckTotal += summary.player.luck.total; + rolls += summary.player.luck.rolls; + + const review = reviewOf(journal); + const losses = review.matchLosses ?? {}; + const chances = review.matchChances ?? {}; + const advice = journal.advice ?? {}; + const turns = gameTurns(journal); + for (const turn of turns) { + for (const event of decisionsOf(turn.events, "player")) { + const a = advice[event.id]; + if (a !== undefined) { + decisions.push({ + game: number, + gameId: game.id, + turn: turn.number, + score: before, + advice: a, + loss: losses[event.id] ?? null, + }); + } + } + } + + const start = line[0]; + if (index === 0 && start !== undefined) { + curve.push({ + game: number, + gameId: game.id, + turn: null, + side: null, + roll: null, + chance: chances[start.id] ?? null, + verdict: null, + ends: false, + }); + } + const mainVerdict = (events: readonly { readonly id: string }[]): Verdict | null => { + let worst: Advice | null = null; + for (const event of events) { + const a = advice[event.id]; + if (a !== undefined && (worst === null || a.equityLoss < worst.equityLoss)) { + worst = a; + } + } + return worst === null ? null : verdictOf(worst.skill); + }; + for (const turn of turns) { + let chance: number | null = turn.move === null ? null : (chances[turn.move.id] ?? null); + if (turn.end !== null && (turn.move === null || chance === null)) { + chance = chances[turn.end.id] ?? null; + } + curve.push({ + game: number, + gameId: game.id, + turn: turn.number, + side: turn.side, + roll: turn.roll, + chance, + verdict: mainVerdict(decisionsOf(turn.events, "player")), + ends: turn.end !== null, + }); + } + }); + + const all = decisions.map((d) => d.advice); + const cubeAdvices = all.filter((a) => a.kind === "cube"); + const cubeErrors: CubeError[] = []; + for (const kind of CUBE_ERROR_KINDS) { + for (const d of decisions) { + const a = d.advice; + if (a.kind === "cube" && a.equityLoss < 0 && CUBE_KIND[a.action] === kind) { + cubeErrors.push({ ...d, kind }); + } + } + } + const cube = errorRateOf(cubeAdvices); + const perRoll = rolls > 0 ? luckTotal / rolls : 0; + + let toReview: MatchDecision | null = null; + for (const d of decisions) { + if (verdictOf(d.advice.skill) === "good") { + continue; + } + const cost = (x: MatchDecision) => x.loss ?? 0; + if (toReview === null || cost(d) < cost(toReview)) { + toReview = d; + } + } + + return { + match, + rows, + ready, + errorRate: errorRateOf(all), + chequer: errorRateOf(all.filter((a) => a.kind === "move")), + cube, + luck: { + total: luckTotal, + rolls, + perRoll, + rating: luckRatingOf(perRoll), + points: 0, + }, + cubeDecisions: Math.max(cube.decisions, cubeErrors.length), + cubeErrors, + decisive: decisiveMoment(curve), + toReview, + curve, + comeback: comebackOf(match, rows), + }; +} + +/** Le tour qui a fait le plus varier les chances de gagner le match, entre + * deux points analysés qui se suivent (le premier en cas d'égalité). */ +function decisiveMoment(curve: readonly MatchCurvePoint[]): DecisiveMoment | null { + let best: DecisiveMoment | null = null; + for (let i = 1; i < curve.length; i++) { + const a = curve[i - 1] as MatchCurvePoint; + const b = curve[i] as MatchCurvePoint; + if (a.chance === null || b.chance === null || b.turn === null || b.side === null) { + continue; + } + if (best === null || Math.abs(b.chance - a.chance) > Math.abs(best.to - best.from)) { + best = { + game: b.game, + gameId: b.gameId, + turn: b.turn, + side: b.side, + roll: b.roll, + from: a.chance, + to: b.chance, + }; + } + } + return best; +} + +/** Le plus grand retard du vainqueur au début d'une partie. */ +function comebackOf( + match: PlayedMatch, + rows: readonly MatchGameRow[], +): Readonly> | null { + const winner = match.winner; + if (winner === null) { + return null; + } + const loser: Side = winner === "player" ? "computer" : "player"; + let deepest: Readonly> | null = null; + for (const row of rows) { + const gap = row.scoreBefore[loser] - row.scoreBefore[winner]; + if (gap > 0 && (deepest === null || gap > deepest[loser] - deepest[winner])) { + deepest = row.scoreBefore; + } + } + return deepest; +} + +/** Les décisions de videau du bilan sans écart avec le moteur, par sorte : + * celles dont aucune décision ne diffère. */ +export function cubeKindsWithoutError(summary: MatchSummary): CubeErrorKind[] { + return CUBE_ERROR_KINDS.filter((kind) => !summary.cubeErrors.some((e) => e.kind === kind)); +} + +/** Une perte de chances de gagner le match, en pourcentage à une décimale, + * avec une espace insécable : « −3,4 % » (charte : jamais en équité). */ +export function formatMatchLoss(loss: number): string { + const text = (Math.abs(loss) * 100).toFixed(1).replace(".", ","); + return `${loss < -0.0005 ? "−" : ""}${text}\u00a0%`; +} diff --git a/app/src/domain/analysis/phrases.ts b/app/src/domain/analysis/phrases.ts index 2c1a01b..827aab3 100644 --- a/app/src/domain/analysis/phrases.ts +++ b/app/src/domain/analysis/phrases.ts @@ -17,6 +17,8 @@ import { } from "../game/advice.js"; import type { CubeAction, LuckRating } from "../game/engine.js"; import type { GameSummary } from "./game-analysis.js"; +import type { CubeErrorKind, DecisiveMoment } from "./match-analysis.js"; +import { formatPercent } from "./numbers.js"; import type { ProgressionTrend } from "./progression.js"; /** Les gabarits, par clé de section (« coup.meilleur »…). */ @@ -108,6 +110,15 @@ export const PHRASE_KEYS: readonly string[] = [ "progression.hausse", "progression.stable", "progression.attente", + "match.videau.ecarts", + "match.videau.un-seul-ecart", + "match.videau.aucun-ecart", + "match.videau.seule", + "match.videau.aucune", + "match.videau.sans-ecart", + "match.decisif.jet", + "match.decisif.jet-ordinateur", + "match.decisif.videau", ]; const DICE_KEYS: Readonly> = { @@ -165,6 +176,65 @@ export function progressionSentence(phrases: MasterPhrases, trend: ProgressionTr }); } +/** La phrase de la section « Le videau » du bilan du match (étape 1l) : + * combien de décisions de videau, et pour combien le maître aurait fait + * autrement. */ +export function matchCubeSentence( + phrases: MasterPhrases, + decisions: number, + differing: number, +): string { + const counted = `${decisions} décision${decisions > 1 ? "s" : ""} de videau`; + if (decisions === 0) { + return pick(phrases, "match.videau.aucune", "0"); + } + if (decisions === 1) { + return pick( + phrases, + differing > 0 ? "match.videau.un-seul-ecart" : "match.videau.seule", + "0", + ); + } + return differing > 0 + ? fillIn(pick(phrases, "match.videau.ecarts", "0"), { + decisions: counted, + ecarts: String(differing), + }) + : fillIn(pick(phrases, "match.videau.aucun-ecart", "0"), { decisions: counted }); +} + +/** Les sortes de décisions de videau sans écart, en une phrase chacune : + * vos doubles (doubler à tort, ne pas doubler à tort) et vos réponses + * (prendre, passer), quand aucune des deux sortes n'a d'écart. */ +export function matchCubeAgreements( + phrases: MasterPhrases, + without: readonly CubeErrorKind[], +): string[] { + const groups = [ + { kinds: ["wrongDouble", "missedDouble"], name: "Doubles" }, + { kinds: ["wrongTake", "wrongPass"], name: "Prises et refus" }, + ] as const; + return groups + .filter((group) => group.kinds.every((kind) => without.includes(kind))) + .map((group) => + fillIn(pick(phrases, "match.videau.sans-ecart", "0"), { sortes: group.name }), + ); +} + +/** La phrase du moment décisif du match : le jet (ou le double passé) et + * vos chances de gagner le match avant et après, en pourcentages. */ +export function decisiveSentence(phrases: MasterPhrases, moment: DecisiveMoment): string { + const values = { avant: formatPercent(moment.from), apres: formatPercent(moment.to) }; + if (moment.roll === null) { + return fillIn(pick(phrases, "match.decisif.videau", "0"), values); + } + const key = moment.side === "player" ? "match.decisif.jet" : "match.decisif.jet-ordinateur"; + return fillIn(pick(phrases, key, "0"), { + ...values, + roll: `${moment.roll[0]}-${moment.roll[1]}`, + }); +} + /** Ce que le maître dit d'un conseil du moteur. */ export function masterWords(phrases: MasterPhrases, advice: Advice): MasterWords { return advice.kind === "move" ? moveWords(phrases, advice) : cubeWords(phrases, advice); diff --git a/app/src/domain/game/events.ts b/app/src/domain/game/events.ts index 15d76ee..ba0feab 100644 --- a/app/src/domain/game/events.ts +++ b/app/src/domain/game/events.ts @@ -26,9 +26,13 @@ import type { Side } from "./side.js"; * - 1 : jusqu'à l'étape 1b, partie libre au niveau 2 plis ; * - 2 (étape 1c) : GameStarted porte le niveau de l'ordinateur (level) et, * pour une partie de match, le match (match) ; GameEnded porte le match - * après la partie. migrateJournal passe un journal de la version 1 à la 2. + * après la partie ; + * - 3 (étape 1l) : le match de GameStarted porte l'identifiant du match + * (match.id), commun à toutes ses parties. Une partie de la version 2 + * n'en a pas : rien d'autre ne change. + * migrateJournal passe un journal des versions 1 et 2 à la 3. */ -export const EVENT_VERSION = 2; +export const EVENT_VERSION = 3; /** Le niveau des parties de la version 1 : 2 plis (STANDARD_PLY, sans * bruit), le seul qui existait. */ @@ -37,8 +41,11 @@ const VERSION_1_LEVEL: Level = "2ply"; /** * Un journal enregistré, à la version courante du format. Version 1 : le * niveau, implicite, devient explicite (2 plis) ; rien d'autre ne change, - * une partie de la version 1 étant une partie libre. Un événement d'une - * version inconnue est laissé tel quel (Game.resume le refuse). + * une partie de la version 1 étant une partie libre. Version 2 : seul le + * numéro change ; une partie de match de la version 2 reste sans + * identifiant de match (il n'est pas inventé : groupMatches la rattache à + * son match d'après les scores et les dates). Un événement d'une version + * inconnue est laissé tel quel (Game.resume le refuse). */ export function migrateJournal(saved: GameJournal): GameJournal { const journal = keepKnownReview(keepKnownAdvice(saved)); @@ -46,10 +53,10 @@ export function migrateJournal(saved: GameJournal): GameJournal { return journal; } const events = journal.events.map((event): GameEvent => { - if (event.version !== 1) { + if (event.version !== 1 && event.version !== 2) { return event; } - if (event.type === "GameStarted") { + if (event.type === "GameStarted" && event.version === 1) { return Object.freeze({ ...event, level: event.level ?? VERSION_1_LEVEL, @@ -125,16 +132,33 @@ function keepKnownReview(journal: GameJournal): GameJournal { a.eventId === id, ), ); + // Les tables du match (étape 1l), facultatives : une table mal formée + // est oubliée, ses nombres hors d'un événement du journal aussi. + const numbers = (table: unknown): Record | undefined => + typeof table === "object" && table !== null + ? Object.fromEntries( + Object.entries(table).filter( + ([id, value]) => ids.has(id) && typeof value === "number", + ), + ) + : undefined; + const matchChances = numbers(review.matchChances); + const matchLosses = numbers(review.matchLosses); + const { matchChances: _c, matchLosses: _l, ...base } = review; const kept: GameReview = { - ...review, + ...base, luck: known(review.luck), winChances: known(review.winChances), computer, unanalysed: review.unanalysed.filter((id) => ids.has(id)), + ...(matchChances === undefined ? {} : { matchChances }), + ...(matchLosses === undefined ? {} : { matchLosses }), }; // Le nombre d'entrées de chaque table : rien d'oublié, rien ne change. const sizes = (r: GameReview) => - [r.luck, r.winChances, r.computer, r.unanalysed].map((t) => Object.keys(t).length).join(); + [r.luck, r.winChances, r.computer, r.unanalysed, r.matchChances, r.matchLosses] + .map((t) => (t === undefined ? "-" : Object.keys(t).length)) + .join(); return sizes(kept) === sizes(review) ? journal : { ...journal, review: kept }; } diff --git a/app/src/domain/game/match.ts b/app/src/domain/game/match.ts index e5960b8..716ea42 100644 --- a/app/src/domain/game/match.ts +++ b/app/src/domain/game/match.ts @@ -19,6 +19,11 @@ import type { Side } from "./side.js"; * Glossaire : docs/glossaire/match.md */ export interface Match { + /** L'identifiant du match, commun à toutes ses parties (version 3 des + * événements) ; absent dans les parties enregistrées avant, que + * groupMatches (domain/analysis/match-analysis.ts) rattache d'après + * leurs scores et leurs dates quand c'est sûr. */ + readonly id?: string; /** Le nombre de points à atteindre pour gagner le match. */ readonly length: number; readonly score: Readonly>; @@ -37,12 +42,25 @@ export interface MatchAfterGame { /** Les longueurs de match proposées à l'écran « Nouvelle partie ». */ export const MATCH_LENGTHS = [3, 5, 7, 11] as const; -/** La première partie d'un match en length points : 0 à 0. */ -export function firstGameOf(length: number): Match { +/** La première partie d'un match en length points : 0 à 0. L'identifiant + * du match vient de l'appelant (le domaine ne tire pas de hasard) : sans + * lui, la session de jeu lui donne celui de la première partie + * (storage/game-session.ts). */ +export function firstGameOf(length: number, id?: string): Match { if (!Number.isInteger(length) || length < 1) { throw new Error(`longueur de match invalide : ${length}`); } - return { length, score: { player: 0, computer: 0 }, crawford: false }; + return { + ...(id === undefined ? {} : { id }), + length, + score: { player: 0, computer: 0 }, + crawford: false, + }; +} + +/** Le match avec son identifiant (rien ne change s'il en a déjà un). */ +export function withMatchId(match: Match, id: string): Match { + return match.id === undefined ? { id, ...match } : match; } /** La partie suivante d'un match, d'après ce que le moteur a dit à la fin @@ -51,5 +69,10 @@ export function nextGameOf(match: Match, after: MatchAfterGame): Match | null { if (after.over) { return null; } - return { length: match.length, score: after.score, crawford: after.crawford }; + return { + ...(match.id === undefined ? {} : { id: match.id }), + length: match.length, + score: after.score, + crawford: after.crawford, + }; } diff --git a/app/src/domain/game/review.ts b/app/src/domain/game/review.ts index 1bed493..61f8fe9 100644 --- a/app/src/domain/game/review.ts +++ b/app/src/domain/game/review.ts @@ -40,6 +40,18 @@ export interface GameReview { /** Les décisions (des deux camps) que le moteur n'analyse pas : videau * inaccessible, position de départ. Elles ne sont plus demandées. */ readonly unanalysed: readonly string[]; + /** Dans un match (étape 1l, facultatif) : les chances du joueur de + * gagner le match, de 0 à 1, selon le moteur : au début de la partie + * (sous l'identifiant de GameStarted, la table d'équité de match au + * score), après chaque coup (MovePlayed, l'évaluation du moteur + * convertie), et après la partie (GameEnded : 1 ou 0 si le match est + * fini, sinon la table au nouveau score). */ + readonly matchChances?: Readonly>; + /** Dans un match (étape 1l, facultatif) : pour chaque décision du + * joueur analysée, les chances de gagner le match qu'elle lui a + * coûtées (0 ou négatif), converties par le moteur à partir de + * l'équité perdue, comme les statistiques de match de gnubg. */ + readonly matchLosses?: Readonly>; } /** Une analyse vide, au niveau ply. */ diff --git a/app/src/domain/game/saved-game.ts b/app/src/domain/game/saved-game.ts index ede5121..091c942 100644 --- a/app/src/domain/game/saved-game.ts +++ b/app/src/domain/game/saved-game.ts @@ -42,6 +42,9 @@ export interface SavedGameSummary { /** Le match d'une partie enregistrée, pour la liste. */ export interface SavedMatch { + /** L'identifiant du match (absent avant la version 3 des + * événements). */ + readonly id?: string; readonly length: number; readonly score: Readonly>; readonly crawford: boolean; @@ -83,6 +86,7 @@ export function summarizeGame( ? {} : { match: { + ...(state.match.id === undefined ? {} : { id: state.match.id }), length: state.match.length, score: state.matchAfter?.score ?? state.match.score, crawford: state.match.crawford, diff --git a/app/src/domain/prompts/prompts.ts b/app/src/domain/prompts/prompts.ts index dc49337..a76f313 100644 --- a/app/src/domain/prompts/prompts.ts +++ b/app/src/domain/prompts/prompts.ts @@ -20,6 +20,13 @@ import { type ReviewedDecision, summarizeAnalysis, } from "../analysis/game-analysis.js"; +import { + type CubeErrorKind, + cubeKindsWithoutError, + formatMatchLoss, + type MatchDecision, + type MatchSummary, +} from "../analysis/match-analysis.js"; import { formatEquity, formatPercent, @@ -27,7 +34,14 @@ import { rankingPly, rankingRows, } from "../analysis/numbers.js"; -import { diceWords, type MasterPhrases, masterWords } from "../analysis/phrases.js"; +import { + decisiveSentence, + diceWords, + type MasterPhrases, + masterWords, + matchCubeAgreements, + matchCubeSentence, +} from "../analysis/phrases.js"; import { type Advice, type CubeAdvice, @@ -524,3 +538,188 @@ export function exercisesPrompt( position_titre: `La plus coûteuse (partie ${worst.game}, coup ${worst.turn}) : la position avant ma décision`, }); } + +// ------------------------------------------------- Le bilan d'un match + +/** Les sortes d'erreurs de videau, comme le bilan du match les nomme + * (charte, « Bilan du match »). */ +export const CUBE_ERROR_WORDS: Readonly> = { + wrongDouble: "Mauvais double", + missedDouble: "Double manqué", + wrongTake: "Prise fautive", + wrongPass: "Refus fautif", +}; + +/** Un score de match, « vous – l'ordinateur » : « 0–2 ». */ +export function matchScoreText(score: Readonly>): string { + return `${score.player}–${score.computer}`; +} + +/** Le nombre de parties d'un match, en lettres jusqu'à douze : « cinq ». */ +export function gamesWord(n: number): string { + const words = [ + "zéro", + "une", + "deux", + "trois", + "quatre", + "cinq", + "six", + "sept", + "huit", + "neuf", + "dix", + "onze", + "douze", + ]; + return words[n] ?? String(n); +} + +/** La position que montre le prompt du bilan du match : celle d'avant la + * décision à revoir, ou la position finale de la dernière partie. */ +export async function matchPosition( + engine: Engine, + summary: MatchSummary, +): Promise { + const reviewed = summary.toReview; + const games = summary.match.games; + if (reviewed !== null) { + const game = games[reviewed.game - 1]; + if (game !== undefined) { + return positionBefore(engine, game.journal, reviewed.advice.eventId); + } + } + return positionNow(engine, games.at(-1)?.journal ?? null); +} + +/** Ce que demande le prompt du bilan du match. */ +export interface MatchPromptData { + readonly summary: MatchSummary; + /** matchPosition. */ + readonly position: PromptPosition; +} + +/** Le résultat d'un match, comme l'en-tête de son bilan. */ +function matchResultText(summary: MatchSummary): string { + const { match, comeback } = summary; + const score = `${match.score.player} à ${match.score.computer}`; + const games = `en ${gamesWord(match.games.length)} partie${match.games.length > 1 ? "s" : ""}`; + if (!match.over) { + return `match en cours, ${score} (moi, puis l'ordinateur), après ${gamesWord(match.games.length)} partie${match.games.length > 1 ? "s" : ""}`; + } + const who = match.winner === "player" ? "j'ai gagné le match" : "l'ordinateur a gagné le match"; + const back = + comeback === null + ? "" + : match.winner === "player" + ? `, après avoir été mené ${comeback.player} à ${comeback.computer}` + : `, alors que je menais ${comeback.player} à ${comeback.computer}`; + return `${who} ${score} ${games}${back}`; +} + +/** Une partie du match, en une ligne. */ +function matchGameLine(row: MatchSummary["rows"][number]): string { + const where = `- Partie ${row.number} (${matchScoreText(row.scoreBefore)}${row.crawford ? ", partie Crawford" : ""})`; + const result = row.result; + if (result === null) { + return `${where} : en cours.`; + } + const who = result.winner === "player" ? "je gagne" : "l'ordinateur gagne"; + const kind = { single: "une partie simple", gammon: "un gammon", backgammon: "un backgammon" }[ + result.kind + ]; + const cube = row.cube > 1 ? `, videau à ${row.cube}` : ""; + return `${where} : ${who} ${kind}${cube}, ${plural(result.points, "point", "points")}.`; +} + +/** Une décision du match, avec sa perte en chances de gagner le match. */ +function matchDecisionLine(phrases: MasterPhrases, d: MatchDecision, label: string): string { + const a = d.advice; + const where = `- Partie ${d.game}, coup ${d.turn}, à ${matchScoreText(d.score)}`; + const cost = + d.loss === null + ? masterWords(phrases, a).word + : `perte de ${formatMatchLoss(d.loss).replace("−", "")} de chances de gagner le match (${masterWords(phrases, a).word})`; + if (a.kind === "move") { + return `${where}${label} : j'ai joué ${a.played.notation} avec ${a.roll[0]}-${a.roll[1]}, GNU Backgammon préférait ${a.best.notation} ; ${cost}.`; + } + return `${where}${label} : j'ai choisi de ${CUBE_ACTION_WORDS[a.action]}, GNU Backgammon aurait choisi de ${CUBE_ACTION_WORDS[masterCubeAction(a)]} ; ${cost}.`; +} + +/** Le prompt « Bilan de mon match ». */ +export function matchPrompt( + templates: PromptTemplates, + phrases: MasterPhrases, + data: MatchPromptData, +): Prompt { + const { summary } = data; + const cubeLines = [ + matchCubeSentence(phrases, summary.cubeDecisions, summary.cubeErrors.length), + ...summary.cubeErrors.map((e) => + matchDecisionLine(phrases, e, ` (${CUBE_ERROR_WORDS[e.kind].toLowerCase()})`), + ), + ...matchCubeAgreements(phrases, cubeKindsWithoutError(summary)), + ]; + const costly = matchMistakes(summary); + const listed = costly.slice(0, MAX_ERRORS).map((d) => matchDecisionLine(phrases, d, "")); + if (costly.length > listed.length) { + listed.push(`- et ${costly.length - listed.length} de moins coûteuses.`); + } + const level = computerLevelOf(summary.match.level); + const reviewed = summary.toReview; + return fillPrompt(templates.match, { + ...positionValues(data.position), + joueur: playerSentence(summary.errorRate), + niveau_eval: plyText(reviewed?.advice.ply ?? 2), + ordinateur: + level === null ? `GNU Backgammon, réglage ${summary.match.level}` : LEVEL_NAMES[level], + longueur: plural(summary.match.length, "point", "points"), + resultat: matchResultText(summary), + parties: summary.rows.map(matchGameLine).join("\n"), + taux: formatEquity(-summary.errorRate.perDecision), + decisions: plural(summary.errorRate.decisions, "décision", "décisions"), + niveau_jeu: LEVEL_NAMES[summary.errorRate.level], + taux_pions: `${formatEquity(-summary.chequer.perDecision)} sur ${plural(summary.chequer.decisions, "décision", "décisions")}`, + taux_videau: `${formatEquity(-summary.cube.perDecision)} sur ${plural(summary.cube.decisions, "décision", "décisions")}`, + chance: formatEquity(summary.luck.perRoll), + chance_mots: diceWords(phrases, summary.luck.rating), + videau_decisions: cubeLines.join("\n"), + decisif: + summary.decisive === null + ? "pas encore analysé." + : decisiveSentence(phrases, summary.decisive), + erreurs: + listed.length === 0 ? "- aucune : j'ai joué comme GNU Backgammon." : listed.join("\n"), + position_titre: + reviewed === null + ? "Je n'ai fait ni imprécision ni erreur. Voici la position finale" + : `La décision à revoir, ma plus grande perte de chances de gagner le match (partie ${reviewed.game}, coup ${reviewed.turn}) : la position avant ma décision`, + }); +} + +/** Les imprécisions et erreurs du joueur sur le match, de la plus + * coûteuse en chances de gagner le match à la moins coûteuse. */ +export function matchMistakes(summary: MatchSummary): MatchDecision[] { + const decisions: MatchDecision[] = []; + for (const [index, game] of summary.match.games.entries()) { + const advice = game.journal.advice ?? {}; + const losses = game.journal.review?.matchLosses ?? {}; + const score = summary.rows[index]?.scoreBefore ?? { player: 0, computer: 0 }; + for (const turn of gameTurns(game.journal)) { + for (const event of turn.events) { + const a = advice[event.id]; + if (a !== undefined && verdictOf(a.skill) !== "good") { + decisions.push({ + game: index + 1, + gameId: game.id, + turn: turn.number, + score, + advice: a, + loss: losses[event.id] ?? null, + }); + } + } + } + } + return decisions.sort((a, b) => (a.loss ?? 0) - (b.loss ?? 0)); +} diff --git a/app/src/domain/prompts/templates.ts b/app/src/domain/prompts/templates.ts index c725b49..f46459e 100644 --- a/app/src/domain/prompts/templates.ts +++ b/app/src/domain/prompts/templates.ts @@ -14,8 +14,9 @@ */ export type Prompt = string; -/** Les cinq gabarits du cadrage (« IA générative en V1 »). */ -export type PromptKind = "move" | "cube" | "summary" | "concept" | "exercises"; +/** Les cinq gabarits du cadrage (« IA générative en V1 »), et le bilan + * d'un match entier (étape 1l). */ +export type PromptKind = "move" | "cube" | "summary" | "concept" | "exercises" | "match"; export const PROMPT_KINDS: readonly PromptKind[] = [ "move", @@ -23,6 +24,7 @@ export const PROMPT_KINDS: readonly PromptKind[] = [ "summary", "concept", "exercises", + "match", ]; /** Le fichier de chaque gabarit, dans docs/prompts/. */ @@ -32,6 +34,7 @@ export const PROMPT_FILES: Readonly> = { summary: "bilan.md", concept: "concept.md", exercises: "exercices.md", + match: "match.md", }; /** Les gabarits lus, par sorte. */ diff --git a/app/src/storage/game-session.ts b/app/src/storage/game-session.ts index b5f4a7d..fc97b15 100644 --- a/app/src/storage/game-session.ts +++ b/app/src/storage/game-session.ts @@ -11,6 +11,7 @@ import { switchToBranch } from "../domain/game/branches.js"; import type { GameJournal } from "../domain/game/events.js"; import type { Game, NewGame } from "../domain/game/game.js"; +import { withMatchId } from "../domain/game/match.js"; import { levelOf } from "../domain/game/saved-game.js"; import { type GameLibrary, newGameId } from "./game-library.js"; @@ -78,8 +79,14 @@ export function createGameSession(library: GameLibrary, games: GameFactory): Gam }, newGame(newGame) { previousId = shownId; - shownId = newGameId(); - return games.start(newGame); + const id = newGameId(); + shownId = id; + // La première partie d'un match donne son identifiant au match + // (version 3 des événements) ; les suivantes le reprennent. + const match = newGame?.match; + return games.start( + match === undefined ? newGame : { ...newGame, match: withMatchId(match, id) }, + ); }, save(journal) { if (shownId !== null) { diff --git a/app/src/ui/help.ts b/app/src/ui/help.ts index 5ced9fc..4406fba 100644 --- a/app/src/ui/help.ts +++ b/app/src/ui/help.ts @@ -37,6 +37,7 @@ export const FEATURES = [ "docs/scenarios/apprendre-les-regles.feature", "docs/scenarios/suivre-une-lecon.feature", "docs/scenarios/suivre-ma-progression.feature", + "docs/scenarios/analyser-mon-match.feature", "docs/scenarios/mes-parties.feature", "docs/scenarios/partager-une-position.feature", "docs/scenarios/regler-l-application.feature", diff --git a/app/src/ui/match-summary-texts.ts b/app/src/ui/match-summary-texts.ts new file mode 100644 index 0000000..72c545d --- /dev/null +++ b/app/src/ui/match-summary-texts.ts @@ -0,0 +1,167 @@ +// Les textes du bilan d'un match entier (étape 1l ; charte, +// ecrans-etape-1.md, « Bilan du match »), des lignes de match des listes +// et des accès au bilan du match. Les phrases du maître elles-mêmes (le +// videau, le moment décisif) sont dans docs/maitre/phrases.md (une seule +// source, ADR 0008). +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). + +import type { MatchSummary, PlayedMatch } from "../domain/analysis/match-analysis.js"; +import type { Side } from "../domain/game/side.js"; +import type { GameResult } from "../domain/game/state.js"; +import { gamesWord, matchScoreText } from "../domain/prompts/prompts.js"; + +export { CUBE_ERROR_WORDS, matchScoreText } from "../domain/prompts/prompts.js"; + +const DATE = new Intl.DateTimeFormat("fr-FR", { day: "numeric", month: "long" }); + +const partsWord = (n: number) => `${gamesWord(n)} partie${n > 1 ? "s" : ""}`; + +/** « mené 0 à 4 » : un score lu du point de vue du joueur. */ +const scoreWords = (score: Readonly>) => `${score.player} à ${score.computer}`; + +export const MATCH_SUMMARY_TEXTS = { + title: "Bilan du match", + close: "Fermer", + loading: "Le match se lit…", + analysing: "Le maître analyse les parties du match…", + missing: "Ce match n'est plus sur ce téléphone.", + /** L'en-tête, en caption : « Fin du match · 5 points · 12 novembre ». */ + overline: (match: PlayedMatch) => + match.over + ? `Fin du match · ${match.length} points · ${DATE.format(match.updatedAt)}` + : `Match en cours · ${matchScoreText(match.score)}`, + headline: (match: PlayedMatch) => + match.over + ? match.winner === "player" + ? "Vous gagnez le match" + : "L'ordinateur gagne le match" + : `Match en ${match.length} points`, + /** « 5 à 4, en cinq parties, après avoir été mené 0 à 4. » */ + sentence: (summary: MatchSummary) => { + const { match, comeback } = summary; + const games = match.games.length; + if (!match.over) { + return `${scoreWords(match.score)} après ${partsWord(games)}.`; + } + const back = + comeback === null + ? "" + : match.winner === "player" + ? `, après avoir été mené ${scoreWords(comeback)}` + : `, alors que vous meniez ${scoreWords(comeback)}`; + const final = + match.winner === "player" + ? scoreWords(match.score) + : `${match.score.computer} à ${match.score.player}`; + return `${final}, en ${partsWord(games)}${back}.`; + }, + inferred: + "Match joué avant que l'application relie les parties : elles sont rattachées d'après leurs scores et leurs dates.", + + // La courbe + curveTitle: "Vos chances de gagner le match", + curveLabel: (start: string, low: string, end: string, decisive: string) => + `Courbe de vos chances de gagner le match : ${start} au départ, ${low} au plus bas, ${end} à la fin.${decisive}`, + curveDecisive: (game: number, turn: number) => + ` Moment décisif : partie ${game}, coup ${turn}.`, + curveKeys: "Glissez le doigt sur la courbe, ou utilisez les flèches gauche et droite.", + half: "50 %", + gameShort: (n: number) => `P${n}`, + legendDecisive: "Moment décisif", + legendReview: "Décision à revoir", + legendEnd: "Fin du match", + bubble: (game: number, turn: number | null, score: string, chance: string) => + turn === null + ? `Début du match · ${score} · ${chance}` + : `Partie ${game}, coup ${turn} · ${score} · ${chance}`, + bubbleOpen: "Toucher pour ouvrir cette décision", + pending: "La courbe se complète pendant l'analyse.", + + // Partie par partie + gamesTitle: "Partie par partie", + gameRow: (n: number) => `Partie ${n}`, + gameResult: (result: GameResult | null, cube: number) => { + if (result === null) { + return "en cours"; + } + const who = result.winner === "player" ? "Gagnée" : "Perdue"; + const kind = + result.kind === "single" + ? "" + : ` · ${result.kind === "gammon" ? "gammon" : "backgammon"}`; + const doubled = cube > 1 ? ` · videau ${cube}` : ""; + return `${who}${kind}${doubled}`; + }, + gamePoints: (result: GameResult | null) => + result === null + ? "" + : `${result.winner === "player" ? "Vous marquez" : "L'ordinateur marque"} ${result.points} point${result.points > 1 ? "s" : ""}`, + gameRowLabel: (n: number, result: string, points: string, score: string) => + `Partie ${n} : ${result}. ${points}. Score après la partie : ${score}.`, + crawford: "Crawford", + scoreReminder: "Le score se lit toujours vous – l'ordinateur.", + + // Votre jeu + playTitle: "Votre jeu sur le match", + tiles: { all: "Tout le match", chequer: "Les pions", cube: "Le videau" }, + tileUnit: "millièmes par décision", + tileNone: "aucune décision", + + // Le videau + cubeTitle: "Le videau", + cubeWhere: (game: number, turn: number, score: string) => + `Partie ${game}, coup ${turn}, à ${score}`, + cubeLossPending: "perte en calcul", + cubeRowLabel: (kind: string, where: string, loss: string) => + `${kind}, ${where} : ${loss} de chances de gagner le match`, + + // Le moment décisif + decisiveTitle: "Le moment décisif", + decisiveNone: "Le moment décisif apparaîtra quand l'analyse sera finie.", + seeThisMove: "Voir ce coup", + + // La décision à revoir + reviewTitle: "La décision à revoir", + reviewWhere: (game: number, turn: number, score: string) => + `Partie ${game}, coup ${turn}, à ${score}`, + lossOf: (loss: string) => `${loss} de chances de gagner le match`, + review: "Revoir", + + // Export + exportSgf: "Exporter le match (SGF)", + exportHint: "pour l'ouvrir dans GNU Backgammon", + exportFailed: (reason: string) => `L'export n'a pas abouti : ${reason}`, + + // Barre d'actions + reviewMatch: "Revoir le match", + newMatch: "Nouveau match", + resumeMatch: "Reprendre le match", + + // Accès + seeMatchSummary: "Bilan du match", + seeMatchSummaryLink: "Voir le bilan du match", + /** Sous l'en-tête du bilan d'une partie de match. */ + gameOfMatch: (n: number, length: number) => `Partie ${n} du match en ${length} points`, + /** En tête de l'analyse d'une partie de match : « Partie 2 sur 5 · 0–2 ». */ + analysisHeader: (n: number, total: number, score: string) => + `Partie ${n} sur ${total} · ${score}`, + previousGame: "Partie précédente", + nextGame: "Partie suivante", + + // Les listes + listTitle: (match: PlayedMatch) => { + const score = matchScoreText(match.score); + const state = match.over + ? `${match.winner === "player" ? "gagné" : "perdu"} ${score}` + : `en cours, ${score}`; + return `Match en ${match.length} points · ${state}`; + }, + listCaption: (date: string, games: number, level: string) => + `${date} · ${games} partie${games > 1 ? "s" : ""} · ${level}`, + listInferred: "rattaché d'après les scores", + resume: "Reprendre", + errorRate: (millis: number) => `${millis}`, + errorRateLabel: (millis: number) => `Taux d'erreur du match : ${millis} millièmes`, +} as const; diff --git a/app/src/ui/prompt-source.ts b/app/src/ui/prompt-source.ts index 3d17b03..40ac999 100644 --- a/app/src/ui/prompt-source.ts +++ b/app/src/ui/prompt-source.ts @@ -84,12 +84,13 @@ export function createPromptSource(options: PromptSourceOptions): PromptSource { parsePromptTemplate(await fetchText(PROMPTS_DIR + PROMPT_FILES[kind])), ), ).then( - ([move, cube, summary, concept, exercises]) => ({ + ([move, cube, summary, concept, exercises, match]) => ({ move: move ?? "", cube: cube ?? "", summary: summary ?? "", concept: concept ?? "", exercises: exercises ?? "", + match: match ?? "", }), (error: unknown) => { loading = null; diff --git a/app/tests/game.test.ts b/app/tests/game.test.ts index 83b31e7..fb39f38 100644 --- a/app/tests/game.test.ts +++ b/app/tests/game.test.ts @@ -360,7 +360,7 @@ test("les événements sont immuables et versionnés ; le rejeu est déterminist }); journal = appendEvent(journal, { type: "DiceRolled", side: null, roll: [5, 2] }); const [started, rolled] = currentLine(journal); - assert.equal(started?.version, 2); + assert.equal(started?.version, 3); assert.equal(started?.parent, null); assert.equal(rolled?.parent, started?.id); assert.throws(() => { @@ -608,7 +608,7 @@ test("migration : un journal de la version 1 se reprend en version 2, au niveau assert.equal(resumed.state.level, "2ply"); assert.equal(resumed.state.match, null); assert.ok(resumed.journal.events.every((event) => event.version === EVENT_VERSION)); - // La partie continue en version 2. + // La partie continue à la version courante. await resumed.playComputerTurn(); assert.ok(resumed.journal.events.every((event) => event.version === EVENT_VERSION)); }); diff --git a/app/tests/match-analysis.test.ts b/app/tests/match-analysis.test.ts new file mode 100644 index 0000000..21a857b --- /dev/null +++ b/app/tests/match-analysis.test.ts @@ -0,0 +1,401 @@ +// Tests de l'analyse d'un match entier (étape 1l) : l'identifiant de match +// (version 3 des événements) et sa migration, les tables du match dans +// l'analyse de partie, le rattachement des parties d'un match (avec et sans +// identifiant), le bilan du match sur un vrai match joué par le moteur (la +// remontée de 0–4 à 5–4), les phrases du maître et le prompt « Bilan de mon +// match ». +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import { + missingAnalyses, + readyForMatchSummary, + readyForSummary, +} from "../src/domain/analysis/game-analysis.js"; +import { + cubeKindsWithoutError, + formatMatchLoss, + groupMatches, + LINK_DELAY_MS, + type MatchGame, + matchOfGame, + summarizeMatch, +} from "../src/domain/analysis/match-analysis.js"; +import { + decisiveSentence, + LINE_LIMIT, + matchCubeAgreements, + matchCubeSentence, + PHRASE_KEYS, +} from "../src/domain/analysis/phrases.js"; +import type { Engine } from "../src/domain/game/engine.js"; +import { + currentLine, + EVENT_VERSION, + type GameJournal, + migrateJournal, +} from "../src/domain/game/events.js"; +import { Game } from "../src/domain/game/game.js"; +import { firstGameOf, nextGameOf, withMatchId } from "../src/domain/game/match.js"; +import { replay } from "../src/domain/game/state.js"; +import { CUBE_ERROR_WORDS, matchPosition, matchPrompt } from "../src/domain/prompts/prompts.js"; +import { PROMPT_FILES, parsePromptTemplate } from "../src/domain/prompts/templates.js"; +import { createGameSession } from "../src/storage/game-session.js"; +import { memoryStorage, openGameLibrary } from "../src/storage/open-library.js"; +import { loadPhrases } from "./support/advice.js"; +import { COMEBACK_MATCH_ID, playComebackMatch } from "./support/match.js"; +import { loadNodeEngine } from "./support/node-engine.js"; + +const root = new URL("../../../", import.meta.url); +const phrases = loadPhrases(); +const engine: Engine = await loadNodeEngine(); +const comeback = await playComebackMatch(engine); + +/** Un nombre de gnubg de bureau (tests/reference/analysis/). */ +function reference(id: string): { at_score: number; equities: { equity: number; loss: number }[] } { + return JSON.parse(readFileSync(new URL(`tests/reference/analysis/${id}.json`, root), "utf8")); +} + +// --------------------------------------------- Identifiant et migration + +test("un journal de la version 2 passe à la 3 sans identifiant de match inventé", () => { + const v2 = JSON.parse(JSON.stringify(comeback[1]?.journal)) as { + events: { version: number; type: string; match?: { id?: string } }[]; + }; + for (const event of v2.events) { + event.version = 2; + if (event.type === "GameStarted") { + delete event.match?.id; + } + } + const migrated = migrateJournal(v2 as unknown as GameJournal); + assert.ok(migrated.events.every((event) => event.version === EVENT_VERSION)); + assert.equal(EVENT_VERSION, 3); + const start = migrated.events[0]; + assert.ok(start?.type === "GameStarted"); + assert.deepEqual(start.match, { + length: 5, + score: { player: 0, computer: 2 }, + crawford: false, + }); + // Le reste de la partie est le même. + assert.deepEqual( + replay(currentLine(migrated)).matchAfter, + replay(currentLine(comeback[1]?.journal as GameJournal)).matchAfter, + ); + // Le journal analysé reste analysé : l'analyse ne dépend pas du numéro. + assert.deepEqual(migrated.review, comeback[1]?.journal.review); +}); + +test("les tables du match d'une analyse enregistrée sont relues, ou oubliées si mal formées", () => { + const journal = comeback[3]?.journal as GameJournal; + const review = journal.review; + assert.ok(review?.matchChances !== undefined && review.matchLosses !== undefined); + // Bien formées : rien ne change. + assert.equal(migrateJournal(journal), journal); + // Une entrée hors du journal, une valeur qui n'est pas un nombre : oubliées. + const damaged = { + ...journal, + review: { + ...review, + matchChances: { ...review.matchChances, "99": 0.5, "1": "beaucoup" }, + matchLosses: "rien", + }, + } as unknown as GameJournal; + const read = migrateJournal(damaged); + const { "1": _, ...others } = review.matchChances; + assert.deepEqual(read.review?.matchChances, others); + assert.equal(read.review?.matchLosses, undefined); + // Une analyse d'avant l'étape 1l (sans ces tables) les fait calculer, sans + // retarder le bilan de la partie. + const { matchChances: _c, matchLosses: _l, ...before } = review; + const old = { ...journal, review: before }; + assert.equal(migrateJournal(old), old); + const tasks = missingAnalyses(old); + assert.ok(tasks.some((t) => t.kind === "matchChance")); + assert.ok(tasks.some((t) => t.kind === "matchLoss")); + assert.ok(readyForSummary(old)); + assert.ok(!readyForMatchSummary(old)); +}); + +test("la première partie d'un match lui donne son identifiant ; les suivantes le gardent", async () => { + const match = firstGameOf(5); + assert.equal(match.id, undefined); + assert.equal(withMatchId(match, "m1").id, "m1"); + assert.equal(withMatchId(firstGameOf(5, "m0"), "m1").id, "m0"); + const next = nextGameOf(firstGameOf(5, "m0"), { + score: { player: 0, computer: 2 }, + over: false, + crawford: false, + }); + assert.equal(next?.id, "m0"); + + const { library } = await openGameLibrary({ localStorage: memoryStorage() }); + const session = createGameSession(library, { + start: (newGame) => Game.start(engine, newGame), + resume: (journal) => Game.resume(engine, journal), + }); + const first = session.newGame({ match: firstGameOf(5) }); + const id = session.shownId; + assert.equal(first.state.match?.id, id); + // Une partie libre reste sans match. + assert.equal(session.newGame({}).state.match, null); + // La partie suivante d'un match garde son identifiant. + const second = session.newGame({ + match: { ...firstGameOf(5, id ?? ""), score: { player: 1, computer: 0 } }, + }); + assert.equal(second.state.match?.id, id); +}); + +// ------------------------------------------- Les parties d'un match + +test("les parties d'un match sont réunies par leur identifiant", () => { + const { matches, loose } = groupMatches([...comeback].reverse()); + assert.equal(loose.length, 0); + assert.equal(matches.length, 1); + const match = matches[0]; + assert.ok(match !== undefined); + assert.equal(match.id, COMEBACK_MATCH_ID); + assert.equal(match.inferred, false); + assert.deepEqual( + match.games.map((g) => g.id), + comeback.map((g) => g.id), + ); + assert.deepEqual(match.score, { player: 5, computer: 4 }); + assert.equal(match.over, true); + assert.equal(match.winner, "player"); + assert.equal(match.waiting, false); + assert.deepEqual(matchOfGame(matches, "partie-3")?.number, 3); + assert.equal(matchOfGame(matches, "ailleurs"), null); + // Un match en cours : la dernière partie finie, la suivante à venir. + const ongoing = groupMatches(comeback.slice(0, 2)).matches[0]; + assert.deepEqual(ongoing?.score, { player: 0, computer: 4 }); + assert.equal(ongoing?.over, false); + assert.equal(ongoing?.waiting, true); +}); + +test("les matchs joués avant l'identifiant sont rattachés d'après les scores et les dates", async () => { + const legacy = await playComebackMatch(engine, { matchId: null, analyse: false }); + const { matches, loose } = groupMatches(legacy); + assert.equal(loose.length, 0); + assert.equal(matches.length, 1); + assert.equal(matches[0]?.inferred, true); + assert.equal(matches[0]?.id, "partie-1"); + assert.deepEqual( + matches[0]?.games.map((g) => g.id), + legacy.map((g) => g.id), + ); + + // Trop de temps entre deux parties : on ne devine pas. + const late = legacy.map( + (g, i): MatchGame => + i < 2 + ? g + : { + ...g, + startedAt: g.startedAt + LINK_DELAY_MS, + updatedAt: g.updatedAt + LINK_DELAY_MS, + }, + ); + const split = groupMatches(late); + assert.deepEqual( + split.matches.map((m) => m.games.length), + [2], + ); + assert.deepEqual( + split.loose.map((g) => g.id), + ["partie-3", "partie-4", "partie-5"], + ); + + // Deux parties pourraient suivre la même : la chaîne s'arrête là. + const twin = { + ...(legacy[2] as MatchGame), + id: "jumelle", + startedAt: (legacy[2]?.startedAt ?? 0) + 1, + }; + const ambiguous = groupMatches([...legacy, twin]); + assert.deepEqual( + ambiguous.matches.map((m) => m.games.map((g) => g.id)), + [["partie-1", "partie-2"]], + ); + assert.equal(ambiguous.loose.length, 4); +}); + +// ------------------------------------------------------- Le bilan + +test("le bilan du match : la remontée de 0–4 à 5–4", () => { + const match = groupMatches(comeback).matches[0]; + assert.ok(match !== undefined); + const summary = summarizeMatch(match); + assert.equal(summary.ready, true); + assert.deepEqual(summary.comeback, { player: 0, computer: 4 }); + assert.deepEqual( + summary.rows.map((r) => [r.scoreBefore, r.scoreAfter, r.crawford, r.result?.winner]), + [ + [{ player: 0, computer: 0 }, { player: 0, computer: 2 }, false, "computer"], + [{ player: 0, computer: 2 }, { player: 0, computer: 4 }, false, "computer"], + [{ player: 0, computer: 4 }, { player: 2, computer: 4 }, true, "player"], + [{ player: 2, computer: 4 }, { player: 3, computer: 4 }, false, "player"], + [{ player: 3, computer: 4 }, { player: 5, computer: 4 }, false, "player"], + ], + ); + // Le double de la partie 4 : le moteur n'aurait pas doublé. + assert.equal(summary.cubeErrors.length, 1); + const error = summary.cubeErrors[0]; + assert.equal(error?.kind, "wrongDouble"); + assert.equal(error?.game, 4); + assert.equal(error?.turn, 1); + assert.deepEqual(error?.score, { player: 2, computer: 4 }); + assert.ok(error?.loss !== null && (error?.loss ?? 0) < 0); + assert.deepEqual(cubeKindsWithoutError(summary), ["missedDouble", "wrongTake", "wrongPass"]); + assert.equal(summary.toReview?.advice.eventId, error?.advice.eventId); + assert.equal(summary.cube.decisions, 1); + assert.equal(summary.chequer.decisions, 0); + // Le moment décisif : le 5-5 de la dernière partie, qui gagne le match. + assert.equal(summary.decisive?.game, 5); + assert.deepEqual(summary.decisive?.roll, [5, 5]); + assert.equal(summary.decisive?.to, 1); +}); + +test("la courbe du match est continue d'une partie à l'autre, en chances de gagner le match", () => { + const match = groupMatches(comeback).matches[0]; + assert.ok(match !== undefined); + const curve = summarizeMatch(match).curve; + assert.ok(curve.every((p) => p.chance !== null)); + // Le début du match : 50 %, la table de gnubg à 0–0. + assert.equal(curve[0]?.turn, null); + assert.equal(curve[0]?.chance, reference("chances-5-0-0").at_score); + // Après la partie 1 (0–2), la table de gnubg de bureau à ce score. + assert.ok(Math.abs((curve[1]?.chance ?? 0) - reference("chances-5-0-2").at_score) < 1e-6); + // La fin d'une partie est le début de la suivante : les chances de + // GameEnded d'une partie sont celles de GameStarted de la suivante. + for (let i = 1; i < comeback.length; i++) { + const before = comeback[i - 1]?.journal as GameJournal; + const after = comeback[i]?.journal as GameJournal; + const end = currentLine(before).at(-1); + const start = currentLine(after)[0]; + assert.ok(end?.type === "GameEnded" && start?.type === "GameStarted"); + assert.equal(after.review?.matchChances?.[start.id], before.review?.matchChances?.[end.id]); + } + // La fin du match gagné : 100 %. + assert.equal(curve.at(-1)?.chance, 1); + assert.ok(curve.at(-1)?.ends); +}); + +test("la perte du double de la partie 4 vient du moteur, comme gnubg de bureau", async () => { + const match = groupMatches(comeback).matches[0]; + assert.ok(match !== undefined); + const error = summarizeMatch(match).cubeErrors[0]; + assert.ok(error !== undefined); + // Score 2–4 après Crawford, videau au centre à 1, le joueur au trait. + const cube = { + value: 1, + owner: "centered" as const, + match: { length: 5, score: { onRoll: 2, opponent: 4 }, crawford: false }, + }; + const converted = await engine.matchChances(cube, error.advice.equityLoss); + assert.equal(error.loss, converted.ofLoss); + // La même conversion, comparée à gnubg de bureau (2–4 videau 2 chez + // l'adversaire : équité −0,25 → perte −0,0625). + const ref = reference("chances-5-2-4-cube-2").equities[0]; + const owned = await engine.matchChances( + { + value: 2, + owner: "opponent", + match: { length: 5, score: { onRoll: 2, opponent: 4 }, crawford: false }, + }, + ref?.equity ?? 0, + ); + assert.ok(Math.abs(owned.ofLoss - (ref?.loss ?? 1)) < 1e-6); +}); + +// ----------------------------------------------- Phrases et prompt + +test("les phrases du bilan du match", () => { + for (const key of PHRASE_KEYS.filter((k) => k.startsWith("match."))) { + assert.ok((phrases.get(key)?.length ?? 0) > 0, key); + } + assert.equal( + matchCubeSentence(phrases, 8, 2), + "8 décisions de videau ; pour 2 d'entre elles, j'aurais fait autrement.", + ); + assert.equal( + matchCubeSentence(phrases, 3, 0), + "3 décisions de videau, toutes comme je les aurais prises.", + ); + assert.equal( + matchCubeSentence(phrases, 1, 1), + "Une seule décision de videau, et j'aurais fait autrement.", + ); + assert.equal( + matchCubeSentence(phrases, 1, 0), + "Une seule décision de videau, comme je l'aurais prise.", + ); + assert.equal( + matchCubeSentence(phrases, 0, 0), + "Aucune décision de videau à relever sur ce match.", + ); + assert.deepEqual(matchCubeAgreements(phrases, ["missedDouble", "wrongTake", "wrongPass"]), [ + "Prises et refus : aucune différence avec mes choix.", + ]); + const moment = { + game: 3, + gameId: "x", + turn: 6, + side: "player", + roll: [5, 5], + from: 0.24, + to: 0.46, + } as const; + assert.equal( + decisiveSentence(phrases, moment), + "Avec 5-5, vos chances de gagner le match passent de 24\u00a0% à 46\u00a0%. C'est le plus grand écart du match.", + ); + assert.match( + decisiveSentence(phrases, { ...moment, side: "computer", roll: [6, 6] }), + /^Avec le 6-6 de l'ordinateur/, + ); + assert.match(decisiveSentence(phrases, { ...moment, roll: null }), /^Sur ce double/); + for (const text of [ + decisiveSentence(phrases, { ...moment, side: "computer", roll: [6, 6] }), + matchCubeSentence(phrases, 12, 11), + ]) { + assert.ok(text.length < LINE_LIMIT, text); + } + assert.equal(formatMatchLoss(-0.0119700283), "−1,2\u00a0%"); + assert.equal(formatMatchLoss(0), "0,0\u00a0%"); +}); + +test("le prompt « Bilan de mon match » cite le videau en chances de gagner le match", async () => { + const match = groupMatches(comeback).matches[0]; + assert.ok(match !== undefined); + const summary = summarizeMatch(match); + const read = (kind: keyof typeof PROMPT_FILES) => + parsePromptTemplate( + readFileSync(new URL(`docs/prompts/${PROMPT_FILES[kind]}`, root), "utf8"), + ); + const templates = { + move: read("move"), + cube: read("cube"), + summary: read("summary"), + concept: read("concept"), + exercises: read("exercises"), + match: read("match"), + }; + const position = await matchPosition(engine, summary); + const prompt = matchPrompt(templates, phrases, { summary, position }); + assert.ok(!/[{}]/.test(prompt), prompt); + assert.match(prompt, /j'ai gagné le match 5 à 4 en cinq parties, après avoir été mené 0 à 4/); + assert.match(prompt, /- Partie 3 \(0–4, partie Crawford\) : je gagne un gammon, 2 points\./); + assert.match(prompt, /Une seule décision de videau, et j'aurais fait autrement\./); + assert.ok(prompt.includes(`(${CUBE_ERROR_WORDS.wrongDouble.toLowerCase()})`), prompt); + assert.match(prompt, /perte de 1,2\u00a0% de chances de gagner le match/); + // Jamais d'équité pour une perte en match. + assert.ok(!/écart [−+]?\d,\d{3}/.test(prompt), prompt); + assert.match(prompt, /partie 4, coup 1\) : la position avant ma décision/); + assert.equal(position.positionId, "wN1tAwADAAAAAA"); +}); diff --git a/app/tests/progression.test.ts b/app/tests/progression.test.ts index baab703..5c01778 100644 --- a/app/tests/progression.test.ts +++ b/app/tests/progression.test.ts @@ -207,7 +207,14 @@ test("« Créer des exercices » : erreurs, thèmes comptés sur les faits du mo const template = parsePromptTemplate( readFileSync(new URL(`docs/prompts/${PROMPT_FILES.exercises}`, root), "utf8"), ); - const templates = { move: "", cube: "", summary: "", concept: "", exercises: template }; + const templates = { + move: "", + cube: "", + summary: "", + concept: "", + exercises: template, + match: "", + }; const journals: GameJournal[] = []; for (const [seed, choice] of [ [3, 3], diff --git a/app/tests/prompts.test.ts b/app/tests/prompts.test.ts index fe7b40c..d37ddfe 100644 --- a/app/tests/prompts.test.ts +++ b/app/tests/prompts.test.ts @@ -78,6 +78,7 @@ function loadTemplates(): PromptTemplates { summary: read(PROMPT_FILES.summary), concept: read(PROMPT_FILES.concept), exercises: read(PROMPT_FILES.exercises), + match: read(PROMPT_FILES.match), }; } const templates = loadTemplates(); @@ -101,8 +102,8 @@ function assertComplete(prompt: string, position: { positionId: string; matchId: assert.ok(prompt.includes("Réponds en français"), "langue absente"); } -test("les cinq gabarits se lisent dans leur source, avec les repères du cadrage", () => { - assert.equal(PROMPT_KINDS.length, 5); +test("les six gabarits (les cinq du cadrage et le bilan du match) se lisent dans leur source, avec les repères du cadrage", () => { + assert.equal(PROMPT_KINDS.length, 6); for (const kind of PROMPT_KINDS) { const names = placeholders(templates[kind]); for (const name of [ diff --git a/app/tests/steps/analyser-mon-match.steps.ts b/app/tests/steps/analyser-mon-match.steps.ts new file mode 100644 index 0000000..1c035e5 --- /dev/null +++ b/app/tests/steps/analyser-mon-match.steps.ts @@ -0,0 +1,237 @@ +// Étapes du scénario docs/scenarios/analyser-mon-match.feature (ADR 0008) : +// un match en 5 points joué par le domaine sur le vrai moteur, avec des +// dés imposés, où le joueur remonte de 0–4 à 5–4 (app/tests/support/ +// match.ts), analysé comme le fait l'application en arrière-plan ; le bilan +// du match (domain/analysis/match-analysis.ts), ses phrases et ses textes, +// le rattachement des matchs d'avant l'identifiant, l'export SGF. +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { BeforeAll, Given, setDefaultTimeout, Then, When } from "@cucumber/cucumber"; +import { + cubeKindsWithoutError, + formatMatchLoss, + groupMatches, + LINK_DELAY_MS, + type MatchGame, + type MatchSummary, + summarizeMatch, +} from "../../src/domain/analysis/match-analysis.js"; +import { matchCubeAgreements, matchCubeSentence } from "../../src/domain/analysis/phrases.js"; +import type { Engine } from "../../src/domain/game/engine.js"; +import { exportMatchSgf } from "../../src/domain/game/sgf.js"; +import { CUBE_ERROR_WORDS, MATCH_SUMMARY_TEXTS } from "../../src/ui/match-summary-texts.js"; +import { loadPhrases } from "../support/advice.js"; +import { COMEBACK_GAMES, playComebackMatch } from "../support/match.js"; +import { loadNodeEngine } from "../support/node-engine.js"; + +setDefaultTimeout(120_000); + +const root = new URL("../../../../", import.meta.url); +const phrases = loadPhrases(); + +let engine: Engine; +let games: MatchGame[]; +let summary: MatchSummary; +let sgf: string; + +BeforeAll(async () => { + engine = await loadNodeEngine(); +}); + +/** Le bilan du match joué. */ +function summarize(): MatchSummary { + const { matches, loose } = groupMatches(games); + assert.equal(loose.length, 0); + assert.equal(matches.length, 1); + return summarizeMatch(matches[0] as NonNullable<(typeof matches)[0]>); +} + +Given("vous avez joué un match en 5 points, mené 0 à 4 après deux parties", async () => { + games = await playComebackMatch(engine); + const second = summarizeMatch(groupMatches(games.slice(0, 2)).matches[0] as never); + assert.deepEqual(second.match.score, { player: 0, computer: 4 }); +}); + +When("vous gagnez les trois parties suivantes", () => { + assert.equal(games.length, COMEBACK_GAMES.length); + summary = summarize(); + assert.equal(summary.match.over, true); + assert.equal(summary.match.winner, "player"); +}); + +Then( + "le bilan du match dit « Vous gagnez le match » et « 5 à 4, en cinq parties, après avoir été mené 0 à 4. »", + () => { + assert.equal(MATCH_SUMMARY_TEXTS.headline(summary.match), "Vous gagnez le match"); + assert.equal( + MATCH_SUMMARY_TEXTS.sentence(summary), + "5 à 4, en cinq parties, après avoir été mené 0 à 4.", + ); + }, +); + +Then("« Partie par partie » donne les scores 0–2, 0–4, 2–4, 3–4 et 5–4", () => { + assert.deepEqual( + summary.rows.map((row) => + row.scoreAfter === null ? "" : `${row.scoreAfter.player}–${row.scoreAfter.computer}`, + ), + ["0–2", "0–4", "2–4", "3–4", "5–4"], + ); + // La partie 3 est la partie Crawford. + assert.deepEqual( + summary.rows.map((row) => row.crawford), + [false, false, true, false, false], + ); +}); + +Then("la courbe va de 50 % à 100 %, sans coupure d'une partie à l'autre", () => { + const curve = summary.curve; + assert.equal(curve[0]?.chance, 0.5); + assert.equal(curve.at(-1)?.chance, 1); + // Une seule suite de points, tous analysés, une partie après l'autre : + // le premier point d'une partie suit le dernier de la précédente. + assert.ok(curve.every((point) => point.chance !== null)); + const order = curve.map((point) => point.game); + assert.deepEqual( + order, + [...order].sort((a, b) => a - b), + ); + for (let game = 1; game < games.length; game++) { + const last = curve.findLastIndex((point) => point.game === game); + assert.ok(curve[last]?.ends, `la partie ${game} finit sur la courbe`); + assert.equal(curve[last + 1]?.game, game + 1); + } +}); + +Then("ses chances viennent de la table d'équité de match de GNU Backgammon", () => { + // Après la partie 1, à 0–2 : la table de gnubg de bureau + // (tests/reference/analysis/chances-5-0-2.json). + const reference = JSON.parse( + readFileSync(new URL("tests/reference/analysis/chances-5-0-2.json", root), "utf8"), + ) as { at_score: number }; + assert.ok(Math.abs((summary.curve[1]?.chance ?? 0) - reference.at_score) < 1e-6); +}); + +// ------------------------------------------------------------- Le videau + +Given( + "à 2–4, après la partie Crawford, vous avez doublé quand le maître ne l'aurait pas fait", + () => { + const fourth = games[3]?.journal; + const doubled = Object.values(fourth?.advice ?? {}).find( + (a) => a.kind === "cube" && a.action === "double", + ); + assert.ok(doubled !== undefined && doubled.equityLoss < 0); + }, +); + +When("vous ouvrez le bilan du match", () => { + summary = summarize(); +}); + +Then("« Le videau » dit « Une seule décision de videau, et j'aurais fait autrement. »", () => { + assert.equal( + matchCubeSentence(phrases, summary.cubeDecisions, summary.cubeErrors.length), + "Une seule décision de videau, et j'aurais fait autrement.", + ); +}); + +Then( + "il liste « Mauvais double » à la partie 4, coup 1, à 2–4, avec sa perte en chances de gagner le match", + () => { + const [error] = summary.cubeErrors; + assert.ok(error !== undefined && error.loss !== null); + assert.equal(CUBE_ERROR_WORDS[error.kind], "Mauvais double"); + assert.equal( + MATCH_SUMMARY_TEXTS.cubeWhere(error.game, error.turn, "2–4"), + "Partie 4, coup 1, à 2–4", + ); + assert.deepEqual(error.score, { player: 2, computer: 4 }); + // En chances de gagner le match, à une décimale : jamais en équité. + assert.match(formatMatchLoss(error.loss), /^−\d+,\d %$/); + }, +); + +Then("il dit « Prises et refus : aucune différence avec mes choix. »", () => { + assert.deepEqual(matchCubeAgreements(phrases, cubeKindsWithoutError(summary)), [ + "Prises et refus : aucune différence avec mes choix.", + ]); +}); + +Then("la décision à revoir est ce double", () => { + const [error] = summary.cubeErrors; + assert.equal(summary.toReview?.advice.eventId, error?.advice.eventId); + assert.equal(summary.toReview?.game, 4); +}); + +// ----------------------------------------- Les matchs d'avant l'identifiant + +Given("vous avez joué un match en 5 points avant cette version", async () => { + games = await playComebackMatch(engine, { matchId: null, analyse: false }); + assert.ok(games.every((g) => g.journal.events[0]?.type === "GameStarted")); +}); + +When("vous ouvrez « Mes parties »", () => { + // Rien à faire : la liste regroupe les parties à chaque ouverture. +}); + +Then("ses cinq parties forment un seul match, rattaché d'après les scores", () => { + const { matches, loose } = groupMatches(games); + assert.equal(loose.length, 0); + assert.equal(matches.length, 1); + assert.equal(matches[0]?.games.length, 5); + assert.equal(matches[0]?.inferred, true); +}); + +Then( + "si une partie a commencé bien plus tard, elle et les suivantes restent des lignes séparées", + () => { + const late = games.map((g, i) => + i < 3 + ? g + : { + ...g, + startedAt: g.startedAt + LINK_DELAY_MS, + updatedAt: g.updatedAt + LINK_DELAY_MS, + }, + ); + const { matches, loose } = groupMatches(late); + assert.deepEqual( + matches.map((m) => m.games.length), + [3], + ); + assert.equal(loose.length, 2); + }, +); + +// --------------------------------------------------------------- L'export + +When("vous exportez le match", async () => { + sgf = await exportMatchSgf( + engine, + games.map((g) => g.journal), + { playerName: "Vous", computerName: "Ordinateur" }, + ); +}); + +Then( + "le fichier contient les cinq parties, numérotées de 0 à 4, avec le score avant chacune", + () => { + const infos = [ + ...sgf.matchAll(/MI\[length:(\d+)\]\[game:(\d+)\]\[ws:(\d+)\]\[bs:(\d+)\]/g), + ].map((m) => m.slice(1).map(Number)); + // W est l'ordinateur, B le joueur (conventions de gnubg). + assert.deepEqual(infos, [ + [5, 0, 0, 0], + [5, 1, 2, 0], + [5, 2, 4, 0], + [5, 3, 4, 2], + [5, 4, 4, 3], + ]); + assert.equal((sgf.match(/\(;FF\[4\]/g) ?? []).length, 5); + }, +); diff --git a/app/tests/steps/demander-a-une-ia.steps.ts b/app/tests/steps/demander-a-une-ia.steps.ts index b9aa31e..8ad0711 100644 --- a/app/tests/steps/demander-a-une-ia.steps.ts +++ b/app/tests/steps/demander-a-une-ia.steps.ts @@ -57,6 +57,7 @@ const templates: PromptTemplates = { summary: parsePromptTemplate(read(`docs/prompts/${PROMPT_FILES.summary}`)), concept: parsePromptTemplate(read(`docs/prompts/${PROMPT_FILES.concept}`)), exercises: parsePromptTemplate(read(`docs/prompts/${PROMPT_FILES.exercises}`)), + match: parsePromptTemplate(read(`docs/prompts/${PROMPT_FILES.match}`)), }; /** Le joueur au trait : un pion sur son point 6, un sur son point 1 ; diff --git a/app/tests/steps/suivre-ma-progression.steps.ts b/app/tests/steps/suivre-ma-progression.steps.ts index 2395c76..de14b80 100644 --- a/app/tests/steps/suivre-ma-progression.steps.ts +++ b/app/tests/steps/suivre-ma-progression.steps.ts @@ -216,10 +216,14 @@ When("vous demandez des exercices", async () => { const exercises = parsePromptTemplate( readFileSync(new URL(`docs/prompts/${PROMPT_FILES.exercises}`, root), "utf8"), ); - prompt = exercisesPrompt({ move: "", cube: "", summary: "", concept: "", exercises }, phrases, { - journals, - position, - }); + prompt = exercisesPrompt( + { move: "", cube: "", summary: "", concept: "", exercises, match: "" }, + phrases, + { + journals, + position, + }, + ); }); Then("la question cite vos erreurs avec leur coût et ce qui y revient", () => { diff --git a/app/tests/support/match.ts b/app/tests/support/match.ts new file mode 100644 index 0000000..223c1dd --- /dev/null +++ b/app/tests/support/match.ts @@ -0,0 +1,98 @@ +// Un match en 5 points joué par le domaine sur le vrai moteur, avec des dés +// imposés, où le joueur remonte après avoir été mené 0 à 4 (l'exemple de +// Pierre, plan 2026-11-12-analyse-du-match.md) ; pour les tests du bilan du +// match et son scénario (docs/scenarios/analyser-mon-match.feature). +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). +// +// Chaque partie part d'une fin de partie courte, pour que le match se joue +// en quelques secondes : le camp au trait a deux pions sur sa case 1 et les +// sort au premier jet ; l'autre a ses quinze pions hors de son jan +// intérieur (gammon) ou quatorze (partie simple). Le score suit : +// 0–2, 0–4 (la partie suivante est la partie Crawford), 2–4, puis à 2–4 +// après Crawford le joueur double alors que le moteur ne doublerait pas +// (l'ordinateur passe : 3–4), et gagne la dernière partie d'un gammon : 5–4. + +import { missingAnalyses, runAnalysis } from "../../src/domain/analysis/game-analysis.js"; +import type { MatchGame } from "../../src/domain/analysis/match-analysis.js"; +import type { Engine } from "../../src/domain/game/engine.js"; +import type { GameJournal } from "../../src/domain/game/events.js"; +import { Game, type NewGame } from "../../src/domain/game/game.js"; +import { firstGameOf } from "../../src/domain/game/match.js"; +import { fixedDice } from "../../src/domain/game/roll.js"; +import type { Side } from "../../src/domain/game/side.js"; +import { step } from "./play.js"; + +/** Le camp au trait a deux pions sur sa case 1 ; l'autre, quinze pions sur + * ses cases 7 à 12 (Position ID de gnubg). */ +export const GAMMON_ENDING = "wN1tAwADAAAAAA"; + +/** Les parties du match : qui a la main au départ, et si le joueur double. */ +export const COMEBACK_GAMES: readonly { readonly first: Side; readonly double: boolean }[] = [ + { first: "computer", double: false }, + { first: "computer", double: false }, + { first: "player", double: false }, + { first: "player", double: true }, + { first: "player", double: false }, +]; + +/** L'identifiant du match joué. */ +export const COMEBACK_MATCH_ID = "remontee"; + +/** Analyse tout ce qui manque à un journal, comme l'analyse en + * arrière-plan de l'application. */ +export async function analyseAll(engine: Engine, journal: GameJournal): Promise { + let current = journal; + for (;;) { + const task = missingAnalyses(current)[0]; + if (task === undefined) { + return current; + } + current = await runAnalysis(engine, current, task); + } +} + +/** + * Joue le match, partie après partie (la suivante reprend le match que la + * précédente a laissé), et l'analyse si analyse est vrai. Les parties ont + * des dates qui se suivent, une heure d'écart. + */ +export async function playComebackMatch( + engine: Engine, + options: { readonly analyse?: boolean; readonly matchId?: string | null } = {}, +): Promise { + const games: MatchGame[] = []; + const id = options.matchId === undefined ? COMEBACK_MATCH_ID : options.matchId; + let next: NewGame | null = { + level: "beginner", + match: id === null ? firstGameOf(5) : firstGameOf(5, id), + }; + for (const [index, plan] of COMEBACK_GAMES.entries()) { + if (next === null) { + throw new Error(`le match a fini avant la partie ${index + 1}`); + } + const game = Game.start(engine, { + ...next, + dice: fixedDice(Array(40).fill(5)), + setup: { position: GAMMON_ENDING, firstTurn: plan.first }, + }); + for (let i = 0; i < 40 && game.state.phase !== "over"; i++) { + await step(game, engine, { double: plan.double, take: true }); + } + if (game.state.phase !== "over") { + throw new Error(`partie ${index + 1} pas finie`); + } + const journal = + options.analyse === false ? game.journal : await analyseAll(engine, game.journal); + const startedAt = 1_000_000 + index * 3_600_000; + games.push({ + id: `partie-${index + 1}`, + startedAt, + updatedAt: startedAt + 60_000, + journal, + }); + next = game.nextGame; + } + return games; +} diff --git a/app/tests/tools/prompt-sample.ts b/app/tests/tools/prompt-sample.ts index 72b50fc..64647b6 100644 --- a/app/tests/tools/prompt-sample.ts +++ b/app/tests/tools/prompt-sample.ts @@ -37,6 +37,7 @@ const templates: PromptTemplates = { summary: read(PROMPT_FILES.summary), concept: read(PROMPT_FILES.concept), exercises: read(PROMPT_FILES.exercises), + match: read(PROMPT_FILES.match), }; const phrases = loadPhrases(); const engine: Engine = await loadNodeEngine(); diff --git a/docs/maitre/phrases.md b/docs/maitre/phrases.md index edb5aa8..3be8795 100644 --- a/docs/maitre/phrases.md +++ b/docs/maitre/phrases.md @@ -1,7 +1,8 @@ # Les phrases du maître Les mots et les phrases du conseil du maître (étape 1d), du bilan de fin -de partie (étape 1e) et de l'écran de progression (étape 1h), en une seule source (ADR 0008) : `make site` copie ce +de partie (étape 1e), de l'écran de progression (étape 1h) et du bilan du +match (étape 1l), en une seule source (ADR 0008) : `make site` copie ce dossier dans le site publié (`docs/maitre/`), l'application le lit à l'exécution (`app/src/domain/analysis/phrases.ts`), et `make test` rend chaque gabarit @@ -42,6 +43,11 @@ mots entre accolades sont remplis avec les données du moteur : | `{parties}` | le nombre de parties analysées sur la courbe (progression, étape 1h) | | `{debut}` | le taux d'erreur moyen de la plus ancienne moitié de ces parties, en millièmes (14 pour 0,014) | | `{fin}` | le même, sur la plus récente moitié | +| `{decisions}` | le nombre de vos décisions de videau sur le match, avec son nom : « 8 décisions de videau » (bilan du match, étape 1l) | +| `{ecarts}` | le nombre de ces décisions que le maître aurait prises autrement, en chiffres | +| `{sortes}` | les décisions de videau sans écart : « Prises et refus » ou « Doubles » | +| `{roll}` (bilan du match) | le jet du moment décisif, « 5-5 » | +| `{avant}`, `{apres}` | vos chances de gagner le match avant et après le moment décisif, « 24 % » | Un fait (sections `fait.…`) s'ajoute à la phrase seulement si la ligne reste sous 140 caractères. @@ -312,3 +318,64 @@ Les deux moyennes, arrondies, sont égales. Moins de trois parties analysées : pas encore de courbe. - Votre courbe apparaîtra après trois parties. + +## match.videau.ecarts + +Bilan du match (étape 1l), section « Le videau » : plusieurs décisions de +videau, dont au moins une que le moteur aurait prise autrement. Le score et +les pertes, en chances de gagner le match, sont sur les lignes qui suivent. + +- {decisions} ; pour {ecarts} d'entre elles, j'aurais fait autrement. + +## match.videau.un-seul-ecart + +Une seule décision de videau sur le match, et le moteur l'aurait prise +autrement. + +- Une seule décision de videau, et j'aurais fait autrement. + +## match.videau.aucun-ecart + +Plusieurs décisions de videau, toutes comme le moteur. + +- {decisions}, toutes comme je les aurais prises. + +## match.videau.seule + +Une seule décision de videau, comme le moteur. + +- Une seule décision de videau, comme je l'aurais prise. + +## match.videau.aucune + +Aucune décision de videau comptée sur le match (personne n'a doublé, et +jamais doubler n'était à envisager). + +- Aucune décision de videau à relever sur ce match. + +## match.videau.sans-ecart + +Les sortes de décisions sans écart tiennent en une phrase : vos doubles +(doubler, ne pas doubler), ou vos réponses aux doubles (prendre, passer). + +- {sortes} : aucune différence avec mes choix. + +## match.decisif.jet + +Section « Le moment décisif » : le tour qui a fait le plus varier vos +chances de gagner le match, un tour où vous aviez la main. Pas de jugement : +ce peut être un coup de dés. + +- Avec {roll}, vos chances de gagner le match passent de {avant} à {apres}. C'est le plus grand écart du match. + +## match.decisif.jet-ordinateur + +Le même, un tour de l'ordinateur. + +- Avec le {roll} de l'ordinateur, vos chances de gagner le match passent de {avant} à {apres}. C'est le plus grand écart du match. + +## match.decisif.videau + +Le même, un tour fini sur un double passé (sans jet). + +- Sur ce double, vos chances de gagner le match passent de {avant} à {apres}. C'est le plus grand écart du match. diff --git a/docs/prompts/README.md b/docs/prompts/README.md index cda9daf..608229a 100644 --- a/docs/prompts/README.md +++ b/docs/prompts/README.md @@ -24,6 +24,7 @@ d'après le cadrage, **à relire** par Pierre. | [bilan.md](bilan.md) | Bilan de ma partie | Bilan de fin de partie | | [concept.md](concept.md) | Expliquer ce concept | Fiche d'un terme du glossaire | | [exercices.md](exercices.md) | Demander des exercices à une IA | Écran de progression (étape 1h) | +| [match.md](match.md) | Bilan de mon match | Bilan du match (étape 1l) | Chaque prompt contient : diff --git a/docs/prompts/match.md b/docs/prompts/match.md new file mode 100644 index 0000000..da2c107 --- /dev/null +++ b/docs/prompts/match.md @@ -0,0 +1,58 @@ +# Bilan de mon match + +Bouton « Demander à une IA » de la carte « La décision à revoir » du bilan +du match (étape 1l). Texte sous licence CC BY-SA 4.0 (voir +[README.md](README.md)). + +En match, les pertes s'écrivent en chances de gagner le match, à une +décimale, jamais en équité (charte, « Bilan du match ») : ce sont les +chiffres que le bilan affiche. + +Repères propres à ce gabarit : + +| Repère | Ce qu'il devient | +| --- | --- | +| `{ordinateur}` | le niveau de l'ordinateur, « Intermédiaire » | +| `{longueur}` | la longueur du match, « 5 points » | +| `{resultat}` | le résultat du match (ou « match en cours »), le score et le plus grand retard remonté | +| `{parties}` | une ligne par partie : le score au début, qui l'a gagnée, comment et combien | +| `{taux}`, `{decisions}`, `{niveau_jeu}` | votre erreur par décision sur tout le match, le nombre de décisions comptées et le niveau correspondant | +| `{taux_pions}`, `{taux_videau}` | la même mesure, sur les coups et sur les décisions de videau | +| `{chance}`, `{chance_mots}` | la chance par tour de vos dés sur le match, en chiffres et en mots | +| `{videau_decisions}` | la phrase du maître sur vos décisions de videau, puis une ligne par décision qui diffère de la sienne, avec la partie, le coup, le score et la perte en chances de gagner le match | +| `{decisif}` | le moment décisif du match, comme le bilan le dit | +| `{erreurs}` | vos imprécisions et erreurs les plus coûteuses du match, avec leur perte en chances de gagner le match | +| `{position_titre}` | ce que montre la position : la décision à revoir, ou la position finale s'il n'y en a pas | + +## Gabarit + +```text +Tu es un coach de backgammon, bienveillant et précis. {joueur} + +Je viens de jouer un match en {longueur} contre l'ordinateur (niveau {ordinateur}), analysé par GNU Backgammon ({niveau_eval}). +Résultat : {resultat}. +Les parties, avec le score au début de chacune (moi – l'ordinateur) : +{parties} + +Mon erreur par décision sur le match : {taux} sur {decisions}, soit le niveau {niveau_jeu} ; sur les coups : {taux_pions} ; sur le videau : {taux_videau}. +La chance de mes dés par tour : {chance} ({chance_mots}). + +Le videau : +{videau_decisions} + +Le moment décisif : {decisif} + +Mes imprécisions et erreurs les plus coûteuses, en chances de gagner le match : +{erreurs} + +{position_titre} (GNU Backgammon, Position ID : {position_id}, Match ID : {match_id} ; ces identifiants la décrivent du point de vue du joueur qui a la main : {au_trait}). +Elle s'ouvre aussi à cette adresse : {lien} + +{diagramme} + +Score : {score}. Videau : {videau}. + +Ces évaluations font foi : ne les recalcule pas et ne les contredis pas. +À partir de ce bilan, explique-moi surtout mes décisions de videau compte tenu du score du match, puis donne-moi deux conseils concrets pour mes prochains matchs. +Réponds en {langue}, simplement, en moins de 350 mots. +``` diff --git a/docs/scenarios/README.md b/docs/scenarios/README.md index 1848686..31ce44b 100644 --- a/docs/scenarios/README.md +++ b/docs/scenarios/README.md @@ -67,4 +67,5 @@ Règles d'écriture : | [apprendre-les-regles.feature](apprendre-les-regles.feature) | Apprendre les règles avec le tutoriel | Étape 0e.5 | | [suivre-une-lecon.feature](suivre-une-lecon.feature) | Progresser avec les leçons, garder sa progression | Étape 1g | | [suivre-ma-progression.feature](suivre-ma-progression.feature) | Suivre sa progression : courbe du taux d'erreur, parties, exercices | Étape 1h | +| [analyser-mon-match.feature](analyser-mon-match.feature) | Analyser un match entier : courbe des chances de gagner le match, videau, export | Étape 1l | | [installer-l-application.feature](installer-l-application.feature) | Installer l'application | Étape 0e.5 | diff --git a/docs/scenarios/analyser-mon-match.feature b/docs/scenarios/analyser-mon-match.feature new file mode 100644 index 0000000..92c90e4 --- /dev/null +++ b/docs/scenarios/analyser-mon-match.feature @@ -0,0 +1,63 @@ +# language: fr +Fonctionnalité: Analyser mon match + + Le bilan du match regarde le match entier, et pas seulement une partie : + comment le score a évolué, comment vos chances de gagner le match ont + varié d'une partie à l'autre, et surtout vos décisions de videau, qui + dépendent beaucoup du score. Il s'ouvre depuis le bilan de la dernière + partie d'un match (« Bilan du match »), et depuis « Mes parties » et votre + progression, où un match tient en une ligne. En match, les pertes se + comptent en chances de gagner le match, en pourcentage. + + Scénario: Comment lire le bilan de mon match ? + L'en-tête donne le résultat, le score final et le plus grand retard + remonté. La courbe suit vos chances de gagner le match, de 0 à 100 %, + d'un bout à l'autre du match : la fin d'une partie est le début de la + suivante. « Partie par partie » donne le score après chaque partie, + toujours dans l'ordre vous – l'ordinateur ; chaque ligne ouvre le bilan + de la partie. + + Étant donné que vous avez joué un match en 5 points, mené 0 à 4 après deux parties + Quand vous gagnez les trois parties suivantes + Alors le bilan du match dit « Vous gagnez le match » et « 5 à 4, en cinq parties, après avoir été mené 0 à 4. » + Et « Partie par partie » donne les scores 0–2, 0–4, 2–4, 3–4 et 5–4 + Et la courbe va de 50 % à 100 %, sans coupure d'une partie à l'autre + Et ses chances viennent de la table d'équité de match de GNU Backgammon + + Scénario: Comment voir mes décisions de videau sur tout le match ? + « Le videau » compte vos décisions de videau sur toutes les parties et + liste celles où le maître aurait fait autrement : mauvais double, double + manqué, prise fautive, refus fautif. Chaque ligne dit la partie, le coup + et le score, et ce que la décision vous a coûté en chances de gagner le + match ; elle ouvre la décision dans l'analyse. « La décision à revoir » + est la plus coûteuse du match, pions ou videau. + + Étant donné que vous avez joué un match en 5 points, mené 0 à 4 après deux parties + Et qu'à 2–4, après la partie Crawford, vous avez doublé quand le maître ne l'aurait pas fait + Quand vous ouvrez le bilan du match + Alors « Le videau » dit « Une seule décision de videau, et j'aurais fait autrement. » + Et il liste « Mauvais double » à la partie 4, coup 1, à 2–4, avec sa perte en chances de gagner le match + Et il dit « Prises et refus : aucune différence avec mes choix. » + Et la décision à revoir est ce double + + Scénario: Et les matchs que j'ai joués avant cette version ? + Depuis cette version, chaque partie porte l'identifiant de son match. + Les parties jouées avant sont rattachées à leur match quand c'est sûr : + même longueur et même niveau, chaque partie commence au score où la + précédente a fini, et peu après elle. Au moindre doute, elles restent des + lignes séparées dans « Mes parties ». Un match ainsi rattaché le dit. + + Étant donné que vous avez joué un match en 5 points avant cette version + Quand vous ouvrez « Mes parties » + Alors ses cinq parties forment un seul match, rattaché d'après les scores + Mais si une partie a commencé bien plus tard, elle et les suivantes restent des lignes séparées + + Scénario: Comment ouvrir mon match dans GNU Backgammon ? + « Exporter le match (SGF) », en bas du bilan du match, enregistre le + match entier dans un seul fichier : la longueur du match, puis chaque + partie avec le score avant elle. GNU Backgammon l'ouvre par « Ouvrir un + match ». + + Étant donné que vous avez joué un match en 5 points, mené 0 à 4 après deux parties + Quand vous exportez le match + Alors le fichier contient les cinq parties, numérotées de 0 à 4, avec le score avant chacune diff --git a/tests/reference/README.md b/tests/reference/README.md index 302285a..cd8d019 100644 --- a/tests/reference/README.md +++ b/tests/reference/README.md @@ -234,7 +234,7 @@ décision, puis l'analyse. Rien n'est calculé dans le script : les valeurs viennent des enregistrements de la partie analysée et des statistiques que gnubg en tire. -`analyses.json` a trois listes : +`analyses.json` a quatre listes : - `moves` : `position_id`, `match_id`, `dice` et `played`, le coup joué en notation de gnubg (`null` : le meilleur coup selon gnubg, pour les cas qui @@ -243,10 +243,13 @@ gnubg en tire. `no_double` ou `double` pour le joueur au trait, `take` ou `pass` pour son adversaire ; - `levels` : `position_id`, `match_id` et `dice` (`null` : décision de - videau). + videau) ; +- `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` ou -`level`), `gnubg_commit` et `met`, puis, aux niveaux d'analyse 0 et 2 plis +Un fichier de résultat reprend le cas, avec `type` (`move`, `cube`, +`level` ou `chance`), `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 ») : @@ -273,7 +276,17 @@ Un fichier de résultat reprend le cas, avec `type` (`move`, `cube` ou (3 et 4 plis sont trop lents pour la suite de tests), `plies` et `noise` (réglages de gnubg), puis `move`, le coup que joue l'ordinateur de gnubg réglé à ce niveau (commande « play »), ou la décision de videau de gnubg - avec ces réglages, bruit compris. + avec ces réglages, bruit compris ; +- **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 : diff --git a/tests/test_reference.sh b/tests/test_reference.sh index ca49b0c..7ee474d 100644 --- a/tests/test_reference.sh +++ b/tests/test_reference.sh @@ -143,10 +143,15 @@ elif .type == "level" then (if (.levels | length) > 0 and all(.levels[]; (.plies | nombre) and (.noise | nombre) and ((.move | type) == "string" or (.decision | type) == "string")) then empty else "niveaux incomplets" 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)[].id' analyses.json) +mapfile -t analyses < <(jq -r '(.moves + .cubes + .levels + .chances)[].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 From 3b0107af1b520cc9612eb31c44cdea96a29fb27a Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Fri, 13 Nov 2026 00:21:24 +0100 Subject: [PATCH 3/6] =?UTF-8?q?Bilan=20du=20match=20:=20page,=20courbe=20d?= =?UTF-8?q?es=20chances=20de=20gagner=20le=20match,=20listes=20et=20acc?= =?UTF-8?q?=C3=A8s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Page #/matchs//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 --- app/src/domain/analysis/match-analysis.ts | 28 +- app/src/main.ts | 40 +- app/src/ui/analysis-view.ts | 58 ++ app/src/ui/app.ts | 341 +++++++- app/src/ui/ask-ai-texts.ts | 4 + app/src/ui/games-view.ts | 37 +- app/src/ui/haptics.ts | 6 +- app/src/ui/match-line.ts | 110 +++ app/src/ui/match-summary-view.ts | 766 ++++++++++++++++++ app/src/ui/progression-view.ts | 39 +- app/src/ui/prompt-source.ts | 15 + app/src/ui/router.ts | 22 +- app/src/ui/summary-view.ts | 29 + app/tests/match-analysis.test.ts | 19 + app/tests/router.test.ts | 8 + ...007-architecture-et-conventions-de-code.md | 42 + docs/adr/0013-position-dans-l-adresse.md | 34 + docs/etape-1.md | 2 +- docs/glossaire/README.md | 1 + docs/glossaire/chances-de-gagner-le-match.md | 24 + docs/plans/2026-11-12-analyse-du-match.md | 42 - tests/browser.sh | 21 +- tests/browser/match-bilan.mjs | 409 ++++++++++ tests/browser/match.mjs | 4 +- web/app.css | 265 ++++++ web/index.html | 4 + 26 files changed, 2273 insertions(+), 97 deletions(-) create mode 100644 app/src/ui/match-line.ts create mode 100644 app/src/ui/match-summary-view.ts create mode 100644 docs/glossaire/chances-de-gagner-le-match.md delete mode 100644 docs/plans/2026-11-12-analyse-du-match.md create mode 100644 tests/browser/match-bilan.mjs diff --git a/app/src/domain/analysis/match-analysis.ts b/app/src/domain/analysis/match-analysis.ts index 6437327..c05a192 100644 --- a/app/src/domain/analysis/match-analysis.ts +++ b/app/src/domain/analysis/match-analysis.ts @@ -45,11 +45,8 @@ export interface MatchGame { readonly journal: GameJournal; } -/** - * Un match joué : ses parties dans l'ordre, et où il en est. - * - * Glossaire : docs/glossaire/match.md - */ +/** Un match joué : ses parties dans l'ordre, et où il en est (voir + * docs/glossaire/match.md). */ export interface PlayedMatch { /** L'identifiant du match (version 3 des événements) ; pour un match * d'avant, celui de sa première partie. */ @@ -251,9 +248,8 @@ export interface MatchGameRow { /** * Un point de la courbe des chances de gagner le match : le début du * match, puis chaque tour de chaque partie. La fin d'une partie est le - * début de la suivante : la courbe est continue d'une partie à l'autre. - * - * Glossaire : docs/glossaire/chances-de-gagner-le-match.md + * début de la suivante : la courbe est continue d'une partie à l'autre + * (voir docs/glossaire/chances-de-gagner-le-match.md). */ export interface MatchCurvePoint { readonly game: number; @@ -299,7 +295,8 @@ export interface MatchSummary { /** La chance de vos dés sur tout le match. */ readonly luck: LuckSummary; /** Vos décisions de videau comptées (comme le taux d'erreur du - * videau), et celles qui diffèrent du moteur, dans l'ordre du bilan. */ + * videau), et celles qui diffèrent du moteur d'au moins + * CUBE_LOSS_SHOWN, dans l'ordre du bilan. */ readonly cubeDecisions: number; readonly cubeErrors: readonly CubeError[]; readonly decisive: DecisiveMoment | null; @@ -417,7 +414,7 @@ export function summarizeMatch(match: PlayedMatch): MatchSummary { for (const kind of CUBE_ERROR_KINDS) { for (const d of decisions) { const a = d.advice; - if (a.kind === "cube" && a.equityLoss < 0 && CUBE_KIND[a.action] === kind) { + if (a.kind === "cube" && differs(d) && CUBE_KIND[a.action] === kind) { cubeErrors.push({ ...d, kind }); } } @@ -459,6 +456,17 @@ export function summarizeMatch(match: PlayedMatch): MatchSummary { }; } +/** Plus petite perte de chances de gagner le match qui fait d'une décision + * de videau une décision « autre que celle du moteur » : 0,05 %, ce qui + * s'écrit au moins « −0,1 % ». En dessous, gnubg compte un écart, mais la + * ligne dirait « 0,0 % » : elle n'apprendrait rien au joueur. */ +export const CUBE_LOSS_SHOWN = 0.0005; + +/** La décision diffère de celle du moteur, d'une perte qui se voit. */ +function differs(d: MatchDecision): boolean { + return d.advice.equityLoss < 0 && (d.loss === null || d.loss <= -CUBE_LOSS_SHOWN); +} + /** Le tour qui a fait le plus varier les chances de gagner le match, entre * deux points analysés qui se suivent (le premier en cas d'égalité). */ function decisiveMoment(curve: readonly MatchCurvePoint[]): DecisiveMoment | null { diff --git a/app/src/main.ts b/app/src/main.ts index d3eb3d2..35babef 100644 --- a/app/src/main.ts +++ b/app/src/main.ts @@ -10,7 +10,7 @@ import { runAnalysis } from "./domain/analysis/game-analysis.js"; import { Game } from "./domain/game/game.js"; import { linkOf, readPosition } from "./domain/game/position-link.js"; import { levelOf } from "./domain/game/saved-game.js"; -import { exportSgf } from "./domain/game/sgf.js"; +import { exportMatchSgf, exportSgf } from "./domain/game/sgf.js"; import { illustratedMove, MovePractice, @@ -18,7 +18,12 @@ import { tutorialBoard, } from "./domain/learning/tutorial.js"; import { positionBefore } from "./domain/prompts/position.js"; -import { conceptExample, exercisesPosition, summaryPosition } from "./domain/prompts/prompts.js"; +import { + conceptExample, + exercisesPosition, + matchPosition, + summaryPosition, +} from "./domain/prompts/prompts.js"; import { createWasmEngine } from "./engine/wasm-engine.js"; import { type EngineWorker, startEngineWorker } from "./engine/worker-run.js"; import { createGameSession } from "./storage/game-session.js"; @@ -129,17 +134,28 @@ startApp({ if (game === null) { throw new Error("partie introuvable"); } - const started = new Date(game.summary.startedAt); - const two = (n: number) => String(n).padStart(2, "0"); - const date = `${started.getFullYear()}-${two(started.getMonth() + 1)}-${two(started.getDate())}`; + const { date, time } = fileDate(game.summary.startedAt); const text = await exportSgf(engine, game.journal, { playerName: "Vous", computerName: "Ustagammon", date, }); - const time = `${two(started.getHours())}${two(started.getMinutes())}`; return { fileName: `ustagammon-${date}-${time}.sgf`, text }; }, + exportMatchSgf: async (ids) => { + const games = await Promise.all(ids.map((id) => storage().library.load(id))); + const first = games[0]; + if (first === undefined || games.some((g) => g === null)) { + throw new Error("partie du match introuvable"); + } + const { date, time } = fileDate(first?.summary.startedAt ?? 0); + const text = await exportMatchSgf( + engine, + games.flatMap((g) => (g === null ? [] : [g.journal])), + { playerName: "Vous", computerName: "Ustagammon", date }, + ); + return { fileName: `ustagammon-match-${date}-${time}.sgf`, text }; + }, }, cachedBoard: () => settings.loadBoard(), saveBoard: (board) => settings.saveBoard(board), @@ -181,11 +197,23 @@ startApp({ summary: (journal) => summaryPosition(engine, journal), concept: (journal) => conceptExample(engine, journal, ANALYSIS_PLY), exercises: (journals) => exercisesPosition(engine, journals), + match: (summary) => matchPosition(engine, summary), }, startUpdates: (onAvailable) => startUpdates(new URL("../sw.js", import.meta.url), worker.ready, onAvailable), }); +/** La date et l'heure d'un début de partie, pour un nom de fichier SGF : + * AAAA-MM-JJ et HHMM. */ +function fileDate(time: number): { readonly date: string; readonly time: string } { + const started = new Date(time); + const two = (n: number) => String(n).padStart(2, "0"); + return { + date: `${started.getFullYear()}-${two(started.getMonth() + 1)}-${two(started.getDate())}`, + time: `${two(started.getHours())}${two(started.getMinutes())}`, + }; +} + /** La valeur, ou undefined si l'obtenir lève une exception. */ function attempt(get: () => T): T | undefined { try { diff --git a/app/src/ui/analysis-view.ts b/app/src/ui/analysis-view.ts index 3f290fe..f3d5007 100644 --- a/app/src/ui/analysis-view.ts +++ b/app/src/ui/analysis-view.ts @@ -33,6 +33,7 @@ import { formatHalfMoves } from "../domain/game/position.js"; import { VERDICT_ICONS } from "./advice-view.js"; import { askAiLink } from "./ask-ai.js"; import { icon } from "./icons.js"; +import { MATCH_SUMMARY_TEXTS } from "./match-summary-texts.js"; import { MATCH_TEXTS } from "./match-texts.js"; import { boardSvg, createMovePlayer, drawSteps, type MovePlayer } from "./move-board.js"; import { percent, REVIEW_TEXTS, signed } from "./review-texts.js"; @@ -47,6 +48,19 @@ export interface AnalysisData { /** Le coup choisi (null : le coup à revoir, ou le premier). */ readonly turn: number | null; readonly phrases: MasterPhrases | null; + /** Une partie de match (étape 1l) : sa place dans le match, le score + * au début, et les parties d'avant et d'après (null : partie libre). */ + readonly match: AnalysisMatch | null; +} + +/** La place d'une partie dans son match, pour l'en-tête de l'analyse. */ +export interface AnalysisMatch { + readonly number: number; + readonly total: number; + /** « 0–2 », vous – l'ordinateur. */ + readonly score: string; + readonly previous: string | null; + readonly next: string | null; } export interface AnalysisViewOptions { @@ -144,6 +158,29 @@ export function createAnalysisView(options: AnalysisViewOptions): AnalysisView { className: "analysis-title", text: REVIEW_TEXTS.analysisTitle, }); + // Une partie de match (étape 1l) : « ‹ Partie 2 sur 5 · 0–2 › », pour + // passer d'une partie à l'autre. La courbe reste celle de la partie. + const matchNav = element(section, "nav", { + id: "analysis-match", + className: "viewer-nav analysis-match", + }); + matchNav.hidden = true; + const previousGame = element(matchNav, "a", { + id: "analysis-previous-game", + className: "icon-button viewer-step", + }); + previousGame.append(icon("chevron")); + previousGame.setAttribute("aria-label", MATCH_SUMMARY_TEXTS.previousGame); + const matchTitle = element(matchNav, "p", { + id: "analysis-match-title", + className: "viewer-turn", + }); + const nextGame = element(matchNav, "a", { + id: "analysis-next-game", + className: "icon-button viewer-step", + }); + nextGame.append(icon("chevron")); + nextGame.setAttribute("aria-label", MATCH_SUMMARY_TEXTS.nextGame); const message = element(section, "p", { id: "analysis-message", className: "analysis-message", @@ -661,6 +698,27 @@ export function createAnalysisView(options: AnalysisViewOptions): AnalysisView { numbers.hidden = true; return; } + const match = next.match; + matchNav.hidden = match === null; + if (match !== null) { + matchTitle.textContent = MATCH_SUMMARY_TEXTS.analysisHeader( + match.number, + match.total, + match.score, + ); + for (const [link, id] of [ + [previousGame, match.previous], + [nextGame, match.next], + ] as const) { + if (id === null) { + link.removeAttribute("href"); + link.setAttribute("aria-disabled", "true"); + } else { + link.href = routeHash({ screen: "analysis", game: id, turn: null }); + link.removeAttribute("aria-disabled"); + } + } + } turns = gameTurns(next.journal); curve = chanceCurve(next.journal); const summary = summarizeAnalysis(next.journal); diff --git a/app/src/ui/app.ts b/app/src/ui/app.ts index fb9559d..cb9f730 100644 --- a/app/src/ui/app.ts +++ b/app/src/ui/app.ts @@ -28,6 +28,13 @@ import { readyForSummary, summarizeAnalysis, } from "../domain/analysis/game-analysis.js"; +import { + groupMatches, + type MatchGame, + matchOfGame, + type PlayedMatch, + summarizeMatch, +} from "../domain/analysis/match-analysis.js"; import { type MasterPhrases, masterLine, @@ -42,13 +49,13 @@ import { import type { Advice } from "../domain/game/advice.js"; import type { Cube } from "../domain/game/cube.js"; import type { MoveNotation } from "../domain/game/engine.js"; -import type { GameJournal } from "../domain/game/events.js"; +import { currentLine, EMPTY_JOURNAL, type GameJournal } from "../domain/game/events.js"; import type { Game, MoveSteps, NewGame, SideBoards } from "../domain/game/game.js"; import type { HalfMove } from "../domain/game/position.js"; import { type PositionLink, type SharedPosition, setupOf } from "../domain/game/position-link.js"; import type { SavedGameSummary } from "../domain/game/saved-game.js"; import { otherSide, type Side } from "../domain/game/side.js"; -import type { GameState } from "../domain/game/state.js"; +import { type GameState, replay } from "../domain/game/state.js"; import { finishedLessons, LESSON_END, @@ -61,7 +68,7 @@ import { import { ADVICE_TEXTS } from "./advice-texts.js"; import { type Analyse, createAdviceTracker } from "./advice-tracker.js"; import { createAdviceView, VERDICT_ICONS } from "./advice-view.js"; -import { createAnalysisView } from "./analysis-view.js"; +import { type AnalysisMatch, createAnalysisView } from "./analysis-view.js"; import { createPromptView, type PromptResult } from "./ask-ai.js"; import { ASK_AI_TEXTS } from "./ask-ai-texts.js"; import { @@ -86,7 +93,7 @@ import { slideChecker, } from "./board-view.js"; import { GAMES_TEXTS } from "./games-texts.js"; -import { createGamesView, type GamesView } from "./games-view.js"; +import { createGamesView, downloadFile, type GamesView } from "./games-view.js"; import { boardGeometry, type Geometry, type Layout, PORTRAIT_ASPECT } from "./geometry.js"; import { createHaptics, type Vibrate } from "./haptics.js"; import { createHelpView, loadGlossaryEntry } from "./help.js"; @@ -100,6 +107,9 @@ import { LESSON_COUNT, type Lesson, lessonSource, outlineOf, parseLesson } from import { LESSON_TEXTS } from "./lesson-texts.js"; import { lessonCards, nextLessonCard } from "./lessons-model.js"; import { createLessonsView } from "./lessons-view.js"; +import { matchLineOf } from "./match-line.js"; +import { MATCH_SUMMARY_TEXTS, matchScoreText } from "./match-summary-texts.js"; +import { createMatchSummaryView } from "./match-summary-view.js"; import { MATCH_TEXTS } from "./match-texts.js"; import { replacingLink, startNavigation } from "./navigation.js"; import { createNewGameView } from "./new-game-view.js"; @@ -222,6 +232,11 @@ export interface SavedGamesAccess { readonly saveAnalyses: (id: string, journal: GameJournal) => void; readonly remove: (id: string) => Promise; readonly exportSgf: (id: string) => Promise<{ fileName: string; text: string }>; + /** Le fichier SGF d'un match entier, ses parties dans l'ordre (étape + * 1l). */ + readonly exportMatchSgf: ( + ids: readonly string[], + ) => Promise<{ fileName: string; text: string }>; } /** Ce que la vue d'une position demande au domaine et au moteur. */ @@ -289,6 +304,7 @@ export function startApp(options: AppOptions): void { promptVeil: byId("prompt-veil"), analysis: byId("analysis"), progression: byId("progression"), + matchSummary: byId("match-summary"), menuAdvice: byId("menu-advice"), prompt: byId("prompt"), strips: { computer: stripOf("strip-computer"), player: stripOf("strip-player") }, @@ -725,7 +741,7 @@ export function startApp(options: AppOptions): void { show(ui.take, doubled); show(ui.drop, doubled); show(ui.again, over && panelDismissed); - ui.again.textContent = afterGameLabel(game); + ui.again.textContent = afterGameLabel(game, false); show(ui.replay, shownMove !== null); // Le coup de l'ordinateur montré : sa position se copie en lien. show(ui.copyLink, shownMove !== null && currentLink !== null); @@ -947,7 +963,7 @@ export function startApp(options: AppOptions): void { ui.panelText.textContent = end.title; detail.textContent = end.detail; ui.panelSecondary.textContent = TEXTS.reviewGame; - ui.panelPrimary.textContent = afterGameLabel(g); + ui.panelPrimary.textContent = afterGameLabel(g, true); ui.panelSettings.hidden = false; ui.panelVeil.dataset.kind = "over"; } else if (ask) { @@ -1254,10 +1270,19 @@ export function startApp(options: AppOptions): void { /** Après une partie finie : la partie suivante du match s'il continue, * sinon « Rejouer », une nouvelle partie aux mêmes réglages (un match de * même longueur après un match), tout de suite. */ - function afterGame(): void { - if (game !== null) { - newGame(game.nextGame ?? game.rematch); + function afterGame(toMatchSummary: boolean): void { + if (game === null) { + return; } + // Le match fini : le panneau de fin de partie et le bilan de la + // dernière partie mènent au bilan du match (étape 1l) ; « Rejouer » + // reste sous le plateau. + const finished = toMatchSummary ? matchSummaryIdOf(game) : null; + if (finished !== null) { + navigation.go(routeHash({ screen: "matchSummary", match: finished })); + return; + } + newGame(game.nextGame ?? game.rematch); } function showBanner(journal: GameJournal): void { @@ -1332,6 +1357,12 @@ export function startApp(options: AppOptions): void { remove: options.games.remove, exportSgf: options.games.exportSgf, onClose: () => leaveSheet(), + matches: async () => (await loadMatches()).map(matchLineOf), + resumeMatch: (match) => { + if (!busy) { + void resumeMatch(match); + } + }, }); const helpView = createHelpView(ui.helpContent, ui.helpTabs); @@ -1351,11 +1382,13 @@ export function startApp(options: AppOptions): void { // moteur à part ; la partie regardée (bilan, analyse) et son journal. const reviewRunner = createReviewRunner(options.analyseGame); let reviewed: { id: string; journal: GameJournal; game: Game } | null = null; + // Le match de la partie regardée (étape 1l), lu à son ouverture. + let reviewedMatch: { id: string; match: PlayedMatch; number: number } | null = null; const summaryView = createSummaryView({ veil: ui.summaryVeil, close: () => leaveSheet(), - again: () => afterGame(), + again: () => afterGame(true), }); const analysisView = createAnalysisView({ @@ -1474,6 +1507,16 @@ export function startApp(options: AppOptions): void { } case "glossary": return promptSource.concept(route.term ?? "", game?.journal ?? null); + case "matchSummary": { + const match = await loadMatch(route.match); + if (match === null) { + return { message: ASK_AI_TEXTS.missingMatch }; + } + const summary = summarizeMatch(match); + return summary.ready + ? promptSource.match(summary) + : { message: ASK_AI_TEXTS.matchNotReady }; + } case "progression": { // Les parties analysées de l'écran, de la plus ancienne à la // plus récente : rien n'est analysé pour le prompt. @@ -1513,6 +1556,10 @@ export function startApp(options: AppOptions): void { } if (reviewed !== null) { review(reviewed.id, reviewed.journal); + if (reviewedMatch?.id !== id) { + const found = await matchOf(id, reviewed.journal).catch(() => null); + reviewedMatch = found === null ? null : { id, ...found }; + } } showReview(id, false); } @@ -1538,12 +1585,17 @@ export function startApp(options: AppOptions): void { reviewed = { ...reviewed, journal: live?.journal ?? analysed }; } progressionAnalysed(id, live?.journal ?? analysed); + matchAnalysed(id, live?.journal ?? analysed); showReview(id, false); render(); }, - // L'écran de progression attend peut-être cette analyse pour - // lancer celle de la partie suivante. - () => reviewProgression(), + // L'écran de progression ou le bilan du match attendent + // peut-être cette analyse pour lancer celle de la partie + // suivante. + () => { + reviewProgression(); + reviewMatch(); + }, ); } @@ -1553,8 +1605,17 @@ export function startApp(options: AppOptions): void { // relues à chaque visite, avec leurs analyses rangées. Celles qui n'en // ont pas encore sont analysées en arrière-plan, une à une, la plus // récente d'abord ; rien n'est recalculé pour les autres. - const progressionView = createProgressionView({ section: ui.progression }); + const progressionView = createProgressionView({ + section: ui.progression, + resumeMatch: (match) => { + if (!busy) { + void resumeMatch(match); + } + }, + }); let progressionGames: FinishedGame[] | null = null; + // Les matchs, pour leurs lignes (étape 1l). + let progressionMatches: PlayedMatch[] = []; // Chaque lecture a son numéro : une lecture dépassée n'est pas dessinée. let progressionRequest = 0; // Les parties dont l'analyse a été lancée depuis l'ouverture de l'écran. @@ -1596,13 +1657,14 @@ export function startApp(options: AppOptions): void { progressionGames = null; renderProgression(); options.engineReady - .then(() => loadProgression()) + .then(() => Promise.all([loadProgression(), loadMatches()])) .then( - (games) => { + ([games, matches]) => { if (request !== progressionRequest) { return; } progressionGames = games; + progressionMatches = matches; renderProgression(); reviewProgression(); }, @@ -1627,7 +1689,11 @@ export function startApp(options: AppOptions): void { progressionView.render( progressionGames === null ? null - : { entries: progressionEntries(progressionGames), phrases }, + : { + entries: progressionEntries(progressionGames), + matches: progressionMatches.map(matchLineOf), + phrases, + }, ); } @@ -1636,6 +1702,11 @@ export function startApp(options: AppOptions): void { function progressionAnalysed(id: string, journal: GameJournal): void { if (progressionGames?.some((g) => g.id === id)) { progressionGames = progressionGames.map((g) => (g.id === id ? { ...g, journal } : g)); + progressionMatches = progressionMatches.map((m) => + m.games.some((g) => g.id === id) + ? { ...m, games: m.games.map((g) => (g.id === id ? { ...g, journal } : g)) } + : m, + ); renderProgression(); } } @@ -1662,6 +1733,173 @@ export function startApp(options: AppOptions): void { } } + // ------------------------------------------- Bilan du match (1l) + + // L'écran #/matchs//bilan : les parties du match, relues à chaque + // visite avec leurs analyses rangées ; celles qui n'en ont pas assez + // sont analysées en arrière-plan, une à une. + const matchSummaryView = createMatchSummaryView({ + section: ui.matchSummary, + stepsBefore: async (gameId, advice) => { + const viewed = liveGame(gameId) ?? (await options.games.view(gameId)); + return viewed === null + ? null + : viewed.stepsBefore( + advice.eventId, + "player", + advice.kind === "move" ? advice.played.halfMoves : [], + ); + }, + exportSgf: async (summary) => { + downloadFile(await options.games.exportMatchSgf(summary.match.games.map((g) => g.id))); + }, + resume: (summary) => void resumeMatch(summary.match), + vibrate: () => haptic("curveGame"), + }); + let shownMatch: PlayedMatch | null = null; + let matchShownId: string | null = null; + let matchRequest = 0; + // Les parties dont l'analyse a été lancée depuis l'ouverture de l'écran. + const matchTried = new Set(); + + /** Les parties de match enregistrées, avec leur journal (celui de la + * partie à l'écran, s'il s'agit d'elle), réunies en matchs. */ + async function loadMatches(): Promise { + const list = await options.games.list(); + const games = await Promise.all( + list + .filter((summary) => summary.match !== undefined) + .map(async (summary): Promise => { + const journal = + liveGame(summary.id)?.journal ?? (await options.games.journal(summary.id)); + return journal === null + ? null + : { + id: summary.id, + startedAt: summary.startedAt, + updatedAt: summary.updatedAt, + journal, + }; + }), + ); + return groupMatches(games.filter((g): g is MatchGame => g !== null)).matches; + } + + /** Un match par son identifiant (null s'il n'existe pas). */ + async function loadMatch(id: string): Promise { + if (shownMatch?.id === id) { + return shownMatch; + } + return (await loadMatches()).find((m) => m.id === id) ?? null; + } + + /** Le match d'une partie et sa place dans le match (null : partie + * libre, ou partie qu'on ne sait rattacher à aucun match). */ + async function matchOf( + gameId: string, + journal: GameJournal, + ): Promise<{ match: PlayedMatch; number: number } | null> { + const start = journal.events[0]; + if (start?.type !== "GameStarted" || start.match === undefined) { + return null; + } + return matchOfGame(await loadMatches(), gameId); + } + + function showMatchSummary(id: string): void { + const request = ++matchRequest; + matchShownId = id; + matchTried.clear(); + shownMatch = null; + matchSummaryView.show(null); + options.engineReady + .then(() => loadMatches()) + .then( + (matches) => { + if (request !== matchRequest) { + return; + } + shownMatch = matches.find((m) => m.id === id) ?? null; + if (shownMatch === null) { + matchSummaryView.show(null, true); + return; + } + renderMatchSummary(); + reviewMatch(); + }, + () => { + if (request === matchRequest) { + matchSummaryView.show(null, true); + } + }, + ); + if (phrases === null) { + phrasesLoading.then( + () => renderMatchSummary(), + () => undefined, + ); + } + } + + function renderMatchSummary(): void { + if (navigation.route.screen !== "matchSummary" || shownMatch === null) { + return; + } + matchSummaryView.show({ summary: summarizeMatch(shownMatch), phrases }); + // La feuille du prompt attendait l'analyse : elle se met à jour. + const route = navigation.route; + if (isAiRoute(route) && promptView.isOpen && !promptView.ready) { + showPrompt(route); + } + } + + /** Une analyse rangée : le match, s'il est à l'écran, se met à jour. */ + function matchAnalysed(id: string, journal: GameJournal): void { + if (shownMatch?.games.some((g) => g.id === id)) { + shownMatch = { + ...shownMatch, + games: shownMatch.games.map((g) => (g.id === id ? { ...g, journal } : g)), + }; + renderMatchSummary(); + } + } + + /** Lance l'analyse de la prochaine partie du match à l'écran à qui il + * en manque (rien si une analyse tourne déjà : à sa fin, elle rappelle + * cette fonction). */ + function reviewMatch(): void { + if ( + navigation.route.screen !== "matchSummary" || + shownMatch === null || + reviewRunner.running !== null + ) { + return; + } + const next = shownMatch.games.find( + (g) => !matchTried.has(g.id) && missingAnalyses(g.journal).length > 0, + ); + if (next !== undefined) { + matchTried.add(next.id); + review(next.id, next.journal); + } + } + + /** « Reprendre le match » : sa dernière partie à l'écran ; si elle est + * finie, la partie suivante commence. */ + async function resumeMatch(match: PlayedMatch): Promise { + const last = match.games.at(-1); + if (last === undefined || busy) { + return; + } + const other = await options.games.open(last.id); + hideBanner(); + navigation.replace("#/"); + await act(() => showGame(other)); + if (other.state.phase === "over" && other.nextGame !== null) { + afterGame(false); + } + } + /** L'analyse en cours d'une partie qui n'est ni regardée ni à l'écran * s'arrête : le moteur à part revient au conseil du maître. */ function stopForeignReview(): void { @@ -1696,8 +1934,16 @@ export function startApp(options: AppOptions): void { journal: shown.journal, game: shown.game, end: shown.game.state.phase === "over" ? endParts(shown.game) : null, - afterLabel: live === null ? null : afterGameLabel(live), + afterLabel: live === null ? null : afterGameLabel(live, true), phrases, + match: + reviewedMatch?.id === id + ? { + id: reviewedMatch.match.id, + number: reviewedMatch.number, + length: reviewedMatch.match.length, + } + : null, }, ); } else { @@ -1710,11 +1956,30 @@ export function startApp(options: AppOptions): void { game: shown.game, turn: route.turn, phrases, + match: analysisMatch(id), }, ); } } + /** La place de la partie id dans son match, pour l'en-tête de + * l'analyse (null : partie libre). */ + function analysisMatch(id: string): AnalysisMatch | null { + if (reviewedMatch?.id !== id) { + return null; + } + const { match, number } = reviewedMatch; + const games = match.games; + const start = replay(currentLine(games[number - 1]?.journal ?? EMPTY_JOURNAL)).match; + return { + number, + total: games.length, + score: start === null ? "" : matchScoreText(start.score), + previous: games[number - 2]?.id ?? null, + next: games[number]?.id ?? null, + }; + } + /** * La partie à l'écran vient de finir : son analyse part en * arrière-plan, et le bilan remplace le panneau de fin de partie dès @@ -1863,7 +2128,7 @@ export function startApp(options: AppOptions): void { selected = null; void settle(true); }, - again: () => afterGame(), + again: () => afterGame(false), // Le menu a son adresse : l'ouvrir, c'est aller à #/menu (comme son // lien) ; le refermer, revenir à l'écran d'avant. menu: () => { @@ -1907,6 +2172,8 @@ export function startApp(options: AppOptions): void { navigation.leave((r) => r.screen === "lessons"); } else if (route.screen === "progression") { navigation.leave((r) => r.screen === "progression"); + } else if (route.screen === "matchSummary") { + navigation.leave((r) => r.screen === "matchSummary"); } }, }; @@ -1983,7 +2250,7 @@ export function startApp(options: AppOptions): void { if (ui.panelVeil.dataset.kind === "doubled") { actions.take(); } else { - afterGame(); + afterGame(true); } }; // « Changer les réglages » : un lien vers l'écran « Nouvelle partie » ; @@ -2069,6 +2336,7 @@ export function startApp(options: AppOptions): void { const choosing = below.screen === "newGame"; const analysing = below.screen === "analysis"; const progression = below.screen === "progression"; + const matchPage = below.screen === "matchSummary"; const page = help || position || @@ -2078,7 +2346,8 @@ export function startApp(options: AppOptions): void { lesson || choosing || analysing || - progression; + progression || + matchPage; const wasPage = ui.game.hidden; const wasScreen = ui.root.dataset.screen; ui.game.hidden = page; @@ -2090,6 +2359,7 @@ export function startApp(options: AppOptions): void { ui.lesson.hidden = !lesson; ui.analysis.hidden = !analysing; ui.progression.hidden = !progression; + ui.matchSummary.hidden = !matchPage; const opening = choosing && ui.newGameSection.hidden; ui.newGameSection.hidden = !choosing; ui.root.classList.toggle("page-open", page); @@ -2137,6 +2407,15 @@ export function startApp(options: AppOptions): void { if (progression && wasScreen !== "progression") { showProgression(); } + // Le bilan du match aussi (étape 1l) : ses parties ont pu être + // analysées entre-temps. + if (below.screen === "matchSummary") { + if (wasScreen !== "matchSummary" || matchShownId !== below.match) { + showMatchSummary(below.match); + } + } else { + matchShownId = null; + } // La marche à suivre pour installer : une feuille, comme le menu. if (route.screen === "install" && ui.installVeil.hidden) { @@ -2197,7 +2476,7 @@ export function startApp(options: AppOptions): void { () => openReview(id), () => undefined, ); - } else if (route.screen !== "progression") { + } else if (route.screen !== "progression" && route.screen !== "matchSummary") { stopForeignReview(); } if (route.screen === "games") { @@ -3150,11 +3429,25 @@ function bandText(prompt: string, crawford: boolean): string { } /** Le bouton qui suit une partie finie : « Partie suivante » dans un match - * qui continue, sinon « Rejouer » (mêmes réglages). */ -function afterGameLabel(game: Game): string { + * qui continue, sinon « Rejouer » (mêmes réglages) ; à la fin d'un match, + * dans le panneau de fin de partie et le bilan (toMatchSummary), « Bilan du + * match » (étape 1l). */ +function afterGameLabel(game: Game, toMatchSummary: boolean): string { + if (toMatchSummary && matchSummaryIdOf(game) !== null) { + return MATCH_SUMMARY_TEXTS.seeMatchSummary; + } return game.nextGame === null ? MATCH_TEXTS.replay : MATCH_TEXTS.nextGame; } +/** L'identifiant du match que cette partie vient de finir (null : partie + * libre, match qui continue, ou match d'avant l'identifiant). */ +function matchSummaryIdOf(game: Game): string | null { + const state = game.state; + return state.phase === "over" && state.matchAfter?.over === true + ? (state.match?.id ?? null) + : null; +} + /** Le résultat d'une partie finie, sur une ligne (consigne, une fois le * panneau fermé). */ function resultText(game: Game): string { diff --git a/app/src/ui/ask-ai-texts.ts b/app/src/ui/ask-ai-texts.ts index beb8c33..58d8cd0 100644 --- a/app/src/ui/ask-ai-texts.ts +++ b/app/src/ui/ask-ai-texts.ts @@ -22,11 +22,15 @@ export const ASK_AI_TEXTS = { analysis: "Analyse", glossary: "Glossaire", progression: "Progression", + matchSummary: "Bilan du match", }, failed: "Le prompt n'a pas pu être préparé.", noAdvice: "Pas de prompt pour cette décision : le maître ne l'a pas encore analysée.", notReady: "Le maître analyse encore la partie : le prompt sera prêt avec le bilan.", missingGame: "Cette partie n'est plus sur ce téléphone.", + missingMatch: "Ce match n'est plus sur ce téléphone.", + matchNotReady: + "Le maître analyse encore les parties du match : le prompt sera prêt avec le bilan.", missingTerm: "Ce terme n'est pas dans le glossaire.", noAnalysedGame: "Pas encore d'exercices : le maître n'a analysé aucune partie terminée. Ils seront prêts avec la première.", diff --git a/app/src/ui/games-view.ts b/app/src/ui/games-view.ts index 191208a..b053d9f 100644 --- a/app/src/ui/games-view.ts +++ b/app/src/ui/games-view.ts @@ -13,11 +13,13 @@ // (#/parties/, ses branches dépliées) : l'écran de jeu l'ouvre et la // ferme selon l'adresse (show, hide), et « Branches » est un vrai lien. +import type { PlayedMatch } from "../domain/analysis/match-analysis.js"; import { branches } from "../domain/game/branches.js"; import type { GameJournal } from "../domain/game/events.js"; import type { SavedGameSummary } from "../domain/game/saved-game.js"; import { GAMES_TEXTS } from "./games-texts.js"; import { icon } from "./icons.js"; +import { type MatchLine, renderMatchLine } from "./match-line.js"; import { routeHash } from "./router.js"; export interface GamesViewOptions { @@ -36,6 +38,11 @@ export interface GamesViewOptions { /** La croix ou le voile touché : quitter la feuille (l'écran de jeu * change d'adresse, puis appelle hide). */ readonly onClose: () => void; + /** Les matchs (étape 1l) : chacun tient en une ligne, à la place de + * ses parties. */ + readonly matches: () => Promise; + /** « Reprendre » sur la ligne d'un match en cours. */ + readonly resumeMatch: (match: PlayedMatch) => void; } export interface GamesView { @@ -93,13 +100,35 @@ export function createGamesView(options: GamesViewOptions): GamesView { }; async function render(): Promise { - const games = await options.list(); - list.replaceChildren(...games.map((game) => gameItem(game, game.id === options.shownId()))); + const [games, matches] = await Promise.all([ + options.list(), + options.matches().catch((): readonly MatchLine[] => []), + ]); + // Un match tient en une ligne, à la place de ses parties, à la date + // de sa dernière action ; les parties libres gardent la leur. + const inMatch = new Set(matches.flatMap((line) => line.match.games.map((g) => g.id))); + const items = [ + ...games + .filter((game) => !inMatch.has(game.id)) + .map((game) => ({ + at: game.updatedAt, + item: () => gameItem(game, game.id === options.shownId()), + })), + ...matches.map((line) => ({ at: line.match.updatedAt, item: () => matchItem(line) })), + ].sort((a, b) => b.at - a.at); + list.replaceChildren(...items.map((entry) => entry.item())); if (games.length === 0) { message.textContent = GAMES_TEXTS.empty; } } + function matchItem(line: MatchLine): HTMLElement { + const item = element("li", "games-item games-match"); + item.dataset.match = line.match.id; + renderMatchLine(item, line, () => options.resumeMatch(line.match)); + return item; + } + function gameItem(game: SavedGameSummary, shown: boolean): HTMLElement { const item = element("li", "games-item"); item.dataset.id = game.id; @@ -126,7 +155,7 @@ export function createGamesView(options: GamesViewOptions): GamesView { ...(game.status === "over" ? [summaryLink(game.id)] : []), button( GAMES_TEXTS.exportSgf, - run(async () => download(await options.exportSgf(game.id))), + run(async () => downloadFile(await options.exportSgf(game.id))), "secondary", "export", ), @@ -276,7 +305,7 @@ function button( } /** Fait télécharger un fichier texte au navigateur. */ -function download(file: { fileName: string; text: string }): void { +export function downloadFile(file: { fileName: string; text: string }): void { const url = URL.createObjectURL(new Blob([file.text], { type: "application/x-go-sgf" })); const link = element("a"); link.href = url; diff --git a/app/src/ui/haptics.ts b/app/src/ui/haptics.ts index 235e49e..e604eb5 100644 --- a/app/src/ui/haptics.ts +++ b/app/src/ui/haptics.ts @@ -10,7 +10,10 @@ export type HapticEvent = | "checkerHit" | "computerDoubles" | "gameWon" - | "gameLost"; + | "gameLost" + /** Bilan du match : le doigt passe d'une partie à l'autre sur la + * courbe (étape 1l). */ + | "curveGame"; /** Motifs en millisecondes (vibration, pause, vibration…). */ export const HAPTIC_PATTERNS: Readonly> = { @@ -19,6 +22,7 @@ export const HAPTIC_PATTERNS: Readonly> = computerDoubles: [40, 60, 40], gameWon: [30, 50, 30, 50, 60], gameLost: [60], + curveGame: [8], }; /** navigator.vibrate, s'il existe. */ diff --git a/app/src/ui/match-line.ts b/app/src/ui/match-line.ts new file mode 100644 index 0000000..ec95387 --- /dev/null +++ b/app/src/ui/match-line.ts @@ -0,0 +1,110 @@ +// Un match en une ligne, dans « Mes parties » et la progression (étape 1l ; +// charte, ecrans-etape-1.md, « Bilan du match », accès) : le titre (« Match +// en 5 points · gagné 5–4 »), un trait par partie, la date, le nombre de +// parties et le niveau, le taux d'erreur du match à droite ; la ligne ouvre +// le bilan du match. Un match en cours a « Reprendre » à côté. +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). + +import { readyForSummary } from "../domain/analysis/game-analysis.js"; +import { type PlayedMatch, summarizeMatch } from "../domain/analysis/match-analysis.js"; +import { errorRateMillis } from "../domain/analysis/progression.js"; +import { currentLine } from "../domain/game/events.js"; +import { computerLevelOf } from "../domain/game/level.js"; +import { replay } from "../domain/game/state.js"; +import { icon } from "./icons.js"; +import { MATCH_SUMMARY_TEXTS as T } from "./match-summary-texts.js"; +import { MATCH_TEXTS } from "./match-texts.js"; +import { PROGRESSION_TEXTS } from "./progression-texts.js"; +import { routeHash } from "./router.js"; + +/** Un match et son taux d'erreur (null : analyse pas encore finie). */ +export interface MatchLine { + readonly match: PlayedMatch; + readonly errorRate: number | null; +} + +/** La ligne d'un match : son taux d'erreur, celui du bilan du match, dès + * que toutes ses parties ont leur bilan. */ +export function matchLineOf(match: PlayedMatch): MatchLine { + const ready = match.games.every((g) => readyForSummary(g.journal)); + return { match, errorRate: ready ? summarizeMatch(match).errorRate.perDecision : null }; +} + +/** Dessine la ligne d'un match dans parent ; resume : « Reprendre », pour + * un match en cours. */ +export function renderMatchLine( + parent: HTMLElement, + line: MatchLine, + resume: (() => void) | null, +): HTMLElement { + const { match } = line; + const box = document.createElement("div"); + box.className = "match-line"; + box.dataset.match = match.id; + const link = document.createElement("a"); + link.className = "progression-game match-line-link"; + link.href = routeHash({ screen: "matchSummary", match: match.id }); + const text = document.createElement("span"); + text.className = "progression-text"; + const title = document.createElement("strong"); + title.textContent = T.listTitle(match); + const strokes = document.createElement("span"); + strokes.className = "match-strokes"; + strokes.setAttribute("aria-hidden", "true"); + for (const game of match.games) { + const state = replay(currentLine(game.journal)); + const stroke = document.createElement("span"); + stroke.className = + state.result === null + ? "match-stroke" + : `match-stroke ${state.result.winner === "player" ? "won" : "lost"}`; + strokes.append(stroke); + } + if (!match.over) { + const next = document.createElement("span"); + next.className = "match-stroke next"; + strokes.append(next); + } + const level = computerLevelOf(match.level); + const caption = document.createElement("span"); + caption.className = "caption"; + caption.textContent = [ + T.listCaption( + PROGRESSION_TEXTS.date(match.startedAt), + match.games.length, + level === null ? match.level : MATCH_TEXTS.levels[level].name, + ), + ...(match.inferred ? [T.listInferred] : []), + ].join(" · "); + text.append(title, strokes, caption); + const rate = document.createElement("span"); + rate.className = "progression-rate"; + if (line.errorRate === null) { + rate.classList.add("pending"); + rate.textContent = PROGRESSION_TEXTS.rateLoading; + } else { + const millis = errorRateMillis(line.errorRate); + rate.dataset.rate = String(line.errorRate); + const strong = document.createElement("strong"); + strong.textContent = T.errorRate(millis); + const unit = document.createElement("span"); + unit.className = "caption"; + unit.textContent = PROGRESSION_TEXTS.rateLabel; + rate.append(strong, unit); + rate.setAttribute("aria-label", T.errorRateLabel(millis)); + } + link.append(text, rate, icon("chevron")); + box.append(link); + if (!match.over && resume !== null) { + const button = document.createElement("button"); + button.type = "button"; + button.className = "match-resume"; + button.textContent = T.resume; + button.onclick = () => resume(); + box.append(button); + } + parent.append(box); + return box; +} diff --git a/app/src/ui/match-summary-view.ts b/app/src/ui/match-summary-view.ts new file mode 100644 index 0000000..dbc028a --- /dev/null +++ b/app/src/ui/match-summary-view.ts @@ -0,0 +1,766 @@ +// Le bilan d'un match entier (#/matchs//bilan, étape 1l ; charte, +// ecrans-etape-1.md, « Bilan du match ») : une page qui défile. L'en-tête, +// la courbe des chances de gagner le match à travers toutes les parties, +// « Partie par partie », votre jeu sur le match, le videau, le moment +// décisif, la décision à revoir, l'export SGF, puis la barre d'actions. +// +// Copyright (C) 2026 les auteurs d'Ustagammon. +// Licence : GPLv3 ou ultérieure (voir LICENSE). +// +// Tout ce qu'elle affiche vient du bilan du match (domain/analysis/ +// match-analysis.ts), donc des analyses du moteur rangées dans chaque +// partie, et des phrases du maître. La courbe est dessinée à la main en +// SVG ; la bulle de lecture y est un lien SVG vers la décision (pas de +// style en ligne : CSP stricte). + +import { + cubeKindsWithoutError, + formatMatchLoss, + type MatchCurvePoint, + type MatchSummary, +} from "../domain/analysis/match-analysis.js"; +import { + decisiveSentence, + diceWords, + type MasterPhrases, + masterWords, + matchCubeAgreements, + matchCubeSentence, + nothingToReview, +} from "../domain/analysis/phrases.js"; +import { errorRateMillis } from "../domain/analysis/progression.js"; +import type { Advice } from "../domain/game/advice.js"; +import type { MoveSteps } from "../domain/game/game.js"; +import { COMPUTER_LEVELS } from "../domain/game/level.js"; +import { VERDICT_ICONS } from "./advice-view.js"; +import { askAiLink } from "./ask-ai.js"; +import { icon } from "./icons.js"; +import { + CUBE_ERROR_WORDS, + matchScoreText, + MATCH_SUMMARY_TEXTS as T, +} from "./match-summary-texts.js"; +import { MATCH_TEXTS } from "./match-texts.js"; +import { boardSvg, drawSteps } from "./move-board.js"; +import { percent, REVIEW_TEXTS } from "./review-texts.js"; +import { routeHash } from "./router.js"; + +/** Ce que montre la page. */ +export interface MatchSummaryData { + readonly summary: MatchSummary; + readonly phrases: MasterPhrases | null; +} + +export interface MatchSummaryViewOptions { + /** La page (index.html) ; son contenu est construit ici. */ + readonly section: HTMLElement; + /** Le plateau d'avant une décision d'une partie du match. */ + readonly stepsBefore: (gameId: string, advice: Advice) => Promise; + /** « Exporter le match (SGF) ». */ + readonly exportSgf: (summary: MatchSummary) => Promise; + /** « Reprendre le match » : la dernière partie, à l'écran. */ + readonly resume: (summary: MatchSummary) => void; + /** Une vibration légère, à chaque changement de partie sur la courbe. */ + readonly vibrate: () => void; +} + +export interface MatchSummaryView { + /** Dessine la page (null : le match se lit ; missing : il n'existe + * pas). */ + show(data: MatchSummaryData | null, missing?: boolean): void; + hide(): void; +} + +const SVG_NS = "http://www.w3.org/2000/svg"; +/** Hauteur de la courbe (au moins 150 px de zone tactile, charte) et ses + * marges : les scores au-dessus, les noms des parties en dessous. */ +const CURVE_HEIGHT = 196; +const PAD = { left: 40, right: 12, top: 26, bottom: 26 }; +const BUBBLE = { width: 210, height: 44 }; + +function element( + parent: HTMLElement, + tag: K, + options: { id?: string; className?: string; text?: string } = {}, +): HTMLElementTagNameMap[K] { + const child = document.createElement(tag); + if (options.id !== undefined) { + child.id = options.id; + } + if (options.className !== undefined) { + child.className = options.className; + } + if (options.text !== undefined) { + child.textContent = options.text; + } + parent.append(child); + return child; +} + +function svgElement( + parent: Element, + tag: K, + attributes: Record, +): SVGElementTagNameMap[K] { + const child = document.createElementNS(SVG_NS, tag); + for (const [name, value] of Object.entries(attributes)) { + child.setAttribute(name, String(value)); + } + parent.append(child); + return child; +} + +/** L'adresse d'une décision : l'analyse de sa partie, sur son coup. */ +function decisionHref(gameId: string, turn: number | null): string { + return routeHash({ screen: "analysis", game: gameId, turn }); +} + +const DICE_SIDE = { + veryLucky: "for-2", + lucky: "for-1", + none: "even", + unlucky: "against-1", + veryUnlucky: "against-2", +} as const; + +export function createMatchSummaryView(options: MatchSummaryViewOptions): MatchSummaryView { + const { section } = options; + let drawn = ""; + let redrawCurve: (() => void) | null = null; + window.addEventListener("resize", () => { + if (!section.hidden) { + redrawCurve?.(); + } + }); + + function show(data: MatchSummaryData | null, missing = false): void { + const key = + data === null + ? `none|${missing}` + : JSON.stringify({ + id: data.summary.match.id, + phrases: data.phrases !== null, + ready: data.summary.ready, + games: data.summary.match.games.map((g) => g.id), + curve: data.summary.curve.map((p) => p.chance), + errors: data.summary.cubeErrors.map((e) => e.loss), + review: data.summary.toReview?.advice.eventId ?? null, + rate: data.summary.errorRate.perDecision, + }); + if (key === drawn) { + return; + } + drawn = key; + section.replaceChildren(); + redrawCurve = null; + delete section.dataset.ready; + if (data === null) { + element(section, "h1", { className: "progression-title", text: T.title }); + const status = element(section, "p", { + id: "match-status", + className: "progression-summary", + text: missing ? T.missing : T.loading, + }); + status.setAttribute("role", "status"); + return; + } + render(data); + } + + function render(data: MatchSummaryData): void { + const { summary, phrases } = data; + const { match } = summary; + section.dataset.match = match.id; + // Paysage : deux colonnes (charte) ; en portrait, l'une sous l'autre. + const left = element(section, "div", { className: "match-column match-main" }); + const right = element(section, "div", { className: "match-column match-side" }); + + // 1. L'en-tête. + const head = element(left, "header", { className: "match-head" }); + element(head, "p", { + id: "match-overline", + className: "overline", + text: T.overline(match), + }); + element(head, "h1", { + id: "match-title", + className: "progression-title", + text: T.headline(match), + }); + element(head, "p", { + id: "match-sentence", + className: "progression-summary", + text: T.sentence(summary), + }); + if (match.inferred) { + element(head, "p", { id: "match-inferred", className: "caption", text: T.inferred }); + } + if (!summary.ready) { + element(head, "p", { + id: "match-analysing", + className: "muted", + text: T.analysing, + }).setAttribute("role", "status"); + } + + // 2. La courbe. + curveCard(left, summary); + + // 3. Partie par partie. + gamesCard(left, summary); + + // 4. Votre jeu sur le match. + if (phrases !== null) { + playCard(right, summary, phrases); + cubeCard(right, summary, phrases); + decisiveCard(right, summary, phrases); + reviewCard(right, summary, phrases); + } + + // 8. L'export, puis la barre d'actions. + const exportBox = element(right, "p", { className: "match-export" }); + const exportButton = element(exportBox, "button", { + id: "match-export", + className: "link-button", + text: T.exportSgf, + }); + exportButton.type = "button"; + const exportHint = element(exportBox, "span", { + className: "caption", + text: ` ${T.exportHint}`, + }); + exportButton.onclick = () => { + exportHint.textContent = ` ${T.exportHint}`; + options.exportSgf(summary).catch((error: unknown) => { + exportHint.textContent = ` ${T.exportFailed(error instanceof Error ? error.message : String(error))}`; + }); + }; + const bar = element(right, "div", { className: "panel-actions match-actions" }); + const firstGame = match.games[0]; + if (firstGame !== undefined) { + const again = element(bar, "a", { + id: "match-review", + className: "button secondary", + text: T.reviewMatch, + }); + again.href = decisionHref(firstGame.id, 1); + } + if (match.over) { + const start = element(bar, "a", { + id: "match-primary", + className: "button", + text: T.newMatch, + }); + start.href = routeHash({ screen: "newGame" }); + } else { + const resume = element(bar, "button", { + id: "match-primary", + text: T.resumeMatch, + }); + resume.type = "button"; + resume.onclick = () => options.resume(summary); + } + section.dataset.ready = String(summary.ready); + } + + // ------------------------------------------------------------ Courbe + + function curveCard(parent: HTMLElement, summary: MatchSummary): void { + const card = element(parent, "section", { + id: "match-curve-card", + className: "analysis-card match-curve-card", + }); + element(card, "h2", { className: "overline", text: T.curveTitle }); + const svg = document.createElementNS(SVG_NS, "svg"); + svg.id = "match-curve"; + svg.setAttribute("class", "analysis-curve match-curve"); + svg.setAttribute("role", "img"); + svg.setAttribute("tabindex", "0"); + card.append(svg); + const legend = element(card, "ul", { className: "match-legend" }); + for (const [mark, text] of [ + ["decisive", T.legendDecisive], + ["review", T.legendReview], + [summary.match.winner === "player" ? "end won" : "end", T.legendEnd], + ] as const) { + const item = element(legend, "li"); + const dot = element(item, "span", { className: `match-mark ${mark}` }); + dot.setAttribute("aria-hidden", "true"); + item.append(text); + } + const points = summary.curve; + const known = points.filter((p) => p.chance !== null); + if (known.length < points.length) { + element(card, "p", { className: "caption", text: T.pending }); + } + const chances = known.map((p) => p.chance as number); + const decisive = summary.decisive; + svg.setAttribute( + "aria-label", + known.length === 0 + ? T.pending + : T.curveLabel( + percent(chances[0] ?? 0.5), + percent(Math.min(...chances)), + percent(chances.at(-1) ?? 0.5), + decisive === null ? "" : T.curveDecisive(decisive.game, decisive.turn), + ), + ); + svg.dataset.points = JSON.stringify(points.map((p) => [p.game, p.turn, p.chance])); + let selected: number | null = null; + const draw = () => drawCurve(svg, summary, selected); + redrawCurve = draw; + draw(); + + // Lecture au doigt : glisser choisit le point sous le doigt (une + // vibration légère à chaque changement de partie) ; lâcher garde la + // bulle, qui ouvre la décision. + const indexAt = (clientX: number): number => { + const box = svg.getBoundingClientRect(); + const inner = Math.max(1, box.width - PAD.left - PAD.right); + const step = points.length > 1 ? inner / (points.length - 1) : inner; + const i = Math.round((clientX - box.left - PAD.left) / step); + return Math.min(points.length - 1, Math.max(0, i)); + }; + const choose = (index: number) => { + if (index === selected) { + return; + } + const before = selected === null ? null : points[selected]?.game; + selected = index; + if (before !== undefined && before !== null && before !== points[index]?.game) { + options.vibrate(); + } + draw(); + }; + let dragging = false; + svg.addEventListener("pointerdown", (event) => { + if ((event.target as Element).closest(".match-bubble") !== null) { + return; + } + dragging = true; + svg.setPointerCapture?.(event.pointerId); + choose(indexAt(event.clientX)); + }); + svg.addEventListener("pointermove", (event) => { + if (dragging) { + choose(indexAt(event.clientX)); + } + }); + for (const end of ["pointerup", "pointercancel"] as const) { + svg.addEventListener(end, () => { + dragging = false; + }); + } + svg.addEventListener("keydown", (event) => { + if (event.key === "ArrowLeft" || event.key === "ArrowRight") { + event.preventDefault(); + event.stopPropagation(); + const from = selected ?? (event.key === "ArrowLeft" ? points.length : -1); + choose( + Math.min( + points.length - 1, + Math.max(0, from + (event.key === "ArrowLeft" ? -1 : 1)), + ), + ); + } else if (event.key === "Enter" && selected !== null) { + const point = points[selected]; + if (point !== undefined) { + event.preventDefault(); + location.hash = decisionHref(point.gameId, point.turn); + } + } + }); + } + + // --------------------------------------------------- Partie par partie + + function gamesCard(parent: HTMLElement, summary: MatchSummary): void { + const card = element(parent, "section", { id: "match-games", className: "match-games" }); + element(card, "h2", { className: "overline", text: T.gamesTitle }); + const list = element(card, "ol", { className: "progression-list match-game-list" }); + for (const row of summary.rows) { + const li = element(list, "li", { className: "progression-item" }); + li.dataset.game = String(row.number); + const link = element(li, "a", { className: "progression-game match-game" }); + link.href = routeHash({ screen: "summary", game: row.id }); + const result = T.gameResult(row.result, row.cube); + const points = T.gamePoints(row.result); + const after = row.scoreAfter === null ? "" : matchScoreText(row.scoreAfter); + link.setAttribute("aria-label", T.gameRowLabel(row.number, result, points, after)); + const text = element(link, "span", { className: "progression-text" }); + element(text, "strong", { + text: `${T.gameRow(row.number)}${row.crawford ? ` · ${T.crawford}` : ""}`, + }); + element(text, "span", { + className: "caption", + text: points === "" ? result : `${result} · ${points}`, + }); + const score = element(link, "span", { className: "match-game-score", text: after }); + score.setAttribute("aria-hidden", "true"); + link.append(icon("chevron")); + } + element(card, "p", { className: "caption", text: T.scoreReminder }); + } + + // ------------------------------------------------- Votre jeu + + function playCard(parent: HTMLElement, summary: MatchSummary, phrases: MasterPhrases): void { + const card = element(parent, "section", { id: "match-play", className: "analysis-card" }); + element(card, "h2", { className: "overline", text: T.playTitle }); + const tiles = element(card, "div", { className: "match-tiles" }); + for (const [key, rate] of [ + ["all", summary.errorRate], + ["chequer", summary.chequer], + ["cube", summary.cube], + ] as const) { + const tile = element(tiles, "div", { className: "match-tile" }); + tile.dataset.tile = key; + element(tile, "span", { className: "caption", text: T.tiles[key] }); + element(tile, "strong", { + text: rate.decisions === 0 ? "–" : String(errorRateMillis(rate.perDecision)), + }); + element(tile, "span", { + className: "caption", + text: rate.decisions === 0 ? T.tileNone : T.tileUnit, + }); + } + const box = element(card, "div", { className: "summary-gauges" }); + const level = summary.errorRate.level; + const levelName = MATCH_TEXTS.levels[level].name; + const play = element(box, "div", { id: "match-gauge-play", className: "gauge" }); + play.setAttribute("aria-label", REVIEW_TEXTS.playGauge(levelName)); + play.setAttribute("role", "img"); + element(play, "span", { className: "gauge-name", text: REVIEW_TEXTS.yourPlay }); + const track = element(play, "span", { className: "gauge-track" }); + element(track, "span", { + className: `gauge-fill level-${COMPUTER_LEVELS.indexOf(level) + 1}`, + }); + element(play, "span", { className: "gauge-value", text: levelName }); + const words = diceWords(phrases, summary.luck.rating); + const dice = element(box, "div", { id: "match-gauge-dice", className: "gauge" }); + dice.setAttribute("aria-label", REVIEW_TEXTS.diceGauge(words)); + dice.setAttribute("role", "img"); + element(dice, "span", { className: "gauge-name", text: REVIEW_TEXTS.theDice }); + const centred = element(dice, "span", { className: "gauge-track centred" }); + element(centred, "span", { + className: `gauge-fill dice ${DICE_SIDE[summary.luck.rating]}`, + }); + element(dice, "span", { className: "gauge-value", text: words }); + } + + // ------------------------------------------------------- Le videau + + function cubeCard(parent: HTMLElement, summary: MatchSummary, phrases: MasterPhrases): void { + const card = element(parent, "section", { id: "match-cube", className: "analysis-card" }); + element(card, "h2", { className: "overline", text: T.cubeTitle }); + element(card, "p", { + id: "match-cube-sentence", + className: "match-sentence", + text: matchCubeSentence(phrases, summary.cubeDecisions, summary.cubeErrors.length), + }); + if (summary.cubeErrors.length > 0) { + const list = element(card, "ul", { className: "match-cube-list" }); + for (const error of summary.cubeErrors) { + const li = element(list, "li", { className: "match-cube-item" }); + li.dataset.kind = error.kind; + const link = element(li, "a", { className: "match-cube-row" }); + link.href = decisionHref(error.gameId, error.turn); + const where = T.cubeWhere(error.game, error.turn, matchScoreText(error.score)); + const loss = error.loss === null ? T.cubeLossPending : formatMatchLoss(error.loss); + link.setAttribute( + "aria-label", + T.cubeRowLabel(CUBE_ERROR_WORDS[error.kind], where, loss), + ); + const text = element(link, "span", { className: "progression-text" }); + element(text, "strong", { text: CUBE_ERROR_WORDS[error.kind] }); + element(text, "span", { className: "caption", text: where }); + const value = element(link, "span", { className: "match-loss", text: loss }); + value.dataset.verdict = error.advice.skill === "none" ? "good" : error.advice.skill; + value.setAttribute("aria-hidden", "true"); + link.append(icon("chevron")); + } + } + for (const sentence of matchCubeAgreements(phrases, cubeKindsWithoutError(summary))) { + element(card, "p", { className: "match-agreement caption", text: sentence }); + } + } + + // --------------------------------------------- Le moment décisif + + function decisiveCard( + parent: HTMLElement, + summary: MatchSummary, + phrases: MasterPhrases, + ): void { + const card = element(parent, "section", { + id: "match-decisive", + className: "analysis-card", + }); + element(card, "h2", { className: "overline", text: T.decisiveTitle }); + const moment = summary.decisive; + if (moment === null) { + element(card, "p", { className: "muted", text: T.decisiveNone }); + return; + } + element(card, "p", { + id: "match-decisive-sentence", + className: "match-sentence", + text: decisiveSentence(phrases, moment), + }); + const link = element(card, "a", { + id: "match-decisive-link", + className: "link-button", + text: T.seeThisMove, + }); + link.href = decisionHref(moment.gameId, moment.turn); + } + + // ------------------------------------------- La décision à revoir + + function reviewCard(parent: HTMLElement, summary: MatchSummary, phrases: MasterPhrases): void { + const card = element(parent, "section", { + id: "match-to-review", + className: "summary-review analysis-card", + }); + element(card, "h2", { className: "overline", text: T.reviewTitle }); + const reviewed = summary.toReview; + if (reviewed === null) { + element(card, "p", { className: "summary-none", text: nothingToReview(phrases) }); + return; + } + const advice = reviewed.advice; + const words = masterWords(phrases, advice); + const body = element(card, "div", { className: "summary-review-body" }); + const box = element(body, "div", { className: "summary-board-box" }); + const svg = boardSvg(box, "match-board", "summary-board"); + svg.setAttribute("aria-label", REVIEW_TEXTS.toReviewBoard); + void options + .stepsBefore(reviewed.gameId, advice) + .then((steps) => { + if (steps !== null) { + drawSteps(svg, steps, steps.halfMoves.length, true, "match-"); + } + }) + .catch(() => undefined); + const text = element(body, "div", { className: "summary-review-text" }); + const verdict = element(text, "p", { className: "summary-verdict" }); + verdict.dataset.verdict = words.verdict; + verdict.append(icon(VERDICT_ICONS[words.verdict]), `${words.word} · ${words.context}`); + element(text, "p", { + className: "caption", + text: T.reviewWhere(reviewed.game, reviewed.turn, matchScoreText(reviewed.score)), + }); + if (reviewed.loss !== null) { + const loss = element(text, "p", { + id: "match-review-loss", + className: "match-loss", + text: T.lossOf(formatMatchLoss(reviewed.loss)), + }); + loss.dataset.verdict = words.verdict; + } + element(text, "p", { + className: "summary-master", + text: + advice.kind === "move" + ? REVIEW_TEXTS.yourMove(advice.played.notation) + : REVIEW_TEXTS.yourDecision(REVIEW_TEXTS.cubeActions[advice.action]), + }); + element(text, "p", { className: "summary-master", text: words.title }); + const links = element(card, "div", { className: "summary-review-actions" }); + const revisit = element(links, "a", { + id: "match-revisit", + className: "button secondary", + text: T.review, + }); + revisit.href = decisionHref(reviewed.gameId, reviewed.turn); + const slot = element(links, "div", { className: "ask-ai-slot" }); + askAiLink( + slot, + "match-ask-ai", + routeHash({ screen: "matchSummary", match: summary.match.id, ai: true }), + ); + } + + return { + show, + hide() { + drawn = ""; + redrawCurve = null; + section.replaceChildren(); + }, + }; +} + +/** + * La courbe : un point par décision (le début du match, puis chaque tour de + * chaque partie), une seule ligne de 0 à 100 % ; un trait vertical entre + * les parties, le score au début de chacune au-dessus, son nom court en + * dessous ; la partie Crawford sur fond creusé ; la ligne des 50 % en + * pointillés ; trois marques (moment décisif, décision à revoir, fin) ; la + * bulle du point choisi. + */ +function drawCurve(svg: SVGSVGElement, summary: MatchSummary, selected: number | null): void { + const width = Math.round(svg.getBoundingClientRect().width || 360); + const height = CURVE_HEIGHT; + svg.setAttribute("viewBox", `0 0 ${width} ${height}`); + svg.replaceChildren(); + const points = summary.curve; + const inner = width - PAD.left - PAD.right; + const step = points.length > 1 ? inner / (points.length - 1) : 0; + const x = (i: number) => PAD.left + i * step; + const y = (chance: number) => PAD.top + (1 - chance) * (height - PAD.top - PAD.bottom); + + // Les parties : de leur premier point (le dernier de la précédente) à + // leur dernier. + const spans = summary.rows.map((row) => { + const indexes = points.flatMap((p, i) => (p.game === row.number ? [i] : [])); + const first = indexes[0] ?? 0; + const last = indexes.at(-1) ?? first; + return { row, from: row.number === 1 ? first : Math.max(0, first - 1), to: last }; + }); + for (const span of spans) { + if (span.row.crawford) { + svgElement(svg, "rect", { + x: x(span.from), + y: PAD.top, + width: Math.max(2, x(span.to) - x(span.from)), + height: height - PAD.top - PAD.bottom, + class: "match-crawford", + }); + } + } + for (const level of [1, 0.5, 0]) { + svgElement(svg, "line", { + x1: PAD.left, + x2: width - PAD.right, + y1: y(level), + y2: y(level), + class: level === 0.5 ? "curve-half" : "curve-axis", + }); + const label = svgElement(svg, "text", { + x: PAD.left - 6, + y: y(level) + 4, + class: "curve-label", + "text-anchor": "end", + }); + label.textContent = percent(level); + } + for (const span of spans) { + if (span.row.number > 1) { + svgElement(svg, "line", { + x1: x(span.from), + x2: x(span.from), + y1: PAD.top, + y2: height - PAD.bottom, + class: "match-separator", + }); + } + const middle = (x(span.from) + x(span.to)) / 2; + const score = svgElement(svg, "text", { + x: middle, + y: PAD.top - 9, + class: "curve-label match-score", + "text-anchor": "middle", + }); + score.textContent = matchScoreText(span.row.scoreBefore); + const name = svgElement(svg, "text", { + x: middle, + y: height - 8, + class: "curve-label", + "text-anchor": "middle", + }); + name.textContent = T.gameShort(span.row.number); + } + + const known = points.flatMap((p, i) => (p.chance === null ? [] : [{ i, p, c: p.chance }])); + if (known.length > 0) { + svgElement(svg, "polyline", { + points: known.map(({ i, c }) => `${x(i)},${y(c)}`).join(" "), + class: "curve-line", + }); + } + const indexOf = (game: number, turn: number) => + points.findIndex((p) => p.game === game && p.turn === turn); + const mark = (i: number, cls: string, r: number) => { + const c = points[i]?.chance; + if (i >= 0 && c !== null && c !== undefined) { + svgElement(svg, "circle", { cx: x(i), cy: y(c), r, class: cls }).setAttribute( + "aria-hidden", + "true", + ); + } + }; + const decisive = summary.decisive; + if (decisive !== null) { + mark(indexOf(decisive.game, decisive.turn), "match-mark-ring", 8); + } + const reviewed = summary.toReview; + if (reviewed !== null) { + mark(indexOf(reviewed.game, reviewed.turn), "match-mark-review", 5); + } + if (summary.match.over) { + mark( + points.length - 1, + summary.match.winner === "player" ? "match-mark-end won" : "match-mark-end", + 5, + ); + } + + // Le point choisi : un trait qui suit le doigt, et la bulle. + const point = selected === null ? undefined : points[selected]; + if (selected !== null && point !== undefined) { + svgElement(svg, "line", { + x1: x(selected), + x2: x(selected), + y1: PAD.top, + y2: height - PAD.bottom, + class: "curve-cursor", + }); + bubble(svg, summary, point, x(selected), width); + } +} + +/** La bulle du point choisi : partie, coup, score, chances ; un lien SVG + * vers la décision dans l'analyse. */ +function bubble( + svg: SVGSVGElement, + summary: MatchSummary, + point: MatchCurvePoint, + cx: number, + width: number, +): void { + const row = summary.rows[point.game - 1]; + const score = row === undefined ? "" : matchScoreText(row.scoreBefore); + const chance = point.chance === null ? REVIEW_TEXTS.curveUnknown : percent(point.chance); + const link = svgElement(svg, "a", { + href: decisionHref(point.gameId, point.turn), + class: "match-bubble", + id: "match-bubble", + }); + link.setAttribute( + "aria-label", + `${T.bubble(point.game, point.turn, score, chance)}. ${T.bubbleOpen}`, + ); + const left = Math.min(Math.max(4, cx - BUBBLE.width / 2), width - BUBBLE.width - 4); + svgElement(link, "rect", { + x: left, + y: 2, + width: BUBBLE.width, + height: BUBBLE.height, + rx: 8, + class: "match-bubble-box", + }); + const line1 = svgElement(link, "text", { + x: left + 10, + y: 19, + class: "match-bubble-text", + }); + line1.textContent = T.bubble(point.game, point.turn, score, chance); + const line2 = svgElement(link, "text", { + x: left + 10, + y: 36, + class: "match-bubble-hint", + }); + line2.textContent = T.bubbleOpen; +} diff --git a/app/src/ui/progression-view.ts b/app/src/ui/progression-view.ts index a1bfaca..5097354 100644 --- a/app/src/ui/progression-view.ts +++ b/app/src/ui/progression-view.ts @@ -12,6 +12,7 @@ // (domain/analysis/progression.ts), et la redessine quand une analyse en // arrière-plan se termine. +import type { PlayedMatch } from "../domain/analysis/match-analysis.js"; import type { MasterPhrases } from "../domain/analysis/phrases.js"; import { progressionSentence } from "../domain/analysis/phrases.js"; import { @@ -23,6 +24,7 @@ import { } from "../domain/analysis/progression.js"; import { computerLevelOf } from "../domain/game/level.js"; import { icon } from "./icons.js"; +import { type MatchLine, renderMatchLine } from "./match-line.js"; import { MATCH_TEXTS } from "./match-texts.js"; import { PROGRESSION_TEXTS } from "./progression-texts.js"; import { routeHash } from "./router.js"; @@ -31,12 +33,17 @@ import { routeHash } from "./router.js"; export interface ProgressionData { /** Les parties terminées, de la plus ancienne à la plus récente. */ readonly entries: readonly ProgressionEntry[]; + /** Les matchs (étape 1l) : chacun tient en une ligne dans la liste, à + * la place de ses parties (la courbe garde un point par partie). */ + readonly matches: readonly MatchLine[]; /** Les phrases du maître (null : pas encore lues). */ readonly phrases: MasterPhrases | null; } export interface ProgressionViewOptions { readonly section: HTMLElement; + /** « Reprendre » sur la ligne d'un match en cours. */ + readonly resumeMatch: (match: PlayedMatch) => void; } export interface ProgressionView { @@ -129,6 +136,12 @@ export function createProgressionView(options: ProgressionViewOptions): Progress e.level, e.errorRate?.perDecision ?? null, ]), + matches: data.matches.map((m) => [ + m.match.id, + m.match.games.map((g) => g.id), + m.match.score, + m.errorRate, + ]), }, ); if (key === drawn) { @@ -211,9 +224,29 @@ export function createProgressionView(options: ProgressionViewOptions): Progress element(body, "h3", { className: "overline", text: PROGRESSION_TEXTS.listTitle }); const list = element(body, "ol", { id: "progression-list", className: "progression-list" }); - // La plus récente d'abord, comme « Mes parties ». - for (const entry of [...data.entries].reverse()) { - list.append(item(entry)); + // La plus récente d'abord, comme « Mes parties » ; un match en une + // ligne, à la date de sa partie la plus récente de la liste. + const shown = new Set(data.entries.map((e) => e.id)); + const matches = data.matches.filter((m) => m.match.games.some((g) => shown.has(g.id))); + const inMatch = new Set(matches.flatMap((m) => m.match.games.map((g) => g.id))); + const lines = [ + ...data.entries + .filter((entry) => !inMatch.has(entry.id)) + .map((entry) => ({ at: entry.startedAt, add: () => list.append(item(entry)) })), + ...matches.map((line) => ({ + at: Math.max( + ...line.match.games.filter((g) => shown.has(g.id)).map((g) => g.startedAt), + ), + add: () => { + const li = document.createElement("li"); + li.className = "progression-item progression-match"; + renderMatchLine(li, line, () => options.resumeMatch(line.match)); + list.append(li); + }, + })), + ].sort((a, b) => b.at - a.at); + for (const line of lines) { + line.add(); } section.dataset.ready = String(waiting === 0); } diff --git a/app/src/ui/prompt-source.ts b/app/src/ui/prompt-source.ts index 40ac999..0e87263 100644 --- a/app/src/ui/prompt-source.ts +++ b/app/src/ui/prompt-source.ts @@ -7,6 +7,7 @@ // Copyright (C) 2026 les auteurs d'Ustagammon. // Licence : GPLv3 ou ultérieure (voir LICENSE). +import type { MatchSummary } from "../domain/analysis/match-analysis.js"; import type { MasterPhrases } from "../domain/analysis/phrases.js"; import type { Advice } from "../domain/game/advice.js"; import type { GameJournal } from "../domain/game/events.js"; @@ -16,6 +17,7 @@ import { conceptPrompt, decisionPrompt, exercisesPrompt, + matchPrompt, summaryPrompt, } from "../domain/prompts/prompts.js"; import { @@ -44,6 +46,9 @@ export interface PromptsAccess { /** La position de la plus coûteuse des erreurs de ces parties (null : * aucune imprécision ni erreur). */ readonly exercises: (journals: readonly GameJournal[]) => Promise; + /** La position que montre le prompt du bilan du match (décision à + * revoir, ou position finale). */ + readonly match: (summary: MatchSummary) => Promise; } export interface PromptSourceOptions { @@ -63,6 +68,8 @@ export interface PromptSource { /** Le prompt « Créer des exercices » (progression, étape 1h), sur les * parties analysées, de la plus ancienne à la plus récente. */ exercises(journals: readonly GameJournal[]): Promise; + /** Le prompt « Bilan de mon match » (étape 1l). */ + match(summary: MatchSummary): Promise; } async function fetchText(url: string): Promise { @@ -128,6 +135,14 @@ export function createPromptSource(options: PromptSourceOptions): PromptSource { } return { text: exercisesPrompt(all, phrases, { journals, position }) }; }, + async match(summary) { + const [all, phrases, position] = await Promise.all([ + templates(), + options.phrases(), + options.access.match(summary), + ]); + return { text: matchPrompt(all, phrases, { summary, position }) }; + }, async concept(term, journal) { const [all, entry, example] = await Promise.all([ templates(), diff --git a/app/src/ui/router.ts b/app/src/ui/router.ts index b2b5d85..e295404 100644 --- a/app/src/ui/router.ts +++ b/app/src/ui/router.ts @@ -54,6 +54,9 @@ export type Route = readonly turn: number | null; readonly ai?: boolean; } + /** #/matchs//bilan : le bilan d'un match entier (étape + * 1l) ; son prompt pour une IA : #/matchs//bilan/ia. */ + | { readonly screen: "matchSummary"; readonly match: string; readonly ai?: boolean } /** #/progression : l'historique des parties et la courbe du taux * d'erreur (étape 1h) ; le prompt « Créer des exercices » : * #/progression/ia. */ @@ -114,6 +117,12 @@ export function parseRoute(hash: string): Route { if (head === "parties" && rest.length > 1) { return gameReviewRoute(rest) ?? unknown; } + if (head === "matchs") { + const [match = "", part, ...more] = rest; + return NAME.test(match) && part === "bilan" && more.length === 0 + ? { screen: "matchSummary", match } + : unknown; + } if (rest.length > 1) { return unknown; } @@ -156,7 +165,15 @@ export function parseRoute(hash: string): Route { /** Les écrans qui ont une feuille de prompt pour une IA. */ export type AiRoute = Extract< Route, - { screen: "explanation" | "summary" | "analysis" | "glossary" | "progression" } + { + screen: + | "explanation" + | "summary" + | "analysis" + | "glossary" + | "progression" + | "matchSummary"; + } >; /** L'écran, avec sa feuille de prompt ouverte (null : écran sans prompt). */ @@ -166,6 +183,7 @@ function aiRoute(route: Route): AiRoute | null { case "summary": case "analysis": case "progression": + case "matchSummary": return route.ai === true ? null : { ...route, ai: true }; case "glossary": return route.term === null || route.ai === true ? null : { ...route, ai: true }; @@ -316,6 +334,8 @@ function screenHash(route: Route): string { : `#/parties/${route.game}/analyse/${route.turn}`; case "progression": return "#/progression"; + case "matchSummary": + return `#/matchs/${route.match}/bilan`; case "menu": return "#/menu"; case "newGame": diff --git a/app/src/ui/summary-view.ts b/app/src/ui/summary-view.ts index 8092b5d..28e814c 100644 --- a/app/src/ui/summary-view.ts +++ b/app/src/ui/summary-view.ts @@ -30,6 +30,7 @@ import { COMPUTER_LEVELS } from "../domain/game/level.js"; import { VERDICT_ICONS } from "./advice-view.js"; import { askAiLink, clearSheet } from "./ask-ai.js"; import { icon } from "./icons.js"; +import { MATCH_SUMMARY_TEXTS } from "./match-summary-texts.js"; import { MATCH_TEXTS } from "./match-texts.js"; import { boardSvg, drawSteps } from "./move-board.js"; import { REVIEW_TEXTS } from "./review-texts.js"; @@ -49,6 +50,13 @@ export interface SummaryData { * l'écran des choix. */ readonly afterLabel: string | null; readonly phrases: MasterPhrases | null; + /** Une partie de match (étape 1l) : sa place et le bilan du match + * (null : partie libre, ou partie rattachée à aucun match). */ + readonly match: { + readonly id: string; + readonly number: number; + readonly length: number; + } | null; } export interface SummaryViewOptions { @@ -137,6 +145,7 @@ export function createSummaryView(options: SummaryViewOptions): SummaryView { data.end?.title ?? "", data.end?.detail ?? "", data.afterLabel ?? "", + JSON.stringify(data.match), ready, JSON.stringify(shown), ].join("|"); @@ -166,6 +175,7 @@ export function createSummaryView(options: SummaryViewOptions): SummaryView { return; } title.textContent = data.end.title; + matchLine(data); const reading = element(panel, "p", { id: "summary-reading", className: "summary-reading", @@ -191,6 +201,25 @@ export function createSummaryView(options: SummaryViewOptions): SummaryView { actions(data); } + /** « Partie 2 du match en 5 points · Bilan du match » (charte, « Bilan + * du match », accès). */ + function matchLine(data: SummaryData): void { + const match = data.match; + if (match === null) { + return; + } + const line = element(panel, "p", { + id: "summary-match", + className: "caption summary-match", + }); + line.append(`${MATCH_SUMMARY_TEXTS.gameOfMatch(match.number, match.length)} · `); + const link = element(line, "a", { + id: "summary-match-link", + text: MATCH_SUMMARY_TEXTS.seeMatchSummary, + }); + link.href = routeHash({ screen: "matchSummary", match: match.id }); + } + function counts(summary: GameSummary): void { const box = element(panel, "div", { id: "summary-counts", className: "summary-counts" }); box.setAttribute("role", "list"); diff --git a/app/tests/match-analysis.test.ts b/app/tests/match-analysis.test.ts index 21a857b..68fe036 100644 --- a/app/tests/match-analysis.test.ts +++ b/app/tests/match-analysis.test.ts @@ -399,3 +399,22 @@ test("le prompt « Bilan de mon match » cite le videau en chances de gagner le assert.match(prompt, /partie 4, coup 1\) : la position avant ma décision/); assert.equal(position.positionId, "wN1tAwADAAAAAA"); }); + +test("une décision de videau dont la perte s'écrirait 0,0 % n'est pas listée", () => { + const fourth = comeback[3] as MatchGame; + const review = fourth.journal.review; + assert.ok(review?.matchLosses !== undefined); + const tiny = Object.fromEntries(Object.keys(review.matchLosses).map((id) => [id, -0.0004])); + const games = comeback.map((g, i) => + i === 3 ? { ...g, journal: { ...g.journal, review: { ...review, matchLosses: tiny } } } : g, + ); + const match = groupMatches(games).matches[0]; + assert.ok(match !== undefined); + const summary = summarizeMatch(match); + assert.equal(summary.cubeErrors.length, 0); + assert.equal(summary.cubeDecisions, 1); + assert.equal( + matchCubeSentence(phrases, summary.cubeDecisions, 0), + "Une seule décision de videau, comme je l'aurais prise.", + ); +}); diff --git a/app/tests/router.test.ts b/app/tests/router.test.ts index bd292ad..4c543ae 100644 --- a/app/tests/router.test.ts +++ b/app/tests/router.test.ts @@ -49,6 +49,9 @@ const TABLE: [string, Route][] = [ // La progression (étape 1h) et son prompt « Créer des exercices ». ["#/progression", { screen: "progression" }], ["#/progression/ia", { screen: "progression", ai: true }], + // Le bilan d'un match entier (étape 1l) et son prompt. + ["#/matchs/mh3k2-a1b2c3/bilan", { screen: "matchSummary", match: "mh3k2-a1b2c3" }], + ["#/matchs/mh3k2-a1b2c3/bilan/ia", { screen: "matchSummary", match: "mh3k2-a1b2c3", ai: true }], ["#/menu", { screen: "menu" }], ["#/nouvelle-partie", { screen: "newGame" }], ["#/explication/12", { screen: "explanation", event: "12" }], @@ -131,6 +134,11 @@ test("une adresse inconnue est reconnue comme telle", () => { "#/parties/ab/ia", "#/explication/12/ia/ia", "#/progression/x", + "#/matchs", + "#/matchs/m1", + "#/matchs/M1/bilan", + "#/matchs/m1/bilan/x", + "#/matchs/m1/analyse", "#/progression/ia/ia", ]) { assert.equal(parseRoute(hash).screen, "unknown", hash); diff --git a/docs/adr/0007-architecture-et-conventions-de-code.md b/docs/adr/0007-architecture-et-conventions-de-code.md index e16b909..62ed1ab 100644 --- a/docs/adr/0007-architecture-et-conventions-de-code.md +++ b/docs/adr/0007-architecture-et-conventions-de-code.md @@ -227,3 +227,45 @@ cours : - Une leçon est terminée quand tous ses exercices sont réussis ; ce n'est pas enregistré à part, mais déduit des exercices réussis et du texte de la leçon : ajouter un exercice à une leçon la fait repasser « en cours ». + +### 2026-11-13 — Version 3 des événements : l'identifiant de match + +Avec l'analyse d'un match entier (étape 1l), les parties d'un même match +doivent se retrouver. Jusqu'ici, rien ne les reliait : chaque partie a son +journal (amendement du 2026-11-09), et la suivante ne fait que reprendre le +score que la précédente a laissé. + +- Le format des événements passe à la version 3 (`EVENT_VERSION`, + `app/src/domain/game/events.ts`) : le match de `GameStarted` porte + l'identifiant du match (`match.id`), commun à toutes ses parties. La + session de jeu (`app/src/storage/game-session.ts`) donne au match + l'identifiant de sa première partie ; la partie suivante le reprend + (`nextGameOf`). Le domaine ne tire toujours pas de hasard. +- La migration (`migrateJournal`) passe un journal des versions 1 et 2 à la + version 3 en changeant seulement le numéro : une partie de match de la + version 2 reste sans identifiant, il n'est pas inventé. Testé dans + `app/tests/match-analysis.test.ts` et `app/tests/game.test.ts`. +- Les matchs joués avant sont rattachés à la lecture, sans rien réécrire + (`groupMatches`, `app/src/domain/analysis/match-analysis.ts`) : à partir + d'une partie à 0–0, la suivante doit avoir la même longueur et le même + niveau, commencer au score où la précédente a fini (partie Crawford + comprise), après elle et moins de 12 heures après sa dernière action. + Deux candidates, ou une candidate qui pourrait suivre deux parties : + la chaîne s'arrête, et les parties restantes gardent leur ligne à part + dans « Mes parties ». Un match ainsi rattaché le dit dans les listes et + dans son bilan. +- Le résumé d'une partie enregistrée gagne `match.id` (facultatif, absent + avant la version 3), recalculé à chaque enregistrement. Le schéma + IndexedDB ne change pas (version 1). +- L'analyse de partie (`review`, amendement du 2026-11-10) gagne deux tables + facultatives, pour les parties de match : `matchChances`, les chances du + joueur de gagner le match au début de la partie (sous l'identifiant de + `GameStarted`), après chaque coup et après la partie (`GameEnded`) ; et + `matchLosses`, les chances de gagner le match que chaque décision du + joueur lui a coûtées. Les deux viennent du moteur + (`engine_match_chances_of` : table d'équité de match de gnubg et + `eq2mwc`, comparés à gnubg de bureau dans `tests/reference/`). Le domaine + ne lit aucune table d'équité. `REVIEW_VERSION` ne change pas : une + analyse enregistrée avant n'a pas ces tables, et l'analyse en + arrière-plan les complète ; une table mal formée, ou ses entrées hors du + journal, est oubliée à la reprise. diff --git a/docs/adr/0013-position-dans-l-adresse.md b/docs/adr/0013-position-dans-l-adresse.md index 16790d6..f3ea562 100644 --- a/docs/adr/0013-position-dans-l-adresse.md +++ b/docs/adr/0013-position-dans-l-adresse.md @@ -244,3 +244,37 @@ Ajoutées avec l'écran de progression (étape 1h), dans le même schéma : la feuille le dit, jamais une page cassée. - Comme « Mes parties », ces adresses n'ont de sens que sur l'appareil qui a joué les parties : ce ne sont pas des liens à partager. + +### 2026-11-13 — Adresses du bilan d'un match + +Ajoutées avec l'analyse d'un match entier (étape 1l), dans le même schéma : + +| Écran | Adresse | +| --- | --- | +| Bilan d'un match entier | `#/matchs//bilan` | +| Prompt « Bilan de mon match », depuis ce bilan | `#/matchs//bilan/ia` | + +- `` est l'identifiant du match (ADR 0007, amendement du 2026-11-13) : + celui de sa première partie. Pour un match joué avant l'identifiant de + match, c'est aussi l'identifiant de sa première partie, retrouvée par le + rattachement d'après les scores et les dates. +- Le bilan du match est une page, comme la progression : la barre du haut, + Échap et le retour du téléphone suffisent. Il s'ouvre depuis la fin de la + dernière partie d'un match (« Bilan du match » remplace l'action + principale du panneau de fin de partie et du bilan de cette partie), depuis + la ligne « Partie n du match en N points · Bilan du match » du bilan de + chaque partie de match, et depuis « Mes parties » et la progression, où un + match tient en une ligne. +- Chaque partie du bilan du match mène à son bilan + (`#/parties//bilan`), chaque décision (lignes du videau, moment + décisif, décision à revoir, bulle de la courbe) à l'analyse de sa partie + (`#/parties//analyse/`). L'analyse d'une partie de match a en + tête « Partie 2 sur 5 · 0–2 », avec ‹ et › vers l'analyse des parties + voisines. +- Le prompt suit la règle des prompts (amendement du 2026-11-10) : sa + propre feuille au-dessus du bilan du match (« ‹ Bilan du match »). + Rechargée, l'adresse recalcule le prompt à partir des analyses + enregistrées ; tant que l'analyse du match n'est pas finie, la feuille le + dit. +- Comme « Mes parties », ces adresses n'ont de sens que sur l'appareil qui a + joué le match. Un match absent donne un message, jamais une page cassée. diff --git a/docs/etape-1.md b/docs/etape-1.md index 1bd1fc4..5e9cbec 100644 --- a/docs/etape-1.md +++ b/docs/etape-1.md @@ -27,7 +27,7 @@ Repris du cadrage (modules, écrans clés, IA générative en V1) et des ADR 001 | 1h. Progression (fait) | Historique des parties et courbe du taux d'erreur | 1b, 1e | | 1i. Plateau soigné | Dessin du plateau aligné sur la charte (`docs/identite/charte/board.js`), animations des pions, glisser-déposer en plus du toucher, double toucher pour le seul coup évident | 0e.3 | | 1k. Retours des joueurs, 2e lot | Crawford signalé sur la barre ; abandon (simple, gammon, backgammon) accepté ou refusé par l'ordinateur selon GNU Backgammon (plan `2026-11-12-retours-joueurs-2.md`) | 1c, 1e | -| 1l. Analyse du match | Bilan et courbe d'un match entier (chances de gagner le match), erreurs de videau sur tout le match, prompt et export SGF du match (plan `2026-11-12-analyse-du-match.md`) | 1c, 1e, 1f | +| 1l. Analyse du match (fait) | Bilan et courbe d'un match entier (chances de gagner le match), erreurs de videau sur tout le match, prompt et export SGF du match | 1c, 1e, 1f | | 1j. Plan de test | `docs/guide-test-etape-1.md` : parcours du débutant et du joueur de club sur le téléphone, avec ce qu'il faut rapporter | toutes | ## Orientation donnée par Pierre diff --git a/docs/glossaire/README.md b/docs/glossaire/README.md index c2a3342..f9d58b0 100644 --- a/docs/glossaire/README.md +++ b/docs/glossaire/README.md @@ -41,6 +41,7 @@ exportée. `make test` vérifie le lien dans les deux sens : chaque fiche avec | [Blot](blot.md) | Blot | | [Branche](branche.md) | Branch | | [Chance](chance.md) | Luck | +| [Chances de gagner le match](chances-de-gagner-le-match.md) | Match winning chances | | [Compte de points](compte-de-points.md) | Pip count | | [Conseil du maître](conseil-du-maitre.md) | Advice | | [Coup](coup.md) | Move | diff --git a/docs/glossaire/chances-de-gagner-le-match.md b/docs/glossaire/chances-de-gagner-le-match.md new file mode 100644 index 0000000..c7cd39c --- /dev/null +++ b/docs/glossaire/chances-de-gagner-le-match.md @@ -0,0 +1,24 @@ +--- +term: Chances de gagner le match +english: Match winning chances +code: MatchChances +--- +# Chances de gagner le match + +**En bref** : en match, vos chances de remporter le match entier, et non la seule partie en cours, de 0 à 100 %. + +En match, ce qui compte est le match : gagner une partie d'un point ne vaut +pas la même chose à 0–0 qu'à 3–4. GNU Backgammon le mesure en chances de +gagner le match (en anglais *match winning chances*, MWC). Avant chaque +partie, elles se lisent dans sa table d'équité de match (Kazaross-XG2), qui +donne vos chances à chaque score ; pendant la partie, le moteur évalue la +position et les convertit avec le videau et le score. + +Le bilan du match trace ces chances d'un bout à l'autre du match : la fin +d'une partie est le début de la suivante. Une erreur s'y compte aussi en +chances de gagner le match perdues, à une décimale (« −1,2 % »), jamais en +[équité](equite.md) : c'est ainsi que GNU Backgammon compte les erreurs dans +ses statistiques de match. Une même erreur de [videau](videau.md) coûte plus +ou moins selon le score. + +Voir aussi : [Match](match.md), [Courbe des chances de gagner](courbe-des-chances.md), [Équité](equite.md), [Règle de Crawford](regle-de-crawford.md) diff --git a/docs/plans/2026-11-12-analyse-du-match.md b/docs/plans/2026-11-12-analyse-du-match.md deleted file mode 100644 index a5e2b5a..0000000 --- a/docs/plans/2026-11-12-analyse-du-match.md +++ /dev/null @@ -1,42 +0,0 @@ -# Analyse d'un match entier - -- **Date** : 2026-11-12 -- **Étape** : 1 (demande de Pierre) -- **Statut** : prévu (après le 2e lot de retours des joueurs, et une fois les maquettes de la session « identité » disponibles) -- **Exécutant** : sous-agent general-purpose, dans un worktree - -## Objectif - -Demande de Pierre du 2026-11-12 : « proposer une analyse complète du match, notamment pour l'utilisation du videau (pas que l'analyse d'une manche) ». Il cite son propre exemple : mené 4-0 après deux parties, il a gagné le match en 5 points trois parties plus tard. - -Aujourd'hui, chaque partie d'un match a son bilan et son analyse (1e), mais rien ne montre le match dans son ensemble. - -## Consignes - -Respecter les ADR 0007, 0008, 0011 et 0013. Suivre les règles et maquettes de la session « identité ». - -1. **Bilan du match.** Une adresse (par exemple `#/matchs//bilan`) donne : - - le résultat et le déroulé du score, partie par partie ; - - le taux d'erreur du joueur sur tout le match, à la manière de gnubg (statistiques du match) ; - - les erreurs de videau regroupées : doubles manqués, mauvais doubles, prises et refus fautifs ; - - le moment décisif ; - - « le coup à revoir » du match. -2. **Courbe du match.** Elle suit les chances de gagner le match (MWC, tables d'équité de match du moteur) à travers toutes les parties, et non les chances de gagner la partie. Toucher un point ouvre la décision. -3. **Données.** - - Réutiliser les analyses déjà rangées dans les journaux de chaque partie (`review`). - - Relier les parties d'un même match. Aujourd'hui, une partie = un journal (choix de 1c). Il faut un identifiant de match commun, avec un format durable et une migration testée. Les matchs déjà joués sont rattachés si c'est possible, sinon on le dit honnêtement. - - Les équités de match viennent du moteur. Le domaine ne fait aucun calcul de table d'équité. -4. **Accès.** Depuis le bilan de la dernière partie d'un match, « Voir l'analyse du match ». Depuis « Mes parties » et la progression, le match apparaît comme une entrée. -5. **Prompt.** Un gabarit « bilan de mon match », avec un bouton « Demander à une IA » (1f). -6. **Export SGF.** Exporter le match entier : MI et toutes les parties. -7. **Tests.** Scénario Gherkin d'un match en 5 points avec dés imposés, où le joueur remonte après avoir été mené. Tests unitaires de l'agrégation, référence MWC comparée à gnubg de bureau. - -Tests : `make lint`, `make test`, `make test-browser`, captures pour la recette design. - -## Critères de réussite - -Sur un match joué jusqu'au bout, le bilan du match reprend les erreurs de videau de toutes les parties, et la courbe des chances de gagner le match est continue d'une partie à l'autre. Les trois commandes passent. - -## Résultat - -À remplir à la clôture. diff --git a/tests/browser.sh b/tests/browser.sh index 802aee3..c5bee76 100755 --- a/tests/browser.sh +++ b/tests/browser.sh @@ -23,10 +23,15 @@ # progression gardée), captures dans build/browser-shots/lecons/. La # progression (tests/browser/progression.mjs : cas vide, trois parties, courbe # égale aux taux des bilans, ligne de l'accueil, « Créer des exercices »), -# captures dans build/browser-shots/progression/. +# captures dans build/browser-shots/progression/. 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) restreignent le test. +# prompts, nouvelle-partie, retours-joueurs, lecons, progression, match-bilan) +# restreignent le test. # # Outils : l'image de Playwright (navigateurs) et le paquet playwright, # installé une fois par npm dans build/browser-tools/ (réseau nécessaire la @@ -39,7 +44,7 @@ cd "$(dirname "$0")/.." image="${PLAYWRIGHT_IMAGE:?lancer via make test-browser}" browsers="${BROWSERS:-chromium firefox}" # Les scripts à lancer (tests/browser/.mjs), tous par défaut. -scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression}" +scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression match-bilan}" unset MAKEFLAGS MFLAGS MAKELEVEL make -s package >/dev/null @@ -78,7 +83,8 @@ rm -rf build/browser-shots 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 "$tools/" + tests/browser/retours-joueurs.mjs tests/browser/lecons.mjs tests/browser/progression.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 @@ -155,5 +161,12 @@ for browser in $browsers; do -v "$PWD/$tools:/tools" -v "$PWD/build/browser-shots:/shots" -w /tools "$image" \ node progression.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" diff --git a/tests/browser/match-bilan.mjs b/tests/browser/match-bilan.mjs new file mode 100644 index 0000000..a1e49e8 --- /dev/null +++ b/tests/browser/match-bilan.mjs @@ -0,0 +1,409 @@ +// 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 +// 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 /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 "); + 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}`); diff --git a/tests/browser/match.mjs b/tests/browser/match.mjs index 120bef8..33589fa 100644 --- a/tests/browser/match.mjs +++ b/tests/browser/match.mjs @@ -301,7 +301,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) ?? []; diff --git a/web/app.css b/web/app.css index 7a765b1..f256980 100644 --- a/web/app.css +++ b/web/app.css @@ -3948,3 +3948,268 @@ html.landscape .prompting .prompt-text { .viewer-actions { flex-wrap: wrap; } + +/* ------------------------------------------- Bilan du match (1l) */ + +/* Charte, ecrans-etape-1.md, « Bilan du match » : une page qui défile ; en + * paysage, deux colonnes (l'en-tête, la courbe et les parties à gauche ; le + * jeu, le videau, le moment décisif, la décision à revoir et les actions à + * droite). */ +.match-summary { + max-width: var(--page-width); +} + +html.landscape .match-summary { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + column-gap: var(--space-6); + align-items: start; + max-width: 60rem; +} + +.match-column { + min-width: 0; +} + +.match-head .overline { + margin-top: var(--space-3); +} + +.match-head .progression-title { + margin-top: var(--space-1); +} + +/* La courbe : la zone tactile est tout son cadre. */ +.match-curve { + height: 196px; +} + +.match-crawford { fill: var(--surface-sunken); } +.match-separator { stroke: var(--border); stroke-width: 1; } +.match-score { fill: var(--text); font-weight: 700; } +.match-mark-ring { fill: none; stroke: var(--last-move); stroke-width: 3; } +.match-mark-review { fill: var(--verdict-bad); } +.match-mark-end { fill: var(--text); } +.match-mark-end.won { fill: var(--verdict-good); } + +.match-bubble { cursor: pointer; } +.match-bubble-box { fill: var(--surface); stroke: var(--border-strong); stroke-width: 1; } +.match-bubble-text { fill: var(--text); font-size: 13px; font-weight: 700; } +.match-bubble-hint { fill: var(--accent); font-size: 12px; text-decoration: underline; } + +/* La légende : trois marques, sans autre couleur. */ +.match-legend { + display: flex; + flex-wrap: wrap; + gap: var(--space-1) var(--space-3); + margin: var(--space-2) 0 0; + padding: 0; + list-style: none; + font-size: 13px; + color: var(--muted); +} + +.match-legend li { + display: inline-flex; + gap: 6px; + align-items: center; +} + +.match-mark { + display: inline-block; + width: 12px; + height: 12px; + border-radius: 50%; +} + +.match-mark.decisive { border: 3px solid var(--last-move); } +.match-mark.review { background: var(--verdict-bad); } +.match-mark.end { background: var(--text); } +.match-mark.end.won { background: var(--verdict-good); } + +/* « Partie par partie » : une ligne de 52 px par partie, le score après + * la partie en chiffres gras à droite. */ +.match-games { + margin: 0 0 var(--space-4); +} + +.match-games > .caption { + margin-top: var(--space-2); +} + +.match-game { + min-height: 52px; +} + +.match-game-score { + flex: none; + font-size: 22px; + line-height: 26px; + font-weight: 800; + font-variant-numeric: tabular-nums; +} + +/* « Votre jeu sur le match » : trois tuiles, puis les jauges. */ +.match-tiles { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--space-2); + margin-bottom: var(--space-3); +} + +.match-tile { + display: flex; + flex-direction: column; + padding: var(--space-2); + background: var(--surface-sunken); + border-radius: var(--radius-sm); +} + +.match-tile strong { + font-size: 24px; + line-height: 30px; + font-variant-numeric: tabular-nums; +} + +.match-sentence { + margin: 0 0 var(--space-2); +} + +.match-cube-list { + display: flex; + flex-direction: column; + gap: var(--space-1); + margin: 0 0 var(--space-2); + padding: 0; + list-style: none; +} + +.match-cube-row { + display: flex; + gap: var(--space-3); + align-items: center; + min-height: 52px; + color: inherit; + text-decoration: none; + border-top: 1px solid var(--border); +} + +.match-cube-row > .icon { + flex: none; + width: 20px; + height: 20px; + color: var(--muted); +} + +/* Une perte, colorée comme le verdict. */ +.match-loss { + flex: none; + font-weight: 700; + font-variant-numeric: tabular-nums; +} + +.match-loss[data-verdict="doubtful"] { color: var(--verdict-doubtful); } +.match-loss[data-verdict="bad"], +.match-loss[data-verdict="veryBad"] { color: var(--verdict-bad); } + +.match-agreement { + margin: 0; +} + +.match-summary .summary-review { + padding-top: var(--space-3); + border-top: 1px solid var(--border); +} + +.match-summary .summary-verdict { + display: inline-flex; + gap: 6px; + align-items: center; + margin: 0; + font-weight: 700; +} + +.match-summary .summary-master { + margin: var(--space-1) 0 0; + font-style: italic; +} + +.match-export { + margin: 0 0 var(--space-3); +} + +.match-actions { + margin-bottom: var(--space-4); +} + +.match-actions > * { + flex: 1 1 0; + height: var(--button-height); + padding: 0 12px; +} + +/* Sous l'en-tête du bilan d'une partie de match. */ +.summary-match { + margin: 0; +} + +.summary-match a { + display: inline-flex; + align-items: center; + min-height: 44px; + color: var(--accent); +} + +/* En tête de l'analyse d'une partie de match : « ‹ Partie 2 sur 5 · 0–2 › ». */ +.analysis-match { + margin: 0 0 var(--space-3); +} + +#analysis-previous-game .icon { + transform: rotate(180deg); +} + +.analysis-match .viewer-step:not([href]) { + opacity: 0.35; + pointer-events: none; +} + +/* Un match en une ligne (« Mes parties », progression) : un trait par + * partie, vert si vous l'avez gagnée ; en pointillés, la partie à venir + * d'un match en cours. */ +.match-line { + display: flex; + gap: var(--space-2); + align-items: center; +} + +.match-line-link { + flex: 1; + min-width: 0; +} + +.match-strokes { + display: flex; + gap: 3px; + margin: 3px 0; +} + +.match-stroke { + width: 18px; + height: 0; + border-top: 4px solid var(--border-strong); + border-radius: 2px; +} + +.match-stroke.won { border-top-color: var(--verdict-good); } +.match-stroke.next { border-top: 3px dashed var(--border-strong); } + +.match-resume { + flex: none; + margin-right: var(--space-2); + padding: 0 16px; +} + +.games-match .match-line { + padding: var(--space-1) 0; +} diff --git a/web/index.html b/web/index.html index 1aa69ad..9c0dc79 100644 --- a/web/index.html +++ b/web/index.html @@ -114,6 +114,10 @@ parties terminées, construite par app/src/ui/progression-view.ts. --> + + +