Migrate Go Fish and Hearts to the shared card-table kit
- Rewrite both games on CardTableScene with new table layout (GoFishTable.js, HeartsTable.js) and baked room art (GoFishArt.js, HeartsArt.js) - Add skill-scaled AI for both: Go Fish gains recall/random-ask memory and a no-re-ask rule per turn; Hearts tracks voids, the Queen, and moon shots - Support Go Fish pairs mode, book tracking, and heads-up (minOpponents 1) - Extend Hearts rules with configurable target score and add/subtract moon modes - Add headless verification suites (tools/verifyGoFish.js, tools/verifyHearts.js) covering rules, AI legality, layout collisions, and all-AI soaks - Enable skill selection for both games in OpponentSelectScene
This commit is contained in:
parent
e09986d53f
commit
5e7d4bb172
|
|
@ -35,7 +35,7 @@ registerGame({ slug: 'yatzi', name: 'Zahtzee', category: 'cards', minPlayers: 1,
|
|||
registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 5 });
|
||||
registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 });
|
||||
registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 6, maxPlayers: 6, minOpponents: 5, maxOpponents: 5, hasTutorial: true, iconFrame: 7 });
|
||||
registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, iconFrame: 8 });
|
||||
registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 8 });
|
||||
registerGame({ slug: 'uno', name: 'Uno', category: 'cards', cardGame: false, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 9 });
|
||||
registerGame({ slug: 'craps', name: 'Craps', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 10 });
|
||||
registerGame({ slug: 'roulette', name: 'Roulette', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 11 });
|
||||
|
|
|
|||
|
|
@ -6,11 +6,21 @@
|
|||
// entries.
|
||||
|
||||
import { RANKS } from '../cards/Deck.js';
|
||||
import { clampSkill } from '../../ui/cardtable/AITiming.js';
|
||||
|
||||
// Skill = how well the opponent remembers the table. Each fact it sees (who
|
||||
// asked for what, who handed what over) sticks with this probability, and a
|
||||
// beginner sometimes just asks a random player for a random card it holds.
|
||||
export const RECALL = { 1: 0.3, 2: 0.5, 3: 0.75, 4: 0.92, 5: 1 };
|
||||
const RANDOM_ASK = { 1: 0.35, 2: 0.18, 3: 0.05, 4: 0, 5: 0 };
|
||||
|
||||
const TOTAL_PER_RANK = 4; // 4 suits per rank
|
||||
|
||||
export function createMemory(seatCount) {
|
||||
export function createMemory(seatCount, { skill = 3, matchSize = 4, rng = Math.random } = {}) {
|
||||
return {
|
||||
skill: clampSkill(skill),
|
||||
matchSize,
|
||||
rng,
|
||||
// beliefs[targetSeat][rank] ∈ [0, 4]: a soft count of how many of that
|
||||
// rank we believe `targetSeat` still holds. Bumped when they ask for or
|
||||
// catch a rank; zeroed when they get fished or hand it over.
|
||||
|
|
@ -30,8 +40,13 @@ export function createMemory(seatCount) {
|
|||
* Replay every log entry from memory.logCursor onward and update memory.
|
||||
*/
|
||||
export function observeLog(memory, state, selfSeat) {
|
||||
const recall = RECALL[memory.skill ?? 5];
|
||||
const rand = memory.rng ?? Math.random;
|
||||
for (let i = memory.logCursor; i < state.log.length; i++) {
|
||||
const e = state.log[i];
|
||||
// a forgetful player simply misses some of what happens at the table
|
||||
// (books are laid face up, so everyone always sees those)
|
||||
if (e.kind !== 'pair' && e.kind !== 'sitout' && rand() > recall) continue;
|
||||
if (e.kind === 'ask') {
|
||||
// The asker held at least 1 of `rank` at the moment of the ask.
|
||||
memory.beliefs[e.askerSeat][e.rank] = Math.max(memory.beliefs[e.askerSeat][e.rank], 1);
|
||||
|
|
@ -52,9 +67,10 @@ export function observeLog(memory, state, selfSeat) {
|
|||
memory.beliefs[e.askerSeat][e.rank] += 1;
|
||||
memory.turnRecorded[e.askerSeat][e.rank] = state.turnCount;
|
||||
} else if (e.kind === 'pair') {
|
||||
memory.pairedCount[e.rank] += 2;
|
||||
// The pairer no longer holds 2 of that rank.
|
||||
memory.beliefs[e.seat][e.rank] = Math.max(0, memory.beliefs[e.seat][e.rank] - 2);
|
||||
const size = memory.matchSize ?? 2;
|
||||
memory.pairedCount[e.rank] += size;
|
||||
// The pairer no longer holds those cards.
|
||||
memory.beliefs[e.seat][e.rank] = Math.max(0, memory.beliefs[e.seat][e.rank] - size);
|
||||
} else if (e.kind === 'refill') {
|
||||
// Refills draw from the pool; we don't know specific ranks. No update.
|
||||
} else if (e.kind === 'sitout') {
|
||||
|
|
@ -67,6 +83,22 @@ export function observeLog(memory, state, selfSeat) {
|
|||
for (const r of RANKS) memory.beliefs[selfSeat][r] = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Players `seat` has already caught cards from during its current turn (a
|
||||
* catch keeps the turn going). Read back through the log until another
|
||||
* player's ask — that's where this turn began.
|
||||
*/
|
||||
export function caughtFromThisTurn(state, seat) {
|
||||
const out = new Set();
|
||||
for (let i = state.log.length - 1; i >= 0; i--) {
|
||||
const e = state.log[i];
|
||||
if (e.kind !== 'ask') continue;
|
||||
if (e.askerSeat !== seat) break;
|
||||
if (e.result === 'catch') out.add(e.targetSeat);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick (targetSeat, rank) for the AI. Falls back gracefully if memory is
|
||||
* empty (e.g. very first turn).
|
||||
|
|
@ -77,6 +109,17 @@ export function chooseAction(state, seat, memory, exclude = new Set()) {
|
|||
|
||||
// Our distinct ranks (we must hold at least one).
|
||||
const myRanks = [...new Set(me.hand.map((c) => c.rank))];
|
||||
const rand = memory.rng ?? Math.random;
|
||||
// Don't go back to a player we've already taken cards from this turn — unless
|
||||
// there's nobody else left to ask (always the case heads-up).
|
||||
const open = state.players.filter((p) => p.seat !== seat && !p.sittingOut && p.hand.length > 0).map((p) => p.seat);
|
||||
const caught = caughtFromThisTurn(state, seat);
|
||||
const fresh = open.filter((t) => !caught.has(t));
|
||||
const allowed = new Set(fresh.length ? fresh : open);
|
||||
if (rand() < RANDOM_ASK[memory.skill ?? 5]) {
|
||||
const targets = [...allowed];
|
||||
if (targets.length) return { targetSeat: targets[Math.floor(rand() * targets.length)], rank: myRanks[Math.floor(rand() * myRanks.length)] };
|
||||
}
|
||||
|
||||
// Cards-per-opponent for statistical weighting.
|
||||
const handSizes = state.players.map((p) => p.hand.length);
|
||||
|
|
@ -94,12 +137,16 @@ export function chooseAction(state, seat, memory, exclude = new Set()) {
|
|||
if (target === seat) continue;
|
||||
const opp = state.players[target];
|
||||
if (opp.sittingOut || opp.hand.length === 0) continue;
|
||||
if (!allowed.has(target)) continue;
|
||||
if (exclude.has(`${target}:${rank}`)) continue;
|
||||
|
||||
let score = 0;
|
||||
const belief = memory.beliefs[target][rank] || 0;
|
||||
// Strong signal: they've shown they hold this rank.
|
||||
if (belief > 0) score += 3 + Math.min(belief, 3);
|
||||
// …and they just told us "go fish" for it: don't ask straight back.
|
||||
const said = memory.turnRecorded[target][rank];
|
||||
if (belief === 0 && said != null && state.turnCount - said < 3) score -= 3;
|
||||
|
||||
// We pair on a catch, so more in-hand = bigger payoff.
|
||||
score += myCount;
|
||||
|
|
@ -115,7 +162,7 @@ export function chooseAction(state, seat, memory, exclude = new Set()) {
|
|||
score += (opp.hand.length - avgHand) * 0.3;
|
||||
|
||||
// Long-tail random tiebreak.
|
||||
score += Math.random() * 0.1;
|
||||
score += rand() * 0.1;
|
||||
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
|
|
@ -132,7 +179,7 @@ export function chooseAction(state, seat, memory, exclude = new Set()) {
|
|||
if (t === seat) continue;
|
||||
if (exclude.has(`${t}:${rank}`)) continue;
|
||||
const opp = state.players[t];
|
||||
if (!opp.sittingOut && opp.hand.length > 0) {
|
||||
if (!opp.sittingOut && opp.hand.length > 0 && allowed.has(t)) {
|
||||
return { targetSeat: t, rank };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,234 @@
|
|||
// Go Fish art — the lakeside dock at dusk, baked once per page load. The card
|
||||
// FACES are the owner's own illustrated sheet ('gofish-cards', one fish per
|
||||
// rank, loaded from assets/images/gofish-cards.png via the asset manifest);
|
||||
// this module only adds a matching back and the room.
|
||||
//
|
||||
// gofish-back dusky blue back with waves and a fish
|
||||
// gofish-table-<n> sunset sky + lake, a plank dock with a pond cut into the
|
||||
// middle, faint book rows in front of each player
|
||||
|
||||
import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js';
|
||||
import {
|
||||
bakeRoom, canvas, rr, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, CARD_TEX,
|
||||
} from '../../ui/cardtable/TableArt.js';
|
||||
import { W, H } from '../../ui/cardtable/TableGeometry.js';
|
||||
import { T, layoutFor, pondOutline, bookRowRect, SEAT_HEX } from './GoFishTable.js';
|
||||
|
||||
const CW = CARD_TEX.W, CH = CARD_TEX.H;
|
||||
|
||||
function fishShape(ctx, x, y, s, color) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.scale(s, s);
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(0, 0, 34, 20, 0, 0, Math.PI * 2);
|
||||
ctx.moveTo(30, 0);
|
||||
ctx.lineTo(56, -18);
|
||||
ctx.lineTo(52, 0);
|
||||
ctx.lineTo(56, 18);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = color;
|
||||
ctx.fill();
|
||||
ctx.beginPath(); ctx.arc(-18, -5, 4, 0, Math.PI * 2); ctx.fillStyle = '#0b1a2e'; ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function bakeBack(scene) {
|
||||
const c = canvas(CW, CH);
|
||||
const ctx = c.getContext('2d');
|
||||
rr(ctx, 2, 2, CW - 4, CH - 4, 16);
|
||||
ctx.fillStyle = '#f3ecdc';
|
||||
ctx.fill();
|
||||
ctx.save();
|
||||
rr(ctx, 12, 12, CW - 24, CH - 24, 12);
|
||||
ctx.clip();
|
||||
const g = ctx.createLinearGradient(0, 0, 0, CH);
|
||||
g.addColorStop(0, '#2a4f7a'); g.addColorStop(1, '#122a48');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, CW, CH);
|
||||
ctx.strokeStyle = 'rgba(160,210,240,0.35)';
|
||||
ctx.lineWidth = 4;
|
||||
for (let y = 20; y < CH; y += 22) {
|
||||
ctx.beginPath();
|
||||
for (let x = 0; x <= CW; x += 8) ctx.lineTo(x, y + Math.sin(x / 14 + y) * 4);
|
||||
ctx.stroke();
|
||||
}
|
||||
fishShape(ctx, CW / 2 - 8, CH / 2, 1.3, '#f0b23a');
|
||||
ctx.restore();
|
||||
rr(ctx, 2, 2, CW - 4, CH - 4, 16);
|
||||
ctx.lineWidth = 2.5;
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.55)';
|
||||
ctx.stroke();
|
||||
scene.textures.addCanvas('gofish-back', c);
|
||||
}
|
||||
|
||||
// ── The dock at dusk ─────────────────────────────────────────────────────────
|
||||
const HORIZON = 150;
|
||||
|
||||
function sky(ctx) {
|
||||
const g = ctx.createLinearGradient(0, 0, 0, HORIZON);
|
||||
g.addColorStop(0, '#2b1f4f');
|
||||
g.addColorStop(0.55, '#a0456a');
|
||||
g.addColorStop(1, '#f39a4a');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, W, HORIZON);
|
||||
// the low sun, half-set behind the far shore
|
||||
const sun = ctx.createRadialGradient(1320, HORIZON, 4, 1320, HORIZON, 160);
|
||||
sun.addColorStop(0, 'rgba(255,230,160,0.95)');
|
||||
sun.addColorStop(0.25, 'rgba(255,190,110,0.6)');
|
||||
sun.addColorStop(1, 'rgba(255,150,80,0)');
|
||||
ctx.fillStyle = sun;
|
||||
ctx.fillRect(0, 0, W, HORIZON);
|
||||
// tree line on the far shore
|
||||
ctx.fillStyle = '#1c1630';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, HORIZON);
|
||||
for (let x = 0; x <= W; x += 14) {
|
||||
const h = 14 + Math.abs(Math.sin(x * 0.013) * 22) + Math.abs(Math.sin(x * 0.051)) * 12 + ((x * 7919) % 11);
|
||||
ctx.lineTo(x, HORIZON - h);
|
||||
}
|
||||
ctx.lineTo(W, HORIZON);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
// lake below
|
||||
const lake = ctx.createLinearGradient(0, HORIZON, 0, H);
|
||||
lake.addColorStop(0, '#5a3a5e');
|
||||
lake.addColorStop(0.2, '#24324e');
|
||||
lake.addColorStop(1, '#0b1424');
|
||||
ctx.fillStyle = lake;
|
||||
ctx.fillRect(0, HORIZON, W, H - HORIZON);
|
||||
// the sun's path on the water
|
||||
for (let y = HORIZON + 4; y < H; y += 9) {
|
||||
const w = 30 + (y - HORIZON) * 0.25;
|
||||
ctx.fillStyle = `rgba(255,190,120,${Math.max(0, 0.5 - (y - HORIZON) / 900)})`;
|
||||
ctx.fillRect(1320 - w / 2 + Math.sin(y) * 10, y, w, 2);
|
||||
}
|
||||
}
|
||||
|
||||
const PLANK = ['#7a5a3a', '#6e5034', '#83633f', '#6a4a2e', '#765638'];
|
||||
|
||||
function front(ctx, Tb) {
|
||||
frontBands(ctx, Tb, ['#4a3420', '#3e2c1a', '#332414', '#281c10', '#1e150c'], { grooves: [0.5] });
|
||||
}
|
||||
|
||||
function rim(ctx, Tb) {
|
||||
rimBand(ctx, Tb, { base: '#5a4028', dark: '#2a1c10', light: '#9a7448', grain: ['#1a1008', '#b8905a'], gloss: 1.2 });
|
||||
}
|
||||
|
||||
function planks(ctx, Tb) {
|
||||
// boards run left-right; each band is a row of boards with staggered joints
|
||||
const rows = 26;
|
||||
for (let r = 0; r < rows; r++) {
|
||||
const v0 = -0.02 + (r / rows) * 1.04, v1 = v0 + 1.04 / rows;
|
||||
let u = -1.1 + ((r * 0.37) % 0.4);
|
||||
let k = r * 3;
|
||||
while (u < 1.1) {
|
||||
const len = 0.42 + ((k * 0.61) % 0.3);
|
||||
const a = Tb.P.project(u, v0), b = Tb.P.project(u + len, v0), c = Tb.P.project(u + len, v1), d = Tb.P.project(u, v1);
|
||||
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.lineTo(c.x, c.y); ctx.lineTo(d.x, d.y); ctx.closePath();
|
||||
ctx.fillStyle = PLANK[k % PLANK.length];
|
||||
ctx.fill();
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.strokeStyle = 'rgba(20,12,6,0.65)';
|
||||
ctx.stroke();
|
||||
// a nail at each end
|
||||
for (const p of [Tb.P.project(u + 0.02, (v0 + v1) / 2), Tb.P.project(u + len - 0.02, (v0 + v1) / 2)]) {
|
||||
ctx.beginPath(); ctx.arc(p.x, p.y, 1.8 * p.s, 0, Math.PI * 2); ctx.fillStyle = 'rgba(30,30,34,0.7)'; ctx.fill();
|
||||
}
|
||||
u += len;
|
||||
k++;
|
||||
}
|
||||
}
|
||||
// weathering + grain
|
||||
ctx.fillStyle = noisePattern(ctx, 200, 34);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.globalAlpha = 0.12;
|
||||
for (let i = 0; i < 260; i++) {
|
||||
const y = Math.random() * H, x = Math.random() * W;
|
||||
ctx.fillStyle = Math.random() < 0.5 ? '#1a0e06' : '#c8a070';
|
||||
ctx.fillRect(x, y, 40 + Math.random() * 120, 1);
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
// dusk light: warm from the sun (upper right), cool shadow elsewhere
|
||||
lampPool(ctx, Tb, { color: '255,180,120', alpha: 0.22, vignette: 0.6, at: { u: 0.35, v: 0.2 } });
|
||||
ctx.fillStyle = 'rgba(30,30,80,0.12)';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
rimShadow(ctx, Tb, 0.3);
|
||||
}
|
||||
|
||||
function pond(ctx) {
|
||||
const outer = pondOutline(1.07);
|
||||
const shore = pondOutline(1.0);
|
||||
// log rim around the hole
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 4;
|
||||
poly(ctx, outer); ctx.fillStyle = '#4a3220'; ctx.fill();
|
||||
ctx.restore();
|
||||
for (let i = 0; i < 6; i++) {
|
||||
poly(ctx, pondOutline(1.07 - i * 0.012));
|
||||
ctx.lineWidth = 3;
|
||||
ctx.strokeStyle = mix('#2a1a0c', '#8a6238', Math.sin((i / 5) * Math.PI));
|
||||
ctx.stroke();
|
||||
}
|
||||
// water
|
||||
ctx.save();
|
||||
poly(ctx, shore);
|
||||
ctx.clip();
|
||||
const c = T.P.project(0, 0.44);
|
||||
const g = ctx.createRadialGradient(c.x, c.y, 10, c.x, c.y, 360);
|
||||
g.addColorStop(0, '#2f6a86');
|
||||
g.addColorStop(0.7, '#1c4560');
|
||||
g.addColorStop(1, '#0e2638');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.strokeStyle = 'rgba(180,225,245,0.18)';
|
||||
ctx.lineWidth = 2;
|
||||
for (let i = 1; i <= 6; i++) {
|
||||
poly(ctx, pondOutline(i / 7));
|
||||
ctx.stroke();
|
||||
}
|
||||
// sunset glints
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const x = c.x - 300 + Math.random() * 600, y = c.y - 110 + Math.random() * 220;
|
||||
ctx.fillStyle = `rgba(255,${180 + Math.floor(Math.random() * 60)},140,${0.12 + Math.random() * 0.2})`;
|
||||
ctx.fillRect(x, y, 6 + Math.random() * 14, 1.5);
|
||||
}
|
||||
ctx.restore();
|
||||
poly(ctx, shore);
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.6)';
|
||||
ctx.stroke();
|
||||
ctx.font = '15px "Julius Sans One", sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = 'rgba(242,214,160,0.55)';
|
||||
ctx.fillText('THE POND', c.x, pondOutline(1.07)[48].y - 18);
|
||||
}
|
||||
|
||||
function bookRows(ctx, playerCount) {
|
||||
const L = layoutFor(playerCount);
|
||||
for (const st of L.seats) {
|
||||
const r = bookRowRect(L, st.seat, 13);
|
||||
rr(ctx, r.x0 - 6, r.y0 - 4, r.x1 - r.x0 + 12, r.y1 - r.y0 + 8, 10);
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.14)';
|
||||
ctx.fill();
|
||||
ctx.setLineDash([8, 6]);
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = SEAT_HEX[st.seat];
|
||||
ctx.globalAlpha = 0.45;
|
||||
ctx.stroke();
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareGoFishArt(scene, playerCount) {
|
||||
await prepareCasinoArt(scene);
|
||||
if (!scene.textures.exists('gofish-back')) bakeBack(scene);
|
||||
return bakeRoom(scene, `gofish-table-${playerCount}`, T, {
|
||||
wall: sky, front, rim, top: planks,
|
||||
onTop: (ctx) => { pond(ctx); bookRows(ctx, playerCount); },
|
||||
});
|
||||
}
|
||||
|
||||
export { fishShape };
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -64,6 +64,7 @@ export function cloneState(state) {
|
|||
hand: p.hand.map(cloneCard),
|
||||
pairs: p.pairs,
|
||||
pairedRanks: p.pairedRanks.slice(),
|
||||
books: (p.books ?? []).map((b) => b.map(cloneCard)),
|
||||
sittingOut: p.sittingOut,
|
||||
})),
|
||||
pool: state.pool.map(cloneCard),
|
||||
|
|
@ -91,6 +92,7 @@ export function createInitialState({ playerCount = 4, matchSize = 4, seed } = {}
|
|||
hand: deck.splice(0, HAND_DEAL),
|
||||
pairs: 0,
|
||||
pairedRanks: [],
|
||||
books: [],
|
||||
sittingOut: false,
|
||||
});
|
||||
}
|
||||
|
|
@ -266,6 +268,7 @@ function collectPairs(player, state) {
|
|||
player.hand = player.hand.filter((c) => !idsToRemove.has(c.id));
|
||||
player.pairs += 1;
|
||||
player.pairedRanks.push(foundRank);
|
||||
(player.books ??= []).push(group.map(cloneCard));
|
||||
collected += 1;
|
||||
if (state) state.log.push({ kind: 'pair', seat: player.seat, rank: foundRank });
|
||||
}
|
||||
|
|
@ -333,6 +336,11 @@ function checkGameOver(state) {
|
|||
}
|
||||
}
|
||||
|
||||
/** Every card in the game — hands, pool and books (for conservation checks). */
|
||||
export function countCards(state) {
|
||||
return state.pool.length + state.players.reduce((n, p) => n + p.hand.length + (p.books ?? []).reduce((m, b) => m + b.length, 0), 0);
|
||||
}
|
||||
|
||||
export function isGameOver(state) {
|
||||
return state.phase === 'gameOver';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,162 @@
|
|||
// Go Fish table layout — Phaser-free so tools/verifyGoFish.js can test it.
|
||||
//
|
||||
// A weathered lakeside dock at dusk on the shared card-table kit. The draw
|
||||
// pool is a POND cut into the middle of the boards: its cards float face down
|
||||
// in the water (scattered by card id, so they never jump around). Each
|
||||
// player's finished books stack in a row on the boards in front of them.
|
||||
//
|
||||
// 2 human · across 3 human · far corners 4 human · left · across · right
|
||||
// (logic seats clockwise from the human's left, as in every table game)
|
||||
|
||||
import { makeTable, CARD_W, CARD_H, fanPose, fanPoint, HUMAN_PLATE, PLATE } from '../../ui/cardtable/TableGeometry.js';
|
||||
|
||||
export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 };
|
||||
export const T = makeTable(VIEW, { shape: 'rect', corner: 0.12, feltK: 0.97, faceH: 40 });
|
||||
export const SQ = VIEW.squash;
|
||||
|
||||
export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c];
|
||||
export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c'];
|
||||
|
||||
const HUMAN_FAN = { x: 960, y: 994, rot: 0, k: 1, spread: 82, curve: 1.3, tilt: 0.034, q: 1, maxSpan: 880, maxDrop: 34, maxTilt: 0.2 };
|
||||
const opp = (x, y, rot, k = 0.55) => ({ x, y, rot, k, spread: 34, curve: 0.5, tilt: 0.03, q: 1, maxSpan: 420, maxDrop: 14, maxTilt: 0.16 });
|
||||
|
||||
// books: row start (u, v), direction along u, max row width (px)
|
||||
const HUMAN_BOOKS = { u: 0.02, v: 0.76, dir: 1, maxW: 540 };
|
||||
const SEATS = {
|
||||
2: [
|
||||
{ fan: HUMAN_FAN, plate: HUMAN_PLATE, books: HUMAN_BOOKS },
|
||||
{ fan: opp(960, 80, Math.PI), plate: { x: 1420, y: 86 }, books: { u: -0.04, v: 0.17, dir: -1, maxW: 440 } },
|
||||
],
|
||||
3: [
|
||||
{ fan: HUMAN_FAN, plate: HUMAN_PLATE, books: HUMAN_BOOKS },
|
||||
{ fan: opp(600, 82, Math.PI - 0.1), plate: { x: 190, y: 150 }, books: { u: -0.79, v: 0.25, dir: 1, maxW: 280 } },
|
||||
{ fan: opp(1320, 82, Math.PI + 0.1), plate: { x: 1730, y: 150 }, books: { u: 0.79, v: 0.25, dir: -1, maxW: 280 } },
|
||||
],
|
||||
4: [
|
||||
{ fan: HUMAN_FAN, plate: HUMAN_PLATE, books: HUMAN_BOOKS },
|
||||
{ fan: opp(84, 540, Math.PI / 2, 0.5), plate: { x: 190, y: 150 }, books: { u: -0.86, v: 0.66, dir: 1, maxW: 320 } },
|
||||
{ fan: opp(960, 80, Math.PI, 0.52), plate: { x: 1400, y: 86 }, books: { u: -0.04, v: 0.17, dir: -1, maxW: 420 } },
|
||||
{ fan: opp(1836, 540, -Math.PI / 2, 0.5), plate: { x: 1730, y: 150 }, books: { u: 0.86, v: 0.66, dir: -1, maxW: 320 } },
|
||||
],
|
||||
};
|
||||
|
||||
// The pond: an ellipse in table space.
|
||||
export const POND = { u: 0, v: 0.44, ru: 0.34, rv: 0.165 };
|
||||
export const POOL_K = 0.6;
|
||||
export const BOOK_K = 0.46;
|
||||
|
||||
const cache = new Map();
|
||||
export function layoutFor(playerCount) {
|
||||
if (cache.has(playerCount)) return cache.get(playerCount);
|
||||
const defs = SEATS[playerCount];
|
||||
if (!defs) throw new Error(`Go Fish layout supports 2..4 players, got ${playerCount}`);
|
||||
const L = { playerCount, seats: defs.map((d, seat) => ({ seat, ...d })) };
|
||||
cache.set(playerCount, L);
|
||||
return L;
|
||||
}
|
||||
|
||||
export const handPose = (L, seat, i, n, lift = 0) => fanPose(L.seats[seat].fan, i, n, lift);
|
||||
|
||||
// deterministic 0..1 values per card id
|
||||
function hash01(id, salt) {
|
||||
let h = Math.imul((id + 1) * 2654435761 + salt * 40503, 2246822507) >>> 0;
|
||||
h ^= h >>> 13; h = Math.imul(h, 3266489909) >>> 0; h ^= h >>> 16;
|
||||
return (h >>> 0) / 4294967296;
|
||||
}
|
||||
|
||||
/** Where a pool card floats in the pond (stable per card id). */
|
||||
export function poolPose(id) {
|
||||
const a = hash01(id, 1) * Math.PI * 2;
|
||||
const r = Math.sqrt(hash01(id, 2)) * 0.78;
|
||||
const u = POND.u + Math.cos(a) * r * POND.ru;
|
||||
const v = POND.v + Math.sin(a) * r * POND.rv;
|
||||
return T.flat(u, v, POOL_K, (hash01(id, 3) - 0.5) * 1.4);
|
||||
}
|
||||
|
||||
/** Points along the pond's shoreline (screen), for the art and checks. */
|
||||
export function pondOutline(k = 1, steps = 64) {
|
||||
const pts = [];
|
||||
for (let i = 0; i < steps; i++) {
|
||||
const a = (i / steps) * Math.PI * 2;
|
||||
pts.push(T.P.project(POND.u + Math.cos(a) * POND.ru * k, POND.v + Math.sin(a) * POND.rv * k));
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
export function inPond(pt) {
|
||||
const { u, v } = T.P.unproject(pt.x, pt.y);
|
||||
const du = (u - POND.u) / POND.ru, dv = (v - POND.v) / POND.rv;
|
||||
return du * du + dv * dv <= 1;
|
||||
}
|
||||
|
||||
/** Book i of n in a seat's row (each book is a squared-up stack). */
|
||||
export function bookPose(L, seat, i, n) {
|
||||
const b = L.seats[seat].books;
|
||||
const base = T.flat(b.u, b.v, BOOK_K);
|
||||
const natural = CARD_W * base.s + 10;
|
||||
const step = n <= 1 ? natural : Math.min(natural, (b.maxW - CARD_W * base.s) / (n - 1));
|
||||
return { ...base, x: base.x + b.dir * i * step, rot: ((i * 37) % 7 - 3) * 0.012 };
|
||||
}
|
||||
|
||||
/** Screen rect a seat's book row covers at its widest. */
|
||||
export function bookRowRect(L, seat, n = 13) {
|
||||
const a = bookPose(L, seat, 0, n), b = bookPose(L, seat, n - 1, n);
|
||||
const hw = (CARD_W / 2) * a.s + 4, hh = (CARD_H / 2) * a.s * SQ + 10;
|
||||
return { x0: Math.min(a.x, b.x) - hw, x1: Math.max(a.x, b.x) + hw, y0: a.y - hh, y1: a.y + hh };
|
||||
}
|
||||
|
||||
// Show spots: where an asker holds up the card they're asking about, and where
|
||||
// the player asked lays out what they hand over — between their hand and the
|
||||
// pond, clear of the book rows.
|
||||
const SHOW = {
|
||||
2: [{ x: 700, y: 775 }, { x: 1180, y: 230 }],
|
||||
3: [{ x: 700, y: 775 }, { x: 760, y: 205 }, { x: 1160, y: 205 }],
|
||||
4: [{ x: 700, y: 775 }, { x: 250, y: 450 }, { x: 1180, y: 230 }, { x: 1670, y: 450 }],
|
||||
};
|
||||
export const SHOW_K = 0.82;
|
||||
|
||||
/** Card i of n laid out at a seat's show spot (upright, readable). */
|
||||
export function showPose(L, seat, i = 0, n = 1) {
|
||||
const c = SHOW[L.playerCount][seat];
|
||||
const k = seat === 0 ? 0.86 : SHOW_K;
|
||||
const step = CARD_W * k * 0.55;
|
||||
return { x: c.x + (i - (n - 1) / 2) * step, y: c.y, rot: (i - (n - 1) / 2) * 0.06, s: k, q: 1 };
|
||||
}
|
||||
|
||||
export function handHome(L, seat) {
|
||||
const f = L.seats[seat].fan;
|
||||
const p = fanPoint(f, 0, -CARD_H * 0.95);
|
||||
return { ...p, rot: f.rot, k: f.k };
|
||||
}
|
||||
|
||||
export function handBadge(L, seat) {
|
||||
const f = L.seats[seat].fan;
|
||||
return fanPoint(f, -(f.maxSpan / 2 + CARD_W / 2 + 50), 0);
|
||||
}
|
||||
|
||||
/** Where a seat's speech bubble pops up. */
|
||||
export function bubbleAt(L, seat) {
|
||||
if (seat === 0) return { x: 960, y: 846 };
|
||||
const f = L.seats[seat].fan;
|
||||
return fanPoint(f, 0, -CARD_H * 1.55);
|
||||
}
|
||||
|
||||
/** The clickable region of an opponent (their hand fan) for asking. */
|
||||
export function seatTargetRect(L, seat, n = 7) {
|
||||
const f = L.seats[seat].fan;
|
||||
const pts = [];
|
||||
for (let i = 0; i < Math.max(1, n); i++) pts.push(fanPose(f, i, Math.max(1, n)));
|
||||
const xs = pts.map(p => p.x), ys = pts.map(p => p.y);
|
||||
const pad = 60;
|
||||
return { x0: Math.min(...xs) - pad, x1: Math.max(...xs) + pad, y0: Math.min(...ys) - pad, y1: Math.max(...ys) + pad };
|
||||
}
|
||||
|
||||
export function spotFor(L, seat) {
|
||||
const f = L.seats[seat].fan;
|
||||
if (seat === 0) return { x: f.x, y: 820, w: 1300, h: 420 };
|
||||
const c = fanPoint(f, 0, -CARD_H * 0.9);
|
||||
const side = Math.abs(Math.sin(f.rot)) > 0.7;
|
||||
return side ? { x: c.x, y: c.y, w: 420, h: 620 } : { x: c.x, y: c.y + 30, w: 640, h: 320 };
|
||||
}
|
||||
|
||||
export { PLATE };
|
||||
|
|
@ -1,13 +1,24 @@
|
|||
// Hearts AI — heuristic opponent. No Phaser imports.
|
||||
// Hearts AI — heuristic opponent scaled by skill (1..5). No Phaser imports.
|
||||
//
|
||||
// choosePass(state, seat) → array of 3 card ids to pass.
|
||||
// choosePlay(state, seat) → a single card id to play (always legal).
|
||||
// choosePass(state, seat, { skill, rng }) → array of 3 card ids to pass.
|
||||
// choosePlay(state, seat, { skill, rng }) → a single card id to play (always legal).
|
||||
//
|
||||
// The AI has no hidden-information memory; it plays a sound, defensive game:
|
||||
// shed dangerous cards in the pass, duck under tricks that carry points, and
|
||||
// dump high/dangerous cards when void in the led suit.
|
||||
// Skill:
|
||||
// 1-2 plays loosely: random-ish passes, sometimes a random legal card.
|
||||
// 3 sound defensive play: shed danger in the pass, duck under tricks
|
||||
// that carry points, dump high cards when void.
|
||||
// 4-5 remembers who is void in what and whether the Queen is gone, leads
|
||||
// low spades to flush her out, sheds high cards on safe last-to-play
|
||||
// tricks and breaks up a moon shot. 5 also avoids leading into voids.
|
||||
// (Measured over 2400 hands: skill 5 takes ~9% fewer points than skill 3.)
|
||||
|
||||
import { legalPlays, cardPoints, isQueenOfSpades } from './HeartsLogic.js';
|
||||
import {
|
||||
legalPlays, cardPoints, isQueenOfSpades, knownVoids, playedKeys, PLAYER_COUNT,
|
||||
} from './HeartsLogic.js';
|
||||
import { clampSkill } from '../../ui/cardtable/AITiming.js';
|
||||
|
||||
const RANDOM_PLAY = { 1: 0.35, 2: 0.15, 3: 0.05, 4: 0, 5: 0 };
|
||||
const RANDOM_PASS = { 1: 0.6, 2: 0.25, 3: 0, 4: 0, 5: 0 };
|
||||
|
||||
// How much we'd like to be rid of a card. Higher = more dangerous to keep.
|
||||
function danger(card) {
|
||||
|
|
@ -17,44 +28,61 @@ function danger(card) {
|
|||
return card.value;
|
||||
}
|
||||
|
||||
export function choosePass(state, seat) {
|
||||
export function choosePass(state, seat, opts = {}) {
|
||||
const skill = clampSkill(opts.skill);
|
||||
const rand = opts.rng ?? Math.random;
|
||||
const hand = state.players[seat].hand;
|
||||
|
||||
// Suit counts so we can reward voiding a short side suit.
|
||||
if (rand() < RANDOM_PASS[skill]) {
|
||||
const pool = hand.slice();
|
||||
for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
|
||||
return pool.slice(0, 3).map((c) => c.id);
|
||||
}
|
||||
const counts = { s: 0, h: 0, d: 0, c: 0 };
|
||||
for (const c of hand) counts[c.suit] += 1;
|
||||
|
||||
const scored = hand.map((c) => {
|
||||
let score = danger(c);
|
||||
// Encourage voiding short non-heart suits — being void buys flexibility.
|
||||
if (c.suit !== 'h' && !isQueenOfSpades(c) && counts[c.suit] <= 2) score += 40;
|
||||
if (skill === 2) score += rand() * 60;
|
||||
return { c, score };
|
||||
});
|
||||
|
||||
scored.sort((a, b) => b.score - a.score);
|
||||
return scored.slice(0, 3).map((s) => s.c.id);
|
||||
}
|
||||
|
||||
export function choosePlay(state, seat) {
|
||||
export function choosePlay(state, seat, opts = {}) {
|
||||
const skill = clampSkill(opts.skill);
|
||||
const rand = opts.rng ?? Math.random;
|
||||
const legal = legalPlays(state, seat);
|
||||
if (legal.length === 0) return null;
|
||||
if (legal.length === 1) return legal[0].id;
|
||||
if (rand() < RANDOM_PLAY[skill]) return legal[Math.floor(rand() * legal.length)].id;
|
||||
|
||||
const ctx = skill >= 4 ? context(state, seat) : null;
|
||||
const leading = state.trick.length === 0;
|
||||
if (leading) return chooseLead(state, seat, legal).id;
|
||||
|
||||
if (leading) return chooseLead(state, seat, legal, skill, ctx).id;
|
||||
const haveLead = state.players[seat].hand.some((c) => c.suit === state.leadSuit);
|
||||
if (!haveLead) return chooseSlough(legal).id;
|
||||
|
||||
return chooseFollow(state, legal).id;
|
||||
if (!haveLead) return chooseSlough(state, legal, skill, ctx).id;
|
||||
return chooseFollow(state, seat, legal, skill, ctx).id;
|
||||
}
|
||||
|
||||
// Leading a trick: lead low and safe; avoid leading spades while we still hold
|
||||
// the Queen (don't draw spades onto ourselves) and avoid hearts when possible.
|
||||
function chooseLead(state, seat, legal) {
|
||||
const holdsQueen = state.players[seat].hand.some(isQueenOfSpades);
|
||||
let pool = legal;
|
||||
// What a sharp player knows: voids, whether the Queen is still out, and
|
||||
// whether someone is running away with every point (a moon shot).
|
||||
function context(state, seat) {
|
||||
const played = playedKeys(state);
|
||||
const voids = knownVoids(state);
|
||||
const pts = state.players.map((p) => p.roundPoints);
|
||||
const totalPts = pts.reduce((a, b) => a + b, 0);
|
||||
let moonThreat = null;
|
||||
for (let s = 0; s < PLAYER_COUNT; s++) {
|
||||
if (s !== seat && pts[s] >= 6 && pts[s] === totalPts) moonThreat = s;
|
||||
}
|
||||
return { played, voids, queenOut: !played.has('Qs'), moonThreat };
|
||||
}
|
||||
|
||||
function chooseLead(state, seat, legal, skill, ctx) {
|
||||
const hand = state.players[seat].hand;
|
||||
const holdsQueen = hand.some(isQueenOfSpades);
|
||||
let pool = legal;
|
||||
if (holdsQueen) {
|
||||
const nonSpade = legal.filter((c) => c.suit !== 's');
|
||||
if (nonSpade.length > 0) pool = nonSpade;
|
||||
|
|
@ -62,28 +90,54 @@ function chooseLead(state, seat, legal) {
|
|||
const nonHeart = pool.filter((c) => c.suit !== 'h');
|
||||
if (nonHeart.length > 0) pool = nonHeart;
|
||||
|
||||
if (ctx) {
|
||||
// flush the Queen: lead a low spade when we don't hold her
|
||||
if (!holdsQueen && ctx.queenOut) {
|
||||
const lowSpades = legal.filter((c) => c.suit === 's' && c.value < 12);
|
||||
const highSpades = hand.filter((c) => c.suit === 's' && c.value > 12);
|
||||
if (lowSpades.length && (lowSpades.length >= highSpades.length)) return lowest(lowSpades);
|
||||
}
|
||||
// stay out of suits somebody has shown out of — they'd dump points on us
|
||||
if (skill >= 5) {
|
||||
const others = [1, 2, 3].map((d) => (seat + d) % PLAYER_COUNT);
|
||||
const safe = pool.filter((c) => !others.some((s) => ctx.voids[s].has(c.suit)));
|
||||
if (safe.length) pool = safe;
|
||||
}
|
||||
}
|
||||
return lowest(pool);
|
||||
}
|
||||
|
||||
// Void in the led suit — discard the most dangerous card we can.
|
||||
function chooseSlough(legal) {
|
||||
function chooseSlough(state, legal, skill, ctx) {
|
||||
// breaking a moon shot: don't feed the runaway player any more points
|
||||
if (ctx && ctx.moonThreat != null && trickWinner(state)?.seat === ctx.moonThreat) {
|
||||
const clean = legal.filter((c) => cardPoints(c) === 0);
|
||||
if (clean.length) return highest(clean);
|
||||
}
|
||||
let best = legal[0];
|
||||
let bestDanger = -Infinity;
|
||||
for (const c of legal) {
|
||||
const d = danger(c);
|
||||
let d = danger(c);
|
||||
// with the Queen gone, A♠ / K♠ are harmless — shed high hearts first
|
||||
if (ctx && !ctx.queenOut && c.suit === 's' && c.value > 12) d = c.value;
|
||||
if (d > bestDanger) { bestDanger = d; best = c; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Following in-suit: try to stay under the current winner; otherwise win as
|
||||
// cheaply as possible.
|
||||
function chooseFollow(state, legal) {
|
||||
const winning = currentWinningCard(state);
|
||||
const under = legal.filter((c) => c.value < winning.value);
|
||||
function chooseFollow(state, seat, legal, skill, ctx) {
|
||||
const win = trickWinner(state);
|
||||
const winning = win.card;
|
||||
const trickPts = state.trick.reduce((s, t) => s + cardPoints(t.card), 0);
|
||||
const last = state.trick.length === PLAYER_COUNT - 1;
|
||||
|
||||
// stop a moon shot: take a point trick away from the runaway player
|
||||
if (ctx && ctx.moonThreat != null && win.seat === ctx.moonThreat && trickPts > 0) {
|
||||
const over = legal.filter((c) => c.value > winning.value && !isQueenOfSpades(c));
|
||||
if (over.length) return lowest(over);
|
||||
}
|
||||
|
||||
const under = legal.filter((c) => c.value < winning.value);
|
||||
if (under.length > 0) {
|
||||
// We can avoid taking the lead — dump our highest/most dangerous safe card.
|
||||
let best = under[0];
|
||||
let bestDanger = -Infinity;
|
||||
for (const c of under) {
|
||||
|
|
@ -92,20 +146,19 @@ function chooseFollow(state, legal) {
|
|||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Every legal card beats the current winner — we'll likely take it. Spend
|
||||
// the cheapest card (and never volunteer the Queen if we can avoid it).
|
||||
const nonQueen = legal.filter((c) => !isQueenOfSpades(c));
|
||||
return lowest(nonQueen.length > 0 ? nonQueen : legal);
|
||||
const pool = nonQueen.length > 0 ? nonQueen : legal;
|
||||
// last to play on a clean trick: we take it anyway, so shed our highest card
|
||||
if (ctx && last && trickPts === 0) return highest(pool);
|
||||
return lowest(pool);
|
||||
}
|
||||
|
||||
function currentWinningCard(state) {
|
||||
function trickWinner(state) {
|
||||
if (!state.trick.length) return null;
|
||||
const lead = state.leadSuit;
|
||||
let winner = state.trick[0].card;
|
||||
for (const t of state.trick) {
|
||||
if (t.card.suit === lead && t.card.value > winner.value) winner = t.card;
|
||||
}
|
||||
return winner;
|
||||
let w = state.trick[0];
|
||||
for (const t of state.trick) if (t.card.suit === lead && t.card.value > w.card.value) w = t;
|
||||
return w;
|
||||
}
|
||||
|
||||
function lowest(cards) {
|
||||
|
|
@ -113,3 +166,13 @@ function lowest(cards) {
|
|||
for (const c of cards) if (c.value < best.value) best = c;
|
||||
return best;
|
||||
}
|
||||
|
||||
function highest(cards) {
|
||||
let best = cards[0];
|
||||
for (const c of cards) if (c.value > best.value) best = c;
|
||||
return best;
|
||||
}
|
||||
|
||||
/** What a sharp player would do — the human's hints. */
|
||||
export function suggestPass(state, seat) { return choosePass(state, seat, { skill: 5, rng: () => 0.5 }); }
|
||||
export function suggestPlay(state, seat) { return choosePlay(state, seat, { skill: 5, rng: () => 0.5 }); }
|
||||
|
|
|
|||
|
|
@ -0,0 +1,177 @@
|
|||
// Hearts art — the den, baked once per page load. Cards are the shared casino
|
||||
// deck ('casino-cards' atlas, keyed 'As', 'Qs', …).
|
||||
//
|
||||
// hearts-table bookshelves + fireplace glow, a walnut card table with brass
|
||||
// studs and an oxblood leather top tooled with a gold border,
|
||||
// faint trick spots and won-card areas
|
||||
// hearts-heart a big red heart (cracks in two when hearts are broken)
|
||||
|
||||
import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js';
|
||||
import {
|
||||
bakeRoom, canvas, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, pileSpot, ring,
|
||||
} from '../../ui/cardtable/TableArt.js';
|
||||
import { W, H } from '../../ui/cardtable/TableGeometry.js';
|
||||
import { T, trickPose, tricksPose, pointPose, SEAT_HEX } from './HeartsTable.js';
|
||||
|
||||
function wall(ctx) {
|
||||
ctx.fillStyle = '#1e120b';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
// bookshelves: rows of spines
|
||||
const shelfH = 120;
|
||||
let seed = 7;
|
||||
const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
|
||||
const spines = ['#6b1f1f', '#2f4a2a', '#1f3354', '#7a5a22', '#4a2a14', '#5a2a4a', '#8a7a52', '#2a2a2a'];
|
||||
for (let y = 0; y < H; y += shelfH) {
|
||||
let x = 0;
|
||||
while (x < W) {
|
||||
const w = 14 + Math.floor(rnd() * 22);
|
||||
const h = shelfH - 18 - Math.floor(rnd() * 26);
|
||||
const col = spines[Math.floor(rnd() * spines.length)];
|
||||
ctx.fillStyle = col;
|
||||
ctx.fillRect(x, y + shelfH - 12 - h, w - 2, h);
|
||||
ctx.fillStyle = 'rgba(255,220,150,0.18)';
|
||||
ctx.fillRect(x + 3, y + shelfH - 12 - h + 10, w - 8, 3);
|
||||
ctx.fillRect(x + 3, y + shelfH - 30, w - 8, 2);
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.35)';
|
||||
ctx.fillRect(x + w - 5, y + shelfH - 12 - h, 3, h);
|
||||
x += w + (rnd() < 0.08 ? 30 : 0);
|
||||
}
|
||||
// the shelf board
|
||||
const g = ctx.createLinearGradient(0, y + shelfH - 12, 0, y + shelfH);
|
||||
g.addColorStop(0, '#5a3418'); g.addColorStop(1, '#2a160a');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, y + shelfH - 12, W, 12);
|
||||
}
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 18);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
// the room is dark; the fire (left) and a lamp (centre) light it
|
||||
ctx.fillStyle = 'rgba(10,5,2,0.55)';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
const fire = ctx.createRadialGradient(-80, 760, 40, -80, 760, 1300);
|
||||
fire.addColorStop(0, 'rgba(255,140,50,0.55)');
|
||||
fire.addColorStop(0.4, 'rgba(255,110,40,0.16)');
|
||||
fire.addColorStop(1, 'rgba(255,110,40,0)');
|
||||
ctx.fillStyle = fire;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
const lamp = ctx.createRadialGradient(W / 2, 90, 30, W / 2, 300, 1000);
|
||||
lamp.addColorStop(0, 'rgba(255,214,150,0.22)');
|
||||
lamp.addColorStop(1, 'rgba(255,214,150,0)');
|
||||
ctx.fillStyle = lamp;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
}
|
||||
|
||||
function front(ctx, Tb) {
|
||||
frontBands(ctx, Tb, ['#6b4024', '#56321a', '#432612', '#341c0c', '#26140a'], { grooves: [0.4, 0.75] });
|
||||
}
|
||||
|
||||
function rim(ctx, Tb) {
|
||||
rimBand(ctx, Tb, { base: '#5a3519', dark: '#24130a', light: '#a8692f', grain: ['#1a0d05', '#d9a066'], gloss: 1.5 });
|
||||
// brass studs just outside the leather
|
||||
const pts = Tb.outline(Tb.feltK + 0.012, 60);
|
||||
let acc = 0;
|
||||
for (let i = 1; i < pts.length; i++) {
|
||||
const a = pts[i - 1], b = pts[i];
|
||||
acc += Math.hypot(b.x - a.x, b.y - a.y);
|
||||
if (acc < 26 * b.s) continue;
|
||||
acc = 0;
|
||||
const r = 3.6 * b.s;
|
||||
const g = ctx.createRadialGradient(b.x - r * 0.35, b.y - r * 0.35, 0.5, b.x, b.y, r);
|
||||
g.addColorStop(0, '#fff2b8'); g.addColorStop(0.5, '#d9a84a'); g.addColorStop(1, '#6a4a12');
|
||||
ctx.beginPath(); ctx.arc(b.x, b.y, r, 0, Math.PI * 2); ctx.fillStyle = g; ctx.fill();
|
||||
}
|
||||
}
|
||||
|
||||
function leather(ctx, Tb) {
|
||||
ctx.fillStyle = '#4a1414';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.fillStyle = noisePattern(ctx, 220, 30);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
// leather grain: faint mottling
|
||||
for (let i = 0; i < 900; i++) {
|
||||
const x = Math.random() * W, y = Math.random() * H;
|
||||
ctx.fillStyle = Math.random() < 0.5 ? 'rgba(0,0,0,0.06)' : 'rgba(255,200,170,0.04)';
|
||||
ctx.beginPath(); ctx.ellipse(x, y, 6 + Math.random() * 18, 3 + Math.random() * 8, Math.random() * 3, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
// tooled gold border, two lines
|
||||
ring(ctx, Tb, Tb.feltK * 0.94, 2.5, 'rgba(217,168,74,0.55)');
|
||||
ring(ctx, Tb, Tb.feltK * 0.925, 1.2, 'rgba(217,168,74,0.4)');
|
||||
lampPool(ctx, Tb, { color: '255,214,160', alpha: 0.26, vignette: 0.55, at: { u: 0, v: 0.46 } });
|
||||
// fire warms the left side of the table
|
||||
const f = Tb.P.project(-1, 0.6);
|
||||
const fire = ctx.createRadialGradient(f.x, f.y, 20, f.x, f.y, 900);
|
||||
fire.addColorStop(0, 'rgba(255,130,50,0.22)');
|
||||
fire.addColorStop(1, 'rgba(255,130,50,0)');
|
||||
ctx.fillStyle = fire;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
rimShadow(ctx, Tb, 0.42);
|
||||
}
|
||||
|
||||
function marks(ctx) {
|
||||
// faint card spots where tricks land and where won cards collect
|
||||
for (let s = 0; s < 4; s++) {
|
||||
pileSpot(ctx, trickPose(s), '', { color: '217,168,74', alpha: 0.22 });
|
||||
pileSpot(ctx, tricksPose(s), '', { color: SEAT_HEX[s].replace('#', '').match(/../g).map(h => parseInt(h, 16)).join(','), alpha: 0.3 });
|
||||
const p = pointPose(s, 0);
|
||||
ctx.font = '13px "Julius Sans One", sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = 'rgba(217,168,74,0.4)';
|
||||
ctx.fillText('POINTS', p.x + (s === 3 ? -40 : 40), p.y - 36 * (p.s / 0.4));
|
||||
}
|
||||
// a small tooled heart in the middle of the table
|
||||
const c = T.P.project(0, 0.45);
|
||||
ctx.save();
|
||||
ctx.translate(c.x, c.y);
|
||||
ctx.scale(1, 0.9);
|
||||
heartPath(ctx, 0, 0, 34);
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = 'rgba(217,168,74,0.35)';
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
export function heartPath(ctx, x, y, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y + r * 0.9);
|
||||
ctx.bezierCurveTo(x - r * 1.4, y + r * 0.1, x - r * 0.9, y - r * 1.0, x, y - r * 0.35);
|
||||
ctx.bezierCurveTo(x + r * 0.9, y - r * 1.0, x + r * 1.4, y + r * 0.1, x, y + r * 0.9);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
function bakeHeart(scene) {
|
||||
const S = 200;
|
||||
for (const [key, clip] of [['hearts-heart', null], ['hearts-heart-l', 'l'], ['hearts-heart-r', 'r']]) {
|
||||
const c = canvas(S, S);
|
||||
const ctx = c.getContext('2d');
|
||||
ctx.save();
|
||||
if (clip) {
|
||||
// a jagged crack down the middle
|
||||
ctx.beginPath();
|
||||
const zig = [[100, 10], [88, 50], [108, 85], [90, 120], [106, 150], [96, 196]];
|
||||
if (clip === 'l') { ctx.moveTo(0, 0); zig.forEach(([x, y]) => ctx.lineTo(x, y)); ctx.lineTo(0, S); }
|
||||
else { ctx.moveTo(S, 0); zig.forEach(([x, y]) => ctx.lineTo(x, y)); ctx.lineTo(S, S); }
|
||||
ctx.closePath();
|
||||
ctx.clip();
|
||||
}
|
||||
heartPath(ctx, S / 2, S / 2 + 6, 70);
|
||||
const g = ctx.createLinearGradient(40, 30, 160, 170);
|
||||
g.addColorStop(0, '#ff6a6a'); g.addColorStop(1, '#a8101e');
|
||||
ctx.fillStyle = g;
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 12;
|
||||
ctx.fill();
|
||||
ctx.shadowColor = 'transparent';
|
||||
ctx.lineWidth = 5;
|
||||
ctx.strokeStyle = '#5a0810';
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
scene.textures.addCanvas(key, c);
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareHeartsArt(scene) {
|
||||
await prepareCasinoArt(scene);
|
||||
if (!scene.textures.exists('hearts-heart')) bakeHeart(scene);
|
||||
return bakeRoom(scene, 'hearts-table', T, { wall, front, rim, top: leather, onTop: marks });
|
||||
}
|
||||
|
||||
export { mix, poly };
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -14,7 +14,11 @@
|
|||
// - Scoring: each heart = 1 pt, Q♠ = 13 pts (26 per hand).
|
||||
// - Shooting the moon: if one player takes all 26 points, they score 0 and
|
||||
// every other player gets +26.
|
||||
// - Match runs until any player's total reaches 100; lowest total wins.
|
||||
// - Match runs until any player's total reaches the target (default 100);
|
||||
// lowest total wins.
|
||||
//
|
||||
// Options (createInitialState): target (50 / 100), moonMode 'add' (everyone
|
||||
// else +26, the classic) or 'subtract' (the shooter −26 instead).
|
||||
|
||||
import { SUITS, RANKS, Card } from '../cards/Deck.js';
|
||||
|
||||
|
|
@ -103,6 +107,9 @@ export function cloneState(state) {
|
|||
winnerSeats: state.winnerSeats.slice(),
|
||||
seed: state.seed,
|
||||
log: state.log.map((e) => ({ ...e })),
|
||||
target: state.target,
|
||||
moonMode: state.moonMode,
|
||||
_rand: state._rand,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -133,6 +140,7 @@ function dealHand(state, rand) {
|
|||
state.lastTrick = null;
|
||||
state.handScores = null;
|
||||
state.moonShooter = null;
|
||||
state.log.push({ kind: 'deal', hand: state.handNumber, direction: state.passDirection });
|
||||
|
||||
if (state.passDirection === 'hold') {
|
||||
// No passing this hand — go straight to play.
|
||||
|
|
@ -144,7 +152,7 @@ function dealHand(state, rand) {
|
|||
}
|
||||
}
|
||||
|
||||
export function createInitialState({ seed } = {}) {
|
||||
export function createInitialState({ seed, target = GAME_OVER_SCORE, moonMode = 'add' } = {}) {
|
||||
const rand = seed === undefined ? Math.random : rng(seed);
|
||||
const players = [];
|
||||
for (let i = 0; i < PLAYER_COUNT; i++) {
|
||||
|
|
@ -169,6 +177,8 @@ export function createInitialState({ seed } = {}) {
|
|||
seed: seed ?? null,
|
||||
log: [],
|
||||
_rand: rand,
|
||||
target,
|
||||
moonMode,
|
||||
};
|
||||
dealHand(state, rand);
|
||||
return state;
|
||||
|
|
@ -285,8 +295,12 @@ export function playCard(state, cardId) {
|
|||
|
||||
if (next.trick.length === 0) next.leadSuit = card.suit;
|
||||
next.trick.push({ seat, card });
|
||||
if (card.suit === 'h') next.heartsBroken = true;
|
||||
if (card.suit === 'h' && !next.heartsBroken) {
|
||||
next.heartsBroken = true;
|
||||
next.log.push({ kind: 'heartsBroken', seat });
|
||||
}
|
||||
next.log.push({ kind: 'play', seat, card: { rank: card.rank, suit: card.suit }, leadSuit: next.leadSuit });
|
||||
if (isQueenOfSpades(card)) next.log.push({ kind: 'queen', seat });
|
||||
|
||||
if (next.trick.length < PLAYER_COUNT) {
|
||||
next.currentPlayer = (seat + 1) % PLAYER_COUNT;
|
||||
|
|
@ -335,10 +349,12 @@ function scoreHand(state) {
|
|||
|
||||
const applied = roundPoints.slice();
|
||||
if (shooter !== -1) {
|
||||
// Shoot the moon: shooter scores 0, everyone else +26.
|
||||
// Shoot the moon: shooter scores 0 and everyone else +26 — or, with the
|
||||
// 'subtract' option, the shooter −26 and everyone else 0.
|
||||
state.moonShooter = shooter;
|
||||
for (let seat = 0; seat < PLAYER_COUNT; seat++) {
|
||||
applied[seat] = seat === shooter ? 0 : MAX_POINTS;
|
||||
if (state.moonMode === 'subtract') applied[seat] = seat === shooter ? -MAX_POINTS : 0;
|
||||
else applied[seat] = seat === shooter ? 0 : MAX_POINTS;
|
||||
}
|
||||
} else {
|
||||
state.moonShooter = null;
|
||||
|
|
@ -350,7 +366,7 @@ function scoreHand(state) {
|
|||
state.handScores = applied;
|
||||
state.log.push({ kind: 'handScored', applied, shooter });
|
||||
|
||||
const reached = state.players.some((p) => p.totalScore >= GAME_OVER_SCORE);
|
||||
const reached = state.players.some((p) => p.totalScore >= (state.target ?? GAME_OVER_SCORE));
|
||||
if (reached) {
|
||||
state.phase = 'gameOver';
|
||||
const min = Math.min(...state.players.map((p) => p.totalScore));
|
||||
|
|
@ -373,6 +389,33 @@ export function startNextHand(state) {
|
|||
return next;
|
||||
}
|
||||
|
||||
/** Log entries for the hand in progress (since its deal). */
|
||||
export function handLog(state) {
|
||||
for (let i = state.log.length - 1; i >= 0; i--) if (state.log[i].kind === 'deal') return state.log.slice(i);
|
||||
return state.log;
|
||||
}
|
||||
|
||||
/** Card keys ('Qs', '7h', …) already played this hand, including the open trick. */
|
||||
export function playedKeys(state) {
|
||||
const out = new Set();
|
||||
for (const e of handLog(state)) if (e.kind === 'play') out.add(`${e.card.rank}${e.card.suit}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** voids[seat] = set of suits that seat has shown out of this hand. */
|
||||
export function knownVoids(state) {
|
||||
const voids = state.players.map(() => new Set());
|
||||
for (const e of handLog(state)) {
|
||||
if (e.kind === 'play' && e.leadSuit && e.card.suit !== e.leadSuit) voids[e.seat].add(e.leadSuit);
|
||||
}
|
||||
return voids;
|
||||
}
|
||||
|
||||
/** Points each seat has taken so far this hand. */
|
||||
export function pointsTaken(state) {
|
||||
return state.players.map((p) => p.roundPoints);
|
||||
}
|
||||
|
||||
export function isGameOver(state) {
|
||||
return state.phase === 'gameOver';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,92 @@
|
|||
// Hearts table layout — Phaser-free so tools/verifyHearts.js can test it.
|
||||
//
|
||||
// A leather-topped card table in a firelit den, on the shared card-table kit.
|
||||
// Always four players: human (bottom) · left · across · right (logic seats
|
||||
// clockwise from the human's left, so "pass left" = seat + 1).
|
||||
//
|
||||
// Each seat has a hand fan, a spot in the middle where its trick card lands,
|
||||
// and a "won" area: a face-down stack of the tricks it has taken plus a
|
||||
// face-up row of the point cards (hearts, Q♠) among them — so everyone's
|
||||
// points this hand are visible at a glance.
|
||||
|
||||
import { makeTable, CARD_W, CARD_H, fanPose, fanPoint, HUMAN_PLATE, PLATE } from '../../ui/cardtable/TableGeometry.js';
|
||||
|
||||
export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 };
|
||||
export const T = makeTable(VIEW, { shape: 'rect', corner: 0.17, feltK: 0.94, faceH: 36 });
|
||||
export const SQ = VIEW.squash;
|
||||
|
||||
export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c];
|
||||
export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c'];
|
||||
|
||||
const HUMAN_FAN = { x: 960, y: 994, rot: 0, k: 1, spread: 82, curve: 1.3, tilt: 0.034, q: 1, maxSpan: 880, maxDrop: 34, maxTilt: 0.2 };
|
||||
const opp = (x, y, rot, k) => ({ x, y, rot, k, spread: 34, curve: 0.5, tilt: 0.03, q: 1, maxSpan: 520, maxDrop: 14, maxTilt: 0.16 });
|
||||
|
||||
export const SEATS = [
|
||||
{ fan: HUMAN_FAN, plate: HUMAN_PLATE, trick: { u: 0, v: 0.6 }, tricks: { u: 0.36, v: 0.74 }, points: { u: 0.45, v: 0.74, dir: 1 } },
|
||||
{ fan: opp(84, 540, Math.PI / 2, 0.5), plate: { x: 190, y: 150 }, trick: { u: -0.17, v: 0.46 }, tricks: { u: -0.62, v: 0.28 }, points: { u: -0.53, v: 0.28, dir: 1 } },
|
||||
{ fan: opp(960, 80, Math.PI, 0.52), plate: { x: 1400, y: 86 }, trick: { u: 0, v: 0.3 }, tricks: { u: 0.3, v: 0.17 }, points: { u: 0.39, v: 0.17, dir: 1 } },
|
||||
{ fan: opp(1836, 540, -Math.PI / 2, 0.5), plate: { x: 1730, y: 150 }, trick: { u: 0.17, v: 0.46 }, tricks: { u: 0.62, v: 0.28 }, points: { u: 0.53, v: 0.28, dir: -1 } },
|
||||
];
|
||||
|
||||
export const TRICK_K = 0.95;
|
||||
export const WON_K = 0.44;
|
||||
const POINT_STEP = 19; // px between overlapped point cards (at s = 1)
|
||||
|
||||
export function layout() {
|
||||
return { seats: SEATS.map((d, seat) => ({ seat, ...d })) };
|
||||
}
|
||||
export const L = layout();
|
||||
|
||||
export const handPose = (seat, i, n, lift = 0) => fanPose(SEATS[seat].fan, i, n, lift);
|
||||
|
||||
/** Where `seat`'s card lands in the trick (slightly turned, readable from your chair). */
|
||||
export function trickPose(seat) {
|
||||
const t = SEATS[seat].trick;
|
||||
const tilt = [0.02, -0.12, 0.05, 0.12][seat];
|
||||
return T.flat(t.u, t.v, TRICK_K, tilt);
|
||||
}
|
||||
|
||||
/** Top of `seat`'s face-down won-tricks stack (n cards). */
|
||||
export function tricksPose(seat, n = 1) {
|
||||
const t = SEATS[seat].tricks;
|
||||
const p = T.flat(t.u, t.v, WON_K, 0.06 * (seat % 2 ? -1 : 1));
|
||||
return { ...p, y: p.y - Math.min(8, Math.max(0, n - 1) * 0.18) };
|
||||
}
|
||||
|
||||
/** Point card i of n in `seat`'s face-up row. */
|
||||
export function pointPose(seat, i) {
|
||||
const t = SEATS[seat].points;
|
||||
const base = T.flat(t.u, t.v, WON_K);
|
||||
return { ...base, x: base.x + t.dir * i * POINT_STEP * (base.s / WON_K) };
|
||||
}
|
||||
|
||||
/** Screen rect a seat's point row covers when it holds `n` cards. */
|
||||
export function pointRowRect(seat, n) {
|
||||
const a = pointPose(seat, 0), b = pointPose(seat, Math.max(0, n - 1));
|
||||
const hw = (CARD_W / 2) * a.s, hh = (CARD_H / 2) * a.s * SQ;
|
||||
return { x0: Math.min(a.x, b.x) - hw, x1: Math.max(a.x, b.x) + hw, y0: a.y - hh, y1: a.y + hh };
|
||||
}
|
||||
|
||||
export function handHome(seat) {
|
||||
const f = SEATS[seat].fan;
|
||||
const p = fanPoint(f, 0, -CARD_H * 0.95);
|
||||
return { ...p, rot: f.rot, k: f.k };
|
||||
}
|
||||
|
||||
export function handBadge(seat) {
|
||||
const f = SEATS[seat].fan;
|
||||
return fanPoint(f, -(f.maxSpan / 2 + CARD_W / 2 + 50), 0);
|
||||
}
|
||||
|
||||
export function spotFor(seat) {
|
||||
const f = SEATS[seat].fan;
|
||||
if (seat === 0) return { x: f.x, y: 820, w: 1300, h: 420 };
|
||||
const c = fanPoint(f, 0, -CARD_H * 0.9);
|
||||
const side = Math.abs(Math.sin(f.rot)) > 0.7;
|
||||
return side ? { x: c.x, y: c.y, w: 420, h: 620 } : { x: c.x, y: c.y + 30, w: 640, h: 320 };
|
||||
}
|
||||
|
||||
/** Where the pass arrow sits (the middle of the table). */
|
||||
export const CENTRE = T.P.project(0, 0.45);
|
||||
|
||||
export { PLATE };
|
||||
|
|
@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
|
|||
|
||||
// Skill control: pips always show the level; the +/- buttons appear only
|
||||
// when this opponent is selected. Enabled for games with a 1–5 AI skill.
|
||||
if (['nerts', 'phase10', 'uno', 'skipbo', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) {
|
||||
if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) {
|
||||
bio.style.webkitLineClamp = '1';
|
||||
|
||||
const skillRow = document.createElement('div');
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@ import {
|
|||
// Fish and Old Maid next). Extracted from Phase 10 / Nerts.
|
||||
//
|
||||
// A game subclass provides:
|
||||
// faceFrame(card) → { key, frame } texture for a face-up card
|
||||
// faceFrame(card) → { key, frame, sized? } texture for a face-up card
|
||||
// (sized: true → scaled to the card, for custom sheets)
|
||||
// computeLayout() → { visible: Map(id → view), loc: Map(id → {pose,faceUp,depth}) }
|
||||
// view = { card, pose, faceUp, depth, kind, … }
|
||||
// decorate(c, view) (optional) hint marks / chips / glow per card
|
||||
|
|
@ -143,7 +144,10 @@ export class CardTableScene extends Phaser.Scene {
|
|||
c.faceUp = faceUp;
|
||||
if (faceUp) {
|
||||
const f = this.faceFrame(c.card);
|
||||
c.faceImg.setTexture(f.key, f.frame).setScale(0.5);
|
||||
c.faceImg.setTexture(f.key, f.frame);
|
||||
// custom sheets (e.g. Go Fish's own illustrated faces) are sized to the
|
||||
// card; baked 2× atlases just halve
|
||||
if (f.sized) c.faceImg.setDisplaySize(CARD_W, CARD_H); else c.faceImg.setScale(0.5);
|
||||
} else {
|
||||
const b = this.backFrame();
|
||||
c.faceImg.setTexture(b.key, b.frame);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,251 @@
|
|||
#!/usr/bin/env node
|
||||
// verifyGoFish.js — headless checks for Go Fish: rules (deal, asks, catches,
|
||||
// go fish + lucky draws, books AND pairs, refills, sitting out, game end), the
|
||||
// memory AI (always legal, skill-scaled recall), the dock layout for 2/3/4
|
||||
// players (pond, book rows, hands, HUD all clear), and an all-AI soak (every
|
||||
// game ends, 52 cards conserved, better memory wins more).
|
||||
// Usage: node tools/verifyGoFish.js [--quick]
|
||||
|
||||
import * as G from '../src/games/gofish/GoFishLogic.js';
|
||||
import { Card } from '../src/games/cards/Deck.js';
|
||||
import { createMemory, observeLog, chooseAction, RECALL, caughtFromThisTurn } from '../src/games/gofish/GoFishAI.js';
|
||||
import { aiTiming, mulberry32 } from '../src/ui/cardtable/AITiming.js';
|
||||
import {
|
||||
CARD_W, CARD_H, cardBounds, cardCorners, fanHit, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect, inRect, unionRect,
|
||||
} from '../src/ui/cardtable/TableGeometry.js';
|
||||
import {
|
||||
T, layoutFor, handPose, poolPose, pondOutline, inPond, bookPose, bookRowRect, handBadge, handHome, bubbleAt, seatTargetRect, POND, showPose,
|
||||
} from '../src/games/gofish/GoFishTable.js';
|
||||
|
||||
const QUICK = process.argv.includes('--quick');
|
||||
let pass = 0, fail = 0;
|
||||
function ok(label, cond, detail = '') {
|
||||
if (cond) pass++;
|
||||
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
|
||||
}
|
||||
const section = (n) => console.log(`\n${n}`);
|
||||
let nid = 900;
|
||||
const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++ });
|
||||
|
||||
function rig(hands, { matchSize = 4, pool = ['9s', '9h', 'Kd', '2c', '3c'], current = 0 } = {}) {
|
||||
const gs = G.createInitialState({ playerCount: hands.length, matchSize, seed: 3 });
|
||||
gs.players.forEach((p, s) => { p.hand = hands[s].map(C); p.books = []; p.pairs = 0; p.pairedRanks = []; p.sittingOut = false; });
|
||||
gs.pool = pool.map(C);
|
||||
gs.currentPlayer = current;
|
||||
gs.phase = 'play';
|
||||
gs.log = [];
|
||||
return gs;
|
||||
}
|
||||
|
||||
// ── Rules ────────────────────────────────────────────────────────────────────
|
||||
section('Rules');
|
||||
for (const n of [2, 3, 4]) for (const m of [2, 4]) {
|
||||
const gs = G.createInitialState({ playerCount: n, matchSize: m, seed: 10 + n + m });
|
||||
ok(`${n}p ${m === 4 ? 'books' : 'pairs'}: 52 conserved`, G.countCards(gs) === 52);
|
||||
ok(`${n}p ${m === 4 ? 'books' : 'pairs'}: dealt 7 (minus deal books)`, gs.players.every(p => p.hand.length + p.books.flat().length === 7 || p.hand.length > 0));
|
||||
}
|
||||
{
|
||||
const gs = rig([['7s', '7h', '2d'], ['7d', '7c', 'Kh']]);
|
||||
ok('cannot ask for a rank you lack', G.applyAsk(gs, 1, 'K') === gs);
|
||||
ok('cannot ask yourself', G.applyAsk(gs, 0, '7') === gs);
|
||||
const c = G.applyAsk(gs, 1, '7');
|
||||
ok('catch takes every card of the rank', c.lastAsk.result === 'catch' && c.lastAsk.cardsTransferred.length === 2);
|
||||
ok('four of a kind makes a book', c.players[0].pairs === 1 && c.players[0].books[0].length === 4 && c.players[0].hand.length === 1);
|
||||
ok('book logged', c.log.some(e => e.kind === 'pair' && e.rank === '7'));
|
||||
ok('catch: asker goes again', c.currentPlayer === 0);
|
||||
ok('52 conserved after a catch', G.countCards({ ...c, pool: c.pool }) === G.countCards(gs));
|
||||
}
|
||||
{
|
||||
const gs = rig([['7s', '2d'], ['Kd', 'Kh']], { pool: ['3c', '7h'] });
|
||||
const f = G.applyAsk(gs, 1, '7');
|
||||
ok('miss → go fish (pick phase)', f.phase === 'pick' && f.lastAsk.result === 'fish');
|
||||
const lucky = G.applyFishPick(f, f.pool.find(c => c.rank === '7').id);
|
||||
ok('fishing up the asked rank is lucky: go again', lucky.lastAsk.result === 'lucky' && lucky.currentPlayer === 0);
|
||||
const plain = G.applyFishPick(f, f.pool.find(c => c.rank === '3').id);
|
||||
ok('otherwise the turn passes', plain.lastAsk.result === 'fish' && plain.currentPlayer === 1);
|
||||
}
|
||||
{
|
||||
const gs = rig([['7s', '2d'], ['7d', 'Kh']], { matchSize: 2 });
|
||||
const c = G.applyAsk(gs, 1, '7');
|
||||
ok('pairs mode: two make a pair', c.players[0].pairs === 1 && c.players[0].books[0].length === 2);
|
||||
const empty = rig([['7s'], ['7d']], { matchSize: 2, pool: ['2c', '3c', '4c', '5c', '6c', '8c', '9c', 'Tc', 'Jc', 'Qc'] });
|
||||
const e = G.applyAsk(empty, 1, '7');
|
||||
ok('emptied hands refill to five', e.players[0].hand.length === 5 && e.players[1].hand.length === 5);
|
||||
const out = rig([['7s'], ['7d']], { matchSize: 2, pool: [] });
|
||||
const o = G.applyAsk(out, 1, '7');
|
||||
ok('no cards and an empty pond → game over', G.isGameOver(o));
|
||||
}
|
||||
{
|
||||
// a full game always conserves cards
|
||||
const gs = G.createInitialState({ playerCount: 3, matchSize: 4, seed: 99 });
|
||||
ok('countCards', G.countCards(gs) === 52);
|
||||
}
|
||||
|
||||
// ── AI ───────────────────────────────────────────────────────────────────────
|
||||
section('AI');
|
||||
{
|
||||
ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry);
|
||||
ok('recall rises with skill', RECALL[1] < RECALL[3] && RECALL[3] < RECALL[5] && RECALL[5] === 1);
|
||||
const gs = rig([['7s', '2d'], ['Kd', 'Kh'], ['Qs', '9d']], { current: 1 });
|
||||
let g = G.applyAsk(gs, 0, 'K'); // seat 1 asks the human for kings: go fish
|
||||
g = G.applyFishPick(g, g.pool[0].id);
|
||||
const mem = createMemory(3, { skill: 5, matchSize: 4, rng: () => 0.5 });
|
||||
observeLog(mem, g, 2);
|
||||
ok('perfect memory: seat 1 holds kings', mem.beliefs[1].K >= 1);
|
||||
g.currentPlayer = 2;
|
||||
g.players[2].hand.push(C('Kc'));
|
||||
const a = chooseAction(g, 2, mem);
|
||||
ok('asks the player who showed the rank', a && a.targetSeat === 1 && a.rank === 'K');
|
||||
// after a catch, the asker won't go back to the same player this turn
|
||||
const t3 = rig([['7s', '9d', 'Qh'], ['7d', 'Kh'], ['9s', 'Qc'], ['2c', '3d']], { current: 0 });
|
||||
const caught = G.applyAsk(t3, 1, '7');
|
||||
ok('catch noted for this turn', caughtFromThisTurn(caught, 0).has(1) && caught.currentPlayer === 0);
|
||||
let againOk = true;
|
||||
for (const sk of [1, 2, 3, 4, 5]) for (let k = 0; k < 20; k++) {
|
||||
const m = createMemory(4, { skill: sk, matchSize: 4, rng: mulberry32(k * 31 + sk) });
|
||||
observeLog(m, caught, 0);
|
||||
const a = chooseAction(caught, 0, m);
|
||||
if (!a || a.targetSeat === 1) againOk = false;
|
||||
}
|
||||
ok('no skill asks the same player twice in one turn', againOk);
|
||||
const nextTurn = G.applyAsk(caught, 2, '7'); // a different player's ask ends the run
|
||||
nextTurn.currentPlayer = 1;
|
||||
ok('the rule resets on the next turn', caughtFromThisTurn({ ...nextTurn, log: [...nextTurn.log, { kind: 'ask', askerSeat: 3, targetSeat: 0, rank: '2', result: 'fish' }] }, 0).size === 0);
|
||||
const heads = rig([['7s', '9d'], ['7d', '9h', 'Kh']], { current: 0 });
|
||||
const h1 = G.applyAsk(heads, 1, '7');
|
||||
const hm = createMemory(2, { skill: 5, matchSize: 4, rng: () => 0.5 });
|
||||
observeLog(hm, h1, 0);
|
||||
const ha = chooseAction(h1, 0, hm);
|
||||
ok('heads-up: the only opponent can still be asked again', ha && ha.targetSeat === 1);
|
||||
const forgetful = createMemory(3, { skill: 1, matchSize: 4, rng: () => 0.99 });
|
||||
observeLog(forgetful, g, 2);
|
||||
ok('skill 1 can miss what it saw', (forgetful.beliefs[1].K || 0) === 0);
|
||||
}
|
||||
|
||||
// ── Layout ───────────────────────────────────────────────────────────────────
|
||||
section('Layout');
|
||||
for (const n of [2, 3, 4]) {
|
||||
const L = layoutFor(n);
|
||||
const furn = hudFurniture();
|
||||
for (let s = 1; s < n; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) });
|
||||
for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) ok(`${n}p: ${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r));
|
||||
const pond = pondOutline(1.07);
|
||||
const pondBox = { x0: Math.min(...pond.map(p => p.x)), x1: Math.max(...pond.map(p => p.x)), y0: Math.min(...pond.map(p => p.y)) - 30, y1: Math.max(...pond.map(p => p.y)) + 34 };
|
||||
ok(`${n}p: pond on the dock`, pond.every(p => T.onFelt(p)));
|
||||
let inside = true;
|
||||
for (let id = 0; id < 52; id++) { const p = poolPose(id); if (!inPond(p)) inside = false; }
|
||||
ok(`${n}p: every pool card floats inside the pond`, inside);
|
||||
const rows = [];
|
||||
for (let s = 0; s < n; s++) {
|
||||
const row = bookRowRect(L, s, 13);
|
||||
rows[s] = row;
|
||||
ok(`${n}p seat ${s}: book row on the dock`, T.onFelt({ x: row.x0, y: row.y0 }) && T.onFelt({ x: row.x1, y: row.y1 }), JSON.stringify(row));
|
||||
ok(`${n}p seat ${s}: book row clear of the pond`, !rectsOverlap(row, pondBox), `${JSON.stringify(row)} vs ${JSON.stringify(pondBox)}`);
|
||||
for (const f of furn) ok(`${n}p seat ${s}: book row clear of ${f.name}`, !rectsOverlap(row, f.r), `${JSON.stringify(row)} vs ${JSON.stringify(f.r)}`);
|
||||
for (const cards of [1, 7, 15, 22]) {
|
||||
const hb = fanBounds(L.seats[s].fan, cards, s === 0 ? 40 : 0);
|
||||
ok(`${n}p seat ${s} (${cards}): hand on screen`, onScreen(hb, s === 0 ? 50 : 10));
|
||||
for (const f of furn) ok(`${n}p seat ${s} (${cards}): hand clear of ${f.name}`, !rectsOverlap(hb, f.r), `${JSON.stringify(hb)} vs ${JSON.stringify(f.r)}`);
|
||||
ok(`${n}p seat ${s} (${cards}): hand clear of the pond`, !rectsOverlap(hb, pondBox));
|
||||
for (let t = 0; t < n; t++) ok(`${n}p hand ${s} (${cards}) clear of book row ${t}`, !rectsOverlap(hb, bookRowRect(L, t, 13)));
|
||||
}
|
||||
if (s > 0) {
|
||||
const b = handBadge(L, s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 };
|
||||
ok(`${n}p seat ${s}: badge on screen`, onScreen(br));
|
||||
for (const f of furn) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r));
|
||||
const bb = bubbleAt(L, s);
|
||||
ok(`${n}p seat ${s}: speech bubble on screen`, bb.x > 120 && bb.x < 1800 && bb.y > 40 && bb.y < 1000);
|
||||
const tr = seatTargetRect(L, s, 7);
|
||||
ok(`${n}p seat ${s}: ask target covers their hand`, inRect(handPose(L, s, 3, 7), tr));
|
||||
const hh = handHome(L, s);
|
||||
ok(`${n}p seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < 1920 && hh.y > 0 && hh.y < 1080);
|
||||
}
|
||||
}
|
||||
for (let s = 0; s < n; s++) for (let t = s + 1; t < n; t++) ok(`${n}p book rows ${s}/${t} apart`, !rectsOverlap(rows[s], rows[t]));
|
||||
// show spots: up to 3 cards held up / laid out, clear of everything else
|
||||
const shows = [];
|
||||
for (let s = 0; s < n; s++) {
|
||||
let r = null;
|
||||
const corners = [];
|
||||
for (let i = 0; i < 3; i++) { const p = showPose(L, s, i, 3); r = unionRect(r, cardBounds(p)); corners.push(...cardCorners(p)); }
|
||||
shows[s] = r;
|
||||
ok(`${n}p seat ${s}: show spot on screen`, onScreen(r));
|
||||
ok(`${n}p seat ${s}: show spot clear of the pond`, corners.every(p => !inPond(p)));
|
||||
for (const f of furn) ok(`${n}p seat ${s}: show spot clear of ${f.name}`, !rectsOverlap(r, f.r), `${JSON.stringify(r)} vs ${JSON.stringify(f.r)}`);
|
||||
for (let t = 0; t < n; t++) {
|
||||
ok(`${n}p show ${s} clear of book row ${t}`, !rectsOverlap(r, rows[t]), `${JSON.stringify(r)} vs ${JSON.stringify(rows[t])}`);
|
||||
ok(`${n}p show ${s} clear of hand ${t}`, !rectsOverlap(r, fanBounds(L.seats[t].fan, 15, t === 0 ? 40 : 0)), `${JSON.stringify(r)}`);
|
||||
}
|
||||
}
|
||||
for (let s = 0; s < n; s++) for (let t = s + 1; t < n; t++) ok(`${n}p show spots ${s}/${t} apart`, !rectsOverlap(shows[s], shows[t]));
|
||||
for (let s = 1; s < n; s++) for (let t = s + 1; t < n; t++) ok(`${n}p ask targets ${s}/${t} apart`, !rectsOverlap(seatTargetRect(L, s, 7), seatTargetRect(L, t, 7)));
|
||||
let rt = true;
|
||||
for (let i = 0; i < 7; i++) { const p = handPose(L, 0, i, 7); if (fanHit(L.seats[0].fan, 7, { x: p.x - CARD_W * 0.3, y: p.y - CARD_H * 0.3 }) !== i) rt = false; }
|
||||
ok(`${n}p: hand hit-test round trip`, rt);
|
||||
ok(`${n}p: books compress to fit 13`, bookPose(L, 0, 12, 13).x !== bookPose(L, 0, 0, 13).x);
|
||||
}
|
||||
void POND; void cardBounds;
|
||||
|
||||
// ── Soak ─────────────────────────────────────────────────────────────────────
|
||||
section('Soak');
|
||||
function game(skills, seed, matchSize = 4) {
|
||||
const rand = mulberry32(seed);
|
||||
let gs = G.createInitialState({ playerCount: skills.length, matchSize, seed });
|
||||
const mem = skills.map((sk) => createMemory(skills.length, { skill: sk, matchSize, rng: rand }));
|
||||
let steps = 0, noop = 0, conserve = true, repeats = 0;
|
||||
while (!G.isGameOver(gs) && steps++ < 3000) {
|
||||
mem.forEach((m, s) => observeLog(m, gs, s));
|
||||
if (gs.phase === 'pick') { gs = G.applyFishPick(gs, gs.pool[Math.floor(rand() * gs.pool.length)].id); continue; }
|
||||
const s = gs.currentPlayer;
|
||||
const a = chooseAction(gs, s, mem[s]);
|
||||
if (!a) { noop++; break; }
|
||||
const open = gs.players.filter(p => p.seat !== s && !p.sittingOut && p.hand.length > 0).map(p => p.seat);
|
||||
const before = caughtFromThisTurn(gs, s);
|
||||
if (before.has(a.targetSeat) && open.some(t => !before.has(t))) repeats++;
|
||||
const nx = G.applyAsk(gs, a.targetSeat, a.rank);
|
||||
if (nx === gs) { noop++; break; }
|
||||
gs = nx;
|
||||
if (G.countCards(gs) !== 52) conserve = false;
|
||||
}
|
||||
return { gs, over: G.isGameOver(gs), noop, conserve, repeats };
|
||||
}
|
||||
{
|
||||
const M = QUICK ? 40 : 150;
|
||||
for (const m of [4, 2]) for (const n of [2, 3, 4]) {
|
||||
let over = 0, noop = 0, conserved = true, books = true, repeats = 0;
|
||||
for (let i = 0; i < M; i++) {
|
||||
const r = game(Array.from({ length: n }, (_, s) => 1 + ((i + s) % 5)), 100 + i * 7 + n, m);
|
||||
if (r.over) over++;
|
||||
noop += r.noop;
|
||||
if (!r.conserve) conserved = false;
|
||||
repeats += r.repeats;
|
||||
const total = r.gs.players.reduce((a, p) => a + p.pairs, 0);
|
||||
if (m === 4 && total !== 13) books = false;
|
||||
}
|
||||
const tag = `${n}p ${m === 4 ? 'books' : 'pairs'}`;
|
||||
ok(`${tag}: every game ends`, over === M, `${over}/${M}`);
|
||||
ok(`${tag}: AI never makes an illegal ask`, noop === 0);
|
||||
ok(`${tag}: 52 cards conserved`, conserved);
|
||||
ok(`${tag}: never re-asks a player already caught from this turn`, repeats === 0, `${repeats}`);
|
||||
if (m === 4) ok(`${tag}: all 13 books get made`, books);
|
||||
}
|
||||
// skill: in 4-player games memory matters a lot; heads-up books is mostly luck
|
||||
const one = (a, b, games) => {
|
||||
let w = 0;
|
||||
for (let i = 0; i < games; i++) {
|
||||
const seat = i % 4; const sk = [b, b, b, b]; sk[seat] = a;
|
||||
const r = game(sk, 7000 + i, 4);
|
||||
if (r.gs.winnerSeats.includes(seat)) w += 1 / r.gs.winnerSeats.length;
|
||||
}
|
||||
return w / games;
|
||||
};
|
||||
const G4 = QUICK ? 300 : 800;
|
||||
const w51 = one(5, 1, G4), w53 = one(5, 3, G4), w15 = one(1, 5, G4);
|
||||
console.log(` 4p win rates (fair 25%): skill 5 vs 1s ${(w51 * 100).toFixed(0)}% · 5 vs 3s ${(w53 * 100).toFixed(0)}% · 1 vs 5s ${(w15 * 100).toFixed(0)}%`);
|
||||
ok('skill 5 dominates a table of skill 1s', w51 >= 0.45);
|
||||
ok('skill 5 beats a table of skill 3s', w53 >= (QUICK ? 0.27 : 0.29));
|
||||
ok('skill 1 loses to a table of skill 5s', w15 <= 0.16);
|
||||
}
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
|
|
@ -0,0 +1,282 @@
|
|||
#!/usr/bin/env node
|
||||
// verifyHearts.js — headless checks for Hearts: rules (deal, passing in all
|
||||
// four directions, 2♣ lead, follow suit, hearts breaking, first-trick rule,
|
||||
// scoring, both moon rules, match end at the target), the memory helpers and
|
||||
// AI (always legal, skill timing), the den layout (on screen, clear of the HUD
|
||||
// and each other), and an all-AI soak (every match ends, 52 cards conserved,
|
||||
// skill ordering by points per hand).
|
||||
// Usage: node tools/verifyHearts.js [--quick]
|
||||
|
||||
import * as Hr from '../src/games/hearts/HeartsLogic.js';
|
||||
import { Card } from '../src/games/cards/Deck.js';
|
||||
import { choosePass, choosePlay, suggestPass, suggestPlay } from '../src/games/hearts/HeartsAI.js';
|
||||
import { aiTiming, mulberry32 } from '../src/ui/cardtable/AITiming.js';
|
||||
import {
|
||||
CARD_W, CARD_H, cardBounds, fanHit, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect, inPose,
|
||||
} from '../src/ui/cardtable/TableGeometry.js';
|
||||
import { T, L, handPose, trickPose, tricksPose, pointRowRect, handBadge, handHome, CENTRE } from '../src/games/hearts/HeartsTable.js';
|
||||
|
||||
const QUICK = process.argv.includes('--quick');
|
||||
let pass = 0, fail = 0;
|
||||
function ok(label, cond, detail = '') {
|
||||
if (cond) pass++;
|
||||
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
|
||||
}
|
||||
const section = (n) => console.log(`\n${n}`);
|
||||
let nid = 500;
|
||||
const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++ });
|
||||
const count = (gs) => gs.players.reduce((n, p) => n + p.hand.length + p.wonCards.length, 0) + gs.trick.length;
|
||||
|
||||
function playing(hands, { current = 0, broken = false, trickNumber = 1 } = {}) {
|
||||
const gs = Hr.createInitialState({ seed: 4 });
|
||||
gs.phase = 'playing';
|
||||
gs.players.forEach((p, s) => { p.hand = hands[s].map(C); p.wonCards = []; p.roundPoints = 0; });
|
||||
gs.currentPlayer = current;
|
||||
gs.heartsBroken = broken;
|
||||
gs.trickNumber = trickNumber;
|
||||
gs.trick = [];
|
||||
gs.leadSuit = null;
|
||||
return gs;
|
||||
}
|
||||
|
||||
// ── Rules ────────────────────────────────────────────────────────────────────
|
||||
section('Rules');
|
||||
{
|
||||
const gs = Hr.createInitialState({ seed: 9 });
|
||||
ok('13 cards each', gs.players.every(p => p.hand.length === 13));
|
||||
ok('52 unique', new Set(gs.players.flatMap(p => p.hand.map(c => c.id))).size === 52);
|
||||
ok('first hand passes left', gs.phase === 'passing' && gs.passDirection === 'left');
|
||||
ok('deal is logged', gs.log.some(e => e.kind === 'deal'));
|
||||
ok('pass targets', Hr.passTargetSeat(0, 'left') === 1 && Hr.passTargetSeat(0, 'right') === 3 && Hr.passTargetSeat(0, 'across') === 2);
|
||||
let g = gs;
|
||||
const picks = [];
|
||||
for (let s = 0; s < 4; s++) { const ids = g.players[s].hand.slice(0, 3).map(c => c.id); picks.push(ids); g = Hr.selectPass(g, s, ids); }
|
||||
ok('passes resolve when all four are in', g.phase === 'playing' && g.players.every(p => p.hand.length === 13));
|
||||
ok('passed cards land with the left neighbour', picks[0].every(id => g.players[1].hand.some(c => c.id === id)));
|
||||
ok('2♣ holder leads', g.players[g.currentPlayer].hand.some(c => c.key === '2c'));
|
||||
ok('must lead the 2♣', Hr.legalPlays(g, g.currentPlayer).length === 1 && Hr.legalPlays(g, g.currentPlayer)[0].key === '2c');
|
||||
// directions cycle left → right → across → hold
|
||||
let h = Hr.createInitialState({ seed: 3 });
|
||||
const dirs = [];
|
||||
for (let k = 0; k < 4; k++) {
|
||||
dirs.push(h.passDirection);
|
||||
h.phase = 'handOver';
|
||||
h = Hr.startNextHand(h);
|
||||
}
|
||||
ok('pass directions cycle', dirs.join() === 'left,right,across,hold');
|
||||
let hold = Hr.createInitialState({ seed: 3 });
|
||||
for (let k = 0; k < 3; k++) { hold.phase = 'handOver'; hold = Hr.startNextHand(hold); }
|
||||
ok('hold hand skips passing', hold.passDirection === 'hold' && hold.phase === 'playing' && hold.players[hold.currentPlayer].hand.some(c => c.key === '2c'));
|
||||
}
|
||||
{
|
||||
const gs = playing([['5c', 'Kh', 'Qs'], ['9c', '2h', '3d'], ['Ac', '4h', '5d'], ['2c', 'Jh', '6s']], { current: 3, trickNumber: 0 });
|
||||
let g = Hr.playCard(gs, gs.players[3].hand[0].id);
|
||||
ok('must follow suit', Hr.legalPlays(g, 0).every(c => c.suit === 'c'));
|
||||
g = Hr.playCard(g, g.players[0].hand[0].id);
|
||||
g = Hr.playCard(g, g.players[1].hand[0].id);
|
||||
g = Hr.playCard(g, g.players[2].hand[0].id);
|
||||
ok('highest of the led suit wins', g.lastTrick.winnerSeat === 2 && g.currentPlayer === 2);
|
||||
ok('hearts not broken yet', !g.heartsBroken);
|
||||
ok('cannot lead hearts before broken', Hr.legalPlays(g, 2).every(c => c.suit !== 'h'));
|
||||
}
|
||||
{
|
||||
const first = playing([['Qs', 'Kh', '9d'], ['2c', '2h', '3d'], ['Ac', '4h', '5d'], ['3c', 'Jh', '6s']], { current: 1, trickNumber: 0 });
|
||||
let g = Hr.playCard(first, first.players[1].hand[0].id);
|
||||
g = Hr.playCard(g, g.players[2].hand[0].id);
|
||||
g = Hr.playCard(g, g.players[3].hand[0].id);
|
||||
const leg = Hr.legalPlays(g, 0);
|
||||
ok('no points on the first trick when void', leg.length === 1 && leg[0].key === '9d');
|
||||
const allPts = playing([['Qs', 'Kh'], ['2c', '2h'], ['Ac', '4h'], ['3c', 'Jh']], { current: 1, trickNumber: 0 });
|
||||
let a = Hr.playCard(allPts, allPts.players[1].hand[0].id);
|
||||
a = Hr.playCard(a, a.players[2].hand[0].id);
|
||||
a = Hr.playCard(a, a.players[3].hand[0].id);
|
||||
ok('…unless you hold only point cards', Hr.legalPlays(a, 0).length === 2);
|
||||
const brk = playing([['5c', 'Kh'], ['9c', '2h'], ['2d', '4h'], ['3d', 'Jh']], { current: 0, trickNumber: 3 });
|
||||
let b = Hr.playCard(brk, brk.players[0].hand[0].id);
|
||||
b = Hr.playCard(b, b.players[1].hand[0].id);
|
||||
b = Hr.playCard(b, b.players[2].hand[1].id);
|
||||
ok('a heart breaks hearts (logged)', b.heartsBroken && b.log.some(e => e.kind === 'heartsBroken'));
|
||||
const onlyH = playing([['Kh', '2h'], ['9c'], ['2d'], ['3d']], { current: 0, trickNumber: 3 });
|
||||
ok('may lead hearts holding nothing else', Hr.legalPlays(onlyH, 0).length === 2);
|
||||
const voids = playing([['5c'], ['9c'], ['2d'], ['3d']], { current: 0, trickNumber: 3 });
|
||||
let v = Hr.playCard(voids, voids.players[0].hand[0].id);
|
||||
v = Hr.playCard(v, v.players[1].hand[0].id);
|
||||
v = Hr.playCard(v, v.players[2].hand[0].id);
|
||||
ok('known voids from the log', Hr.knownVoids(v)[2].has('c'));
|
||||
ok('played keys tracked', Hr.playedKeys(v).has('5c') && Hr.playedKeys(v).has('2d'));
|
||||
}
|
||||
{
|
||||
// scoring: a full hand dealt by hand; seat 0 takes everything → moon
|
||||
const mk = (target, moonMode) => {
|
||||
const gs = Hr.createInitialState({ seed: 1, target, moonMode });
|
||||
gs.phase = 'playing';
|
||||
const suits = ['h', 's', 'd', 'c'];
|
||||
const ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
|
||||
// seat 0 holds every heart; others hold the rest; Q♠ forced onto seat 0's trick
|
||||
gs.players[0].hand = ranks.map(r => C(`${r}h`));
|
||||
gs.players[1].hand = ranks.map(r => C(`${r}s`));
|
||||
gs.players[2].hand = ranks.map(r => C(`${r}d`));
|
||||
gs.players[3].hand = ranks.map(r => C(`${r}c`));
|
||||
gs.players.forEach(p => { p.wonCards = []; p.roundPoints = 0; });
|
||||
gs.heartsBroken = true;
|
||||
gs.trickNumber = 1;
|
||||
gs.currentPlayer = 0;
|
||||
return gs;
|
||||
};
|
||||
const runOut = (g) => {
|
||||
let guard = 0;
|
||||
while (g.phase === 'playing' && guard++ < 100) {
|
||||
const s = g.currentPlayer;
|
||||
const legal = Hr.legalPlays(g, s);
|
||||
// seat 1 dumps the Queen as soon as it can
|
||||
const pick = s === 1 ? (legal.find(c => c.key === 'Qs') ?? legal[legal.length - 1]) : legal[legal.length - 1];
|
||||
g = Hr.playCard(g, pick.id);
|
||||
}
|
||||
return g;
|
||||
};
|
||||
const m = runOut(mk(100, 'add'));
|
||||
ok('moon: shooter 0, others +26', m.moonShooter === 0 && m.handScores.join() === '0,26,26,26');
|
||||
const sub = runOut(mk(100, 'subtract'));
|
||||
ok('moon (subtract): shooter −26, others 0', sub.handScores.join() === '-26,0,0,0');
|
||||
const low = runOut(mk(20, 'add'));
|
||||
ok('reaching the target ends the match, lowest wins', low.phase === 'gameOver' && low.winnerSeats.join() === '0');
|
||||
ok('52 cards accounted for after a hand', m.players.reduce((n, p) => n + p.wonCards.length, 0) === 52);
|
||||
}
|
||||
|
||||
// ── AI ───────────────────────────────────────────────────────────────────────
|
||||
section('AI');
|
||||
{
|
||||
ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry);
|
||||
const gs = Hr.createInitialState({ seed: 12 });
|
||||
for (const sk of [1, 3, 5]) {
|
||||
const ids = choosePass(gs, 1, { skill: sk, rng: mulberry32(sk) });
|
||||
ok(`skill ${sk} passes 3 of its own cards`, ids.length === 3 && new Set(ids).size === 3 && ids.every(id => gs.players[1].hand.some(c => c.id === id)));
|
||||
}
|
||||
const withQ = playing([['Qs', '5c', '9d'], ['2c'], ['3c'], ['4c']], { current: 1, trickNumber: 3 });
|
||||
withQ.players[0].hand = [C('Qs'), C('9d'), C('Kh')];
|
||||
let g = Hr.playCard(withQ, withQ.players[1].hand[0].id);
|
||||
g = Hr.playCard(g, g.players[2].hand[0].id);
|
||||
g = Hr.playCard(g, g.players[3].hand[0].id);
|
||||
ok('void → dumps the Queen', choosePlay(g, 0, { skill: 3, rng: () => 0.5 }) === g.players[0].hand.find(c => c.key === 'Qs').id);
|
||||
const duck = playing([['Kd', '7d', '2d'], ['9d'], ['3c'], ['4c']], { current: 1, trickNumber: 3 });
|
||||
const d1 = Hr.playCard(duck, duck.players[1].hand[0].id);
|
||||
const d2 = Hr.playCard(Hr.playCard(d1, d1.players[2].hand[0].id), Hr.playCard(d1, d1.players[2].hand[0].id).players[3].hand[0].id);
|
||||
ok('ducks under the winner with its highest safe card', choosePlay(d2, 0, { skill: 3, rng: () => 0.5 }) === d2.players[0].hand.find(c => c.key === '7d').id);
|
||||
ok('hints are legal', (() => { const s = Hr.createInitialState({ seed: 2 }); return suggestPass(s, 0).length === 3; })());
|
||||
const lead = playing([['5c', '9d', 'Kh'], ['2c'], ['3c'], ['4c']], { current: 0, trickNumber: 3, broken: true });
|
||||
ok('hint play is legal', Hr.isLegalPlay(lead, 0, suggestPlay(lead, 0)));
|
||||
}
|
||||
|
||||
// ── Layout ───────────────────────────────────────────────────────────────────
|
||||
section('Layout');
|
||||
{
|
||||
const furn = hudFurniture();
|
||||
for (let s = 1; s < 4; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) });
|
||||
for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) ok(`${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r));
|
||||
const tricks = [0, 1, 2, 3].map(s => cardBounds(trickPose(s)));
|
||||
for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) ok(`trick spots ${i}/${j} apart`, !rectsOverlap(tricks[i], tricks[j]));
|
||||
const won = [0, 1, 2, 3].map(s => {
|
||||
const st = cardBounds(tricksPose(s, 20));
|
||||
const pr = pointRowRect(s, 14);
|
||||
return { st, pr };
|
||||
});
|
||||
const fans = [0, 1, 2, 3].map(s => fanBounds(L.seats[s].fan, 13, s === 0 ? 44 : 0));
|
||||
for (let s = 0; s < 4; s++) {
|
||||
ok(`seat ${s}: hand on screen`, onScreen(fans[s], s === 0 ? 50 : 10));
|
||||
ok(`seat ${s}: trick spot on the table`, T.onFelt({ x: tricks[s].x0, y: tricks[s].y0 }) && T.onFelt({ x: tricks[s].x1, y: tricks[s].y1 }));
|
||||
ok(`seat ${s}: won stack on the table`, T.onFelt({ x: won[s].st.x0, y: won[s].st.y0 }) && T.onFelt({ x: won[s].st.x1, y: won[s].st.y1 }));
|
||||
ok(`seat ${s}: 14-card point row on the table`, T.onFelt({ x: won[s].pr.x0, y: won[s].pr.y0 }) && T.onFelt({ x: won[s].pr.x1, y: won[s].pr.y1 }));
|
||||
ok(`seat ${s}: won stack clear of its point row`, !rectsOverlap(won[s].st, won[s].pr));
|
||||
for (const f of furn) {
|
||||
ok(`seat ${s}: hand clear of ${f.name}`, !rectsOverlap(fans[s], f.r), `${JSON.stringify(fans[s])} vs ${JSON.stringify(f.r)}`);
|
||||
ok(`seat ${s}: point row clear of ${f.name}`, !rectsOverlap(won[s].pr, f.r));
|
||||
ok(`seat ${s}: won stack clear of ${f.name}`, !rectsOverlap(won[s].st, f.r));
|
||||
}
|
||||
for (let t = 0; t < 4; t++) {
|
||||
ok(`hand ${s} clear of trick spot ${t}`, !rectsOverlap(fans[s], tricks[t]));
|
||||
ok(`hand ${s} clear of point row ${t}`, !rectsOverlap(fans[s], won[t].pr), `${JSON.stringify(fans[s])} vs ${JSON.stringify(won[t].pr)}`);
|
||||
ok(`trick ${s} clear of point row ${t}`, !rectsOverlap(tricks[s], won[t].pr));
|
||||
if (t !== s) ok(`point rows ${s}/${t} apart`, !rectsOverlap(won[s].pr, won[t].pr) && !rectsOverlap(won[s].pr, won[t].st));
|
||||
}
|
||||
if (s > 0) {
|
||||
const b = handBadge(s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 };
|
||||
ok(`seat ${s}: badge on screen`, onScreen(br));
|
||||
for (const f of furn) ok(`seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r));
|
||||
const hh = handHome(s);
|
||||
ok(`seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < 1920 && hh.y > 0 && hh.y < 1080);
|
||||
}
|
||||
}
|
||||
let rt = true;
|
||||
for (let i = 0; i < 13; i++) {
|
||||
const p = handPose(0, i, 13);
|
||||
const step = handPose(0, 1, 13).x - handPose(0, 0, 13).x;
|
||||
if (fanHit(L.seats[0].fan, 13, { x: p.x - CARD_W / 2 + step * 0.45, y: p.y - CARD_H * 0.3 }) !== i) rt = false;
|
||||
}
|
||||
ok('hand hit-test round trip (13)', rt);
|
||||
ok('drop onto your trick spot', inPose(trickPose(0), trickPose(0), 60));
|
||||
ok('pass arrow centre on the table', T.onFelt(CENTRE));
|
||||
}
|
||||
|
||||
// ── Soak ─────────────────────────────────────────────────────────────────────
|
||||
section('Soak');
|
||||
function match(skills, seed, opts = {}) {
|
||||
const rand = mulberry32(seed);
|
||||
let gs = Hr.createInitialState({ seed, ...opts });
|
||||
let hands = 0, noop = 0, conserve = true;
|
||||
const pts = [0, 0, 0, 0];
|
||||
while (!Hr.isGameOver(gs) && hands < 80) {
|
||||
let st = 0;
|
||||
while (gs.phase !== 'handOver' && gs.phase !== 'gameOver' && st++ < 600) {
|
||||
if (gs.phase === 'passing') { for (let s = 0; s < 4; s++) if (!gs.passReady[s]) gs = Hr.selectPass(gs, s, choosePass(gs, s, { skill: skills[s], rng: rand })); continue; }
|
||||
const id = choosePlay(gs, gs.currentPlayer, { skill: skills[gs.currentPlayer], rng: rand });
|
||||
const nx = Hr.playCard(gs, id);
|
||||
if (nx === gs) { noop++; break; }
|
||||
gs = nx;
|
||||
if (count(gs) !== 52) conserve = false;
|
||||
}
|
||||
if (gs.phase !== 'handOver' && gs.phase !== 'gameOver') break;
|
||||
hands++;
|
||||
gs.handScores.forEach((p, s) => { pts[s] += p; });
|
||||
if (gs.phase === 'handOver') gs = Hr.startNextHand(gs);
|
||||
}
|
||||
return { gs, hands, noop, conserve, pts };
|
||||
}
|
||||
{
|
||||
const M = QUICK ? 20 : 80;
|
||||
for (const opts of [{}, { target: 50 }, { moonMode: 'subtract' }]) {
|
||||
let ended = 0, noops = 0, conserved = true, hands = 0;
|
||||
for (let i = 0; i < M; i++) {
|
||||
const r = match([1, 2, 3, 4].map((_, s) => 1 + ((i + s) % 5)), 400 + i * 7, opts);
|
||||
if (Hr.isGameOver(r.gs)) ended++;
|
||||
noops += r.noop;
|
||||
if (!r.conserve) conserved = false;
|
||||
hands += r.hands;
|
||||
}
|
||||
const tag = JSON.stringify(opts);
|
||||
ok(`${tag}: every match ends`, ended === M, `${ended}/${M}`);
|
||||
ok(`${tag}: AI never plays illegally`, noops === 0, `${noops}`);
|
||||
ok(`${tag}: 52 cards conserved`, conserved);
|
||||
console.log(` ${tag}: avg ${(hands / M).toFixed(1)} hands per match`);
|
||||
}
|
||||
// skill: one seat of skill a among three of skill b — points per hand
|
||||
const vs = (a, b, games) => {
|
||||
let pa = 0, pb = 0, hands = 0;
|
||||
for (let i = 0; i < games; i++) {
|
||||
const seat = i % 4;
|
||||
const skills = [b, b, b, b]; skills[seat] = a;
|
||||
const r = match(skills, 9000 + i);
|
||||
hands += r.hands;
|
||||
pa += r.pts[seat];
|
||||
pb += r.pts.reduce((x, y) => x + y, 0) - r.pts[seat];
|
||||
}
|
||||
return { a: pa / hands, b: pb / hands / 3 };
|
||||
};
|
||||
const G = QUICK ? 80 : 300;
|
||||
const s53 = vs(5, 3, G), s31 = vs(3, 1, G);
|
||||
console.log(` points per hand: skill 5 ${s53.a.toFixed(2)} vs skill 3 ${s53.b.toFixed(2)} · skill 3 ${s31.a.toFixed(2)} vs skill 1 ${s31.b.toFixed(2)}`);
|
||||
ok('skill 3 takes clearly fewer points than skill 1', s31.a < s31.b * 0.85);
|
||||
ok('skill 5 takes fewer points than skill 3', s53.a < s53.b * (QUICK ? 1.0 : 0.97));
|
||||
}
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
Loading…
Reference in New Issue