Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
233 changes: 190 additions & 43 deletions packages/engine/src/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ActionCandidate> {
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<ActionCandidate> {
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<CheckedAction> {
for (const candidate of candidateActions(state, role, contentSet, explainLessons))
yield { ...candidate, code: refusalCode(state, candidate.action, contentSet) };
}

/**
Expand All @@ -1449,16 +1502,110 @@ function turnChanged(state: GameState): boolean {
return hashCanonical(snapshotCheckpoint(state)) !== hashCanonical(state.checkpoint);
}

function listLegalActions(state: GameState, checked: Iterable<CheckedAction>): 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<string, string | null>();
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(
Expand Down
17 changes: 16 additions & 1 deletion packages/engine/src/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Loading
Loading