Improve cooperative AI and preserve player decisions during teammate updates

This commit is contained in:
coyotte508 2026-09-08 18:29:57 +02:00
commit 10ebfe821f
13 changed files with 1222 additions and 37 deletions

383
docs/ai-benchmark.json Normal file
View file

@ -0,0 +1,383 @@
{
"training": [
{
"name": "baseline",
"policy": {
"equipment": false,
"lead": 1,
"progress": 4,
"success": 12,
"stamina": 2,
"teamwork": 0.4,
"cost": 0.8
},
"family": "training",
"games": 180,
"wins": 51,
"moves": 8409,
"stalled": [],
"byPlayers": {
"2": {
"games": 60,
"wins": 26
},
"3": {
"games": 60,
"wins": 9
},
"4": {
"games": 60,
"wins": 16
}
},
"equipment": {},
"abilities": {
"help": 3
}
},
{
"name": "balanced",
"policy": {
"equipment": true,
"lead": 1,
"progress": 4,
"success": 12,
"stamina": 2,
"teamwork": 0.4,
"cost": 0.8
},
"family": "training",
"games": 180,
"wins": 70,
"moves": 8729,
"stalled": [],
"byPlayers": {
"2": {
"games": 60,
"wins": 31
},
"3": {
"games": 60,
"wins": 12
},
"4": {
"games": 60,
"wins": 27
}
},
"equipment": {
"shovel": 66,
"water": 51,
"machete": 32,
"rope": 41,
"radio": 40,
"binoculars": 65,
"map": 49,
"flare": 63,
"compass": 16,
"torch": 40,
"aid": 57,
"tape": 7
},
"abilities": {
"buddy": 520,
"help": 15,
"give": 42
}
},
{
"name": "stamina",
"policy": {
"equipment": true,
"lead": 1,
"progress": 4,
"success": 8,
"stamina": 4,
"teamwork": 0.4,
"cost": 0.8
},
"family": "training",
"games": 180,
"wins": 70,
"moves": 8734,
"stalled": [],
"byPlayers": {
"2": {
"games": 60,
"wins": 31
},
"3": {
"games": 60,
"wins": 12
},
"4": {
"games": 60,
"wins": 27
}
},
"equipment": {
"shovel": 66,
"water": 51,
"machete": 33,
"rope": 41,
"radio": 40,
"binoculars": 65,
"map": 50,
"flare": 63,
"compass": 16,
"torch": 40,
"aid": 58,
"tape": 7
},
"abilities": {
"buddy": 521,
"help": 15,
"give": 42
}
},
{
"name": "escape",
"policy": {
"equipment": true,
"lead": 1,
"progress": 4,
"success": 18,
"stamina": 1,
"teamwork": 0.4,
"cost": 0.8
},
"family": "training",
"games": 180,
"wins": 71,
"moves": 8697,
"stalled": [],
"byPlayers": {
"2": {
"games": 60,
"wins": 31
},
"3": {
"games": 60,
"wins": 13
},
"4": {
"games": 60,
"wins": 27
}
},
"equipment": {
"shovel": 67,
"water": 51,
"machete": 32,
"rope": 41,
"radio": 40,
"binoculars": 65,
"map": 49,
"flare": 63,
"compass": 16,
"torch": 40,
"aid": 55,
"tape": 7
},
"abilities": {
"buddy": 517,
"help": 16,
"give": 41
}
},
{
"name": "cautious",
"policy": {
"equipment": true,
"lead": 1.5,
"progress": 4,
"success": 12,
"stamina": 2,
"teamwork": 0.4,
"cost": 0.8
},
"family": "training",
"games": 180,
"wins": 58,
"moves": 9413,
"stalled": [
{
"players": 3,
"seed": 56,
"round": 9,
"error": "Error: No available destination."
}
],
"byPlayers": {
"2": {
"games": 60,
"wins": 27
},
"3": {
"games": 60,
"wins": 10
},
"4": {
"games": 60,
"wins": 21
}
},
"equipment": {
"shovel": 70,
"water": 59,
"machete": 37,
"rope": 46,
"radio": 38,
"aid": 58,
"torch": 40,
"binoculars": 65,
"map": 51,
"flare": 65,
"compass": 16,
"tape": 6
},
"abilities": {
"buddy": 560,
"help": 17,
"give": 35
}
},
{
"name": "progress",
"policy": {
"equipment": true,
"lead": 1,
"progress": 5,
"success": 12,
"stamina": 2,
"teamwork": 0.4,
"cost": 0.8
},
"family": "training",
"games": 180,
"wins": 66,
"moves": 8436,
"stalled": [],
"byPlayers": {
"2": {
"games": 60,
"wins": 28
},
"3": {
"games": 60,
"wins": 14
},
"4": {
"games": 60,
"wins": 24
}
},
"equipment": {
"shovel": 66,
"water": 53,
"machete": 28,
"rope": 45,
"radio": 38,
"binoculars": 64,
"map": 47,
"flare": 63,
"compass": 18,
"torch": 36,
"aid": 56,
"tape": 7
},
"abilities": {
"buddy": 503,
"help": 9,
"give": 33
}
}
],
"heldout": [
{
"name": "baseline",
"policy": {
"equipment": false,
"lead": 1,
"progress": 4,
"success": 12,
"stamina": 2,
"teamwork": 0.4,
"cost": 0.8
},
"family": "heldout",
"games": 300,
"wins": 87,
"moves": 14243,
"stalled": [],
"byPlayers": {
"2": {
"games": 100,
"wins": 39
},
"3": {
"games": 100,
"wins": 17
},
"4": {
"games": 100,
"wins": 31
}
},
"equipment": {},
"abilities": {
"help": 11
}
},
{
"name": "escape",
"policy": {
"equipment": true,
"lead": 1,
"progress": 4,
"success": 18,
"stamina": 1,
"teamwork": 0.4,
"cost": 0.8
},
"family": "heldout",
"games": 300,
"wins": 112,
"moves": 15484,
"stalled": [],
"byPlayers": {
"2": {
"games": 100,
"wins": 45
},
"3": {
"games": 100,
"wins": 28
},
"4": {
"games": 100,
"wins": 39
}
},
"equipment": {
"shovel": 113,
"binoculars": 76,
"aid": 79,
"radio": 69,
"torch": 123,
"flare": 91,
"rope": 72,
"machete": 52,
"map": 87,
"tape": 31,
"water": 87,
"compass": 29
},
"abilities": {
"buddy": 903,
"help": 48,
"give": 80
}
}
]
}

59
docs/ai-policy.md Normal file
View file

