Add random or chosen skills, BGS player clicks and sound controls

This commit is contained in:
coyotte508 2026-09-09 00:01:05 +02:00
commit 6aa8dc7171
13 changed files with 224 additions and 18 deletions

View file

@ -7,7 +7,7 @@
"engine": {
"package": {
"name": "fuji-engine",
"version": "0.1.2"
"version": "0.1.3"
},
"entryPoint": "dist/wrapper.js"
},
@ -85,6 +85,22 @@
"label": "Level 4 (tie or lower: lose 6 stamina)"
}
]
},
{
"name": "skillAssignment",
"label": "Skills",
"type": "select",
"default": "random",
"items": [
{
"name": "random",
"label": "Random"
},
{
"name": "choose",
"label": "Choose skills"
}
]
}
],
"preferences": [
@ -93,6 +109,12 @@
"label": "Show color labels (colorblind support)",
"type": "checkbox",
"default": false
},
{
"name": "sound",
"label": "Sound effects",
"type": "checkbox",
"default": true
}
],
"alias": null,

View file

@ -1,6 +1,6 @@
{
"name": "fuji-engine",
"version": "0.1.2",
"version": "0.1.3",
"private": true,
"license": "AGPL-3.0-only",
"files": [

View file

@ -338,6 +338,13 @@ function chooseEquipment(
export function chooseMove(game: View, seat: number, policy: AiPolicy = DEFAULT_AI_POLICY): Move {
const p = game.players[seat]!;
if (game.skillChoices?.length) {
const taken = game.players.filter((_, i) => !game.skillChoices!.includes(i)).map((p) => p.skill);
const skill = ["buddy", "gatherer", "manager", "survivalist", "scout", "tinkerer"].find(
(skill) => !taken.includes(skill as typeof p.skill)
);
return { action: "chooseSkill", skill };
}
if (game.pending) {
if (game.pending.kind === "lend") {
const die = lendingChoice(game, seat, game.pending.receiver!);

View file

@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
initGame,
initGame as createGame,
choosePowerBars,
applyMove,
stripSecret,
@ -18,6 +18,9 @@ import {
activePlayers,
} from "../index.js";
import type { State, Move } from "./types.js";
// Existing rule fixtures deliberately use the legacy roster to isolate each rule.
const initGame = (players = 3, options: Record<string, unknown> = {}, seed = "fuji") =>
createGame(players, { skillAssignment: "fixed", ...options }, seed);
function prepared(players = 3) {
let s = initGame(players, { autoMovement: false, autoProgress: false }, "test-seed");
for (let i = 0; i < players; i++) {
@ -1318,3 +1321,39 @@ test("random scenario is seeded, covers all seven layouts and replays exactly",
}
assert.equal(seen.size, 7);
});
test("new games assign distinct seeded random skills; legacy saves keep their roster", () => {
const rosters = new Set<string>();
for (let i = 0; i < 20; i++) {
const s = createGame(4, {}, `skill-random-${i}`);
assert.equal(s.initOptions.skillAssignment, "random");
assert.equal(new Set(s.players.map((p) => p.skill)).size, 4);
assert.deepEqual(replay(s), s);
rosters.add(s.players.map((p) => p.skill).join());
}
assert(rosters.size > 1);
const legacy = initGame();
delete legacy.initOptions.skillAssignment;
assert.deepEqual(replay(legacy), legacy);
});
test("players choose distinct skills before equipment is dealt, with exact replay", () => {
let s = createGame(3, { skillAssignment: "choose" }, "skill-draft");
assert(s.players.every((p) => p.cards.length === 0));
assert.deepEqual(activePlayers(s), [0]);
assert.throws(() => applyMove(s, { action: "setup", keep: [] }, 0));
assert.throws(() => applyMove(s, { action: "chooseSkill", skill: "manager" }, 1));
s = applyMove(s, { action: "chooseSkill", skill: "manager" }, 0);
const before = structuredClone(s);
assert.throws(() => applyMove(s, { action: "chooseSkill", skill: "manager" }, 1));
assert.deepEqual(s, before);
s = applyMove(s, { action: "chooseSkill", skill: "scout" }, 1);
s = applyMove(s, { action: "chooseSkill", skill: "gatherer" }, 2);
assert.equal(s.skillChoices, undefined);
assert.deepEqual(
s.players.map((p) => p.cards.length),
[4, 2, 1]
);
assert.deepEqual(activePlayers(s), [0, 1]);
assert.deepEqual(replay(s), s);
});

View file

@ -258,7 +258,7 @@ export function initGame(players = 3, options: Record<string, unknown> = {}, see
ghost: [],
ghostVisible: [],
history: [],
initOptions: { autoMovement: true, autoProgress: true, ...options },
initOptions: { autoMovement: true, autoProgress: true, skillAssignment: "random", ...options },
};
if (options.scenario === "random") s.scenario = scenario = 1 + Math.floor(random(s) * SCENARIOS.length);
const lands = shuffle(
@ -288,9 +288,16 @@ export function initGame(players = 3, options: Record<string, unknown> = {}, see
s,
EQUIPMENT.map((c) => c.id)
);
const skillList: Skill[] = Array.isArray(options.skills)
? (options.skills as Skill[])
: (["buddy", "gatherer", "manager", "survivalist"] as Skill[]);
if (options.skillAssignment !== undefined && !["random", "choose", "fixed"].includes(String(options.skillAssignment)))
throw Error("Invalid skill assignment.");
const assignment = options.skillAssignment ?? "random";
const choosingSkills = assignment === "choose";
const skillList: Skill[] =
assignment === "random"
? shuffle(s, Object.keys(SKILLS) as Skill[])
: Array.isArray(options.skills)
? (options.skills as Skill[])
: (["buddy", "gatherer", "manager", "survivalist"] as Skill[]);
if (skillList.length < players || skillList.some((x) => !(x in SKILLS))) throw Error("Invalid skill selection.");
for (let i = 0; i < players; i++) {
const skill = skillList[i]!;
@ -322,10 +329,10 @@ export function initGame(players = 3, options: Record<string, unknown> = {}, see
aid: false,
bonus: 0,
resolved: false,
setupDone: SKILLS[skill].draw === SKILLS[skill].keep && SKILLS[skill].dice === 6,
setupDone: !choosingSkills && SKILLS[skill].draw === SKILLS[skill].keep && SKILLS[skill].dice === 6,
buddyUsed: false,
};
for (let j = 0; j < SKILLS[skill].draw; j++) draw(s, p, 1);
if (!choosingSkills) for (let j = 0; j < SKILLS[skill].draw; j++) draw(s, p, 1);
s.players.push(p);
}
if (players === 2) {
@ -339,6 +346,7 @@ export function initGame(players = 3, options: Record<string, unknown> = {}, see
}));
s.ghostVisible = s.ghost.filter((_, j) => j % 2 === 0).map((d) => d.id);
}
if (choosingSkills) s.skillChoices = s.players.map((_, i) => i);
event(s, `Scenario ${scenario} · the path to the village`, "phase");
if (s.players.every((p) => p.setupDone)) startRound(s);
return s;
@ -573,6 +581,28 @@ function execute(s: State, m: Move, seat: number) {
finishPending(s);
return;
}
if (s.skillChoices?.length) {
if (m.action !== "chooseSkill" || seat !== s.skillChoices[0]) throw Error("Wait for your skill choice.");
const skill = m.skill as Skill;
if (
!Object.hasOwn(SKILLS, skill) ||
s.players.some((other, i) => !s.skillChoices!.includes(i) && other.skill === skill)
)
throw Error("Choose an available skill.");
p.skill = skill;
s.skillChoices.shift();
event(s, `${p.name} chose ${SKILLS[skill].name}.`);
if (!s.skillChoices.length) {
delete s.skillChoices;
for (const player of s.players) {
const spec = SKILLS[player.skill];
for (let j = 0; j < spec.draw; j++) draw(s, player, 1);
player.setupDone = spec.draw === spec.keep && spec.dice === 6;
}
if (s.players.every((player) => player.setupDone)) startRound(s);
}
return;
}
if (s.players.some((p) => p.pendingInjuries) && m.action !== "injury") throw Error("Choose an injury first.");
switch (m.action) {
case "setup": {
@ -1018,6 +1048,7 @@ export function applyMove(data: State, input: unknown, seat: number): State {
if (typeof raw.action !== "string") throw Error("Invalid action.");
const allowed = [
"action",
"skill",
"keep",
"drop",
"path",
@ -1078,6 +1109,7 @@ export function stripSecret(s: State, seat?: number): View {
}
export function activePlayers(s: State | View): number[] {
if (s.outcome) return [];
if (s.skillChoices?.length) return [s.skillChoices[0]!];
if (s.pending) return s.pending.players;
const injured = s.players.flatMap((p, i) => (p.pendingInjuries ? [i] : []));
if (injured.length) return injured;
@ -1113,7 +1145,9 @@ export function setPlayerName(s: State, seat: number, name: string): State {
return next;
}
export function replay(s: State, to?: number): State {
let state = initGame(s.players.length, s.initOptions, s.seed);
// Saves predating skill assignment used the fixed roster.
let state = initGame(s.players.length, { skillAssignment: "fixed", ...s.initOptions }, s.seed);
state.initOptions = structuredClone(s.initOptions);
for (const e of s.history.slice(0, to ?? s.history.length)) {
if (e.move.action === "$planning") {
restorePlanning(state, e.move.snapshot as unknown as PlanningSnapshot);

View file

@ -85,6 +85,7 @@ export interface PlanningSnapshot {
revision: number;
}
export interface State {
skillChoices?: number[];
liveUpdate?: boolean;
planningSnapshot?: PlanningSnapshot;
schemaVersion: 1;

View file

@ -93,6 +93,7 @@
let newPlayers = $state(3);
let newDifficulty = $state(1);
let newScenario = $state(1);
let newSkills = $state("random");
let newSeed = $state("first-light");
function openNewGame() {
const current = store.state;
@ -482,8 +483,8 @@
style:--player-color={CHARACTER_COLORS[p.character]}
onclick={() => {
if (store.local) store.selectSeat(i);
else store.clickPlayer(i);
}}
disabled={!store.local}
aria-label={`${p.name}${seat === i ? ", you" : ""}${actingSeats.includes(i) ? ", can act now" : ""}. ${EXHAUSTION - p.stamina} stamina remaining${p.skill === "gatherer" ? `, ${p.powerBars} power bars` : ""}${store.local ? ". Switch to this player." : ""}`}
>
<img src={art("character", p.character + 1)} alt="" class="portrait" />
@ -491,7 +492,9 @@
<span class="teammate-name"
>{p.name}{#if seat === i}<small>YOU</small>{/if}</span
><span class="role-name"
>{SKILLS[p.skill].name}{#each p.injuries as injury}<InjuryIcon
>{s.skillChoices?.includes(i)
? "Choosing skill"
: SKILLS[p.skill].name}{#each p.injuries as injury}<InjuryIcon
{injury}
/>{/each}{#if p.skill === "gatherer"}<span
class="public-bars"
@ -762,6 +765,28 @@
</div>
{#if store.local}<button class="primary" onclick={openNewGame}>Start a new expedition</button>{/if}
{:else if !me}<p class="instruction">Follow the expedition. Private dice remain hidden until the reveal.</p>
{:else if s.skillChoices?.length}
<p class="instruction">
{s.skillChoices[0] === seat
? "Choose your skill."
: `${s.players[s.skillChoices[0]!]!.name} is choosing a skill.`}
</p>
<div class="skill-choices">
{#each Object.entries(SKILLS) as [id, skill]}
{@const owner = s.players.find((p, i) => !s.skillChoices!.includes(i) && p.skill === id)}
<button
disabled={s.skillChoices[0] !== seat || !!owner || store.waiting}
onclick={() => store.dispatch({ action: "chooseSkill", skill: id })}
>
<strong>{skill.name}</strong><span>{skill.description}</span>
<small
>{skill.dice} dice · draw {skill.draw}, keep {skill.keep} equipment{owner
? ` · ${owner.name}`
: ""}</small
>
</button>
{/each}
</div>
{:else if s.phase === "setup"}
{#if me.setupDone}<p class="instruction">
Your bag is packed. Waiting for the rest of the expedition.
@ -1289,6 +1314,15 @@
Seven official map layouts. The seed shuffles terrain and equipment within the chosen layout.
</p>
</fieldset>
<fieldset class="visible-choices">
<legend>Skills</legend>
<div class="choice-row">
{#each [["random", "Random"], ["choose", "Choose skills"]] as [value, label]}<button
aria-pressed={newSkills === value}
onclick={() => (newSkills = value!)}>{label}</button
>{/each}
</div>
</fieldset>
<fieldset class="visible-choices">
<legend>Difficulty</legend>
<div class="choice-row">
@ -1305,7 +1339,7 @@
><button
class="primary"
onclick={() => {
store.restart(newPlayers, newSeed, newDifficulty, newScenario);
store.restart(newPlayers, newSeed, newDifficulty, newScenario, newSkills);
newGame = false;
inspected = "";
}}>Begin expedition <span>→</span></button

View file

@ -66,8 +66,8 @@ store.selectSeat = (seat) => {
store.error = "";
publish();
};
store.restart = (players, seed, difficulty, scenario = 1) => {
game = initGame(players, { difficulty, scenario }, seed);
store.restart = (players, seed, difficulty, scenario = 1, skillAssignment = "random") => {
game = initGame(players, { difficulty, scenario, skillAssignment }, seed);
store.seat = 0;
publish();
};

View file

@ -3,6 +3,7 @@ import type { View, Move } from "fuji-engine";
export class Store {
state: View | null = $state(null);
avatars: string[] = $state([]);
clickPlayer: (index: number) => void = () => {};
private audio = new SoundDesign();
sound = $state(true);
setSound(enabled: boolean) {
@ -65,7 +66,8 @@ export class Store {
}
send: (move: Move) => void = () => {};
selectSeat: (seat: number) => void = () => {};
restart: (players: number, seed: string, difficulty: number, scenario?: number) => void = () => {};
restart: (players: number, seed: string, difficulty: number, scenario?: number, skillAssignment?: string) => void =
() => {};
teammateStep: () => void = () => {};
dispatch(move: Move) {
if (this.animating && this.blocksInput) return;

View file

@ -1640,3 +1640,27 @@ h3 {
.teammate.opposite:focus-visible {
opacity: 1;
}
.teammate {
cursor: pointer;
}
.teammate:hover .teammate-name,
.teammate:focus-visible .teammate-name {
color: var(--gold);
text-decoration: underline;
text-underline-offset: 3px;
}
.skill-choices {
display: grid;
gap: 10px;
}
.skill-choices button {
display: grid;
gap: 8px;
text-align: left;
padding: 14px;
}
.skill-choices span {
font-size: 14px;
line-height: 1.5;
}

View file

@ -18,6 +18,7 @@ export function launch(selector: string) {
events.on<string[]>("avatars", (avatars) => {
store.avatars = avatars;
});
store.clickPlayer = (index) => events.emit("player:clicked", { index });
store.send = (move) => events.emit("move", move);
events.on<View>("state", async (state) => {
store.receive(state);

View file

@ -5,7 +5,7 @@ import path from "node:path";
const { initGame, applyMove, stripSecret, SKILLS, paths, comparison } = await import(
root + "/packages/engine/dist/index.js"
);
const game = initGame(3, { autoMovement: false, autoProgress: false }, "bridge-test");
const game = initGame(3, { autoMovement: false, autoProgress: false, skillAssignment: "fixed" }, "bridge-test");
const view = stripSecret(game, 2);
const browser = await chromium.launch({ headless: true, executablePath: process.env.FUJI_CHROMIUM_EXECUTABLE });
const page = await browser.newPage();
@ -162,7 +162,7 @@ import path from "node:path";
if (await page.locator(".die-caption").count()) throw Error("Color labels did not turn off");
await page.keyboard.press("Escape");
if ((await page.locator(".village-marker").count()) !== 5) throw Error("Every village location needs a marker");
const conflictState = initGame(4, {}, "dice-conflicts");
const conflictState = initGame(4, { skillAssignment: "fixed" }, "dice-conflicts");
conflictState.phase = "reroll";
conflictState.board.forEach((c) => {
if (!c.lava) c.terrain = 16;

View file

@ -0,0 +1,42 @@
import { chromium } from "playwright";
import assert from "node:assert/strict";
import { initGame, stripSecret, applyMove } from "../packages/engine/dist/index.js";
const browser = await chromium.launch({ executablePath: process.env.FUJI_CHROMIUM_EXECUTABLE });
try {
const page = await browser.newPage();
await page.setContent('<div id="app"></div>');
await page.addStyleTag({ path: "packages/viewer/dist/fuji-viewer.css" });
await page.addScriptTag({ path: "packages/viewer/dist/fuji-viewer.iife.js" });
let state = initGame(3, { skillAssignment: "choose" }, "skill-ui");
await page.evaluate(
(view) => {
window.bridge = window.fuji.launch("#app");
window.moves = [];
window.clicked = [];
window.bridge.on("move", (m) => window.moves.push(m));
window.bridge.on("player:clicked", (m) => window.clicked.push(m));
window.bridge.emit("player", { index: 0 });
window.bridge.emit("state", view);
},
stripSecret(state, 0)
);
await page.locator(".teammate-name").nth(1).click();
assert.deepEqual(await page.evaluate(() => window.clicked), [{ index: 1 }]);
assert.equal(await page.locator(".skill-choices button:enabled").count(), 6);
await page.locator(".skill-choices button").filter({ hasText: "Equipment manager" }).click();
const move = await page.evaluate(() => window.moves.at(-1));
assert.deepEqual(move, { action: "chooseSkill", skill: "manager" });
state = applyMove(state, move, 0);
await page.evaluate(
(view) => {
window.bridge.emit("player", { index: 1 });
window.bridge.emit("state", view);
},
stripSecret(state, 1)
);
assert(await page.locator(".skill-choices button").filter({ hasText: "Equipment manager" }).isDisabled());
assert.equal(await page.locator(".skill-choices button:enabled").count(), 5);
console.log("BGS player clicks and skill selection work; taken skills are disabled.");
} finally {
await browser.close();
}