diff --git a/packages/engine/src/game.ts b/packages/engine/src/game.ts index 29bfbcc..b58235e 100644 --- a/packages/engine/src/game.ts +++ b/packages/engine/src/game.ts @@ -1388,57 +1388,110 @@ export function refusalCode( } } +interface ActionCandidate { + action: GameAction; + floorCard?: { instanceId: string; type: DanceCard["type"] }; +} + +function* singleCardCandidates( + hand: readonly string[], + type: DanceCard["type"], + actionForCard: (instanceId: string) => GameAction, +): Generator { + for (const instanceId of hand) + yield { action: actionForCard(instanceId), floorCard: { instanceId, type } }; +} + /** * Every action `role` could name from where its arguments come from, in `legalActions`' order. * Holds no rule: anything the reducer would reject is left to `checkAction`. */ -function candidateActions(state: GameState, role: Role, contentSet: ContentSet): GameAction[] { - if (state.status === "setup") - return [ - { type: "MULLIGAN", role }, - { type: "CONFIRM_HAND", role }, - ]; - const hand = state.players[role].hand.map((entry) => entry.instanceId); - const candidates: GameAction[] = [ - ...hand.map((instanceId): GameAction => ({ type: "SIGNAL_CARD", role, instanceId })), - { type: "CLEAR_SIGNAL", role }, - { type: "UNDO_TURN", role }, - ]; - if (state.phase === "dance") { - for (const positionInstanceId of hand) - for (const moveInstanceId of hand) - candidates.push({ type: "PLAY_OPEN", role, positionInstanceId, moveInstanceId }); - for (const moveInstanceId of hand) candidates.push({ type: "PLAY_MOVE", role, moveInstanceId }); - for (const positionInstanceId of hand) - candidates.push({ type: "TRANSITION", role, positionInstanceId }); - for (const positionInstanceId of hand) - candidates.push({ type: "ADJUST", role, positionInstanceId }); - for (const flourishInstanceId of hand) - candidates.push({ type: "PLAY_FLOURISH", role, flourishInstanceId }); - candidates.push({ type: "STUMBLE", role, recoveryInstanceId: null }); - for (const recoveryInstanceId of hand) - candidates.push({ type: "STUMBLE", role, recoveryInstanceId }); - for (const recoveryInstanceId of hand) - candidates.push({ type: "COVER_CALL", role, recoveryInstanceId }); - candidates.push({ type: "END_DANCE", role, callId: null }); - for (const option of contentSet.rules.call?.options ?? []) - candidates.push({ type: "END_DANCE", role, callId: option.id }); +function* candidateActions( + state: GameState, + role: Role, + contentSet: ContentSet, + explainLessons: boolean, +): Generator { + if (state.status === "setup") { + yield { action: { type: "MULLIGAN", role } }; + yield { action: { type: "CONFIRM_HAND", role } }; + } else { + const hand = state.players[role].hand.map((entry) => entry.instanceId); + for (const instanceId of hand) yield { action: { type: "SIGNAL_CARD", role, instanceId } }; + yield { action: { type: "CLEAR_SIGNAL", role } }; + yield { action: { type: "UNDO_TURN", role } }; + if (state.phase === "dance") { + for (const positionInstanceId of hand) + for (const moveInstanceId of hand) + yield { action: { type: "PLAY_OPEN", role, positionInstanceId, moveInstanceId } }; + yield* singleCardCandidates(hand, "move", (moveInstanceId) => ({ + type: "PLAY_MOVE", + role, + moveInstanceId, + })); + yield* singleCardCandidates(hand, "position", (positionInstanceId) => ({ + type: "TRANSITION", + role, + positionInstanceId, + })); + yield* singleCardCandidates(hand, "position", (positionInstanceId) => ({ + type: "ADJUST", + role, + positionInstanceId, + })); + yield* singleCardCandidates(hand, "flourish", (flourishInstanceId) => ({ + type: "PLAY_FLOURISH", + role, + flourishInstanceId, + })); + yield { action: { type: "STUMBLE", role, recoveryInstanceId: null } }; + yield* singleCardCandidates(hand, "recovery", (recoveryInstanceId) => ({ + type: "STUMBLE", + role, + recoveryInstanceId, + })); + yield* singleCardCandidates(hand, "recovery", (recoveryInstanceId) => ({ + type: "COVER_CALL", + role, + recoveryInstanceId, + })); + yield { action: { type: "END_DANCE", role, callId: null } }; + for (const option of contentSet.rules.call?.options ?? []) + yield { action: { type: "END_DANCE", role, callId: option.id } }; + } } - if (state.phase === "lesson") { + + const lessonStep = state.status !== "setup" && state.phase === "lesson"; + if (lessonStep || explainLessons) { for (const cardId of contentSet.decks.beginnerSupply) - candidates.push({ type: "BUY_LESSON", role, source: "beginner", cardId }); + yield { action: { type: "BUY_LESSON", role, source: "beginner", cardId } }; for (const cardId of state.market.intermediateDisplay) - candidates.push({ type: "BUY_LESSON", role, source: "intermediate", cardId }); + yield { action: { type: "BUY_LESSON", role, source: "intermediate", cardId } }; for (const cardId of state.market.advancedDisplay) - candidates.push({ type: "BUY_LESSON", role, source: "advanced", cardId }); + yield { action: { type: "BUY_LESSON", role, source: "advanced", cardId } }; + } + if (lessonStep) { const partnerMoves = state.moveHistory .filter((entry) => entry.role === otherRole(role) && entry.phrase === state.phrase.number) .map((entry) => entry.cardId); for (const cardId of new Set(partnerMoves)) - candidates.push({ type: "LEARN_FROM_PARTNER", role, cardId }); - candidates.push({ type: "END_LESSON", role }); + yield { action: { type: "LEARN_FROM_PARTNER", role, cardId } }; + yield { action: { type: "END_LESSON", role } }; } - return candidates; +} + +interface CheckedAction extends ActionCandidate { + code: string | null; +} + +function* checkedActions( + state: GameState, + role: Role, + contentSet: ContentSet, + explainLessons: boolean, +): Generator { + for (const candidate of candidateActions(state, role, contentSet, explainLessons)) + yield { ...candidate, code: refusalCode(state, candidate.action, contentSet) }; } /** @@ -1449,16 +1502,110 @@ function turnChanged(state: GameState): boolean { return hashCanonical(snapshotCheckpoint(state)) !== hashCanonical(state.checkpoint); } +function listLegalActions(state: GameState, checked: Iterable): GameAction[] { + const actions: GameAction[] = []; + for (const { action, code } of checked) { + if (code === null && (action.type !== "UNDO_TURN" || turnChanged(state))) actions.push(action); + } + return actions; +} + export function legalActions( state: GameState, role: Role, contentSet: ContentSet = defaultContent, ): GameAction[] { - return candidateActions(state, role, contentSet).filter( - (action) => - refusalCode(state, action, contentSet) === null && - (action.type !== "UNDO_TURN" || turnChanged(state)), - ); + return listLegalActions(state, checkedActions(state, role, contentSet, false)); +} + +/** An accepted pair wins. Otherwise prefer the first failure that explains more than a mismatch. */ +function openingRefusal( + checked: readonly CheckedAction[], + instanceId: string, + type: "position" | "move", + oppositeIds: readonly string[], +): string | null { + const pairCodes = new Map(); + for (const { action, code } of checked) { + if (action.type !== "PLAY_OPEN") continue; + const { positionInstanceId, moveInstanceId } = action; + const [origin, opposite] = + type === "position" + ? [positionInstanceId, moveInstanceId] + : [moveInstanceId, positionInstanceId]; + if (instanceId === origin) pairCodes.set(opposite, code); + } + let first = "POSITION_MISMATCH"; + for (const opposite of oppositeIds) { + const code = pairCodes.get(opposite); + if (code === null) return null; + if (code !== undefined && first === "POSITION_MISMATCH") first = code; + } + return first; +} + +function listFloorRefusals( + state: GameState, + role: Role, + contentSet: ContentSet, + checked: readonly CheckedAction[], +): { instanceId: string; code: string }[] { + if (state.status !== "playing" || state.phase !== "dance" || state.activeRole !== role) return []; + + const cardTypes = new Map(contentSet.cards.map(({ id, type }) => [id, type])); + const hand = state.players[role].hand.map(({ instanceId, cardId }) => { + const type = cardTypes.get(cardId); + if (!type) throw new Error(`Missing content for ${cardId}.`); + return { instanceId, type }; + }); + const positions = hand.filter(({ type }) => type === "position").map((card) => card.instanceId); + const moves = hand.filter(({ type }) => type === "move").map((card) => card.instanceId); + + const refusals: { instanceId: string; code: string }[] = []; + for (const { instanceId, type } of hand) { + const plays = checked.filter( + ({ floorCard }) => floorCard?.instanceId === instanceId && floorCard.type === type, + ); + if (plays.some(({ code }) => code === null)) continue; + + if (state.table.position === null && (type === "position" || type === "move")) { + const code = openingRefusal( + checked, + instanceId, + type, + type === "position" ? moves : positions, + ); + if (code !== null) refusals.push({ instanceId, code }); + continue; + } + + // Before dancing a card, explain the Hold before the Transition. Otherwise the legal-list + // order gives the intended precedence, including Stumble before Cover. + const hold = + state.turnDance.cardsPlayed === 0 && plays.find(({ action }) => action.type === "ADJUST"); + const code = (hold || plays[0])?.code; + if (code) refusals.push({ instanceId, code }); + } + return refusals; +} + +function listLessonRefusals(checked: readonly CheckedAction[]) { + const refusals = []; + for (const { action, code } of checked) { + if (action.type === "BUY_LESSON" && code !== null) + refusals.push({ source: action.source, cardId: action.cardId, code }); + } + return refusals; +} + +/** The availability fields of one role's Snapshot share the reducer checks for this read. */ +export function actionAvailability(state: GameState, role: Role, contentSet: ContentSet) { + const checked = [...checkedActions(state, role, contentSet, true)]; + return { + legalActions: listLegalActions(state, checked), + floorRefusals: listFloorRefusals(state, role, contentSet, checked), + lessonRefusals: listLessonRefusals(checked), + }; } export function replayActions( diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index 472c751..0b86419 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -1,5 +1,20 @@ export * from "./envelope.js"; -export * from "./game.js"; +export { + afinqueBonus, + afinqueCap, + applyAction, + bonusConditionMet, + callDefinition, + callMet, + createGame, + legalActions, + refusalCode, + replayActions, + replayFrom, + rungFor, + songBonusFor, + standingCall, +} from "./game.js"; export * from "./rng.js"; export * from "./schemas.js"; export * from "./snapshot.js"; diff --git a/packages/engine/src/snapshot.ts b/packages/engine/src/snapshot.ts index fb6e7f7..e06af79 100644 --- a/packages/engine/src/snapshot.ts +++ b/packages/engine/src/snapshot.ts @@ -7,13 +7,12 @@ import { type SongCard, } from "@clave/content"; import { + actionAvailability, afinqueBonus, afinqueCap, applyAction, callDefinition, callMet, - legalActions, - refusalCode, songBonusFor, standingCall, } from "./game.js"; @@ -173,161 +172,6 @@ export interface PlayerSnapshot { rating: { name: string; description: string } | null; } -function viewersDanceStep(state: GameState, role: Role): boolean { - return state.status === "playing" && state.phase === "dance" && state.activeRole === role; -} - -/** - * The floor actions a card attempts once a Position is on the table, and those a Flourish or - * Recovery attempts on an empty floor, in the order the player would mean them: a Position - * takes or adjusts the hold before the dance and carries it after, a Recovery covers the call - * standing over the player or marks a stumble. - */ -function establishedFloorActions( - state: GameState, - role: Role, - instanceId: string, - type: DanceCard["type"], -): GameAction[] { - switch (type) { - case "move": - return [{ type: "PLAY_MOVE", role, moveInstanceId: instanceId }]; - case "position": - return state.turnDance.cardsPlayed === 0 - ? [ - { type: "ADJUST", role, positionInstanceId: instanceId }, - { type: "TRANSITION", role, positionInstanceId: instanceId }, - ] - : [ - { type: "TRANSITION", role, positionInstanceId: instanceId }, - { type: "ADJUST", role, positionInstanceId: instanceId }, - ]; - case "flourish": - return [{ type: "PLAY_FLOURISH", role, flourishInstanceId: instanceId }]; - case "recovery": - return [ - { type: "STUMBLE", role, recoveryInstanceId: instanceId }, - { type: "COVER_CALL", role, recoveryInstanceId: instanceId }, - ]; - } -} - -/** - * Empty-floor Position or Move: `PLAY_OPEN` with each opposite card. - * A passing pair omits the card. A shared non-mismatch failure (turn and phase fail first) - * wins over `POSITION_MISMATCH`. No opposite card is a mismatch. - */ -function openingRefusal( - state: GameState, - role: Role, - contentSet: ContentSet, - hand: readonly CardInstance[], - instance: CardInstance, - cards: Record, -): string | null { - const card = cards[instance.cardId]!; - const opposite = card.type === "position" ? "move" : "position"; - const oppositeCards = hand.filter((other) => cards[other.cardId]?.type === opposite); - if (oppositeCards.length === 0) return "POSITION_MISMATCH"; - let shared: string | null = null; - for (const oppositeCard of oppositeCards) { - const action: GameAction = - card.type === "position" - ? { - type: "PLAY_OPEN", - role, - positionInstanceId: instance.instanceId, - moveInstanceId: oppositeCard.instanceId, - } - : { - type: "PLAY_OPEN", - role, - positionInstanceId: oppositeCard.instanceId, - moveInstanceId: instance.instanceId, - }; - const code = refusalCode(state, action, contentSet); - if (code === null) return null; - if (code !== "POSITION_MISMATCH") shared ??= code; - } - return shared ?? "POSITION_MISMATCH"; -} - -/** - * Why none of a card's floor actions can be played, or null when one of them can. The first - * failure is the one published: the actions are ordered by what the player would mean. - */ -function floorRefusal( - state: GameState, - role: Role, - contentSet: ContentSet, - hand: readonly CardInstance[], - instance: CardInstance, - cards: Record, -): string | null { - const card = cards[instance.cardId]!; - const codes: string[] = []; - if (state.table.position === null && (card.type === "position" || card.type === "move")) { - const opening = openingRefusal(state, role, contentSet, hand, instance, cards); - if (opening === null) return null; - codes.push(opening); - } - for (const action of establishedFloorActions(state, role, instance.instanceId, card.type)) { - const code = refusalCode(state, action, contentSet); - if (code === null) return null; - codes.push(code); - } - return codes[0] ?? null; -} - -function floorRefusalList( - state: GameState, - role: Role, - contentSet: ContentSet, - cards: Record, -): { instanceId: string; code: string }[] { - if (!viewersDanceStep(state, role)) return []; - const hand = state.players[role].hand; - const refusals: { instanceId: string; code: string }[] = []; - for (const instance of hand) { - if (!cards[instance.cardId]) throw new Error(`Missing content for ${instance.cardId}.`); - const code = floorRefusal(state, role, contentSet, hand, instance, cards); - if (code) refusals.push({ instanceId: instance.instanceId, code }); - } - return refusals; -} - -function lessonRefusalList( - state: GameState, - role: Role, - contentSet: ContentSet, -): PlayerSnapshot["lessonRefusals"] { - const offered: { source: PlayerSnapshot["lessonRefusals"][number]["source"]; cardId: string }[] = - [ - ...contentSet.decks.beginnerSupply.map((cardId) => ({ - source: "beginner" as const, - cardId, - })), - ...state.market.intermediateDisplay.map((cardId) => ({ - source: "intermediate" as const, - cardId, - })), - ...state.market.advancedDisplay.map((cardId) => ({ - source: "advanced" as const, - cardId, - })), - ]; - const refusals: PlayerSnapshot["lessonRefusals"] = []; - for (const entry of offered) { - const code = refusalCode( - state, - { type: "BUY_LESSON", role, source: entry.source, cardId: entry.cardId }, - contentSet, - ); - if (code) refusals.push({ source: entry.source, cardId: entry.cardId, code }); - } - return refusals; -} - function lookup(contentSet: ContentSet): Record { return Object.fromEntries(contentSet.cards.map((card) => [card.id, card])); } @@ -528,9 +372,7 @@ export function snapshotFor( state.signal && signaledInstance ? { role: state.signal.role, card: cardView(signaledInstance, cards)! } : null, - legalActions: legalActions(state, role, contentSet), - floorRefusals: floorRefusalList(state, role, contentSet, cards), - lessonRefusals: lessonRefusalList(state, role, contentSet), + ...actionAvailability(state, role, contentSet), // A window while the dance runs: a long song logs more than any screen in play shows. The // end screen recaps the whole song from its own sentences, and is sent once. log: diff --git a/packages/engine/tests/refusals.test.ts b/packages/engine/tests/refusals.test.ts index 35afe2f..4899efe 100644 --- a/packages/engine/tests/refusals.test.ts +++ b/packages/engine/tests/refusals.test.ts @@ -1,9 +1,10 @@ -import { content } from "@clave/content"; +import { content, ContentSetSchema, hashCanonical } from "@clave/content"; import { describe, expect, it } from "vitest"; import { ENGINE_VERSION, applyAction, createEnvelope, + createGame, refusalCode, snapshotFor, type GameAction, @@ -167,6 +168,73 @@ describe("snapshot refusal codes", () => { expect(follow.phase).toBe("dance"); }); + it("publishes floor guidance for a card added to the bundled content catalog", () => { + const move = content.cards.find(({ id }) => id === "mov_002")!; + const starter = content.decks.starter.find(({ cardId }) => cardId === move.id)!; + const handSize = content.rules.handSize; + const addedMove = { ...move, id: "mov_999" }; + content.cards.push(addedMove); + try { + starter.cardId = addedMove.id; + content.rules.handSize = content.decks.starter.reduce((total, { count }) => total + count, 0); + const parsedCopy = ContentSetSchema.parse(content); + let state = createGame({ seed: 9, content, contentHash: hashCanonical(content) }); + state = applyOk(state, { type: "CONFIRM_HAND", role: "lead" }); + state = applyOk(state, { type: "CONFIRM_HAND", role: "follow" }); + + const instance = state.players.lead.hand.find(({ cardId }) => cardId === addedMove.id)!; + expect(() => snapshotFor(state, "lead", parsedCopy)).not.toThrow(); + expect(snapshotFor(state, "lead", content).floorRefusals).toContainEqual({ + instanceId: instance.instanceId, + code: "UNKNOWN_CARD", + }); + } finally { + content.cards.pop(); + starter.cardId = move.id; + content.rules.handSize = handSize; + } + }); + + it("omits a Recovery refusal while the card can cover a Call after a Move", () => { + let state = readyGame(); + setHand(state, "lead", ["pos_001", "mov_002"]); + const [position, openingMove] = state.players.lead.hand; + state = applyOk(state, { + type: "PLAY_OPEN", + role: "lead", + positionInstanceId: position!.instanceId, + moveInstanceId: openingMove!.instanceId, + }); + state = applyOk(state, { type: "END_DANCE", role: "lead", callId: "call_005" }); + state = applyOk(state, { type: "END_LESSON", role: "lead" }); + setHand(state, "follow", ["mov_002", "rec_001", "rec_001"]); + const [move, cover, remaining] = state.players.follow.hand; + state = applyOk(state, { type: "PLAY_MOVE", role: "follow", moveInstanceId: move!.instanceId }); + + expect( + applyAction( + state, + { type: "STUMBLE", role: "follow", recoveryInstanceId: cover!.instanceId }, + content, + ), + ).toMatchObject({ ok: false, error: { code: "ALREADY_DANCED" } }); + const coverAction = { + type: "COVER_CALL", + role: "follow", + recoveryInstanceId: cover!.instanceId, + } as const; + const before = snapshotFor(state, "follow", content); + expect(before.legalActions).toContainEqual(coverAction); + expect(before.floorRefusals).toEqual([]); + + state = applyOk(state, coverAction); + const after = snapshotFor(state, "follow", content); + expect(after.legalActions.filter((action) => action.type === "COVER_CALL")).toEqual([]); + expect(after.floorRefusals).toEqual([ + { instanceId: remaining!.instanceId, code: "ALREADY_DANCED" }, + ]); + }); + it("publishes each market card's buy failure and omits a legal buy", () => { let state = readyGame(); state = applyOk(state, { type: "END_DANCE", role: "lead", callId: null }); diff --git a/tasks/done.md b/tasks/done.md index ec8551f..3a9e88f 100644 --- a/tasks/done.md +++ b/tasks/done.md @@ -1,3 +1,4 @@ +- [x] Deepen the engine's legal actions and refusals (issue #55) with one checked action inventory, preserved Snapshot ordering, and a Recovery cover regression. - [x] Build, test, and run on Node 26 alongside Node 22 (issue #53): add exact-release CI matrix coverage, retain one Node 22 production artifact gated on both runtimes, update workflow pin checks, and smoke-start the built server against an isolated database on both runtimes without startup deprecation warnings; existing engine constraints and locked dependencies need no changes. - [x] turn images into markdown - [x] Write an opinionated rulebook to docs/rules/game-rules according to docs/rules/decisions and docs/rules/game-rules-draft. Feel free to look elsewhere in the repo, and especially the handwritten-notes, for inspiration.