Files
agentic-labs-challenge/body-snatcher/index.html
T
2026-08-12 15:56:07 +02:00

1089 lines
61 KiB
HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Body Snatcher</title>
<style>
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
display: grid;
place-items: center;
overflow: hidden;
background: #08090d;
color: #eef2ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
canvas {
width: min(800px, 100vw);
height: auto;
max-height: 100vh;
border: 1px solid #303342;
background: #0b0c12;
image-rendering: pixelated;
box-shadow: 0 24px 80px #000;
}
</style>
</head>
<body>
<canvas id="game" width="800" height="640" aria-label="Body Snatcher game canvas"></canvas>
<script>
(() => {
'use strict';
const TILE = 32, COLS = 25, ROWS = 18, HUD = 64, FOG_RADIUS = 5;
const canvas = document.getElementById('game') || document.querySelector('canvas');
const ctx = canvas && canvas.getContext ? canvas.getContext('2d') : null;
const DIRECTIONS = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
const MOVES = {
ArrowUp: [0, -1], ArrowDown: [0, 1], ArrowLeft: [-1, 0], ArrowRight: [1, 0],
w: [0, -1], W: [0, -1], s: [0, 1], S: [0, 1],
a: [-1, 0], A: [-1, 0], d: [1, 0], D: [1, 0]
};
const KITS = {
Brute: { ai: 'slow chase', color: '#df3f4f', maxHp: 8, enemyDamage: 2, damage: 3, speed: 2, special: 'heavy melee', essence: 3 },
Skitterer: { ai: 'swarm flank', color: '#f48a2a', maxHp: 2, enemyDamage: 1, damage: 1, speed: 1, special: 'rapid melee', essence: 1 },
Sentinel: { ai: 'ranged distance', color: '#9d64e8', maxHp: 4, enemyDamage: 0, damage: 0, speed: 1, projectileDamage: 1, special: 'projectile shot', essence: 3 },
Shielder: { ai: 'shield chase', color: '#3987e8', maxHp: 5, enemyDamage: 1, damage: 2, speed: 2, special: 'frontal shield', essence: 4 },
Bomber: { ai: 'suicide chase', color: '#8f2635', maxHp: 3, enemyDamage: 3, damage: 4, speed: 1, special: 'detonate', essence: 2 },
Healer: { ai: 'heal and flee', color: '#39bc68', maxHp: 3, enemyDamage: 0, damage: 0, speed: 2, special: 'healing pulse', essence: 5 },
Phaser: { ai: 'teleport ambush', color: '#39d7df', maxHp: 4, enemyDamage: 2, damage: 1, speed: 3, special: 'blink', essence: 4 },
Turret: { ai: 'rooted tracking', color: '#89909c', maxHp: 4, enemyDamage: 1, damage: 2, speed: 99, projectileDamage: 1, special: 'rapid fire', essence: 5 },
Charger: { ai: 'telegraph charge', color: '#e7c83e', maxHp: 5, enemyDamage: 3, damage: 2, speed: 1, special: 'dash charge', essence: 4 },
Siren: { ai: 'pull field', color: '#ed61b1', maxHp: 3, enemyDamage: 1, damage: 1, speed: 3, special: 'pull field', essence: 3 },
Mimic: { ai: 'disguise burst', color: '#9b663a', maxHp: 4, enemyDamage: 2, damage: 2, speed: 2, special: 'surprise burst', essence: 4 },
Leech: { ai: 'drain chase', color: '#582b7d', maxHp: 4, enemyDamage: 1, damage: 1, speed: 2, special: 'life drain', essence: 4 }
};
const UPGRADE_LIST = [
{ id: 'ghost1', tree: 'ghost', tier: 1, name: 'Lingering Spirit', text: 'Ghost timer lasts 8 seconds.', cost: 5 },
{ id: 'ghost2', tree: 'ghost', tier: 2, name: 'Long Reach', text: 'Possess enemies from 2 tiles away.', cost: 8, requires: 'ghost1' },
{ id: 'ghost3', tree: 'ghost', tier: 3, name: 'Wall Phase', text: 'Q phases through walls for 1 second.', cost: 12, requires: 'ghost2' },
{ id: 'ghost4', tree: 'ghost', tier: 4, name: 'Ghost Dash', text: 'Space dashes 3 tiles when no body is near.', cost: 15, requires: 'ghost3' },
{ id: 'body1', tree: 'body', tier: 1, name: 'Retain', text: 'Keep the previous host ability.', cost: 10 },
{ id: 'body2', tree: 'body', tier: 2, name: 'Overclock', text: 'Fresh hosts gain +50% power for 5 turns.', cost: 12, requires: 'body1' },
{ id: 'body3', tree: 'body', tier: 3, name: 'Dual Wield', text: 'Retain two previous host abilities.', cost: 18, requires: 'body2' },
{ id: 'meta1', tree: 'meta', tier: 1, name: 'Borrowed Start', text: 'Start each floor in a random body.', cost: 8 },
{ id: 'meta2', tree: 'meta', tier: 2, name: 'Ghost Sight', text: 'See enemy types through fog.', cost: 10, requires: 'meta1' },
{ id: 'meta3', tree: 'meta', tier: 3, name: 'Bargain', text: 'Shop prices are 30% lower.', cost: 6, requires: 'meta2' }
];
const FLOOR_POOLS = [
['Brute', 'Skitterer', 'Sentinel'],
['Brute', 'Skitterer', 'Sentinel', 'Shielder', 'Bomber', 'Charger'],
['Brute', 'Skitterer', 'Sentinel', 'Shielder', 'Bomber', 'Charger', 'Healer', 'Phaser', 'Siren', 'Turret'],
Object.keys(KITS)
];
let generation = 0;
function hasUpgrade(id) { return !!GAME.upgrades[id]; }
function ghostDuration() { return hasUpgrade('ghost1') ? 8 : 5; }
function randomInt(min, max) { return min + Math.floor(Math.random() * (max - min + 1)); }
function shuffle(items) {
for (let i = items.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[items[i], items[j]] = [items[j], items[i]];
}
return items;
}
let animationStarted = false, lastTime = 0;
let audioContext = null;
const ACHIEVEMENT_NAMES = ['First Possession', 'Body Hopper', 'Pacifist Ghost', 'Essence Hoarder', 'Deep Diver', 'Escape Artist', 'Bomberman', 'Dual Wield'];
const TONES = { hit: [150, .07, 'square'], possess: [330, .18, 'sine'], death: [110, .28, 'sawtooth'], pickup: [660, .12, 'triangle'], explosion: [70, .3, 'square'], achievement: [880, .25, 'sine'] };
function loadAchievements() {
let saved = {};
try { saved = JSON.parse(localStorage.getItem('bodysnatcher_achievements')) || {}; } catch (_) {}
return Object.fromEntries(ACHIEVEMENT_NAMES.map(name => [name, saved[name]?.unlocked || saved[name] === true ? { name, unlocked: true, unlockedAt: saved[name]?.unlockedAt || null } : { name, unlocked: false, unlockedAt: null }]));
}
function sound(name) {
try {
const Audio = window.AudioContext || window.webkitAudioContext;
if (!Audio) return false;
if (!audioContext) audioContext = new Audio();
if (audioContext.resume && audioContext.state === 'suspended') audioContext.resume();
const tone = TONES[name] || TONES.hit, oscillator = audioContext.createOscillator && audioContext.createOscillator(), gain = audioContext.createGain && audioContext.createGain();
if (!oscillator || !gain) return false;
const now = Number(audioContext.currentTime) || 0;
oscillator.type = tone[2];
if (oscillator.frequency?.setValueAtTime) oscillator.frequency.setValueAtTime(tone[0], now); else if (oscillator.frequency) oscillator.frequency.value = tone[0];
if (gain.gain?.setValueAtTime) gain.gain.setValueAtTime(.08, now); else if (gain.gain) gain.gain.value = .08;
if (gain.gain?.exponentialRampToValueAtTime) gain.gain.exponentialRampToValueAtTime(.001, now + tone[1]);
oscillator.connect && oscillator.connect(gain); gain.connect && gain.connect(audioContext.destination);
oscillator.start && oscillator.start(now); oscillator.stop && oscillator.stop(now + tone[1]);
return true;
} catch (_) { return false; }
}
function snapMotion(entity) {
if (!entity) return;
entity.renderX = entity.motionX = entity.x; entity.renderY = entity.motionY = entity.y; entity.motionTime = .15;
}
function animateEntity(entity, dt) {
if (!entity) return;
if (!Number.isFinite(entity.renderX) || !Number.isFinite(entity.renderY)) snapMotion(entity);
if (entity.motionX !== entity.x || entity.motionY !== entity.y) {
entity.fromX = entity.renderX; entity.fromY = entity.renderY; entity.motionX = entity.x; entity.motionY = entity.y; entity.motionTime = 0;
}
entity.motionTime = Math.min(.15, (entity.motionTime || 0) + dt);
const t = Math.min(1, entity.motionTime / .15), eased = 1 - Math.pow(1 - t, 3);
entity.renderX = (entity.fromX ?? entity.x) + (entity.motionX - (entity.fromX ?? entity.x)) * eased;
entity.renderY = (entity.fromY ?? entity.y) + (entity.motionY - (entity.fromY ?? entity.y)) * eased;
}
function emitParticles(x, y, color, count = 8) {
for (let i = 0; i < count; i++) {
const angle = Math.PI * 2 * i / count, speed = 1.4 + (i % 3) * .45;
GAME.particles.push({ x: x + .5, y: y + .5, vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed, life: .45, maxLife: .45, color });
}
}
function unlockAchievement(name) {
const achievement = GAME.achievements[name];
if (!achievement || achievement.unlocked) return false;
achievement.unlocked = true; achievement.unlockedAt = Date.now();
GAME.log.push(`Achievement unlocked: ${name}.`); sound('achievement');
try { localStorage.setItem('bodysnatcher_achievements', JSON.stringify(GAME.achievements)); } catch (_) {}
return true;
}
function checkAchievements() {
if ((GAME.runStats.possessedTypes || []).length >= 5) unlockAchievement('Body Hopper');
if (GAME.floor >= 3 && GAME.runStats.hostDamage === 0) unlockAchievement('Pacifist Ghost');
if (GAME.essence >= 30) unlockAchievement('Essence Hoarder');
if (GAME.floor >= 7) unlockAchievement('Deep Diver');
}
function addEssence(amount, x = GAME.player.x, y = GAME.player.y) {
amount = Math.max(0, Number(amount) || 0); GAME.essence += amount;
if (amount) { emitParticles(x, y, '#e8cf64', 6); sound('pickup'); checkAchievements(); }
return amount;
}
function statsLine() {
const stats = GAME.runStats;
return `FLOOR ${GAME.floor} · ${stats.kills} KILLS · ${stats.possessions} POSSESSIONS · ${GAME.essence} ESSENCE · ${GAME.turn} TURNS`;
}
function staticDungeon() {
const grid = Array.from({ length: ROWS }, (_, y) =>
Array.from({ length: COLS }, (_, x) =>
x === 0 || y === 0 || x === COLS - 1 || y === ROWS - 1 ? 'wall' : 'floor'
)
);
for (let x = 3; x <= 20; x++) if (x !== 7 && x !== 15) grid[4][x] = 'wall';
for (let x = 4; x <= 22; x++) if (x !== 11 && x !== 18) grid[9][x] = 'wall';
for (let x = 2; x <= 18; x++) if (x !== 6 && x !== 13) grid[14][x] = 'wall';
for (let y = 5; y <= 13; y++) if (y !== 9) grid[y][8] = 'wall';
for (let y = 1; y <= 8; y++) if (y !== 4) grid[y][17] = 'wall';
return grid;
}
function generateFloor(floor = GAME.floor) {
floor = Math.max(1, Math.min(10, Math.floor(Number(floor) || 1)));
const oldBody = GAME.player.host || GAME.player.body;
if (oldBody && hasUpgrade('body1')) {
const limit = hasUpgrade('body3') ? 2 : 1;
GAME.retainedAbilities = [oldBody.special, ...(GAME.retainedAbilities || []).filter(name => name !== oldBody.special)].slice(0, limit);
}
const grid = Array.from({ length: ROWS }, () => Array(COLS).fill('wall'));
const rooms = [], wanted = randomInt(5, 8);
generation++;
for (let attempt = 0; rooms.length < wanted && attempt < 300; attempt++) {
const room = { w: randomInt(4, 8), h: randomInt(4, 6) };
room.x = randomInt(1, COLS - room.w - 2);
room.y = randomInt(1, ROWS - room.h - 2);
if (rooms.some(other => room.x <= other.x + other.w && room.x + room.w >= other.x && room.y <= other.y + other.h && room.y + room.h >= other.y)) continue;
room.cx = room.x + Math.floor(room.w / 2); room.cy = room.y + Math.floor(room.h / 2);
rooms.push(room);
for (let y = room.y; y < room.y + room.h; y++) for (let x = room.x; x < room.x + room.w; x++) grid[y][x] = 'floor';
}
if (rooms.length < 5) return generateFloor(floor);
const carve = (x, y) => { if (grid[y]?.[x] != null) grid[y][x] = 'floor'; };
for (let i = 1; i < rooms.length; i++) {
let x = rooms[i - 1].cx, y = rooms[i - 1].cy;
const target = rooms[i];
if ((generation + i) % 2) {
while (x !== target.cx) { carve(x, y); x += Math.sign(target.cx - x); }
while (y !== target.cy) { carve(x, y); y += Math.sign(target.cy - y); }
} else {
while (y !== target.cy) { carve(x, y); y += Math.sign(target.cy - y); }
while (x !== target.cx) { carve(x, y); x += Math.sign(target.cx - x); }
}
carve(target.cx, target.cy);
}
const spawnRoom = rooms[0];
const exitRoom = rooms.slice(1).sort((a, b) => Math.abs(b.cx - spawnRoom.cx) + Math.abs(b.cy - spawnRoom.cy) - Math.abs(a.cx - spawnRoom.cx) - Math.abs(a.cy - spawnRoom.cy))[0];
grid[exitRoom.cy][exitRoom.cx] = 'exit';
const occupied = new Set([`${spawnRoom.cx},${spawnRoom.cy}`, `${exitRoom.cx},${exitRoom.cy}`]);
const openTiles = () => {
const tiles = [];
for (let y = 1; y < ROWS - 1; y++) for (let x = 1; x < COLS - 1; x++) if (grid[y][x] === 'floor' && !occupied.has(`${x},${y}`)) tiles.push({ x, y });
return shuffle(tiles);
};
for (const point of openTiles().slice(0, randomInt(1, 2))) { grid[point.y][point.x] = 'chest'; occupied.add(`${point.x},${point.y}`); }
GAME.floor = floor;
GAME.grid = grid;
GAME.enemies.length = 0;
GAME.projectiles.length = 0;
GAME.state = 'ghost';
Object.assign(GAME.player, {
x: spawnRoom.cx, y: spawnRoom.cy, hp: 1, maxHp: 1, mode: 'ghost', type: 'ghost', host: null, body: null,
damage: 0, speed: 1, special: 'possess', ability: 'possess', ghostTimer: ghostDuration(), timer: ghostDuration(),
facing: 'down', moveCounter: 0, phaseTime: 0, phaseCooldown: 0, dashCooldown: 0,
abilities: [...(GAME.retainedAbilities || [])]
});
snapMotion(GAME.player);
GAME.explored = fogMap(false);
GAME.visible = fogMap(false);
const pool = FLOOR_POOLS[floor <= 3 ? 0 : floor <= 6 ? 1 : floor <= 9 ? 2 : 3];
const spots = openTiles().filter(point => Math.abs(point.x - spawnRoom.cx) + Math.abs(point.y - spawnRoom.cy) > 3);
const roster = shuffle([...pool]);
for (let i = 0; i < 4 + floor && spots[i]; i++) {
const point = spots[i]; occupied.add(`${point.x},${point.y}`);
spawn(roster[i % roster.length], point.x, point.y);
}
if (hasUpgrade('meta1')) {
const type = pool[randomInt(0, pool.length - 1)];
possessEnemy(spawn(type, GAME.player.x, GAME.player.y), false);
}
updateFog();
checkAchievements();
GAME.log.push(`The ghost enters floor ${floor}.`);
render();
return grid;
}
function fogMap(value) {
return Array.from({ length: ROWS }, () => Array(COLS).fill(value));
}
function restoredFog(value) {
return Array.isArray(value) && value.length === ROWS && value.every(row => Array.isArray(row) && row.length === COLS)
? value.map(row => row.map(Boolean)) : fogMap(false);
}
function restoredEnemy(raw) {
const kit = raw && KITS[raw.type], x = Math.floor(Number(raw?.x)), y = Math.floor(Number(raw?.y));
if (!kit || !Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x >= COLS || y >= ROWS) return null;
const number = (value, fallback) => Number.isFinite(Number(value)) ? Number(value) : fallback;
const base = raw.baseStats, overclockTurns = Math.max(0, number(raw.overclockTurns, 0));
const overclock = overclockTurns > 0 && base && ['maxHp', 'damage', 'speed', 'projectileDamage'].every(key => Number.isFinite(Number(base[key])))
? { baseStats: { maxHp: Math.max(1, number(base.maxHp, kit.maxHp)), damage: Math.max(0, number(base.damage, kit.damage)), speed: Math.max(1, number(base.speed, kit.speed)), projectileDamage: Math.max(0, number(base.projectileDamage, kit.projectileDamage || 0)) }, overclockTurns }
: {};
return {
type: raw.type, x, y, hp: number(raw.hp, kit.maxHp), maxHp: Math.max(1, number(raw.maxHp, kit.maxHp)),
damage: Math.max(0, number(raw.damage, kit.enemyDamage)), speed: Math.max(1, number(raw.speed, kit.speed)),
special: kit.special, ability: kit.special, color: kit.color, essence: kit.essence,
projectileDamage: Math.max(0, number(raw.projectileDamage, kit.projectileDamage || 0)), enemyDamage: kit.enemyDamage,
facing: DIRECTIONS[raw.facing] ? raw.facing : 'down', turns: Math.max(0, number(raw.turns, 0)), hitFlash: 0,
disguised: raw.type === 'Mimic' && raw.disguised !== false, revealed: raw.type !== 'Mimic' || raw.revealed === true,
cooldown: Math.max(0, number(raw.cooldown, 0)), stunned: Math.max(0, number(raw.stunned, 0)),
...overclock
};
}
function isWall(x, y) {
const tile = GAME.grid[y] && GAME.grid[y][x];
return tile == null || tile === 1 || /wall|#/.test(String(tile && (tile.type || tile.kind || tile.tile) || tile).toLowerCase());
}
function enemyAt(x, y, except) {
return GAME.enemies.find(enemy => enemy !== except && enemy.hp > 0 && enemy.x === x && enemy.y === y);
}
function distance(a, b) { return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); }
function facingFrom(dx, dy) {
return Math.abs(dx) >= Math.abs(dy) ? (dx < 0 ? 'left' : 'right') : (dy < 0 ? 'up' : 'down');
}
function rotateFacing(facing, clockwise) {
const order = ['up', 'right', 'down', 'left'];
return order[(order.indexOf(facing) + (clockwise ? 1 : 3)) % 4];
}
function canStand(x, y, except) {
return !isWall(x, y) && !enemyAt(x, y, except) && !(GAME.player.x === x && GAME.player.y === y);
}
function lineOfSight(a, b) {
const dx = Math.sign(b.x - a.x), dy = Math.sign(b.y - a.y);
if (a.x !== b.x && a.y !== b.y) return false;
for (let x = a.x + dx, y = a.y + dy; x !== b.x || y !== b.y; x += dx, y += dy) if (isWall(x, y)) return false;
return true;
}
function findPath(sx, sy, tx, ty) {
const queue = [{ x: sx, y: sy }], seen = new Set([`${sx},${sy}`]), previous = new Map();
for (let i = 0; i < queue.length; i++) {
const current = queue[i];
if (current.x === tx && current.y === ty) {
const path = [current];
let key = `${current.x},${current.y}`;
while (previous.has(key)) {
const point = previous.get(key);
path.push(point);
key = `${point.x},${point.y}`;
}
return path.reverse();
}
for (const [dx, dy] of Object.values(DIRECTIONS)) {
const x = current.x + dx, y = current.y + dy, key = `${x},${y}`;
if (seen.has(key) || isWall(x, y)) continue;
seen.add(key);
previous.set(key, current);
queue.push({ x, y });
}
}
return [];
}
function spawn(type, x, y) {
const kit = KITS[type];
if (!kit) throw new Error(`Unknown enemy type: ${type}`);
const enemy = {
type, x: Number(x), y: Number(y), hp: kit.maxHp, maxHp: kit.maxHp,
damage: kit.enemyDamage, speed: kit.speed, special: kit.special, ability: kit.special,
color: kit.color, essence: kit.essence, projectileDamage: kit.projectileDamage || 0,
enemyDamage: kit.enemyDamage, facing: 'down', turns: 0, hitFlash: 0,
disguised: type === 'Mimic', revealed: type !== 'Mimic', cooldown: 0, stunned: 0
};
snapMotion(enemy);
GAME.enemies.push(enemy);
return enemy;
}
function damageEnemy(enemy, amount, source) {
if (!enemy || !GAME.enemies.includes(enemy) || enemy.hp <= 0) return false;
if (enemy.type === 'Shielder' && source) {
const incoming = facingFrom(source.x - enemy.x, source.y - enemy.y);
if (incoming === enemy.facing) { GAME.log.push('The shield blocked the hit.'); return false; }
}
const damage = Math.max(0, Number(amount) || 0);
enemy.hp -= damage; enemy.hitFlash = .1;
if (damage) { sound('hit'); if (damage >= 3) GAME.shake = Math.max(GAME.shake, 5); }
if (enemy.hp > 0) return false;
GAME.enemies.splice(GAME.enemies.indexOf(enemy), 1);
const essence = enemy.essence || KITS[enemy.type]?.essence || 0;
addEssence(essence, enemy.x, enemy.y); GAME.runStats.kills++;
emitParticles(enemy.x, enemy.y, enemy.color || '#fff', 12); sound('death');
GAME.log.push(`${enemy.type} fell. +${essence} essence.`);
if (enemy.type === 'Bomber') explode(enemy.x, enemy.y, 3, enemy);
return true;
}
function eject() {
const body = GAME.player.host || GAME.player.body;
if (!body) return;
GAME.log.push(`${body.type} body was destroyed.`); emitParticles(GAME.player.x, GAME.player.y, body.color || '#fff', 12); sound('death');
if (hasUpgrade('body1')) {
const limit = hasUpgrade('body3') ? 2 : 1;
GAME.retainedAbilities = [body.special, ...(GAME.retainedAbilities || []).filter(name => name !== body.special)].slice(0, limit);
}
Object.assign(GAME.player, {
hp: 1, maxHp: 1, mode: 'ghost', type: 'ghost', host: null, body: null,
damage: 0, speed: 1, special: 'possess', ability: 'possess', ghostTimer: ghostDuration(), timer: ghostDuration(),
abilities: [...(GAME.retainedAbilities || [])]
});
GAME.state = 'ghost';
}
function lose(message) {
if (GAME.state === 'lost' || GAME.state === 'gameover') return;
GAME.player.hp = Math.max(0, GAME.player.hp); GAME.player.ghostTimer = GAME.player.timer = 0;
GAME.state = 'lost'; GAME.log.push(message); sound('death'); render();
}
function damagePlayer(amount, source) {
const damage = Math.max(0, Number(amount) || 0);
const body = GAME.player.host || GAME.player.body;
if (GAME.state === 'possessed' && body?.type === 'Shielder' && source && facingFrom(source.x - GAME.player.x, source.y - GAME.player.y) === GAME.player.facing) {
GAME.log.push('Your shield blocked the hit.'); return;
}
if (damage) { GAME.player.hitFlash = .1; sound('hit'); if (damage >= 3) GAME.shake = Math.max(GAME.shake, 5); }
if (GAME.state === 'possessed') {
body.hp -= damage; body.hitFlash = .1; GAME.player.hp = body.hp; GAME.runStats.hostDamage += damage;
if (body.hp <= 0) eject();
} else if (GAME.state === 'ghost') {
GAME.player.hp -= damage;
if (GAME.player.hp <= 0) lose('The ghost was destroyed.');
}
}
function heal(entity, amount) {
entity.hp = Math.min(entity.maxHp, entity.hp + amount);
if (entity === GAME.player.host || entity === GAME.player.body) GAME.player.hp = entity.hp;
}
function explode(x, y, damage, source, playerOwned = false) {
let kills = 0;
GAME.shake = Math.max(GAME.shake, 10); emitParticles(x, y, '#ff784f', 18); sound('explosion');
for (const enemy of [...GAME.enemies]) if (Math.max(Math.abs(enemy.x - x), Math.abs(enemy.y - y)) <= 1 && damageEnemy(enemy, damage, source || { x, y })) kills++;
if (!playerOwned && Math.max(Math.abs(GAME.player.x - x), Math.abs(GAME.player.y - y)) <= 1) damagePlayer(damage, source || { x, y });
GAME.log.push(`Explosion at ${x},${y}.`); return kills;
}
function movePointToward(entity, target, toward = true) {
const choices = Object.values(DIRECTIONS).map(([dx, dy]) => ({ x: entity.x + dx, y: entity.y + dy }))
.filter(point => canStand(point.x, point.y, entity))
.sort((a, b) => (toward ? 1 : -1) * (distance(a, target) - distance(b, target)));
if (choices[0]) { entity.facing = facingFrom(choices[0].x - entity.x, choices[0].y - entity.y); Object.assign(entity, choices[0]); return true; }
return false;
}
function possessEnemy(enemy, autosave = true) {
if (!enemy) return false;
const player = GAME.player, index = GAME.enemies.indexOf(enemy);
if (index >= 0) GAME.enemies.splice(index, 1);
const kit = KITS[enemy.type];
Object.assign(enemy, { damage: kit.damage, speed: kit.speed, special: kit.special, ability: kit.special, enemyDamage: kit.enemyDamage });
if (hasUpgrade('body2')) {
enemy.baseStats = { maxHp: enemy.maxHp, damage: enemy.damage, speed: enemy.speed, projectileDamage: enemy.projectileDamage };
enemy.maxHp = Math.ceil(enemy.maxHp * 1.5); enemy.hp = Math.ceil(enemy.hp * 1.5); enemy.damage = Math.ceil(enemy.damage * 1.5);
enemy.projectileDamage = Math.ceil((enemy.projectileDamage || 0) * 1.5); enemy.speed = Math.max(1, Math.floor(enemy.speed / 1.5)); enemy.overclockTurns = 5;
}
const dx = enemy.x - player.x, dy = enemy.y - player.y;
Object.assign(player, {
x: enemy.x, y: enemy.y, hp: enemy.hp, maxHp: enemy.maxHp, mode: 'possessed', type: enemy.type, host: enemy, body: enemy,
damage: enemy.damage, speed: enemy.speed, special: enemy.special, ability: enemy.ability,
abilities: [enemy.special, ...(GAME.retainedAbilities || [])], facing: dx < 0 ? 'left' : dx > 0 ? 'right' : dy < 0 ? 'up' : 'down', moveCounter: 0
});
GAME.state = 'possessed'; GAME.runStats.possessions++;
if (!GAME.runStats.possessedTypes.includes(enemy.type)) GAME.runStats.possessedTypes.push(enemy.type);
emitParticles(player.x, player.y, '#f4f8ff', 14); sound('possess'); unlockAchievement('First Possession'); checkAchievements();
GAME.log.push(`Possessed ${enemy.type}.`); updateFog();
if (autosave && GAME.save) GAME.save();
return true;
}
function possess() {
const range = hasUpgrade('ghost2') ? 2 : 1, player = GAME.player;
return possessEnemy(GAME.enemies.find(item => Math.abs(item.x - player.x) + Math.abs(item.y - player.y) <= range));
}
function fireProjectile(owner, x, y, dx, dy, damage, homing = false) {
GAME.projectiles.push({ owner, x, y, dx, dy, damage, homing, age: 0 });
}
function playerAttack() {
const player = GAME.player, body = player.host || player.body;
if (!body) return;
const [dx, dy] = DIRECTIONS[player.facing] || DIRECTIONS.down;
if (body.type === 'Sentinel' || body.type === 'Turret') {
fireProjectile('player', player.x, player.y, dx, dy, body.projectileDamage || body.damage || 1);
} else if (body.type === 'Bomber') {
const kills = explode(player.x, player.y, 4, player, true); if (kills >= 3) unlockAchievement('Bomberman'); body.hp = 0; player.hp = 0; eject();
} else if (body.type === 'Healer') {
heal(body, 2);
} else if (body.type === 'Phaser') {
if (body.cooldown > 0) return;
let destination = { x: player.x, y: player.y };
for (let i = 1; i <= 5; i++) {
const point = { x: player.x + dx * i, y: player.y + dy * i };
if (GAME.grid[point.y] && GAME.grid[point.y][point.x] != null && !isWall(point.x, point.y) && !enemyAt(point.x, point.y)) destination = point;
}
Object.assign(player, destination); Object.assign(body, destination); body.cooldown = 3;
} else if (body.type === 'Charger') {
for (let i = 0; i < 4; i++) {
const x = player.x + dx, y = player.y + dy;
if (isWall(x, y)) break;
const target = enemyAt(x, y);
if (target) damageEnemy(target, 2, player);
player.x = x; player.y = y; body.x = x; body.y = y;
}
} else if (body.type === 'Siren') {
for (const enemy of GAME.enemies) if (distance(enemy, player) <= 4 && distance(enemy, player) > 1) movePointToward(enemy, player);
} else if (body.type === 'Mimic') {
body.disguised = false; body.revealed = true;
for (const enemy of [...GAME.enemies]) if (Math.abs(enemy.x - player.x) + Math.abs(enemy.y - player.y) <= 1) damageEnemy(enemy, 2, player);
} else {
const target = enemyAt(player.x + dx, player.y + dy);
if (target) { const before = target.hp; damageEnemy(target, body.damage, player); if (body.type === 'Leech' && target.hp < before) heal(body, 1); }
}
}
function useRetained(slot) {
const special = GAME.retainedAbilities[slot], body = GAME.player.host || GAME.player.body;
const type = Object.keys(KITS).find(name => KITS[name].special === special);
if (!body || !type || type === body.type) return false;
const originalType = body.type, playerType = GAME.player.type;
body.type = type; GAME.player.type = type;
playerAttack();
body.type = originalType;
if (GAME.player.host) GAME.player.type = playerType;
enemyTurn(); updateFog(); render();
return true;
}
function moveEnemy(enemy) {
const player = GAME.player;
if (distance(enemy, player) === 1) {
if (enemy.type === 'Bomber') { addEssence(enemy.essence, enemy.x, enemy.y); GAME.runStats.kills++; GAME.log.push(`Bomber fell. +${enemy.essence} essence.`); GAME.enemies.splice(GAME.enemies.indexOf(enemy), 1); explode(enemy.x, enemy.y, 3, enemy); return; }
const before = GAME.player.hp;
damagePlayer(enemy.damage, enemy);
if (enemy.type === 'Leech' && GAME.player.hp < before) heal(enemy, 1);
return;
}
const path = findPath(enemy.x, enemy.y, player.x, player.y);
const next = path[1];
if (next && !enemyAt(next.x, next.y, enemy) && !(next.x === player.x && next.y === player.y)) {
enemy.facing = facingFrom(next.x - enemy.x, next.y - enemy.y);
enemy.x = next.x; enemy.y = next.y;
}
}
function moveSentinel(enemy) {
const player = GAME.player;
const distance = Math.abs(enemy.x - player.x) + Math.abs(enemy.y - player.y);
if (distance <= 6) {
const horizontal = Math.abs(player.x - enemy.x) >= Math.abs(player.y - enemy.y);
fireProjectile('enemy', enemy.x, enemy.y,
horizontal ? Math.sign(player.x - enemy.x) : 0,
horizontal ? 0 : Math.sign(player.y - enemy.y), enemy.projectileDamage || 1);
}
if (distance > 4) return moveEnemy(enemy);
if (distance < 4) {
const choices = Object.values(DIRECTIONS).map(([dx, dy]) => ({ x: enemy.x + dx, y: enemy.y + dy }))
.filter(point => !isWall(point.x, point.y) && !enemyAt(point.x, point.y, enemy) && !(point.x === player.x && point.y === player.y))
.sort((a, b) => (Math.abs(b.x - player.x) + Math.abs(b.y - player.y)) - (Math.abs(a.x - player.x) + Math.abs(a.y - player.y)));
if (choices[0]) Object.assign(enemy, choices[0]);
}
}
function moveSkitterer(enemy) {
if (distance(enemy, GAME.player) === 1) return moveEnemy(enemy);
const swarm = GAME.enemies.filter(other => other !== enemy && other.type === 'Skitterer');
const flank = Object.values(DIRECTIONS).map(([dx, dy]) => ({ x: GAME.player.x + dx, y: GAME.player.y + dy }))
.filter(point => canStand(point.x, point.y, enemy))
.sort((a, b) => distance(enemy, a) + (swarm[0] ? distance(a, swarm[0]) * .25 : 0) - distance(enemy, b) - (swarm[0] ? distance(b, swarm[0]) * .25 : 0))[0];
const path = findPath(enemy.x, enemy.y, (flank || GAME.player).x, (flank || GAME.player).y), next = path[1];
if (next && canStand(next.x, next.y, enemy)) Object.assign(enemy, next);
}
function enemyHealer(enemy) {
for (const ally of GAME.enemies) if (ally !== enemy && distance(enemy, ally) <= 3) heal(ally, 1);
if (distance(enemy, GAME.player) <= 4) movePointToward(enemy, GAME.player, false);
else {
const hurt = GAME.enemies.filter(ally => ally !== enemy).sort((a, b) => (a.hp === a.maxHp) - (b.hp === b.maxHp) || distance(enemy, a) - distance(enemy, b))[0];
if (hurt && distance(enemy, hurt) > 2) movePointToward(enemy, hurt);
}
}
function enemyPhaser(enemy) {
if (distance(enemy, GAME.player) === 1) { damagePlayer(enemy.damage, enemy); return; }
if (!lineOfSight(enemy, GAME.player)) return;
const path = findPath(enemy.x, enemy.y, GAME.player.x, GAME.player.y), point = path[Math.min(path.length - 1, 2)];
if (point && canStand(point.x, point.y, enemy)) Object.assign(enemy, point);
if (distance(enemy, GAME.player) === 1) damagePlayer(enemy.damage, enemy);
}
function enemyTurret(enemy) {
const player = GAME.player, path = findPath(enemy.x, enemy.y, player.x, player.y);
if (!path[1]) return;
const dx = path[1].x - enemy.x, dy = path[1].y - enemy.y;
enemy.facing = facingFrom(player.x - enemy.x, player.y - enemy.y);
fireProjectile('enemy', enemy.x, enemy.y, dx, dy, enemy.projectileDamage || 1, true);
}
function enemyCharger(enemy) {
if (enemy.stunned > 0) { enemy.stunned--; return; }
if (!enemy.chargeTarget) {
const dx = GAME.player.x - enemy.x, dy = GAME.player.y - enemy.y;
if (dx !== 0 && dy !== 0) { moveEnemy(enemy); return; }
enemy.chargeTarget = { x: GAME.player.x, y: GAME.player.y }; enemy.telegraph = 1; return;
}
const target = enemy.chargeTarget; enemy.chargeTarget = null; enemy.telegraph = 0;
const step = [Math.sign(target.x - enemy.x), Math.sign(target.y - enemy.y)];
enemy.facing = facingFrom(...step);
for (let i = 0; i < 6; i++) {
const x = enemy.x + step[0], y = enemy.y + step[1];
if (isWall(x, y)) { enemy.stunned = 2; break; }
if (enemyAt(x, y, enemy)) break;
enemy.x = x; enemy.y = y;
if (x === GAME.player.x && y === GAME.player.y) { damagePlayer(3, enemy); break; }
}
}
function enemySiren(enemy) {
if (distance(enemy, GAME.player) === 1) { damagePlayer(enemy.damage, enemy); return; }
if (distance(enemy, GAME.player) > 5) return;
const point = Object.values(DIRECTIONS).map(([dx, dy]) => ({ x: GAME.player.x + dx, y: GAME.player.y + dy }))
.filter(p => !isWall(p.x, p.y) && !enemyAt(p.x, p.y)).sort((a, b) => distance(a, enemy) - distance(b, enemy))[0];
if (point) { Object.assign(GAME.player, point); if (GAME.player.host) Object.assign(GAME.player.host, point); }
}
function enemyMimic(enemy) {
if (enemy.disguised && distance(enemy, GAME.player) === 1) {
enemy.disguised = false; enemy.revealed = true; enemy.color = '#b88935'; damagePlayer(2, enemy); return;
}
if (enemy.revealed) moveEnemy(enemy);
}
function updateProjectiles() {
for (const projectile of [...GAME.projectiles]) {
projectile.age++;
if (projectile.age === 1) continue;
if (projectile.homing && projectile.owner === 'enemy') {
const path = findPath(projectile.x, projectile.y, GAME.player.x, GAME.player.y);
if (path[1]) { projectile.dx = path[1].x - projectile.x; projectile.dy = path[1].y - projectile.y; }
}
projectile.x += projectile.dx; projectile.y += projectile.dy;
let remove = isWall(projectile.x, projectile.y);
if (!remove && projectile.owner === 'player') {
const target = enemyAt(projectile.x, projectile.y);
if (target) { damageEnemy(target, projectile.damage, GAME.player); remove = true; }
} else if (!remove && projectile.owner === 'enemy' && projectile.x === GAME.player.x && projectile.y === GAME.player.y) {
damagePlayer(projectile.damage, { x: projectile.x - projectile.dx, y: projectile.y - projectile.dy }); remove = true;
}
if (remove) GAME.projectiles.splice(GAME.projectiles.indexOf(projectile), 1);
}
}
function enemyTurn() {
GAME.turn++;
const hiddenMimic = GAME.state === 'possessed' && GAME.player.type === 'Mimic' && GAME.player.host?.disguised;
const body = GAME.player.host || GAME.player.body;
if (body?.cooldown > 0) body.cooldown--;
if (body?.overclockTurns > 0 && --body.overclockTurns === 0) {
const ratio = body.baseStats.maxHp / body.maxHp;
body.maxHp = body.baseStats.maxHp;
body.hp = Math.max(1, Math.min(body.maxHp, Math.ceil(body.hp * ratio)));
body.damage = body.baseStats.damage; body.speed = body.baseStats.speed; body.projectileDamage = body.baseStats.projectileDamage;
Object.assign(GAME.player, { hp: body.hp, maxHp: body.maxHp, damage: body.damage, speed: body.speed });
}
for (const enemy of [...GAME.enemies]) {
if (!GAME.enemies.includes(enemy) || GAME.state === 'lost') continue;
enemy.turns++;
if (enemy.cooldown > 0) enemy.cooldown--;
if (enemy.type === 'Healer') { enemyHealer(enemy); continue; }
if (hiddenMimic) continue;
if (enemy.type === 'Turret') { enemyTurret(enemy); continue; }
if (enemy.type === 'Siren') { enemySiren(enemy); if (enemy.turns % enemy.speed) continue; }
if (enemy.type === 'Mimic') { enemyMimic(enemy); continue; }
if (enemy.turns % enemy.speed) continue;
if (enemy.type === 'Sentinel') moveSentinel(enemy);
else if (enemy.type === 'Skitterer') moveSkitterer(enemy);
else if (enemy.type === 'Phaser') enemyPhaser(enemy);
else if (enemy.type === 'Charger') enemyCharger(enemy);
else moveEnemy(enemy);
}
updateProjectiles();
}
function updateFog() {
GAME.visible = fogMap(false);
for (let y = 0; y < ROWS; y++) for (let x = 0; x < COLS; x++) {
const dx = x - GAME.player.x, dy = y - GAME.player.y;
if (dx * dx + dy * dy <= FOG_RADIUS * FOG_RADIUS) {
GAME.visible[y][x] = true;
GAME.explored[y][x] = true;
}
}
}
function update(dt, advanceTurn) {
dt = Math.max(0, Math.min(.1, Number(dt) || 0));
if (GAME.state === 'possessed') {
const body = GAME.player.host || GAME.player.body;
if (!body || body.hp <= 0 || GAME.player.hp <= 0) eject();
else GAME.player.hp = body.hp;
} else if (GAME.state === 'ghost') {
const player = GAME.player;
player.ghostTimer = Math.max(0, player.ghostTimer - dt); player.timer = player.ghostTimer;
player.phaseTime = Math.max(0, (player.phaseTime || 0) - dt);
player.phaseCooldown = Math.max(0, (player.phaseCooldown || 0) - dt);
player.dashCooldown = Math.max(0, (player.dashCooldown || 0) - dt);
if (player.ghostTimer === 0) lose('The ghost faded away.');
}
if (advanceTurn && (GAME.state === 'ghost' || GAME.state === 'possessed')) enemyTurn();
const moving = [GAME.player, ...GAME.enemies, ...GAME.projectiles];
for (const entity of moving) {
animateEntity(entity, dt);
if (entity.hitFlash > 0) entity.hitFlash = Math.max(0, entity.hitFlash - dt);
}
for (const particle of [...GAME.particles]) {
particle.x += particle.vx * dt; particle.y += particle.vy * dt; particle.vy += 2.5 * dt; particle.life -= dt;
if (particle.life <= 0) GAME.particles.splice(GAME.particles.indexOf(particle), 1);
}
GAME.shake = Math.max(0, GAME.shake - dt * 35);
}
const GAME = window.GAME = {
state: 'title',
player: { x: 2, y: 2, hp: 1, maxHp: 1, mode: 'ghost', type: 'ghost', ghostTimer: 5, timer: 5, facing: 'down' },
enemies: [], projectiles: [], particles: [], grid: staticDungeon(), floor: 1, essence: 0,
upgrades: {}, achievements: loadAchievements(), log: [], explored: fogMap(false), visible: fogMap(false), turn: 0,
shopChoices: [], shopSelection: 0, pendingFloor: 0, retainedAbilities: [], shake: 0, pausedFrom: 'ghost',
runStats: { kills: 0, possessions: 0, possessedTypes: [], hostDamage: 0 },
continueAvailable: (() => { try { return !!localStorage.getItem('bodysnatcher_save'); } catch (_) { return false; } })(),
start() {
if (this.state === 'title' && !this.continueAvailable) this.newRun();
else if (this.state === 'lost' || this.state === 'gameover' || this.state === 'won' || this.state === 'victory') this.newRun();
if (!animationStarted) {
animationStarted = true; lastTime = performance.now(); requestAnimationFrame(frame);
}
render(); return this;
},
newRun() {
this.floor = 1; this.essence = 0; this.upgrades = {};
this.enemies.length = 0; this.projectiles.length = 0; this.particles.length = 0; this.log.length = 0;
this.turn = 0; this.pendingFloor = 0; this.shopChoices = []; this.retainedAbilities = []; this.shake = 0;
this.runStats = { kills: 0, possessions: 0, possessedTypes: [], hostDamage: 0 };
this.continueAvailable = false;
try { localStorage.removeItem('bodysnatcher_save'); } catch (_) {}
generateFloor(1); this.save(); return this;
},
generateFloor,
completeFloor() {
if (this.floor >= 10) {
this.state = 'won'; this.log.push('The ghost escaped the tenth floor.');
unlockAchievement('Escape Artist'); sound('achievement'); this.save(); render(); return this;
}
this.pendingFloor = this.floor + 1; this.state = 'shop';
const eligible = UPGRADE_LIST.filter(item => !this.upgrades[item.id] && (!item.requires || this.upgrades[item.requires]));
const locked = UPGRADE_LIST.filter(item => !this.upgrades[item.id] && !eligible.includes(item));
this.shopChoices = [...shuffle(eligible), ...shuffle(locked)].slice(0, 3).map(item => ({ ...item, price: Math.ceil(item.cost * (hasUpgrade('meta3') ? .7 : 1)) }));
while (this.shopChoices.length < 3) this.shopChoices.push({ id: 'sold-out', name: 'Sold Out', text: 'No upgrades remain.', cost: 0, price: 0, locked: true });
this.shopSelection = 0; this.save(); render(); return this;
},
leaveShop() {
const next = this.pendingFloor || Math.min(10, this.floor + 1);
this.pendingFloor = 0;
generateFloor(next);
this.save();
return this;
},
buyUpgrade(index) {
const choice = this.shopChoices[Math.floor(Number(index))];
if (!choice || choice.locked || choice.id === 'sold-out' || this.upgrades[choice.id] || (choice.requires && !this.upgrades[choice.requires])) return false;
const price = Math.ceil(choice.cost * (hasUpgrade('meta3') ? .7 : 1));
if (this.essence < price) return false;
this.essence -= price; this.upgrades[choice.id] = true; this.log.push(`Purchased ${choice.name}.`);
if (choice.id === 'body3') unlockAchievement('Dual Wield');
this.save(); if (this.state === 'shop') this.leaveShop(); return true;
},
save() {
try {
const { host, body, ...player } = this.player;
localStorage.setItem('bodysnatcher_save', JSON.stringify({
state: this.state === 'paused' ? this.pausedFrom : this.state, floor: this.floor, essence: this.essence, upgrades: this.upgrades,
grid: this.grid, enemies: this.enemies, projectiles: this.projectiles, player,
host: host || body || null, explored: this.explored, visible: this.visible, turn: this.turn,
pendingFloor: this.pendingFloor, shopChoices: this.shopChoices, shopSelection: this.shopSelection,
retainedAbilities: this.retainedAbilities, runStats: this.runStats, log: this.log.slice(-30)
}));
this.continueAvailable = true; return true;
} catch (_) { return false; }
},
load() {
try {
const data = JSON.parse(localStorage.getItem('bodysnatcher_save'));
if (!data || !data.player || typeof data.player !== 'object' || !Array.isArray(data.grid) || data.grid.length !== ROWS || data.grid.some(row => !Array.isArray(row) || row.length !== COLS)) return false;
const number = (value, fallback) => Number.isFinite(Number(value)) ? Number(value) : fallback;
const states = ['ghost', 'possessed', 'playing', 'shop', 'won', 'victory', 'lost', 'gameover'];
this.state = states.includes(data.state) ? data.state : 'ghost';
this.floor = Math.max(1, Math.min(10, Math.floor(number(data.floor, 1))));
this.essence = Math.max(0, Math.floor(number(data.essence, 0)));
this.upgrades = data.upgrades && typeof data.upgrades === 'object' && !Array.isArray(data.upgrades) ? data.upgrades : {};
this.grid = data.grid;
this.enemies = (Array.isArray(data.enemies) ? data.enemies : []).map(restoredEnemy).filter(enemy => enemy && enemy.hp > 0);
this.projectiles = (Array.isArray(data.projectiles) ? data.projectiles : []).filter(item => item && Number.isFinite(Number(item.x)) && Number.isFinite(Number(item.y))).map(item => ({ ...item, x: number(item.x, 0), y: number(item.y, 0), dx: number(item.dx, 0), dy: number(item.dy, 0), damage: Math.max(0, number(item.damage, 0)), owner: item.owner === 'player' ? 'player' : 'enemy' }));
this.particles.length = 0; this.explored = restoredFog(data.explored); this.visible = restoredFog(data.visible); this.turn = Math.max(0, Math.floor(number(data.turn, 0)));
this.pendingFloor = Math.max(0, Math.min(10, Math.floor(number(data.pendingFloor, 0))));
this.shopChoices = (Array.isArray(data.shopChoices) ? data.shopChoices : []).filter(choice => choice && typeof choice.name === 'string' && typeof choice.text === 'string').slice(0, 3);
while (this.state === 'shop' && this.shopChoices.length < 3) this.shopChoices.push({ id: 'sold-out', name: 'Sold Out', text: 'No upgrade available.', cost: 0, price: 0, locked: true });
this.shopSelection = Math.max(0, Math.min(2, Math.floor(number(data.shopSelection, 0))));
this.retainedAbilities = (Array.isArray(data.retainedAbilities) ? data.retainedAbilities : []).filter(name => typeof name === 'string').slice(0, 2);
const stats = data.runStats && typeof data.runStats === 'object' ? data.runStats : {};
this.runStats = {
kills: Math.max(0, Math.floor(number(stats.kills, 0))), possessions: Math.max(0, Math.floor(number(stats.possessions, 0))),
possessedTypes: (Array.isArray(stats.possessedTypes) ? stats.possessedTypes : []).filter(type => KITS[type]),
hostDamage: Math.max(0, number(stats.hostDamage, 0))
};
this.log = (Array.isArray(data.log) ? data.log : []).filter(item => typeof item === 'string').slice(-30);
Object.assign(this.player, data.player);
let x = Math.floor(number(this.player.x, 1)), y = Math.floor(number(this.player.y, 1));
if (!this.grid[y]?.[x] || isWall(x, y)) {
const origin = { x, y }; let best = { x: 1, y: 1, distance: Infinity };
for (let yy = 0; yy < ROWS; yy++) for (let xx = 0; xx < COLS; xx++) if (!isWall(xx, yy)) {
const candidate = Math.abs(xx - origin.x) + Math.abs(yy - origin.y);
if (candidate < best.distance) best = { x: xx, y: yy, distance: candidate };
}
x = best.x; y = best.y;
}
Object.assign(this.player, { x, y, hp: number(this.player.hp, 1), maxHp: Math.max(1, number(this.player.maxHp, 1)), ghostTimer: Math.max(0, number(this.player.ghostTimer, ghostDuration())), timer: Math.max(0, number(this.player.timer, ghostDuration())) });
const host = this.state === 'ghost' ? null : restoredEnemy(data.host);
if (host) {
Object.assign(host, { x, y }); this.player.host = host; this.player.body = host;
Object.assign(this.player, { type: host.type, mode: 'possessed', hp: host.hp, maxHp: host.maxHp, damage: host.damage, speed: host.speed, special: host.special, ability: host.special });
} else {
this.player.host = null; this.player.body = null;
if (this.state === 'possessed') this.state = 'ghost';
if (this.state === 'ghost') Object.assign(this.player, { type: 'ghost', mode: 'ghost', hp: Math.max(1, this.player.hp), maxHp: 1, damage: 0, speed: 1, special: 'possess', ability: 'possess' });
}
this.player.facing = DIRECTIONS[this.player.facing] ? this.player.facing : 'down';
this.player.abilities = host ? [host.special, ...this.retainedAbilities] : [...this.retainedAbilities];
snapMotion(this.player); if (host) snapMotion(host); for (const entity of [...this.enemies, ...this.projectiles]) snapMotion(entity);
this.continueAvailable = false; checkAchievements(); updateFog(); render(); return true;
} catch (_) { return false; }
},
saveAndQuit() {
const resumableState = this.state === 'paused' ? this.pausedFrom : this.state;
this.state = resumableState; this.save(); this.state = 'title'; this.continueAvailable = true; render(); return true;
},
input(key) {
if (this.state === 'title') {
if (this.continueAvailable) {
if (key === 'y' || key === 'Y') { if (this.load()) this.start(); return; }
if (key === 'n' || key === 'N') { this.newRun(); this.start(); return; }
return;
}
this.start(); return;
}
if (this.state === 'lost' || this.state === 'gameover' || this.state === 'won' || this.state === 'victory') { this.newRun(); this.start(); return; }
if (this.state === 'paused') {
if (key === 'Escape') { this.state = this.pausedFrom; render(); }
else if (key === 'Enter') this.saveAndQuit();
return;
}
if (key === 'Escape' && (this.state === 'ghost' || this.state === 'possessed' || this.state === 'playing')) {
this.pausedFrom = this.state; this.state = 'paused'; render(); return;
}
if (this.state === 'shop') {
if (key === 'ArrowLeft' || key === 'a' || key === 'A') this.shopSelection = (this.shopSelection + 2) % 3;
else if (key === 'ArrowRight' || key === 'd' || key === 'D') this.shopSelection = (this.shopSelection + 1) % 3;
else if (key === 'Enter') this.buyUpgrade(this.shopSelection);
else if (key === ' ' || key === 'Space' || key === 'Escape') this.leaveShop();
render(); return;
}
if ((key === 'q' || key === 'Q') && this.state === 'ghost' && hasUpgrade('ghost3') && this.player.phaseCooldown <= 0) {
this.player.phaseTime = 1; this.player.phaseCooldown = 5; this.log.push('The ghost slips between walls.'); render(); return;
}
if (this.state === 'possessed' && (key === 'r' || key === 'R' || key === 'f' || key === 'F')) {
useRetained(key === 'f' || key === 'F' ? 1 : 0); return;
}
if ((key === 'q' || key === 'Q' || key === 'e' || key === 'E') && this.state === 'possessed' && (this.player.type === 'Shielder' || this.player.type === 'Turret')) {
this.player.facing = rotateFacing(this.player.facing, key === 'e' || key === 'E');
this.player.host.facing = this.player.facing; enemyTurn(); render(); return;
}
if (key === ' ' || key === 'Space') {
if (this.state === 'ghost') {
const possessed = possess();
if (!possessed && hasUpgrade('ghost4') && this.player.dashCooldown <= 0) {
const [dx, dy] = DIRECTIONS[this.player.facing] || DIRECTIONS.down;
for (let i = 0; i < 3; i++) {
const x = this.player.x + dx, y = this.player.y + dy;
if (!this.grid[y]?.[x] || (isWall(x, y) && this.player.phaseTime <= 0) || enemyAt(x, y)) break;
this.player.x = x; this.player.y = y;
}
this.player.dashCooldown = 3;
const tile = this.grid[this.player.y][this.player.x];
if (tile === 'chest') { const found = randomInt(2, 5); addEssence(found, this.player.x, this.player.y); this.grid[this.player.y][this.player.x] = 'floor'; this.log.push(`Chest opened. +${found} essence.`); }
if (tile === 'exit') { this.completeFloor(); return; }
}
} else if (this.state === 'possessed') playerAttack();
else return;
enemyTurn(); updateFog(); render(); return;
}
if (this.state !== 'ghost' && this.state !== 'possessed' && this.state !== 'playing') return;
const move = MOVES[key];
if (!move) return;
const [dx, dy] = move, player = this.player;
player.facing = dx < 0 ? 'left' : dx > 0 ? 'right' : dy < 0 ? 'up' : 'down';
if (player.host) player.host.facing = player.facing;
player.moveCounter = (player.moveCounter || 0) + 1;
const rooted = this.state === 'possessed' && player.type === 'Turret';
if (!rooted && (this.state !== 'possessed' || player.moveCounter % (player.speed || 1) === 0)) {
const x = player.x + dx, y = player.y + dy, target = enemyAt(x, y);
if (target && this.state === 'possessed') {
const before = target.hp;
damageEnemy(target, player.damage, player);
if (player.type === 'Leech' && target.hp < before) heal(player.host, 1);
if (player.type === 'Mimic') { player.host.disguised = false; player.host.revealed = true; }
} else if (!target && this.grid[y]?.[x] != null && (!isWall(x, y) || (this.state === 'ghost' && player.phaseTime > 0))) {
player.x = x; player.y = y;
if (player.host) { player.host.x = x; player.host.y = y; }
const tile = this.grid[y][x];
if (tile === 'chest') { const found = randomInt(2, 5); addEssence(found, x, y); this.grid[y][x] = 'floor'; this.log.push(`Chest opened. +${found} essence.`); }
if (tile === 'exit') { this.completeFloor(); return; }
}
}
enemyTurn(); updateFog(); render();
},
tick(n = 1) {
n = Math.max(0, Math.min(10000, Math.floor(Number(n) || 0)));
for (let i = 0; i < n; i++) update(1 / 60, true);
updateFog(); render(); return this;
},
spawn, damageEnemy, findPath, sound, unlockAchievement
};
snapMotion(GAME.player);
function frame(now) {
const dt = Math.max(0, (now - lastTime) / 1000);
lastTime = now;
update(dt, false);
render();
requestAnimationFrame(frame);
}
function drawHud() {
const body = GAME.player.host || GAME.player.body;
ctx.fillStyle = '#11131c';
ctx.fillRect(0, 0, canvas.width, HUD);
ctx.strokeStyle = '#303342';
ctx.beginPath(); ctx.moveTo(0, HUD - 0.5); ctx.lineTo(canvas.width, HUD - 0.5); ctx.stroke();
ctx.fillStyle = '#f4f6ff'; ctx.font = 'bold 16px monospace'; ctx.textAlign = 'left';
ctx.fillText('BODY SNATCHER', 18, 25);
ctx.font = '14px monospace'; ctx.fillStyle = '#bec4d8';
const label = body ? `${body.type.toUpperCase()} HP ${body.hp}/${body.maxHp}` : `GHOST HP ${GAME.player.hp}/${GAME.player.maxHp}`;
ctx.fillText(`FLOOR ${GAME.floor} ${label} ESSENCE ${GAME.essence}`, 18, 49);
ctx.textAlign = 'right';
ctx.fillStyle = GAME.player.ghostTimer < 2 && !body ? '#ff6477' : '#e8edff';
ctx.fillText(body ? 'GHOST TIMER PAUSED' : `GHOST ${GAME.player.ghostTimer.toFixed(1)}s`, 782, 25);
ctx.fillStyle = '#7f879e';
ctx.fillText(`ABILITY: ${(GAME.player.abilities || [body ? body.special : 'possess']).join(' + ').toUpperCase()}`, 782, 49);
}
function drawDungeon() {
for (let y = 0; y < ROWS; y++) for (let x = 0; x < COLS; x++) {
const px = x * TILE, py = HUD + y * TILE;
if (!GAME.explored[y][x]) {
ctx.fillStyle = '#050609'; ctx.fillRect(px, py, TILE, TILE); continue;
}
const wall = isWall(x, y);
ctx.fillStyle = wall ? '#252837' : '#151822'; ctx.fillRect(px, py, TILE, TILE);
ctx.strokeStyle = wall ? '#34384a' : '#202430'; ctx.strokeRect(px + 0.5, py + 0.5, TILE - 1, TILE - 1);
const tile = GAME.grid[y][x];
if (tile === 'exit') {
ctx.fillStyle = '#70d7ff'; ctx.fillRect(px + 7, py + 8, 18, 4); ctx.fillRect(px + 10, py + 14, 15, 4); ctx.fillRect(px + 13, py + 20, 12, 4);
} else if (tile === 'chest') {
ctx.fillStyle = '#9b663a'; ctx.fillRect(px + 6, py + 10, 20, 15); ctx.strokeStyle = '#e5bc55'; ctx.strokeRect(px + 6.5, py + 10.5, 19, 14);
}
if (!GAME.visible[y][x]) { ctx.fillStyle = 'rgba(2,3,7,.68)'; ctx.fillRect(px, py, TILE, TILE); }
}
}
function shape(entity, x = entity.renderX ?? entity.x, y = entity.renderY ?? entity.y) {
const type = entity.type, color = entity.color || KITS[type]?.color || '#fff', flash = entity.hitFlash > 0;
const cx = x * TILE + TILE / 2, cy = HUD + y * TILE + TILE / 2;
ctx.save(); ctx.fillStyle = flash ? '#fff' : color; ctx.strokeStyle = flash ? '#fff' : '#dbe8ff'; ctx.lineWidth = 2; ctx.beginPath();
if (type === 'Brute') ctx.rect(cx - 14, cy - 14, 28, 28);
else if (type === 'Skitterer') { ctx.moveTo(cx, cy - 10); ctx.lineTo(cx + 9, cy + 8); ctx.lineTo(cx - 9, cy + 8); ctx.closePath(); }
else if (type === 'Shielder') ctx.rect(cx - 12, cy - 12, 24, 24);
else if (type === 'Bomber' || type === 'Siren') ctx.arc(cx, cy, 11, 0, Math.PI * 2);
else if (type === 'Healer') { ctx.rect(cx - 4, cy - 13, 8, 26); ctx.rect(cx - 13, cy - 4, 26, 8); }
else if (type === 'Phaser') { ctx.moveTo(cx, cy - 14); ctx.lineTo(cx + 12, cy); ctx.lineTo(cx, cy + 14); ctx.lineTo(cx - 12, cy); ctx.closePath(); }
else if (type === 'Charger') { ctx.moveTo(cx + 14, cy); ctx.lineTo(cx - 4, cy - 12); ctx.lineTo(cx - 4, cy - 5); ctx.lineTo(cx - 13, cy - 5); ctx.lineTo(cx - 13, cy + 5); ctx.lineTo(cx - 4, cy + 5); ctx.lineTo(cx - 4, cy + 12); ctx.closePath(); }
else if (type === 'Mimic' && entity.disguised) { ctx.rect(cx - 13, cy - 9, 26, 18); }
else if (type === 'Leech') { ctx.moveTo(cx, cy - 14); ctx.bezierCurveTo(cx + 14, cy, cx + 10, cy + 13, cx, cy + 13); ctx.bezierCurveTo(cx - 10, cy + 13, cx - 14, cy, cx, cy - 14); }
else {
const sides = type === 'Turret' ? 8 : 6;
for (let i = 0; i < sides; i++) {
const angle = Math.PI * 2 / sides * i - Math.PI / 2, px = cx + Math.cos(angle) * 12, py = cy + Math.sin(angle) * 12;
if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py);
}
ctx.closePath();
}
ctx.fill();
if (type === 'Shielder') {
const [dx, dy] = DIRECTIONS[entity.facing || 'down']; ctx.beginPath(); ctx.moveTo(cx + dx * 15 - dy * 9, cy + dy * 15 - dx * 9); ctx.lineTo(cx + dx * 15 + dy * 9, cy + dy * 15 + dx * 9); ctx.stroke();
} else if (type === 'Bomber') { ctx.beginPath(); ctx.moveTo(cx + 5, cy - 9); ctx.quadraticCurveTo(cx + 11, cy - 16, cx + 14, cy - 11); ctx.stroke(); }
else if (type === 'Siren') { ctx.globalAlpha = .5; ctx.beginPath(); ctx.arc(cx, cy, 15 + GAME.turn % 3, 0, Math.PI * 2); ctx.stroke(); }
else if (type === 'Mimic' && entity.disguised) { ctx.beginPath(); ctx.moveTo(cx - 13, cy - 3); ctx.lineTo(cx + 13, cy - 3); ctx.stroke(); ctx.fillStyle = '#e5bc55'; ctx.fillRect(cx - 2, cy - 5, 4, 7); }
else if (type === 'Turret') { const [dx, dy] = DIRECTIONS[entity.facing || 'down']; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + dx * 15, cy + dy * 15); ctx.stroke(); }
if (entity.telegraph) { ctx.strokeStyle = '#fff16b'; ctx.lineWidth = 3; ctx.strokeRect(cx - 15, cy - 15, 30, 30); }
ctx.restore();
}
function drawGhost() {
const x = (GAME.player.renderX ?? GAME.player.x) * TILE + TILE / 2, y = HUD + (GAME.player.renderY ?? GAME.player.y) * TILE + TILE / 2;
ctx.save(); ctx.fillStyle = GAME.player.hitFlash > 0 ? '#fff' : 'rgba(244,248,255,.78)'; ctx.shadowColor = '#dcecff'; ctx.shadowBlur = 12;
ctx.beginPath(); ctx.arc(x, y, 11, 0, Math.PI * 2); ctx.fill();
ctx.shadowBlur = 0; ctx.fillStyle = '#202432'; ctx.beginPath();
ctx.arc(x - 4, y - 2, 2, 0, Math.PI * 2); ctx.arc(x + 4, y - 2, 2, 0, Math.PI * 2); ctx.fill(); ctx.restore();
}
function drawEntities() {
for (const enemy of GAME.enemies) if (GAME.visible[enemy.y]?.[enemy.x] || hasUpgrade('meta2')) shape(enemy);
for (const projectile of GAME.projectiles) if (GAME.visible[projectile.y]?.[projectile.x]) {
ctx.fillStyle = projectile.owner === 'player' ? '#f7f2ff' : '#c27aff'; ctx.beginPath();
ctx.arc((projectile.renderX ?? projectile.x) * TILE + 16, HUD + (projectile.renderY ?? projectile.y) * TILE + 16, 4, 0, Math.PI * 2); ctx.fill();
}
for (const particle of GAME.particles) {
ctx.globalAlpha = Math.max(0, particle.life / particle.maxLife); ctx.fillStyle = particle.color;
ctx.fillRect(particle.x * TILE - 2, HUD + particle.y * TILE - 2, 4, 4);
}
ctx.globalAlpha = 1;
const body = GAME.player.host || GAME.player.body;
if (body) shape(body, GAME.player.renderX ?? GAME.player.x, GAME.player.renderY ?? GAME.player.y); else drawGhost();
}
function overlay(title, subtitle, detail = '') {
ctx.fillStyle = 'rgba(3,4,8,.84)'; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.textAlign = 'center'; ctx.fillStyle = '#f5f7ff'; ctx.font = 'bold 46px monospace'; ctx.fillText(title, canvas.width / 2, 265);
ctx.fillStyle = '#aeb6cc'; ctx.font = '16px monospace'; ctx.fillText(subtitle, canvas.width / 2, 310);
if (detail) { ctx.fillStyle = '#d7c879'; ctx.font = '14px monospace'; ctx.fillText(detail, canvas.width / 2, 345); }
}
function drawShop() {
ctx.fillStyle = 'rgba(3,4,8,.94)'; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.textAlign = 'center'; ctx.fillStyle = '#f5f7ff'; ctx.font = 'bold 34px monospace'; ctx.fillText(`SHOP — FLOOR ${GAME.pendingFloor}`, 400, 120);
ctx.font = '15px monospace'; ctx.fillStyle = '#d7c879'; ctx.fillText(`${GAME.essence} ESSENCE · ←/→ SELECT · ENTER BUY · SPACE SKIP`, 400, 154);
GAME.shopChoices.forEach((choice, index) => {
const x = 20 + index * 260, selected = index === GAME.shopSelection;
const locked = choice.locked || (choice.requires && !GAME.upgrades[choice.requires]);
ctx.fillStyle = selected ? '#292e42' : '#151822'; ctx.fillRect(x, 205, 240, 250);
ctx.strokeStyle = selected ? '#8da2ff' : '#34384a'; ctx.lineWidth = selected ? 3 : 1; ctx.strokeRect(x + .5, 205.5, 239, 249);
ctx.fillStyle = locked ? '#70758a' : '#eef2ff'; ctx.font = 'bold 18px monospace'; ctx.fillText(choice.name, x + 120, 250);
ctx.font = '14px monospace'; ctx.fillStyle = '#d7c879'; ctx.fillText(`${choice.price} ESSENCE`, x + 120, 284);
ctx.fillStyle = '#abb2c8'; ctx.font = '13px monospace';
const words = choice.text.split(' '), lines = [''];
for (const word of words) { const line = lines[lines.length - 1]; if ((line + word).length > 25) lines.push(word); else lines[lines.length - 1] = `${line} ${word}`.trim(); }
lines.forEach((line, lineIndex) => ctx.fillText(line, x + 120, 330 + lineIndex * 20));
if (locked) { ctx.fillStyle = '#ff7f90'; ctx.fillText('PREREQUISITE LOCKED', x + 120, 415); }
});
}
function render() {
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save();
if (GAME.shake > 0) ctx.translate(Math.sin(GAME.turn * 7) * GAME.shake, Math.cos(GAME.turn * 11) * GAME.shake * .6);
drawHud(); drawDungeon();
if (GAME.state !== 'title' && GAME.state !== 'shop') drawEntities();
ctx.restore();
if (GAME.state === 'title') overlay('BODY SNATCHER', GAME.continueAvailable ? 'Continue run? Y / N' : 'Press any key to begin', 'WASD / ARROWS MOVE · SPACE ACTS · Q/E ROTATE · ESC PAUSES');
if (GAME.state === 'shop') drawShop();
if (GAME.state === 'paused') overlay('PAUSED', 'ENTER — SAVE + QUIT', 'ESC — RETURN TO THE DUNGEON');
if (GAME.state === 'won' || GAME.state === 'victory') overlay('ESCAPED', 'The tenth floor could not hold you. Press any key.', statsLine());
if (GAME.state === 'lost' || GAME.state === 'gameover') overlay('YOU FADED', 'Press any key to begin again', statsLine());
}
document.addEventListener('keydown', event => {
const key = event.key === ' ' ? 'Space' : event.key;
if (/^(Arrow|Space)/.test(key)) event.preventDefault && event.preventDefault();
GAME.input(key);
});
render();
})();
</script>
</body>
</html>