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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-23 08:03:02 +01:00
co-authored by Claude Opus 5.5
74 changed files with 5232 additions and 156 deletions
+164 -17
View File
@@ -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<number> {
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<number> {
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<number> {
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) {
+526
View File
@@ -0,0 +1,526 @@
// 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 (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. */
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<Record<Side, number>>;
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<string, Facts[]>();
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<string>();
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<Record<Side, number>>;
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<Record<Side, number>>;
/** Le score après la partie (null : pas finie). */
readonly scoreAfter: Readonly<Record<Side, number>> | 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
* (voir 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 d'au moins
* CUBE_LOSS_SHOWN, 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<Record<Side, number>> | null;
}
const CUBE_KIND: Readonly<Record<string, CubeErrorKind>> = {
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" && differs(d) && 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),
};
}
/** 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 {
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<Record<Side, number>> | null {
const winner = match.winner;
if (winner === null) {
return null;
}
const loser: Side = winner === "player" ? "computer" : "player";
let deepest: Readonly<Record<Side, number>> | 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%`;
}
+70
View File
@@ -17,6 +17,8 @@ import {
} from "../game/advice.js";
import type { CubeAction, LuckRating, ResultKind } 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",
"abandon.refus",
"abandon.accepte",
];
@@ -189,6 +200,65 @@ export function resignationAnswer(
}).replace(/\bque (une?)\b/g, "qu'$1");
}
/** 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);
+23
View File
@@ -75,6 +75,12 @@ export interface Engine {
points: number,
): Promise<EngineMatchAfter>;
/** 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<MatchChances>;
/** 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. */
@@ -135,6 +141,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
+33 -10
View File
@@ -27,13 +27,16 @@ import type { Side } from "./side.js";
* - 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 ;
* - 3 (étape 1k) : l'abandon, avec trois nouveaux événements
* - 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 ;
* - 4 (étape 1k) : l'abandon, avec trois nouveaux événements
* (ResignationOffered, ResignationAccepted, ResignationDeclined) et le
* champ resigned de GameEnded. Rien ne change pour les événements déjà
* écrits.
* migrateJournal passe un journal des versions 1 et 2 à la 3.
* migrateJournal passe un journal des versions 1, 2 et 3 à la 4.
*/
export const EVENT_VERSION = 3;
export const EVENT_VERSION = 4;
/** Le niveau des parties de la version 1 : 2 plis (STANDARD_PLY, sans
* bruit), le seul qui existait. */
@@ -43,9 +46,12 @@ 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. Version 2 : seul le
* numéro de version change, la version 3 n'ayant fait qu'ajouter des
* événements et un champ facultatif. Un événement d'une version inconnue
* est laissé tel quel (Game.resume le refuse).
* 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). Version 3 :
* seul le numéro change, la version 4 n'ayant fait qu'ajouter des
* événements et un champ facultatif.
*/
export function migrateJournal(saved: GameJournal): GameJournal {
const journal = keepKnownReview(keepKnownAdvice(saved));
@@ -53,10 +59,10 @@ export function migrateJournal(saved: GameJournal): GameJournal {
return journal;
}
const events = journal.events.map((event): GameEvent => {
if (event.version !== 1 && event.version !== 2) {
if (event.version !== 1 && event.version !== 2 && event.version !== 3) {
return event;
}
if (event.version === 1 && event.type === "GameStarted") {
if (event.type === "GameStarted" && event.version === 1) {
return Object.freeze({
...event,
level: event.level ?? VERSION_1_LEVEL,
@@ -132,16 +138,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<string, number> | 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 };
}
+27 -4
View File
@@ -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<Record<Side, number>>;
@@ -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,
};
}
+12
View File
@@ -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<Record<string, number>>;
/** 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<Record<string, number>>;
}
/** Une analyse vide, au niveau ply. */
+4
View File
@@ -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<Record<Side, number>>;
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,
+24 -2
View File
@@ -39,6 +39,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. */
@@ -86,13 +89,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)}]`,
@@ -109,6 +113,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<SgfOptions, "gameIndex">,
): Promise<string> {
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 {
+200 -1
View File
@@ -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,
@@ -527,3 +541,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<Record<CubeErrorKind, string>> = {
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<Record<"player" | "computer", number>>): 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<PromptPosition> {
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));
}
+5 -2
View File
@@ -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<Record<PromptKind, string>> = {
summary: "bilan.md",
concept: "concept.md",
exercises: "exercices.md",
match: "match.md",
};
/** Les gabarits lus, par sorte. */
+13
View File
@@ -24,6 +24,7 @@ import type {
Level,
Luck,
LuckRating,
MatchChances,
MatchDescription,
MatchId,
Move,
@@ -188,6 +189,18 @@ export function createWasmEngine(run: RunCommand): Engine {
};
},
async matchChances(cube: EngineCube, equity: number): Promise<MatchChances> {
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,
+34 -6
View File
@@ -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<T>(get: () => T): T | undefined {
try {
+9 -2
View File
@@ -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) {
+61
View File
@@ -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,21 @@ 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;
/** C'est la partie Crawford du match. */
readonly crawford: boolean;
readonly previous: string | null;
readonly next: string | null;
}
export interface AnalysisViewOptions {
@@ -144,6 +160,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",
@@ -663,6 +702,28 @@ 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,
match.crawford,
);
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);
+320 -24
View File
@@ -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,
@@ -43,7 +50,7 @@ import {
import type { Advice } from "../domain/game/advice.js";
import type { Cube } from "../domain/game/cube.js";
import type { MoveNotation, ResultKind } 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,
@@ -56,7 +63,7 @@ import { BAR, 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,
@@ -69,7 +76,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 { attachDrag, createDoubleTap, nextPlace } from "./board-gestures.js";
@@ -99,7 +106,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";
@@ -113,6 +120,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";
@@ -235,6 +245,11 @@ export interface SavedGamesAccess {
readonly saveAnalyses: (id: string, journal: GameJournal) => void;
readonly remove: (id: string) => Promise<void>;
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. */
@@ -317,6 +332,7 @@ export function startApp(options: AppOptions): void {
promptVeil: byId("prompt-veil"),
analysis: byId("analysis"),
progression: byId("progression"),
matchSummary: byId("match-summary"),
menuAdvice: byId<HTMLButtonElement>("menu-advice"),
prompt: byId("prompt"),
strips: { computer: stripOf("strip-computer"), player: stripOf("strip-player") },
@@ -631,6 +647,9 @@ export function startApp(options: AppOptions): void {
let previous: GameJournal | null = null;
// « Mes parties », créé plus bas (il a besoin des actions de l'écran).
let gamesView: GamesView | null = null;
// Le match du bilan du match à l'écran (étape 1l). Déclaré avant le
// début de la navigation : applyRoute le lit pour toute adresse.
let matchShownId: string | null = null;
let bannerTimer: ReturnType<typeof setTimeout> | null = null;
// Plein écran demandé ; rotated : repli, l'écran tourné d'un quart de
// tour par CSS, quand le paysage ne peut pas être verrouillé.
@@ -858,7 +877,7 @@ export function startApp(options: AppOptions): void {
show(ui.take, doubled);
show(ui.drop, doubled);
show(ui.again, over && panelDismissed);
againLabel.textContent = afterGameLabel(game);
againLabel.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);
@@ -1238,7 +1257,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) {
@@ -1573,10 +1592,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 {
@@ -1651,6 +1679,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);
@@ -1670,11 +1704,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({
@@ -1793,6 +1829,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.
@@ -1832,6 +1878,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);
}
@@ -1857,12 +1907,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();
},
);
}
@@ -1872,8 +1927,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.
@@ -1915,13 +1979,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();
},
@@ -1946,7 +2011,11 @@ export function startApp(options: AppOptions): void {
progressionView.render(
progressionGames === null
? null
: { entries: progressionEntries(progressionGames), phrases },
: {
entries: progressionEntries(progressionGames),
matches: progressionMatches.map(matchLineOf),
phrases,
},
);
}
@@ -1955,6 +2024,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();
}
}
@@ -1981,6 +2055,172 @@ export function startApp(options: AppOptions): void {
}
}
// ------------------------------------------- Bilan du match (1l)
// L'écran #/matchs/<id>/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 matchRequest = 0;
// Les parties dont l'analyse a été lancée depuis l'ouverture de l'écran.
const matchTried = new Set<string>();
/** 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<PlayedMatch[]> {
const list = await options.games.list();
const games = await Promise.all(
list
.filter((summary) => summary.match !== undefined)
.map(async (summary): Promise<MatchGame | null> => {
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<PlayedMatch | null> {
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<void> {
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 {
@@ -2015,8 +2255,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 {
@@ -2029,11 +2277,31 @@ 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),
crawford: start?.crawford ?? false,
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
@@ -2249,7 +2517,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: () => {
@@ -2293,6 +2561,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");
}
},
};
@@ -2374,7 +2644,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 » ;
@@ -2460,6 +2730,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 ||
@@ -2469,7 +2740,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;
@@ -2481,6 +2753,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);
@@ -2528,6 +2801,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) {
@@ -2588,7 +2870,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") {
@@ -3732,11 +4014,25 @@ function refusedResignation(game: Game): ResultKind | null {
}
/** 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 {
+4
View File
@@ -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.",
+33 -4
View File
@@ -13,11 +13,13 @@
// (#/parties/<id>, 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<readonly MatchLine[]>;
/** « 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<void> {
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;
+5 -1
View File
@@ -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<Record<HapticEvent, readonly number[]>> = {
@@ -19,6 +22,7 @@ export const HAPTIC_PATTERNS: Readonly<Record<HapticEvent, readonly number[]>> =
computerDoubles: [40, 60, 40],
gameWon: [30, 50, 30, 50, 60],
gameLost: [60],
curveGame: [8],
};
/** navigator.vibrate, s'il existe. */
+1
View File
@@ -38,6 +38,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",
+110
View File
@@ -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;
}
+169
View File
@@ -0,0 +1,169 @@
// 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<Record<Side, number>>) => `${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",
/** Le moment décisif tombe sur la fin du match : une seule marque. */
legendDecisiveEnd: "Moment décisif, 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" },
tilesCaption: "Taux d'erreur, en millièmes par décision",
tilesHow: "Comment le lire",
// 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, crawford: boolean) =>
`Partie ${n} sur ${total} · ${score}${crawford ? " · Crawford" : ""}`,
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" : ""} · contre ${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;
+820
View File
@@ -0,0 +1,820 @@
// Le bilan d'un match entier (#/matchs/<id>/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<MoveSteps | null>;
/** « Exporter le match (SGF) ». */
readonly exportSgf: (summary: MatchSummary) => Promise<void>;
/** « 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 };
/** Deux marques plus proches que ceci à l'écran (en x et en y) n'en font
* qu'une : l'anneau du moment décisif (charte, « Bilan du match »). */
const MERGE_DISTANCE = 16;
function element<K extends keyof HTMLElementTagNameMap>(
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<K extends keyof SVGElementTagNameMap>(
parent: Element,
tag: K,
attributes: Record<string, string | number>,
): 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;
// Après un changement de taille de la fenêtre, la mise en page (une
// ou deux colonnes) n'est finie qu'aux images suivantes : la courbe se
// redessine après deux images, sur sa taille rendue.
window.addEventListener("resize", () => {
if (!section.hidden) {
afterLayout(() => 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" });
// La légende suit le tracé : quand l'anneau du moment décisif et le
// point de fin se touchent à l'écran, l'anneau or seul (charte).
let legendKey = "";
const renderLegend = (merged: boolean) => {
const marks: [string, string][] = merged
? [
["decisive", T.legendDecisiveEnd],
["review", T.legendReview],
]
: [
["decisive", T.legendDecisive],
["review", T.legendReview],
[summary.match.winner === "player" ? "end won" : "end", T.legendEnd],
];
const key = String(merged);
if (key === legendKey) {
return;
}
legendKey = key;
legend.replaceChildren();
for (const [mark, text] of marks) {
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 = () => renderLegend(drawCurve(svg, summary, selected));
redrawCurve = draw;
draw();
// Le tracé suit la taille rendue de la courbe (une unité du viewBox
// pour un pixel, les libellés à leur taille) : il se redessine à
// chaque changement de taille, après la mise en page.
if (typeof ResizeObserver !== "undefined") {
new ResizeObserver(() => afterLayout(draw)).observe(svg);
}
afterLayout(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)),
});
}
const unit = element(card, "p", {
id: "match-tiles-caption",
className: "caption match-tiles-caption",
});
unit.append(`${T.tilesCaption} · `);
const how = element(unit, "a", { id: "match-tiles-glossary", text: T.tilesHow });
how.href = routeHash({ screen: "glossary", term: "taux-d-erreur" });
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): boolean {
const box = svg.getBoundingClientRect();
const width = Math.round(box.width || 360);
const height = Math.round(box.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 at = (i: number): { x: number; y: number } | null => {
const c = points[i]?.chance;
return i >= 0 && c !== null && c !== undefined ? { x: x(i), y: y(c) } : null;
};
const mark = (i: number, cls: string, r: number) => {
const p = at(i);
if (p !== null) {
svgElement(svg, "circle", { cx: p.x, cy: p.y, r, class: cls }).setAttribute(
"aria-hidden",
"true",
);
}
};
const decisive = summary.decisive;
const decisiveIndex = decisive === null ? -1 : indexOf(decisive.game, decisive.turn);
if (decisive !== null) {
mark(decisiveIndex, "match-mark-ring", 8);
}
const reviewed = summary.toReview;
if (reviewed !== null) {
mark(indexOf(reviewed.game, reviewed.turn), "match-mark-review", 5);
}
// Le moment décisif et la fin du match à moins de MERGE_DISTANCE l'un
// de l'autre à l'écran : l'anneau or seul tient lieu des deux marques.
const ring = at(decisiveIndex);
const end = summary.match.over ? at(points.length - 1) : null;
const merged =
ring !== null &&
end !== null &&
Math.abs(ring.x - end.x) < MERGE_DISTANCE &&
Math.abs(ring.y - end.y) < MERGE_DISTANCE;
if (end !== null && !merged) {
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);
}
return merged;
}
/** Lance fn après deux images : la mise en page en cours est finie. */
function afterLayout(fn: () => void): void {
requestAnimationFrame(() => requestAnimationFrame(fn));
}
/** 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;
}
+36 -3
View File
@@ -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);
}
+17 -1
View File
@@ -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<PromptPosition | null>;
/** La position que montre le prompt du bilan du match (décision à
* revoir, ou position finale). */
readonly match: (summary: MatchSummary) => Promise<PromptPosition>;
}
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<PromptResult>;
/** Le prompt « Bilan de mon match » (étape 1l). */
match(summary: MatchSummary): Promise<PromptResult>;
}
async function fetchText(url: string): Promise<string> {
@@ -84,12 +91,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;
@@ -127,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(),
+21 -1
View File
@@ -54,6 +54,9 @@ export type Route =
readonly turn: number | null;
readonly ai?: boolean;
}
/** #/matchs/<identifiant>/bilan : le bilan d'un match entier (étape
* 1l) ; son prompt pour une IA : #/matchs/<identifiant>/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":
+29
View File
@@ -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");