@ -0,0 +1,59 @@
# Playtest AI
The platform export and local harness use the same deterministic `moveAI`. Every decision receives `stripSecret(state, seat)`. Neither the seed nor hidden teammate faces are available. Wireless reveals therefore affect both route selection and equipment decisions; masked faces remain an estimate.
## Scoring
Routes balance distance to the village, imminent lava, eruption markers, pickups and expected matching contribution after available rerolls. The bot avoids reserving a neighbor's only remaining destination when it can choose another. Rerolls compare each face with its destination-specific expected replacement, including weak matching faces.
Equipment scoring convolves the published die faces into distributions for opposing matching totals. Visible faces are fixed; hidden faces use independent fair-roll priors. It estimates strict comparison success and stamina loss, rather than using one universal “good total.” These estimates do not model teammates' subsequent reroll strategy.
Deterministic face changes may not reduce the bot's own contribution or increase its contribution against any comparison neighbor's destination. Conflict reductions carry three times the weight when that neighbor's current location is threatened by the next eruption. Four-player opposite seats are not comparison neighbors.
## Equipment and abilities
| Card or ability | Heuristic |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Flare gun | Spend for improved estimated movement success or stamina loss; conserve if already unbeatable without loss. |
| Shovel, Tape, Compass | Compare legal face changes and subsets using the destination criteria and teammate conflicts. |
| Machete | Remove one or two conflicting dice without reducing the bot's own total. |
| First aid kit | Compare expected stamina saved with other equipment; do not reuse an active effect. |
| Torch, Water flask | Reroll weak dice, accounting for expected extra conflict. Water can help a teammate whose revealed dice show a benefit. Optional responses decline if no useful reroll remains. |
| Map, Fire lighter | Lend or request a publicly identifiable useful die that does not contribute to the donor's destination or worsen a third player's comparison. The donor independently validates the loan. |
| Wireless | Reveal a weak roll or substantial conflict while teammates still have decisions. Revealed faces inform their route and equipment scoring. |
| Carabiner | Require revealed evidence that every player has a non-negative expected reroll choice. Mandatory responses choose the best available die. |
| Rope | Advance toward the village or escape an imminent eruption, avoiding threatened destinations, eruption triggers and reserved endpoints. |
| Binoculars | Improve a nearby reachable empty location by swapping in more favorable criteria. Do not disturb chosen locations. |
| Pocketknife | Evaluate eligible copies through the same heuristics; prefer a dedicated card for equivalent deterministic benefits. |
| Buddy | Set aside a die that contributes nothing locally but conflicts with a neighbor, prioritizing the threatened neighbor. |
| Gatherer | Keep rerolls for improving weak rolls; collect unused rerolls as bars. Spend the minimum bars that turns a failed comparison into success. |
| Equipment manager | Pass cards blocked by an arm injury to an uninjured teammate, prioritizing imminent danger. |
| Scout, Survivalist | Route scoring includes their movement limits and reroll allowances. |
| Tinkerer | Reevaluate the retained card after its first use, respecting the engine's two-use limit. |
These are deliberately bounded heuristics. Setup card selection and injury choice remain simple; equipment gifting is conservative. Carabiner and Fire lighter can be rare without Wireless reveals. Bots do not negotiate privately or infer another player's secret dice from their actions.
## Reproducing the experiment
Run `pnpm --filter fuji-engine build`, then `node scripts/benchmark-ai.mjs`. The report is `docs/ai-benchmark.json`.
Six policies each run 180 training games, with the same seeds across policies, 2–4 players and difficulty 1–4. The strongest candidate without stalled games is compared with the no-equipment baseline on 300 separate held-out games each. Replay equality is checked every tenth seed. Stalled games count as non-wins and disqualify a candidate; they are recorded rather than silently discarded.
The benchmark uses scenario 1 and the default skill assignments. It measures complete-team wins, not individual matching totals. Results do not establish optimal play or performance on unimplemented scenarios.
### September 8 experiment
1,680 games were attempted: 1,080 training and 600 held-out comparisons.
| Policy | Training wins / 180 |
| --------------------------- | ------------------: |
| No equipment baseline | 51 |
| Balanced equipment | 70 |
| Stamina emphasis | 70 |
| Escape emphasis | 71 |
| Higher expected-lead weight | 58 |
| Faster village progress | 66 |
The escape-emphasis policy was selected before held-out evaluation. It won **112/300 (37.3%)**, compared with **87/300 (29.0%)** for the baseline: an 8.3 percentage-point improvement on this seed set. Neither stalled in held-out evaluation. The small training differences between equipment variants are not evidence of a universally optimal parameter set.
The higher-lead candidate stalled once: two neighbors ended up sharing an isolated village card with no remaining legal distinct destinations. That candidate was rejected. This late-game engine/rules edge case remains recorded in the report; the AI cannot invent a legal move in that state. All other benchmark games terminated. Tests also exercise each equipment card in constructed useful situations, since conservative lending and Carabiner use are rare in full games without multiple Wireless reveals.

View file

@ -64,7 +64,7 @@ Automatic equipment passes use only public eligibility (cards, phase, injuries),
### Baseline AI
`moveAI(state, player)` is exported from both the engine and BGS wrapper and returns a new state through `applyMove`. The local harness and full-game simulations call the same implementation. Decisions use `stripSecret` for that player, with no access to hidden teammate dice or the random seed. The route heuristic prioritizes destinations outside the next eruption, then balances expected comparison lead after the available rerolls, village distance, distance from lava, pickups and eruption markers. Expectations use the published die faces and only publicly visible teammate faces. Rerolls include low matching faces when rolling again improves expected contribution; unused rerolls yield Gatherer bars. This is a heuristic, not a guarantee of movement or a full model of teammates’ future rerolls. It spends the minimum bars that turn a failed comparison into success. It does not optimize equipment use or Gatherer bar farming.
`moveAI(state, player)` is exported from both the engine and BGS wrapper and returns a new state through `applyMove`. The local harness and full-game simulations call the same implementation. Decisions use `stripSecret` for that player, with no access to hidden teammate dice or the random seed. The route heuristic prioritizes destinations outside the next eruption, then balances expected comparison lead after the available rerolls, village distance, distance from lava, pickups and eruption markers. Expectations use the published die faces and only publicly visible teammate faces. Rerolls include low matching faces when rolling again improves expected contribution; unused rerolls yield Gatherer bars. This is a heuristic, not a guarantee of movement or a full model of teammates’ future rerolls. It spends the minimum bars that turn a failed comparison into success. Equipment and ability heuristics now use destination-specific estimates and public teammate conflicts; see [AI policy](ai-policy.md) for each card and the reproducible benchmark. Gatherer bar farming and setup/injury choices remain simple.
The wrapper's `currentPlayer` excludes players with confirmed planning intentions, so the platform bot driver does not repeatedly play an already-ready bot. Provisional confirmations remain live updates; the platform's stored clock behavior is unchanged.

View file

@ -2,4 +2,11 @@ export * from "./src/data.js";
export * from "./src/types.js";
export * from "./src/game.js";
export { choosePowerBars, chooseMove, moveAI } from "./src/ai.js";
export {
choosePowerBars,
chooseMove,
moveAI,
DEFAULT_AI_POLICY,
contributionDistribution,
type AiPolicy,
} from "./src/ai.js";

View file

