fertig-classic-games/src/games/blockfighter/BlockFighterLogic.js

788 lines
29 KiB
JavaScript

// Block Fighter — pure game engine (no Phaser, no DOM, no timers).
// A Super Puzzle Fighter II Turbo style versus engine. The scene (or a headless
// script) drives all timing; every transition returns an ordered event list,
// each event carrying a board snapshot, which the renderer replays as animation.
//
// Power-gem fusion here is a deterministic approximation of the arcade's
// folklore rules: greedy largest-rectangle fusion, then full-row/column
// extension, then same-seam merging. Fixtures in verifyBlockFighter.js pin it.
export const WIDTH = 6;
export const VISIBLE_ROWS = 12;
export const HIDDEN_ROWS = 2;
export const HEIGHT = VISIBLE_ROWS + HIDDEN_ROWS; // row 0 = top (hidden)
export const NUM_COLORS = 4; // 0=red 1=green 2=blue 3=yellow
export const SPAWN_COL = 3;
export const KIND = { GEM: 'gem', CRASH: 'crash', COUNTER: 'counter', DIAMOND: 'diamond' };
export const CRASH_RATE = 0.14;
export const DIAMOND_EVERY = 25;
export const COUNTER_START = 5;
export const MAX_GARBAGE_PER_DROP = 24;
export const CHAIN_MULT = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32];
export const POWER_BONUS = 0.5; // extra attack per cleared power-gem cell
export const ATTACK_DISCOUNT = 2; // cells "free" per clear step before attack
export const DIAMOND_DAMAGE_DIV = 2;
// Super meter: 0..SUPER_MAX, spent in SUPER_TIER units.
export const SUPER_MAX = 300;
export const SUPER_TIER = 100;
export const SUPER_COST = { 1: 100, 3: 300 }; // tier 1 = Purge, tier 3 = Overdrive
export const SUPER_PER_ATTACK = 4; // per point of attack (sent or offset)
export const SUPER_PER_CHAIN = 12; // per chain link beyond the first
export const SUPER_PER_POWER = 2; // per cleared power-gem cell
export const SPEED_GRAVITY_MS = [null, 900, 750, 600, 475, 350]; // index = level speed 1-5
export const COLOR_LETTERS = 'RGBY';
export const DEFAULT_DROP_PATTERN = ['RRGGYY', 'BBRRGG', 'YYBBRR', 'GGYYBB'];
// ── Seeded RNG (mulberry32, matches genRushHour.js) ─────────────────────────
export function makeRng(seed) {
let a = seed >>> 0;
return () => {
a |= 0; a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export function parseDropPattern(rows) {
const src = Array.isArray(rows) && rows.length === 4 ? rows : DEFAULT_DROP_PATTERN;
return src.map((row) =>
[...String(row).padEnd(WIDTH, 'R').slice(0, WIDTH)].map((ch) => {
const c = COLOR_LETTERS.indexOf(ch.toUpperCase());
return c >= 0 ? c : 0;
})
);
}
// ── Match / player construction ──────────────────────────────────────────────
function emptyBoard() {
return Array.from({ length: HEIGHT }, () => Array(WIDTH).fill(null));
}
function createPlayer(dropPattern) {
return {
board: emptyBoard(),
powerGems: new Map(), // id -> { id, color, x, y, w, h }
nextPowerId: 1,
piece: null, // { a, b, row, col, orient }; orient: 0 b-above, 1 b-right, 2 b-below, 3 b-left
pieceIndex: 0, // next index into match.pieceSeq
pendingGarbage: 0,
dropPattern: parseDropPattern(dropPattern),
patternRow: 0,
garbageSent: 0,
garbageReceived: 0,
bestChain: 0,
bestPower: 0, // largest power gem (cells) ever cleared
lastResolve: { attack: 0, cleared: 0, chain: 0, powerCells: 0 },
nextCellId: 1, // stable ids let the renderer track cells as they fall
super: 0,
overdrive: 0, // pieces left to be forced into crash pairs
supersUsed: 0,
lost: false,
};
}
export function createMatch({ seed = 1, dropPatterns = [null, null] } = {}) {
return {
rng: makeRng(seed),
pieceSeq: [], // shared by both players for fairness
players: [createPlayer(dropPatterns[0]), createPlayer(dropPatterns[1])],
over: false,
winner: null,
};
}
// Wipe one player's board back to empty and reopen the match (Garbage Rush
// refills the sandbag this way). Stats and the super meter are kept.
export function resetBoard(match, pIdx) {
const p = match.players[pIdx];
const fresh = createPlayer(null);
p.board = fresh.board;
p.powerGems = fresh.powerGems;
p.piece = null;
p.pendingGarbage = 0;
p.overdrive = 0;
p.lost = false;
match.over = false;
match.winner = null;
return snapshot(p);
}
function getSeqPiece(match, index) {
while (match.pieceSeq.length <= index) {
const i = match.pieceSeq.length;
const half = () => ({
color: Math.floor(match.rng() * NUM_COLORS),
kind: match.rng() < CRASH_RATE ? KIND.CRASH : KIND.GEM,
});
const a = half();
const b = half();
if ((i + 1) % DIAMOND_EVERY === 0) { a.kind = KIND.DIAMOND; a.color = null; }
match.pieceSeq.push({ a, b });
}
return match.pieceSeq[index];
}
// Peek at (and lazily generate) the shared sequence — used for next-piece
// previews and AI lookahead.
export function peekPiece(match, index) {
return getSeqPiece(match, index);
}
// ── Snapshots (for renderer playback) ────────────────────────────────────────
function cloneCell(cell) { return cell ? { ...cell } : null; }
function cloneBoard(board) { return board.map((row) => row.map(cloneCell)); }
export function snapshot(player) {
return {
board: cloneBoard(player.board),
powerGems: [...player.powerGems.values()].map((g) => ({ ...g })),
};
}
function evt(player, type, extra = {}) {
return { type, ...extra, ...snapshot(player) };
}
// ── Piece geometry ───────────────────────────────────────────────────────────
const ORIENT_DELTA = [[-1, 0], [0, 1], [1, 0], [0, -1]]; // b relative to a
export function pieceCells(piece) {
const [dr, dc] = ORIENT_DELTA[piece.orient];
return [
{ r: piece.row, c: piece.col, half: 'a' },
{ r: piece.row + dr, c: piece.col + dc, half: 'b' },
];
}
function cellFree(board, r, c) {
return r >= 0 && r < HEIGHT && c >= 0 && c < WIDTH && !board[r][c];
}
function pieceFits(board, piece) {
return pieceCells(piece).every(({ r, c }) => cellFree(board, r, c));
}
// ── Spawning & garbage drops ─────────────────────────────────────────────────
export function spawnPiece(match, pIdx) {
const player = match.players[pIdx];
const events = [];
if (match.over || player.lost) return events;
if (player.pendingGarbage > 0) {
const dropped = dropGarbage(player);
events.push(evt(player, 'garbage', { cells: dropped, remaining: player.pendingGarbage }));
}
const proto = getSeqPiece(match, player.pieceIndex);
player.pieceIndex += 1;
const piece = { a: { ...proto.a }, b: { ...proto.b }, row: 1, col: SPAWN_COL, orient: 0 };
if (player.overdrive > 0) {
player.overdrive -= 1;
overdrivePiece(player, piece);
}
if (!pieceFits(player.board, piece)) {
player.lost = true;
match.over = true;
match.winner = 1 - pIdx;
events.push(evt(player, 'lose'));
return events;
}
player.piece = piece;
events.push(evt(player, 'spawn', { piece: { ...piece, a: { ...piece.a }, b: { ...piece.b } } }));
return events;
}
function topOfStack(board, col) {
for (let r = 0; r < HEIGHT; r++) if (board[r][col]) return r;
return HEIGHT;
}
function dropGarbage(player) {
const n = Math.min(player.pendingGarbage, MAX_GARBAGE_PER_DROP);
player.pendingGarbage -= n;
player.garbageReceived += n;
const placed = [];
for (let i = 0; i < n; i++) {
const col = i % WIDTH;
const rowOffset = Math.floor(i / WIDTH);
const color = player.dropPattern[(player.patternRow + rowOffset) % 4][col];
const r = topOfStack(player.board, col) - 1;
if (r < 0) continue; // column already full; the loss check happens at spawn
player.board[r][col] = { color, kind: KIND.COUNTER, count: COUNTER_START, id: player.nextCellId++ };
placed.push({ r, c: col, color });
}
player.patternRow = (player.patternRow + Math.ceil(n / WIDTH)) % 4;
return placed;
}
// ── Player input ─────────────────────────────────────────────────────────────
function tryShift(player, dc) {
if (!player.piece) return false;
const moved = { ...player.piece, col: player.piece.col + dc };
if (!pieceFits(player.board, moved)) return false;
player.piece = moved;
return true;
}
export function moveLeft(match, pIdx) { return tryShift(match.players[pIdx], -1); }
export function moveRight(match, pIdx) { return tryShift(match.players[pIdx], 1); }
const ROTATE_KICKS = [[0, 0], [0, -1], [0, 1], [-1, 0]];
function tryRotate(player, dir) {
if (!player.piece) return false;
const orient = (player.piece.orient + dir + 4) % 4;
for (const [dr, dc] of ROTATE_KICKS) {
const rotated = { ...player.piece, orient, row: player.piece.row + dr, col: player.piece.col + dc };
if (pieceFits(player.board, rotated)) { player.piece = rotated; return true; }
}
return false;
}
export function rotateCW(match, pIdx) { return tryRotate(match.players[pIdx], 1); }
export function rotateCCW(match, pIdx) { return tryRotate(match.players[pIdx], -1); }
export function stepDown(match, pIdx) {
const player = match.players[pIdx];
if (!player.piece || player.lost) return { locked: false, events: [] };
const moved = { ...player.piece, row: player.piece.row + 1 };
if (pieceFits(player.board, moved)) {
player.piece = moved;
return { locked: false, events: [] };
}
return { locked: true, events: lockPiece(match, pIdx) };
}
export function hardDrop(match, pIdx) {
const player = match.players[pIdx];
if (!player.piece || player.lost) return [];
let step = stepDown(match, pIdx);
while (!step.locked) step = stepDown(match, pIdx);
return step.events;
}
export function getGhostCells(player) {
if (!player.piece) return [];
let probe = { ...player.piece };
while (true) {
const next = { ...probe, row: probe.row + 1 };
if (!pieceFits(player.board, next)) break;
probe = next;
}
return pieceCells(probe);
}
// ── Lock + resolution pipeline ───────────────────────────────────────────────
function restingRow(board, col) {
return topOfStack(board, col) - 1; // -1 means column full
}
function lockPiece(match, pIdx) {
const player = match.players[pIdx];
const opponent = match.players[1 - pIdx];
const piece = player.piece;
player.piece = null;
const events = [];
const live = !match.headless; // headless sims (AI search) skip snapshot events
const push = (type, extra) => { if (live) events.push(evt(player, type, extra)); };
player.lastResolve = { attack: 0, cleared: 0, chain: 0, powerCells: 0 };
// Place: vertical pairs stack in-column; horizontal halves settle independently.
const placedCells = [];
const place = (half, r, c) => {
if (r < 0) return;
player.board[r][c] = { ...half, id: player.nextCellId++ };
placedCells.push({ r, c });
};
let diamondPos = null;
if (piece.orient === 0 || piece.orient === 2) {
const bottomHalf = piece.orient === 0 ? piece.a : piece.b;
const topHalf = piece.orient === 0 ? piece.b : piece.a;
const rBottom = restingRow(player.board, piece.col);
place(bottomHalf, rBottom, piece.col);
place(topHalf, rBottom - 1, piece.col);
if (bottomHalf.kind === KIND.DIAMOND) diamondPos = { r: rBottom, c: piece.col };
if (topHalf.kind === KIND.DIAMOND) diamondPos = { r: rBottom - 1, c: piece.col };
} else {
const cells = pieceCells(piece);
for (const { c, half } of cells) {
const r = restingRow(player.board, c);
place(piece[half], r, c);
if (piece[half].kind === KIND.DIAMOND) diamondPos = { r, c };
}
}
push('place', { cells: placedCells });
let attack = 0;
// Diamond: wipe every cell of the color directly beneath it.
if (diamondPos && player.board[diamondPos.r]?.[diamondPos.c]?.kind === KIND.DIAMOND) {
const below = player.board[diamondPos.r + 1]?.[diamondPos.c];
const wiped = [];
if (below && below.color != null) {
for (let r = 0; r < HEIGHT; r++) {
for (let c = 0; c < WIDTH; c++) {
const cell = player.board[r][c];
if (cell && cell.color === below.color) {
if (cell.powerId != null) player.powerGems.delete(cell.powerId);
player.board[r][c] = null;
wiped.push({ r, c, color: cell.color, kind: cell.kind, id: cell.id });
}
}
}
attack += Math.floor(wiped.length / DIAMOND_DAMAGE_DIV);
player.lastResolve.cleared += wiped.length;
}
player.board[diamondPos.r][diamondPos.c] = null;
push('diamond', { cells: wiped, color: below?.color ?? null, at: diamondPos });
}
attack += runCascade(player, live ? events : null);
// Counter tick: one decrement per lock; matured counters become plain gems
// and may themselves enable fusions/crashes, so re-resolve if any matured.
const matured = [];
for (let r = 0; r < HEIGHT; r++) {
for (let c = 0; c < WIDTH; c++) {
const cell = player.board[r][c];
if (cell?.kind === KIND.COUNTER) {
cell.count -= 1;
if (cell.count <= 0) {
player.board[r][c] = { color: cell.color, kind: KIND.GEM, id: cell.id };
matured.push({ r, c, color: cell.color });
}
}
}
}
if (matured.length) {
push('counter', { matured });
attack += runCascade(player, live ? events : null);
}
applyAttack(player, opponent, attack, push);
return events;
}
// Damage: offset our own pending garbage first, remainder goes to opponent.
// Also charges the super meter.
function applyAttack(player, opponent, attack, push) {
const lr = player.lastResolve;
lr.attack = attack;
if (lr.powerCells > player.bestPower) player.bestPower = lr.powerCells;
const gain = attack * SUPER_PER_ATTACK
+ Math.max(0, lr.chain - 1) * SUPER_PER_CHAIN
+ lr.powerCells * SUPER_PER_POWER;
player.super = Math.min(SUPER_MAX, player.super + gain);
if (attack > 0) {
const offset = Math.min(attack, player.pendingGarbage);
player.pendingGarbage -= offset;
const sent = attack - offset;
opponent.pendingGarbage += sent;
player.garbageSent += sent;
push('attack', { amount: attack, offset, sent, chain: lr.chain, fromPower: lr.powerCells > 0, powerCells: lr.powerCells });
}
}
// ── Lock-delay support (timing lives in the scene) ──────────────────────────
export function canStepDown(match, pIdx) {
const player = match.players[pIdx];
if (!player.piece || player.lost) return false;
return pieceFits(player.board, { ...player.piece, row: player.piece.row + 1 });
}
// Lock the current piece where it is (it must be resting). Returns events.
export function lockNow(match, pIdx) {
const player = match.players[pIdx];
if (!player.piece || player.lost) return [];
return lockPiece(match, pIdx);
}
// ── Super moves ──────────────────────────────────────────────────────────────
// Largest connected same-color groups (gems + crash gems), biggest first.
export function colorGroups(board) {
const seen = new Set();
const groups = [];
for (let r = 0; r < HEIGHT; r++) {
for (let c = 0; c < WIDTH; c++) {
const cell = board[r][c];
if (!cell || (cell.kind !== KIND.GEM && cell.kind !== KIND.CRASH) || seen.has(r * WIDTH + c)) continue;
let size = 0;
const stack = [[r, c]];
seen.add(r * WIDTH + c);
while (stack.length) {
const [gr, gc] = stack.pop();
size += 1;
for (const [dr, dc] of ORTH) {
const nr = gr + dr, nc = gc + dc;
if (nr < 0 || nr >= HEIGHT || nc < 0 || nc >= WIDTH || seen.has(nr * WIDTH + nc)) continue;
const n = board[nr][nc];
if (n && n.color === cell.color && (n.kind === KIND.GEM || n.kind === KIND.CRASH)) {
seen.add(nr * WIDTH + nc);
stack.push([nr, nc]);
}
}
}
groups.push({ color: cell.color, size });
}
}
return groups.sort((a, b) => b.size - a.size);
}
function overdrivePiece(player, piece) {
const groups = colorGroups(player.board);
const first = groups[0]?.color ?? 0;
const second = groups.find((g) => g.color !== first)?.color ?? ((first + 1) % NUM_COLORS);
if (piece.a.kind !== KIND.DIAMOND) piece.a = { color: first, kind: KIND.CRASH };
piece.b = { color: piece.a.kind === KIND.DIAMOND ? first : second, kind: KIND.CRASH };
}
export function canUseSuper(match, pIdx, tier) {
const player = match.players[pIdx];
const cost = SUPER_COST[tier];
if (!cost || match.over || player.lost || player.super < cost) return false;
if (tier === 1) {
for (const row of player.board) for (const cell of row) if (cell?.kind === KIND.COUNTER) return true;
return false;
}
return true;
}
// tier 1 PURGE: every counter gem on your board becomes a plain gem now, then
// the board resolves (any crash gems touching them fire).
// tier 3 OVERDRIVE: the falling piece and the next one become crash pairs in
// the colors of your two biggest groups.
// Returns an event list, or null when the super can't be used.
export function useSuper(match, pIdx, tier) {
if (!canUseSuper(match, pIdx, tier)) return null;
const player = match.players[pIdx];
const opponent = match.players[1 - pIdx];
const events = [];
const live = !match.headless;
const push = (type, extra) => { if (live) events.push(evt(player, type, extra)); };
player.super -= SUPER_COST[tier];
player.supersUsed += 1;
player.lastResolve = { attack: 0, cleared: 0, chain: 0, powerCells: 0 };
if (tier === 1) {
const purged = [];
for (let r = 0; r < HEIGHT; r++) {
for (let c = 0; c < WIDTH; c++) {
const cell = player.board[r][c];
if (cell?.kind === KIND.COUNTER) {
player.board[r][c] = { color: cell.color, kind: KIND.GEM, id: cell.id };
purged.push({ r, c, color: cell.color });
}
}
}
push('super', { tier, name: 'PURGE', cells: purged });
const attack = runCascade(player, live ? events : null);
applyAttack(player, opponent, attack, push);
} else {
if (player.piece) overdrivePiece(player, player.piece);
player.overdrive = 1;
push('super', { tier, name: 'OVERDRIVE', piece: player.piece ? { ...player.piece, a: { ...player.piece.a }, b: { ...player.piece.b } } : null });
}
return events;
}
function runCascade(player, events) {
let attack = 0;
let chain = 0;
while (true) {
const fell = settle(player);
const fused = fuseAll(player);
if ((fell || fused) && events) events.push(evt(player, 'settle'));
const { cleared, powerCells, powerShapes } = crashClear(player);
if (!cleared.length) break;
chain += 1;
player.bestChain = Math.max(player.bestChain, chain);
player.lastResolve.cleared += cleared.length;
player.lastResolve.powerCells += powerCells;
player.lastResolve.chain = Math.max(player.lastResolve.chain, chain);
const mult = CHAIN_MULT[Math.min(chain - 1, CHAIN_MULT.length - 1)];
attack += Math.max(0, Math.ceil((cleared.length - ATTACK_DISCOUNT + powerCells * POWER_BONUS) * mult));
if (events) events.push(evt(player, 'clear', { cells: cleared, chain, powerCells, powerShapes }));
}
return attack;
}
// ── Gravity (power gems fall rigidly) ────────────────────────────────────────
function settle(player) {
const { board, powerGems } = player;
let movedAny = false;
let movedThisPass = true;
while (movedThisPass) {
movedThisPass = false;
for (let r = HEIGHT - 2; r >= 0; r--) {
for (let c = 0; c < WIDTH; c++) {
const cell = board[r][c];
if (!cell || cell.powerId != null) continue;
if (!board[r + 1][c]) {
board[r + 1][c] = cell;
board[r][c] = null;
movedThisPass = true;
}
}
}
for (const gem of powerGems.values()) {
let canFall = gem.y + gem.h < HEIGHT;
for (let c = gem.x; canFall && c < gem.x + gem.w; c++) {
if (board[gem.y + gem.h][c]) canFall = false;
}
if (canFall) {
for (let c = gem.x; c < gem.x + gem.w; c++) {
board[gem.y + gem.h][c] = board[gem.y + gem.h - 1][c];
for (let r = gem.y + gem.h - 1; r > gem.y; r--) board[r][c] = board[r - 1][c];
board[gem.y][c] = null;
}
gem.y += 1;
movedThisPass = true;
}
}
if (movedThisPass) movedAny = true;
}
return movedAny;
}
// ── Power-gem fusion ─────────────────────────────────────────────────────────
function isFusable(cell, color) {
return cell && cell.kind === KIND.GEM && cell.powerId == null && cell.color === color;
}
function hasAnyTwoByTwo(board) {
for (let r = 0; r < HEIGHT - 1; r++) {
for (let c = 0; c < WIDTH - 1; c++) {
const cell = board[r][c];
if (!cell || cell.kind !== KIND.GEM || cell.powerId != null) continue;
if (isFusable(board[r][c + 1], cell.color) &&
isFusable(board[r + 1][c], cell.color) &&
isFusable(board[r + 1][c + 1], cell.color)) return true;
}
}
return false;
}
function findBestRect(board) {
let best = null;
for (let r = 0; r < HEIGHT - 1; r++) {
for (let c = 0; c < WIDTH - 1; c++) {
const cell = board[r][c];
if (!cell || cell.kind !== KIND.GEM || cell.powerId != null) continue;
const color = cell.color;
let maxW = 0;
while (c + maxW < WIDTH && isFusable(board[r][c + maxW], color)) maxW++;
for (let w = 2; w <= maxW; w++) {
let h = 1;
outer: while (r + h < HEIGHT) {
for (let cc = c; cc < c + w; cc++) {
if (!isFusable(board[r + h][cc], color)) break outer;
}
h++;
}
if (h >= 2 && (!best || w * h > best.w * best.h)) best = { x: c, y: r, w, h, color };
}
}
}
return best;
}
function applyPowerId(board, gem) {
for (let r = gem.y; r < gem.y + gem.h; r++) {
for (let c = gem.x; c < gem.x + gem.w; c++) board[r][c].powerId = gem.id;
}
}
function fuseAll(player) {
const { board, powerGems } = player;
let changed = false;
// New 2x2+ rectangles, largest-first.
if (hasAnyTwoByTwo(board)) {
let rect;
while ((rect = findBestRect(board))) {
const gem = { id: player.nextPowerId++, color: rect.color, x: rect.x, y: rect.y, w: rect.w, h: rect.h };
powerGems.set(gem.id, gem);
applyPowerId(board, gem);
changed = true;
}
}
// Row/column extension and same-seam merging.
let again = true;
while (again) {
again = false;
for (const gem of powerGems.values()) {
for (const dy of [-1, gem.h]) { // row above / below
const r = gem.y + (dy === -1 ? -1 : gem.h);
if (r < 0 || r >= HEIGHT) continue;
let full = true;
for (let c = gem.x; c < gem.x + gem.w; c++) if (!isFusable(board[r][c], gem.color)) { full = false; break; }
if (full) {
if (dy === -1) gem.y -= 1;
gem.h += 1;
applyPowerId(board, gem);
again = true; changed = true;
}
}
for (const dx of [-1, gem.w]) { // column left / right
const c = gem.x + (dx === -1 ? -1 : gem.w);
if (c < 0 || c >= WIDTH) continue;
let full = true;
for (let r = gem.y; r < gem.y + gem.h; r++) if (!isFusable(board[r][c], gem.color)) { full = false; break; }
if (full) {
if (dx === -1) gem.x -= 1;
gem.w += 1;
applyPowerId(board, gem);
again = true; changed = true;
}
}
}
// Merge pairs sharing a full seam.
const gems = [...powerGems.values()];
for (let i = 0; i < gems.length && !again; i++) {
for (let j = i + 1; j < gems.length && !again; j++) {
const a = gems[i], b = gems[j];
if (a.color !== b.color) continue;
const vStack = a.x === b.x && a.w === b.w && (a.y + a.h === b.y || b.y + b.h === a.y);
const hStack = a.y === b.y && a.h === b.h && (a.x + a.w === b.x || b.x + b.w === a.x);
if (vStack || hStack) {
a.x = Math.min(a.x, b.x); a.y = Math.min(a.y, b.y);
if (vStack) a.h += b.h; else a.w += b.w;
powerGems.delete(b.id);
applyPowerId(board, a);
again = true; changed = true;
}
}
}
}
return changed;
}
// ── Crash clearing ───────────────────────────────────────────────────────────
const ORTH = [[-1, 0], [1, 0], [0, -1], [0, 1]];
function crashClear(player) {
const { board, powerGems } = player;
const toClear = new Set();
const visited = new Set();
for (let r = 0; r < HEIGHT; r++) {
for (let c = 0; c < WIDTH; c++) {
const cell = board[r][c];
if (!cell || cell.kind !== KIND.CRASH) continue;
const startKey = r * WIDTH + c;
if (visited.has(startKey)) continue;
const group = [];
const stack = [[r, c]];
visited.add(startKey);
while (stack.length) {
const [gr, gc] = stack.pop();
group.push([gr, gc]);
for (const [dr, dc] of ORTH) {
const nr = gr + dr, nc = gc + dc;
if (nr < 0 || nr >= HEIGHT || nc < 0 || nc >= WIDTH) continue;
const key = nr * WIDTH + nc;
if (visited.has(key)) continue;
const ncell = board[nr][nc];
if (ncell && ncell.color === cell.color && (ncell.kind === KIND.GEM || ncell.kind === KIND.CRASH)) {
visited.add(key);
stack.push([nr, nc]);
}
}
}
if (group.length >= 2) group.forEach(([gr, gc]) => toClear.add(gr * WIDTH + gc));
}
}
if (!toClear.size) return { cleared: [], powerCells: 0, powerShapes: [] };
// Counter gems adjacent to a cleared cell of their own color also clear.
for (const key of [...toClear]) {
const r = Math.floor(key / WIDTH), c = key % WIDTH;
const color = board[r][c].color;
for (const [dr, dc] of ORTH) {
const nr = r + dr, nc = c + dc;
if (nr < 0 || nr >= HEIGHT || nc < 0 || nc >= WIDTH) continue;
const ncell = board[nr][nc];
if (ncell?.kind === KIND.COUNTER && ncell.color === color) toClear.add(nr * WIDTH + nc);
}
}
const cleared = [];
const powerShapes = [];
let powerCells = 0;
for (const key of toClear) {
const r = Math.floor(key / WIDTH), c = key % WIDTH;
const cell = board[r][c];
if (cell.powerId != null) {
powerCells += 1;
const g = powerGems.get(cell.powerId);
if (g) { powerShapes.push({ ...g }); powerGems.delete(cell.powerId); }
}
cleared.push({ r, c, color: cell.color, kind: cell.kind, id: cell.id, power: cell.powerId != null });
board[r][c] = null;
}
// Drop powerId from any cells whose gem was destroyed (partial overlap can't
// happen — a power gem is monochrome and connected, so it clears whole — but
// guard against stale ids anyway).
for (let r = 0; r < HEIGHT; r++) {
for (let c = 0; c < WIDTH; c++) {
const cell = board[r][c];
if (cell?.powerId != null && !powerGems.has(cell.powerId)) delete cell.powerId;
}
}
return { cleared, powerCells, powerShapes };
}
// ── AI support ───────────────────────────────────────────────────────────────
export function legalPlacements(player) {
const placements = [];
for (let orient = 0; orient < 4; orient++) {
const [, dc] = ORIENT_DELTA[orient];
for (let col = 0; col < WIDTH; col++) {
const bCol = col + dc;
if (bCol < 0 || bCol >= WIDTH) continue;
placements.push({ col, orient });
}
}
return placements;
}
function clonePlayer(player) {
return {
...player,
board: cloneBoard(player.board),
powerGems: new Map([...player.powerGems.values()].map((g) => [g.id, { ...g }])),
piece: player.piece ? { ...player.piece, a: { ...player.piece.a }, b: { ...player.piece.b } } : null,
dropPattern: player.dropPattern,
};
}
// Simulate hard-dropping the current piece at (col, orient). Returns metrics
// without mutating the real match, or null if the placement is impossible.
export function simulatePlacement(match, pIdx, col, orient) {
const real = match.players[pIdx];
if (!real.piece) return null;
const player = clonePlayer(real);
const opponent = clonePlayer(match.players[1 - pIdx]);
const sim = { players: pIdx === 0 ? [player, opponent] : [opponent, player], over: false, winner: null, headless: true };
const target = { ...player.piece, row: 1, col, orient };
if (!pieceFits(player.board, target)) return null;
player.piece = target;
hardDrop(sim, pIdx);
const spawnBlocked = !cellFree(player.board, 1, SPAWN_COL) || !cellFree(player.board, 0, SPAWN_COL);
return {
player,
attack: player.lastResolve.attack,
cleared: player.lastResolve.cleared,
chain: player.lastResolve.chain,
powerCells: player.lastResolve.powerCells,
died: spawnBlocked,
};
}