/** * Pure rules for Ordnance Disposal (internal key `bomperator`). No I/O, no * timers, no Payload: the server registry (./registry.ts) owns live match * records and drives these functions from a fixed tick loop, and unit tests * call them directly. * * Every mutator returns a NEW state built from local copies; the input state is * never mutated. Randomness is injected through `state.rngState` / `gridSeed`, * so a given seed reproduces the same grid and the same sudden-death draws. */ import { BASE_SPEED_CELLS_PER_S, BOMB_FUSE_TICKS, CELL_COUNT, CRATE_DENSITY, FLAME_LIFETIME_TICKS, GRID_H, GRID_W, INTER_ROUND_COUNTDOWN_TICKS, MAX_BOMBS, MAX_RANGE, MAX_SPEED_CELLS_PER_S, MAX_SUDDEN_DEATH_EXPLOSIONS, POWERUP_WEIGHTS, ROUND_END_HOLD_TICKS, ROUND_TIMER_TICKS, SPAWN_INVULNERABLE_TICKS, SPAWN_POINTS, SPEED_BOOST_CELLS_PER_S, START_BOMBS, START_RANGE, SUDDEN_DEATH_INTERVAL_TICKS, TICK_MS, } from "./constants"; import type { BomperatorEvent, BomperatorState, Bomb, CellType, Dir, Drop, Flame, Player, PowerUpKind, } from "./types"; /* --------------------------------------------------------------------- rng */ /** Shallow-mutable view of a readonly interface, for per-tick working copies. */ type Mutable = { -readonly [K in keyof T]: T[K] }; /** mulberry32 step: returns a float in [0,1) and the next integer state. */ function rng(state: number): { value: number; next: number } { const a = (state + 0x6d2b79f5) | 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); const value = ((t ^ (t >>> 14)) >>> 0) / 4294967296; return { value, next: a }; } /** Derive an independent seed for a round from the match seed + round index. */ export function deriveSeed(matchSeed: number, roundIndex: number): number { let h = (matchSeed ^ 0x9e3779b9) >>> 0; h = Math.imul(h ^ (roundIndex + 0x85ebca6b), 0xc2b2ae35); h ^= h >>> 13; return h >>> 0; } /* ------------------------------------------------------------------- grid */ export function idx(x: number, y: number): number { return y * GRID_W + x; } export function inBounds(x: number, y: number): boolean { return x >= 0 && y >= 0 && x < GRID_W && y < GRID_H; } function isSolidLayout(x: number, y: number): boolean { if (x === 0 || y === 0 || x === GRID_W - 1 || y === GRID_H - 1) return true; // border return x % 2 === 0 && y % 2 === 0; // interior pillars on even/even } /** Weighted power-up pick from a [0,1) draw. */ function pickPowerUp(value: number): PowerUpKind { const order: PowerUpKind[] = ["bomb", "range", "speed", "kick"]; const total = order.reduce((sum, kind) => sum + POWERUP_WEIGHTS[kind], 0); let acc = 0; const roll = value * total; for (const kind of order) { acc += POWERUP_WEIGHTS[kind]; if (roll < acc) return kind; } return "kick"; } /** Cells that must stay crate-free so every spawn has an escape corridor. */ function protectedSpawnCells(): Set { const set = new Set(); const dirs: Array<[number, number]> = [ [0, 0], [1, 0], [-1, 0], [0, 1], [0, -1], ]; for (const spawn of SPAWN_POINTS) { for (const [dx, dy] of dirs) { const x = spawn.x + dx; const y = spawn.y + dy; if (inBounds(x, y) && !isSolidLayout(x, y)) set.add(idx(x, y)); } } return set; } /** * Build the classic depot layout from a seed: solid border, pillar grid on even * coordinates, seeded-random destructible crates on the remaining passable * cells (spawn areas and their escape corridors kept clear), and one hidden * power-up under each crate. */ export function generateGrid(seed: number): { grid: CellType[]; hidden: (PowerUpKind | null)[]; } { const grid: CellType[] = new Array(CELL_COUNT).fill("empty"); const hidden: (PowerUpKind | null)[] = new Array(CELL_COUNT).fill(null); for (let y = 0; y < GRID_H; y += 1) { for (let x = 0; x < GRID_W; x += 1) { if (isSolidLayout(x, y)) grid[idx(x, y)] = "solid"; } } const protectedCells = protectedSpawnCells(); let rs = seed >>> 0; for (let y = 0; y < GRID_H; y += 1) { for (let x = 0; x < GRID_W; x += 1) { const i = idx(x, y); if (grid[i] !== "empty" || protectedCells.has(i)) continue; const roll = rng(rs); rs = roll.next; if (roll.value < CRATE_DENSITY) { grid[i] = "crate"; const pick = rng(rs); rs = pick.next; hidden[i] = pickPowerUp(pick.value); } } } return { grid, hidden }; } /* --------------------------------------------------------------- lifecycle */ function freshPlayer(seat: number, userId: number, name: string): Player { const spawn = SPAWN_POINTS[seat % SPAWN_POINTS.length]; return { seat, userId, name, x: spawn.x, y: spawn.y, dir: "down", alive: true, invulnerableTicks: 0, bombsMax: START_BOMBS, range: START_RANGE, speed: BASE_SPEED_CELLS_PER_S, kick: false, kills: 0, deaths: 0, roundsWon: 0, inputDir: null, wantDrop: false, connected: true, disconnectedAt: null, }; } export interface SeatDescriptor { readonly seat: number; readonly userId: number; readonly name: string; } /** A fresh match in the lobby (no grid yet; the first startRound builds one). */ export function createMatchState( seats: readonly SeatDescriptor[], roundTarget: number, matchSeed: number, ): BomperatorState { const players = seats.map((s) => freshPlayer(s.seat, s.userId, s.name)); return { phase: "lobby", roundTarget, roundIndex: 0, gridSeed: matchSeed >>> 0, tickCount: 0, rngState: matchSeed >>> 0, grid: new Array(CELL_COUNT).fill("empty"), hidden: new Array(CELL_COUNT).fill(null), players, bombs: [], flames: [], drops: [], countdownTicks: 0, roundTimerTicks: ROUND_TIMER_TICKS, roundEndHoldTicks: 0, suddenDeath: false, suddenDeathTicks: 0, suddenDeathExplosions: 0, roundWinnerSeat: null, matchWinnerSeat: null, endReason: null, events: [], lastEventId: 0, }; } /** * Begin a round: regenerate the grid from a fresh seed, reset every seated * player to their spawn with base loadout, and enter the countdown. Match-scoped * counters (kills, roundsWon) are preserved. */ export function startRound(state: BomperatorState, seedOverride?: number): BomperatorState { const seed = (seedOverride ?? deriveSeed(state.gridSeed, state.roundIndex)) >>> 0; const { grid, hidden } = generateGrid(seed); const players = state.players.map((p) => { const spawn = SPAWN_POINTS[p.seat % SPAWN_POINTS.length]; return { ...p, x: spawn.x, y: spawn.y, dir: "down" as Dir, alive: true, invulnerableTicks: SPAWN_INVULNERABLE_TICKS, bombsMax: START_BOMBS, range: START_RANGE, speed: BASE_SPEED_CELLS_PER_S, kick: false, inputDir: null, wantDrop: false, }; }); return { ...state, phase: "countdown", gridSeed: seed, rngState: seed >>> 0, grid, hidden, players, bombs: [], flames: [], drops: [], countdownTicks: INTER_ROUND_COUNTDOWN_TICKS, roundTimerTicks: ROUND_TIMER_TICKS, roundEndHoldTicks: 0, suddenDeath: false, suddenDeathTicks: 0, suddenDeathExplosions: 0, roundWinnerSeat: null, }; } /* ------------------------------------------------------------------ inputs */ export interface BomperatorInput { readonly dir?: Dir | null; readonly drop?: boolean; /** * Client-issued sequence number. The registry applies only strictly newer * values so direction POSTs that arrive out of order (the client now fires * them immediately rather than queueing) can never resurrect a stale intent. */ readonly seq?: number; } /** * Record a seat's latest intent. Movement direction is level-triggered (the last * value wins and persists until changed); `drop` is edge-triggered and sticky so * a press between ticks is never lost, consumed by the next tick. */ export function applyInput( state: BomperatorState, seat: number, input: BomperatorInput, ): BomperatorState { if (state.phase !== "battle") return state; const player = state.players[seat]; if (!player || !player.alive) return state; const players = [...state.players]; players[seat] = { ...player, inputDir: input.dir ?? null, wantDrop: player.wantDrop || input.drop === true, }; return { ...state, players }; } /* -------------------------------------------------------------- presence */ /** Mark a seat connected/disconnected (engine keeps them frozen while held). */ export function setConnected(state: BomperatorState, seat: number, connected: boolean): BomperatorState { const player = state.players[seat]; if (!player || player.connected === connected) return state; const players = [...state.players]; players[seat] = { ...player, connected }; return { ...state, players }; } /** Eliminate a seat from the current round (no-show or dropped connection). */ export function eliminateSeat(state: BomperatorState, seat: number): BomperatorState { const player = state.players[seat]; if (!player || !player.alive) return state; const players = [...state.players]; players[seat] = { ...player, alive: false, deaths: player.deaths + 1, inputDir: null, wantDrop: false }; return withEvent({ ...state, players }, { type: "death", seat, killerSeat: null }); } /* ----------------------------------------------------------------- helpers */ function bombsActiveFor(bombs: readonly Bomb[], seat: number): number { let n = 0; for (const b of bombs) if (b.ownerSeat === seat) n += 1; return n; } function bombAt(bombs: readonly Bomb[], x: number, y: number): Bomb | undefined { return bombs.find((b) => b.x === x && b.y === y); } function terrainIsOpen(grid: readonly CellType[], x: number, y: number): boolean { return inBounds(x, y) && grid[idx(x, y)] === "empty"; } /** A cell a technician may stand on: open terrain and no charge sitting there. */ function canStand(state: BomperatorState, bombs: readonly Bomb[], x: number, y: number): boolean { return terrainIsOpen(state.grid, x, y) && !bombAt(bombs, x, y); } const DIR_VEC: Record = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0], }; /** True when a position sits exactly on a cell center (within float epsilon). */ function isCellCentered(x: number, y: number): boolean { const EPS = 1e-6; return Math.abs(x - Math.round(x)) < EPS && Math.abs(y - Math.round(y)) < EPS; } /* --------------------------------------------------------------- movement */ interface MoveResult { readonly x: number; readonly y: number; readonly pushedBombId?: string; readonly pushedTo?: { x: number; y: number }; } /** * Advance one technician along its input direction for a single tick. Movement is * grid-locked: a technician only leaves a cell center toward an adjacent open * cell, and finishes lining up on the perpendicular axis before turning. A * kick-capable technician shoves an adjacent charge one cell forward instead of * being blocked by it. */ function advancePlayer( state: BomperatorState, player: Player, bombs: readonly Bomb[], step: number, ): MoveResult { const dir = player.inputDir; if (!dir) return { x: player.x, y: player.y }; const [dx, dy] = DIR_VEC[dir]; const EPS = 1e-6; let { x, y } = player; if (dx !== 0) { // Finish aligning vertically before moving horizontally. if (Math.abs(y - Math.round(y)) > EPS) { const ty = Math.round(y); y += Math.sign(ty - y) * Math.min(Math.abs(ty - y), step); if (Math.abs(ty - y) < EPS) y = ty; return { x, y }; } const cy = Math.round(y); const entering = dx > 0 ? Math.floor(x) + 1 : Math.ceil(x) - 1; const home = dx > 0 ? Math.floor(x + EPS) : Math.ceil(x - EPS); const bomb = bombAt(bombs, entering, cy); if (bomb) { if (player.kick) { const bx = entering + dx; if (terrainIsOpen(state.grid, bx, cy) && !bombAt(bombs, bx, cy)) { return { x: approach(x, entering, step), y, pushedBombId: bomb.id, pushedTo: { x: bx, y: cy } }; } } return { x: home, y }; } if (!canStand(state, bombs, entering, cy)) return { x: home, y }; x = approach(x, entering, step); } else { // Finish aligning horizontally before moving vertically. if (Math.abs(x - Math.round(x)) > EPS) { const tX = Math.round(x); x += Math.sign(tX - x) * Math.min(Math.abs(tX - x), step); if (Math.abs(tX - x) < EPS) x = tX; return { x, y }; } const cx = Math.round(x); const entering = dy > 0 ? Math.floor(y) + 1 : Math.ceil(y) - 1; const home = dy > 0 ? Math.floor(y + EPS) : Math.ceil(y - EPS); const bomb = bombAt(bombs, cx, entering); if (bomb) { if (player.kick) { const by = entering + dy; if (terrainIsOpen(state.grid, cx, by) && !bombAt(bombs, cx, by)) { return { x, y: approach(y, entering, step), pushedBombId: bomb.id, pushedTo: { x: cx, y: by } }; } } return { x, y: home }; } if (!canStand(state, bombs, cx, entering)) return { x, y: home }; y = approach(y, entering, step); } return { x, y }; } function approach(current: number, target: number, step: number): number { const delta = target - current; if (Math.abs(delta) <= step) return target; return current + Math.sign(delta) * step; } /* -------------------------------------------------------------- explosions */ interface SimContext { grid: CellType[]; hidden: (PowerUpKind | null)[]; bombs: Bomb[]; flames: Flame[]; drops: Drop[]; events: BomperatorEvent[]; } /** * Spread a cross flame from a detonation. Each arm runs until it hits a solid * wall; the first crate in an arm is destroyed (revealing its power-up) and stops * that arm; another charge is either shoved along (kickable) or chain-detonated. */ function spreadExplosion( ctx: SimContext, centerX: number, centerY: number, range: number, sourceSeat: number | null, queue: Bomb[], ): void { const addFlame = (x: number, y: number) => { if (!ctx.flames.some((f) => f.x === x && f.y === y)) { ctx.flames.push({ x, y, ticksLeft: FLAME_LIFETIME_TICKS, sourceSeat }); } }; addFlame(centerX, centerY); for (const [dx, dy] of Object.values(DIR_VEC)) { let x = centerX + dx; let y = centerY + dy; for (let step = 1; step <= range; step += 1) { if (!inBounds(x, y)) break; const cell = ctx.grid[idx(x, y)]; if (cell === "solid") break; if (cell === "crate") { addFlame(x, y); destroyCrate(ctx, x, y); break; } const other = bombAt(ctx.bombs, x, y); if (other) { const remaining = range - step; const pushed = tryKickBomb(ctx, other, dx, dy, remaining); if (pushed) { // Flame fills the vacated trail up to (not including) the charge's rest. for (const cell of pushed) addFlame(cell.x, cell.y); } else { addFlame(x, y); queue.push(other); } break; } addFlame(x, y); x += dx; y += dy; } } } /** Destroy a crate at a cell and expose its hidden power-up as a drop. */ function destroyCrate(ctx: SimContext, x: number, y: number): void { const i = idx(x, y); if (ctx.grid[i] !== "crate") return; ctx.grid[i] = "empty"; const kind = ctx.hidden[i]; ctx.hidden[i] = null; if (kind) ctx.drops.push({ x, y, kind }); ctx.events.push({ type: "crateBroken", x, y }); } /** * Kick-push rule: shove a kickable charge along the flame direction by up to * `remaining` cells, stopping before the first blocked cell. Returns the vacated * trail (cells the flame may fill) on success, or null when it cannot move at all * (the caller then chain-detonates the charge instead). */ function tryKickBomb( ctx: SimContext, bomb: Bomb, dx: number, dy: number, remaining: number, ): { x: number; y: number }[] | null { if (!bomb.kickable || remaining < 1) return null; let bx = bomb.x; let by = bomb.y; const vacated: { x: number; y: number }[] = []; for (let i = 0; i < remaining; i += 1) { const nx = bx + dx; const ny = by + dy; if (!terrainIsOpen(ctx.grid, nx, ny) || bombAt(ctx.bombs, nx, ny)) break; vacated.push({ x: bx, y: by }); bx = nx; by = ny; } if (vacated.length === 0) return null; ctx.bombs = ctx.bombs.map((b) => (b.id === bomb.id ? { ...b, x: bx, y: by } : b)); return vacated; } /** Detonate a set of charges (fuses that expired), resolving chains. */ function detonateAll( ctx: SimContext, initial: readonly Bomb[], ): void { const queue: Bomb[] = [...initial]; const detonatedIds = new Set(); while (queue.length > 0) { const bomb = queue.shift()!; if (detonatedIds.has(bomb.id)) continue; // Remove it from the live set before spreading so it is not re-hit. ctx.bombs = ctx.bombs.filter((b) => b.id !== bomb.id); detonatedIds.add(bomb.id); ctx.events.push({ type: "explosion", x: bomb.x, y: bomb.y }); spreadExplosion(ctx, bomb.x, bomb.y, bomb.range, bomb.ownerSeat, queue); } } /* -------------------------------------------------------------------- tick */ const EVENT_BUFFER = 48; function withEvent(state: BomperatorState, event: BomperatorEvent): BomperatorState { const id = state.lastEventId + 1; const events = [...state.events, { ...event, id }].slice(-EVENT_BUFFER); return { ...state, events, lastEventId: id }; } /** * Advance the simulation by one fixed tick. Handles phase transitions * (countdown -> battle -> roundEnd -> next round / complete), movement, charge * placement, fuses and chain detonations, flame decay, pickups, elimination and * round-end checks, the round timer, and sudden-death spawning. */ export function tick(state: BomperatorState): BomperatorState { switch (state.phase) { case "countdown": return tickCountdown(state); case "battle": return tickBattle(state); case "roundEnd": return tickRoundEnd(state); default: // lobby / complete are inert to ticking. return { ...state, tickCount: state.tickCount + 1 }; } } function tickCountdown(state: BomperatorState): BomperatorState { const countdownTicks = state.countdownTicks - 1; if (countdownTicks > 0) { return { ...state, tickCount: state.tickCount + 1, countdownTicks }; } return { ...state, tickCount: state.tickCount + 1, countdownTicks: 0, phase: "battle" }; } function tickRoundEnd(state: BomperatorState): BomperatorState { const hold = state.roundEndHoldTicks - 1; if (hold > 0) { return { ...state, tickCount: state.tickCount + 1, roundEndHoldTicks: hold }; } // Advance to the next round. return startRound({ ...state, roundIndex: state.roundIndex + 1 }); } function tickBattle(state: BomperatorState): BomperatorState { let rngState = state.rngState; const ctx: SimContext = { grid: [...state.grid], hidden: [...state.hidden], bombs: [...state.bombs], flames: [...state.flames], drops: [...state.drops], events: [], }; // 1. Movement (with kick pushes applied to ctx.bombs). const players: Mutable[] = state.players.map((p) => ({ ...p })); for (let seat = 0; seat < players.length; seat += 1) { const p = players[seat]; if (!p.alive) continue; // Slip feel: with no active input, keep traveling in the last direction until // the technician reaches the next cell center, then rest exactly on it. This // reuses advancePlayer's collision rules, so a slip can never enter a wall or // charge; if the cell ahead is blocked the technician settles back onto the one // they are leaving. Resting on a whole cell also makes bomb/flame rounding exact. const slipping = p.inputDir === null && !isCellCentered(p.x, p.y); const dir = p.inputDir ?? (slipping ? p.dir : null); if (!dir) continue; const cellsPerTick = (p.speed * TICK_MS) / 1000; const res = advancePlayer(state, { ...p, inputDir: dir }, ctx.bombs, cellsPerTick); p.x = res.x; p.y = res.y; if (p.inputDir) p.dir = p.inputDir; if (res.pushedBombId && res.pushedTo) { ctx.bombs = ctx.bombs.map((b) => b.id === res.pushedBombId ? { ...b, x: res.pushedTo!.x, y: res.pushedTo!.y } : b, ); } } // 2. Charge placement. for (let seat = 0; seat < players.length; seat += 1) { const p = players[seat]; if (!p.alive || !p.wantDrop) continue; p.wantDrop = false; const cx = Math.round(p.x); const cy = Math.round(p.y); if (!terrainIsOpen(ctx.grid, cx, cy)) continue; if (bombAt(ctx.bombs, cx, cy)) continue; if (bombsActiveFor(ctx.bombs, seat) >= p.bombsMax) continue; ctx.bombs.push({ id: `${state.tickCount}:${seat}:${ctx.bombs.length}`, ownerSeat: seat, x: cx, y: cy, fuseTicks: BOMB_FUSE_TICKS, range: p.range, kickable: p.kick, }); } // 3. Advance fuses and detonate whatever reached zero (with chains). const expired: Bomb[] = []; ctx.bombs = ctx.bombs.map((b) => { const fuseTicks = b.fuseTicks - 1; if (fuseTicks <= 0) { expired.push({ ...b, fuseTicks: 0 }); return { ...b, fuseTicks: 0 }; } return { ...b, fuseTicks }; }); if (expired.length > 0) detonateAll(ctx, expired); // 4. Flame overlap kills (covers both fresh flames and lingering ones). for (let seat = 0; seat < players.length; seat += 1) { const p = players[seat]; if (!p.alive || p.invulnerableTicks > 0) continue; const cx = Math.round(p.x); const cy = Math.round(p.y); const hit = ctx.flames.find((f) => f.x === cx && f.y === cy); if (hit) { p.alive = false; p.deaths += 1; p.inputDir = null; p.wantDrop = false; const killerSeat = hit.sourceSeat !== null && hit.sourceSeat !== seat ? hit.sourceSeat : null; if (killerSeat !== null && players[killerSeat]) players[killerSeat].kills += 1; ctx.events.push({ type: "death", seat, killerSeat }); } } // 5. Pickups: a living technician entering an exposed drop collects it. for (let seat = 0; seat < players.length; seat += 1) { const p = players[seat]; if (!p.alive) continue; const cx = Math.round(p.x); const cy = Math.round(p.y); const di = ctx.drops.findIndex((d) => d.x === cx && d.y === cy); if (di >= 0) { const drop = ctx.drops[di]; ctx.drops.splice(di, 1); applyPowerUp(p, drop.kind); ctx.events.push({ type: "pickup", seat, kind: drop.kind }); } } // 6. Flame decay + spawn protection decay. ctx.flames = ctx.flames .map((f) => ({ ...f, ticksLeft: f.ticksLeft - 1 })) .filter((f) => f.ticksLeft > 0); for (const p of players) { if (p.invulnerableTicks > 0) p.invulnerableTicks -= 1; } // 7. Round timer / sudden death. let suddenDeath = state.suddenDeath; let suddenDeathTicks = state.suddenDeathTicks; let suddenDeathExplosions = state.suddenDeathExplosions; const aliveSeats = players.filter((p) => p.alive).map((p) => p.seat); if (aliveSeats.length > 1) { if (!suddenDeath) { const roundTimerTicks = state.roundTimerTicks - 1; if (roundTimerTicks <= 0) { suddenDeath = true; suddenDeathTicks = SUDDEN_DEATH_INTERVAL_TICKS; ctx.events.push({ type: "suddenDeath" }); } else { state = { ...state, roundTimerTicks }; } } if (suddenDeath) { suddenDeathTicks -= 1; if (suddenDeathTicks <= 0 && suddenDeathExplosions < MAX_SUDDEN_DEATH_EXPLOSIONS) { const draw = rng(rngState); rngState = draw.next; spawnSuddenDeath(ctx, draw.value); suddenDeathExplosions += 1; suddenDeathTicks = SUDDEN_DEATH_INTERVAL_TICKS; // Re-check kills from the new flames. for (let seat = 0; seat < players.length; seat += 1) { const p = players[seat]; if (!p.alive || p.invulnerableTicks > 0) continue; const cx = Math.round(p.x); const cy = Math.round(p.y); if (ctx.flames.some((f) => f.x === cx && f.y === cy)) { p.alive = false; p.deaths += 1; p.inputDir = null; ctx.events.push({ type: "death", seat, killerSeat: null }); } } } } } // 8. Round-end resolution. const survivors = players.filter((p) => p.alive); let next: BomperatorState = { ...state, tickCount: state.tickCount + 1, rngState, grid: ctx.grid, hidden: ctx.hidden, bombs: ctx.bombs, flames: ctx.flames, drops: ctx.drops, players, suddenDeath, suddenDeathTicks, suddenDeathExplosions, }; if (survivors.length <= 1) { next = resolveRoundEnd(next, survivors[0]?.seat ?? null); } else if (suddenDeath && suddenDeathExplosions >= MAX_SUDDEN_DEATH_EXPLOSIONS) { // Draw guard: sudden death spent its whole explosion budget without reducing // the field to one technician, so call the round a draw rather than loop. next = resolveRoundEnd(next, null); } // Fold this tick's events into the rolling buffer. for (const ev of ctx.events) next = withEvent(next, ev); return next; } function applyPowerUp(player: Mutable, kind: PowerUpKind): void { switch (kind) { case "bomb": player.bombsMax = Math.min(MAX_BOMBS, player.bombsMax + 1); break; case "range": player.range = Math.min(MAX_RANGE, player.range + 1); break; case "speed": player.speed = Math.min(MAX_SPEED_CELLS_PER_S, player.speed + SPEED_BOOST_CELLS_PER_S); break; case "kick": player.kick = true; break; } } /** Pick a random open cell and detonate a small charge there. */ function spawnSuddenDeath(ctx: SimContext, value: number): void { const openCells: Array<{ x: number; y: number }> = []; for (let y = 0; y < GRID_H; y += 1) { for (let x = 0; x < GRID_W; x += 1) { if (ctx.grid[idx(x, y)] === "empty" && !bombAt(ctx.bombs, x, y)) { openCells.push({ x, y }); } } } if (openCells.length === 0) return; const pick = openCells[Math.floor(value * openCells.length) % openCells.length]; const queue: Bomb[] = []; spreadExplosion( ctx, pick.x, pick.y, 1, null, queue, ); // Any charges caught by the sudden-death blast go off too. detonateAll(ctx, queue); ctx.events.push({ type: "explosion", x: pick.x, y: pick.y }); } /** Award a round and either continue to the next or complete the match. */ function resolveRoundEnd(state: BomperatorState, winnerSeat: number | null): BomperatorState { let players = state.players; let matchWinnerSeat: number | null = null; if (winnerSeat !== null) { players = players.map((p) => (p.seat === winnerSeat ? { ...p, roundsWon: p.roundsWon + 1 } : p)); const champ = players.find((p) => p.seat === winnerSeat); if (champ && champ.roundsWon >= state.roundTarget) matchWinnerSeat = winnerSeat; } let next: BomperatorState = { ...state, players, roundWinnerSeat: winnerSeat, bombs: [], flames: [], }; next = withEvent(next, { type: "roundEnd", roundIndex: state.roundIndex, winnerSeat }); if (matchWinnerSeat !== null) { return { ...next, phase: "complete", matchWinnerSeat, endReason: "rounds" }; } return { ...next, phase: "roundEnd", roundEndHoldTicks: ROUND_END_HOLD_TICKS }; } /** * End the match early (used by the registry when it dissolves below two seated * players). No round is awarded. */ export function dissolveMatch(state: BomperatorState): BomperatorState { return { ...state, phase: "complete", endReason: "dissolved", matchWinnerSeat: null }; }