@ -11,9 +11,75 @@ import {
activeDice,
face,
threatened,
hasSkill,
walkable,
} from "./game.js";
import { terrain, SKILLS, matches, DICE, type Requirement } from "./data.js";
import type { State, View, Move } from "./types.js";
import { terrain, SKILLS, matches, DICE, EQUIPMENT, type Requirement, type EquipmentId } from "./data.js";
import type { State, View, Move, Die } from "./types.js";
export interface AiPolicy {
equipment: boolean;
lead: number;
progress: number;
success: number;
stamina: number;
teamwork: number;
cost: number;
}
export const DEFAULT_AI_POLICY: AiPolicy = {
equipment: true,
lead: 1,
progress: 4,
success: 18,
stamina: 1,
teamwork: 0.4,
cost: 0.8,
};
const ruleAt = (game: View, seat: number) =>
terrain(cell(game, game.players[seat]!.path.at(-1) ?? game.players[seat]!.position).terrain).requirement;
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);
// Convolve independent fair rolls; revealed faces are point masses. This is a
// prior, not access to private rolls or a model of another player's strategy.
export function contributionDistribution(dice: Die[], rule: Requirement): number[] {
let distribution = [1];
for (const die of dice) {
const next = Array<number>(distribution.length + 6).fill(0);
const faces = die.face ? [die.face] : [1, 2, 3, 4, 5, 6];
for (const f of faces) {
const score = valueOf({ ...die, face: f }, rule);
distribution.forEach((probability, total) => {
next[total + score]! += probability / faces.length;
});
}
distribution = next;
}
return distribution;
}
function rollGain(game: View, seat: number, die: Die, attempts = 1): number {
const own = ruleAt(game, seat);
const gain = rerollValue(die.type, own, attempts) - valueOf(die, own);
const harm = neighbors(game, seat).reduce((sum, other) => {
const rule = ruleAt(game, other);
return sum + Math.max(0, rerollValue(die.type, rule, 1) - valueOf(die, rule)) * urgency(game, other);
}, 0);
return gain - 0.2 * harm;
}
function lendingChoice(game: View, donor: number, receiver: number): Die | undefined {
return (
activeDice(game.players[donor]!)
.filter((d) => valueOf(d, ruleAt(game, donor)) === 0)
.filter((d) => valueOf(d, ruleAt(game, receiver)) > 0)
// A loan must not worsen a third player's comparison either.
.filter((d) =>
neighbors(game, receiver).every(
(i) => i === donor || neighbors(game, donor).includes(i) || valueOf(d, ruleAt(game, i)) === 0
)
)
.sort((a, b) => valueOf(b, ruleAt(game, receiver)) - valueOf(a, ruleAt(game, receiver)))[0]
);
}
// Expected contribution after rolling, with the option to keep a result or
// try again. This uses the published die faces, never a teammate's hidden roll.
@ -40,11 +106,204 @@ export function choosePowerBars(state: State | View, helper: number): number {
return powerBarChoices(state, helper).includes(needed) ? needed : 0;
}
export function chooseMove(game: View, seat: number): Move {
// Consider deterministic equipment effects against public destination criteria.
// Never increase the total a comparison neighbor must beat, even when their
// dice are hidden. Unknown opposition is estimated from the published faces.
function chooseEquipment(game: View, seat: number, policy: AiPolicy): Move | undefined {
const player = game.players[seat]!;
if (player.injuries.includes("arm")) return;
const dice = activeDice(player);
const peers = neighbors(game, seat);
const ruleFor = (i: number) =>
terrain(cell(game, game.players[i]!.path.at(-1) ?? game.players[i]!.position).terrain).requirement;
const contribution = (roll: Die[], rule: Requirement) =>
roll.reduce((sum, d) => sum + (matches(face(d), rule) ? d.face : 0), 0);
const ownRule = ruleFor(seat);
const own = contribution(dice, ownRule) + player.bonus;
const rolls = peers.map((i) => activeDice(game.players[i]!));
if (game.players.length === 2) rolls.push(game.ghost);
const cdfs = rolls.map((roll) => {
let cumulative = 0;
return contributionDistribution(roll, ownRule).map((p) => (cumulative += p));
});
const maximum = Array.from({ length: Math.max(...cdfs.map((c) => c.length)) }, (_, score) =>
cdfs.reduce((p, c) => p * (c[score] ?? 1), 1)
);
const metrics = (score: number, aid: boolean) => {
let win = 0,
loss = 0;
maximum.forEach((cdf, other) => {
const probability = Math.max(0, cdf - (maximum[other - 1] ?? 0));
const margin = score - other;
if (margin > 0) win += probability;
if (!aid)
loss +=
probability * (margin <= 0 ? game.difficulty + 2 : Math.max(0, game.difficulty + 2 - Math.ceil(margin / 2)));
});
return { win, loss };
};
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;
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;
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);
if (!best || adjusted > best.score) best = { move, score: adjusted };
};
const offer = (move: Move, score: number) => {
if (score > policy.cost && (!best || score > best.score)) best = { move, score };
};
const phase = game.phase === "planning" ? 2 : 4;
for (const card of player.cards.filter((c) => c.availableRound <= game.round)) {
const effects: EquipmentId[] =
card.id === "knife"
? EQUIPMENT.filter(
(effect) =>
effect.id !== "knife" &&
game.players.some(
(p, i) => i !== seat && p.cards.some((c) => c.id === effect.id && c.availableRound <= game.round)
)
).map((e) => e.id)
: [card.id];
for (const effect of effects.filter((id) =>
(EQUIPMENT.find((e) => e.id === id)!.phases as readonly number[]).includes(phase)
)) {
const move: Move = { action: "equipment", id: card.id, ...(card.id === "knife" ? { copy: effect } : {}) };
if (effect === "flare") consider(move, dice, 3);
else if (effect === "aid") consider(move, dice, 0, true);
else if (effect === "shovel") {
for (const die of dice)
for (let value = 1; value <= 6; value++) {
if (value === die.face) continue;
consider(
{ ...move, ids: [die.id], face: value },
dice.map((d) => (d.id === die.id ? { ...d, face: value } : d))
);
}
} else if (["tape", "compass", "machete"].includes(effect)) {
const eligible = dice.filter((d) => effect === "machete" || d.face === (effect === "tape" ? 1 : 6));
for (let mask = 1; mask < 2 ** eligible.length; mask++) {
const ids = eligible.filter((_, i) => mask & (1 << i)).map((d) => d.id);
if (effect === "machete" && ids.length > 2) continue;
const after =
effect === "machete"
? dice.filter((d) => !ids.includes(d.id))
: dice.map((d) => (ids.includes(d.id) ? { ...d, face: 7 - d.face } : d));
consider({ ...move, ids }, after);
}
} else if (effect === "torch" || effect === "water") {
const ids = dice.filter((d) => rollGain(game, seat, d) > 0.3).map((d) => d.id);
const gain = dice.filter((d) => ids.includes(d.id)).reduce((sum, d) => sum + rollGain(game, seat, d), 0);
if (ids.length)
offer({ ...move, ...(effect === "torch" ? { ids } : { target: seat }) }, gain * urgency(game, seat));
if (effect === "water")
for (const other of peers) {
const known = activeDice(game.players[other]!);
if (known.every((d) => d.face > 0))
offer(
{ ...move, target: other },
known.reduce((sum, d) => sum + Math.max(0, rollGain(game, other, d)), 0) * urgency(game, other)
);
}
} else if (effect === "map") {
for (let other = 0; other < game.players.length; other++)
if (other !== seat) {
const die = lendingChoice(game, seat, other);
if (die)
offer({ ...move, target: other, ids: [die.id] }, valueOf(die, ruleFor(other)) * urgency(game, other));
}
} else if (effect === "lighter") {
for (const other of peers) {
// Only ask for a visible, useful loan. Hidden dice never justify a guess.
const die = lendingChoice(game, other, seat);
if (die) offer({ ...move, target: other }, valueOf(die, ownRule) * urgency(game, seat));
}
} else if (effect === "radio") {
const conflicts = peers.some((i) => contribution(dice, ruleFor(i)) >= 6 * urgency(game, i) ** -1);
if (!player.radio && peers.some((i) => !game.players[i]!.ready) && (before.win < 0.65 || conflicts))
offer(move, policy.cost + 0.1);
} else if (effect === "carabiner") {
// It forces every player to roll, so require visible evidence of a safe
// beneficial choice for everyone; otherwise conserve it.
const gains = game.players.map((p, i) =>
activeDice(p).some((d) => !d.face) ? -Infinity : Math.max(...activeDice(p).map((d) => rollGain(game, i, d)))
);
if (gains.every((g) => g >= 0))
offer(
move,
gains.reduce((sum, g, i) => sum + g * urgency(game, i), 0)
);
} else if (effect === "rope") {
const origin = cell(game, player.position);
const villageDistance = (id: string) => {
const c = cell(game, id);
return Math.min(
...game.board
.filter((t) => terrain(t.terrain).kind === "village")
.map((t) => Math.abs(t.x - c.x) + Math.abs(t.y - c.y))
);
};
for (const c of game.board.filter(
(c) =>
walkable(c) &&
terrain(c.terrain).kind === "land" &&
!c.eruption &&
Math.abs(c.x - origin.x) + Math.abs(c.y - origin.y) === 1
)) {
if (threatened(game).includes(c.id) || game.players.some((p, i) => i !== seat && p.path.at(-1) === c.id))
continue;
const gain = villageDistance(origin.id) - villageDistance(c.id);
if (gain > 0 || urgency(game, seat) > 1)
offer({ ...move, tiles: [c.id] }, gain * 2 + (urgency(game, seat) - 1) * 5);
}
} else if (effect === "binoculars") {
const empty = game.board.filter(
(c) =>
terrain(c.terrain).kind === "land" &&
!c.lava &&
!c.equipment &&
!c.eruption &&
!game.players.some((p) => p.position === c.id || p.path.at(-1) === c.id)
);
const reachable = new Set(Object.values(paths(game, seat)).map((p) => p.at(-1)));
for (const a of empty.filter((c) => reachable.has(c.id)))
for (const b of empty.filter((c) => !reachable.has(c.id))) {
const old = contribution(dice, terrain(a.terrain).requirement);
const improved = contribution(dice, terrain(b.terrain).requirement);
const distance = (c: typeof a) =>
Math.abs(c.x - cell(game, player.position).x) + Math.abs(c.y - cell(game, player.position).y);
// Improve a nearby destination without disturbing anyone's chosen tile.
if (improved > old + 5 && distance(a) <= 2) offer({ ...move, tiles: [a.id, b.id] }, (improved - old) * 0.3);
}
}
}
}
return best?.move;
}
export function chooseMove(game: View, seat: number, policy: AiPolicy = DEFAULT_AI_POLICY): Move {
const p = game.players[seat]!;
if (game.pending) {
if (game.pending.kind === "lend") return { action: "decline" };
return { action: "respond", ids: [activeDice(p)[0]!.id] };
if (game.pending.kind === "lend") {
const die = lendingChoice(game, seat, game.pending.receiver!);
return die ? { action: "respond", ids: [die.id] } : { action: "decline" };
}
const dice = activeDice(p).sort((a, b) => rollGain(game, seat, b) - rollGain(game, seat, a));
const ids = game.pending.required
? dice.slice(0, 1).map((d) => d.id)
: dice
.filter((d) => rollGain(game, seat, d) > 0)
.slice(0, 6)
.map((d) => d.id);
return ids.length ? { action: "respond", ids } : { action: "decline" };
}
if (p.pendingInjuries) {
const injury = ["arm", "eye", "amnesia", "leg"].find((i) => !p.injuries.includes(i as never))!;
@ -52,11 +311,36 @@ export function chooseMove(game: View, seat: number): Move {
}
if (game.phase === "setup")
return { action: "setup", keep: p.cards.slice(0, SKILLS[p.skill].keep).map((c) => c.id), drop: p.dice.at(-1)?.id };
if (policy.equipment && ["planning", "equipment"].includes(game.phase)) {
// An injured manager can still pass unusable cards to an uninjured teammate.
if (hasSkill(p, "manager") && p.injuries.includes("arm") && p.cards.length) {
const target = game.players
.map((other, i) => ({ other, i }))
.filter(({ other, i }) => i !== seat && !other.injuries.includes("arm"))
.sort((a, b) => urgency(game, b.i) - urgency(game, a.i))[0];
if (target) return { action: "give", id: p.cards[0]!.id, target: target.i };
}
const equipment = chooseEquipment(game, seat, policy);
if (equipment) return equipment;
}
if (game.phase === "planning") {
const choices = Object.values(paths(game, seat)).filter(
(path) =>
!neighbors(game, seat).some((i) => game.players[i]!.ready && game.players[i]!.path.at(-1) === path.at(-1))
);
const preservesEscape = (path: string[]) =>
neighbors(game, seat).every((other) => {
if (game.players[other]!.ready) return true;
return Object.values(paths(game, other)).some(
(route) =>
route.at(-1) !== path.at(-1) &&
!neighbors(game, other).some(
(i) => i !== seat && game.players[i]!.ready && game.players[i]!.path.at(-1) === route.at(-1)
)
);
});
const cooperative = choices.filter(preservesEscape);
if (cooperative.length) choices.splice(0, choices.length, ...cooperative);
const danger = new Set(threatened(game));
const score = (path: string[]) => {
const c = cell(game, path.at(-1)!);
@ -94,8 +378,8 @@ export function chooseMove(game: View, seat: number): Move {
return (
(danger.has(c.id) ? -1000 : 0) -
12 / Math.max(1, lavaDistance) +
expectedLead * 1 -
closestVillage * 4 +
expectedLead * policy.lead -
closestVillage * policy.progress +
(terrain(c.terrain).kind === "village" ? 8 : 0) +
(c.equipment ? 1 : 0) -
path.slice(1).reduce((cost, id) => cost + cell(game, id).eruption * 4, 0)
@ -109,6 +393,14 @@ export function chooseMove(game: View, seat: number): Move {
}
if (game.phase === "reroll") {
const r = terrain(cell(game, p.path.at(-1)!).terrain).requirement;
if (policy.equipment && hasSkill(p, "buddy") && !p.buddyUsed) {
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)
.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))
.map((d) => d.id);

View file

@ -701,6 +701,7 @@ test("AI leaves a threatened location even when staying has the best dice total"
const { chooseMove } = await import("../index.js");
const s = prepared();
cell(s, "0,2").lava = true;
s.players[1]!.cards = [];
cell(s, "0,3").terrain = 16;
s.players[1]!.dice.forEach((d) => (d.face = 6));
const move = chooseMove(stripSecret(s, 1), 1);
@ -861,3 +862,189 @@ test("set-aside journal snapshots reveal only the chosen dice", () => {
assert(publicView.players[0]!.dice.filter((d) => !d.aside).every((d) => d.face === 0));
}
});
test("AI estimates destination-specific distributions and conditions on revealed faces", async () => {
const { contributionDistribution } = await import("../index.js");
const die = { ...prepared().players[0]!.dice[0]!, type: 0, face: 0 };
const pink = contributionDistribution([die], { colors: ["pink"] });
const any = contributionDistribution([die], {});
const mean = (p: number[]) => p.reduce((sum, v, i) => sum + v * i, 0);
assert(Math.abs(mean(pink) - 7 / 6) < 1e-10);
assert(Math.abs(mean(any) - 3.5) < 1e-10);
assert.equal(contributionDistribution([{ ...die, face: 4 }], { colors: ["pink"] })[4], 1);
});
test("AI uses Flare for a weak result without reading hidden rolls, and conserves it when unbeatable", async () => {
const { chooseMove } = await import("../index.js");
const s = withPhase();
s.players.forEach((p, i) => {
p.position = ["0,3", "1,3", "1,2"][i]!;
});
for (const p of s.players) {
p.path = [p.position];
cell(s, p.position).terrain = 16;
p.dice.forEach((d) => (d.face = 3));
}
s.players[0]!.cards = [{ id: "flare", used: 0, availableRound: 0 }];
const move = chooseMove(stripSecret(s, 0), 0);
assert.equal(move.id, "flare");
assert.doesNotThrow(() => applyMove(s, move, 0));
s.players[1]!.dice.forEach((d) => (d.face = 6));
assert.deepEqual(chooseMove(stripSecret(s, 0), 0), move);
s.players[0]!.bonus = 100;
assert.equal(chooseMove(stripSecret(s, 0), 0).action, "ready");
});
test("Buddy and Machete remove conflicts without reducing their own matching total", async () => {
const { chooseMove } = await import("../index.js");
for (const ability of ["buddy", "machete"]) {
const s = withPhase(ability === "buddy" ? "reroll" : "equipment");
s.players.forEach((p, i) => {
p.position = ["0,3", "1,3", "1,2"][i]!;
});
for (const p of s.players) {
p.path = [p.position];
cell(s, p.position).terrain = 8;
p.cards = [];
}
const p = s.players[0]!;
cell(s, p.position).terrain = 19;
p.skill = "buddy";
p.buddyUsed = false;
p.rerolls = 0;
p.dice.forEach((d) => (d.face = 3));
p.dice[0]!.face = 6;
if (ability === "machete") p.cards = [{ id: "machete", used: 0, availableRound: 0 }];
const move = chooseMove(stripSecret(s, 0), 0);
assert.equal(ability === "buddy" ? move.action : move.id, ability);
assert.deepEqual(move.ids, [p.dice[0]!.id]);
assert.doesNotThrow(() => applyMove(s, move, 0));
}
});
test("AI flips useful dice only when the change does not strengthen teammates' opposition", async () => {
const { chooseMove } = await import("../index.js");
const s = withPhase();
s.players.forEach((p, i) => {
p.position = ["0,3", "1,3", "1,2"][i]!;
});
for (const p of s.players) {
p.path = [p.position];
cell(s, p.position).terrain = 19;
p.cards = [];
}
const p = s.players[0]!;
cell(s, p.position).terrain = 8;
p.cards = [{ id: "tape", used: 0, availableRound: 0 }];
p.dice.forEach((d) => (d.face = 1));
assert.equal(chooseMove(stripSecret(s, 0), 0).id, "tape");
cell(s, s.players[1]!.position).terrain = 16;
assert.equal(chooseMove(stripSecret(s, 0), 0).action, "ready");
p.injuries = ["arm"];
assert.equal(chooseMove(stripSecret(s, 0), 0).action, "ready");
});
test("AI lending and optional reroll responses choose useful dice or decline", async () => {
const { chooseMove } = await import("../index.js");
const s = withPhase();
s.players.forEach((p, i) => {
p.position = ["0,3", "1,3", "1,2"][i]!;
});
s.players.forEach((p) => {
p.path = [p.position];
cell(s, p.position).terrain = 19;
});
cell(s, s.players[1]!.position).terrain = 8;
s.players[0]!.dice.forEach((d) => (d.face = 3));
s.players[0]!.dice[0]!.face = 6;
s.pending = { kind: "lend", players: [0], receiver: 1, remaining: 1, required: false };
assert.deepEqual(chooseMove(stripSecret(s, 0), 0), { action: "respond", ids: [s.players[0]!.dice[0]!.id] });
s.players[0]!.dice[0]!.face = 3;
assert.equal(chooseMove(stripSecret(s, 0), 0).action, "decline");
s.pending = { kind: "reroll", players: [0], remaining: 2, required: false };
s.players[0]!.dice.forEach((d) => (d.face = 5));
assert.equal(chooseMove(stripSecret(s, 0), 0).action, "decline");
});
test("Wireless changes AI estimates only when the other player's dice become public", async () => {
const { chooseMove } = await import("../index.js");
const s = withPhase();
s.players.forEach((p, i) => {
p.position = ["0,3", "1,3", "1,2"][i]!;
p.path = [p.position];
cell(s, p.position).terrain = 16;
p.dice.forEach((d) => (d.face = i === 0 ? 3 : 1));
});
s.players[0]!.cards = [{ id: "flare", used: 0, availableRound: 0 }];
assert.equal(chooseMove(stripSecret(s, 0), 0).id, "flare");
s.players[1]!.radio = true;
s.players[2]!.radio = true;
assert.equal(chooseMove(stripSecret(s, 0), 0).action, "ready");
});
test("AI has legal useful choices for every equipment card, including copied effects", async () => {
const { chooseMove, EQUIPMENT } = await import("../index.js");
for (const card of EQUIPMENT) {
let used = false;
for (let example = 0; example < 180 && !used; example++) {
const s = withPhase((card.phases as readonly number[]).includes(4) ? "equipment" : "planning");
s.players.forEach((p, i) => {
p.position = ["0,3", "3,3", "3,2"][i]!;
p.path = [p.position];
p.radio = true;
p.cards = [];
cell(s, p.position).terrain = 4 + ((example * 7 + i * 11) % 24);
p.dice.forEach((d, j) => (d.face = 1 + ((example * 3 + i * 2 + j * 5) % 6)));
});
s.players[0]!.radio = false;
s.players[0]!.cards = [{ id: card.id, used: 0, availableRound: 0 }];
if (card.id === "knife") s.players[1]!.cards = [{ id: "flare", used: 0, availableRound: 0 }];
const view = stripSecret(s, 0),
before = structuredClone(view);
const move = chooseMove(view, 0);
assert.deepEqual(view, before);
if (move.action === "equipment" && move.id === card.id) {
assert.doesNotThrow(() => applyMove(s, move, 0), card.id);
used = true;
}
}
assert(used, `No useful example for ${card.id}`);
}
});
test("AI route selection reacts to Wireless reveals while hidden dice remain irrelevant", async () => {
const { chooseMove } = await import("../index.js");
let changed = false;
for (let example = 0; example < 30 && !changed; example++) {
const s = prepared();
s.players.forEach((p) => (p.cards = []));
s.players[0]!.dice.forEach((d, i) => (d.face = 1 + ((i + example) % 6)));
s.players[1]!.dice.forEach((d) => (d.face = 1));
const hidden = chooseMove(stripSecret(s, 0), 0);
s.players[1]!.dice.forEach((d) => (d.face = 6));
assert.deepEqual(chooseMove(stripSecret(s, 0), 0), hidden);
s.players[1]!.radio = true;
const high = chooseMove(stripSecret(s, 0), 0);
s.players[1]!.dice.forEach((d) => (d.face = 1));
const low = chooseMove(stripSecret(s, 0), 0);
if (JSON.stringify(high) !== JSON.stringify(low)) {
assert.doesNotThrow(() => applyMove(s, low, 0));
changed = true;
}
}
assert(changed, "Revealed contributions must influence route choice");
});
test("Water flask journal describes the recipient and each reroll without exposing private faces", () => {
let s = withPhase();
s.players[0]!.cards = [{ id: "water", used: 0, availableRound: 0 }];
s = applyMove(s, { action: "equipment", id: "water", target: 0 }, 0);
assert.match(s.log.at(-1)!.text, /gets up to 2 rerolls/);
const ids = s.players[0]!.dice.slice(0, 2).map((d) => d.id);
s = applyMove(s, { action: "respond", ids }, 0);
assert.match(s.log.at(-1)!.text, /rerolled 2 dice with Water flask/);
assert.equal(s.log.at(-1)!.dice, undefined);
assert.equal(stripSecret(s, 1).log.at(-1)!.dice, undefined);
s = applyMove(s, { action: "decline" }, 0);
assert.match(s.log.at(-1)!.text, /skipped the remaining Water flask reroll/);
});

View file

@ -393,6 +393,7 @@ function useEquipment(s: State, seat: number, m: Move) {
throw Error("This equipment is not usable in this phase.");
const target = () => integer(m.target, 0, s.players.length - 1);
let setAside: Die[] | undefined;
let effectText = "";
switch (id) {
case "binoculars": {
const ids = strings(m.tiles, 2);
@ -407,11 +408,13 @@ function useEquipment(s: State, seat: number, m: Move) {
s.players.some((p) => p.position === c.id || (p.path.length > 0 && p.path.at(-1) === c.id))
)
throw Error("Both land locations must be completely empty.");
effectText = `swapped ${terrain(a.terrain).name} and ${terrain(b.terrain).name}`;
[a.terrain, b.terrain] = [b.terrain, a.terrain];
break;
}
case "flare":
p.bonus += 3;
effectText = "+3 movement value";
break;
case "rope": {
const ids = strings(m.tiles, 1);
@ -433,21 +436,34 @@ function useEquipment(s: State, seat: number, m: Move) {
case "shovel": {
const d = selectedDice(p, m.ids, 1, 1)[0]!;
d.face = integer(m.face, 1, 6);
effectText = "turned 1 die";
break;
}
case "torch":
roll(s, selectedDice(p, m.ids, 1));
case "torch": {
const dice = selectedDice(p, m.ids, 1);
roll(s, dice);
effectText = `rerolled ${dice.length} ${dice.length === 1 ? "die" : "dice"}`;
break;
}
case "water": {
const recipient = target();
s.pending = { kind: "reroll", players: [recipient], remaining: recipient === seat ? 2 : 1, required: false };
s.pending = {
kind: "reroll",
equipment: id,
players: [recipient],
remaining: recipient === seat ? 2 : 1,
required: false,
};
effectText = `${s.players[recipient]!.name} gets ${recipient === seat ? "up to 2 rerolls" : "1 reroll"}`;
break;
}
case "aid":
p.aid = true;
effectText = "no stamina loss this round";
break;
case "radio":
p.radio = true;
effectText = "dice revealed to teammates for this phase";
break;
case "tape":
case "compass": {
@ -455,6 +471,7 @@ function useEquipment(s: State, seat: number, m: Move) {
const from = id === "tape" ? 1 : 6;
if (dice.some((d) => d.face !== from)) throw Error(`Select dice showing ${from}.`);
for (const d of dice) d.face = 7 - from;
effectText = `turned ${dice.length} ${dice.length === 1 ? "die" : "dice"}`;
break;
}
case "machete":
@ -464,11 +481,13 @@ function useEquipment(s: State, seat: number, m: Move) {
case "lighter": {
const donor = target();
if (donor === seat) throw Error("Choose a teammate.");
s.pending = { kind: "lend", players: [donor], receiver: seat, remaining: 1, required: false };
s.pending = { kind: "lend", equipment: id, players: [donor], receiver: seat, remaining: 1, required: false };
effectText = `asked ${s.players[donor]!.name} to lend a die`;
break;
}
case "carabiner":
s.pending = { kind: "reroll", players: s.players.map((_, i) => i), remaining: 1, required: true };
s.pending = { kind: "reroll", equipment: id, players: s.players.map((_, i) => i), remaining: 1, required: true };
effectText = "everyone rerolls 1 die";
break;
case "map": {
const recipient = target();
@ -476,6 +495,7 @@ function useEquipment(s: State, seat: number, m: Move) {
const d = selectedDice(p, m.ids, 1, 1)[0]!;
p.dice = p.dice.filter((x) => x.id !== d.id);
s.players[recipient]!.dice.push(d);
effectText = `lent 1 die to ${s.players[recipient]!.name} until the end of the round`;
break;
}
}
@ -485,7 +505,11 @@ function useEquipment(s: State, seat: number, m: Move) {
s.discard.push(card.id);
}
resetReady(s);
event(s, `${p.name} used ${equipment(card.id).name}${id !== card.id ? ` as ${info.name}` : ""}.`, "equipment");
event(
s,
`${p.name} used ${equipment(card.id).name}${id !== card.id ? ` as ${info.name}` : ""}${effectText ? ` · ${effectText}` : ""}.`,
"equipment"
);
if (id === "torch") s.log.at(-1)!.sound = "dice";
if (setAside) s.log.at(-1)!.setAside = structuredClone(setAside);
}
@ -495,6 +519,11 @@ function execute(s: State, m: Move, seat: number) {
if (!p) throw Error("Invalid player.");
if (s.pending) {
const pending = s.pending;
const source = pending.equipment ? equipment(pending.equipment).name : "equipment";
let responseText =
pending.kind === "lend"
? `declined the loan to ${s.players[pending.receiver!]!.name}`
: `skipped the remaining ${source} reroll${pending.remaining === 1 ? "" : "s"}`;
if (!pending.players.includes(seat)) throw Error("Waiting for another player.");
if (m.action === "decline") {
if (pending.required) throw Error("This reroll is mandatory.");
@ -506,14 +535,16 @@ function execute(s: State, m: Move, seat: number) {
const d = dice[0]!;
p.dice = p.dice.filter((x) => x !== d);
s.players[pending.receiver!]!.dice.push(d);
responseText = `lent 1 die to ${s.players[pending.receiver!]!.name} until the end of the round`;
pending.players = [];
} else {
roll(s, dice);
responseText = `rerolled ${dice.length} ${dice.length === 1 ? "die" : "dice"} with ${source}`;
pending.remaining--;
if (pending.required || pending.remaining <= 0) pending.players = pending.players.filter((i) => i !== seat);
}
} else throw Error("Resolve the equipment effect first.");
event(s, `${p.name} resolved an equipment effect.`, "equipment");
event(s, `${p.name} ${responseText}.`, "equipment");
if (pending.kind === "reroll") s.log.at(-1)!.sound = "dice";
finishPending(s);
return;

View file

@ -73,6 +73,7 @@ export interface Event {
type: "phase" | "move" | "equipment" | "eruption" | "injury" | "end";
}
export interface Pending {
equipment?: EquipmentId;
kind: "reroll" | "lend";
players: number[];
remaining: number;

View file

@ -1,4 +1,5 @@
<script lang="ts">
import { untrack } from "svelte";
import {
terrain,
cell,
@ -27,6 +28,7 @@
import { art } from "./lib/assets";
import Landscape from "./lib/Landscape.svelte";
import Die from "./lib/Die.svelte";
import InjuryIcon from "./lib/InjuryIcon.svelte";
import EquipmentIcon from "./lib/EquipmentIcon.svelte";
import JournalEntry from "./lib/JournalEntry.svelte";
import PhaseIcon from "./lib/PhaseIcon.svelte";
@ -45,6 +47,8 @@
const seat = $derived(store.seat);
const me = $derived(seat === undefined ? undefined : s?.players[seat]);
let inspected = $state("");
let dangerousRoute = $state("");
let acceptedLavaRisk = $state("");
let dice = $state<string[]>([]);
let tilePicks = $state<string[]>([]);
let tool = $state<EquipmentId | null>(null);
@ -141,21 +145,45 @@
ended: s.outcome === "won" ? "Together, you made it." : "The mountain won.",
}[s.phase]
);
let decision = "";
let decisionScreen = "";
$effect(() => {
const revision = s?.revision;
const currentSeat = seat;
void revision;
void currentSeat;
dice = [];
tilePicks = [];
tool = null;
if (me) {
keep = me.cards.slice(0, SKILLS[me.skill].keep).map((c) => c.id);
drop = me.dice.at(-1)?.id ?? "";
target = seat ?? 0;
giveTarget = seat === 0 ? 1 : 0;
}
const context = JSON.stringify([
seat,
s?.round,
s?.phase,
me?.ready,
me?.rerolls,
me?.pendingInjuries,
me?.dice,
s?.pending?.players.includes(seat ?? -1) ? s.pending : null,
]);
const player = me;
untrack(() => {
const screen = `${seat}:${s?.round}:${s?.phase}`;
if (screen !== decisionScreen) {
decisionScreen = screen;
dangerousRoute = "";
acceptedLavaRisk = "";
}
if (context !== decision) {
decision = context;
dice = [];
tilePicks = [];
tool = null;
if (player) {
keep = player.cards.slice(0, SKILLS[player.skill].keep).map((c) => c.id);
drop = player.dice.at(-1)?.id ?? "";
target = seat ?? 0;
giveTarget = seat === 0 ? 1 : 0;
}
} else if (tool && !player?.cards.some((c) => c.id === tool && c.availableRound <= (s?.round ?? 0))) {
tool = null;
tilePicks = [];
}
});
});
function pickDie(id: string) {
dice = dice.includes(id) ? dice.filter((x) => x !== id) : [...dice, id];
}
@ -171,10 +199,30 @@
if (s?.phase !== "planning" || !me || me.ready || store.waiting || s.pending) return;
const route = reachable[id];
if (!route) return;
dangerousRoute = "";
if (danger.includes(id) && !reserved[id]) {
dangerousRoute = id;
return;
}
if (!reserved[route.at(-1)!] && route.join(";") !== me.path.join(";"))
store.dispatch({ action: "plan", path: route });
}
function confirmTravel() {
const id = currentRoute.at(-1) ?? "";
if (danger.includes(id) && acceptedLavaRisk !== `${s?.round}:${id}`) {
dangerousRoute = id;
return;
}
store.dispatch({ action: "ready" });
}
function acceptDangerousRoute() {
const path = reachable[dangerousRoute];
if (!path || reserved[dangerousRoute] || store.waiting) return;
acceptedLavaRisk = `${s?.round}:${dangerousRoute}`;
dangerousRoute = "";
store.dispatch({ action: "plan", path });
}
function mobileAction() {
if (!s || !me) return;
if (s.pending || me.pendingInjuries || s.phase === "setup") {
@ -182,7 +230,8 @@
return;
}
if (s.phase === "planning") {
store.dispatch({ action: me.ready ? "plan" : "ready", ...(me.ready ? { path: me.path } : {}) });
if (me.ready) store.dispatch({ action: "plan", path: me.path });
else confirmTravel();
return;
}
if (s.phase === "reroll") {
@ -366,7 +415,9 @@
<span class="teammate-name"
>{p.name}{#if seat === i}<small>YOU</small>{/if}</span
><span class="role-name"
>{SKILLS[p.skill].name}{#if p.skill === "gatherer"}<span class="public-bars">
>{SKILLS[p.skill].name}{#each p.injuries as injury}<InjuryIcon
{injury}
/>{/each}{#if p.skill === "gatherer"}<span class="public-bars">
· {p.powerBars} power bar{p.powerBars === 1 ? "" : "s"}</span
>{/if}</span
>
@ -537,7 +588,7 @@
</div>
{/if}
{#if me.injuries.length}<div class="injury-list">
{#each me.injuries as injury}<span>{injury}</span>{/each}
{#each me.injuries as injury}<InjuryIcon {injury} />{/each}
</div>{/if}
{/if}
</section>
@ -662,7 +713,8 @@
onclick={() => store.dispatch({ action: "injury", injury, die: dice[0] })}
disabled={injury === "leg" && dice.length !== 1}
><strong
>{injury === "amnesia" ? "Amnesia" : `${injury[0]!.toUpperCase()}${injury.slice(1)} injury`}</strong
><InjuryIcon {injury} />
{injury === "amnesia" ? "Amnesia" : `${injury[0]!.toUpperCase()}${injury.slice(1)} injury`}</strong
><span
>{{
leg: "Select one of your dice to lose after this round.",
@ -698,6 +750,16 @@
<p class="instruction">
Choose a destination. Share your intentions, but keep numbers and exact dice results private.
</p>
{#if dangerousRoute && !me.ready}<div class="warning" role="alert">
<p>
Lava will reach {terrain(cell(s, dangerousRoute).terrain).name} at the next eruption. Choose a safer destination.
</p>
<button
class="text-button"
disabled={store.waiting || !!reserved[dangerousRoute]}
onclick={acceptDangerousRoute}>Choose this dangerous route</button
>
</div>{/if}
{#if destination}<div class="destination">
<img src={art("land", destination.id)} alt="" />
<div>
@ -723,7 +785,7 @@
{#if !me.ready}<button
class="primary"
disabled={store.waiting || !!reserved[currentRoute.at(-1)!]}
onclick={() => store.dispatch({ action: "ready" })}>Ready to travel <span>→</span></button
onclick={confirmTravel}>Ready to travel <span>→</span></button
>{:else}<p class="confirmed">✓ Your route is set. Waiting for the team.</p>
<button class="text-button" onclick={() => store.dispatch({ action: "plan", path: me.path })}
>Change my route</button

View file

@ -0,0 +1,47 @@
<script lang="ts">
import type { Injury } from "fuji-engine";
let { injury }: { injury: Injury } = $props();
const labels = {
arm: "Arm injury: cannot use equipment.",
eye: "Eye injury: lose normal rerolls, including location bonuses. Survivalist still grants its extra reroll.",
leg: "Leg injury: permanently lose one die.",
amnesia: "Amnesia: character skill is unavailable.",
};
</script>
<span class="injury-icon" role="img" aria-label={labels[injury]} title={labels[injury]}>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.7"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
{#if injury === "arm"}<path d="m5 4 3-1 3 8 6-3 3 3-2 7H9l-4-5V4Z M9 12l8 4 M14 10l-3 8" />
{:else if injury === "eye"}<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z M4 21 20 3" /><circle
cx="12"
cy="12"
r="3"
/>
{:else if injury === "leg"}<path d="m10 3-1 8 4 5-2 5h8l-3-8-2-2 2-8 M8 8l8 2 M10 13l6-3" />
{:else}<path
d="M9 21v-4c-4-1-5-5-4-9a7 7 0 0 1 13-1l3 6h-3v4h-4v4 M10 7a2 2 0 0 1 4 0c0 2-2 2-2 4 M12 14h.01"
/>{/if}
</svg>
</span>
<style>
.injury-icon {
display: inline-flex;
align-items: center;
color: #e5a383;
cursor: help;
vertical-align: middle;
}
svg {
width: 22px;
height: 22px;
}
</style>

View file

@ -19,6 +19,7 @@ export class Store {
journal: View["log"] = $state([]);
animating = $state(false);
private received: View | null = null;
private blocksInput = true;
private receivedSeat: number | undefined;
private frames: { scene: View; duration: number; cue?: SoundCue }[] = [];
private animationTimer: ReturnType<typeof setTimeout> | undefined;
@ -32,7 +33,7 @@ export class Store {
return;
}
this.animating = true;
this.waiting = true;
this.waiting = this.blocksInput;
this.scene = frame.scene;
this.journal = frame.scene.log;
if (frame.cue) this.audio.play(frame.cue);
@ -65,7 +66,7 @@ export class Store {
restart: (players: number, seed: string, difficulty: number) => void = () => {};
teammateStep: () => void = () => {};
dispatch(move: Move) {
if (this.animating) return;
if (this.animating && this.blocksInput) return;
this.error = "";
this.waiting = true;
try {
@ -86,6 +87,17 @@ export class Store {
this.received = s;
this.receivedSeat = this.seat;
this.state = s;
const localDecision = (view: View) =>
JSON.stringify([
view.round,
view.phase,
view.players[this.seat ?? -1],
view.pending?.players.includes(this.seat ?? -1) ? view.pending : null,
]);
const unrelated = previous && this.seat !== undefined && localDecision(previous) === localDecision(s);
// Teammate playback must not interrupt an unchanged local decision.
if (!this.animating || !unrelated) this.blocksInput = !unrelated;
this.waiting = this.animating && this.blocksInput;
if (reset) {
this.dispose();
this.scene = s;

76
scripts/benchmark-ai.mjs Normal file
View file

@ -0,0 +1,76 @@
import {
initGame,
chooseMove,
stripSecret,
applyMove,
replay,
DEFAULT_AI_POLICY,
} from "../packages/engine/dist/index.js";
import { currentPlayer } from "../packages/engine/dist/wrapper.js";
import assert from "node:assert/strict";
import { writeFileSync } from "node:fs";
const base = { ...DEFAULT_AI_POLICY, success: 12, stamina: 2, lead: 1, progress: 4 };
const variants = {
baseline: { ...base, equipment: false },
balanced: { ...base },
stamina: { ...base, success: 8, stamina: 4 },
escape: { ...base, success: 18, stamina: 1 },
cautious: { ...base, lead: 1.5 },
progress: { ...base, progress: 5 },
};
function run(name, policy, family, count) {
const result = {
name,
policy,
family,
games: 0,
wins: 0,
moves: 0,
stalled: [],
byPlayers: {},
equipment: {},
abilities: {},
};
for (let players = 2; players <= 4; players++)
for (let seed = 0; seed < count; seed++) {
let state = initGame(players, { difficulty: 1 + (seed % 4) }, `ai-${family}-${seed}`),
steps = 0;
while (!state.outcome && steps < 1000) {
const current = currentPlayer(state),
seat = Array.isArray(current) ? current[0] : current;
assert.notEqual(seat, undefined);
let move;
try {
move = chooseMove(stripSecret(state, seat), seat, policy);
} catch (error) {
result.stalled.push({ players, seed, round: state.round, error: String(error) });
break;
}
try {
state = applyMove(state, move, seat);
} catch (error) {
throw new Error(`${name}/${players}/${seed}/${steps}: ${JSON.stringify(move)}`, { cause: error });
}
if (move.action === "equipment")
result.equipment[move.copy ?? move.id] = (result.equipment[move.copy ?? move.id] ?? 0) + 1;
if (["buddy", "give", "help"].includes(move.action))
result.abilities[move.action] = (result.abilities[move.action] ?? 0) + 1;
steps++;
}
if (!state.outcome && steps >= 1000) result.stalled.push({ players, seed, error: "Move limit" });
if (seed % 10 === 0) assert.deepEqual(replay(state), state);
result.games++;
result.moves += steps;
const won = state.outcome === "won" ? 1 : 0;
result.wins += won;
result.byPlayers[players] ??= { games: 0, wins: 0 };
result.byPlayers[players].games++;
result.byPlayers[players].wins += won;
}
console.log(JSON.stringify(result));
return result;
}
const training = Object.entries(variants).map(([name, policy]) => run(name, policy, "training", 60));
const winner = training.filter((r) => r.name !== "baseline" && !r.stalled.length).sort((a, b) => b.wins - a.wins)[0];
const heldout = [run("baseline", variants.baseline, "heldout", 100), run(winner.name, winner.policy, "heldout", 100)];
writeFileSync("docs/ai-benchmark.json", JSON.stringify({ training, heldout }, null, 2) + "\n");

View file

@ -50,6 +50,19 @@ import path from "node:path";
s = applyMove(s, { action: "plan", path: teammatePath }, 1);
s.players[1].radio = true;
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(s, 0));
const lavaWarning = structuredClone(s);
lavaWarning.board.find((c) => c.id === "0,2").lava = true;
lavaWarning.revision++;
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(lavaWarning, 0));
const moveCount = await page.evaluate(() => window.captured.filter((e) => e.name === "move").length);
await page.locator('.location.reachable[aria-label*="threatened by the next eruption"]').first().click();
await page.getByRole("button", { name: "Choose this dangerous route" }).waitFor();
if ((await page.evaluate(() => window.captured.filter((e) => e.name === "move").length)) !== moveCount)
throw Error("Dangerous route was selected without acknowledgement");
await page.getByRole("button", { name: "Choose this dangerous route" }).click();
if ((await page.evaluate(() => window.captured.findLast((e) => e.name === "move").payload.action)) !== "plan")
throw Error("Explicit lava override must remain possible");
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(s, 0));
await page.waitForSelector(".revealed-team");
await page.waitForSelector('.teammate-route[data-player="1"] .shared-route-line', { state: "attached" });
if (s.players[1].ready) throw Error("Shared route fixture must be unconfirmed");
@ -122,6 +135,20 @@ import path from "node:path";
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(conflictState, 0));
if (JSON.stringify(await conflictMarkers.allTextContents()) !== JSON.stringify(markers))
throw Error("Conflict markers used hidden teammate rolls");
await page.locator(".personal .die:not(:disabled)").first().click();
const rerollSelection = page.locator(".personal .die.chosen");
if ((await rerollSelection.count()) !== 1) throw Error("Reroll fixture must have one selection");
conflictState.revision++;
conflictState.log.push({ round: conflictState.round, type: "move", text: "A teammate rerolled.", sound: "dice" });
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(conflictState, 0));
if ((await rerollSelection.count()) !== 1) throw Error("Teammate update reset the selected die");
if (!(await page.getByRole("button", { name: /^Reroll 1 die/ }).isEnabled()))
throw Error("Teammate playback blocked reroll input");
await page.getByRole("button", { name: "Skip to latest" }).click();
conflictState.players[0].injuries = ["arm"];
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(conflictState, 0));
if (!(await page.locator('.personal .injury-icon[title="Arm injury: cannot use equipment."]').count()))
throw Error("Injury needs icon and effect help");
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));
@ -223,7 +250,8 @@ import path from "node:path";
const unavailableKnife = page.locator(".equipment-list button").filter({ hasText: "Pocketknife" });
if ((await unavailableKnife.getAttribute("class")).includes("usable"))
throw Error("Pocketknife advertised with no eligible copy target");
await unavailableKnife.click();
if (!(await page.getByRole("button", { name: "Use Pocketknife", exact: true }).count()))
await unavailableKnife.click();
if (!(await page.getByRole("button", { name: "Use Pocketknife", exact: true }).isDisabled()))
throw Error("Empty copy action must be disabled");