<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Caveman Engine — Editor</title>
<style>
  :root{ --orange:#e0552b; --panel:#1c1c28; --panel2:#24243440; --line:#33334a; --txt:#dcdce6; --mut:#8a8aa0; }
  *{ box-sizing:border-box; }
  body{ margin:0; height:100vh; overflow:hidden; background:#0e0e16; color:var(--txt);
        font-family:"SF Mono",Menlo,monospace; font-size:13px;
        display:grid; grid-template-rows:auto 1fr; }
  /* top bar */
  header{ display:flex; align-items:center; gap:10px; padding:8px 12px; background:var(--panel);
          border-bottom:2px solid var(--orange); }
  header h1{ margin:0; font-size:15px; color:var(--orange); letter-spacing:2px; }
  header .sp{ flex:1; }
  button{ background:#2a2a3e; color:var(--txt); border:1px solid var(--line); border-radius:5px;
          padding:6px 11px; cursor:pointer; font-family:inherit; font-size:12px; }
  button:hover{ background:#34344e; }
  button.primary{ background:var(--orange); border-color:var(--orange); color:#fff; font-weight:bold; }
  button.danger{ background:#3a2424; border-color:#5a3030; }
  header select{ background:#2a2a3e; color:var(--txt); border:1px solid var(--line); border-radius:5px;
                 padding:6px 8px; font-family:inherit; font-size:12px; cursor:pointer; }
  /* main 3-pane */
  main{ display:grid; grid-template-columns:200px 1fr 240px; overflow:hidden; }
  .pane{ background:var(--panel); overflow-y:auto; }
  .pane.left{ border-right:1px solid var(--line); }
  .pane.right{ border-left:1px solid var(--line); }
  .ph{ padding:8px 10px; font-size:11px; color:var(--mut); text-transform:uppercase;
       letter-spacing:1px; border-bottom:1px solid var(--line); position:sticky; top:0; background:var(--panel); }
  /* viewport */
  .viewport{ position:relative; background:#0a0a12; display:flex; align-items:center; justify-content:center; overflow:hidden; }
  canvas{ background:#181826; box-shadow:0 0 0 1px var(--line); image-rendering:pixelated; }
  /* hierarchy */
  .item{ padding:6px 10px; cursor:pointer; border-bottom:1px solid #24243430; display:flex; gap:6px; align-items:center; }
  .item:hover{ background:#24243480; }
  .item.sel{ background:var(--orange); color:#fff; }
  .item .dot{ width:9px; height:9px; border-radius:2px; flex:none; }
  .item .nm{ flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  /* palette buttons */
  .palette{ display:flex; flex-direction:column; gap:6px; padding:10px; }
  .palette button{ text-align:left; }
  /* inspector */
  .insp{ padding:10px; }
  .row{ display:flex; align-items:center; gap:8px; margin-bottom:8px; }
  .row label{ width:64px; color:var(--mut); font-size:11px; flex:none; }
  .row input[type=number], .row input[type=text]{ width:100%; background:#12121c; border:1px solid var(--line);
      color:var(--txt); border-radius:4px; padding:4px 6px; font-family:inherit; }
  .row input[type=color]{ width:40px; height:26px; background:none; border:1px solid var(--line); border-radius:4px; }
  .row select{ width:100%; background:#12121c; border:1px solid var(--line); color:var(--txt); border-radius:4px; padding:4px; font-family:inherit; }
  .row.chk{ gap:6px; }
  .row.chk label{ width:auto; }
  .sec{ font-size:11px; color:var(--orange); text-transform:uppercase; letter-spacing:1px;
        margin:14px 0 8px; border-bottom:1px solid var(--line); padding-bottom:4px; }
  .empty{ color:var(--mut); padding:14px; font-style:italic; }
  .tip{ position:absolute; bottom:8px; left:8px; color:var(--mut); font-size:11px; pointer-events:none; }
  .badge{ position:absolute; top:8px; right:8px; background:var(--orange); color:#fff; padding:3px 8px;
          border-radius:4px; font-size:11px; display:none; }
</style>
</head>
<body>
  <header>
    <h1>🦴 CAVEMAN ENGINE</h1>
    <select id="mode" title="game type">
      <option value="platformer">🕹 Platformer (Mario)</option>
      <option value="runner">🟦 Runner (Geometry Dash)</option>
      <option value="topdown">🧭 Top-Down (Zelda)</option>
      <option value="flappy">🐦 Flappy (tap to fly)</option>
      <option value="shooter">🔫 Shooter (top-down, shoot)</option>
    </select>
    <button id="btnPlay" class="primary">▶ Play</button>
    <button id="btnStop" disabled>■ Stop</button>
    <span class="sp"></span>
    <button id="btnSave">Save</button>
    <button id="btnLoad">Load</button>
    <button id="btnExport">Export Game</button>
    <button id="btnClear" class="danger">Clear</button>
  </header>

  <main>
    <!-- LEFT: palette + hierarchy -->
    <div class="pane left">
      <div class="ph">Add Object</div>
      <div class="palette">
        <button data-add="platform">▦ Platform (solid)</button>
        <button data-add="player">★ Player</button>
        <button data-add="coin">● Coin (pickup)</button>
        <button data-add="enemy">▲ Enemy (patrol)</button>
        <button data-add="spike">▲ Spike (instant death)</button>
        <button data-add="box">■ Box (physics)</button>
        <button data-add="goal">⚑ Goal</button>
      </div>
      <div class="ph">Hierarchy</div>
      <div id="hierarchy"></div>
    </div>

    <!-- CENTER: viewport -->
    <div class="pane viewport">
      <canvas id="view" width="640" height="380"></canvas>
      <div class="badge" id="playBadge">● PLAYING</div>
      <div class="tip" id="tip">Click object to select · drag to move · Delete key removes</div>
    </div>

    <!-- RIGHT: inspector -->
    <div class="pane right">
      <div class="ph">Inspector</div>
      <div id="inspector" class="insp"><div class="empty">no object selected</div></div>
    </div>
  </main>

<script>
/* ============================================================
   CAVEMAN ENGINE EDITOR — make game by clicking. press play.
   one file. no deps. me caveman, me proud.
   ============================================================ */
const canvas = document.getElementById("view");
const ctx = canvas.getContext("2d");
const W = canvas.width, H = canvas.height;

/* ---- object types: the "prefabs" ---- */
const TYPES = {
  platform: { color:"#3a3a5c", w:140, h:24, solid:true,  gravity:0,    role:"platform", label:"Platform" },
  player:   { color:"#ffd166", w:28,  h:36, solid:true,  gravity:1800, role:"player",   label:"Player"   },
  coin:     { color:"#ffe66d", w:18,  h:18, solid:false, gravity:0,    role:"coin",     label:"Coin"     },
  enemy:    { color:"#ef476f", w:30,  h:30, solid:false, gravity:1800, role:"enemy",    label:"Enemy"    },
  box:      { color:"#a0a0c0", w:36,  h:36, solid:true,  gravity:1800, role:"box",      label:"Box"      },
  goal:     { color:"#06d6a0", w:34,  h:48, solid:false, gravity:0,    role:"goal",     label:"Goal"     },
  spike:    { color:"#ff5c5c", w:30,  h:30, solid:false, gravity:0,    role:"spike",    label:"Spike"    },
};

let gameMode = "platformer";   // "platformer" or "runner" (Geometry-Dash style)

let scene = [];      // list of objects (the level)
let uid = 1;
let selected = null;
let playing = false;
let runtime = null;  // copy of scene used while playing

function makeObj(type, x, y) {
  const t = TYPES[type];
  return { id: uid++, type, name: t.label + " " + uid,
    x: Math.round(x), y: Math.round(y), w: t.w, h: t.h,
    color: t.color, solid: t.solid, gravity: t.gravity, role: t.role,
    speed: 220, jump: 620, patrol: 60 };
}

/* ---- add from palette ---- */
document.querySelectorAll("[data-add]").forEach(b => {
  b.onclick = () => {
    if (playing) return;
    const o = makeObj(b.dataset.add, W/2 - 30, 60);
    scene.push(o); select(o); refreshHierarchy();
  };
});

/* ============================================================
   EDIT MODE — drawing, selecting, dragging
   ============================================================ */
let drag = null;
canvas.addEventListener("mousedown", (e) => {
  if (playing) return;
  const m = mousePos(e);
  // top-most hit
  let hit = null;
  for (let i = scene.length - 1; i >= 0; i--) if (inside(scene[i], m)) { hit = scene[i]; break; }
  select(hit);
  if (hit) drag = { o: hit, dx: m.x - hit.x, dy: m.y - hit.y };
  refreshHierarchy();
});
addEventListener("mousemove", (e) => {
  if (!drag) return;
  const m = mousePos(e);
  drag.o.x = Math.round(m.x - drag.dx);
  drag.o.y = Math.round(m.y - drag.dy);
  if (selected === drag.o) buildInspector();
});
addEventListener("mouseup", () => drag = null);
addEventListener("keydown", (e) => {
  if (playing) return;
  if ((e.key === "Delete" || e.key === "Backspace") && selected) {
    scene = scene.filter(o => o !== selected); select(null); refreshHierarchy();
  }
});
function mousePos(e){ const r = canvas.getBoundingClientRect();
  return { x:(e.clientX-r.left)*(W/r.width), y:(e.clientY-r.top)*(H/r.height) }; }
function inside(o, m){ return m.x>=o.x && m.x<=o.x+o.w && m.y>=o.y && m.y<=o.y+o.h; }

/* ============================================================
   SELECTION + INSPECTOR
   ============================================================ */
function select(o){ selected = o; buildInspector(); refreshHierarchy(); }

function buildInspector(){
  const box = document.getElementById("inspector");
  if (!selected){ box.innerHTML = '<div class="empty">no object selected</div>'; return; }
  const o = selected;
  const num = (k, lbl) => `<div class="row"><label>${lbl}</label>
      <input type="number" value="${o[k]}" oninput="setProp('${k}', +this.value)"></div>`;
  let html = `
    <div class="row"><label>Name</label><input type="text" value="${o.name}" oninput="setProp('name', this.value)"></div>
    <div class="row"><label>Type</label><input type="text" value="${o.type}" disabled></div>
    <div class="sec">Transform</div>
    ${num("x","X")}${num("y","Y")}${num("w","Width")}${num("h","Height")}
    <div class="sec">Look</div>
    <div class="row"><label>Color</label><input type="color" value="${o.color}" oninput="setProp('color', this.value)"></div>
    <div class="sec">Physics</div>
    <div class="row chk"><input type="checkbox" ${o.solid?"checked":""} onchange="setProp('solid', this.checked)"><label>Solid (block)</label></div>
    ${num("gravity","Gravity")}`;
  if (o.role === "player") html += `<div class="sec">Player</div>${num("speed","Move spd")}${num("jump","Jump pwr")}`;
  if (o.role === "enemy")  html += `<div class="sec">Enemy</div>${num("speed","Move spd")}${num("patrol","Patrol ±")}`;
  box.innerHTML = html;
}
function setProp(k, v){ if (!selected) return; selected[k] = v; if (k!=="name") {} refreshHierarchy(); render(); }

/* ============================================================
   HIERARCHY LIST
   ============================================================ */
function refreshHierarchy(){
  const h = document.getElementById("hierarchy");
  if (!scene.length){ h.innerHTML = '<div class="empty">empty. add object →</div>'; return; }
  h.innerHTML = "";
  scene.forEach(o => {
    const d = document.createElement("div");
    d.className = "item" + (o === selected ? " sel" : "");
    d.innerHTML = `<span class="dot" style="background:${o.color}"></span><span class="nm">${o.name}</span>`;
    d.onclick = () => select(o);
    h.appendChild(d);
  });
}

/* ============================================================
   RENDER (edit mode)
   ============================================================ */
function drawObj(c, o){
  c.fillStyle = o.color;
  if (o.role === "coin"){ c.beginPath(); c.arc(o.x+o.w/2, o.y+o.h/2, o.w/2, 0, 7); c.fill(); }
  else if (o.role === "spike"){
    c.beginPath(); c.moveTo(o.x, o.y+o.h); c.lineTo(o.x+o.w/2, o.y); c.lineTo(o.x+o.w, o.y+o.h); c.closePath(); c.fill();
  }
  else c.fillRect(o.x, o.y, o.w, o.h);
  if (o.role === "player"){ c.fillStyle="#000"; c.fillRect(o.x+o.w-12,o.y+8,5,5); }
  if (o.role === "goal"){ c.fillStyle="#fff"; c.font="20px monospace"; c.fillText("⚑", o.x+6, o.y+o.h-12); }
}
let camX = 0;   // camera scroll (used in runner play mode)
function render(){
  ctx.fillStyle = "#181826"; ctx.fillRect(0,0,W,H);
  ctx.save();
  ctx.translate(-camX, 0);
  // grid (scrolls with camera)
  ctx.strokeStyle = "#22223380"; ctx.lineWidth = 1;
  const gx0 = Math.floor(camX/32)*32;
  for (let x=gx0;x<gx0+W+32;x+=32){ ctx.beginPath(); ctx.moveTo(x,0); ctx.lineTo(x,H); ctx.stroke(); }
  for (let y=0;y<H;y+=32){ ctx.beginPath(); ctx.moveTo(gx0,y); ctx.lineTo(gx0+W+32,y); ctx.stroke(); }
  const list = playing ? runtime : scene;
  list.forEach(o => drawObj(ctx, o));
  // selection outline (edit only)
  if (!playing && selected){
    ctx.strokeStyle = "#fff"; ctx.lineWidth = 2;
    ctx.strokeRect(selected.x-1, selected.y-1, selected.w+2, selected.h+2);
  }
  ctx.restore();
}

/* ============================================================
   PLAY MODE — real game runs here
   ============================================================ */
const keys = {}, pressed = {};
let mouseHeld = false, mousePressed = false;
addEventListener("keydown", e => { if(!keys[e.code]) pressed[e.code]=true; keys[e.code]=true;
  if(["ArrowUp","ArrowDown","Space"].includes(e.code) && playing) e.preventDefault(); });
addEventListener("keyup", e => keys[e.code]=false);
// tap / hold to jump in runner play mode
canvas.addEventListener("mousedown", () => { if(playing){ mouseHeld = true; mousePressed = true; } });
addEventListener("mouseup", () => mouseHeld = false);
canvas.addEventListener("touchstart", e => { if(playing){ mouseHeld = true; mousePressed = true; e.preventDefault(); } }, {passive:false});
addEventListener("touchend", () => mouseHeld = false);

document.getElementById("mode").onchange = (e) => { gameMode = e.target.value; };

let raf = null, last = 0, msg = "", attempts = 1, won = false;
function spawnRuntime(){
  runtime = scene.map(o => ({ ...o, vx:0, vy:0, onGround:false, alive:true,
                              startX:o.x, startY:o.y, dir:1 }));
  camX = 0; msg = ""; won = false;
}
function play(){
  if (!scene.some(o=>o.role==="player")){ alert("caveman say: add a Player first!"); return; }
  playing = true; attempts = 1;
  spawnRuntime();
  document.getElementById("btnPlay").disabled = true;
  document.getElementById("btnStop").disabled = false;
  document.getElementById("playBadge").style.display = "block";
  last = performance.now(); loop(last);
}
function stop(){
  playing = false; camX = 0; cancelAnimationFrame(raf);
  document.getElementById("btnPlay").disabled = false;
  document.getElementById("btnStop").disabled = true;
  document.getElementById("playBadge").style.display = "none";
  render();
}
function overlaps(a,b){ return a.x<b.x+b.w && a.x+a.w>b.x && a.y<b.y+b.h && a.y+a.h>b.y; }

// which modes instantly retry on death (fast arcade feel)
function instantRetry(){ return gameMode==="runner" || gameMode==="flappy"; }
function die(reason){
  if (instantRetry()){ attempts++; spawnRuntime(); }
  else { msg = reason + "  (Stop + Play to retry)"; }
}
function loop(t){
  let dt = (t-last)/1000; last = t; if (dt>0.05) dt=0.05;
  const M = gameMode;
  const topdownish = (M==="topdown" || M==="shooter");
  const sidescroll  = (M==="runner" || M==="flappy");
  const useGravity  = (M==="platformer" || M==="runner" || M==="flappy");
  const solids = runtime.filter(o=>o.solid && o.alive);

  if (!won && !msg){
    const player = runtime.find(o=>o.role==="player"&&o.alive);

    for (const o of runtime){
      if (!o.alive) continue;

      if (o.role === "player"){
        if (M==="runner"){
          o.vx = o.speed;
          if ((keys.Space||keys.KeyW||keys.ArrowUp||mouseHeld) && o.onGround) o.vy = -o.jump;
        } else if (M==="flappy"){
          o.vx = o.speed;
          if (pressed.Space||pressed.KeyW||pressed.ArrowUp||mousePressed) o.vy = -o.jump*0.55;  // flap
        } else if (topdownish){
          let dx=0,dy=0;
          if(keys.ArrowLeft||keys.KeyA)dx--; if(keys.ArrowRight||keys.KeyD)dx++;
          if(keys.ArrowUp||keys.KeyW)dy--;   if(keys.ArrowDown||keys.KeyS)dy++;
          const l=Math.hypot(dx,dy)||1; o.vx=dx/l*o.speed; o.vy=dy/l*o.speed;
          if(dx||dy){ o.faceX=dx; o.faceY=dy; }                 // remember aim
          if (M==="shooter" && (pressed.Space||mousePressed)){    // SHOOT
            const fx=o.faceX||1, fy=o.faceY||0, fl=Math.hypot(fx,fy)||1;
            runtime.push({ role:"bullet", x:o.cx??o.x+o.w/2, y:o.y+o.h/2-3, w:8, h:8,
              color:"#ffe066", solid:false, alive:true, life:1.2,
              vx:fx/fl*620, vy:fy/fl*620 });
          }
        } else { // platformer
          let d=0; if(keys.ArrowLeft||keys.KeyA)d--; if(keys.ArrowRight||keys.KeyD)d++;
          o.vx = d*o.speed;
          if ((pressed.Space||pressed.KeyW||pressed.ArrowUp) && o.onGround) o.vy = -o.jump;
        }
      }
      else if (o.role === "enemy"){
        o.vx = o.dir*o.speed;
        if (o.x > o.startX+o.patrol) o.dir=-1;
        if (o.x < o.startX-o.patrol) o.dir=1;
      }
      else if (o.role === "bullet"){
        o.life -= dt; if (o.life<=0) o.alive=false;
      }

      if (useGravity && o.gravity && o.role!=="bullet") o.vy += o.gravity*dt;

      // integrate + collide vs solids (bullets pass through nothing but solids -> die)
      o.onGround = false;
      o.x += o.vx*dt;
      for (const s of solids){ if(s===o)continue; if(overlaps(o,s)){
        if(o.role==="bullet"){ o.alive=false; break; }
        if(o.vx>0)o.x=s.x-o.w; else if(o.vx<0)o.x=s.x+s.w; o.vx=0;
        if(M==="runner" && o.role==="player") die("CRASH!"); } }
      o.y += o.vy*dt;
      for (const s of solids){ if(s===o)continue; if(overlaps(o,s)){
        if(o.role==="bullet"){ o.alive=false; break; }
        if(o.vy>0){o.y=s.y-o.h;o.onGround=true;} else if(o.vy<0)o.y=s.y+s.h; o.vy=0; } }
    }

    // interactions
    if (player){
      for (const o of runtime){
        if (!o.alive || o===player) continue;
        if (o.role==="coin" && overlaps(player,o)) o.alive=false;
        if (o.role==="goal" && overlaps(player,o)){ msg="YOU WIN! 🏆"; won=true; }
        if ((o.role==="enemy"||o.role==="spike") && overlaps(player,o)) die("OUCH! 💀");
      }
      // bullets vs enemies
      for (const b of runtime){
        if (b.role!=="bullet"||!b.alive) continue;
        for (const e of runtime){ if(e.role==="enemy"&&e.alive&&overlaps(b,e)){ e.alive=false; b.alive=false; } }
      }
      // bounds
      if (useGravity && player.y > H+100) die("fell in pit! 💀");
      if (M==="flappy" && player.y < -40) die("flew too high! 💀");
      if (topdownish){ // keep player on screen
        player.x=Math.max(0,Math.min(W-player.w,player.x));
        player.y=Math.max(0,Math.min(H-player.h,player.y));
      }
      // camera scroll for side-scrollers
      if (sidescroll){ const tg=player.x-W/3; camX+=(tg-camX)*Math.min(1,dt*8); if(camX<0)camX=0; }
    }
    // drop dead bullets so array no grow forever
    runtime = runtime.filter(o=>o.role!=="bullet"||o.alive);
  }

  render();
  // HUD
  ctx.fillStyle="#fff"; ctx.font="bold 16px monospace";
  if (instantRetry()) ctx.fillText("Attempt "+attempts, 12, 24);
  else if (M==="shooter") ctx.fillText("enemies: "+runtime.filter(o=>o.role==="enemy"&&o.alive).length, 12, 24);
  else ctx.fillText("coins left: "+runtime.filter(o=>o.role==="coin"&&o.alive).length, 12, 24);
  if (msg){ ctx.fillStyle="#000a"; ctx.fillRect(0,H/2-30,W,60);
    ctx.fillStyle="#ffd166"; ctx.font="bold 26px monospace"; ctx.textAlign="center";
    ctx.fillText(msg, W/2, H/2+8); ctx.textAlign="left"; }

  pressed.Space = pressed.KeyW = pressed.ArrowUp = false;   // consume one-shots
  mousePressed = false;
  raf = requestAnimationFrame(loop);
}

/* ============================================================
   SAVE / LOAD / EXPORT / CLEAR
   ============================================================ */
document.getElementById("btnPlay").onclick = play;
document.getElementById("btnStop").onclick = stop;
document.getElementById("btnClear").onclick = () => { if(confirm("clear whole level?")){ scene=[]; select(null); refreshHierarchy(); render(); } };

document.getElementById("btnSave").onclick = () => {
  localStorage.setItem("cavemanLevel", JSON.stringify(scene));
  flash("saved to browser!");
};
document.getElementById("btnLoad").onclick = () => {
  const d = localStorage.getItem("cavemanLevel");
  if (!d){ alert("nothing saved yet"); return; }
  scene = JSON.parse(d); uid = scene.reduce((m,o)=>Math.max(m,o.id),0)+1;
  select(null); refreshHierarchy(); render(); flash("loaded!");
};
function flash(t){ const tip=document.getElementById("tip"); const old=tip.textContent;
  tip.textContent="🦴 "+t; tip.style.color="#ffd166"; setTimeout(()=>{tip.textContent=old;tip.style.color="";},1500); }

/* export = standalone playable HTML, no editor */
document.getElementById("btnExport").onclick = () => {
  const html = EXPORT_TEMPLATE
    .replace("/*__LEVEL__*/", JSON.stringify(scene))
    .replace("__MODE__", gameMode);
  const blob = new Blob([html], {type:"text/html"});
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob); a.download = "MyCavemanGame.html"; a.click();
  flash("exported MyCavemanGame.html → Downloads");
};

const EXPORT_TEMPLATE = `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>My Caveman Game</title>
<style>body{margin:0;background:#0a0a12;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;font-family:monospace;color:#888}
canvas{background:#181826;image-rendering:pixelated;border:2px solid #e0552b;max-width:96vw}</style></head><body>
<canvas id="v" width="${W}" height="${H}"></canvas><p>move: ARROWS/WASD &nbsp; jump/flap/shoot: SPACE/tap &nbsp; restart: R</p><script>
const scene=/*__LEVEL__*/;const M="__MODE__";const W=${W},H=${H};
const topd=(M==="topdown"||M==="shooter"),side=(M==="runner"||M==="flappy"),grav=(M==="platformer"||M==="runner"||M==="flappy"),inst=(M==="runner"||M==="flappy");
const c=document.getElementById("v").getContext("2d");
const keys={},pressed={};let mh=false,mp=false;
addEventListener("keydown",e=>{if(!keys[e.code])pressed[e.code]=true;keys[e.code]=true;if(["ArrowUp","ArrowDown","Space"].includes(e.code))e.preventDefault();});addEventListener("keyup",e=>keys[e.code]=false);
addEventListener("mousedown",()=>{mh=true;mp=true;});addEventListener("mouseup",()=>mh=false);
addEventListener("touchstart",e=>{mh=true;mp=true;e.preventDefault();},{passive:false});addEventListener("touchend",()=>mh=false);
let rt,msg="",won=false,att=1,camX=0,last=0;
function reset(){rt=scene.map(o=>({...o,vx:0,vy:0,onGround:false,alive:true,startX:o.x,dir:1,faceX:1,faceY:0}));msg="";won=false;camX=0;}
function die(){if(inst){att++;reset();}else msg="GAME OVER";}
function ov(a,b){return a.x<b.x+b.w&&a.x+a.w>b.x&&a.y<b.y+b.h&&a.y+a.h>b.y;}
function draw(o){c.fillStyle=o.color;if(o.role==="coin"){c.beginPath();c.arc(o.x+o.w/2,o.y+o.h/2,o.w/2,0,7);c.fill();}
else if(o.role==="spike"){c.beginPath();c.moveTo(o.x,o.y+o.h);c.lineTo(o.x+o.w/2,o.y);c.lineTo(o.x+o.w,o.y+o.h);c.closePath();c.fill();}
else c.fillRect(o.x,o.y,o.w,o.h);if(o.role==="player"){c.fillStyle="#000";c.fillRect(o.x+o.w-12,o.y+8,5,5);}}
function loop(t){let dt=(t-last)/1000;last=t;if(dt>0.05)dt=0.05;const sol=rt.filter(o=>o.solid&&o.alive);
if(!won&&!msg){const p=rt.find(o=>o.role==="player"&&o.alive);
for(const o of rt){if(!o.alive)continue;
if(o.role==="player"){
if(M==="runner"){o.vx=o.speed;if((keys.Space||keys.KeyW||keys.ArrowUp||mh)&&o.onGround)o.vy=-o.jump;}
else if(M==="flappy"){o.vx=o.speed;if(pressed.Space||pressed.KeyW||pressed.ArrowUp||mp)o.vy=-o.jump*0.55;}
else if(topd){let dx=0,dy=0;if(keys.ArrowLeft||keys.KeyA)dx--;if(keys.ArrowRight||keys.KeyD)dx++;if(keys.ArrowUp||keys.KeyW)dy--;if(keys.ArrowDown||keys.KeyS)dy++;const l=Math.hypot(dx,dy)||1;o.vx=dx/l*o.speed;o.vy=dy/l*o.speed;if(dx||dy){o.faceX=dx;o.faceY=dy;}
if(M==="shooter"&&(pressed.Space||mp)){const fx=o.faceX||1,fy=o.faceY||0,fl=Math.hypot(fx,fy)||1;rt.push({role:"bullet",x:o.x+o.w/2,y:o.y+o.h/2-3,w:8,h:8,color:"#ffe066",solid:false,alive:true,life:1.2,vx:fx/fl*620,vy:fy/fl*620});}}
else{let d=0;if(keys.ArrowLeft||keys.KeyA)d--;if(keys.ArrowRight||keys.KeyD)d++;o.vx=d*o.speed;if((pressed.Space||pressed.KeyW||pressed.ArrowUp)&&o.onGround)o.vy=-o.jump;}}
else if(o.role==="enemy"){o.vx=o.dir*o.speed;if(o.x>o.startX+o.patrol)o.dir=-1;if(o.x<o.startX-o.patrol)o.dir=1;}
else if(o.role==="bullet"){o.life-=dt;if(o.life<=0)o.alive=false;}
if(grav&&o.gravity&&o.role!=="bullet")o.vy+=o.gravity*dt;
o.onGround=false;o.x+=o.vx*dt;for(const s of sol){if(s===o)continue;if(ov(o,s)){if(o.role==="bullet"){o.alive=false;break;}if(o.vx>0)o.x=s.x-o.w;else if(o.vx<0)o.x=s.x+s.w;o.vx=0;if(M==="runner"&&o.role==="player")die();}}
o.y+=o.vy*dt;for(const s of sol){if(s===o)continue;if(ov(o,s)){if(o.role==="bullet"){o.alive=false;break;}if(o.vy>0){o.y=s.y-o.h;o.onGround=true;}else if(o.vy<0)o.y=s.y+s.h;o.vy=0;}}}
if(p){for(const o of rt){if(!o.alive||o===p)continue;if(o.role==="coin"&&ov(p,o))o.alive=false;if(o.role==="goal"&&ov(p,o)){msg="YOU WIN!";won=true;}if((o.role==="enemy"||o.role==="spike")&&ov(p,o))die();}
for(const b of rt){if(b.role!=="bullet"||!b.alive)continue;for(const e of rt)if(e.role==="enemy"&&e.alive&&ov(b,e)){e.alive=false;b.alive=false;}}
if(grav&&p.y>H+100)die();if(M==="flappy"&&p.y<-40)die();
if(topd){p.x=Math.max(0,Math.min(W-p.w,p.x));p.y=Math.max(0,Math.min(H-p.h,p.y));}
if(side){const tg=p.x-W/3;camX+=(tg-camX)*Math.min(1,dt*8);if(camX<0)camX=0;}}
rt=rt.filter(o=>o.role!=="bullet"||o.alive);}
c.fillStyle="#181826";c.fillRect(0,0,W,H);c.save();c.translate(-camX,0);rt.forEach(draw);c.restore();
c.fillStyle="#fff";c.font="bold 16px monospace";c.fillText(inst?("Attempt "+att):M==="shooter"?("enemies: "+rt.filter(o=>o.role==="enemy"&&o.alive).length):("coins: "+rt.filter(o=>o.role==="coin"&&o.alive).length),12,24);
if(msg){c.fillStyle="#000a";c.fillRect(0,H/2-30,W,60);c.fillStyle="#ffd166";c.font="bold 26px monospace";c.textAlign="center";c.fillText(msg+"  (press R)",W/2,H/2+8);c.textAlign="left";if(pressed.KeyR)reset();}
pressed.Space=pressed.KeyW=pressed.ArrowUp=pressed.KeyR=false;mp=false;requestAnimationFrame(loop);}
reset();requestAnimationFrame(loop);
<\/script></body></html>`;

/* ---- boot ---- */
function seedDemo(){
  scene = [
    makeObj("platform", 0, 340), makeObj("platform", 120, 270),
    makeObj("platform", 380, 210), makeObj("player", 40, 60),
    makeObj("coin", 170, 235), makeObj("coin", 430, 175),
    makeObj("enemy", 250, 310), makeObj("goal", 560, 292),
  ];
  scene[0].w = 640; // ground stretch
  refreshHierarchy(); render();
}
seedDemo();
// clear pressed flags each frame even in edit
setInterval(()=>{ if(!playing){ for(const k in pressed) pressed[k]=false; } }, 16);
</script>
</body>
</html>
