Files
2026-08-15 19:23:11 +02:00

2016 lines
98 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Body Snatcher</title>
<style>
html,body{margin:0;padding:0;background:#07080d;height:100%;display:flex;align-items:center;justify-content:center;overflow:hidden}
canvas{box-shadow:0 14px 70px rgba(0,0,0,.85),0 0 0 1px #1c2030;border-radius:6px}
</style>
</head>
<body>
<canvas id="game" width="800" height="640"></canvas>
<script>
(function(){
'use strict';
/* ============ constants ============ */
var W=25,H=18,T=32,HUD_H=64; // 25x18 grid of 32px tiles, HUD bar on top
var VIEW_R=5.5; // fog-of-war sight radius (tiles)
var STEP_MS=600; // live loop turn cadence (presentation only)
var MOVE_MS=85; // snappy movement interpolation
var TIMER_STEP=0.6; // ghost timer seconds lost per deterministic tick (STEP_MS*25 = 15s)
var SAVE_KEY='bodysnatcher_save';
/* ============ tiny helpers ============ */
function nowMs(){try{return (window.performance&&performance.now)?performance.now():0;}catch(e){return 0;}}
function clamp(v,a,b){return v<a?a:v>b?b:v;}
function lerp(a,b,t){return a+(b-a)*t;}
function easeOut(t){t=clamp(t,0,1);return 1-(1-t)*(1-t);}
function hash(x,y){var h=(x*374761393+y*668265263)>>>0;h=((h^(h>>>13))*1274126177)>>>0;return ((h^(h>>>16))>>>0)/4294967296;}
function rrect(c,x,y,w,h,r){c.beginPath();c.moveTo(x+r,y);c.lineTo(x+w-r,y);c.quadraticCurveTo(x+w,y,x+w,y+r);c.lineTo(x+w,y+h-r);c.quadraticCurveTo(x+w,y+h,x+w-r,y+h);c.lineTo(x+r,y+h);c.quadraticCurveTo(x,y+h,x,y+h-r);c.lineTo(x,y+r);c.quadraticCurveTo(x,y,x+r,y);c.closePath();}
/* ============ audio (procedural tones, guarded) ============ */
var AC=null;
function initAudio(){
if(AC)return;
try{var Ctor=window.AudioContext||window.webkitAudioContext;if(Ctor)AC=new Ctor();}catch(e){AC=null;}
}
function tone(freq,dur,type,vol,slide){
try{
if(!AC)return;
var t=AC.currentTime||0;
var o=AC.createOscillator(),g=AC.createGain();
o.type=type||'sine';
o.frequency.setValueAtTime(freq,t);
if(slide)o.frequency.exponentialRampToValueAtTime(slide,t+dur);
g.gain.setValueAtTime(vol||0.08,t);
g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
o.connect(g);g.connect(AC.destination);
o.start(t);o.stop(t+dur+0.02);
}catch(e){}
}
function sfx(name){
if(name==='move')tone(340+Math.random()*40,0.06,'triangle',0.035);
else if(name==='bump')tone(90,0.09,'sawtooth',0.05);
else if(name==='confirm'){tone(520,0.09,'square',0.05,780);tone(780,0.12,'sine',0.05,1040);}
else if(name==='ui')tone(500,0.05,'sine',0.04);
else if(name==='hit')tone(170,0.09,'square',0.06,80);
else if(name==='shoot')tone(720,0.07,'square',0.04,240);
else if(name==='possess')tone(220,0.35,'sine',0.08,880);
else if(name==='death')tone(300,0.4,'sawtooth',0.07,60);
else if(name==='pickup')tone(880,0.09,'sine',0.06,1320);
else if(name==='boom')tone(140,0.35,'sawtooth',0.09,40);
}
/* ============ data: the 12 enemy types (dual system: enemy AI + possessed kit) ============ */
var BESTIARY=[
{n:'Brute',c:'#e0483c',hp:8,dmg:3,edmg:2,spd:2,ess:3,ai:'Slow chase with pathfinding; heavy 2-dmg melee when adjacent.',kit:'HP 8 / dmg 3 / slow. A wrecking ball.'},
{n:'Skitterer',c:'#f08c2a',hp:2,dmg:1,edmg:1,spd:2,ess:1,ai:'Loose swarm; drifts to other Skitterers and flanks you. Weak 1-dmg bites.',kit:'HP 2 / fast / rapid 1-dmg hits.'},
{n:'Sentinel',c:'#a86ce8',hp:4,dmg:0,edmg:1,spd:3,ranged:true,ess:3,ai:'Keeps its distance; 3-shot burst then overheats 3 turns - a free window to close in.',kit:'HP 4 / shoot facing dir / 3-shot burst then overheat. No melee.'},
{n:'Shielder',c:'#4f8fe8',hp:5,dmg:2,edmg:2,spd:2,ess:4,ai:'Slow chase; frontal tower shield blocks all frontal damage. Flank it.',kit:'HP 5 / frontal shield / rotate with Q + E.'},
{n:'Bomber',c:'#b23a2e',hp:3,dmg:3,edmg:3,spd:2,ess:2,ai:'Chases when aggroed; explodes 3x3 (3 dmg) on contact or death. Hurts only you.',kit:'HP 3 / SPACE detonates 3x3 for 4 dmg, ejects you.'},
{n:'Healer',c:'#4fc06a',hp:3,dmg:1,edmg:1,spd:2,ess:5,ai:'Flees from you; heals nearby enemies +1 per turn within 3 tiles. Kill it first.',kit:'HP 3 / SPACE heal pulse: +2 self, +1 allies in 3 tiles.'},
{n:'Phaser',c:'#3ee0e0',hp:4,dmg:2,edmg:2,spd:3,ess:4,ai:'Teleports toward you every 3 turns in line of sight, strikes, fades.',kit:'HP 4 / SPACE blink 5 tiles through walls / 2-turn cooldown.'},
{n:'Turret',c:'#9aa3b0',hp:4,dmg:2,edmg:2,spd:0,ess:5,ai:'Stationary; 360-degree 3-shot burst then overheats 3 turns. Rush it while it vents.',kit:'HP 4 / rooted / SPACE fires facing dir, Q + E rotate.'},
{n:'Charger',c:'#f2d23c',hp:5,dmg:3,edmg:3,spd:2,ess:4,ai:'Telegraphs 1 turn, then charges in a straight line. 3 dmg; walls stun it.',kit:'HP 5 / SPACE dash 4 tiles, 2 dmg per enemy in path.'},
{n:'Siren',c:'#f07ac8',hp:3,dmg:1,edmg:1,spd:3,ess:3,ai:'Slow drift; pull field drags you 1 tile per turn within 5 tiles. Weak melee.',kit:'HP 3 / SPACE pulls all enemies within 4 tiles toward you.'},
{n:'Mimic',c:'#c8a23c',hp:4,dmg:2,edmg:2,spd:2,ess:4,ai:'Disguised as a chest; reveals a fanged maw and bursts (2 dmg cross) when adjacent.',kit:'HP 4 / no aggro while disguised / SPACE surprise burst.'},
{n:'Leech',c:'#8a4fd0',hp:4,dmg:1,edmg:1,spd:2,ess:4,ai:'Slow chase; each hit drains 1 HP from you and heals itself +1.',kit:'HP 4 / your hits deal 1 dmg and heal you +1.'}
];
var HINTS={ // contextual SPACE hints while possessed
Sentinel:'SPACE: shoot facing dir (3-shot burst, then overheat)',
Turret:'SPACE: fire facing dir / Q E rotate - rooted',
Shielder:'SPACE: bash - your shield blocks your facing (Q E rotate)',
Bomber:'SPACE: detonate 3x3 (4 dmg) - you are ejected!',
Healer:'SPACE: heal pulse +2 HP',
Phaser:'SPACE: blink 5 tiles through walls (2-turn cd)',
Charger:'SPACE: dash 4 tiles, 2 dmg per enemy hit',
Siren:'SPACE: pull all enemies within 4 tiles closer',
Mimic:'SPACE: surprise burst - disguised: enemies ignore you',
Leech:'SPACE: drain strike (1 dmg, heals you +1)'};
/* ============ state ============ */
var S={
state:'title', floor:1, essence:0, turn:0,
grid:[], explored:[], enemies:[], projectiles:[], particles:[],
upgrades:{ghost:0,body:0,meta:0}, achievements:{}, log:[],
legend:false, pausedFrom:null, shake:0, ghostTintPulse:0,
runTypes:{}, hostHurt:false, toastUntil:0, toastTxt:'',
spawnX:2, spawnY:2, retained:null,
shopChoices:null, shopSel:0, shopAfterExit:false,
ghostPhase:0, phaseCd:0, ghostDashCd:0, contSeen:false,
player:{x:2,y:2,fromX:2,fromY:2,toX:2,toY:2,renderX:2,renderY:2,moveStart:-9999,moveCooldown:0,
ghost:true,timer:15,host:null,facing:'down',possessing:0,moveCd:0}
};
function setState(v){S.state=v;}
function logMsg(m){S.log.push(m);if(S.log.length>40)S.log.shift();}
/* ============ achievements (all 8, localStorage-tracked) ============ */
var ACHV=[
{id:'possess1',n:'First Possession',d:'Possess your first enemy'},
{id:'hopper',n:'Body Hopper',d:'Possess 5 different enemy types in one run'},
{id:'pacifist',n:'Pacifist Ghost',d:'Reach floor 3 without taking host damage'},
{id:'hoarder',n:'Essence Hoarder',d:'Accumulate 30 essence'},
{id:'diver',n:'Deep Diver',d:'Reach floor 7'},
{id:'escape',n:'Escape Artist',d:'Win - escape through the floor 10 exit'},
{id:'bomber',n:'Bomberman',d:'Kill 3+ enemies with one detonation'},
{id:'dual',n:'Dual Wield',d:'Unlock Body Tree T3 at the shrine'}
];
var ACH_KEY='bodysnatcher_achv';
function achCount(){var n=0,k;for(k in S.achievements)if(S.achievements[k])n++;return n;}
function ach(id){
if(S.achievements[id])return;
var i,d=null;for(i=0;i<ACHV.length;i++)if(ACHV[i].id===id)d=ACHV[i];
if(!d)return;
S.achievements[id]=true;
S.toastUntil=nowMs()+3400;S.toastTxt=d.n;
logMsg('Achievement: '+d.n+' - '+d.d);sfx('pickup');
try{window.localStorage.setItem(ACH_KEY,JSON.stringify(S.achievements));}catch(e){}
}
try{var _achRaw=window.localStorage?window.localStorage.getItem(ACH_KEY):null;
if(_achRaw){var _ach=JSON.parse(_achRaw);if(_ach&&typeof _ach==='object')S.achievements=_ach;}}catch(e){}
/* ============ dungeon: random walk + 5-8 carved rooms joined by L corridors ============ */
function ri(n){return (Math.random()*n)|0;}
function enemyPool(f){
var base=['Brute','Skitterer','Sentinel'];
if(f<=3)return base;
if(f<=6)return base.concat(['Shielder','Bomber','Charger']);
if(f<=9)return base.concat(['Shielder','Bomber','Charger','Healer','Phaser','Siren','Turret']);
return base.concat(['Shielder','Bomber','Charger','Healer','Phaser','Siren','Turret','Mimic','Leech']);
}
function buildDungeon(floorN){
var f=floorN||S.floor||1,y,x,i;
var g=[];for(y=0;y<H;y++){g.push([]);for(x=0;x<W;x++)g[y].push(1);}
function carve(cx,cy,w,h){for(var j=cy;j<cy+h;j++)for(var k=cx;k<cx+w;k++)if(g[j]&&g[j][k]!==undefined)g[j][k]=0;}
var nRooms=5+ri(4),rooms=[]; // 5-8 rooms of 4x4 to 8x6
for(i=0;i<nRooms;i++){
var rw=4+ri(5),rh=4+ri(3),rx=1+ri(W-rw-2),ry2=1+ri(H-rh-2),tryN=0,ok;
do{ // nudge until it clears existing rooms (best effort)
ok=true;
for(var r=0;r<rooms.length;r++)if(rx<rooms[r].x+rooms[r].w+1&&rx+rw+1>rooms[r].x&&ry2<rooms[r].y+rooms[r].h+1&&ry2+rh+1>rooms[r].y){ok=false;break;}
if(ok)break;
rw=4+ri(5);rh=4+ri(3);rx=1+ri(W-rw-2);ry2=1+ri(H-rh-2);tryN++;
}while(tryN<12);
rooms.push({x:rx,y:ry2,w:rw,h:rh,cx:rx+(rw>>1),cy:ry2+(rh>>1)});
carve(rx,ry2,rw,rh);
}
for(i=1;i<rooms.length;i++){ // 1-tile L corridors, never diagonal
var a=rooms[i-1],b=rooms[i],ax=a.cx,ay=a.cy;
if(ri(2)){carve(Math.min(ax,b.cx),ay,Math.abs(b.cx-ax)+1,1);carve(b.cx,Math.min(ay,b.cy),1,Math.abs(b.cy-ay)+1);}
else{carve(ax,Math.min(ay,b.cy),1,Math.abs(b.cy-ay)+1);carve(Math.min(ax,b.cx),b.cy,Math.abs(b.cx-ax)+1,1);}
}
for(i=0;i<2;i++){ // bonus random-walk tunnels
var wx=rooms[ri(rooms.length)].cx,wy=rooms[ri(rooms.length)].cy;
for(var s=0;s<8;s++){carve(wx,wy,1,1);if(ri(2))wx=clamp(wx+(ri(2)?1:-1),1,W-2);else wy=clamp(wy+(ri(2)?1:-1),1,H-2);}
carve(wx,wy,1,1);
}
var sp=rooms[0],best=null,bd=-1; // exit in the FARTHEST room from spawn
for(i=1;i<rooms.length;i++){
var dd=Math.abs(rooms[i].cx-sp.cx)+Math.abs(rooms[i].cy-sp.cy);
if(dd>bd){bd=dd;best=rooms[i];}
}
if(!best)best=rooms[rooms.length-1];
S.spawnX=sp.cx;S.spawnY=sp.cy;g[best.cy][best.cx]=3;
function randSpot(exclude){
for(var t=0;t<80;t++){
var rr=rooms[ri(rooms.length)],tx=rr.x+ri(rr.w),ty=rr.y+ri(rr.h);
if(g[ty][tx]!==0||exclude(tx,ty))continue;
return{x:tx,y:ty};
}
return null;
}
var nChest=1+ri(2); // 1-2 treasure chests
for(i=0;i<nChest;i++){var c=randSpot(function(x,y){return Math.abs(x-S.spawnX)+Math.abs(y-S.spawnY)<3;});if(c)g[c.y][c.x]=5;}
if(f===3||f===5||f===7||f===9){ // shop pad on floors 3/5/7/9
var pd=randSpot(function(x,y){return (x===best.cx&&y===best.cy)||Math.abs(x-S.spawnX)+Math.abs(y-S.spawnY)<3;});
if(pd)g[pd.y][pd.x]=4;
}
S.grid=g;
S.explored=[];for(y=0;y<H;y++){S.explored.push([]);for(x=0;x<W;x++)S.explored[y].push(false);}
S.enemies=[];S.projectiles=[];S.particles=[];
var pool=enemyPool(f),count=4+f+(f>=10?3:0); // floor N = 4+N enemies; floor 10 packs denser
for(i=0;i<count;i++){
var spot=null;
for(var t2=0;t2<120&&!spot;t2++){
var rr2=rooms[ri(rooms.length)],ex2=rr2.x+ri(rr2.w),ey2=rr2.y+ri(rr2.h);
if(g[ey2][ex2]!==0)continue;
if(Math.abs(ex2-S.spawnX)+Math.abs(ey2-S.spawnY)<5)continue; // spawn safety: 5 clear tiles
if(occupied(ex2,ey2))continue;
spot={x:ex2,y:ey2};
}
if(spot)spawn(pool[ri(pool.length)],spot.x,spot.y);
}
}
function reveal(){
var p=S.player,rr=VIEW_R*VIEW_R;
for(var y=0;y<H;y++)for(var x=0;x<W;x++){
var dx=x-p.x,dy=y-p.y;
if(dx*dx+dy*dy<=rr)S.explored[y][x]=true;
}
}
function placeGhostAtSpawn(){
var p=S.player,sx=S.spawnX||2,sy=S.spawnY||2;
p.x=sx;p.y=sy;p.fromX=sx;p.fromY=sy;p.toX=sx;p.toY=sy;p.renderX=sx;p.renderY=sy;
p.ghost=true;p.host=null;p.facing='down';p.moveStart=-9999;p.moveCooldown=0;p.moveCd=0;
reveal();
}
/* ============ run control ============ */
function ghostTime(){return S.upgrades.ghost>=1?20:15;} // Ghost T1: 15s -> 20s
function startRun(floorN){
S.floor=floorN||1;S.turn=0;S.legend=false;
buildDungeon(S.floor);
S.player.timer=ghostTime();
placeGhostAtSpawn();
setState('playing');
logMsg('Floor '+S.floor+': you drift into the dungeon.');
}
function newRun(){S.essence=0;S.upgrades={ghost:0,body:0,meta:0};S.retained=null;S.runTypes={};S.hostHurt=false;startRun(1);sfx('confirm');}
function setFloor(n){startRun(Math.max(1,Math.min(10,n|0)));logMsg('Debug jump to floor '+S.floor);}
function save(){
try{
var p=S.player,hostIdx=p.host?S.enemies.indexOf(p.host):-1;
window.localStorage.setItem(SAVE_KEY,JSON.stringify({
floor:S.floor,essence:S.essence,upgrades:S.upgrades,turn:S.turn,retained:S.retained||null,
player:{x:p.x,y:p.y,ghost:p.ghost,timer:p.timer,hostIdx:hostIdx,facing:p.facing},
enemies:S.enemies.map(function(e){return{type:e.type,x:e.x,y:e.y,hp:e.hp,maxHp:e.maxHp,aggro:!!e.aggro,facing:e.facing,stun:e.stun||0,lockout:e.lockout||0};}),
grid:S.grid,explored:S.explored
}));
}catch(e){}
}
function load(){
try{
var raw=window.localStorage?window.localStorage.getItem(SAVE_KEY):null;
if(!raw)return false;
var d=JSON.parse(raw);
S.floor=d.floor||1;S.essence=d.essence||0;S.upgrades=d.upgrades||{ghost:0,body:0,meta:0};S.turn=d.turn||0;S.retained=d.retained||null;
S.grid=Array.isArray(d.grid)&&d.grid.length===H?d.grid:null;
if(!S.grid)buildDungeon();else{
S.explored=[];for(var y=0;y<H;y++){S.explored.push([]);for(var x=0;x<W;x++)S.explored[y].push(!!(d.explored&&d.explored[y]&&d.explored[y][x]));}
S.enemies=[];S.projectiles=[];S.particles=[];
var list=d.enemies||[],i;
for(i=0;i<list.length;i++){
var s=list[i];if(!s||!s.type)continue;
var e=spawn(s.type,s.x,s.y);
if(s.maxHp)e.maxHp=s.maxHp;if(typeof s.hp==='number')e.hp=s.hp;
e.aggro=!!s.aggro;if(s.facing)e.facing=s.facing;e.stun=s.stun||0;e.lockout=s.lockout||0;
}
}
var p=S.player,dv=d.player||{};
p.x=dv.x||2;p.y=dv.y||2;p.fromX=p.x;p.fromY=p.y;p.toX=p.x;p.toY=p.y;
p.facing=dv.facing||'down';p.timer=typeof dv.timer==='number'?dv.timer:15;
p.moveStart=-9999;p.moveCooldown=0;p.moveCd=0;
var hi=typeof dv.hostIdx==='number'?dv.hostIdx:-1;
if(dv.ghost===false&&hi>=0&&S.enemies[hi]){p.host=S.enemies[hi];p.ghost=false;setState('possessed');}
else{p.ghost=true;p.host=null;setState('playing');}
S.legend=false;reveal();logMsg('Run restored.');
return true;
}catch(e){return false;}
}
function hasSave(){try{return !!(window.localStorage&&window.localStorage.getItem(SAVE_KEY));}catch(e){return false;}}
/* ============ shop: between floors, 3 random tiered upgrades ============ */
var UPGRADES=[
{tree:'ghost',tier:1,cost:5,short:'GHOST T1',name:'Longer Haunt',desc:'Ghost countdown 15s -> 20s before you fade away.',accent:'#9fd8ff'},
{tree:'ghost',tier:2,cost:8,short:'GHOST T2',name:'Grasping Reach',desc:'Possess enemies from 2 tiles away, not just adjacent.',accent:'#9fd8ff'},
{tree:'ghost',tier:3,cost:12,short:'GHOST T3',name:'Wall Phase',desc:'Q as a ghost: slip through walls for 1s. 5s cooldown.',accent:'#9fd8ff'},
{tree:'ghost',tier:4,cost:15,short:'GHOST T4',name:'Ghost Dash',desc:'E as a ghost: dash 3 tiles instantly. 3s cooldown.',accent:'#9fd8ff'},
{tree:'body',tier:1,cost:10,short:'BODY T1',name:'Retain',desc:'Keep a gift of your last host: its power rides along.',accent:'#ffc9a0'},
{tree:'body',tier:2,cost:12,short:'BODY T2',name:'Overclock',desc:'Fresh possessions hit 50% harder for 5 turns.',accent:'#ffc9a0'},
{tree:'body',tier:3,cost:18,short:'BODY T3',name:'Dual-wield',desc:'Carry two powers: +1 damage on every hit.',accent:'#ffc9a0'},
{tree:'meta',tier:1,cost:8,short:'META T1',name:'Borrowed Flesh',desc:'Start every floor already wearing a random body.',accent:'#c0f0c8'},
{tree:'meta',tier:2,cost:10,short:'META T2',name:'Farsight',desc:'Sense enemy types through the fog of war.',accent:'#c0f0c8'},
{tree:'meta',tier:3,cost:6,short:'META T3',name:'Haggler',desc:'All shrine prices 30% off, forever.',accent:'#c0f0c8'}
];
function shopPrice(u){return S.upgrades.meta>=3?Math.max(1,Math.round(u.cost*0.7)):u.cost;} // Meta T3 discount
function availUpgrades(){var a=[],i;for(i=0;i<UPGRADES.length;i++)if(S.upgrades[UPGRADES[i].tree]===UPGRADES[i].tier-1)a.push(UPGRADES[i]);return a;}
function openShop(afterExit){
var pool=availUpgrades(),i,j;
for(i=pool.length-1;i>0;i--){j=ri(i+1);var tmp=pool[i];pool[i]=pool[j];pool[j]=tmp;}
S.shopChoices=pool.slice(0,3);S.shopSel=0;S.shopAfterExit=!!afterExit;
setState('shop');sfx('ui');
return true;
}
function buy(i){
if(S.state!=='shop'||!S.shopChoices)return false;
var c=S.shopChoices[i|0];
if(!c)return false;
var price=shopPrice(c);
if(S.essence<price){logMsg('Not enough essence ('+price+' needed).');sfx('bump');return false;}
S.essence-=price;S.upgrades[c.tree]=c.tier;
if(c.tree==='body'&&c.tier===3)ach('dual'); // Dual Wield achievement
logMsg('Bought '+c.short+' '+c.name+' for '+price+' essence.');sfx('confirm');
S.shopChoices=null;
if(S.shopAfterExit)descend();else{setState('playing');save();}
return true;
}
function skipShop(){
if(S.state!=='shop')return false;
S.shopChoices=null;
if(S.shopAfterExit)descend();else setState('playing');
sfx('ui');return true;
}
function startInBody(){ // Meta T1: arrive wearing a random body
var pool=enemyPool(S.floor),p=S.player,i;
for(i=0;i<4;i++){
var nx=S.spawnX+D4[i][0],ny=S.spawnY+D4[i][1];
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1)continue;
var e=spawn(pool[ri(pool.length)],nx,ny);
p.host=e;p.ghost=false;e.aggro=false;p.x=e.x;p.y=e.y;
setState('possessed');
logMsg('You pour into a fresh '+e.type+' at the threshold.');
burst(e.x,e.y,'120,240,255',10);sfx('possess');
return;
}
}
function descend(){
S.floor=Math.min(10,S.floor+1);
buildDungeon(S.floor);
S.player.timer=ghostTime();
placeGhostAtSpawn();
setState('playing');
if(S.upgrades.meta>=1)startInBody();
logMsg('Floor '+S.floor+': the dark deepens.');
save();
}
/* ============ enemies (data-driven; AI arrives in later phases) ============ */
function spawn(type,tx,ty){
var t=String(type||'').toLowerCase(),def=null;
for(var i=0;i<BESTIARY.length;i++)if(BESTIARY[i].n.toLowerCase()===t){def=BESTIARY[i];break;}
if(!def)def=BESTIARY[0];
var ex=clamp(tx|0,0,W-1),ey=clamp(ty|0,0,H-1);
var e={type:def.n,x:ex,y:ey,
hp:def.hp,maxHp:def.hp,damage:def.dmg,edmg:def.edmg||def.dmg,speed:def.spd,essenceVal:def.ess,
ranged:!!def.ranged,
facing:'down',aggro:false,stun:0,hitFlash:0,lockout:0,cd:0,shots:0,overheatLeft:0,revealed:false,telegraph:false,
fromX:ex,fromY:ey,moveStart:0,bobSeed:Math.random()*6.28};
S.enemies.push(e);
return e;
}
/* ============ combat + enemy AI (calm pacing: everyone starts docile) ============ */
var D4=[[1,0],[-1,0],[0,1],[0,-1]];
var FACING={up:[0,-1],down:[0,1],left:[-1,0],right:[1,0]};
var AGGRO_R=6;
function occupied(x,y){
for(var i=0;i<S.enemies.length;i++){var e=S.enemies[i];if(e!==S.player.host&&e.x===x&&e.y===y)return true;}
return false;
}
function los(x0,y0,x1,y1){ // Bresenham; enemies never aggro through walls
var dx=Math.abs(x1-x0),dy=Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,err=dx-dy;
while(!(x0===x1&&y0===y1)){
var e2=2*err;
if(e2>-dy){err-=dy;x0+=sx;}
if(e2<dx){err+=dx;y0+=sy;}
if(x0===x1&&y0===y1)break;
if(S.grid[y0]&&S.grid[y0][x0]===1)return false;
}
return true;
}
function pathStep(sx,sy,tx,ty){ // BFS: first step of the shortest walkable path
if(sx===tx&&sy===ty)return null;
var prev=[],q=[],x,y,i;
for(y=0;y<H;y++)prev.push([]);
prev[sy][sx]={x:sx,y:sy};q.push([sx,sy]);
while(q.length){
var c=q.shift();
if(c[0]===tx&&c[1]===ty)break;
for(i=0;i<4;i++){
var nx=c[0]+D4[i][0],ny=c[1]+D4[i][1];
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1||prev[ny][nx])continue;
prev[ny][nx]={x:c[0],y:c[1]};q.push([nx,ny]);
}
}
if(!prev[ty]||!prev[ty][tx])return null;
var cx=tx,cy=ty;
while(prev[cy][cx]&&(prev[cy][cx].x!==sx||prev[cy][cx].y!==sy)){cx=prev[cy][cx].x;cy=prev[cy][cx].y;}
return prev[cy][cx]?{x:cx,y:cy}:null;
}
function distP(e){var p=S.player;return Math.abs(e.x-p.x)+Math.abs(e.y-p.y);}
function faceToward(e,p){
var dx=p.x-e.x,dy=p.y-e.y;
if(Math.abs(dx)>Math.abs(dy))return dx>0?'right':'left';
return dy>0?'down':'up';
}
function moveEnemy(e,nx,ny){
e.facing=nx>e.x?'right':nx<e.x?'left':ny>e.y?'down':'up';
e.fromX=e.x;e.fromY=e.y;e.x=nx;e.y=ny;e.moveStart=nowMs();
}
function burst(tx,ty,color,n){
for(var i=0;i<n;i++)S.particles.push({x:tx*T+16+(Math.random()*14-7),y:ty*T+16+HUD_H+(Math.random()*14-7),
vx:(Math.random()-0.5)*1.8,vy:(Math.random()-0.8)*1.8,life:0.5,max:0.5,c:color,r:2.5});
}
function dmgNumber(tx,ty,amt){
S.particles.push({x:tx*T+16,y:ty*T+HUD_H-4,vx:0,vy:-0.9,life:0.8,max:0.8,c:'255,150,150',r:0,txt:String(amt)});
}
function damageEnemy(e,amt){ // used by YOUR host's attacks only; enemies never hurt each other
e.hp-=amt;e.hitFlash=1;
burst(e.x,e.y,'255,215,150',5);dmgNumber(e.x,e.y,amt);sfx('hit');
if(e.hp<=0)killEnemy(e);
}
function killEnemy(e){
var i=S.enemies.indexOf(e);if(i>=0)S.enemies.splice(i,1);
S.essence+=(e.essenceVal||1);
burst(e.x,e.y,'190,150,255',14);S.shake=Math.max(S.shake,3);sfx('death');
logMsg(e.type+' destroyed. +'+(e.essenceVal||1)+' essence');
if(e.type==='Bomber'&&!e.detonated&&S.player.host!==e){ // volatile shell pops: 3 dmg to the PLAYER only
e.detonated=true;
S.shake=Math.max(S.shake,6);burst(e.x,e.y,'255,140,60',18);sfx('boom');
var pl=S.player;
if(pl.host&&Math.abs(pl.x-e.x)<=1&&Math.abs(pl.y-e.y)<=1)damageHost(3,e.x,e.y);
}
if(S.player.host===e)ejectFromHost();
}
function shieldBlocks(e,adx,ady){ // frontal tower shield: blocks damage arriving along its facing
if(!e||e.type!=='Shielder')return false;
var f=FACING[e.facing]||FACING.down;
return f[0]===adx&&f[1]===ady;
}
function damageHost(amt,fx,fy){ // enemy attacks can only ever hit the player's body
var h=S.player.host;if(!h)return;
if(fx!=null&&shieldBlocks(h,h.x-fx,h.y-fy)){burst(h.x,h.y,'140,200,255',4);sfx('bump');logMsg('Your shield blocks the blow!');return;}
h.hp-=amt;h.hitFlash=1;S.shake=Math.max(S.shake,2.5);
S.hostHurt=true; // Pacifist Ghost: run purity broken
dmgNumber(h.x,h.y,amt);sfx('hit');
if(h.hp<=0)killEnemy(h);
}
function detonate(e,edmg,pdmg){ // Bomber blast: edmg hits enemies (ONLY when you pressed the button), pdmg hits the player
e.detonated=true;
S.shake=Math.max(S.shake,7);burst(e.x,e.y,'255,170,80',22);burst(e.x,e.y,'255,90,40',14);sfx('boom');
var i,p=S.player,kills=0;
if(edmg>0)for(i=0;i<S.enemies.length;i++){
var v=S.enemies[i];
if(v!==e&&Math.abs(v.x-e.x)<=1&&Math.abs(v.y-e.y)<=1){damageEnemy(v,edmg);if(v.hp<=0)kills++;}
}
if(kills>=3)ach('bomber'); // Bomberman: triple detonation
if(pdmg>0&&p.host&&Math.abs(p.x-e.x)<=1&&Math.abs(p.y-e.y)<=1)damageHost(pdmg,e.x,e.y);
killEnemy(e);
logMsg('A Bomber detonates!');
}
function ejectFromHost(){
var p=S.player,h=p.host;
if(h)S.retained=h.type; // Body T1: a gift of the fallen host rides along
p.ghost=true;p.host=null;p.timer=ghostTime(); // a host DEATH fully resets the countdown
setState('playing');
burst(p.x,p.y,'150,240,255',12);sfx('possess');
logMsg('Your body died. You spill out as a ghost.');
save();
}
function tryPossess(){
var p=S.player,i,e,range=S.upgrades.ghost>=2?2:1; // Ghost T2: reach out 2 tiles
for(i=0;i<S.enemies.length;i++){
e=S.enemies[i];
if((e.lockout||0)>0)continue;
if(Math.abs(e.x-p.x)+Math.abs(e.y-p.y)<=range){
p.host=e;p.ghost=false;
p.x=e.x;p.y=e.y;p.fromX=e.x;p.fromY=e.y;p.toX=e.x;p.toY=e.y;p.moveStart=-9999;p.moveCd=0;
e.aggro=false;
S.runTypes[e.type]=true; // Body Hopper: distinct types this run
ach('possess1');
var _rk,_rc=0;for(_rk in S.runTypes)_rc++;
if(_rc>=5)ach('hopper');
setState('possessed');
if(S.upgrades.body>=2){e.ov=5;logMsg('Overclock: the body surges for 5 turns!');} // Body T2
if(S.upgrades.body>=1&&S.retained==='Shielder'){e.maxHp+=1;e.hp+=1;} // Body T1 gift
burst(e.x,e.y,'120,240,255',10);S.shake=Math.max(S.shake,2);sfx('possess');
logMsg('You wear the '+e.type+'.');
save();
return true;
}
}
sfx('bump');return false;
}
function abandonHost(){
var h=S.player.host;if(!h)return;
S.retained=h.type; // Body T1: keep one ability from the host you leave
h.lockout=2;h.stun=2;h.aggro=false; // survives, dazed, briefly locked out
S.player.ghost=true;S.player.host=null;
setState('playing');
burst(h.x,h.y,'150,240,255',10);sfx('possess');
logMsg('Abandoned the '+h.type+'. It stands dazed.');
save();
}
function fireProj(x,y,dx,dy,own,dmg){
if(x<0||y<0||x>=W||y>=H||!S.grid[y]||S.grid[y][x]===1)return;
S.projectiles.push({x:x,y:y,dx:dx,dy:dy,dmg:dmg||1,life:12,own:!!own});
sfx('shoot');
}
function pullEnemies(){ // Siren kit: drag every enemy within 4 tiles one tile toward you
var p=S.player,i,nx,ny,pulled=0;
for(i=0;i<S.enemies.length;i++){
var e=S.enemies[i];if(e===p.host)continue;
var d=Math.abs(e.x-p.x)+Math.abs(e.y-p.y);
if(d<1||d>4)continue;
var dx=p.x-e.x,dy=p.y-e.y;
if(Math.abs(dx)>Math.abs(dy)){nx=e.x+(dx>0?1:-1);ny=e.y;}
else{ny=e.y+(dy>0?1:-1);nx=e.x;}
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1||occupied(nx,ny)||(nx===p.x&&ny===p.y))continue;
moveEnemy(e,nx,ny);pulled++;
}
burst(p.x,p.y,'246,150,214',12);sfx('possess');S.shake=Math.max(S.shake,1.5);
if(pulled)logMsg(pulled+' enem'+(pulled===1?'y':'ies')+' dragged toward you.');
}
function crossBurst(x,y,dmg){ // Mimic kit: your AoE cross
var p=S.player,i,j;
for(j=0;j<4;j++){var dx=D4[j][0],dy=D4[j][1];
for(i=S.enemies.length-1;i>=0;i--){var e=S.enemies[i];
if(e!==p.host&&e.x===x+dx&&e.y===y+dy)damageEnemy(e,dmg);}
}
}
function blinkPlayer(h,d){ // Phaser kit: blink 5 tiles through walls
var p=S.player,tx=h.x,ty=h.y,i;
for(i=0;i<5;i++){var ax=tx+d[0],ay=ty+d[1];if(ax<0||ay<0||ax>=W||ay>=H)break;tx=ax;ty=ay;}
while((tx!==h.x||ty!==h.y)&&(S.grid[ty][tx]===1||occupied(tx,ty))){tx-=d[0];ty-=d[1];}
if(tx===h.x&&ty===h.y)return false;
burst(h.x,h.y,'120,250,255',8);
h.fromX=h.x;h.fromY=h.y;h.x=tx;h.y=ty;h.moveStart=nowMs();
p.x=tx;p.y=ty;p.fromX=tx;p.fromY=ty;p.toX=tx;p.toY=ty;p.moveStart=nowMs();
burst(tx,ty,'120,250,255',8);sfx('possess');reveal();
return true;
}
function dash(e,d,maxN,dmg){ // Charger kit: dash in a line, 2 dmg per enemy hit
var p=S.player,steps=0,i;
while(steps<maxN){
var nx=e.x+d[0],ny=e.y+d[1];
if(nx<0||ny<0||nx>=W||ny>=H||!S.grid[ny]||S.grid[ny][nx]===1)break;
var hit=null;
for(i=0;i<S.enemies.length;i++){var v=S.enemies[i];if(v!==e&&v.x===nx&&v.y===ny){hit=v;break;}}
if(hit){if(dmg)damageEnemy(hit,dmg);break;}
moveEnemy(e,nx,ny);steps++;burst(nx,ny,'250,230,120',2);
}
if(steps>0){sfx('shoot');S.shake=Math.max(S.shake,2.5);}
if(p.host===e){p.x=e.x;p.y=e.y;p.fromX=e.x;p.fromY=e.y;p.toX=e.x;p.toY=e.y;p.moveStart=nowMs();reveal();}
}
function hostAction(){
var p=S.player,h=p.host;if(!h)return;
var d=FACING[p.facing]||FACING.down,i,e;
h.facing=p.facing;
if(h.type==='Sentinel'||h.type==='Turret'){ // burst-fire, then a forced overheat window
if((h.overheatLeft||0)>0||(h.shots||0)>=3){sfx('bump');return;}
var pd=h.type==='Turret'?2:1;
if((h.ov||0)>0)pd=Math.ceil(pd*1.5); // Body T2 overclock
if(S.upgrades.body>=3)pd+=1; // Body T3 dual-wield
fireProj(h.x+d[0],h.y+d[1],d[0],d[1],true,pd);
burst(h.x+d[0],h.y+d[1],h.type==='Turret'?'220,230,180':'190,140,255',3);
h.shots=(h.shots||0)+1;
if(h.shots>=3){h.overheatLeft=3;h.shots=0;logMsg('The '+h.type+' overheats!');}
return;
}
if(h.type==='Bomber'){detonate(h,4,0);return;} // your detonation: 4-dmg AoE, ejects you
if(h.type==='Healer'){ // AoE heal pulse
h.hp=Math.min(h.maxHp,h.hp+2);
burst(h.x,h.y,'120,255,160',10);sfx('pickup');dmgNumber(h.x,h.y,'+2');
logMsg('Healing pulse washes over your body.');return;
}
if(h.type==='Phaser'){ // blink 5 tiles through walls, 2-turn cooldown
if((h.cd||0)>0){sfx('bump');return;}
if(blinkPlayer(h,d))h.cd=2;
return;
}
if(h.type==='Charger'){dash(h,d,4,2);return;}
if(h.type==='Siren'){pullEnemies();return;}
if(h.type==='Mimic'){ // surprise burst from the disguise
h.revealed=true;S.shake=Math.max(S.shake,3);sfx('boom');
crossBurst(h.x,h.y,2);burst(h.x,h.y,'255,200,90',12);
logMsg('Surprise! The maw snaps open.');return;
}
var tx=h.x+d[0],ty=h.y+d[1],victim=null; // melee: Brute, Skitterer, Shielder, Leech...
for(i=0;i<S.enemies.length;i++){e=S.enemies[i];if(e!==h&&e.x===tx&&e.y===ty){victim=e;break;}}
if(victim){
if(shieldBlocks(victim,d[0],d[1])){burst(tx,ty,'140,200,255',4);sfx('bump');logMsg('Blocked by its tower shield! Flank it.');return;}
var dmg=h.damage;
if(S.upgrades.body>=3)dmg+=1; // Body T3 dual-wield
if(S.upgrades.body>=1&&(S.retained==='Brute'||S.retained==='Charger'))dmg+=1; // Body T1 gift
if((h.ov||0)>0)dmg=Math.ceil(dmg*1.5); // Body T2 overclock
damageEnemy(victim,dmg);
if(h.type==='Leech'||(S.upgrades.body>=1&&S.retained==='Leech')){h.hp=Math.min(h.maxHp,h.hp+1);burst(h.x,h.y,'255,120,160',3);} // drain
}
else{burst(tx,ty,'255,255,255',2);sfx('bump');}
}
function fireAtPlayer(e){
var p=S.player,dx=p.x-e.x,dy=p.y-e.y;
if(Math.abs(dx)>Math.abs(dy)){dx=dx>0?1:-1;dy=0;}else{dy=dy>0?1:-1;dx=0;}
e.facing=dy<0?'up':dy>0?'down':dx<0?'left':'right';
fireProj(e.x+dx,e.y+dy,dx,dy,false,e.edmg||1);
e.shots=(e.shots||0)+1;
if(e.shots>=3){e.overheatLeft=3;e.shots=0;}
}
function pullPlayerToward(sx,sy,r){ // Siren enemy: drag the player 1 tile closer
var p=S.player,d=Math.abs(p.x-sx)+Math.abs(p.y-sy);
if(d<1||d>r)return;
var dx=sx-p.x,dy=sy-p.y,mx=0,my=0;
if(Math.abs(dx)>Math.abs(dy))mx=dx>0?1:-1;else my=dy>0?1:-1;
var nx=p.x+mx,ny=p.y+my;
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1||occupied(nx,ny))return;
if(p.host)moveEnemy(p.host,nx,ny);
p.fromX=p.x;p.fromY=p.y;p.x=nx;p.y=ny;p.toX=nx;p.toY=ny;p.moveStart=nowMs();
reveal();burst(nx,ny,'246,150,214',3);
}
function enemyAct(e){
var p=S.player,d=distP(e),i,nx,ny;
if(e.type==='Sentinel'){
fireAtPlayer(e);
if(d<=2){ // slides away when pressured
var best=null,bd=d;
for(i=0;i<4;i++){
nx=e.x+D4[i][0];ny=e.y+D4[i][1];
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1||occupied(nx,ny)||(nx===p.x&&ny===p.y))continue;
var nd=Math.abs(nx-p.x)+Math.abs(ny-p.y);
if(nd>bd){bd=nd;best={x:nx,y:ny};}
}
if(best)moveEnemy(e,best.x,best.y);
}
return;
}
if(e.type==='Turret'){ // stationary 360-degree burst, one shot every 2 turns
fireAtPlayer(e);e.cd=1;return;
}
if(e.type==='Phaser'){ // teleports near you, strikes, fades
if(p.host&&d===1){e.facing=faceToward(e,p);damageHost(e.edmg||2,e.x,e.y);return;}
var cand=null,r;
for(i=0;i<4&&!cand;i++)for(r=2;r>=1&&!cand;r--){
nx=p.x+D4[i][0]*r;ny=p.y+D4[i][1]*r;
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1||occupied(nx,ny)||(nx===p.x&&ny===p.y))continue;
cand={x:nx,y:ny};
}
if(cand){
burst(e.x,e.y,'120,250,255',8);
e.fromX=e.x;e.fromY=e.y;e.x=cand.x;e.y=cand.y;e.moveStart=nowMs();e.facing=faceToward(e,p);
burst(cand.x,cand.y,'120,250,255',6);sfx('possess');
}
return;
}
if(e.type==='Charger'){ // telegraph 1 turn, then a straight-line charge
if(e.chargeDir){
var cd=e.chargeDir,steps=0;e.chargeDir=null;
while(steps<8){
nx=e.x+cd[0];ny=e.y+cd[1];
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1){e.stun=2;S.shake=Math.max(S.shake,3);sfx('bump');break;} // wall: stunned
if(nx===p.x&&ny===p.y&&p.host){damageHost(3,e.x,e.y);S.shake=Math.max(S.shake,4);break;} // hits only you
var block=false;
for(i=0;i<S.enemies.length;i++){var o=S.enemies[i];if(o!==e&&o.x===nx&&o.y===ny){block=true;break;}}
if(block)break; // never charges through (or damages) other enemies
moveEnemy(e,nx,ny);steps++;burst(nx,ny,'250,230,120',2);
if(nx===p.x&&ny===p.y)break; // a ghost offers no resistance
}
e.cd=Math.max(e.cd||0,2);
return;
}
if(e.telegraph){
e.telegraph=false;
var tdx=p.x-e.x,tdy=p.y-e.y;
e.chargeDir=Math.abs(tdx)>Math.abs(tdy)?[tdx>0?1:-1,0]:[0,tdy>0?1:-1];
return;
}
if(p.host&&d===1){e.facing=faceToward(e,p);damageHost(e.edmg||3,e.x,e.y);return;}
e.telegraph=true;e.facing=faceToward(e,p);
return;
}
if(e.type==='Bomber'){ // chases, detonates on contact - the blast never touches other enemies
if(d===1){detonate(e,0,3);return;}
}
else if(e.type==='Healer'){ // mends its allies, flees from you
for(i=0;i<S.enemies.length;i++){
var a=S.enemies[i];
if(a!==e&&a.hp<a.maxHp&&Math.abs(a.x-e.x)<=3&&Math.abs(a.y-e.y)<=3){
a.hp++;burst(a.x,a.y,'120,255,160',2);
}
}
var hb=null,hbd=d;
for(i=0;i<4;i++){
nx=e.x+D4[i][0];ny=e.y+D4[i][1];
if(nx<0||ny<0||nx>=W||ny>=H||S.grid[ny][nx]===1||occupied(nx,ny)||(nx===p.x&&ny===p.y))continue;
var hnd=Math.abs(nx-p.x)+Math.abs(ny-p.y);
if(hnd>hbd){hbd=hnd;hb={x:nx,y:ny};}
}
if(hb)moveEnemy(e,hb.x,hb.y);
return;
}
else if(e.type==='Siren'){ // stationary lure with a pull field
if(p.host&&d===1){e.facing=faceToward(e,p);damageHost(e.edmg||1,e.x,e.y);return;}
pullPlayerToward(e.x,e.y,5);
return;
}
else if(e.type==='Mimic'&&!e.revealed){ // disguised as a chest until you touch it
if(d<=1){
e.revealed=true;S.shake=Math.max(S.shake,3);burst(e.x,e.y,'255,200,90',10);sfx('possess');
if(p.host&&Math.abs(p.x-e.x)+Math.abs(p.y-e.y)===1)damageHost(2,e.x,e.y);
logMsg('The chest splits into a fanged maw!');
}
return;
}
else if(e.type==='Leech'&&d===1){ // drains you, feeds itself
e.facing=faceToward(e,p);
damageHost(1,e.x,e.y);e.hp=Math.min(e.maxHp,e.hp+1);
burst(e.x,e.y,'255,110,150',4);
return;
}
// shared slow chase + melee: Brute, Shielder, Skitterer, aggroed Bomber, revealed Mimic, Leech
if(p.host&&d===1){e.facing=faceToward(e,p);damageHost(e.edmg||e.damage||1,e.x,e.y);return;} // never targets other enemies
var st=pathStep(e.x,e.y,p.x,p.y);
if(st&&!(st.x===p.x&&st.y===p.y)&&!occupied(st.x,st.y))moveEnemy(e,st.x,st.y);
}
function enemyTurn(){
var list=S.enemies.slice(),i,e;
for(i=0;i<list.length;i++){
e=list[i];
if(S.enemies.indexOf(e)<0)continue; // died earlier this turn
if(e.lockout>0)e.lockout--;
if(e.overheatLeft>0){e.overheatLeft--;if(e.overheatLeft<=0)e.shots=0;continue;} // venting: no acting
if(e===S.player.host)continue; // you are wearing this one
if(e.stun>0){e.stun--;continue;}
var d=distP(e);
if(!e.aggro){ // docile until the player gets close WITH line of sight
var stealth=S.player.host&&S.player.host.type==='Mimic'&&!S.player.host.revealed; // disguised: no aggro
var need=e.type==='Mimic'?1:AGGRO_R;
if(!stealth&&d<=need&&los(e.x,e.y,S.player.x,S.player.y))e.aggro=true;
else continue;
}else if(d>AGGRO_R+3){e.aggro=false;continue;} // lost you: back to idle
if(e.cd>0){e.cd--;continue;}
e.cd=e.type==='Sentinel'?0:Math.max(0,(e.speed||2)-1); // most chasers act every 2 turns
enemyAct(e);
if(S.state==='lost')return;
}
}
function projectilesTick(){ // shots only ever hurt the player's body; yours hurt enemies
var p=S.player,i,q,j;
for(i=S.projectiles.length-1;i>=0;i--){
q=S.projectiles[i];q.x+=q.dx;q.y+=q.dy;q.life--;
if(q.own){
var victim=null;
for(j=0;j<S.enemies.length;j++){var v=S.enemies[j];if(v!==p.host&&v.x===q.x&&v.y===q.y){victim=v;break;}}
if(victim){
if(shieldBlocks(victim,q.dx,q.dy)){burst(q.x,q.y,'140,200,255',4);sfx('bump');}
else damageEnemy(victim,q.dmg);
S.projectiles.splice(i,1);continue;
}
}else if(p.host&&q.x===p.x&&q.y===p.y){
damageHost(q.dmg,q.x-q.dx,q.y-q.dy);S.projectiles.splice(i,1);continue;
}
if(q.life<=0||q.x<0||q.y<0||q.x>=W||q.y>=H||!S.grid[q.y]||S.grid[q.y][q.x]===1){
burst(q.x,q.y,'170,140,230',2);S.projectiles.splice(i,1);
}
}
}
/* ============ movement ============ */
var DIRS={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],w:[0,-1],s:[0,1],a:[-1,0],d:[1,0]};
function tryMove(dx,dy){
var p=S.player;
if(S.state!=='playing'&&S.state!=='possessed')return false;
p.facing=dy<0?'up':dy>0?'down':dx<0?'left':'right';
var nx=p.x+dx,ny=p.y+dy;
if(nx<0||ny<0||nx>=W||ny>=H||!S.grid[ny]||(S.grid[ny][nx]===1&&!(p.ghost&&(S.ghostPhase||0)>0))){sfx('bump');return false;}
if(!p.ghost){ // steering a host body; slower hosts step every `speed` turns
var h=p.host;if(!h)return false;
if(h.type==='Turret'){sfx('bump');return false;} // rooted: rotate + fire instead
if((p.moveCd||0)>0)return false;
if(occupied(nx,ny)){sfx('bump');return false;}
moveEnemy(h,nx,ny);
p.fromX=p.x;p.fromY=p.y;p.x=nx;p.y=ny;p.toX=nx;p.toY=ny;p.moveStart=nowMs();
p.moveCd=h.type==='Skitterer'?0:Math.max(1,(h.speed||2)-1); // Skitterer kit: fast host, steps every turn
spawnDust(nx,ny);reveal();sfx('move');
afterStep();
return true;
}
p.fromX=p.x;p.fromY=p.y;p.x=nx;p.y=ny;p.toX=nx;p.toY=ny;
p.moveStart=nowMs();p.moveCooldown=120;
spawnDust(nx,ny);reveal();sfx('move');
afterStep();
return true;
}
function afterStep(){ // stepped onto something interesting: chest, shop pad, exit stairs
var p=S.player,tile=S.grid[p.y]?S.grid[p.y][p.x]:0;
if(tile===5){ // gilded chest: pays out its hoard
var amt=3+((hash(p.x,p.y)*6)|0);
S.essence+=amt;S.grid[p.y][p.x]=0;
burst(p.x,p.y,'255,220,120',12);sfx('pickup');
logMsg('The chest holds '+amt+' essence.');
}else if(tile===4){openShop(false);logMsg('A merchant shrine hums awake.');}
else if(tile===3){
if(S.floor>=10){setState('won');ach('escape');sfx('confirm');logMsg('You slip through the final gate!');save();}
else{logMsg('You descend toward floor '+(S.floor+1)+'...');openShop(true);save();}
}
}
function dashGhost(){ // Ghost T4: blink 3 tiles in the facing direction
var p=S.player,d=FACING[p.facing]||FACING.down,i,nx=p.x,ny=p.y;
for(i=0;i<3;i++){
var ax=nx+d[0],ay=ny+d[1];
if(ax<0||ay<0||ax>=W||ay>=H)break;
if((S.ghostPhase||0)<=0&&S.grid[ay][ax]===1)break;
nx=ax;ny=ay;
}
if(nx===p.x&&ny===p.y)return false;
p.fromX=p.x;p.fromY=p.y;p.x=nx;p.y=ny;p.toX=nx;p.toY=ny;p.moveStart=nowMs();
burst(nx,ny,'150,240,255',6);sfx('possess');reveal();afterStep();
return true;
}
function spawnDust(x,y){
for(var i=0;i<3;i++)S.particles.push({x:x*T+16+(Math.random()*10-5),y:y*T+HUD_H+26,vx:(Math.random()-0.5)*0.4,vy:-0.2-Math.random()*0.3,life:0.4,max:0.4,c:'160,190,220',r:2});
}
/* ============ deterministic tick ============ */
function tick(n){
n=Math.max(1,(n|0)||0);
for(var i=0;i<n;i++){
S.turn++;
var p=S.player;
if(S.state==='playing'&&p.ghost){ // timer pauses while possessing
p.timer-=TIMER_STEP;
if(p.timer<=0){p.timer=0;setState('lost');sfx('death');logMsg('You faded away...');}
}
if(S.state==='playing'||S.state==='possessed'){
if((S.ghostPhase||0)>0)S.ghostPhase--; // Ghost T3 phase burst ticks down
if((S.phaseCd||0)>0)S.phaseCd--;
if((S.ghostDashCd||0)>0)S.ghostDashCd--; // Ghost T4 dash cooldown
if(!p.ghost&&p.host){
if((p.moveCd||0)>0)p.moveCd--;
if((p.host.cd||0)>0)p.host.cd--;
if((p.host.ov||0)>0)p.host.ov--; // Body T2 overclock window
if(S.upgrades.body>=1&&S.retained==='Healer'&&(S.turn%2===0)&&p.host.hp<p.host.maxHp){p.host.hp++;burst(p.host.x,p.host.y,'120,255,160',2);}
}
enemyTurn();
projectilesTick();
}
if(S.floor>=7)ach('diver'); // Deep Diver
if(S.floor>=3&&!S.hostHurt)ach('pacifist'); // Pacifist Ghost
if((S.essence|0)>=30)ach('hoarder'); // Essence Hoarder
for(var j=S.particles.length-1;j>=0;j--){var q=S.particles[j];q.x+=q.vx;q.y+=q.vy;q.life-=0.05;if(q.life<=0)S.particles.splice(j,1);}
}
return true;
}
/* ============ input ============ */
var held={};
function input(key){
var k=String(key==null?'':key);
if(k===' ')k='Space';
initAudio();
// legend toggle (works from title AND during play)
if(k==='l'||k==='L'){S.legend=!S.legend;sfx('ui');return true;}
if(S.legend&&(k==='Escape')){S.legend=false;sfx('ui');return true;}
if(S.state==='title'){
if(k==='Enter'){S.legend=false;S.contSeen=true;newRun();return true;}
if(k==='y'||k==='Y'){S.contSeen=true;if(load())sfx('confirm');else logMsg('No saved run found.');return true;}
if(k==='n'||k==='N'){S.contSeen=true;sfx('ui');return true;}
if(k==='c'||k==='C'){S.contSeen=true;if(load())sfx('confirm');return true;}
return true;
}
if(S.state==='lost'||S.state==='won'){
if(k==='Enter'){start();sfx('confirm');}
return true;
}
if(S.state==='paused'){
if(k==='Escape'){setState(S.pausedFrom||'playing');sfx('ui');}
else if(k==='Enter'){save();setState('title');S.legend=false;S.contSeen=true;sfx('confirm');}
return true;
}
if(S.state==='shop'){ // between-floor shrine / merchant pad
if(k==='ArrowLeft'||k==='a'){S.shopSel=Math.max(0,(S.shopSel||0)-1);sfx('ui');}
else if(k==='ArrowRight'||k==='d'){S.shopSel=Math.min(Math.max(0,(S.shopChoices||[]).length-1),(S.shopSel||0)+1);sfx('ui');}
else if(k==='Enter'){if(!buy(S.shopSel||0))sfx('bump');}
else if(k==='x'||k==='X'||k==='Escape'){skipShop();}
return true;
}
if(S.state==='playing'||S.state==='possessed'){
if(k==='Escape'){S.pausedFrom=S.state;setState('paused');sfx('ui');return true;}
if(S.legend)return true;
if(DIRS[k]){tryMove(DIRS[k][0],DIRS[k][1]);return true;}
if(k==='q'||k==='Q'||k==='e'||k==='E'){ // rotate facing; ghost upgrades when incorporeal
var lc=k.toLowerCase();
if(S.player.ghost){
if(lc==='q'&&S.upgrades.ghost>=3&&(S.phaseCd||0)<=0){ // Ghost T3: phase through walls
S.ghostPhase=2;S.phaseCd=8;logMsg('You phase between the stones.');sfx('possess');return true;
}
if(lc==='e'&&S.upgrades.ghost>=4&&(S.ghostDashCd||0)<=0&&dashGhost()){S.ghostDashCd=5;return true;} // Ghost T4
}
var rot={up:'left',left:'down',down:'right',right:'up'};
if(lc==='e')rot={up:'right',right:'down',down:'left',left:'up'};
S.player.facing=rot[S.player.facing]||'down';
if(S.player.host)S.player.host.facing=S.player.facing; // directional bodies (Shielder, Turret)
sfx('ui');return true;
}
if(k==='Space'){
if(S.state==='playing'&&S.player.ghost)tryPossess();
else if(S.state==='possessed')hostAction();
else sfx('ui');
return true;
}
if(k==='x'||k==='X'){
if(S.state==='possessed'&&S.player.host)abandonHost();
else sfx('ui');
return true;
}
}
return true;
}
/* ============ rendering ============ */
var cv=document.getElementById('game'),ctx=null;
try{ctx=cv.getContext('2d');}catch(e){ctx=null;}
if(!ctx)ctx={fillRect:function(){},strokeRect:function(){},beginPath:function(){},closePath:function(){},moveTo:function(){},lineTo:function(){},arc:function(){},ellipse:function(){},quadraticCurveTo:function(){},fill:function(){},stroke:function(){},save:function(){},restore:function(){},translate:function(){},fillText:function(){},strokeText:function(){},createLinearGradient:function(){return{addColorStop:function(){}};},createRadialGradient:function(){return{addColorStop:function(){}};},measureText:function(t){return{width:String(t).length*8};}};
var C='#0a0b12';
function px(i){return i*T;}
function drawFloorTile(x,y){
var X=px(x),Y=px(y),h=hash(x,y);
var base=h<0.33?'#22242e':h<0.66?'#262834':'#20222b';
ctx.fillStyle=base;ctx.fillRect(X,Y,T,T);
var g=ctx.createLinearGradient(X,Y,X+T,Y+T);
g.addColorStop(0,'rgba(255,255,255,0.035)');g.addColorStop(1,'rgba(0,0,0,0.14)');
ctx.fillStyle=g;ctx.fillRect(X,Y,T,T);
// flagstone seams
ctx.strokeStyle='rgba(0,0,0,0.32)';ctx.lineWidth=1;
ctx.strokeRect(X+0.5,Y+0.5,T-1,T-1);
ctx.strokeStyle='rgba(255,255,255,0.028)';
ctx.beginPath();ctx.moveTo(X+2,Y+T-2);ctx.lineTo(X+T-2,Y+T-2);ctx.stroke();
if(h>0.86){ // crack
ctx.strokeStyle='rgba(0,0,0,0.35)';ctx.beginPath();
ctx.moveTo(X+6+h*8,Y+5);ctx.lineTo(X+12+h*6,Y+16);ctx.lineTo(X+9+h*10,Y+27);ctx.stroke();
}else if(h<0.12){ // pebbles
ctx.fillStyle='rgba(255,255,255,0.05)';
ctx.beginPath();ctx.arc(X+10+h*80,Y+12+h*40,1.6,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(X+20-h*40,Y+22,1.2,0,6.284);ctx.fill();
}
// shadow cast by a wall above
if(y>0&&S.grid[y-1]&&S.grid[y-1][x]===1){
var sg=ctx.createLinearGradient(X,Y,X,Y+11);
sg.addColorStop(0,'rgba(0,0,0,0.42)');sg.addColorStop(1,'rgba(0,0,0,0)');
ctx.fillStyle=sg;ctx.fillRect(X,Y,T,11);
}
}
function drawWallTile(x,y){
var X=px(x),Y=px(y),h=hash(x,y);
var g=ctx.createLinearGradient(X,Y,X,Y+T);
g.addColorStop(0,'#4a4b58');g.addColorStop(0.55,'#3a3b46');g.addColorStop(1,'#26272f');
ctx.fillStyle=g;ctx.fillRect(X,Y,T,T);
// bevels
ctx.fillStyle='rgba(255,255,255,0.14)';ctx.fillRect(X,Y,T,3);
ctx.fillStyle='rgba(255,255,255,0.06)';ctx.fillRect(X,Y,3,T);
ctx.fillStyle='rgba(0,0,0,0.38)';ctx.fillRect(X,Y+T-4,T,4);
ctx.fillStyle='rgba(0,0,0,0.26)';ctx.fillRect(X+T-3,Y,3,T);
// mortar joints
ctx.strokeStyle='rgba(8,8,14,0.55)';ctx.lineWidth=1;
ctx.beginPath();
ctx.moveTo(X,Y+T*0.52);ctx.lineTo(X+T,Y+T*0.52);
var off=h>0.5?T*0.32:T*0.66;
ctx.moveTo(X+off,Y);ctx.lineTo(X+off,Y+T*0.52);
var off2=h>0.5?T*0.7:T*0.35;
ctx.moveTo(X+off2,Y+T*0.52);ctx.lineTo(X+off2,Y+T);
ctx.stroke();
if(h>0.72){ // crack down the block
ctx.strokeStyle='rgba(5,5,10,0.5)';
ctx.beginPath();ctx.moveTo(X+14-h*10,Y+4);ctx.lineTo(X+16-h*8,Y+T*0.5);ctx.lineTo(X+13-h*6,Y+T-4);ctx.stroke();
}
if(h<0.18){ // moss fleck
ctx.fillStyle='rgba(90,130,80,0.22)';
ctx.beginPath();ctx.arc(X+8+h*60,Y+24,2.4,0,6.284);ctx.fill();
}
ctx.strokeStyle='rgba(6,6,12,0.8)';ctx.strokeRect(X+0.5,Y+0.5,T-1,T-1);
}
function drawExitTile(x,y,t){
var X=px(x),Y=px(y);
ctx.fillStyle='#10121c';ctx.fillRect(X,Y,T,T);
for(var s=0;s<3;s++){
ctx.fillStyle='rgba('+(70+s*20)+','+(90+s*20)+','+(140+s*30)+','+(0.5-s*0.12)+')';
ctx.fillRect(X+4+s*4,Y+6+s*6,T-8-s*8,4);
}
var pulse=0.35+0.25*Math.sin(t*3);
var g=ctx.createRadialGradient(X+16,Y+16,2,X+16,Y+16,22);
g.addColorStop(0,'rgba(80,220,255,'+pulse+')');g.addColorStop(1,'rgba(80,220,255,0)');
ctx.fillStyle=g;ctx.fillRect(X-8,Y-8,T+16,T+16);
// rune marks
ctx.strokeStyle='rgba(120,230,255,'+(0.5+0.3*Math.sin(t*2+x))+')';ctx.lineWidth=1.5;
ctx.beginPath();ctx.moveTo(X+9,Y+9);ctx.lineTo(X+13,Y+9);ctx.lineTo(X+9,Y+13);ctx.stroke();
ctx.beginPath();ctx.moveTo(X+19,Y+9);ctx.lineTo(X+23,Y+13);ctx.lineTo(X+19,Y+13);ctx.stroke();
}
function drawDoorTile(x,y){ // wooden dungeon door in a stone frame
drawFloorTile(x,y);
var X=px(x),Y=px(y);
var g=ctx.createLinearGradient(X,Y,X+T,Y);
g.addColorStop(0,'#7a5a30');g.addColorStop(0.5,'#5c4020');g.addColorStop(1,'#3a280f');
ctx.fillStyle=g;rrect(ctx,X+3,Y+4,T-6,T-8,3);ctx.fill();
ctx.strokeStyle='rgba(16,10,4,0.85)';ctx.lineWidth=1.5;rrect(ctx,X+3,Y+4,T-6,T-8,3);ctx.stroke();
// planks
ctx.strokeStyle='rgba(20,12,4,0.5)';ctx.lineWidth=1;
ctx.beginPath();ctx.moveTo(X+12,Y+5);ctx.lineTo(X+12,Y+T-5);ctx.moveTo(X+20,Y+5);ctx.lineTo(X+20,Y+T-5);ctx.stroke();
// iron bands + handle
ctx.fillStyle='#3c4048';ctx.fillRect(X+3,Y+12,T-6,3);ctx.fillRect(X+3,Y+T-15,T-6,3);
ctx.fillStyle='#c9a24c';ctx.beginPath();ctx.arc(X+T-9,Y+T/2,2,0,6.284);ctx.fill();
}
function playerRenderPos(t){
var p=S.player;
var f=easeOut((nowMs()-p.moveStart)/MOVE_MS);
var rx=lerp(p.fromX,p.toX,f),ry=lerp(p.fromY,p.toY,f);
p.renderX=rx;p.renderY=ry;
return{cx:rx*T+T/2,cy:ry*T+T/2+Math.sin(t*2.2)*2.2};
}
function drawGhost(t,cx,cy,aura,scale){
if(scale&&scale!==1){ctx.save();ctx.translate(cx,cy);ctx.scale(scale,scale);ctx.translate(-cx,-cy);}
// soft shadow
ctx.fillStyle='rgba(0,0,0,0.30)';
ctx.beginPath();ctx.ellipse(cx,cy+15,10,4,0,0,6.284);ctx.fill();
if(aura){ // possession aura ring
var ag=ctx.createRadialGradient(cx,cy,4,cx,cy,24);
ag.addColorStop(0,'rgba(120,240,255,0.22)');ag.addColorStop(1,'rgba(120,240,255,0)');
ctx.fillStyle=ag;ctx.fillRect(cx-26,cy-26,52,52);
}
// outer glow
var og=ctx.createRadialGradient(cx,cy-2,2,cx,cy,22);
og.addColorStop(0,'rgba(170,225,255,0.30)');og.addColorStop(1,'rgba(150,200,255,0)');
ctx.fillStyle=og;ctx.fillRect(cx-24,cy-24,48,48);
// wisp body with tattered tail
var wob=Math.sin(t*3)*1.4;
var bg=ctx.createLinearGradient(cx,cy-16,cx,cy+16);
bg.addColorStop(0,'rgba(225,240,255,0.92)');bg.addColorStop(0.6,'rgba(170,205,240,0.72)');bg.addColorStop(1,'rgba(130,170,220,0.30)');
ctx.fillStyle=bg;
ctx.beginPath();
ctx.moveTo(cx,cy-15+wob*0.4);
ctx.bezierCurveTo(cx+11,cy-13,cx+12+wob,cy+2,cx+9,cy+10);
// tattered tail zigzag
ctx.lineTo(cx+6,cy+8+Math.sin(t*5)*2);
ctx.lineTo(cx+3,cy+14);ctx.lineTo(cx,cy+9+Math.sin(t*5+1)*2);
ctx.lineTo(cx-3,cy+14);ctx.lineTo(cx-6,cy+8+Math.sin(t*5+2)*2);
ctx.lineTo(cx-9,cy+10);
ctx.bezierCurveTo(cx-12-wob,cy+2,cx-11,cy-13,cx,cy-15+wob*0.4);
ctx.closePath();ctx.fill();
// inner core light
var ig=ctx.createRadialGradient(cx,cy-4,1,cx,cy-4,9);
ig.addColorStop(0,'rgba(255,255,255,0.55)');ig.addColorStop(1,'rgba(200,230,255,0)');
ctx.fillStyle=ig;ctx.fillRect(cx-10,cy-14,20,20);
// glowing eyes tracking facing
var p=S.player,ex=0,ey=0;
if(p.facing==='left')ex=-2;else if(p.facing==='right')ex=2;
else if(p.facing==='up')ey=-1.5;else ey=1.5;
ctx.fillStyle='#9ff3ff';
ctx.shadowColor='#7fe8ff';ctx.shadowBlur=6;
ctx.beginPath();ctx.arc(cx-3.5+ex,cy-4+ey+wob*0.3,1.7,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+3.5+ex,cy-4+ey+wob*0.3,1.7,0,6.284);ctx.fill();
ctx.shadowBlur=0;
if(scale&&scale!==1)ctx.restore();
}
function eyeOffset(e){ // eyes track the player (or your facing when you wear it)
var tx,ty;
if(S.player.host===e){var f=FACING[S.player.facing]||FACING.down;tx=f[0];ty=f[1];}
else{var dx=S.player.x-e.x,dy=S.player.y-e.y,m=Math.max(1,Math.abs(dx)+Math.abs(dy));tx=dx/m;ty=dy/m;}
return{x:tx*2,y:ty*1.4};
}
function drawBrute(cx,cy,t,e){ // hulking crimson armored body
var sway=Math.sin(t*1.7+e.bobSeed)*1.1,bx=cx+sway*0.5;
// dragging knuckle-fists
ctx.fillStyle='#8f2a22';
rrect(ctx,cx-17,cy+3+sway,8,11,4);ctx.fill();
rrect(ctx,cx+9,cy+3-sway,8,11,4);ctx.fill();
ctx.fillStyle='rgba(255,255,255,0.12)';
rrect(ctx,cx-17,cy+3+sway,8,4,3);ctx.fill();
rrect(ctx,cx+9,cy+3-sway,8,4,3);ctx.fill();
// torso
var g=ctx.createLinearGradient(cx-12,cy-14,cx+12,cy+13);
g.addColorStop(0,'#ef6a50');g.addColorStop(0.55,'#c23a30');g.addColorStop(1,'#701a18');
ctx.fillStyle=g;rrect(ctx,bx-12,cy-13,24,25,8);ctx.fill();
ctx.strokeStyle='rgba(20,4,4,0.85)';ctx.lineWidth=1.6;rrect(ctx,bx-12,cy-13,24,25,8);ctx.stroke();
// beveled chest plate + rivets
var pg=ctx.createLinearGradient(bx,cy-10,bx,cy+8);
pg.addColorStop(0,'rgba(255,255,255,0.28)');pg.addColorStop(1,'rgba(255,255,255,0.02)');
ctx.fillStyle=pg;rrect(ctx,bx-8,cy-8,16,14,4);ctx.fill();
ctx.strokeStyle='rgba(60,10,10,0.6)';ctx.lineWidth=1;rrect(ctx,bx-8,cy-8,16,14,4);ctx.stroke();
ctx.fillStyle='rgba(255,210,160,0.8)';
ctx.beginPath();ctx.arc(bx-6,cy-6,1.1,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(bx+6,cy-6,1.1,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(bx,cy+4,1.1,0,6.284);ctx.fill();
// shoulder pauldrons
ctx.fillStyle='#a12c24';
ctx.beginPath();ctx.ellipse(bx-11,cy-9,5.5,4.5,-0.4,0,6.284);ctx.fill();
ctx.beginPath();ctx.ellipse(bx+11,cy-9,5.5,4.5,0.4,0,6.284);ctx.fill();
ctx.strokeStyle='rgba(20,4,4,0.7)';ctx.lineWidth=1;ctx.stroke();
// heavy brow + glowing eyes
ctx.fillStyle='#5c1410';rrect(ctx,bx-9,cy-11,18,5,2);ctx.fill();
var look=eyeOffset(e);
ctx.fillStyle='#ffd24a';ctx.shadowColor='#ffae30';ctx.shadowBlur=5;
ctx.beginPath();ctx.arc(bx-4+look.x,cy-8.5+look.y,1.6,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(bx+4+look.x,cy-8.5+look.y,1.6,0,6.284);ctx.fill();
ctx.shadowBlur=0;
}
function drawSkitterer(cx,cy,t,e){ // orange insectile carapace
var i,twitch=Math.sin(t*9+e.bobSeed);
// three pointed legs per side, quick shuffle
ctx.strokeStyle='#7a3c0e';ctx.lineWidth=1.6;
for(var s=-1;s<=1;s+=2)for(i=0;i<3;i++){
var lx=cx+s*(6+i*2.5),ly=cy-2+i*4,ph=Math.sin(t*11+i*2.1+s)*2;
ctx.beginPath();ctx.moveTo(cx+s*4,cy-3+i*3.5);ctx.lineTo(lx+s*2,ly-3+ph*0.4);ctx.lineTo(lx+s*4,ly+7+ph*0.5);ctx.stroke();
}
// segmented carapace plates
var segs=[[0,-9,7,5.5],[0,-1,8,6],[0,7,6.5,4.5]];
for(i=2;i>=0;i--){
var sg=ctx.createLinearGradient(cx,cy-12,cx,cy+11);
sg.addColorStop(0,i===0?'#ffc06a':'#f08c2a');sg.addColorStop(0.6,'#c25e12');sg.addColorStop(1,'#6e2f08');
ctx.fillStyle=sg;
ctx.beginPath();ctx.ellipse(cx+segs[i][0],cy+segs[i][1],segs[i][2],segs[i][3],0,0,6.284);ctx.fill();
ctx.strokeStyle='rgba(40,14,2,0.8)';ctx.lineWidth=1;ctx.stroke();
ctx.fillStyle='rgba(255,235,200,0.22)'; // glossy wet highlight
ctx.beginPath();ctx.ellipse(cx-2,cy+segs[i][1]-2,segs[i][2]*0.45,segs[i][3]*0.4,0,0,6.284);ctx.fill();
}
// twitching mandibles
ctx.strokeStyle='#8a4210';ctx.lineWidth=1.8;
ctx.beginPath();ctx.moveTo(cx-3,cy-11);ctx.lineTo(cx-5,cy-15+twitch);ctx.stroke();
ctx.beginPath();ctx.moveTo(cx+3,cy-11);ctx.lineTo(cx+5,cy-15-twitch);ctx.stroke();
var look=eyeOffset(e);
ctx.fillStyle='#2a0e02';
ctx.beginPath();ctx.arc(cx-3+look.x*0.8,cy-8+look.y,1.2,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+3+look.x*0.8,cy-8+look.y,1.2,0,6.284);ctx.fill();
}
function drawSentinel(cx,cy,t,e){ // purple floating crystal pod
var i,hot=(e.overheatLeft||0)>0;
var charging=e.aggro||(S.player.host===e&&(e.shots||0)>0&&!hot);
cy+=Math.sin(t*2.4+e.bobSeed)*2.2;
// energy coils underneath
ctx.strokeStyle=hot?'rgba(255,120,80,0.55)':'rgba(190,140,255,0.5)';ctx.lineWidth=1.4;
for(i=0;i<2;i++){ctx.beginPath();ctx.ellipse(cx,cy+11-i*2,9-i*3,3,0,0,6.284);ctx.stroke();}
// hex shell
var g=ctx.createRadialGradient(cx-4,cy-6,2,cx,cy,15);
g.addColorStop(0,'#d9c2ff');g.addColorStop(0.45,hot?'#c46a5a':'#a86ce8');g.addColorStop(1,'#3c1e62');
ctx.fillStyle=g;
ctx.beginPath();
for(i=0;i<6;i++){var a=Math.PI/6+i*Math.PI/3,hx=cx+Math.cos(a)*13,hy=cy+Math.sin(a)*13;i?ctx.lineTo(hx,hy):ctx.moveTo(hx,hy);}
ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(20,8,40,0.85)';ctx.lineWidth=1.6;ctx.stroke();
// facet lines
ctx.strokeStyle='rgba(255,255,255,0.18)';ctx.lineWidth=1;
ctx.beginPath();ctx.moveTo(cx-11,cy-6);ctx.lineTo(cx+11,cy-6);ctx.moveTo(cx-13,cy+1);ctx.lineTo(cx+13,cy+1);ctx.stroke();
// single aiming eye
var look=eyeOffset(e);
var eg=ctx.createRadialGradient(cx+look.x,cy+look.y,0.5,cx,cy,6);
eg.addColorStop(0,'#ffffff');eg.addColorStop(0.4,hot?'#ffb090':'#e0b0ff');eg.addColorStop(1,'rgba(120,60,190,0)');
ctx.fillStyle=eg;ctx.beginPath();ctx.arc(cx,cy,6,0,6.284);ctx.fill();
ctx.fillStyle='#1a0b30';ctx.beginPath();ctx.arc(cx+look.x*1.6,cy+look.y*1.6,1.8,0,6.284);ctx.fill();
// muzzle glow toward facing (charges before each burst; red while venting)
var f=(S.player.host===e)?(FACING[S.player.facing]||FACING.down):(FACING[e.facing]||FACING.down);
var mx=cx+f[0]*14,my=cy+f[1]*14;
var mg=ctx.createRadialGradient(mx,my,0.5,mx,my,hot?7:5);
mg.addColorStop(0,hot?'rgba(255,140,90,0.9)':charging?'rgba(230,170,255,0.9)':'rgba(190,140,255,0.45)');
mg.addColorStop(1,'rgba(150,90,230,0)');
ctx.fillStyle=mg;ctx.fillRect(mx-8,my-8,16,16);
if(hot){ // venting steam while overheated
ctx.fillStyle='rgba(255,150,110,'+(0.25+0.15*Math.sin(t*9))+')';
ctx.beginPath();ctx.arc(cx-8,cy-10,2.5+Math.sin(t*7),0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+8,cy-10,2.5+Math.cos(t*7),0,6.284);ctx.fill();
}
}
function drawShielder(cx,cy,t,e){ // stocky body behind a rotating tower shield
var host=S.player.host===e;
var f=host?(FACING[S.player.facing]||FACING.down):(FACING[e.facing]||FACING.down);
var vert=f[1]!==0,bob=Math.sin(t*2+e.bobSeed)*1.1;
// stocky armored body
var g=ctx.createLinearGradient(cx,cy-11,cx,cy+12);
g.addColorStop(0,'#7cb4f4');g.addColorStop(0.6,'#3a6fc0');g.addColorStop(1,'#1c3a78');
ctx.fillStyle=g;rrect(ctx,cx-9,cy-10+bob*0.3,18,21,6);ctx.fill();
ctx.strokeStyle='rgba(8,18,40,0.85)';ctx.lineWidth=1.5;ctx.stroke();
// pauldrons
ctx.fillStyle='#2c56a4';
ctx.beginPath();ctx.ellipse(cx-8,cy-8+bob*0.3,4,3.4,-0.4,0,6.284);ctx.fill();
ctx.beginPath();ctx.ellipse(cx+8,cy-8+bob*0.3,4,3.4,0.4,0,6.284);ctx.fill();
// narrow visor slit with tracking glow
ctx.fillStyle='#0c1c38';rrect(ctx,cx-6,cy-6+bob*0.3,12,3.4,1.6);ctx.fill();
var look=eyeOffset(e);
ctx.fillStyle='#8fd0ff';
ctx.fillRect(cx-4.5+look.x*0.7,cy-5.4+bob*0.3,2.6,1.8);ctx.fillRect(cx+1.9+look.x*0.7,cy-5.4+bob*0.3,2.6,1.8);
// embossed tower shield plate on the facing side
var sx=cx+f[0]*10,sy=cy+f[1]*10+bob*0.2,sw=vert?21:8,sh=vert?8:21;
var sg=ctx.createLinearGradient(sx-sw/2,sy-sh/2,sx+sw/2,sy+sh/2);
sg.addColorStop(0,'#a6c8fa');sg.addColorStop(0.5,'#4f8fe8');sg.addColorStop(1,'#274d94');
ctx.fillStyle=sg;rrect(ctx,sx-sw/2,sy-sh/2,sw,sh,4);ctx.fill();
ctx.strokeStyle='rgba(10,20,45,0.95)';ctx.lineWidth=1.6;rrect(ctx,sx-sw/2,sy-sh/2,sw,sh,4);ctx.stroke();
// crest stripe + rivets
ctx.fillStyle='rgba(255,220,140,0.9)';
if(vert)rrect(ctx,sx-6,sy-1.8,12,3.6,1.8);else rrect(ctx,sx-1.8,sy-6,3.6,12,1.8);
ctx.fill();
ctx.fillStyle='#dcecff';
var rx2=vert?[-8,8]:[0],ry2=vert?[0]:[-8,8];
for(var i=0;i<2;i++)for(var j=0;j<2;j++){
ctx.beginPath();ctx.arc(sx+(vert?rx2[i]:rx2[i]||0)+(vert?0:(i?4:-4)),sy+(vert?(j?4:-4):ry2[j]),1,0,6.284);ctx.fill();
}
}
function drawBomber(cx,cy,t,e){ // cast-iron shell, fuse sparks harder as it closes
var p=S.player,d=Math.abs(e.x-p.x)+Math.abs(e.y-p.y);
var heat=e.aggro?clamp(1-(d-1)/5,0,1):0;
var puls=1+Math.sin(t*(4+heat*10))*0.05*heat;
var g=ctx.createRadialGradient(cx-4,cy-6,2,cx,cy+2,14);
g.addColorStop(0,'#d86a50');g.addColorStop(0.5,'#a03226');g.addColorStop(1,'#4a120e');
ctx.fillStyle=g;
ctx.beginPath();ctx.ellipse(cx,cy,12*puls,11*puls,0,0,6.284);ctx.fill();
ctx.strokeStyle='rgba(15,4,4,0.9)';ctx.lineWidth=1.6;ctx.stroke();
// iron seam + rivets
ctx.strokeStyle='rgba(60,20,16,0.85)';ctx.lineWidth=2;
ctx.beginPath();ctx.moveTo(cx-11,cy);ctx.lineTo(cx+11,cy);ctx.stroke();
ctx.fillStyle='#e8c9a0';
ctx.beginPath();ctx.arc(cx-7,cy,1,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+7,cy,1,0,6.284);ctx.fill();
// exposed fuse
ctx.strokeStyle='#3a2a18';ctx.lineWidth=2;
ctx.beginPath();ctx.moveTo(cx,cy-10);ctx.quadraticCurveTo(cx+3,cy-15,cx+1+Math.sin(t*6)*1.5,cy-17);ctx.stroke();
// sparking tip (intensifies with heat)
var spark=clamp(0.5+heat*0.5+Math.sin(t*12+e.bobSeed)*0.2,0,1);
var sp=ctx.createRadialGradient(cx+1,cy-17,0.5,cx+1,cy-17,4+heat*4);
sp.addColorStop(0,'rgba(255,240,180,'+spark+')');sp.addColorStop(0.4,'rgba(255,160,60,'+spark*0.7+')');sp.addColorStop(1,'rgba(255,90,30,0)');
ctx.fillStyle=sp;ctx.fillRect(cx-7,cy-25,16,16);
// soot puffs when hot
if(heat>0.3){
ctx.fillStyle='rgba(60,50,44,'+(0.2*heat)+')';
ctx.beginPath();ctx.arc(cx-9,cy-7-heat*4,2.4+heat*2,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+9,cy-6-heat*4,2+heat*2,0,6.284);ctx.fill();
}
var look=eyeOffset(e);
ctx.fillStyle='#ffce6a';
ctx.beginPath();ctx.arc(cx-3.5+look.x,cy-3+look.y,1.5,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+3.5+look.x,cy-3+look.y,1.5,0,6.284);ctx.fill();
}
function drawHealer(cx,cy,t,e){ // hooded robe, glowing ankh, drifting motes
var bob=Math.sin(t*2.1+e.bobSeed)*1.6;cy+=bob*0.5;
var g=ctx.createLinearGradient(cx,cy-13,cx,cy+13);
g.addColorStop(0,'#8fe0a0');g.addColorStop(0.55,'#3fae62');g.addColorStop(1,'#175c34');
ctx.fillStyle=g;
ctx.beginPath();
ctx.moveTo(cx,cy-14);ctx.bezierCurveTo(cx+11,cy-10,cx+12,cy+8,cx+9,cy+13);
ctx.lineTo(cx-9,cy+13);ctx.bezierCurveTo(cx-12,cy+8,cx-11,cy-10,cx,cy-14);
ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(8,32,18,0.85)';ctx.lineWidth=1.5;ctx.stroke();
// hood shadow + kind eyes
ctx.fillStyle='rgba(6,22,12,0.8)';
ctx.beginPath();ctx.ellipse(cx,cy-6,5.5,4.5,0,0,6.284);ctx.fill();
var look=eyeOffset(e);
ctx.fillStyle='#a8ffd0';
ctx.beginPath();ctx.arc(cx-2+look.x,cy-6+look.y,1,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+2+look.x,cy-6+look.y,1,0,6.284);ctx.fill();
// glowing ankh sigil on the chest
var pulse=0.7+0.3*Math.sin(t*3+e.bobSeed);
ctx.strokeStyle='rgba(190,255,210,'+pulse+')';ctx.lineWidth=2;ctx.shadowColor='#7fffa8';ctx.shadowBlur=6;
ctx.beginPath();ctx.moveTo(cx,cy+1);ctx.lineTo(cx,cy+9);ctx.moveTo(cx-3,cy+4);ctx.lineTo(cx+3,cy+4);
ctx.moveTo(cx,cy-1.5);ctx.lineTo(cx,cy+1);ctx.stroke();
ctx.beginPath();ctx.ellipse(cx,cy-3.4,2.2,1.9,0,0,6.284);ctx.stroke();
ctx.shadowBlur=0;
// raised hands
ctx.fillStyle='#6cc88a';
ctx.beginPath();ctx.arc(cx-9,cy-1+Math.sin(t*3)*1.2,2.6,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+9,cy-1+Math.cos(t*3)*1.2,2.6,0,6.284);ctx.fill();
// healing motes drifting up
for(var i=0;i<3;i++){
var ph=(t*8+i*9+e.bobSeed*3)%18;
ctx.fillStyle='rgba(140,255,180,'+(0.5*(1-ph/18))+')';
ctx.beginPath();ctx.arc(cx-6+i*6,cy+10-ph,1.3,0,6.284);ctx.fill();
}
}
function drawPhaser(cx,cy,t,e){ // faceted crystal that fractures after each blink
var bob=Math.sin(t*2.6+e.bobSeed)*2;cy+=bob;
var recent=e.moveStart&&(nowMs()-e.moveStart)<240;
if(recent){ // fracture scatter
for(var i=0;i<5;i++){
var a=e.bobSeed+i*1.256+t*3;
ctx.fillStyle='rgba(120,250,255,0.5)';
ctx.beginPath();ctx.arc(cx+Math.cos(a)*13,cy+Math.sin(a)*13,1.4,0,6.284);ctx.fill();
}
}
var g=ctx.createLinearGradient(cx-9,cy-12,cx+9,cy+12);
g.addColorStop(0,'#c8fbff');g.addColorStop(0.5,'#3ee0e0');g.addColorStop(1,'#0e6a78');
ctx.fillStyle=g;
ctx.beginPath();
ctx.moveTo(cx,cy-14);ctx.lineTo(cx+9,cy-4);ctx.lineTo(cx+6,cy+12);ctx.lineTo(cx-6,cy+12);ctx.lineTo(cx-9,cy-4);
ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(6,40,48,0.9)';ctx.lineWidth=1.5;ctx.stroke();
// facet lines
ctx.strokeStyle='rgba(255,255,255,0.28)';ctx.lineWidth=1;
ctx.beginPath();ctx.moveTo(cx,cy-14);ctx.lineTo(cx,cy+12);ctx.moveTo(cx-9,cy-4);ctx.lineTo(cx+9,cy-4);
ctx.moveTo(cx-6,cy+12);ctx.lineTo(cx,cy-4);ctx.lineTo(cx+6,cy+12);ctx.stroke();
// inner glow
var ig=ctx.createRadialGradient(cx,cy-2,1,cx,cy,8);
ig.addColorStop(0,'rgba(230,255,255,0.75)');ig.addColorStop(1,'rgba(60,224,224,0)');
ctx.fillStyle=ig;ctx.fillRect(cx-9,cy-9,18,18);
var look=eyeOffset(e);
ctx.fillStyle='#083a44';
ctx.beginPath();ctx.arc(cx-3+look.x,cy-3+look.y,1.4,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+3+look.x,cy-3+look.y,1.4,0,6.284);ctx.fill();
if((e.cd||0)>0){ // recharge shimmer
ctx.strokeStyle='rgba(120,250,255,'+(0.3+0.2*Math.sin(t*8))+')';ctx.lineWidth=1.4;
ctx.beginPath();ctx.arc(cx,cy,17,0,6.284);ctx.stroke();
}
}
function drawTurret(cx,cy,t,e){ // bolted octagon base, swivel barrel, vent glow
var host=S.player.host===e;
var f=host?(FACING[S.player.facing]||FACING.down):(FACING[e.facing]||FACING.down);
var heat=Math.min(1,(e.shots||0)/3),hot=(e.overheatLeft||0)>0,i;
cy+=Math.sin(t*1.8+e.bobSeed)*0.6;
var g=ctx.createLinearGradient(cx-12,cy-12,cx+12,cy+12);
g.addColorStop(0,'#c3cad6');g.addColorStop(0.5,'#79828f');g.addColorStop(1,'#3c424c');
ctx.fillStyle=g;
ctx.beginPath();
for(i=0;i<8;i++){var a=Math.PI/8+i*Math.PI/4;i?ctx.lineTo(cx+Math.cos(a)*12,cy+Math.sin(a)*12):ctx.moveTo(cx+Math.cos(a)*12,cy+Math.sin(a)*12);}
ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(12,14,20,0.9)';ctx.lineWidth=1.6;ctx.stroke();
// bolts
ctx.fillStyle='#2c3138';
for(i=0;i<8;i++){var ba=Math.PI/8+i*Math.PI/4;
ctx.beginPath();ctx.arc(cx+Math.cos(ba)*8.5,cy+Math.sin(ba)*8.5,1.1,0,6.284);ctx.fill();}
// swivel mount
var mg=ctx.createRadialGradient(cx-2,cy-3,1,cx,cy,7);
mg.addColorStop(0,'#aeb6c2');mg.addColorStop(1,'#4a505a');
ctx.fillStyle=mg;ctx.beginPath();ctx.arc(cx,cy,6,0,6.284);ctx.fill();
// barrel tracks facing
ctx.save();ctx.translate(cx,cy);ctx.rotate(Math.atan2(f[1],f[0]));
var bg=ctx.createLinearGradient(2,0,16,0);
bg.addColorStop(0,'#565e6a');bg.addColorStop(1,'#20242c');
ctx.fillStyle=bg;rrect(ctx,2,-3,14,6,2);ctx.fill();
ctx.strokeStyle='rgba(10,12,16,0.9)';ctx.lineWidth=1.2;rrect(ctx,2,-3,14,6,2);ctx.stroke();
ctx.fillStyle='#14171d';rrect(ctx,13,-2,4,4,1);ctx.fill();
ctx.restore();
// cooling vents glow red toward overheat
var glow=0.25+(hot?0.55:0.5*heat)+0.15*Math.sin(t*9);
ctx.fillStyle='rgba(255,'+(hot?120:90+heat*100|0)+',70,'+glow+')';
ctx.beginPath();ctx.arc(cx-8,cy+7,2,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+8,cy+7,2,0,6.284);ctx.fill();
if(hot){ // venting steam
ctx.fillStyle='rgba(255,160,120,'+(0.2+0.15*Math.sin(t*8))+')';
ctx.beginPath();ctx.arc(cx,cy-14,3+Math.sin(t*6),0,6.284);ctx.fill();
}
}
function drawCharger(cx,cy,t,e){ // coiled beast, horn crest, telegraph flash
var host=S.player.host===e;
var f=host?(FACING[S.player.facing]||FACING.down):(FACING[e.facing]||FACING.down);
var px=-f[1],py=f[0],i;
// coiled hind segments
for(i=2;i>=0;i--){
var hx=cx-f[0]*(6+i*5),hy=cy-f[1]*(6+i*5);
var rg=ctx.createRadialGradient(hx-2,hy-2,1,hx,hy,7-i*0.8);
rg.addColorStop(0,'#ffe98a');rg.addColorStop(0.6,'#e0b22c');rg.addColorStop(1,'#7a5a0a');
ctx.fillStyle=rg;
ctx.beginPath();ctx.ellipse(hx,hy,7-i*0.8,6-i*0.8,0,0,6.284);ctx.fill();
ctx.strokeStyle='rgba(60,44,6,0.8)';ctx.lineWidth=1;ctx.stroke();
}
// head
var hg=ctx.createLinearGradient(cx-f[0]*8,cy-f[1]*8,cx+f[0]*8,cy+f[1]*8);
hg.addColorStop(0,'#ffe98a');hg.addColorStop(0.55,'#f2d23c');hg.addColorStop(1,'#8a6a0e');
ctx.fillStyle=hg;
ctx.beginPath();ctx.ellipse(cx,cy,9,7.5,Math.atan2(f[1],f[0]),0,6.284);ctx.fill();
ctx.strokeStyle='rgba(60,44,6,0.9)';ctx.lineWidth=1.5;ctx.stroke();
// forward horn / arrow crest
ctx.fillStyle='#f8f0c8';
ctx.beginPath();ctx.moveTo(cx+f[0]*6,cy+f[1]*6);
ctx.lineTo(cx+f[0]*15+px*3,cy+f[1]*15+py*3);ctx.lineTo(cx+f[0]*15-px*3,cy+f[1]*15-py*3);
ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(90,70,10,0.7)';ctx.lineWidth=1;ctx.stroke();
// eyes
var look=eyeOffset(e);
ctx.fillStyle='#3a2c04';
ctx.beginPath();ctx.arc(cx+f[0]*3+px*3.5+look.x*0.6,cy+f[1]*3+py*3.5+look.y*0.6,1.5,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+f[0]*3-px*3.5+look.x*0.6,cy+f[1]*3-py*3.5+look.y*0.6,1.5,0,6.284);ctx.fill();
if(e.telegraph){ // white telegraph flash + stomp windup
var fl=0.35+0.3*Math.sin(t*18);
ctx.globalAlpha=fl;ctx.fillStyle='#fff';
ctx.beginPath();ctx.ellipse(cx,cy,13,10,0,0,6.284);ctx.fill();ctx.globalAlpha=1;
ctx.fillStyle='rgba(255,240,180,0.5)';
ctx.beginPath();ctx.arc(cx-px*10,cy-py*10+Math.sin(t*20)*2,1.8,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+px*10,cy+py*10-Math.sin(t*20)*2,1.8,0,6.284);ctx.fill();
}
}
function drawSiren(cx,cy,t,e){ // hollow orb with pulsing lure rings
var i;cy+=Math.sin(t*1.9+e.bobSeed)*2.4;
// trailing wisps
for(i=0;i<4;i++){
var a=e.bobSeed+i*1.57+t*1.2;
ctx.fillStyle='rgba(246,150,214,'+(0.25+0.15*Math.sin(t*3+i))+')';
ctx.beginPath();ctx.arc(cx+Math.cos(a)*11,cy+Math.sin(a)*11+Math.sin(t*4+i)*2,2,0,6.284);ctx.fill();
}
// concentric lure rings pulsing outward
for(i=3;i>=1;i--){
var rp=(t*0.9+i*0.33)%1;
ctx.strokeStyle='rgba(246,150,214,'+(0.55*(1-rp))+')';ctx.lineWidth=1.6;
ctx.beginPath();ctx.arc(cx,cy,4+rp*14,0,6.284);ctx.stroke();
}
// hollow orb body
var g=ctx.createRadialGradient(cx,cy,3,cx,cy,11);
g.addColorStop(0,'rgba(30,4,26,0.95)');g.addColorStop(0.7,'#c04898');g.addColorStop(1,'#ff9ad8');
ctx.fillStyle=g;
ctx.beginPath();ctx.arc(cx,cy,10,0,6.284);ctx.fill();
ctx.strokeStyle='rgba(60,8,48,0.9)';ctx.lineWidth=1.5;ctx.stroke();
var cg=ctx.createRadialGradient(cx,cy,0.5,cx,cy,5);
cg.addColorStop(0,'rgba(255,230,248,0.95)');cg.addColorStop(0.5,'rgba(255,140,210,0.5)');cg.addColorStop(1,'rgba(255,140,210,0)');
ctx.fillStyle=cg;ctx.fillRect(cx-6,cy-6,12,12);
ctx.fillStyle='#1a0416';ctx.beginPath();ctx.arc(cx,cy,2.6,0,6.284);ctx.fill();
var look=eyeOffset(e);
ctx.fillStyle='#ffd8f0';
ctx.beginPath();ctx.arc(cx-4+look.x,cy-5+look.y,1.2,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+4+look.x,cy-5+look.y,1.2,0,6.284);ctx.fill();
}
function drawMimic(cx,cy,t,e){ // ornate chest that splits into a fanged maw
if(!e.revealed){ // treasure chest disguise
var g=ctx.createLinearGradient(cx,cy-10,cx,cy+12);
g.addColorStop(0,'#8a5f2e');g.addColorStop(0.55,'#6b4420');g.addColorStop(1,'#3c2410');
ctx.fillStyle=g;rrect(ctx,cx-12,cy-6,24,17,3);ctx.fill();
var lg=ctx.createLinearGradient(cx,cy-12,cx,cy-4);
lg.addColorStop(0,'#a87840');lg.addColorStop(1,'#5c3a18');
ctx.fillStyle=lg;rrect(ctx,cx-12,cy-11,24,7,3);ctx.fill();
ctx.strokeStyle='rgba(20,10,4,0.85)';ctx.lineWidth=1.4;
rrect(ctx,cx-12,cy-6,24,17,3);ctx.stroke();rrect(ctx,cx-12,cy-11,24,7,3);ctx.stroke();
// gold bands + lock
ctx.fillStyle='#d8a83c';
ctx.fillRect(cx-12,cy-6,24,2);ctx.fillRect(cx-8,cy-11,2.4,17);ctx.fillRect(cx+5.6,cy-11,2.4,17);
var lock=ctx.createRadialGradient(cx-1,cy-4,0.5,cx,cy-3,3.5);
lock.addColorStop(0,'#ffe9a0');lock.addColorStop(1,'#8a6410');
ctx.fillStyle=lock;rrect(ctx,cx-3,cy-6,6,7,2);ctx.fill();
ctx.fillStyle='#3a2408';ctx.beginPath();ctx.arc(cx,cy-3,1.2,0,6.284);ctx.fill();
// wood grain
ctx.strokeStyle='rgba(30,16,6,0.4)';ctx.lineWidth=1;
ctx.beginPath();ctx.moveTo(cx-10,cy+3);ctx.lineTo(cx+10,cy+3);ctx.moveTo(cx-10,cy+7);ctx.lineTo(cx+10,cy+7);ctx.stroke();
return;
}
// revealed: split maw with fangs and a lolling tongue
var g2=ctx.createLinearGradient(cx,cy-13,cx,cy+12);
g2.addColorStop(0,'#c89a3c');g2.addColorStop(0.55,'#8a6414');g2.addColorStop(1,'#3c2a06');
ctx.fillStyle=g2;
ctx.beginPath();ctx.moveTo(cx-13,cy-6);ctx.lineTo(cx+13,cy-6);ctx.lineTo(cx+9,cy-13);ctx.lineTo(cx-9,cy-13);ctx.closePath();ctx.fill();
rrect(ctx,cx-13,cy+2,26,9,3);ctx.fill();
ctx.strokeStyle='rgba(20,10,2,0.9)';ctx.lineWidth=1.4;ctx.stroke();
var i;
ctx.fillStyle='#f4ecd8';
for(i=-2;i<=2;i++){
ctx.beginPath();ctx.moveTo(cx+i*5-2,cy-6);ctx.lineTo(cx+i*5+2,cy-6);ctx.lineTo(cx+i*5,cy-1+Math.sin(t*6+i));ctx.closePath();ctx.fill();
ctx.beginPath();ctx.moveTo(cx+i*5-2,cy+4);ctx.lineTo(cx+i*5+2,cy+4);ctx.lineTo(cx+i*5,cy+8);ctx.closePath();ctx.fill();
}
ctx.fillStyle='#d05878';
ctx.beginPath();ctx.ellipse(cx+Math.sin(t*4)*2,cy+6,4,2.4,0.3,0,6.284);ctx.fill();
var look=eyeOffset(e);
ctx.fillStyle='#ffde7a';
ctx.beginPath();ctx.arc(cx-6,cy-11+look.y,1.5,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx+6,cy-11+look.y,1.5,0,6.284);ctx.fill();
}
function drawLeech(cx,cy,t,e){ // bulbous segmented sucker
var host=S.player.host===e;
var dir=host?(FACING[S.player.facing]||FACING.down):(FACING[e.facing]||FACING.down);
var squish=Math.sin(t*2.6+e.bobSeed)*0.08,i;
var px=-dir[1],py=dir[0];
var segs=[[0,9,7.5],[4.5,7,6],[8,5,4.6],[10.5,3.2,3]];
for(i=segs.length-1;i>=0;i--){
var sx=cx-dir[0]*segs[i][0],sy=cy-dir[1]*segs[i][1];
var g=ctx.createRadialGradient(sx-2,sy-2,1,sx,sy,segs[i][1]);
g.addColorStop(0,'#b078e8');g.addColorStop(0.55,'#8a4fd0');g.addColorStop(1,'#3c1860');
ctx.fillStyle=g;
ctx.beginPath();ctx.ellipse(sx,sy,segs[i][1]*(1+squish),segs[i][2]*(1-squish),0,0,6.284);ctx.fill();
ctx.strokeStyle='rgba(20,6,36,0.8)';ctx.lineWidth=1;ctx.stroke();
}
// sucker maw toward facing
var mx=cx+dir[0]*4,my=cy+dir[1]*4;
var mg=ctx.createRadialGradient(mx,my,1,mx,my,7);
mg.addColorStop(0,'#2a0a3c');mg.addColorStop(0.6,'#5a2a8a');mg.addColorStop(1,'#8a4fd0');
ctx.fillStyle=mg;ctx.beginPath();ctx.arc(mx,my,6.5,0,6.284);ctx.fill();
ctx.strokeStyle='rgba(20,6,36,0.9)';ctx.lineWidth=1.4;ctx.stroke();
ctx.fillStyle='#1a0426';ctx.beginPath();ctx.arc(mx+dir[0]*1.5,my+dir[1]*1.5,3,0,6.284);ctx.fill();
// ring of teeth slowly rotating
ctx.fillStyle='#e8d8f4';
for(i=0;i<6;i++){var a=i*1.047+t*0.6;
ctx.beginPath();ctx.moveTo(mx+Math.cos(a)*6,my+Math.sin(a)*6);
ctx.lineTo(mx+Math.cos(a+0.3)*6,my+Math.sin(a+0.3)*6);
ctx.lineTo(mx+Math.cos(a+0.15)*3.6,my+Math.sin(a+0.15)*3.6);ctx.closePath();ctx.fill();}
// glossy wet highlight + drip
ctx.fillStyle='rgba(255,255,255,0.25)';
ctx.beginPath();ctx.ellipse(cx-3,cy-3,4,2.2,-0.5,0,6.284);ctx.fill();
ctx.fillStyle='rgba(200,90,160,'+(0.3+0.2*Math.sin(t*4))+')';
ctx.beginPath();ctx.arc(cx-dir[0]*11,cy-dir[1]*11+((t*10)%6),1.2,0,6.284);ctx.fill();
var look=eyeOffset(e);
ctx.fillStyle='#ffd0f0';
ctx.beginPath();ctx.arc(cx+px*3-2+look.x*0.5,cy+py*3-3+look.y*0.5,1.1,0,6.284);ctx.fill();
ctx.beginPath();ctx.arc(cx-px*3-2+look.x*0.5,cy-py*3-3+look.y*0.5,1.1,0,6.284);ctx.fill();
}
function drawEnemySprite(e,t){
var f=e.moveStart?clamp((nowMs()-e.moveStart)/MOVE_MS,0,1):1;
var rx=lerp(e.fromX,e.x,easeOut(f)),ry=lerp(e.fromY,e.y,easeOut(f));
var cx=rx*T+16,cy=ry*T+16+Math.sin(t*2+e.bobSeed)*1.6;
// soft shadow
ctx.fillStyle='rgba(0,0,0,0.32)';
ctx.beginPath();ctx.ellipse(cx,ry*T+28,10,3.5,0,0,6.284);ctx.fill();
// possession aura on your current body
if(S.player.host===e){
var ag=ctx.createRadialGradient(cx,cy,4,cx,cy,26);
ag.addColorStop(0,'rgba(120,240,255,0.28)');ag.addColorStop(1,'rgba(120,240,255,0)');
ctx.fillStyle=ag;ctx.fillRect(cx-28,cy-28,56,56);
ctx.strokeStyle='rgba(140,250,255,'+(0.45+0.3*Math.sin(t*4))+')';ctx.lineWidth=1.5;
ctx.beginPath();ctx.arc(cx,cy+2,19,0,6.284);ctx.stroke();
}
if(e.type==='Brute')drawBrute(cx,cy,t,e);
else if(e.type==='Skitterer')drawSkitterer(cx,cy,t,e);
else if(e.type==='Sentinel')drawSentinel(cx,cy,t,e);
else if(e.type==='Shielder')drawShielder(cx,cy,t,e);
else if(e.type==='Bomber')drawBomber(cx,cy,t,e);
else if(e.type==='Healer')drawHealer(cx,cy,t,e);
else if(e.type==='Phaser')drawPhaser(cx,cy,t,e);
else if(e.type==='Turret')drawTurret(cx,cy,t,e);
else if(e.type==='Charger')drawCharger(cx,cy,t,e);
else if(e.type==='Siren')drawSiren(cx,cy,t,e);
else if(e.type==='Mimic')drawMimic(cx,cy,t,e);
else if(e.type==='Leech')drawLeech(cx,cy,t,e);
if(e.hitFlash>0){ // hit flash ~100ms
ctx.globalAlpha=Math.min(0.65,e.hitFlash);ctx.fillStyle='#fff';
rrect(ctx,cx-11,cy-12,22,24,7);ctx.fill();ctx.globalAlpha=1;
e.hitFlash*=0.85;if(e.hitFlash<0.02)e.hitFlash=0;
}
if((e.lockout||0)>0){ // dazed after being abandoned
ctx.fillStyle='rgba(10,14,30,0.45)';rrect(ctx,cx-11,cy-12,22,24,7);ctx.fill();
ctx.fillStyle='#9fd8ff';ctx.font='bold 10px Georgia,serif';ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillText('dazed',cx,cy-15);
}
if(e.aggro){ // subtle red aggro pip
ctx.fillStyle='rgba(255,90,80,'+(0.5+0.4*Math.sin(t*6))+')';
ctx.beginPath();ctx.arc(cx,cy-17,2,0,6.284);ctx.fill();
}
}
function drawParticles(){
for(var i=0;i<S.particles.length;i++){
var q=S.particles[i],a=q.life/q.max;
if(q.txt){ // floating damage number
ctx.fillStyle='rgba(255,170,170,'+Math.min(1,a+0.2)+')';
ctx.font='bold 12px Georgia,serif';ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillText(q.txt,q.x,q.y-HUD_H);
}else{
ctx.fillStyle='rgba('+q.c+','+(a*0.55)+')';
ctx.beginPath();ctx.arc(q.x,q.y-HUD_H,q.r*a+0.5,0,6.284);ctx.fill();
}
}
}
function drawWorld(t){
// tiles
for(var y=0;y<H;y++)for(var x=0;x<W;x++){
if(!S.explored[y][x])continue;
if(S.grid[y][x]===1)drawWallTile(x,y);
else if(S.grid[y][x]===3)drawExitTile(x,y,t);
else if(S.grid[y][x]===2)drawDoorTile(x,y);
else drawFloorTile(x,y);
}
// faint grid structure over floors
ctx.strokeStyle='rgba(255,255,255,0.02)';ctx.lineWidth=1;
ctx.beginPath();
for(var gx=0;gx<=W;gx++){ctx.moveTo(gx*T,0);ctx.lineTo(gx*T,H*T);}
for(var gy=0;gy<=H;gy++){ctx.moveTo(0,gy*T);ctx.lineTo(W*T,gy*T);}
ctx.stroke();
// enemies
for(var j=0;j<S.enemies.length;j++)drawEnemySprite(S.enemies[j],t);
// projectiles (enemy volleys + your own)
for(var pj=0;pj<S.projectiles.length;pj++){
var pr=S.projectiles[pj],pcx=pr.x*T+16,pcy=pr.y*T+16;
var pc=pr.own?'120,240,255':'200,140,255';
var pgr=ctx.createRadialGradient(pcx,pcy,0.5,pcx,pcy,7);
pgr.addColorStop(0,'rgba(255,255,255,0.95)');pgr.addColorStop(0.4,'rgba('+pc+',0.8)');pgr.addColorStop(1,'rgba('+pc+',0)');
ctx.fillStyle=pgr;ctx.fillRect(pcx-8,pcy-8,16,16);
ctx.strokeStyle='rgba('+pc+',0.5)';ctx.lineWidth=2;
ctx.beginPath();ctx.moveTo(pcx-pr.dx*7,pcy-pr.dy*7);ctx.lineTo(pcx,pcy);ctx.stroke();
}
// player: full ghost, or your spirit riding the host
var pos=playerRenderPos(t);
if(S.player.ghost)drawGhost(t,pos.cx,pos.cy,true);
else drawGhost(t,pos.cx,pos.cy-22,false,0.5);
drawParticles();
// warm torch grading around player
var wg=ctx.createRadialGradient(pos.cx,pos.cy,10,pos.cx,pos.cy,T*6);
wg.addColorStop(0,'rgba(255,175,90,0.07)');wg.addColorStop(1,'rgba(255,150,70,0)');
ctx.fillStyle=wg;ctx.fillRect(0,0,W*T,H*T);
drawFog(pos);
if(S.upgrades.meta>=2){ // Meta T2 Farsight: sense enemy types through the fog
for(var m=0;m<S.enemies.length;m++){
var en=S.enemies[m];
if(Math.abs(en.x-S.player.x)+Math.abs(en.y-S.player.y)<=VIEW_R)continue;
if(!S.explored[en.y]||!S.explored[en.y][en.x])continue;
var defn=null;for(var bi=0;bi<BESTIARY.length;bi++)if(BESTIARY[bi].n===en.type)defn=BESTIARY[bi];
if(!defn)continue;
ctx.globalAlpha=0.8;ctx.fillStyle=defn.c;ctx.font='bold 13px Georgia,serif';ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillText(defn.n.charAt(0),px(en.x)+16,px(en.y)+16);
ctx.globalAlpha=1;
}
}
// vignette
var vg=ctx.createRadialGradient(W*T/2,H*T/2,H*T*0.35,W*T/2,H*T/2,W*T*0.72);
vg.addColorStop(0,'rgba(0,0,0,0)');vg.addColorStop(1,'rgba(0,0,0,0.45)');
ctx.fillStyle=vg;ctx.fillRect(0,0,W*T,H*T);
}
function drawFog(pos){
var p=S.player,rr=VIEW_R*VIEW_R,i,x,y;
for(y=0;y<H;y++)for(x=0;x<W;x++){
var dx=x-p.x,dy=y-p.y,d=dx*dx+dy*dy;
if(d<=rr)continue; // visible
if(!S.explored[y][x]){ctx.fillStyle='#04050a';ctx.fillRect(px(x),px(y),T,T);} // unexplored: hidden
else{ctx.fillStyle='rgba(16,24,44,0.72)';ctx.fillRect(px(x),px(y),T,T);} // explored memory tint
}
// soft gradient falloff at the sight edge
var g=ctx.createRadialGradient(pos.cx,pos.cy,T*3.4,pos.cx,pos.cy,T*6.4);
g.addColorStop(0,'rgba(4,5,10,0)');g.addColorStop(1,'rgba(4,5,10,0.55)');
ctx.fillStyle=g;ctx.fillRect(0,0,W*T,H*T);
}
/* ============ UI panels ============ */
function panel(x,y,w,h,border){
ctx.fillStyle='rgba(12,14,24,0.92)';
rrect(ctx,x,y,w,h,10);ctx.fill();
var g=ctx.createLinearGradient(x,y,x,y+h);
g.addColorStop(0,'rgba(255,255,255,0.05)');g.addColorStop(1,'rgba(255,255,255,0)');
ctx.fillStyle=g;rrect(ctx,x,y,w,h,10);ctx.fill();
ctx.strokeStyle=border||'rgba(110,200,255,0.4)';ctx.lineWidth=2;
rrect(ctx,x+1,y+1,w-2,h-2,9);ctx.stroke();
ctx.strokeStyle='rgba(0,0,0,0.6)';ctx.lineWidth=1;
rrect(ctx,x+3,y+3,w-6,h-6,8);ctx.stroke();
}
function keycap(x,y,label,w){
w=w||26;
ctx.fillStyle='#1b2030';
rrect(ctx,x,y,w,20,5);ctx.fill();
var g=ctx.createLinearGradient(x,y,x,y+20);
g.addColorStop(0,'rgba(255,255,255,0.16)');g.addColorStop(1,'rgba(255,255,255,0.02)');
ctx.fillStyle=g;rrect(ctx,x,y,w,20,5);ctx.fill();
ctx.strokeStyle='rgba(130,190,255,0.5)';ctx.lineWidth=1;
rrect(ctx,x+0.5,y+0.5,w-1,19,4.5);ctx.stroke();
ctx.fillStyle='#cfe6ff';ctx.font='bold 11px Georgia,serif';ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillText(label,x+w/2,y+10.5);
}
function drawHUD(t){
var g=ctx.createLinearGradient(0,0,0,HUD_H);
g.addColorStop(0,'#171826');g.addColorStop(1,'#101020');
ctx.fillStyle=g;ctx.fillRect(0,0,800,HUD_H);
var lg=ctx.createLinearGradient(0,0,800,0);
lg.addColorStop(0,'rgba(90,180,255,0)');lg.addColorStop(0.5,'rgba(90,180,255,0.55)');lg.addColorStop(1,'rgba(90,180,255,0)');
ctx.fillStyle=lg;ctx.fillRect(0,HUD_H-2,800,2);
var p=S.player,h=p.host;
// form + timer / hp
ctx.textAlign='left';ctx.textBaseline='middle';
if(p.ghost){
var frac=clamp(p.timer/ghostTime(),0,1);
ctx.fillStyle='#bfe8ff';ctx.font='bold 13px Georgia,serif';
ctx.fillText('GHOST FORM',14,18);
ctx.fillStyle='#232a3c';rrect(ctx,14,30,120,10,5);ctx.fill();
var tg=ctx.createLinearGradient(14,0,134,0);
var col=frac>0.5?'110,230,140':frac>0.25?'240,200,80':'240,90,80';
tg.addColorStop(0,'rgba('+col+',0.95)');tg.addColorStop(1,'rgba('+col+',0.6)');
ctx.fillStyle=tg;
if(p.timer>0){rrect(ctx,14,30,Math.max(6,120*frac),10,5);ctx.fill();}
ctx.fillStyle='#dfe9ff';ctx.font='bold 12px Georgia,serif';
ctx.fillText(Math.ceil(p.timer)+'s',142,35);
ctx.fillStyle='rgba(190,210,240,0.55)';ctx.font='11px Georgia,serif';
ctx.fillText('find a body before you fade',14,52);
}else{ // wearing a host: its name, its HP
var hf=clamp(h?h.hp/h.maxHp:0,0,1);
ctx.fillStyle='#ffd9a8';ctx.font='bold 13px Georgia,serif';
ctx.fillText('HOST: '+(h?h.type.toUpperCase():'?'),14,18);
ctx.fillStyle='#232a3c';rrect(ctx,14,30,120,10,5);ctx.fill();
var hg=ctx.createLinearGradient(14,0,134,0);
hg.addColorStop(0,'rgba(240,110,90,0.95)');hg.addColorStop(1,'rgba(240,180,90,0.7)');
ctx.fillStyle=hg;
if(hf>0){rrect(ctx,14,30,Math.max(6,120*hf),10,5);ctx.fill();}
ctx.fillStyle='#ffe3d0';ctx.font='bold 12px Georgia,serif';
ctx.fillText(h?(h.hp+'/'+h.maxHp+' HP'):'',142,35);
ctx.fillStyle='rgba(190,210,240,0.55)';ctx.font='11px Georgia,serif';
ctx.fillText('X - abandon this body',14,52);
}
// floor + essence
ctx.textAlign='center';
ctx.fillStyle='#8899c8';ctx.font='bold 11px Georgia,serif';
ctx.fillText('FLOOR',330,16);
ctx.fillStyle='#eaf2ff';ctx.font='bold 20px Georgia,serif';
ctx.fillText(String(S.floor),330,38);
ctx.fillStyle='rgba(150,170,205,0.7)';ctx.font='bold 9px Georgia,serif';
ctx.fillText('GHOST '+S.upgrades.ghost+' BODY '+S.upgrades.body+' META '+S.upgrades.meta,330,54); // owned upgrade tiers
// essence gem
var ex=395,ey=32;
var eg=ctx.createRadialGradient(ex-2,ey-3,1,ex,ey,11);
eg.addColorStop(0,'#b9f2ff');eg.addColorStop(0.5,'#54c8e8');eg.addColorStop(1,'#1f6f9e');
ctx.fillStyle=eg;
ctx.beginPath();ctx.moveTo(ex,ey-11);ctx.lineTo(ex+9,ey);ctx.lineTo(ex,ey+11);ctx.lineTo(ex-9,ey);ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(255,255,255,0.5)';ctx.lineWidth=1;ctx.stroke();
ctx.textAlign='left';ctx.fillStyle='#d8f4ff';ctx.font='bold 16px Georgia,serif';
ctx.fillText(String(S.essence),ex+16,33);
ctx.fillStyle='rgba(160,190,230,0.6)';ctx.font='10px Georgia,serif';
ctx.fillText('essence',ex+16,50);
// contextual SPACE hint (required on-HUD)
ctx.textAlign='right';
ctx.fillStyle='#9fd8ff';ctx.font='bold 12px Georgia,serif';
var hint=p.ghost?'SPACE: possess adjacent enemy (ghosts cannot attack)'
:(h?(HINTS[h.type]||'SPACE: host attack'):'SPACE: host attack');
ctx.fillText(hint,788,18);
ctx.fillStyle='rgba(170,190,220,0.65)';ctx.font='11px Georgia,serif';
ctx.fillText('L legend ESC pause',788,40);
ctx.fillStyle='rgba(170,190,220,0.45)';ctx.font='10px Georgia,serif';
ctx.fillText('WASD / arrows: move hold to glide Q / E: face',788,54);
}
function drawTitle(t){
// backdrop
var bg=ctx.createLinearGradient(0,0,0,640);
bg.addColorStop(0,'#0b0d1a');bg.addColorStop(1,'#060810');
ctx.fillStyle=bg;ctx.fillRect(0,0,800,640);
var vg=ctx.createRadialGradient(400,300,60,400,320,520);
vg.addColorStop(0,'rgba(70,120,220,0.14)');vg.addColorStop(1,'rgba(0,0,0,0.6)');
ctx.fillStyle=vg;ctx.fillRect(0,0,800,640);
// drifting ghost mascot
var gx=110+Math.sin(t*0.8)*10,gy=200+Math.sin(t*1.7)*14;
drawGhost(t,gx,gy,false);
// rune rings behind the title
ctx.strokeStyle='rgba(120,190,255,0.10)';ctx.lineWidth=2;
ctx.beginPath();ctx.ellipse(430,152,252,60,0,0,6.284);ctx.stroke();
ctx.strokeStyle='rgba(120,190,255,0.05)';ctx.lineWidth=7;
ctx.beginPath();ctx.ellipse(430,152,274,72,0,0,6.284);ctx.stroke();
// a few foes lurking on the right flank
drawBrute(716,306,t,{x:0,y:0,bobSeed:1.3,facing:'down',aggro:false});
drawSentinel(716,398,t,{x:0,y:0,bobSeed:4.1,facing:'down',aggro:false,shots:0,overheatLeft:0});
// drifting essence gems on the left
for(var gi=0;gi<3;gi++){
var gex=64+gi*26,gey=330+Math.sin(t*1.4+gi*2)*7;
var geg=ctx.createRadialGradient(gex-1,gey-2,0.5,gex,gey,7);
geg.addColorStop(0,'#b9f2ff');geg.addColorStop(0.5,'rgba(84,200,232,0.7)');geg.addColorStop(1,'rgba(31,111,158,0.15)');
ctx.fillStyle=geg;
ctx.beginPath();ctx.moveTo(gex,gey-7);ctx.lineTo(gex+6,gey);ctx.lineTo(gex,gey+7);ctx.lineTo(gex-6,gey);ctx.closePath();ctx.fill();
}
// title
ctx.textAlign='center';
var tg=ctx.createLinearGradient(0,120,0,180);
tg.addColorStop(0,'#dff4ff');tg.addColorStop(0.5,'#7fd4ff');tg.addColorStop(1,'#a07fe8');
ctx.fillStyle=tg;ctx.font='bold 52px Georgia,serif';
ctx.shadowColor='rgba(110,190,255,0.45)';ctx.shadowBlur=18;
ctx.fillText('BODY SNATCHER',430,158);
ctx.shadowBlur=0;
ctx.fillStyle='rgba(200,215,240,0.75)';ctx.font='italic 15px Georgia,serif';
ctx.fillText('Possess your enemies. Survive the descent.',430,190);
// controls panel (readable BEFORE play starts)
panel(240,224,440,238);
ctx.fillStyle='#8fd0ff';ctx.font='bold 13px Georgia,serif';ctx.textAlign='left';
ctx.fillText('CONTROLS',262,248);
var rows=[
['WASD / ARROWS','Move - hold to glide (ghosts cannot attack)',104],
['SPACE','Ghost: possess enemy Host: attack / special',74],
['Q / E','Rotate facing (Shielder, Turret...)',74],
['X','Abandon host - eject as ghost',74],
['ENTER','Start run / confirm choice',74],
['ESC','Pause (save + quit inside)']
];
for(var i=0;i<rows.length;i++){
var y=268+i*31,cw=rows[i][2]||74;
keycap(262,y,rows[i][0],cw);
ctx.fillStyle='#cdd8ec';ctx.font='12px Georgia,serif';ctx.textAlign='left';ctx.textBaseline='middle';
ctx.fillText(rows[i][1],272+cw,y+10);
}
// footer
ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillStyle='#ffe9a8';ctx.font='bold 14px Georgia,serif';
ctx.fillText('ENTER - descend into the dungeon',460,492);
if(hasSave()){ // save detected on load: offer Continue Y / N, never auto-start
ctx.fillStyle='#b8f0c8';ctx.font='bold 13px Georgia,serif';
ctx.fillText('Continue run? Y - yes, resume saved run N - no, start fresh',460,518);
}
ctx.fillStyle='#cfe2ff';ctx.font='bold 12px Georgia,serif';
ctx.fillText('L - enemy legend / bestiary'+(hasSave()?' C - continue saved run':''),460,543);
ctx.fillStyle='rgba(190,212,240,0.85)';ctx.font='11px Georgia,serif';
ctx.fillText('1 HP. No attack. Steal a body or fade away. achievements: '+achCount()+'/8',460,566);
}
function drawLegend(t){
ctx.fillStyle='rgba(3,4,9,0.82)';ctx.fillRect(0,0,800,640);
panel(18,14,764,596,'rgba(255,214,140,0.45)');
ctx.textAlign='center';
var tg=ctx.createLinearGradient(0,30,0,60);
tg.addColorStop(0,'#ffe9b0');tg.addColorStop(1,'#d0a24c');
ctx.fillStyle=tg;ctx.font='bold 22px Georgia,serif';
ctx.fillText('ENEMY LEGEND - each foe is a dual system: how it hunts you, and what you get when you possess it',400,42);
ctx.font='11px Georgia,serif';ctx.fillStyle='rgba(200,180,140,0.7)';
ctx.fillText('as an ENEMY it uses the top line - as your BODY you get the POSSESSED kit',400,60);
var colW=372,x0=34,y0=80;
for(var i=0;i<BESTIARY.length;i++){
var e=BESTIARY[i],cx=x0+(i%2)*colW,cy=y0+Math.floor(i/2)*81;
// entry card
ctx.fillStyle='rgba(20,24,40,0.85)';rrect(ctx,cx,cy,colW-14,74,7);ctx.fill();
ctx.strokeStyle='rgba(255,255,255,0.10)';ctx.lineWidth=1;rrect(ctx,cx+0.5,cy+0.5,colW-15,73,6.5);ctx.stroke();
// colored glyph
var g=ctx.createRadialGradient(cx+20,cy+18,2,cx+22,cy+20,15);
g.addColorStop(0,'rgba(255,255,255,0.45)');g.addColorStop(0.4,e.c);g.addColorStop(1,'rgba(0,0,0,0.6)');
ctx.fillStyle=g;
ctx.beginPath();ctx.moveTo(cx+22,cy+8);ctx.lineTo(cx+33,cy+20);ctx.lineTo(cx+22,cy+32);ctx.lineTo(cx+11,cy+20);ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(0,0,0,0.6)';ctx.stroke();
// name
ctx.textAlign='left';ctx.fillStyle=e.c;ctx.font='bold 13px Georgia,serif';
ctx.fillText(e.n,cx+42,cy+16);
ctx.fillStyle='#9aa8c8';ctx.font='10.5px Georgia,serif';
ctx.fillText('Enemy: '+e.ai,cx+42,cy+34);
ctx.fillStyle='#8fe0d8';
ctx.fillText('Possess: '+e.kit,cx+42,cy+52);
ctx.fillStyle='rgba(150,170,200,0.55)';ctx.font='9.5px Georgia,serif';
ctx.fillText('drops '+e.ess+' essence',cx+42,cy+67);
}
ctx.textAlign='center';ctx.fillStyle='#ffe9a8';ctx.font='bold 12px Georgia,serif';
ctx.fillText('L / ESC - close legend',400,612);
}
/* ============ shop screen ============ */
function wrapText(s,cx,y,maxW,lh){ // shop card description wrapping
var words=String(s).split(' '),line='';
for(var i=0;i<words.length;i++){
var test=line?line+' '+words[i]:words[i];
if(ctx.measureText(test).width>maxW&&line){ctx.fillText(line,cx,y);line=words[i];y+=lh;}
else line=test;
}
if(line)ctx.fillText(line,cx,y);
}
function drawShop(t){
ctx.fillStyle='rgba(3,4,9,0.8)';ctx.fillRect(0,0,800,640);
panel(66,104,668,412,'rgba(255,214,140,0.45)');
ctx.textAlign='center';ctx.textBaseline='middle';
var tg=ctx.createLinearGradient(0,120,0,152);
tg.addColorStop(0,'#ffe9b0');tg.addColorStop(1,'#d0a24c');
ctx.fillStyle=tg;ctx.font='bold 24px Georgia,serif';
ctx.fillText('THE BETWEEN-FLOOR SHRINE',400,136);
ctx.fillStyle='#9fd8ff';ctx.font='bold 13px Georgia,serif';
ctx.fillText('essence: '+S.essence+(S.upgrades.meta>=3?' (haggler prices: -30%)':''),400,164);
var ch=S.shopChoices||[],i;
if(!ch.length){
ctx.fillStyle='rgba(210,220,240,0.8)';ctx.font='14px Georgia,serif';
ctx.fillText('The shrine has nothing more to teach you.',400,300);
}
for(i=0;i<ch.length;i++){
var x=92+i*206,y=198,w=192,h=210,sel=i===(S.shopSel||0);
var g=ctx.createLinearGradient(x,y,x,y+h);
g.addColorStop(0,sel?'rgba(52,68,102,0.96)':'rgba(22,26,42,0.92)');g.addColorStop(1,'rgba(12,14,24,0.92)');
ctx.fillStyle=g;rrect(ctx,x,y,w,h,10);ctx.fill();
ctx.strokeStyle=sel?'rgba(140,250,255,0.85)':'rgba(255,255,255,0.12)';ctx.lineWidth=sel?2.5:1;
rrect(ctx,x+1,y+1,w-2,h-2,9);ctx.stroke();
ctx.fillStyle=ch[i].accent;ctx.font='bold 12px Georgia,serif';ctx.textAlign='center';
ctx.fillText(ch[i].short,x+w/2,y+22);
ctx.fillStyle='#e8eefc';ctx.font='bold 14px Georgia,serif';
ctx.fillText(ch[i].name,x+w/2,y+46);
ctx.fillStyle='rgba(200,212,235,0.85)';ctx.font='11.5px Georgia,serif';
wrapText(ch[i].desc,x+w/2,y+76,w-26,15);
var price=shopPrice(ch[i]),can=S.essence>=price;
ctx.fillStyle=can?'#9fffc4':'#ff9d94';ctx.font='bold 16px Georgia,serif';
ctx.fillText(price+' essence',x+w/2,y+h-28);
}
ctx.textAlign='center';ctx.fillStyle='#ffe9a8';ctx.font='bold 12px Georgia,serif';
ctx.fillText('A / D or \u25c0 \u25b6 - choose ENTER - buy X / ESC - '+(S.shopAfterExit?'skip and descend':'leave the shrine'),400,488);
}
function drawPause(){
ctx.fillStyle='rgba(3,4,9,0.7)';ctx.fillRect(0,0,800,640);
panel(238,222,324,196);
var tg=ctx.createLinearGradient(0,246,0,276);
tg.addColorStop(0,'#e6f2ff');tg.addColorStop(1,'#7fb4e8');
ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillStyle=tg;ctx.font='bold 26px Georgia,serif';
ctx.shadowColor='rgba(120,190,255,0.4)';ctx.shadowBlur=10;
ctx.fillText('PAUSED',400,258);ctx.shadowBlur=0;
keycap(312,288,'ESC',36);keycap(356,'ENTER',60);keycap(424,'L',26);
ctx.fillStyle='#cdd8ec';ctx.font='12px Georgia,serif';ctx.textAlign='left';
ctx.fillText('resume',296,330);ctx.fillText('save + quit to title',344,330);ctx.fillText('legend',460,330);
// achievement medal strip
var n=achCount(),mx=400,my=372;
var mg=ctx.createRadialGradient(mx,my,2,mx,my,26);
mg.addColorStop(0,'rgba(255,232,160,0.5)');mg.addColorStop(1,'rgba(255,200,90,0)');
ctx.fillStyle=mg;ctx.fillRect(mx-28,my-28,56,56);
var cup=ctx.createLinearGradient(mx-7,my-9,mx+7,my+9);
cup.addColorStop(0,'#ffe9a0');cup.addColorStop(1,'#b07c1c');
ctx.fillStyle=cup;
ctx.beginPath();ctx.moveTo(mx-7,my-9);ctx.lineTo(mx+7,my-9);ctx.lineTo(mx+5,my+1);
ctx.quadraticCurveTo(mx,my+7,mx,my+7);ctx.quadraticCurveTo(mx,my+7,mx-5,my+1);
ctx.closePath();ctx.fill();
ctx.strokeStyle='rgba(90,60,10,0.8)';ctx.lineWidth=1;ctx.stroke();
ctx.fillStyle='#d8a83c';ctx.fillRect(mx-1.5,my+6,3,5);ctx.fillRect(mx-5,my+11,10,2.5);
ctx.textAlign='center';ctx.fillStyle='#e8d9a8';ctx.font='bold 12px Georgia,serif';
ctx.fillText(n+' / 8 achievements',mx,my+27);
}
function drawToast(){ // achievement unlock banner
if(!S.toastTxt||nowMs()>=S.toastUntil)return;
var left=S.toastUntil-nowMs(),a=left<600?left/600:1;
ctx.save();ctx.globalAlpha=a;
panel(452,6,336,46,'rgba(255,220,140,0.55)');
var gx=474,gy=30;
var mg=ctx.createRadialGradient(gx,gy,2,gx,gy,20);
mg.addColorStop(0,'rgba(255,232,160,0.55)');mg.addColorStop(1,'rgba(255,200,90,0)');
ctx.fillStyle=mg;ctx.fillRect(gx-22,gy-22,44,44);
var cup=ctx.createLinearGradient(gx-6,gy-8,gx+6,gy+8);
cup.addColorStop(0,'#ffe9a0');cup.addColorStop(1,'#b07c1c');
ctx.fillStyle=cup;
ctx.beginPath();ctx.moveTo(gx-6,gy-8);ctx.lineTo(gx+6,gy-8);ctx.lineTo(gx+4,gy);
ctx.quadraticCurveTo(gx,gy+6,gx,gy+6);ctx.quadraticCurveTo(gx,gy+6,gx-4,gy);
ctx.closePath();ctx.fill();
ctx.fillStyle='#d8a83c';ctx.fillRect(gx-1.5,gy+5,3,4);ctx.fillRect(gx-4,gy+9,8,2);
ctx.textAlign='left';ctx.textBaseline='middle';
ctx.fillStyle='#d8c088';ctx.font='bold 9px Georgia,serif';
ctx.fillText('ACHIEVEMENT UNLOCKED',494,18);
ctx.fillStyle='#ffeeb8';ctx.font='bold 14px Georgia,serif';
ctx.fillText(S.toastTxt,494,36);
ctx.restore();
}
function drawEnd(won){
ctx.fillStyle='rgba(3,4,9,0.85)';ctx.fillRect(0,0,800,640);
panel(210,196,380,242,won?'rgba(140,255,190,0.5)':'rgba(255,120,110,0.5)');
// emblem: glowing gate (won) or fading ghost (lost)
var ex=400,ey=248;
var eg=ctx.createRadialGradient(ex,ey,3,ex,ey,34);
eg.addColorStop(0,won?'rgba(120,255,180,0.4)':'rgba(150,190,255,0.3)');eg.addColorStop(1,'rgba(0,0,0,0)');
ctx.fillStyle=eg;ctx.fillRect(ex-36,ey-36,72,72);
if(won){ // rune gate
var gg=ctx.createLinearGradient(ex-12,ey-14,ex+12,ey+14);
gg.addColorStop(0,'#a8ffe0');gg.addColorStop(1,'#2c9e78');
ctx.strokeStyle=gg;ctx.lineWidth=3;
ctx.beginPath();ctx.ellipse(ex,ey,13,17,0,0,6.284);ctx.stroke();
ctx.strokeStyle='rgba(180,255,220,0.8)';ctx.lineWidth=1.5;
ctx.beginPath();ctx.moveTo(ex-6,ey-8);ctx.lineTo(ex+2,ey-2);ctx.lineTo(ex-3,ey+3);ctx.lineTo(ex+5,ey+9);ctx.stroke();
}else drawGhost(nowMs()/1000,ex,ey+4,false,0.85);
ctx.textAlign='center';ctx.textBaseline='middle';
var tg=ctx.createLinearGradient(0,278,0,306);
tg.addColorStop(0,won?'#d8ffe8':'#ffd9d4');tg.addColorStop(1,won?'#5ce0a0':'#e07060');
ctx.fillStyle=tg;ctx.font='bold 29px Georgia,serif';
ctx.shadowColor=won?'rgba(120,255,180,0.5)':'rgba(255,120,110,0.4)';ctx.shadowBlur=12;
ctx.fillText(won?'YOU ESCAPED':'YOU FADED AWAY',400,296);ctx.shadowBlur=0;
ctx.fillStyle='rgba(210,220,240,0.85)';ctx.font='14px Georgia,serif';
ctx.fillText('Floor reached: '+S.floor,400,332);
ctx.fillText('Essence gathered: '+S.essence,400,354);
ctx.fillText('Achievements: '+achCount()+' / 8',400,376);
keycap(352,398,'ENTER',60);
ctx.fillStyle='#ffe9a8';ctx.font='bold 12px Georgia,serif';
ctx.fillText('return to title',400,428);
}
function render(){
var t=nowMs()/1000;
try{
ctx.fillStyle=C;ctx.fillRect(0,0,800,640);
if(S.state==='title'){drawTitle(t);if(S.legend)drawLegend(t);return;}
ctx.save();
if(S.shake>0.1){ // screen shake scaled to intensity
ctx.translate((Math.random()-0.5)*S.shake*2,(Math.random()-0.5)*S.shake*2);
S.shake*=0.85;
}else S.shake=0;
ctx.translate(0,HUD_H);
drawWorld(t);
ctx.restore();
drawHUD(t);
drawToast();
if(S.state==='paused')drawPause();
if(S.state==='shop')drawShop(t);
if(S.state==='lost')drawEnd(false);
if(S.state==='won')drawEnd(true);
if(S.legend)drawLegend(t);
}catch(e){/* rendering must never break game state */}
}
/* ============ public API ============ */
var GAME={
get state(){return S.state;},set state(v){setState(String(v));},
get player(){return S.player;},
get enemies(){return S.enemies;},
get grid(){return S.grid;},
get floor(){return S.floor;},
get essence(){return S.essence;},set essence(v){S.essence=Number(v)||0;},
get upgrades(){return S.upgrades;},
get achievements(){return S.achievements;},
get projectiles(){return S.projectiles;},
get log(){return S.log;},
start:function(){S.legend=false;buildDungeon();S.player.timer=15;placeGhostAtSpawn();setState('title');return true;},
input:input,
tick:tick,
spawn:spawn,
newRun:newRun,
setFloor:setFloor,
openShop:function(){openShop(false);return true;},
buy:buy,
save:save,
load:load
};
window.GAME=GAME;
/* ============ boot: title screen only, never auto-start play ============ */
GAME.start();
try{
document.addEventListener('keydown',function(ev){
var k=ev.key;
if(k===' ')k='Space';
if(k&&k.length===1&&k!==k.toLowerCase())k=k.toLowerCase();
if(k==='Space'||k.indexOf('Arrow')===0)initAudio();
if(DIRS[k])held[k]=true;
input(k);
if(k==='Space'||k.indexOf('Arrow')===0)ev.preventDefault();
});
document.addEventListener('keyup',function(ev){
var k=ev.key==null?'':String(ev.key);
if(k===' ')k='Space';
if(k&&k.length===1&&k!==k.toLowerCase())k=k.toLowerCase();
delete held[k];
});
}catch(e){}
// live presentation loop: visuals, hold-to-move repeat, and a brisk real-time turn cadence
// (core state stays deterministic through tick(); this loop only CALLS tick)
try{
setInterval(function(){
if(S.state==='playing'||S.state==='possessed')tick(1);
},STEP_MS);
}catch(e){}
(function loop(){
render();
// hold-to-move: repeat the held direction at turn cadence
var p=S.player,now=nowMs();
if((S.state==='playing'||S.state==='possessed')&&now-p.moveStart>Math.max(MOVE_MS,110)){
var ks=['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','w','a','s','d'];
for(var i=0;i<ks.length;i++){if(held[ks[i]]){tryMove(DIRS[ks[i]][0],DIRS[ks[i]][1]);break;}}
}
if(typeof window.requestAnimationFrame==='function'){try{window.requestAnimationFrame(loop);}catch(e){}}
})();
})();
</script>
</body>
</html>