Skip to content
Make the player visible with a procedural 3D humanoid132be7c
JavaScript204 lines9.0 KB
import { createMatch, step, DT } from "./game/engine.mjs";import { LEVELS } from "./game/levels.mjs";import { createBot } from "./game/bot.mjs";import { createInputTracker, isGameKey } from "./game/input.mjs";import { interpolate, hudLayout, healthFraction, generateRoomCode } from "./render-utils.mjs"; const $ = (id) => document.getElementById(id);const canvas = $("game");const W = canvas.width, H = canvas.height; // 3D path: public/render3d.mjs (WebGL renderer) + public/stage.mjs (stage data).// Loaded dynamically so the page still works with the 2D fallback if either is missing.async function loadModule(p) { try { return await import(p); } catch { return null; } }function makeRenderer3d(mod, stageMod) {  if (!mod) return null;  const stage = stageMod && (stageMod.STAGE || stageMod.stage || stageMod.default || stageMod);  const opts = { stage, width: W, height: H };  try {    if (typeof mod.createRenderer === "function") {      const r = mod.createRenderer(canvas, opts);      if (r && typeof r.render === "function") return r;      if (typeof r === "function") return { render: r };    }    if (typeof mod.init === "function") {      const r = mod.init(canvas, opts);      if (r && typeof r.render === "function") return r;      if (typeof mod.render === "function") return { render: (s, o) => mod.render(s, { ...opts, ...o }) };    }    if (typeof mod.render === "function") return { render: (s, o) => mod.render(s, { canvas, ...opts, ...o }) };    if (typeof mod.default === "function") {      const r = mod.default(canvas, opts);      if (r && typeof r.render === "function") return r;    }  } catch (e) { console.warn("3D renderer unavailable, using 2D fallback", e); }  return null;}const renderer3d = makeRenderer3d(await loadModule("./render3d.mjs"), await loadModule("./stage.mjs"));// With WebGL on the game canvas, the HUD/particles/banner go on a 2D overlay canvas.let ctx;if (renderer3d) {  const hudCanvas = document.createElement("canvas");  hudCanvas.id = "hud"; hudCanvas.width = W; hudCanvas.height = H;  hudCanvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;pointer-events:none";  canvas.insertAdjacentElement("afterend", hudCanvas);  ctx = hudCanvas.getContext("2d");} else {  ctx = canvas.getContext("2d");}const levelList = [...LEVELS];let mode = "bot", levelIdx = 0, running = false, ws = null;let state = null, prev = null, acc = 0, last = 0, particles = [], banner = { text: "", t: 0 };let bot = null, lastSend = 0;const tracker = createInputTracker(); levelList.forEach((l, i) => {  const b = document.createElement("button");  b.textContent = l.name || `Level ${i + 1}`;  if (i === 0) b.classList.add("sel");  b.addEventListener("click", () => { levelIdx = i; [...$("levels").children].forEach((c) => c.classList.toggle("sel", c === b)); });  $("levels").append(b);});$("modes").addEventListener("click", (e) => {  const btn = e.target.closest("button[data-mode]"); if (!btn) return;  mode = btn.dataset.mode; [...$("modes").children].forEach((c) => c.classList.toggle("sel", c === btn));  $("roombox").classList.toggle("hidden", mode !== "multi");  if (mode === "multi" && !$("room").value) $("room").value = generateRoomCode();});$("newroom").addEventListener("click", () => { $("room").value = generateRoomCode(); });$("start").addEventListener("click", start);window.addEventListener("keydown", (e) => {  if (e.target instanceof HTMLInputElement) return;  const handled = tracker.keyDown(e.code);  if (running && (handled || isGameKey(e.code))) e.preventDefault();});window.addEventListener("keyup", (e) => { tracker.keyUp(e.code); });window.addEventListener("blur", () => tracker.clear()); const curLevel = () => levelList[levelIdx] || {};const groundY = () => (curLevel().arena || {}).floorY || H * 0.82;const arenaScale = () => W / ((curLevel().arena || {}).width || W); function start() {  const level = curLevel();  state = createMatch(level);  prev = state; running = true; acc = 0; last = performance.now(); particles = [];  tracker.clear();  bot = createBot({ difficulty: level.botDifficulty ?? "medium", seed: (Date.now() % 100000) + 1 });  $("menu").classList.add("hidden");  $("status").textContent = "";  banner = { text: "FIGHT!", t: 2 };  if (mode === "multi") connect();  canvas.focus();} function endMatch() {  running = false; ws = null;  $("menu").classList.remove("hidden");} function connect() {  const id = $("room").value || generateRoomCode();  ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/room/${id}`);  $("status").textContent = `Room ${id} — waiting…`;  ws.onopen = () => ws.send(JSON.stringify({ type: "join" }));  ws.onmessage = (ev) => {    let m; try { m = JSON.parse(ev.data); } catch { return; }    if (m.type === "state" && m.state) { prev = state; state = m.state; acc = 0; $("status").textContent = `Room ${id}`; }    if (m.type === "gameover") banner = { text: "GAME OVER", t: 4 };  };  ws.onclose = () => { $("status").textContent = "Disconnected"; endMatch(); };} function tick(now) {  const mine = tracker.snapshot();  if (mode === "multi") {    if (ws && ws.readyState === 1 && now - lastSend > 33) { ws.send(JSON.stringify({ type: "input", input: mine })); lastSend = now; }    return;  }  const botIn = bot.update(state);  prev = state;  state = step(state, [mine, botIn], DT);  spawnHits(prev, state);  if (state.phase === "matchover" && prev.phase !== "matchover") {    banner = { text: state.winner === 0 ? "YOU WIN" : "BOT WINS", t: 4 };    setTimeout(endMatch, 3000);  } else if (state.phase === "roundover" && prev.phase === "fight") {    banner = { text: state.roundWinner === 0 ? "ROUND WON" : state.roundWinner === 1 ? "ROUND LOST" : "DRAW", t: 1.5 };  }} function spawnHits(a, b) {  const s = arenaScale(), gy = groundY();  (b.fighters || []).forEach((f, i) => {    const p = a.fighters && a.fighters[i];    if (p && f.health < p.health) for (let n = 0; n < 14; n++)      particles.push({ x: f.x * s, y: gy - 90 - (f.y || 0), vx: (Math.random() - .5) * 420, vy: -Math.random() * 380, life: 0.5 });  });} function drawFighter(f, t, color) {  // Engine y is height above the floor (positive = up); convert to screen space.  ctx.save(); ctx.translate(f.x * arenaScale(), groundY() - Math.max(0, f.y || 0)); ctx.scale(f.facing >= 0 ? 1 : -1, 1);  ctx.strokeStyle = color; ctx.fillStyle = color; ctx.lineWidth = 12; ctx.lineCap = "round";  const idle = Math.sin(t * 4) * 3, kick = f.stance === "kick", punch = f.stance === "punch";  const line = (a, b, c, d) => { ctx.beginPath(); ctx.moveTo(a, b); ctx.lineTo(c, d); ctx.stroke(); };  line(0, -50, -12, 0); line(0, -50, 14, 0);  if (kick) line(0, -50, 70, -60);  line(0, -50, 0, -110 + idle);  line(0, -100, 20 + (punch ? 50 : 0), -90 + idle); line(0, -100, -15, -75);  if (f.stance === "block") line(0, -100, 25, -115);  ctx.beginPath(); ctx.arc(0, -128 + idle, 16, 0, 7); ctx.fill();  ctx.restore();} function draw(now) {  const th = curLevel().theme || {}, gy = groundY();  const alpha = acc / DT;  if (renderer3d) {    ctx.clearRect(0, 0, W, H);    try { renderer3d.render(state, { prev, alpha, time: now / 1000, level: curLevel(), theme: th }); }    catch (e) { console.warn("3D render failed", e); }    if (!state) return;  } else {    const g = ctx.createLinearGradient(0, 0, 0, H);    g.addColorStop(0, th.sky || "#2a1040"); g.addColorStop(1, th.ground || "#0b0b18");    ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);    ctx.fillStyle = th.ground || "#000"; ctx.fillRect(0, gy, W, H - gy);    if (!state) return;    (state.fighters || []).forEach((f, i) => {      const p = (prev && prev.fighters && prev.fighters[i]) || f;      drawFighter(interpolate(p, f, alpha), now / 1000, i ? "#b33" : "#222");    });  }  ctx.fillStyle = "#fff";  particles.forEach((q) => { ctx.globalAlpha = Math.max(0, q.life * 2); ctx.fillRect(q.x, q.y, 4, 4); });  ctx.globalAlpha = 1;  const hud = hudLayout(W, H);  (state.fighters || []).forEach((f, i) => {    const r = i ? hud.p2 : hud.p1, fr = healthFraction(f.health, f.maxHealth || 100), w = r.w * fr;    ctx.fillStyle = "#222"; ctx.fillRect(r.x, r.y, r.w, r.h);    ctx.fillStyle = fr > .3 ? "#3c6" : "#e33"; ctx.fillRect(i ? r.x + r.w - w : r.x, r.y, w, r.h);  });  ctx.fillStyle = "#fff"; ctx.font = "bold 28px system-ui"; ctx.textAlign = "center";  ctx.fillText(String(Math.ceil(state.roundTime || 0)), hud.timer.x, hud.timer.y + 28);  if (banner.t > 0) {    ctx.globalAlpha = Math.min(1, banner.t); ctx.font = "bold 56px system-ui";    ctx.fillText(banner.text, W / 2, H / 3); ctx.globalAlpha = 1;  }} function frame(now) {  const dt = Math.min(0.1, (now - last) / 1000); last = now;  if (running && state) {    if (mode === "bot") { acc += dt; while (acc >= DT) { tick(now); acc -= DT; } }    else { acc = Math.min(acc + dt, DT); tick(now); }    banner.t -= dt;    particles.forEach((q) => { q.x += q.vx * dt; q.y += q.vy * dt; q.vy += 900 * dt; q.life -= dt; });    particles = particles.filter((q) => q.life > 0);  }  draw(now);  requestAnimationFrame(frame);}requestAnimationFrame(frame);