Use avatar map markers and let safe village bots weaken conflicting dice

This commit is contained in:
coyotte508 2026-09-08 23:02:14 +02:00
commit b02964b375
10 changed files with 269 additions and 19 deletions

View file

@ -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.

View file

@ -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": []
}
}

View file

@ -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<string, number> {
// Measure progress along the trail, including detours around gaps and lava.
const villageDistances = new Map<string, number>();
@ -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" };
}

View file

@ -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");
});

View file

@ -417,6 +417,17 @@
onchange={(e) => store.setAutoTeammates(e.currentTarget.checked)}
/>Automatically play teammates</label
>
<label class="auto-teammates" title="Use character portraits to preview BGS avatar markers.">
<input
type="checkbox"
checked={store.avatars.length > 0}
onchange={(e) => {
store.avatars = e.currentTarget.checked
? s.players.map((p) => art("character", p.character + 1))
: [];
}}
/>Preview avatar markers
</label>
<button onclick={() => store.teammateStep()} disabled={!!s.outcome || store.animating}
>Play next teammate action</button
>
@ -571,6 +582,7 @@
<div class="game-layout">
<div class="world-column">
<Landscape
avatars={store.avatars}
colorblind={store.colorblind}
state={store.scene ?? s}
{seat}

View file

@ -1,10 +1,12 @@
<script lang="ts">
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<string, string>;
@ -218,10 +221,7 @@
/>
{/if}
<g transform={`translate(${x(destination) + 27},${y(destination) - 27 + i * 20})`}>
<circle r="10" fill="#102b25" stroke={CHARACTER_COLORS[p.character]} stroke-width="2" />
<text y="4" text-anchor="middle" fill={CHARACTER_COLORS[p.character]} font-size="12" font-weight="700"
>{i + 1}</text
>
<PlayerMarker avatar={avatars[i]} number={i + 1} color={CHARACTER_COLORS[p.character]!} radius={10} />
</g>
</g>
{/if}
@ -262,8 +262,7 @@
? ": opposite player, not your neighbour. Your dice are not compared with each other."
: ""}</title
>
<circle r="19" fill="#091e1b" stroke={CHARACTER_COLORS[p.character]} stroke-width={i === seat ? 3 : 2} />
<text text-anchor="middle" y="6" fill={CHARACTER_COLORS[p.character]} class="traveler-number">{i + 1}</text>
<PlayerMarker avatar={avatars[i]} number={i + 1} color={CHARACTER_COLORS[p.character]!} own={i === seat} />
{#if i === seat}<path d="M-4 -28H4L0 -22Z" fill="#f4d888" />{/if}
</g>
{/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;

View file

@ -0,0 +1,31 @@
<script lang="ts">
let {
avatar,
number,
color,
radius = 19,
own = false,
}: { avatar?: string; number: number; color: string; radius?: number; own?: boolean } = $props();
const clip = $props.id();
let failed = $state<string>();
</script>
<circle r={radius} fill="#091e1b" stroke={color} stroke-width={own ? 3 : 2} />
{#if avatar && failed !== avatar}
<defs><clipPath id={clip}><circle r={radius - 2} /></clipPath></defs>
<image
class="player-avatar"
href={avatar}
x={2 - radius}
y={2 - radius}
width={(radius - 2) * 2}
height={(radius - 2) * 2}
preserveAspectRatio="xMidYMid slice"
clip-path={`url(#${clip})`}
onerror={() => (failed = avatar)}
/>
{:else}
<text text-anchor="middle" y={radius > 10 ? 6 : 4} fill={color} font-size={radius > 10 ? 17 : 12} font-weight="600"
>{number}</text
>
{/if}

View file

@ -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) {

View file

@ -15,6 +15,9 @@ export function launch(selector: string) {
store.colorblind = preferences?.colorblind === true;
store.setSound(preferences?.sound !== false);
});
events.on<string[]>("avatars", (avatars) => {
store.avatars = avatars;
});
store.send = (move) => events.emit("move", move);
events.on<View>("state", async (state) => {
store.receive(state);

View file

@ -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(
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="teal"/></svg>'
)
)
)
);
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));