diff --git a/assets/videos/mahjong/mm-background-03.mp4 b/assets/videos/mahjong/mm-background-03.mp4 new file mode 100644 index 0000000..a303129 Binary files /dev/null and b/assets/videos/mahjong/mm-background-03.mp4 differ diff --git a/src/games/freecell/FreecellArt.js b/src/games/freecell/FreecellArt.js new file mode 100644 index 0000000..c2e7e69 --- /dev/null +++ b/src/games/freecell/FreecellArt.js @@ -0,0 +1,568 @@ +// Freecell art — the Night Study, baked once per page load (no image files). +// +// freecell-room 1920×1080: panelled wall strip with bookshelves, a rainy +// night window between velvet curtains and the mantel clock; +// a walnut desk, a tooled green-leather blotter with brass +// card clips (free cells) and engraved suit trays, the +// banker's lamp and its light pool, a teacup, pen and glasses +// freecell-back card back (bottle green, gold filigree) +// freecell-dealcard the ruled index card on the left of the desk +// freecell-plaque the brass plaque under the clock +// freecell-box the open card box the deck deals from +// Cards are the shared casino deck ('casino-cards'). + +import { prepareCasinoArt, drawSuit, canvas, rr, mix, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { + W, H, S, CW, CH, WALL_H, BLOTTER, WINDOW, CLOCK, PLAQUE, DEAL_CARD, LAMP, POOL, DECK, + cellPose, foundPose, colX, TAB_TOP, +} from './FreecellTable.js'; +import { FOUNDATION_ORDER } from './FreecellLogic.js'; + +const RES = 2; +let seed = 11; +const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }; + +// ── Desk ───────────────────────────────────────────────────────────────────── +function walnut(ctx) { + const g = ctx.createLinearGradient(0, WALL_H, 0, H); + g.addColorStop(0, '#3a2213'); g.addColorStop(1, '#24140a'); + ctx.fillStyle = g; + ctx.fillRect(0, WALL_H, W, H - WALL_H); + // long grain lines across the desk + for (let i = 0; i < 420; i++) { + const y = WALL_H + rnd() * (H - WALL_H); + const x0 = rnd() * W, len = 200 + rnd() * 900; + ctx.strokeStyle = rnd() < 0.5 ? `rgba(0,0,0,${0.08 + rnd() * 0.12})` : `rgba(200,140,80,${0.03 + rnd() * 0.06})`; + ctx.lineWidth = 0.8 + rnd() * 2.4; + ctx.beginPath(); + ctx.moveTo(x0, y); + ctx.bezierCurveTo(x0 + len * 0.3, y + (rnd() - 0.5) * 14, x0 + len * 0.7, y + (rnd() - 0.5) * 14, x0 + len, y + (rnd() - 0.5) * 8); + ctx.stroke(); + } + // a few knots + for (let i = 0; i < 5; i++) { + const x = rnd() * W, y = WALL_H + 60 + rnd() * (H - WALL_H - 80); + for (let r = 26; r > 2; r -= 4) { + ctx.strokeStyle = `rgba(0,0,0,${0.06 + (26 - r) * 0.006})`; + ctx.lineWidth = 1.2; + ctx.beginPath(); ctx.ellipse(x, y, r * 2.4, r * 0.7, 0, 0, Math.PI * 2); ctx.stroke(); + } + } + ctx.fillStyle = noisePattern(ctx, 180, 18); + ctx.fillRect(0, WALL_H, W, H - WALL_H); + // polished sheen + const sh = ctx.createLinearGradient(0, WALL_H, W, H); + sh.addColorStop(0, 'rgba(255,220,170,0.05)'); sh.addColorStop(0.5, 'rgba(255,220,170,0)'); sh.addColorStop(1, 'rgba(255,220,170,0.03)'); + ctx.fillStyle = sh; + ctx.fillRect(0, WALL_H, W, H - WALL_H); +} + +function blotter(ctx) { + const b = BLOTTER, w = b.x1 - b.x0, h = b.y1 - b.y0; + // drop shadow + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.65)'; ctx.shadowBlur = 26; ctx.shadowOffsetY = 8; + rr(ctx, b.x0, b.y0, w, h, 10); + ctx.fillStyle = '#123224'; + ctx.fill(); + ctx.restore(); + ctx.save(); + rr(ctx, b.x0, b.y0, w, h, 10); + ctx.clip(); + const g = ctx.createLinearGradient(0, b.y0, 0, b.y1); + g.addColorStop(0, '#173d2c'); g.addColorStop(1, '#0f2a1e'); + ctx.fillStyle = g; + ctx.fillRect(b.x0, b.y0, w, h); + // leather mottling + for (let i = 0; i < 1400; i++) { + const x = b.x0 + rnd() * w, y = b.y0 + rnd() * h; + ctx.fillStyle = rnd() < 0.55 ? 'rgba(0,0,0,0.07)' : 'rgba(190,255,215,0.025)'; + ctx.beginPath(); ctx.ellipse(x, y, 4 + rnd() * 16, 2 + rnd() * 7, rnd() * 3, 0, Math.PI * 2); ctx.fill(); + } + ctx.fillStyle = noisePattern(ctx, 200, 24); + ctx.fillRect(b.x0, b.y0, w, h); + // tooled gold border, double line with corner flourishes + ctx.strokeStyle = 'rgba(214,176,90,0.55)'; ctx.lineWidth = 2.4; + rr(ctx, b.x0 + 22, b.y0 + 22, w - 44, h - 44, 6); ctx.stroke(); + ctx.strokeStyle = 'rgba(214,176,90,0.32)'; ctx.lineWidth = 1.2; + rr(ctx, b.x0 + 30, b.y0 + 30, w - 60, h - 60, 4); ctx.stroke(); + for (const [cx, cy, sx, sy] of [[b.x0 + 30, b.y0 + 30, 1, 1], [b.x1 - 30, b.y0 + 30, -1, 1], [b.x0 + 30, b.y1 - 30, 1, -1], [b.x1 - 30, b.y1 - 30, -1, -1]]) { + ctx.save(); ctx.translate(cx, cy); ctx.scale(sx, sy); + ctx.strokeStyle = 'rgba(214,176,90,0.5)'; ctx.lineWidth = 1.6; + ctx.beginPath(); ctx.arc(18, 18, 12, Math.PI, Math.PI * 1.5); ctx.stroke(); + ctx.beginPath(); ctx.arc(18, 18, 5, 0, Math.PI * 2); ctx.stroke(); + ctx.restore(); + } + ctx.restore(); + // oxblood leather corner pieces + for (const [cx, cy, sx, sy] of [[b.x0, b.y0, 1, 1], [b.x1, b.y0, -1, 1], [b.x0, b.y1, 1, -1], [b.x1, b.y1, -1, -1]]) { + ctx.save(); ctx.translate(cx, cy); ctx.scale(sx, sy); + ctx.beginPath(); ctx.moveTo(-4, -4); ctx.lineTo(96, -4); ctx.lineTo(-4, 96); ctx.closePath(); + const cg = ctx.createLinearGradient(0, 0, 60, 60); + cg.addColorStop(0, '#6a1c1a'); cg.addColorStop(1, '#3a0d0c'); + ctx.fillStyle = cg; + ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 8; ctx.shadowOffsetX = 2 * sx; ctx.shadowOffsetY = 3 * sy; + ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.strokeStyle = 'rgba(214,176,90,0.55)'; ctx.lineWidth = 1.4; + ctx.beginPath(); ctx.moveTo(84, 4); ctx.lineTo(4, 84); ctx.stroke(); + ctx.restore(); + } +} + +function slot(ctx, pose, { tray = false } = {}) { + const x = pose.x - CW / 2, y = pose.y - CH / 2; + ctx.save(); + rr(ctx, x - 6, y - 6, CW + 12, CH + 12, 14); + ctx.fillStyle = tray ? 'rgba(10,22,16,0.55)' : 'rgba(6,16,11,0.5)'; + ctx.fill(); + // inner bevel: dark top-left, light bottom-right + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(0,0,0,0.55)'; + rr(ctx, x - 4, y - 4, CW + 8, CH + 8, 12); ctx.stroke(); + ctx.lineWidth = 1.4; + ctx.strokeStyle = tray ? 'rgba(214,176,90,0.55)' : 'rgba(214,176,90,0.3)'; + rr(ctx, x + 4, y + 4, CW - 8, CH - 8, 9); ctx.stroke(); + ctx.restore(); +} + +function brassClip(ctx, x, y) { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 6; ctx.shadowOffsetY = 3; + const g = ctx.createLinearGradient(x - 22, y - 8, x + 22, y + 8); + g.addColorStop(0, '#fff0b0'); g.addColorStop(0.4, '#c9973c'); g.addColorStop(1, '#6a4612'); + rr(ctx, x - 22, y - 9, 44, 18, 7); + ctx.fillStyle = g; ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.strokeStyle = '#4a300a'; ctx.lineWidth = 1.2; ctx.stroke(); + ctx.fillStyle = 'rgba(60,36,6,0.8)'; + ctx.beginPath(); ctx.arc(x, y, 3.2, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); +} + +function slots(ctx) { + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + for (let i = 0; i < 4; i++) { + const p = cellPose(i); + slot(ctx, p); + ctx.font = '13px "Julius Sans One", serif'; + ctx.fillStyle = 'rgba(214,176,90,0.42)'; + ctx.fillText('FREE CELL', p.x, p.y + 4); + brassClip(ctx, p.x, p.y - CH / 2 - 2); + } + FOUNDATION_ORDER.forEach((suit, i) => { + const p = foundPose(i); + slot(ctx, p, { tray: true }); + drawSuit(ctx, suit, p.x, p.y - 6, 50, 'rgba(214,176,90,0.36)'); + ctx.font = '22px Georgia, serif'; + ctx.fillStyle = 'rgba(214,176,90,0.45)'; + ctx.fillText('A', p.x, p.y + 46); + }); + // section captions tooled into the leather + ctx.font = '15px "Julius Sans One", serif'; + ctx.fillStyle = 'rgba(214,176,90,0.5)'; + ctx.fillText('— FREE CELLS —', (cellPose(0).x + cellPose(3).x) / 2, cellPose(0).y - CH / 2 - 26); + ctx.fillText('— FOUNDATIONS —', (foundPose(0).x + foundPose(3).x) / 2, foundPose(0).y - CH / 2 - 26); + // faint spots where the columns stand + for (let c = 0; c < 8; c++) { + const x = colX(c) - CW / 2, y = TAB_TOP - CH / 2; + ctx.strokeStyle = 'rgba(214,176,90,0.16)'; + ctx.lineWidth = 1.4; + ctx.setLineDash([6, 6]); + rr(ctx, x, y, CW, CH, 9); ctx.stroke(); + ctx.setLineDash([]); + } +} + +// ── Lamp, light, desk things ───────────────────────────────────────────────── +function light(ctx) { + // the lamp's pool across the blotter, and darkness pooling at the edges + const p = ctx.createRadialGradient(POOL.x, POOL.y, 40, POOL.x, POOL.y, 900); + p.addColorStop(0, 'rgba(255,226,170,0.20)'); + p.addColorStop(0.5, 'rgba(255,210,150,0.07)'); + p.addColorStop(1, 'rgba(255,210,150,0)'); + ctx.fillStyle = p; + ctx.fillRect(0, WALL_H, W, H - WALL_H); + const l = ctx.createRadialGradient(LAMP.x, LAMP.y + 70, 10, LAMP.x, LAMP.y + 70, 420); + l.addColorStop(0, 'rgba(255,230,170,0.30)'); + l.addColorStop(1, 'rgba(255,230,170,0)'); + ctx.fillStyle = l; + ctx.fillRect(0, WALL_H, W, H - WALL_H); + const v = ctx.createRadialGradient(W * 0.55, H * 0.55, 380, W * 0.55, H * 0.55, 1250); + v.addColorStop(0, 'rgba(0,0,0,0)'); + v.addColorStop(1, 'rgba(0,0,0,0.6)'); + ctx.fillStyle = v; + ctx.fillRect(0, 0, W, H); +} + +function lamp(ctx) { + const { x, y } = LAMP; + ctx.save(); + // base shadow + brass base + ctx.fillStyle = 'rgba(0,0,0,0.45)'; + ctx.beginPath(); ctx.ellipse(x + 10, y + 128, 92, 26, 0, 0, Math.PI * 2); ctx.fill(); + let g = ctx.createLinearGradient(x - 80, 0, x + 80, 0); + g.addColorStop(0, '#5a3a0e'); g.addColorStop(0.35, '#f2d58a'); g.addColorStop(0.6, '#b88732'); g.addColorStop(1, '#4a2e08'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.ellipse(x, y + 118, 80, 22, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#3a2406'; ctx.lineWidth = 1.5; ctx.stroke(); + // stem + g = ctx.createLinearGradient(x - 8, 0, x + 8, 0); + g.addColorStop(0, '#6a4612'); g.addColorStop(0.5, '#ffe9a8'); g.addColorStop(1, '#6a4612'); + ctx.fillStyle = g; + ctx.fillRect(x - 7, y + 10, 14, 104); + // green glass shade (seen from the front, slightly from above) + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 6; + ctx.beginPath(); + ctx.moveTo(x - 112, y + 22); ctx.quadraticCurveTo(x - 104, y - 44, x, y - 50); + ctx.quadraticCurveTo(x + 104, y - 44, x + 112, y + 22); + ctx.closePath(); + g = ctx.createLinearGradient(0, y - 50, 0, y + 22); + g.addColorStop(0, '#2c8a4e'); g.addColorStop(0.55, '#0f5a2c'); g.addColorStop(1, '#06341a'); + ctx.fillStyle = g; ctx.fill(); + ctx.shadowColor = 'transparent'; + // glass highlight + ctx.beginPath(); + ctx.moveTo(x - 80, y - 4); ctx.quadraticCurveTo(x - 70, y - 38, x - 10, y - 42); + ctx.quadraticCurveTo(x - 60, y - 30, x - 66, y + 2); ctx.closePath(); + ctx.fillStyle = 'rgba(220,255,225,0.35)'; ctx.fill(); + // brass rim + the warm glow under the shade + ctx.fillStyle = '#c9973c'; + ctx.fillRect(x - 114, y + 18, 228, 8); + const glow = ctx.createRadialGradient(x, y + 30, 4, x, y + 30, 130); + glow.addColorStop(0, 'rgba(255,240,190,0.85)'); + glow.addColorStop(1, 'rgba(255,240,190,0)'); + ctx.fillStyle = glow; + ctx.beginPath(); ctx.ellipse(x, y + 34, 120, 22, 0, 0, Math.PI * 2); ctx.fill(); + // pull chain + ctx.strokeStyle = '#d9b45a'; ctx.lineWidth = 1.2; + ctx.beginPath(); ctx.moveTo(x + 60, y + 26); ctx.lineTo(x + 60, y + 74); ctx.stroke(); + ctx.fillStyle = '#d9b45a'; ctx.beginPath(); ctx.arc(x + 60, y + 78, 4, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); +} + +function teacup(ctx, x, y) { + ctx.save(); + ctx.fillStyle = 'rgba(0,0,0,0.45)'; + ctx.beginPath(); ctx.ellipse(x + 8, y + 10, 84, 64, 0, 0, Math.PI * 2); ctx.fill(); + // saucer + let g = ctx.createRadialGradient(x - 20, y - 20, 10, x, y, 80); + g.addColorStop(0, '#fbf6ea'); g.addColorStop(1, '#cfc6b0'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.ellipse(x, y, 78, 60, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(40,90,60,0.7)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.ellipse(x, y, 68, 52, 0, 0, Math.PI * 2); ctx.stroke(); + // cup, from above + ctx.fillStyle = '#f6f0e2'; + ctx.beginPath(); ctx.ellipse(x, y - 4, 46, 40, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(40,90,60,0.8)'; ctx.lineWidth = 2.5; ctx.stroke(); + g = ctx.createRadialGradient(x - 8, y - 12, 4, x, y - 4, 40); + g.addColorStop(0, '#9a5a24'); g.addColorStop(1, '#4a2208'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.ellipse(x, y - 4, 38, 32, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = 'rgba(255,240,210,0.35)'; + ctx.beginPath(); ctx.ellipse(x - 12, y - 16, 12, 5, -0.4, 0, Math.PI * 2); ctx.fill(); + // handle + ctx.strokeStyle = '#efe7d4'; ctx.lineWidth = 7; + ctx.beginPath(); ctx.arc(x + 54, y - 2, 12, -1.4, 1.4); ctx.stroke(); + ctx.restore(); +} + +function pen(ctx, x, y, rot) { + ctx.save(); + ctx.translate(x, y); ctx.rotate(rot); + ctx.fillStyle = 'rgba(0,0,0,0.45)'; + rr(ctx, -96, -4, 196, 16, 8); ctx.fill(); + const g = ctx.createLinearGradient(0, -8, 0, 8); + g.addColorStop(0, '#5a1a1a'); g.addColorStop(0.4, '#b23a30'); g.addColorStop(1, '#3a0a0a'); + ctx.fillStyle = g; + rr(ctx, -100, -8, 150, 16, 8); ctx.fill(); + ctx.fillStyle = '#d9b45a'; + ctx.fillRect(-20, -8, 6, 16); + ctx.fillRect(-96, -2, 60, 3); + ctx.beginPath(); ctx.moveTo(50, -6); ctx.lineTo(92, 0); ctx.lineTo(50, 6); ctx.closePath(); + ctx.fillStyle = '#e8d08a'; ctx.fill(); + ctx.restore(); +} + +function glasses(ctx, x, y) { + ctx.save(); + ctx.strokeStyle = 'rgba(0,0,0,0.4)'; ctx.lineWidth = 6; + for (const dx of [-38, 38]) { ctx.beginPath(); ctx.ellipse(x + dx + 5, y + 6, 30, 24, 0, 0, Math.PI * 2); ctx.stroke(); } + ctx.strokeStyle = '#c9a050'; ctx.lineWidth = 3.5; + for (const dx of [-38, 38]) { + ctx.beginPath(); ctx.ellipse(x + dx, y, 30, 24, 0, 0, Math.PI * 2); ctx.stroke(); + ctx.fillStyle = 'rgba(220,235,255,0.08)'; ctx.fill(); + } + ctx.beginPath(); ctx.moveTo(x - 9, y - 4); ctx.quadraticCurveTo(x, y - 12, x + 9, y - 4); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x - 68, y - 4); ctx.lineTo(x - 120, y + 18); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x + 68, y - 4); ctx.lineTo(x + 112, y + 30); ctx.stroke(); + ctx.restore(); +} + +// ── The wall strip ─────────────────────────────────────────────────────────── +function wall(ctx) { + const g = ctx.createLinearGradient(0, 0, 0, WALL_H); + g.addColorStop(0, '#1d120a'); g.addColorStop(1, '#2a190d'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, WALL_H); + // raised oak panels + for (let x = 0; x < W; x += 120) { + ctx.fillStyle = 'rgba(255,200,140,0.04)'; + rr(ctx, x + 12, 14, 96, WALL_H - 40, 4); ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 2; + rr(ctx, x + 12, 14, 96, WALL_H - 40, 4); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,200,140,0.07)'; ctx.lineWidth = 1; + rr(ctx, x + 15, 17, 90, WALL_H - 46, 3); ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 128, 16); + ctx.fillRect(0, 0, W, WALL_H); + books(ctx, 392, 630); + books(ctx, 1808, W); + windowPanes(ctx); + mantelClock(ctx); + // the desk's back edge + const e = ctx.createLinearGradient(0, WALL_H - 14, 0, WALL_H + 10); + e.addColorStop(0, '#5a3418'); e.addColorStop(0.5, '#8a5a2c'); e.addColorStop(1, '#2a160a'); + ctx.fillStyle = e; + ctx.fillRect(0, WALL_H - 12, W, 20); + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + ctx.fillRect(0, WALL_H + 8, W, 6); +} + +function books(ctx, x0, x1) { + const top = 10, base = WALL_H - 14; + ctx.fillStyle = '#140b05'; + ctx.fillRect(x0 - 6, top - 4, x1 - x0 + 12, base - top + 4); + const spines = ['#5a1a1a', '#1f3a2a', '#1a2a4a', '#6a4a1a', '#3a1a10', '#4a1f3a', '#7a6a42', '#222']; + let x = x0; + while (x < x1 - 10) { + const w = 14 + Math.floor(rnd() * 20); + if (x + w > x1) break; + const h = base - top - 6 - Math.floor(rnd() * 22); + ctx.fillStyle = spines[Math.floor(rnd() * spines.length)]; + ctx.fillRect(x, base - h, w - 2, h); + ctx.fillStyle = 'rgba(217,180,90,0.35)'; + ctx.fillRect(x + 3, base - h + 10, w - 8, 2); + ctx.fillRect(x + 3, base - 18, w - 8, 2); + ctx.fillStyle = 'rgba(0,0,0,0.4)'; + ctx.fillRect(x + w - 5, base - h, 3, h); + x += w + (rnd() < 0.1 ? 18 : 0); + } + ctx.fillStyle = '#4a2a12'; + ctx.fillRect(x0 - 6, base, x1 - x0 + 12, 6); +} + +function windowPanes(ctx) { + const wdw = WINDOW, w = wdw.x1 - wdw.x0, h = wdw.y1 - wdw.y0; + // velvet curtains either side + for (const [cx, dir] of [[wdw.x0 - 34, 1], [wdw.x1 + 34, -1]]) { + const g = ctx.createLinearGradient(cx - 40, 0, cx + 40, 0); + g.addColorStop(0, '#3a0a0c'); g.addColorStop(0.5, '#7a1a1e'); g.addColorStop(1, '#3a0a0c'); + ctx.fillStyle = g; + ctx.fillRect(cx - 44, 0, 88, WALL_H - 12); + for (let k = -30; k <= 30; k += 15) { + ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.moveTo(cx + k, 0); ctx.lineTo(cx + k + dir * 4, WALL_H - 12); ctx.stroke(); + } + } + // night beyond the glass: deep blue, a few blurred city lights + const sky = ctx.createLinearGradient(0, wdw.y0, 0, wdw.y1); + sky.addColorStop(0, '#0a1424'); sky.addColorStop(1, '#16243a'); + ctx.fillStyle = sky; + ctx.fillRect(wdw.x0, wdw.y0, w, h); + for (let i = 0; i < 26; i++) { + const x = wdw.x0 + rnd() * w, y = wdw.y0 + h * 0.55 + rnd() * h * 0.4; + const r = 3 + rnd() * 7; + const gl = ctx.createRadialGradient(x, y, 0, x, y, r * 3); + const col = rnd() < 0.7 ? '255,200,120' : '180,210,255'; + gl.addColorStop(0, `rgba(${col},0.55)`); gl.addColorStop(1, `rgba(${col},0)`); + ctx.fillStyle = gl; + ctx.beginPath(); ctx.arc(x, y, r * 3, 0, Math.PI * 2); ctx.fill(); + } + // beaded droplets on the glass + for (let i = 0; i < 160; i++) { + const x = wdw.x0 + rnd() * w, y = wdw.y0 + rnd() * h, r = 0.8 + rnd() * 2.2; + ctx.fillStyle = 'rgba(200,220,255,0.18)'; + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = 'rgba(255,255,255,0.25)'; + ctx.beginPath(); ctx.arc(x - r * 0.3, y - r * 0.3, r * 0.35, 0, Math.PI * 2); ctx.fill(); + } + // mullions + frame + ctx.fillStyle = '#2a180c'; + ctx.fillRect(wdw.x0 + w / 3 - 4, wdw.y0, 8, h); + ctx.fillRect(wdw.x0 + (2 * w) / 3 - 4, wdw.y0, 8, h); + ctx.fillRect(wdw.x0, wdw.y0 + h / 2 - 3, w, 6); + ctx.strokeStyle = '#3a2210'; ctx.lineWidth = 10; + ctx.strokeRect(wdw.x0 - 4, wdw.y0 - 6, w + 8, h + 8); + // the sill + const sill = ctx.createLinearGradient(0, wdw.y1, 0, wdw.y1 + 10); + sill.addColorStop(0, '#6a4224'); sill.addColorStop(1, '#2a160a'); + ctx.fillStyle = sill; + ctx.fillRect(wdw.x0 - 20, wdw.y1, w + 40, 10); +} + +function mantelClock(ctx) { + const { x, y, r } = CLOCK; + ctx.save(); + // the wooden case: an arched top on a plinth + ctx.shadowColor = 'rgba(0,0,0,0.7)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 4; + const g = ctx.createLinearGradient(x - 90, 0, x + 90, 0); + g.addColorStop(0, '#2a1408'); g.addColorStop(0.5, '#6a3a18'); g.addColorStop(1, '#2a1408'); + ctx.fillStyle = g; + ctx.beginPath(); + ctx.moveTo(x - 92, WALL_H - 14); ctx.lineTo(x - 92, y + 6); + ctx.quadraticCurveTo(x - 92, y - r - 22, x, y - r - 24); + ctx.quadraticCurveTo(x + 92, y - r - 22, x + 92, y + 6); + ctx.lineTo(x + 92, WALL_H - 14); ctx.closePath(); + ctx.fill(); + ctx.shadowColor = 'transparent'; + // brass bezel + ivory face + const bz = ctx.createLinearGradient(x - r, y - r, x + r, y + r); + bz.addColorStop(0, '#fff0b0'); bz.addColorStop(0.5, '#c9973c'); bz.addColorStop(1, '#5a3a0a'); + ctx.fillStyle = bz; + ctx.beginPath(); ctx.arc(x, y, r + 6, 0, Math.PI * 2); ctx.fill(); + const face = ctx.createRadialGradient(x - 12, y - 14, 6, x, y, r); + face.addColorStop(0, '#fbf6e6'); face.addColorStop(1, '#d9cfb4'); + ctx.fillStyle = face; + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + // minute ticks + hour numerals + ctx.strokeStyle = '#2a2014'; + for (let i = 0; i < 60; i++) { + const a = (i / 60) * Math.PI * 2; + const big = i % 5 === 0; + ctx.lineWidth = big ? 2 : 0.8; + ctx.beginPath(); + ctx.moveTo(x + Math.sin(a) * (r - (big ? 9 : 5)), y - Math.cos(a) * (r - (big ? 9 : 5))); + ctx.lineTo(x + Math.sin(a) * (r - 2), y - Math.cos(a) * (r - 2)); + ctx.stroke(); + } + ctx.fillStyle = '#2a2014'; + ctx.font = '11px Georgia, serif'; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + const nums = ['XII', 'III', 'VI', 'IX']; + nums.forEach((n, i) => { + const a = (i / 4) * Math.PI * 2; + ctx.fillText(n, x + Math.sin(a) * (r - 19), y - Math.cos(a) * (r - 19)); + }); + ctx.font = '7px Georgia, serif'; + ctx.fillText('ELAPSED', x, y + 18); + // the plinth feet + ctx.fillStyle = '#d9b45a'; + ctx.fillRect(x - 96, WALL_H - 18, 192, 5); + ctx.restore(); +} + +// ── Small textures ─────────────────────────────────────────────────────────── +function bakeBack(scene) { + const cw = 96 * RES, ch = 134 * RES; + const c = canvas(cw, ch); + const ctx = c.getContext('2d'); + rr(ctx, 0, 0, cw, ch, 14); + ctx.fillStyle = '#f4eedc'; ctx.fill(); + rr(ctx, 8, 8, cw - 16, ch - 16, 10); + const g = ctx.createLinearGradient(0, 0, cw, ch); + g.addColorStop(0, '#1e5a3a'); g.addColorStop(1, '#0c3220'); + ctx.fillStyle = g; ctx.fill(); + ctx.save(); ctx.clip(); + ctx.strokeStyle = 'rgba(217,180,90,0.28)'; ctx.lineWidth = 1.4; + for (let k = -ch; k < cw + ch; k += 14) { + ctx.beginPath(); ctx.moveTo(k, 0); ctx.lineTo(k - ch, ch); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(k - ch, 0); ctx.lineTo(k, ch); ctx.stroke(); + } + ctx.restore(); + ctx.strokeStyle = '#d9b45a'; ctx.lineWidth = 3; + rr(ctx, 16, 16, cw - 32, ch - 32, 8); ctx.stroke(); + ctx.fillStyle = '#0c3220'; + ctx.beginPath(); ctx.ellipse(cw / 2, ch / 2, 40, 52, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#d9b45a'; ctx.lineWidth = 2.5; ctx.stroke(); + ctx.fillStyle = '#d9b45a'; + ctx.font = 'bold 44px Georgia, serif'; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('F', cw / 2, ch / 2 + 2); + scene.textures.addCanvas('freecell-back', c); +} + +function bakeDealCard(scene) { + const { w, h } = DEAL_CARD; + const c = canvas(w + 24, h + 24); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 14; ctx.shadowOffsetY = 6; + ctx.fillStyle = '#f3ecd8'; + ctx.fillRect(12, 10, w, h); + ctx.restore(); + ctx.fillStyle = noisePattern(ctx, 96, 10); + ctx.fillRect(12, 10, w, h); + ctx.strokeStyle = 'rgba(200,60,60,0.55)'; ctx.lineWidth = 1.6; + ctx.beginPath(); ctx.moveTo(12, 64); ctx.lineTo(12 + w, 64); ctx.stroke(); + ctx.strokeStyle = 'rgba(80,120,190,0.3)'; ctx.lineWidth = 1; + for (let y = 96; y < h; y += 32) { ctx.beginPath(); ctx.moveTo(12, y); ctx.lineTo(12 + w, y); ctx.stroke(); } + // a brass paper clip + ctx.strokeStyle = '#c9a050'; ctx.lineWidth = 3; + rr(ctx, w - 30, 0, 18, 56, 9); ctx.stroke(); + rr(ctx, w - 26, 8, 10, 40, 5); ctx.stroke(); + scene.textures.addCanvas('freecell-dealcard', c); +} + +function bakePlaque(scene) { + const { w, h } = PLAQUE; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + rr(ctx, 2, 2, w - 4, h - 4, 10); + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, '#f2d58a'); g.addColorStop(0.45, '#c9973c'); g.addColorStop(1, '#6a4612'); + ctx.fillStyle = g; ctx.fill(); + ctx.strokeStyle = '#3a2406'; ctx.lineWidth = 2; ctx.stroke(); + rr(ctx, 9, 9, w - 18, h - 18, 6); + ctx.strokeStyle = 'rgba(60,36,6,0.6)'; ctx.lineWidth = 1.2; ctx.stroke(); + for (const [sx, sy] of [[16, 16], [w - 16, 16], [16, h - 16], [w - 16, h - 16]]) { + ctx.fillStyle = '#5a3a0a'; ctx.beginPath(); ctx.arc(sx, sy, 3, 0, Math.PI * 2); ctx.fill(); + } + scene.textures.addCanvas('freecell-plaque', c); +} + +function bakeBox(scene) { + const bw = Math.round(CW + 26), bh = Math.round(CH + 26); + const c = canvas(bw + 30, bh + 30); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 7; + rr(ctx, 15, 12, bw, bh, 10); + ctx.fillStyle = '#4a1414'; ctx.fill(); + ctx.restore(); + rr(ctx, 25, 22, bw - 20, bh - 20, 7); + ctx.fillStyle = '#1a0606'; ctx.fill(); + ctx.strokeStyle = '#d9b45a'; ctx.lineWidth = 2; + rr(ctx, 15, 12, bw, bh, 10); ctx.stroke(); + scene.textures.addCanvas('freecell-box', c); +} + +function bakeRoomCanvas(scene) { + seed = 11; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + walnut(ctx); + wall(ctx); + blotter(ctx); + slots(ctx); + light(ctx); + lamp(ctx); + teacup(ctx, 1720, 610); + pen(ctx, 1690, 740, -0.35); + glasses(ctx, 210, 960); + scene.textures.addCanvas('freecell-room', c); +} + +export async function prepareFreecellArt(scene) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('freecell-back')) bakeBack(scene); + if (!scene.textures.exists('freecell-dealcard')) bakeDealCard(scene); + if (!scene.textures.exists('freecell-plaque')) bakePlaque(scene); + if (!scene.textures.exists('freecell-box')) bakeBox(scene); + if (!scene.textures.exists('freecell-room')) bakeRoomCanvas(scene); + return 'freecell-room'; +} + +export { mix, S, DECK }; diff --git a/src/games/freecell/FreecellGame.js b/src/games/freecell/FreecellGame.js index f24733d..11c6e58 100644 --- a/src/games/freecell/FreecellGame.js +++ b/src/games/freecell/FreecellGame.js @@ -1,609 +1,726 @@ import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { api } from '../../services/api.js'; -import { FreecellEngine, freshDeck } from './FreecellLogic.js'; +import { + SolitaireScene, DEPTH as D, CX, CY, COLORS, Button, playSound, playSoundEx, SFX, FONT_HAND, +} from '../../ui/solitaire/SolitaireScene.js'; +import { hitIndex, inPose, inRect } from '../../ui/solitaire/SolitaireGeometry.js'; +import { formatTime, loadStats } from '../../ui/solitaire/SolitaireStats.js'; +import { RainBed, clockTick, thunder } from '../../ui/solitaire/SolitaireSound.js'; +import { jitterFor } from '../../ui/casino/CasinoCards.js'; +import { + FreecellEngine, FOUNDATION_ORDER, dailyDealNumber, randomDealNumber, MAX_DEAL, isRed, +} from './FreecellLogic.js'; +import { FreecellSolver, stateFromEngine, exactKey } from './FreecellSolver.js'; +import { + CW, CH, WINDOW, CLOCK, PLAQUE, DEAL_CARD, DECK, LAMP, POOL, + cellPose, foundPose, foundIndex, foundCardPose, columnPosesFor, columnZone, cellZone, foundZone, colX, TAB_TOP, +} from './FreecellTable.js'; +import { prepareFreecellArt } from './FreecellArt.js'; -const CARD_W = 100; -const CARD_H = 140; -const CARD_R = 10; -const COL_GAP = 132; -const START_X = 448; -const colX = (c) => START_X + c * COL_GAP; +// ─── Freecell — the Night Study ─────────────────────────────────────────────── +// A late-night desk: rain on the window, the banker's lamp, a ticking mantel +// clock that keeps the game time. Rules in FreecellLogic.js (pure); hints and +// the "can this still be won?" check come from FreecellSolver.js, run a few +// milliseconds per frame. Input, undo, the cascade and records come from the +// shared solitaire layer (src/ui/solitaire/). -const FC_Y = 100; // freecell row centre-y -const HOME_Y = 100; // foundation row centre-y -const TAB_Y = 280; // tableau top card centre-y -const FAN = 28; // px per fanned card in a column +const DEFAULTS = { autoPlay: true, analysis: true, tick: true }; +const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣' }; +const SUIT_NAME = { s: 'spades', h: 'hearts', d: 'diamonds', c: 'clubs' }; +const RANK_NAME = { 1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King' }; +const rankName = (v) => RANK_NAME[v] ?? String(v); +const cardName = (c) => `${c.label}${SUIT_SYM[c.suit]}`; +const INK = '#23324a', INK_RED = '#a32424', INK_GREEN = '#2f6a3a', INK_GREY = '#6c6450'; +const BG_SLICE_MS = 6; -const FELT = 0x0e3b2a; -const SEL = 0x2ec28a; -const HINT = 0xc8a84b; - -const SUITS_ORDER = ['s', 'h', 'd', 'c']; -const SUIT_GLYPH = { s: '♠', h: '♥', d: '♦', c: '♣' }; - -const D = { felt: -2, table: -1, card: 10, ui: 30, banner: 34, overlay: 60, overlayUI: 62 }; - -export default class FreecellGame extends Phaser.Scene { +export default class FreecellGame extends SolitaireScene { constructor() { super('FreecellGame'); } init(data) { - this.gameDef = data.game; - this.engine = null; - this.sel = null; // { kind:'tableau', col, fromIdx } | { kind:'freecell', fcIdx } - this.animating = false; - this.autoRunning = false; - this.recorded = false; - this.overlayObjs = []; - this.overlayUp = false; - this.pulse = null; - - this.board = null; - this.cardSprites = new Map(); - this.dropZones = []; - this.potentialDrag = null; - this.dragState = null; - this.dropHighlight = null; + this.initSolitaire(data, { settingsKey: 'freecell-settings', defaults: DEFAULTS, slug: 'freecell' }); + this.dealKind = 'random'; + this.analysis = null; + this.verdict = 'checking'; + this.path = null; // exact position key → index of the next move on a known winning line + this.pathMoves = null; + this.hintPending = false; + this.finishing = false; + this.dealEntry = null; + this.lastSecond = -1; } - create() { - try { - const music = this.cache.json.get('music'); - if (music?.tracks) new MusicPlayer(this, music.tracks); - } catch (_) { /* optional */ } + faceFrame(card) { return { key: 'casino-cards', frame: card.key }; } - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, FELT).setDepth(D.felt); - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH - 24, GAME_HEIGHT - 24, FELT) - .setStrokeStyle(3, COLORS.accent, 0.35).setDepth(D.table); - - this.add.text(40, 28, 'FREECELL', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex, - }).setDepth(D.ui); - - this.movesText = this.add.text(24, GAME_HEIGHT - 24, 'Moves: 0', { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0, 1).setDepth(D.ui); - - this.stuckBanner = this.add.text(GAME_WIDTH / 2, 200, 'No more moves!', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.banner).setVisible(false); - - this.board = this.add.container(0, 0).setDepth(D.card); - - this.autoCompleteBtn = new Button(this, GAME_WIDTH / 2, 1018, 'Auto-Complete', () => this.onAutoComplete(), - { width: 280, height: 60, fontSize: 24 }); - this.autoCompleteBtn.setDepth(D.ui).setVisible(false); - - this.newGameBtn = new Button(this, GAME_WIDTH / 2 - 180, 1018, 'New Game', () => this.startGame(), - { width: 240, height: 60, fontSize: 24 }); - this.newGameBtn.setDepth(D.ui).setVisible(false); - - this.leaveBtn = new Button(this, GAME_WIDTH - 110, 1042, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 160, height: 54, fontSize: 22 }); - this.leaveBtn.setDepth(D.ui); - - this.setupDrag(); - this.startGame(); + async create() { + this.createTableBase(); + const key = await prepareFreecellArt(this); + if (!this.alive()) return; + this.backKey = 'freecell-back'; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildRoomLife(); + this.buildDeskCard(); + this.buildPlaque(); + this.buildSolitaireBase({ keysText: 'Drag or click a card · Z undo · Y redo · H hint\nSpace finish · N new deal · R restart · Esc menu' }); + this.buildDock(); + this.rain = new RainBed(this); + this.rain.setOn(this.settings.ambience); + this.events.once('shutdown', () => { this.rain?.stop(); this.lightningTimer?.remove(false); }); + this.scheduleLightning(); + this.dealNew(randomDealNumber(), 'random'); } - startGame() { - this.sel = null; - this.animating = false; - this.autoRunning = false; - this.recorded = false; - this.overlayUp = false; - this.clearOverlay(); - this.stuckBanner.setVisible(false); - this.newGameBtn.setVisible(false); - if (this.pulse) { this.pulse.stop(); this.pulse = null; } - this.engine = new FreecellEngine(freshDeck()); - playSound(this, SFX.CARD_SHUFFLE); - this.refresh(); - this.dealAnimation(); + // ── Room life: rain, the clock, lightning, the lamp ────────────────────── + buildRoomLife() { + this.rainG = this.add.graphics().setDepth(D.table + 0.2); + const w = WINDOW.x1 - WINDOW.x0; + this.drops = Array.from({ length: 46 }, () => ({ + x: WINDOW.x0 + Math.random() * w, y: WINDOW.y0 + Math.random() * (WINDOW.y1 - WINDOW.y0), + v: 0.7 + Math.random() * 2.2, len: 6 + Math.random() * 16, wob: Math.random() * 6.28, + })); + this.flashWin = this.add.rectangle((WINDOW.x0 + WINDOW.x1) / 2, (WINDOW.y0 + WINDOW.y1) / 2, w, WINDOW.y1 - WINDOW.y0, 0xdde8ff, 0) + .setDepth(D.table + 0.3); + this.flashRoom = this.add.rectangle(CX, CY, 1920, 1080, 0xb8c8ff, 0).setDepth(D.table + 0.4).setBlendMode(Phaser.BlendModes.ADD); + this.dimmer = this.add.rectangle(CX, CY, 1920, 1080, 0x000000, 0).setDepth(D.table + 0.5); + this.lampGlow = this.add.image(POOL.x, POOL.y, 'ct-spot').setDisplaySize(1500, 1050).setTint(0xffd9a0) + .setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.1).setDepth(D.table + 0.1); + this.clockG = this.add.graphics().setDepth(D.table + 0.3); + this.drawClock(0); } - // ── card rendering helpers (same as SolitaireTourGame) ──────────────────── - - drawFace(container, card, faceUp, selected, hint) { - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); - if (!faceUp) { - g.fillStyle(0x16324f, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, COLORS.accent, 0.7); g.strokeRoundedRect(x + 5, y + 5, CARD_W - 10, CARD_H - 10, CARD_R - 2); - container.add(g); - container.add(this.add.text(0, 0, '✦', { fontFamily: 'serif', fontSize: '40px', color: '#caa84b' }).setOrigin(0.5).setAlpha(0.55)); - return; + tickRain(delta) { + const k = Math.min(3, delta / 16.67); + const g = this.rainG; + g.clear(); + for (const d of this.drops) { + d.y += d.v * k; + d.wob += 0.05 * k; + if (d.y - d.len > WINDOW.y1) { d.y = WINDOW.y0 - Math.random() * 30; d.x = WINDOW.x0 + Math.random() * (WINDOW.x1 - WINDOW.x0); } + const x = d.x + Math.sin(d.wob) * 1.2; + const y0 = Math.max(WINDOW.y0, d.y - d.len), y1 = Math.min(WINDOW.y1 - 2, d.y); + if (y1 <= y0) continue; + g.lineStyle(1.6, 0xcfe0ff, 0.22); + g.lineBetween(x, y0, x + 0.6, y1); + g.fillStyle(0xe8f0ff, 0.42); + g.fillCircle(x + 0.6, y1, 1.8); } - g.fillStyle(0xfbf6e7, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - const rimColor = selected ? SEL : hint ? HINT : 0xcc803a; - const rimW = selected ? 5 : hint ? 4 : 2; - g.lineStyle(rimW, rimColor, selected || hint ? 1 : 0.5); - g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - container.add(g); - - const col = card.isRed ? '#c0392b' : '#1a1208'; - container.add(this.add.text(x + 9, y + 6, card.label, { fontFamily: 'Righteous', fontSize: '24px', color: col })); - container.add(this.add.text(x + 11, y + 35, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '22px', color: col })); - container.add(this.add.text(0, 6, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '48px', color: col }).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 9, y + CARD_H - 6, card.label, { fontFamily: 'Righteous', fontSize: '24px', color: col }).setOrigin(1, 1)); } - card(cardObj, x, y, opts = {}) { - const { faceUp = true, selected = false, hint = false, dim = false, onClick = null, onDown = null } = opts; - const c = this.add.container(x, selected ? y - 10 : y); - c.isCard = true; - this.drawFace(c, cardObj, faceUp, selected, hint); - if (dim) c.setAlpha(0.4); - if (onClick || onDown) { - c.setInteractive(new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), Phaser.Geom.Rectangle.Contains); - c.input.cursor = onDown ? 'grab' : 'pointer'; - if (onClick) c.on('pointerdown', onClick); - if (onDown) c.on('pointerdown', (pointer) => onDown(c, pointer)); - } - this.board.add(c); - return c; + scheduleLightning() { + this.lightningTimer?.remove(false); + this.lightningTimer = this.time.delayedCall(55000 + Math.random() * 90000, () => { + if (!this.alive()) return; + if (this.settings.ambience && !this.modal) this.lightning(); + this.scheduleLightning(); + }); } - slot(x, y, label, onClick = null) { - const c = this.add.container(x, y); - const g = this.add.graphics(); - g.lineStyle(2, COLORS.accent, 0.4); - g.strokeRoundedRect(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H, CARD_R); - c.add(g); - if (label) c.add(this.add.text(0, 0, label, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, align: 'center' }).setOrigin(0.5)); - if (onClick) { - c.setInteractive(new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), Phaser.Geom.Rectangle.Contains); - c.input.cursor = 'pointer'; - c.on('pointerdown', onClick); - } - this.board.add(c); - return c; + lightning() { + const flash = (delay, a) => this.time.delayedCall(delay, () => { + this.flashWin.setAlpha(a); + this.flashRoom.setAlpha(a * 0.09); + this.tweens.add({ targets: [this.flashWin, this.flashRoom], alpha: 0, duration: 260, ease: 'Cubic.easeOut' }); + }); + flash(0, 0.75); flash(140, 0.45); flash(420, 0.9); + this.time.delayedCall(1300 + Math.random() * 1400, () => thunder(this)); } - // ── board rendering ─────────────────────────────────────────────────────── + drawClock(ms) { + const g = this.clockG; + const { x, y, r } = CLOCK; + const sec = ms / 1000; + g.clear(); + const hand = (frac, len, w, col) => { + const a = frac * Math.PI * 2; + g.lineStyle(w, col, 1); + g.lineBetween(x - Math.sin(a) * len * 0.18, y + Math.cos(a) * len * 0.18, x + Math.sin(a) * len, y - Math.cos(a) * len); + }; + hand(((sec / 3600) % 12) / 12, r * 0.48, 4, 0x1a120a); + hand(((sec / 60) % 60) / 60, r * 0.74, 3, 0x1a120a); + hand((Math.floor(sec) % 60) / 60, r * 0.84, 1.2, 0xa32424); + g.fillStyle(0xc9973c, 1); g.fillCircle(x, y, 3.6); + } - renderBoard() { - this.board.removeAll(true); - this.cardSprites.clear(); - this.dropZones = []; + setLampDim(dim) { + this.tweens.killTweensOf([this.dimmer, this.lampGlow]); + this.tweens.add({ targets: this.dimmer, alpha: dim ? 0.24 : 0, duration: 900 }); + this.tweens.add({ targets: this.lampGlow, alpha: dim ? 0.02 : 0.1, duration: 900 }); + } - const e = this.engine; + // ── The deal card + plaque ─────────────────────────────────────────────── + buildDeskCard() { + const { x, y } = DEAL_CARD; + this.add.image(x, y, 'freecell-dealcard').setRotation(-0.03).setDepth(D.labels); + const c = this.add.container(x, y).setRotation(-0.03).setDepth(D.labels + 0.1); + const L = -DEAL_CARD.w / 2 + 26; + const T = -DEAL_CARD.h / 2; + const t = (yy, size, color, str = '') => { + const o = this.add.text(L, T + yy, str, { fontFamily: FONT_HAND, fontSize: `${size}px`, color }).setOrigin(0, 0.5); + c.add(o); + return o; + }; + this.deskTxt = { + title: t(38, 34, INK), + kind: t(84, 20, INK_GREY), + home: t(118, 24, INK), + cap: t(150, 24, INK), + capWhy: t(178, 17, INK_GREY), + verdict: t(214, 23, INK_GREEN), + verdict2: t(242, 17, INK_GREY), + }; + this.add.image(DECK.x, DECK.y, 'freecell-box').setDepth(D.slots); + this.add.text(DECK.x, DECK.y + CH / 2 + 30, 'THE DECK', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#c9b08a', + }).setOrigin(0.5).setDepth(D.labels).setAlpha(0.6); + this.hoverZone(x, y, DEAL_CARD.w, DEAL_CARD.h, () => this.deskTip()); + } - // Labels - this.board.add(this.add.text(colX(0), FC_Y - CARD_H / 2 - 18, 'Free Cells', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setOrigin(0.5, 1)); - this.board.add(this.add.text(colX(4) + (colX(7) - colX(4)) / 2, HOME_Y - CARD_H / 2 - 18, 'Foundations', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setOrigin(0.5, 1)); + deskTip() { + if (!this.gs) return null; + return { + title: 'How many cards can move?', + lines: [ + { text: 'One card moves at a time — a run "supermoves" by passing' }, + { text: 'through empty free cells and empty columns:' }, + { text: '(free cells + 1) × 2 for each empty column', color: COLORS.goldHex }, + { text: 'Moving INTO an empty column, that column doesn\'t count.', color: COLORS.mutedHex }, + ], + }; + } - // Freecells (cols 0-3) - for (let fc = 0; fc < 4; fc++) { - const x = colX(fc); - const card = e.freecells[fc]; - const isSel = this.sel?.kind === 'freecell' && this.sel.fcIdx === fc; - this.dropZones.push({ cx: x, cy: FC_Y, hw: CARD_W * 0.7, hh: CARD_H * 0.8, hlx: x, hly: FC_Y, kind: 'freecell', idx: fc }); - if (card) { - const sprite = this.card(card, x, FC_Y, { - selected: isSel, - onDown: (_c, pointer) => this.onCardDown({ kind: 'freecell', fcIdx: fc }, pointer), - }); - this.cardSprites.set(card.id, sprite); - } else { - this.slot(x, FC_Y, 'Free', () => this.onSlotClick('freecell', fc)); - } - } + buildPlaque() { + this.add.image(PLAQUE.x, PLAQUE.y, 'freecell-plaque').setDepth(D.labels); + const st = (size) => ({ fontFamily: 'Righteous', fontSize: `${size}px`, color: '#3a2406', stroke: '#f6dc96', strokeThickness: 1 }); + this.timeTxt = this.add.text(PLAQUE.x - 66, PLAQUE.y - 2, '0:00', st(30)).setOrigin(0.5).setDepth(D.labels + 0.1); + this.movesTxt = this.add.text(PLAQUE.x + 72, PLAQUE.y - 2, '0', st(30)).setOrigin(0.5).setDepth(D.labels + 0.1); + const cap = { fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#4a300a' }; + this.add.text(PLAQUE.x - 66, PLAQUE.y + 24, 'TIME', cap).setOrigin(0.5).setDepth(D.labels + 0.1); + this.add.text(PLAQUE.x + 72, PLAQUE.y + 24, 'MOVES', cap).setOrigin(0.5).setDepth(D.labels + 0.1); + } - // Foundations (cols 4-7) + updateDesk() { + const gs = this.gs, d = this.deskTxt; + if (!gs || !d) return; + d.title.setText(`Deal No. ${gs.deal?.toLocaleString?.() ?? '—'}`); + d.kind.setText({ daily: `Today's deal · ${new Date().toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}`, chosen: 'A chosen deal', random: 'A random deal' }[this.dealKind] ?? ''); + d.home.setText(`${gs.homeCount()} of 52 cards home`); + const cells = gs._emptyFreecells(), cols = gs._emptyColumns(); + d.cap.setText(`Can move ${gs.maxMovable()} at once`); + d.capWhy.setText(`${cells} free cell${cells === 1 ? '' : 's'} · ${cols} empty column${cols === 1 ? '' : 's'}`); + const v = this.settings.analysis ? this.verdict : 'off'; + const lines = { + winnable: ['✓ Still winnable', INK_GREEN, 'Press H if you want a nudge.'], + checking: ['… thinking it over', INK_GREY, ''], + unknown: ['? Too tangled to tell', INK_GREY, 'Keep going — or ask for a hint.'], + lost: ['✗ Can\'t be won from here', INK_RED, 'Undo a few moves, or restart.'], + off: ['', INK_GREY, ''], + }[v]; + d.verdict.setText(lines[0]).setColor(lines[1]); + d.verdict2.setText(lines[2]); + } + + updatePlaque() { + this.timeTxt?.setText(this.settings.timer ? formatTime(this.elapsed) : '—'); + this.movesTxt?.setText(String(this.gs?.moveCount ?? 0)); + } + + onClock(ms) { + const s = Math.floor(ms / 1000); + if (s === this.lastSecond) return; + this.lastSecond = s; + this.drawClock(ms); + this.updatePlaque(); + if (this.settings.tick && this.settings.ambience) clockTick(this, s % 2 === 1); + } + + update(time, delta) { + super.update(time, delta); + if (this.rainG) this.tickRain(delta); + this.tickAnalysis(delta); + } + + // ── Deals ───────────────────────────────────────────────────────────────── + dealNew(n, kind) { + this.closeModal(); + this.dealKind = kind; + this.path = null; + this.pathMoves = null; + this.analysis = null; + this.verdict = 'checking'; + this.hintPending = false; + this.finishing = false; + this.lastSecond = -1; + this.setLampDim(false); + this.drawClock(0); + const gs = FreecellEngine.fromDeal(n); + const order = []; + for (let row = 0; row < 7; row++) for (let c = 0; c < 8; c++) if (gs.tableau[c][row]) order.push(gs.tableau[c][row].id); + this.beginGame(gs, { dealFrom: { ...DECK, rot: 0.05 }, order, step: 20 }); + this.updatePlaque(); + } + + /** Run fn, first confirming when it would abandon a deal in progress. */ + guardAbandon(title, fn, yes = 'Deal again') { + if (!this.started || this.finished) { fn(); return; } + this.confirm(title, 'An unfinished deal counts as a loss in your records.', yes, () => { + this.abandonIfStarted(this.gs.homeCount()); + fn(); + }); + } + + newDealPrompt() { this.guardAbandon('Start a new deal?', () => this.dealNew(randomDealNumber(), 'random')); } + + // ── Layout ──────────────────────────────────────────────────────────────── + jit(pose, card, k = 0.35) { + const j = jitterFor(card.key); + return { ...pose, x: pose.x + j.x * 0.5, y: pose.y + j.y * 0.3, rot: pose.rot + j.rot * k }; + } + + computeLayout() { + const visible = new Map(); + const gs = this.gs; + const put = (card, pose, depth) => visible.set(card.id, { card, pose, faceUp: true, depth, kind: 'card' }); + gs.tableau.forEach((col, c) => { + const poses = columnPosesFor(c, col.length); + col.forEach((card, k) => put(card, this.jit(poses[k], card), D.cards + 1 + k * 0.02)); + }); + gs.freecells.forEach((card, i) => { if (card) put(card, this.jit(cellPose(i), card, 0.6), D.cards + 0.5); }); + FOUNDATION_ORDER.forEach((s, i) => gs.foundations[s].forEach((card, k) => put(card, this.jit(foundCardPose(i, k), card, 0.5), D.cards + k * 0.02))); + return { visible, loc: visible }; + } + + // ── Picking + targets ───────────────────────────────────────────────────── + pickAt(pt) { + const gs = this.gs; + if (!gs) return null; for (let i = 0; i < 4; i++) { - const x = colX(4 + i); - const suit = SUITS_ORDER[i]; - const pile = e.foundations[suit]; - const top = pile[pile.length - 1]; - this.dropZones.push({ cx: x, cy: HOME_Y, hw: CARD_W * 0.7, hh: CARD_H * 0.8, hlx: x, hly: HOME_Y, kind: 'foundation', suit }); - if (top) { - this.card(top, x, HOME_Y, { onClick: () => this.onSlotClick('foundation', i) }); - } else { - this.slot(x, HOME_Y, SUIT_GLYPH[suit], () => this.onSlotClick('foundation', i)); - } + const c = gs.freecells[i]; + if (c && inPose(pt, cellPose(i), 2)) return { key: `cell${i}`, kind: 'cell', i, n: 1, ids: [c.id] }; } - - // Tableau (cols 0-7) for (let c = 0; c < 8; c++) { - const pile = e.tableau[c]; - const x = colX(c); - const colH = Math.max(CARD_H, pile.length * FAN + CARD_H); - const midY = TAB_Y + (pile.length * FAN) / 2; - this.dropZones.push({ cx: x, cy: midY, hw: CARD_W * 0.7, hh: colH / 2 + 20, hlx: x, hly: TAB_Y + pile.length * FAN, kind: 'column', idx: c }); - if (!pile.length) { - this.slot(x, TAB_Y, '', () => this.onSlotClick('column', c)); - continue; - } - pile.forEach((cardObj, idx) => { - const isTop = idx === pile.length - 1; - const inSel = this.sel?.kind === 'tableau' && this.sel.col === c && idx >= this.sel.fromIdx; - const isHint = isTop && e.canMoveToFoundation(cardObj); - // A card is draggable if the entire run from here passes _validRun - const draggable = e._validRun(c, idx) !== null; - const sprite = this.card(cardObj, x, TAB_Y + idx * FAN, { - selected: inSel, - hint: isHint && !inSel, - onDown: draggable ? (_co, pointer) => this.onCardDown({ kind: 'tableau', col: c, fromIdx: idx }, pointer) : null, - onClick: draggable ? null : null, // non-draggable interior cards are inaccessible - }); - this.cardSprites.set(cardObj.id, sprite); - }); - } - } - - // ── interaction ────────────────────────────────────────────────────────── - - interactive() { return !this.animating && !this.autoRunning && !this.overlayUp; } - - onCardDown(descriptor, pointer) { - if (!this.interactive()) return; - this.beginDrag( - this.dragSpritesFor(descriptor), - pointer, - () => this.onTap(descriptor), - (x, y) => this.resolveDrop(descriptor, x, y), - ); - } - - dragSpritesFor(descriptor) { - if (descriptor.kind === 'freecell') { - const card = this.engine.freecells[descriptor.fcIdx]; - const o = card && this.cardSprites.get(card.id); - return o ? [o] : []; - } - const run = this.engine._validRun(descriptor.col, descriptor.fromIdx); - if (!run) return []; - return run.map((c) => this.cardSprites.get(c.id)).filter(Boolean); - } - - onTap(descriptor) { - if (!this.interactive()) return; - if (this.sel) { - const sameSpot = this.sel.kind === descriptor.kind && - (descriptor.kind === 'freecell' ? this.sel.fcIdx === descriptor.fcIdx - : this.sel.col === descriptor.col && this.sel.fromIdx === descriptor.fromIdx); - if (sameSpot) { this.sel = null; this.refresh(); return; } - // Try to complete a move from sel → descriptor location - if (this.commitMove(descriptor)) return; - } - this.sel = descriptor; - this.refresh(); - } - - onSlotClick(kind, idx) { - if (!this.interactive() || !this.sel) return; - if (kind === 'foundation') { - this.commitToFoundation(this.sel); - } else if (kind === 'freecell') { - if (this.sel.kind === 'tableau') { - const col = this.sel.col; - const pile = this.engine.tableau[col]; - const isTop = this.sel.fromIdx === pile.length - 1; - if (isTop && this.applyMove(this.engine.moveToFreecell(col))) return; - } - } else if (kind === 'column') { - this.commitToColumn(this.sel, idx); - } - } - - // Try to move sel → the tapped card's location (used when tapping a card while another is selected) - commitMove(descriptor) { - const e = this.engine; - // Try foundation - if (this.commitToFoundation(this.sel)) return true; - // Try freecell (only top tableau card) - if (descriptor.kind === 'freecell' && this.sel.kind === 'tableau') { - const isTop = this.sel.fromIdx === e.tableau[this.sel.col].length - 1; - if (isTop && this.applyMove(e.moveToFreecell(this.sel.col))) return true; - } - // Try column (tapped on a card in destCol → use that col as destination) - if (descriptor.kind === 'tableau' && descriptor.col !== (this.sel.col ?? -1)) { - if (this.commitToColumn(this.sel, descriptor.col)) return true; - } - if (descriptor.kind === 'freecell' && this.sel.kind === 'freecell') { - // freecell → freecell not a standard move; ignore - } - return false; - } - - commitToFoundation(sel) { - let ok = false; - if (sel.kind === 'tableau') { - const pile = this.engine.tableau[sel.col]; - if (sel.fromIdx === pile.length - 1) ok = this.engine.moveToFoundation('tableau', sel.col); - } else { - ok = this.engine.moveFromFreecellToFoundation(sel.fcIdx); - } - if (ok) { this.sel = null; this.applyMove(true); return true; } - return false; - } - - commitToColumn(sel, destCol) { - let ok = false; - if (sel.kind === 'freecell') { - ok = this.engine.moveFromFreecellToColumn(sel.fcIdx, destCol); - } else { - ok = this.engine.moveRun(sel.col, sel.fromIdx, destCol); - } - if (ok) { this.sel = null; this.applyMove(true); return true; } - return false; - } - - resolveDrop(descriptor, x, y) { - const z = this.dropZones.find((zone) => Math.abs(x - zone.cx) < zone.hw && Math.abs(y - zone.cy) < zone.hh); - if (!z) return null; - const pos = { x: z.hlx, y: z.hly }; - const e = this.engine; - - if (z.kind === 'foundation') { - if (descriptor.kind === 'tableau') { - const pile = e.tableau[descriptor.col]; - if (descriptor.fromIdx !== pile.length - 1) return null; - if (!e.canMoveToFoundation(pile[descriptor.fromIdx])) return null; - } else { - const card = e.freecells[descriptor.fcIdx]; - if (!card || !e.canMoveToFoundation(card)) return null; - } - const commit = () => { - if (descriptor.kind === 'tableau') return e.moveToFoundation('tableau', descriptor.col); - return e.moveFromFreecellToFoundation(descriptor.fcIdx); - }; - return { pos, color: 0xffd700, commit }; - } - if (z.kind === 'freecell') { - if (descriptor.kind !== 'tableau') return null; - const pile = e.tableau[descriptor.col]; - if (descriptor.fromIdx !== pile.length - 1) return null; - if (e._emptyFreecells() === 0) return null; - const commit = () => e.moveToFreecell(descriptor.col); - return { pos, color: HINT, commit }; - } - if (z.kind === 'column') { - if (descriptor.kind === 'tableau') { - if (!e.canMoveRun(descriptor.col, descriptor.fromIdx, z.idx)) return null; - } else { - const card = e.freecells[descriptor.fcIdx]; - if (!card || !e.canMoveToColumn(card, z.idx)) return null; - } - const commit = () => { - if (descriptor.kind === 'freecell') return e.moveFromFreecellToColumn(descriptor.fcIdx, z.idx); - return e.moveRun(descriptor.col, descriptor.fromIdx, z.idx); - }; - return { pos, color: SEL, commit }; + const col = gs.tableau[c]; + if (!col.length) continue; + const k = hitIndex(columnPosesFor(c, col.length), pt, 2); + if (k >= 0) return { key: `col${c}:${k}`, kind: 'col', i: c, idx: k, n: col.length - k, ids: col.slice(k).map(x => x.id) }; } return null; } - applyMove(ok, sfx = SFX.CARD_PLACE) { - if (ok) { playSound(this, sfx); this.refresh(); } - return ok; - } + srcCards(src) { return src.kind === 'cell' ? [this.gs.freecells[src.i]] : this.gs.tableau[src.i].slice(src.idx); } - refresh() { - this.renderBoard(); - this.updateHud(); - if (this.engine.isWon()) { this.endGame(); return; } - this.updateAutoComplete(); - this.updateStuck(); - } - - updateHud() { - this.movesText.setText(`Moves: ${this.engine.moveCount}`); - } - - updateAutoComplete() { - const show = !this.animating && !this.autoRunning && !this.overlayUp && this.engine.canAutoComplete() && !this.engine.isWon(); - this.autoCompleteBtn.setVisible(show); - } - - updateStuck() { - const stuck = this.interactive() && !this.engine.hasMoves() && !this.engine.isWon(); - this.stuckBanner.setVisible(stuck); - this.newGameBtn.setVisible(stuck); - if (stuck && !this.pulse) { - this.pulse = this.tweens.add({ targets: this.newGameBtn, scaleX: 1.06, scaleY: 1.06, yoyo: true, repeat: -1, duration: 520, ease: 'Sine.easeInOut' }); - } else if (!stuck && this.pulse) { - this.pulse.stop(); this.pulse = null; this.newGameBtn.setScale(1); + movesFor(src) { + const gs = this.gs; + const out = []; + const from = { kind: src.kind, i: src.i }; + const n = src.n; + const head = this.srcCards(src)[0]; + if (!head) return out; + if (n === 1) { + const m = { from, to: { kind: 'found' }, n: 1 }; + if (gs.isLegal(m)) { + const fi = foundIndex(head.suit); + out.push({ move: m, kind: 'found', anchor: foundCardPose(fi, gs.foundations[head.suit].length), zone: foundZone(fi), score: 100 }); + } } + for (let d = 0; d < 8; d++) { + if (src.kind === 'col' && d === src.i) continue; + const m = { from, to: { kind: 'col', i: d }, n }; + if (!gs.isLegal(m)) continue; + const len = gs.tableau[d].length; + let score = len ? 60 + n : 24 + n * 0.5; + if (src.kind === 'col') { + const below = gs.tableau[src.i][src.idx - 1]; + if (!below) score += len ? 6 : -22; + else if (gs.canMoveToFoundation(below)) score += 8; + } else score += len ? 10 : 4; + out.push({ move: m, kind: 'col', anchor: columnPosesFor(d, len + n)[len], zone: columnZone(d), score: score - d * 0.01 }); + } + if (n === 1 && src.kind === 'col') { + for (let i = 0; i < 4; i++) { + if (!gs.freecells[i]) out.push({ move: { from, to: { kind: 'cell', i }, n: 1 }, kind: 'cell', anchor: cellPose(i), zone: cellZone(i), score: 10 - i * 0.1 }); + } + } + return out; } - // ── auto-complete ───────────────────────────────────────────────────────── - - onAutoComplete() { - if (!this.interactive()) return; - this.autoRunning = true; - this.animating = true; - this.sel = null; - this.autoCompleteBtn.setVisible(false); - this.doAutoStep(); + grabBlocker(src) { + if (src.kind === 'col' && !this.gs._validRun(src.i, src.idx)) return 'Only an ordered run moves together'; + return null; } - doAutoStep() { - const next = this.engine.autoCompleteStep(); - if (!next) { - this.autoRunning = false; - this.animating = false; - this.refresh(); + noMoveReason(src) { + const gs = this.gs; + if (src.kind === 'col' && src.n > 1) { + for (let d = 0; d < 8; d++) { + if (d !== src.i && gs.runBlocker(src.i, src.idx, d) === 'space') { + return `That's ${src.n} cards — there's room to move ${gs.maxMovable(d)}`; + } + } + } + return 'Nowhere for that to go yet'; + } + + dropBlocker(src, pt) { + const gs = this.gs; + const head = this.srcCards(src)[0]; + for (let i = 0; i < 4; i++) { + if (!inRect(pt, foundZone(i))) continue; + if (src.n > 1) return 'One card at a time to the foundations'; + const suit = FOUNDATION_ORDER[i]; + if (head.suit !== suit) return `That's the ${SUIT_NAME[suit]} foundation`; + return `The ${SUIT_NAME[suit]} need the ${rankName(gs._foundationNext(suit))} next`; + } + for (let i = 0; i < 4; i++) { + if (!inRect(pt, cellZone(i))) continue; + if (src.n > 1) return 'A free cell holds one card'; + if (gs.freecells[i]) return 'That cell is taken'; + } + for (let d = 0; d < 8; d++) { + if (!inRect(pt, columnZone(d)) || (src.kind === 'col' && d === src.i)) continue; + const col = gs.tableau[d]; + const top = col[col.length - 1]; + if (top && !gs.canMoveToColumn(head, d)) { + return `${cardName(head)} goes on a ${isRed(head) ? 'black' : 'red'} ${rankName(head.pval + 1)}`; + } + if (src.kind === 'col' && gs.runBlocker(src.i, src.idx, d) === 'space') { + return `${src.n} cards needs more room — you can move ${gs.maxMovable(d)}`; + } + } + return null; + } + + /** "4 of 6" beside a dragged run: how many you carry vs how many the room allows. */ + dragBadge(src, target) { + if (src.kind !== 'col' || src.n < 2) return null; + const dest = target?.move.to.kind === 'col' ? target.move.to.i : null; + const cap = this.gs.maxMovable(dest); + return { text: `${src.n} of ${cap}`, ok: src.n <= cap }; + } + + commitMove(m) { return this.gs.apply(m); } + + nextAutoMove() { + const gs = this.gs; + if (this.finishing) { + const s = gs.autoCompleteStep(); + return s ? { ...s.move, fast: true } : null; + } + if (!this.settings.autoPlay) return null; + const m = gs.nextSafeMove(); + return m ? { ...m, fast: true } : null; + } + + moveFx(move, cards, via) { + if (move.n > 1) return { stagger: 42, duration: 250 }; + return { duration: via === 'auto' ? (this.finishing ? 170 : 220) : 230 }; + } + + // ── State → HUD ─────────────────────────────────────────────────────────── + onStateChanged() { + if (!this.gs) return; + this.updateDesk(); + this.updatePlaque(); + this.updateDock(); + if (this.mode === 'play' && !this.finished) this.startAnalysis(); + } + + canFinish() { return !this.finished && this.gs && !this.gs.isWon() && this.gs.canAutoComplete(); } + + updateDock() { + if (!this.gs) return; + const undo = { label: 'Undo', act: () => this.undo(), enabled: this.undoStack.length > 0 && !this.finishing }; + const hint = { label: this.hintPending ? 'Thinking…' : 'Hint', act: () => this.requestHint(), enabled: !this.hintPending && !this.finishing }; + const finish = this.canFinish() && !this.finishing; + const third = finish + ? { label: 'Finish ▶', act: () => this.startFinish(), hot: true } + : { label: 'Restart', act: () => this.confirmRestart(), enabled: this.started && !this.finishing }; + const deal = { label: 'New Deal', act: () => this.newDealPrompt() }; + let prompt; + if (this.mode === 'deal') prompt = 'Dealing…'; + else if (this.finishing) prompt = 'Sending every card home…'; + else if (finish) prompt = 'Every card can go home now —\npress Finish (or Space).'; + else if (this.hintPending) prompt = 'Studying the cards…'; + else if (this.verdict === 'lost' && this.settings.analysis) prompt = 'No winning line from here.\nUndo a few moves or restart.'; + else if (!this.gs.hasMoves()) prompt = 'No moves left.\nUndo, restart, or deal again.'; + else if (!this.started) prompt = 'Drag a card, or click it to\nsend it to its best spot.'; + else prompt = `${52 - this.gs.homeCount()} cards to go.`; + this.setDock(prompt, [undo, hint, third, deal]); + } + + confirmRestart() { + if (!this.started || this.finished) return; + this.confirm('Restart this deal?', 'Every card goes back to where it was dealt (you can still Undo).', 'Restart', () => this.restartDeal()); + } + + onAutoIdle() { if (this.finishing) { this.finishing = false; this.updateDock(); } } + onRewind() { this.finishing = false; } + + startFinish() { + if (!this.canAct() || !this.canFinish()) return; + this.finishing = true; + this.updateDock(); + this.scheduleAuto(); + } + + // ── Analysis + hints (FreecellSolver, time-sliced) ─────────────────────── + posKey() { return exactKey(stateFromEngine(this.gs)); } + + startAnalysis() { + if (this.finishing) return; + const known = this.path?.get(this.posKey()); + if (known != null) { + this.analysis = null; + this.setVerdict('winnable'); return; } - - const suitIdx = SUITS_ORDER.indexOf(next.card.suit); - const toX = colX(4 + suitIdx); - const toY = HOME_Y; - - const src = this.cardSprites.get(next.card.id); - const fromX = src ? src.x : GAME_WIDTH / 2; - const fromY = src ? src.y : GAME_HEIGHT / 2; - if (src) src.setVisible(false); - - this.engine.moveToFoundation(next.srcKind, next.srcIdx); - - const fly = this.add.container(fromX, fromY).setDepth(D.banner); - this.drawFace(fly, next.card, true, false, false); - this.tweens.add({ - targets: fly, x: toX, y: toY, duration: 110, ease: 'Quad.easeIn', - onComplete: () => { - fly.destroy(); - playSound(this, SFX.CARD_PLACE); - this.renderBoard(); - this.updateHud(); - if (this.engine.isWon()) { this.autoRunning = false; this.animating = false; this.endGame(); return; } - this.doAutoStep(); - }, - }); + if (!this.gs.hasMoves()) { this.analysis = null; this.setVerdict('lost'); return; } + if (!this.settings.analysis && !this.hintPending) { this.analysis = null; return; } + this.setVerdict('checking'); + this.analysis = { delay: this.hintPending ? 0 : 380, maxNodes: this.hintPending ? 150000 : 60000, solver: null }; } - // ── deal animation (same as SolitaireTourGame) ──────────────────────────── - - dealAnimation() { - const cards = this.board.list.filter((o) => o.isCard); - if (!cards.length) return; - const deckX = GAME_WIDTH / 2, deckY = GAME_HEIGHT + 90; - const homes = cards.map((c) => ({ c, x: c.x, y: c.y, alpha: c.alpha })); - this.animating = true; - for (const { c } of homes) { c.setPosition(deckX, deckY).setScale(0.7).setAlpha(0); } - homes.forEach(({ c, x, y, alpha }, i) => { - const last = i === homes.length - 1; - this.tweens.add({ - targets: c, x, y, scaleX: 1, scaleY: 1, alpha, - delay: i * 12, duration: 200, ease: 'Quad.easeOut', - onComplete: last ? () => { this.animating = false; this.updateStuck(); } : undefined, - }); - }); - } - - // ── drag-and-drop (verbatim from SolitaireTourGame) ─────────────────────── - - setupDrag() { - this.input.on('pointermove', (pointer) => { - if (!pointer.isDown) return; - if (this.dragState) { - this.dragUpdate(pointer); - } else if (this.potentialDrag) { - const dx = pointer.x - this.potentialDrag.startX; - const dy = pointer.y - this.potentialDrag.startY; - if (dx * dx + dy * dy > 80) this.dragPromote(); + setVerdict(v) { + const was = this.verdict; + this.verdict = v; + if (v !== was) { + this.setLampDim(v === 'lost' && this.settings.analysis); + if (v === 'lost' && this.settings.analysis && this.started) { + this.floatText({ x: DEAL_CARD.x, y: DEAL_CARD.y + DEAL_CARD.h / 2 + 24 }, 'The lamp flickers…', '#ffd2a0', { size: 20, ms: 2200, rise: 20 }); } - }); - this.input.on('pointerup', () => { - if (this.dragState) this.dragEnd(); - else if (this.potentialDrag) { - const pd = this.potentialDrag; - this.potentialDrag = null; - pd.tap(); - } - }); - } - - beginDrag(objs, pointer, tap, resolve) { - if (!this.interactive() || this.dragState || !objs.length) return; - this.potentialDrag = { - startX: pointer.x, startY: pointer.y, tap, resolve, - sprites: objs.map((obj) => ({ obj, offX: obj.x - pointer.x, offY: obj.y - pointer.y, homeX: obj.x, homeY: obj.y })), - }; - } - - dragPromote() { - const pd = this.potentialDrag; - this.potentialDrag = null; - pd.sprites.forEach(({ obj }) => { - this.board.bringToTop(obj); - this.tweens.add({ targets: obj, scaleX: 1.05, scaleY: 1.05, duration: 90 }); - }); - this.dragState = pd; - } - - dragUpdate(pointer) { - for (const { obj, offX, offY } of this.dragState.sprites) { - obj.x = pointer.x + offX; - obj.y = pointer.y + offY; } - const primary = this.dragState.sprites[0].obj; - this.highlightDrop(this.dragState.resolve(primary.x, primary.y)); + this.updateDesk(); + this.updateDock(); } - highlightDrop(target) { - if (this.dropHighlight) { this.dropHighlight.destroy(); this.dropHighlight = null; } - if (!target) return; - this.dropHighlight = this.add.rectangle(target.pos.x, target.pos.y, CARD_W + 16, CARD_H + 16, target.color, 0.18) - .setStrokeStyle(3, target.color, 0.9).setDepth(D.card - 1); + tickAnalysis() { + const a = this.analysis; + if (!a || this.paused || this.dragState || this.mode !== 'play') return; + if (a.delay > 0) { a.delay -= this.game.loop.delta; return; } + if (!a.solver) { a.solver = new FreecellSolver(this.gs, { maxNodes: a.maxNodes }); a.snap = this.gs.snapshot(); } + const t0 = performance.now(); + while (!a.solver.done && performance.now() - t0 < BG_SLICE_MS) a.solver.step(120); + if (!a.solver.done) return; + this.analysis = null; + const r = a.solver.result; + if (r.status === 'solved') { + this.storePath(a.snap, r.moves); + this.setVerdict('winnable'); + } else this.setVerdict(r.status === 'unsolvable' ? 'lost' : 'unknown'); + if (this.hintPending) { + this.hintPending = false; + this.updateDock(); + this.deliverHint(r.status); + } } - dragEnd() { - const ds = this.dragState; - this.dragState = null; - if (this.dropHighlight) { this.dropHighlight.destroy(); this.dropHighlight = null; } + /** Remember every position along a winning line, so hints are instant while you follow it. */ + storePath(snap, moves) { + const e = FreecellEngine.fromSnapshot(snap); + this.path = this.path ?? new Map(); + this.pathMoves = this.pathMoves ?? []; + const base = this.pathMoves.length; + for (let i = 0; i < moves.length; i++) { + this.path.set(exactKey(stateFromEngine(e)), base + i); + this.pathMoves.push(moves[i]); + if (!e.apply(moves[i]).length) break; + } + } - const primary = ds.sprites[0].obj; - const target = ds.resolve(primary.x, primary.y); - if (target && target.commit()) { this.sel = null; this.applyMove(true); return; } - ds.sprites.forEach(({ obj, homeX, homeY }) => { - this.tweens.add({ targets: obj, x: homeX, y: homeY, scaleX: 1, scaleY: 1, duration: 220, ease: 'Back.easeOut' }); + requestHint() { + if (!this.canAct() || this.finishing) return; + const idx = this.path?.get(this.posKey()); + if (idx != null) { this.showHintMove(this.pathMoves[idx], 'This way'); return; } + if (!this.gs.hasMoves()) { + this.floatText({ x: CX, y: 860 }, 'No moves left — Undo or deal again', '#ffd2a0', { size: 21, ms: 2000 }); + return; + } + if (this.verdict === 'lost') { + this.floatText({ x: CX, y: 860 }, 'No winning line from here — try Undo', '#ffd2a0', { size: 21, ms: 2000 }); + const fallback = this.fallbackMove(); + if (fallback) this.showHintMove(fallback, 'Still, you could…'); + return; + } + this.hintPending = true; + this.updateDock(); + this.startAnalysis(); + } + + deliverHint(status) { + const idx = this.path?.get(this.posKey()); + if (idx != null) { this.showHintMove(this.pathMoves[idx], 'This way'); return; } + const fb = this.fallbackMove(); + if (status === 'unsolvable') this.floatText({ x: CX, y: 860 }, 'No winning line from here — try Undo', '#ffd2a0', { size: 21, ms: 2000 }); + if (fb) this.showHintMove(fb, status === 'unsolvable' ? 'Still, you could…' : 'Worth a try'); + } + + /** Best-looking single move by the smart-click ranking (when the solver has no line). */ + fallbackMove() { + let best = null; + const gs = this.gs; + const srcs = []; + gs.freecells.forEach((c, i) => c && srcs.push({ kind: 'cell', i, n: 1 })); + gs.tableau.forEach((col, c) => { for (let k = gs.runStart(c); k < col.length; k++) if (col.length) srcs.push({ kind: 'col', i: c, idx: k, n: col.length - k }); }); + for (const s of srcs) for (const t of this.movesFor(s)) if (!best || t.score > best.score) best = t; + return best?.move ?? null; + } + + showHintMove(m, text) { + const gs = this.gs; + if (!gs.isLegal(m)) return; + const cards = gs.cardsOf(m.from, m.n); + const from = this.poseOf(cards[0].id); + let to; + if (m.to.kind === 'found') to = foundCardPose(foundIndex(cards[0].suit), gs.foundations[cards[0].suit].length); + else if (m.to.kind === 'cell') to = cellPose(m.to.i ?? gs.freecells.indexOf(null)); + else { const len = gs.tableau[m.to.i].length; to = columnPosesFor(m.to.i, len + m.n)[len]; } + if (!from || !to) return; + const what = m.n > 1 ? `${m.n} cards` : cardName(cards[0]); + const where = m.to.kind === 'found' ? 'home' : m.to.kind === 'cell' ? 'to a free cell' : gs.tableau[m.to.i].length ? `onto ${cardName(gs.tableau[m.to.i][gs.tableau[m.to.i].length - 1])}` : 'to the empty column'; + this.showHint({ ids: cards.map(c => c.id), from, to, text: `${text}: ${what} ${where}` }); + } + + // ── Win ─────────────────────────────────────────────────────────────────── + onWin() { + this.finishing = false; + this.analysis = null; + const { stats, newBest } = this.recordSolitaire({ won: true, score: this.gs.moveCount, extra: { deal: this.gs.deal } }); + this.updatePlaque(); + this.updateDesk(); + this.setDock('Solved!', []); + this.time.delayedCall(420, async () => { + if (!this.alive()) return; + const stacks = FOUNDATION_ORDER.map((s, i) => ({ cards: this.gs.foundations[s].slice(), pose: foundPose(i) })); + await this.winCascade(stacks); + if (this.alive()) this.showWinCard(stats, newBest); }); } - // ── win / end ───────────────────────────────────────────────────────────── - - endGame() { - this.animating = false; - this.autoRunning = false; - this.sel = null; - this.stuckBanner.setVisible(false); - this.newGameBtn.setVisible(false); - this.autoCompleteBtn.setVisible(false); - if (this.pulse) { this.pulse.stop(); this.pulse = null; } - playSound(this, SFX.CASINO_WIN); - this.recordResult(); - this.showWinOverlay(); + showWinCard(stats, newBest) { + const w = 760, h = 560; + this.openModal({ w, h, paper: true, freeze: false }); + const top = CY - h / 2; + const ink = '#22201a', grey = INK_GREY; + this.modalText(CX, top + 70, 'Solved!', { fontFamily: FONT_HAND, fontSize: '64px', color: '#2f6a3a' }); + this.modalText(CX, top + 128, `Deal No. ${this.gs.deal.toLocaleString()}${this.dealKind === 'daily' ? ' · today\'s deal' : ''}`, { fontFamily: FONT_HAND, fontSize: '28px', color: grey }); + const rows = [ + ['Time', formatTime(this.elapsed), newBest.time ? 'new best!' : ''], + ['Moves', String(this.gs.moveCount), newBest.moves ? 'fewest yet!' : ''], + ['Win streak', String(stats.streak), newBest.streak ? 'best streak!' : ''], + ['Deals won', `${stats.won} of ${stats.played}`, ''], + ]; + rows.forEach(([k, v, note], i) => { + const y = top + 200 + i * 56; + this.addToModal(this.add.text(CX - 250, y, k, { fontFamily: FONT_HAND, fontSize: '32px', color: grey }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX + 90, y, v, { fontFamily: FONT_HAND, fontSize: '36px', color: ink }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + if (note) { + const t = this.addToModal(this.add.text(CX + 120, y, note, { fontFamily: FONT_HAND, fontSize: '28px', color: '#b8231f' }).setOrigin(0, 0.5).setDepth(D.modal + 1).setRotation(-0.05)); + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 1)); + g.lineStyle(2.5, 0xb8231f, 0.8); + g.strokeEllipse(t.x + t.width / 2, y, t.width + 30, 46); + playSoundEx(this, SFX.PENCIL_WRITE, { volume: 0.5 }); + } + }); + const by = top + h - 60; + this.modalButton(CX - 240, by, 'New Deal', () => this.dealNew(randomDealNumber(), 'random'), { width: 210, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + this.modalButton(CX, by, 'Replay Deal', () => this.dealNew(this.gs.deal, this.dealKind === 'daily' ? 'daily' : 'chosen'), { width: 210 }); + this.modalButton(CX + 240, by, 'Leave', () => this.scene.start('GameMenu'), { width: 210, variant: 'ghost' }); + this.modal.onEnter = () => this.dealNew(randomDealNumber(), 'random'); } - showWinOverlay() { - this.overlayUp = true; - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - const dim = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62).setDepth(D.overlay).setInteractive(); - const g = this.add.graphics().setDepth(D.overlay); - g.fillStyle(COLORS.panel, 1); g.fillRoundedRect(cx - 380, cy - 200, 760, 400, 20); - g.lineStyle(3, COLORS.accent, 1); g.strokeRoundedRect(cx - 380, cy - 200, 760, 400, 20); - this.overlayObjs.push(dim, g); - - this.overlayObjs.push(this.add.text(cx, cy - 130, 'You Win!', { - fontFamily: 'Righteous', fontSize: '62px', color: '#5fd29a', - }).setOrigin(0.5).setDepth(D.overlayUI)); - - this.overlayObjs.push(this.add.text(cx, cy - 30, `Completed in ${this.engine.moveCount} moves`, { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - - const again = new Button(this, cx - 130, cy + 110, 'Play Again', () => { - this.clearOverlay(); this.overlayUp = false; this.startGame(); - }, { width: 220, height: 60, fontSize: 24 }); - again.setDepth(D.overlayUI); - - const leave = new Button(this, cx + 130, cy + 110, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 220, height: 60, fontSize: 24 }); - leave.setDepth(D.overlayUI); - - this.overlayObjs.push(again, leave); + // ── Menus ───────────────────────────────────────────────────────────────── + openMenu() { + if (this.modal) return; + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Choose a deal…', act: () => { this.closeModal(); this.openDealPicker(); } }, + { label: 'Restart this deal', act: () => { this.closeModal(); this.confirmRestart(); } }, + { label: 'Records', act: () => { this.closeModal(); this.openStats(); } }, + { label: 'How to play', act: () => { this.closeModal(); this.openRules(); } }, + { label: 'New deal', ghost: true, act: () => { this.closeModal(); this.newDealPrompt(); } }, + { label: 'Leave the study', ghost: true, act: () => { this.closeModal(); this.onLeave(); } }, + ]); } - clearOverlay() { - for (const o of this.overlayObjs) o.destroy(); - this.overlayObjs = []; + openStats() { + const daily = dailyDealNumber(); + const st = loadStats('freecell'); + const solvedToday = (st.recent ?? []).some(r => r.won && r.deal === daily); + super.openStats({ title: 'Freecell Records', extraLines: [['Today\'s deal', solvedToday ? 'solved ✓' : 'not yet']] }); } - recordResult() { - if (this.recorded) return; - this.recorded = true; - api.post('/history/single-player', { - slug: 'freecell', score: this.engine.moveCount, opponentScores: [], result: 'win', - }).catch(() => { /* best effort */ }); + openSettings() { + const s = this.settings; + this.openSettingsModal([ + { label: 'Clicking a card', options: [['smart', 'Moves it'], ['select', 'Selects it']], get: () => s.click, set: (v) => { s.click = v; this.selected = null; this.refreshGlows(); } }, + { label: 'Auto-play safe cards home', options: [[true, 'On'], [false, 'Off']], get: () => s.autoPlay, set: (v) => { s.autoPlay = v; if (v) this.scheduleAuto(); } }, + { label: 'Tell me if it\'s still winnable', options: [[true, 'On'], [false, 'Off']], get: () => s.analysis, set: (v) => { s.analysis = v; this.setLampDim(v && this.verdict === 'lost'); this.startAnalysis(); this.updateDesk(); } }, + { label: 'Card speed', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['brisk', 'Brisk']], get: () => s.anim, set: (v) => { s.anim = v; } }, + { label: 'Rain & thunder', options: [[true, 'On'], [false, 'Off']], get: () => s.ambience, set: (v) => { s.ambience = v; this.rain?.setOn(v); } }, + { label: 'Clock tick', options: [[true, 'On'], [false, 'Off']], get: () => s.tick, set: (v) => { s.tick = v; } }, + { label: 'Show the time', options: [[true, 'On'], [false, 'Off']], get: () => s.timer, set: (v) => { s.timer = v; this.updatePlaque(); } }, + ], { title: 'Study Settings', note: '"Safe" cards are ones nothing could ever need to be built on.' }); + } + + openDealPicker() { + const w = 820, h = 660; + this.openModal({ w, h, onEscape: () => { this.dealEntry = null; this.closeModal(); } }); + const top = CY - h / 2; + this.dealEntry = ''; + this.modalText(CX, top + 56, 'Choose a Deal', { fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex }); + this.modalText(CX, top + 100, `Every number from 1 to ${MAX_DEAL.toLocaleString()} is the same deal for everyone.`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex }); + const daily = dailyDealNumber(); + const go = (n, kind) => { this.dealEntry = null; this.guardAbandon('Leave this deal?', () => this.dealNew(n, kind), 'Deal it'); }; + this.modalButton(CX - 190, top + 160, 'A random deal', () => go(randomDealNumber(), 'random'), { width: 300 }); + this.modalButton(CX + 190, top + 160, `Today's deal #${daily.toLocaleString()}`, () => go(daily, 'daily'), { width: 300, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + if (this.gs?.deal) this.modalButton(CX, top + 222, `Replay this deal #${this.gs.deal.toLocaleString()}`, () => go(this.gs.deal, this.dealKind === 'daily' ? 'daily' : 'chosen'), { width: 380, variant: 'ghost' }); + // number entry + this.modalText(CX, top + 286, 'or type a deal number', { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex }); + const box = this.addToModal(this.add.rectangle(CX, top + 332, 300, 54, 0x0c0705).setStrokeStyle(2, COLORS.accent).setDepth(D.modal + 1)); + this.dealEntryTxt = this.modalText(CX, top + 332, '', { fontFamily: 'Righteous', fontSize: '32px', color: COLORS.textHex }); + void box; + const refresh = () => { this.dealEntryTxt.setText(this.dealEntry || '…'); dealBtn.setEnabled(this.dealEntryValid()); }; + const keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'C', '0', '⌫']; + keys.forEach((k, i) => { + const x = CX - 110 + (i % 3) * 110, y = top + 402 + Math.floor(i / 3) * 52; + this.modalButton(x, y, k, () => { this.dealKey(k); refresh(); }, { width: 96, height: 44, fontSize: 20, variant: 'ghost' }); + }); + const dealBtn = this.modalButton(CX + 260, top + 332, 'Deal it', () => { if (this.dealEntryValid()) go(Number(this.dealEntry), 'chosen'); }, { width: 150, height: 50 }); + this.modalButton(CX, top + h - 40, 'Cancel', () => { this.dealEntry = null; this.closeModal(); }, { width: 200, height: 42, fontSize: 18, variant: 'ghost' }); + this.modal.onEnter = () => { if (this.dealEntryValid()) go(Number(this.dealEntry), 'chosen'); }; + this.dealEntryRefresh = refresh; + refresh(); + } + + dealEntryValid() { const n = Number(this.dealEntry); return Number.isInteger(n) && n >= 1 && n <= MAX_DEAL; } + + dealKey(k) { + if (this.dealEntry == null) return; + if (k === 'C') this.dealEntry = ''; + else if (k === '⌫') this.dealEntry = this.dealEntry.slice(0, -1); + else if (this.dealEntry.length < 7) this.dealEntry = (this.dealEntry + k).replace(/^0+/, ''); + playSoundEx(this, SFX.CLICK, { volume: 0.3 }); + } + + onKey(e) { + if (this.modal && this.dealEntry != null) { + if (/^Digit[0-9]$|^Numpad[0-9]$/.test(e.code)) { this.dealKey(e.code.slice(-1)); this.dealEntryRefresh?.(); return; } + if (e.code === 'Backspace') { this.dealKey('⌫'); this.dealEntryRefresh?.(); return; } + } + super.onKey(e); + } + + onKeyExtra(e) { + if (e.code === 'KeyH') this.requestHint(); + else if (e.code === 'Space') { if (this.canFinish()) this.startFinish(); } + else if (e.code === 'KeyN') this.newDealPrompt(); + else if (e.code === 'KeyR') this.confirmRestart(); + } + + onLeave() { + if (!this.started || this.finished) { this.scene.start('GameMenu'); return; } + this.confirm('Leave this deal?', 'An unfinished deal counts as a loss in your records.', 'Leave', () => { + this.abandonIfStarted(this.gs.homeCount()); + this.scene.start('GameMenu'); + }, { no: 'Stay' }); } } + +export { LAMP, colX, TAB_TOP, CW, Button, playSound }; diff --git a/src/games/freecell/FreecellLogic.js b/src/games/freecell/FreecellLogic.js index 2a7f9f1..1171d62 100644 --- a/src/games/freecell/FreecellLogic.js +++ b/src/games/freecell/FreecellLogic.js @@ -1,9 +1,27 @@ +// Freecell — pure rules engine (Phaser-free; tools/verifyFreecell.js tests it). +// +// 52 cards dealt face-up into 8 columns (7,7,7,7,6,6,6,6). Four free cells +// hold one card each; four foundations build up by suit from Ace. Columns +// build down in alternating colours. Only one card moves at a time — a longer +// run "supermoves" when there is room to shuffle it through the free cells and +// empty columns: (freeCells + 1) × 2^(emptyColumns), not counting the +// destination column itself when it is empty. +// +// Moves are plain objects so the scene, the hint solver and undo can all share +// them: { from: { kind: 'col' | 'cell', i }, to: { kind: 'col' | 'cell' | 'found', i? }, n } +// n = cards moved (runs only come from columns; cells and foundations move 1). + import { Card, SUITS, RANKS } from '../cards/Deck.js'; +import { mulberry32 } from '../../ui/cardtable/AITiming.js'; const PVAL = { A: 1, T: 10, J: 11, Q: 12, K: 13 }; for (let n = 2; n <= 9; n++) PVAL[String(n)] = n; -export function freshDeck() { +export const MAX_DEAL = 1000000; +export const FOUNDATION_ORDER = ['s', 'h', 'd', 'c']; + +/** A 52-card deck, shuffled by `rng` (Math.random when omitted). Ids are stable per card. */ +export function freshDeck(rng = Math.random) { const cards = []; let id = 0; for (const suit of SUITS) { @@ -15,204 +33,283 @@ export function freshDeck() { } } for (let i = cards.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)); + const j = Math.floor(rng() * (i + 1)); [cards[i], cards[j]] = [cards[j], cards[i]]; } return cards; } +/** The deck for numbered deal `n` (1 … MAX_DEAL) — same cards every time. */ +export function deckForDeal(n) { + return freshDeck(mulberry32((n * 2654435761) >>> 0 ^ 0x5eed)); +} + +export const randomDealNumber = (rng = Math.random) => 1 + Math.floor(rng() * MAX_DEAL); + +/** Today's deal number (local date), the same for everyone on that day. */ +export function dailyDealNumber(date = new Date()) { + const ymd = date.getFullYear() * 10000 + (date.getMonth() + 1) * 100 + date.getDate(); + let h = 2166136261; + for (const ch of String(ymd)) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); + return 1 + ((h >>> 0) % MAX_DEAL); +} + +export const isRed = (c) => c.suit === 'h' || c.suit === 'd'; + export class FreecellEngine { - constructor(deck) { + constructor(deck, { deal = null } = {}) { + this.deal = deal; this.tableau = Array.from({ length: 8 }, () => []); this.freecells = [null, null, null, null]; this.foundations = { s: [], h: [], d: [], c: [] }; this.moveCount = 0; - // Deal: cols 0-3 get 7 cards, cols 4-7 get 6 cards (round-robin) + // Round-robin: cols 0-3 get 7 cards, cols 4-7 get 6. let k = 0; for (let row = 0; row < 7; row++) { - const cols = row < 6 ? 8 : 4; // first 6 rows fill all 8; row 6 fills only cols 0-3 + const cols = row < 6 ? 8 : 4; for (let c = 0; c < cols; c++) this.tableau[c].push(deck[k++]); } } - // ── internal helpers ─────────────────────────────────────────────────────── + static fromDeal(n) { return new FreecellEngine(deckForDeal(n), { deal: n }); } + /** A detached engine at a snapshot (solver replays, tests). */ + static fromSnapshot(snap, deal = null) { + const e = new FreecellEngine(Array(52).fill(null), { deal }); + e.restore(snap); + return e; + } + + // ── snapshots (undo) ───────────────────────────────────────────────────── + snapshot() { + return { + tableau: this.tableau.map(col => col.slice()), + freecells: this.freecells.slice(), + foundations: Object.fromEntries(SUITS.map(s => [s, this.foundations[s].slice()])), + moveCount: this.moveCount, + }; + } + + restore(s) { + this.tableau = s.tableau.map(col => col.slice()); + this.freecells = s.freecells.slice(); + this.foundations = Object.fromEntries(SUITS.map(x => [x, s.foundations[x].slice()])); + this.moveCount = s.moveCount; + } + + allCards() { + return [...this.tableau.flat(), ...this.freecells.filter(Boolean), ...SUITS.flatMap(s => this.foundations[s])]; + } + + // ── internal helpers ───────────────────────────────────────────────────── _foundationNext(suit) { const pile = this.foundations[suit]; return pile.length === 0 ? 1 : pile[pile.length - 1].pval + 1; } - _emptyFreecells() { - return this.freecells.filter((s) => s === null).length; - } + _emptyFreecells() { return this.freecells.filter((s) => s === null).length; } + _emptyColumns() { return this.tableau.filter((col) => col.length === 0).length; } - _emptyColumns() { - return this.tableau.filter((col) => col.length === 0).length; - } - - // Returns the valid alternating-color descending run from fromIdx to bottom, - // or null if it doesn't form one. + /** The alternating-colour descending run from fromIdx to the bottom, or null. */ _validRun(col, fromIdx) { const pile = this.tableau[col]; if (fromIdx < 0 || fromIdx >= pile.length) return null; - const run = [pile[fromIdx]]; for (let i = fromIdx + 1; i < pile.length; i++) { const prev = pile[i - 1], cur = pile[i]; - if (cur.isRed === prev.isRed || cur.pval !== prev.pval - 1) return null; - run.push(cur); + if (isRed(cur) === isRed(prev) || cur.pval !== prev.pval - 1) return null; } - return run; + return pile.slice(fromIdx); } - // ── move validation ──────────────────────────────────────────────────────── - - canMoveToFoundation(card) { - return card.pval === this._foundationNext(card.suit); + /** Index where the column's bottom ordered run starts. */ + runStart(col) { + const pile = this.tableau[col]; + if (!pile.length) return 0; + let i = pile.length - 1; + while (i > 0) { + const a = pile[i - 1], b = pile[i]; + if (isRed(a) === isRed(b) || b.pval !== a.pval - 1) break; + i--; + } + return i; } + /** Most cards one move can carry onto `destCol` (an empty destination doesn't count as space). */ + maxMovable(destCol = null) { + const emptyCols = this._emptyColumns() - (destCol != null && this.tableau[destCol].length === 0 ? 1 : 0); + return (this._emptyFreecells() + 1) * 2 ** Math.max(0, emptyCols); + } + + // ── move validation ────────────────────────────────────────────────────── + canMoveToFoundation(card) { return !!card && card.pval === this._foundationNext(card.suit); } + canMoveToColumn(card, destCol) { const dest = this.tableau[destCol]; if (dest.length === 0) return true; const top = dest[dest.length - 1]; - return card.isRed !== top.isRed && card.pval === top.pval - 1; + return isRed(card) !== isRed(top) && card.pval === top.pval - 1; } - canMoveRun(srcCol, fromIdx, destCol) { - if (srcCol === destCol) return false; + /** Why a run can't go there, or null when it can. */ + runBlocker(srcCol, fromIdx, destCol) { + if (srcCol === destCol) return 'same'; const run = this._validRun(srcCol, fromIdx); - if (!run) return false; - return this.canMoveToColumn(run[0], destCol); + if (!run) return 'unordered'; + if (!this.canMoveToColumn(run[0], destCol)) return 'mismatch'; + if (run.length > this.maxMovable(destCol)) return 'space'; + return null; } - // ── mutations (all return boolean) ──────────────────────────────────────── + canMoveRun(srcCol, fromIdx, destCol) { return this.runBlocker(srcCol, fromIdx, destCol) === null; } - moveToFoundation(srcKind, srcIdx) { - let card; - if (srcKind === 'tableau') { - const pile = this.tableau[srcIdx]; - if (!pile.length) return false; - card = pile[pile.length - 1]; - } else { - card = this.freecells[srcIdx]; - if (!card) return false; + // ── generic moves ──────────────────────────────────────────────────────── + cardsOf(from, n = 1) { + if (from.kind === 'cell') return this.freecells[from.i] ? [this.freecells[from.i]] : []; + const pile = this.tableau[from.i]; + return n > 0 && n <= pile.length ? pile.slice(pile.length - n) : []; + } + + isLegal(m) { + const n = m.n ?? 1; + const cards = this.cardsOf(m.from, n); + if (!cards.length || cards.length !== n) return false; + if (m.from.kind === 'cell' && n !== 1) return false; + if (m.to.kind === 'found') return n === 1 && this.canMoveToFoundation(cards[0]); + if (m.to.kind === 'cell') { + if (n !== 1 || m.from.kind === 'cell') return false; + const i = m.to.i ?? this.freecells.indexOf(null); + return i >= 0 && this.freecells[i] === null; } - if (!this.canMoveToFoundation(card)) return false; - this.foundations[card.suit].push(card); - if (srcKind === 'tableau') this.tableau[srcIdx].pop(); - else this.freecells[srcIdx] = null; - this.moveCount++; - return true; - } - - moveToFreecell(srcCol) { - const pile = this.tableau[srcCol]; - if (!pile.length) return false; - const fcIdx = this.freecells.indexOf(null); - if (fcIdx === -1) return false; - this.freecells[fcIdx] = pile.pop(); - this.moveCount++; - return true; - } - - moveFromFreecellToFoundation(fcIdx) { - return this.moveToFoundation('freecell', fcIdx); - } - - moveFromFreecellToColumn(fcIdx, destCol) { - const card = this.freecells[fcIdx]; - if (!card) return false; - if (!this.canMoveToColumn(card, destCol)) return false; - this.tableau[destCol].push(card); - this.freecells[fcIdx] = null; - this.moveCount++; - return true; - } - - moveRun(srcCol, fromIdx, destCol) { - if (!this.canMoveRun(srcCol, fromIdx, destCol)) return false; - const run = this.tableau[srcCol].splice(fromIdx); - this.tableau[destCol].push(...run); - this.moveCount++; - return true; - } - - // ── queries ──────────────────────────────────────────────────────────────── - - hasMoves() { - const allCards = [ - ...this.freecells.filter(Boolean), - ...this.tableau.map((col) => col[col.length - 1]).filter(Boolean), - ]; - // Any card to foundation? - if (allCards.some((c) => this.canMoveToFoundation(c))) return true; - // Any card to freecell? - if (this._emptyFreecells() > 0 && this.tableau.some((col) => col.length > 0)) return true; - // Any card/run to any column? - for (let dest = 0; dest < 8; dest++) { - for (const card of allCards) { - if (this.canMoveToColumn(card, dest)) return true; - } - // Runs from tableau to any column - for (let src = 0; src < 8; src++) { - if (src === dest) continue; - const pile = this.tableau[src]; - for (let idx = 0; idx < pile.length; idx++) { - if (this.canMoveRun(src, idx, dest)) return true; - } + if (m.to.kind === 'col') { + if (m.from.kind === 'col') { + const pile = this.tableau[m.from.i]; + return this.canMoveRun(m.from.i, pile.length - n, m.to.i); } + return this.canMoveToColumn(cards[0], m.to.i); } return false; } - isWon() { - return SUITS.every((s) => this.foundations[s].length === 13); + /** Apply a legal move; returns the moved cards (empty when illegal). */ + apply(m) { + if (!this.isLegal(m)) return []; + const n = m.n ?? 1; + let cards; + if (m.from.kind === 'cell') { cards = [this.freecells[m.from.i]]; this.freecells[m.from.i] = null; } + else cards = this.tableau[m.from.i].splice(this.tableau[m.from.i].length - n); + if (m.to.kind === 'found') this.foundations[cards[0].suit].push(cards[0]); + else if (m.to.kind === 'cell') this.freecells[m.to.i ?? this.freecells.indexOf(null)] = cards[0]; + else this.tableau[m.to.i].push(...cards); + this.moveCount++; + return cards; } - // Simulate foundation-only play; returns true if all 52 cards would clear. + /** Every legal move from here (runs of every movable length; cells to the first empty cell). */ + legalMoves() { + const out = []; + const firstCell = this.freecells.indexOf(null); + for (let i = 0; i < 4; i++) { + const c = this.freecells[i]; + if (!c) continue; + const from = { kind: 'cell', i }; + if (this.canMoveToFoundation(c)) out.push({ from, to: { kind: 'found' }, n: 1 }); + for (let d = 0; d < 8; d++) if (this.canMoveToColumn(c, d)) out.push({ from, to: { kind: 'col', i: d }, n: 1 }); + } + for (let s = 0; s < 8; s++) { + const pile = this.tableau[s]; + if (!pile.length) continue; + const from = { kind: 'col', i: s }; + const top = pile[pile.length - 1]; + if (this.canMoveToFoundation(top)) out.push({ from, to: { kind: 'found' }, n: 1 }); + if (firstCell >= 0) out.push({ from, to: { kind: 'cell', i: firstCell }, n: 1 }); + const start = this.runStart(s); + for (let d = 0; d < 8; d++) { + if (d === s) continue; + for (let idx = start; idx < pile.length; idx++) { + if (this.canMoveRun(s, idx, d)) out.push({ from, to: { kind: 'col', i: d }, n: pile.length - idx }); + } + } + } + return out; + } + + // ── classic mutations (kept for callers/tests; all return boolean) ─────── + moveToFoundation(srcKind, srcIdx) { + const from = srcKind === 'tableau' ? { kind: 'col', i: srcIdx } : { kind: 'cell', i: srcIdx }; + return this.apply({ from, to: { kind: 'found' }, n: 1 }).length > 0; + } + moveToFreecell(srcCol) { return this.apply({ from: { kind: 'col', i: srcCol }, to: { kind: 'cell' }, n: 1 }).length > 0; } + moveFromFreecellToFoundation(fcIdx) { return this.moveToFoundation('freecell', fcIdx); } + moveFromFreecellToColumn(fcIdx, destCol) { return this.apply({ from: { kind: 'cell', i: fcIdx }, to: { kind: 'col', i: destCol }, n: 1 }).length > 0; } + moveRun(srcCol, fromIdx, destCol) { + const n = this.tableau[srcCol].length - fromIdx; + return this.apply({ from: { kind: 'col', i: srcCol }, to: { kind: 'col', i: destCol }, n }).length > 0; + } + + // ── queries ────────────────────────────────────────────────────────────── + hasMoves() { return this.legalMoves().length > 0; } + + isWon() { return SUITS.every((s) => this.foundations[s].length === 13); } + + homeCount() { return SUITS.reduce((t, s) => t + this.foundations[s].length, 0); } + + /** + * A card is safe to send home when nothing could ever need to be built on + * it: both opposite-colour cards one rank lower are already home (Aces and + * Twos are always safe). + */ + isSafeHome(card) { + if (!this.canMoveToFoundation(card)) return false; + if (card.pval <= 2) return true; + const opp = isRed(card) ? ['s', 'c'] : ['h', 'd']; + return opp.every(s => this.foundations[s].length >= card.pval - 1); + } + + /** The next safe foundation move (cells first, then columns), or null. */ + nextSafeMove() { + for (let i = 0; i < 4; i++) { + const c = this.freecells[i]; + if (c && this.isSafeHome(c)) return { from: { kind: 'cell', i }, to: { kind: 'found' }, n: 1 }; + } + for (let s = 0; s < 8; s++) { + const pile = this.tableau[s]; + const top = pile[pile.length - 1]; + if (top && this.isSafeHome(top)) return { from: { kind: 'col', i: s }, to: { kind: 'found' }, n: 1 }; + } + return null; + } + + /** True when playing straight to the foundations would clear everything. */ canAutoComplete() { const need = {}; for (const s of SUITS) need[s] = this._foundationNext(s); const cols = this.tableau.map((col) => col.slice()); const fcs = this.freecells.slice(); let remaining = cols.reduce((t, c) => t + c.length, 0) + fcs.filter(Boolean).length; - if (remaining === 0) return true; let moved = true; while (remaining > 0 && moved) { moved = false; for (let i = 0; i < 4; i++) { - if (fcs[i] && fcs[i].pval === need[fcs[i].suit]) { - need[fcs[i].suit]++; - fcs[i] = null; - remaining--; - moved = true; - } + if (fcs[i] && fcs[i].pval === need[fcs[i].suit]) { need[fcs[i].suit]++; fcs[i] = null; remaining--; moved = true; } } for (const col of cols) { const top = col[col.length - 1]; - if (top && top.pval === need[top.suit]) { - col.pop(); - need[top.suit]++; - remaining--; - moved = true; - } + if (top && top.pval === need[top.suit]) { col.pop(); need[top.suit]++; remaining--; moved = true; } } } return remaining === 0; } - // Returns the next card that can go to a foundation, or null. - // Checks freecells first, then tableau tops. + /** Next card the auto-complete would send home (lowest rank first so it looks orderly). */ autoCompleteStep() { - for (let i = 0; i < 4; i++) { - const card = this.freecells[i]; - if (card && this.canMoveToFoundation(card)) return { card, srcKind: 'freecell', srcIdx: i }; + let best = null; + const consider = (card, move) => { if (card && this.canMoveToFoundation(card) && (!best || card.pval < best.card.pval)) best = { card, move }; }; + for (let i = 0; i < 4; i++) consider(this.freecells[i], { from: { kind: 'cell', i }, to: { kind: 'found' }, n: 1 }); + for (let s = 0; s < 8; s++) { + const pile = this.tableau[s]; + consider(pile[pile.length - 1], { from: { kind: 'col', i: s }, to: { kind: 'found' }, n: 1 }); } - for (let c = 0; c < 8; c++) { - const pile = this.tableau[c]; - const top = pile[pile.length - 1]; - if (top && this.canMoveToFoundation(top)) return { card: top, srcKind: 'tableau', srcIdx: c }; - } - return null; + return best; } } diff --git a/src/games/freecell/FreecellSolver.js b/src/games/freecell/FreecellSolver.js new file mode 100644 index 0000000..ce35e28 --- /dev/null +++ b/src/games/freecell/FreecellSolver.js @@ -0,0 +1,258 @@ +// Freecell solver — Phaser-free best-first search (hints + "can this still be won?"). +// +// const s = new FreecellSolver(engine, { maxNodes }); +// while (!s.done) s.step(2000); // resumable: the scene time-slices it +// s.result → { status: 'solved' | 'unsolvable' | 'gaveup', moves?, nodes } +// +// 'unsolvable' is only reported when the whole reachable space was searched +// (honest: the deal really is lost). 'gaveup' means the node budget ran out. +// +// State: 8 columns of card codes (suit * 13 + rank - 1, suits in SUITS order), +// 4 cells (-1 = empty), 4 foundation counts. Children are atomic moves plus +// supermoves within the (cells + 1) × 2^emptyCols limit; after every move the +// safe foundation plays are applied (they can never hurt), recorded as moves +// so a solution replays exactly on the engine. Duplicate positions are cut +// with a canonical key (columns and cells sorted). + +import { SUITS } from '../cards/Deck.js'; + +const SUIT_IDX = Object.fromEntries(SUITS.map((s, i) => [s, i])); +const RED = SUITS.map(s => s === 'h' || s === 'd'); +const rankOf = (c) => (c % 13) + 1; +const suitOf = (c) => (c / 13) | 0; +const redOf = (c) => RED[suitOf(c)]; +const codeOf = (card) => SUIT_IDX[card.suit] * 13 + card.pval - 1; +const OPP = SUITS.map((_, i) => SUITS.map((__, j) => j).filter(j => RED[j] !== RED[i])); + +export function stateFromEngine(e) { + return { + cols: e.tableau.map(col => col.map(codeOf)), + cells: e.freecells.map(c => (c ? codeOf(c) : -1)), + found: SUITS.map(s => e.foundations[s].length), + }; +} + +const clone = (s) => ({ cols: s.cols.map(c => c.slice()), cells: s.cells.slice(), found: s.found.slice() }); + +export function stateKey(s) { + const cols = s.cols.map(c => String.fromCharCode(...c.map(x => x + 65))).sort(); + const cells = s.cells.filter(c => c >= 0).sort((a, b) => a - b).map(x => String.fromCharCode(x + 65)).join(''); + return `${cols.join('|')}#${cells}#${s.found.join('')}`; +} + +/** Order-exact key (column and cell positions matter) — for replaying a stored line. */ +export function exactKey(s) { + return `${s.cols.map(c => String.fromCharCode(...c.map(x => x + 65))).join('|')}#${s.cells.map(c => (c < 0 ? '.' : String.fromCharCode(c + 65))).join('')}#${s.found.join(',')}`; +} + +const canStack = (card, onto) => redOf(card) !== redOf(onto) && rankOf(card) === rankOf(onto) - 1; +const canHome = (s, c) => rankOf(c) === s.found[suitOf(c)] + 1; +function isSafe(s, c) { + if (!canHome(s, c)) return false; + const r = rankOf(c); + if (r <= 2) return true; + return OPP[suitOf(c)].every(j => s.found[j] >= r - 1); +} + +function emptyCols(s) { let n = 0; for (const c of s.cols) if (!c.length) n++; return n; } +function emptyCells(s) { let n = 0; for (const c of s.cells) if (c < 0) n++; return n; } +const capacity = (s, destEmpty) => (emptyCells(s) + 1) * 2 ** Math.max(0, emptyCols(s) - (destEmpty ? 1 : 0)); + +function runStart(col) { + let i = col.length - 1; + while (i > 0 && canStack(col[i], col[i - 1])) i--; + return Math.max(0, i); +} + +/** Apply a move to a solver state (assumed legal). Returns the move in engine form. */ +function applyRaw(s, m) { + let cards; + if (m.from.kind === 'cell') { cards = [s.cells[m.from.i]]; s.cells[m.from.i] = -1; } + else cards = s.cols[m.from.i].splice(s.cols[m.from.i].length - m.n); + if (m.to.kind === 'found') s.found[suitOf(cards[0])]++; + else if (m.to.kind === 'cell') s.cells[m.to.i] = cards[0]; + else s.cols[m.to.i].push(...cards); +} + +/** Apply safe foundation plays to a fixpoint (cells first, then columns — the engine's order). */ +export function autoSafe(s, out = []) { + for (;;) { + let m = null; + for (let i = 0; i < 4 && !m; i++) if (s.cells[i] >= 0 && isSafe(s, s.cells[i])) m = { from: { kind: 'cell', i }, to: { kind: 'found' }, n: 1, auto: true }; + for (let i = 0; i < 8 && !m; i++) { + const col = s.cols[i]; + if (col.length && isSafe(s, col[col.length - 1])) m = { from: { kind: 'col', i }, to: { kind: 'found' }, n: 1, auto: true }; + } + if (!m) return out; + applyRaw(s, m); + out.push(m); + } +} + +function children(s) { + const out = []; + const firstCell = s.cells.indexOf(-1); + const firstEmpty = s.cols.findIndex(c => !c.length); + // foundation plays that weren't auto-safe + for (let i = 0; i < 4; i++) if (s.cells[i] >= 0 && canHome(s, s.cells[i])) out.push({ from: { kind: 'cell', i }, to: { kind: 'found' }, n: 1 }); + for (let i = 0; i < 8; i++) { + const col = s.cols[i]; + if (col.length && canHome(s, col[col.length - 1])) out.push({ from: { kind: 'col', i }, to: { kind: 'found' }, n: 1 }); + } + // column → column (runs) + for (let a = 0; a < 8; a++) { + const src = s.cols[a]; + if (!src.length) continue; + const start = runStart(src); + const runLen = src.length - start; + for (let b = 0; b < 8; b++) { + if (a === b) continue; + const dst = s.cols[b]; + if (dst.length) { + const top = dst[dst.length - 1]; + // the card in the run that fits on `top` + for (let k = start; k < src.length; k++) { + if (canStack(src[k], top)) { + const n = src.length - k; + if (n <= capacity(s, false)) out.push({ from: { kind: 'col', i: a }, to: { kind: 'col', i: b }, n }); + break; + } + } + } else if (b === firstEmpty) { + const cap = capacity(s, true); + for (let n = Math.min(runLen, cap); n >= 1; n--) { + if (n === src.length) continue; // whole column into an empty one: pointless + out.push({ from: { kind: 'col', i: a }, to: { kind: 'col', i: b }, n }); + } + } + } + } + // cell → column + for (let i = 0; i < 4; i++) { + const c = s.cells[i]; + if (c < 0) continue; + for (let b = 0; b < 8; b++) { + const dst = s.cols[b]; + if (dst.length ? canStack(c, dst[dst.length - 1]) : b === firstEmpty) out.push({ from: { kind: 'cell', i }, to: { kind: 'col', i: b }, n: 1 }); + } + } + // column → cell + if (firstCell >= 0) { + for (let a = 0; a < 8; a++) if (s.cols[a].length) out.push({ from: { kind: 'col', i: a }, to: { kind: 'cell', i: firstCell }, n: 1 }); + } + return out; +} + +/** Lower is better. */ +export function heuristic(s) { + let home = 0; + for (const f of s.found) home += f; + let h = (52 - home) * 4; + // cards stacked above the next card each suit needs + const need = s.found.map((f, i) => i * 13 + f); // code of the next card per suit (rank f+1) + for (const col of s.cols) { + for (let k = 0; k < col.length; k++) { + const c = col[k]; + if (need[suitOf(c)] === c) h += (col.length - 1 - k) * 3; + } + // out-of-order breaks + for (let k = 1; k < col.length; k++) if (!canStack(col[k], col[k - 1])) h += 2; + } + for (const c of s.cells) if (c >= 0) h += 3; + h -= emptyCols(s) * 4; + return h; +} + +// ── a small binary heap ───────────────────────────────────────────────────── +class Heap { + constructor() { this.a = []; } + get size() { return this.a.length; } + push(n) { + const a = this.a; a.push(n); + let i = a.length - 1; + while (i > 0) { + const p = (i - 1) >> 1; + if (a[p].f <= n.f) break; + a[i] = a[p]; i = p; + } + a[i] = n; + } + pop() { + const a = this.a, top = a[0], last = a.pop(); + if (a.length) { + let i = 0; + for (;;) { + const l = i * 2 + 1, r = l + 1; + let m = i; + const fm = () => (m === i ? last.f : a[m].f); + if (l < a.length && a[l].f < fm()) m = l; + if (r < a.length && a[r].f < fm()) m = r; + if (m === i) break; + a[i] = a[m]; i = m; + } + a[i] = last; + } + return top; + } +} + +export class FreecellSolver { + constructor(engineOrState, { maxNodes = 120000, depthWeight = 1 } = {}) { + const s0 = engineOrState.tableau ? stateFromEngine(engineOrState) : clone(engineOrState); + const pre = autoSafe(s0); + this.maxNodes = maxNodes; + this.depthWeight = depthWeight; + this.seen = new Set([stateKey(s0)]); + this.heap = new Heap(); + this.nodes = 0; + this.done = false; + this.result = null; + const root = { s: s0, parent: null, moves: pre, depth: 0, f: 0 }; + if (s0.found.every(f => f === 13)) this.finish('solved', root); + else this.heap.push(root); + } + + finish(status, node = null) { + this.done = true; + let moves; + if (node) { + const chain = []; + for (let n = node; n; n = n.parent) chain.push(n.moves); + moves = chain.reverse().flat(); + } + this.result = { status, moves, nodes: this.nodes }; + this.heap = null; + this.seen = null; + } + + /** Expand up to `budget` nodes. Returns this.done. */ + step(budget = 2000) { + if (this.done) return true; + for (let b = 0; b < budget; b++) { + if (!this.heap.size) { this.finish('unsolvable'); return true; } + if (this.nodes >= this.maxNodes) { this.finish('gaveup'); return true; } + const node = this.heap.pop(); + this.nodes++; + for (const m of children(node.s)) { + const s = clone(node.s); + applyRaw(s, m); + const moves = [m]; + autoSafe(s, moves); + const key = stateKey(s); + if (this.seen.has(key)) continue; + this.seen.add(key); + const child = { s, parent: node, moves, depth: node.depth + 1, f: 0 }; + if (s.found.every(f => f === 13)) { this.finish('solved', child); return true; } + child.f = heuristic(s) + child.depth * this.depthWeight; + this.heap.push(child); + } + } + return false; + } + + /** Run to completion synchronously (tests / small budgets). */ + run() { while (!this.step(5000)); return this.result; } +} + +/** Convenience: solve an engine position synchronously. */ +export function solve(engine, opts) { return new FreecellSolver(engine, opts).run(); } diff --git a/src/games/freecell/FreecellTable.js b/src/games/freecell/FreecellTable.js new file mode 100644 index 0000000..15ccb3e --- /dev/null +++ b/src/games/freecell/FreecellTable.js @@ -0,0 +1,71 @@ +// Freecell table layout — Phaser-free so tools/verifyFreecell.js can test it. +// +// The Night Study: a walnut desk seen from above, a tooled leather blotter +// holding the game, and a strip of the room along the top (bookshelf, a +// rain-streaked window, the mantel clock). Cards are flat (q = 1) at scale S. +// +// free cells: brass card clips, top-left foundations: engraved trays, top-right +// 8 columns below, fanning down and squeezing to fit above the bottom edge +// left desk: the deal card (deal no., cards home, move capacity, winnable?) +// right desk: the banker's lamp, the leather dock (bottom-right) + +import { CARD_W, CARD_H, flatPose, columnPoses, stackPose, poseRect, cardBounds } from '../../ui/solitaire/SolitaireGeometry.js'; +import { FOUNDATION_ORDER } from './FreecellLogic.js'; + +export const W = 1920, H = 1080; +export const S = 1.12; +export const CW = CARD_W * S, CH = CARD_H * S; +export const WALL_H = 150; // the room strip above the desk +export const BLOTTER = { x0: 378, x1: 1552, y0: 168, y1: 1074 }; +export const ROW_Y = 254; // free cells + foundations +export const TAB_TOP = 436; // first card of each column (centre) +export const MAX_BOTTOM = 1066; // a column's last card stays above this +export const COL_GAP = 148; +export const colX = (c) => 960 + (c - 3.5) * COL_GAP; +export const STEP = 36; // preferred fan step (px at s = 1) + +export const cellPose = (i) => flatPose(colX(i) - 14, ROW_Y, S); +export const foundPose = (i) => flatPose(colX(4 + i) + 14, ROW_Y, S); +export const foundIndex = (suit) => FOUNDATION_ORDER.indexOf(suit); +export const DECK = flatPose(196, 760, S); + +/** Poses for column c holding n cards. */ +export const columnPosesFor = (c, n) => columnPoses(n, null, { x: colX(c), top: TAB_TOP, s: S, maxBottom: MAX_BOTTOM, step: STEP, minStep: 12 }); + +/** Where the k-th card (0-based) of a foundation pile sits. */ +export const foundCardPose = (i, k) => stackPose(foundPose(i), k, 13, 0.22, 3); + +// ── Room furniture (painted by FreecellArt; animated by the scene) ─────────── +export const WINDOW = { x0: 716, x1: 1204, y0: 0, y1: 136 }; // rain panes +export const CLOCK = { x: 1380, y: 76, r: 54 }; // mantel clock face +export const PLAQUE = { x: 1642, y: 76, w: 300, h: 74 }; // brass time + moves plaque +export const DEAL_CARD = { x: 196, y: 330, w: 316, h: 300 }; // left desk index card +export const LAMP = { x: 1738, y: 300 }; // banker's lamp (desk, right) +export const POOL = { x: 1010, y: 610 }; // where the lamp light falls +export const DOCK = { x0: 1588, x1: 1904, y0: 846, y1: 1072 }; +export const TOP_BUTTONS = [ + { x: 70, y: 38, w: 110, h: 40 }, { x: 190, y: 38, w: 110, h: 40 }, { x: 310, y: 38, w: 110, h: 40 }, +]; +export const KEYS = { x0: 16, x1: 360, y0: 1036, y1: 1078 }; + +const centre = (r) => ({ x0: r.x - r.w / 2, x1: r.x + r.w / 2, y0: r.y - r.h / 2, y1: r.y + r.h / 2 }); + +/** HUD rects the cards must never sit under (named, for the verify script). */ +export function hudRects() { + return [ + ...TOP_BUTTONS.map((b, i) => ({ name: `top button ${i}`, r: centre(b) })), + { name: 'dock', r: DOCK }, + { name: 'deal card', r: centre(DEAL_CARD) }, + { name: 'keys line', r: KEYS }, + { name: 'plaque', r: centre(PLAQUE) }, + ]; +} + +/** Drop zone for column c (the whole column strip). */ +export function columnZone(c) { + return { x0: colX(c) - CW / 2 - 16, x1: colX(c) + CW / 2 + 16, y0: TAB_TOP - CH / 2 - 30, y1: MAX_BOTTOM + 10 }; +} +export const cellZone = (i) => poseRect(cellPose(i), 18); +export const foundZone = (i) => poseRect(foundPose(i), 18); + +export { flatPose, poseRect, cardBounds }; diff --git a/src/games/freecell/tutorial.md b/src/games/freecell/tutorial.md new file mode 100644 index 0000000..48715be --- /dev/null +++ b/src/games/freecell/tutorial.md @@ -0,0 +1,111 @@ +# Freecell: A Tutorial by Professor Quill + +*Good evening. I'm Mabel Quill — forty years a reference librarian, and for most of them the last one to leave the reading room. On wet nights I'd stay on with the lamp, a pot of tea and a deck of cards, because Freecell is the rare solitaire where luck has almost nothing to say. Every card is face-up from the start. If you lose, the cards were never against you — you simply haven't found the line yet. Pull up a chair.* + +--- + +## The Goal + +Move all **52 cards** onto the four **foundations** (the engraved trays, top right), building each one **up by suit from Ace to King**: A♠, 2♠, 3♠ … K♠. + +--- + +## The Desk + +- **The eight columns** (the middle of the blotter): the whole deck is dealt into them, face-up — four columns of seven and four of six. +- **The four free cells** (the brass card clips, top left): each holds **one card**, any card, for as long as you like. +- **The four foundations** (top right): one per suit, Ace first. +- **The deal card** (the index card on the left): which deal you're playing, how many cards are home, and how many cards you can move at once. +- **The mantel clock and the brass plaque** (above the desk): your time and your move count. + +--- + +## Moving Cards + +You may move only **the top card** of a column or a card in a free cell: + +- **To a foundation** — if it's the next card of that suit. +- **To a free cell** — if one is empty. +- **Onto another column** — if it's **one rank lower and the opposite colour** (a red 7 on a black 8, a black 7 on a red 8). +- **Into an empty column** — any card at all. + +**Drag** a card to move it; every place it could legally go glows as you carry it. Or just **click** it, and it goes to its best spot (home first, then onto another column, then a free cell). If it can't move, it gives a little shake and tells you why. + +*Prefer the old way?* Under **Menu → Settings → Clicking a card**, choose **Selects it**: click a card to pick it up (it glows green), then click where it should go. A **double-click** always sends a card home if it can go. + +--- + +## Moving Runs — "How Many Can I Move?" + +Strictly, Freecell moves one card at a time. But a run of cards that's already in order (descending, alternating colours) can be moved together, because you *could* shuffle it across one card at a time through your empty spaces. The desk does that bookkeeping for you: + +| Empty free cells | Empty columns | Cards you can move | +|---|---|---| +| 0 | 0 | 1 | +| 1 | 0 | 2 | +| 2 | 0 | 3 | +| 3 | 0 | 4 | +| 1 | 1 | 4 | +| 2 | 1 | 6 | +| 4 | 1 | 10 | + +The rule is **(free cells + 1) × 2 for every empty column**. One catch: when you move a run **into** an empty column, that column can't also be used as a stepping stone, so it doesn't count. + +The deal card always shows your current number ("Can move 6 at once"). Hover over it for a reminder of the rule. Try to move a run that's too long and you'll be told exactly how much room you have. + +--- + +## Help When You Want It + +- **Undo** (Z) — as many moves back as you like. **Redo** is Y. +- **Restart** (R) — puts every card back where it was dealt. You can still Undo the restart. +- **Hint** (H) — an arrow shows a good next move. Behind it is a real solver, quietly working through the position, so the hint is a move on an actual winning line whenever one can be found. +- **"Still winnable?"** — the bottom of the deal card says whether the position can still be won. If a move ever makes the deal impossible, the lamp dims and the card says so. That's your cue to Undo a few moves. (You can switch this off in Settings if you'd rather not know.) +- **Safe auto-play** — cards that nothing could ever need to be built on (Aces, Twos, and any card whose two lower opposite-colour cards are already home) fly to the foundations by themselves. Turn it off in Settings if you like to do it all by hand. +- **Finish** (Space) — once every remaining card can simply go home, the dock offers **Finish ▶** and the desk tidies up for you. + +--- + +## Choosing a Deal + +Every deal has a **number from 1 to 1,000,000**, and the same number is the same deal for everyone. Open **Menu → Choose a deal…** to: + +- take a **random deal**, +- play **today's deal** (a new one every day — compare notes with a friend), or +- type in any deal number, to replay a favourite or try one you've been told about. + +After a win you can **Replay Deal** to try for a faster time or fewer moves. + +--- + +## Records + +The **Stats** button opens your ledger: games played and won, your current and best winning streak, your fastest win and your fewest moves, and a row of ticks for your recent deals. **An unfinished deal counts as a loss.** If you start a new deal or leave after making a move, the game will check with you first. + +--- + +## Keyboard + +| Key | Does | +|---|---| +| Z / Ctrl+Z | Undo | +| Y / Ctrl+Shift+Z | Redo | +| H | Hint | +| Space | Finish (when it's offered) | +| R | Restart this deal | +| N | New deal | +| Esc | Menu (or drop a selected card) | + +--- + +## The Professor's Advice + +1. **Free cells are precious.** Each one you fill halves your ability to move runs. Fill them only with a plan to empty them again. +2. **An empty column is worth two free cells.** Clearing a short column early is often the best move on the board. +3. **Dig for the Aces and Twos.** Note where they're buried, and work towards them. +4. **Don't build on a card you'll need soon.** Burying the 3♣ under a long run when the clubs foundation is at 2 will cost you later. +5. **Before a big move, count.** Check the deal card: can you actually move that run? +6. **Kings belong at the top of an empty column.** A King anywhere else is a wall. +7. **When stuck, Undo is not cheating.** It's how every good player learns to see further ahead. + +*Nearly every Freecell deal can be won. The lamp will tell you if you've wandered off the path. Now — more tea?* diff --git a/src/games/solitairetour/SolitaireTourArt.js b/src/games/solitairetour/SolitaireTourArt.js new file mode 100644 index 0000000..dbaecca --- /dev/null +++ b/src/games/solitairetour/SolitaireTourArt.js @@ -0,0 +1,665 @@ +// Solitaire Tour art — five rooms on one trip, baked lazily (no image files). +// +// st-room- 1920×1080 room for that leg: a wall strip with a window +// onto the place, the playing surface with its pile spots, +// and the floor/furniture around it +// golf The Old Links Clubhouse — oak, tartan baize, the links at dusk +// klondike A Gold-Rush Cabin — log walls, pine planks, snowy peaks +// pyramid The Terrace at Giza — sandstone, a brass tray table, the pyramids +// fourteen The Riverboat Salon — mahogany, green baize, moonlit river +// threeshuffles Café de la Belle Lucie — marble, zinc, Paris rooftops at dusk +// st-back travel card back (navy, gold compass rose) +// st-scorecard the golf-style scorecard (left of every room) +// st-plate the leg plate (right of every room) +// st-post- a postcard of each stop (interlude between legs) +// st-map the route map (parchment world) + +import { prepareCasinoArt, drawSuit, canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { W, H, WALL_H, PLAY, WINDOW, SCORECARD, PLATE } from './SolitaireTourTable.js'; +import { TOUR } from './SolitaireTourLogic.js'; + +let seed = 1; +const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }; +const reseed = (n) => { seed = n; }; + +// ── Themes ─────────────────────────────────────────────────────────────────── +export const THEMES = { + golf: { wall: ['#2a1a0e', '#3a2414'], trim: '#c9973c', floor: 'wood', floorTones: ['#2e1c10', '#22140a'], surface: 'tartan', light: '255,226,180', lightAt: { x: 960, y: 520 }, flicker: 0.02, life: 'clouds', ambience: null }, + klondike: { wall: ['#3a2414', '#4a2e18'], trim: '#8a5a2c', floor: 'planks', floorTones: ['#3a2615', '#2a1a0c'], surface: 'pine', light: '255,190,110', lightAt: { x: 980, y: 560 }, flicker: 0.07, life: 'snow', ambience: 'wind' }, + pyramid: { wall: ['#8a6a44', '#6a4e30'], trim: '#e0b860', floor: 'carpet', floorTones: ['#4a1414', '#2a0a0a'], surface: 'brass', light: '255,200,130', lightAt: { x: 960, y: 520 }, flicker: 0.05, life: 'stars', ambience: null }, + fourteen: { wall: ['#2a0e0a', '#3a1610'], trim: '#d9b45a', floor: 'carpet', floorTones: ['#3a0c10', '#200608'], surface: 'baize', light: '255,214,150', lightAt: { x: 960, y: 500 }, flicker: 0.03, life: 'river', ambience: 'water' }, + threeshuffles: { wall: ['#d8c8a8', '#c4b08a'], trim: '#3a2a1a', floor: 'checker', floorTones: ['#e8e2d4', '#1c1a18'], surface: 'marble', light: '255,222,170', lightAt: { x: 960, y: 520 }, flicker: 0.02, life: 'rain', ambience: 'rain' }, +}; + +// ── Window vistas (also the postcard pictures) ─────────────────────────────── +function sky(ctx, x, y, w, h, stops) { + const g = ctx.createLinearGradient(0, y, 0, y + h); + stops.forEach(([t, c]) => g.addColorStop(t, c)); + ctx.fillStyle = g; + ctx.fillRect(x, y, w, h); +} +function hills(ctx, x, y, w, h, base, color, amp, freq, phase) { + ctx.beginPath(); + ctx.moveTo(x, y + h); + for (let i = 0; i <= 60; i++) { + const t = i / 60; + ctx.lineTo(x + t * w, y + base * h - Math.sin(t * freq + phase) * amp * h - Math.sin(t * freq * 2.3 + phase * 1.7) * amp * 0.4 * h); + } + ctx.lineTo(x + w, y + h); + ctx.closePath(); + ctx.fillStyle = color; + ctx.fill(); +} +function stars(ctx, x, y, w, h, n, alpha = 0.8) { + for (let i = 0; i < n; i++) { + ctx.fillStyle = `rgba(255,250,230,${alpha * (0.3 + rnd() * 0.7)})`; + ctx.beginPath(); ctx.arc(x + rnd() * w, y + rnd() * h, 0.6 + rnd() * 1.2, 0, Math.PI * 2); ctx.fill(); + } +} + +export function vista(ctx, leg, x, y, w, h) { + ctx.save(); + ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); + reseed(TOUR.indexOf(leg) * 101 + 7); + if (leg === 'golf') { + sky(ctx, x, y, w, h, [[0, '#2a3a6a'], [0.45, '#e08a5a'], [0.7, '#f6c47a'], [1, '#f6c47a']]); + ctx.fillStyle = 'rgba(255,240,200,0.9)'; + ctx.beginPath(); ctx.arc(x + w * 0.72, y + h * 0.58, h * 0.1, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#3a5a7a'; ctx.fillRect(x, y + h * 0.6, w, h * 0.06); // the sea + hills(ctx, x, y, w, h, 0.72, '#3f6a34', 0.05, 5, 0.4); + hills(ctx, x, y, w, h, 0.84, '#2f5428', 0.04, 7, 1.2); + ctx.fillStyle = '#d9c98a'; + ctx.beginPath(); ctx.ellipse(x + w * 0.3, y + h * 0.9, w * 0.07, h * 0.035, 0, 0, Math.PI * 2); ctx.fill(); // bunker + ctx.fillStyle = '#5a8a44'; + ctx.beginPath(); ctx.ellipse(x + w * 0.55, y + h * 0.86, w * 0.09, h * 0.04, 0, 0, Math.PI * 2); ctx.fill(); // the green + ctx.strokeStyle = '#eee'; ctx.lineWidth = Math.max(1, w / 300); + ctx.beginPath(); ctx.moveTo(x + w * 0.56, y + h * 0.86); ctx.lineTo(x + w * 0.56, y + h * 0.66); ctx.stroke(); + ctx.fillStyle = '#d02a2a'; + ctx.beginPath(); ctx.moveTo(x + w * 0.56, y + h * 0.66); ctx.lineTo(x + w * 0.6, y + h * 0.69); ctx.lineTo(x + w * 0.56, y + h * 0.72); ctx.closePath(); ctx.fill(); + } else if (leg === 'klondike') { + sky(ctx, x, y, w, h, [[0, '#0c1428'], [1, '#2a3a5a']]); + stars(ctx, x, y, w, h * 0.5, Math.round(w * h / 900)); + hills(ctx, x, y, w, h, 0.55, '#c8d4e8', 0.22, 4, 0.2); // snowy peaks + hills(ctx, x, y, w, h, 0.7, '#8a9ab8', 0.1, 6, 2.1); + for (let i = 0; i < 26; i++) { // pines + const px = x + rnd() * w, py = y + h * (0.78 + rnd() * 0.2), s = h * (0.12 + rnd() * 0.1); + ctx.fillStyle = '#12261c'; + ctx.beginPath(); ctx.moveTo(px, py - s); ctx.lineTo(px + s * 0.35, py); ctx.lineTo(px - s * 0.35, py); ctx.closePath(); ctx.fill(); + ctx.fillStyle = 'rgba(230,240,255,0.6)'; + ctx.beginPath(); ctx.moveTo(px, py - s); ctx.lineTo(px + s * 0.12, py - s * 0.62); ctx.lineTo(px - s * 0.12, py - s * 0.62); ctx.closePath(); ctx.fill(); + } + ctx.fillStyle = '#e8eef8'; ctx.fillRect(x, y + h * 0.95, w, h * 0.05); + } else if (leg === 'pyramid') { + sky(ctx, x, y, w, h, [[0, '#1a1440'], [0.55, '#8a3a5a'], [0.85, '#e8904a'], [1, '#f0b060']]); + stars(ctx, x, y, w, h * 0.45, Math.round(w * h / 700)); + ctx.fillStyle = '#fff4d0'; + ctx.beginPath(); ctx.arc(x + w * 0.18, y + h * 0.22, h * 0.07, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#1a1440'; + ctx.beginPath(); ctx.arc(x + w * 0.18 + h * 0.03, y + h * 0.2, h * 0.065, 0, Math.PI * 2); ctx.fill(); // crescent + const pyr = (cx, base, s, c) => { ctx.fillStyle = c; ctx.beginPath(); ctx.moveTo(cx - s, base); ctx.lineTo(cx, base - s * 0.78); ctx.lineTo(cx + s, base); ctx.closePath(); ctx.fill(); }; + pyr(x + w * 0.42, y + h * 0.88, h * 0.5, '#3a2030'); + pyr(x + w * 0.66, y + h * 0.88, h * 0.38, '#2e1a28'); + pyr(x + w * 0.83, y + h * 0.9, h * 0.22, '#28161e'); + ctx.fillStyle = 'rgba(255,180,100,0.25)'; + ctx.beginPath(); ctx.moveTo(x + w * 0.42, y + h * 0.88 - h * 0.39); ctx.lineTo(x + w * 0.42 + h * 0.5, y + h * 0.88); ctx.lineTo(x + w * 0.42, y + h * 0.88); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#6a3a2a'; ctx.fillRect(x, y + h * 0.88, w, h * 0.12); + } else if (leg === 'fourteen') { + sky(ctx, x, y, w, h, [[0, '#060a1a'], [0.6, '#16224a'], [1, '#16224a']]); + stars(ctx, x, y, w, h * 0.5, Math.round(w * h / 800)); + ctx.fillStyle = '#fff6da'; + ctx.beginPath(); ctx.arc(x + w * 0.66, y + h * 0.26, h * 0.1, 0, Math.PI * 2); ctx.fill(); + hills(ctx, x, y, w, h, 0.58, '#0a1410', 0.04, 9, 0.8); // far bank, trees + ctx.fillStyle = '#0c1834'; ctx.fillRect(x, y + h * 0.6, w, h * 0.4); // the river + for (let i = 0; i < 24; i++) { // moonlight on the water + const yy = y + h * (0.62 + i * 0.016), ww = w * (0.03 + rnd() * 0.08); + ctx.fillStyle = `rgba(255,240,200,${0.5 - i * 0.018})`; + ctx.fillRect(x + w * 0.66 - ww / 2 + (rnd() - 0.5) * w * 0.04, yy, ww, Math.max(1, h * 0.006)); + } + for (let i = 0; i < 7; i++) { // lights on the far bank + ctx.fillStyle = 'rgba(255,200,120,0.8)'; + ctx.beginPath(); ctx.arc(x + w * (0.05 + rnd() * 0.5), y + h * (0.56 + rnd() * 0.03), Math.max(1, h * 0.008), 0, Math.PI * 2); ctx.fill(); + } + } else { + sky(ctx, x, y, w, h, [[0, '#2a2a5a'], [0.6, '#c87a6a'], [1, '#e8b080']]); + // a lattice iron tower in the distance + const tx = x + w * 0.72, tb = y + h * 0.78, th = h * 0.68; + ctx.strokeStyle = '#2a1e2a'; ctx.lineWidth = Math.max(1, w / 260); + ctx.beginPath(); + ctx.moveTo(tx - th * 0.22, tb); ctx.quadraticCurveTo(tx - th * 0.05, tb - th * 0.45, tx, tb - th); + ctx.quadraticCurveTo(tx + th * 0.05, tb - th * 0.45, tx + th * 0.22, tb); ctx.stroke(); + for (const k of [0.25, 0.5, 0.72]) { const hw = th * 0.2 * (1 - k) + th * 0.02; ctx.beginPath(); ctx.moveTo(tx - hw, tb - th * k); ctx.lineTo(tx + hw, tb - th * k); ctx.stroke(); } + // mansard rooftops with chimneys and warm windows + let rx = x; + while (rx < x + w) { + const bw = w * (0.08 + rnd() * 0.08), bh = h * (0.25 + rnd() * 0.2); + ctx.fillStyle = '#2a2430'; + ctx.beginPath(); ctx.moveTo(rx, y + h); ctx.lineTo(rx, y + h - bh); ctx.lineTo(rx + bw * 0.12, y + h - bh - h * 0.06); ctx.lineTo(rx + bw * 0.88, y + h - bh - h * 0.06); ctx.lineTo(rx + bw, y + h - bh); ctx.lineTo(rx + bw, y + h); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#3a2e36'; ctx.fillRect(rx + bw * 0.6, y + h - bh - h * 0.14, bw * 0.12, h * 0.09); + for (let k = 0; k < 4; k++) if (rnd() < 0.55) { + ctx.fillStyle = 'rgba(255,200,120,0.85)'; + ctx.fillRect(rx + bw * (0.15 + (k % 2) * 0.45), y + h - bh + h * (0.06 + Math.floor(k / 2) * 0.1), bw * 0.18, h * 0.05); + } + rx += bw + w * 0.005; + } + } + ctx.restore(); +} + +// ── Room parts ─────────────────────────────────────────────────────────────── +function floor(ctx, th) { + const [a, b] = th.floorTones; + if (th.floor === 'checker') { + const s = 72; + for (let y = WALL_H; y < H; y += s) for (let x = 0; x < W; x += s) { + ctx.fillStyle = ((x / s + (y - WALL_H) / s) | 0) % 2 ? a : b; + ctx.fillRect(x, y, s, s); + } + } else if (th.floor === 'carpet') { + ctx.fillStyle = a; ctx.fillRect(0, WALL_H, W, H - WALL_H); + ctx.strokeStyle = 'rgba(217,170,90,0.18)'; ctx.lineWidth = 2; + for (let y = WALL_H + 30; y < H; y += 60) for (let x = 30; x < W; x += 60) { + ctx.beginPath(); ctx.moveTo(x, y - 14); ctx.lineTo(x + 14, y); ctx.lineTo(x, y + 14); ctx.lineTo(x - 14, y); ctx.closePath(); ctx.stroke(); + } + ctx.fillStyle = 'rgba(0,0,0,0.25)'; + for (let x = 0; x < W; x += 120) ctx.fillRect(x, WALL_H, 2, H); + } else { + // wood: long boards + const bw = th.floor === 'planks' ? 46 : 64; + for (let y = WALL_H; y < H; y += bw) { + ctx.fillStyle = rnd() < 0.5 ? a : b; + ctx.fillRect(0, y, W, bw - 2); + ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fillRect(0, y + bw - 2, W, 2); + let x = -rnd() * 400; + while (x < W) { x += 300 + rnd() * 500; ctx.fillRect(x, y, 2, bw - 2); } + for (let i = 0; i < 14; i++) { + ctx.strokeStyle = `rgba(0,0,0,${0.06 + rnd() * 0.1})`; ctx.lineWidth = 1; + const yy = y + rnd() * (bw - 4); + ctx.beginPath(); ctx.moveTo(rnd() * W, yy); ctx.lineTo(rnd() * W, yy + (rnd() - 0.5) * 6); ctx.stroke(); + } + } + } + ctx.fillStyle = noisePattern(ctx, 160, 16); + ctx.fillRect(0, WALL_H, W, H - WALL_H); +} + +function wall(ctx, leg, th) { + const g = ctx.createLinearGradient(0, 0, 0, WALL_H); + g.addColorStop(0, th.wall[0]); g.addColorStop(1, th.wall[1]); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, WALL_H); + if (leg === 'klondike') { + for (let y = 0; y < WALL_H; y += 26) { // logs + const lg = ctx.createLinearGradient(0, y, 0, y + 26); + lg.addColorStop(0, '#6a4224'); lg.addColorStop(0.5, '#4a2e18'); lg.addColorStop(1, '#2a1a0c'); + ctx.fillStyle = lg; ctx.fillRect(0, y, W, 25); + } + } else if (leg === 'pyramid') { + for (let y = 0; y < WALL_H; y += 38) for (let x = (y / 38) % 2 ? -50 : 0; x < W; x += 100) { + ctx.strokeStyle = 'rgba(60,40,20,0.4)'; ctx.lineWidth = 2; ctx.strokeRect(x, y, 100, 38); + } + // a tile frieze along the bottom of the wall + for (let x = 0; x < W; x += 32) { + ctx.fillStyle = (x / 32) % 2 ? '#1f5a7a' : '#e0b860'; + ctx.beginPath(); ctx.moveTo(x + 16, WALL_H - 38); ctx.lineTo(x + 32, WALL_H - 26); ctx.lineTo(x + 16, WALL_H - 14); ctx.lineTo(x, WALL_H - 26); ctx.closePath(); ctx.fill(); + } + } else if (leg === 'threeshuffles') { + // cream plaster above a dark wainscot, a striped awning edge + ctx.fillStyle = '#2a1e14'; ctx.fillRect(0, WALL_H - 44, W, 30); + for (let x = 0; x < W; x += 60) { + ctx.fillStyle = (x / 60) % 2 ? '#a3242a' : '#f2ead8'; + ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x + 60, 0); ctx.lineTo(x + 60, 18); ctx.quadraticCurveTo(x + 30, 34, x, 18); ctx.closePath(); ctx.fill(); + } + } else { + for (let x = 0; x < W; x += 120) { // raised panels + ctx.fillStyle = 'rgba(255,200,140,0.04)'; rr(ctx, x + 12, 16, 96, WALL_H - 44, 4); ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 2; rr(ctx, x + 12, 16, 96, WALL_H - 44, 4); ctx.stroke(); + } + if (leg === 'fourteen') { ctx.fillStyle = th.trim; ctx.fillRect(0, WALL_H - 30, W, 4); ctx.fillRect(0, 10, W, 3); } + } + ctx.fillStyle = noisePattern(ctx, 128, 14); + ctx.fillRect(0, 0, W, WALL_H); + // the window, with a frame suited to the room + const wd = WINDOW, ww = wd.x1 - wd.x0, wh = wd.y1 - wd.y0; + vista(ctx, leg, wd.x0, wd.y0, ww, wh); + ctx.fillStyle = leg === 'threeshuffles' ? '#2a2a2a' : leg === 'pyramid' ? '#5a3a1a' : '#2a180c'; + for (const k of [1 / 3, 2 / 3]) ctx.fillRect(wd.x0 + ww * k - 4, wd.y0, 8, wh); + if (leg !== 'pyramid') ctx.fillRect(wd.x0, wd.y0 + wh / 2 - 3, ww, 6); + ctx.strokeStyle = leg === 'threeshuffles' ? '#1a1a1a' : th.trim; ctx.lineWidth = 8; + ctx.strokeRect(wd.x0 - 4, wd.y0 - 6, ww + 8, wh + 8); + if (leg === 'pyramid') { // a pointed arch over the opening + ctx.fillStyle = th.wall[1]; + ctx.beginPath(); ctx.moveTo(wd.x0 - 8, wd.y0 - 8); ctx.lineTo(wd.x0 - 8, wd.y0 + 40); ctx.quadraticCurveTo(wd.x0 + ww * 0.1, wd.y0 - 4, wd.x0 + ww / 2, wd.y0 - 4); + ctx.quadraticCurveTo(wd.x1 - ww * 0.1, wd.y0 - 4, wd.x1 + 8, wd.y0 + 40); ctx.lineTo(wd.x1 + 8, wd.y0 - 8); ctx.closePath(); ctx.fill(); + } + // curtains for the cosier rooms + if (leg === 'golf' || leg === 'fourteen' || leg === 'threeshuffles') { + const col = leg === 'golf' ? ['#1a3a24', '#2f5a3a'] : leg === 'fourteen' ? ['#3a0a0c', '#7a1a1e'] : ['#5a1a1a', '#8a2a2a']; + for (const cx of [wd.x0 - 34, wd.x1 + 34]) { + const cg = ctx.createLinearGradient(cx - 40, 0, cx + 40, 0); + cg.addColorStop(0, col[0]); cg.addColorStop(0.5, col[1]); cg.addColorStop(1, col[0]); + ctx.fillStyle = cg; ctx.fillRect(cx - 44, 0, 88, WALL_H - 12); + } + } + wallDecor(ctx, leg, th); + // the table's back edge + const e = ctx.createLinearGradient(0, WALL_H - 12, 0, WALL_H + 10); + e.addColorStop(0, 'rgba(0,0,0,0.2)'); e.addColorStop(1, 'rgba(0,0,0,0.6)'); + ctx.fillStyle = e; ctx.fillRect(0, WALL_H - 10, W, 20); +} + +function wallDecor(ctx, leg, th) { + ctx.save(); + if (leg === 'golf') { + // a shelf of trophies + ctx.fillStyle = '#4a2a12'; ctx.fillRect(420, 108, 240, 8); + for (let i = 0; i < 4; i++) { + const x = 450 + i * 60, s = 1 - (i % 2) * 0.25; + const g = ctx.createLinearGradient(x - 14, 0, x + 14, 0); + g.addColorStop(0, '#7a5a1a'); g.addColorStop(0.5, '#ffe9a0'); g.addColorStop(1, '#7a5a1a'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.moveTo(x - 16 * s, 70); ctx.quadraticCurveTo(x, 104, x + 16 * s, 70); ctx.closePath(); ctx.fill(); + ctx.fillRect(x - 3, 92, 6, 10); ctx.fillRect(x - 10, 100, 20, 8); + } + // crossed clubs, right + ctx.strokeStyle = '#c9c0a8'; ctx.lineWidth = 4; + ctx.beginPath(); ctx.moveTo(1300, 24); ctx.lineTo(1420, 120); ctx.moveTo(1420, 24); ctx.lineTo(1300, 120); ctx.stroke(); + ctx.fillStyle = '#5a4a3a'; ctx.fillRect(1290, 116, 24, 10); ctx.fillRect(1406, 116, 24, 10); + } else if (leg === 'klondike') { + // gold pan on a nail, crossed snowshoes + const g = ctx.createRadialGradient(470, 72, 6, 470, 72, 52); + g.addColorStop(0, '#9a8a6a'); g.addColorStop(0.7, '#4a4034'); g.addColorStop(1, '#2a241c'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(470, 72, 50, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#f0c040'; + for (let i = 0; i < 9; i++) { ctx.beginPath(); ctx.arc(458 + rnd() * 28, 64 + rnd() * 22, 2 + rnd() * 3, 0, Math.PI * 2); ctx.fill(); } + for (const [x, r] of [[1340, -0.4], [1400, 0.4]]) { + ctx.save(); ctx.translate(x, 74); ctx.rotate(r); + ctx.strokeStyle = '#a07a4a'; ctx.lineWidth = 4; ctx.beginPath(); ctx.ellipse(0, 0, 20, 54, 0, 0, Math.PI * 2); ctx.stroke(); + ctx.strokeStyle = 'rgba(200,170,120,0.6)'; ctx.lineWidth = 1; + for (let k = -40; k <= 40; k += 10) { ctx.beginPath(); ctx.moveTo(-18, k); ctx.lineTo(18, k); ctx.stroke(); } + ctx.restore(); + } + } else if (leg === 'pyramid') { + // pierced brass lanterns + for (const x of [500, 1420]) { + ctx.strokeStyle = th.trim; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, 30); ctx.stroke(); + const g = ctx.createRadialGradient(x, 70, 4, x, 70, 70); + g.addColorStop(0, 'rgba(255,200,110,0.55)'); g.addColorStop(1, 'rgba(255,200,110,0)'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x, 70, 70, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#b88a3a'; + ctx.beginPath(); ctx.moveTo(x, 30); ctx.lineTo(x + 22, 56); ctx.lineTo(x + 16, 100); ctx.lineTo(x - 16, 100); ctx.lineTo(x - 22, 56); ctx.closePath(); ctx.fill(); + ctx.fillStyle = 'rgba(255,230,160,0.9)'; + for (let k = 0; k < 10; k++) { ctx.beginPath(); ctx.arc(x - 12 + (k % 4) * 8, 54 + Math.floor(k / 4) * 14, 2, 0, Math.PI * 2); ctx.fill(); } + } + } else if (leg === 'fourteen') { + // a brass ship's wheel and a framed paddle-steamer print + ctx.strokeStyle = th.trim; ctx.lineWidth = 4; + ctx.beginPath(); ctx.arc(480, 72, 42, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.arc(480, 72, 10, 0, Math.PI * 2); ctx.stroke(); + for (let k = 0; k < 8; k++) { const a = (k / 8) * Math.PI * 2; ctx.beginPath(); ctx.moveTo(480 + Math.cos(a) * 10, 72 + Math.sin(a) * 10); ctx.lineTo(480 + Math.cos(a) * 56, 72 + Math.sin(a) * 56); ctx.stroke(); } + ctx.fillStyle = '#e8dcc0'; ctx.fillRect(1300, 30, 150, 86); + ctx.strokeStyle = th.trim; ctx.lineWidth = 5; ctx.strokeRect(1300, 30, 150, 86); + ctx.fillStyle = '#3a2a1a'; + ctx.fillRect(1330, 82, 90, 10); ctx.fillRect(1345, 66, 60, 16); ctx.fillRect(1356, 44, 6, 22); ctx.fillRect(1386, 44, 6, 22); + ctx.beginPath(); ctx.arc(1410, 86, 12, Math.PI, 0); ctx.fill(); + } else { + // a café chalkboard and a mirror + ctx.fillStyle = '#5a3a1a'; ctx.fillRect(420, 40, 230, 80); + ctx.fillStyle = '#1e2420'; ctx.fillRect(428, 48, 214, 64); + ctx.fillStyle = 'rgba(240,240,230,0.85)'; ctx.font = 'italic 20px Georgia, serif'; ctx.textAlign = 'center'; + ctx.fillText('Café · Croissant', 535, 76); ctx.font = '14px Georgia, serif'; ctx.fillText('— la belle lucie —', 535, 100); + const mg = ctx.createLinearGradient(1300, 30, 1440, 120); + mg.addColorStop(0, '#c8d0d8'); mg.addColorStop(0.5, '#8a96a2'); mg.addColorStop(1, '#c8d0d8'); + ctx.fillStyle = '#b89a4a'; ctx.beginPath(); ctx.ellipse(1370, 72, 64, 48, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = mg; ctx.beginPath(); ctx.ellipse(1370, 72, 56, 40, 0, 0, Math.PI * 2); ctx.fill(); + } + ctx.restore(); +} + +function surface(ctx, leg, th) { + const p = PLAY, w = p.x1 - p.x0, h = p.y1 - p.y0; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.7)'; ctx.shadowBlur = 30; ctx.shadowOffsetY = 10; + rr(ctx, p.x0 - 14, p.y0 - 10, w + 28, h + 20, 18); + ctx.fillStyle = leg === 'threeshuffles' ? '#9aa0a6' : leg === 'pyramid' ? '#6a4a1a' : '#3a2010'; + ctx.fill(); + ctx.restore(); + // rim + rr(ctx, p.x0 - 14, p.y0 - 10, w + 28, h + 20, 18); + const rim = ctx.createLinearGradient(0, p.y0 - 10, 0, p.y1 + 10); + if (leg === 'threeshuffles') { rim.addColorStop(0, '#e0e4e8'); rim.addColorStop(1, '#7a8088'); } + else if (leg === 'pyramid') { rim.addColorStop(0, '#f2d58a'); rim.addColorStop(1, '#6a4612'); } + else { rim.addColorStop(0, '#8a5a2c'); rim.addColorStop(1, '#2a160a'); } + ctx.fillStyle = rim; ctx.fill(); + ctx.save(); + rr(ctx, p.x0, p.y0, w, h, 10); + ctx.clip(); + if (th.surface === 'tartan') { + ctx.fillStyle = '#1d4430'; ctx.fillRect(p.x0, p.y0, w, h); + const band = (vertical, off, size, color, alpha) => { + ctx.fillStyle = color; ctx.globalAlpha = alpha; + for (let k = off; k < (vertical ? w : h); k += 180) { + if (vertical) ctx.fillRect(p.x0 + k, p.y0, size, h); else ctx.fillRect(p.x0, p.y0 + k, w, size); + } + ctx.globalAlpha = 1; + }; + for (const v of [true, false]) { + band(v, 0, 60, '#0e2a4a', 0.55); + band(v, 90, 22, '#0e2a4a', 0.4); + band(v, 70, 3, '#c8a840', 0.5); + band(v, 140, 4, '#b02a2a', 0.45); + } + } else if (th.surface === 'pine') { + for (let x = p.x0; x < p.x1; x += 118) { + const g = ctx.createLinearGradient(x, 0, x + 118, 0); + const base = rnd() < 0.5 ? '#9a6a3a' : '#8a5e32'; + g.addColorStop(0, '#6a4222'); g.addColorStop(0.08, base); g.addColorStop(0.92, base); g.addColorStop(1, '#5a361a'); + ctx.fillStyle = g; ctx.fillRect(x, p.y0, 118, h); + for (let i = 0; i < 22; i++) { + ctx.strokeStyle = `rgba(60,30,10,${0.1 + rnd() * 0.18})`; ctx.lineWidth = 1 + rnd() * 1.5; + const xx = x + 8 + rnd() * 100; + ctx.beginPath(); ctx.moveTo(xx, p.y0); ctx.bezierCurveTo(xx + (rnd() - 0.5) * 20, p.y0 + h * 0.3, xx + (rnd() - 0.5) * 20, p.y0 + h * 0.7, xx + (rnd() - 0.5) * 10, p.y1); ctx.stroke(); + } + ctx.fillStyle = '#2a1a0a'; + for (const yy of [p.y0 + 30, p.y1 - 30]) { ctx.beginPath(); ctx.arc(x + 59, yy, 4, 0, Math.PI * 2); ctx.fill(); } + if (rnd() < 0.6) { // a knot + const ky = p.y0 + rnd() * h; + for (let r = 18; r > 2; r -= 4) { ctx.strokeStyle = 'rgba(60,30,10,0.3)'; ctx.beginPath(); ctx.ellipse(x + 40 + rnd() * 30, ky, r * 0.6, r * 1.6, 0, 0, Math.PI * 2); ctx.stroke(); } + } + } + } else if (th.surface === 'brass') { + const g = ctx.createRadialGradient(PLAY_CX(), p.y0 + h / 2, 40, PLAY_CX(), p.y0 + h / 2, w * 0.7); + g.addColorStop(0, '#d8a84a'); g.addColorStop(0.6, '#a87a2a'); g.addColorStop(1, '#5a3e12'); + ctx.fillStyle = g; ctx.fillRect(p.x0, p.y0, w, h); + for (let i = 0; i < 2600; i++) { // hammered dimples + const x = p.x0 + rnd() * w, y = p.y0 + rnd() * h, r = 3 + rnd() * 6; + const d = ctx.createRadialGradient(x - r * 0.3, y - r * 0.3, 0, x, y, r); + d.addColorStop(0, 'rgba(255,240,190,0.16)'); d.addColorStop(1, 'rgba(60,30,0,0.08)'); + ctx.fillStyle = d; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + } + // engraved arabesque border + ctx.strokeStyle = 'rgba(70,40,5,0.55)'; ctx.lineWidth = 2; + rr(ctx, p.x0 + 24, p.y0 + 24, w - 48, h - 48, 8); ctx.stroke(); + rr(ctx, p.x0 + 40, p.y0 + 40, w - 80, h - 80, 6); ctx.stroke(); + for (let x = p.x0 + 52; x < p.x1 - 40; x += 32) for (const y of [p.y0 + 32, p.y1 - 32]) { + ctx.beginPath(); ctx.arc(x, y, 6, 0, Math.PI * 2); ctx.stroke(); + } + for (let y = p.y0 + 52; y < p.y1 - 40; y += 32) for (const x of [p.x0 + 32, p.x1 - 32]) { + ctx.beginPath(); ctx.arc(x, y, 6, 0, Math.PI * 2); ctx.stroke(); + } + } else if (th.surface === 'baize') { + const g = ctx.createLinearGradient(0, p.y0, 0, p.y1); + g.addColorStop(0, '#1f5a36'); g.addColorStop(1, '#134026'); + ctx.fillStyle = g; ctx.fillRect(p.x0, p.y0, w, h); + ctx.fillStyle = noisePattern(ctx, 200, 26); ctx.fillRect(p.x0, p.y0, w, h); + ctx.strokeStyle = 'rgba(217,180,90,0.5)'; ctx.lineWidth = 3; + rr(ctx, p.x0 + 26, p.y0 + 26, w - 52, h - 52, 14); ctx.stroke(); + } else { + // marble + ctx.fillStyle = '#ece8e0'; ctx.fillRect(p.x0, p.y0, w, h); + for (let i = 0; i < 46; i++) { + ctx.strokeStyle = `rgba(110,110,120,${0.05 + rnd() * 0.16})`; ctx.lineWidth = 0.6 + rnd() * 2.2; + let x = p.x0 + rnd() * w, y = p.y0 + rnd() * h; + ctx.beginPath(); ctx.moveTo(x, y); + for (let k = 0; k < 8; k++) { x += (rnd() - 0.3) * 140; y += (rnd() - 0.5) * 90; ctx.lineTo(x, y); } + ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 180, 10); ctx.fillRect(p.x0, p.y0, w, h); + } + // the room's light pool and darker corners + const L = ctx.createRadialGradient(th.lightAt.x, th.lightAt.y, 60, th.lightAt.x, th.lightAt.y, 900); + L.addColorStop(0, `rgba(${th.light},0.16)`); L.addColorStop(1, `rgba(${th.light},0)`); + ctx.fillStyle = L; ctx.fillRect(p.x0, p.y0, w, h); + const v = ctx.createRadialGradient(PLAY_CX(), p.y0 + h / 2, h * 0.3, PLAY_CX(), p.y0 + h / 2, w * 0.75); + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, `rgba(0,0,0,${leg === 'threeshuffles' ? 0.28 : 0.45})`); + ctx.fillStyle = v; ctx.fillRect(p.x0, p.y0, w, h); + ctx.restore(); +} +const PLAY_CX = () => (PLAY.x0 + PLAY.x1) / 2; + +function slotsOn(ctx, leg, slots) { + const light = leg === 'threeshuffles' ? 'rgba(60,60,70,' : leg === 'pyramid' ? 'rgba(70,40,5,' : 'rgba(240,220,170,'; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + for (const sl of slots) { + const { x, y, s } = sl.pose; + const cw = 96 * s, ch = 134 * s; + ctx.save(); + rr(ctx, x - cw / 2 - 3, y - ch / 2 - 3, cw + 6, ch + 6, 11); + ctx.fillStyle = `${light}0.08)`; ctx.fill(); + ctx.setLineDash([7, 6]); ctx.lineWidth = 2; ctx.strokeStyle = `${light}0.42)`; ctx.stroke(); + ctx.setLineDash([]); + if (sl.suit) drawSuit(ctx, sl.suit, x, y, 44 * s, `${light}0.32)`); + if (sl.label) { + ctx.font = `${sl.label.length > 2 ? 13 : 30}px "Julius Sans One", Georgia, serif`; + ctx.fillStyle = `${light}0.5)`; + ctx.fillText(sl.label, x, sl.label.length > 2 ? y + ch / 2 + 18 : y); + } + ctx.restore(); + } +} + +function edgeLight(ctx) { + const v = ctx.createRadialGradient(W / 2, H * 0.55, 500, W / 2, H * 0.55, 1300); + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(0,0,0,0.55)'); + ctx.fillStyle = v; ctx.fillRect(0, WALL_H, W, H - WALL_H); +} + +function bakeRoomCanvas(scene, leg, slots) { + const th = THEMES[leg]; + reseed(1000 + TOUR.indexOf(leg) * 977); + const c = canvas(W, H); + const ctx = c.getContext('2d'); + floor(ctx, th); + edgeLight(ctx); + surface(ctx, leg, th); + slotsOn(ctx, leg, slots); + wall(ctx, leg, th); + scene.textures.addCanvas(`st-room-${leg}`, c); +} + +// ── Paper pieces ───────────────────────────────────────────────────────────── +function paper(ctx, x, y, w, h, tint = '#f4eedc') { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 6; + ctx.fillStyle = tint; ctx.fillRect(x, y, w, h); + ctx.restore(); + ctx.fillStyle = noisePattern(ctx, 96, 10); ctx.fillRect(x, y, w, h); +} + +function bakeScorecard(scene) { + const { w, h } = SCORECARD, pad = 14; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + paper(ctx, pad, pad, w, h); + ctx.fillStyle = '#1f4a32'; ctx.fillRect(pad, pad, w, 92); + ctx.strokeStyle = '#c9a050'; ctx.lineWidth = 2; ctx.strokeRect(pad + 6, pad + 6, w - 12, 80); + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillStyle = '#f2e6c0'; ctx.font = 'bold 24px Georgia, serif'; + ctx.fillText('THE GRAND TOUR', pad + w / 2, pad + 36); + ctx.font = '13px "Julius Sans One", Georgia, serif'; + ctx.fillText('OFFICIAL SCORECARD · LOW SCORE WINS', pad + w / 2, pad + 66); + // column heads + ctx.fillStyle = '#1f4a32'; ctx.font = '12px "Julius Sans One", Georgia, serif'; + ctx.textAlign = 'left'; ctx.fillText('HOLE', pad + 12, pad + 116); + ctx.fillText('VENUE · GAME', pad + 62, pad + 116); + ctx.textAlign = 'right'; ctx.fillText('SCORE', pad + w - 12, pad + 116); + ctx.strokeStyle = '#1f4a32'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(pad, pad + 130); ctx.lineTo(pad + w, pad + 130); ctx.stroke(); + for (let i = 0; i < 5; i++) { + const y = pad + 130 + i * 102; + ctx.strokeStyle = 'rgba(31,74,50,0.45)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(pad, y + 102); ctx.lineTo(pad + w, y + 102); ctx.stroke(); + ctx.fillStyle = '#1f4a32'; ctx.font = 'bold 26px Georgia, serif'; ctx.textAlign = 'center'; + ctx.fillText(String(i + 1), pad + 30, y + 51); + } + ctx.strokeStyle = 'rgba(31,74,50,0.45)'; + ctx.beginPath(); ctx.moveTo(pad + 52, pad + 100); ctx.lineTo(pad + 52, pad + 640); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(pad + w - 84, pad + 100); ctx.lineTo(pad + w - 84, pad + 640); ctx.stroke(); + // totals + ctx.fillStyle = '#1f4a32'; ctx.fillRect(pad, pad + 640, w, 4); + ctx.font = '15px "Julius Sans One", Georgia, serif'; ctx.textAlign = 'left'; + ctx.fillText('TOUR TOTAL', pad + 14, pad + 676); + ctx.font = '11px "Julius Sans One", Georgia, serif'; ctx.fillStyle = '#6c6450'; + ctx.fillText('Cards left on the table add their value:', pad + 14, pad + 722); + ctx.fillText('A = 1 … 10 = 10, J = 11, Q = 12, K = 13', pad + 14, pad + 740); + scene.textures.addCanvas('st-scorecard', c); +} + +function bakePlate(scene) { + const { w, h } = PLATE, pad = 14; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 18; ctx.shadowOffsetY = 6; + rr(ctx, pad, pad, w, h, 14); + const g = ctx.createLinearGradient(0, pad, 0, pad + h); + g.addColorStop(0, '#2a1a0e'); g.addColorStop(1, '#120a05'); + ctx.fillStyle = g; ctx.fill(); + ctx.restore(); + rr(ctx, pad, pad, w, h, 14); + ctx.fillStyle = noisePattern(ctx, 128, 18); ctx.fill(); + ctx.strokeStyle = '#c9a050'; ctx.lineWidth = 3; ctx.stroke(); + ctx.setLineDash([6, 5]); ctx.strokeStyle = 'rgba(214,174,120,0.35)'; ctx.lineWidth = 1.4; + rr(ctx, pad + 8, pad + 8, w - 16, h - 16, 10); ctx.stroke(); ctx.setLineDash([]); + // a luggage-label header + ctx.fillStyle = '#f2e6c0'; + rr(ctx, pad + 18, pad + 18, w - 36, 120, 10); ctx.fill(); + ctx.strokeStyle = '#a3242a'; ctx.lineWidth = 3; rr(ctx, pad + 24, pad + 24, w - 48, 108, 7); ctx.stroke(); + scene.textures.addCanvas('st-plate', c); +} + +function bakeBack(scene) { + const cw = 192, ch = 268; + const c = canvas(cw, ch); + const ctx = c.getContext('2d'); + rr(ctx, 0, 0, cw, ch, 14); ctx.fillStyle = '#f4eedc'; ctx.fill(); + rr(ctx, 8, 8, cw - 16, ch - 16, 10); + const g = ctx.createLinearGradient(0, 0, cw, ch); + g.addColorStop(0, '#1c2e5a'); g.addColorStop(1, '#0e1a36'); + ctx.fillStyle = g; ctx.fill(); + ctx.save(); ctx.clip(); + ctx.strokeStyle = 'rgba(217,180,90,0.22)'; ctx.lineWidth = 1.2; + for (let r = 20; r < 200; r += 14) { ctx.beginPath(); ctx.arc(cw / 2, ch / 2, r, 0, Math.PI * 2); ctx.stroke(); } + ctx.restore(); + ctx.strokeStyle = '#d9b45a'; ctx.lineWidth = 3; rr(ctx, 16, 16, cw - 32, ch - 32, 8); ctx.stroke(); + // compass rose + ctx.save(); ctx.translate(cw / 2, ch / 2); + for (let k = 0; k < 8; k++) { + const long = k % 2 === 0, len = long ? 60 : 34; + ctx.rotate(Math.PI / 4); + ctx.fillStyle = long ? '#d9b45a' : '#a8843a'; + ctx.beginPath(); ctx.moveTo(0, -len); ctx.lineTo(8, 0); ctx.lineTo(0, 8); ctx.lineTo(-8, 0); ctx.closePath(); ctx.fill(); + } + ctx.fillStyle = '#0e1a36'; ctx.beginPath(); ctx.arc(0, 0, 9, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#d9b45a'; ctx.lineWidth = 2; ctx.stroke(); + ctx.restore(); + scene.textures.addCanvas('st-back', c); +} + +export const POSTCARD = { w: 600, h: 380 }; +function bakePostcard(scene, leg) { + const { w, h } = POSTCARD, pad = 16; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + paper(ctx, pad, pad, w, h, '#f6f0e0'); + // the picture, with a white border + vista(ctx, leg, pad + 18, pad + 18, 300, h - 36); + ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.lineWidth = 1; ctx.strokeRect(pad + 18, pad + 18, 300, h - 36); + // divider + address lines + ctx.strokeStyle = 'rgba(60,50,40,0.4)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(pad + 336, pad + 30); ctx.lineTo(pad + 336, pad + h - 30); ctx.stroke(); + for (let i = 0; i < 4; i++) { ctx.beginPath(); ctx.moveTo(pad + 356, pad + 210 + i * 36); ctx.lineTo(pad + w - 22, pad + 210 + i * 36); ctx.stroke(); } + // the stamp + const sx = pad + w - 92, sy = pad + 22; + ctx.fillStyle = '#fff'; ctx.fillRect(sx, sy, 70, 84); + ctx.strokeStyle = '#ccc'; ctx.setLineDash([3, 3]); ctx.strokeRect(sx, sy, 70, 84); ctx.setLineDash([]); + vista(ctx, leg, sx + 6, sy + 6, 58, 72); + // postmark + ctx.strokeStyle = 'rgba(40,40,90,0.55)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.arc(sx - 20, sy + 58, 30, 0, Math.PI * 2); ctx.stroke(); + for (let k = 0; k < 4; k++) { ctx.beginPath(); ctx.moveTo(sx - 4, sy + 40 + k * 10); ctx.bezierCurveTo(sx + 20, sy + 34 + k * 10, sx + 50, sy + 46 + k * 10, sx + 80, sy + 40 + k * 10); ctx.stroke(); } + scene.textures.addCanvas(`st-post-${leg}`, c); +} + +// ── The route map ──────────────────────────────────────────────────────────── +export const MAP = { w: 1240, h: 560, lon0: -175, lon1: 70, lat0: 78, lat1: -32 }; +export const mapXY = (lon, lat) => ({ x: ((lon - MAP.lon0) / (MAP.lon1 - MAP.lon0)) * MAP.w, y: ((MAP.lat0 - lat) / (MAP.lat0 - MAP.lat1)) * MAP.h }); +export const STOPS = { + golf: { lon: -2.8, lat: 56.3, label: 'St Andrews' }, + klondike: { lon: -139.4, lat: 64.1, label: 'Dawson City' }, + pyramid: { lon: 31.2, lat: 30.0, label: 'Cairo' }, + fourteen: { lon: -90.1, lat: 29.9, label: 'New Orleans' }, + threeshuffles: { lon: 2.35, lat: 48.85, label: 'Paris' }, +}; +const LANDS = [ + [[-168, 66], [-162, 70], [-140, 70], [-125, 72], [-95, 72], [-80, 73], [-62, 66], [-55, 52], [-66, 45], [-75, 38], [-80, 32], [-81, 25], [-84, 30], [-90, 30], [-97, 27], [-97, 21], [-90, 21], [-87, 15], [-83, 9], [-78, 8], [-85, 12], [-92, 16], [-105, 20], [-112, 30], [-118, 34], [-124, 40], [-124, 48], [-133, 56], [-150, 60], [-165, 60]], + [[-45, 60], [-20, 70], [-25, 82], [-60, 82], [-72, 77], [-55, 68]], + [[-78, 8], [-60, 10], [-50, 0], [-35, -6], [-40, -22], [-48, -28], [-58, -38], [-65, -42], [-68, -55], [-74, -50], [-72, -30], [-70, -18], [-81, -5], [-80, 2]], + [[-10, 36], [-9, 43], [-2, 44], [-5, 48], [0, 50], [5, 53], [8, 57], [5, 62], [15, 69], [25, 71], [40, 68], [30, 60], [24, 58], [28, 55], [40, 52], [45, 45], [30, 45], [26, 40], [23, 36], [20, 40], [15, 38], [18, 45], [12, 44], [8, 44], [3, 43], [-2, 37]], + [[-5, 50], [1, 51], [2, 53], [-1, 55], [-2, 57], [-5, 58.5], [-6, 56], [-3, 54], [-4.5, 52]], + [[-17, 15], [-17, 21], [-10, 30], [-6, 36], [10, 37], [20, 32], [32, 31], [34, 28], [43, 12], [51, 12], [40, -2], [40, -15], [35, -25], [20, -35], [17, -29], [12, -17], [13, -5], [9, 4], [-8, 5], [-15, 10]], + [[26, 40], [36, 36], [35, 30], [45, 15], [55, 22], [58, 25], [67, 25], [72, 20], [72, 50], [80, 73], [68, 70], [55, 68], [40, 68], [30, 60], [40, 52], [45, 45], [38, 45], [30, 45]], + [[-24, 64], [-14, 66], [-13, 64], [-22, 63]], +]; + +function bakeMap(scene) { + const { w, h } = MAP; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(w / 2, h / 2, 100, w / 2, h / 2, w * 0.7); + g.addColorStop(0, '#f2e2b8'); g.addColorStop(1, '#c8a870'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + ctx.fillStyle = noisePattern(ctx, 128, 20); ctx.fillRect(0, 0, w, h); + // graticule + ctx.strokeStyle = 'rgba(120,90,50,0.18)'; ctx.lineWidth = 1; + for (let lon = -180; lon <= 90; lon += 30) { const p = mapXY(lon, 0); ctx.beginPath(); ctx.moveTo(p.x, 0); ctx.lineTo(p.x, h); ctx.stroke(); } + for (let lat = -30; lat <= 90; lat += 15) { const p = mapXY(0, lat); ctx.beginPath(); ctx.moveTo(0, p.y); ctx.lineTo(w, p.y); ctx.stroke(); } + // land + for (const poly of LANDS) { + ctx.beginPath(); + poly.forEach(([lon, lat], i) => { const p = mapXY(lon, lat); if (i) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y); }); + ctx.closePath(); + ctx.fillStyle = 'rgba(140,150,90,0.55)'; ctx.fill(); + ctx.strokeStyle = 'rgba(90,60,30,0.7)'; ctx.lineWidth = 1.6; ctx.stroke(); + } + // compass + cartouche + ctx.save(); ctx.translate(w - 90, h - 90); + ctx.strokeStyle = 'rgba(90,60,30,0.7)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.arc(0, 0, 44, 0, Math.PI * 2); ctx.stroke(); + for (let k = 0; k < 4; k++) { ctx.rotate(Math.PI / 2); ctx.fillStyle = k % 2 ? 'rgba(90,60,30,0.75)' : 'rgba(160,40,40,0.75)'; ctx.beginPath(); ctx.moveTo(0, -40); ctx.lineTo(7, 0); ctx.lineTo(-7, 0); ctx.closePath(); ctx.fill(); } + ctx.restore(); + ctx.fillStyle = 'rgba(90,60,30,0.85)'; ctx.font = 'italic 26px Georgia, serif'; ctx.textAlign = 'left'; + ctx.fillText('The Grand Tour', 26, 40); + ctx.font = '13px "Julius Sans One", Georgia, serif'; + ctx.fillText('FIVE STOPS · FIVE SOLITAIRES', 28, 62); + // edge burn + const e = ctx.createRadialGradient(w / 2, h / 2, h * 0.45, w / 2, h / 2, w * 0.62); + e.addColorStop(0, 'rgba(90,50,10,0)'); e.addColorStop(1, 'rgba(90,50,10,0.45)'); + ctx.fillStyle = e; ctx.fillRect(0, 0, w, h); + scene.textures.addCanvas('st-map', c); +} + +// ── Entry points ───────────────────────────────────────────────────────────── +export async function prepareTourArt(scene) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('st-back')) bakeBack(scene); + if (!scene.textures.exists('st-scorecard')) bakeScorecard(scene); + if (!scene.textures.exists('st-plate')) bakePlate(scene); +} + +/** Bake (once) and return the room key for a leg; `slots` are that leg's pile spots. */ +export function ensureRoom(scene, leg, slots) { + const key = `st-room-${leg}`; + if (!scene.textures.exists(key)) bakeRoomCanvas(scene, leg, slots); + return key; +} + +export function ensurePostcard(scene, leg) { + const key = `st-post-${leg}`; + if (!scene.textures.exists(key)) bakePostcard(scene, leg); + return key; +} + +export function ensureMap(scene) { + if (!scene.textures.exists('st-map')) bakeMap(scene); + return 'st-map'; +} diff --git a/src/games/solitairetour/SolitaireTourGame.js b/src/games/solitairetour/SolitaireTourGame.js index 703afdb..fc531b5 100644 --- a/src/games/solitairetour/SolitaireTourGame.js +++ b/src/games/solitairetour/SolitaireTourGame.js @@ -1,927 +1,776 @@ import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; +import { + SolitaireScene, DEPTH as D, CX, CY, COLORS, playSound, playSoundEx, SFX, FONT_HAND, +} from '../../ui/solitaire/SolitaireScene.js'; +import { loadStats, recordGame, recordBest, bumpCount, formatTime } from '../../ui/solitaire/SolitaireStats.js'; +import { RainBed, homeChime, pickUp, flourish } from '../../ui/solitaire/SolitaireSound.js'; import { api } from '../../services/api.js'; -import { TOUR, GAME_META, createEngine } from './SolitaireTourLogic.js'; +import { TOUR, GAME_META, createEngine, engineFromSave, encode } from './SolitaireTourLogic.js'; +import { legFor, remainingCards, homeStacks } from './SolitaireTourLegs.js'; +import { WINDOW, SCORECARD, PLATE, DEAL_FROM, PCX, GOLF } from './SolitaireTourTable.js'; +import { + THEMES, MAP, STOPS, POSTCARD, mapXY, prepareTourArt, ensureRoom, ensurePostcard, ensureMap, +} from './SolitaireTourArt.js'; -const CARD_W = 100; -const CARD_H = 140; -const CARD_R = 10; -const COL_GAP = 132; -const colX = (c) => 564 + c * COL_GAP; // 7 columns, centred on 960 +// ─── Solitaire Tour — five stops, one trip ──────────────────────────────────── +// Golf at a Scottish clubhouse, Klondike in a Yukon cabin, Pyramid on a Cairo +// terrace, Take Fourteen aboard a riverboat, Three Shuffles in a Paris café. +// A golf scorecard follows you round: every card left on the table adds its +// value, lowest tour wins. Rules in SolitaireTourLogic.js, per-game decisions +// in SolitaireTourLegs.js; input, undo, cascade and records come from the +// shared solitaire layer (src/ui/solitaire/). The tour saves as you play. -const FELT = 0x0e3b2a; -const SEL = 0x2ec28a; // selection rim (green) -const HINT = 0xc8a84b; // "playable now" rim (gold) +const DEFAULTS = { autoPlay: true, hints: true, undo: true }; +const SAVE_KEY = 'solitairetour-save'; +const INK = '#22201a', GREY = '#6c6450', GREEN = '#2f6a3a', RED = '#a32424'; +const ROW_H = 102; -const D = { felt: -2, table: -1, card: 10, ui: 30, banner: 34, overlay: 60, overlayUI: 62 }; +const scTop = () => SCORECARD.y - SCORECARD.h / 2; +const rowY = (i) => scTop() + 130 + i * ROW_H + ROW_H / 2; -export default class SolitaireTourGame extends Phaser.Scene { +export default class SolitaireTourGame extends SolitaireScene { constructor() { super('SolitaireTourGame'); } init(data) { - this.gameDef = data.game; + this.initSolitaire(data, { settingsKey: 'solitairetour-settings', defaults: DEFAULTS, slug: 'solitairetour' }); this.tourIndex = 0; this.total = 0; this.results = []; - this.recorded = false; - - this.engine = null; + this.tourMode = 'casual'; + this.tourTime = 0; + this.bestRun = 0; + this.leg = null; this.legType = null; - this.sel = null; - this.legEnded = false; - this.overlayUp = false; - this.animating = false; - this.overlayObjs = []; - this.pulse = null; - - // Klondike / Three Shuffles drag-and-drop state. - this.kSprites = new Map(); // card.id → container (for the current render) - this.dropZones = []; // hit-test zones for the active leg - this.potentialDrag = null; // pointer-down recorded, not yet a drag - this.dragState = null; // an in-progress drag - this.dropHighlight = null; - this.tsDrawMode = false; // Three Shuffles: picking a buried card to free + this.legDone = false; + this.drawMode = false; + this.lifeMode = null; + this.bed = null; + this.stuckShown = false; } - create() { - try { - const music = this.cache.json.get('music'); - if (music?.tracks) new MusicPlayer(this, music.tracks); - } catch (_) { /* music optional */ } + faceFrame(card) { return { key: 'casino-cards', frame: card.key }; } - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, FELT).setDepth(D.felt); - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH - 24, GAME_HEIGHT - 24, FELT) - .setStrokeStyle(3, COLORS.accent, 0.35).setDepth(D.table); + async create() { + this.createTableBase(); + await prepareTourArt(this); + if (!this.alive()) return; + this.backKey = 'st-back'; + this.roomImg = this.add.image(0, 0, 'st-scorecard').setOrigin(0, 0).setDepth(D.table).setVisible(false); + this.lifeG = this.add.graphics().setDepth(D.table + 0.2); + this.glowLight = this.add.image(CX, CY, 'ct-spot').setDisplaySize(1500, 1000).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0).setDepth(D.table + 0.1); + this.buildScorecard(); + this.buildPlate(); + this.buildSolitaireBase({ keysText: 'Drag or click cards · Z undo · Y redo · B bank this leg\nS shuffle · D draw (Three Shuffles) · Esc menu' }); + this.buildDock(); + this.events.once('shutdown', () => { this.bed?.stop(); }); + const save = this.loadSave(); + if (save) this.offerResume(save); + else this.startTour(); + } - this.add.text(40, 28, 'SOLITAIRE TOUR', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex, - }).setDepth(D.ui); - - this.legText = this.add.text(40, 84, '', { fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex }).setDepth(D.ui); - this.blurbText = this.add.text(40, 120, '', { fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.mutedHex, wordWrap: { width: 1020 } }).setDepth(D.ui); - - this.totalText = this.add.text(GAME_WIDTH - 40, 28, '', { fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex }).setOrigin(1, 0).setDepth(D.ui); - this.liveText = this.add.text(GAME_WIDTH - 40, 72, '', { fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex }).setOrigin(1, 0).setDepth(D.ui); - this.statusText = this.add.text(GAME_WIDTH - 40, 102, '', { fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex }).setOrigin(1, 0).setDepth(D.ui); - - this.stuckBanner = this.add.text(GAME_WIDTH / 2, 156, 'No moves left — tap “No More Moves” to bank the remaining cards.', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.banner).setVisible(false); - - this.board = this.add.container(0, 0).setDepth(D.card); - - this.noMoreBtn = new Button(this, GAME_WIDTH / 2, 1018, 'No More Moves', () => this.onNoMore(), - { width: 300, height: 60, fontSize: 24 }); - this.noMoreBtn.setDepth(D.ui); - - // Three Shuffles recovery controls (hidden on the other legs). - this.shuffleBtn = new Button(this, GAME_WIDTH / 2 - 360, 1018, 'Shuffle', () => this.onShuffle(), - { width: 220, height: 60, fontSize: 24 }); - this.shuffleBtn.setDepth(D.ui).setVisible(false); - - this.drawBtn = new Button(this, GAME_WIDTH / 2 + 360, 1018, 'Draw', () => this.onDraw(), - { width: 200, height: 60, fontSize: 24 }); - this.drawBtn.setDepth(D.ui).setVisible(false); - - this.leaveBtn = new Button(this, GAME_WIDTH - 110, 1042, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 160, height: 54, fontSize: 22 }); - this.leaveBtn.setDepth(D.ui); - - this.setupDrag(); + // ── Tour flow ───────────────────────────────────────────────────────────── + startTour() { + this.closeModal(); + this.tourIndex = 0; + this.total = 0; + this.results = []; + this.tourMode = this.settings.undo ? 'casual' : 'tournament'; + this.tourTime = 0; + this.bestRun = 0; + this.clearSave(); + this.updateScorecard(); this.startLeg(); } - // ── tour flow ─────────────────────────────────────────────────────────────── - startLeg() { + startLeg(engine = null) { + this.closeModal(); this.legType = TOUR[this.tourIndex]; - this.engine = createEngine(this.legType); - this.sel = null; - this.legEnded = false; - this.tsDrawMode = false; + const gs = engine ?? createEngine(this.legType); + this.leg = legFor(gs); + this.legDone = false; + this.drawMode = false; + this.stuckShown = false; + this.setRoom(this.legType); + this.updateScorecard(); + this.beginGame(gs, { dealFrom: DEAL_FROM, order: gs.allCards().map(c => c.id), step: 16 }); + this.saveTour(); + } + + setRoom(leg) { + const th = THEMES[leg]; + this.roomImg.setTexture(ensureRoom(this, leg, this.leg.slots())).setVisible(true); + this.lifeMode = th.life; + this.lifeParts = null; + this.tweens.killTweensOf(this.glowLight); + const [r, g, b] = th.light.split(',').map(Number); + this.glowLight.setPosition(th.lightAt.x, th.lightAt.y).setTint((r << 16) | (g << 8) | b).setAlpha(0.07); + const flick = () => { + if (!this.alive() || this.lifeMode !== th.life) return; + this.tweens.add({ targets: this.glowLight, alpha: 0.07 + (Math.random() - 0.4) * th.flicker * 2, duration: 140 + Math.random() * 380, ease: 'Sine.easeInOut', onComplete: flick }); + }; + if (th.flicker > 0.025) flick(); + this.bed?.stop(); + this.bed = null; + const bedOpts = { rain: { vol: 0.03 }, wind: { vol: 0.028, lp: 520, hp: 70, drips: false }, water: { vol: 0.022, lp: 700, hp: 140, drips: true } }[th.ambience]; + if (bedOpts) { this.bed = new RainBed(this, bedOpts); this.bed.setOn(this.settings.ambience); } + this.updatePlate(); + } + + // ── Room life (the window) ──────────────────────────────────────────────── + tickLife(delta) { + const g = this.lifeG; + if (!g || !this.lifeMode) return; + const k = Math.min(3, delta / 16.67); + const W0 = WINDOW.x0, W1 = WINDOW.x1, Y0 = WINDOW.y0, Y1 = WINDOW.y1, ww = W1 - W0, wh = Y1 - Y0; + const mode = this.lifeMode; + if (!this.lifeParts) { + const n = { clouds: 6, snow: 70, stars: 18, river: 14, rain: 40 }[mode]; + this.lifeParts = Array.from({ length: n }, () => ({ x: W0 + Math.random() * ww, y: Y0 + Math.random() * wh, v: 0.3 + Math.random(), p: Math.random() * 6.28, s: Math.random() })); + } + g.clear(); + for (const q of this.lifeParts) { + q.p += 0.03 * k; + if (mode === 'clouds') { + q.x += 0.08 * k * (0.5 + q.s); + if (q.x > W1 + 60) q.x = W0 - 60; + const y = Y0 + 10 + q.s * wh * 0.35; + g.fillStyle(0xfff4e4, 0.16); + for (let j = 0; j < 3; j++) { + const cx = Math.max(W0 + 20, Math.min(W1 - 20, q.x + j * 18)); + g.fillEllipse(cx, y - (j === 1 ? 6 : 0), 46 + q.s * 30, 14 + q.s * 8); + } + } else if (mode === 'snow') { + q.y += (0.4 + q.s * 0.9) * k; + q.x += Math.sin(q.p) * 0.4 * k; + if (q.y > Y1) { q.y = Y0; q.x = W0 + Math.random() * ww; } + if (q.x < W0 || q.x > W1) continue; + g.fillStyle(0xffffff, 0.55 + q.s * 0.35); + g.fillCircle(q.x, q.y, 1 + q.s * 1.6); + } else if (mode === 'stars') { + const y = Y0 + 6 + q.s * wh * 0.45; + const a = 0.2 + Math.max(0, Math.sin(q.p * (0.6 + q.v))) * 0.8; + g.fillStyle(0xfff6dc, a); + g.fillCircle(q.x, y, 1.1 + a * 0.8); + } else if (mode === 'river') { + const y = Y0 + wh * (0.64 + q.s * 0.32); + const x = W0 + ww * 0.66 + Math.sin(q.p * 0.7 + q.s * 9) * ww * 0.05; + g.fillStyle(0xfff0c8, 0.15 + Math.max(0, Math.sin(q.p * 1.3)) * 0.45); + g.fillRect(x - 10 - q.s * 20, y, 20 + q.s * 40, 1.6); + } else { + q.y += (1.6 + q.s * 2.2) * k; + if (q.y > Y1 + 10) { q.y = Y0 - Math.random() * 20; q.x = W0 + Math.random() * ww; } + const y0 = Math.max(Y0, q.y - 12), y1 = Math.min(Y1 - 2, q.y); + if (y1 <= y0) continue; + g.lineStyle(1.4, 0xd8e4ff, 0.26); + g.lineBetween(q.x, y0, q.x + 0.6, y1); + } + } + } + + update(time, delta) { + super.update(time, delta); + this.tickLife(delta); + } + + // ── The scorecard ───────────────────────────────────────────────────────── + buildScorecard() { + this.add.image(SCORECARD.x, SCORECARD.y, 'st-scorecard').setDepth(D.labels); + const L = SCORECARD.x - SCORECARD.w / 2; + this.scHighlight = this.add.rectangle(SCORECARD.x, rowY(0), SCORECARD.w - 4, ROW_H - 6, 0xffe066, 0.35).setDepth(D.labels + 0.05); + this.scRows = TOUR.map((type, i) => { + const y = rowY(i); + const meta = GAME_META[type]; + const label = type === 'threeshuffles' ? 'Three Shuffles' : meta.name; + const name = this.add.text(L + 62, y - 14, label, { fontFamily: FONT_HAND, fontSize: '24px', color: INK }).setOrigin(0, 0.5).setDepth(D.labels + 0.1); + const venue = this.add.text(L + 62, y + 16, meta.venue, { fontFamily: '"Julius Sans One"', fontSize: '11px', color: GREY, wordWrap: { width: 180 } }).setOrigin(0, 0.5).setDepth(D.labels + 0.1); + const score = this.add.text(L + SCORECARD.w - 42, y - 4, '', { fontFamily: FONT_HAND, fontSize: '34px', color: INK }).setOrigin(0.5).setDepth(D.labels + 0.1); + const live = this.add.text(L + SCORECARD.w - 42, y + 26, '', { fontFamily: FONT_HAND, fontSize: '17px', color: GREY }).setOrigin(0.5).setDepth(D.labels + 0.1); + const stamp = this.add.text(L + SCORECARD.w - 110, y, '', { + fontFamily: 'Righteous', fontSize: '22px', color: '#2f7a3a', stroke: '#f4eedc', strokeThickness: 2, + }).setOrigin(0.5).setRotation(-0.18).setDepth(D.labels + 0.2).setAlpha(0.85).setVisible(false); + return { name, venue, score, live, stamp }; + }); + const ty = scTop() + 676; + this.scTotal = this.add.text(L + SCORECARD.w - 42, ty - 2, '0', { fontFamily: FONT_HAND, fontSize: '40px', color: INK }).setOrigin(0.5).setDepth(D.labels + 0.1); + this.scMode = this.add.text(L + 14, scTop() + 772, '', { fontFamily: '"Julius Sans One"', fontSize: '11px', color: GREY }).setOrigin(0, 0.5).setDepth(D.labels + 0.1); + } + + updateScorecard() { + if (!this.scRows) return; + TOUR.forEach((type, i) => { + const row = this.scRows[i], r = this.results[i]; + if (r) { + row.score.setText(String(r.pts)).setColor(r.won ? GREEN : INK).setAlpha(1).setScale(1); + row.live.setText(''); + if (r.won || r.best) row.stamp.setText(r.won ? 'CLEARED' : 'BEST!').setColor(r.won ? '#2f7a3a' : '#b8231f').setVisible(true).setScale(1).setAlpha(0.88); + else row.stamp.setVisible(false); + } else if (i === this.tourIndex && this.gs && !this.legDone) { + row.score.setText(''); + row.live.setText(`now +${this.gs.remainingValue()}`); + } else { row.score.setText(''); row.live.setText(''); } + if (!r) row.stamp.setVisible(false); + }); + this.scHighlight.setY(rowY(Math.min(this.tourIndex, TOUR.length - 1))).setVisible(this.results.length < TOUR.length); + this.scTotal.setText(String(this.total)); + const best = loadStats('solitairetour', this.tourMode).bests?.tour; + this.scMode.setText(`${this.tourMode === 'casual' ? 'Casual rules · undo allowed' : 'Tournament rules · no undo'}${best != null ? ` · best ${best}` : ''}`); + } + + /** Pencil the leg's score in, then stamp it. */ + async writeScore(i, pts, cleared, newBest) { + const row = this.scRows[i]; + row.live.setText(''); + row.score.setText(String(pts)).setColor(cleared ? GREEN : INK).setAlpha(0).setScale(1.4); + playSoundEx(this, SFX.PENCIL_WRITE, { volume: 0.6 }); + this.tweens.add({ targets: row.score, alpha: 1, scale: 1, duration: 420, ease: 'Cubic.easeOut' }); + await this.wait(480); + const label = cleared ? 'CLEARED' : newBest ? 'BEST!' : null; + if (label) { + row.stamp.setText(label).setColor(cleared ? '#2f7a3a' : '#b8231f').setVisible(true).setScale(2.4).setAlpha(0); + this.tweens.add({ targets: row.stamp, scale: 1, alpha: 0.88, duration: 220, ease: 'Back.easeOut' }); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.7, rate: 0.7 }); + } + this.scTotal.setText(String(this.total)); + await this.wait(400); + } + + // ── The leg plate ───────────────────────────────────────────────────────── + buildPlate() { + const x = PLATE.x, top = PLATE.y - PLATE.h / 2; + this.add.image(x, PLATE.y, 'st-plate').setDepth(D.labels); + const L = x - PLATE.w / 2 + 28; + this.pl = { + hole: this.add.text(x, top + 44, '', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#a3242a' }).setOrigin(0.5).setDepth(D.labels + 0.1), + venue: this.add.text(x, top + 76, '', { fontFamily: FONT_HAND, fontSize: '26px', color: INK, align: 'center', wordWrap: { width: 250 } }).setOrigin(0.5).setDepth(D.labels + 0.1), + place: this.add.text(x, top + 110, '', { fontFamily: '"Julius Sans One"', fontSize: '12px', color: GREY }).setOrigin(0.5).setDepth(D.labels + 0.1), + game: this.add.text(x, top + 172, '', { fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex, align: 'center', wordWrap: { width: 280 } }).setOrigin(0.5).setDepth(D.labels + 0.1), + blurb: this.add.text(L, top + 214, '', { fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.textHex, wordWrap: { width: 262 }, lineSpacing: 4 }).setOrigin(0, 0).setDepth(D.labels + 0.1), + status: this.add.text(L, top + 446, '', { fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#c9b08a', wordWrap: { width: 262 }, lineSpacing: 6 }).setOrigin(0, 0).setDepth(D.labels + 0.1), + points: this.add.text(x, top + PLATE.h - 64, '', { fontFamily: 'Righteous', fontSize: '24px', color: '#ffd2a0', align: 'center' }).setOrigin(0.5).setDepth(D.labels + 0.1), + clock: this.add.text(x, top + PLATE.h - 30, '', { fontFamily: '"Julius Sans One"', fontSize: '12px', color: COLORS.mutedHex }).setOrigin(0.5).setDepth(D.labels + 0.1), + }; + } + + updatePlate() { + if (!this.pl || !this.legType) return; + const meta = GAME_META[this.legType]; + this.pl.hole.setText(`HOLE ${this.tourIndex + 1} OF ${TOUR.length}`); + this.pl.venue.setText(meta.venue); + this.pl.place.setText(meta.place.toUpperCase()); + this.pl.game.setText(meta.name); + this.pl.blurb.setText(meta.blurb); + this.pl.status.setText(this.leg ? this.leg.status().filter(Boolean).join('\n') : ''); + const left = this.gs ? this.gs.remainingValue() : 0; + this.pl.points.setText(this.legDone ? '' : left ? `On the table: ${left} pts` : 'Board clear!'); + } + + onClock(ms) { + const s = Math.floor(ms / 1000); + if (s === this.lastSec) return; + this.lastSec = s; + this.pl?.clock.setText(this.settings.timer ? `leg time ${formatTime(ms)} · tour ${formatTime(this.tourTime + ms)}` : ''); + } + + // ── Solitaire-layer hooks ───────────────────────────────────────────────── + computeLayout() { const v = this.leg.layout(); return { visible: v, loc: v }; } + + pickAt(pt) { + if (!this.leg) return null; + const src = this.leg.pickAt(pt, { drawMode: this.drawMode }); + if (src?.tapMove) src.tapAction = () => this.tapMove(src.tapMove); + return src; + } + + tapMove(m) { + if (!this.doMove(m, { via: 'click' })) { + this.floatText({ x: PCX, y: 860 }, m.t === 'kstock' || m.t === 'pstock' ? 'No more passes through the stock' : 'Not now', '#ffd2a0', { size: 20 }); + } + if (m.t === 'tdraw') { this.drawMode = false; this.updateDock(); this.refreshGlows(); } + } + + onTapEmpty(pt) { + const m = this.leg?.tapEmpty(pt); + if (!m) return false; + this.doMove(m, { via: 'click' }); + return true; + } + + movesFor(src) { return this.leg.movesFor(src); } + grabBlocker(src) { return this.leg.grabBlocker(src); } + dropBlocker(src, pt) { return this.leg.dropBlocker(src, pt); } + noMoveReason(src) { return this.leg.noMoveReason(src); } + commitMove(m) { return this.gs.apply(m); } + nextAutoMove() { return this.leg?.autoMove({ autoPlay: this.settings.autoPlay }) ?? null; } + + moveFx(move, cards) { + if (move.t === 'kstock' || move.t === 'pstock') return cards.length > 1 ? { duration: 320 } : { duration: 300 }; + if (move.t === 'ppair' || move.t === 'fpair' || move.t === 'pking') return { duration: 340 }; + return { duration: 240 }; + } + + /** Pair games: click one card, then its partner (or drag one onto the other). */ + onTap(src, pointer) { + if (!this.leg?.isPairLeg || src.tapAction) { super.onTap(src, pointer); return; } + if (this.leg.isKing(src)) { this.doMove(this.leg.movesFor(src)[0].move, { via: 'click' }); return; } + if (this.selected) { + if (this.selected.key === src.key) { this.selected = null; this.refreshGlows(); return; } + const idx = this.leg.partnerIds(this.selected).indexOf(src.ids[0]); + if (idx >= 0) { this.doMove(this.leg.movesFor(this.selected)[idx].move, { via: 'click' }); return; } + } + this.selected = src; + pickUp(this); + this.refreshGlows(); + if (!this.leg.partnerIds(src).length) { + const p = this.poseOf(src.ids[0]); + if (p) this.floatText({ x: p.x, y: p.y - 80 }, this.leg.noMoveReason(src), '#ffe29a', { size: 18, ms: 1300, rise: 24 }); + } + } + + extraGlow(id) { + if (!this.settings.hints || !this.leg || this.mode !== 'play') return null; + if (this.drawMode) return this.gs.piles?.some(p => { const k = p.findIndex(c => c.id === id); return k >= 0 && k < p.length - 1; }) ? { tint: 0xffd35a, alpha: 0.7 } : null; + if (this.leg.isPairLeg) { + if (this.selected && this.leg.partnerIds(this.selected).includes(id)) return { tint: 0xffd35a, alpha: 0.95 }; + if (!this.selected && this.hoverSrc && !this.hoverSrc.tapAction && this.leg.partnerIds(this.hoverSrc).includes(id)) return { tint: 0xffd35a, alpha: 0.5 }; + return null; + } + if (this.legType === 'golf' && this.leg.playableIds().has(id)) return { tint: 0xffd35a, alpha: 0.42 }; + return null; + } + + decorate(c) { + super.decorate(c); + c.faceImg.setTint(this.leg?.dimmed(c.card.id) ? 0x9c9890 : 0xffffff); + } + + animateMove(move, cards, via) { + if (move.t === 'tredeal') { this.animateRedeal(cards); return; } + const before = cards.map(c => this.poseOf(c.id)).filter(Boolean); + super.animateMove(move, cards, via); + if (['kwf', 'kcf', 'tfound'].includes(move.t)) homeChime(this, cards[0].pval); + if (move.t === 'ppair' || move.t === 'fpair' || move.t === 'pking') { + const at = before.length ? { x: before.reduce((t, p) => t + p.x, 0) / before.length, y: before.reduce((t, p) => t + p.y, 0) / before.length } : { x: PCX, y: 500 }; + const sum = move.t === 'fpair' ? 14 : 13; + this.floatText(at, move.t === 'pking' ? 'King!' : `${cards[0].label} + ${cards[1].label} = ${sum}`, '#ffe29a', { size: 26, ms: 1000 }); + this.burst(at, 0xffd35a, { n: 10, r: 80 }); + homeChime(this, 6 + Math.min(6, this.gs.discard.length / 6)); + } + if (move.t === 'gplay') this.golfRun(); + } + + golfRun() { + const run = this.gs.run; + this.bestRun = Math.max(this.bestRun, run); + homeChime(this, Math.min(13, run)); + if (run < 3) return; + const n = this.gs.foundation.length; + const p = { x: GOLF.FOUND.x + Math.min(GOLF.SHOW - 1, n - 1) * GOLF.FAN, y: GOLF.FOUND.y - 120 }; + const words = run >= 10 ? 'Hole in one!' : run >= 7 ? `Birdie run — ${run}!` : `Run of ${run}!`; + this.floatText(p, words, run >= 7 ? '#ffd35a' : '#f2e6c0', { size: 22 + Math.min(12, run * 1.2), ms: 1200 }); + if (run >= 5) this.burst(p, 0xffd35a, { n: 8 + run, r: 60 + run * 4 }); + } + + /** Three Shuffles: gather every fan, shuffle, and deal the fans out again. */ + async animateRedeal(cards) { + this.mode = 'anim'; + const centre = { x: PCX, y: 620, rot: 0, s: 1, q: 1 }; + cards.forEach((c, i) => { + const spr = this.sprites.get(c.id); + if (spr) this.tweenCard(spr, { ...centre, rot: (i % 7 - 3) * 0.02 }, { faceUp: false, duration: this.ms(320), delay: Math.min(300, i * 5) }); + }); playSound(this, SFX.CARD_SHUFFLE); - this.refresh(); - this.dealAnimation(); + await this.wait(this.ms(700)); + if (!this.alive()) return; + playSound(this, SFX.CARD_SHUFFLE); + const order = new Map(cards.map((c, i) => [c.id, i])); + this.layout({ duration: this.ms(260), delayFor: (v) => (order.has(v.card.id) ? order.get(v.card.id) * this.ms(14) : 0) }); + await this.wait(cards.length * this.ms(14) + this.ms(300)); + if (!this.alive()) return; + this.mode = 'play'; + this.onStateChanged(); + this.scheduleAuto(); } - // Fling the freshly-rendered cards from an off-screen deck into their dealt - // positions with a quick stagger. Runs on the real board sprites, so it needs - // no per-game layout math; input stays blocked (via `animating`) until it ends. - dealAnimation() { - const cards = this.board.list.filter((o) => o.isCard); - if (!cards.length) return; - const deckX = GAME_WIDTH / 2, deckY = GAME_HEIGHT + 90; - const homes = cards.map((c) => ({ c, x: c.x, y: c.y, alpha: c.alpha })); - this.animating = true; - for (const { c } of homes) { c.setPosition(deckX, deckY).setScale(0.7).setAlpha(0); } - homes.forEach(({ c, x, y, alpha }, i) => { - const last = i === homes.length - 1; - this.tweens.add({ - targets: c, x, y, scaleX: 1, scaleY: 1, alpha, - delay: i * 12, duration: 200, ease: 'Quad.easeOut', - onComplete: last ? () => { this.animating = false; this.updateStuck(); } : undefined, - }); - }); + undo() { + if (this.tourMode === 'tournament') { this.floatText({ x: PCX, y: 860 }, 'Tournament rules — no undo', '#ffd2a0', { size: 20 }); return; } + super.undo(); } - interactive() { return !this.legEnded && !this.overlayUp && !this.animating; } + redo() { if (this.tourMode !== 'tournament') super.redo(); } - // Animate a face-down stock card flipping face-up as it flies to its - // destination, then refresh the board with the post-move state. The engine - // move must already be applied; input is blocked until the flip lands. - animateDraw(card, fromX, fromY, toX, toY, sfx = SFX.CARD_SHOW) { - this.animating = true; - const fly = this.add.container(fromX, fromY).setDepth(D.banner); - this.drawFace(fly, {}, false, false, false); - const half = 170; - this.tweens.add({ targets: fly, x: toX, y: toY, duration: half * 2, ease: 'Quad.easeInOut' }); - this.tweens.add({ - targets: fly, scaleX: 0, duration: half, ease: 'Sine.easeIn', - onComplete: () => { - fly.removeAll(true); // edge-on: swap the back for the face - this.drawFace(fly, card, true, false, false); - playSound(this, sfx); - this.tweens.add({ - targets: fly, scaleX: 1, duration: half, ease: 'Sine.easeOut', - onComplete: () => { fly.destroy(); this.animating = false; this.refresh(); }, - }); - }, - }); - } + onRewind() { this.drawMode = false; this.stuckShown = false; } - applyMove(ok, sfx = SFX.CARD_PLACE) { - if (ok) { playSound(this, sfx); this.refresh(); } - return ok; - } - - refresh() { - this.renderBoard(); - this.updateHud(); - if (!this.legEnded && this.engine.isWon()) { this.endLeg(); return; } - if (this.kAutoReady()) { this.kAutoFinish(); return; } - this.updateStuck(); - } - - updateHud() { - const meta = GAME_META[this.legType]; - this.legText.setText(`Leg ${this.tourIndex + 1} / ${TOUR.length} · ${meta.name}`); - this.blurbText.setText(meta.blurb); - this.totalText.setText(`Tour total: ${this.total}`); - this.liveText.setText(`Stop now → +${this.engine.remainingValue()}`); - - const e = this.engine; - let status = ''; - if (this.legType === 'golf') status = `Stock: ${e.stock.length}`; - else if (this.legType === 'klondike') status = `Stock: ${e.stock.length} · Waste: ${e.waste.length}`; - else if (this.legType === 'pyramid') status = `Stock: ${e.stock.length} · Passes left: ${e.passesLeft}`; - else if (this.legType === 'fourteen') status = 'Remove pairs that total 14'; - else if (this.legType === 'threeshuffles') status = `Shuffles left: ${e.shufflesLeft} · Draw: ${e.drawsLeft}${this.tsDrawMode ? ' · pick a buried card' : ''}`; - this.statusText.setText(status); - - const ts = this.legType === 'threeshuffles'; - this.shuffleBtn.setVisible(ts); - this.drawBtn.setVisible(ts); - if (ts) { - this.shuffleBtn.setLabel(`Shuffle (${e.shufflesLeft})`).setEnabled(e.shufflesLeft > 0); - this.drawBtn.setLabel(this.tsDrawMode ? 'Cancel Draw' : 'Draw').setEnabled(this.tsDrawMode || e.canDraw()); + onStateChanged() { + if (!this.gs || !this.leg) return; + this.updateScorecard(); + this.updatePlate(); + this.updateDock(); + if (this.mode === 'play' && !this.finished) { + this.saveTour(); + if (this.isStuck() && !this.stuckShown) { + this.stuckShown = true; + this.floatText({ x: PCX, y: 560 }, 'No moves left — bank the leg', '#ffd2a0', { size: 26, ms: 1800 }); + } } } - updateStuck() { - const stuck = this.interactive() && !this.engine.hasMoves(); - this.stuckBanner.setVisible(stuck); - if (stuck && !this.pulse) { - this.pulse = this.tweens.add({ targets: this.noMoreBtn, scaleX: 1.06, scaleY: 1.06, yoyo: true, repeat: -1, duration: 520, ease: 'Sine.easeInOut' }); - } else if (!stuck && this.pulse) { - this.pulse.stop(); this.pulse = null; this.noMoreBtn.setScale(1); - } + isStuck() { return this.gs.isStuck ? this.gs.isStuck() : !this.gs.hasMoves(); } + + updateDock() { + if (!this.gs || !this.leg) return; + if (this.legDone) { this.setDock('Writing it on the card…', []); return; } + const casual = this.tourMode === 'casual'; + const stuck = this.mode === 'play' && this.isStuck(); + const left = this.gs.remainingValue(); + const undo = casual ? { label: 'Undo', act: () => this.undo(), enabled: this.undoStack.length > 0 } : null; + const bank = { label: `Bank +${left}`, act: () => this.onBank(), hot: stuck, enabled: this.mode === 'play' }; + const btns = [undo, bank]; + if (this.legType === 'threeshuffles') { + const e = this.gs; + btns.push({ label: `Shuffle (${e.shufflesLeft})`, act: () => this.onShuffle(), enabled: e.shufflesLeft > 0 && this.mode === 'play' && !this.drawMode }); + btns.push({ label: this.drawMode ? 'Cancel' : 'Draw', act: () => this.toggleDraw(), enabled: this.drawMode || e.canDraw() }); + } else if (casual) btns.push({ label: 'Redo', act: () => this.redo(), enabled: this.redoStack.length > 0 }); + let prompt; + if (this.mode === 'deal') prompt = 'Dealing…'; + else if (this.drawMode) prompt = 'Click a buried card to lift it free.'; + else if (stuck) prompt = `No moves left.\nBank the ${left} points still out.`; + else if (!this.started) prompt = this.leg.isPairLeg ? 'Click a card, then its partner —\nor drag one onto the other.' : 'Drag a card, or click it to\nsend it to its best spot.'; + else prompt = `Hole ${this.tourIndex + 1}: ${left} points on the table.`; + this.setDock(prompt, btns); } - onNoMore() { - if (!this.interactive()) return; - this.endLeg(); + onShuffle() { + if (!this.canAct() || this.legType !== 'threeshuffles') return; + this.selected = null; + if (!this.doMove({ t: 'tredeal' }, { via: 'click' })) this.floatText({ x: PCX, y: 860 }, 'No shuffles left', '#ffd2a0', { size: 20 }); } - onDraw() { - if (!this.interactive() || this.legType !== 'threeshuffles') return; - if (this.tsDrawMode) { this.tsDrawMode = false; this.refresh(); return; } - if (this.engine.canDraw()) { this.tsDrawMode = true; this.sel = null; this.refresh(); } + toggleDraw() { + if (!this.canAct() || this.legType !== 'threeshuffles') return; + if (!this.drawMode && !this.gs.canDraw()) { this.floatText({ x: PCX, y: 860 }, this.gs.shufflesLeft ? 'Use both shuffles before the Draw' : 'The Draw is spent', '#ffd2a0', { size: 20 }); return; } + this.drawMode = !this.drawMode; + this.selected = null; + this.updateDock(); + this.refreshGlows(); } - endLeg() { - if (this.legEnded) return; - this.legEnded = true; - this.sel = null; - if (this.pulse) { this.pulse.stop(); this.pulse = null; this.noMoreBtn.setScale(1); } - this.stuckBanner.setVisible(false); + onBank() { + if (!this.canAct() || this.legDone) return; + const left = this.gs.remainingValue(); + if (this.isStuck()) { this.endLeg(false); return; } + this.confirm('Bank this leg?', `There are still moves to make. End ${GAME_META[this.legType].name} now and add +${left} to your tour?`, `Bank +${left}`, () => this.endLeg(false), { no: 'Keep playing' }); + } - const won = this.engine.isWon(); - const pts = won ? 0 : this.engine.remainingValue(); + onKeyExtra(e) { + if (e.code === 'KeyB') this.onBank(); + else if (e.code === 'KeyS') this.onShuffle(); + else if (e.code === 'KeyD') this.toggleDraw(); + } + + onKey(e) { + if (e.code === 'Escape' && !this.modal && this.drawMode) { this.drawMode = false; this.updateDock(); this.refreshGlows(); return; } + super.onKey(e); + } + + // ── Ending a leg ────────────────────────────────────────────────────────── + onWin() { this.endLeg(true); } + + async endLeg(cleared) { + if (this.legDone) return; + this.legDone = true; + this.finished = true; + this.timerOn = false; + this.autoToken++; + this.mode = 'over'; + this.cancelDrag(); + this.selected = null; + this.drawMode = false; + const type = this.legType, i = this.tourIndex; + const pts = cleared ? 0 : this.gs.remainingValue(); + this.tourTime += this.elapsed; this.total += pts; - this.results.push({ type: this.legType, pts, won }); - playSound(this, won ? SFX.CASINO_WIN : SFX.CARD_PLACE); - this.showRecap(pts, won); + const newBest = recordBest('solitairetour', `leg-${type}`, pts, { mode: this.tourMode }); + this.results.push({ type, pts, won: cleared, best: newBest && !cleared }); + if (cleared) bumpCount('solitairetour', `clear-${type}`, { mode: this.tourMode }); + this.saveTour({ between: true }); + this.updateDock(); + this.updatePlate(); + if (cleared) { + this.stamp('CLEARED!', { x: PCX, y: 520 }, '#7cf0a0', { size: 90, sub: `${GAME_META[type].venue} — nothing left behind`, hold: 1400 }); + await this.wait(900); + if (!this.alive()) return; + await this.winCascade(homeStacks(this.gs), { interval: 60 }); + } else { + await this.bankCards(i, pts); + } + if (!this.alive()) return; + await this.writeScore(i, pts, cleared, newBest); + if (!this.alive()) return; + await this.wait(500); + if (i === TOUR.length - 1) this.finishTour(); + else this.showInterlude(); } - // ── overlays ───────────────────────────────────────────────────────────────── - clearOverlay() { - for (const o of this.overlayObjs) o.destroy(); - this.overlayObjs = []; - } - - overlayPanel(w, h) { - this.overlayUp = true; - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - const dim = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62).setDepth(D.overlay).setInteractive(); - const g = this.add.graphics().setDepth(D.overlay); - g.fillStyle(COLORS.panel, 1); g.fillRoundedRect(cx - w / 2, cy - h / 2, w, h, 20); - g.lineStyle(3, COLORS.accent, 1); g.strokeRoundedRect(cx - w / 2, cy - h / 2, w, h, 20); - this.overlayObjs.push(dim, g); - return { cx, cy }; - } - - showRecap(pts, won) { - const { cx, cy } = this.overlayPanel(820, 460); - const meta = GAME_META[this.legType]; - const last = this.tourIndex === TOUR.length - 1; - - this.overlayObjs.push(this.add.text(cx, cy - 165, won ? 'Board Cleared!' : 'No More Moves', { - fontFamily: 'Righteous', fontSize: '54px', color: won ? '#5fd29a' : COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - - this.overlayObjs.push(this.add.text(cx, cy - 92, meta.name, { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - - this.overlayObjs.push(this.add.text(cx, cy - 24, won ? '+0 — perfect, nothing left behind!' : `Cards left this leg → +${pts} points`, { - fontFamily: 'Righteous', fontSize: '40px', color: won ? '#5fd29a' : COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - - this.overlayObjs.push(this.add.text(cx, cy + 48, `Tour total: ${this.total}`, { - fontFamily: 'Righteous', fontSize: '34px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - - const nextName = last ? null : GAME_META[TOUR[this.tourIndex + 1]].name; - const cont = new Button(this, cx, cy + 150, last ? 'See Final Score' : `Next: ${nextName}`, () => { - this.clearOverlay(); this.overlayUp = false; this.advance(); - }, { width: 420, height: 64, fontSize: 26 }); - cont.setDepth(D.overlayUI); - this.overlayObjs.push(cont); - } - - advance() { - this.tourIndex++; - if (this.tourIndex < TOUR.length) this.startLeg(); - else this.showFinal(); - } - - showFinal() { - const { cx, cy } = this.overlayPanel(900, 760); - this.recordResult(); - - this.overlayObjs.push(this.add.text(cx, cy - 320, 'TOUR COMPLETE', { - fontFamily: 'Righteous', fontSize: '56px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - - this.overlayObjs.push(this.add.text(cx, cy - 238, `${this.total}`, { - fontFamily: 'Righteous', fontSize: '96px', color: this.total === 0 ? '#5fd29a' : COLORS.textHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - this.overlayObjs.push(this.add.text(cx, cy - 168, 'total points · closest to zero wins', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); - - this.results.forEach((r, i) => { - const y = cy - 96 + i * 46; - this.overlayObjs.push(this.add.text(cx - 320, y, GAME_META[r.type].name, { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.overlayUI)); - this.overlayObjs.push(this.add.text(cx + 320, y, r.won ? 'cleared · +0' : `+${r.pts}`, { - fontFamily: 'Righteous', fontSize: '24px', color: r.won ? '#5fd29a' : COLORS.dangerHex, - }).setOrigin(1, 0.5).setDepth(D.overlayUI)); + /** The cards left over fly off to the scorecard, counting up. */ + async bankCards(i, pts) { + const left = remainingCards(this.gs); + const to = { x: SCORECARD.x + SCORECARD.w / 2 - 42, y: rowY(i) }; + playSound(this, SFX.CARD_SHUFFLE); + left.forEach((card, k) => { + const c = this.sprites.get(card.id); + if (!c) return; + this.tweens.add({ targets: c, x: to.x, y: to.y, scaleX: 0.25, scaleY: 0.25, alpha: 0, delay: k * 18, duration: 420, ease: 'Cubic.easeIn' }); }); + this.floatText({ x: PCX, y: 520 }, `+${pts}`, '#ff9a7a', { size: 64, ms: 1400, rise: 30 }); + await this.wait(left.length * 18 + 520); + } - this.overlayObjs.push(this.add.text(cx, cy + 192, this.resultBlurb(), { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); + // ── Between legs: the route map and a postcard ─────────────────────────── + showInterlude() { + const from = TOUR[this.tourIndex], next = TOUR[this.tourIndex + 1]; + const w = 1340, h = 960; + this.openModal({ w, h, freeze: false }); + const top = CY - h / 2; + const mx = CX, my = top + 360; + this.addToModal(this.add.image(mx, my, ensureMap(this)).setDepth(D.modal + 1)); + const ox = mx - MAP.w / 2, oy = my - MAP.h / 2; + const P = (leg) => { const p = mapXY(STOPS[leg].lon, STOPS[leg].lat); return { x: ox + p.x, y: oy + p.y }; }; + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 2)); + const arc = (a, b) => { + const c = { x: (a.x + b.x) / 2, y: Math.min(a.y, b.y) - 60 - Math.abs(a.x - b.x) * 0.12 }; + return (t) => ({ x: (1 - t) ** 2 * a.x + 2 * (1 - t) * t * c.x + t * t * b.x, y: (1 - t) ** 2 * a.y + 2 * (1 - t) * t * c.y + t * t * b.y }); + }; + const dash = (f, alpha, color) => { + for (let t = 0; t < 1; t += 0.03) { + const a = f(t), b = f(Math.min(1, t + 0.016)); + g.lineStyle(3, color, alpha); g.lineBetween(a.x, a.y, b.x, b.y); + } + }; + for (let k = 0; k < TOUR.length - 1; k++) dash(arc(P(TOUR[k]), P(TOUR[k + 1])), k < this.tourIndex ? 0.85 : 0.28, k < this.tourIndex ? 0xa3242a : 0x6a4a2a); + TOUR.forEach((leg, k) => { + const p = P(leg); + const done = k <= this.tourIndex; + g.fillStyle(done ? 0xa3242a : 0xf2e6c0, 1); g.fillCircle(p.x, p.y, 9); + g.lineStyle(2.5, 0x4a2a12, 1); g.strokeCircle(p.x, p.y, 9); + const r = this.results[k]; + this.addToModal(this.add.text(p.x, p.y + 22, `${STOPS[leg].label}${r ? ` · ${r.pts}` : ''}`, { fontFamily: FONT_HAND, fontSize: '22px', color: '#3a2410' }).setOrigin(0.5, 0).setDepth(D.modal + 3)); + }); + // the token travels to the next stop + const route = arc(P(from), P(next)); + const tok = this.addToModal(this.add.container(P(from).x, P(from).y).setDepth(D.modal + 4)); + const tg = this.add.graphics(); + tg.fillStyle(0x1a1208, 0.35); tg.fillEllipse(3, 6, 34, 12); + tg.fillStyle(0xf2e6c0, 1); tg.fillCircle(0, 0, 15); + tg.lineStyle(3, 0xa3242a, 1); tg.strokeCircle(0, 0, 15); + tg.fillStyle(0xa3242a, 1); tg.fillTriangle(-7, 6, 7, 6, 0, -9); + tok.add(tg); + const prog = { t: 0 }; + const trail = this.addToModal(this.add.graphics().setDepth(D.modal + 3)); + this.tweens.add({ + targets: prog, t: 1, duration: 1700, delay: 400, ease: 'Sine.easeInOut', + onUpdate: () => { + const p = route(prog.t); + tok.setPosition(p.x, p.y); + trail.lineStyle(3, 0xa3242a, 0.9); + const q = route(Math.max(0, prog.t - 0.02)); + trail.lineBetween(q.x, q.y, p.x, p.y); + }, + onComplete: () => { playSoundEx(this, SFX.CARD_SHOW, { volume: 0.6 }); this.showPostcard(next, top, h); }, + }); + playSoundEx(this, SFX.WOOSH ?? SFX.CARD_SHUFFLE, { volume: 0.4 }); + this.modalText(CX, top + 40, `Hole ${this.tourIndex + 1} done — ${this.total} point${this.total === 1 ? '' : 's'} so far`, { fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex }); + const go = () => { if (!this.modal) return; this.closeModal(); this.tourIndex++; this.startLeg(); }; + this.modalButton(CX - 170, top + h - 52, `Deal me in at ${STOPS[next].label} ▶`, go, { width: 440, height: 54, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + this.modalButton(CX + 230, top + h - 52, 'Leave (tour is saved)', () => this.scene.start('GameMenu'), { width: 300, height: 54, variant: 'ghost', fontSize: 18 }); + this.modal.onEnter = go; + } - const again = new Button(this, cx - 170, cy + 290, 'Play Again', () => { - this.clearOverlay(); this.overlayUp = false; - this.tourIndex = 0; this.total = 0; this.results = []; this.recorded = false; - this.startLeg(); - }, { width: 280, height: 64, fontSize: 26 }); - again.setDepth(D.overlayUI); - const leave = new Button(this, cx + 170, cy + 290, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 280, height: 64, fontSize: 26 }); - leave.setDepth(D.overlayUI); - this.overlayObjs.push(again, leave); + showPostcard(leg, top, h) { + if (!this.modal) return; + const key = ensurePostcard(this, leg); + const meta = GAME_META[leg]; + const x = CX + 10, y = top + h - 310; + const card = this.addToModal(this.add.container(x + 900, y).setDepth(D.modal + 6).setRotation(0.12)); + card.add(this.add.image(0, 0, key)); + const L = -POSTCARD.w / 2 + 360; + card.add(this.add.text(L, -POSTCARD.h / 2 + 52, meta.greet, { fontFamily: FONT_HAND, fontSize: '30px', color: '#23324a', wordWrap: { width: 210 } }).setOrigin(0, 0.5)); + card.add(this.add.text(L, -POSTCARD.h / 2 + 128, `Next up: ${meta.name}`, { fontFamily: FONT_HAND, fontSize: '22px', color: '#a3242a', wordWrap: { width: 220 } }).setOrigin(0, 0.5)); + card.add(this.add.text(L, -POSTCARD.h / 2 + 168, meta.venue, { fontFamily: FONT_HAND, fontSize: '19px', color: '#23324a', wordWrap: { width: 220 } }).setOrigin(0, 0)); + card.add(this.add.text(L, -POSTCARD.h / 2 + 244, `So far: ${this.total} pts\n${this.results.filter(r => r.won).length} leg${this.results.filter(r => r.won).length === 1 ? '' : 's'} cleared`, { fontFamily: FONT_HAND, fontSize: '20px', color: '#23324a', lineSpacing: 14 }).setOrigin(0, 0)); + this.tweens.add({ targets: card, x, rotation: -0.035, duration: 520, ease: 'Back.easeOut' }); + } + + // ── The end of the tour ─────────────────────────────────────────────────── + finishTour() { + const total = this.total; + const won = total <= 40; + recordGame('solitairetour', { won, time: Math.round(this.tourTime), mode: this.tourMode, extra: { total } }); + const prevBest = loadStats('solitairetour', this.tourMode).bests?.tour; + const newBest = recordBest('solitairetour', 'tour', total, { mode: this.tourMode }); + recordBest('solitairetour', 'run', this.bestRun, { lower: false, mode: this.tourMode }); + const result = total <= 40 ? 'win' : total <= 120 ? 'draw' : 'loss'; + api.post('/history/single-player', { slug: 'solitairetour', score: total, opponentScores: [], result }).catch(() => { /* best effort */ }); + this.clearSave(); + this.updateScorecard(); + flourish(this); + this.showFinal({ newBest, firstTour: prevBest == null }); + } + + showFinal({ newBest, firstTour }) { + const w = 1000, h = 820; + this.openModal({ w, h, paper: true, freeze: false }); + const top = CY - h / 2; + this.modalText(CX, top + 64, 'Tour Complete', { fontFamily: FONT_HAND, fontSize: '58px', color: INK }); + this.modalText(CX, top + 150, String(this.total), { fontFamily: FONT_HAND, fontSize: '110px', color: this.total === 0 ? GREEN : INK }); + this.modalText(CX, top + 220, 'total points · closest to zero wins', { fontFamily: '"Julius Sans One"', fontSize: '16px', color: GREY }); + if (newBest || firstTour) { + const t = this.modalText(CX + 190, top + 140, newBest ? 'new best!' : 'first tour!', { fontFamily: FONT_HAND, fontSize: '32px', color: '#b8231f' }); + t.setRotation(-0.12); + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 1)); + g.lineStyle(3, 0xb8231f, 0.8); g.strokeEllipse(t.x, t.y, t.width + 34, 56); + } + this.results.forEach((r, i) => { + const y = top + 280 + i * 58; + const meta = GAME_META[r.type]; + this.addToModal(this.add.text(CX - 380, y, `${i + 1}`, { fontFamily: FONT_HAND, fontSize: '30px', color: GREY }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX - 330, y, meta.name, { fontFamily: FONT_HAND, fontSize: '30px', color: INK }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX - 40, y, meta.venue, { fontFamily: '"Julius Sans One"', fontSize: '14px', color: GREY }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX + 380, y, r.won ? 'cleared · 0' : `+${r.pts}`, { fontFamily: FONT_HAND, fontSize: '30px', color: r.won ? GREEN : RED }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + }); + const runs = this.bestRun >= 3 ? ` · longest Golf run ${this.bestRun}` : ''; + this.modalText(CX, top + 590, `${this.resultBlurb()}${runs}`, { fontFamily: FONT_HAND, fontSize: '30px', color: '#a3242a' }); + this.modalText(CX, top + 640, `${this.tourMode === 'casual' ? 'Casual rules' : 'Tournament rules'} · ${formatTime(this.tourTime)}`, { fontFamily: '"Julius Sans One"', fontSize: '14px', color: GREY }); + const by = top + h - 60; + this.modalButton(CX - 250, by, 'New Tour', () => this.startTour(), { width: 220, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + this.modalButton(CX, by, 'Records', () => { this.closeModal(); this.openStats(true); }, { width: 220 }); + this.modalButton(CX + 250, by, 'Leave', () => this.scene.start('GameMenu'), { width: 220, variant: 'ghost' }); + this.modal.onEnter = () => this.startTour(); } resultBlurb() { const t = this.total; - if (t === 0) return 'Flawless tour — a perfect zero!'; + if (t === 0) return 'A flawless tour — a perfect zero!'; if (t <= 40) return 'Outstanding — right on the edge of zero!'; - if (t <= 90) return 'Solid run around the course.'; + if (t <= 90) return 'A solid trip round the world.'; if (t <= 160) return 'Not bad — a few cards got away.'; return 'Plenty of room to improve next tour.'; } - recordResult() { - if (this.recorded) return; - this.recorded = true; - const result = this.total <= 40 ? 'win' : this.total <= 120 ? 'draw' : 'loss'; - api.post('/history/single-player', { - slug: 'solitairetour', score: this.total, opponentScores: [], result, - }).catch(() => { /* best effort */ }); - } - - // ── card drawing helpers ───────────────────────────────────────────────────── - drawFace(container, card, faceUp, selected, hint) { - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); - if (!faceUp) { - g.fillStyle(0x16324f, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, COLORS.accent, 0.7); g.strokeRoundedRect(x + 5, y + 5, CARD_W - 10, CARD_H - 10, CARD_R - 2); - container.add(g); - container.add(this.add.text(0, 0, '✦', { fontFamily: 'serif', fontSize: '40px', color: '#caa84b' }).setOrigin(0.5).setAlpha(0.55)); - return; - } - g.fillStyle(0xfbf6e7, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - const rimColor = selected ? SEL : hint ? HINT : 0xcc803a; - const rimW = selected ? 5 : hint ? 4 : 2; - g.lineStyle(rimW, rimColor, selected || hint ? 1 : 0.5); - g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - container.add(g); - - const col = card.isRed ? '#c0392b' : '#1a1208'; - container.add(this.add.text(x + 9, y + 6, card.label, { fontFamily: 'Righteous', fontSize: '24px', color: col })); - container.add(this.add.text(x + 11, y + 35, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '22px', color: col })); - container.add(this.add.text(0, 6, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '48px', color: col }).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 9, y + CARD_H - 6, card.label, { fontFamily: 'Righteous', fontSize: '24px', color: col }).setOrigin(1, 1)); - } - - card(cardObj, x, y, opts = {}) { - const { faceUp = true, selected = false, hint = false, dim = false, onClick = null, onDown = null } = opts; - const c = this.add.container(x, selected ? y - 10 : y); - c.isCard = true; // marks it for the start-of-leg deal animation - this.drawFace(c, cardObj, faceUp, selected, hint); - if (dim) c.setAlpha(0.4); - if (onClick || onDown) { - c.setInteractive(new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), Phaser.Geom.Rectangle.Contains); - c.input.cursor = onDown ? 'grab' : 'pointer'; - if (onClick) c.on('pointerdown', onClick); - if (onDown) c.on('pointerdown', (pointer) => onDown(c, pointer)); - } - this.board.add(c); - return c; - } - - slot(x, y, label, onClick = null) { - const c = this.add.container(x, y); - const g = this.add.graphics(); - g.lineStyle(2, COLORS.accent, 0.4); - g.strokeRoundedRect(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H, CARD_R); - c.add(g); - if (label) c.add(this.add.text(0, 0, label, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, align: 'center' }).setOrigin(0.5)); - if (onClick) { - c.setInteractive(new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), Phaser.Geom.Rectangle.Contains); - c.input.cursor = 'pointer'; - c.on('pointerdown', onClick); - } - this.board.add(c); - return c; - } - - // ── board rendering / input, per game ───────────────────────────────────────── - renderBoard() { - this.board.removeAll(true); - switch (this.legType) { - case 'golf': return this.renderGolf(); - case 'klondike': return this.renderKlondike(); - case 'pyramid': return this.renderPyramid(); - case 'fourteen': return this.renderFourteen(); - case 'threeshuffles': return this.renderThreeShuffles(); - } - } - - // Golf ------------------------------------------------------------------------- - renderGolf() { - const e = this.engine; - const topY = 250, fan = 30; - for (let c = 0; c < 7; c++) { - const pile = e.tableau[c]; - if (!pile.length) { this.slot(colX(c), topY, ''); continue; } - pile.forEach((card, idx) => { - const last = idx === pile.length - 1; - this.card(card, colX(c), topY + idx * fan, { - hint: last && e.canPlay(card), - onClick: last ? () => this.gAct(() => e.playColumn(c)) : null, - }); - }); - } - // foundation + stock - const top = e.foundationTop(); - if (top) this.card(top, 880, 800, {}); - if (e.stock.length) { - this.card({}, 1040, 800, { faceUp: false, onClick: () => this.gStock() }); - this.board.add(this.add.text(1040, 884, `Stock ×${e.stock.length}`, { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex }).setOrigin(0.5)); - } else { - this.slot(1040, 800, 'empty'); - } - this.board.add(this.add.text(880, 884, 'Foundation', { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex }).setOrigin(0.5)); - } - - gAct(fn, sfx = SFX.CARD_PLACE) { if (!this.interactive()) return; this.applyMove(fn(), sfx); } - - gStock() { - if (!this.interactive() || !this.engine.stock.length) return; - const card = this.engine.stock[this.engine.stock.length - 1]; - this.engine.dealStock(); - this.animateDraw(card, 1040, 800, 880, 800); // stock → foundation - } - - // Klondike / Three Shuffles ---------------------------------------------------- - renderKlondike() { - const e = this.engine; - const suits = ['s', 'h', 'd', 'c']; - this.kSprites.clear(); - this.dropZones = []; - // stock - if (e.stock.length) { - this.card({}, 600, 250, { faceUp: false, onClick: () => this.kStock() }); - } else { - this.slot(600, 250, e.recyclesLeft > 0 ? '↻ recycle' : 'empty', e.waste.length && e.recyclesLeft > 0 ? () => this.kStock() : null); - } - this.board.add(this.add.text(600, 332, `Stock ×${e.stock.length}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex }).setOrigin(0.5)); - - // waste (fan last 3) - const wShown = e.waste.slice(-3); - if (!wShown.length) this.slot(735, 250, ''); - wShown.forEach((card, i) => { - const isTop = i === wShown.length - 1; - const c = this.card(card, 735 + i * 26, 250, { - selected: isTop && this.sel?.kind === 'waste', - onDown: isTop ? (_co, pointer) => this.kPointerDown({ kind: 'waste' }, pointer) : null, - }); - this.kSprites.set(card.id, c); + // ── Records ─────────────────────────────────────────────────────────────── + openStats(afterTour = false) { + const mode = this.tourMode; + const st = loadStats('solitairetour', mode); + const other = loadStats('solitairetour', mode === 'casual' ? 'tournament' : 'casual'); + const h = 760; + this.openModal({ w: 900, h, paper: true, onEscape: () => { this.closeModal(); if (afterTour) this.showFinal({ newBest: false, firstTour: false }); } }); + const top = CY - h / 2; + this.modalText(CX, top + 60, `Tour Records — ${mode === 'casual' ? 'Casual' : 'Tournament'}`, { fontFamily: FONT_HAND, fontSize: '44px', color: INK }); + const recent = (st.recent ?? []).map(r => r.total).filter(x => x != null); + const avg = recent.length ? Math.round(recent.reduce((a, b) => a + b, 0) / recent.length) : null; + const lines = [ + ['Tours finished', String(st.played)], + ['Best tour', st.bests?.tour != null ? String(st.bests.tour) : '—'], + ['Average (recent)', avg != null ? String(avg) : '—'], + ['Tours at 40 or under', String(st.won)], + ['Longest Golf run', st.bests?.run != null ? String(st.bests.run) : '—'], + [`Best ${mode === 'casual' ? 'tournament' : 'casual'} tour`, other.bests?.tour != null ? String(other.bests.tour) : '—'], + ]; + lines.forEach(([k, v], i) => { + const y = top + 130 + i * 40; + this.addToModal(this.add.text(CX - 380, y, k, { fontFamily: FONT_HAND, fontSize: '26px', color: GREY }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX - 40, y, v, { fontFamily: FONT_HAND, fontSize: '28px', color: INK }).setOrigin(1, 0.5).setDepth(D.modal + 1)); }); - - // foundations - suits.forEach((s, i) => { - const x = 1090 + i * COL_GAP; - const top = e.foundationTop(s); - if (top) this.card(top, x, 250, { onClick: () => this.kFoundation() }); - else this.slot(x, 250, { s: '♠', h: '♥', d: '♦', c: '♣' }[s], () => this.kFoundation()); - this.dropZones.push({ cx: x, cy: 250, hw: CARD_W * 0.7, hh: CARD_H * 0.8, hlx: x, hly: 250, kind: 'foundation', idx: i }); + this.modalText(CX + 220, top + 120, 'Each stop', { fontFamily: FONT_HAND, fontSize: '28px', color: INK }); + TOUR.forEach((type, i) => { + const y = top + 170 + i * 44; + const best = st.bests?.[`leg-${type}`]; + const clears = st.counts?.[`clear-${type}`] ?? 0; + this.addToModal(this.add.text(CX + 20, y, GAME_META[type].name, { fontFamily: FONT_HAND, fontSize: '24px', color: GREY }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX + 400, y, `${best != null ? `best ${best}` : '—'}${clears ? ` · ${clears}✓` : ''}`, { fontFamily: FONT_HAND, fontSize: '24px', color: INK }).setOrigin(1, 0.5).setDepth(D.modal + 1)); }); - - // tableau - const topY = 430; - for (let c = 0; c < 7; c++) { - const pile = e.tableau[c]; - this.dropZones.push({ cx: colX(c), cy: 640, hw: CARD_W * 0.7, hh: 320, hlx: colX(c), hly: topY + pile.length * 32, kind: 'column', idx: c }); - if (!pile.length) { this.slot(colX(c), topY, '', () => this.kColumnDrop(c)); continue; } - let y = topY; - pile.forEach((entry, idx) => { - const selected = this.sel?.kind === 'run' && this.sel.col === c && idx >= this.sel.idx; - const cont = this.card(entry.card, colX(c), y, { - faceUp: entry.faceUp, - selected, - onDown: entry.faceUp ? (_co, pointer) => this.kPointerDown({ kind: 'tableau', col: c, idx }, pointer) : null, - }); - if (entry.faceUp) this.kSprites.set(entry.card.id, cont); - y += entry.faceUp ? 32 : 14; - }); - } - } - - kStock() { - if (!this.interactive()) return; - this.sel = null; - const e = this.engine; - if (!e.stock.length) { this.applyMove(e.dealStock(), SFX.CARD_SHUFFLE); return; } // recycle - const card = e.stock[e.stock.length - 1]; - e.dealStock(); - const shown = Math.min(e.waste.length, 3); // waste fans the last three - this.animateDraw(card, 600, 250, 735 + (shown - 1) * 26, 250); - } - - kWaste() { - if (!this.interactive()) return; - if (this.sel?.kind === 'waste') this.sel = null; - else this.sel = { kind: 'waste' }; - this.refresh(); - } - - kCard(col, idx) { - if (!this.interactive()) return; - if (this.sel && this.kDrop(col)) return; - const run = this.engine.faceUpRun(col, idx); - if (run) { - if (this.sel?.kind === 'run' && this.sel.col === col && this.sel.idx === idx) this.sel = null; - else this.sel = { kind: 'run', col, idx }; - } else { - this.sel = null; - } - this.refresh(); - } - - kColumnDrop(col) { - if (!this.interactive() || !this.sel) return; - if (!this.kDrop(col)) { this.sel = null; this.refresh(); } - } - - kDrop(destCol) { - const e = this.engine; - let ok = false; - if (this.sel.kind === 'waste') ok = e.moveWasteToColumn(destCol); - else ok = e.moveRun(this.sel.col, this.sel.idx, destCol); - if (ok) { this.sel = null; this.applyMove(true); return true; } - return false; - } - - kFoundation() { - if (!this.interactive() || !this.sel) return; - const e = this.engine; - let ok = false; - if (this.sel.kind === 'waste') ok = e.playWasteToFoundation(); - else { - const run = e.faceUpRun(this.sel.col, this.sel.idx); - if (run && run.length === 1) ok = e.playColumnToFoundation(this.sel.col); - } - this.sel = null; - if (ok) this.applyMove(true); else this.refresh(); - } - - // ── Klondike auto-finish ────────────────────────────────────────────────────── - // Once the stock is spent and every tableau card is face-up, the leg is often a - // foregone win — all that's left is sending cards to the foundations. We detect - // that exact state and fly the cards home automatically. The face-up requirement - // alone isn't enough (a low card can sit buried under a higher one of its suit - // and stall a foundation-only finish), so we first simulate the run and only - // take over when playing to foundations actually clears the board. - kAutoReady() { - const e = this.engine; - if (this.legType !== 'klondike' || this.legEnded || this.animating) return false; - if (e.stock.length || e.isWon()) return false; - if (!e.tableau.every((pile) => pile.every((entry) => entry.faceUp))) return false; - return this.kFoundationOnlyWins(); - } - - // Dry-run of foundation-only play over copies of the piles/waste tops. - kFoundationOnlyWins() { - const e = this.engine; - const cols = e.tableau.map((pile) => pile.map((entry) => entry.card)); - const waste = e.waste.slice(); - const need = {}; - for (const s of ['s', 'h', 'd', 'c']) need[s] = (e.foundationTop(s)?.pval ?? 0) + 1; - let remaining = waste.length + cols.reduce((t, c) => t + c.length, 0); - let moved = true; - while (remaining > 0 && moved) { - moved = false; - const wt = waste[waste.length - 1]; - if (wt && wt.pval === need[wt.suit]) { waste.pop(); need[wt.suit]++; remaining--; moved = true; } - for (const col of cols) { - const top = col[col.length - 1]; - if (top && top.pval === need[top.suit]) { col.pop(); need[top.suit]++; remaining--; moved = true; } - } - } - return remaining === 0; - } - - kAutoFinish() { - if (this.animating) return; - this.animating = true; - this.sel = null; - this.stuckBanner.setVisible(false); - if (this.pulse) { this.pulse.stop(); this.pulse = null; this.noMoreBtn.setScale(1); } - this.kAutoStep(); - } - - kAutoStep() { - const e = this.engine; - const suits = ['s', 'h', 'd', 'c']; - // Pick the next card that can go home: waste top first, then any column top. - let next = null; - const wt = e.waste[e.waste.length - 1]; - if (e.canPlayFoundation(wt)) next = { card: wt, apply: () => e.playWasteToFoundation() }; - else for (let c = 0; c < 7; c++) { - const pile = e.tableau[c]; - const top = pile[pile.length - 1]; - if (top && top.faceUp && e.canPlayFoundation(top.card)) { next = { card: top.card, apply: () => e.playColumnToFoundation(c) }; break; } - } - if (!next) { this.animating = false; this.refresh(); return; } - - const src = this.kSprites.get(next.card.id); - const fromX = src ? src.x : 735, fromY = src ? src.y : 250; - if (src) src.setVisible(false); // hand the card off to the flyer - const toX = 1090 + suits.indexOf(next.card.suit) * COL_GAP, toY = 250; - next.apply(); - - const fly = this.add.container(fromX, fromY).setDepth(D.banner); - this.drawFace(fly, next.card, true, false, false); - this.tweens.add({ - targets: fly, x: toX, y: toY, duration: 120, ease: 'Quad.easeIn', - onComplete: () => { - fly.destroy(); - playSound(this, SFX.CARD_PLACE); - this.renderBoard(); - this.updateHud(); - this.kAutoStep(); - }, + const tail = (st.recent ?? []).slice(0, 12).reverse(); + this.modalText(CX, top + 450, tail.length ? 'Recent tours' : 'No tours finished yet', { fontFamily: FONT_HAND, fontSize: '24px', color: GREY }); + tail.forEach((r, i) => { + this.modalText(CX + (i - (tail.length - 1) / 2) * 62, top + 494, String(r.total ?? '?'), { fontFamily: FONT_HAND, fontSize: '26px', color: (r.total ?? 99) <= 40 ? GREEN : INK }); }); + this.modalText(CX, top + 560, 'Every card left on the table scores its value; a cleared board scores 0.', { fontFamily: '"Julius Sans One"', fontSize: '14px', color: GREY }); + this.modalButton(CX, top + h - 52, 'Close', () => this.modal.onEscape(), { width: 220, height: 46, fontSize: 19 }); } - // ── Generic drag-and-drop (Klondike + Three Shuffles) ───────────────────────── - // Pointer-down on a card records a potential drag; moving past a small - // threshold promotes it to a real drag, and a release without movement falls - // back to a tap. Each renderer fills this.dropZones; resolveDrop() turns a - // pointer position into a highlight + a commit closure for the active game. - setupDrag() { - this.input.on('pointermove', (pointer) => { - if (!pointer.isDown) return; - if (this.dragState) { - this.dragUpdate(pointer); - } else if (this.potentialDrag) { - const dx = pointer.x - this.potentialDrag.startX; - const dy = pointer.y - this.potentialDrag.startY; - if (dx * dx + dy * dy > 80) this.dragPromote(); - } - }); - this.input.on('pointerup', () => { - if (this.dragState) this.dragEnd(); - else if (this.potentialDrag) { - const pd = this.potentialDrag; - this.potentialDrag = null; - pd.tap(); - } - }); + // ── Menu + settings ─────────────────────────────────────────────────────── + openMenu() { + if (this.modal) return; + const items = [ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Records', act: () => { this.closeModal(); this.openStats(); } }, + { label: 'How to play', act: () => { this.closeModal(); this.openRules(); } }, + ]; + if (this.tourMode === 'casual' && this.started && !this.legDone) { + items.push({ label: 'Restart this hole', act: () => { this.closeModal(); this.confirm('Restart this hole?', 'Every card goes back to where it was dealt (you can still Undo).', 'Restart', () => this.restartDeal()); } }); + } + items.push({ label: 'New tour', ghost: true, act: () => { this.closeModal(); this.confirm('Start a new tour?', 'The tour in progress will be thrown away.', 'New tour', () => this.startTour()); } }); + items.push({ label: 'Leave (tour is saved)', ghost: true, act: () => this.scene.start('GameMenu') }); + this.openPauseMenu(items); } - beginDrag(objs, pointer, tap, resolve) { - if (!this.interactive() || this.dragState || !objs.length) return; - this.potentialDrag = { - startX: pointer.x, startY: pointer.y, tap, resolve, - sprites: objs.map((obj) => ({ obj, offX: obj.x - pointer.x, offY: obj.y - pointer.y, homeX: obj.x, homeY: obj.y })), + openSettings() { + const s = this.settings; + this.openSettingsModal([ + { label: 'Clicking a card (building games)', options: [['smart', 'Moves it'], ['select', 'Selects it']], get: () => s.click, set: (v) => { s.click = v; this.selected = null; this.refreshGlows(); } }, + { label: 'Auto-play safe cards home', options: [[true, 'On'], [false, 'Off']], get: () => s.autoPlay, set: (v) => { s.autoPlay = v; if (v) this.scheduleAuto(); } }, + { label: 'Show playable cards & partners', options: [[true, 'On'], [false, 'Off']], get: () => s.hints, set: (v) => { s.hints = v; this.refreshGlows(); } }, + { label: 'Rules for your next tour', options: [[true, 'Casual'], [false, 'Tournament']], get: () => s.undo, set: (v) => { s.undo = v; } }, + { label: 'Card speed', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['brisk', 'Brisk']], get: () => s.anim, set: (v) => { s.anim = v; } }, + { label: 'Room sounds', options: [[true, 'On'], [false, 'Off']], get: () => s.ambience, set: (v) => { s.ambience = v; this.bed?.setOn(v); } }, + { label: 'Show leg & tour time', options: [[true, 'On'], [false, 'Off']], get: () => s.timer, set: (v) => { s.timer = v; if (!v) this.pl?.clock.setText(''); } }, + ], { title: 'Tour Settings', note: 'Casual allows Undo; Tournament doesn\'t. Records are kept separately for each, so the choice applies from your next tour.' }); + } + + // ── Saving ──────────────────────────────────────────────────────────────── + saveTour({ between = false } = {}) { + if (!this.gs) return; + const data = { + v: 1, tourIndex: this.tourIndex, total: this.total, results: this.results, tourMode: this.tourMode, + tourTime: Math.round(this.tourTime + (between ? 0 : this.elapsed)), bestRun: this.bestRun, + next: between ? this.tourIndex + 1 : this.tourIndex, + snap: between ? null : encode(this.gs.snapshot()), }; + try { localStorage.setItem(SAVE_KEY, JSON.stringify(data)); } catch { /* private mode */ } } - dragPromote() { - const pd = this.potentialDrag; - this.potentialDrag = null; - pd.sprites.forEach(({ obj }) => { - this.board.bringToTop(obj); - this.tweens.add({ targets: obj, scaleX: 1.05, scaleY: 1.05, duration: 90 }); - }); - this.dragState = pd; + loadSave() { + try { + const d = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!d || d.v !== 1 || d.next >= TOUR.length || !Array.isArray(d.results)) return null; + return d; + } catch { return null; } } - dragUpdate(pointer) { - for (const { obj, offX, offY } of this.dragState.sprites) { - obj.x = pointer.x + offX; - obj.y = pointer.y + offY; - } - const primary = this.dragState.sprites[0].obj; - this.highlightDrop(this.dragState.resolve(primary.x, primary.y)); + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch { /* ignore */ } } + + offerResume(save) { + const leg = TOUR[save.next]; + this.openModal({ w: 720, h: 400, onEscape: null }); + const top = CY - 200; + this.modalText(CX, top + 60, 'Welcome back', { fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex }); + this.modalText(CX, top + 130, `Your tour is waiting at hole ${save.next + 1} of 5 —\n${GAME_META[leg].name}, ${GAME_META[leg].place}.`, { fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, align: 'center', lineSpacing: 6 }); + this.modalText(CX, top + 200, `${save.total} point${save.total === 1 ? '' : 's'} so far · ${save.tourMode === 'casual' ? 'casual' : 'tournament'} rules`, { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex }); + const resume = () => this.resumeTour(save); + this.modalButton(CX - 140, top + 310, 'Resume tour', resume, { width: 250, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + this.modalButton(CX + 140, top + 310, 'New tour', () => this.startTour(), { width: 250, variant: 'ghost' }); + this.modal.onEnter = resume; } - highlightDrop(target) { - if (this.dropHighlight) { this.dropHighlight.destroy(); this.dropHighlight = null; } - if (!target) return; - this.dropHighlight = this.add.rectangle(target.pos.x, target.pos.y, CARD_W + 16, CARD_H + 16, target.color, 0.18) - .setStrokeStyle(3, target.color, 0.9).setDepth(D.card - 1); - } - - dragEnd() { - const ds = this.dragState; - this.dragState = null; - if (this.dropHighlight) { this.dropHighlight.destroy(); this.dropHighlight = null; } - - const primary = ds.sprites[0].obj; - const target = ds.resolve(primary.x, primary.y); - if (target && target.commit()) { this.sel = null; this.applyMove(true); return; } - // Rejected drop — slide the cards back where they came from. - ds.sprites.forEach(({ obj, homeX, homeY }) => { - this.tweens.add({ targets: obj, x: homeX, y: homeY, scaleX: 1, scaleY: 1, duration: 220, ease: 'Back.easeOut' }); - }); - } - - resolveDrop(descriptor, x, y) { - const z = this.dropZones.find((zone) => Math.abs(x - zone.cx) < zone.hw && Math.abs(y - zone.cy) < zone.hh); - if (!z) return null; - const pos = { x: z.hlx, y: z.hly }; - if (this.legType === 'threeshuffles') { - const commit = z.kind === 'foundation' - ? () => this.engine.playToFoundation(descriptor.pile) - : () => this.engine.moveTop(descriptor.pile, z.idx); - return { pos, color: z.kind === 'foundation' ? 0xffd700 : SEL, commit }; - } - const commit = z.kind === 'foundation' - ? () => this.kCommitFoundation(descriptor) - : () => this.kCommitColumn(descriptor, z.idx); - return { pos, color: z.kind === 'foundation' ? 0xffd700 : SEL, commit }; - } - - // Klondike drag helpers -------------------------------------------------------- - kDragSprites(descriptor) { - if (descriptor.kind === 'waste') { - const top = this.engine.waste[this.engine.waste.length - 1]; - const o = top && this.kSprites.get(top.id); - return o ? [o] : []; - } - const run = this.engine.faceUpRun(descriptor.col, descriptor.idx); - if (!run) return []; - return run.map((card) => this.kSprites.get(card.id)).filter(Boolean); - } - - kPointerDown(descriptor, pointer) { - this.beginDrag(this.kDragSprites(descriptor), pointer, - () => this.kTap(descriptor), (x, y) => this.resolveDrop(descriptor, x, y)); - } - - kCommitColumn(descriptor, destCol) { - if (descriptor.kind === 'waste') return this.engine.moveWasteToColumn(destCol); - return this.engine.moveRun(descriptor.col, descriptor.idx, destCol); - } - - kCommitFoundation(descriptor) { - const e = this.engine; - if (descriptor.kind === 'waste') return e.playWasteToFoundation(); - const run = e.faceUpRun(descriptor.col, descriptor.idx); - return run && run.length === 1 ? e.playColumnToFoundation(descriptor.col) : false; - } - - kTap(descriptor) { - if (descriptor.kind === 'waste') this.kWaste(); - else this.kCard(descriptor.col, descriptor.idx); - } - - // Three Shuffles and a Draw ---------------------------------------------------- - renderThreeShuffles() { - const e = this.engine; - this.kSprites.clear(); - this.dropZones = []; - const COLS = 6; - const rows = Math.max(3, Math.ceil(e.piles.length / COLS)); // grows if the Draw adds a pile - const rowStep = Math.min(265, Math.floor(720 / rows)); - const PILE_X = (col) => 380 + col * 200; - const rowYOf = (row) => 220 + row * rowStep; - const FAN = 20; - const FX = 1820; - const FY = [235, 400, 565, 730]; - const suits = ['s', 'h', 'd', 'c']; - const glyph = { s: '♠', h: '♥', d: '♦', c: '♣' }; - - this.board.add(this.add.text(FX, 150, 'Foundations', { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex }).setOrigin(0.5)); - suits.forEach((s, i) => { - const top = e.foundationTop(s); - if (top) this.card(top, FX, FY[i], { onClick: () => this.tsFoundation() }); - else this.slot(FX, FY[i], glyph[s], () => this.tsFoundation()); - this.dropZones.push({ cx: FX, cy: FY[i], hw: CARD_W * 0.7, hh: CARD_H * 0.8, hlx: FX, hly: FY[i], kind: 'foundation', idx: i }); - }); - - e.piles.forEach((pile, p) => { - const x = PILE_X(p % COLS); - const topY = rowYOf(Math.floor(p / COLS)); - pile.forEach((card, idx) => { - const isTop = idx === pile.length - 1; - const buriedDrawable = this.tsDrawMode && !isTop; - const cont = this.card(card, x, topY + idx * FAN, { - selected: isTop && this.sel?.kind === 'tspile' && this.sel.pile === p, - hint: buriedDrawable, - onDown: isTop && !this.tsDrawMode ? (_co, pointer) => this.tsPointerDown(p, pointer) : null, - onClick: buriedDrawable ? () => this.tsBuried(card.id) : null, - }); - this.kSprites.set(card.id, cont); - }); - const len = pile.length; - this.dropZones.push({ cx: x, cy: topY + (len * FAN) / 2, hw: CARD_W * 0.7, hh: (len * FAN) / 2 + CARD_H * 0.6, hlx: x, hly: topY + len * FAN, kind: 'pile', idx: p }); - }); - } - - tsPointerDown(pile, pointer) { - const top = this.engine.pileTop(pile); - const o = top && this.kSprites.get(top.id); - this.beginDrag(o ? [o] : [], pointer, - () => this.tsTap(pile), (x, y) => this.resolveDrop({ kind: 'ts', pile }, x, y)); - } - - tsTap(pile) { - if (!this.interactive() || this.tsDrawMode) return; - if (this.sel?.kind === 'tspile') { - const src = this.sel.pile; - if (src === pile) { this.sel = null; this.refresh(); return; } - if (this.engine.moveTop(src, pile)) { this.sel = null; this.applyMove(true); return; } - } - this.sel = { kind: 'tspile', pile }; - this.refresh(); - } - - tsFoundation() { - if (!this.interactive() || this.sel?.kind !== 'tspile') return; - const ok = this.engine.playToFoundation(this.sel.pile); - this.sel = null; - if (ok) this.applyMove(true); else this.refresh(); - } - - tsBuried(cardId) { - if (!this.interactive() || !this.tsDrawMode) return; - const ok = this.engine.drawCard(cardId); - this.tsDrawMode = false; - if (ok) this.applyMove(true, SFX.CARD_SHOW); else this.refresh(); - } - - onShuffle() { - if (!this.interactive() || this.legType !== 'threeshuffles') return; - this.sel = null; - this.tsDrawMode = false; - this.applyMove(this.engine.redeal(), SFX.CARD_SHUFFLE); - } - - // Pyramid ---------------------------------------------------------------------- - renderPyramid() { - const e = this.engine; - const dx = 104, dy = 64, topY = 176, cxx = 960; - for (let r = 0; r < 7; r++) { - for (let i = 0; i <= r; i++) { - const card = e.rows[r][i]; - if (!card) continue; - const x = cxx + (i - r / 2) * dx; - const y = topY + r * dy; - const avail = e.available(r, i); - const selected = this.sel?.area === 'pyramid' && this.sel.r === r && this.sel.i === i; - this.card(card, x, y, { - dim: !avail, - selected, - hint: avail && card.pval === 13, - onClick: avail ? () => this.pPick({ area: 'pyramid', r, i }) : null, - }); - } - } - // stock + waste - if (e.stock.length) this.card({}, 800, 840, { faceUp: false, onClick: () => this.pStock() }); - else this.slot(800, 840, e.passesLeft > 0 ? '↻ recycle' : 'empty', e.waste.length && e.passesLeft > 0 ? () => this.pStock() : null); - this.board.add(this.add.text(800, 924, `Stock ×${e.stock.length}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex }).setOrigin(0.5)); - - const wt = e.wasteTop(); - if (wt) this.card(wt, 960, 840, { selected: this.sel?.area === 'waste', hint: wt.pval === 13, onClick: () => this.pPick({ area: 'waste' }) }); - else this.slot(960, 840, 'waste'); - } - - pStock() { - if (!this.interactive()) return; - this.sel = null; - const e = this.engine; - if (!e.stock.length) { this.applyMove(e.dealStock(), SFX.CARD_SHUFFLE); return; } // recycle - const card = e.stock[e.stock.length - 1]; - e.dealStock(); - this.animateDraw(card, 800, 840, 960, 840); // stock → waste - } - - pPick(loc) { - if (!this.interactive()) return; - const e = this.engine; - const card = e.cardAt(loc); - if (!card) return; - if (card.pval === 13) { this.sel = null; this.applyMove(e.removeKing(loc)); return; } - if (this.sel) { - if (this.sameLoc(this.sel, loc)) { this.sel = null; this.refresh(); return; } - if (e.removePair(this.sel, loc)) { this.sel = null; this.applyMove(true); return; } - } - this.sel = loc; - this.refresh(); - } - - sameLoc(a, b) { return a.area === b.area && (a.area === 'waste' || (a.r === b.r && a.i === b.i)); } - - // Take Fourteen ---------------------------------------------------------------- - renderFourteen() { - const e = this.engine; - const fan = 26; - for (let p = 0; p < 12; p++) { - const x = 585 + (p % 6) * 150; - const topY = p < 6 ? 250 : 560; - const pile = e.piles[p]; - if (!pile.length) { this.slot(x, topY, ''); continue; } - pile.forEach((card, idx) => { - const isTop = idx === pile.length - 1; - this.card(card, x, topY + idx * fan, { - selected: isTop && this.sel === p, - onClick: isTop ? () => this.fPick(p) : null, - }); - }); - } - } - - fPick(p) { - if (!this.interactive()) return; - const e = this.engine; - if (this.sel != null) { - if (this.sel === p) { this.sel = null; this.refresh(); return; } - if (e.removePair(this.sel, p)) { this.sel = null; this.applyMove(true); return; } - } - this.sel = p; - this.refresh(); + resumeTour(save) { + this.closeModal(); + this.tourIndex = save.next; + this.total = save.total; + this.results = save.results; + this.tourMode = save.tourMode === 'tournament' ? 'tournament' : 'casual'; + this.tourTime = save.tourTime ?? 0; + this.bestRun = save.bestRun ?? 0; + let engine = null; + if (save.snap) { try { engine = engineFromSave(TOUR[save.next], save.snap); } catch { engine = null; } } + this.startLeg(engine); } } diff --git a/src/games/solitairetour/SolitaireTourLegs.js b/src/games/solitairetour/SolitaireTourLegs.js new file mode 100644 index 0000000..2cd25ad --- /dev/null +++ b/src/games/solitairetour/SolitaireTourLegs.js @@ -0,0 +1,496 @@ +// Solitaire Tour — one controller per game, Phaser-free (the scene delegates to +// these; tools/verifySolitaireTour.js tests them directly). +// +// A leg turns its engine into things the shared solitaire scene understands: +// layout() → Map(id → { card, pose, faceUp, depth }) +// pickAt(pt, ui) → src { key, kind, ids, tapMove?, … } — what a press there grabs +// movesFor(src) → [{ move, kind, anchor, zone, score }] drop targets / click choices +// tapEmpty(pt) → a move for a press on an empty stock, or null +// autoMove(opts) → a move to play by itself (safe cards home / foregone finish), or null +// grabBlocker / dropBlocker / noMoveReason → short reasons when something can't happen +// slots() → [{ pose, label }] empty-pile outlines to draw on the table +// status() → lines for the leg plate +// Pair games (Pyramid, Take Fourteen) also expose partnersOf(src) / isKing(src). + +import { SUITS } from '../cards/Deck.js'; +import { columnPoses, stackPose, inPose, poseRect, inRect } from '../../ui/solitaire/SolitaireGeometry.js'; +import { GOLF, KLON, PYR, FOUR, THREE, MAX_BOTTOM } from './SolitaireTourTable.js'; + +export const CARD_DEPTH = 10; +const SYM = { s: '♠', h: '♥', d: '♦', c: '♣' }; +const SUIT_NAME = { s: 'spades', h: 'hearts', d: 'diamonds', c: 'clubs' }; +const RANK = { 1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King' }; +const rankName = (v) => RANK[v] ?? String(v); +const short = (c) => `${c.label}${SYM[c.suit]}`; +const isRed = (c) => c.suit === 'h' || c.suit === 'd'; + +class Leg { + constructor(engine) { this.e = engine; } + put(map, card, pose, depth, faceUp = true) { map.set(card.id, { card, pose, faceUp, depth }); } + /** Top-most pickable whose card contains pt. */ + pickAt(pt, ui = {}) { + const list = this.pickables(ui); + let best = null; + for (const p of list) if (inPose(pt, p.pose, 2) && (!best || p.depth >= best.depth)) best = p; + return best?.src ?? null; + } + tapEmpty() { return null; } + autoMove() { return null; } + grabBlocker() { return null; } + dropBlocker() { return null; } + noMoveReason() { return 'No move for that card right now'; } + slots() { return []; } + status() { return []; } + dimmed() { return false; } + playableIds() { return new Set(); } +} + +// ── Golf ───────────────────────────────────────────────────────────────────── +export class GolfLeg extends Leg { + colPoses(c, n) { return columnPoses(n, null, { x: GOLF.colX(c), top: GOLF.TOP, s: GOLF.S, step: GOLF.STEP }); } + + foundPose(k, n) { + const j = Math.max(0, k - (n - GOLF.SHOW)); + return { ...GOLF.FOUND, x: GOLF.FOUND.x + j * GOLF.FAN }; + } + + layout() { + const m = new Map(), e = this.e; + e.tableau.forEach((pile, c) => { + const ps = this.colPoses(c, pile.length); + pile.forEach((card, k) => this.put(m, card, ps[k], CARD_DEPTH + 1 + k * 0.02)); + }); + e.stock.forEach((card, k) => this.put(m, card, stackPose(GOLF.STOCK, k, e.stock.length, 0.28, 5), CARD_DEPTH + k * 0.01, false)); + const n = e.foundation.length; + e.foundation.forEach((card, k) => this.put(m, card, this.foundPose(k, n), CARD_DEPTH + 2 + k * 0.01)); + return m; + } + + pickables() { + const e = this.e, out = []; + e.tableau.forEach((pile, c) => { + if (!pile.length) return; + const k = pile.length - 1; + out.push({ pose: this.colPoses(c, pile.length)[k], depth: 1 + k * 0.02, src: { key: `g${c}`, kind: 'gcol', col: c, ids: [pile[k].id] } }); + }); + if (e.stock.length) { + const top = e.stock[e.stock.length - 1]; + out.push({ pose: stackPose(GOLF.STOCK, e.stock.length - 1, e.stock.length, 0.28, 5), depth: 0.5, src: { key: 'gstock', kind: 'stock', ids: [top.id], tapMove: { t: 'gstock' } } }); + } + return out; + } + + foundRect() { + const n = this.e.foundation.length; + const a = poseRect(this.foundPose(0, n), 24), b = poseRect(this.foundPose(n - 1, n), 24); + return { x0: a.x0, x1: b.x1, y0: a.y0, y1: a.y1 }; + } + + movesFor(src) { + if (src.kind !== 'gcol') return []; + const pile = this.e.tableau[src.col]; + const card = pile[pile.length - 1]; + if (!this.e.canPlay(card)) return []; + const n = this.e.foundation.length + 1; + return [{ move: { t: 'gplay', col: src.col }, kind: 'found', anchor: this.foundPose(n - 1, n), zone: this.foundRect(), score: 100 }]; + } + + noMoveReason(src) { + if (src.kind !== 'gcol') return null; + const top = this.e.foundationTop(); + const lo = top.pval - 1, hi = top.pval + 1; + const want = [lo >= 1 ? rankName(lo) : null, hi <= 13 ? rankName(hi) : null].filter(Boolean).join(' or '); + return `The foundation needs a ${want}`; + } + + dropBlocker(src, pt) { return inRect(pt, this.foundRect()) ? this.noMoveReason(src) : null; } + + playableIds() { + const s = new Set(); + for (const p of this.e.tableau) if (p.length && this.e.canPlay(p[p.length - 1])) s.add(p[p.length - 1].id); + return s; + } + + slots() { return [{ pose: GOLF.STOCK, label: 'STOCK' }, { pose: GOLF.FOUND, label: 'FOUNDATION' }]; } + + status() { + const e = this.e; + return [`Stock: ${e.stock.length} card${e.stock.length === 1 ? '' : 's'}`, `Current run: ${e.run}`]; + } +} + +// ── Klondike ───────────────────────────────────────────────────────────────── +export class KlondikeLeg extends Leg { + colPoses(c) { + const pile = this.e.tableau[c]; + return columnPoses(pile.length, pile.map(x => x.faceUp), { x: KLON.colX(c), top: KLON.TOP, s: KLON.S, maxBottom: MAX_BOTTOM, step: KLON.STEP, downStep: KLON.DOWN, minStep: 18, minDown: 6 }); + } + colAnchor(c, extra) { + const pile = this.e.tableau[c]; + const ups = [...pile.map(x => x.faceUp), ...Array(extra).fill(true)]; + return columnPoses(ups.length, ups, { x: KLON.colX(c), top: KLON.TOP, s: KLON.S, maxBottom: MAX_BOTTOM, step: KLON.STEP, downStep: KLON.DOWN, minStep: 18, minDown: 6 })[pile.length]; + } + wastePose(k, n) { return { ...KLON.WASTE, x: KLON.WASTE.x + Math.max(0, k - (n - 3)) * KLON.WASTE_FAN }; } + + layout() { + const m = new Map(), e = this.e; + e.stock.forEach((card, k) => this.put(m, card, stackPose(KLON.STOCK, k, e.stock.length, 0.25, 5), CARD_DEPTH + k * 0.01, false)); + e.waste.forEach((card, k) => this.put(m, card, this.wastePose(k, e.waste.length), CARD_DEPTH + k * 0.01)); + SUITS.forEach((s, i) => e.foundations[s].forEach((card, k) => this.put(m, card, stackPose(KLON.found(i), k, 13, 0.2, 3), CARD_DEPTH + k * 0.01))); + e.tableau.forEach((pile, c) => { + const ps = this.colPoses(c); + pile.forEach((x, k) => this.put(m, x.card, ps[k], CARD_DEPTH + 1 + k * 0.02, x.faceUp)); + }); + return m; + } + + pickables() { + const e = this.e, out = []; + if (e.stock.length) { + const top = e.stock[e.stock.length - 1]; + out.push({ pose: stackPose(KLON.STOCK, e.stock.length - 1, e.stock.length, 0.25, 5), depth: 0.5, src: { key: 'kstock', kind: 'stock', ids: [top.id], tapMove: { t: 'kstock' } } }); + } + const w = e.wasteTop(); + if (w) out.push({ pose: this.wastePose(e.waste.length - 1, e.waste.length), depth: 0.6, src: { key: 'kwaste', kind: 'kwaste', ids: [w.id] } }); + e.tableau.forEach((pile, c) => { + const ps = this.colPoses(c); + pile.forEach((x, k) => { + if (!x.faceUp) return; + out.push({ pose: ps[k], depth: 1 + k * 0.02, src: { key: `k${c}:${k}`, kind: 'krun', col: c, idx: k, ids: pile.slice(k).map(y => y.card.id) } }); + }); + }); + return out; + } + + tapEmpty(pt) { + const e = this.e; + if (!e.stock.length && inPose(pt, KLON.STOCK, 8) && e.waste.length && e.recyclesLeft > 0) return { t: 'kstock' }; + return null; + } + + headOf(src) { return src.kind === 'kwaste' ? this.e.wasteTop() : this.e.tableau[src.col][src.idx]?.card; } + + movesFor(src) { + const e = this.e, out = []; + if (src.kind !== 'kwaste' && src.kind !== 'krun') return out; + const head = this.headOf(src); + if (!head) return out; + if (src.kind === 'krun' && !e.faceUpRun(src.col, src.idx)) return out; + const single = src.kind === 'kwaste' || src.idx === e.tableau[src.col].length - 1; + if (single && e.canPlayFoundation(head)) { + const i = SUITS.indexOf(head.suit); + out.push({ move: src.kind === 'kwaste' ? { t: 'kwf' } : { t: 'kcf', col: src.col }, kind: 'found', anchor: stackPose(KLON.found(i), e.foundations[head.suit].length, 13, 0.2, 3), zone: poseRect(KLON.found(i), 22), score: 100 }); + } + const n = src.kind === 'kwaste' ? 1 : e.tableau[src.col].length - src.idx; + const reveals = src.kind === 'krun' && src.idx > 0 && !e.tableau[src.col][src.idx - 1].faceUp; + for (let d = 0; d < 7; d++) { + if (src.kind === 'krun' && d === src.col) continue; + if (!e.canStack(head, d)) continue; + const empty = !e.tableau[d].length; + if (empty && src.kind === 'krun' && src.idx === 0) continue; // a King already at the base: pointless + const move = src.kind === 'kwaste' ? { t: 'kwc', to: d } : { t: 'krun', col: src.col, idx: src.idx, to: d }; + const score = (empty ? 30 : 60) + (reveals ? 15 : 0) + (src.kind === 'kwaste' ? -4 : 0) - d * 0.01; + out.push({ move, kind: 'col', anchor: this.colAnchor(d, n), zone: this.colZone(d), score }); + } + return out; + } + + colZone(d) { + const x = KLON.colX(d), hw = (96 * KLON.S) / 2 + 16; + return { x0: x - hw, x1: x + hw, y0: KLON.TOP - 90, y1: MAX_BOTTOM + 10 }; + } + + grabBlocker(src) { + if (src.kind === 'krun' && !this.e.faceUpRun(src.col, src.idx)) return 'Only an ordered run moves together'; + return null; + } + + noMoveReason(src) { + const head = this.headOf(src); + if (!head) return null; + if (head.pval === 13) return 'A King needs an empty column'; + return `Needs a ${isRed(head) ? 'black' : 'red'} ${rankName(head.pval + 1)}`; + } + + dropBlocker(src, pt) { + const e = this.e, head = this.headOf(src); + if (!head) return null; + for (let i = 0; i < 4; i++) { + if (!inRect(pt, poseRect(KLON.found(i), 22))) continue; + if (src.kind === 'krun' && src.idx !== e.tableau[src.col].length - 1) return 'One card at a time to the foundations'; + const suit = SUITS[i]; + if (head.suit !== suit) return `That's the ${SUIT_NAME[suit]} foundation`; + return `The ${SUIT_NAME[suit]} need the ${rankName((e.foundationTop(suit)?.pval ?? 0) + 1)} next`; + } + for (let d = 0; d < 7; d++) { + if (!inRect(pt, this.colZone(d)) || (src.kind === 'krun' && d === src.col)) continue; + if (!e.tableau[d].length) return head.pval === 13 ? null : 'Only a King fills an empty column'; + return `${short(head)} goes on a ${isRed(head) ? 'black' : 'red'} ${rankName(head.pval + 1)}`; + } + return null; + } + + autoMove({ autoPlay = true } = {}) { + const e = this.e; + if (e.canAutoFinish()) return { ...e.homeMove(), fast: true }; + if (!autoPlay) return null; + const m = e.homeMove({ safeOnly: true }); + return m ? { ...m, fast: true } : null; + } + + slots() { + return [ + { pose: KLON.STOCK, label: 'STOCK' }, { pose: KLON.WASTE, label: '' }, + ...SUITS.map((s, i) => ({ pose: KLON.found(i), label: '', suit: s })), + ...Array.from({ length: 7 }, (_, c) => ({ pose: { ...KLON.WASTE, x: KLON.colX(c), y: KLON.TOP }, label: 'K' })), + ]; + } + + status() { + const e = this.e; + const home = SUITS.reduce((t, s) => t + e.foundations[s].length, 0); + return [`Stock: ${e.stock.length} · Waste: ${e.waste.length}`, `${home} of 52 cards home`, e.stock.length ? 'Click the stock to turn a card' : (e.waste.length ? 'Click the empty stock to turn the waste over' : '')]; + } +} + +// ── Pyramid ────────────────────────────────────────────────────────────────── +export class PyramidLeg extends Leg { + get isPairLeg() { return true; } + + layout() { + const m = new Map(), e = this.e; + for (let r = 0; r < 7; r++) for (let i = 0; i <= r; i++) { + const c = e.rows[r][i]; + if (c) this.put(m, c, PYR.pos(r, i), CARD_DEPTH + 1 + r * 0.1 + i * 0.001); + } + e.stock.forEach((card, k) => this.put(m, card, stackPose(PYR.STOCK, k, e.stock.length, 0.25, 5), CARD_DEPTH + k * 0.01, false)); + e.waste.forEach((card, k) => this.put(m, card, stackPose(PYR.WASTE, k, e.waste.length, 0.12, 3), CARD_DEPTH + k * 0.01)); + e.discard.forEach((card, k) => this.put(m, card, { ...stackPose(PYR.DISCARD, k, e.discard.length, 0.12, 4), rot: ((k * 37) % 11 - 5) * 0.012 }, CARD_DEPTH + k * 0.01)); + return m; + } + + locPose(loc) { return loc.area === 'waste' ? stackPose(PYR.WASTE, this.e.waste.length - 1, this.e.waste.length, 0.12, 3) : PYR.pos(loc.r, loc.i); } + + pickables() { + const e = this.e, out = []; + for (const loc of e.availableLocs()) { + const c = e.cardAt(loc); + out.push({ pose: this.locPose(loc), depth: loc.area === 'waste' ? 0.6 : 1 + loc.r * 0.1 + loc.i * 0.001, src: { key: loc.area === 'waste' ? 'pw' : `p${loc.r}:${loc.i}`, kind: 'ploc', loc, ids: [c.id] } }); + } + if (e.stock.length) { + const top = e.stock[e.stock.length - 1]; + out.push({ pose: stackPose(PYR.STOCK, e.stock.length - 1, e.stock.length, 0.25, 5), depth: 0.5, src: { key: 'pstock', kind: 'stock', ids: [top.id], tapMove: { t: 'pstock' } } }); + } + return out; + } + + tapEmpty(pt) { + const e = this.e; + if (!e.stock.length && inPose(pt, PYR.STOCK, 8) && e.waste.length && e.passesLeft > 0) return { t: 'pstock' }; + return null; + } + + isKing(src) { return src.kind === 'ploc' && this.e.cardAt(src.loc)?.pval === 13; } + partnersOf(src) { return src.kind === 'ploc' ? this.e.partnersOf(src.loc) : []; } + partnerIds(src) { return this.partnersOf(src).map(l => this.e.cardAt(l).id); } + srcFor(loc) { return { key: loc.area === 'waste' ? 'pw' : `p${loc.r}:${loc.i}`, kind: 'ploc', loc, ids: [this.e.cardAt(loc).id] }; } + + movesFor(src) { + if (src.kind !== 'ploc') return []; + if (this.isKing(src)) return [{ move: { t: 'pking', loc: src.loc }, kind: 'found', anchor: PYR.DISCARD, zone: poseRect(PYR.DISCARD, 26), score: 100 }]; + return this.partnersOf(src).map(l => ({ move: { t: 'ppair', a: src.loc, b: l }, kind: 'pair', anchor: this.locPose(l), zone: poseRect(this.locPose(l), 8), score: 50 })); + } + + noMoveReason(src) { + const c = this.e.cardAt(src.loc); + return c ? `Needs a ${rankName(13 - c.pval)} to make 13` : null; + } + + dimmed(id) { + const e = this.e; + for (let r = 0; r < 7; r++) for (let i = 0; i <= r; i++) if (e.rows[r][i]?.id === id) return !e.available(r, i); + return false; + } + + slots() { return [{ pose: PYR.STOCK, label: 'STOCK' }, { pose: PYR.WASTE, label: 'WASTE' }, { pose: PYR.DISCARD, label: 'CLEARED' }]; } + + status() { + const e = this.e; + const left = e.rows.flat().filter(Boolean).length; + return [`Stock: ${e.stock.length} · Passes left: ${e.passesLeft}`, `${left} of 28 pyramid cards left`, 'Pairs make 13: A+Q, 2+J, 3+10 … K alone']; + } +} + +// ── Take Fourteen ──────────────────────────────────────────────────────────── +export class FourteenLeg extends Leg { + get isPairLeg() { return true; } + pilePoses(p, n) { return columnPoses(n, null, { x: FOUR.pileX(p), top: FOUR.pileTop(p), s: FOUR.S, step: FOUR.STEP }); } + topPose(p) { const n = this.e.piles[p].length; return this.pilePoses(p, n)[n - 1]; } + + layout() { + const m = new Map(), e = this.e; + e.piles.forEach((pile, p) => { + const ps = this.pilePoses(p, pile.length); + pile.forEach((card, k) => this.put(m, card, ps[k], CARD_DEPTH + 1 + k * 0.02)); + }); + e.discard.forEach((card, k) => this.put(m, card, { ...stackPose(FOUR.DISCARD, k, e.discard.length, 0.12, 4), rot: ((k * 37) % 11 - 5) * 0.012 }, CARD_DEPTH + k * 0.01)); + return m; + } + + pickables() { + const out = []; + this.e.piles.forEach((pile, p) => { + if (!pile.length) return; + out.push({ pose: this.topPose(p), depth: 1, src: { key: `f${p}`, kind: 'fpile', p, ids: [pile[pile.length - 1].id] } }); + }); + return out; + } + + isKing() { return false; } + partnersOf(src) { return src.kind === 'fpile' ? this.e.partnersOf(src.p) : []; } + partnerIds(src) { return this.partnersOf(src).map(q => this.e.top(q).id); } + srcFor(p) { return { key: `f${p}`, kind: 'fpile', p, ids: [this.e.top(p).id] }; } + + movesFor(src) { + if (src.kind !== 'fpile') return []; + return this.partnersOf(src).map(q => ({ move: { t: 'fpair', a: src.p, b: q }, kind: 'pair', anchor: this.topPose(q), zone: poseRect(this.topPose(q), 8), score: 50 })); + } + + noMoveReason(src) { + const c = this.e.top(src.p); + return c ? `Needs a ${rankName(14 - c.pval)} to make 14` : null; + } + + slots() { + return [ + ...Array.from({ length: 12 }, (_, p) => ({ pose: { x: FOUR.pileX(p), y: FOUR.pileTop(p), rot: 0, s: FOUR.S, q: 1 }, label: '' })), + { pose: FOUR.DISCARD, label: 'CLEARED' }, + ]; + } + + status() { + const e = this.e; + const left = e.piles.reduce((t, p) => t + p.length, 0); + return [`${left} cards left in ${e.piles.filter(p => p.length).length} piles`, `Pairs available: ${e.legalMoves().length}`, 'Pairs make 14: A+K, 2+Q, 3+J … 7+7']; + } +} + +// ── Three Shuffles and a Draw ──────────────────────────────────────────────── +export class ThreeShufflesLeg extends Leg { + layout() { + const m = new Map(), e = this.e; + SUITS.forEach((s, i) => e.foundations[s].forEach((card, k) => this.put(m, card, stackPose(THREE.found(i), k, 13, 0.2, 3), CARD_DEPTH + k * 0.01))); + e.piles.forEach((pile, p) => pile.forEach((card, k) => this.put(m, card, THREE.fanPose(p, k, pile.length), CARD_DEPTH + 1 + k * 0.02))); + return m; + } + + pickables({ drawMode = false } = {}) { + const e = this.e, out = []; + e.piles.forEach((pile, p) => { + pile.forEach((card, k) => { + const top = k === pile.length - 1; + if (drawMode ? top : !top) return; + const src = drawMode + ? { key: `td${card.id}`, kind: 'buried', ids: [card.id], tapMove: { t: 'tdraw', id: card.id } } + : { key: `t${p}`, kind: 'tpile', p, ids: [card.id] }; + out.push({ pose: THREE.fanPose(p, k, pile.length), depth: 1 + k * 0.02, src }); + }); + }); + return out; + } + + movesFor(src) { + const e = this.e, out = []; + if (src.kind !== 'tpile') return out; + const c = e.pileTop(src.p); + if (!c) return out; + if (e.canPlayFoundation(c)) { + const i = SUITS.indexOf(c.suit); + out.push({ move: { t: 'tfound', p: src.p }, kind: 'found', anchor: stackPose(THREE.found(i), e.foundations[c.suit].length, 13, 0.2, 3), zone: poseRect(THREE.found(i), 22), score: 100 }); + } + e.piles.forEach((pile, d) => { + if (d === src.p || !e.canStack(c, d)) return; + const n = pile.length + 1; + const anchor = THREE.fanPose(d, n - 1, n); + out.push({ move: { t: 'tmove', p: src.p, to: d }, kind: 'col', anchor, zone: this.fanZone(d), score: 60 - d * 0.01 }); + }); + return out; + } + + fanZone(d) { + const c = THREE.fanCentre(d); + return { x0: c.x - 92, x1: c.x + 92, y0: c.y - 72, y1: c.y + 72 }; + } + + noMoveReason(src) { + const c = this.e.pileTop(src.p); + if (!c) return null; + if (c.pval === 13) return `The K${SYM[c.suit]} goes home after the Q${SYM[c.suit]}`; + return `Builds on the ${rankName(c.pval + 1)}${SYM[c.suit]}, or goes home after the ${rankName(c.pval - 1)}${SYM[c.suit]}`; + } + + dropBlocker(src, pt) { + const e = this.e, c = e.pileTop(src.p); + if (!c) return null; + for (let i = 0; i < 4; i++) { + if (!inRect(pt, poseRect(THREE.found(i), 22))) continue; + const suit = SUITS[i]; + if (c.suit !== suit) return `That's the ${SUIT_NAME[suit]} foundation`; + return `The ${SUIT_NAME[suit]} need the ${rankName((e.foundationTop(suit)?.pval ?? 0) + 1)} next`; + } + for (let d = 0; d < e.piles.length; d++) { + if (d === src.p || !inRect(pt, this.fanZone(d))) continue; + if (!e.piles[d].length) return 'Empty spaces stay empty'; + return `Builds down in suit — ${short(c)} goes on the ${rankName(c.pval + 1)}${SYM[c.suit]}`; + } + return null; + } + + autoMove({ autoPlay = true } = {}) { + const e = this.e; + if (!autoPlay && !e.canAutoFinish()) return null; + const m = e.homeMove(); + return m ? { ...m, fast: true } : null; + } + + slots() { return SUITS.map((s, i) => ({ pose: THREE.found(i), label: '', suit: s })); } + + status() { + const e = this.e; + const home = SUITS.reduce((t, s) => t + e.foundations[s].length, 0); + return [`Shuffles left: ${e.shufflesLeft} · Draw: ${e.drawsLeft}`, `${home} of 52 cards home`, e.shufflesLeft ? 'Stuck? Shuffle gathers and redeals the fans' : (e.canDraw() ? 'Draw lifts one buried card free' : '')]; + } +} + +/** Cards still on the table (these are what score). */ +export function remainingCards(e) { + switch (e.type) { + case 'golf': return [...e.tableau.flat(), ...e.stock]; + case 'klondike': return [...e.tableau.flat().map(x => x.card), ...e.stock, ...e.waste]; + case 'pyramid': return [...e.rows.flat().filter(Boolean), ...e.stock, ...e.waste]; + case 'fourteen': return e.piles.flat(); + default: return e.piles.flat(); + } +} + +/** Where the cleared cards sit — the win cascade launches from these. */ +export function homeStacks(e) { + switch (e.type) { + case 'golf': return [{ cards: e.foundation.slice(), pose: GOLF.FOUND }]; + case 'klondike': return SUITS.map((s, i) => ({ cards: e.foundations[s].slice(), pose: KLON.found(i) })); + case 'pyramid': return [{ cards: e.discard.slice(), pose: PYR.DISCARD }]; + case 'fourteen': return [{ cards: e.discard.slice(), pose: FOUR.DISCARD }]; + default: return SUITS.map((s, i) => ({ cards: e.foundations[s].slice(), pose: THREE.found(i) })); + } +} + +export function legFor(engine) { + switch (engine.type) { + case 'golf': return new GolfLeg(engine); + case 'klondike': return new KlondikeLeg(engine); + case 'pyramid': return new PyramidLeg(engine); + case 'fourteen': return new FourteenLeg(engine); + case 'threeshuffles': return new ThreeShufflesLeg(engine); + default: throw new Error(`No leg for ${engine.type}`); + } +} diff --git a/src/games/solitairetour/SolitaireTourLogic.js b/src/games/solitairetour/SolitaireTourLogic.js index 3924c40..9531944 100644 --- a/src/games/solitairetour/SolitaireTourLogic.js +++ b/src/games/solitairetour/SolitaireTourLogic.js @@ -1,125 +1,188 @@ -// Solitaire Tour — pure game logic for the five-game tour. +// Solitaire Tour — pure game logic for the five-game tour (Phaser-free; +// tools/verifySolitaireTour.js tests it). // -// Each of the five solitaires is a self-contained engine exposing a common -// surface the scene relies on: -// • mutation methods that return true when they changed state -// • hasMoves() → false when the player is stuck (drives the -// "No More Moves" prompt) -// • remainingValue() → sum of the point value of every card NOT yet cleared -// (this is what gets added to the tour score) -// • isWon() → true when every card has been cleared +// Each of the five solitaires is a self-contained engine with a common surface: +// apply(move) → the cards the move touched ([] when it was illegal) +// legalMoves() → every move available now +// hasMoves() → false when the player is stuck ("bank it" time) +// remainingValue() → points still on the table (added to the tour score) +// isWon() → every card cleared +// snapshot()/restore(s), allCards(), moveCount +// +// Moves are plain objects tagged by `t`: +// Golf { t: 'gplay', col } · { t: 'gstock' } +// Klondike { t: 'kstock' } (draw, or recycle the waste) · { t: 'kwf' } waste → home +// { t: 'kcf', col } column → home · { t: 'kwc', to } waste → column +// { t: 'krun', col, idx, to } column run → column +// Pyramid { t: 'pking', loc } · { t: 'ppair', a, b } · { t: 'pstock' } +// (loc = { area: 'pyramid', r, i } | { area: 'waste' }) +// Take Fourteen { t: 'fpair', a, b } (pile indexes) +// Three Shuffles{ t: 'tfound', p } · { t: 'tmove', p, to } · { t: 'tredeal' } · { t: 'tdraw', id } // // Card point values are A=1 … 10=10, J=11, Q=12, K=13 — the same scale Pyramid // and Take Fourteen use for their pairing rules, applied everywhere for scoring. import { Card, SUITS, RANKS } from '../cards/Deck.js'; -// A=1 … K=13 (RANKS is ['2'…'A']; 'T' is the ten). const PVAL = { A: 1, T: 10, J: 11, Q: 12, K: 13 }; for (let n = 2; n <= 9; n++) PVAL[String(n)] = n; -/** Build a shuffled 52-card deck; every card carries a stable id + pval (1–13). */ -export function freshDeck() { - const cards = []; - let id = 0; - for (const suit of SUITS) { - for (const rank of RANKS) { - const c = new Card(rank, suit); - c.id = id++; - c.pval = PVAL[rank]; - cards.push(c); - } - } +// ── Cards ──────────────────────────────────────────────────────────────────── +// Ids are fixed per card (suit-major, RANKS order), so saves can store ids. +const CANON = []; +for (const suit of SUITS) for (const rank of RANKS) { + const c = new Card(rank, suit); + c.id = CANON.length; + c.pval = PVAL[rank]; + CANON.push(c); +} +export const cardById = (id) => CANON[id]; + +/** A shuffled 52-card deck (shared Card objects; rng defaults to Math.random). */ +export function freshDeck(rng = Math.random) { + const cards = CANON.slice(); for (let i = cards.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)); + const j = Math.floor(rng() * (i + 1)); [cards[i], cards[j]] = [cards[j], cards[i]]; } return cards; } const sumVal = (cards) => cards.reduce((t, c) => t + c.pval, 0); +const isRed = (c) => c.suit === 'h' || c.suit === 'd'; +const copyFound = (f) => Object.fromEntries(SUITS.map(s => [s, f[s].slice()])); + +/** Snapshot ↔ JSON: Card objects become { $c: id }. */ +export function encode(v) { + if (v instanceof Card) return { $c: v.id }; + if (Array.isArray(v)) return v.map(encode); + if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, encode(x)])); + return v; +} +export function decode(v) { + if (Array.isArray(v)) return v.map(decode); + if (v && typeof v === 'object') { + if ('$c' in v) return cardById(v.$c); + return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, decode(x)])); + } + return v; +} // The five legs of the tour, in play order. export const TOUR = ['golf', 'klondike', 'pyramid', 'fourteen', 'threeshuffles']; export const GAME_META = { - golf: { name: 'Golf', blurb: 'Clear the tableau onto the foundation, one rank up or down. No wrapping (Aces are low).' }, - klondike: { name: 'Klondike', blurb: 'Build the four foundations up by suit from Ace. Stack the tableau down in alternating colours.' }, - pyramid: { name: 'Pyramid', blurb: 'Remove pairs of exposed cards that total 13. Kings clear on their own.' }, - fourteen: { name: 'Take Fourteen', blurb: 'Remove pairs of available cards that total 14 until every pile is empty.' }, - threeshuffles: { name: 'Three Shuffles and a Draw', blurb: 'Foundations up by suit from Ace. Tableau piles build down in suit; only the top card plays and empty spaces stay empty. Shuffle twice, then take one Draw to free a buried card.' }, + golf: { + name: 'Golf', venue: 'The Old Links Clubhouse', place: 'the Scottish links', greet: 'Greetings from the Links!', + blurb: 'Play a column\'s top card onto the foundation if it is one rank higher or lower. Aces are low — no wrapping round. Stuck? Turn the next stock card.', + }, + klondike: { + name: 'Klondike', venue: 'A Gold-Rush Cabin', place: 'the Yukon', greet: 'Greetings from the Yukon!', + blurb: 'Build the four foundations up by suit from Ace. Stack the columns down in alternating colours; only a King fills an empty column. Turn stock cards one at a time.', + }, + pyramid: { + name: 'Pyramid', venue: 'The Terrace at Giza', place: 'Cairo', greet: 'Greetings from Cairo!', + blurb: 'Remove pairs of uncovered cards that total 13 — the waste card counts. Kings clear on their own. Three passes through the stock.', + }, + fourteen: { + name: 'Take Fourteen', venue: 'The Riverboat Salon', place: 'the Mississippi', greet: 'Greetings from the River!', + blurb: 'Remove pairs of top cards that total 14 (Ace + King, 2 + Queen, 7 + 7…) until every pile is gone.', + }, + threeshuffles: { + name: 'Three Shuffles and a Draw', venue: 'Café de la Belle Lucie', place: 'Paris', greet: 'Greetings from Paris!', + blurb: 'Foundations build up by suit from Ace. Fans build down in suit; only the top card plays and empty spaces stay empty. Two reshuffles, then one Draw frees a buried card.', + }, }; -// ── Golf ─────────────────────────────────────────────────────────────────────── +// ── Golf ───────────────────────────────────────────────────────────────────── export class GolfEngine { constructor(deck) { this.type = 'golf'; this.tableau = Array.from({ length: 7 }, () => []); let k = 0; - for (let row = 0; row < 5; row++) { - for (let col = 0; col < 7; col++) this.tableau[col].push(deck[k++]); - } + for (let row = 0; row < 5; row++) for (let col = 0; col < 7; col++) this.tableau[col].push(deck[k++]); this.foundation = [deck[k++]]; // one card seeded face-up - this.stock = deck.slice(k); // remaining 16 + this.stock = deck.slice(k); // the remaining 16 + this.run = 0; // consecutive plays from the columns (flavour only) + this.moveCount = 0; } + snapshot() { return { tableau: this.tableau.map(p => p.slice()), foundation: this.foundation.slice(), stock: this.stock.slice(), run: this.run, moveCount: this.moveCount }; } + restore(s) { this.tableau = s.tableau.map(p => p.slice()); this.foundation = s.foundation.slice(); this.stock = s.stock.slice(); this.run = s.run ?? 0; this.moveCount = s.moveCount ?? 0; } + allCards() { return [...this.tableau.flat(), ...this.foundation, ...this.stock]; } + foundationTop() { return this.foundation[this.foundation.length - 1] ?? null; } - /** Classic Golf: play onto the foundation if exactly one rank away, no wrap. */ + /** Classic Golf: one rank away from the foundation card, no wrap. */ canPlay(card) { const top = this.foundationTop(); - return !!top && Math.abs(card.pval - top.pval) === 1; + return !!card && !!top && Math.abs(card.pval - top.pval) === 1; } - playColumn(col) { - const pile = this.tableau[col]; - const card = pile[pile.length - 1]; - if (!card || !this.canPlay(card)) return false; - this.foundation.push(pile.pop()); - return true; + playColumn(col) { return this.apply({ t: 'gplay', col }).length > 0; } + dealStock() { return this.apply({ t: 'gstock' }).length > 0; } + + apply(m) { + if (m.t === 'gplay') { + const pile = this.tableau[m.col]; + const card = pile?.[pile.length - 1]; + if (!card || !this.canPlay(card)) return []; + this.foundation.push(pile.pop()); + this.run++; + } else if (m.t === 'gstock') { + if (!this.stock.length) return []; + this.foundation.push(this.stock.pop()); + this.run = 0; + } else return []; + this.moveCount++; + return [this.foundationTop()]; } - dealStock() { - if (!this.stock.length) return false; - this.foundation.push(this.stock.pop()); - return true; - } - - hasMoves() { - if (this.stock.length) return true; - return this.tableau.some((p) => p.length && this.canPlay(p[p.length - 1])); - } - - remainingValue() { - return sumVal(this.stock) + this.tableau.reduce((t, p) => t + sumVal(p), 0); + legalMoves() { + const out = []; + this.tableau.forEach((p, col) => { if (p.length && this.canPlay(p[p.length - 1])) out.push({ t: 'gplay', col }); }); + if (this.stock.length) out.push({ t: 'gstock' }); + return out; } + hasMoves() { return this.legalMoves().length > 0; } + remainingValue() { return sumVal(this.stock) + this.tableau.reduce((t, p) => t + sumVal(p), 0); } isWon() { return this.tableau.every((p) => p.length === 0); } } -// ── Klondike ──────────────────────────────────────────────────────────────────── +// ── Klondike ───────────────────────────────────────────────────────────────── export class KlondikeEngine { constructor(deck, opts = {}) { this.type = opts.type ?? 'klondike'; - this.recycleLimit = opts.recycleLimit ?? Infinity; // stock passes allowed + this.recycleLimit = opts.recycleLimit ?? Infinity; this.recyclesLeft = this.recycleLimit; - this.tableau = Array.from({ length: 7 }, () => []); let k = 0; for (let col = 0; col < 7; col++) { - for (let row = 0; row <= col; row++) { - this.tableau[col].push({ card: deck[k++], faceUp: row === col }); - } + for (let row = 0; row <= col; row++) this.tableau[col].push({ card: deck[k++], faceUp: row === col }); } this.stock = deck.slice(k); // 24 this.waste = []; this.foundations = { s: [], h: [], d: [], c: [] }; + this.moveCount = 0; } - foundationTop(suit) { - const f = this.foundations[suit]; - return f[f.length - 1] ?? null; + snapshot() { + return { + tableau: this.tableau.map(p => p.map(e => ({ card: e.card, faceUp: e.faceUp }))), + stock: this.stock.slice(), waste: this.waste.slice(), foundations: copyFound(this.foundations), + recyclesLeft: this.recyclesLeft, moveCount: this.moveCount, + }; } + restore(s) { + this.tableau = s.tableau.map(p => p.map(e => ({ card: e.card, faceUp: e.faceUp }))); + this.stock = s.stock.slice(); this.waste = s.waste.slice(); this.foundations = copyFound(s.foundations); + this.recyclesLeft = s.recyclesLeft ?? Infinity; this.moveCount = s.moveCount ?? 0; + } + allCards() { return [...this.tableau.flat().map(e => e.card), ...this.stock, ...this.waste, ...SUITS.flatMap(s => this.foundations[s])]; } + + foundationTop(suit) { const f = this.foundations[suit]; return f[f.length - 1] ?? null; } + wasteTop() { return this.waste[this.waste.length - 1] ?? null; } canPlayFoundation(card) { if (!card) return false; @@ -127,13 +190,21 @@ export class KlondikeEngine { return top ? card.pval === top.pval + 1 : card.pval === 1; } - // A face-up, properly-sequenced (down, alternating colour) run from `idx` down. + /** Nothing could ever need to be built on it: both opposite-colour cards one lower are home. */ + isSafeHome(card) { + if (!this.canPlayFoundation(card)) return false; + if (card.pval <= 2) return true; + const opp = isRed(card) ? ['s', 'c'] : ['h', 'd']; + return opp.every(s => this.foundations[s].length >= card.pval - 1); + } + + /** A face-up, properly sequenced (down, alternating colour) run from `idx` down. */ faceUpRun(col, idx) { const pile = this.tableau[col]; - if (idx < 0 || idx >= pile.length || !pile[idx].faceUp) return null; + if (!pile || idx < 0 || idx >= pile.length || !pile[idx].faceUp) return null; for (let i = idx; i < pile.length - 1; i++) { const a = pile[i].card, b = pile[i + 1].card; - if (!(b.pval === a.pval - 1 && b.isRed !== a.isRed)) return null; + if (!(b.pval === a.pval - 1 && isRed(b) !== isRed(a))) return null; } return pile.slice(idx).map((e) => e.card); } @@ -142,7 +213,7 @@ export class KlondikeEngine { const pile = this.tableau[destCol]; if (!pile.length) return card.pval === 13; // only a King to an empty column const top = pile[pile.length - 1]; - return top.faceUp && card.pval === top.card.pval - 1 && card.isRed !== top.card.isRed; + return top.faceUp && card.pval === top.card.pval - 1 && isRed(card) !== isRed(top.card); } flipColumnTop(col) { @@ -150,72 +221,126 @@ export class KlondikeEngine { if (p.length && !p[p.length - 1].faceUp) p[p.length - 1].faceUp = true; } - // ── moves ── - dealStock() { - if (this.stock.length) { this.waste.push(this.stock.pop()); return true; } - if (!this.waste.length || this.recyclesLeft <= 0) return false; - this.recyclesLeft--; - this.stock = this.waste.reverse(); - this.waste = []; - return true; + apply(m) { + let out = []; + switch (m.t) { + case 'kstock': + if (this.stock.length) { const c = this.stock.pop(); this.waste.push(c); out = [c]; } + else if (this.waste.length && this.recyclesLeft > 0) { + this.recyclesLeft--; + out = this.waste.slice(); + this.stock = this.waste.reverse(); + this.waste = []; + } + break; + case 'kwf': { + const c = this.wasteTop(); + if (this.canPlayFoundation(c)) { this.foundations[c.suit].push(this.waste.pop()); out = [c]; } + break; + } + case 'kcf': { + const pile = this.tableau[m.col], top = pile?.[pile.length - 1]; + if (top?.faceUp && this.canPlayFoundation(top.card)) { this.foundations[top.card.suit].push(pile.pop().card); this.flipColumnTop(m.col); out = [top.card]; } + break; + } + case 'kwc': { + const c = this.wasteTop(); + if (c && this.tableau[m.to] && this.canStack(c, m.to)) { this.tableau[m.to].push({ card: this.waste.pop(), faceUp: true }); out = [c]; } + break; + } + case 'krun': { + if (m.col === m.to || !this.tableau[m.to]) break; + const run = this.faceUpRun(m.col, m.idx); + if (!run || !this.canStack(run[0], m.to)) break; + const moving = this.tableau[m.col].splice(m.idx); + for (const e of moving) this.tableau[m.to].push(e); + this.flipColumnTop(m.col); + out = run; + break; + } + default: break; + } + if (out.length) this.moveCount++; + return out; } - playWasteToFoundation() { - const card = this.waste[this.waste.length - 1]; - if (!this.canPlayFoundation(card)) return false; - this.foundations[card.suit].push(this.waste.pop()); - return true; - } + // classic helpers (tests + readability) + dealStock() { return this.apply({ t: 'kstock' }).length > 0; } + playWasteToFoundation() { return this.apply({ t: 'kwf' }).length > 0; } + playColumnToFoundation(col) { return this.apply({ t: 'kcf', col }).length > 0; } + moveWasteToColumn(to) { return this.apply({ t: 'kwc', to }).length > 0; } + moveRun(col, idx, to) { return this.apply({ t: 'krun', col, idx, to }).length > 0; } - playColumnToFoundation(col) { - const pile = this.tableau[col]; - const top = pile[pile.length - 1]; - if (!top || !top.faceUp || !this.canPlayFoundation(top.card)) return false; - this.foundations[top.card.suit].push(pile.pop().card); - this.flipColumnTop(col); - return true; - } - - moveWasteToColumn(destCol) { - const card = this.waste[this.waste.length - 1]; - if (!card || !this.canStack(card, destCol)) return false; - this.tableau[destCol].push({ card: this.waste.pop(), faceUp: true }); - return true; - } - - moveRun(srcCol, idx, destCol) { - if (srcCol === destCol) return false; - const run = this.faceUpRun(srcCol, idx); - if (!run || !this.canStack(run[0], destCol)) return false; - const moving = this.tableau[srcCol].splice(idx); - for (const e of moving) this.tableau[destCol].push(e); - this.flipColumnTop(srcCol); - return true; - } - - anyImmediateMove() { - if (this.canPlayFoundation(this.waste[this.waste.length - 1])) return true; + legalMoves() { + const out = []; + const w = this.wasteTop(); + if (this.canPlayFoundation(w)) out.push({ t: 'kwf' }); + if (w) for (let d = 0; d < 7; d++) if (this.canStack(w, d)) out.push({ t: 'kwc', to: d }); for (let c = 0; c < 7; c++) { const pile = this.tableau[c]; const top = pile[pile.length - 1]; - if (top && this.canPlayFoundation(top.card)) return true; - // any face-up run head that can move to another column - const firstUp = pile.findIndex((e) => e.faceUp); - if (firstUp >= 0) { - const run = this.faceUpRun(c, firstUp); - if (run && this.tableau.some((_, d) => d !== c && this.canStack(run[0], d))) return true; + if (top?.faceUp && this.canPlayFoundation(top.card)) out.push({ t: 'kcf', col: c }); + for (let idx = 0; idx < pile.length; idx++) { + const run = this.faceUpRun(c, idx); + if (!run) continue; + for (let d = 0; d < 7; d++) { + if (d === c || !this.canStack(run[0], d)) continue; + if (idx === 0 && !this.tableau[d].length) continue; // a whole column into an empty one: pointless + out.push({ t: 'krun', col: c, idx, to: d }); + } } } - const w = this.waste[this.waste.length - 1]; - if (w && this.tableau.some((_, d) => this.canStack(w, d))) return true; - return false; + if (this.stock.length || (this.waste.length && this.recyclesLeft > 0)) out.push({ t: 'kstock' }); + return out; } - hasMoves() { - if (this.anyImmediateMove()) return true; - if (this.stock.length) return true; - if (this.waste.length && this.recyclesLeft > 0) return true; - return false; + /** + * Truly stuck: no move but the stock, and with unlimited recycling every + * stock/waste card will come round — so stuck only if none of them can be + * played anywhere either. + */ + isStuck() { + if (this.anyImmediateMove()) return false; + if (!this.stock.length && !(this.waste.length && this.recyclesLeft > 0)) return true; + if (this.recyclesLeft !== Infinity) return false; + return ![...this.stock, ...this.waste].some(c => this.canPlayFoundation(c) || this.tableau.some((_, d) => this.canStack(c, d))); + } + + /** A move that makes progress (not just turning the stock). */ + anyImmediateMove() { return this.legalMoves().some(m => m.t !== 'kstock'); } + hasMoves() { return this.legalMoves().length > 0; } + + /** Stock spent, everything face-up, and playing straight home clears the board. */ + canAutoFinish() { + if (this.stock.length || this.isWon()) return false; + if (!this.tableau.every(p => p.every(e => e.faceUp))) return false; + const cols = this.tableau.map(p => p.map(e => e.card)); + const waste = this.waste.slice(); + const need = {}; + for (const s of SUITS) need[s] = (this.foundationTop(s)?.pval ?? 0) + 1; + let remaining = waste.length + cols.reduce((t, c) => t + c.length, 0); + let moved = true; + while (remaining > 0 && moved) { + moved = false; + const wt = waste[waste.length - 1]; + if (wt && wt.pval === need[wt.suit]) { waste.pop(); need[wt.suit]++; remaining--; moved = true; } + for (const col of cols) { + const top = col[col.length - 1]; + if (top && top.pval === need[top.suit]) { col.pop(); need[top.suit]++; remaining--; moved = true; } + } + } + return remaining === 0; + } + + /** Next foundation play (waste first, then columns), or null. */ + homeMove({ safeOnly = false } = {}) { + const ok = (c) => (safeOnly ? this.isSafeHome(c) : this.canPlayFoundation(c)); + if (ok(this.wasteTop())) return { t: 'kwf' }; + for (let c = 0; c < 7; c++) { + const top = this.tableau[c][this.tableau[c].length - 1]; + if (top?.faceUp && ok(top.card)) return { t: 'kcf', col: c }; + } + return null; } remainingValue() { @@ -224,40 +349,54 @@ export class KlondikeEngine { return total; } - isWon() { - return ['s', 'h', 'd', 'c'].every((s) => this.foundations[s].length === 13); - } + isWon() { return SUITS.every((s) => this.foundations[s].length === 13); } } -// ── Three Shuffles and a Draw (a La Belle Lucie variant) ──────────────────────── -// Four foundations build UP in suit from Ace. The tableau is dealt into piles of -// three (the last pile is short); piles build DOWN in suit and only the top card -// is in play. Empty spaces are never refilled. When stuck the player gathers all -// tableau cards, shuffles, and redeals — twice (the initial deal is the first of -// the three "shuffles"). After the redeals are spent, one Draw frees any single -// buried card. Win by clearing every card to the foundations. +// ── Three Shuffles and a Draw (a La Belle Lucie variant) ───────────────────── +// Four foundations build UP in suit from Ace. The tableau is dealt into fans of +// three (the last is short); fans build DOWN in suit and only the top card is in +// play. Empty spaces are never refilled. When stuck the player gathers all fan +// cards, shuffles, and redeals — twice (the initial deal is the first of the +// three "shuffles"). After the redeals are spent, one Draw frees any single +// buried card. The reshuffle is seeded and the seed is part of the snapshot, +// so undoing a shuffle and shuffling again gives the same cards. export class ThreeShufflesEngine { - constructor(deck) { + constructor(deck, { seed = (Math.random() * 2 ** 32) >>> 0 } = {}) { this.type = 'threeshuffles'; this.foundations = { s: [], h: [], d: [], c: [] }; - this.shufflesLeft = 2; // two redeals beyond the initial deal - this.drawsLeft = 1; // usable only once the redeals are spent + this.shufflesLeft = 2; + this.drawsLeft = 1; + this.seed = seed >>> 0; + this.moveCount = 0; this.dealPiles(deck); } - // Chunk cards into piles of three; the final pile holds the remainder. On the - // first 52-card deal this is 17 piles of three plus one single card (18 piles). + snapshot() { + return { + piles: this.piles.map(p => p.slice()), foundations: copyFound(this.foundations), + shufflesLeft: this.shufflesLeft, drawsLeft: this.drawsLeft, seed: this.seed, moveCount: this.moveCount, + }; + } + restore(s) { + this.piles = s.piles.map(p => p.slice()); this.foundations = copyFound(s.foundations); + this.shufflesLeft = s.shufflesLeft; this.drawsLeft = s.drawsLeft; this.seed = s.seed >>> 0; this.moveCount = s.moveCount ?? 0; + } + allCards() { return [...this.piles.flat(), ...SUITS.flatMap(s => this.foundations[s])]; } + + rand() { + let t = (this.seed = (this.seed + 0x6d2b79f5) >>> 0); + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + } + + /** Fans of three; the final fan holds the remainder (17 × 3 + 1 on the first deal). */ dealPiles(cards) { this.piles = []; for (let i = 0; i < cards.length; i += 3) this.piles.push(cards.slice(i, i + 3)); } - prune() { this.piles = this.piles.filter((p) => p.length > 0); } - - foundationTop(suit) { - const f = this.foundations[suit]; - return f[f.length - 1] ?? null; - } + foundationTop(suit) { const f = this.foundations[suit]; return f[f.length - 1] ?? null; } canPlayFoundation(card) { if (!card) return false; @@ -265,85 +404,112 @@ export class ThreeShufflesEngine { return top ? card.pval === top.pval + 1 : card.pval === 1; } - pileTop(p) { - const pile = this.piles[p]; - return pile ? pile[pile.length - 1] ?? null : null; - } + pileTop(p) { const pile = this.piles[p]; return pile ? pile[pile.length - 1] ?? null : null; } - // Build down in suit; empty piles can never be filled. + /** Build down in suit; an empty fan can never be filled. */ canStack(card, destP) { - const pile = this.piles[destP]; - if (!pile || !pile.length) return false; - const top = pile[pile.length - 1]; - return top.suit === card.suit && card.pval === top.pval - 1; + const top = this.pileTop(destP); + return !!card && !!top && top.suit === card.suit && card.pval === top.pval - 1; } - playToFoundation(p) { - const card = this.pileTop(p); - if (!this.canPlayFoundation(card)) return false; - this.foundations[card.suit].push(this.piles[p].pop()); - this.prune(); - return true; - } + canDraw() { return this.shufflesLeft === 0 && this.drawsLeft > 0 && this.piles.some(p => p.length > 1); } - moveTop(srcP, destP) { - if (srcP === destP) return false; - const card = this.pileTop(srcP); - if (!card || !this.canStack(card, destP)) return false; - this.piles[destP].push(this.piles[srcP].pop()); - this.prune(); - return true; - } - - redeal() { - if (this.shufflesLeft <= 0) return false; - const rest = []; - for (const pile of this.piles) for (const card of pile) rest.push(card); - if (!rest.length) return false; - for (let i = rest.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)); - [rest[i], rest[j]] = [rest[j], rest[i]]; + apply(m) { + let out = []; + switch (m.t) { + case 'tfound': { + const c = this.pileTop(m.p); + if (this.canPlayFoundation(c)) { this.foundations[c.suit].push(this.piles[m.p].pop()); out = [c]; } + break; + } + case 'tmove': { + if (m.p === m.to) break; + const c = this.pileTop(m.p); + if (c && this.canStack(c, m.to)) { this.piles[m.to].push(this.piles[m.p].pop()); out = [c]; } + break; + } + case 'tredeal': { + if (this.shufflesLeft <= 0) break; + const rest = this.piles.flat(); + if (!rest.length) break; + for (let i = rest.length - 1; i > 0; i--) { + const j = Math.floor(this.rand() * (i + 1)); + [rest[i], rest[j]] = [rest[j], rest[i]]; + } + this.dealPiles(rest); + this.shufflesLeft--; + out = rest; + break; + } + case 'tdraw': { + if (!this.canDraw()) break; + for (const pile of this.piles) { + const idx = pile.findIndex((c) => c.id === m.id); + if (idx < 0) continue; + if (idx === pile.length - 1) break; // already a top card + const [card] = pile.splice(idx, 1); + this.piles.push([card]); + this.drawsLeft--; + out = [card]; + break; + } + break; + } + default: break; } - this.dealPiles(rest); - this.shufflesLeft--; - return true; + if (out.length) this.moveCount++; + return out; } - canDraw() { return this.shufflesLeft === 0 && this.drawsLeft > 0; } + playToFoundation(p) { return this.apply({ t: 'tfound', p }).length > 0; } + moveTop(p, to) { return this.apply({ t: 'tmove', p, to }).length > 0; } + redeal() { return this.apply({ t: 'tredeal' }).length > 0; } + drawCard(id) { return this.apply({ t: 'tdraw', id }).length > 0; } - /** The Draw: free one buried card by lifting it into its own new pile. */ - drawCard(cardId) { - if (!this.canDraw()) return false; - for (const pile of this.piles) { - const idx = pile.findIndex((c) => c.id === cardId); - if (idx < 0) continue; - if (idx === pile.length - 1) return false; // already a top card - const [card] = pile.splice(idx, 1); - this.piles.push([card]); - this.drawsLeft--; - return true; - } - return false; - } - - hasMoves() { + legalMoves() { + const out = []; for (let p = 0; p < this.piles.length; p++) { - const card = this.pileTop(p); - if (!card) continue; - if (this.canPlayFoundation(card)) return true; - for (let d = 0; d < this.piles.length; d++) if (d !== p && this.canStack(card, d)) return true; + const c = this.pileTop(p); + if (!c) continue; + if (this.canPlayFoundation(c)) out.push({ t: 'tfound', p }); + for (let d = 0; d < this.piles.length; d++) if (d !== p && this.canStack(c, d)) out.push({ t: 'tmove', p, to: d }); } - if (this.shufflesLeft > 0 && this.piles.some((p) => p.length)) return true; - if (this.canDraw() && this.piles.some((p) => p.length > 1)) return true; - return false; + if (this.shufflesLeft > 0 && this.piles.some(p => p.length)) out.push({ t: 'tredeal' }); + if (this.canDraw()) out.push({ t: 'tdraw' }); // needs a card id to apply + return out; + } + + hasMoves() { return this.legalMoves().length > 0; } + + /** Playing straight home would clear every fan. */ + canAutoFinish() { + if (this.isWon()) return false; + const piles = this.piles.map(p => p.slice()); + const need = {}; + for (const s of SUITS) need[s] = (this.foundationTop(s)?.pval ?? 0) + 1; + let remaining = piles.reduce((t, p) => t + p.length, 0); + let moved = true; + while (remaining > 0 && moved) { + moved = false; + for (const p of piles) { + const top = p[p.length - 1]; + if (top && top.pval === need[top.suit]) { p.pop(); need[top.suit]++; remaining--; moved = true; } + } + } + return remaining === 0; + } + + /** Next foundation play. In this game every one is safe: only the same suit could build on it. */ + homeMove() { + for (let p = 0; p < this.piles.length; p++) if (this.canPlayFoundation(this.pileTop(p))) return { t: 'tfound', p }; + return null; } remainingValue() { return this.piles.reduce((t, p) => t + sumVal(p), 0); } - - isWon() { return ['s', 'h', 'd', 'c'].every((s) => this.foundations[s].length === 13); } + isWon() { return SUITS.every((s) => this.foundations[s].length === 13); } } -// ── Pyramid ──────────────────────────────────────────────────────────────────── +// ── Pyramid ────────────────────────────────────────────────────────────────── export class PyramidEngine { constructor(deck) { this.type = 'pyramid'; @@ -356,72 +522,91 @@ export class PyramidEngine { } this.stock = deck.slice(k); // 24 this.waste = []; + this.discard = []; // removed cards, in removal order this.passesLeft = 3; + this.moveCount = 0; } + snapshot() { return { rows: this.rows.map(r => r.slice()), stock: this.stock.slice(), waste: this.waste.slice(), discard: this.discard.slice(), passesLeft: this.passesLeft, moveCount: this.moveCount }; } + restore(s) { this.rows = s.rows.map(r => r.slice()); this.stock = s.stock.slice(); this.waste = s.waste.slice(); this.discard = s.discard.slice(); this.passesLeft = s.passesLeft; this.moveCount = s.moveCount ?? 0; } + allCards() { return [...this.rows.flat().filter(Boolean), ...this.stock, ...this.waste, ...this.discard]; } + /** Exposed = present and not covered by either card in the row below. */ available(r, i) { - if (!this.rows[r][i]) return false; + if (!this.rows[r]?.[i]) return false; if (r === 6) return true; return !this.rows[r + 1][i] && !this.rows[r + 1][i + 1]; } wasteTop() { return this.waste[this.waste.length - 1] ?? null; } - - removeKing(loc) { - const card = this.cardAt(loc); - if (!card || card.pval !== 13 || !this.locAvailable(loc)) return false; - this.clear(loc); - return true; - } - - removePair(a, b) { - const ca = this.cardAt(a), cb = this.cardAt(b); - if (!ca || !cb || a === b) return false; - if (!this.locAvailable(a) || !this.locAvailable(b)) return false; - if (ca.pval + cb.pval !== 13) return false; - this.clear(a); - this.clear(b); - return true; - } - - // Locations are { area:'pyramid', r, i } or { area:'waste' }. - cardAt(loc) { return loc.area === 'waste' ? this.wasteTop() : this.rows[loc.r][loc.i]; } + cardAt(loc) { return loc.area === 'waste' ? this.wasteTop() : this.rows[loc.r]?.[loc.i] ?? null; } locAvailable(loc) { return loc.area === 'waste' ? !!this.wasteTop() : this.available(loc.r, loc.i); } + sameLoc(a, b) { return a.area === b.area && (a.area === 'waste' || (a.r === b.r && a.i === b.i)); } clear(loc) { + const c = this.cardAt(loc); if (loc.area === 'waste') this.waste.pop(); else this.rows[loc.r][loc.i] = null; + this.discard.push(c); } - dealStock() { - if (this.stock.length) { this.waste.push(this.stock.pop()); return true; } - if (!this.waste.length || this.passesLeft <= 0) return false; - this.passesLeft--; - this.stock = this.waste.reverse(); - this.waste = []; - return true; - } - - availableCards() { + /** Every uncovered location (pyramid + waste top). */ + availableLocs() { const out = []; - for (let r = 0; r < 7; r++) for (let i = 0; i <= r; i++) { - if (this.available(r, i)) out.push(this.rows[r][i]); - } - if (this.wasteTop()) out.push(this.wasteTop()); + for (let r = 0; r < 7; r++) for (let i = 0; i <= r; i++) if (this.available(r, i)) out.push({ area: 'pyramid', r, i }); + if (this.wasteTop()) out.push({ area: 'waste' }); return out; } - hasMoves() { - const cards = this.availableCards(); - if (cards.some((c) => c.pval === 13)) return true; - for (let a = 0; a < cards.length; a++) - for (let b = a + 1; b < cards.length; b++) - if (cards[a].pval + cards[b].pval === 13) return true; - if (this.stock.length) return true; - if (this.waste.length && this.passesLeft > 0) return true; - return false; + /** Uncovered locations whose card makes 13 with the card at `loc`. */ + partnersOf(loc) { + const c = this.cardAt(loc); + if (!c || !this.locAvailable(loc) || c.pval === 13) return []; + return this.availableLocs().filter(l => !this.sameLoc(l, loc) && this.cardAt(l).pval + c.pval === 13); } + apply(m) { + let out = []; + if (m.t === 'pking') { + const c = this.cardAt(m.loc); + if (c && c.pval === 13 && this.locAvailable(m.loc)) { this.clear(m.loc); out = [c]; } + } else if (m.t === 'ppair') { + const a = this.cardAt(m.a), b = this.cardAt(m.b); + if (a && b && !this.sameLoc(m.a, m.b) && this.locAvailable(m.a) && this.locAvailable(m.b) && a.pval + b.pval === 13) { + // clear the pyramid card first so a waste pair can't disturb indexes + const [first, second] = m.a.area === 'waste' ? [m.b, m.a] : [m.a, m.b]; + this.clear(first); this.clear(second); + out = [a, b]; + } + } else if (m.t === 'pstock') { + if (this.stock.length) { const c = this.stock.pop(); this.waste.push(c); out = [c]; } + else if (this.waste.length && this.passesLeft > 0) { + this.passesLeft--; + out = this.waste.slice(); + this.stock = this.waste.reverse(); + this.waste = []; + } + } + if (out.length) this.moveCount++; + return out; + } + + removeKing(loc) { return this.apply({ t: 'pking', loc }).length > 0; } + removePair(a, b) { return this.apply({ t: 'ppair', a, b }).length > 0; } + dealStock() { return this.apply({ t: 'pstock' }).length > 0; } + + legalMoves() { + const out = []; + const locs = this.availableLocs(); + for (const l of locs) if (this.cardAt(l).pval === 13) out.push({ t: 'pking', loc: l }); + for (let a = 0; a < locs.length; a++) for (let b = a + 1; b < locs.length; b++) { + if (this.cardAt(locs[a]).pval + this.cardAt(locs[b]).pval === 13) out.push({ t: 'ppair', a: locs[a], b: locs[b] }); + } + if (this.stock.length || (this.waste.length && this.passesLeft > 0)) out.push({ t: 'pstock' }); + return out; + } + + hasMoves() { return this.legalMoves().length > 0; } + remainingValue() { let total = sumVal(this.stock) + sumVal(this.waste); for (const row of this.rows) for (const c of row) if (c) total += c.pval; @@ -431,7 +616,7 @@ export class PyramidEngine { isWon() { return this.rows.every((row) => row.every((c) => !c)); } } -// ── Take Fourteen ─────────────────────────────────────────────────────────────── +// ── Take Fourteen ──────────────────────────────────────────────────────────── export class FourteenEngine { constructor(deck) { this.type = 'fourteen'; @@ -442,40 +627,64 @@ export class FourteenEngine { const size = p < 4 ? 5 : 4; for (let n = 0; n < size; n++) this.piles[p].push(deck[k++]); } + this.discard = []; + this.moveCount = 0; } - top(p) { return this.piles[p][this.piles[p].length - 1] ?? null; } + snapshot() { return { piles: this.piles.map(p => p.slice()), discard: this.discard.slice(), moveCount: this.moveCount }; } + restore(s) { this.piles = s.piles.map(p => p.slice()); this.discard = s.discard.slice(); this.moveCount = s.moveCount ?? 0; } + allCards() { return [...this.piles.flat(), ...this.discard]; } - removePair(p1, p2) { - if (p1 === p2) return false; - const a = this.top(p1), b = this.top(p2); - if (!a || !b || a.pval + b.pval !== 14) return false; - this.piles[p1].pop(); - this.piles[p2].pop(); - return true; + top(p) { return this.piles[p]?.[this.piles[p].length - 1] ?? null; } + + partnersOf(p) { + const c = this.top(p); + if (!c) return []; + return this.piles.map((_, q) => q).filter(q => q !== p && this.top(q) && this.top(q).pval + c.pval === 14); } - hasMoves() { - const tops = this.piles.map((_, p) => this.top(p)).filter(Boolean); - for (let a = 0; a < tops.length; a++) - for (let b = a + 1; b < tops.length; b++) - if (tops[a].pval + tops[b].pval === 14) return true; - return false; + apply(m) { + if (m.t !== 'fpair' || m.a === m.b) return []; + const a = this.top(m.a), b = this.top(m.b); + if (!a || !b || a.pval + b.pval !== 14) return []; + this.piles[m.a].pop(); + this.piles[m.b].pop(); + this.discard.push(a, b); + this.moveCount++; + return [a, b]; } + removePair(a, b) { return this.apply({ t: 'fpair', a, b }).length > 0; } + + legalMoves() { + const out = []; + for (let a = 0; a < 12; a++) for (let b = a + 1; b < 12; b++) { + const x = this.top(a), y = this.top(b); + if (x && y && x.pval + y.pval === 14) out.push({ t: 'fpair', a, b }); + } + return out; + } + + hasMoves() { return this.legalMoves().length > 0; } remainingValue() { return this.piles.reduce((t, p) => t + sumVal(p), 0); } - isWon() { return this.piles.every((p) => p.length === 0); } } -export function createEngine(type) { - const deck = freshDeck(); +export function createEngine(type, rng = Math.random) { + const deck = freshDeck(rng); switch (type) { case 'golf': return new GolfEngine(deck); case 'klondike': return new KlondikeEngine(deck); case 'pyramid': return new PyramidEngine(deck); case 'fourteen': return new FourteenEngine(deck); - case 'threeshuffles': return new ThreeShufflesEngine(deck); + case 'threeshuffles': return new ThreeShufflesEngine(deck, { seed: (rng() * 2 ** 32) >>> 0 }); default: throw new Error(`Unknown solitaire: ${type}`); } } + +/** Rebuild an engine from an encoded snapshot (a saved tour). */ +export function engineFromSave(type, encodedSnap) { + const e = createEngine(type); + e.restore(decode(encodedSnap)); + return e; +} diff --git a/src/games/solitairetour/SolitaireTourTable.js b/src/games/solitairetour/SolitaireTourTable.js new file mode 100644 index 0000000..b75f068 --- /dev/null +++ b/src/games/solitairetour/SolitaireTourTable.js @@ -0,0 +1,86 @@ +// Solitaire Tour table layout — Phaser-free (tools/verifySolitaireTour.js tests it). +// +// Every stop on the tour shares one frame: a strip of the room along the top +// (with a window onto that place), the scorecard down the left, the leg plate +// and dock down the right, and the playing surface in between. Cards are flat +// (q = 1); each game picks its own card scale. + +import { flatPose, poseRect } from '../../ui/solitaire/SolitaireGeometry.js'; + +export const W = 1920, H = 1080; +export const WALL_H = 150; +export const PLAY = { x0: 372, x1: 1560, y0: 166, y1: 1074 }; // the table surface +export const PCX = 966; // its centre line +export const WINDOW = { x0: 716, x1: 1204, y0: 0, y1: 136 }; +export const SCORECARD = { x: 190, y: 566, w: 336, h: 780 }; // left: y 176 … 956 +export const PLATE = { x: 1746, y: 500, w: 316, h: 648 }; // right: y 176 … 824 +export const DOCK = { x0: 1588, x1: 1904, y0: 846, y1: 1072 }; +export const TOP_BUTTONS = [{ x: 70, y: 38, w: 110, h: 40 }, { x: 190, y: 38, w: 110, h: 40 }, { x: 310, y: 38, w: 110, h: 40 }]; +export const KEYS = { x0: 16, x1: 360, y0: 1036, y1: 1078 }; +export const DEAL_FROM = flatPose(PCX, H + 120, 1, 0.1); +export const MAX_BOTTOM = 1066; + +// ── Golf ───────────────────────────────────────────────────────────────────── +export const GOLF = { + S: 1.1, TOP: 262, STEP: 44, GAP: 150, + colX: (c) => PCX + (c - 3) * 150, + STOCK: flatPose(PCX - 230, 800, 1.1), + FOUND: flatPose(PCX - 40, 800, 1.1), + FAN: 30, SHOW: 6, +}; + +// ── Klondike ───────────────────────────────────────────────────────────────── +export const KLON = { + S: 1.08, TOP: 452, STEP: 34, DOWN: 14, + colX: (c) => PCX + (c - 3) * 150, + STOCK: flatPose(PCX - 450, 262, 1.08), + WASTE: flatPose(PCX - 310, 262, 1.08), + WASTE_FAN: 26, + found: (i) => flatPose(PCX + i * 150, 262, 1.08), +}; + +// ── Pyramid ────────────────────────────────────────────────────────────────── +export const PYR = { + S: 1.0, DX: 104, DY: 62, APEX: { x: PCX, y: 246 }, + pos: (r, i) => flatPose(PCX + (i - r / 2) * 104, 246 + r * 62, 1.0), + STOCK: flatPose(PCX - 250, 866, 1.0), + WASTE: flatPose(PCX - 112, 866, 1.0), + DISCARD: flatPose(PCX + 210, 866, 1.0), +}; + +// ── Take Fourteen ──────────────────────────────────────────────────────────── +export const FOUR = { + S: 1.06, STEP: 36, + pileX: (p) => PCX + ((p % 6) - 2.5) * 168, + pileTop: (p) => (p < 6 ? 262 : 612), + DISCARD: flatPose(PCX, 958, 1.06), +}; + +// ── Three Shuffles and a Draw ──────────────────────────────────────────────── +export const THREE = { + S: 0.98, FAN: 29, PER_ROW: 6, + found: (i) => flatPose(PCX + (i - 1.5) * 130, 250, 0.98), + fanCentre: (p) => ({ x: PCX + ((p % 6) - 2.5) * 186, y: 440 + Math.floor(p / 6) * 160 }), + // long fans (building down in suit can reach 13) tighten to stay inside their slot + fanStep: (n) => (n > 1 ? Math.min(29, 80 / (n - 1)) : 0), + fanPose: (p, k, n) => { + const c = PCX + ((p % 6) - 2.5) * 186, y = 440 + Math.floor(p / 6) * 160; + const step = n > 1 ? Math.min(29, 80 / (n - 1)) : 0; + return flatPose(c + (k - (n - 1) / 2) * step, y, 0.98); + }, +}; + +const centre = (r) => ({ x0: r.x - r.w / 2, x1: r.x + r.w / 2, y0: r.y - r.h / 2, y1: r.y + r.h / 2 }); + +/** HUD rects no card may sit under (for the verify script). */ +export function hudRects() { + return [ + ...TOP_BUTTONS.map((b, i) => ({ name: `top button ${i}`, r: centre(b) })), + { name: 'scorecard', r: centre(SCORECARD) }, + { name: 'leg plate', r: centre(PLATE) }, + { name: 'dock', r: DOCK }, + { name: 'keys line', r: KEYS }, + ]; +} + +export { flatPose, poseRect }; diff --git a/src/games/solitairetour/tutorial.md b/src/games/solitairetour/tutorial.md new file mode 100644 index 0000000..f5f4ee0 --- /dev/null +++ b/src/games/solitairetour/tutorial.md @@ -0,0 +1,119 @@ +# Solitaire Tour: A Tutorial by Miss Hollis + +*How do you do — Winifred Hollis, tour conductor. For thirty years I've walked travellers round the world with a deck of cards in my coat pocket, because in every port I've ever docked there's been somebody playing patience at a café table. This tour is the best of them: five solitaires, five stops, one scorecard. Mind the gangway.* + +--- + +## The Tour + +You play **five solitaires in a row**, each in a different corner of the world: + +| Hole | Game | Where | +|---|---|---| +| 1 | **Golf** | The Old Links Clubhouse, Scotland | +| 2 | **Klondike** | A Gold-Rush Cabin, the Yukon | +| 3 | **Pyramid** | The Terrace at Giza, Cairo | +| 4 | **Take Fourteen** | The Riverboat Salon, the Mississippi | +| 5 | **Three Shuffles and a Draw** | Café de la Belle Lucie, Paris | + +### Scoring — like golf, low is good + +When a game ends, **every card still on the table counts against you** at its face value: **Ace = 1, 2–10 as marked, Jack = 11, Queen = 12, King = 13**. Clear the whole board and that hole scores **0**. Add the five holes together; **the closest to zero wins.** + +Your **scorecard** (on the left) is pencilled in as you go. The current hole is highlighted, with a running "now +N" showing what you'd score if you stopped this minute. A cleared hole gets a green **CLEARED** stamp; beating your best on that hole earns a red **BEST!** + +--- + +## Playing + +- **Drag** a card to move it. Every legal place it could go glows as you carry it. +- Or **click** it, and it goes to its best spot (home first, then a build). If it can't go anywhere, it gives a shake and says why ("Needs a black 7"). +- In the pairing games (**Pyramid** and **Take Fourteen**), click a card, then click its partner — or drag one onto the other. Hovering a card shows its partners in gold. +- Cards that nothing could ever need are sent home automatically (you can switch that off), and once a board is a foregone conclusion the tour finishes it for you. + +### Banking a hole + +When you've done all you can, press **Bank +N** in the dock (or **B**). The cards left over are counted onto your scorecard and you're off to the next stop. If you're truly stuck, the button lights up for you. If there are still moves, it asks first. + +### Undo, and Tournament rules + +On **Casual** rules you may **Undo** (Z) and **Redo** (Y) as much as you like, and restart a hole from the menu. On **Tournament** rules there's no undo: every card stands. Choose under **Menu → Settings → Rules for your next tour**. Each set of rules keeps its own records. + +### Your tour is saved + +Leave whenever you like. The tour is saved as you play, and next time you'll be offered **Resume tour** right where you left off. (Your undo history doesn't travel with it.) + +--- + +## The Five Stops + +### 1 · Golf — the Clubhouse + +Seven columns of five cards, a **foundation** pile, and a **stock** of 16. + +- Play the top card of any column onto the foundation if it is **one rank higher or lower** (a 7 on a 6 or an 8). Suits don't matter. +- **Aces are low and there's no wrapping**: nothing goes on a King, and only a 2 goes on an Ace. +- Stuck? Click the stock to turn its next card onto the foundation. +- Clear all seven columns to score 0. Cards left in the stock don't count against you if the columns are clear. + +*Tip:* Look for long runs before you play — 5, 6, 7, 8, then back down 7, 6… The clubhouse cheers a **run** of three or more, and the tour keeps your longest. + +### 2 · Klondike — the Cabin + +The classic. Seven columns (1 to 7 cards, only the top one face-up), four **foundations**, and the stock. + +- Build the foundations **up by suit from Ace to King**. +- Build the columns **down in alternating colours** (red 6 on a black 7). Move any properly ordered run together. +- **Only a King** may fill an empty column. +- Click the stock to turn one card onto the waste. When it runs out, click the empty stock to turn the waste back over. There's no limit. + +*Tip:* Turning face-down cards over is everything. Prefer moves that uncover a card. + +### 3 · Pyramid — the Terrace + +Twenty-eight cards in a pyramid, the stock and a waste pile below. + +- Remove **pairs of uncovered cards that total 13**: A + Q, 2 + J, 3 + 10, 4 + 9, 5 + 8, 6 + 7. +- **Kings** are 13 on their own — click to clear them. +- The top waste card counts as uncovered. +- You get **three passes** through the stock. +- Clear the pyramid to score 0. (Covered cards are shaded so you can see what's still trapped.) + +### 4 · Take Fourteen — the Riverboat + +Twelve piles (four of five, eight of four). + +- Remove **pairs of top cards that total 14**: A + K, 2 + Q, 3 + J, 4 + 10, 5 + 9, 6 + 8, and 7 + 7. +- That's all there is. Clear every pile. + +*Tip:* When you have a choice, take the pair that uncovers a card with a partner already showing. + +### 5 · Three Shuffles and a Draw — the Café + +The whole deck is dealt into **fans of three** (the last fan has one card), with four **foundations** above. + +- Foundations build **up by suit from Ace**. +- Only the **top card of a fan** plays. Fans build **down in the same suit** (the 6♥ goes on the 7♥). +- **Empty spaces stay empty.** +- When stuck, **Shuffle** (S): every fan card is gathered, shuffled and dealt out in threes again. You get **two** shuffles. +- Once both shuffles are used, you get one **Draw** (D): click any buried card to lift it free. + +--- + +## Keyboard + +| Key | Does | +|---|---| +| Z / Y | Undo / Redo (Casual rules) | +| B | Bank this hole | +| S | Shuffle (Three Shuffles) | +| D | Draw (Three Shuffles) | +| Esc | Menu (or cancel a Draw / drop a selected card) | + +--- + +## Records + +**Stats** opens your tour records: tours finished, your best and recent tour totals, how many came in at 40 or under, your longest Golf run, and your best score and number of clears at each stop. + +*Under 40 is a very fine tour. Zero is the stuff of legend — I've seen it twice. Your train is boarding; off you go.* diff --git a/src/ui/cardtable/CardTableScene.js b/src/ui/cardtable/CardTableScene.js index e905cca..39762a9 100644 --- a/src/ui/cardtable/CardTableScene.js +++ b/src/ui/cardtable/CardTableScene.js @@ -220,7 +220,7 @@ export class CardTableScene extends Phaser.Scene { } c.card = v.card; this.decorate?.(c, v); - if (this.dragState?.id === id) continue; + if (this.dragState?.id === id || this.dragState?.ids?.has?.(id)) continue; if (c._tw && samePose(c._to, v.pose) && c._toFace === v.faceUp) continue; if (!samePose(c.pose, v.pose) || c.faceUp !== v.faceUp) { this.tweenCard(c, v.pose, { diff --git a/src/ui/solitaire/SolitaireGeometry.js b/src/ui/solitaire/SolitaireGeometry.js new file mode 100644 index 0000000..603296a --- /dev/null +++ b/src/ui/solitaire/SolitaireGeometry.js @@ -0,0 +1,63 @@ +// Solitaire geometry — Phaser-free so verify scripts can test layouts. +// +// Solitaire tables are seen from straight above: every card pose is +// { x, y, rot, s, q: 1 } (the card-table kit's pose, never squashed), so all +// 52 cards stay readable. Columns fan downward and squeeze to fit. + +import { CARD_W, CARD_H, cardBounds, inPose, unionRect } from '../cardtable/TableGeometry.js'; + +export { CARD_W, CARD_H, cardBounds, inPose, unionRect }; + +export const flatPose = (x, y, s = 1, rot = 0) => ({ x, y, rot, s, q: 1 }); + +/** + * Poses for a fanned column of n cards. + * faceUp[i] false → the tighter face-down step + * top centre-y of the first card + * maxBottom the last card's bottom edge must stay above this + * step / downStep preferred gaps (px at s = 1); minStep / minDown the squeeze floor + */ +export function columnPoses(n, faceUp, { + x, top, s = 1, maxBottom, step = 34, downStep = 14, minStep = 16, minDown = 6, +} = {}) { + if (!n) return []; + const up = (i) => (faceUp ? faceUp[i] !== false : true); + let ups = 0, downs = 0; + for (let i = 0; i < n - 1; i++) { if (up(i)) ups++; else downs++; } + const room = maxBottom != null ? maxBottom - (CARD_H * s) / 2 - top : Infinity; + let su = step * s, sd = downStep * s; + const need = ups * su + downs * sd; + if (need > room) { + // squeeze face-down cards first, then the face-up ones + sd = Math.max(minDown * s, downs ? (room - ups * su) / downs : sd); + if (ups * su + downs * sd > room) su = Math.max(minStep * s, ups ? (room - downs * sd) / ups : su); + } + const out = []; + let y = top; + for (let i = 0; i < n; i++) { + out.push(flatPose(x, y, s)); + y += up(i) ? su : sd; + } + return out; +} + +/** A face-down/face-up stack of n cards drawn as a slightly thickened pile. */ +export function stackPose(base, i, n, per = 0.25, max = 6) { + const lift = Math.min(max, i * per); + return { ...base, x: base.x - lift * 0.4, y: base.y - lift }; +} + +/** Index of the top-most pose in `poses` containing pt (−1 when none). */ +export function hitIndex(poses, pt, pad = 0) { + for (let i = poses.length - 1; i >= 0; i--) if (inPose(pt, poses[i], pad)) return i; + return -1; +} + +/** Rect covering a pose (plus pad). */ +export function poseRect(pose, pad = 0) { + const b = cardBounds(pose); + return { x0: b.x0 - pad, x1: b.x1 + pad, y0: b.y0 - pad, y1: b.y1 + pad }; +} + +export const inRect = (pt, r) => pt.x >= r.x0 && pt.x <= r.x1 && pt.y >= r.y0 && pt.y <= r.y1; +export const rectCentre = (r) => ({ x: (r.x0 + r.x1) / 2, y: (r.y0 + r.y1) / 2 }); diff --git a/src/ui/solitaire/SolitaireScene.js b/src/ui/solitaire/SolitaireScene.js new file mode 100644 index 0000000..9466040 --- /dev/null +++ b/src/ui/solitaire/SolitaireScene.js @@ -0,0 +1,618 @@ +import * as Phaser from 'phaser'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { + CardTableScene, DEPTH as D, CX, CY, COLORS, Button, playSound, playSoundEx, SFX, FONT_HAND, +} from '../cardtable/CardTableScene.js'; +import { TutorialModal } from '../TutorialModal.js'; +import { CARD_H, flatPose, inRect } from './SolitaireGeometry.js'; +import { loadStats, recordGame, formatTime } from './SolitaireStats.js'; +import { homeChime, pickUp, deny, flourish } from './SolitaireSound.js'; + +// ─── SolitaireScene ─────────────────────────────────────────────────────────── +// Base scene for the one-player solitaires (Freecell first, Solitaire Tour +// next), on top of the card-table kit: persistent keyed card sprites that +// glide and flip (CardTableScene.layout), modals, dock and effects. +// +// It adds what every solitaire wants: drag a card or run with every legal +// target glowing, smart click-to-move (or classic click-select-click), +// unlimited undo/redo + restart, auto-play hooks, a game clock, hints, a win +// cascade and a stats ledger. +// +// A subclass sets this.gs (an engine with snapshot()/restore()/isWon()) and +// implements: +// computeLayout() → { visible, loc } (kit contract) +// faceFrame(card) → texture frame (kit contract) +// pickAt(pt) → src | null src = { key, ids, … } — what a press there grabs +// movesFor(src) → [{ move, anchor: pose, zone: rect, kind, score }] +// commitMove(move) → cards moved (array; empty/falsy = refused) +// and optionally: +// grabBlocker(src) → reason string when src can't be picked up +// dropBlocker(src, pt) → reason string for a failed drop there +// bestMove(src) → move (default: highest-scoring of movesFor) +// doubleTapMove(src) → move (default: its foundation move, if any) +// nextAutoMove() → move to play automatically after a move (or null) +// moveFx(move, cards, via) → { delayFor?, duration? } layout options + sounds +// onStateChanged() → refresh HUD / dock after anything changes +// onWin() → called once when gs.isWon() +// onTapEmpty(pt) → true when a press on no card was handled +// onAutoIdle() → auto-play ran out of moves (without a win) +// dragBadge(src, target) → short text shown beside a dragged run (or null) +// onRewind() → undo / redo / restart just changed the position + +const ANIM = { relaxed: 1.35, normal: 1, brisk: 0.6 }; +export const SOLITAIRE_DEFAULTS = { anim: 'normal', click: 'smart', ambience: true, timer: true }; +const DOUBLE_TAP_MS = 380; +const DRAG_START_SQ = 64; +const TOP = [ + { x: 70, y: 38, w: 110, h: 40, label: 'Menu' }, + { x: 190, y: 38, w: 110, h: 40, label: 'Stats' }, + { x: 310, y: 38, w: 110, h: 40, label: 'Rules' }, +]; + +export { D as DEPTH, CX, CY, COLORS, Button, playSound, playSoundEx, SFX, FONT_HAND }; + +export class SolitaireScene extends CardTableScene { + // ── Setup ───────────────────────────────────────────────────────────────── + initSolitaire(data, { settingsKey, defaults = {}, slug }) { + this.initTable(data, { settingsKey, defaults: { ...SOLITAIRE_DEFAULTS, ...defaults }, minPlayers: 1, maxPlayers: 1 }); + this.playerCount = 1; + this.slug = slug; + this.gs = null; + this.mode = 'deal'; + this.undoStack = []; + this.redoStack = []; + this.initialSnap = null; + this.started = false; + this.finished = false; + this.elapsed = 0; + this.timerOn = false; + this.autoToken = 0; + this.potentialDrag = null; + this.dragState = null; + this.selected = null; + this.hoverSrc = null; + this.hint = null; + this.lastTap = null; + this.targetGlows = []; + this.tutorial = null; + } + + /** Call from create() after createTableBase() and the room art. */ + buildSolitaireBase({ keysText = '' } = {}) { + this.hintG = this.add.graphics().setDepth(D.float - 1); + for (const b of TOP) { + const act = { Menu: () => this.openMenu(), Stats: () => this.openStats(), Rules: () => this.openRules() }[b.label]; + new Button(this, b.x, b.y, b.label, () => { if (!this.modal) act(); }, { + variant: 'ghost', width: b.w, height: b.h, fontSize: 17, + }).setDepth(D.ui); + } + if (keysText) { + this.keysTxt = this.add.text(16, GAME_HEIGHT - 32, keysText, { + fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#c9b08a', lineSpacing: 2, + }).setOrigin(0, 0).setDepth(D.ui).setAlpha(0.75); + } + this.input.on('pointerdown', (p, over) => this.onPointerDown(p, over)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.on('pointerupoutside', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this.events.once('shutdown', () => { this.autoToken++; this.tutorial?.close?.(); }); + } + + ms(x) { return Math.round(x * (ANIM[this.settings.anim] ?? 1)); } + canAct() { return this.mode === 'play' && !this.modal && !this.paused && !this.tutorial?._el; } + + /** Start a fresh game on engine `gs`; dealFrom = pose every card flies from. */ + async beginGame(gs, { dealFrom, order = null, step = 22 } = {}) { + this.autoToken++; + this.cancelDrag(); + this.clearHint(); + this.clearSprites(); + this.gs = gs; + this.undoStack = []; + this.redoStack = []; + this.initialSnap = gs.snapshot(); + this.started = false; + this.finished = false; + this.elapsed = 0; + this.timerOn = false; + this.selected = null; + this.mode = 'deal'; + const token = ++this.turnToken; + const ids = order ?? gs.allCards().map(c => c.id); + const rank = new Map(ids.map((id, i) => [id, i])); + for (const id of ids) this.lastLoc.set(id, { pose: dealFrom, faceUp: false, depth: D.fly }); + this.onStateChanged?.(); + playSound(this, SFX.CARD_SHUFFLE); + this.layout({ duration: this.ms(300), delayFor: (v) => 250 + (rank.get(v.card.id) ?? 0) * this.ms(step) }); + for (let i = 0; i < ids.length; i += 4) this.time.delayedCall(270 + i * this.ms(step), () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.35 })); + await this.wait(250 + ids.length * this.ms(step) + this.ms(380)); + if (!this.alive() || token !== this.turnToken) return; + this.mode = 'play'; + this.onStateChanged?.(); + this.scheduleAuto(); + } + + // ── Moves ───────────────────────────────────────────────────────────────── + bestMove(src) { + const ms = this.movesFor(src); + if (!ms.length) return null; + return ms.reduce((a, b) => (b.score > a.score ? b : a)).move; + } + + doubleTapMove(src) { return this.movesFor(src).find(t => t.kind === 'found')?.move ?? null; } + + /** Play a move the player chose. Returns true when it happened. */ + doMove(move, { via = 'click' } = {}) { + if (!move || this.finished) return false; + const snap = this.gs.snapshot(); + const cards = this.commitMove(move); + if (!cards?.length) return false; + this.undoStack.push(snap); + this.redoStack.length = 0; + this.selected = null; + this.clearHint(); + if (!this.started) { this.started = true; this.timerOn = true; this.onFirstMove?.(); } + this.animateMove(move, cards, via); + this.onStateChanged?.(); + if (this.gs.isWon()) this.handleWin(); + else this.scheduleAuto(); + return true; + } + + animateMove(move, cards, via) { + const fx = this.moveFx?.(move, cards, via) ?? {}; + const order = new Map(cards.map((c, i) => [c.id, i])); + const stagger = fx.stagger ?? 0; + this.layout({ + duration: this.ms(fx.duration ?? 240), + delayFor: (v) => (order.has(v.card.id) ? order.get(v.card.id) * this.ms(stagger) : 0), + }); + if (fx.sound !== false) { + if (move.to?.kind === 'found') homeChime(this, cards[0]?.pval ?? 1); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.55, rate: 0.95 + Math.random() * 0.1 }); + } + } + + /** Auto-play (safe moves / auto-complete) after a move settles. */ + scheduleAuto() { + if (!this.nextAutoMove) return; + const token = ++this.autoToken; + this.runAuto(token); + } + + async runAuto(token) { + await this.wait(this.ms(170)); + while (this.alive() && token === this.autoToken && !this.finished) { + if (this.dragState || this.modal || this.mode !== 'play') { await this.wait(150); continue; } + const m = this.nextAutoMove(); + if (!m) break; + const cards = this.commitMove(m); + if (!cards?.length) break; + this.animateMove(m, cards, 'auto'); + this.onStateChanged?.(); + if (this.gs.isWon()) { this.handleWin(); return; } + await this.wait(this.ms(m.fast ? 90 : 140)); + } + if (this.alive() && token === this.autoToken && !this.finished) this.onAutoIdle?.(); + } + + undo() { + if (!this.canAct() && this.mode !== 'auto') return; + if (!this.undoStack.length) { deny(this); this.floatText({ x: CX, y: 860 }, 'Nothing to undo', '#f2d6a0', { size: 20 }); return; } + this.autoToken++; + this.cancelDrag(); + this.redoStack.push(this.gs.snapshot()); + this.gs.restore(this.undoStack.pop()); + this.afterRewind(); + } + + redo() { + if (!this.canAct() || !this.redoStack.length) return; + this.autoToken++; + this.undoStack.push(this.gs.snapshot()); + this.gs.restore(this.redoStack.pop()); + this.afterRewind(); + } + + restartDeal() { + if (!this.started || this.finished || !this.initialSnap) return; + this.autoToken++; + this.cancelDrag(); + this.undoStack.push(this.gs.snapshot()); + this.redoStack.length = 0; + this.gs.restore(this.initialSnap); + playSound(this, SFX.CARD_SHUFFLE); + this.afterRewind(420); + } + + afterRewind(duration = 220) { + this.selected = null; + this.clearHint(); + this.mode = 'play'; + this.onRewind?.(); + this.layout({ duration: this.ms(duration) }); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.35, rate: 1.25 }); + this.onStateChanged?.(); + } + + // ── Input ───────────────────────────────────────────────────────────────── + onPointerDown(pointer, over) { + if (!this.canAct() || this.dragState || this.overUI(over)) return; + const src = this.pickAt(pointer); + if (!src) { + if (this.selected && this.trySelectedAt(pointer)) return; + if (this.onTapEmpty?.(pointer)) return; + if (this.selected) { this.selected = null; this.refreshGlows(); } + return; + } + this.potentialDrag = { src, x: pointer.x, y: pointer.y }; + } + + onPointerMove(pointer) { + if (this.dragState) { this.updateDrag(pointer); return; } + if (this.potentialDrag && pointer.isDown) { + const dx = pointer.x - this.potentialDrag.x, dy = pointer.y - this.potentialDrag.y; + if (dx * dx + dy * dy > DRAG_START_SQ) this.startDrag(pointer); + return; + } + if (pointer.isDown || !this.canAct()) return; + const src = this.pickAt(pointer); + const key = src?.key ?? null; + if (key !== (this.hoverSrc?.key ?? null)) { this.hoverSrc = src; this.refreshGlows(); } + this.input.setDefaultCursor(src ? (src.tapAction ? 'pointer' : 'grab') : 'default'); + } + + onPointerUp(pointer) { + if (this.dragState) { this.endDrag(pointer); return; } + const pd = this.potentialDrag; + if (!pd) return; + this.potentialDrag = null; + if (this.canAct()) this.onTap(pd.src, pointer); + } + + onTap(src, pointer) { + const now = this.time.now; + const dbl = this.lastTap && this.lastTap.key === src.key && now - this.lastTap.t < DOUBLE_TAP_MS; + this.lastTap = dbl ? null : { key: src.key, t: now }; + if (src.tapAction) { src.tapAction(); return; } + if (dbl) { + const m = this.doubleTapMove(src); + if (m) { this.doMove(m, { via: 'click' }); return; } + } + if (this.settings.click === 'select') { + if (this.selected) { + if (this.selected.key === src.key) { this.selected = null; this.refreshGlows(); return; } + if (this.trySelectedAt(pointer)) return; + } + const why = this.grabBlocker?.(src); + if (why) { this.refuse(src, why); return; } + this.selected = src; + pickUp(this); + this.refreshGlows(); + return; + } + const why = this.grabBlocker?.(src); + if (why) { this.refuse(src, why); return; } + const m = this.bestMove(src); + if (m) this.doMove(m, { via: 'click' }); + else this.refuse(src, this.noMoveReason?.(src) ?? 'No move for that card right now'); + } + + /** Select mode: move the selection to whatever target is under pt. */ + trySelectedAt(pt) { + const t = this.movesFor(this.selected).find(m => inRect(pt, m.zone)); + if (!t) return false; + this.doMove(t.move, { via: 'click' }); + return true; + } + + refuse(src, why) { + deny(this); + const id = src.ids?.[0]; + if (id != null) this.nudge(id); + const p = id != null ? this.poseOf(id) : null; + this.floatText(p ? { x: p.x, y: p.y - CARD_H * 0.55 } : { x: CX, y: 860 }, why, '#ffd2a0', { size: 19, ms: 1500, rise: 30 }); + } + + // ── Drag ────────────────────────────────────────────────────────────────── + startDrag(pointer) { + const pd = this.potentialDrag; + this.potentialDrag = null; + const src = pd.src; + if (src.tapAction) return; + const why = this.grabBlocker?.(src); + if (why) { this.refuse(src, why); return; } + const list = src.ids.map(id => this.sprites.get(id)).filter(Boolean); + if (list.length !== src.ids.length) return; + for (const c of list) { c._tw?.stop(); c._tw = null; } + const offs = list.map(c => ({ x: c.pose.x - pd.x, y: c.pose.y - pd.y, s: c.pose.s })); + this.selected = null; + this.clearHint(); + this.dragState = { id: src.ids[0], ids: new Set(src.ids), list, offs, src, targets: this.movesFor(src), target: null }; + list.forEach((c, i) => c.setDepth(D.drag + i * 0.01)); + pickUp(this); + this.input.setDefaultCursor('grabbing'); + this.refreshGlows(); + this.updateDrag(pointer); + } + + updateDrag(pointer) { + const ds = this.dragState; + ds.list.forEach((c, i) => { + const o = ds.offs[i]; + this.applyPose(c, flatPose(pointer.x + o.x, pointer.y + o.y, o.s), 0.9); + }); + const head = ds.list[0].pose; + let best = null, bestD = Infinity; + for (const t of ds.targets) { + const inside = inRect(head, t.zone) || inRect(pointer, t.zone); + const d = Math.hypot(head.x - t.anchor.x, head.y - t.anchor.y); + if ((inside || d < 110) && d < bestD) { best = t; bestD = d; } + } + if (best !== ds.target) { ds.target = best; this.drawTargetGlows(); } + const badge = this.dragBadge?.(ds.src, ds.target) ?? null; + if (badge) { + if (!this.badgeTxt) { + this.badgeTxt = this.add.text(0, 0, '', { + fontFamily: 'Righteous', fontSize: '18px', color: '#1a0e06', backgroundColor: '#ffd35a', padding: { x: 8, y: 3 }, + }).setOrigin(0, 0.5).setDepth(D.drag + 1); + } + const h = ds.list[0]; + this.badgeTxt.setText(badge.text).setBackgroundColor(badge.ok ? '#ffd35a' : '#ff9a7a') + .setPosition(h.x + 62 * (h.pose.s ?? 1), h.y - 80 * (h.pose.s ?? 1)).setVisible(true); + } else this.badgeTxt?.setVisible(false); + } + + endDrag(pointer) { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + this.hideTargetGlows(); + this.badgeTxt?.setVisible(false); + if (ds.target && this.doMove(ds.target.move, { via: 'drag' })) return; + const moved = Math.hypot(pointer.x - ds.list[0].pose.x, pointer.y - ds.list[0].pose.y); + const why = ds.targets.length ? this.dropBlocker?.(ds.src, pointer) : (this.noMoveReason?.(ds.src) ?? null); + if (why && moved < 2000) { + deny(this); + this.floatText({ x: pointer.x, y: pointer.y - 90 }, why, '#ffd2a0', { size: 19, ms: 1500, rise: 30 }); + } + this.layout({ duration: this.ms(260) }); + this.refreshGlows(); + } + + cancelDrag() { + this.potentialDrag = null; + if (!this.dragState) return; + this.dragState = null; + this.hideTargetGlows(); + this.badgeTxt?.setVisible(false); + if (this.gs) this.layout({ duration: 200 }); + } + + // ── Glows (targets · selection · hint · hover) ──────────────────────────── + drawTargetGlows() { + const ds = this.dragState; + this.hideTargetGlows(); + if (!ds) return; + ds.targets.forEach((t, i) => { + let g = this.targetGlows[i]; + if (!g) { g = this.add.image(0, 0, 'ct-glow'); this.targetGlows[i] = g; } + const hot = t === ds.target; + g.setPosition(t.anchor.x, t.anchor.y).setScale(0.5 * (t.anchor.s ?? 1)).setRotation(t.anchor.rot ?? 0) + .setTint(hot ? 0x9dffb0 : (t.kind === 'found' ? 0xffd35a : 0x8fd6ff)).setAlpha(hot ? 1 : 0.38) + .setDepth(D.glow).setVisible(true); + }); + } + + hideTargetGlows() { for (const g of this.targetGlows) g.setVisible(false); } + + glowFor(id) { + if (this.dragState?.ids.has(id)) return null; + if (this.hint?.ids?.has(id)) return { tint: 0xffd35a, alpha: 1 }; + if (this.selected?.ids?.includes(id)) return { tint: 0x7cf0a0, alpha: 1 }; + if (this.hoverSrc && !this.hoverSrc.tapAction && this.hoverSrc.ids?.[0] === id) return { tint: 0xfff4d6, alpha: 0.35 }; + return this.extraGlow?.(id) ?? null; + } + + refreshGlows() { + for (const [id, c] of this.sprites) { + const g = this.glowFor(id); + if (g) c.glow.setVisible(true).setTint(g.tint).setAlpha(g.alpha); + else c.glow.setVisible(false); + } + } + + /** Kit hook — keep per-card glows in step with every layout. */ + decorate(c) { + const g = this.glowFor(c.card.id); + if (g) c.glow.setVisible(true).setTint(g.tint).setAlpha(g.alpha); + else c.glow.setVisible(false); + } + + // ── Hints ───────────────────────────────────────────────────────────────── + /** h = { ids: [id…], from: pose, to: pose, text? } */ + showHint(h) { + this.clearHint(); + this.hint = { ids: new Set(h.ids) }; + this.refreshGlows(); + const g = this.hintG; + const a = h.from, b = h.to; + const mx = (a.x + b.x) / 2, my = Math.min(a.y, b.y) - 80 - Math.abs(a.x - b.x) * 0.12; + const pts = []; + for (let i = 0; i <= 24; i++) { + const t = i / 24; + pts.push({ x: (1 - t) ** 2 * a.x + 2 * (1 - t) * t * mx + t * t * b.x, y: (1 - t) ** 2 * a.y + 2 * (1 - t) * t * my + t * t * b.y }); + } + g.clear(); + g.lineStyle(9, 0x1a0e06, 0.5); g.strokePoints(pts); + g.lineStyle(5, 0xffd35a, 0.95); g.strokePoints(pts); + const e = pts[pts.length - 1], p = pts[pts.length - 3]; + const ang = Math.atan2(e.y - p.y, e.x - p.x); + g.fillStyle(0xffd35a, 1); + g.fillTriangle(e.x, e.y, e.x - Math.cos(ang - 0.5) * 22, e.y - Math.sin(ang - 0.5) * 22, e.x - Math.cos(ang + 0.5) * 22, e.y - Math.sin(ang + 0.5) * 22); + g.setAlpha(0).setVisible(true); + this.tweens.add({ targets: g, alpha: 1, duration: 180 }); + let tg = this.hintTarget; + if (!tg) { tg = this.add.image(0, 0, 'ct-glow').setDepth(D.glow); this.hintTarget = tg; } + tg.setPosition(b.x, b.y).setScale(0.5 * (b.s ?? 1)).setTint(0x9dffb0).setAlpha(1).setVisible(true); + this.tweens.add({ targets: tg, alpha: 0.35, duration: 520, yoyo: true, repeat: 3 }); + if (h.text) this.floatText({ x: b.x, y: b.y - CARD_H * 0.62 }, h.text, '#ffe29a', { size: 20, ms: 2200, rise: 24 }); + const token = this.hint; + this.time.delayedCall(3200, () => { if (this.hint === token) this.clearHint(); }); + } + + clearHint() { + if (!this.hint && !this.hintG?.visible) return; + this.hint = null; + if (this.hintG) { this.tweens.killTweensOf(this.hintG); this.hintG.clear().setVisible(false); } + if (this.hintTarget) { this.tweens.killTweensOf(this.hintTarget); this.hintTarget.setVisible(false); } + this.refreshGlows(); + } + + // ── Clock ───────────────────────────────────────────────────────────────── + update(_time, delta) { + if (this.timerOn && !this.finished && !this.paused && !this.modal && !document.hidden) { + this.elapsed += delta; + this.onClock?.(this.elapsed); + } + } + + // ── Win ─────────────────────────────────────────────────────────────────── + handleWin() { + if (this.finished) return; + this.finished = true; + this.timerOn = false; + this.autoToken++; + this.mode = 'over'; + this.cancelDrag(); + this.clearHint(); + this.onWin?.(); + } + + /** Record the finished game (stats + history). Returns { stats, newBest }. */ + recordSolitaire({ won, score, mode = 'default', extra = null }) { + const res = recordGame(this.slug, { won, time: Math.round(this.elapsed), moves: this.gs?.moveCount ?? null, mode, extra }); + this.recordResult(this.slug, { score, opponentScores: [], won }); + return res; + } + + /** The game was abandoned after the first move: it counts as a loss. */ + abandonIfStarted(score = 0) { + if (!this.started || this.finished) return; + this.finished = true; + this.timerOn = false; + this.recordSolitaire({ won: false, score }); + } + + /** + * The classic bouncing-card finale. stacks: [{ cards: [bottom … top], pose }]. + * Cards leave trails on a RenderTexture; any click or key skips. + */ + winCascade(stacks, { interval = 110 } = {}) { + return new Promise((resolve) => { + this.mode = 'cascade'; + const rt = this.add.renderTexture(0, 0, GAME_WIDTH, GAME_HEIGHT).setOrigin(0, 0).setDepth(D.float - 2); + const s = stacks[0]?.pose?.s ?? 1; + const stampImg = this.make.image({ x: 0, y: 0, key: 'casino-cards', frame: 'As', add: false }).setScale(0.5 * s); + const copies = stacks.map(st => st.cards.slice()); + const order = []; + while (copies.some(c => c.length)) copies.forEach((c, i) => { if (c.length) order.push({ card: c.pop(), pose: stacks[i].pose }); }); + const floorY = GAME_HEIGHT - (CARD_H * s) / 2 - 2; + const live = []; + let next = 0, launchIn = 300, done = false, skip = false; + const onSkip = () => { skip = true; }; + this.time.delayedCall(400, () => { if (!done) { this.input.once('pointerdown', onSkip); this.input.keyboard?.once('keydown', onSkip); } }); + flourish(this); + const launch = ({ card, pose }) => { + this.sprites.get(card.id)?.setVisible(false); + const dir = pose.x < CX ? -1 : 1; + live.push({ card, x: pose.x, y: pose.y, vx: dir * (2.6 + Math.random() * 4.6) * (Math.random() < 0.2 ? -1 : 1), vy: -(2 + Math.random() * 9) }); + if (next % 3 === 0) playSoundEx(this, SFX.CARD_DEAL, { volume: 0.25, rate: 0.9 + Math.random() * 0.3 }); + }; + const tick = (_t, delta) => { + if (done) return; + const k = Math.min(3, delta / 16.67); + launchIn -= delta; + if (!skip && launchIn <= 0 && next < order.length) { launch(order[next++]); launchIn = interval; } + for (const b of live) { + b.vy += 0.5 * k; b.x += b.vx * k; b.y += b.vy * k; + if (b.y > floorY) { b.y = floorY; b.vy = -Math.abs(b.vy) * (0.72 + Math.random() * 0.08); } + stampImg.setFrame(b.card.key); + rt.draw(stampImg, b.x, b.y); + if (b.x < -90 || b.x > GAME_WIDTH + 90) b.dead = true; + } + for (let i = live.length - 1; i >= 0; i--) if (live[i].dead) live.splice(i, 1); + if (skip || (next >= order.length && !live.length)) finish(); + }; + const finish = () => { + if (done) return; + done = true; + this.events.off('update', tick); + this.input.off('pointerdown', onSkip); + this.input.keyboard?.off('keydown', onSkip); + for (const o of order) this.sprites.get(o.card.id)?.setVisible(false); + this.tweens.add({ targets: rt, alpha: 0, duration: 700, delay: skip ? 0 : 500, onComplete: () => { rt.destroy(); stampImg.destroy(); } }); + this.time.delayedCall(skip ? 150 : 700, resolve); + }; + this.events.on('update', tick); + }); + } + + // ── Menus ───────────────────────────────────────────────────────────────── + onKey(e) { + if (this.tutorial?._el) return; + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal && this.selected) { this.selected = null; this.refreshGlows(); } + else if (!this.modal) this.openMenu(); + return; + } + if (this.modal) { if (e.code === 'Enter') this.modal.onEnter?.(); return; } + if (this.dragState) return; + const ctrl = e.ctrlKey || e.metaKey; + if (e.code === 'KeyZ' && (ctrl ? !e.shiftKey : true)) { this.undo(); return; } + if (e.code === 'KeyY' || (ctrl && e.shiftKey && e.code === 'KeyZ')) { this.redo(); return; } + this.onKeyExtra?.(e); + } + + openRules() { + this.tutorial = new TutorialModal(this.gameDef); + this.tutorial.open(); + } + + /** The ledger of records for this game (mode = stats bucket). */ + openStats({ mode = 'default', title = 'Records', extraLines = [] } = {}) { + const st = loadStats(this.slug, mode); + const h = 560 + extraLines.length * 34; + this.openModal({ w: 760, h, paper: true, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + const ink = '#22201a', grey = '#6c6450'; + this.modalText(CX, top + 64, title, { fontFamily: FONT_HAND, fontSize: '46px', color: ink }); + const pct = st.played ? Math.round((st.won / st.played) * 100) : 0; + const rows = [ + ['Games played', String(st.played)], + ['Games won', st.played ? `${st.won} (${pct}%)` : '0'], + ['Current streak', String(st.streak)], + ['Best streak', String(st.bestStreak)], + ['Fastest win', formatTime(st.bestTime)], + ['Fewest moves', st.fewestMoves == null ? '—' : String(st.fewestMoves)], + ...extraLines, + ]; + rows.forEach(([k, v], i) => { + const y = top + 140 + i * 44; + this.addToModal(this.add.text(CX - 270, y, k, { fontFamily: FONT_HAND, fontSize: '28px', color: grey }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX + 270, y, v, { fontFamily: FONT_HAND, fontSize: '30px', color: ink }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 1)); + g.lineStyle(1, 0x6c6450, 0.25); g.lineBetween(CX - 270, y + 20, CX + 270, y + 20); + }); + const recent = (st.recent ?? []).slice(0, 12).reverse(); + const ry = top + 140 + rows.length * 44 + 30; + this.modalText(CX, ry, recent.length ? 'Recent games' : 'No games finished yet', { fontFamily: FONT_HAND, fontSize: '24px', color: grey }); + recent.forEach((r, i) => { + const x = CX + (i - (recent.length - 1) / 2) * 36; + this.modalText(x, ry + 38, r.won ? '✓' : '✗', { fontFamily: 'sans-serif', fontSize: '26px', color: r.won ? '#2f7a3a' : '#b8231f' }); + }); + this.modalButton(CX, top + h - 52, 'Close', () => this.closeModal(), { width: 220, height: 46, fontSize: 19 }); + } +} diff --git a/src/ui/solitaire/SolitaireSound.js b/src/ui/solitaire/SolitaireSound.js new file mode 100644 index 0000000..0739641 --- /dev/null +++ b/src/ui/solitaire/SolitaireSound.js @@ -0,0 +1,153 @@ +// SolitaireSound.js — small Web Audio synths for the solitaire rooms. No audio +// files; silent without Web Audio or when the game is muted. Card handling +// itself keeps using the shared SFX.CARD_* samples. +// +// homeChime(scene, rank) a card reaches its foundation (pitch climbs with rank) +// pickUp(scene) a soft card lift +// deny(scene) that move isn't allowed +// clockTick(scene, tock) a quiet mantel-clock tick +// thunder(scene) distant thunder +// flourish(scene) the win arpeggio +// RainBed looping rain on glass (start / stop / setOn) + +function ctxOf(scene) { + const sm = scene?.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} +const noiseCache = new WeakMap(); +function noise(ac) { + if (noiseCache.has(ac)) return noiseCache.get(ac); + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + noiseCache.set(ac, buf); + return buf; +} +function out(scene, ac, gain) { + const sm = scene.sound; + const node = sm.masterVolumeNode ?? sm.destination ?? null; + const g = ac.createGain(); + g.gain.value = node ? gain : gain * (sm.volume ?? 1); + g.connect(node ?? ac.destination); + return g; +} +function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.003 } = {}) { + const o = ac.createOscillator(); o.type = type; + o.frequency.setValueAtTime(f, t0); + if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(a, t0 + attack); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03); +} +function hiss(ac, dest, t0, f, vol = 1, d = 0.03, q = 3, type = 'bandpass') { + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.value = f; bp.Q.value = q; + const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02); +} +const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } }; +const semi = (f, n) => f * Math.pow(2, n / 12); +const MAJOR = [0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21]; + +export function homeChime(scene, rank = 1, { vol = 0.05 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.005; + const f = semi(523.25, MAJOR[Math.max(0, Math.min(12, rank - 1))]); + tone(ac, dest, t, f, { type: 'sine', a: 0.8, d: 0.9 }); + tone(ac, dest, t, f * 2.002, { type: 'sine', a: 0.18, d: 0.5 }); + tone(ac, dest, t, f * 3.01, { type: 'triangle', a: 0.06, d: 0.25 }); + }); +} + +export function pickUp(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003; + hiss(ac, dest, t, 3400, 0.6, 0.05, 1.2); + }); +} + +export function deny(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.003; + tone(ac, dest, t, 180, { a: 0.8, d: 0.13, glide: 0.7 }); + hiss(ac, dest, t, 900, 0.4); + }); +} + +export function clockTick(scene, tock = false, { vol = 0.018 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.003; + hiss(ac, dest, t, tock ? 2300 : 3100, 1, 0.025, 6); + tone(ac, dest, t, tock ? 1150 : 1500, { type: 'triangle', a: 0.25, d: 0.03 }); + }); +} + +export function thunder(scene, { vol = 0.12 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.05; + hiss(ac, dest, t, 120, 1, 3.2, 0.7, 'lowpass'); + hiss(ac, dest, t + 0.35, 80, 0.8, 2.6, 0.7, 'lowpass'); + tone(ac, dest, t, 48, { a: 0.5, d: 2.4, attack: 0.3, glide: 0.8 }); + }); +} + +export function flourish(scene, { vol = 0.06 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.01; + [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(ac, dest, t + i * 0.07, semi(523.25, n), { a: 0.7, d: 1.2 })); + }); +} + +/** Rain against a window: filtered noise bed plus the odd heavier drop. */ +export class RainBed { + /** Options shape the bed: rain (default), wind ({ lp: 520, hp: 70, drips: false }), water… */ + constructor(scene, { vol = 0.035, lp = 2400, hp = 380, drips = true } = {}) { + this.scene = scene; this.vol = vol; this.lp = lp; this.hp = hp; this.drips = drips; this.nodes = null; this.timer = null; + } + start() { + if (this.nodes) return; + const ac = ctxOf(this.scene); if (!ac) return; + safe(() => { + const dest = out(this.scene, ac, 0); + const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true; + const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = this.lp; + const hp = ac.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = this.hp; + src.connect(hp); hp.connect(lp); lp.connect(dest); + src.start(); + dest.gain.linearRampToValueAtTime(this.vol, ac.currentTime + 2.5); + this.nodes = { src, dest }; + const drip = () => { + if (!this.drips) return; + this.timer = setTimeout(drip, 180 + Math.random() * 900); + const a2 = ctxOf(this.scene); if (!a2 || !this.nodes) return; + safe(() => { + const d2 = out(this.scene, a2, this.vol * 0.6), t = a2.currentTime + 0.01; + hiss(a2, d2, t, 1800 + Math.random() * 2600, 0.5 + Math.random() * 0.5, 0.02 + Math.random() * 0.03, 4); + }); + }; + drip(); + }); + } + stop() { + clearTimeout(this.timer); this.timer = null; + const n = this.nodes; this.nodes = null; + if (!n) return; + safe(() => { + const ac = n.src.context; + n.dest.gain.cancelScheduledValues(ac.currentTime); + n.dest.gain.setValueAtTime(n.dest.gain.value, ac.currentTime); + n.dest.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6); + n.src.stop(ac.currentTime + 0.7); + }); + } + setOn(on) { if (on) this.start(); else this.stop(); } +} diff --git a/src/ui/solitaire/SolitaireStats.js b/src/ui/solitaire/SolitaireStats.js new file mode 100644 index 0000000..074b38d --- /dev/null +++ b/src/ui/solitaire/SolitaireStats.js @@ -0,0 +1,76 @@ +// Solitaire records — Phaser-free, kept in localStorage per game (and mode). +// +// loadStats(slug, mode) → { played, won, streak, bestStreak, bestTime, fewestMoves, recent[] } +// recordGame(slug, { won, time, moves, mode, extra }) → { stats, newBest: { time?, moves?, streak? } } +// recordBest(slug, key, value, { lower = true, mode }) → true when it beat the old best +// bumpCount(slug, key, { mode }) → the counter's new value +// +// `time` is in ms. Storage defaults to globalThis.localStorage and quietly +// does nothing when it's unavailable (private mode, Node tests pass a stub). + +const KEY = (slug) => `solitaire-stats-${slug}`; +const blank = () => ({ played: 0, won: 0, streak: 0, bestStreak: 0, bestTime: null, fewestMoves: null, recent: [], bests: {}, counts: {} }); + +function store(storage) { return storage ?? globalThis.localStorage ?? null; } + +function readAll(slug, storage) { + try { return JSON.parse(store(storage)?.getItem(KEY(slug)) || '{}') || {}; } catch { return {}; } +} +function writeAll(slug, all, storage) { + try { store(storage)?.setItem(KEY(slug), JSON.stringify(all)); } catch { /* full or private */ } +} + +export function loadStats(slug, mode = 'default', storage) { + return { ...blank(), ...(readAll(slug, storage)[mode] ?? {}) }; +} + +export function recordGame(slug, { won, time = null, moves = null, mode = 'default', extra = null } = {}, storage) { + const all = readAll(slug, storage); + const s = { ...blank(), ...(all[mode] ?? {}) }; + const newBest = {}; + s.played++; + if (won) { + s.won++; + s.streak++; + if (s.streak > s.bestStreak) { s.bestStreak = s.streak; if (s.streak > 1) newBest.streak = true; } + if (time != null && (s.bestTime == null || time < s.bestTime)) { if (s.bestTime != null) newBest.time = true; s.bestTime = time; } + if (moves != null && (s.fewestMoves == null || moves < s.fewestMoves)) { if (s.fewestMoves != null) newBest.moves = true; s.fewestMoves = moves; } + } else { + s.streak = 0; + } + s.recent = [{ won: !!won, time, moves, at: Date.now(), ...(extra ?? {}) }, ...(s.recent ?? [])].slice(0, 12); + all[mode] = s; + writeAll(slug, all, storage); + return { stats: s, newBest }; +} + +export function recordBest(slug, key, value, { lower = true, mode = 'default' } = {}, storage) { + const all = readAll(slug, storage); + const s = { ...blank(), ...(all[mode] ?? {}) }; + const old = s.bests?.[key]; + const better = old == null || (lower ? value < old : value > old); + if (better) { + s.bests = { ...(s.bests ?? {}), [key]: value }; + all[mode] = s; + writeAll(slug, all, storage); + } + return better && old != null; +} + +/** Add 1 (or n) to a named counter (e.g. how many times a Tour leg was cleared). */ +export function bumpCount(slug, key, { mode = 'default', n = 1 } = {}, storage) { + const all = readAll(slug, storage); + const s = { ...blank(), ...(all[mode] ?? {}) }; + s.counts = { ...(s.counts ?? {}), [key]: (s.counts?.[key] ?? 0) + n }; + all[mode] = s; + writeAll(slug, all, storage); + return s.counts[key]; +} + +export function formatTime(ms) { + if (ms == null) return '—'; + const t = Math.floor(ms / 1000); + const h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), sec = t % 60; + const mm = h ? String(m).padStart(2, '0') : String(m); + return `${h ? `${h}:` : ''}${mm}:${String(sec).padStart(2, '0')}`; +} diff --git a/tools/verifyFreecell.js b/tools/verifyFreecell.js new file mode 100644 index 0000000..12b19a4 --- /dev/null +++ b/tools/verifyFreecell.js @@ -0,0 +1,387 @@ +#!/usr/bin/env node +// verifyFreecell.js — headless checks for the Night Study Freecell: the rules +// engine (deal, every move type, the supermove limit, safe auto-play, undo +// snapshots, numbered/daily deals), the solver (solves deals, every line +// replays legally, honest "unsolvable"), the scene's decisions (what a press +// picks up, drop targets, smart-click ranking, refusal reasons), the desk +// layout (19-card columns fit, nothing under the HUD) and the records store. +// Usage: node tools/verifyFreecell.js [--quick] + +import { Card } from '../src/games/cards/Deck.js'; +import { + FreecellEngine, freshDeck, deckForDeal, dailyDealNumber, randomDealNumber, MAX_DEAL, FOUNDATION_ORDER, +} from '../src/games/freecell/FreecellLogic.js'; +import { FreecellSolver, stateFromEngine, autoSafe, exactKey, stateKey } from '../src/games/freecell/FreecellSolver.js'; +import { + W, H, S, CW, CH, colX, cellPose, foundPose, foundCardPose, columnPosesFor, columnZone, cellZone, foundZone, hudRects, + MAX_BOTTOM, TAB_TOP, BLOTTER, DECK, +} from '../src/games/freecell/FreecellTable.js'; +import { cardBounds, columnPoses } from '../src/ui/solitaire/SolitaireGeometry.js'; +import { recordGame, loadStats, recordBest, formatTime } from '../src/ui/solitaire/SolitaireStats.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import FreecellGame from '../src/games/freecell/FreecellGame.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}`); + +const PV = { A: 1, T: 10, J: 11, Q: 12, K: 13 }; +let nid = 500; +const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++, pval: PV[key[0]] ?? Number(key[0]) }); +const cards = (s) => (s ? s.split(' ').map(C) : []); + +/** Build an engine from a sketch: cols = ['Ks Qh', …] (bottom → top), cells = ['Ah', null…], found = { s: 3, … }. */ +function pos({ cols = [], cells = [], found = {} }) { + const snap = { + tableau: Array.from({ length: 8 }, (_, i) => cards(cols[i] ?? '')), + freecells: [0, 1, 2, 3].map(i => (cells[i] ? C(cells[i]) : null)), + foundations: Object.fromEntries(FOUNDATION_ORDER.map(s => { + const n = found[s] ?? 0; + return [s, Array.from({ length: n }, (_, k) => C(`${['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'][k]}${s}`))]; + })), + moveCount: 0, + }; + return FreecellEngine.fromSnapshot(snap); +} +const M = (fromKind, fi, toKind, ti, n = 1) => ({ from: { kind: fromKind, i: fi }, to: { kind: toKind, ...(ti != null ? { i: ti } : {}) }, n }); +const keysOf = (e) => e.allCards().map(c => c.key).sort().join(','); +const FULL = (() => { const d = freshDeck(); return d.map(c => c.key).sort().join(','); })(); + +// ── Deal ───────────────────────────────────────────────────────────────────── +section('Deal'); +{ + const e = FreecellEngine.fromDeal(1); + ok('52 cards dealt', e.allCards().length === 52); + ok('every card once', keysOf(e) === FULL); + ok('ids unique', new Set(e.allCards().map(c => c.id)).size === 52); + ok('columns 7,7,7,7,6,6,6,6', e.tableau.map(c => c.length).join(',') === '7,7,7,7,6,6,6,6'); + ok('cells + foundations empty', e.freecells.every(c => c === null) && e.homeCount() === 0); + ok('deal is numbered', e.deal === 1); + const a = deckForDeal(12345).map(c => c.key).join(), b = deckForDeal(12345).map(c => c.key).join(), c = deckForDeal(12346).map(c => c.key).join(); + ok('same number → same deal', a === b); + ok('different number → different deal', a !== c); + const d1 = dailyDealNumber(new Date(2026, 10, 25)), d2 = dailyDealNumber(new Date(2026, 10, 25, 23, 59)), d3 = dailyDealNumber(new Date(2026, 10, 26)); + ok('daily deal stable through the day', d1 === d2); + ok('daily deal changes each day', d1 !== d3); + ok('daily deal in range', d1 >= 1 && d1 <= MAX_DEAL); + const rng = mulberry32(9); + ok('random deal numbers in range', Array.from({ length: 200 }, () => randomDealNumber(rng)).every(n => n >= 1 && n <= MAX_DEAL)); +} + +// ── Moves ──────────────────────────────────────────────────────────────────── +section('Moves'); +{ + let e = pos({ cols: ['5s Ah', '9d 8c', '7h', ''], cells: ['2h'] }); + ok('ace goes home', e.isLegal(M('col', 0, 'found'))); + ok('two can\'t go home before its ace', !e.isLegal(M('cell', 0, 'found'))); + e.apply(M('col', 0, 'found')); + ok('then the two can', e.isLegal(M('cell', 0, 'found'))); + ok('7♥ onto 8♣', e.isLegal(M('col', 2, 'col', 1))); + ok('5♠ not onto 7♥', !e.isLegal(M('col', 0, 'col', 2))); + ok('any card to an empty column', e.isLegal(M('col', 0, 'col', 3))); + ok('cell card onto a column needs a fit', !e.isLegal(M('cell', 0, 'col', 1))); + ok('cell card to empty column', e.isLegal(M('cell', 0, 'col', 3))); + ok('cell to cell is not a move', !e.isLegal(M('cell', 0, 'cell', 1))); + ok('column card to a free cell', e.isLegal(M('col', 2, 'cell', 1))); + ok('not into a taken cell', !e.isLegal(M('col', 2, 'cell', 0))); + const before = e.moveCount; + const moved = e.apply(M('col', 2, 'col', 1)); + ok('apply returns the moved cards', moved.length === 1 && moved[0].key === '7h'); + ok('move counted', e.moveCount === before + 1); + ok('illegal apply does nothing', e.apply(M('col', 0, 'col', 1)).length === 0 && e.moveCount === before + 1); + e = pos({ cols: ['Ks', 'Kh'], cells: ['Qs', 'Qh', 'Qd', 'Qc'] }); + ok('full cells: no cell move', !e.isLegal(M('col', 0, 'cell'))); + // classic wrappers still work + e = pos({ cols: ['Ah', '3s', '4h'], cells: [] }); + ok('moveToFoundation wrapper', e.moveToFoundation('tableau', 0) === true); + ok('moveRun wrapper', e.moveRun(1, 0, 2) === true && e.tableau[2].length === 2); + ok('moveToFreecell wrapper', e.moveToFreecell(2) === true && e.freecells[0]?.key === '3s'); +} + +// ── Supermoves ─────────────────────────────────────────────────────────────── +section('Supermove limit'); +{ + // a 4-card run in col 0, a black 9 in col 1 to receive it (8♥ 7♠ 6♥ 5♠) + const fill = ['Kc', 'Kd', 'Ks', 'Kh']; + let e = pos({ cols: ['8h 7s 6h 5s', '9c', 'Qc', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: fill }); + ok('no cells, no columns → move 1', e.maxMovable(1) === 1); + ok('the 4-card run is blocked by space', e.runBlocker(0, 0, 1) === 'space'); + ok('…but the single top card isn\'t limited', e.maxMovable() >= 1); + e = pos({ cols: ['8h 7s 6h 5s', '9c', 'Qc', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: ['Kc', 'Kd', 'Ks'] }); + ok('1 free cell → 2', e.maxMovable(1) === 2); + e = pos({ cols: ['8h 7s 6h 5s', '9c', '', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: ['Kc', 'Kd', 'Ks'] }); + ok('1 cell + 1 empty column → 4', e.maxMovable(1) === 4); + ok('the 4-card run now fits', e.canMoveRun(0, 0, 1)); + ok('into the empty column itself → 2', e.maxMovable(2) === 2); + ok('4 cards into that empty column: no room', e.runBlocker(0, 0, 2) === 'space'); + ok('2 cards into it: fine', e.canMoveRun(0, 2, 2)); + e = pos({ cols: ['8h 7s 6h 5s', '9c', '', '', 'Qs', 'Qh', 'Jc', 'Jd'], cells: [] }); + ok('4 cells + 2 empty columns → 20', e.maxMovable(1) === 20); + ok('…onto an empty column → 10', e.maxMovable(2) === 10); + e = pos({ cols: ['8h 7s 5h', '9c'] }); + ok('an unordered run can\'t move', e.runBlocker(0, 0, 1) === 'unordered'); + e = pos({ cols: ['8h 7s 6h', 'Tc'] }); + ok('a run that doesn\'t fit', e.runBlocker(0, 0, 1) === 'mismatch'); + ok('runStart finds the ordered tail', pos({ cols: ['2c 9h 8s 7d'] }).runStart(0) === 1); +} + +// ── Safe auto-play ─────────────────────────────────────────────────────────── +section('Safe auto-play'); +{ + let e = pos({ cols: ['3h'], found: { h: 2, s: 1, c: 2 } }); + ok('3♥ not safe while 2♠ is out', !e.isSafeHome(e.tableau[0][0])); + e = pos({ cols: ['3h'], found: { h: 2, s: 2, c: 2 } }); + ok('3♥ safe once both black twos are home', e.isSafeHome(e.tableau[0][0])); + e = pos({ cols: ['Ac', '2c'], found: {} }); + ok('aces always safe', e.isSafeHome(e.tableau[0][0])); + e = pos({ cols: ['5s'], cells: ['Ad'], found: {} }); + ok('cells are checked first', JSON.stringify(e.nextSafeMove()) === JSON.stringify(M('cell', 0, 'found'))); + // engine safe sequence == solver autoSafe on random mid-game positions + let same = true; + for (let d = 1; d <= 30; d++) { + const g = FreecellEngine.fromDeal(d); + const rng = mulberry32(d); + for (let k = 0; k < 25; k++) { const ms = g.legalMoves(); if (!ms.length) break; g.apply(ms[Math.floor(rng() * ms.length)]); } + const st = stateFromEngine(g); + autoSafe(st); + for (let m = g.nextSafeMove(); m; m = g.nextSafeMove()) g.apply(m); + if (exactKey(st) !== exactKey(stateFromEngine(g))) same = false; + } + ok('engine safe plays match the solver\'s', same); +} + +// ── Legal moves, conservation, undo snapshots ──────────────────────────────── +section('Random play: legality, conservation, snapshots'); +{ + let allLegal = true, conserved = true, roundTrip = true, countsOk = true; + const games = QUICK ? 40 : 160; + for (let d = 1; d <= games; d++) { + const e = FreecellEngine.fromDeal(1000 + d); + const rng = mulberry32(d * 7); + const snaps = []; + for (let k = 0; k < 120; k++) { + const ms = e.legalMoves(); + if (!ms.length) break; + for (const m of ms) if (!e.isLegal(m)) allLegal = false; + snaps.push({ snap: e.snapshot(), key: exactKey(stateFromEngine(e)), n: e.moveCount }); + const m = ms[Math.floor(rng() * ms.length)]; + const before = e.moveCount; + if (!e.apply(m).length) allLegal = false; + if (e.moveCount !== before + 1) countsOk = false; + if (keysOf(e) !== FULL) conserved = false; + } + // unwind: every snapshot restores exactly + for (let i = snaps.length - 1; i >= 0; i--) { + e.restore(snaps[i].snap); + if (exactKey(stateFromEngine(e)) !== snaps[i].key || e.moveCount !== snaps[i].n) roundTrip = false; + } + } + ok('every listed move is legal and applies', allLegal); + ok('52 cards conserved through every move', conserved); + ok('each move counts once', countsOk); + ok('snapshots restore exactly (undo)', roundTrip); + const e = FreecellEngine.fromDeal(77); + const s0 = e.snapshot(); + e.apply(e.legalMoves()[0]); + ok('snapshot is a copy, not a reference', s0.tableau.map(c => c.length).join() === '7,7,7,7,6,6,6,6'); +} + +// ── Solver ─────────────────────────────────────────────────────────────────── +section('Solver'); +{ + const N = QUICK ? 15 : 60; + let solved = 0, replayOk = true, worst = 0, total = 0; + for (let d = 1; d <= N; d++) { + const e = FreecellEngine.fromDeal(d); + const t0 = performance.now(); + const r = new FreecellSolver(e).run(); + const ms = performance.now() - t0; + total += ms; worst = Math.max(worst, ms); + if (r.status !== 'solved') continue; + solved++; + for (const m of r.moves) if (!e.apply(m).length) { replayOk = false; break; } + if (!e.isWon()) replayOk = false; + } + ok(`solves ≥ 97% of the first ${N} deals`, solved >= Math.ceil(N * 0.97), `${solved}/${N}`); + ok('every solution replays to a win on the engine', replayOk); + ok('average solve under 250 ms', total / N < 250, `${(total / N).toFixed(0)} ms`); + console.log(` solver: ${solved}/${N} deals, avg ${(total / N).toFixed(0)} ms, worst ${worst.toFixed(0)} ms`); + + // mid-game positions solve and replay too + let midOk = true, midSolved = 0; + for (let d = 1; d <= (QUICK ? 8 : 25); d++) { + const e = FreecellEngine.fromDeal(d + 300); + const first = new FreecellSolver(e).run(); + if (first.status !== 'solved') continue; + for (const m of first.moves.slice(0, 30)) e.apply(m); + const r = new FreecellSolver(e).run(); + if (r.status !== 'solved') continue; + midSolved++; + for (const m of r.moves) if (!e.apply(m).length) { midOk = false; break; } + if (!e.isWon()) midOk = false; + } + ok('mid-game positions solve and replay', midOk && midSolved > 0, `${midSolved}`); + + // a dead position: cells full of kings, every column topped by a black card, aces buried + const dead = pos({ + cols: ['Ah 5d 7d Qs', 'Ad 5h 7h Qc', 'As 9h 9d Js', 'Ac Th Td Jc', '2h 2d 3h 3d 4h Ts', '4d 6h 6d 8h 8d Tc', '2s 3s 4s 5s 6s 7s 8s 9s', '2c 3c 4c 5c 6c 7c 8c Jh Jd Qh Qd 9c'], + cells: ['Ks', 'Kh', 'Kd', 'Kc'], + }); + ok('dead position is a full deck', keysOf(dead) === FULL); + ok('dead position: no legal moves', dead.legalMoves().length === 0); + const rd = new FreecellSolver(dead).run(); + ok('solver says unsolvable (honestly)', rd.status === 'unsolvable'); + // a tiny budget gives up rather than lying + const hard = new FreecellSolver(FreecellEngine.fromDeal(5), { maxNodes: 3 }).run(); + ok('out of budget → "gaveup", never "unsolvable"', hard.status === 'gaveup' || hard.status === 'solved'); + // canonical keys: swapping two columns is the same position, but not the same exact key + const a = stateFromEngine(pos({ cols: ['Ks', 'Qh'] })), b = stateFromEngine(pos({ cols: ['Qh', 'Ks'] })); + ok('canonical key ignores column order', stateKey(a) === stateKey(b)); + ok('exact key keeps column order (hint replay safety)', exactKey(a) !== exactKey(b)); + // time-slicing gives the same answer as one go + const e1 = FreecellEngine.fromDeal(42); + const sliced = new FreecellSolver(e1); + let steps = 0; + while (!sliced.step(50)) steps++; + const whole = new FreecellSolver(FreecellEngine.fromDeal(42)).run(); + ok('step(budget) is resumable and deterministic', sliced.result.status === whole.status && sliced.result.moves?.length === whole.moves?.length && steps > 0); +} + +// ── Auto-complete ──────────────────────────────────────────────────────────── +section('Auto-complete'); +{ + const e = pos({ cols: ['Kh Qh Jh', 'Ks', 'Kd', 'Kc'], cells: ['Th'], found: { s: 12, d: 12, c: 12, h: 9 } }); + ok('canAutoComplete when only foundation plays remain', e.canAutoComplete()); + let n = 0; + for (let s = e.autoCompleteStep(); s && n < 60; s = e.autoCompleteStep(), n++) e.apply(s.move); + ok('auto-complete clears the board', e.isWon(), `${e.homeCount()} home`); + const stuck = pos({ cols: ['Ah 2h', 'Ks'], found: {} }); + ok('a buried ace blocks auto-complete', !stuck.canAutoComplete()); +} + +// ── Scene decisions (FreecellGame logic, no Phaser) ────────────────────────── +section('Scene: picking, targets, smart click, reasons'); +{ + const g = new FreecellGame(); + g.settings = { autoPlay: true, analysis: true, click: 'smart', anim: 'normal' }; + g.gs = pos({ cols: ['9d 8c', '7h', 'Ah', '5s 4h 3s', '', 'Qs', 'Kd 2c', 'Td'], cells: ['6c'] }); + const poses = (c) => columnPosesFor(c, g.gs.tableau[c].length); + const top = (c) => poses(c)[g.gs.tableau[c].length - 1]; + let src = g.pickAt(top(1)); + ok('a press on a top card picks it', src?.kind === 'col' && src.i === 1 && src.n === 1 && src.ids.length === 1); + src = g.pickAt({ x: poses(3)[0].x, y: poses(3)[0].y - CH * 0.3 }); + ok('a press on a buried card picks the run from it', src?.kind === 'col' && src.i === 3 && src.idx === 0 && src.n === 3); + ok('press on a free-cell card', g.pickAt(cellPose(0))?.kind === 'cell'); + ok('press on empty felt picks nothing', g.pickAt({ x: colX(4), y: TAB_TOP }) === null); + ok('press on a foundation picks nothing', g.pickAt(foundPose(0)) === null); + const best = (s) => g.bestMove(s); + const m1 = best(g.pickAt(top(2))); + ok('smart click sends an ace home', m1?.to.kind === 'found'); + const m2 = best(g.pickAt(top(1))); + ok('smart click builds 7♥ onto 8♣', m2?.to.kind === 'col' && m2.to.i === 0); + const m3 = best(g.pickAt(cellPose(0))); + ok('smart click plays the cell 6♣ onto 7♥', m3?.to.kind === 'col' && m3.to.i === 1); + const tgts = g.movesFor(g.pickAt(top(5))); + ok('drag targets include every empty cell', tgts.filter(t => t.kind === 'cell').length === 3); + ok('drag targets include the empty column', tgts.some(t => t.kind === 'col' && t.move.to.i === 4)); + ok('targets have anchors on screen', tgts.every(t => t.anchor.x > 0 && t.anchor.x < W && t.anchor.y > 0 && t.anchor.y < H)); + ok('every target move is legal', tgts.every(t => g.gs.isLegal(t.move))); + // reasons + const unordered = pos({ cols: ['9d 3c 8c'] }); + g.gs = unordered; + ok('grabbing an unordered run is refused with a reason', /ordered/.test(g.grabBlocker({ kind: 'col', i: 0, idx: 0, n: 3 }) ?? '')); + g.gs = pos({ cols: ['8h 7s 6h 5s', '9c', 'Qc', 'Qd', 'Qs', 'Qh', 'Jc', 'Jd'], cells: ['Kc', 'Kd', 'Ks', 'Kh'] }); + ok('too-long run explains the room', /room to move 1/.test(g.noMoveReason({ kind: 'col', i: 0, idx: 0, n: 4 }))); + ok('drop explains space', /move 1/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 0, n: 4 }, { x: colX(1), y: TAB_TOP }) ?? '')); + ok('drop explains colours', /goes on a red 6/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 3, n: 1 }, { x: colX(2), y: TAB_TOP }) ?? '')); + ok('drop explains the foundation', /spades need the Ace/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 3, n: 1 }, foundPose(0)) ?? '')); + ok('drop explains a taken cell', /taken/.test(g.dropBlocker({ kind: 'col', i: 0, idx: 3, n: 1 }, cellPose(1)) ?? '')); + // auto-play hook + g.gs = pos({ cols: ['5s Ac'], found: {} }); + ok('auto-play offers the safe ace', g.nextAutoMove()?.to.kind === 'found'); + g.settings.autoPlay = false; + ok('auto-play off → nothing', g.nextAutoMove() === null); + g.finishing = true; + ok('finishing always plays home', g.nextAutoMove()?.to.kind === 'found'); + g.finishing = false; + // fallback hint is a legal move + g.gs = FreecellEngine.fromDeal(9); + const fb = g.fallbackMove(); + ok('fallback hint is legal', fb && g.gs.isLegal(fb)); + // the layout lists all 52 cards + const { visible } = g.computeLayout(); + ok('layout places all 52 cards', visible.size === 52); + ok('layout poses are flat (q = 1)', [...visible.values()].every(v => v.pose.q === 1)); +} + +// ── Desk layout ────────────────────────────────────────────────────────────── +section('Desk layout'); +{ + const huds = hudRects(); + const rectsOverlap = (a, b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; + let fits = true, clear = true, onScreen = true, minStep = Infinity; + for (let c = 0; c < 8; c++) { + for (let n = 1; n <= 19; n++) { + const ps = columnPosesFor(c, n); + const last = cardBounds(ps[n - 1]); + if (last.y1 > MAX_BOTTOM + 0.5) fits = false; + for (const p of ps) { + const b = cardBounds(p); + if (b.x0 < 0 || b.x1 > W || b.y0 < 0 || b.y1 > H) onScreen = false; + for (const h of huds) if (rectsOverlap(b, h.r)) clear = false; + } + if (n > 1) minStep = Math.min(minStep, ps[1].y - ps[0].y); + } + } + ok('19-card columns fit above the bottom edge', fits); + ok('column cards never sit under the HUD', clear); + ok('column cards stay on screen', onScreen); + ok('fan step stays readable (≥ 25 px)', minStep >= 25, `${minStep.toFixed(1)}`); + const slotsClear = [0, 1, 2, 3].every(i => huds.every(h => !rectsOverlap(cardBounds(cellPose(i)), h.r) && !rectsOverlap(cardBounds(foundPose(i)), h.r))); + ok('cells + foundations clear of the HUD', slotsClear); + let zonesApart = true; + for (let a = 0; a < 8; a++) for (let b = a + 1; b < 8; b++) if (rectsOverlap(columnZone(a), columnZone(b))) zonesApart = false; + ok('column drop zones don\'t overlap', zonesApart); + let slotZones = true; + const zs = [0, 1, 2, 3].flatMap(i => [cellZone(i), foundZone(i)]); + for (let a = 0; a < zs.length; a++) for (let b = a + 1; b < zs.length; b++) if (rectsOverlap(zs[a], zs[b])) slotZones = false; + ok('cell + foundation drop zones don\'t overlap', slotZones); + ok('cards sit on the blotter', [0, 7].every(c => { const b = cardBounds(columnPosesFor(c, 1)[0]); return b.x0 >= BLOTTER.x0 && b.x1 <= BLOTTER.x1; })); + ok('the deck sits off the blotter', cardBounds(DECK).x1 < BLOTTER.x0); + ok('foundation pile grows but stays put', Math.abs(foundCardPose(0, 12).y - foundPose(0).y) <= 3); + const sq = columnPoses(25, null, { x: 100, top: 100, s: 1, maxBottom: 600, step: 34, minStep: 16 }); + ok('columnPoses squeezes long columns', sq[24].y + 134 / 2 <= 600 + 0.5); + const fd = columnPoses(6, [false, false, false, true, true, true], { x: 0, top: 0, s: 1, step: 30, downStep: 10 }); + ok('face-down cards use the tighter step', fd[1].y - fd[0].y === 10 && fd[4].y - fd[3].y === 30); + ok('card scale is the desk scale', Math.abs(CW - 96 * S) < 0.01 && Math.abs(CH - 134 * S) < 0.01); +} + +// ── Records ────────────────────────────────────────────────────────────────── +section('Records (SolitaireStats)'); +{ + const mem = new Map(); + const store = { getItem: (k) => mem.get(k) ?? null, setItem: (k, v) => mem.set(k, v) }; + recordGame('t', { won: true, time: 90000, moves: 110 }, store); + let r = recordGame('t', { won: true, time: 80000, moves: 120 }, store); + ok('second win: streak 2', r.stats.streak === 2 && r.stats.bestStreak === 2); + ok('faster time is a new best', r.newBest.time === true && r.stats.bestTime === 80000); + ok('more moves is not a best', !r.newBest.moves && r.stats.fewestMoves === 110); + r = recordGame('t', { won: false }, store); + ok('a loss resets the streak, keeps the best', r.stats.streak === 0 && r.stats.bestStreak === 2); + const st = loadStats('t', 'default', store); + ok('played/won tallied', st.played === 3 && st.won === 2); + ok('recent list newest-first', st.recent[0].won === false && st.recent.length === 3); + ok('modes are separate', loadStats('t', 'other', store).played === 0); + ok('first best isn\'t "beaten"', recordBest('t', 'golf', 12, {}, store) === false); + ok('a lower score beats it', recordBest('t', 'golf', 8, {}, store) === true); + ok('a higher one doesn\'t', recordBest('t', 'golf', 20, {}, store) === false); + ok('formatTime', formatTime(65000) === '1:05' && formatTime(3725000) === '1:02:05' && formatTime(null) === '—'); + ok('no storage → no crash', (() => { try { recordGame('x', { won: true }, { getItem() { throw new Error('nope'); }, setItem() { throw new Error('nope'); } }); return true; } catch { return false; } })()); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/tools/verifySolitaireTour.js b/tools/verifySolitaireTour.js new file mode 100644 index 0000000..e6e79ba --- /dev/null +++ b/tools/verifySolitaireTour.js @@ -0,0 +1,343 @@ +#!/usr/bin/env node +// verifySolitaireTour.js — headless checks for the five-stop Solitaire Tour: +// each engine's rules (Golf, Klondike, Pyramid, Take Fourteen, Three Shuffles +// and a Draw), random play (every listed move applies, 52 cards conserved, +// snapshots + save/load round-trip), the seeded reshuffle (undo can't re-roll +// it), Klondike's stuck test, the leg controllers (layout, picking, targets, +// smart-click ranking, partners, reasons, auto-play) and the room layouts +// (cards on the table, never under the scorecard / plate / dock). +// Usage: node tools/verifySolitaireTour.js [--quick] + +import { + TOUR, GAME_META, createEngine, engineFromSave, encode, decode, cardById, freshDeck, + GolfEngine, KlondikeEngine, PyramidEngine, FourteenEngine, ThreeShufflesEngine, +} from '../src/games/solitairetour/SolitaireTourLogic.js'; +import { legFor, remainingCards, homeStacks } from '../src/games/solitairetour/SolitaireTourLegs.js'; +import { hudRects, PLAY, W, H, KLON, PYR, THREE, GOLF } from '../src/games/solitairetour/SolitaireTourTable.js'; +import { cardBounds } from '../src/ui/solitaire/SolitaireGeometry.js'; +import { bumpCount, loadStats, recordBest } from '../src/ui/solitaire/SolitaireStats.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { MAP, STOPS, mapXY, THEMES } from '../src/games/solitairetour/SolitaireTourArt.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}`); +const C = (key) => { + const RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']; + const SUITS = ['s', 'h', 'd', 'c']; + return cardById(SUITS.indexOf(key[1]) * 13 + RANKS.indexOf(key[0])); +}; +const cs = (s) => (s ? s.split(' ').map(C) : []); +const FULL = freshDeck(() => 0.5).map(c => c.id).sort((a, b) => a - b).join(); +const idsOf = (e) => e.allCards().map(c => c.id).sort((a, b) => a - b).join(); +const rectsOverlap = (a, b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; + +// ── Cards + saves ──────────────────────────────────────────────────────────── +section('Cards + saves'); +{ + ok('52 canonical cards', new Set(Array.from({ length: 52 }, (_, i) => cardById(i).key)).size === 52); + ok('ids are stable per card', C('Ah').id === cardById(C('Ah').id).id && C('As').id !== C('Ah').id); + ok('point values A=1 … K=13', C('As').pval === 1 && C('Ts').pval === 10 && C('Ks').pval === 13); + const d1 = freshDeck(mulberry32(5)).map(c => c.key).join(), d2 = freshDeck(mulberry32(5)).map(c => c.key).join(); + ok('seeded decks repeat', d1 === d2); + const snap = { a: [C('Qh'), { card: C('2c'), faceUp: false }], n: 3, inf: null }; + const back = decode(JSON.parse(JSON.stringify(encode(snap)))); + ok('encode/decode round trip', back.a[0] === C('Qh') && back.a[1].card === C('2c') && back.a[1].faceUp === false && back.n === 3); + ok('every leg has its meta', TOUR.every(t => GAME_META[t]?.name && GAME_META[t].venue && GAME_META[t].blurb && GAME_META[t].greet)); +} + +// ── Golf ───────────────────────────────────────────────────────────────────── +section('Golf'); +{ + const e = createEngine('golf', mulberry32(1)); + ok('7 columns of 5, 1 on the foundation, 16 in stock', e.tableau.every(p => p.length === 5) && e.foundation.length === 1 && e.stock.length === 16); + e.restore({ tableau: [cs('2s 9h'), cs('Ks'), cs('Qd'), [], [], [], []], foundation: cs('8c'), stock: cs('5d'), run: 0, moveCount: 0 }); + ok('one rank away plays', e.canPlay(C('9h'))); + ok('two away does not', !e.canPlay(C('Qd'))); + e.apply({ t: 'gplay', col: 0 }); + ok('run counts tableau plays', e.run === 1); + e.restore({ ...e.snapshot(), foundation: cs('Ac') }); + ok('no wrap: K doesn\'t play on A', !e.canPlay(C('Ks'))); + ok('…and 2 does', e.canPlay(C('2s'))); + e.apply({ t: 'gstock' }); + ok('stock resets the run', e.run === 0 && e.foundationTop().key === '5d'); + ok('cleared columns win even with stock left', new GolfEngine(freshDeck()).isWon() === false); +} + +// ── Klondike ───────────────────────────────────────────────────────────────── +section('Klondike'); +{ + const e = createEngine('klondike', mulberry32(2)); + ok('1…7 dealt, tops face up', e.tableau.every((p, c) => p.length === c + 1 && p.every((x, k) => x.faceUp === (k === c)))); + ok('24 in stock', e.stock.length === 24 && e.waste.length === 0); + const T = (spec) => spec.split('|').map(col => (col ? col.split(' ').map(t => ({ card: C(t.replace('*', '')), faceUp: !t.endsWith('*') })) : [])); + e.restore({ tableau: T('4c* 9h|8s|Kd|||Ts|'), stock: [], waste: cs('Qs'), foundations: { s: [], h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + ok('black 8 goes on red 9', e.canStack(C('8s'), 0) && !e.canStack(C('8s'), 2)); + ok('only a King fills an empty column', e.canStack(C('Kd'), 3) && !e.canStack(C('Qs'), 3)); + ok('moving a run flips the card underneath', e.apply({ t: 'krun', col: 0, idx: 1, to: 2 }).length === 0 && e.apply({ t: 'krun', col: 1, idx: 0, to: 0 }).length === 1); + e.apply({ t: 'krun', col: 0, idx: 1, to: 5 }); + ok('…and the covered 4♣ turns face up', e.tableau[0][0].faceUp === true); + e.restore({ tableau: T('|||||||'), stock: cs('3d 2d'), waste: [], foundations: { s: [], h: [], d: cs('Ad'), c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + e.apply({ t: 'kstock' }); + ok('turning the stock puts its top on the waste', e.wasteTop().key === '2d'); + ok('waste plays home', e.apply({ t: 'kwf' }).length === 1); + e.apply({ t: 'kstock' }); e.apply({ t: 'kstock' }); + ok('empty stock recycles the waste', e.stock.length === 1 && e.waste.length === 0 && e.stock[0].key === '3d'); + // stuck detection with unlimited recycling + e.restore({ tableau: T('Ks||||||'), stock: cs('5h 9c'), waste: cs('3s'), foundations: { s: [], h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + ok('stuck when no stock/waste card can ever play', e.isStuck() === true && e.hasMoves() === true); + e.restore({ ...e.snapshot(), stock: cs('5h As') }); + ok('not stuck while an ace waits in the stock', e.isStuck() === false); + // auto-finish + safe home + e.restore({ tableau: T('2s|Ah 2h||||||'.replace('|||||||', '||||')), stock: [], waste: [], foundations: { s: cs('As'), h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + ok('a buried ace blocks auto-finish', !e.canAutoFinish()); + e.restore({ tableau: T('2s|2h|Ah||||'), stock: [], waste: [], foundations: { s: cs('As'), h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + ok('auto-finish when everything can go home', e.canAutoFinish() === true); + e.restore({ tableau: T('3h|||||||'), stock: [], waste: [], foundations: { s: cs('As 2s'), h: cs('Ah 2h'), d: [], c: cs('Ac') }, recyclesLeft: Infinity, moveCount: 0 }); + ok('3♥ not safe until both black twos are home', !e.isSafeHome(C('3h'))); + e.restore({ ...e.snapshot(), foundations: { s: cs('As 2s'), h: cs('Ah 2h'), d: [], c: cs('Ac 2c') } }); + ok('…then it is', e.isSafeHome(C('3h'))); +} + +// ── Pyramid ────────────────────────────────────────────────────────────────── +section('Pyramid'); +{ + const e = createEngine('pyramid', mulberry32(3)); + ok('28 in the pyramid, 24 in stock, 3 passes', e.rows.flat().length === 28 && e.stock.length === 24 && e.passesLeft === 3); + ok('only the bottom row is uncovered at the start', e.availableLocs().filter(l => l.area === 'pyramid').every(l => l.r === 6)); + const rows = Array.from({ length: 7 }, (_, r) => Array(r + 1).fill(null)); + rows[6][0] = C('5s'); rows[6][1] = C('8h'); rows[5][0] = C('Kd'); + e.restore({ rows, stock: [], waste: cs('Qc'), discard: [], passesLeft: 3, moveCount: 0 }); + ok('covered card isn\'t available', !e.available(5, 0)); + const partners = e.partnersOf({ area: 'pyramid', r: 6, i: 0 }); + ok('5 + 8 = 13 partners', partners.length === 1 && partners[0].i === 1); + ok('the waste card counts', e.availableLocs().some(l => l.area === 'waste')); + e.apply({ t: 'ppair', a: { area: 'pyramid', r: 6, i: 0 }, b: { area: 'pyramid', r: 6, i: 1 } }); + ok('pair goes to the discard', e.discard.length === 2 && e.available(5, 0)); + ok('kings clear alone', e.apply({ t: 'pking', loc: { area: 'pyramid', r: 5, i: 0 } }).length === 1); + ok('pyramid gone → won (stock doesn\'t matter)', e.isWon()); + const f = createEngine('pyramid', mulberry32(4)); + let n = 0; + while (f.apply({ t: 'pstock' }).length && n < 500) n++; + ok('stock: 4 times through (3 recycles), then done', n === 24 * 4 + 3 && f.passesLeft === 0, `${n}`); +} + +// ── Take Fourteen ──────────────────────────────────────────────────────────── +section('Take Fourteen'); +{ + const e = createEngine('fourteen', mulberry32(5)); + ok('12 piles: four of 5, eight of 4', e.piles.map(p => p.length).join() === '5,5,5,5,4,4,4,4,4,4,4,4'); + e.restore({ piles: [cs('Ah'), cs('Ks'), cs('7c'), cs('7d'), cs('6h'), [], [], [], [], [], [], []], discard: [], moveCount: 0 }); + ok('A + K = 14', e.partnersOf(0).join() === '1'); + ok('7 + 7 = 14', e.partnersOf(2).join() === '3'); + ok('6 has no partner here', e.partnersOf(4).length === 0); + e.apply({ t: 'fpair', a: 2, b: 3 }); + ok('pair goes to the discard', e.discard.length === 2 && !e.piles[2].length); + ok('a non-pair is refused', e.apply({ t: 'fpair', a: 0, b: 4 }).length === 0); +} + +// ── Three Shuffles and a Draw ──────────────────────────────────────────────── +section('Three Shuffles and a Draw'); +{ + const e = createEngine('threeshuffles', mulberry32(6)); + ok('17 fans of 3 + 1 single', e.piles.length === 18 && e.piles.slice(0, 17).every(p => p.length === 3) && e.piles[17].length === 1); + e.restore({ piles: [cs('9s 8s'), cs('7s'), cs('7h'), [], cs('As')], foundations: { s: [], h: [], d: [], c: [] }, shufflesLeft: 2, drawsLeft: 1, seed: 99, moveCount: 0 }); + ok('builds down in suit', e.canStack(C('7s'), 0) && !e.canStack(C('7h'), 0)); + ok('empty spaces stay empty', !e.canStack(C('7h'), 3)); + ok('ace goes home', e.apply({ t: 'tfound', p: 4 }).length === 1); + ok('no Draw before the shuffles are spent', !e.canDraw()); + // the reshuffle is seeded: undo + shuffle again gives the same fans + const g = createEngine('threeshuffles', mulberry32(7)); + const s0 = g.snapshot(); + g.apply({ t: 'tredeal' }); + const after1 = g.piles.map(p => p.map(c => c.key).join()).join('|'); + g.restore(s0); + g.apply({ t: 'tredeal' }); + const after2 = g.piles.map(p => p.map(c => c.key).join()).join('|'); + ok('undo can\'t re-roll a shuffle', after1 === after2); + ok('a shuffle keeps all the cards', idsOf(g) === FULL); + g.apply({ t: 'tredeal' }); + ok('two reshuffles, then none', g.shufflesLeft === 0 && g.apply({ t: 'tredeal' }).length === 0); + ok('then the Draw is open', g.canDraw()); + const buried = g.piles.find(p => p.length > 1)[0]; + ok('the Draw lifts a buried card into its own fan', g.apply({ t: 'tdraw', id: buried.id }).length === 1 && g.piles[g.piles.length - 1][0] === buried); + ok('only one Draw', !g.canDraw()); + e.restore({ piles: [cs('2s'), cs('As')], foundations: { s: [], h: [], d: [], c: [] }, shufflesLeft: 0, drawsLeft: 0, seed: 1, moveCount: 0 }); + ok('foundation-only finish detected', e.canAutoFinish()); +} + +// ── Random play: legality, conservation, snapshots, saves ─────────────────── +section('Random play (all five games)'); +{ + const games = QUICK ? 40 : 150; + for (const type of TOUR) { + let legal = true, conserved = true, trips = true, saveOk = true, layoutOk = true, valueOk = true; + for (let gi = 0; gi < games; gi++) { + const rng = mulberry32(gi * 31 + type.length); + const e = createEngine(type, rng); + const leg = legFor(e); + const snaps = []; + for (let k = 0; k < 300; k++) { + let ms = e.legalMoves().filter(m => m.t !== 'tdraw'); + if (e.canDraw?.() && rng() < 0.3) { const p = e.piles.find(x => x.length > 1); ms.push({ t: 'tdraw', id: p[0].id }); } + if (!ms.length) break; + const prog = ms.filter(m => !['gstock', 'kstock', 'pstock', 'tredeal'].includes(m.t)); + const pool = prog.length && rng() < 0.85 ? prog : ms; + const m = pool[Math.floor(rng() * pool.length)]; + snaps.push(JSON.stringify(encode(e.snapshot()))); + if (!e.apply(m).length) { legal = false; break; } + if (idsOf(e) !== FULL) conserved = false; + if (leg.layout().size !== 52) layoutOk = false; + if (e.remainingValue() !== remainingCards(e).reduce((t, c) => t + c.pval, 0)) valueOk = false; + if (k % 20 === 0) { + const saved = JSON.stringify(encode(e.snapshot())); + const e2 = engineFromSave(type, JSON.parse(saved)); + if (JSON.stringify(encode(e2.snapshot())) !== saved) saveOk = false; + } + if (e.isWon()) break; + } + for (let i = snaps.length - 1; i >= 0; i--) { + e.restore(decode(JSON.parse(snaps[i]))); + if (JSON.stringify(encode(e.snapshot())) !== snaps[i]) { trips = false; break; } + } + } + ok(`${type}: every listed move applies`, legal); + ok(`${type}: 52 cards conserved`, conserved); + ok(`${type}: layout places all 52`, layoutOk); + ok(`${type}: score = value of the cards left`, valueOk); + ok(`${type}: snapshots restore exactly (undo)`, trips); + ok(`${type}: saves reload exactly`, saveOk); + } +} + +// ── Leg controllers ────────────────────────────────────────────────────────── +section('Leg controllers'); +{ + // Golf + let e = createEngine('golf', mulberry32(8)); + e.restore({ tableau: [cs('2s 9h'), cs('Qd'), [], [], [], [], []], foundation: cs('8c'), stock: cs('5d 6d'), run: 0, moveCount: 0 }); + let leg = legFor(e); + let lay = leg.layout(); + const top = lay.get(C('9h').id).pose; + let src = leg.pickAt(top); + ok('golf: pressing a top card picks it', src?.kind === 'gcol' && src.col === 0); + ok('golf: buried cards aren\'t pickable', leg.pickAt({ x: lay.get(C('2s').id).pose.x, y: lay.get(C('2s').id).pose.y - 55 }) === null); + ok('golf: a playable card targets the foundation', leg.movesFor(src)[0]?.move.t === 'gplay'); + ok('golf: unplayable says what it needs', /7 or 9/.test(leg.noMoveReason(leg.pickAt(lay.get(C('Qd').id).pose)))); + ok('golf: playable tops glow', leg.playableIds().has(C('9h').id) && !leg.playableIds().has(C('Qd').id)); + ok('golf: stock press turns a card', leg.pickAt(GOLF.STOCK)?.tapMove?.t === 'gstock'); + // Klondike ranking + reasons + e = createEngine('klondike', mulberry32(9)); + const T = (spec) => spec.split('|').map(col => (col ? col.split(' ').map(t => ({ card: C(t.replace('*', '')), faceUp: !t.endsWith('*') })) : [])); + e.restore({ tableau: T('3c* 9h|Ts|Ah||Kd|Js|'), stock: [], waste: cs('8s'), foundations: { s: [], h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + leg = legFor(e); + lay = leg.layout(); + const pick = (key) => leg.pickAt(lay.get(C(key).id).pose); + const best = (s) => leg.movesFor(s).reduce((a, b) => (b.score > a.score ? b : a), { score: -1 }).move; + ok('klondike: ace goes home first', best(pick('Ah'))?.t === 'kcf'); + ok('klondike: 9♥ onto 10♠, revealing the 3♣', best(pick('9h'))?.t === 'krun' && best(pick('9h')).to === 1); + ok('klondike: waste 8♠ onto 9♥', leg.movesFor(pick('8s')).some(t => t.move.t === 'kwc' && t.move.to === 0)); + ok('klondike: a King at a column\'s base doesn\'t hop between empty columns', leg.movesFor(pick('Kd')).length === 0 && !e.legalMoves().some(m => m.t === 'krun' && m.col === 4)); + ok('klondike: reason for a Queen', /red Queen|black Queen|Needs a/.test(leg.noMoveReason(pick('Js')))); + ok('klondike: dropping a non-King on an empty column explains', /King/.test(leg.dropBlocker(pick('Js'), { x: KLON.colX(3), y: KLON.TOP }) ?? '')); + ok('klondike: face-down cards aren\'t pickable', !leg.pickables().some(p => p.src.ids[0] === C('3c').id && p.src.kind === 'krun' && p.src.idx === 0)); + e.restore({ tableau: T('|||||||'), stock: [], waste: cs('9c'), foundations: { s: [], h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + ok('klondike: tapping the empty stock recycles', leg.tapEmpty(KLON.STOCK)?.t === 'kstock'); + e.restore({ tableau: T('Ac|||||||'.slice(0, 9)), stock: [], waste: [], foundations: { s: [], h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + ok('klondike: safe auto-play sends an ace', leg.autoMove({ autoPlay: true })?.t === 'kcf'); + ok('klondike: auto-play off still finishes a foregone board', leg.autoMove({ autoPlay: false })?.t === 'kcf'); + // Pyramid partners + dimming + e = createEngine('pyramid', mulberry32(10)); + leg = legFor(e); + const bottom = e.rows[6].map((c, i) => ({ c, i })); + const covered = e.rows[5][0]; + ok('pyramid: covered cards are dimmed', leg.dimmed(covered.id) && !leg.dimmed(e.rows[6][0].id)); + const s6 = leg.pickAt(PYR.pos(6, 0)); + ok('pyramid: a bottom card is pickable', s6?.kind === 'ploc' && s6.loc.r === 6); + ok('pyramid: covered cards aren\'t pickable', leg.pickAt({ x: PYR.pos(5, 0).x, y: PYR.pos(5, 0).y - 50 }) === null); + ok('pyramid: partner targets are real pairs', bottom.every(({ i }) => leg.movesFor(leg.srcFor({ area: 'pyramid', r: 6, i })).every(t => t.move.t === 'pking' || e.cardAt(t.move.a).pval + e.cardAt(t.move.b).pval === 13))); + ok('pyramid: partner ids line up with moves', bottom.every(({ i }) => { const s = leg.srcFor({ area: 'pyramid', r: 6, i }); return leg.isKing(s) || leg.partnerIds(s).length === leg.movesFor(s).length; })); + // Take Fourteen + e = createEngine('fourteen', mulberry32(11)); + leg = legFor(e); + const pairs = e.legalMoves(); + ok('fourteen: moves agree with partners', e.piles.every((p, i) => !p.length || leg.partnerIds(leg.srcFor(i)).length === e.partnersOf(i).length)); + ok('fourteen: pair count shown', leg.status().some(l => l.includes(String(pairs.length)))); + // Three Shuffles + e = createEngine('threeshuffles', mulberry32(12)); + leg = legFor(e); + ok('three: only fan tops pickable normally', leg.pickables().every(p => e.piles[p.src.p][e.piles[p.src.p].length - 1].id === p.src.ids[0])); + ok('three: draw mode offers only buried cards', leg.pickables({ drawMode: true }).every(p => p.src.tapMove?.t === 'tdraw')); + ok('three: targets are legal', e.piles.every((_, p) => leg.movesFor({ kind: 'tpile', p }).every(t => { const g = engineFromSave('threeshuffles', encode(e.snapshot())); return g.apply(t.move).length > 0; }))); + // homes + remaining + for (const type of TOUR) { + const g = createEngine(type, mulberry32(13)); + ok(`${type}: home stacks + remaining cards cover the deck at the start`, homeStacks(g).reduce((t, s) => t + s.cards.length, 0) + remainingCards(g).length === (type === 'golf' ? 52 : 52)); + } +} + +// ── Room layouts ───────────────────────────────────────────────────────────── +section('Room layouts'); +{ + const huds = hudRects(); + for (const type of TOUR) { + let onTable = true, clear = true; + for (let gi = 0; gi < (QUICK ? 15 : 40); gi++) { + const rng = mulberry32(gi + 500); + const e = createEngine(type, rng); + const leg = legFor(e); + for (let k = 0; k < 200; k++) { + for (const v of leg.layout().values()) { + const b = cardBounds(v.pose); + if (b.x0 < PLAY.x0 - 2 || b.x1 > PLAY.x1 + 2 || b.y0 < PLAY.y0 - 2 || b.y1 > PLAY.y1 + 2) onTable = false; + for (const h of huds) if (rectsOverlap(b, h.r)) clear = false; + } + const ms = e.legalMoves().filter(m => m.t !== 'tdraw'); + if (e.canDraw?.() && rng() < 0.5) { const p = e.piles.find(x => x.length > 1); e.apply({ t: 'tdraw', id: p[0].id }); continue; } + if (!ms.length || e.isWon()) break; + e.apply(ms[Math.floor(rng() * ms.length)]); + } + } + ok(`${type}: every card stays on the table`, onTable); + ok(`${type}: no card under the scorecard, plate or dock`, clear); + } + // Klondike worst case: 6 face-down + a 13-card run + const e = createEngine('klondike', mulberry32(1)); + const deck = freshDeck(mulberry32(2)); + const tab = Array.from({ length: 7 }, () => []); + tab[6] = [...deck.slice(0, 6).map(card => ({ card, faceUp: false })), ...deck.slice(6, 19).map(card => ({ card, faceUp: true }))]; + e.restore({ tableau: tab, stock: deck.slice(19), waste: [], foundations: { s: [], h: [], d: [], c: [] }, recyclesLeft: Infinity, moveCount: 0 }); + const last = cardBounds(legFor(e).layout().get(tab[6][18].card.id).pose); + ok('klondike: a 19-card column fits on the table', last.y1 <= PLAY.y1 + 1); + // Three Shuffles with 19 fans (after a Draw) still fits + const t = createEngine('threeshuffles', mulberry32(3)); + t.shufflesLeft = 0; + t.apply({ t: 'tdraw', id: t.piles[0][0].id }); + const ok19 = [...legFor(t).layout().values()].every(v => cardBounds(v.pose).y1 <= PLAY.y1); + ok('three: 19 fans fit', t.piles.length === 19 && ok19); + // the map has every stop on it + ok('route map has all five stops inside it', TOUR.every(l => { const p = mapXY(STOPS[l].lon, STOPS[l].lat); return p.x > 0 && p.x < MAP.w && p.y > 0 && p.y < MAP.h; })); + ok('every leg has a room theme', TOUR.every(l => THEMES[l]?.surface && THEMES[l].life)); + ok('pyramid apex below the wall strip', cardBounds(PYR.pos(0, 0)).y0 >= PLAY.y0); + ok('three foundations clear of the fans', cardBounds(THREE.found(0)).y1 < cardBounds(THREE.fanPose(0, 0, 3)).y0); + ok('screen size', W === 1920 && H === 1080); +} + +// ── Records ────────────────────────────────────────────────────────────────── +section('Records'); +{ + const mem = new Map(); + const store = { getItem: (k) => mem.get(k) ?? null, setItem: (k, v) => mem.set(k, v) }; + ok('bumpCount counts', bumpCount('t', 'clear-golf', { mode: 'casual' }, store) === 1 && bumpCount('t', 'clear-golf', { mode: 'casual' }, store) === 2); + ok('counts are per mode', loadStats('t', 'tournament', store).counts['clear-golf'] === undefined); + recordBest('t', 'tour', 80, { mode: 'casual' }, store); + ok('lower tour beats it', recordBest('t', 'tour', 61, { mode: 'casual' }, store) === true); + ok('higher run (lower: false) beats it', recordBest('t', 'run', 4, { lower: false, mode: 'casual' }, store) === false && recordBest('t', 'run', 7, { lower: false, mode: 'casual' }, store) === true); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);