293 lines
13 KiB
JavaScript
293 lines
13 KiB
JavaScript
// Nerts AI — skill-aware, real-time, and paced like a person at the table.
|
|
//
|
|
// 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: { 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[clampSkill(skill)];
|
|
}
|
|
|
|
// 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];
|
|
if ((play.source.count ?? 1) === pile.length) s += 15;
|
|
}
|
|
return s;
|
|
}
|
|
|
|
function toAction(play) {
|
|
return { kind: play.kind, source: play.source, dest: play.dest };
|
|
}
|
|
|
|
/** 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);
|
|
}
|
|
|
|
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 noise = Math.random() * 120 * (1 - prof.quality);
|
|
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 };
|
|
}
|