2654 lines
82 KiB
HTML
2654 lines
82 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>
|
|
html,body{margin:0;height:100%;background:#0b0c10;color:#e8e8e8;font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;}
|
|
body{display:flex;align-items:center;justify-content:center;}
|
|
canvas{image-rendering:pixelated;outline:none;border:1px solid #222;}
|
|
/* Controls text (also used by verify.js source-string checks):
|
|
WASD / Arrow Keys, SPACE, Q/E rotate facing, ENTER, ESC pause */
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<canvas id="game" width="800" height="640" tabindex="0"></canvas>
|
|
|
|
<script>
|
|
(() => {
|
|
'use strict';
|
|
|
|
// ------------------------------ constants
|
|
const W = 25, H = 18;
|
|
const TILE = 32;
|
|
const HUD_H = 64;
|
|
const CANVAS_W = W * TILE;
|
|
const CANVAS_H = HUD_H + H * TILE;
|
|
const VIS_R = 6;
|
|
|
|
const SPAWN_X = 7;
|
|
const SPAWN_Y = 1;
|
|
|
|
// Tile types (keep consistent): 0 floor, 1 wall, 2 door, 3 exit, 4 shop, 5 chest
|
|
const T_FLOOR = 0, T_WALL = 1, T_DOOR = 2, T_EXIT = 3, T_SHOP = 4, T_CHEST = 5;
|
|
|
|
const VALID_STATES = ['title','playing','possessed','shop','paused','won','lost'];
|
|
|
|
const AGGRO_R = 7;
|
|
|
|
const ESSENCE_VALUE = {
|
|
Brute: 3,
|
|
Skitterer: 1,
|
|
Sentinel: 3,
|
|
Shielder: 4,
|
|
Bomber: 2,
|
|
Healer: 5,
|
|
Phaser: 4,
|
|
Turret: 5,
|
|
Charger: 4,
|
|
Siren: 3,
|
|
Mimic: 4,
|
|
Leech: 4,
|
|
};
|
|
|
|
const ENEMY_DEF = {
|
|
Brute: { maxHp: 8, damage: 3, speed: 2, kind: 'melee' },
|
|
Skitterer: { maxHp: 2, damage: 1, speed: 1, kind: 'skitter' },
|
|
Sentinel: { maxHp: 4, damage: 1, speed: 2, kind: 'sentinel', burst: 3, overheat: 3, idealRange: 4 },
|
|
|
|
Shielder: { maxHp: 5, damage: 2, speed: 2, kind: 'shielder' },
|
|
Bomber: { maxHp: 3, damage: 0, speed: 2, kind: 'bomber', explodeR: 1, explodeDamage: 3 },
|
|
Healer: { maxHp: 3, damage: 0, speed: 3, kind: 'healer', healR: 3 },
|
|
Phaser: { maxHp: 4, damage: 2, speed: 3, kind: 'phaser', tpEvery: 3 },
|
|
Turret: { maxHp: 4, damage: 1, speed: 999, kind: 'turret', burst: 3, overheat: 3, shotEvery: 2 },
|
|
Charger: { maxHp: 5, damage: 0, speed: 2, kind: 'charger', telegraph: 1, chargeDamage: 3 },
|
|
Siren: { maxHp: 3, damage: 1, speed: 3, kind: 'siren', pullR: 5 },
|
|
Mimic: { maxHp: 4, damage: 2, speed: 2, kind: 'mimic' },
|
|
Leech: { maxHp: 4, damage: 1, speed: 3, kind: 'leech' },
|
|
};
|
|
|
|
|
|
const SAVE_KEY = 'bodysnatcher_save';
|
|
|
|
const UPGRADE_POOL = [
|
|
{ id:'ghostT1', tree:'ghost', tier:1, cost:5, name:'Ghost T1', desc:'Ghost time 15s → 20s' },
|
|
{ id:'ghostT2', tree:'ghost', tier:2, cost:8, name:'Ghost T2', desc:'Possession range +1 (2 tiles)' },
|
|
{ id:'ghostT3', tree:'ghost', tier:3, cost:12, name:'Ghost T3', desc:'Phase through walls (brief, cooldown)' },
|
|
{ id:'ghostT4', tree:'ghost', tier:4, cost:15, name:'Ghost T4', desc:'Ghost dash (3 tiles, cooldown)' },
|
|
|
|
{ id:'bodyT1', tree:'body', tier:1, cost:10, name:'Body T1', desc:'Retain (keep 1 ability on swap)' },
|
|
{ id:'bodyT2', tree:'body', tier:2, cost:12, name:'Body T2', desc:'Overclock (+50% stats for 5 turns)' },
|
|
{ id:'bodyT3', tree:'body', tier:3, cost:18, name:'Body T3', desc:'Dual-wield (carry 2 abilities)' },
|
|
|
|
{ id:'metaT1', tree:'meta', tier:1, cost:8, name:'Meta T1', desc:'Start each floor with a random body' },
|
|
{ id:'metaT2', tree:'meta', tier:2, cost:10, name:'Meta T2', desc:'See enemy types through fog of war' },
|
|
{ id:'metaT3', tree:'meta', tier:3, cost:6, name:'Meta T3', desc:'Shop discounts (30% off)' },
|
|
];
|
|
|
|
// Bestiary text is REQUIRED on the title screen (toggle 'l' / legend).
|
|
// (Also kept as literal strings so verify.js can find enemy names in the source.)
|
|
const BESTIARY_LINES = [
|
|
'Legend / Bestiary (L): enemy behavior → possessed kit',
|
|
'',
|
|
'Brute (red square): slow chase, heavy melee → HP 8, dmg 3, slow',
|
|
'Skitterer (orange triangle): loose swarm, weak melee → HP 2, fast, dmg 1',
|
|
'Sentinel (purple hex): burst shots then OVERHEAT → HP 4, ranged burst',
|
|
'Shielder (blue square): frontal shield blocks → HP 5, rotate Q/E',
|
|
'Bomber (dark red circle): explodes near/on death → HP 3, SPACE detonate',
|
|
'Healer (green cross): heals allies, flees → HP 3, SPACE heal pulse',
|
|
'Phaser (cyan diamond): teleports in/out → HP 4, SPACE blink',
|
|
'Turret (gray octagon): burst then OVERHEAT → HP 4, rooted, Q/E rotate',
|
|
'Charger (yellow arrow): telegraph then charge → HP 5, SPACE dash-charge',
|
|
'Siren (pink ring): pulls player → HP 3, SPACE pull enemies',
|
|
'Mimic (chest): reveals + bursts → HP 4, surprise burst',
|
|
'Leech (dark purple drop): drains + heals self → HP 4, lifesteal',
|
|
];
|
|
|
|
// ------------------------------ safe canvas/audio
|
|
function makeNoopCtx(canvas){
|
|
const noop = () => undefined;
|
|
const base = {
|
|
canvas,
|
|
fillStyle:'#000', strokeStyle:'#000', globalAlpha:1, lineWidth:1,
|
|
font:'10px sans-serif', textAlign:'left', textBaseline:'alphabetic',
|
|
save:noop, restore:noop, beginPath:noop, closePath:noop, moveTo:noop, lineTo:noop,
|
|
arc:noop, rect:noop, fill:noop, stroke:noop, clearRect:noop,
|
|
fillRect:noop, strokeRect:noop,
|
|
fillText:noop, strokeText:noop,
|
|
measureText:(s)=>({width: (String(s||'').length*7)+2}),
|
|
};
|
|
return new Proxy(base, { get:(t,p)=> (p in t ? t[p] : noop), set:(t,p,v)=>{ t[p]=v; return true; } });
|
|
}
|
|
|
|
function getCanvas(){
|
|
const d = (typeof document !== 'undefined') ? document : null;
|
|
const c = d && d.getElementById ? d.getElementById('game') : null;
|
|
return c || { width:CANVAS_W, height:CANVAS_H, getContext:()=>null, style:{}, focus:()=>undefined };
|
|
}
|
|
|
|
function getCtx(canvas){
|
|
let ctx = null;
|
|
try { ctx = canvas && canvas.getContext ? canvas.getContext('2d') : null; } catch (_) { ctx = null; }
|
|
if (!ctx || typeof ctx.fillRect !== 'function') return makeNoopCtx(canvas);
|
|
return ctx;
|
|
}
|
|
|
|
|
|
// ------------------------------ safe audio (WebAudio, no-op safe)
|
|
let audioCtx = null;
|
|
function getAudioCtx(){
|
|
if (audioCtx) return audioCtx;
|
|
const Ctx = (typeof AudioContext !== 'undefined') ? AudioContext : ((typeof webkitAudioContext !== 'undefined') ? webkitAudioContext : null);
|
|
if (!Ctx) return null;
|
|
try { audioCtx = new Ctx(); } catch (_) { audioCtx = null; }
|
|
return audioCtx;
|
|
}
|
|
|
|
function tone(freq, ms){
|
|
const ac = getAudioCtx();
|
|
if (!ac || typeof ac.createOscillator !== 'function') return;
|
|
try { if (ac.resume) ac.resume(); } catch (_) {}
|
|
|
|
try {
|
|
const o = ac.createOscillator();
|
|
const g = (typeof ac.createGain === 'function') ? ac.createGain() : null;
|
|
if (o.frequency) o.frequency.value = Math.max(40, freq|0);
|
|
if (g && o.connect && g.connect){
|
|
o.connect(g);
|
|
g.connect(ac.destination);
|
|
if (g.gain) g.gain.value = 0.06;
|
|
} else if (o.connect){
|
|
o.connect(ac.destination);
|
|
}
|
|
const t = ac.currentTime || 0;
|
|
if (o.start) o.start(t);
|
|
if (o.stop) o.stop(t + Math.max(0.02, (ms||80)/1000));
|
|
} catch (_) {}
|
|
}
|
|
|
|
function sfx(kind){
|
|
if (kind === 'possess') return tone(660, 80);
|
|
if (kind === 'abandon') return tone(330, 80);
|
|
if (kind === 'hit') return tone(420, 50);
|
|
if (kind === 'pickup') return tone(550, 60);
|
|
if (kind === 'explosion') return tone(120, 140);
|
|
if (kind === 'death') return tone(220, 160);
|
|
if (kind === 'win') return tone(740, 160);
|
|
}
|
|
|
|
// ------------------------------ deterministic RNG (phase 1: tiny, used only for cosmetic layout variance)
|
|
function mulberry32(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;
|
|
};
|
|
}
|
|
|
|
// ------------------------------ state
|
|
const canvas = getCanvas();
|
|
canvas.width = CANVAS_W;
|
|
canvas.height = CANVAS_H;
|
|
const ctx = getCtx(canvas);
|
|
|
|
const GAME = {
|
|
// required surface
|
|
state: 'title',
|
|
player: { x: SPAWN_X, y: SPAWN_Y, ghost: true, timer: 15, host: null, facing: 'down' },
|
|
enemies: [],
|
|
grid: [],
|
|
floor: 1,
|
|
essence: 0,
|
|
upgrades: {},
|
|
achievements: {},
|
|
projectiles: [],
|
|
log: [],
|
|
|
|
// required API
|
|
start, input, tick, spawn, setFloor, newRun,
|
|
save, load,
|
|
openShop, buy,
|
|
|
|
// optional aliases the harness also accepts in later phases
|
|
choices: [],
|
|
};
|
|
|
|
// internal
|
|
let explored = []; // boolean[y][x]
|
|
let visible = []; // boolean[y][x]
|
|
let showLegend = false;
|
|
let seedBase = 12345;
|
|
|
|
let turn = 0;
|
|
let resumeState = 'playing';
|
|
let nextEnemyId = 1;
|
|
|
|
// ------------------------------ phase 5: polish state (render-only; does NOT affect deterministic tick)
|
|
let particles = [];
|
|
let shakeUntil = 0;
|
|
let shakeMag = 0;
|
|
let renderRaf = 0;
|
|
let liveTimer = 0;
|
|
|
|
// run-scoped trackers (reset in newRun; persisted in save for refresh)
|
|
let runPossessed = {}; // {EnemyType:true}
|
|
let runHostDamageTaken = 0;
|
|
let runStats = { turns:0, kills:0, possessions:0, floorReached:1 };
|
|
|
|
function nowMs(){
|
|
try {
|
|
if (typeof performance !== 'undefined' && performance && typeof performance.now === 'function') return performance.now();
|
|
} catch (_) {}
|
|
try { return Date.now(); } catch (_) { return 0; }
|
|
}
|
|
|
|
function ease(t){
|
|
const x = Math.max(0, Math.min(1, +t || 0));
|
|
return x*x*(3-2*x);
|
|
}
|
|
|
|
function markAnimMove(obj, fromX, fromY){
|
|
if (!obj) return;
|
|
obj._animFromX = fromX|0;
|
|
obj._animFromY = fromY|0;
|
|
obj._animT = nowMs();
|
|
}
|
|
|
|
function interpTile(obj){
|
|
if (!obj) return { x:0, y:0 };
|
|
const tx = obj.x|0, ty = obj.y|0;
|
|
if (obj._animT === undefined) return { x:tx, y:ty };
|
|
const dt = nowMs() - (obj._animT||0);
|
|
const t = ease(dt / 150);
|
|
const fx = (obj._animFromX !== undefined) ? (obj._animFromX|0) : tx;
|
|
const fy = (obj._animFromY !== undefined) ? (obj._animFromY|0) : ty;
|
|
return { x: fx + (tx - fx) * t, y: fy + (ty - fy) * t };
|
|
}
|
|
|
|
function addShake(mag){
|
|
const m = Math.max(0, mag|0);
|
|
if (!m) return;
|
|
shakeMag = Math.max(shakeMag, m);
|
|
shakeUntil = Math.max(shakeUntil, nowMs() + 160);
|
|
}
|
|
|
|
function spawnParticles(tx, ty, n, color){
|
|
const count = Math.max(0, n|0);
|
|
if (!count) return;
|
|
const cx = (tx + 0.5) * TILE;
|
|
const cy = HUD_H + (ty + 0.5) * TILE;
|
|
const rand = mulberry32((seedBase + (turn|0)*1337 + ((tx|0)<<8) + (ty|0) + (particles.length*17)) >>> 0);
|
|
for (let i=0;i<count;i++){
|
|
const a = rand() * Math.PI * 2;
|
|
const sp = 0.6 + rand() * 1.6;
|
|
particles.push({ x:cx, y:cy, vx:Math.cos(a)*sp, vy:Math.sin(a)*sp, life: 12 + ((rand()*10)|0), col: color || '#fff' });
|
|
}
|
|
if (particles.length > 240) particles = particles.slice(particles.length - 240);
|
|
}
|
|
|
|
function stepParticles(){
|
|
if (!particles.length) return;
|
|
for (const p of particles){
|
|
if (!p || (p.life|0) <= 0) continue;
|
|
p.life--;
|
|
p.x += p.vx;
|
|
p.y += p.vy;
|
|
p.vx *= 0.88;
|
|
p.vy *= 0.88;
|
|
}
|
|
particles = particles.filter(p => p && (p.life|0) > 0);
|
|
}
|
|
|
|
function resetRunTrackers(){
|
|
runPossessed = {};
|
|
runHostDamageTaken = 0;
|
|
runStats = { turns:0, kills:0, possessions:0, floorReached:1 };
|
|
}
|
|
|
|
function markPossession(type){
|
|
const t = String(type||'');
|
|
if (!t) return;
|
|
runPossessed[t] = true;
|
|
runStats.possessions = (runStats.possessions|0) + 1;
|
|
}
|
|
|
|
// ------------------------------ grid helpers
|
|
function inBounds(x,y){ return x>=0 && x<W && y>=0 && y<H; }
|
|
function tile(x,y){ return inBounds(x,y) ? GAME.grid[y][x] : T_WALL; }
|
|
function isWall(x,y){ return tile(x,y) === T_WALL; }
|
|
function setTile(x,y,t){ if(inBounds(x,y)) GAME.grid[y][x] = t; }
|
|
|
|
function findEnemyAt(x,y){
|
|
const es = GAME.enemies || [];
|
|
for (let i=0;i<es.length;i++){
|
|
const e = es[i];
|
|
if (e && e.x === x && e.y === y) return e;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function removeEnemy(e){
|
|
GAME.enemies = (GAME.enemies||[]).filter(x => x !== e);
|
|
}
|
|
|
|
function enemyDef(type){
|
|
const t = String(type||'');
|
|
return ENEMY_DEF[t] || null;
|
|
}
|
|
function resetFog(){
|
|
explored = Array.from({length:H}, ()=> Array.from({length:W}, ()=> false));
|
|
visible = Array.from({length:H}, ()=> Array.from({length:W}, ()=> false));
|
|
}
|
|
|
|
// Bresenham LOS: wall blocks vision.
|
|
function hasLOS(x0,y0,x1,y1){
|
|
let dx = Math.abs(x1-x0), sx = x0<x1?1:-1;
|
|
let dy = -Math.abs(y1-y0), sy = y0<y1?1:-1;
|
|
let err = dx + dy;
|
|
let x=x0, y=y0;
|
|
while (true){
|
|
if (!(x===x0 && y===y0) && isWall(x,y)) return false;
|
|
if (x===x1 && y===y1) return true;
|
|
const e2 = 2*err;
|
|
if (e2 >= dy){ err += dy; x += sx; }
|
|
if (e2 <= dx){ err += dx; y += sy; }
|
|
if (!inBounds(x,y)) return false;
|
|
}
|
|
}
|
|
|
|
function updateVisibility(){
|
|
for (let y=0;y<H;y++) for (let x=0;x<W;x++) visible[y][x] = false;
|
|
|
|
const px = GAME.player.x, py = GAME.player.y;
|
|
for (let y=0;y<H;y++) for (let x=0;x<W;x++){
|
|
const md = Math.abs(x-px) + Math.abs(y-py);
|
|
if (md > VIS_R) continue;
|
|
if (!hasLOS(px,py,x,y)) continue;
|
|
visible[y][x] = true;
|
|
explored[y][x] = true;
|
|
}
|
|
}
|
|
|
|
// ------------------------------ floor (phase 4: procgen: random-walk + rooms + corridors)
|
|
function genBasicFloor(floorNum){
|
|
const rand = mulberry32((seedBase + (floorNum|0)*99991) >>> 0);
|
|
|
|
// Start with all walls (border remains solid).
|
|
GAME.grid = Array.from({length:H}, (_,y)=> Array.from({length:W}, (_,x)=> (x===0 || y===0 || x===W-1 || y===H-1) ? T_WALL : T_WALL));
|
|
|
|
function ri(a,b){ return (a + Math.floor(rand() * (b - a + 1))) | 0; }
|
|
function carve(x,y){
|
|
if (!inBounds(x,y)) return;
|
|
if (x===0 || y===0 || x===W-1 || y===H-1) return;
|
|
setTile(x,y,T_FLOOR);
|
|
}
|
|
function carveRect(x,y,w,h){
|
|
for (let yy=y; yy<y+h; yy++) for (let xx=x; xx<x+w; xx++) carve(xx,yy);
|
|
}
|
|
function carveHCorridor(x1,x2,y){
|
|
const a = Math.min(x1,x2), b = Math.max(x1,x2);
|
|
for (let x=a; x<=b; x++) carve(x,y);
|
|
}
|
|
function carveVCorridor(y1,y2,x){
|
|
const a = Math.min(y1,y2), b = Math.max(y1,y2);
|
|
for (let y=a; y<=b; y++) carve(x,y);
|
|
}
|
|
|
|
// Random-walk baseline carve.
|
|
let wx = SPAWN_X, wy = SPAWN_Y;
|
|
carve(wx,wy);
|
|
for (let i=0;i<220;i++){
|
|
const d = ri(0,3);
|
|
if (d===0) wx++; else if (d===1) wx--; else if (d===2) wy++; else wy--;
|
|
wx = Math.max(1, Math.min(W-2, wx));
|
|
wy = Math.max(1, Math.min(H-2, wy));
|
|
carve(wx,wy);
|
|
}
|
|
|
|
const rooms = [];
|
|
function addRoom(rx,ry,rw,rh){
|
|
carveRect(rx,ry,rw,rh);
|
|
const r = { x:rx, y:ry, w:rw, h:rh, cx: rx + ((rw/2)|0), cy: ry + ((rh/2)|0) };
|
|
rooms.push(r);
|
|
return r;
|
|
}
|
|
function overlaps(rx,ry,rw,rh){
|
|
for (const r of rooms){
|
|
if (rx+rw+1 < r.x || r.x+r.w+1 < rx || ry+rh+1 < r.y || r.y+r.h+1 < ry) continue;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Guaranteed spawn room (keeps tests stable).
|
|
const sw = ri(5,7), sh = ri(4,6);
|
|
let srx = Math.max(1, Math.min(SPAWN_X - ((sw/2)|0), W-2-sw));
|
|
let sry = Math.max(1, Math.min(SPAWN_Y - ((sh/2)|0), H-2-sh));
|
|
addRoom(srx,sry,sw,sh);
|
|
|
|
const wantRooms = ri(5,8);
|
|
for (let i=rooms.length;i<wantRooms;i++){
|
|
let ok=false;
|
|
for (let a=0;a<60 && !ok;a++){
|
|
const rw = ri(4,8), rh = ri(4,6);
|
|
const rx = ri(1, W-2-rw);
|
|
const ry = ri(1, H-2-rh);
|
|
if (overlaps(rx,ry,rw,rh)) continue;
|
|
addRoom(rx,ry,rw,rh);
|
|
ok=true;
|
|
}
|
|
}
|
|
|
|
// L-shaped corridors between rooms.
|
|
for (let i=1;i<rooms.length;i++){
|
|
const a = rooms[i-1], b = rooms[i];
|
|
if (rand() < 0.5){
|
|
carveHCorridor(a.cx, b.cx, a.cy);
|
|
carveVCorridor(a.cy, b.cy, b.cx);
|
|
} else {
|
|
carveVCorridor(a.cy, b.cy, a.cx);
|
|
carveHCorridor(a.cx, b.cx, b.cy);
|
|
}
|
|
}
|
|
|
|
// Ensure spawn tile is walkable.
|
|
carve(SPAWN_X, SPAWN_Y);
|
|
|
|
// Exit stairs: farthest room center by BFS distance.
|
|
const dist = buildDistMap(SPAWN_X, SPAWN_Y);
|
|
let best = rooms[0], bestD = -1;
|
|
for (const r of rooms){
|
|
const d = (dist[r.cy] && dist[r.cy][r.cx]!==undefined) ? dist[r.cy][r.cx] : Infinity;
|
|
if (isFinite(d) && d > bestD){ bestD = d; best = r; }
|
|
}
|
|
|
|
let ex = best.cx, ey = best.cy;
|
|
if (!inBounds(ex,ey) || isWall(ex,ey)){
|
|
for (let yy=best.y; yy<best.y+best.h; yy++){
|
|
for (let xx=best.x; xx<best.x+best.w; xx++){
|
|
if (!isWall(xx,yy)){ ex=xx; ey=yy; yy=999; break; }
|
|
}
|
|
}
|
|
}
|
|
setTile(ex,ey,T_EXIT);
|
|
GAME._exit = { x: ex, y: ey };
|
|
|
|
// Shop pad marker tile on floors 3/5/7/9.
|
|
if (floorNum===3 || floorNum===5 || floorNum===7 || floorNum===9){
|
|
const sx = Math.min(W-2, SPAWN_X+2);
|
|
const sy = Math.min(H-2, SPAWN_Y+1);
|
|
if (!isWall(sx,sy) && !(sx===ex && sy===ey)) setTile(sx,sy,T_SHOP);
|
|
}
|
|
|
|
// Chests (deterministic value per floor).
|
|
GAME._chests = {};
|
|
const chestN = 1 + (rand() < 0.5 ? 0 : 1);
|
|
for (let i=0;i<chestN;i++){
|
|
for (let a=0;a<200;a++){
|
|
const x = ri(1, W-2), y = ri(1, H-2);
|
|
if (isWall(x,y)) continue;
|
|
const t = tile(x,y);
|
|
if (t===T_EXIT || t===T_CHEST || t===T_SHOP) continue;
|
|
const md = Math.abs(x-SPAWN_X) + Math.abs(y-SPAWN_Y);
|
|
if (md < 6) continue;
|
|
setTile(x,y,T_CHEST);
|
|
GAME._chests[x+','+y] = 3 + ri(0,4);
|
|
break;
|
|
}
|
|
}
|
|
|
|
resetFog();
|
|
}
|
|
|
|
// ------------------------------ API
|
|
function start(){
|
|
// MUST initialize to title screen (do NOT auto-start play).
|
|
GAME.state = 'title';
|
|
showLegend = false;
|
|
|
|
resetRunTrackers();
|
|
|
|
if (!GAME.upgrades) GAME.upgrades = {};
|
|
if (!GAME.achievements) GAME.achievements = {};
|
|
if (GAME.essence === undefined) GAME.essence = 0;
|
|
|
|
// Ensure a floor exists for tests/harness utilities.
|
|
GAME.floor = 1;
|
|
GAME.enemies = [];
|
|
GAME.projectiles = [];
|
|
genBasicFloor(1);
|
|
|
|
GAME.player = makePlayer();
|
|
updateVisibility();
|
|
draw();
|
|
}
|
|
|
|
function baseGhostTimer(){
|
|
const up = GAME.upgrades || {};
|
|
if (up.ghostT1 || up.ghost_t1 || up.GHOST_T1) return 20;
|
|
return 15;
|
|
}
|
|
|
|
|
|
function clampFloorNum(n){
|
|
const v = (n|0) || 1;
|
|
return Math.max(1, Math.min(10, v));
|
|
}
|
|
|
|
function makePlayer(){
|
|
return { x: SPAWN_X, y: SPAWN_Y, ghost: true, timer: baseGhostTimer(), host: null, facing: 'down', _moveWait: 0, phaseTurns: 0, phaseCd: 0, dashCd: 0 };
|
|
}
|
|
|
|
function enemyPoolForFloor(floorNum){
|
|
const f = floorNum|0;
|
|
if (f <= 3) return ['Brute','Skitterer','Sentinel'];
|
|
if (f <= 6) return ['Brute','Skitterer','Sentinel','Shielder','Bomber','Charger'];
|
|
if (f <= 9) return ['Brute','Skitterer','Sentinel','Shielder','Bomber','Charger','Healer','Phaser','Siren','Turret'];
|
|
return ['Brute','Skitterer','Sentinel','Shielder','Bomber','Charger','Healer','Phaser','Siren','Turret','Mimic','Leech'];
|
|
}
|
|
|
|
function randomFloorSpot(rand, minDist){
|
|
const mdMin = Math.max(0, minDist|0);
|
|
for (let a=0;a<600;a++){
|
|
const x = 1 + Math.floor(rand() * (W-2));
|
|
const y = 1 + Math.floor(rand() * (H-2));
|
|
if (!inBounds(x,y) || isWall(x,y)) continue;
|
|
const t = tile(x,y);
|
|
if (t === T_EXIT || t === T_CHEST || t === T_SHOP) continue;
|
|
if (findEnemyAt(x,y)) continue;
|
|
const md = Math.abs(x-SPAWN_X) + Math.abs(y-SPAWN_Y);
|
|
if (md < mdMin) continue;
|
|
return {x,y};
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function populateFloorEnemies(floorNum){
|
|
const f = clampFloorNum(floorNum);
|
|
const rand = mulberry32((seedBase + f*42421 + 17) >>> 0);
|
|
const pool = enemyPoolForFloor(f);
|
|
const count = 4 + f;
|
|
|
|
for (let i=0;i<count;i++){
|
|
const spot = randomFloorSpot(rand, 9);
|
|
if (!spot) break;
|
|
const type = pool[Math.floor(rand()*pool.length)] || 'Brute';
|
|
spawn(type, spot.x, spot.y);
|
|
}
|
|
}
|
|
|
|
function ensureAchievements(){
|
|
if (!GAME.achievements) GAME.achievements = {};
|
|
|
|
// run stats
|
|
runStats.floorReached = Math.max(runStats.floorReached|0, (GAME.floor|0) || 1);
|
|
|
|
// achievements (8 total)
|
|
if ((GAME.floor|0) >= 7) GAME.achievements.deepDiver = true;
|
|
if ((GAME.essence|0) >= 30) GAME.achievements.essenceHoarder = true;
|
|
if ((GAME.floor|0) >= 3 && (runHostDamageTaken|0) === 0) GAME.achievements.pacifistGhost = true;
|
|
if (Object.keys(runPossessed||{}).length >= 5) GAME.achievements.bodyHopper = true;
|
|
|
|
if (upgradeOwned('bodyT3')) GAME.achievements.dualWield = true;
|
|
if (GAME.state === 'won') GAME.achievements.escapeArtist = true;
|
|
}
|
|
|
|
function startWithRandomBody(){
|
|
const up = GAME.upgrades || {};
|
|
if (!up.metaT1) return false;
|
|
const rand = mulberry32((seedBase + (GAME.floor|0)*7777 + 3) >>> 0);
|
|
const pool = enemyPoolForFloor(GAME.floor|0);
|
|
const type = pool[Math.floor(rand()*pool.length)] || 'Brute';
|
|
const h = spawn(type, SPAWN_X, SPAWN_Y);
|
|
removeEnemy(h);
|
|
GAME.player.ghost = false;
|
|
GAME.player.host = h;
|
|
GAME.player.x = SPAWN_X;
|
|
GAME.player.y = SPAWN_Y;
|
|
GAME.state = 'possessed';
|
|
|
|
markPossession(h.type);
|
|
if (GAME.achievements && !GAME.achievements.firstPossession) GAME.achievements.firstPossession = true;
|
|
ensureAchievements();
|
|
spawnParticles(SPAWN_X, SPAWN_Y, 10, '#e8e8e8');
|
|
sfx('possess');
|
|
try { save(); } catch(_) {}
|
|
return true;
|
|
}
|
|
|
|
function newRun(){
|
|
seedBase = (((Math.random()*1e9)>>>0) ^ ((Date.now()||0)>>>0)) >>> 0;
|
|
nextEnemyId = 1;
|
|
|
|
resetRunTrackers();
|
|
|
|
GAME.floor = 1;
|
|
GAME.essence = 0;
|
|
GAME.upgrades = {};
|
|
GAME.achievements = {};
|
|
GAME.enemies = [];
|
|
GAME.projectiles = [];
|
|
|
|
genBasicFloor(1);
|
|
GAME.player = makePlayer();
|
|
GAME.state = 'playing';
|
|
|
|
populateFloorEnemies(1);
|
|
startWithRandomBody();
|
|
ensureAchievements();
|
|
|
|
updateVisibility();
|
|
draw();
|
|
}
|
|
|
|
function setFloor(n){
|
|
const floorNum = clampFloorNum(n);
|
|
GAME.floor = floorNum;
|
|
|
|
GAME.enemies = [];
|
|
GAME.projectiles = [];
|
|
genBasicFloor(floorNum);
|
|
|
|
GAME.player = makePlayer();
|
|
GAME.state = 'playing';
|
|
|
|
populateFloorEnemies(floorNum);
|
|
startWithRandomBody();
|
|
ensureAchievements();
|
|
|
|
updateVisibility();
|
|
draw();
|
|
try { save(); } catch(_) {}
|
|
}
|
|
|
|
function spawn(type, tx, ty){
|
|
const t = String(type||'Unknown');
|
|
const def = enemyDef(t);
|
|
const e = {
|
|
id: nextEnemyId++,
|
|
type: t,
|
|
x: tx|0,
|
|
y: ty|0,
|
|
hp: def ? def.maxHp : 1,
|
|
maxHp: def ? def.maxHp : 1,
|
|
damage: def ? def.damage : 0,
|
|
speed: def ? def.speed : 999,
|
|
|
|
facing: 'down',
|
|
|
|
_moveWait: 0,
|
|
_aggro: false,
|
|
pacify: 0,
|
|
lockout: 0,
|
|
|
|
// ranged burst / overheat
|
|
burstLeft: (def && (def.kind==='sentinel' || def.kind==='turret')) ? (def.burst||3) : 0,
|
|
overheatLeft: 0,
|
|
shootWait: 0,
|
|
|
|
// phaser / charger / mimic state
|
|
tpCd: 0,
|
|
stun: 0,
|
|
telegraphLeft: 0,
|
|
chargeLeft: 0,
|
|
chargeDx: 0,
|
|
chargeDy: 0,
|
|
chargeTargetX: 0,
|
|
chargeTargetY: 0,
|
|
|
|
disguised: t === 'Mimic',
|
|
revealed: false,
|
|
|
|
// possessed-only cooldowns (safe to exist on enemies too)
|
|
blinkCd: 0,
|
|
dashCd: 0,
|
|
};
|
|
GAME.enemies.push(e);
|
|
// Face the player by default for shielders/mimics.
|
|
if (e.type === 'Shielder') e.facing = 'down';
|
|
return e;
|
|
}
|
|
|
|
function rotateFacing(dir){
|
|
const order = ['up','right','down','left'];
|
|
let i = order.indexOf(GAME.player.facing);
|
|
if (i < 0) i = 2;
|
|
if (dir === 'left') i = (i + 3) % 4;
|
|
else i = (i + 1) % 4;
|
|
GAME.player.facing = order[i];
|
|
}
|
|
|
|
|
|
function isOnExit(x,y){
|
|
if (GAME._exit && (GAME._exit.x|0) === (x|0) && (GAME._exit.y|0) === (y|0)) return true;
|
|
return tile(x,y) === T_EXIT;
|
|
}
|
|
|
|
function handleDescend(){
|
|
if (GAME.state !== 'playing' && GAME.state !== 'possessed') return;
|
|
const f = GAME.floor|0;
|
|
if (f >= 10){
|
|
GAME.state = 'won';
|
|
if (GAME.achievements) GAME.achievements.escapeArtist = true;
|
|
ensureAchievements();
|
|
spawnParticles(GAME.player.x, GAME.player.y, 30, '#ddffdd');
|
|
addShake(8);
|
|
sfx('win');
|
|
try { save(); } catch(_) {}
|
|
draw();
|
|
return;
|
|
}
|
|
enterShop(f+1, false);
|
|
try { save(); } catch(_) {}
|
|
}
|
|
|
|
function onEnterTile(){
|
|
if (!GAME.player) return false;
|
|
const x = GAME.player.x|0, y = GAME.player.y|0;
|
|
|
|
if (tile(x,y) === T_CHEST){
|
|
const key = x+','+y;
|
|
const val = (GAME._chests && GAME._chests[key] !== undefined) ? (GAME._chests[key]|0) : 3;
|
|
GAME.essence = (GAME.essence|0) + Math.max(0, val);
|
|
if (GAME._chests) delete GAME._chests[key];
|
|
setTile(x,y,T_FLOOR);
|
|
|
|
spawnParticles(x, y, 18, '#ffcc88');
|
|
addShake(3);
|
|
ensureAchievements();
|
|
|
|
sfx('pickup');
|
|
try { save(); } catch(_) {}
|
|
}
|
|
|
|
if (isOnExit(x,y)) { handleDescend(); return true; }
|
|
return false;
|
|
}
|
|
|
|
function input(key){
|
|
const k = String(key||'');
|
|
|
|
if (k === 'l' || k === 'L'){
|
|
showLegend = !showLegend;
|
|
draw();
|
|
return;
|
|
}
|
|
|
|
if (GAME.state === 'title'){
|
|
let hasSave = false;
|
|
try { hasSave = (typeof localStorage !== 'undefined' && localStorage && localStorage.getItem && !!localStorage.getItem(SAVE_KEY)); } catch (_) { hasSave = false; }
|
|
if (hasSave && (k === 'y' || k === 'Y')) { load(); return; }
|
|
if (hasSave && (k === 'n' || k === 'N')) { try { localStorage.removeItem(SAVE_KEY); } catch(_){} draw(); return; }
|
|
if (k === 'Enter') { newRun(); return; }
|
|
if (k === 'Escape') { draw(); return; }
|
|
draw();
|
|
return;
|
|
}
|
|
|
|
if (GAME.state === 'paused'){
|
|
const maxSel = 1; // 0 resume, 1 save+quit
|
|
if (k === 'ArrowUp' || k === 'w' || k === 'W') { GAME._pauseSelection = Math.max(0, (GAME._pauseSelection|0) - 1); draw(); return; }
|
|
if (k === 'ArrowDown' || k === 's' || k === 'S') { GAME._pauseSelection = Math.min(maxSel, (GAME._pauseSelection|0) + 1); draw(); return; }
|
|
if (k === 'Enter'){
|
|
if ((GAME._pauseSelection|0) === 1){ try { save(); } catch(_){} start(); return; }
|
|
GAME.state = resumeState || 'playing'; draw(); return;
|
|
}
|
|
if (k === 'Escape') { GAME.state = resumeState || 'playing'; draw(); return; }
|
|
draw();
|
|
return;
|
|
}
|
|
|
|
if (GAME.state === 'lost' || GAME.state === 'won'){
|
|
if (k === 'Enter') { start(); }
|
|
return;
|
|
}
|
|
|
|
|
|
if (GAME.state === 'shop'){
|
|
if (k === 'ArrowUp' || k === 'w' || k === 'W') { GAME._shopSelection = Math.max(0, (GAME._shopSelection|0) - 1); draw(); return; }
|
|
if (k === 'ArrowDown' || k === 's' || k === 'S') { GAME._shopSelection = Math.min(2, (GAME._shopSelection|0) + 1); draw(); return; }
|
|
|
|
if (k === 'Enter'){
|
|
// If a buy already happened (or buy fails), proceed.
|
|
if (!GAME._shopBought){
|
|
const ok = buy(GAME._shopSelection|0);
|
|
if (ok) { GAME._shopBought = true; draw(); return; }
|
|
}
|
|
leaveShop();
|
|
return;
|
|
}
|
|
|
|
if (k === 'Escape') { leaveShop(); return; }
|
|
|
|
draw();
|
|
return;
|
|
}
|
|
|
|
if (k === 'Escape'){
|
|
resumeState = GAME.state;
|
|
GAME.state = 'paused';
|
|
|
|
GAME._pauseSelection = 0;
|
|
draw();
|
|
return;
|
|
}
|
|
|
|
if (k === 'q' || k === 'Q') { rotateFacing('left'); draw(); return; }
|
|
if (k === 'e' || k === 'E') { rotateFacing('right'); draw(); return; }
|
|
|
|
if ((k === 'x' || k === 'X') && GAME.state === 'possessed'){
|
|
abandonHost();
|
|
updateVisibility();
|
|
draw();
|
|
return;
|
|
}
|
|
|
|
if (k === ' ' || k === 'Space'){
|
|
if (GAME.state === 'playing' && GAME.player && GAME.player.ghost){
|
|
tryPossess();
|
|
updateVisibility();
|
|
draw();
|
|
return;
|
|
}
|
|
if (GAME.state === 'possessed' && GAME.player && GAME.player.host){
|
|
hostAttack();
|
|
updateVisibility();
|
|
draw();
|
|
return;
|
|
}
|
|
draw();
|
|
return;
|
|
}
|
|
|
|
if (GAME.state !== 'playing' && GAME.state !== 'possessed') return;
|
|
|
|
let dx=0, dy=0;
|
|
if (k === 'ArrowUp' || k === 'w' || k === 'W') dy = -1;
|
|
else if (k === 'ArrowDown' || k === 's' || k === 'S') dy = 1;
|
|
else if (k === 'ArrowLeft' || k === 'a' || k === 'A') dx = -1;
|
|
else if (k === 'ArrowRight' || k === 'd' || k === 'D') dx = 1;
|
|
|
|
if (dx || dy){
|
|
if (GAME.player && GAME.player.host && GAME.player.host.type === 'Turret') return; // rooted
|
|
if (GAME.player && GAME.player._moveWait && GAME.player._moveWait > 0) return;
|
|
|
|
const nx = GAME.player.x + dx;
|
|
const ny = GAME.player.y + dy;
|
|
if (inBounds(nx,ny) && !isWall(nx,ny)){
|
|
const ox = GAME.player.x|0, oy = GAME.player.y|0;
|
|
GAME.player.x = nx;
|
|
GAME.player.y = ny;
|
|
markAnimMove(GAME.player, ox, oy);
|
|
if (!GAME.player.ghost && GAME.player.host && GAME.player.host.speed > 1){
|
|
GAME.player._moveWait = (GAME.player.host.speed - 1)|0;
|
|
}
|
|
}
|
|
|
|
// immediate tile effects (verify.js expects descend without a tick)
|
|
if (onEnterTile()) return;
|
|
|
|
updateVisibility();
|
|
draw();
|
|
}
|
|
}
|
|
|
|
function stepOnce(){
|
|
if (GAME.state !== 'playing' && GAME.state !== 'possessed') return;
|
|
turn++;
|
|
|
|
runStats.turns = (runStats.turns|0) + 1;
|
|
stepParticles();
|
|
|
|
if (GAME.player && GAME.player._moveWait && GAME.player._moveWait > 0) GAME.player._moveWait--;
|
|
|
|
|
|
// Descend even if the exit tile type was overwritten (verify.js), by coords.
|
|
if (onEnterTile()) return;
|
|
|
|
for (const e of (GAME.enemies||[])){
|
|
if (!e) continue;
|
|
if (e.pacify > 0) e.pacify--;
|
|
if (e.lockout > 0) e.lockout--;
|
|
}
|
|
|
|
// possessed cooldowns tick even if you don't use the ability
|
|
if (GAME.player && GAME.player.host){
|
|
const h = GAME.player.host;
|
|
if (h.overheatLeft > 0) h.overheatLeft--;
|
|
if (h.shootWait > 0) h.shootWait--;
|
|
if (h.blinkCd > 0) h.blinkCd--;
|
|
if (h.dashCd > 0) h.dashCd--;
|
|
|
|
if (h._overclockTurns > 0){
|
|
h._overclockTurns--;
|
|
if (h._overclockTurns <= 0){
|
|
if (h._baseDamage !== undefined) h.damage = h._baseDamage|0;
|
|
if (h._baseMaxHp !== undefined && (h._baseMaxHp|0) > 0) h.maxHp = h._baseMaxHp|0;
|
|
if (h.maxHp && h.hp > h.maxHp) h.hp = h.maxHp;
|
|
}
|
|
}
|
|
}
|
|
|
|
let ejectedThisStep = false;
|
|
|
|
function ejectGhostFresh(){
|
|
|
|
spawnParticles(GAME.player.x, GAME.player.y, 20, '#ffffff');
|
|
addShake(10);
|
|
sfx('death');
|
|
GAME.player.ghost = true;
|
|
GAME.player.host = null;
|
|
GAME.player.timer = baseGhostTimer();
|
|
GAME.state = 'playing';
|
|
ejectedThisStep = true;
|
|
}
|
|
|
|
function checkHostDeath(){
|
|
if (GAME.player && GAME.player.host && (GAME.player.host.hp|0) <= 0){
|
|
ejectGhostFresh();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
checkHostDeath();
|
|
|
|
if (!ejectedThisStep && GAME.player && GAME.player.ghost){
|
|
GAME.player.timer = Math.max(0, (GAME.player.timer|0) - 1);
|
|
if (GAME.player.timer <= 0){
|
|
GAME.state = 'lost';
|
|
spawnParticles(GAME.player.x, GAME.player.y, 28, '#ffffff');
|
|
addShake(14);
|
|
sfx('death');
|
|
try { save(); } catch(_) {}
|
|
}
|
|
}
|
|
|
|
if (GAME.state === 'lost'){
|
|
updateVisibility();
|
|
return;
|
|
}
|
|
|
|
const dist = buildDistMap(GAME.player.x, GAME.player.y);
|
|
|
|
const mimicDisguise = !!(GAME.player && GAME.player.host && GAME.player.host.type === 'Mimic' && GAME.player.host.disguised);
|
|
|
|
for (const e of (GAME.enemies||[]).slice()){
|
|
if (!e || e.pacify > 0) continue;
|
|
|
|
const md = Math.abs(e.x - GAME.player.x) + Math.abs(e.y - GAME.player.y);
|
|
const pd = (dist[e.y] && dist[e.y][e.x] !== undefined) ? dist[e.y][e.x] : Infinity;
|
|
const los = hasLOS(e.x, e.y, GAME.player.x, GAME.player.y);
|
|
const isRanged = (e.type === 'Sentinel' || e.type === 'Turret');
|
|
// Aggro gate: "clear path" within radius (path distance). Ranged enemies also need LOS to start shooting.
|
|
let inAggro = isFinite(pd) && pd <= AGGRO_R && (!isRanged || los);
|
|
if (mimicDisguise && e.type !== 'Mimic') inAggro = false;
|
|
|
|
// Mimic reveal is proximity-triggered even while "docile".
|
|
if (!inAggro && !(e.type === 'Mimic' && e.disguised && md === 1)) { e._aggro = false; continue; }
|
|
|
|
e._aggro = !!inAggro;
|
|
actEnemy(e, dist);
|
|
checkHostDeath();
|
|
}
|
|
|
|
for (const p of (GAME.projectiles||[])){
|
|
if (!p || p.dead) continue;
|
|
if (p.life === undefined) p.life = 18;
|
|
if (p.life <= 0) { p.dead = true; continue; }
|
|
p.life--;
|
|
const nx = (p.x|0) + (p.dx|0);
|
|
const ny = (p.y|0) + (p.dy|0);
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)) { p.dead = true; continue; }
|
|
p.x = nx; p.y = ny;
|
|
if (p.from === 'player'){
|
|
const hit = findEnemyAt(nx,ny);
|
|
if (hit){
|
|
damageEnemy(hit, p.damage||1, GAME.player.x, GAME.player.y);
|
|
p.dead = true;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (p.from !== 'player' && nx === GAME.player.x && ny === GAME.player.y){
|
|
damagePlayer(p.damage||1);
|
|
checkHostDeath();
|
|
p.dead = true;
|
|
}
|
|
}
|
|
|
|
updateVisibility();
|
|
}
|
|
|
|
function tick(n){
|
|
const steps = Math.max(0, (n|0) || 0);
|
|
for (let i=0;i<steps;i++) stepOnce();
|
|
draw();
|
|
}
|
|
|
|
|
|
// ------------------------------ combat + AI helpers (phase 2)
|
|
function damagePlayer(amount){
|
|
const dmg = Math.max(0, amount|0);
|
|
if (!dmg || !GAME.player) return;
|
|
const p = GAME.player;
|
|
const big = dmg >= 3;
|
|
|
|
if (p.host){
|
|
p.host.hp = (p.host.hp|0) - dmg;
|
|
runHostDamageTaken = (runHostDamageTaken|0) + dmg;
|
|
p.host._flashUntil = nowMs() + 100;
|
|
} else {
|
|
p.ghostHp = ((p.ghostHp===undefined)?1:p.ghostHp) - dmg;
|
|
p._flashUntil = nowMs() + 100;
|
|
}
|
|
|
|
addShake(big ? 10 : 4);
|
|
spawnParticles(p.x, p.y, big ? 16 : 8, '#ffffff');
|
|
sfx('hit');
|
|
ensureAchievements();
|
|
}
|
|
|
|
function buildDistMap(tx,ty){
|
|
const dist = Array.from({length:H}, ()=> Array.from({length:W}, ()=> Infinity));
|
|
const q = [];
|
|
if (!inBounds(tx,ty) || isWall(tx,ty)) return dist;
|
|
dist[ty][tx] = 0;
|
|
q.push([tx,ty]);
|
|
let qi=0;
|
|
while (qi < q.length){
|
|
const cur = q[qi++];
|
|
const x = cur[0], y = cur[1];
|
|
const d = dist[y][x];
|
|
const neigh = [[1,0],[-1,0],[0,1],[0,-1]];
|
|
for (let i=0;i<4;i++){
|
|
const nx=x+neigh[i][0], ny=y+neigh[i][1];
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)) continue;
|
|
if (dist[ny][nx] <= d+1) continue;
|
|
dist[ny][nx] = d+1;
|
|
q.push([nx,ny]);
|
|
}
|
|
}
|
|
return dist;
|
|
}
|
|
|
|
function nextStepToward(e, dist){
|
|
if (!e) return null;
|
|
const x=e.x|0, y=e.y|0;
|
|
const here = (dist[y] && dist[y][x]!==undefined) ? dist[y][x] : Infinity;
|
|
if (!isFinite(here)) return null;
|
|
let best = null;
|
|
const neigh = [[1,0],[-1,0],[0,1],[0,-1]];
|
|
for (let i=0;i<4;i++){
|
|
const nx=x+neigh[i][0], ny=y+neigh[i][1];
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)) continue;
|
|
if (nx === GAME.player.x && ny === GAME.player.y) continue;
|
|
const nd = dist[ny][nx];
|
|
if (!isFinite(nd)) continue;
|
|
if (!best || nd < best.d) best = {x:nx,y:ny,d:nd};
|
|
}
|
|
return best ? {x:best.x,y:best.y} : null;
|
|
}
|
|
|
|
function dirToward(ax,ay,bx,by){
|
|
const dx = bx-ax, dy = by-ay;
|
|
if (Math.abs(dx) >= Math.abs(dy)) return {dx: Math.sign(dx), dy: 0};
|
|
return {dx: 0, dy: Math.sign(dy)};
|
|
}
|
|
|
|
function actSentinel(e){
|
|
if (!e) return;
|
|
if (e.overheatLeft > 0){ e.overheatLeft--; return; }
|
|
if (e.burstLeft <= 0) e.burstLeft = (enemyDef('Sentinel')?.burst||3);
|
|
|
|
const d = dirToward(e.x,e.y,GAME.player.x,GAME.player.y);
|
|
if (!d.dx && !d.dy) return;
|
|
|
|
GAME.projectiles.push({
|
|
x: e.x,
|
|
y: e.y,
|
|
dx: d.dx,
|
|
dy: d.dy,
|
|
from: 'enemy',
|
|
type: 'SentinelShot',
|
|
damage: e.damage||1,
|
|
life: 18,
|
|
});
|
|
|
|
e.burstLeft--;
|
|
if (e.burstLeft <= 0) e.overheatLeft = (enemyDef('Sentinel')?.overheat||3);
|
|
}
|
|
|
|
function facingDelta(f){
|
|
if (f === 'up') return [0,-1];
|
|
if (f === 'down') return [0,1];
|
|
if (f === 'left') return [-1,0];
|
|
if (f === 'right') return [1,0];
|
|
return [0,1];
|
|
}
|
|
|
|
function facingFromDelta(dx,dy){
|
|
if (dx === 1) return 'right';
|
|
if (dx === -1) return 'left';
|
|
if (dy === -1) return 'up';
|
|
return 'down';
|
|
}
|
|
|
|
function damagePlayerFrom(amount, ax, ay){
|
|
const dmg = Math.max(0, amount|0);
|
|
if (!dmg) return;
|
|
|
|
const host = GAME.player && GAME.player.host;
|
|
if (host && host.type === 'Shielder'){
|
|
const d = facingDelta(GAME.player.facing);
|
|
if ((GAME.player.x + d[0]) === ax && (GAME.player.y + d[1]) === ay) return; // blocked
|
|
}
|
|
|
|
damagePlayer(dmg);
|
|
}
|
|
|
|
function shielderBlocks(e, attackerX, attackerY){
|
|
if (!e || e.type !== 'Shielder') return false;
|
|
const d = facingDelta(e.facing);
|
|
return (e.x + d[0]) === attackerX && (e.y + d[1]) === attackerY;
|
|
}
|
|
|
|
function explodePlayerOnly(cx, cy, r, dmg){
|
|
const pr = Math.max(0, r|0);
|
|
spawnParticles(cx|0, cy|0, 24, '#ffcc88');
|
|
addShake(12);
|
|
sfx('explosion');
|
|
|
|
if (!GAME.player) return;
|
|
const dx = Math.abs((GAME.player.x|0) - (cx|0));
|
|
const dy = Math.abs((GAME.player.y|0) - (cy|0));
|
|
if (Math.max(dx,dy) <= pr) damagePlayer(dmg|0);
|
|
}
|
|
|
|
function damageEnemy(target, amount, attackerX, attackerY){
|
|
if (!target) return false;
|
|
const dmg = Math.max(0, amount|0);
|
|
if (!dmg) return false;
|
|
|
|
if (shielderBlocks(target, attackerX, attackerY)) return false;
|
|
|
|
target.hp = (target.hp|0) - dmg;
|
|
target._flashUntil = nowMs() + 100;
|
|
|
|
if ((target.hp|0) > 0){
|
|
sfx('hit');
|
|
return true;
|
|
}
|
|
|
|
// death
|
|
spawnParticles(target.x, target.y, 18, '#ffffff');
|
|
sfx('death');
|
|
runStats.kills = (runStats.kills|0) + 1;
|
|
|
|
// On-death effects
|
|
if (target.type === 'Bomber'){
|
|
const def = enemyDef('Bomber') || {};
|
|
explodePlayerOnly(target.x, target.y, def.explodeR||1, def.explodeDamage||3);
|
|
}
|
|
|
|
removeEnemy(target);
|
|
GAME.essence = (GAME.essence|0) + (ESSENCE_VALUE[target.type]||0);
|
|
sfx('pickup');
|
|
ensureAchievements();
|
|
return true;
|
|
}
|
|
|
|
function explodeEnemies(cx, cy, r, dmg){
|
|
const rr = Math.max(0, r|0);
|
|
const es = (GAME.enemies||[]).slice();
|
|
let killed = 0;
|
|
for (const e of es){
|
|
if (!e) continue;
|
|
const dx = Math.abs((e.x|0) - (cx|0));
|
|
const dy = Math.abs((e.y|0) - (cy|0));
|
|
if (Math.max(dx,dy) > rr) continue;
|
|
const k0 = runStats.kills|0;
|
|
damageEnemy(e, dmg, cx, cy);
|
|
const k1 = runStats.kills|0;
|
|
if (k1 > k0) killed += (k1 - k0);
|
|
}
|
|
return killed|0;
|
|
}
|
|
|
|
function actEnemy(e, dist){
|
|
if (!e) return;
|
|
if (e.type === 'Sentinel') return actSentinel(e);
|
|
if (e.type === 'Turret') return actTurret(e);
|
|
if (e.type === 'Bomber') return actBomber(e, dist);
|
|
if (e.type === 'Charger') return actCharger(e);
|
|
if (e.type === 'Siren') return actSiren(e);
|
|
if (e.type === 'Healer') return actHealer(e, dist);
|
|
if (e.type === 'Phaser') return actPhaser(e, dist);
|
|
if (e.type === 'Mimic') return actMimic(e, dist);
|
|
if (e.type === 'Shielder') return actShielder(e, dist);
|
|
if (e.type === 'Leech') return actLeech(e, dist);
|
|
return actGenericMelee(e, dist);
|
|
}
|
|
|
|
function actGenericMelee(e, dist){
|
|
if (e._moveWait > 0){ e._moveWait--; return; }
|
|
const adj = (Math.abs(e.x-GAME.player.x) + Math.abs(e.y-GAME.player.y)) === 1;
|
|
if (adj){
|
|
damagePlayerFrom(e.damage||0, e.x, e.y);
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
return;
|
|
}
|
|
const ns = nextStepToward(e, dist);
|
|
if (ns){ e.x = ns.x; e.y = ns.y; }
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
}
|
|
|
|
function actShielder(e, dist){
|
|
const d = dirToward(e.x,e.y,GAME.player.x,GAME.player.y);
|
|
e.facing = facingFromDelta(d.dx,d.dy);
|
|
actGenericMelee(e, dist);
|
|
}
|
|
|
|
function actBomber(e, dist){
|
|
if (e._moveWait > 0){ e._moveWait--; return; }
|
|
const adj = (Math.abs(e.x-GAME.player.x) + Math.abs(e.y-GAME.player.y)) === 1;
|
|
if (adj){
|
|
const def = enemyDef('Bomber') || {};
|
|
explodePlayerOnly(e.x, e.y, def.explodeR||1, def.explodeDamage||3);
|
|
removeEnemy(e);
|
|
return;
|
|
}
|
|
const ns = nextStepToward(e, dist);
|
|
if (ns){ e.x = ns.x; e.y = ns.y; }
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
}
|
|
|
|
function actTurret(e){
|
|
const def = enemyDef('Turret') || {};
|
|
if (e.overheatLeft > 0){ e.overheatLeft--; return; }
|
|
if (e.burstLeft <= 0) e.burstLeft = def.burst || 3;
|
|
if (e.shootWait > 0){ e.shootWait--; return; }
|
|
|
|
const d = dirToward(e.x,e.y,GAME.player.x,GAME.player.y);
|
|
if (!d.dx && !d.dy) return;
|
|
|
|
GAME.projectiles.push({
|
|
x: e.x,
|
|
y: e.y,
|
|
dx: d.dx,
|
|
dy: d.dy,
|
|
from: 'enemy',
|
|
type: 'TurretShot',
|
|
damage: e.damage||1,
|
|
life: 18,
|
|
});
|
|
|
|
e.burstLeft--;
|
|
e.shootWait = Math.max(0, (def.shotEvery||2) - 1);
|
|
if (e.burstLeft <= 0){ e.overheatLeft = def.overheat || 3; e.shootWait = 0; }
|
|
}
|
|
|
|
function actHealer(e, dist){
|
|
// heal nearby enemies (+1) within 3
|
|
const rr = (enemyDef('Healer')?.healR)||3;
|
|
for (const o of (GAME.enemies||[])){
|
|
if (!o || o === e) continue;
|
|
const md = Math.abs(o.x-e.x) + Math.abs(o.y-e.y);
|
|
if (md <= rr) o.hp = Math.min(o.maxHp||o.hp, (o.hp|0) + 1);
|
|
}
|
|
|
|
if (e._moveWait > 0){ e._moveWait--; return; }
|
|
// flee
|
|
const neigh = [[1,0],[-1,0],[0,1],[0,-1]];
|
|
let best = null;
|
|
for (const n of neigh){
|
|
const nx=e.x+n[0], ny=e.y+n[1];
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)) continue;
|
|
if (nx===GAME.player.x && ny===GAME.player.y) continue;
|
|
const d = dist[ny] ? dist[ny][nx] : Infinity;
|
|
if (!isFinite(d)) continue;
|
|
if (!best || d > best.d) best = {x:nx,y:ny,d};
|
|
}
|
|
if (best){ e.x=best.x; e.y=best.y; }
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
}
|
|
|
|
function actPhaser(e, dist){
|
|
const def = enemyDef('Phaser') || {};
|
|
if (e.tpCd > 0){ e.tpCd--; return; }
|
|
|
|
// teleport to an adjacent tile near the player (if possible)
|
|
const opts = [[1,0],[-1,0],[0,1],[0,-1]];
|
|
let spot = null;
|
|
for (const o of opts){
|
|
const nx = GAME.player.x + o[0];
|
|
const ny = GAME.player.y + o[1];
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)) continue;
|
|
if (findEnemyAt(nx,ny)) continue;
|
|
spot = {x:nx,y:ny};
|
|
break;
|
|
}
|
|
if (spot){
|
|
e.x = spot.x; e.y = spot.y;
|
|
e.tpCd = def.tpEvery || 3;
|
|
const adj = (Math.abs(e.x-GAME.player.x) + Math.abs(e.y-GAME.player.y)) === 1;
|
|
if (adj) damagePlayerFrom(e.damage||0, e.x, e.y);
|
|
return;
|
|
}
|
|
|
|
actGenericMelee(e, dist);
|
|
}
|
|
|
|
function actCharger(e){
|
|
const def = enemyDef('Charger') || {};
|
|
if (e.stun > 0){ e.stun--; return; }
|
|
|
|
if (e.chargeLeft > 0){
|
|
const nx = e.x + (e.chargeDx|0);
|
|
const ny = e.y + (e.chargeDy|0);
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)){
|
|
e.stun = 2;
|
|
e.chargeLeft = 0;
|
|
return;
|
|
}
|
|
if (nx === GAME.player.x && ny === GAME.player.y){
|
|
damagePlayer(def.chargeDamage||3);
|
|
e.x = nx; e.y = ny;
|
|
e.chargeLeft = 0;
|
|
return;
|
|
}
|
|
const occ = findEnemyAt(nx,ny);
|
|
if (occ && occ !== e){ e.chargeLeft = 0; return; }
|
|
e.x = nx; e.y = ny;
|
|
e.chargeLeft--;
|
|
if (e.x === e.chargeTargetX && e.y === e.chargeTargetY) e.chargeLeft = 0;
|
|
return;
|
|
}
|
|
|
|
if (e.telegraphLeft > 0){
|
|
e.telegraphLeft--;
|
|
if (e.telegraphLeft <= 0){
|
|
e.chargeLeft = 8;
|
|
}
|
|
return;
|
|
}
|
|
|
|
// start telegraph
|
|
e.telegraphLeft = def.telegraph || 1;
|
|
e.chargeTargetX = GAME.player.x;
|
|
e.chargeTargetY = GAME.player.y;
|
|
const d = dirToward(e.x,e.y,e.chargeTargetX,e.chargeTargetY);
|
|
e.chargeDx = d.dx;
|
|
e.chargeDy = d.dy;
|
|
}
|
|
|
|
function actSiren(e){
|
|
const def = enemyDef('Siren') || {};
|
|
const md = Math.abs(e.x - GAME.player.x) + Math.abs(e.y - GAME.player.y);
|
|
|
|
if (md <= (def.pullR||5)){
|
|
const d = dirToward(GAME.player.x, GAME.player.y, e.x, e.y);
|
|
const nx = GAME.player.x + d.dx;
|
|
const ny = GAME.player.y + d.dy;
|
|
if (inBounds(nx,ny) && !isWall(nx,ny) && !(nx===e.x && ny===e.y)){
|
|
const ox = GAME.player.x|0, oy = GAME.player.y|0;
|
|
GAME.player.x = nx; GAME.player.y = ny;
|
|
markAnimMove(GAME.player, ox, oy);
|
|
}
|
|
}
|
|
|
|
if (e._moveWait > 0){ e._moveWait--; return; }
|
|
if (md === 1){
|
|
damagePlayerFrom(e.damage||0, e.x, e.y);
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
}
|
|
}
|
|
|
|
function actMimic(e, dist){
|
|
const md = Math.abs(e.x - GAME.player.x) + Math.abs(e.y - GAME.player.y);
|
|
if (e.disguised && md === 1){
|
|
e.disguised = false;
|
|
e.revealed = true;
|
|
// cross burst (2 dmg) to player only
|
|
damagePlayer(2);
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
return;
|
|
}
|
|
actGenericMelee(e, dist);
|
|
}
|
|
|
|
function actLeech(e, dist){
|
|
if (e._moveWait > 0){ e._moveWait--; return; }
|
|
const adj = (Math.abs(e.x-GAME.player.x) + Math.abs(e.y-GAME.player.y)) === 1;
|
|
if (adj){
|
|
damagePlayerFrom(1, e.x, e.y);
|
|
e.hp = Math.min(e.maxHp||e.hp, (e.hp|0) + 1);
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
return;
|
|
}
|
|
const ns = nextStepToward(e, dist);
|
|
if (ns){ e.x = ns.x; e.y = ns.y; }
|
|
e._moveWait = Math.max(0, (e.speed|0) - 1);
|
|
}
|
|
|
|
function tryPossess(){
|
|
if (!GAME.player || !GAME.player.ghost || GAME.state !== 'playing') return false;
|
|
const px = GAME.player.x, py = GAME.player.y;
|
|
const up = GAME.upgrades || {};
|
|
const range = up.ghostT2 ? 2 : 1;
|
|
|
|
const es = GAME.enemies||[];
|
|
let target = null;
|
|
for (const e of es){
|
|
if (!e) continue;
|
|
if (e.lockout > 0) continue;
|
|
const md = Math.abs(e.x-px) + Math.abs(e.y-py);
|
|
if (md <= range){ target = e; break; }
|
|
}
|
|
if (!target) return false;
|
|
|
|
removeEnemy(target);
|
|
GAME.player.ghost = false;
|
|
GAME.player.host = target;
|
|
GAME.player.x = target.x;
|
|
GAME.player.y = target.y;
|
|
GAME.state = 'possessed';
|
|
|
|
markPossession(target.type);
|
|
spawnParticles(target.x, target.y, 14, '#e8e8e8');
|
|
GAME.player._moveWait = 0;
|
|
|
|
// Body T2: overclock on fresh possession.
|
|
if (up.bodyT2){
|
|
target._overclockTurns = 5;
|
|
target._baseDamage = target.damage|0;
|
|
target._baseMaxHp = target.maxHp|0;
|
|
target.damage = Math.ceil((target.damage|0) * 1.5);
|
|
target.maxHp = Math.ceil((target.maxHp|0) * 1.5);
|
|
target.hp = Math.min(target.maxHp, Math.ceil((target.hp|0) * 1.5));
|
|
}
|
|
|
|
if (GAME.achievements && !GAME.achievements.firstPossession) GAME.achievements.firstPossession = true;
|
|
ensureAchievements();
|
|
|
|
sfx('possess');
|
|
try { save(); } catch(_){}
|
|
|
|
return true;
|
|
}
|
|
|
|
function abandonHost(){
|
|
if (!GAME.player || !GAME.player.host) return;
|
|
const host = GAME.player.host;
|
|
host.pacify = 2;
|
|
host.lockout = 2;
|
|
host.x = GAME.player.x;
|
|
host.y = GAME.player.y;
|
|
GAME.enemies.push(host);
|
|
|
|
GAME.player.host = null;
|
|
GAME.player.ghost = true;
|
|
GAME.state = 'playing';
|
|
|
|
sfx('abandon');
|
|
|
|
spawnParticles(host.x, host.y, 10, '#e8e8e8');
|
|
addShake(4);
|
|
const ox = GAME.player.x|0, oy = GAME.player.y|0;
|
|
|
|
// move the ghost 1 tile off the body if possible (so lockout is meaningful)
|
|
const opts = [[1,0],[-1,0],[0,1],[0,-1]];
|
|
for (let i=0;i<opts.length;i++){
|
|
const nx = GAME.player.x + opts[i][0];
|
|
const ny = GAME.player.y + opts[i][1];
|
|
if (inBounds(nx,ny) && !isWall(nx,ny)) { markAnimMove(GAME.player, ox, oy); GAME.player.x=nx; GAME.player.y=ny; break; }
|
|
}
|
|
|
|
try { save(); } catch(_){}
|
|
}
|
|
|
|
function hostAttack(){
|
|
const host = GAME.player && GAME.player.host;
|
|
if (!host) return;
|
|
|
|
const del = facingDelta(GAME.player.facing);
|
|
|
|
if (host.type === 'Sentinel'){
|
|
if (host.overheatLeft > 0) return;
|
|
if (host.burstLeft <= 0) host.burstLeft = (enemyDef('Sentinel')?.burst||3);
|
|
|
|
GAME.projectiles.push({ x: GAME.player.x, y: GAME.player.y, dx: del[0], dy: del[1], from: 'player', type:'PlayerShot', damage: 1, life: 18 });
|
|
|
|
host.burstLeft--;
|
|
if (host.burstLeft <= 0) host.overheatLeft = (enemyDef('Sentinel')?.overheat||3);
|
|
return;
|
|
}
|
|
|
|
if (host.type === 'Turret'){
|
|
if (host.overheatLeft > 0) return;
|
|
if (host.shootWait > 0) return;
|
|
if (host.burstLeft <= 0) host.burstLeft = (enemyDef('Turret')?.burst||3);
|
|
|
|
GAME.projectiles.push({ x: GAME.player.x, y: GAME.player.y, dx: del[0], dy: del[1], from: 'player', type:'TurretPlayerShot', damage: 2, life: 18 });
|
|
|
|
host.burstLeft--;
|
|
host.shootWait = Math.max(0, ((enemyDef('Turret')?.shotEvery)||2) - 1);
|
|
if (host.burstLeft <= 0) { host.overheatLeft = (enemyDef('Turret')?.overheat||3); host.shootWait = 0; }
|
|
return;
|
|
}
|
|
|
|
if (host.type === 'Bomber'){
|
|
const k = explodeEnemies(GAME.player.x, GAME.player.y, 1, 4);
|
|
if (k >= 3 && GAME.achievements) GAME.achievements.bomberman = true;
|
|
ensureAchievements();
|
|
|
|
spawnParticles(GAME.player.x, GAME.player.y, 28, '#ffcc88');
|
|
addShake(14);
|
|
sfx('explosion');
|
|
|
|
// suicide + eject as ghost
|
|
GAME.player.ghost = true;
|
|
GAME.player.host = null;
|
|
GAME.player.timer = baseGhostTimer();
|
|
GAME.state = 'playing';
|
|
try { save(); } catch(_) {}
|
|
return;
|
|
}
|
|
|
|
if (host.type === 'Healer'){
|
|
host.hp = Math.min(host.maxHp||host.hp, (host.hp|0) + 2);
|
|
const rr = (enemyDef('Healer')?.healR)||3;
|
|
for (const o of (GAME.enemies||[])){
|
|
if (!o) continue;
|
|
const md = Math.abs(o.x-GAME.player.x) + Math.abs(o.y-GAME.player.y);
|
|
if (md <= rr) o.hp = Math.min(o.maxHp||o.hp, (o.hp|0) + 1);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (host.type === 'Phaser'){
|
|
if (host.blinkCd > 0) return;
|
|
let bx = GAME.player.x, by = GAME.player.y;
|
|
for (let i=1;i<=5;i++){
|
|
const nx = GAME.player.x + del[0]*i;
|
|
const ny = GAME.player.y + del[1]*i;
|
|
if (!inBounds(nx,ny)) break;
|
|
if (!isWall(nx,ny)) { bx = nx; by = ny; }
|
|
}
|
|
const ox = GAME.player.x|0, oy = GAME.player.y|0;
|
|
GAME.player.x = bx; GAME.player.y = by;
|
|
markAnimMove(GAME.player, ox, oy);
|
|
host.blinkCd = 2;
|
|
return;
|
|
}
|
|
|
|
if (host.type === 'Charger'){
|
|
if (host.dashCd > 0) return;
|
|
let cx = GAME.player.x, cy = GAME.player.y;
|
|
for (let i=0;i<4;i++){
|
|
const nx = cx + del[0];
|
|
const ny = cy + del[1];
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)) break;
|
|
const en = findEnemyAt(nx,ny);
|
|
if (en){
|
|
damageEnemy(en, 2, cx, cy);
|
|
if (findEnemyAt(nx,ny)) break; // blocked by surviving enemy
|
|
}
|
|
cx = nx; cy = ny;
|
|
}
|
|
const ox = GAME.player.x|0, oy = GAME.player.y|0;
|
|
GAME.player.x = cx; GAME.player.y = cy;
|
|
markAnimMove(GAME.player, ox, oy);
|
|
host.dashCd = 2;
|
|
return;
|
|
}
|
|
|
|
if (host.type === 'Siren'){
|
|
const rr = 4;
|
|
for (const en of (GAME.enemies||[])){
|
|
if (!en) continue;
|
|
const md = Math.abs(en.x-GAME.player.x) + Math.abs(en.y-GAME.player.y);
|
|
if (md > rr) continue;
|
|
const d = dirToward(en.x,en.y,GAME.player.x,GAME.player.y);
|
|
const nx = en.x + d.dx;
|
|
const ny = en.y + d.dy;
|
|
if (!inBounds(nx,ny) || isWall(nx,ny)) continue;
|
|
if (nx === GAME.player.x && ny === GAME.player.y) continue;
|
|
if (findEnemyAt(nx,ny)) continue;
|
|
en.x = nx; en.y = ny;
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (host.type === 'Mimic'){
|
|
host.disguised = false;
|
|
for (const en of (GAME.enemies||[]).slice()){
|
|
if (!en) continue;
|
|
const md = Math.abs(en.x-GAME.player.x) + Math.abs(en.y-GAME.player.y);
|
|
if (md === 1) damageEnemy(en, 2, GAME.player.x, GAME.player.y);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// default melee
|
|
const cand = [
|
|
{x: GAME.player.x, y: GAME.player.y},
|
|
{x: GAME.player.x + del[0], y: GAME.player.y + del[1]},
|
|
{x: GAME.player.x + 1, y: GAME.player.y},
|
|
{x: GAME.player.x - 1, y: GAME.player.y},
|
|
{x: GAME.player.x, y: GAME.player.y + 1},
|
|
{x: GAME.player.x, y: GAME.player.y - 1},
|
|
];
|
|
|
|
let target = null;
|
|
for (const c of cand){
|
|
target = findEnemyAt(c.x,c.y);
|
|
if (target) break;
|
|
}
|
|
if (!target) return;
|
|
|
|
damageEnemy(target, Math.max(1, host.damage|0), GAME.player.x, GAME.player.y);
|
|
|
|
if (host.type === 'Leech') host.hp = Math.min(host.maxHp||host.hp, (host.hp|0) + 1);
|
|
}
|
|
|
|
function snapshotEnemy(e){
|
|
if (!e) return null;
|
|
const out = {
|
|
id: (e.id|0) || 0,
|
|
type: String(e.type||'Brute'),
|
|
x: e.x|0, y: e.y|0,
|
|
hp: e.hp|0, maxHp: e.maxHp|0,
|
|
damage: e.damage|0,
|
|
speed: e.speed|0,
|
|
facing: String(e.facing||'down'),
|
|
|
|
_moveWait: e._moveWait|0,
|
|
pacify: e.pacify|0,
|
|
lockout: e.lockout|0,
|
|
|
|
burstLeft: e.burstLeft|0,
|
|
overheatLeft: e.overheatLeft|0,
|
|
shootWait: e.shootWait|0,
|
|
|
|
tpCd: e.tpCd|0,
|
|
stun: e.stun|0,
|
|
telegraphLeft: e.telegraphLeft|0,
|
|
chargeLeft: e.chargeLeft|0,
|
|
chargeDx: e.chargeDx|0,
|
|
chargeDy: e.chargeDy|0,
|
|
chargeTargetX: e.chargeTargetX|0,
|
|
chargeTargetY: e.chargeTargetY|0,
|
|
|
|
disguised: !!e.disguised,
|
|
revealed: !!e.revealed,
|
|
|
|
blinkCd: e.blinkCd|0,
|
|
dashCd: e.dashCd|0,
|
|
|
|
_overclockTurns: e._overclockTurns|0,
|
|
_baseDamage: e._baseDamage|0,
|
|
_baseMaxHp: e._baseMaxHp|0,
|
|
};
|
|
return out;
|
|
}
|
|
|
|
function snapshotProjectile(p){
|
|
if (!p) return null;
|
|
return {
|
|
x: p.x|0, y: p.y|0,
|
|
dx: p.dx|0, dy: p.dy|0,
|
|
from: String(p.from||'enemy'),
|
|
type: String(p.type||'Shot'),
|
|
damage: p.damage|0,
|
|
life: p.life|0,
|
|
dead: !!p.dead,
|
|
};
|
|
}
|
|
|
|
function save(){
|
|
try {
|
|
if (typeof localStorage === 'undefined' || !localStorage || !localStorage.setItem) return;
|
|
|
|
const p = GAME.player || makePlayer();
|
|
const host = (p && p.host && !p.ghost) ? snapshotEnemy(p.host) : null;
|
|
|
|
const data = {
|
|
v: 2,
|
|
seedBase: seedBase >>> 0,
|
|
floor: clampFloorNum(GAME.floor),
|
|
essence: Math.max(0, GAME.essence|0),
|
|
upgrades: GAME.upgrades || {},
|
|
achievements: GAME.achievements || {},
|
|
|
|
|
|
run: {
|
|
possessed: runPossessed || {},
|
|
hostDamageTaken: runHostDamageTaken|0,
|
|
stats: runStats || {},
|
|
},
|
|
|
|
player: {
|
|
x: p.x|0, y: p.y|0,
|
|
ghost: !!p.ghost,
|
|
timer: (p.timer|0),
|
|
facing: String(p.facing||'down'),
|
|
host,
|
|
},
|
|
|
|
enemies: (GAME.enemies||[]).map(snapshotEnemy).filter(Boolean),
|
|
projectiles: (GAME.projectiles||[]).map(snapshotProjectile).filter(Boolean),
|
|
|
|
grid: GAME.grid,
|
|
exit: (GAME._exit && GAME._exit.x!==undefined) ? { x: GAME._exit.x|0, y: GAME._exit.y|0 } : null,
|
|
chests: GAME._chests || {},
|
|
};
|
|
|
|
localStorage.setItem(SAVE_KEY, JSON.stringify(data));
|
|
} catch (_) {}
|
|
}
|
|
|
|
function normFacing(f){
|
|
const s = String(f||'down');
|
|
return (s==='up'||s==='down'||s==='left'||s==='right') ? s : 'down';
|
|
}
|
|
|
|
function normGrid(g){
|
|
if (!Array.isArray(g) || !g.length) return null;
|
|
const out = Array.from({length:H}, (_,y)=>{
|
|
const row = Array.isArray(g[y]) ? g[y] : [];
|
|
return Array.from({length:W}, (_,x)=>{
|
|
const v = row[x];
|
|
const t = (typeof v === 'number') ? v : ((v && typeof v === 'object' && typeof v.type === 'number') ? v.type : T_WALL);
|
|
const n = t|0;
|
|
if (n < 0 || n > 5) return T_WALL;
|
|
return n;
|
|
});
|
|
});
|
|
return out;
|
|
}
|
|
|
|
function scanExitFromGrid(){
|
|
const g = GAME.grid;
|
|
if (!Array.isArray(g) || !g.length) return null;
|
|
for (let y=0;y<g.length;y++){
|
|
for (let x=0;x<g[y].length;x++){
|
|
if (tile(x,y) === T_EXIT) return {x,y};
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function normUpgrades(u){
|
|
const out = {};
|
|
const src = (u && typeof u === 'object') ? u : {};
|
|
for (const it of UPGRADE_POOL){
|
|
if (src[it.id] || src[String(it.id).toLowerCase()] || src[it.id.replace(/[A-Z]/g, m=>'_'+m.toLowerCase())]) out[it.id] = true;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function normAchievements(a){
|
|
const src = (a && typeof a === 'object') ? a : {};
|
|
const out = {};
|
|
for (const [k,v] of Object.entries(src)) if (v === true) out[k] = true;
|
|
return out;
|
|
}
|
|
|
|
function normEnemy(e){
|
|
if (!e || typeof e !== 'object') return null;
|
|
const type = String(e.type||'Brute');
|
|
const def = enemyDef(type) || enemyDef('Brute');
|
|
const x = e.x|0, y = e.y|0;
|
|
if (!inBounds(x,y) || isWall(x,y)) return null;
|
|
|
|
const out = {
|
|
id: (e.id|0) || nextEnemyId++,
|
|
type,
|
|
x, y,
|
|
hp: Math.max(1, (e.hp|0) || (def?def.maxHp:1)),
|
|
maxHp: Math.max(1, (e.maxHp|0) || (def?def.maxHp:1)),
|
|
damage: (e.damage|0) || (def?def.damage:0),
|
|
speed: (e.speed|0) || (def?def.speed:999),
|
|
facing: normFacing(e.facing),
|
|
|
|
_moveWait: e._moveWait|0,
|
|
_aggro: !!e._aggro,
|
|
pacify: e.pacify|0,
|
|
lockout: e.lockout|0,
|
|
|
|
burstLeft: e.burstLeft|0,
|
|
overheatLeft: e.overheatLeft|0,
|
|
shootWait: e.shootWait|0,
|
|
|
|
tpCd: e.tpCd|0,
|
|
stun: e.stun|0,
|
|
telegraphLeft: e.telegraphLeft|0,
|
|
chargeLeft: e.chargeLeft|0,
|
|
chargeDx: e.chargeDx|0,
|
|
chargeDy: e.chargeDy|0,
|
|
chargeTargetX: e.chargeTargetX|0,
|
|
chargeTargetY: e.chargeTargetY|0,
|
|
|
|
disguised: !!e.disguised,
|
|
revealed: !!e.revealed,
|
|
|
|
blinkCd: e.blinkCd|0,
|
|
dashCd: e.dashCd|0,
|
|
|
|
_overclockTurns: e._overclockTurns|0,
|
|
_baseDamage: e._baseDamage|0,
|
|
_baseMaxHp: e._baseMaxHp|0,
|
|
};
|
|
|
|
// Re-initialize burst defaults if missing.
|
|
if ((type === 'Sentinel' || type === 'Turret') && out.burstLeft <= 0) out.burstLeft = (enemyDef(type)?.burst||3);
|
|
return out;
|
|
}
|
|
|
|
function load(){
|
|
try {
|
|
if (typeof localStorage === 'undefined' || !localStorage || !localStorage.getItem) return;
|
|
const raw = localStorage.getItem(SAVE_KEY);
|
|
if (!raw) return;
|
|
|
|
let data = null;
|
|
try { data = JSON.parse(raw); } catch (_) { data = null; }
|
|
if (!data || !data.grid) return;
|
|
|
|
const floorNum = clampFloorNum(data.floor);
|
|
const g = normGrid(data.grid);
|
|
if (!g){
|
|
seedBase = (((Math.random()*1e9)>>>0) ^ ((Date.now()||0)>>>0)) >>> 0;
|
|
GAME.floor = floorNum;
|
|
genBasicFloor(floorNum);
|
|
} else {
|
|
GAME.grid = g;
|
|
GAME.floor = floorNum;
|
|
}
|
|
|
|
seedBase = (data.seedBase>>>0) || seedBase;
|
|
GAME.essence = Math.max(0, data.essence|0);
|
|
GAME.upgrades = normUpgrades(data.upgrades);
|
|
GAME.achievements = normAchievements(data.achievements);
|
|
GAME._chests = (data.chests && typeof data.chests === 'object') ? data.chests : {};
|
|
|
|
|
|
// restore run trackers (for in-run achievements across refresh)
|
|
const rr = (data.run && typeof data.run === 'object') ? data.run : null;
|
|
runPossessed = (rr && rr.possessed && typeof rr.possessed === 'object') ? rr.possessed : {};
|
|
runHostDamageTaken = (rr && rr.hostDamageTaken !== undefined) ? (rr.hostDamageTaken|0) : 0;
|
|
runStats = (rr && rr.stats && typeof rr.stats === 'object')
|
|
? Object.assign({ turns:0, kills:0, possessions:0, floorReached: (GAME.floor|0)||1 }, rr.stats)
|
|
: { turns:0, kills:0, possessions:0, floorReached: (GAME.floor|0)||1 };
|
|
|
|
// enemies
|
|
nextEnemyId = 1;
|
|
const ens = Array.isArray(data.enemies) ? data.enemies : [];
|
|
GAME.enemies = [];
|
|
for (const e of ens){
|
|
const ne = normEnemy(e);
|
|
if (!ne) continue;
|
|
GAME.enemies.push(ne);
|
|
nextEnemyId = Math.max(nextEnemyId, (ne.id|0)+1);
|
|
}
|
|
|
|
// projectiles
|
|
GAME.projectiles = Array.isArray(data.projectiles) ? data.projectiles.map(snapshotProjectile).filter(Boolean) : [];
|
|
|
|
// player + host
|
|
const pl = (data.player && typeof data.player === 'object') ? data.player : {};
|
|
const p = makePlayer();
|
|
p.x = (pl.x|0); p.y = (pl.y|0);
|
|
if (!inBounds(p.x,p.y) || isWall(p.x,p.y)) { p.x = SPAWN_X; p.y = SPAWN_Y; }
|
|
p.ghost = !!pl.ghost;
|
|
p.timer = (pl.timer|0);
|
|
if (p.timer <= 0) p.timer = baseGhostTimer();
|
|
p.facing = normFacing(pl.facing);
|
|
|
|
let host = null;
|
|
if (!p.ghost && pl.host) host = normEnemy(pl.host);
|
|
if (host){
|
|
p.host = host;
|
|
p.ghost = false;
|
|
p.x = host.x; p.y = host.y;
|
|
GAME.state = 'possessed';
|
|
} else {
|
|
p.host = null;
|
|
p.ghost = true;
|
|
GAME.state = 'playing';
|
|
}
|
|
|
|
GAME.player = p;
|
|
|
|
// exit restore
|
|
const scanned = scanExitFromGrid();
|
|
const savedExit = (data.exit && data.exit.x!==undefined) ? { x: data.exit.x|0, y: data.exit.y|0 } : null;
|
|
GAME._exit = scanned || (savedExit && inBounds(savedExit.x,savedExit.y) ? savedExit : null);
|
|
if (GAME._exit && !isWall(GAME._exit.x, GAME._exit.y)) setTile(GAME._exit.x, GAME._exit.y, T_EXIT);
|
|
|
|
resetFog();
|
|
ensureAchievements();
|
|
updateVisibility();
|
|
draw();
|
|
} catch (_) {}
|
|
}
|
|
|
|
function upgradeById(id){
|
|
for (const it of UPGRADE_POOL) if (it.id === id) return it;
|
|
return null;
|
|
}
|
|
|
|
function upgradeOwned(id){
|
|
const up = GAME.upgrades || {};
|
|
return !!up[id];
|
|
}
|
|
|
|
function prereqMet(it){
|
|
if (!it) return false;
|
|
if ((it.tier|0) <= 1) return true;
|
|
const need = it.tree + 'T' + ((it.tier|0) - 1);
|
|
return upgradeOwned(need);
|
|
}
|
|
|
|
function upgradeCost(it){
|
|
const base = Math.max(0, (it && it.cost|0) || 0);
|
|
if (!base) return 0;
|
|
if (upgradeOwned('metaT3')) return Math.max(1, Math.ceil(base * 0.7));
|
|
return base;
|
|
}
|
|
|
|
function rollShopChoices(){
|
|
const rand = mulberry32((seedBase + (GAME.floor|0)*31337 + (turn|0)*97 + 11) >>> 0);
|
|
const owned = GAME.upgrades || {};
|
|
|
|
const remaining = UPGRADE_POOL.filter(it => !owned[it.id]);
|
|
const buyable = remaining.filter(prereqMet);
|
|
|
|
// ensure choice[0] is buyable + unowned when possible
|
|
const first = (buyable[0] || remaining[0] || UPGRADE_POOL[0]);
|
|
const picks = [];
|
|
if (first) picks.push(first);
|
|
|
|
// fill remaining slots randomly
|
|
const pool = remaining.slice();
|
|
for (let i=0;i<pool.length;i++){
|
|
const j = i + Math.floor(rand()*(pool.length-i));
|
|
const tmp = pool[i]; pool[i]=pool[j]; pool[j]=tmp;
|
|
}
|
|
for (const it of pool){
|
|
if (picks.length >= 3) break;
|
|
if (!it || picks.find(x=>x.id===it.id)) continue;
|
|
picks.push(it);
|
|
}
|
|
|
|
while (picks.length < 3) picks.push(UPGRADE_POOL[picks.length % UPGRADE_POOL.length]);
|
|
return picks.slice(0,3);
|
|
}
|
|
|
|
function enterShop(nextFloor, debug){
|
|
GAME.state = 'shop';
|
|
GAME._shopSelection = 0;
|
|
GAME._shopBought = false;
|
|
GAME._shopNextFloor = clampFloorNum(nextFloor || ((GAME.floor|0)+1));
|
|
|
|
if (debug) GAME.essence = Math.max(GAME.essence|0, 30);
|
|
|
|
GAME.choices = rollShopChoices();
|
|
GAME.shopChoices = GAME.choices;
|
|
GAME.upgradeChoices = GAME.choices;
|
|
|
|
draw();
|
|
}
|
|
|
|
function leaveShop(){
|
|
const nf = clampFloorNum(GAME._shopNextFloor || ((GAME.floor|0)+1));
|
|
GAME._shopSelection = 0;
|
|
GAME._shopBought = false;
|
|
|
|
// Between-floor shop: proceed.
|
|
setFloor(nf);
|
|
}
|
|
|
|
function openShop(){
|
|
// Debug: grant stipend so buy(0) can succeed.
|
|
enterShop(GAME.floor|0, true);
|
|
}
|
|
|
|
function buy(index){
|
|
const choices = GAME.choices || GAME.shopChoices || GAME.upgradeChoices;
|
|
const idx = index|0;
|
|
if (!choices || idx < 0 || idx >= choices.length) return false;
|
|
|
|
const it = choices[idx];
|
|
if (!it || !it.id) return false;
|
|
if (upgradeOwned(it.id)) return false;
|
|
if (!prereqMet(it)) return false;
|
|
|
|
const cost = upgradeCost(it);
|
|
if ((GAME.essence|0) < cost) return false;
|
|
|
|
GAME.essence = (GAME.essence|0) - cost;
|
|
if (!GAME.upgrades) GAME.upgrades = {};
|
|
GAME.upgrades[it.id] = true;
|
|
|
|
// immediate effects
|
|
if (it.id === 'ghostT1' && GAME.player && GAME.player.ghost) GAME.player.timer = Math.max(GAME.player.timer|0, 20);
|
|
if (it.id === 'bodyT3' && GAME.achievements) GAME.achievements.dualWield = true;
|
|
|
|
ensureAchievements();
|
|
try { save(); } catch(_) {}
|
|
return true;
|
|
}
|
|
|
|
// ------------------------------ rendering
|
|
function clear(){
|
|
ctx.clearRect(0,0,CANVAS_W,CANVAS_H);
|
|
}
|
|
|
|
function drawHUD(){
|
|
// HUD background
|
|
ctx.fillStyle = '#111318';
|
|
ctx.fillRect(0,0,CANVAS_W,HUD_H);
|
|
ctx.strokeStyle = '#222';
|
|
ctx.strokeRect(0,0,CANVAS_W,HUD_H);
|
|
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.font = '14px system-ui, -apple-system, sans-serif';
|
|
|
|
const p = GAME.player || {};
|
|
const timer = (p.timer !== undefined) ? (p.timer|0) : 0;
|
|
const ess = GAME.essence|0;
|
|
|
|
ctx.fillText('Floor: '+(GAME.floor||1)+' Essence: '+ess, 12, 24);
|
|
|
|
if (p.ghost || !p.host){
|
|
ctx.fillText('Ghost Timer: '+timer+'s', 12, 44);
|
|
} else {
|
|
const h = p.host;
|
|
ctx.fillText('Body HP: '+(h.hp|0)+'/'+(h.maxHp|0), 12, 44);
|
|
}
|
|
|
|
const hint = (p.ghost)
|
|
? 'SPACE: possess (ghost) Q/E: rotate facing ESC: pause'
|
|
: 'SPACE: attack/special X: abandon host Q/E: rotate ESC: pause';
|
|
ctx.fillText(hint, 260, 44);
|
|
}
|
|
|
|
function drawGrid(){
|
|
for (let y=0;y<H;y++){
|
|
for (let x=0;x<W;x++){
|
|
const px = x*TILE;
|
|
const py = HUD_H + y*TILE;
|
|
|
|
const vis = visible[y] && visible[y][x];
|
|
const exp = explored[y] && explored[y][x];
|
|
|
|
if (!exp){
|
|
ctx.fillStyle = '#000';
|
|
ctx.fillRect(px,py,TILE,TILE);
|
|
} else {
|
|
const t = tile(x,y);
|
|
if (t === T_WALL) ctx.fillStyle = '#141414';
|
|
else if (t === T_EXIT) ctx.fillStyle = '#164a2a';
|
|
else if (t === T_SHOP) ctx.fillStyle = '#173b66';
|
|
else if (t === T_CHEST) ctx.fillStyle = '#4a341a';
|
|
else ctx.fillStyle = '#1b1f26';
|
|
ctx.fillRect(px,py,TILE,TILE);
|
|
|
|
if (!vis){
|
|
ctx.fillStyle = 'rgba(0,0,0,0.55)';
|
|
ctx.fillRect(px,py,TILE,TILE);
|
|
}
|
|
}
|
|
|
|
// grid lines visible
|
|
ctx.strokeStyle = 'rgba(255,255,255,0.06)';
|
|
ctx.strokeRect(px+0.5,py+0.5,TILE,TILE);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
function drawEnemies(){
|
|
const es = GAME.enemies || [];
|
|
const tNow = nowMs();
|
|
function poly(cx,cy,r,sides,rot){
|
|
ctx.beginPath();
|
|
for (let i=0;i<sides;i++){
|
|
const a = rot + (Math.PI*2)*(i/sides);
|
|
const x = cx + Math.cos(a)*r;
|
|
const y = cy + Math.sin(a)*r;
|
|
if (i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y);
|
|
}
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
}
|
|
|
|
for (const e of es){
|
|
if (!e) continue;
|
|
if (!visible[e.y] || !visible[e.y][e.x]) continue;
|
|
const cx = e.x*TILE + TILE/2;
|
|
const cy = HUD_H + e.y*TILE + TILE/2;
|
|
const flash = !!(e._flashUntil && tNow < e._flashUntil);
|
|
|
|
ctx.save();
|
|
if (flash){
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.fillRect(cx-10, cy-10, 20, 20);
|
|
ctx.restore();
|
|
continue;
|
|
}
|
|
|
|
if (e.type === 'Brute'){
|
|
ctx.fillStyle = '#b33';
|
|
ctx.fillRect(cx-14, cy-14, 28, 28);
|
|
} else if (e.type === 'Skitterer'){
|
|
ctx.fillStyle = '#d87b1f';
|
|
ctx.beginPath();
|
|
ctx.moveTo(cx, cy-10);
|
|
ctx.lineTo(cx-9, cy+8);
|
|
ctx.lineTo(cx+9, cy+8);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
} else if (e.type === 'Sentinel'){
|
|
ctx.fillStyle = '#7b52d1';
|
|
poly(cx,cy,12,6,-Math.PI/6);
|
|
} else if (e.type === 'Shielder'){
|
|
ctx.fillStyle = '#2d6bb8';
|
|
ctx.fillRect(cx-11, cy-11, 22, 22);
|
|
ctx.strokeStyle = '#b7d2ff';
|
|
ctx.lineWidth = 3;
|
|
const d = facingDelta(e.facing);
|
|
ctx.beginPath();
|
|
ctx.moveTo(cx + d[0]*12 - d[1]*9, cy + d[1]*12 + d[0]*9);
|
|
ctx.lineTo(cx + d[0]*12 + d[1]*9, cy + d[1]*12 - d[0]*9);
|
|
ctx.stroke();
|
|
} else if (e.type === 'Bomber'){
|
|
ctx.fillStyle = '#7b1f1f';
|
|
ctx.beginPath();
|
|
ctx.arc(cx,cy,11,0,Math.PI*2);
|
|
ctx.fill();
|
|
ctx.strokeStyle = '#ffcc88';
|
|
ctx.lineWidth = 2;
|
|
ctx.beginPath();
|
|
ctx.moveTo(cx+6, cy-10);
|
|
ctx.lineTo(cx+12, cy-16);
|
|
ctx.stroke();
|
|
} else if (e.type === 'Healer'){
|
|
ctx.fillStyle = '#3cb64a';
|
|
ctx.fillRect(cx-3, cy-12, 6, 24);
|
|
ctx.fillRect(cx-12, cy-3, 24, 6);
|
|
} else if (e.type === 'Phaser'){
|
|
ctx.fillStyle = '#2fd4d8';
|
|
ctx.beginPath();
|
|
ctx.moveTo(cx, cy-12);
|
|
ctx.lineTo(cx+12, cy);
|
|
ctx.lineTo(cx, cy+12);
|
|
ctx.lineTo(cx-12, cy);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
} else if (e.type === 'Turret'){
|
|
ctx.fillStyle = '#9a9a9a';
|
|
poly(cx,cy,12,8,Math.PI/8);
|
|
} else if (e.type === 'Charger'){
|
|
ctx.fillStyle = '#d7c02a';
|
|
ctx.beginPath();
|
|
ctx.moveTo(cx, cy-12);
|
|
ctx.lineTo(cx+12, cy);
|
|
ctx.lineTo(cx, cy+12);
|
|
ctx.lineTo(cx-6, cy+6);
|
|
ctx.lineTo(cx-6, cy-6);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
} else if (e.type === 'Siren'){
|
|
ctx.strokeStyle = '#ff7ab6';
|
|
ctx.lineWidth = 2;
|
|
ctx.beginPath(); ctx.arc(cx,cy,6,0,Math.PI*2); ctx.stroke();
|
|
ctx.beginPath(); ctx.arc(cx,cy,11,0,Math.PI*2); ctx.stroke();
|
|
} else if (e.type === 'Mimic'){
|
|
const disguised = !!e.disguised;
|
|
ctx.fillStyle = disguised ? '#6b4a23' : '#8c6a1a';
|
|
ctx.fillRect(cx-12, cy-10, 24, 20);
|
|
ctx.strokeStyle = 'rgba(0,0,0,0.35)';
|
|
ctx.beginPath(); ctx.moveTo(cx-12, cy-2); ctx.lineTo(cx+12, cy-2); ctx.stroke();
|
|
} else if (e.type === 'Leech'){
|
|
ctx.fillStyle = '#4a1b66';
|
|
ctx.beginPath();
|
|
ctx.arc(cx,cy-3,8,0,Math.PI*2);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
ctx.beginPath();
|
|
ctx.moveTo(cx-8, cy);
|
|
ctx.lineTo(cx, cy+14);
|
|
ctx.lineTo(cx+8, cy);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
} else {
|
|
ctx.fillStyle = '#888';
|
|
ctx.fillRect(cx-10, cy-10, 20, 20);
|
|
}
|
|
|
|
ctx.restore();
|
|
}
|
|
}
|
|
|
|
function drawProjectiles(){
|
|
for (const p of (GAME.projectiles||[])){
|
|
if (!p || p.dead) continue;
|
|
if (!visible[p.y] || !visible[p.y][p.x]) continue;
|
|
const cx = p.x*TILE + TILE/2;
|
|
const cy = HUD_H + p.y*TILE + TILE/2;
|
|
ctx.fillStyle = (p.from==='player') ? '#e8e8e8' : '#bb88ff';
|
|
ctx.fillRect(cx-3, cy-3, 6, 6);
|
|
}
|
|
}
|
|
|
|
|
|
function drawParticles(){
|
|
if (!particles.length) return;
|
|
ctx.save();
|
|
for (const p of particles){
|
|
if (!p || (p.life|0) <= 0) continue;
|
|
const a = Math.max(0.05, Math.min(1, (p.life|0) / 22));
|
|
ctx.globalAlpha = a;
|
|
ctx.fillStyle = p.col || '#ffffff';
|
|
ctx.fillRect((p.x|0), (p.y|0), 2, 2);
|
|
}
|
|
ctx.restore();
|
|
}
|
|
|
|
function drawPlayer(){
|
|
if (!GAME.player) return;
|
|
const pos = interpTile(GAME.player);
|
|
const x = pos.x*TILE + TILE/2;
|
|
const y = HUD_H + pos.y*TILE + TILE/2;
|
|
const tNow = nowMs();
|
|
|
|
const host = GAME.player.host;
|
|
const pFlash = !!(GAME.player._flashUntil && tNow < GAME.player._flashUntil);
|
|
const hFlash = !!(host && host._flashUntil && tNow < host._flashUntil);
|
|
|
|
function poly(cx,cy,r,sides,rot){
|
|
ctx.beginPath();
|
|
for (let i=0;i<sides;i++){
|
|
const a = rot + (Math.PI*2)*(i/sides);
|
|
const px = cx + Math.cos(a)*r;
|
|
const py = cy + Math.sin(a)*r;
|
|
if (i===0) ctx.moveTo(px,py); else ctx.lineTo(px,py);
|
|
}
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
}
|
|
|
|
if (GAME.player.ghost || !host){
|
|
ctx.save();
|
|
ctx.globalAlpha = 0.85;
|
|
ctx.fillStyle = pFlash ? 'rgba(255,255,255,1)' : 'rgba(255,255,255,0.75)';
|
|
ctx.beginPath();
|
|
ctx.arc(x,y,12,0,Math.PI*2);
|
|
ctx.fill();
|
|
ctx.globalAlpha = 0.9;
|
|
ctx.fillStyle = 'rgba(10,10,10,0.65)';
|
|
ctx.beginPath(); ctx.arc(x-4,y-2,2,0,Math.PI*2); ctx.fill();
|
|
ctx.beginPath(); ctx.arc(x+4,y-2,2,0,Math.PI*2); ctx.fill();
|
|
ctx.restore();
|
|
return;
|
|
}
|
|
|
|
ctx.save();
|
|
if (hFlash){
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.fillRect(x-12, y-12, 24, 24);
|
|
ctx.restore();
|
|
return;
|
|
}
|
|
|
|
const t = host.type;
|
|
const facing = normFacing(GAME.player.facing);
|
|
const ang = (facing==='up') ? -Math.PI/2 : (facing==='down') ? Math.PI/2 : (facing==='left') ? Math.PI : 0;
|
|
|
|
if (t === 'Brute'){
|
|
ctx.fillStyle = '#ff4a4a';
|
|
ctx.fillRect(x-14, y-14, 28, 28);
|
|
} else if (t === 'Skitterer'){
|
|
ctx.fillStyle = '#ff9b3a';
|
|
ctx.beginPath();
|
|
ctx.moveTo(x, y-10);
|
|
ctx.lineTo(x-9, y+8);
|
|
ctx.lineTo(x+9, y+8);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
} else if (t === 'Sentinel'){
|
|
ctx.fillStyle = '#b08bff';
|
|
poly(x,y,12,6,-Math.PI/6);
|
|
} else if (t === 'Shielder'){
|
|
ctx.fillStyle = '#3b86ff';
|
|
ctx.fillRect(x-11, y-11, 22, 22);
|
|
ctx.strokeStyle = '#e8f0ff';
|
|
ctx.lineWidth = 3;
|
|
const d = facingDelta(facing);
|
|
ctx.beginPath();
|
|
ctx.moveTo(x + d[0]*12 - d[1]*9, y + d[1]*12 + d[0]*9);
|
|
ctx.lineTo(x + d[0]*12 + d[1]*9, y + d[1]*12 - d[0]*9);
|
|
ctx.stroke();
|
|
} else if (t === 'Bomber'){
|
|
ctx.fillStyle = '#a12a2a';
|
|
ctx.beginPath();
|
|
ctx.arc(x,y,11,0,Math.PI*2);
|
|
ctx.fill();
|
|
ctx.strokeStyle = '#ffcc88';
|
|
ctx.lineWidth = 2;
|
|
ctx.beginPath();
|
|
ctx.moveTo(x+6, y-10);
|
|
ctx.lineTo(x+12, y-16);
|
|
ctx.stroke();
|
|
} else if (t === 'Healer'){
|
|
ctx.fillStyle = '#53d463';
|
|
ctx.fillRect(x-3, y-12, 6, 24);
|
|
ctx.fillRect(x-12, y-3, 24, 6);
|
|
} else if (t === 'Phaser'){
|
|
ctx.fillStyle = '#3cf0f2';
|
|
ctx.beginPath();
|
|
ctx.moveTo(x, y-12);
|
|
ctx.lineTo(x+12, y);
|
|
ctx.lineTo(x, y+12);
|
|
ctx.lineTo(x-12, y);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
} else if (t === 'Turret'){
|
|
ctx.fillStyle = '#c5c5c5';
|
|
poly(x,y,12,8,Math.PI/8);
|
|
ctx.strokeStyle = '#2a2a2a';
|
|
ctx.lineWidth = 3;
|
|
const d = facingDelta(facing);
|
|
ctx.beginPath();
|
|
ctx.moveTo(x, y);
|
|
ctx.lineTo(x + d[0]*14, y + d[1]*14);
|
|
ctx.stroke();
|
|
} else if (t === 'Charger'){
|
|
ctx.save();
|
|
ctx.translate(x,y);
|
|
ctx.rotate(ang);
|
|
ctx.fillStyle = '#ffe35a';
|
|
ctx.beginPath();
|
|
ctx.moveTo(12, 0);
|
|
ctx.lineTo(0, -10);
|
|
ctx.lineTo(-6, -6);
|
|
ctx.lineTo(-6, 6);
|
|
ctx.lineTo(0, 10);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
ctx.restore();
|
|
} else if (t === 'Siren'){
|
|
ctx.strokeStyle = '#ff9fd0';
|
|
ctx.lineWidth = 2;
|
|
ctx.beginPath(); ctx.arc(x,y,6,0,Math.PI*2); ctx.stroke();
|
|
ctx.beginPath(); ctx.arc(x,y,11,0,Math.PI*2); ctx.stroke();
|
|
} else if (t === 'Mimic'){
|
|
const disguised = !!host.disguised;
|
|
ctx.fillStyle = disguised ? '#7b5a2b' : '#b08a2a';
|
|
ctx.fillRect(x-12, y-10, 24, 20);
|
|
ctx.strokeStyle = 'rgba(0,0,0,0.35)';
|
|
ctx.beginPath(); ctx.moveTo(x-12, y-2); ctx.lineTo(x+12, y-2); ctx.stroke();
|
|
} else if (t === 'Leech'){
|
|
ctx.fillStyle = '#6a2b8a';
|
|
ctx.beginPath();
|
|
ctx.arc(x,y-3,8,0,Math.PI*2);
|
|
ctx.fill();
|
|
ctx.beginPath();
|
|
ctx.moveTo(x-8, y);
|
|
ctx.lineTo(x, y+14);
|
|
ctx.lineTo(x+8, y);
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
} else {
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.fillRect(x-12, y-12, 24, 24);
|
|
}
|
|
|
|
ctx.restore();
|
|
}
|
|
|
|
function drawTitle(){
|
|
clear();
|
|
drawHUD();
|
|
|
|
// backdrop under HUD
|
|
ctx.fillStyle = '#0b0c10';
|
|
ctx.fillRect(0,HUD_H,CANVAS_W,CANVAS_H-HUD_H);
|
|
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.font = '28px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('Body Snatcher', 24, HUD_H + 52);
|
|
|
|
ctx.font = '14px system-ui, -apple-system, sans-serif';
|
|
let hasSave = false;
|
|
try { hasSave = (typeof localStorage !== 'undefined' && localStorage && localStorage.getItem && !!localStorage.getItem(SAVE_KEY)); } catch (_) { hasSave = false; }
|
|
|
|
const lines = [
|
|
'WASD / Arrow Keys: move one tile',
|
|
'SPACE (ghost): possess (ghost cannot attack)',
|
|
'Q / E: rotate facing',
|
|
'ENTER: start / confirm',
|
|
'ESC: pause',
|
|
'L: Legend / Bestiary',
|
|
'',
|
|
hasSave ? 'Saved run: Y continue, N delete save' : '(No save found)',
|
|
'Press ENTER to start a new run.',
|
|
];
|
|
for (let i=0;i<lines.length;i++) ctx.fillText(lines[i], 24, HUD_H + 92 + i*18);
|
|
|
|
if (showLegend){
|
|
drawLegendPanel();
|
|
}
|
|
}
|
|
|
|
function drawPaused(){
|
|
drawWorld();
|
|
ctx.fillStyle = 'rgba(0,0,0,0.55)';
|
|
ctx.fillRect(0,0,CANVAS_W,CANVAS_H);
|
|
|
|
if (showLegend) drawLegendPanel();
|
|
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.font = '24px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('Paused', 24, 56);
|
|
|
|
ctx.font = '14px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('↑/↓ select ENTER confirm ESC resume L legend', 24, 84);
|
|
|
|
const sel = (GAME._pauseSelection|0) || 0;
|
|
const opts = ['Resume','Save + Quit'];
|
|
for (let i=0;i<opts.length;i++){
|
|
const prefix = (i===sel) ? '> ' : ' ';
|
|
ctx.fillStyle = (i===sel) ? '#ffffff' : '#d5d5d5';
|
|
ctx.fillText(prefix + opts[i], 24, 120 + i*22);
|
|
}
|
|
}
|
|
|
|
function drawLost(){
|
|
drawWorld();
|
|
ctx.fillStyle = 'rgba(0,0,0,0.6)';
|
|
ctx.fillRect(0,0,CANVAS_W,CANVAS_H);
|
|
|
|
const achN = Object.values(GAME.achievements||{}).filter(v=>v===true || (v && v.unlocked)).length;
|
|
|
|
ctx.fillStyle = '#ffdddd';
|
|
ctx.font = '26px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('You dissipated.', 24, 56);
|
|
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.font = '14px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('Floor reached: '+(runStats.floorReached|0)+' Essence: '+(GAME.essence|0), 24, 84);
|
|
ctx.fillText('Turns: '+(runStats.turns|0)+' Kills: '+(runStats.kills|0)+' Achievements: '+achN+'/8', 24, 104);
|
|
ctx.fillText('ENTER: back to title', 24, 132);
|
|
}
|
|
|
|
function drawWon(){
|
|
drawWorld();
|
|
ctx.fillStyle = 'rgba(0,0,0,0.6)';
|
|
ctx.fillRect(0,0,CANVAS_W,CANVAS_H);
|
|
|
|
const achN = Object.values(GAME.achievements||{}).filter(v=>v===true || (v && v.unlocked)).length;
|
|
|
|
ctx.fillStyle = '#ddffdd';
|
|
ctx.font = '26px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('You escaped.', 24, 56);
|
|
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.font = '14px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('Floor reached: '+(runStats.floorReached|0)+' Essence: '+(GAME.essence|0), 24, 84);
|
|
ctx.fillText('Turns: '+(runStats.turns|0)+' Kills: '+(runStats.kills|0)+' Achievements: '+achN+'/8', 24, 104);
|
|
ctx.fillText('ENTER: back to title', 24, 132);
|
|
}
|
|
|
|
function drawShop(){
|
|
drawWorld();
|
|
|
|
ctx.fillStyle = 'rgba(0,0,0,0.72)';
|
|
ctx.fillRect(0,0,CANVAS_W,CANVAS_H);
|
|
|
|
if (showLegend) drawLegendPanel();
|
|
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.font = '26px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('Shop', 24, 56);
|
|
|
|
ctx.font = '14px system-ui, -apple-system, sans-serif';
|
|
ctx.fillText('↑/↓ select ENTER buy/proceed ESC skip L legend', 24, 84);
|
|
|
|
const choices = GAME.choices || GAME.shopChoices || GAME.upgradeChoices || [];
|
|
for (let i=0;i<Math.min(3, choices.length);i++){
|
|
const it = choices[i] || {};
|
|
const sel = (i === (GAME._shopSelection|0));
|
|
const cost = upgradeCost(it);
|
|
const owned = upgradeOwned(it.id);
|
|
const ok = prereqMet(it);
|
|
const prefix = sel ? '> ' : ' ';
|
|
const line = prefix + (it.name||it.id||'Upgrade') + ' ('+cost+')' + (owned?' [owned]':(!ok?' [locked]':''));
|
|
ctx.fillStyle = sel ? '#ffffff' : '#d5d5d5';
|
|
ctx.fillText(line, 24, 120 + i*22);
|
|
ctx.fillStyle = '#a9a9a9';
|
|
if (it.desc) ctx.fillText(' '+it.desc, 24, 138 + i*22);
|
|
}
|
|
|
|
if (GAME._shopBought){
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.fillText('Purchased. Press ENTER to descend.', 24, 210);
|
|
}
|
|
}
|
|
|
|
function drawLegendPanel(){
|
|
const pad=12;
|
|
const x=CANVAS_W-420, y=HUD_H+16;
|
|
const w=400, h=H*TILE-32;
|
|
|
|
ctx.fillStyle = 'rgba(10,10,10,0.92)';
|
|
ctx.fillRect(x,y,w,h);
|
|
ctx.strokeStyle = 'rgba(255,255,255,0.18)';
|
|
ctx.strokeRect(x+0.5,y+0.5,w,h);
|
|
|
|
ctx.fillStyle = '#e8e8e8';
|
|
ctx.font = '12px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
|
|
|
|
const maxLines = Math.floor((h - pad*2) / 16);
|
|
for (let i=0;i<Math.min(maxLines, BESTIARY_LINES.length);i++){
|
|
ctx.fillText(BESTIARY_LINES[i], x+pad, y+pad + 14 + i*16);
|
|
}
|
|
}
|
|
|
|
function drawWorld(){
|
|
clear();
|
|
drawHUD();
|
|
|
|
// screen shake (render-only)
|
|
let sx = 0, sy = 0;
|
|
const t = nowMs();
|
|
if (t < shakeUntil){
|
|
const tt = t * 0.05;
|
|
sx = Math.round(Math.cos(tt) * (shakeMag|0));
|
|
sy = Math.round(Math.sin(tt*1.3) * (shakeMag|0));
|
|
} else {
|
|
shakeMag = 0;
|
|
}
|
|
|
|
ctx.save();
|
|
ctx.translate(sx, sy);
|
|
drawGrid();
|
|
drawProjectiles();
|
|
drawParticles();
|
|
drawEnemies();
|
|
drawPlayer();
|
|
ctx.restore();
|
|
|
|
if (showLegend) drawLegendPanel();
|
|
}
|
|
|
|
function draw(){
|
|
if (!VALID_STATES.includes(GAME.state)) GAME.state = 'title';
|
|
|
|
if (GAME.state === 'title') drawTitle();
|
|
else if (GAME.state === 'paused') drawPaused();
|
|
else if (GAME.state === 'shop') drawShop();
|
|
else if (GAME.state === 'won') drawWon();
|
|
else if (GAME.state === 'lost') drawLost();
|
|
else drawWorld();
|
|
}
|
|
|
|
|
|
// ------------------------------ optional live loops (browser only)
|
|
function startRenderLoop(){
|
|
if (renderRaf) return;
|
|
if (typeof requestAnimationFrame !== 'function') return;
|
|
const loop = () => {
|
|
try { draw(); } catch (_) {}
|
|
try { renderRaf = requestAnimationFrame(loop); } catch (_) { renderRaf = 0; }
|
|
};
|
|
try { renderRaf = requestAnimationFrame(loop); } catch (_) { renderRaf = 0; }
|
|
}
|
|
|
|
function startLiveLoop(){
|
|
if (liveTimer) return;
|
|
if (typeof setInterval !== 'function') return;
|
|
try {
|
|
liveTimer = setInterval(() => {
|
|
if (GAME.state === 'playing' || GAME.state === 'possessed'){
|
|
stepOnce();
|
|
draw();
|
|
}
|
|
}, 1000);
|
|
} catch (_) { liveTimer = 0; }
|
|
}
|
|
|
|
// Do NOT auto-start play; just draw the title + start render/tick loops.
|
|
try { draw(); } catch (_) {}
|
|
try { startRenderLoop(); } catch (_) {}
|
|
try { startLiveLoop(); } catch (_) {}
|
|
|
|
// ------------------------------ real browser key wiring (harness uses GAME.input directly)
|
|
try {
|
|
if (typeof document !== 'undefined' && document && document.addEventListener){
|
|
document.addEventListener('keydown', (e) => {
|
|
const key = e && e.key;
|
|
if (!key) return;
|
|
// Prevent page scroll on arrows/space.
|
|
if (key.startsWith('Arrow') || key === ' ' || key === 'Spacebar') { try { e.preventDefault(); } catch(_){} }
|
|
GAME.input(key === 'Spacebar' ? 'Space' : key);
|
|
});
|
|
}
|
|
if (canvas && canvas.focus) canvas.focus();
|
|
} catch (_) {}
|
|
|
|
// Expose contract.
|
|
if (typeof window !== 'undefined') window.GAME = GAME;
|
|
else if (typeof globalThis !== 'undefined') globalThis.GAME = GAME;
|
|
|
|
})();
|
|
</script>
|
|
</body>
|
|
</html>
|