Domaine : abandon proposé, accepté ou refusé (événements version 3)

Trois événements d'abandon et le champ resigned de GameEnded, migration
des versions 1 et 2 testée ; points selon le videau, score et Crawford
du match par le moteur ; export SGF à la manière de gnubg (RE[W+4R]),
relu par gnubg de bureau. Phrases abandon.refus et abandon.accepte,
fiche Abandon, scénarios Gherkin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-13 08:14:35 +01:00
co-authored by Claude Opus 5.5
parent e98497e5b1
commit de32811bba
20 changed files with 741 additions and 38 deletions
+154 -3
View File
@@ -63,6 +63,13 @@ function fakeEngine(overrides: Partial<Engine> = {}): Engine {
levelCubeDecision: async () => noDouble,
levelDouble: async () => false,
levelTake: async () => true,
resignation: async () => ({
options: [
{ kind: "single", possible: true, points: 1, accepted: true },
{ kind: "gammon", possible: false, points: 2, accepted: true },
{ kind: "backgammon", possible: false, points: 3, accepted: true },
],
}),
matchAfterGame: async (match, winner, points) => {
const score = { ...match.score };
score[winner] += points;
@@ -355,7 +362,7 @@ test("les événements sont immuables et versionnés ; le rejeu est déterminist
});
journal = appendEvent(journal, { type: "DiceRolled", side: null, roll: [5, 2] });
const [started, rolled] = currentLine(journal);
assert.equal(started?.version, 2);
assert.equal(started?.version, EVENT_VERSION);
assert.equal(started?.parent, null);
assert.equal(rolled?.parent, started?.id);
assert.throws(() => {
@@ -549,7 +556,7 @@ test("« Rejouer » une partie libre : une partie libre au même niveau, depuis
assert.deepEqual(game.rematch, { level: "0ply" });
});
test("migration : un journal de la version 1 se reprend en version 2, au niveau 2 plis, en partie libre", async () => {
test("migration : un journal de la version 1 se reprend en version courante, au niveau 2 plis, en partie libre", async () => {
// Un journal tel que l'étape 1b l'enregistrait : version 1, GameStarted
// sans level ni match, un coup joué, une branche.
const v1 = {
@@ -603,7 +610,151 @@ test("migration : un journal de la version 1 se reprend en version 2, au niveau
assert.equal(resumed.state.level, "2ply");
assert.equal(resumed.state.match, null);
assert.ok(resumed.journal.events.every((event) => event.version === EVENT_VERSION));
// La partie continue en version 2.
// La partie continue en version courante.
await resumed.playComputerTurn();
assert.ok(resumed.journal.events.every((event) => event.version === EVENT_VERSION));
});
test("migration : un journal de la version 2 se reprend en version 3 sans autre changement", () => {
const v2 = {
events: [
{
id: "1",
parent: null,
version: 2,
type: "GameStarted",
position: "X",
cube: { value: 1, owner: null },
firstTurn: "player",
level: "0ply",
},
{ id: "2", parent: "1", version: 2, type: "CubeOffered", side: "player" },
{ id: "3", parent: "2", version: 2, type: "CubeDropped", side: "computer" },
{
id: "4",
parent: "3",
version: 2,
type: "GameEnded",
winner: "player",
kind: "single",
points: 1,
},
],
head: "4",
} as unknown as GameJournal;
assert.equal(EVENT_VERSION, 3);
const migrated = migrateJournal(v2);
assert.ok(migrated.events.every((event) => event.version === 3));
const strip = (journal: GameJournal) => journal.events.map(({ version: _, ...event }) => event);
assert.deepEqual(strip(migrated), strip(v2));
assert.deepEqual(replay(currentLine(migrated)), replay(currentLine(v2)));
// Une partie finie sans abandon : resigned reste absent.
assert.deepEqual(replay(currentLine(migrated)).result, {
winner: "player",
kind: "single",
points: 1,
});
// Une version inconnue est refusée.
const v4 = {
...v2,
events: v2.events.map((e) => ({ ...e, version: 4 })),
} as unknown as GameJournal;
assert.throws(() => Game.resume(fakeEngine(), v4), /autre version/);
});
/** Un faux moteur dont l'ordinateur répond à l'abandon : il accepte le
* gammon, refuse la partie simple ; le backgammon n'est pas proposé. */
function resigningEngine(): Engine {
return fakeEngine({
resignation: async (_position, cube) => ({
options: [
{ kind: "single", possible: true, points: cube.value, accepted: false },
{ kind: "gammon", possible: true, points: 2 * cube.value, accepted: true },
{ kind: "backgammon", possible: false, points: 3 * cube.value, accepted: true },
],
}),
});
}
test("abandon : seulement à votre tour, avant le lancer ; les choix possibles du moteur", async () => {
const game = Game.start(resigningEngine(), {
dice: fixedDice([3, 1]),
setup: { position: "X", firstTurn: "player", cube: { value: 2, owner: "computer" } },
});
assert.deepEqual(
(await game.resignOptions()).map((c) => [c.kind, c.points, c.matchAfter]),
[
["single", 2, null],
["gammon", 4, null],
],
);
await assert.rejects(game.resign("backgammon"), /abandon impossible/);
await game.roll();
assert.deepEqual(await game.resignOptions(), []);
await assert.rejects(game.resign("single"), /action impossible/);
});
test("abandon refusé : la partie continue, toujours à vous de lancer", async () => {
const game = Game.start(resigningEngine(), {
dice: fixedDice([3, 1]),
setup: { position: "X", firstTurn: "player", cube: { value: 2, owner: "computer" } },
});
assert.equal(await game.resign("single"), false);
assert.deepEqual(
game.events.slice(-2).map((e) => [e.type, "side" in e ? e.side : null]),
[
["ResignationOffered", "player"],
["ResignationDeclined", "computer"],
],
);
assert.equal(game.state.phase, "rolling");
assert.equal(game.state.turn, "player");
assert.equal(game.state.result, null);
await game.roll();
assert.equal(game.state.phase, "moving");
});
test("abandon accepté : fin de partie, points du videau ; dans un match, le score et Crawford", async () => {
const free = Game.start(resigningEngine(), {
dice: fixedDice([3, 1]),
setup: { position: "X", firstTurn: "player", cube: { value: 2, owner: "computer" } },
});
assert.equal(await free.resign("gammon"), true);
assert.deepEqual(free.state.result, {
winner: "computer",
kind: "gammon",
points: 4,
resigned: true,
});
const end = free.events.at(-1);
assert.ok(end?.type === "GameEnded" && end.resigned === true);
// Le journal enregistré se reprend tel quel.
const resumed = Game.resume(resigningEngine(), JSON.parse(JSON.stringify(free.journal)));
assert.deepEqual(resumed.state.result, free.state.result);
// Dans un match en 3 points, 0 à 0 : le gammon (2 points, videau à 1)
// mène l'ordinateur à 2 ; la partie suivante est la partie Crawford.
const match = Game.start(resigningEngine(), {
dice: fixedDice([3, 1]),
setup: { position: "X", firstTurn: "player" },
match: { length: 3, score: { player: 0, computer: 0 }, crawford: false },
});
assert.deepEqual(
(await match.resignOptions()).map((c) => [c.kind, c.matchAfter]),
[
["single", { score: { player: 0, computer: 1 }, over: false, crawford: false }],
["gammon", { score: { player: 0, computer: 2 }, over: false, crawford: true }],
],
);
assert.equal(await match.resign("gammon"), true);
assert.deepEqual(match.state.matchAfter, {
score: { player: 0, computer: 2 },
over: false,
crawford: true,
});
assert.deepEqual(match.nextGame?.match, {
length: 3,
score: { player: 0, computer: 2 },
crawford: true,
});
});
+34 -1
View File
@@ -16,7 +16,11 @@ import {
runAnalysis,
summarizeAnalysis,
} from "../src/domain/analysis/game-analysis.js";
import { PHRASE_KEYS, progressionSentence } from "../src/domain/analysis/phrases.js";
import {
PHRASE_KEYS,
progressionSentence,
resignationAnswer,
} from "../src/domain/analysis/phrases.js";
import {
CURVE_MIN_GAMES,
errorRateMillis,
@@ -264,3 +268,32 @@ test("les thèmes des erreurs : faits du moteur seulement, une ligne par fait pr
);
assert.deepEqual(mistakeThemes([cube]), ["- 0 coup et 1 décision de videau"]);
});
test("les phrases de l'abandon (étape 1k) : des faits, sous 140 caractères", () => {
for (const key of ["abandon.refus", "abandon.accepte"]) {
assert.ok(PHRASE_KEYS.includes(key), key);
}
assert.equal(
resignationAnswer(phrases, "single", false, 2),
"L'ordinateur refuse. D'après le moteur, il peut espérer plus qu'une partie simple en continuant. La partie continue.",
);
assert.equal(
resignationAnswer(phrases, "gammon", false, 4),
"L'ordinateur refuse. D'après le moteur, il peut espérer plus qu'un gammon en continuant. La partie continue.",
);
assert.equal(
resignationAnswer(phrases, "gammon", true, 4),
"L'ordinateur accepte votre abandon : vous perdez un gammon, 4 points.",
);
assert.equal(
resignationAnswer(phrases, "single", true, 1),
"L'ordinateur accepte votre abandon : vous perdez une partie simple, 1 point.",
);
for (const kind of ["single", "gammon", "backgammon"] as const) {
for (const accepted of [true, false]) {
const sentence = resignationAnswer(phrases, kind, accepted, 6);
assert.ok(sentence.length < 140, sentence);
assert.ok(!sentence.includes("!"), sentence);
}
}
});
@@ -0,0 +1,143 @@
// Étapes du scénario docs/scenarios/abandonner-une-partie.feature (ADR
// 0008) : le domaine branché sur le vrai moteur, depuis des positions de
// référence comparées à gnubg de bureau (tests/reference/analyses.json,
// abandons resign-…).
//
// Copyright (C) 2026 les auteurs d'Ustagammon.
// Licence : GPLv3 ou ultérieure (voir LICENSE).
import assert from "node:assert/strict";
import { BeforeAll, Given, setDefaultTimeout, Then, When } from "@cucumber/cucumber";
import type { Cube } from "../../src/domain/game/cube.js";
import type { Engine, ResultKind } from "../../src/domain/game/engine.js";
import { Game, type ResignChoice } from "../../src/domain/game/game.js";
import { firstGameOf, type Match } from "../../src/domain/game/match.js";
import { fixedDice } from "../../src/domain/game/roll.js";
import { TEXTS } from "../../src/ui/texts.js";
import { loadNodeEngine } from "../support/node-engine.js";
setDefaultTimeout(60_000);
// Le joueur au trait subit une attaque : gammon perdu à 49 % (0 pli).
const ATTACKED = "sp2DBwDgOfgAaA";
// Une attaque où le gammon est moins probable (36 %).
const LESS_GAMMONS = "tF2DBwDgc/ABUA";
const CUBE_2_COMPUTER: Cube = { value: 2, owner: "computer" };
let engine: Engine;
let game: Game;
let choices: ResignChoice[];
let answer: boolean;
BeforeAll(async () => {
engine = await loadNodeEngine();
});
function start(position: string, cube?: Cube, match?: Match): void {
game = Game.start(engine, {
dice: fixedDice([3, 1]),
setup: { position, firstTurn: "player", ...(cube === undefined ? {} : { cube }) },
...(match === undefined ? {} : { match }),
});
}
const KINDS: Record<string, ResultKind> = {
"une partie simple": "single",
"un gammon": "gammon",
"un backgammon": "backgammon",
};
Given("l'ordinateur vous attaque, avec le videau à 2 chez lui, et qu'un gammon est probable", () =>
start(ATTACKED, CUBE_2_COMPUTER),
);
Given(
"l'ordinateur vous attaque, avec le videau à 2 chez lui, et qu'un gammon est moins probable",
() => start(LESS_GAMMONS, CUBE_2_COMPUTER),
);
Given("la même position se joue en partie libre, videau au centre", () => start(LESS_GAMMONS));
Given("l'ordinateur vous attaque dans un match en 7 points, à 0 partout", () =>
start(ATTACKED, undefined, firstGameOf(7)),
);
When(/^vous proposez d'abandonner (une partie simple|un gammon|un backgammon)$/, async (what) => {
const kind = KINDS[what as string];
assert.ok(kind !== undefined);
answer = await game.resign(kind);
});
Then("l'ordinateur refuse", () => {
assert.equal(answer, false);
assert.deepEqual(
game.events.slice(-2).map((e) => e.type),
["ResignationOffered", "ResignationDeclined"],
);
});
Then("l'ordinateur accepte", () => {
assert.equal(answer, true);
assert.deepEqual(
game.events.slice(-3).map((e) => e.type),
["ResignationOffered", "ResignationAccepted", "GameEnded"],
);
});
Then("la partie continue, et c'est à vous de lancer les dés", async () => {
assert.equal(game.state.phase, "rolling");
assert.equal(game.state.turn, "player");
// Le drapeau reste disponible.
assert.ok((await game.resignOptions()).length > 0);
});
Then(/^la partie est perdue par abandon, (.+)$/, (text) => {
const result = game.state.result;
assert.ok(result !== null);
assert.equal(result.winner, "computer");
assert.equal(result.resigned, true);
assert.equal(TEXTS.resignedResult(result.kind, result.points), `Perdue par abandon, ${text}`);
// Plus rien à proposer : la partie est finie.
assert.equal(game.state.phase, "over");
});
Then("vous pouvez proposer une partie simple, un gammon ou un backgammon", async () => {
choices = await game.resignOptions();
assert.deepEqual(
choices.map((c) => [c.kind, c.points]),
[
["single", 2],
["gammon", 4],
["backgammon", 6],
],
);
});
Then("vous ne pouvez proposer qu'une partie simple", async () => {
choices = await game.resignOptions();
assert.deepEqual(
choices.map((c) => [c.kind, c.points, c.matchAfter]),
[["single", 1, null]],
);
});
Then("chaque choix montre le score qui en résulterait", async () => {
choices = await game.resignOptions();
assert.deepEqual(
choices.map((c) => [c.kind, c.matchAfter?.score.player, c.matchAfter?.score.computer]),
[
["single", 0, 1],
["gammon", 0, 2],
["backgammon", 0, 3],
],
);
});
Then(/^le score du match devient : vous (\d+), l'ordinateur (\d+)$/, (player, computer) => {
const after = game.state.matchAfter;
assert.ok(after !== null);
assert.deepEqual(after.score, { player: Number(player), computer: Number(computer) });
assert.equal(after.over, false);
// Le match continue : la partie suivante reprend ce score.
assert.deepEqual(game.nextGame?.match?.score, after.score);
});
+38
View File
@@ -111,6 +111,44 @@ async function main(): Promise<void> {
games.push(["setup-unfinished", game]);
}
// Abandons (étape 1k), depuis la position de référence
// « resign-gammon-likely » : en partie libre, videau à 2 chez
// l'ordinateur, le simple refusé, quelques coups, puis le gammon
// accepté s'il l'est encore (sinon la partie reste en cours) ; dans un
// match en 7 points, le gammon accepté d'entrée.
{
const game = Game.start(engine, {
dice: seededDice(19),
level: "0ply",
setup: {
position: "sp2DBwDgOfgAaA",
firstTurn: "player",
cube: { value: 2, owner: "computer" },
},
});
await game.resign("single");
await game.resign("gammon");
games.push(["resign-free", game]);
}
{
const game = Game.start(engine, {
dice: seededDice(23),
level: "0ply",
setup: { position: "sp2DBwDgOfgAaA", firstTurn: "player" },
match: { length: 7, score: { player: 0, computer: 0 }, crawford: false },
});
await game.resign("single");
await playMoves(game, engine, 2);
if (game.state.phase === "rolling" && game.state.turn === "player") {
const choices = await game.resignOptions();
const last = choices.at(-1);
if (last !== undefined) {
await game.resign(last.kind);
}
}
games.push(["resign-match", game]);
}
let files = 0;
for (const [name, game] of games) {
const original = game.journal;