Rework Nerts as a real-time table with paced AI and full visual scene
- Replace the timer-based AI with a perception model (read/notice/pounce/chain/scan) so opponents pace like humans, pounce on awaited cards, and skip pointless work-pile shuffles; add ghost-hand reach/carry timing and a "too slow" race loss - Add NertsTable.js (Phaser-free projection/layout for 2–4 players, hit-testing, drop snapping) and NertsArt.js (baked table felt/rim/placemats/foundation zone, score pad, ghost hand) - Rewrite NertsGame.js around persistent card sprites that tween to their state positions: deal animation, countdown, drag with live legal-target highlights, smart click/hotkey plays, idle hints, stall detection with stock rotation/auto-resign, pause/settings modals, count-back scoring and a paper score pad - Support draw-count setting (1 or 3), opponent pace, and stock rotation/reshuffle in NertsLogic.js; add live foundation counts and completion checks - Add tools/verifyNerts.js headless suite covering rules, layout bounds/clearance for all player counts, AI pacing invariants, and a multi-round AI soak with card conservation and score checks
This commit is contained in:
parent
2d1a673b7e
commit
523b946721
|
|
@ -1,44 +1,144 @@
|
|||
// Nerts AI — skill-aware, real-time decision making.
|
||||
// Nerts AI — skill-aware, real-time, and paced like a person at the table.
|
||||
//
|
||||
// The scene runs an independent timer per AI seat. Each tick it calls
|
||||
// chooseAction(state, seat, skill) for ONE atomic action, applies it, then
|
||||
// reschedules after nextThinkDelay(skill) ms. Skill (1..5) controls three axes:
|
||||
// • reaction speed — how fast the next tick fires (thinkDelay range)
|
||||
// • decision quality — how strictly moves are ordered by strategic value
|
||||
// • mistakes — missChance to dawdle (flip) or take a sloppy move
|
||||
// Level 1 is slow and sloppy; level 5 is fast and near-optimal.
|
||||
// A real player doesn't act on a metronome. They need a moment to READ a card
|
||||
// they've just flipped or uncovered, longer to NOTICE that someone else's play
|
||||
// in the middle opened something up for them, and they POUNCE quickly when the
|
||||
// one card their Nerts pile has been waiting for finally lands. They also glance
|
||||
// away now and then, and they don't shuffle cards between work piles for nothing.
|
||||
//
|
||||
// That is modelled with a small per-seat "mind":
|
||||
// • every legal play has a moment it became available (the seat's own last
|
||||
// change, or the last change to the foundation it targets);
|
||||
// • it is only *noticed* after a perception delay that depends on what kind
|
||||
// of change it was (read / notice / pounce / chain / opening scan) and on
|
||||
// skill, using a stable per-play random draw so nothing flickers;
|
||||
// • after each of its own actions a seat needs a read-length look over its
|
||||
// layout before it sees everything again or flips the stock.
|
||||
//
|
||||
// The scene calls planMove() on a short poll; it returns either an action to
|
||||
// perform (the scene then adds the hand's reach time) or how long to wait.
|
||||
// Skill 1..5 sets the speed bands, decision quality, mistakes and distraction.
|
||||
|
||||
import {
|
||||
canFlipStock,
|
||||
canPlayOnFoundation,
|
||||
getValidPlays,
|
||||
rv,
|
||||
} from './NertsLogic.js';
|
||||
|
||||
const SKILL_PROFILES = {
|
||||
1: { delay: [1500, 2300], miss: 0.55, quality: 0.15 },
|
||||
2: { delay: [1050, 1700], miss: 0.38, quality: 0.35 },
|
||||
3: { delay: [700, 1150], miss: 0.22, quality: 0.55 },
|
||||
4: { delay: [450, 750], miss: 0.10, quality: 0.78 },
|
||||
5: { delay: [280, 460], miss: 0.03, quality: 0.95 },
|
||||
1: { miss: 0.45, quality: 0.15, distract: 0.10 },
|
||||
2: { miss: 0.30, quality: 0.35, distract: 0.08 },
|
||||
3: { miss: 0.18, quality: 0.55, distract: 0.06 },
|
||||
4: { miss: 0.09, quality: 0.78, distract: 0.04 },
|
||||
5: { miss: 0.03, quality: 0.95, distract: 0.025 },
|
||||
};
|
||||
|
||||
// Perception delays [lo, hi] ms by skill (before the pace multiplier).
|
||||
// read — a card the seat itself just flipped / uncovered
|
||||
// notice — the middle changed because of someone else
|
||||
// pounce — …and it's the exact card the seat's Nerts top was waiting for
|
||||
// chain — building on a foundation the seat just played to itself
|
||||
// scan — the opening look at a freshly dealt layout
|
||||
export const PERCEPTION = {
|
||||
read: { 1: [1400, 2400], 2: [1150, 1950], 3: [900, 1550], 4: [700, 1200], 5: [520, 900] },
|
||||
notice: { 1: [2000, 3400], 2: [1700, 2900], 3: [1400, 2400], 4: [1100, 1900], 5: [850, 1450] },
|
||||
pounce: { 1: [900, 1500], 2: [750, 1250], 3: [600, 1000], 4: [450, 780], 5: [340, 580] },
|
||||
chain: { 1: [700, 1200], 2: [600, 1000], 3: [480, 820], 4: [380, 650], 5: [280, 480] },
|
||||
scan: { 1: [2400, 3600], 2: [2100, 3200], 3: [1800, 2800], 4: [1500, 2300], 5: [1200, 1900] },
|
||||
};
|
||||
|
||||
// AI pace setting → multiplier on every delay (Relaxed / Normal / Frantic).
|
||||
export const PACE = { relaxed: 1.35, normal: 1, frantic: 0.72 };
|
||||
|
||||
const clampSkill = (skill) => Math.max(1, Math.min(5, skill | 0)) || 3;
|
||||
|
||||
function profileFor(skill) {
|
||||
return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3];
|
||||
return SKILL_PROFILES[clampSkill(skill)];
|
||||
}
|
||||
|
||||
/** Milliseconds until this AI's next think tick, randomized within its band. */
|
||||
export function nextThinkDelay(skill) {
|
||||
const [lo, hi] = profileFor(skill).delay;
|
||||
return lo + Math.random() * (hi - lo);
|
||||
// Stable 0..1 from a string (FNV-1a) — the same play keeps the same draw.
|
||||
function hashU(str) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 16777619);
|
||||
return ((h >>> 0) % 100000) / 100000;
|
||||
}
|
||||
|
||||
export function perceptionDelay(cls, skill, u, pace = 1) {
|
||||
const [lo, hi] = PERCEPTION[cls][clampSkill(skill)];
|
||||
return (lo + u * (hi - lo)) * pace;
|
||||
}
|
||||
|
||||
// Ghost-hand speed by skill, as a fraction of each skill's original hand
|
||||
// timing (HAND_BASE): a novice's hand moves at a quarter speed, an expert's
|
||||
// at full speed. Applies to the reach, the carry and the return home.
|
||||
export const HAND_SPEED = { 1: 0.25, 2: 0.30, 3: 0.5, 4: 0.8, 5: 1 };
|
||||
const HAND_BASE = { 1: 420, 2: 360, 3: 300, 4: 240, 5: 190 }; // full-speed reach (ms)
|
||||
const CARRY_BASE = 300; // full-speed carry (ms)
|
||||
|
||||
export function handSpeed(skill) {
|
||||
return HAND_SPEED[clampSkill(skill)];
|
||||
}
|
||||
|
||||
/**
|
||||
* How long the AI's (ghost) hand takes to reach the card it picked — the motor
|
||||
* part of a move, added on top of perception. The move only lands when the hand
|
||||
* arrives, which is what makes races on a foundation possible.
|
||||
*/
|
||||
export function reachDelay(skill, pace = 1, kind = 'move') {
|
||||
const s = clampSkill(skill);
|
||||
return (HAND_BASE[s] / HAND_SPEED[s]) * pace * (kind === 'flip' ? 0.55 : 1);
|
||||
}
|
||||
|
||||
/** How long the hand takes to carry a card to where it's going (the card rides with it). */
|
||||
export function carryDelay(skill, pace = 1) {
|
||||
return (CARRY_BASE / HAND_SPEED[clampSkill(skill)]) * pace;
|
||||
}
|
||||
|
||||
// ── Which plays are worth making ─────────────────────────────────────────────
|
||||
const isRed = (c) => c.suit === 'h' || c.suit === 'd';
|
||||
const links = (a, b) => rv(b) === rv(a) - 1 && isRed(a) !== isRed(b);
|
||||
|
||||
/**
|
||||
* Nobody shuffles cards between work piles for nothing. A work→work move is
|
||||
* worth it only if it empties the pile, lifts a run off a card it isn't in
|
||||
* sequence with (so something new is uncovered), or splits a run to free a
|
||||
* card that goes straight to a foundation. (When the whole table is stuck,
|
||||
* planMove lets players rearrange more freely — see STUCK_MS.)
|
||||
*/
|
||||
export function isUsefulPlay(state, seat, play) {
|
||||
if (play.kind !== 'work' || play.source.type !== 'work') return true;
|
||||
const pile = state.players[seat].work[play.source.idx];
|
||||
const k = pile.length - (play.source.count ?? 1);
|
||||
if (k === 0) return state.players[seat].work[play.dest].length > 0; // whole pile → empty pile is pointless
|
||||
if (!links(pile[k - 1], pile[k])) return true;
|
||||
const freed = pile[k - 1];
|
||||
return state.foundations.some((_, f) => canPlayOnFoundation(state, freed, f));
|
||||
}
|
||||
|
||||
export function usefulPlays(state, seat) {
|
||||
return getValidPlays(state, seat).filter(p => isUsefulPlay(state, seat, p));
|
||||
}
|
||||
|
||||
// Once nobody at the table has made progress for this long, players start
|
||||
// rearranging their work piles looking for something (any move except
|
||||
// dumping a whole pile onto an empty one). Stalls end it either way.
|
||||
export const STUCK_MS = 20000;
|
||||
|
||||
function rummagePlays(state, seat) {
|
||||
return getValidPlays(state, seat).filter(p => {
|
||||
if (p.kind !== 'work' || p.source.type !== 'work') return true;
|
||||
const pile = state.players[seat].work[p.source.idx];
|
||||
return !(pile.length === (p.source.count ?? 1) && state.players[seat].work[p.dest].length === 0);
|
||||
});
|
||||
}
|
||||
|
||||
/** Strategic value of a play, before quality/noise weighting is applied. */
|
||||
function strategicScore(state, seat, play) {
|
||||
let s = play.kind === 'foundation' ? 100 : 40;
|
||||
|
||||
// Offloading the Nerts pile is the whole game — prize it heavily.
|
||||
if (play.source.type === 'nerts') s += 60;
|
||||
else if (play.source.type === 'waste') s += 8;
|
||||
|
||||
// Emptying a work pile (frees a column for any card) is worthwhile.
|
||||
if (play.source.type === 'work') {
|
||||
const pile = state.players[seat].work[play.source.idx];
|
||||
|
|
@ -51,37 +151,142 @@ function toAction(play) {
|
|||
return { kind: play.kind, source: play.source, dest: play.dest };
|
||||
}
|
||||
|
||||
/**
|
||||
* Return one action for the AI at `seat`, or null if it can do nothing.
|
||||
* Action shapes (mirror the NertsLogic mutators):
|
||||
* { kind:'foundation', source, dest }
|
||||
* { kind:'work', source, dest }
|
||||
* { kind:'flip' }
|
||||
*/
|
||||
export function chooseAction(state, seat, skill) {
|
||||
if (state.phase !== 'playing') return null;
|
||||
const prof = profileFor(skill);
|
||||
const plays = getValidPlays(state, seat);
|
||||
const canFlip = canFlipStock(state, seat);
|
||||
/** Legal, sensible plays for a seat, best first (used for the human's hint glow). */
|
||||
export function rankedPlays(state, seat) {
|
||||
return usefulPlays(state, seat)
|
||||
.map(p => ({ p, s: strategicScore(state, seat, p) }))
|
||||
.sort((a, b) => b.s - a.s)
|
||||
.map(x => x.p);
|
||||
}
|
||||
|
||||
if (plays.length === 0) {
|
||||
return canFlip ? { kind: 'flip' } : null;
|
||||
}
|
||||
|
||||
// Mistake: dawdle (flip instead of playing) or take a random sloppy move.
|
||||
function pick(state, seat, plays, prof, canFlip) {
|
||||
// Mistake: dawdle (flip instead of playing) or take a sloppy move.
|
||||
if (Math.random() < prof.miss) {
|
||||
if (canFlip && Math.random() < 0.5) return { kind: 'flip' };
|
||||
return toAction(plays[Math.floor(Math.random() * plays.length)]);
|
||||
}
|
||||
|
||||
// Weighted pick: low quality flattens strategy and adds large noise.
|
||||
let best = null;
|
||||
let bestScore = -Infinity;
|
||||
for (const p of plays) {
|
||||
const strategic = strategicScore(state, seat, p);
|
||||
const noise = Math.random() * 120 * (1 - prof.quality);
|
||||
const score = strategic * (0.4 + 0.6 * prof.quality) + noise;
|
||||
const score = strategicScore(state, seat, p) * (0.4 + 0.6 * prof.quality) + noise;
|
||||
if (score > bestScore) { bestScore = score; best = p; }
|
||||
}
|
||||
return toAction(best);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instant decision with no perception model (kept for tools and as a fallback).
|
||||
* Action shapes (mirror the NertsLogic mutators):
|
||||
* { kind:'foundation', source, dest } | { kind:'work', source, dest } | { kind:'flip' }
|
||||
*/
|
||||
export function chooseAction(state, seat, skill) {
|
||||
if (state.phase !== 'playing') return null;
|
||||
const plays = usefulPlays(state, seat);
|
||||
const canFlip = canFlipStock(state, seat);
|
||||
if (plays.length === 0) return canFlip ? { kind: 'flip' } : null;
|
||||
return pick(state, seat, plays, profileFor(skill), canFlip);
|
||||
}
|
||||
|
||||
// ── The paced planner ────────────────────────────────────────────────────────
|
||||
|
||||
/** A fresh mind for a seat at the start of a round (`now` = play clock ms). */
|
||||
export function createMind(skill, now = 0) {
|
||||
return { skill: clampSkill(skill), start: now, ownAt: now, ownKind: 'deal', pauseUntil: 0, avail: new Map() };
|
||||
}
|
||||
|
||||
/** Tell the mind its own layout changed (after it flips, plays, or fumbles). */
|
||||
export function noteOwnChange(mind, now, kind = 'move') {
|
||||
mind.ownAt = now;
|
||||
mind.ownKind = kind;
|
||||
}
|
||||
|
||||
const playKey = (p) => `${p.kind}:${p.source.type}:${p.source.idx ?? ''}:${p.source.count ?? 1}:${p.dest}:${p.card.id}`;
|
||||
const flipDraw = (seat, mind) => hashU(`${seat}|flip|${Math.round(mind.ownAt)}`);
|
||||
|
||||
/**
|
||||
* When will this seat notice `play`, judged at the moment it first appears?
|
||||
* Returns { t, cls } (play-clock ms; pure — the same inputs give the same answer).
|
||||
*/
|
||||
export function noticeInfo(seat, mind, play, ctx) {
|
||||
const pace = ctx.pace ?? 1;
|
||||
const f = play.kind === 'foundation' ? ctx.foundationAt?.[play.dest] : null;
|
||||
let at = mind.ownAt;
|
||||
let cls = mind.ownKind === 'deal' ? 'scan' : 'read';
|
||||
let u = null;
|
||||
if (f && f.seat === seat && f.at >= mind.ownAt) {
|
||||
at = f.at;
|
||||
cls = 'chain'; // building on our own play
|
||||
} else if (f && f.at > mind.ownAt) {
|
||||
at = f.at;
|
||||
cls = play.source.type === 'nerts' ? 'pounce' : 'notice';
|
||||
} else if (play.source.type === 'waste' && mind.ownKind === 'flip') {
|
||||
u = flipDraw(seat, mind); // read in the same glance as the flip
|
||||
}
|
||||
if (u === null) u = hashU(`${seat}|${playKey(play)}|${Math.round(at)}`);
|
||||
return { t: at + perceptionDelay(cls, mind.skill, u, pace), cls };
|
||||
}
|
||||
|
||||
export function noticeAt(seat, mind, play, ctx) {
|
||||
return noticeInfo(seat, mind, play, ctx).t;
|
||||
}
|
||||
|
||||
// Reactions quick enough to happen mid-look (before the seat's scan is done).
|
||||
const FAST = new Set(['pounce', 'chain']);
|
||||
|
||||
/**
|
||||
* Decide what this seat does now.
|
||||
* ctx = { now, pace, foundationAt: [{ at, seat }], stalledMs } (play-clock ms;
|
||||
* stalledMs = time since anyone at the table made progress)
|
||||
* Returns { action } to perform now, or { wait: ms } to look again later.
|
||||
*
|
||||
* Each opportunity gets ONE clock, started when it first appears and kept
|
||||
* while it stays legal; and every own action is followed by a read-length look
|
||||
* over the seat's layout, after which it sees everything (so it never flips
|
||||
* past a card it could have played just because it hadn't "noticed" it yet).
|
||||
*/
|
||||
export function planMove(state, seat, mind, ctx) {
|
||||
if (state.phase !== 'playing') return { wait: 500 };
|
||||
const now = ctx.now;
|
||||
const pace = ctx.pace ?? 1;
|
||||
const prof = profileFor(mind.skill);
|
||||
if (now < mind.pauseUntil) return { wait: mind.pauseUntil - now };
|
||||
|
||||
const plays = (ctx.stalledMs ?? 0) >= STUCK_MS ? rummagePlays(state, seat) : usefulPlays(state, seat);
|
||||
const canFlip = canFlipStock(state, seat);
|
||||
// After every own action the seat takes a read-length look over its whole
|
||||
// layout. Once that look is done it sees every play (and may flip again);
|
||||
// before then, only quick reactions get through — pouncing on the card its
|
||||
// Nerts top was waiting for, or building on its own foundation play.
|
||||
const scanCls = mind.ownKind === 'deal' ? 'scan' : 'read';
|
||||
const scanAt = mind.ownAt + perceptionDelay(scanCls, mind.skill, flipDraw(seat, mind), pace);
|
||||
const scanned = now >= scanAt;
|
||||
|
||||
const live = new Set();
|
||||
const noticed = [];
|
||||
let nextNotice = Infinity;
|
||||
for (const p of plays) {
|
||||
const key = playKey(p);
|
||||
live.add(key);
|
||||
let info = mind.avail.get(key);
|
||||
if (info === undefined) { info = noticeInfo(seat, mind, p, ctx); mind.avail.set(key, info); }
|
||||
// mid-look, only the quick reactions fire; anything else waits for the scan
|
||||
// (so a seat never grabs a stale low-value move just because it's the only
|
||||
// one "in mind" a moment after its last action)
|
||||
if (scanned || (FAST.has(info.cls) && info.t <= now)) noticed.push(p);
|
||||
else nextNotice = Math.min(nextNotice, FAST.has(info.cls) ? info.t : scanAt);
|
||||
}
|
||||
for (const key of mind.avail.keys()) if (!live.has(key)) mind.avail.delete(key);
|
||||
|
||||
if (noticed.length) {
|
||||
if (Math.random() < prof.distract) {
|
||||
mind.pauseUntil = now + (600 + Math.random() * 1200) * pace; // glanced away
|
||||
return { wait: mind.pauseUntil - now };
|
||||
}
|
||||
return { action: pick(state, seat, noticed, prof, canFlip && scanned) };
|
||||
}
|
||||
if (scanned && canFlip) return { action: { kind: 'flip' } };
|
||||
if (!scanned) return { wait: Math.max(40, Math.min(scanAt, nextNotice) - now) };
|
||||
return { wait: Number.isFinite(nextNotice) ? Math.max(40, nextNotice - now) : 500 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,365 @@
|
|||
// Nerts table art — a home card table baked once per player count into
|
||||
// 'nerts-table-<n>': floor shadow, a walnut table edge with a visible front
|
||||
// face, a lamp-lit green felt top, a faint seat-coloured placemat (with pile
|
||||
// outlines) in front of every player, and the shared foundation zone with a
|
||||
// suit hint printed in each empty slot.
|
||||
//
|
||||
// Also bakes: 'nerts-pad' (paper score pad), 'nerts-hand' (ghost hand, white —
|
||||
// tinted per seat), 'nerts-tab' (owner corner tab for foundation cards).
|
||||
|
||||
import { prepareCasinoArt, canvas, rr, poly, mix, lerp, noisePattern, drawSuit } from '../../ui/casino/CasinoArt.js';
|
||||
import { FOUNDATION_SUITS } from './NertsLogic.js';
|
||||
import {
|
||||
P, VIEW, W, H, CARD_W, CARD_H, FELT_K, RAIL_FACE_PX, SEAT_HEX,
|
||||
outline, layoutFor, pileBase, placematRect, poseScale,
|
||||
} from './NertsTable.js';
|
||||
|
||||
const FELT = '#1f5a3c';
|
||||
const WOOD_DARK = '#3a1f0e', WOOD_MID = '#6b3c1c', WOOD_HI = '#a8692f';
|
||||
|
||||
// ── Table ────────────────────────────────────────────────────────────────────
|
||||
function drawFloorShadow(ctx) {
|
||||
const OFF = 6000;
|
||||
const pts = outline(1.0, 18).map(p => ({ x: p.x - OFF, y: p.y + RAIL_FACE_PX * p.s + 8 }));
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.75)';
|
||||
ctx.shadowBlur = 70;
|
||||
ctx.shadowOffsetX = OFF;
|
||||
ctx.shadowOffsetY = 30;
|
||||
poly(ctx, pts);
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawFrontFace(ctx) {
|
||||
const top = outline(1.0, 18);
|
||||
ctx.save();
|
||||
for (let i = 0; i <= 14; i++) {
|
||||
const f = i / 14;
|
||||
poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s * f })));
|
||||
ctx.fillStyle = mix(WOOD_MID, WOOD_DARK, Math.min(1, 0.25 + f * 0.9));
|
||||
ctx.fill();
|
||||
}
|
||||
poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s })));
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.8)';
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function bandPath(ctx, k0, k1) {
|
||||
const outer = outline(k1, 18), inner = outline(k0, 18);
|
||||
ctx.beginPath();
|
||||
outer.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
|
||||
ctx.closePath();
|
||||
inner.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
function ring(ctx, k, width, color) {
|
||||
poly(ctx, outline(k, 18));
|
||||
ctx.lineWidth = width;
|
||||
ctx.strokeStyle = color;
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
function drawRim(ctx) {
|
||||
ctx.save();
|
||||
bandPath(ctx, FELT_K, 1.0);
|
||||
ctx.fillStyle = WOOD_MID;
|
||||
ctx.fill('evenodd');
|
||||
ctx.clip('evenodd');
|
||||
// rounded bevel: dark at both edges, a warm highlight along the crown
|
||||
for (let i = 0; i <= 16; i++) {
|
||||
const f = i / 16;
|
||||
const crown = Math.sin(f * Math.PI);
|
||||
ring(ctx, lerp(FELT_K, 1.0, f), 5, mix(WOOD_DARK, WOOD_HI, Math.pow(crown, 1.6) * 0.85));
|
||||
}
|
||||
// grain: long faint streaks
|
||||
ctx.globalAlpha = 0.16;
|
||||
for (let i = 0; i < 70; i++) {
|
||||
const k = lerp(FELT_K + 0.004, 0.996, Math.random());
|
||||
const pts = outline(k, 18);
|
||||
const a = Math.floor(Math.random() * pts.length);
|
||||
const len = 6 + Math.floor(Math.random() * 18);
|
||||
ctx.beginPath();
|
||||
for (let j = 0; j < len; j++) {
|
||||
const p = pts[(a + j) % pts.length];
|
||||
if (j) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y);
|
||||
}
|
||||
ctx.lineWidth = 1 + Math.random() * 1.5;
|
||||
ctx.strokeStyle = Math.random() < 0.5 ? '#1c0d05' : '#d9a066';
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 18);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.restore();
|
||||
ring(ctx, 1.0, 2, 'rgba(0,0,0,0.55)');
|
||||
ring(ctx, FELT_K, 2, 'rgba(0,0,0,0.7)');
|
||||
ring(ctx, lerp(FELT_K, 1.0, 0.55), 1.2, 'rgba(255,220,170,0.18)');
|
||||
}
|
||||
|
||||
function drawFelt(ctx) {
|
||||
ctx.save();
|
||||
poly(ctx, outline(FELT_K, 18));
|
||||
ctx.clip();
|
||||
ctx.fillStyle = FELT;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.fillStyle = noisePattern(ctx, 256, 24);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
// overhead lamp + vignette
|
||||
const c = P.project(0, 0.55);
|
||||
const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1000);
|
||||
lamp.addColorStop(0, 'rgba(255,240,200,0.22)');
|
||||
lamp.addColorStop(0.5, 'rgba(255,240,200,0.07)');
|
||||
lamp.addColorStop(1, 'rgba(255,240,200,0)');
|
||||
ctx.fillStyle = lamp;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
const vig = ctx.createRadialGradient(c.x, c.y, 380, c.x, c.y, 1100);
|
||||
vig.addColorStop(0, 'rgba(0,0,0,0)');
|
||||
vig.addColorStop(1, 'rgba(0,0,0,0.5)');
|
||||
ctx.fillStyle = vig;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
// shadow cast by the rim onto the felt
|
||||
for (let i = 0; i < 10; i++) ring(ctx, FELT_K - i * 0.004, 4, `rgba(0,0,0,${0.3 * (1 - i / 10)})`);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// A card-sized slot outline at a pose (matches how Phaser draws a card there).
|
||||
function slot(ctx, pose, { dash = true, alpha = 0.3, fill = null } = {}) {
|
||||
const { sx, sy } = poseScale(pose.s, pose.rot);
|
||||
ctx.save();
|
||||
ctx.translate(pose.x, pose.y);
|
||||
ctx.rotate(pose.rot);
|
||||
ctx.scale(sx, sy);
|
||||
rr(ctx, -CARD_W / 2 - 3, -CARD_H / 2 - 3, CARD_W + 6, CARD_H + 6, 11);
|
||||
if (fill) { ctx.fillStyle = fill; ctx.fill(); }
|
||||
if (dash) ctx.setLineDash([8, 6]);
|
||||
ctx.lineWidth = 2 / Math.max(sx, 0.4);
|
||||
ctx.strokeStyle = `rgba(242,234,216,${alpha})`;
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawPlacemats(ctx, L) {
|
||||
for (const st of L.seats) {
|
||||
const r = placematRect(st.seat);
|
||||
const hex = SEAT_HEX[st.seat];
|
||||
ctx.save();
|
||||
ctx.translate(st.anchor.x, st.anchor.y);
|
||||
ctx.rotate(st.rot);
|
||||
ctx.scale(st.k, st.k);
|
||||
rr(ctx, r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 26);
|
||||
ctx.globalAlpha = 0.07;
|
||||
ctx.fillStyle = hex;
|
||||
ctx.fill();
|
||||
ctx.globalAlpha = 0.32;
|
||||
ctx.lineWidth = 2.5 / st.k;
|
||||
ctx.strokeStyle = hex;
|
||||
ctx.stroke();
|
||||
ctx.globalAlpha = 1;
|
||||
// a tiny stitched inner line
|
||||
rr(ctx, r.x0 + 8, r.y0 + 8, r.x1 - r.x0 - 16, r.y1 - r.y0 - 16, 20);
|
||||
ctx.setLineDash([6, 6]);
|
||||
ctx.lineWidth = 1 / st.k;
|
||||
ctx.strokeStyle = 'rgba(242,234,216,0.12)';
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
ctx.restore();
|
||||
|
||||
// pile outlines
|
||||
slot(ctx, pileBase(L, st.seat, 'nerts'), { dash: false, alpha: 0.42, fill: 'rgba(0,0,0,0.12)' });
|
||||
for (let w = 0; w < 4; w++) slot(ctx, pileBase(L, st.seat, 'work', w), { alpha: 0.22 });
|
||||
slot(ctx, pileBase(L, st.seat, 'stock'), { alpha: 0.26 });
|
||||
slot(ctx, pileBase(L, st.seat, 'waste'), { alpha: 0.16 });
|
||||
|
||||
if (st.seat === 0) {
|
||||
ctx.font = '15px "Julius Sans One", sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = 'rgba(242,234,216,0.4)';
|
||||
const lbl = (kind, text, dy) => {
|
||||
const b = pileBase(L, 0, kind);
|
||||
ctx.fillText(text, b.x, b.y + dy);
|
||||
};
|
||||
lbl('stock', 'STOCK', CARD_H * 0.45 + 22);
|
||||
lbl('waste', 'WASTE', CARD_H * 0.45 + 22);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawFoundationZone(ctx, L) {
|
||||
const fs = L.foundations;
|
||||
const k = fs[0].s;
|
||||
const x0 = Math.min(...fs.map(f => f.x)) - (CARD_W * k) / 2 - 26;
|
||||
const x1 = Math.max(...fs.map(f => f.x)) + (CARD_W * k) / 2 + 26;
|
||||
const y0 = Math.min(...fs.map(f => f.y)) - (CARD_H * k * VIEW.squash) / 2 - 26;
|
||||
const y1 = Math.max(...fs.map(f => f.y)) + (CARD_H * k * VIEW.squash) / 2 + 26;
|
||||
rr(ctx, x0, y0, x1 - x0, y1 - y0, 22);
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.10)';
|
||||
ctx.fill();
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = 'rgba(217,180,90,0.42)';
|
||||
ctx.stroke();
|
||||
rr(ctx, x0 + 7, y0 + 7, x1 - x0 - 14, y1 - y0 - 14, 17);
|
||||
ctx.lineWidth = 1;
|
||||
ctx.strokeStyle = 'rgba(217,180,90,0.2)';
|
||||
ctx.stroke();
|
||||
|
||||
fs.forEach((f, i) => {
|
||||
slot(ctx, f, { dash: false, alpha: 0.2, fill: 'rgba(255,255,255,0.05)' });
|
||||
const suit = FOUNDATION_SUITS[i % 4];
|
||||
ctx.save();
|
||||
ctx.globalAlpha = 0.24;
|
||||
drawSuit(ctx, suit, f.x, f.y, 44 * f.s, suit === 'h' || suit === 'd' ? '#f08a8a' : '#e8e2d0');
|
||||
ctx.globalAlpha = 0.3;
|
||||
ctx.font = `bold ${Math.round(22 * f.s)}px Georgia, serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = '#e8e2d0';
|
||||
ctx.fillText('A', f.x, f.y - 44 * f.s);
|
||||
ctx.restore();
|
||||
});
|
||||
|
||||
ctx.font = '15px "Julius Sans One", sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = 'rgba(232,193,90,0.55)';
|
||||
ctx.fillText('ACES UP · BUILD BY SUIT · ANYONE MAY PLAY', (x0 + x1) / 2, y1 + 18);
|
||||
}
|
||||
|
||||
function bakeTable(scene, key, playerCount) {
|
||||
const L = layoutFor(playerCount);
|
||||
const c = canvas(W, H);
|
||||
const ctx = c.getContext('2d');
|
||||
drawFloorShadow(ctx);
|
||||
drawFrontFace(ctx);
|
||||
drawRim(ctx);
|
||||
drawFelt(ctx);
|
||||
ctx.save();
|
||||
poly(ctx, outline(FELT_K, 18));
|
||||
ctx.clip();
|
||||
drawPlacemats(ctx, L);
|
||||
drawFoundationZone(ctx, L);
|
||||
ctx.restore();
|
||||
scene.textures.addCanvas(key, c);
|
||||
}
|
||||
|
||||
// ── Score pad paper ──────────────────────────────────────────────────────────
|
||||
// A spiral-bound pad: cream paper, blue rules, red margin. Drawn at any size.
|
||||
export function ensurePad(scene, key, w, h) {
|
||||
if (scene.textures.exists(key)) return key;
|
||||
const c = canvas(w + 24, h + 24);
|
||||
const ctx = c.getContext('2d');
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.55)';
|
||||
ctx.shadowBlur = 16;
|
||||
ctx.shadowOffsetX = 4;
|
||||
ctx.shadowOffsetY = 8;
|
||||
rr(ctx, 8, 8, w, h, 6);
|
||||
ctx.fillStyle = '#f7f1dc';
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
ctx.save();
|
||||
rr(ctx, 8, 8, w, h, 6);
|
||||
ctx.clip();
|
||||
const g = ctx.createLinearGradient(0, 8, 0, h + 8);
|
||||
g.addColorStop(0, '#fbf6e4');
|
||||
g.addColorStop(1, '#ece3c6');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(8, 8, w, h);
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 12);
|
||||
ctx.fillRect(8, 8, w, h);
|
||||
const top = 8 + Math.max(30, h * 0.12);
|
||||
const step = Math.max(22, Math.round(h / 16));
|
||||
ctx.lineWidth = 1;
|
||||
ctx.strokeStyle = 'rgba(80,120,200,0.32)';
|
||||
for (let y = top + step; y < h + 8; y += step) {
|
||||
ctx.beginPath(); ctx.moveTo(8, y); ctx.lineTo(w + 8, y); ctx.stroke();
|
||||
}
|
||||
ctx.strokeStyle = 'rgba(210,60,60,0.45)';
|
||||
ctx.beginPath(); ctx.moveTo(8 + w * 0.16, 8); ctx.lineTo(8 + w * 0.16, h + 8); ctx.stroke();
|
||||
// binding strip + spiral rings
|
||||
ctx.fillStyle = '#2b2b33';
|
||||
ctx.fillRect(8, 8, w, Math.max(14, h * 0.045));
|
||||
const rings = Math.max(6, Math.round(w / 34));
|
||||
for (let i = 0; i < rings; i++) {
|
||||
const x = 8 + ((i + 0.5) * w) / rings;
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(x, 8 + Math.max(14, h * 0.045) * 0.5, 5, 9, 0, 0, Math.PI * 2);
|
||||
ctx.lineWidth = 2.5;
|
||||
ctx.strokeStyle = '#b9b9c2';
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.restore();
|
||||
scene.textures.addCanvas(key, c);
|
||||
return key;
|
||||
}
|
||||
|
||||
// ── Ghost hand ───────────────────────────────────────────────────────────────
|
||||
// A soft cartoon hand seen from above, fingers pointing "up" (away from its
|
||||
// owner). White so the scene can tint it per seat.
|
||||
function bakeHand(scene) {
|
||||
const S = 128;
|
||||
const c = canvas(S, S);
|
||||
const ctx = c.getContext('2d');
|
||||
ctx.translate(S / 2, S / 2 + 10);
|
||||
const shape = () => {
|
||||
ctx.beginPath();
|
||||
// palm
|
||||
ctx.ellipse(0, 18, 30, 30, 0, 0, Math.PI * 2);
|
||||
// fingers
|
||||
const fingers = [[-22, -18, 9, 26], [-7, -28, 9.5, 32], [8, -26, 9.5, 31], [22, -14, 8.5, 24]];
|
||||
for (const [fx, fy, rw, rh] of fingers) {
|
||||
ctx.moveTo(fx + rw, fy);
|
||||
ctx.ellipse(fx, fy, rw, rh, 0, 0, Math.PI * 2);
|
||||
}
|
||||
// thumb
|
||||
ctx.moveTo(-26, 26);
|
||||
ctx.ellipse(-34, 14, 9, 22, -0.75, 0, Math.PI * 2);
|
||||
// wrist/cuff
|
||||
ctx.rect(-22, 36, 44, 22);
|
||||
};
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.45)';
|
||||
ctx.shadowBlur = 8;
|
||||
ctx.shadowOffsetY = 4;
|
||||
shape();
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fill('nonzero');
|
||||
ctx.restore();
|
||||
ctx.lineWidth = 3;
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.35)';
|
||||
shape();
|
||||
ctx.stroke();
|
||||
// cuff band
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.18)';
|
||||
ctx.fillRect(-22, 44, 44, 14);
|
||||
scene.textures.addCanvas('nerts-hand', c);
|
||||
}
|
||||
|
||||
function bakeTab(scene) {
|
||||
const c = canvas(40, 40);
|
||||
const ctx = c.getContext('2d');
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(40, 0);
|
||||
ctx.lineTo(40, 34);
|
||||
ctx.quadraticCurveTo(40, 40, 34, 40);
|
||||
ctx.lineTo(0, 0);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fill();
|
||||
scene.textures.addCanvas('nerts-tab', c);
|
||||
}
|
||||
|
||||
export async function prepareNertsArt(scene, playerCount) {
|
||||
await prepareCasinoArt(scene);
|
||||
const key = `nerts-table-${playerCount}`;
|
||||
if (!scene.textures.exists(key)) bakeTable(scene, key, playerCount);
|
||||
if (!scene.textures.exists('nerts-hand')) bakeHand(scene);
|
||||
if (!scene.textures.exists('nerts-tab')) bakeTab(scene);
|
||||
return key;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -48,7 +48,7 @@ function isRed(card) {
|
|||
|
||||
// ── State construction ────────────────────────────────────────────────────────
|
||||
|
||||
export function createInitialState({ playerCount, targetScore = DEFAULT_TARGET_SCORE, totals = null } = {}) {
|
||||
export function createInitialState({ playerCount, targetScore = DEFAULT_TARGET_SCORE, totals = null, drawCount = STOCK_FLIP } = {}) {
|
||||
if (playerCount < 2 || playerCount > 4) {
|
||||
throw new Error(`Nerts supports 2..4 players, got ${playerCount}`);
|
||||
}
|
||||
|
|
@ -80,6 +80,7 @@ export function createInitialState({ playerCount, targetScore = DEFAULT_TARGET_S
|
|||
return {
|
||||
phase: 'playing', // 'playing' | 'roundover' | 'matchover'
|
||||
targetScore,
|
||||
drawCount: drawCount === 1 ? 1 : STOCK_FLIP, // stock flips 3 (standard) or 1 (relaxed)
|
||||
// Fixed-length slot array. Each slot is null (empty — accepts an Ace) or a
|
||||
// foundation { suit, cards: [...] }. Max foundations = 4 suits × playerCount.
|
||||
foundations: new Array(4 * playerCount).fill(null),
|
||||
|
|
@ -281,7 +282,7 @@ export function playToWork(state, seat, source, dstIdx) {
|
|||
return log;
|
||||
}
|
||||
|
||||
/** Flip up to STOCK_FLIP cards from draw to waste.
|
||||
/** Flip up to drawCount (default STOCK_FLIP) cards from draw to waste.
|
||||
* If draw is empty, recycles waste back to draw and returns without dealing —
|
||||
* the player must click again to actually draw the next three cards. */
|
||||
export function flipStock(state, seat) {
|
||||
|
|
@ -292,7 +293,7 @@ export function flipStock(state, seat) {
|
|||
p.stockWaste = [];
|
||||
return { type: 'recycle', seat };
|
||||
}
|
||||
const n = Math.min(STOCK_FLIP, p.stockDraw.length);
|
||||
const n = Math.min(state.drawCount ?? STOCK_FLIP, p.stockDraw.length);
|
||||
for (let i = 0; i < n; i++) p.stockWaste.push(p.stockDraw.pop());
|
||||
return { type: 'flip', seat, n };
|
||||
}
|
||||
|
|
@ -349,6 +350,38 @@ export function endRound(state) {
|
|||
return summary;
|
||||
}
|
||||
|
||||
/** Cards each seat currently has on the shared foundations (the live "+N"). */
|
||||
export function liveFoundationCounts(state) {
|
||||
const counts = new Array(state.players.length).fill(0);
|
||||
for (const slot of state.foundations) {
|
||||
if (!slot) continue;
|
||||
for (const card of slot.cards) counts[card.owner] += 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** A foundation slot that has been built all the way to its King. */
|
||||
export function isFoundationComplete(state, fIdx) {
|
||||
const slot = state.foundations[fIdx];
|
||||
return !!slot && foundationTopRank(slot) >= 13;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stalemate house rule: every player gathers their stock (waste turned back
|
||||
* over, in order) and moves the top card to the bottom, so the next pass
|
||||
* through the stock groups different cards together.
|
||||
*/
|
||||
export function rotateStocks(state) {
|
||||
for (const p of state.players) {
|
||||
// The order cards would be drawn in from here on: the rest of the draw
|
||||
// pile (top first), then the waste turned back over (oldest flip first).
|
||||
const seq = [...p.stockDraw].reverse().concat(p.stockWaste);
|
||||
if (seq.length > 1) seq.push(seq.shift());
|
||||
p.stockDraw = seq.reverse(); // last element = top of the face-down pile
|
||||
p.stockWaste = [];
|
||||
}
|
||||
}
|
||||
|
||||
export function reshuffleAllStocks(state) {
|
||||
for (const p of state.players) {
|
||||
const combined = [...p.stockDraw, ...p.stockWaste];
|
||||
|
|
|
|||
|
|
@ -0,0 +1,321 @@
|
|||
// Nerts table layout — Phaser-free so tools/verifyNerts.js can test it.
|
||||
//
|
||||
// A home card table (rounded rectangle, wooden rim, felt top) seen in mild
|
||||
// perspective from the human's chair, built on the shared casino projection
|
||||
// (makeProjection). Everyone races on the shared foundations in the middle;
|
||||
// each player's own tableau sits in front of them, turned toward its owner:
|
||||
//
|
||||
// 2 players human (near) · opponent straight across
|
||||
// 3 players human · far-left corner · far-right corner
|
||||
// 4 players human · left side · across · right side
|
||||
//
|
||||
// Logic seats fill clockwise from the human's left (seat 1 = left/far-left).
|
||||
//
|
||||
// Every tableau uses the same template in its owner's frame: x runs along the
|
||||
// row (owner's left → right), y points toward the owner (work piles fan that
|
||||
// way). A seat maps the template to the screen with an anchor, a rotation and
|
||||
// a card scale — so opponents' piles are the real thing, just further away.
|
||||
|
||||
import { makeProjection } from '../../ui/casino/CasinoGeometry.js';
|
||||
|
||||
export const VIEW = { cx: 960, yFar: 78, yNear: 1022, sFar: 0.74, halfW: 930, squash: 0.9 };
|
||||
export const P = makeProjection(VIEW);
|
||||
export const SQ = VIEW.squash;
|
||||
export const CARD_W = 96;
|
||||
export const CARD_H = 134;
|
||||
export const W = 1920, H = 1080;
|
||||
|
||||
// Seat colours (human gold, then blue, red, green) and each seat's deck back.
|
||||
export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c];
|
||||
export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c'];
|
||||
export const SEAT_BACK_HEX = ['#7a5a12', '#1d4f8a', '#8a1f2c', '#1e6b3c'];
|
||||
|
||||
// ── Table outline (table space: u ∈ [-1, 1], v ∈ [0, 1], far → near) ─────────
|
||||
export const TABLE = { halfU: 1, v0: 0, v1: 1, corner: 0.17 };
|
||||
export const FELT_K = 0.955; // felt inset from the outer rim (fraction of the outline)
|
||||
export const RAIL_FACE_PX = 30; // visible front face of the table edge at s = 1
|
||||
|
||||
// Rounded-rectangle outline in table space, scaled about the table centre by k.
|
||||
export function outlineUV(k = 1, steps = 14) {
|
||||
const cu = 0, cv = 0.5;
|
||||
const hu = TABLE.halfU * k, hv = 0.5 * k, r = TABLE.corner * k;
|
||||
const pts = [];
|
||||
const corner = (ox, oy, a0) => {
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const a = a0 + (Math.PI / 2) * (i / steps);
|
||||
// the v axis is squeezed (depth 1 vs width 2) — keep corners round on screen
|
||||
pts.push({ u: ox + Math.cos(a) * r, v: oy + Math.sin(a) * r * 0.62 });
|
||||
}
|
||||
};
|
||||
const rv = r * 0.62;
|
||||
corner(cu + hu - r, cv + hv - rv, 0); // near-right
|
||||
corner(cu - hu + r, cv + hv - rv, Math.PI / 2); // near-left
|
||||
corner(cu - hu + r, cv - hv + rv, Math.PI); // far-left
|
||||
corner(cu + hu - r, cv - hv + rv, Math.PI * 1.5); // far-right
|
||||
return pts;
|
||||
}
|
||||
|
||||
export function outline(k = 1, steps = 14) {
|
||||
return outlineUV(k, steps).map(p => P.project(p.u, p.v));
|
||||
}
|
||||
|
||||
export function onTable(pt, k = 1) {
|
||||
const { u, v } = P.unproject(pt.x, pt.y);
|
||||
return pointInPoly({ x: u, y: v }, outlineUV(k).map(p => ({ x: p.u, y: p.v })));
|
||||
}
|
||||
|
||||
export function pointInPoly(pt, poly) {
|
||||
let inside = false;
|
||||
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
|
||||
const a = poly[i], b = poly[j];
|
||||
if ((a.y > pt.y) !== (b.y > pt.y) && pt.x < ((b.x - a.x) * (pt.y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
// ── Tableau template (owner's frame, px at card scale 1) ─────────────────────
|
||||
// x along the row, y toward the owner. `fan` = work-pile fan step, `fanMax` =
|
||||
// the longest a work pile may grow before its fan compresses.
|
||||
export const HUMAN_TEMPLATE = {
|
||||
nerts: -392, work: [-195, -65, 65, 195], stock: 392, waste: 512,
|
||||
fan: 32, fanMax: 250, wasteFan: 26,
|
||||
};
|
||||
export const OPP_TEMPLATE = {
|
||||
nerts: -372, work: [-218, -110, -2, 106], stock: 246, waste: 352,
|
||||
fan: 28, fanMax: 190, wasteFan: 22,
|
||||
};
|
||||
|
||||
// Seat definitions per player count. anchor = the row's centre line (table space),
|
||||
// rot = screen rotation of the owner's frame (0 = human, π = across), k = card scale.
|
||||
const SEATS = {
|
||||
2: [
|
||||
{ uv: { u: 0, v: 0.74 }, rot: 0, k: 1.0, plate: { x: 196, y: 872 } },
|
||||
{ uv: { u: 0, v: 0.2 }, rot: Math.PI, k: 0.66, plate: { x: 1468, y: 118 } },
|
||||
],
|
||||
3: [
|
||||
{ uv: { u: 0, v: 0.74 }, rot: 0, k: 1.0, plate: { x: 196, y: 872 } },
|
||||
{ uv: { u: -0.42, v: 0.175 }, rot: Math.PI - 0.16, k: 0.55, plate: { x: 160, y: 300 } },
|
||||
{ uv: { u: 0.42, v: 0.175 }, rot: Math.PI + 0.16, k: 0.55, plate: { x: 1760, y: 300 } },
|
||||
],
|
||||
4: [
|
||||
{ uv: { u: 0, v: 0.74 }, rot: 0, k: 1.0, plate: { x: 196, y: 872 } },
|
||||
{ uv: { u: -0.735, v: 0.455 }, rot: Math.PI / 2, k: 0.47, plate: { x: 150, y: 200 } },
|
||||
{ uv: { u: 0, v: 0.135 }, rot: Math.PI, k: 0.5, plate: { x: 1450, y: 104 } },
|
||||
{ uv: { u: 0.735, v: 0.455 }, rot: -Math.PI / 2, k: 0.47, plate: { x: 1770, y: 200 } },
|
||||
],
|
||||
};
|
||||
|
||||
// Foundations: rows × cols block in the middle of the table.
|
||||
const FOUNDATION_GRID = {
|
||||
2: { cols: 4, rows: 2, k: 0.78, gapX: 16, gapY: 18, uv: { u: 0, v: 0.5 } },
|
||||
3: { cols: 6, rows: 2, k: 0.74, gapX: 14, gapY: 16, uv: { u: 0, v: 0.5 } },
|
||||
4: { cols: 8, rows: 2, k: 0.7, gapX: 12, gapY: 14, uv: { u: 0, v: 0.475 } },
|
||||
};
|
||||
|
||||
const rot2 = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) });
|
||||
|
||||
// Card container scale for a pose: the perspective squash always acts on the
|
||||
// SCREEN vertical, so a card turned 90° squashes its local x instead.
|
||||
export function poseScale(s, rot) {
|
||||
const c2 = Math.cos(rot) ** 2, s2 = Math.sin(rot) ** 2;
|
||||
return { sx: s * (c2 + s2 * SQ), sy: s * (s2 + c2 * SQ) };
|
||||
}
|
||||
|
||||
// Screen corners of a card pose.
|
||||
export function cardCorners(pose) {
|
||||
const { sx, sy } = poseScale(pose.s, pose.rot);
|
||||
return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => {
|
||||
const p = rot2(a * (CARD_W / 2) * sx, b * (CARD_H / 2) * sy, pose.rot);
|
||||
return { x: pose.x + p.x, y: pose.y + p.y };
|
||||
});
|
||||
}
|
||||
|
||||
export function cardBounds(pose) {
|
||||
const c = cardCorners(pose);
|
||||
const xs = c.map(p => p.x), ys = c.map(p => p.y);
|
||||
return { x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys) };
|
||||
}
|
||||
|
||||
// ── Layout ───────────────────────────────────────────────────────────────────
|
||||
const cache = new Map();
|
||||
|
||||
export function layoutFor(playerCount) {
|
||||
if (cache.has(playerCount)) return cache.get(playerCount);
|
||||
const defs = SEATS[playerCount];
|
||||
if (!defs) throw new Error(`Nerts layout supports 2..4 players, got ${playerCount}`);
|
||||
const seats = defs.map((d, seat) => {
|
||||
const a = P.project(d.uv.u, d.uv.v);
|
||||
const tpl = seat === 0 ? HUMAN_TEMPLATE : OPP_TEMPLATE;
|
||||
return { seat, anchor: { x: a.x, y: a.y }, rot: d.rot, k: d.k, tpl, plate: d.plate };
|
||||
});
|
||||
const g = FOUNDATION_GRID[playerCount];
|
||||
const c = P.project(g.uv.u, g.uv.v);
|
||||
const fw = CARD_W * g.k, fh = CARD_H * g.k * SQ;
|
||||
const foundations = [];
|
||||
for (let i = 0; i < 4 * playerCount; i++) {
|
||||
const row = Math.floor(i / g.cols), col = i % g.cols;
|
||||
const x = c.x + (col - (g.cols - 1) / 2) * (fw + g.gapX);
|
||||
const y = c.y + (row - (g.rows - 1) / 2) * (fh + g.gapY);
|
||||
foundations.push({ x, y, rot: 0, s: g.k });
|
||||
}
|
||||
const out = { playerCount, seats, foundations, grid: g };
|
||||
cache.set(playerCount, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Map an owner-frame offset (px at card scale 1) to a screen point for a seat.
|
||||
export function seatPoint(L, seat, dx, dy) {
|
||||
const st = L.seats[seat];
|
||||
const p = rot2(dx * st.k, dy * st.k, st.rot);
|
||||
return { x: st.anchor.x + p.x, y: st.anchor.y + p.y };
|
||||
}
|
||||
|
||||
function pose(L, seat, dx, dy) {
|
||||
const st = L.seats[seat];
|
||||
const p = seatPoint(L, seat, dx, dy);
|
||||
return { x: p.x, y: p.y, rot: st.rot, s: st.k };
|
||||
}
|
||||
|
||||
// Fan step for a work pile of n cards (compresses so it never exceeds fanMax).
|
||||
export function fanStep(tpl, n) {
|
||||
if (n <= 1) return tpl.fan;
|
||||
return Math.min(tpl.fan, tpl.fanMax / (n - 1));
|
||||
}
|
||||
|
||||
// Lift (screen px, toward the camera) that a stack of n cards shows as thickness.
|
||||
export function stackLift(n, k = 1) {
|
||||
return Math.min(9, Math.max(0, n - 1) * 0.42) * k;
|
||||
}
|
||||
|
||||
/** Base pose of a pile (where its bottom card lies). kind: nerts | work | stock | waste. */
|
||||
export function pileBase(L, seat, kind, idx = 0) {
|
||||
const t = L.seats[seat].tpl;
|
||||
if (kind === 'work') return pose(L, seat, t.work[idx], 0);
|
||||
return pose(L, seat, t[kind], 0);
|
||||
}
|
||||
|
||||
/** Pose of card i (0 = bottom) in a pile of n cards. */
|
||||
export function cardPose(L, seat, kind, idx, i, n) {
|
||||
const st = L.seats[seat], t = st.tpl;
|
||||
if (kind === 'work') return pose(L, seat, t.work[idx], i * fanStep(t, n));
|
||||
if (kind === 'waste') {
|
||||
// only the last three show, fanned along the row
|
||||
const shown = Math.min(3, n);
|
||||
const j = Math.max(0, i - (n - shown));
|
||||
return pose(L, seat, t.waste + j * t.wasteFan, 0);
|
||||
}
|
||||
// stacked piles (nerts, stock): the top card rides on the stack's thickness
|
||||
const base = pose(L, seat, t[kind], 0);
|
||||
const lift = stackLift(i + 1, st.k);
|
||||
return { ...base, y: base.y - lift };
|
||||
}
|
||||
|
||||
export function foundationPose(L, idx, n = 1) {
|
||||
const f = L.foundations[idx];
|
||||
return { ...f, y: f.y - stackLift(n, f.s) };
|
||||
}
|
||||
|
||||
// Where a seat's player "sits" — ghost hands rest here, count-back cards land here.
|
||||
export function seatHome(L, seat) {
|
||||
const st = L.seats[seat];
|
||||
if (seat === 0) return { x: st.plate.x + 150, y: st.plate.y + 20 };
|
||||
return seatPoint(L, seat, 0, 300);
|
||||
}
|
||||
|
||||
// Spot each seat's deck is dealt from (just in front of the owner).
|
||||
export function dealSpot(L, seat) {
|
||||
return { ...pose(L, seat, 0, seat === 0 ? 210 : 260) };
|
||||
}
|
||||
|
||||
// ── Human hit-testing ────────────────────────────────────────────────────────
|
||||
// Human piles are upright (rot 0), so card rects are axis-aligned.
|
||||
export function inPose(pt, p, pad = 0) {
|
||||
const hw = (CARD_W / 2) * p.s + pad, hh = (CARD_H / 2) * p.s * SQ + pad;
|
||||
return Math.abs(pt.x - p.x) <= hw && Math.abs(pt.y - p.y) <= hh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which human card / pile is under a screen point?
|
||||
* Returns { kind:'nerts'|'waste'|'stock'|'work', idx?, k? } or null.
|
||||
* `player` is gs.players[0].
|
||||
*/
|
||||
export function humanHit(L, player, pt) {
|
||||
const p = player;
|
||||
// work piles — topmost card first
|
||||
for (let w = 0; w < 4; w++) {
|
||||
const pile = p.work[w];
|
||||
for (let k = pile.length - 1; k >= 0; k--) {
|
||||
if (inPose(pt, cardPose(L, 0, 'work', w, k, pile.length))) return { kind: 'work', idx: w, k };
|
||||
}
|
||||
if (pile.length === 0 && inPose(pt, pileBase(L, 0, 'work', w))) return { kind: 'work', idx: w, k: -1 };
|
||||
}
|
||||
if (p.stockWaste.length) {
|
||||
const n = p.stockWaste.length;
|
||||
if (inPose(pt, cardPose(L, 0, 'waste', 0, n - 1, n))) return { kind: 'waste' };
|
||||
}
|
||||
if (inPose(pt, cardPose(L, 0, 'stock', 0, Math.max(0, p.stockDraw.length - 1), Math.max(1, p.stockDraw.length)), 6)) return { kind: 'stock' };
|
||||
if (p.nerts.length && inPose(pt, cardPose(L, 0, 'nerts', 0, p.nerts.length - 1, p.nerts.length))) return { kind: 'nerts' };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nearest legal drop target for a card dragged to `pt` (its centre).
|
||||
* `legal` is an array of { type:'foundation'|'work', idx }. Snaps within a
|
||||
* generous radius; returns null when nothing legal is close.
|
||||
*/
|
||||
export function dropTargetAt(L, player, pt, legal) {
|
||||
let best = null, bestD = Infinity;
|
||||
for (const t of legal) {
|
||||
const p = targetPose(L, player, t);
|
||||
const reach = t.type === 'foundation' ? CARD_W * p.s * 1.15 : CARD_W * 1.05;
|
||||
// work piles accept a drop anywhere along their fan
|
||||
let d = Math.hypot(pt.x - p.x, (pt.y - p.y) * 0.85);
|
||||
if (t.type === 'work') {
|
||||
const top = pileBase(L, 0, 'work', t.idx).y;
|
||||
const dy = pt.y < top ? top - pt.y : Math.max(0, pt.y - (p.y + CARD_H * 0.35));
|
||||
d = Math.hypot(pt.x - p.x, dy * 0.85);
|
||||
}
|
||||
if (d < reach && d < bestD) { bestD = d; best = t; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Where a target's next card would land (for highlights + snapping).
|
||||
export function targetPose(L, player, t) {
|
||||
if (t.type === 'foundation') return L.foundations[t.idx];
|
||||
const n = player.work[t.idx].length;
|
||||
return cardPose(L, 0, 'work', t.idx, n, n + 1);
|
||||
}
|
||||
|
||||
// Depth-of-field scale for a dragged card at screen y — shrinks a touch as it
|
||||
// travels "away" across the table toward the centre.
|
||||
export function dragScale(L, y) {
|
||||
const base = P.unproject(L.seats[0].anchor.x, L.seats[0].anchor.y).s;
|
||||
const s = P.unproject(VIEW.cx, Math.max(VIEW.yFar + 40, y)).s;
|
||||
return Math.max(0.74, Math.min(1.04, s / base)) * L.seats[0].k;
|
||||
}
|
||||
|
||||
// ── Seat furniture ───────────────────────────────────────────────────────────
|
||||
// Placemat: a rounded rect around the tableau, in the owner's frame (px at k = 1).
|
||||
export function placematRect(seat) {
|
||||
const t = seat === 0 ? HUMAN_TEMPLATE : OPP_TEMPLATE;
|
||||
const x0 = t.nerts - CARD_W / 2 - 34, x1 = t.waste + 2 * t.wasteFan + CARD_W / 2 + 30;
|
||||
const y0 = -CARD_H / 2 - 40, y1 = CARD_H / 2 + t.fanMax * 0.55 + 30;
|
||||
return { x0, x1, y0, y1 };
|
||||
}
|
||||
|
||||
export function placematCorners(L, seat) {
|
||||
const r = placematRect(seat);
|
||||
return [
|
||||
seatPoint(L, seat, r.x0, r.y0), seatPoint(L, seat, r.x1, r.y0),
|
||||
seatPoint(L, seat, r.x1, r.y1), seatPoint(L, seat, r.x0, r.y1),
|
||||
];
|
||||
}
|
||||
|
||||
// The paper score pad (screen rect) and the Nerts-count badge offset per pile.
|
||||
export const SCORE_PAD = { x: 1765, y: 880, w: 250, h: 220 };
|
||||
|
||||
export function nertsBadge(L, seat) {
|
||||
const t = L.seats[seat].tpl;
|
||||
return seatPoint(L, seat, t.nerts, -CARD_H / 2 - (seat === 0 ? 24 : 30));
|
||||
}
|
||||
|
|
@ -0,0 +1,437 @@
|
|||
#!/usr/bin/env node
|
||||
// verifyNerts.js — headless checks for Nerts: rules, the table layout for
|
||||
// 2/3/4 players (everything on screen, seats/foundations/furniture clear of
|
||||
// each other, human hit-tests and drop snapping round-trip), and an AI soak
|
||||
// where every seat is played by the AI (rounds must end, cards are conserved,
|
||||
// scores add up). Usage: node tools/verifyNerts.js [--quick]
|
||||
|
||||
import {
|
||||
createInitialState, canPlayOnFoundation, canPlayOnWork, playToFoundation, playToWork,
|
||||
flipStock, endRound, allStuck, nertsTop, getValidPlays, validRunFromIndex, maxRunStart,
|
||||
liveFoundationCounts, isFoundationComplete, rotateStocks, reshuffleAllStocks, rv,
|
||||
NERTS_PILE_SIZE, WORK_PILE_COUNT, FOUNDATION_SUITS,
|
||||
} from '../src/games/nerts/NertsLogic.js';
|
||||
import {
|
||||
chooseAction, reachDelay, carryDelay, handSpeed, HAND_SPEED, rankedPlays, PACE, PERCEPTION, planMove, createMind, noteOwnChange, noticeAt,
|
||||
isUsefulPlay, usefulPlays,
|
||||
} from '../src/games/nerts/NertsAI.js';
|
||||
import {
|
||||
W, H, CARD_W, CARD_H, layoutFor, cardPose, pileBase, foundationPose, cardBounds, cardCorners,
|
||||
humanHit, dropTargetAt, targetPose, dragScale, fanStep, placematCorners, nertsBadge, seatHome,
|
||||
dealSpot, SCORE_PAD, onTable, FELT_K, HUMAN_TEMPLATE, OPP_TEMPLATE, inPose,
|
||||
} from '../src/games/nerts/NertsTable.js';
|
||||
import { Card } from '../src/games/cards/Deck.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, owner = 0, id = 0) => Object.assign(new Card(key[0], key[1]), { owner, id });
|
||||
|
||||
// ── Rules ────────────────────────────────────────────────────────────────────
|
||||
section('Rules');
|
||||
for (const n of [2, 3, 4]) {
|
||||
const gs = createInitialState({ playerCount: n });
|
||||
ok(`${n}p: foundations = 4 × players`, gs.foundations.length === 4 * n);
|
||||
for (const p of gs.players) {
|
||||
ok(`${n}p seat ${p.seat}: 13 nerts`, p.nerts.length === NERTS_PILE_SIZE);
|
||||
ok(`${n}p seat ${p.seat}: 4 work piles of 1`, p.work.length === WORK_PILE_COUNT && p.work.every(w => w.length === 1));
|
||||
ok(`${n}p seat ${p.seat}: 35 in stock`, p.stockDraw.length === 35 && p.stockWaste.length === 0);
|
||||
const all = [...p.nerts, ...p.work.flat(), ...p.stockDraw];
|
||||
ok(`${n}p seat ${p.seat}: owns its 52`, all.length === 52 && all.every(c => c.owner === p.seat));
|
||||
}
|
||||
const ids = gs.players.flatMap(p => [...p.nerts, ...p.work.flat(), ...p.stockDraw].map(c => c.id));
|
||||
ok(`${n}p: card ids unique`, new Set(ids).size === ids.length);
|
||||
}
|
||||
{
|
||||
const gs = createInitialState({ playerCount: 2 });
|
||||
gs.foundations.fill(null);
|
||||
ok('empty slot takes only its suit\'s ace', canPlayOnFoundation(gs, C('As'), 0) && !canPlayOnFoundation(gs, C('Ah'), 0));
|
||||
ok('slot 1 wants hearts', canPlayOnFoundation(gs, C('Ah'), 1) && FOUNDATION_SUITS[1] === 'h');
|
||||
ok('non-ace cannot start a slot', !canPlayOnFoundation(gs, C('2s'), 0));
|
||||
gs.foundations[0] = { suit: 's', cards: [C('As')] };
|
||||
ok('builds up by suit', canPlayOnFoundation(gs, C('2s'), 0) && !canPlayOnFoundation(gs, C('2c'), 0) && !canPlayOnFoundation(gs, C('3s'), 0));
|
||||
const p = gs.players[0];
|
||||
p.work[0] = [C('9h')];
|
||||
ok('work builds down alternating colour', canPlayOnWork(gs, 0, C('8s'), 0) && !canPlayOnWork(gs, 0, C('8d'), 0) && !canPlayOnWork(gs, 0, C('7s'), 0));
|
||||
p.work[1] = [];
|
||||
ok('empty work pile takes anything', canPlayOnWork(gs, 0, C('Kd'), 1));
|
||||
ok('valid run detection', validRunFromIndex([C('9h'), C('8s'), C('7d')], 0) && !validRunFromIndex([C('9h'), C('8h')], 0));
|
||||
ok('maxRunStart', maxRunStart([C('5c'), C('9h'), C('8s'), C('7d')]) === 1);
|
||||
ok('rank values ace-low', rv(C('As')) === 1 && rv(C('Kd')) === 13 && rv(C('Td')) === 10);
|
||||
const full = { suit: 'd', cards: 'A23456789TJQK'.split('').map(r => C(`${r}d`)) };
|
||||
gs.foundations[2] = full;
|
||||
ok('complete foundation detected', isFoundationComplete(gs, 2) && !isFoundationComplete(gs, 0));
|
||||
ok('nothing plays on a completed foundation', !canPlayOnFoundation(gs, C('Ad'), 2));
|
||||
}
|
||||
{
|
||||
// stock: draw 3 / draw 1, recycle order
|
||||
for (const dc of [3, 1]) {
|
||||
const gs = createInitialState({ playerCount: 2, drawCount: dc });
|
||||
const p = gs.players[0];
|
||||
const order = [...p.stockDraw].reverse().map(c => c.id);
|
||||
const seen = [];
|
||||
let guard = 0;
|
||||
while (p.stockDraw.length && guard++ < 100) {
|
||||
const before = p.stockWaste.length;
|
||||
flipStock(gs, 0);
|
||||
seen.push(...p.stockWaste.slice(before).map(c => c.id));
|
||||
ok(`draw ${dc}: flips ${dc} (or the rest)`, p.stockWaste.length - before === Math.min(dc, 35 - before));
|
||||
}
|
||||
ok(`draw ${dc}: cards come off in pile order`, seen.join() === order.join());
|
||||
const r = flipStock(gs, 0);
|
||||
ok(`draw ${dc}: empty draw recycles`, r?.type === 'recycle' && p.stockDraw.length === 35 && p.stockWaste.length === 0);
|
||||
const again = [...p.stockDraw].reverse().map(c => c.id);
|
||||
ok(`draw ${dc}: recycle keeps the order`, again.join() === order.join());
|
||||
}
|
||||
// rotateStocks: the next card to come off moves to the bottom
|
||||
const gs = createInitialState({ playerCount: 3 });
|
||||
for (const p of gs.players) { flipStock(gs, p.seat); flipStock(gs, p.seat); }
|
||||
const seqs = gs.players.map(p => [...p.stockDraw].reverse().concat(p.stockWaste).map(c => c.id));
|
||||
rotateStocks(gs);
|
||||
gs.players.forEach((p, i) => {
|
||||
const now = [...p.stockDraw].reverse().map(c => c.id);
|
||||
ok(`rotateStocks seat ${i}: waste gathered`, p.stockWaste.length === 0 && p.stockDraw.length === 35);
|
||||
ok(`rotateStocks seat ${i}: top card to the bottom`, now.join() === [...seqs[i].slice(1), seqs[i][0]].join());
|
||||
});
|
||||
reshuffleAllStocks(gs);
|
||||
ok('reshuffle keeps every stock card', gs.players.every(p => p.stockDraw.length === 35 && p.stockWaste.length === 0));
|
||||
}
|
||||
{
|
||||
// scoring
|
||||
const gs = createInitialState({ playerCount: 2, targetScore: 10 });
|
||||
gs.foundations.fill(null);
|
||||
gs.foundations[0] = { suit: 's', cards: [C('As', 0), C('2s', 1), C('3s', 0)] };
|
||||
gs.players[0].nerts = [];
|
||||
gs.players[1].nerts = gs.players[1].nerts.slice(0, 5);
|
||||
gs.nertsCaller = 0;
|
||||
ok('live counts by owner', liveFoundationCounts(gs).join() === '2,1');
|
||||
const sum = endRound(gs);
|
||||
ok('caller wins the round', gs.winner === 0);
|
||||
ok('+1 per centre card', sum[0].roundScore === 2);
|
||||
ok('−2 per card left in Nerts', sum[1].roundScore === 1 - 10);
|
||||
ok('round only, below target', gs.phase === 'roundover');
|
||||
}
|
||||
|
||||
// ── AI helpers ───────────────────────────────────────────────────────────────
|
||||
section('AI pacing');
|
||||
const band = (cls, skill) => PERCEPTION[cls][skill];
|
||||
for (let skill = 1; skill <= 5; skill++) {
|
||||
ok(`skill ${skill}: pouncing on an awaited card beats noticing in general`, band('pounce', skill)[1] <= band('notice', skill)[0] + 200);
|
||||
ok(`skill ${skill}: building on your own play is quicker than a fresh read`, band('chain', skill)[1] <= band('read', skill)[1] && band('chain', skill)[0] < band('read', skill)[0]);
|
||||
ok(`skill ${skill}: the opening scan is the slowest look`, band('scan', skill)[0] >= band('read', skill)[1] * 0.9);
|
||||
if (skill > 1) {
|
||||
for (const cls of Object.keys(PERCEPTION)) {
|
||||
ok(`${cls}: skill ${skill} quicker than skill ${skill - 1}`, band(cls, skill)[1] < band(cls, skill - 1)[1]);
|
||||
}
|
||||
}
|
||||
for (const [name, mult] of Object.entries(PACE)) {
|
||||
// fresh deal: nothing may happen before the opening scan has had time
|
||||
const gs = createInitialState({ playerCount: 2 });
|
||||
const mind = createMind(skill, 0);
|
||||
const early = band('scan', skill)[0] * mult - 1;
|
||||
const plan = planMove(gs, 1, mind, { now: early, pace: mult, foundationAt: [] });
|
||||
ok(`skill ${skill} ${name}: no move before the opening scan`, !plan.action && plan.wait > 0, JSON.stringify(plan));
|
||||
// after a flip the seat must read before it does anything new
|
||||
const fresh = createMind(skill, 0);
|
||||
noteOwnChange(fresh, 10000, 'flip');
|
||||
const p2 = planMove(gs, 1, fresh, { now: 10000 + band('read', skill)[0] * mult - 1, pace: mult, foundationAt: [] });
|
||||
ok(`skill ${skill} ${name}: reads before acting after a flip`, !p2.action);
|
||||
ok(`skill ${skill} ${name}: waits are finite and positive`, Number.isFinite(p2.wait) && p2.wait > 0);
|
||||
}
|
||||
if (skill > 1) {
|
||||
ok(`skill ${skill}: hand at least as fast as skill ${skill - 1}`, handSpeed(skill) >= handSpeed(skill - 1)
|
||||
&& reachDelay(skill) < reachDelay(skill - 1) && carryDelay(skill) < carryDelay(skill - 1));
|
||||
}
|
||||
}
|
||||
ok('hand speeds: ¼ · 0.3 · ½ · 0.8 · full', [1, 2, 3, 4, 5].map(k => HAND_SPEED[k]).join() === '0.25,0.3,0.5,0.8,1');
|
||||
ok('skill 5 hand unchanged (190ms reach)', Math.abs(reachDelay(5) - 190) < 1e-9 && Math.abs(carryDelay(5) - 300) < 1e-9);
|
||||
ok('skill 3 hand at half speed', Math.abs(reachDelay(3) - 600) < 1e-9 && Math.abs(carryDelay(3) - 600) < 1e-9);
|
||||
ok('skill 1 hand at quarter speed', Math.abs(reachDelay(1) - 1680) < 1e-9);
|
||||
{
|
||||
// pounce vs notice: someone plays the A♥ our Nerts 2♥ was waiting for
|
||||
const gs = createInitialState({ playerCount: 2 });
|
||||
gs.foundations.fill(null);
|
||||
const two = C('2h', 1, 990);
|
||||
gs.players[1].nerts.push(two);
|
||||
gs.foundations[1] = { suit: 'h', cards: [C('Ah', 0, 991)] };
|
||||
const mind = createMind(3, 0);
|
||||
noteOwnChange(mind, 1000, 'move');
|
||||
const fAt = []; fAt[1] = { at: 5000, seat: 0 };
|
||||
const play = { kind: 'foundation', source: { type: 'nerts' }, dest: 1, card: two };
|
||||
const t = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt }) - 5000;
|
||||
ok('a Nerts card someone else unlocks is pounced on', t >= band('pounce', 3)[0] && t <= band('pounce', 3)[1], String(t));
|
||||
const wplay = { kind: 'foundation', source: { type: 'waste' }, dest: 1, card: two };
|
||||
const tw = noticeAt(1, mind, wplay, { pace: 1, foundationAt: fAt }) - 5000;
|
||||
ok('a waste card someone else unlocks takes longer to notice', tw >= band('notice', 3)[0] && tw <= band('notice', 3)[1], String(tw));
|
||||
fAt[1] = { at: 1000, seat: 1 };
|
||||
const tc = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt }) - 1000;
|
||||
ok('building on your own play is a quick chain', tc >= band('chain', 3)[0] && tc <= band('chain', 3)[1], String(tc));
|
||||
const again = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt });
|
||||
ok('the same play keeps the same notice time (no flicker)', again - 1000 === tc);
|
||||
}
|
||||
{
|
||||
// no busy-work: split runs and whole-pile-to-empty moves are filtered, and
|
||||
// repeatedly applying useful work→work moves never loops
|
||||
const gs = createInitialState({ playerCount: 2 });
|
||||
const p = gs.players[0];
|
||||
p.work = [[C('Kc', 0, 800), C('Qh', 0, 801), C('Js', 0, 802)], [C('Qd', 0, 803)], [], [C('5s', 0, 804), C('Th', 0, 805)]];
|
||||
const split = { kind: 'work', source: { type: 'work', idx: 0, count: 1 }, dest: 1, card: p.work[0][2] };
|
||||
ok('splitting a run is not useful', !isUsefulPlay(gs, 0, split));
|
||||
const whole = { kind: 'work', source: { type: 'work', idx: 0, count: 3 }, dest: 2, card: p.work[0][0] };
|
||||
ok('a whole pile onto an empty pile is not useful', !isUsefulPlay(gs, 0, whole));
|
||||
const uncover = { kind: 'work', source: { type: 'work', idx: 3, count: 1 }, dest: 2, card: p.work[3][1] };
|
||||
ok('lifting a card off a non-sequence card is useful', isUsefulPlay(gs, 0, uncover));
|
||||
for (let trial = 0; trial < 200; trial++) {
|
||||
const g = createInitialState({ playerCount: 2 });
|
||||
const seen = new Set();
|
||||
let looped = false;
|
||||
for (let step = 0; step < 60; step++) {
|
||||
const moves = usefulPlays(g, 0).filter(m => m.kind === 'work' && m.source.type === 'work');
|
||||
if (!moves.length) break;
|
||||
const m = moves[Math.floor(Math.random() * moves.length)];
|
||||
playToWork(g, 0, m.source, m.dest);
|
||||
const key = g.players[0].work.map(w => w.map(c => c.id).join('.')).join('|');
|
||||
if (seen.has(key)) { looped = true; break; }
|
||||
seen.add(key);
|
||||
}
|
||||
if (looped) { ok('useful work moves never loop', false); break; }
|
||||
}
|
||||
ok('useful work moves never loop', true);
|
||||
}
|
||||
{
|
||||
const gs = createInitialState({ playerCount: 2 });
|
||||
const plays = rankedPlays(gs, 0);
|
||||
ok('rankedPlays returns sensible legal plays', plays.length === usefulPlays(gs, 0).length);
|
||||
ok('chooseAction still works headless', chooseAction(gs, 1, 3) !== undefined);
|
||||
}
|
||||
|
||||
// ── Layout ───────────────────────────────────────────────────────────────────
|
||||
section('Layout');
|
||||
const onScreen = (b, m = 0) => b.x0 >= -m && b.y0 >= -m && b.x1 <= W + m && b.y1 <= H + m;
|
||||
const boxOf = (pts) => ({
|
||||
x0: Math.min(...pts.map(p => p.x)), x1: Math.max(...pts.map(p => p.x)),
|
||||
y0: Math.min(...pts.map(p => p.y)), y1: Math.max(...pts.map(p => p.y)),
|
||||
});
|
||||
const union = (bs) => ({ x0: Math.min(...bs.map(b => b.x0)), x1: Math.max(...bs.map(b => b.x1)), y0: Math.min(...bs.map(b => b.y0)), y1: Math.max(...bs.map(b => b.y1)) });
|
||||
const overlap = (a, b, pad = 0) => a.x0 < b.x1 + pad && b.x0 < a.x1 + pad && a.y0 < b.y1 + pad && b.y0 < a.y1 + pad;
|
||||
const rectBox = (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 });
|
||||
const PLATE = { w: 268, h: 92 };
|
||||
|
||||
// Every card a seat could show at worst: 13-deep work piles, a full waste fan, full stacks.
|
||||
function seatCardBoxes(L, seat) {
|
||||
const out = [];
|
||||
out.push(cardBounds(cardPose(L, seat, 'nerts', 0, 12, 13)));
|
||||
for (let w = 0; w < 4; w++) for (let i = 0; i < 13; i++) out.push(cardBounds(cardPose(L, seat, 'work', w, i, 13)));
|
||||
out.push(cardBounds(cardPose(L, seat, 'stock', 0, 34, 35)));
|
||||
for (let i = 0; i < 3; i++) out.push(cardBounds(cardPose(L, seat, 'waste', 0, 30 + i, 33)));
|
||||
return out;
|
||||
}
|
||||
|
||||
for (const n of [2, 3, 4]) {
|
||||
const L = layoutFor(n);
|
||||
ok(`${n}p: one seat per player`, L.seats.length === n);
|
||||
const seatBoxes = [];
|
||||
for (let seat = 0; seat < n; seat++) {
|
||||
const boxes = seatCardBoxes(L, seat);
|
||||
ok(`${n}p seat ${seat}: every card on screen`, boxes.every(b => onScreen(b, 2)), JSON.stringify(union(boxes)));
|
||||
// the base row sits on the felt; fans may run onto the rail but not off the table
|
||||
const base = [cardPose(L, seat, 'nerts', 0, 0, 1), ...[0, 1, 2, 3].map(w => pileBase(L, seat, 'work', w)), pileBase(L, seat, 'stock'), pileBase(L, seat, 'waste')];
|
||||
ok(`${n}p seat ${seat}: pile bases on the felt`, base.every(p => onTable(p, FELT_K)));
|
||||
seatBoxes[seat] = { boxes, all: union(boxes) };
|
||||
const badge = nertsBadge(L, seat);
|
||||
ok(`${n}p seat ${seat}: nerts badge on screen`, badge.x > 20 && badge.x < W - 20 && badge.y > 20 && badge.y < H - 20);
|
||||
const plate = rectBox({ ...L.seats[seat].plate, ...PLATE });
|
||||
ok(`${n}p seat ${seat}: nameplate on screen`, onScreen(plate));
|
||||
const d = dealSpot(L, seat), h = seatHome(L, seat);
|
||||
ok(`${n}p seat ${seat}: deal spot / hand rest on screen`, d.x > 0 && d.x < W && d.y > -40 && d.y < H && h.y > -60);
|
||||
}
|
||||
// seats never overlap each other (card by card)
|
||||
for (let a = 0; a < n; a++) {
|
||||
for (let b = a + 1; b < n; b++) {
|
||||
const hit = seatBoxes[a].boxes.some(x => seatBoxes[b].boxes.some(y => overlap(x, y, 6)));
|
||||
ok(`${n}p: seat ${a} clear of seat ${b}`, !hit);
|
||||
}
|
||||
}
|
||||
// foundations: on the felt, no overlap with each other, clear of every seat
|
||||
const fBoxes = L.foundations.map((f, i) => cardBounds(foundationPose(L, i, 13)));
|
||||
ok(`${n}p: foundations on the felt`, L.foundations.every(f => onTable(f, FELT_K * 0.95)));
|
||||
ok(`${n}p: foundations don't overlap`, fBoxes.every((x, i) => fBoxes.every((y, j) => i === j || !overlap(x, y))));
|
||||
const fAll = union(fBoxes);
|
||||
for (let seat = 0; seat < n; seat++) {
|
||||
ok(`${n}p: foundations clear of seat ${seat}`, !seatBoxes[seat].boxes.some(b => overlap(b, fAll, 20)));
|
||||
}
|
||||
// plates / score pad / stall widget clear of every seat's cards and the foundations
|
||||
const furniture = [
|
||||
...L.seats.map(st => ['plate ' + st.seat, rectBox({ ...st.plate, ...PLATE })]),
|
||||
['score pad', rectBox(SCORE_PAD)],
|
||||
['stall widget', rectBox({ x: 200, y: 760, w: 300, h: 92 })],
|
||||
['top buttons', { x0: 19, x1: 291, y0: 22, y1: 66 }],
|
||||
];
|
||||
for (const [name, box] of furniture) {
|
||||
for (let seat = 0; seat < n; seat++) {
|
||||
ok(`${n}p: ${name} clear of seat ${seat} cards`, !seatBoxes[seat].boxes.some(b => overlap(b, box, 4)));
|
||||
}
|
||||
ok(`${n}p: ${name} clear of the foundations`, !overlap(box, fAll, 4));
|
||||
}
|
||||
for (let i = 0; i < furniture.length; i++) {
|
||||
for (let j = i + 1; j < furniture.length; j++) {
|
||||
ok(`${n}p: ${furniture[i][0]} clear of ${furniture[j][0]}`, !overlap(furniture[i][1], furniture[j][1], 4));
|
||||
}
|
||||
}
|
||||
|
||||
// human hit-testing round-trips on a crafted tableau
|
||||
const gs = createInitialState({ playerCount: n });
|
||||
const p = gs.players[0];
|
||||
p.work[0] = [C('9h', 0, 900), C('8s', 0, 901), C('7d', 0, 902)];
|
||||
p.work[1] = [];
|
||||
p.work[2] = Array.from({ length: 13 }, (_, i) => C('5c', 0, 910 + i));
|
||||
flipStock(gs, 0);
|
||||
const pile0 = p.work[0];
|
||||
pile0.forEach((_, k) => {
|
||||
const pose = cardPose(L, 0, 'work', 0, k, pile0.length);
|
||||
// a point inside the visible strip of card k (above the next card's top edge)
|
||||
const pt = k === pile0.length - 1 ? pose : { x: pose.x, y: pose.y - (CARD_H / 2) * 0.9 + 6 };
|
||||
const hit = humanHit(L, p, pt);
|
||||
ok(`${n}p: hit work card ${k}`, hit?.kind === 'work' && hit.idx === 0 && hit.k === k, JSON.stringify(hit));
|
||||
});
|
||||
const deep = cardPose(L, 0, 'work', 2, 12, 13);
|
||||
ok(`${n}p: hit top of a 13-deep pile`, humanHit(L, p, deep)?.k === 12);
|
||||
ok(`${n}p: hit the nerts top`, humanHit(L, p, cardPose(L, 0, 'nerts', 0, 12, 13))?.kind === 'nerts');
|
||||
ok(`${n}p: hit the waste top`, humanHit(L, p, cardPose(L, 0, 'waste', 0, 2, 3))?.kind === 'waste');
|
||||
ok(`${n}p: hit the stock`, humanHit(L, p, cardPose(L, 0, 'stock', 0, 31, 32))?.kind === 'stock');
|
||||
ok(`${n}p: empty work pile is a target`, humanHit(L, p, pileBase(L, 0, 'work', 1))?.k === -1);
|
||||
ok(`${n}p: felt centre hits nothing`, humanHit(L, p, { x: 960, y: L.foundations[0].y }) === null);
|
||||
|
||||
// drop snapping: each legal target snaps from its own landing spot, and only legal ones
|
||||
const targets = [...L.foundations.map((_, i) => ({ type: 'foundation', idx: i })), ...[0, 1, 2, 3].map(i => ({ type: 'work', idx: i }))];
|
||||
for (const t of targets) {
|
||||
const at = targetPose(L, p, t);
|
||||
const got = dropTargetAt(L, p, at, [t]);
|
||||
ok(`${n}p: drop snaps to ${t.type} ${t.idx}`, got && got.type === t.type && got.idx === t.idx);
|
||||
ok(`${n}p: illegal ${t.type} ${t.idx} never snaps`, dropTargetAt(L, p, at, targets.filter(x => x !== t))?.idx !== t.idx || dropTargetAt(L, p, at, targets.filter(x => x !== t))?.type !== t.type);
|
||||
}
|
||||
ok(`${n}p: drop far from everything snaps to nothing`, dropTargetAt(L, p, { x: 40, y: 500 }, targets) === null);
|
||||
const top = dragScale(L, 200), near = dragScale(L, L.seats[0].anchor.y);
|
||||
ok(`${n}p: a dragged card shrinks toward the middle`, top < near && near <= 1.04 && top >= 0.74);
|
||||
}
|
||||
ok('fan compresses long piles', fanStep(HUMAN_TEMPLATE, 13) * 12 <= HUMAN_TEMPLATE.fanMax + 1e-9 && fanStep(OPP_TEMPLATE, 3) === OPP_TEMPLATE.fan);
|
||||
|
||||
// ── AI soak ──────────────────────────────────────────────────────────────────
|
||||
// Every seat is an AI. Simulated time: each seat acts on its own think timer;
|
||||
// foundation cooldowns mirror the scene; stalls rotate then reshuffle stocks.
|
||||
section('AI soak');
|
||||
function countCards(gs) {
|
||||
const counts = new Array(gs.players.length).fill(0);
|
||||
for (const p of gs.players) {
|
||||
for (const c of [...p.nerts, ...p.work.flat(), ...p.stockDraw, ...p.stockWaste]) counts[c.owner]++;
|
||||
}
|
||||
for (const s of gs.foundations) if (s) for (const c of s.cards) counts[c.owner]++;
|
||||
return counts;
|
||||
}
|
||||
|
||||
// Mirrors NertsGame's AI loop on a simulated play clock: each seat polls
|
||||
// planMove (≤250ms apart), an action lands after the hand's reach, the seat
|
||||
// re-plans 60ms after its move. Records every AI action's time per seat.
|
||||
function soakRound(n, skills, drawCount, pace = 1) {
|
||||
const gs = createInitialState({ playerCount: n, drawCount });
|
||||
const minds = skills.map(s => createMind(s, 0));
|
||||
const foundationAt = [];
|
||||
const next = skills.map(() => 100 + Math.random() * 200); // next poll per seat
|
||||
const pending = skills.map(() => null); // { at, action }
|
||||
const actionTimes = skills.map(() => []);
|
||||
let now = 0, lastProgress = 0, lastRotate = -Infinity, rotations = 0, actions = 0, conserved = true, foundationOk = true;
|
||||
let gaveUp = false, fumbles = 0;
|
||||
while (gs.nertsCaller === null && !allStuck(gs) && now < 30 * 60 * 1000) {
|
||||
let seat = 0, t = Infinity;
|
||||
for (let s = 0; s < n; s++) {
|
||||
const ts = pending[s] ? pending[s].at : next[s];
|
||||
if (ts < t) { t = ts; seat = s; }
|
||||
}
|
||||
now = t;
|
||||
if (!pending[seat]) {
|
||||
const plan = planMove(gs, seat, minds[seat], { now, pace, foundationAt, stalledMs: now - lastProgress });
|
||||
if (!plan.action) { next[seat] = now + Math.min(250, plan.wait ?? 250); continue; }
|
||||
const reach = reachDelay(skills[seat], pace, plan.action.kind === 'flip' ? 'flip' : 'move');
|
||||
pending[seat] = { at: now + reach, action: plan.action };
|
||||
continue;
|
||||
}
|
||||
const a = pending[seat].action;
|
||||
pending[seat] = null;
|
||||
if (a.kind === 'flip') { flipStock(gs, seat); noteOwnChange(minds[seat], now, 'flip'); }
|
||||
else if (a.kind === 'foundation') {
|
||||
const log = playToFoundation(gs, seat, a.source, a.dest);
|
||||
if (log) { foundationAt[a.dest] = { at: now, seat }; lastProgress = now; noteOwnChange(minds[seat], now, 'move'); }
|
||||
else { fumbles++; noteOwnChange(minds[seat], now, 'fumble'); }
|
||||
} else if (a.kind === 'work') {
|
||||
const log = playToWork(gs, seat, a.source, a.dest);
|
||||
if (log && a.source.type === 'nerts') lastProgress = now;
|
||||
noteOwnChange(minds[seat], now, 'move');
|
||||
}
|
||||
actionTimes[seat].push(now);
|
||||
actions++;
|
||||
// the hand finishes carrying a played card before it reaches again
|
||||
next[seat] = now + (a.kind === 'flip' ? 60 : carryDelay(skills[seat], pace));
|
||||
// mirrors NertsGame.updateStall: rotate at 60s idle (30s apart), give up at 180s
|
||||
if (now - lastProgress >= 60000 && now - lastRotate >= 30000) {
|
||||
if (rotations === 0) rotateStocks(gs); else reshuffleAllStocks(gs);
|
||||
for (const m of minds) noteOwnChange(m, now, 'flip');
|
||||
rotations++;
|
||||
lastRotate = now;
|
||||
}
|
||||
if (now - lastProgress >= 180000) { gaveUp = true; break; }
|
||||
if (actions % 50 === 0) {
|
||||
if (!countCards(gs).every(c => c === 52)) conserved = false;
|
||||
for (const s of gs.foundations) {
|
||||
if (!s) continue;
|
||||
s.cards.forEach((c, i) => { if (c.suit !== s.suit || rv(c) !== i + 1) foundationOk = false; });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!countCards(gs).every(c => c === 52)) conserved = false;
|
||||
const live = liveFoundationCounts(gs);
|
||||
const nertsLeft = gs.players.map(p => p.nerts.length);
|
||||
const ended = gs.nertsCaller !== null || allStuck(gs) || gaveUp;
|
||||
const summary = endRound(gs);
|
||||
const scoresOk = summary.every(s => s.founded === live[s.seat] && s.roundScore === s.founded - 2 * nertsLeft[s.seat]);
|
||||
return { ended, gaveUp, conserved, foundationOk, scoresOk, minutes: now / 60000, rotations, caller: gs.nertsCaller, actions, actionTimes, fumbles };
|
||||
}
|
||||
|
||||
const ROUNDS = QUICK ? 24 : 150;
|
||||
const stats = { ended: 0, gaveUp: 0, minutes: [], rotations: 0, wins: [0, 0, 0, 0], fumbles: 0, gaps: {} };
|
||||
for (let r = 0; r < ROUNDS; r++) {
|
||||
const n = 2 + (r % 3);
|
||||
const skills = [3, ...Array.from({ length: n - 1 }, (_, i) => 1 + ((r + i * 2) % 5))];
|
||||
const res = soakRound(n, skills, r % 4 === 3 ? 1 : 3);
|
||||
ok(`round ${r} (${n}p): ended`, res.ended, `${res.minutes.toFixed(1)} min, ${res.rotations} rotations`);
|
||||
ok(`round ${r}: cards conserved`, res.conserved);
|
||||
ok(`round ${r}: foundations build A→K by suit`, res.foundationOk);
|
||||
ok(`round ${r}: scores = +1/centre card −2/nerts card`, res.scoresOk);
|
||||
if (res.ended) stats.ended++;
|
||||
if (res.gaveUp) stats.gaveUp++;
|
||||
stats.minutes.push(res.minutes);
|
||||
stats.rotations += res.rotations;
|
||||
if (res.caller !== null) stats.wins[res.caller]++;
|
||||
stats.fumbles += res.fumbles;
|
||||
res.actionTimes.forEach((times, seat) => {
|
||||
const g = (stats.gaps[skills[seat]] ??= []);
|
||||
for (let i = 1; i < times.length; i++) g.push(times[i] - times[i - 1]);
|
||||
});
|
||||
}
|
||||
const mins = stats.minutes.sort((a, b) => a - b);
|
||||
console.log(` ${stats.ended}/${ROUNDS} rounds ended (${stats.gaveUp} stalled out) · median ${mins[Math.floor(mins.length / 2)].toFixed(1)} sim-min · max ${mins[mins.length - 1].toFixed(1)} · ${stats.rotations} stock rotations · callers by seat ${stats.wins.join('/')}`);
|
||||
|
||||
const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length;
|
||||
const paceLine = Object.keys(stats.gaps).sort().map(sk => `skill ${sk} ${(avg(stats.gaps[sk]) / 1000).toFixed(2)}s`).join(' · ');
|
||||
console.log(` avg time between a seat's actions: ${paceLine} · ${stats.fumbles} lost races`);
|
||||
for (const sk of Object.keys(stats.gaps)) {
|
||||
const a = avg(stats.gaps[sk]) / 1000;
|
||||
ok(`skill ${sk}: plays at a human pace (${a.toFixed(2)}s/action)`, a >= 0.7 && a <= 6);
|
||||
}
|
||||
if (stats.gaps[1] && stats.gaps[5]) ok('skill 5 plays faster than skill 1', avg(stats.gaps[5]) < avg(stats.gaps[1]));
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
Loading…
Reference in New Issue