feat(SCOPONE-0009): complete iteration 0 dealer AI

This commit is contained in:
Giancarmine Salucci
2026-04-08 21:50:40 +02:00
parent c9accb7ae4
commit d0a44d295a
7 changed files with 597 additions and 174 deletions

View File

@@ -1,5 +1,5 @@
import { Card, GameState, PlayerIndex, Difficulty, PRIMIERA_VALUES, Suit, SUITS } from './types';
import { findCaptures, canCapture, teamOf, applyMove, buildDeck, cloneState } from './engine';
import { Card, GameState, PlayerIndex, Difficulty, PRIMIERA_VALUES, Suit, SUITS, DealerRelativeRole } from './types';
import { findCaptures, canCapture, teamOf, applyMove, buildDeck, cloneState, getDealerRelativeRole } from './engine';
import { CardTracker } from './card-tracker';
export interface AIMove {
@@ -22,10 +22,59 @@ interface SearchProfile {
batchSize: number;
}
interface DealerRoleContext {
role: DealerRelativeRole;
onDealerSide: boolean;
defendingDealerAdvantage: boolean;
attackingDealerAdvantage: boolean;
aggressionBias: number;
controlBias: number;
pairPreservingBias: number;
parityBreakingBias: number;
tablePressureBias: number;
}
interface ParitySnapshot {
unseenCounts: number[];
oddResidue: boolean[];
evenResidue: boolean[];
}
const DEALER_ROLE_WEIGHTS: Record<DealerRelativeRole, Omit<DealerRoleContext, 'role' | 'onDealerSide' | 'defendingDealerAdvantage' | 'attackingDealerAdvantage'>> = {
'first-hand': {
aggressionBias: 1.28,
controlBias: 0.9,
pairPreservingBias: 0.88,
parityBreakingBias: 1.26,
tablePressureBias: 1.3,
},
'second-hand': {
aggressionBias: 1,
controlBias: 1.08,
pairPreservingBias: 1.12,
parityBreakingBias: 0.96,
tablePressureBias: 1,
},
'third-hand': {
aggressionBias: 1.16,
controlBias: 0.94,
pairPreservingBias: 0.94,
parityBreakingBias: 1.16,
tablePressureBias: 1.12,
},
dealer: {
aggressionBias: 0.84,
controlBias: 1.32,
pairPreservingBias: 1.34,
parityBreakingBias: 0.82,
tablePressureBias: 0.78,
},
};
const SEARCH_PROFILES: Record<Difficulty, SearchProfile> = {
beginner: { timeBudgetMs: 120, sampleCount: 0, maxDepth: 0, batchSize: 0 },
advanced: { timeBudgetMs: 650, sampleCount: 0, maxDepth: 0, batchSize: 0 },
master: { timeBudgetMs: 9800, sampleCount: 12, maxDepth: 6, batchSize: 2 },
master: { timeBudgetMs: 4600, sampleCount: 10, maxDepth: 6, batchSize: 2 },
};
// ---------------------------------------------------------------------------
@@ -72,18 +121,192 @@ function countValueInHand(hand: Card[], value: number): number {
return n;
}
function getDealerRoleContext(state: GameState, playerIdx: PlayerIndex): DealerRoleContext {
const role = getDealerRelativeRole(state.dealer, playerIdx);
const onDealerSide = role === 'dealer' || role === 'second-hand';
return {
role,
onDealerSide,
defendingDealerAdvantage: onDealerSide,
attackingDealerAdvantage: !onDealerSide,
...DEALER_ROLE_WEIGHTS[role],
};
}
function getParitySnapshot(
tracker: CardTracker | undefined,
myHand: Card[],
table: Card[],
): ParitySnapshot | null {
if (!tracker) return null;
const unseenCounts = Array.from({ length: 11 }, () => 0);
const oddResidue = Array.from({ length: 11 }, () => false);
const evenResidue = Array.from({ length: 11 }, () => false);
const summary = tracker.getValueParityResidueSummary(myHand, table);
for (const residue of summary) {
unseenCounts[residue.value] = residue.unseenCount;
oddResidue[residue.value] = residue.hasOddUnseenResidue;
evenResidue[residue.value] = residue.hasEvenUnseenResidue;
}
return { unseenCounts, oddResidue, evenResidue };
}
function countParityValuesOnTable(afterTable: Card[], parity: ParitySnapshot | null): { oddValues: number; evenValues: number } {
if (!parity || afterTable.length === 0) {
return { oddValues: 0, evenValues: 0 };
}
let oddValues = 0;
let evenValues = 0;
const seenValues = new Set<number>();
for (const card of afterTable) {
if (seenValues.has(card.value)) continue;
seenValues.add(card.value);
if (parity.oddResidue[card.value]) oddValues++;
else if (parity.evenResidue[card.value]) evenValues++;
}
return { oddValues, evenValues };
}
function scoreRoleTablePlan(
afterTable: Card[],
roleContext: DealerRoleContext,
nextIsOpp: boolean,
): number {
if (afterTable.length === 0) return 0;
const tableSum = afterTable.reduce((sum, card) => sum + card.value, 0);
let score = 0;
if (roleContext.role === 'first-hand') {
if (afterTable.length >= 2) score += 22 * roleContext.tablePressureBias;
if (tableSum >= 8 && tableSum <= 15) score += 18 * roleContext.aggressionBias;
}
if (roleContext.role === 'third-hand') {
if (afterTable.length >= 2) score += 14 * roleContext.tablePressureBias;
if (tableSum >= 10) score += 10 * roleContext.aggressionBias;
}
if (roleContext.role === 'second-hand') {
if (nextIsOpp && tableSum >= 11) score += 16 * roleContext.controlBias;
if (!nextIsOpp && tableSum <= 10) score += 10 * roleContext.tablePressureBias;
}
if (roleContext.role === 'dealer') {
if (tableSum >= 11) score += 28 * roleContext.controlBias;
if (tableSum <= 10 && nextIsOpp) score -= 24 * roleContext.controlBias;
if (afterTable.length === 1 && nextIsOpp) score -= 16 * roleContext.controlBias;
}
return Math.round(score);
}
function scoreParityTableState(
afterTable: Card[],
parity: ParitySnapshot | null,
roleContext: DealerRoleContext,
nextIsOpp: boolean,
): number {
const { oddValues, evenValues } = countParityValuesOnTable(afterTable, parity);
if (oddValues === 0 && evenValues === 0) return 0;
let score = 0;
if (roleContext.defendingDealerAdvantage) {
score += evenValues * 18 * roleContext.controlBias;
score -= oddValues * 22 * roleContext.controlBias;
if (nextIsOpp) score += evenValues * 8 - oddValues * 10;
} else {
score += oddValues * 20 * roleContext.tablePressureBias;
score -= evenValues * 10;
if (nextIsOpp) score += oddValues * 12;
}
return Math.round(score);
}
function scoreCaptureParityPlan(
played: Card,
captured: Card[],
afterTable: Card[],
parity: ParitySnapshot | null,
roleContext: DealerRoleContext,
nextIsOpp: boolean,
): number {
if (!parity || captured.length === 0) return 0;
let score = 0;
const directCapture = captured.length === 1 && captured[0].value === played.value;
if (directCapture) {
const unseenCount = parity.unseenCounts[played.value] ?? 0;
const base = parity.oddResidue[played.value] ? 58 : 30;
score += base * roleContext.pairPreservingBias;
if (roleContext.defendingDealerAdvantage && unseenCount > 0) score += 18 * roleContext.controlBias;
} else {
let parityBreaks = 0;
let oddTargets = 0;
const seenValues = new Set<number>();
for (const card of captured) {
if (seenValues.has(card.value)) continue;
seenValues.add(card.value);
if ((parity.unseenCounts[card.value] ?? 0) > 0) parityBreaks++;
if (parity.oddResidue[card.value]) oddTargets++;
}
const disruption = parityBreaks * 20 + oddTargets * 18 + Math.max(0, captured.length - 1) * 12;
score += disruption * roleContext.parityBreakingBias;
if (roleContext.defendingDealerAdvantage) score -= 18 * roleContext.controlBias;
}
score += scoreParityTableState(afterTable, parity, roleContext, nextIsOpp);
return Math.round(score);
}
function scoreDumpParityPlan(
card: Card,
afterTable: Card[],
parity: ParitySnapshot | null,
roleContext: DealerRoleContext,
nextIsOpp: boolean,
): number {
if (!parity) return 0;
let score = scoreParityTableState(afterTable, parity, roleContext, nextIsOpp);
if (parity.oddResidue[card.value]) {
score += roleContext.attackingDealerAdvantage ? 18 * roleContext.tablePressureBias : -20 * roleContext.controlBias;
}
if (parity.evenResidue[card.value]) {
score += roleContext.defendingDealerAdvantage ? 14 * roleContext.pairPreservingBias : 6;
}
return Math.round(score);
}
function getSearchProfile(state: GameState, difficulty: Difficulty): SearchProfile {
if (difficulty !== 'master') return SEARCH_PROFILES[difficulty];
const cardsRemaining = state.players.reduce((sum, player) => sum + player.hand.length, 0);
if (cardsRemaining <= 4) {
return { timeBudgetMs: 3200, sampleCount: 4, maxDepth: cardsRemaining, batchSize: 1 };
}
if (cardsRemaining <= 6) {
return { timeBudgetMs: 9800, sampleCount: 18, maxDepth: Math.min(cardsRemaining, 8), batchSize: 1 };
return { timeBudgetMs: 3600, sampleCount: 6, maxDepth: cardsRemaining, batchSize: 1 };
}
if (cardsRemaining <= 8) {
return { timeBudgetMs: 3900, sampleCount: 8, maxDepth: cardsRemaining, batchSize: 1 };
}
if (cardsRemaining <= 12) {
return { timeBudgetMs: 9000, sampleCount: 16, maxDepth: 8, batchSize: 2 };
return { timeBudgetMs: 4200, sampleCount: 8, maxDepth: 8, batchSize: 1 };
}
if (cardsRemaining <= 20) {
return { timeBudgetMs: 8200, sampleCount: 14, maxDepth: 7, batchSize: 2 };
return { timeBudgetMs: 4400, sampleCount: 9, maxDepth: 7, batchSize: 2 };
}
return SEARCH_PROFILES.master;
}
@@ -432,6 +655,8 @@ function advancedMove(state: GameState, playerIdx: PlayerIndex, tracker?: CardTr
const table = state.table;
const phase = gamePhase(state);
const race = getRaceState(state, playerIdx);
const roleContext = getDealerRoleContext(state, playerIdx);
const parity = getParitySnapshot(tracker, player.hand, table);
const next = nextPlayer(playerIdx);
const nextIsOpp = isOpponent(playerIdx, next);
const partner = partnerOf(playerIdx);
@@ -447,14 +672,14 @@ function advancedMove(state: GameState, playerIdx: PlayerIndex, tracker?: CardTr
for (const captureSet of captures) {
const score = scoreCaptureAdv(
card, captureSet, table, state, playerIdx, race,
tracker, player.hand, phase, nextIsOpp, partnerHandSize, lastPlay,
tracker, player.hand, phase, nextIsOpp, partnerHandSize, lastPlay, roleContext, parity,
);
if (score > bestScore) { bestScore = score; bestMove = { card, capture: captureSet }; }
}
} else {
const score = scoreDumpAdv(
card, table, state, playerIdx, race,
tracker, player.hand, phase, nextIsOpp, partnerHandSize, lastPlay,
tracker, player.hand, phase, nextIsOpp, partnerHandSize, lastPlay, roleContext, parity,
);
if (score > bestScore) { bestScore = score; bestMove = { card, capture: [] }; }
}
@@ -467,7 +692,7 @@ function scoreCaptureAdv(
played: Card, captured: Card[], table: Card[], state: GameState,
playerIdx: PlayerIndex, race: RaceState, tracker: CardTracker | undefined,
myHand: Card[], phase: number, nextIsOpp: boolean, partnerHandSize: number,
lastPlay: boolean,
lastPlay: boolean, roleContext: DealerRoleContext, parity: ParitySnapshot | null,
): number {
let score = 100;
const allCaptured = [played, ...captured];
@@ -508,6 +733,8 @@ function scoreCaptureAdv(
}
}
score += scoreCaptureParityPlan(played, captured, afterTable, parity, roleContext, nextIsOpp);
// --- ANCHOR STRATEGY ---
// Prefer captures that leave table cards matching values we hold (we can recapture)
if (!isScopa) {
@@ -543,6 +770,8 @@ function scoreCaptureAdv(
}
}
score += scoreRoleTablePlan(afterTable, roleContext, nextIsOpp);
// --- PARTNER COOPERATION ---
const next = nextPlayer(playerIdx);
if (!isScopa && !isOpponent(playerIdx, next)) {
@@ -620,6 +849,14 @@ function scoreCaptureAdv(
if (tableSum <= 5 && nextIsOpp) score -= 60;
}
if (roleContext.role === 'first-hand' && !isScopa && afterTable.length >= 2) {
score += Math.round(24 * roleContext.tablePressureBias);
}
if (roleContext.role === 'dealer' && !isScopa) {
const tableSum = afterTable.reduce((s, c) => s + c.value, 0);
if (tableSum >= 11) score += Math.round(30 * roleContext.controlBias);
}
return score;
}
@@ -627,7 +864,7 @@ function scoreDumpAdv(
card: Card, table: Card[], state: GameState,
playerIdx: PlayerIndex, race: RaceState, tracker: CardTracker | undefined,
myHand: Card[], phase: number, nextIsOpp: boolean, partnerHandSize: number,
lastPlay: boolean,
lastPlay: boolean, roleContext: DealerRoleContext, parity: ParitySnapshot | null,
): number {
let score = 0;
const afterTable = [...table, card];
@@ -653,6 +890,8 @@ function scoreDumpAdv(
const partnerProb = partnerLikelyHolds(card.value, playerIdx, state, tracker, myHand, table);
if (partnerProb > 0.4) score += 55; // partner can recapture what we dump
score += scoreDumpParityPlan(card, afterTable, parity, roleContext, nextIsOpp);
// --- ANTI-SCOPA ---
if (tableSum >= 11) {
score += 150;
@@ -694,6 +933,8 @@ function scoreDumpAdv(
score += 20; // safe dump before partner's turn, signals we don't need this suit
}
score += scoreRoleTablePlan(afterTable, roleContext, nextIsOpp);
// --- CARD TRACKING ---
if (tracker) {
const unseen = tracker.getUnseenCards(myHand, afterTable);
@@ -729,6 +970,13 @@ function scoreDumpAdv(
if (card.value >= 8) score += 15;
}
if (roleContext.role === 'first-hand' && afterTable.length >= 2 && tableSum >= 8) {
score += Math.round(18 * roleContext.tablePressureBias);
}
if (roleContext.role === 'dealer' && nextIsOpp && tableSum <= 10) {
score -= Math.round(24 * roleContext.controlBias);
}
return score;
}
@@ -744,6 +992,8 @@ function tableControlPressure(
tracker: CardTracker | undefined,
myHand: Card[],
race: RaceState,
roleContext: DealerRoleContext,
parity: ParitySnapshot | null,
): number {
if (afterTable.length === 0) return 0;
@@ -790,6 +1040,8 @@ function tableControlPressure(
}
if (race.aheadOverall && nextIsOpp && tableSum <= 10) score -= 60;
score += scoreRoleTablePlan(afterTable, roleContext, nextIsOpp);
score += scoreParityTableState(afterTable, parity, roleContext, nextIsOpp);
return score;
}
@@ -814,9 +1066,11 @@ async function masterMove(
// Quick-eval move ordering for better pruning
const lastPlay = isLastPlay(state, playerIdx);
const race = getRaceState(state, playerIdx);
const roleContext = getDealerRoleContext(state, playerIdx);
const parity = getParitySnapshot(tracker, state.players[playerIdx].hand, state.table);
const quickScored = legalMoves.map(m => ({
move: m,
quick: quickEval(m, state, playerIdx, tracker, lastPlay, race),
quick: quickEval(m, state, playerIdx, tracker, lastPlay, race, roleContext, parity),
}));
quickScored.sort((a, b) => b.quick - a.quick);
const sortedMoves = quickScored.map(qs => qs.move);
@@ -891,15 +1145,19 @@ function quickEval(
move: AIMove, state: GameState, playerIdx: PlayerIndex,
tracker: CardTracker | undefined, lastPlay: boolean,
race: RaceState,
roleContext: DealerRoleContext,
parity: ParitySnapshot | null,
): number {
let score = 0;
const table = state.table;
const afterTable = table.filter(c => !move.capture.some(cc => cc.id === c.id));
const afterCaptureTable = table.filter(c => !move.capture.some(cc => cc.id === c.id));
const projectedTable = move.capture.length > 0 ? afterCaptureTable : [...afterCaptureTable, move.card];
const projectedHand = state.players[playerIdx].hand.filter(card => card.id !== move.card.id);
const allCaptured = [move.card, ...move.capture];
const nextIsOpp = isOpponent(playerIdx, nextPlayer(playerIdx));
// Scopa (not on last play!)
if (move.capture.length > 0 && afterTable.length === 0) {
if (move.capture.length > 0 && projectedTable.length === 0) {
score += lastPlay ? 50 : 1200;
}
@@ -924,21 +1182,35 @@ function quickEval(
}
// Anti-scopa
if (afterTable.length > 0) {
const sum = afterTable.reduce((s, c) => s + c.value, 0);
if (projectedTable.length > 0) {
const sum = projectedTable.reduce((s, c) => s + c.value, 0);
if (sum <= 10 && nextIsOpp) score -= 180;
if (sum >= 11) score += 60;
if (afterTable.length === 1 && nextIsOpp) score -= 120;
if (projectedTable.length === 1 && nextIsOpp) score -= 120;
}
// Partner awareness
const next = nextPlayer(playerIdx);
if (!isOpponent(playerIdx, next) && afterTable.length > 0) {
const sum = afterTable.reduce((s, c) => s + c.value, 0);
if (!isOpponent(playerIdx, next) && projectedTable.length > 0) {
const sum = projectedTable.reduce((s, c) => s + c.value, 0);
if (sum >= 1 && sum <= 10) score += 40; // partner might scopa
}
score += tableControlPressure(afterTable, state, playerIdx, tracker, state.players[playerIdx].hand, race);
score += scoreCaptureParityPlan(move.card, move.capture, projectedTable, parity, roleContext, nextIsOpp);
if (move.capture.length === 0) {
score += scoreDumpParityPlan(move.card, projectedTable, parity, roleContext, nextIsOpp);
}
score += tableControlPressure(
projectedTable,
state,
playerIdx,
tracker,
projectedHand,
race,
roleContext,
parity,
);
return score;
}
@@ -1036,20 +1308,22 @@ function alphaBeta(
tracker: CardTracker | undefined,
): number {
if (depth === 0 || state.roundOver || Date.now() > deadline) {
return evaluateFast(state, myTeam, phase);
return evaluateFast(state, myTeam, phase, tracker, rootPlayer);
}
const cur = state.currentPlayer;
const isMyTeam = teamOf(cur) === myTeam;
const moves = getLegalMoves(state, cur);
if (moves.length === 0) return evaluateFast(state, myTeam, phase);
if (moves.length === 0) return evaluateFast(state, myTeam, phase, tracker, rootPlayer);
// Move ordering: settebello captures first, then scopa, then captures by size, then dumps
if (moves.length > 2) {
const race = getRaceState(state, cur);
const lastPlay = isLastPlay(state, cur);
moves.sort((a, b) => quickEval(b, state, cur, tracker, lastPlay, race) - quickEval(a, state, cur, tracker, lastPlay, race));
const roleContext = getDealerRoleContext(state, cur);
const parity = getParitySnapshot(tracker, state.players[rootPlayer].hand, state.table);
moves.sort((a, b) => quickEval(b, state, cur, tracker, lastPlay, race, roleContext, parity) - quickEval(a, state, cur, tracker, lastPlay, race, roleContext, parity));
}
if (isMyTeam) {
@@ -1076,12 +1350,20 @@ function alphaBeta(
}
/** Fast evaluation: avoids flatMap/filter at every leaf node */
function evaluateFast(state: GameState, myTeam: 0 | 1, phase: number): number {
function evaluateFast(
state: GameState,
myTeam: 0 | 1,
phase: number,
tracker: CardTracker | undefined,
rootPlayer: PlayerIndex,
): number {
const p0 = state.players[0], p1 = state.players[1], p2 = state.players[2], p3 = state.players[3];
const myA = myTeam === 0 ? p0 : p1;
const myB = myTeam === 0 ? p2 : p3;
const oppA = myTeam === 0 ? p1 : p0;
const oppB = myTeam === 0 ? p3 : p2;
const roleContext = getDealerRoleContext(state, state.currentPlayer);
const parity = getParitySnapshot(tracker, state.players[rootPlayer].hand, state.table);
// Single-pass pile scan — no flatMap/filter allocations
let myCards = 0, oppCards = 0;
@@ -1204,6 +1486,21 @@ function evaluateFast(state: GameState, myTeam: 0 | 1, phase: number): number {
// Good: table has cards we can capture
score += state.table.length * 5;
}
const parityPressure = scoreParityTableState(state.table, parity, roleContext, !myTurn);
score += myTurn ? parityPressure : -parityPressure;
const rolePlan = scoreRoleTablePlan(state.table, roleContext, !myTurn);
score += myTurn ? rolePlan : -rolePlan;
if (parity) {
const { oddValues, evenValues } = countParityValuesOnTable(state.table, parity);
if (roleContext.defendingDealerAdvantage) {
score += (myTurn ? evenValues : -oddValues) * 14;
} else {
score += (myTurn ? oddValues : -evenValues) * 14;
}
}
}
return score;

View File

@@ -4,12 +4,35 @@ export interface CardTrackerSnapshot {
playedCardIds: string[];
}
export interface CardTrackerValueParityResidue {
value: number;
knownCount: number;
unseenCount: number;
hasOddUnseenResidue: boolean;
hasEvenUnseenResidue: boolean;
}
interface VisibleValueResidueKnowledge {
unseenCards: Card[];
unseenCountBySuit: Record<Suit, number>;
unseenCountByValue: number[];
valueParityResidues: CardTrackerValueParityResidue[];
}
function normalizeSnapshot(snapshot: CardTrackerSnapshot): CardTrackerSnapshot {
return {
playedCardIds: Array.from(new Set(snapshot.playedCardIds)),
};
}
function createEmptySuitCounts(): Record<Suit, number> {
const counts = {} as Record<Suit, number>;
for (const suit of SUITS) {
counts[suit] = 0;
}
return counts;
}
/**
* Tracks which cards have been played/captured during a round.
* Used by AI to infer opponent hands WITHOUT cheating.
@@ -65,44 +88,96 @@ export class CardTracker {
return !this.played.has('denara_7');
}
private buildVisibleValueResidueKnowledge(myHand: Card[], table: Card[]): VisibleValueResidueKnowledge {
const knownCardIds = new Set<string>(this.played);
for (const card of myHand) {
knownCardIds.add(card.id);
}
for (const card of table) {
knownCardIds.add(card.id);
}
const knownCountByValue = Array.from({ length: 11 }, () => 0);
const unseenCountByValue = Array.from({ length: 11 }, () => 0);
const unseenCountBySuit = createEmptySuitCounts();
const unseenCards: Card[] = [];
for (const suit of SUITS) {
for (let value = 1; value <= 10; value++) {
const id = `${suit}_${value}`;
if (knownCardIds.has(id)) {
knownCountByValue[value] += 1;
continue;
}
unseenCountByValue[value] += 1;
unseenCountBySuit[suit] += 1;
unseenCards.push({ suit, value, id });
}
}
const valueParityResidues: CardTrackerValueParityResidue[] = [];
for (let value = 1; value <= 10; value++) {
const unseenCount = unseenCountByValue[value];
valueParityResidues.push({
value,
knownCount: knownCountByValue[value],
unseenCount,
hasOddUnseenResidue: unseenCount % 2 === 1,
hasEvenUnseenResidue: unseenCount % 2 === 0,
});
}
return {
unseenCards,
unseenCountBySuit,
unseenCountByValue,
valueParityResidues,
};
}
/**
* Get cards that could be in opponent hands.
* = full 40-card deck minus: already played, my hand, currently on table
*/
getUnseenCards(myHand: Card[], table: Card[]): Card[] {
const known = new Set<string>();
for (const id of this.played) known.add(id);
for (const c of myHand) known.add(c.id);
for (const c of table) known.add(c.id);
const unseen: Card[] = [];
for (const suit of SUITS) {
for (let v = 1; v <= 10; v++) {
const id = `${suit}_${v}`;
if (!known.has(id)) {
unseen.push({ suit, value: v, id });
}
}
}
return unseen;
return this.buildVisibleValueResidueKnowledge(myHand, table).unseenCards;
}
/** Count how many cards of a suit are still unseen */
countRemainingSuit(suit: Suit, myHand: Card[], table: Card[]): number {
return this.getUnseenCards(myHand, table).filter(c => c.suit === suit).length;
return this.buildVisibleValueResidueKnowledge(myHand, table).unseenCountBySuit[suit];
}
/** Count how many unseen cards share a value */
countRemainingValue(value: number, myHand: Card[], table: Card[]): number {
return this.getUnseenCards(myHand, table).filter(c => c.value === value).length;
return this.getValueParityResidue(value, myHand, table).unseenCount;
}
/** Get visible known-count, unseen-count, and parity residue for a single value */
getValueParityResidue(value: number, myHand: Card[], table: Card[]): CardTrackerValueParityResidue {
const valueParityResidues = this.buildVisibleValueResidueKnowledge(myHand, table).valueParityResidues;
return valueParityResidues[value - 1] ?? {
value,
knownCount: 0,
unseenCount: 0,
hasOddUnseenResidue: false,
hasEvenUnseenResidue: true,
};
}
/** Get visible known-count, unseen-count, and parity residue for all card values */
getValueParityResidueSummary(myHand: Card[], table: Card[]): CardTrackerValueParityResidue[] {
return this.buildVisibleValueResidueKnowledge(myHand, table).valueParityResidues;
}
/** Probability that a hidden hand contains at least one card with the requested value */
probabilityHandHasValue(value: number, handSize: number, myHand: Card[], table: Card[]): number {
if (handSize <= 0) return 0;
const unseen = this.getUnseenCards(myHand, table);
const matching = unseen.filter(c => c.value === value).length;
const visibleValueResidueKnowledge = this.buildVisibleValueResidueKnowledge(myHand, table);
const unseen = visibleValueResidueKnowledge.unseenCards;
const matching = visibleValueResidueKnowledge.unseenCountByValue[value] ?? 0;
if (matching === 0) return 0;
if (handSize >= unseen.length) return 1;

View File

@@ -1,6 +1,6 @@
import {
Card, Suit, SUITS, Player, PlayerIndex, GameState,
TeamScore, ScoreBreakdown, PRIMIERA_VALUES, Capture
TeamScore, ScoreBreakdown, PRIMIERA_VALUES, Capture, DealerRelativeRole
} from './types';
// ---------------------------------------------------------------------------
@@ -76,8 +76,38 @@ export function canCapture(played: Card, table: Card[]): boolean {
// Game state initialisation
// ---------------------------------------------------------------------------
export function createInitialState(startingPlayer: PlayerIndex = 0): GameState {
export function nextPlayer(playerIdx: PlayerIndex, steps = 1): PlayerIndex {
return ((playerIdx + steps) % 4) as PlayerIndex;
}
export function getOpeningPlayerForDealer(dealer: PlayerIndex): PlayerIndex {
return nextPlayer(dealer);
}
export function getDealerRelativeOrder(
dealer: PlayerIndex
): [PlayerIndex, PlayerIndex, PlayerIndex, PlayerIndex] {
const firstHand = getOpeningPlayerForDealer(dealer);
const secondHand = nextPlayer(firstHand);
const thirdHand = nextPlayer(secondHand);
return [firstHand, secondHand, thirdHand, dealer];
}
export function getDealerRelativeRole(
dealer: PlayerIndex,
playerIdx: PlayerIndex
): DealerRelativeRole {
const [firstHand, secondHand, thirdHand] = getDealerRelativeOrder(dealer);
if (playerIdx === firstHand) return 'first-hand';
if (playerIdx === secondHand) return 'second-hand';
if (playerIdx === thirdHand) return 'third-hand';
return 'dealer';
}
export function createInitialState(dealer: PlayerIndex = 3): GameState {
const deck = shuffle(buildDeck());
const startingPlayer = getOpeningPlayerForDealer(dealer);
const players: [Player, Player, Player, Player] = [
{ index: 0, hand: [], pile: [], scope: 0, isHuman: true, name: 'Tu' },
@@ -102,6 +132,7 @@ export function createInitialState(startingPlayer: PlayerIndex = 0): GameState {
players,
table,
matchStartingPlayer: startingPlayer,
dealer,
currentPlayer: startingPlayer,
roundOver: false,
gameOver: false,
@@ -164,7 +195,7 @@ export function applyMove(
}
// Advance turn
state2.currentPlayer = ((playerIdx + 1) % 4) as PlayerIndex;
state2.currentPlayer = nextPlayer(playerIdx);
// Check if round is over (all hands empty)
const allHandsEmpty = state2.players.every(p => p.hand.length === 0);
@@ -353,6 +384,7 @@ export function cloneState(state: GameState): GameState {
],
table: state.table.map(cloneCard),
matchStartingPlayer: state.matchStartingPlayer,
dealer: state.dealer,
currentPlayer: state.currentPlayer,
roundOver: state.roundOver,
gameOver: state.gameOver,

View File

@@ -14,6 +14,8 @@ export interface Capture {
export type PlayerIndex = 0 | 1 | 2 | 3;
export type DealerRelativeRole = 'first-hand' | 'second-hand' | 'third-hand' | 'dealer';
export type Difficulty = 'beginner' | 'advanced' | 'master';
export interface Player {
@@ -29,6 +31,7 @@ export interface GameState {
players: [Player, Player, Player, Player];
table: Card[];
matchStartingPlayer: PlayerIndex;
dealer: PlayerIndex;
currentPlayer: PlayerIndex;
roundOver: boolean;
gameOver: boolean;