Domaine : identifiant de match (événements v3), bilan du match, phrases et prompt

Les parties d'un match partagent un identifiant ; les parties d'avant sont
rattachées d'après les scores et les dates quand c'est sûr. L'analyse de
partie range les chances de gagner le match et les pertes de chaque
décision, converties par le moteur. Bilan du match (agrégation, videau,
moment décisif, courbe continue), phrases du maître, gabarit « Bilan de
mon match », scénario de la remontée de 0–4 à 5–4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-13 00:05:46 +01:00
co-authored by Claude Opus 5.5
parent f9b8663afb
commit 68664dc3f7
29 changed files with 2185 additions and 51 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) {
+518
View File
@@ -0,0 +1,518 @@
// L'analyse d'un match entier (étape 1l ; charte, ecrans-etape-1.md,
// « Bilan du match ») : les parties d'un même match retrouvées, et le bilan
// du match à partir des analyses déjà rangées dans le journal de chaque
// partie (1e). Fonctions pures, testées sous Node
// (app/tests/match-analysis.test.ts).
//
// Copyright (C) 2026 les auteurs d'Ustagammon.
// Licence : GPLv3 ou ultérieure (voir LICENSE).
//
// Rien n'est recalculé ici, et aucune table d'équité de match n'est lue :
// les chances de gagner le match (après chaque coup, au début et à la fin
// de chaque partie) et les pertes en chances de gagner le match viennent
// du moteur, rangées par l'analyse de chaque partie (review.matchChances,
// review.matchLosses). Le taux d'erreur et la chance s'additionnent sur
// tout le match, comme les statistiques de match de gnubg (analysis.c,
// updateStatcontext, cumulées partie après partie par AddStatcontext).
import { type Advice, type Verdict, verdictOf } from "../game/advice.js";
import type { Level } from "../game/engine.js";
import { currentLine, type GameJournal } from "../game/events.js";
import type { Match } from "../game/match.js";
import type { Roll } from "../game/roll.js";
import type { Side } from "../game/side.js";
import { type GameResult, type GameState, replay } from "../game/state.js";
import { decisionsOf } from "./analyse.js";
import {
type ErrorRate,
errorRateOf,
gameTurns,
type LuckSummary,
luckRatingOf,
readyForMatchSummary,
reviewOf,
summarizeAnalysis,
} from "./game-analysis.js";
// ------------------------------------------- Les parties d'un match
/** Une partie de match enregistrée, telle que le stockage la donne. */
export interface MatchGame {
readonly id: string;
/** Début de la partie et dernière action, en millisecondes depuis 1970. */
readonly startedAt: number;
readonly updatedAt: number;
readonly journal: GameJournal;
}
/**
* Un match joué : ses parties dans l'ordre, et où il en est.
*
* Glossaire : docs/glossaire/match.md
*/
export interface PlayedMatch {
/** L'identifiant du match (version 3 des événements) ; pour un match
* d'avant, celui de sa première partie. */
readonly id: string;
/** Les parties ont été rattachées d'après leurs scores et leurs dates
* (parties enregistrées avant l'identifiant de match). */
readonly inferred: boolean;
readonly length: number;
readonly level: Level;
readonly games: readonly MatchGame[];
readonly startedAt: number;
readonly updatedAt: number;
/** Le score : après la dernière partie si elle est finie, avant elle
* sinon. */
readonly score: Readonly<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.
*
* Glossaire : docs/glossaire/chances-de-gagner-le-match.md
*/
export interface MatchCurvePoint {
readonly game: number;
readonly gameId: string;
/** Le tour (null : le début du match, avant le premier jet). */
readonly turn: number | null;
/** Le camp qui avait la main (null au début du match). */
readonly side: Side | null;
readonly roll: Roll | null;
/** Les chances du joueur de gagner le match après ce tour, de 0 à 1
* (null : pas encore analysé). */
readonly chance: number | null;
/** L'appréciation de la décision du joueur la plus coûteuse du tour. */
readonly verdict: Verdict | null;
/** Le tour finit la partie. */
readonly ends: boolean;
}
/** Le moment décisif : le tour qui a fait le plus varier les chances de
* gagner le match. Ce peut être un coup de dés : aucun jugement. */
export interface DecisiveMoment {
readonly game: number;
readonly gameId: string;
readonly turn: number;
readonly side: Side;
/** Le jet du tour (null : un tour fini sur un double passé). */
readonly roll: Roll | null;
readonly from: number;
readonly to: number;
}
/** Le bilan d'un match. */
export interface MatchSummary {
readonly match: PlayedMatch;
readonly rows: readonly MatchGameRow[];
/** Toutes les parties ont l'analyse qu'il faut au bilan
* (readyForMatchSummary) ; sinon, les chiffres sont partiels. */
readonly ready: boolean;
/** Le taux d'erreur sur tout le match, sur les pions, sur le videau. */
readonly errorRate: ErrorRate;
readonly chequer: ErrorRate;
readonly cube: ErrorRate;
/** La chance de vos dés sur tout le match. */
readonly luck: LuckSummary;
/** Vos décisions de videau comptées (comme le taux d'erreur du
* videau), et celles qui diffèrent du moteur, dans l'ordre du bilan. */
readonly cubeDecisions: number;
readonly cubeErrors: readonly CubeError[];
readonly decisive: DecisiveMoment | null;
/** La décision à revoir : la plus grande perte de chances de gagner le
* match, pions ou videau, parmi les imprécisions et les erreurs. */
readonly toReview: MatchDecision | null;
readonly curve: readonly MatchCurvePoint[];
/** Le plus grand retard remonté par le vainqueur du match : le score
* au début de la partie où il était le plus mené (null : jamais
* mené, ou match pas fini). */
readonly comeback: Readonly<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" && a.equityLoss < 0 && CUBE_KIND[a.action] === kind) {
cubeErrors.push({ ...d, kind });
}
}
}
const cube = errorRateOf(cubeAdvices);
const perRoll = rolls > 0 ? luckTotal / rolls : 0;
let toReview: MatchDecision | null = null;
for (const d of decisions) {
if (verdictOf(d.advice.skill) === "good") {
continue;
}
const cost = (x: MatchDecision) => x.loss ?? 0;
if (toReview === null || cost(d) < cost(toReview)) {
toReview = d;
}
}
return {
match,
rows,
ready,
errorRate: errorRateOf(all),
chequer: errorRateOf(all.filter((a) => a.kind === "move")),
cube,
luck: {
total: luckTotal,
rolls,
perRoll,
rating: luckRatingOf(perRoll),
points: 0,
},
cubeDecisions: Math.max(cube.decisions, cubeErrors.length),
cubeErrors,
decisive: decisiveMoment(curve),
toReview,
curve,
comeback: comebackOf(match, rows),
};
}
/** Le tour qui a fait le plus varier les chances de gagner le match, entre
* deux points analysés qui se suivent (le premier en cas d'égalité). */
function decisiveMoment(curve: readonly MatchCurvePoint[]): DecisiveMoment | null {
let best: DecisiveMoment | null = null;
for (let i = 1; i < curve.length; i++) {
const a = curve[i - 1] as MatchCurvePoint;
const b = curve[i] as MatchCurvePoint;
if (a.chance === null || b.chance === null || b.turn === null || b.side === null) {
continue;
}
if (best === null || Math.abs(b.chance - a.chance) > Math.abs(best.to - best.from)) {
best = {
game: b.game,
gameId: b.gameId,
turn: b.turn,
side: b.side,
roll: b.roll,
from: a.chance,
to: b.chance,
};
}
}
return best;
}
/** Le plus grand retard du vainqueur au début d'une partie. */
function comebackOf(
match: PlayedMatch,
rows: readonly MatchGameRow[],
): Readonly<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 } from "../game/engine.js";
import type { GameSummary } from "./game-analysis.js";
import type { CubeErrorKind, DecisiveMoment } from "./match-analysis.js";
import { formatPercent } from "./numbers.js";
import type { ProgressionTrend } from "./progression.js";
/** Les gabarits, par clé de section (« coup.meilleur »…). */
@@ -108,6 +110,15 @@ export const PHRASE_KEYS: readonly string[] = [
"progression.hausse",
"progression.stable",
"progression.attente",
"match.videau.ecarts",
"match.videau.un-seul-ecart",
"match.videau.aucun-ecart",
"match.videau.seule",
"match.videau.aucune",
"match.videau.sans-ecart",
"match.decisif.jet",
"match.decisif.jet-ordinateur",
"match.decisif.videau",
];
const DICE_KEYS: Readonly<Record<LuckRating, string>> = {
@@ -165,6 +176,65 @@ export function progressionSentence(phrases: MasterPhrases, trend: ProgressionTr
});
}
/** La phrase de la section « Le videau » du bilan du match (étape 1l) :
* combien de décisions de videau, et pour combien le maître aurait fait
* autrement. */
export function matchCubeSentence(
phrases: MasterPhrases,
decisions: number,
differing: number,
): string {
const counted = `${decisions} décision${decisions > 1 ? "s" : ""} de videau`;
if (decisions === 0) {
return pick(phrases, "match.videau.aucune", "0");
}
if (decisions === 1) {
return pick(
phrases,
differing > 0 ? "match.videau.un-seul-ecart" : "match.videau.seule",
"0",
);
}
return differing > 0
? fillIn(pick(phrases, "match.videau.ecarts", "0"), {
decisions: counted,
ecarts: String(differing),
})
: fillIn(pick(phrases, "match.videau.aucun-ecart", "0"), { decisions: counted });
}
/** Les sortes de décisions de videau sans écart, en une phrase chacune :
* vos doubles (doubler à tort, ne pas doubler à tort) et vos réponses
* (prendre, passer), quand aucune des deux sortes n'a d'écart. */
export function matchCubeAgreements(
phrases: MasterPhrases,
without: readonly CubeErrorKind[],
): string[] {
const groups = [
{ kinds: ["wrongDouble", "missedDouble"], name: "Doubles" },
{ kinds: ["wrongTake", "wrongPass"], name: "Prises et refus" },
] as const;
return groups
.filter((group) => group.kinds.every((kind) => without.includes(kind)))
.map((group) =>
fillIn(pick(phrases, "match.videau.sans-ecart", "0"), { sortes: group.name }),
);
}
/** La phrase du moment décisif du match : le jet (ou le double passé) et
* vos chances de gagner le match avant et après, en pourcentages. */
export function decisiveSentence(phrases: MasterPhrases, moment: DecisiveMoment): string {
const values = { avant: formatPercent(moment.from), apres: formatPercent(moment.to) };
if (moment.roll === null) {
return fillIn(pick(phrases, "match.decisif.videau", "0"), values);
}
const key = moment.side === "player" ? "match.decisif.jet" : "match.decisif.jet-ordinateur";
return fillIn(pick(phrases, key, "0"), {
...values,
roll: `${moment.roll[0]}-${moment.roll[1]}`,
});
}
/** Ce que le maître dit d'un conseil du moteur. */
export function masterWords(phrases: MasterPhrases, advice: Advice): MasterWords {
return advice.kind === "move" ? moveWords(phrases, advice) : cubeWords(phrases, advice);
+32 -8
View File
@@ -26,9 +26,13 @@ import type { Side } from "./side.js";
* - 1 : jusqu'à l'étape 1b, partie libre au niveau 2 plis ;
* - 2 (étape 1c) : GameStarted porte le niveau de l'ordinateur (level) et,
* pour une partie de match, le match (match) ; GameEnded porte le match
* après la partie. migrateJournal passe un journal de la version 1 à la 2.
* après la partie ;
* - 3 (étape 1l) : le match de GameStarted porte l'identifiant du match
* (match.id), commun à toutes ses parties. Une partie de la version 2
* n'en a pas : rien d'autre ne change.
* migrateJournal passe un journal des versions 1 et 2 à la 3.
*/
export const EVENT_VERSION = 2;
export const EVENT_VERSION = 3;
/** Le niveau des parties de la version 1 : 2 plis (STANDARD_PLY, sans
* bruit), le seul qui existait. */
@@ -37,8 +41,11 @@ const VERSION_1_LEVEL: Level = "2ply";
/**
* Un journal enregistré, à la version courante du format. Version 1 : le
* niveau, implicite, devient explicite (2 plis) ; rien d'autre ne change,
* une partie de la version 1 étant une partie libre. Un événement d'une
* version inconnue est laissé tel quel (Game.resume le refuse).
* une partie de la version 1 étant une partie libre. Version 2 : seul le
* numéro change ; une partie de match de la version 2 reste sans
* identifiant de match (il n'est pas inventé : groupMatches la rattache à
* son match d'après les scores et les dates). Un événement d'une version
* inconnue est laissé tel quel (Game.resume le refuse).
*/
export function migrateJournal(saved: GameJournal): GameJournal {
const journal = keepKnownReview(keepKnownAdvice(saved));
@@ -46,10 +53,10 @@ export function migrateJournal(saved: GameJournal): GameJournal {
return journal;
}
const events = journal.events.map((event): GameEvent => {
if (event.version !== 1) {
if (event.version !== 1 && event.version !== 2) {
return event;
}
if (event.type === "GameStarted") {
if (event.type === "GameStarted" && event.version === 1) {
return Object.freeze({
...event,
level: event.level ?? VERSION_1_LEVEL,
@@ -125,16 +132,33 @@ function keepKnownReview(journal: GameJournal): GameJournal {
a.eventId === id,
),
);
// Les tables du match (étape 1l), facultatives : une table mal formée
// est oubliée, ses nombres hors d'un événement du journal aussi.
const numbers = (table: unknown): Record<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,
+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,
@@ -524,3 +538,188 @@ export function exercisesPrompt(
position_titre: `La plus coûteuse (partie ${worst.game}, coup ${worst.turn}) : la position avant ma décision`,
});
}
// ------------------------------------------------- Le bilan d'un match
/** Les sortes d'erreurs de videau, comme le bilan du match les nomme
* (charte, « Bilan du match »). */
export const CUBE_ERROR_WORDS: Readonly<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. */
+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) {
+1
View File
@@ -37,6 +37,7 @@ export const FEATURES = [
"docs/scenarios/apprendre-les-regles.feature",
"docs/scenarios/suivre-une-lecon.feature",
"docs/scenarios/suivre-ma-progression.feature",
"docs/scenarios/analyser-mon-match.feature",
"docs/scenarios/mes-parties.feature",
"docs/scenarios/partager-une-position.feature",
"docs/scenarios/regler-l-application.feature",
+167
View File
@@ -0,0 +1,167 @@
// Les textes du bilan d'un match entier (étape 1l ; charte,
// ecrans-etape-1.md, « Bilan du match »), des lignes de match des listes
// et des accès au bilan du match. Les phrases du maître elles-mêmes (le
// videau, le moment décisif) sont dans docs/maitre/phrases.md (une seule
// source, ADR 0008).
//
// Copyright (C) 2026 les auteurs d'Ustagammon.
// Licence : GPLv3 ou ultérieure (voir LICENSE).
import type { MatchSummary, PlayedMatch } from "../domain/analysis/match-analysis.js";
import type { Side } from "../domain/game/side.js";
import type { GameResult } from "../domain/game/state.js";
import { gamesWord, matchScoreText } from "../domain/prompts/prompts.js";
export { CUBE_ERROR_WORDS, matchScoreText } from "../domain/prompts/prompts.js";
const DATE = new Intl.DateTimeFormat("fr-FR", { day: "numeric", month: "long" });
const partsWord = (n: number) => `${gamesWord(n)} partie${n > 1 ? "s" : ""}`;
/** « mené 0 à 4 » : un score lu du point de vue du joueur. */
const scoreWords = (score: Readonly<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",
bubble: (game: number, turn: number | null, score: string, chance: string) =>
turn === null
? `Début du match · ${score} · ${chance}`
: `Partie ${game}, coup ${turn} · ${score} · ${chance}`,
bubbleOpen: "Toucher pour ouvrir cette décision",
pending: "La courbe se complète pendant l'analyse.",
// Partie par partie
gamesTitle: "Partie par partie",
gameRow: (n: number) => `Partie ${n}`,
gameResult: (result: GameResult | null, cube: number) => {
if (result === null) {
return "en cours";
}
const who = result.winner === "player" ? "Gagnée" : "Perdue";
const kind =
result.kind === "single"
? ""
: ` · ${result.kind === "gammon" ? "gammon" : "backgammon"}`;
const doubled = cube > 1 ? ` · videau ${cube}` : "";
return `${who}${kind}${doubled}`;
},
gamePoints: (result: GameResult | null) =>
result === null
? ""
: `${result.winner === "player" ? "Vous marquez" : "L'ordinateur marque"} ${result.points} point${result.points > 1 ? "s" : ""}`,
gameRowLabel: (n: number, result: string, points: string, score: string) =>
`Partie ${n} : ${result}. ${points}. Score après la partie : ${score}.`,
crawford: "Crawford",
scoreReminder: "Le score se lit toujours vous – l'ordinateur.",
// Votre jeu
playTitle: "Votre jeu sur le match",
tiles: { all: "Tout le match", chequer: "Les pions", cube: "Le videau" },
tileUnit: "millièmes par décision",
tileNone: "aucune décision",
// Le videau
cubeTitle: "Le videau",
cubeWhere: (game: number, turn: number, score: string) =>
`Partie ${game}, coup ${turn}, à ${score}`,
cubeLossPending: "perte en calcul",
cubeRowLabel: (kind: string, where: string, loss: string) =>
`${kind}, ${where} : ${loss} de chances de gagner le match`,
// Le moment décisif
decisiveTitle: "Le moment décisif",
decisiveNone: "Le moment décisif apparaîtra quand l'analyse sera finie.",
seeThisMove: "Voir ce coup",
// La décision à revoir
reviewTitle: "La décision à revoir",
reviewWhere: (game: number, turn: number, score: string) =>
`Partie ${game}, coup ${turn}, à ${score}`,
lossOf: (loss: string) => `${loss} de chances de gagner le match`,
review: "Revoir",
// Export
exportSgf: "Exporter le match (SGF)",
exportHint: "pour l'ouvrir dans GNU Backgammon",
exportFailed: (reason: string) => `L'export n'a pas abouti : ${reason}`,
// Barre d'actions
reviewMatch: "Revoir le match",
newMatch: "Nouveau match",
resumeMatch: "Reprendre le match",
// Accès
seeMatchSummary: "Bilan du match",
seeMatchSummaryLink: "Voir le bilan du match",
/** Sous l'en-tête du bilan d'une partie de match. */
gameOfMatch: (n: number, length: number) => `Partie ${n} du match en ${length} points`,
/** En tête de l'analyse d'une partie de match : « Partie 2 sur 5 · 0–2 ». */
analysisHeader: (n: number, total: number, score: string) =>
`Partie ${n} sur ${total} · ${score}`,
previousGame: "Partie précédente",
nextGame: "Partie suivante",
// Les listes
listTitle: (match: PlayedMatch) => {
const score = matchScoreText(match.score);
const state = match.over
? `${match.winner === "player" ? "gagné" : "perdu"} ${score}`
: `en cours, ${score}`;
return `Match en ${match.length} points · ${state}`;
},
listCaption: (date: string, games: number, level: string) =>
`${date} · ${games} partie${games > 1 ? "s" : ""} · ${level}`,
listInferred: "rattaché d'après les scores",
resume: "Reprendre",
errorRate: (millis: number) => `${millis}`,
errorRateLabel: (millis: number) => `Taux d'erreur du match : ${millis} millièmes`,
} as const;
+2 -1
View File
@@ -84,12 +84,13 @@ export function createPromptSource(options: PromptSourceOptions): PromptSource {
parsePromptTemplate(await fetchText(PROMPTS_DIR + PROMPT_FILES[kind])),
),
).then(
([move, cube, summary, concept, exercises]) => ({
([move, cube, summary, concept, exercises, match]) => ({
move: move ?? "",
cube: cube ?? "",
summary: summary ?? "",
concept: concept ?? "",
exercises: exercises ?? "",
match: match ?? "",
}),
(error: unknown) => {
loading = null;