diff --git a/docs/ai-policy.md b/docs/ai-policy.md index 89a5fad..8029e4a 100644 --- a/docs/ai-policy.md +++ b/docs/ai-policy.md @@ -89,3 +89,10 @@ Reproduce a current-policy batch with `node scripts/benchmark-policy.mjs current Before using planning rerolls, the bot evaluates its desired route and any useful prospective Binoculars swap. A swap is considered useful only when the normal route planner would choose its improved destination. Torch and Water flask are evaluated against that intended destination, including its hypothetical post-swap requirements. The bot rolls first and reevaluates the route and swap afterward; it does not spend Binoculars merely to improve an unused nearby tile. A prospective swap does not place a destination marker, which would make that tile ineligible for swapping. Regression coverage verifies reroll selection against the proposed destination without mutating the board or consulting hidden teammate dice. A further 168 games spanning all scenarios, player counts and difficulties completed with exact replays and no deadlocks. This validation batch is not a matched win-rate comparison. + + +## Helping from a safe village + +A bot staying on its current village tile can prioritise reducing its dice contributions against escaping comparison neighbours. It applies only outside the next eruption wave, with stamina strictly above the maximum possible loss for this round. Rerolls seek lower opposing contributions instead of improving the resident's own result. Buddy and Machete may set aside dice that also match the resident's own location. Residents at risk of exhaustion or threatened by lava retain the ordinary survival policy. Hidden teammate dice remain unavailable. + +A matched 252-game comparison across seven scenarios, 2–4 players and difficulties 1–4 increased complete-team wins from 65 (25.8%) to 69 (27.4%). Every game terminated and replayed exactly. This four-win difference is modest; it does not establish a universally stronger policy. Results are in `ai-village-help-benchmark.json`, using seed family `village-help`, 12 seeds per scenario/player-count combination. The baseline is the AI from commit b769c7e. diff --git a/docs/ai-village-help-benchmark.json b/docs/ai-village-help-benchmark.json new file mode 100644 index 0000000..12a82ad --- /dev/null +++ b/docs/ai-village-help-benchmark.json @@ -0,0 +1,125 @@ +{ + "baselineCommit": "b769c7e", + "before": { + "name": "old", + "family": "village-help", + "policy": { + "equipment": true, + "lead": 1, + "progress": 4, + "success": 18, + "stamina": 1, + "teamwork": 0.4, + "cost": 0.8 + }, + "games": 252, + "wins": 65, + "moves": 16152, + "byScenario": { + "1": { + "games": 36, + "wins": 14 + }, + "2": { + "games": 36, + "wins": 10 + }, + "3": { + "games": 36, + "wins": 4 + }, + "4": { + "games": 36, + "wins": 8 + }, + "5": { + "games": 36, + "wins": 8 + }, + "6": { + "games": 36, + "wins": 13 + }, + "7": { + "games": 36, + "wins": 8 + } + }, + "equipment": { + "torch": 45, + "flare": 81, + "rope": 41, + "binoculars": 74, + "tape": 17, + "map": 94, + "aid": 99, + "radio": 60, + "shovel": 103, + "water": 62, + "machete": 35, + "compass": 34 + }, + "stalled": [] + }, + "after": { + "name": "current", + "family": "village-help", + "policy": { + "equipment": true, + "lead": 1, + "progress": 4, + "success": 18, + "stamina": 1, + "teamwork": 0.4, + "cost": 0.8 + }, + "games": 252, + "wins": 69, + "moves": 15991, + "byScenario": { + "1": { + "games": 36, + "wins": 15 + }, + "2": { + "games": 36, + "wins": 10 + }, + "3": { + "games": 36, + "wins": 4 + }, + "4": { + "games": 36, + "wins": 9 + }, + "5": { + "games": 36, + "wins": 10 + }, + "6": { + "games": 36, + "wins": 12 + }, + "7": { + "games": 36, + "wins": 9 + } + }, + "equipment": { + "torch": 44, + "flare": 80, + "rope": 41, + "binoculars": 74, + "tape": 16, + "map": 94, + "aid": 100, + "radio": 60, + "shovel": 103, + "water": 62, + "machete": 34, + "compass": 36 + }, + "stalled": [] + } +} diff --git a/packages/engine/src/ai.ts b/packages/engine/src/ai.ts index bb1f55a..9c3121f 100644 --- a/packages/engine/src/ai.ts +++ b/packages/engine/src/ai.ts @@ -15,7 +15,7 @@ import { hasSkill, walkable, } from "./game.js"; -import { terrain, SKILLS, matches, DICE, EQUIPMENT, type Requirement, type EquipmentId } from "./data.js"; +import { terrain, SKILLS, matches, DICE, EQUIPMENT, EXHAUSTION, type Requirement, type EquipmentId } from "./data.js"; import type { State, View, Move, Die } from "./types.js"; export interface AiPolicy { @@ -41,6 +41,18 @@ const ruleAt = (game: View, seat: number) => const valueOf = (d: Die, r: Requirement) => (matches(face(d), r) ? d.face : 0); const urgency = (game: View, seat: number) => (threatened(game).includes(game.players[seat]!.position) ? 3 : 1); +// A resident can sacrifice its comparison when even the worst loss is survivable. +function villageHelper(game: View, seat: number): boolean { + const p = game.players[seat]!; + return ( + p.path.at(-1) === p.position && + terrain(cell(game, p.position).terrain).kind === "village" && + !threatened(game).includes(p.position) && + EXHAUSTION - p.stamina > game.difficulty + 2 && + neighbors(game, seat).some((i) => terrain(cell(game, game.players[i]!.position).terrain).kind !== "village") + ); +} + function distancesToVillage(game: View): Map { // Measure progress along the trail, including detours around gaps and lava. const villageDistances = new Map(); @@ -76,6 +88,14 @@ export function contributionDistribution(dice: Die[], rule: Requirement): number return distribution; } function rollGain(game: View, seat: number, die: Die, attempts = 1): number { + if (villageHelper(game, seat)) { + return neighbors(game, seat).reduce((gain, other) => { + if (terrain(cell(game, game.players[other]!.position).terrain).kind === "village") return gain; + const rule = ruleAt(game, other); + const expected = DICE[die.type]!.reduce((sum, _, i) => sum + valueOf({ ...die, face: i + 1 }, rule), 0) / 6; + return gain + (valueOf(die, rule) - expected) * urgency(game, other); + }, 0); + } const own = ruleAt(game, seat); const gain = rerollValue(die.type, own, attempts) - valueOf(die, own); const harm = neighbors(game, seat).reduce((sum, other) => { @@ -165,17 +185,19 @@ function chooseEquipment( }); return { win, loss }; }; + const helping = villageHelper(game, seat); const before = metrics(own, player.aid); let best: { move: Move; score: number } | undefined; const consider = (move: Move, after: Die[], bonus = 0, aid = false) => { const gain = contribution(after, ownRule) + bonus - contribution(dice, ownRule); const peerChanges = peers.map((i) => contribution(after, ruleFor(i)) - contribution(dice, ruleFor(i))); - if (gain < 0 || peerChanges.some((delta) => delta > 0)) return; + if ((!helping && gain < 0) || peerChanges.some((delta) => delta > 0)) return; const result = metrics(own + gain, player.aid || aid); const score = - (result.win - before.win) * policy.success * urgency(game, seat) + - (before.loss - result.loss) * policy.stamina - - peerChanges.reduce((sum, delta, index) => sum + delta * urgency(game, peers[index]!), 0) * policy.teamwork; + (result.win - before.win) * (helping ? 0 : policy.success * urgency(game, seat)) + + (before.loss - result.loss) * (helping ? 0.1 : policy.stamina) - + peerChanges.reduce((sum, delta, index) => sum + delta * urgency(game, peers[index]!), 0) * + (helping ? 1 : policy.teamwork); if (score <= policy.cost) return; // Preserve the flexible Pocketknife if a dedicated card is equally good. const adjusted = score - (move.id === "knife" ? 0.05 : 0); @@ -476,12 +498,16 @@ export function chooseMove(game: View, seat: number, policy: AiPolicy = DEFAULT_ const conflicts = (d: Die) => neighbors(game, seat).reduce((sum, i) => sum + valueOf(d, ruleAt(game, i)) * urgency(game, i), 0); const die = activeDice(p) - .filter((d) => valueOf(d, r) === 0 && conflicts(d) > 0) + .filter((d) => (villageHelper(game, seat) || valueOf(d, r) === 0) && conflicts(d) > 0) .sort((a, b) => conflicts(b) - conflicts(a))[0]; if (die) return { action: "buddy", ids: [die.id] }; } const ids = activeDice(p) - .filter((d) => (matches(face(d), r) ? d.face : 0) < rerollValue(d.type, r, p.rerolls)) + .filter((d) => + villageHelper(game, seat) + ? rollGain(game, seat, d) > 0 + : (matches(face(d), r) ? d.face : 0) < rerollValue(d.type, r, p.rerolls) + ) .map((d) => d.id); return p.rerolls && ids.length ? { action: "reroll", ids } : { action: "finishRerolls" }; } diff --git a/packages/engine/src/game.spec.ts b/packages/engine/src/game.spec.ts index 5c97c9e..1ae0a95 100644 --- a/packages/engine/src/game.spec.ts +++ b/packages/engine/src/game.spec.ts @@ -1273,3 +1273,36 @@ test("skip injury choices when a resolved explorer is certain to die in the erup } } }); + +test("safe village residents sacrifice strong dice for escaping neighbors without risking exhaustion", async () => { + const { chooseMove } = await import("../index.js"); + const s = withPhase("reroll"); + s.board.forEach((c) => (c.lava = false)); + s.players.forEach((p, i) => { + p.position = ["4,2", "2,2", "3,3"][i]!; + p.path = [p.position]; + p.cards = []; + p.dice.forEach((d) => (d.face = 6)); + cell(s, p.position).terrain = i === 0 ? 33 : 16; + }); + const p = s.players[0]!; + p.skill = "gatherer"; + p.stamina = 0; + p.rerolls = 2; + const roll = chooseMove(stripSecret(s, 0), 0); + assert.equal(roll.action, "reroll"); + assert.equal((roll.ids as string[]).length, p.dice.length); + s.players[1]!.dice.forEach((d) => (d.face = 1)); + assert.deepEqual(chooseMove(stripSecret(s, 0), 0), roll); + p.stamina = 25 - (s.difficulty + 2); + assert.equal(chooseMove(stripSecret(s, 0), 0).action, "finishRerolls"); + p.stamina = 0; + cell(s, "4,1").lava = true; + assert.equal(chooseMove(stripSecret(s, 0), 0).action, "finishRerolls"); + cell(s, "4,1").lava = false; + p.skill = "buddy"; + assert.equal(chooseMove(stripSecret(s, 0), 0).action, "buddy"); + s.phase = "equipment"; + p.cards = [{ id: "machete", used: 0, availableRound: 0 }]; + assert.equal(chooseMove(stripSecret(s, 0), 0).id, "machete"); +}); diff --git a/packages/viewer/src/App.svelte b/packages/viewer/src/App.svelte index 8787a5e..6ef4c0b 100644 --- a/packages/viewer/src/App.svelte +++ b/packages/viewer/src/App.svelte @@ -417,6 +417,17 @@ onchange={(e) => store.setAutoTeammates(e.currentTarget.checked)} />Automatically play teammates + @@ -571,6 +582,7 @@
import { terrain, cell, distance, threatened, CHARACTER_COLORS, requirementLabel, type View } from "fuji-engine"; + import PlayerMarker from "./PlayerMarker.svelte"; import TravelGuide from "./TravelGuide.svelte"; import RequirementSymbols from "./RequirementSymbols.svelte"; import { art } from "./assets"; let { state, + avatars = [], colorblind = false, seat, reserved = {}, @@ -16,6 +18,7 @@ oninspect, }: { state: View; + avatars?: string[]; colorblind?: boolean; seat?: number; reserved?: Record; @@ -218,10 +221,7 @@ /> {/if} - - {i + 1} + {/if} @@ -262,8 +262,7 @@ ? ": opposite player, not your neighbour. Your dice are not compared with each other." : ""} - - {i + 1} + {#if i === seat}{/if} {/each} @@ -483,9 +482,6 @@ pointer-events: auto; filter: drop-shadow(0 4px 3px #0007); } - .traveler-number { - font: 600 17px var(--font-ui); - } .scene-legend { flex-wrap: wrap; padding: 0 0 10px; diff --git a/packages/viewer/src/lib/PlayerMarker.svelte b/packages/viewer/src/lib/PlayerMarker.svelte new file mode 100644 index 0000000..169b41a --- /dev/null +++ b/packages/viewer/src/lib/PlayerMarker.svelte @@ -0,0 +1,31 @@ + + + +{#if avatar && failed !== avatar} + + (failed = avatar)} + /> +{:else} + 10 ? 6 : 4} fill={color} font-size={radius > 10 ? 17 : 12} font-weight="600" + >{number} +{/if} diff --git a/packages/viewer/src/lib/store.svelte.ts b/packages/viewer/src/lib/store.svelte.ts index 1fa779b..e4ee061 100644 --- a/packages/viewer/src/lib/store.svelte.ts +++ b/packages/viewer/src/lib/store.svelte.ts @@ -2,6 +2,7 @@ import { SoundDesign, type SoundCue } from "./sound"; import type { View, Move } from "fuji-engine"; export class Store { state: View | null = $state(null); + avatars: string[] = $state([]); private audio = new SoundDesign(); sound = $state(true); setSound(enabled: boolean) { diff --git a/packages/viewer/src/viewer.ts b/packages/viewer/src/viewer.ts index 90142c8..f71d553 100644 --- a/packages/viewer/src/viewer.ts +++ b/packages/viewer/src/viewer.ts @@ -15,6 +15,9 @@ export function launch(selector: string) { store.colorblind = preferences?.colorblind === true; store.setSound(preferences?.sound !== false); }); + events.on("avatars", (avatars) => { + store.avatars = avatars; + }); store.send = (move) => events.emit("move", move); events.on("state", async (state) => { store.receive(state); diff --git a/tests/bgs-bundle-smoke.mjs b/tests/bgs-bundle-smoke.mjs index df67ada..418eb90 100644 --- a/tests/bgs-bundle-smoke.mjs +++ b/tests/bgs-bundle-smoke.mjs @@ -23,6 +23,23 @@ import path from "node:path"; window.bridge.emit("state", view); }, view); if ((await page.locator(".phase-track svg").count()) !== 5) throw Error("Phase strip must show five icons"); + await page.evaluate(() => + window.bridge.emit( + "avatars", + Array(3).fill( + "data:image/svg+xml," + + encodeURIComponent( + '' + ) + ) + ) + ); + await page.waitForFunction(() => document.querySelectorAll(".traveler .player-avatar").length === 3); + await page.evaluate(() => window.bridge.emit("avatars", ["data:image/png;base64,aW52YWxpZA=="])); + await page.waitForFunction(() => document.querySelectorAll(".traveler .player-avatar").length === 0); + if ((await page.locator(".traveler").first().locator("text").textContent()).trim() !== "1") + throw Error("Broken avatars must fall back to player numbers"); + await page.evaluate(() => window.bridge.emit("avatars", [])); await page.getByRole("button", { name: "Ready for the journey" }).click(); await page.evaluate(() => { window.bridge.emit("state:updated"); @@ -81,8 +98,7 @@ import path from "node:path"; const useBinoculars = page.getByRole("button", { name: "Use Binoculars", exact: true }); if (!(await useBinoculars.isDisabled())) throw Error("Binoculars needs two tiles"); await page - .locator(".location") - .nth(binocularState.board.findIndex((c) => c.id === "0,3")) + .locator(`.traveler[data-player="${binocularState.players.findIndex((p) => p.position === "0,3")}"]`) .click(); await page.getByRole("status").filter({ hasText: "a player is here" }).waitFor(); for (const id of ["1,3", "6,6"]) { @@ -184,7 +200,7 @@ import path from "node:path"; await page.screenshot({ path: "work/browser/fuji-dice-conflicts.png", fullPage: true }); conflictState.phase = "equipment"; await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(conflictState, 0)); - if (await conflictMarkers.count()) throw Error("Reroll conflict markers leaked into another phase"); + if (!(await conflictMarkers.count())) throw Error("Equipment must retain teammate conflict markers"); s.phase = "reroll"; s.players[0].rerolls = 0; await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(s, 0));