/* ===================================================================== FULL-COURT PRESS — Sport on Earth Games arcade Single-file canvas game in the Family Arcade house style. EMBED (inline):
CONTROLS: drag on the court (pointer / touch) or use the arrow keys / WASD to move your defender. Press the STEAL button or Space to lunge for the ball — or tap a ball-handler on the court to lunge at him (same clean-steal / foul / whiff outcomes). RULES: ball handlers dribble down toward the bottom basket for 60 seconds. Watch for the flashing yellow ring — the dribble has popped loose and the steal window is open (0.55s). Steal inside the window to score; reach in while it is closed and it is a foul. SCORING: clean steal +3, reach-in foul -1, a handler who reaches the basket scores on you -2. The score never drops below 0. FIXES (Oct 14 PM): the steal lunge now prefers a handler whose window is OPEN in range over a nearer closed one (was: nearest, period — a foul magnet); window widened 0.45s -> 0.55s; the concurrency ramp is 1 -> 2 -> 3 handlers at 20s/40s (was a cliff from 1 to 3 at 30s); the final-whistle screen no longer freezes a half-faded steal animation behind it; Start/Save blur after click so Space/Enter can't re-trigger them; pressing steal while stunned now shows why nothing happened. ===================================================================== */ (function () { "use strict"; /* ================= LEADERBOARD BACKEND — UPGRADE HOOK ================= Default: LOCAL board (localStorage top-10) so the game runs standalone. To switch to the shared family KV leaderboard later, set KV_ENABLED to true. The site must then serve the paper's functions/api/arcade.js with "full-court-press" added to its GAMES list and ARCADE_KV bound — the fetch calls below already mirror that API exactly: GET /api/arcade/leaderboard?game= -> { game, scores:[{manager,score,at}] } POST /api/arcade/score {game, manager, score} -> { ok, rank } No other code changes are needed. */ var KV_ENABLED = false; var GAME_ID = "full-court-press"; var LS_KEY = "fbiArcade." + GAME_ID; var LS_NAME = "fbiArcade.name"; /* Team Account identity (Batch 3.1, Task I, Oct 22, 2026): when a Team Account session is live, ACCT = { username, club } (from the accounts function's GET /api/accounts/me) and score saves go under that identity automatically — the visitor never re-types who they are. The board itself stays exactly what it has always been: this device's localStorage top-10 (KV_ENABLED above remains off — there is no /api/arcade backend on this site, and none is invented here). Guests keep the free-text name flow unchanged. */ var ACCT = null; function escapeHtml(s) { return String(s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); } function localScores() { try { return JSON.parse(localStorage.getItem(LS_KEY)) || []; } catch (e) { return []; } } function renderBoard(el, scores) { if (!scores || !scores.length) { el.innerHTML = "
  • No scores yet — be the first!
  • "; return; } el.innerHTML = scores.slice(0, 10).map(function (s, i) { return "
  • #" + (i + 1) + " " + escapeHtml(s.manager) + (s.club ? " · " + escapeHtml(s.club) : "") + " — " + s.score + "
  • "; }).join(""); } function loadBoard(el) { if (!KV_ENABLED) { renderBoard(el, localScores()); return; } fetch("/api/arcade/leaderboard?game=" + encodeURIComponent(GAME_ID)) .then(function (r) { return r.json(); }) .then(function (d) { renderBoard(el, d.scores || []); }) .catch(function () { el.innerHTML = "
  • Could not load scores.
  • "; }); } function saveScore(name, score, msgEl, boardEl) { if (ACCT) name = ACCT.username; name = (name || "").trim(); if (!name) { msgEl.textContent = "Enter your name first!"; return; } try { localStorage.setItem(LS_NAME, name); } catch (e) {} if (!KV_ENABLED) { var scores = localScores(); var entry = { manager: name.slice(0, 40), score: Math.floor(score), at: new Date().toISOString() }; if (ACCT) { entry.club = ACCT.club || ""; entry.account = true; } scores.push(entry); scores.sort(function (a, b) { return b.score - a.score; }); scores = scores.slice(0, 10); try { localStorage.setItem(LS_KEY, JSON.stringify(scores)); } catch (e) {} var rank = scores.indexOf(entry) + 1; msgEl.textContent = rank ? ("Saved! You rank #" + rank + " on this device's board.") : "Score saved!"; renderBoard(boardEl, scores); return; } fetch("/api/arcade/score", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ game: GAME_ID, manager: name, club: ACCT ? (ACCT.club || "") : "", score: Math.floor(score) }) }).then(function (r) { return r.json(); }) .then(function (d) { msgEl.textContent = d.rank ? ("Saved! You rank #" + d.rank + " on the family board.") : "Score saved!"; loadBoard(boardEl); }) .catch(function () { msgEl.textContent = "Could not save score."; }); } /* ================= SHARED ARCADE CSS (injected once per page) ================= */ if (!document.getElementById("hoopsArcadeCss")) { var st = document.createElement("style"); st.id = "hoopsArcadeCss"; st.textContent = ".hoops-arcade{max-width:440px;margin:0 auto;font-family:inherit;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}" + ".hoops-arcade *{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}" + ".hoops-arcade input,.hoops-arcade select{-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}" + ".hoops-arcade .arcade-canvas{display:block;width:100%;max-width:400px;height:auto;margin:0 auto;background:#8a5a2b;border:3px solid var(--line,#d8cfc0);border-radius:8px;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}" + ".hoops-arcade .arcade-ui{text-align:center;margin:12px 0}" + ".hoops-arcade .arcade-score{font-size:.85rem;margin-bottom:8px}" + ".hoops-arcade .arcade-score b{color:var(--red,#c8102e)}" + ".hoops-arcade .arcade-btn{background:var(--red,#c8102e);color:#fff;border:none;border-radius:6px;padding:10px 24px;font-size:1rem;font-weight:700;cursor:pointer}" + ".hoops-arcade .arcade-btn.small{padding:6px 12px;font-size:.8rem}" + ".hoops-arcade .arcade-btn:disabled{opacity:.5;cursor:default}" + ".hoops-arcade .arcade-msg{min-height:2.4em;font-size:.8rem;color:var(--muted,#666);margin:8px 0}" + ".hoops-arcade .arcade-name{display:flex;gap:8px;justify-content:center;margin:8px 0}" + ".hoops-arcade .arcade-name input{padding:8px;border:1px solid var(--line,#d8cfc0);border-radius:6px;font-size:.9rem;max-width:220px}" + ".hoops-arcade .arcade-board{margin-top:16px}" + ".hoops-arcade .arcade-board h3{font-size:1rem;margin-bottom:8px}" + ".hoops-arcade .arcade-board ol{list-style-position:inside;padding:0}" + ".hoops-arcade .arcade-board li{padding:4px 0;border-bottom:1px solid var(--line,#d8cfc0);font-size:.85rem}"; document.head.appendChild(st); } /* Long-press fix (iOS copy callout on held controls): kill the context menu anywhere inside an arcade mount. Installed once per page. */ if (!window.__hoopsNoCallout) { window.__hoopsNoCallout = true; document.addEventListener("contextmenu", function (e) { var t = e.target; if (t && t.closest && t.closest(".hoops-arcade")) e.preventDefault(); }); } /* ================= MOUNT ================= */ var mount = document.querySelector('[data-hoops-game="' + GAME_ID + '"]'); if (!mount) { mount = document.createElement("div"); mount.setAttribute("data-hoops-game", GAME_ID); var cs = document.currentScript; if (cs && cs.parentNode) cs.parentNode.insertBefore(mount, cs); else document.body.appendChild(mount); } mount.classList.add("hoops-arcade"); mount.innerHTML = '' + '
    ' + '
    Score: 0 • Time: 60.0 • Steals: 0
    ' + '
    ' + '
    Drag or use arrow keys / WASD to guard. Steal (Space) only when the yellow ring flashes — or tap the handler to lunge at him!
    ' + '
    ' + '
    ' + "
    " + '

    Leaderboard — Full-Court Press

    1. Loading…
    '; var cv = mount.querySelector("canvas"), ctx = cv.getContext("2d"); var el = { score: mount.querySelector(".sc"), round: mount.querySelector(".round"), pts: mount.querySelector(".pts"), msg: mount.querySelector(".arcade-msg"), start: mount.querySelector(".start"), action: mount.querySelector(".action"), name: mount.querySelector(".arcade-name input"), save: mount.querySelector(".save"), board: mount.querySelector(".arcade-board ol") }; try { el.name.value = localStorage.getItem(LS_NAME) || ""; } catch (e) {} /* Team Account session check (Task I): non-blocking; any failure simply leaves the guest flow exactly as it was. */ try { fetch("/api/accounts/me", { credentials: "same-origin" }) .then(function (r) { if (!r.ok) throw 0; return r.json(); }) .then(function (d) { if (!d || !d.ok || !d.username) return; ACCT = { username: d.username, club: d.club || "" }; el.name.value = d.username; el.name.readOnly = true; el.name.title = "Signed in — your scores save under your team account"; var hint = document.createElement("div"); hint.className = "arcade-msg acct-hint"; hint.textContent = "🏀 Signed in as " + d.username + (d.club ? " · " + d.club : "") + " — your high scores save under your account, no typing needed."; el.name.parentNode.parentNode.insertBefore(hint, el.name.parentNode); }) .catch(function () {}); } catch (e) {} /* ================= GAME ================= */ var Fig = window.HoopsFig || null; var W = 400, H = 480; var RIM = { x: 200, y: 446 }; var GAME_LEN = 60; var PALETTE = ["#c8102e", "#e67e22", "#2e7d32", "#6a1b9a", "#00838f", "#4e342e", "#283593"]; var DEF_APPEAR = Fig ? Fig.appearance("full-court-press-you") : { skin: "#f0bd8e", hair: "short", hairColor: "#17130e" }; var state = "idle"; // idle | playing | done var score = 0, steals = 0, fouls = 0, allowed = 0; var elapsed = 0, timeLeft = GAME_LEN; var handlers = [], dying = [], floaters = []; var spawnT = 0, paletteIdx = 0, handlerSeq = 0; var def = { x: 200, y: 350, dir: -Math.PI / 2, stunnedUntil: 0, whiffUntil: 0 }; var keys = {}; var drag = null; // {x, y} target in canvas coords while pointer is down var flashT = 0, flashText = ""; var animT = 0; function verdict() { if (score >= 30) return "🔒 LOCKDOWN LEGEND — nobody gets by you"; if (score >= 21) return "⛓️ All-Defensive First Team"; if (score >= 14) return "🧤 Glove-like — a real pest"; if (score >= 7) return "Scrappy press, some leaks"; if (score >= 1) return "They felt you — barely"; return "Torched. The press got broken tonight."; } function reset() { state = "idle"; score = 0; steals = 0; fouls = 0; allowed = 0; elapsed = 0; timeLeft = GAME_LEN; handlers = []; dying = []; floaters = []; spawnT = 0; paletteIdx = 0; handlerSeq = 0; def.x = 200; def.y = 350; def.dir = -Math.PI / 2; def.stunnedUntil = 0; def.whiffUntil = 0; keys = {}; drag = null; flashT = 0; flashText = ""; updateUI(); } function updateUI() { el.score.textContent = score; el.round.textContent = state === "idle" ? "60.0" : Math.max(0, timeLeft).toFixed(1); el.pts.textContent = steals; } function startGame() { reset(); state = "playing"; el.start.textContent = "Restart"; el.msg.textContent = "Press is on! Shadow the handler — steal when the yellow ring flashes!"; spawnHandler(); updateUI(); } function maxConcurrent() { return elapsed < 20 ? 1 : elapsed < 40 ? 2 : 3; } function handlerSpeed() { return 55 + (105 - 55) * Math.min(1, elapsed / 60); } function spawnHandler() { handlerSeq++; var laneX = 60 + Math.random() * 280; var seed = "full-court-press-handler-" + handlerSeq + "-" + Math.floor(Math.random() * 100000); var appear = Fig ? Fig.appearance(seed) : { skin: "#c68642", hair: "short", hairColor: "#17130e" }; var jersey = PALETTE[paletteIdx % PALETTE.length]; paletteIdx++; handlers.push({ x: laneX, baseX: laneX, y: -20, speed: handlerSpeed() * (0.9 + Math.random() * 0.25), weavePhase: Math.random() * 6.28, weaveAmp: 14 + Math.random() * 18, seed: seed, skin: appear.skin, hair: appear.hair, hairColor: appear.hairColor, jersey: jersey, num: String(1 + Math.floor(Math.random() * 35)), cycleT: 0, nextWindowIn: 1.1 + Math.random() * 1.0, windowUntil: -1, dir: Math.PI / 2 }); } function windowOpen(h) { return h.windowUntil > 0 && animT < h.windowUntil; } function trySteal(tapTarget) { if (state !== "playing") return; if (animT < def.stunnedUntil) { floaters.push({ x: def.x, y: def.y - 24, text: "STUNNED…", life: 0.6 }); return; } if (animT < def.whiffUntil) return; // Targeting: prefer the nearest handler whose steal window is OPEN // within 56px — lunging at the ball that has actually popped loose. // Only if nobody's window is open do we measure the nearest handler // within 48px (a reach-in on a closed window is a foul). // Tap-to-steal (touch): a tap on/near a handler names the target // outright — same ranges and outcomes, judged against that handler. var best = null, bestD = 1e9, bestOpen = false; if (tapTarget) { best = tapTarget; var tdx = tapTarget.x - def.x, tdy = tapTarget.y - def.y; bestD = Math.sqrt(tdx * tdx + tdy * tdy); bestOpen = windowOpen(tapTarget) && bestD <= 56; } else { for (var i = 0; i < handlers.length; i++) { var h = handlers[i]; if (!windowOpen(h)) continue; var dx = h.x - def.x, dy = h.y - def.y; var d = Math.sqrt(dx * dx + dy * dy); if (d < bestD) { bestD = d; best = h; } } if (best && bestD <= 56) bestOpen = true; if (!bestOpen) { best = null; bestD = 1e9; for (var j = 0; j < handlers.length; j++) { var h2 = handlers[j]; var dx2 = h2.x - def.x, dy2 = h2.y - def.y; var d2 = Math.sqrt(dx2 * dx2 + dy2 * dy2); if (d2 < bestD) { bestD = d2; best = h2; } } } } if (!best || bestD > (bestOpen ? 56 : 48)) { def.whiffUntil = animT + 0.35; floaters.push({ x: def.x, y: def.y - 24, text: "whiff…", life: 0.7 }); return; } // Face the handler for the lunge. def.dir = Math.atan2(best.y - def.y, best.x - def.x); if (windowOpen(best)) { score += 3; steals++; dying.push({ x: best.x, y: best.y, jersey: best.jersey, num: best.num, skin: best.skin, hair: best.hair, hairColor: best.hairColor, t: 0, dir: best.dir }); handlers.splice(handlers.indexOf(best), 1); floaters.push({ x: best.x, y: best.y - 18, text: "STEAL! +3", life: 1 }); el.msg.textContent = "STEAL! +3 — ripped it clean!"; spawnT = Math.min(spawnT, 0.4); } else { score = Math.max(0, score - 1); fouls++; def.stunnedUntil = animT + 0.7; floaters.push({ x: def.x, y: def.y - 24, text: "FOUL −1", life: 1 }); el.msg.textContent = "Reach-in foul! −1 — wait for the yellow ring, and you are stunned for a beat."; } updateUI(); } function handlerScores(h) { score = Math.max(0, score - 2); allowed++; handlers.splice(handlers.indexOf(h), 1); flashT = 1.1; flashText = "🏀 they scored"; floaters.push({ x: RIM.x, y: RIM.y - 28, text: "THEY SCORE −2", life: 1 }); el.msg.textContent = "🏀 They scored on you — −2 points. Stay in front of the next one!"; updateUI(); } function endGame() { state = "done"; handlers = []; dying = []; floaters = []; flashT = 0; drag = null; el.msg.textContent = "Full time — final score " + score + " (" + steals + " steals). " + verdict() + " Save it to the board!"; updateUI(); } function drawFallbackTop(x, y, r, jersey, label) { ctx.fillStyle = jersey; ctx.beginPath(); ctx.arc(x, y, r, 0, 7); ctx.fill(); ctx.fillStyle = "#f0bd8e"; ctx.beginPath(); ctx.arc(x, y, r * 0.45, 0, 7); ctx.fill(); if (label) { ctx.fillStyle = "#fff"; ctx.font = "bold 9px sans-serif"; ctx.textAlign = "center"; ctx.fillText(label, x, y - r - 6); } } function drawCourt() { ctx.fillStyle = "#b57e3e"; ctx.fillRect(0, 0, W, H); ctx.fillStyle = "rgba(0,0,0,.05)"; for (var y = 30; y < H; y += 44) ctx.fillRect(0, y, W, 2); ctx.strokeStyle = "rgba(255,255,255,.8)"; ctx.lineWidth = 2; ctx.strokeRect(6, 6, W - 12, H - 12); // Half-court line + centre circle ctx.beginPath(); ctx.moveTo(6, H / 2); ctx.lineTo(W - 6, H / 2); ctx.stroke(); ctx.beginPath(); ctx.arc(W / 2, H / 2, 52, 0, 7); ctx.stroke(); // Bottom key + three-point arc ctx.fillStyle = "rgba(200,16,46,.20)"; ctx.fillRect(W / 2 - 54, 362, 108, 112); ctx.strokeRect(W / 2 - 54, 362, 108, 112); ctx.beginPath(); ctx.arc(RIM.x, RIM.y, 118, Math.PI * 1.08, Math.PI * 1.92); ctx.stroke(); ctx.beginPath(); ctx.arc(RIM.x, RIM.y, 38, 0, 7); ctx.stroke(); // Rim at the bottom basket ctx.strokeStyle = "#e25822"; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(RIM.x, RIM.y, 11, 0, 7); ctx.stroke(); ctx.fillStyle = "#f4f4f4"; ctx.fillRect(RIM.x - 22, RIM.y + 12, 44, 6); } function draw() { ctx.clearRect(0, 0, W, H); drawCourt(); // Clock ctx.fillStyle = state === "playing" && timeLeft <= 10 ? "#ff5a4e" : "#fff"; ctx.font = "bold 22px sans-serif"; ctx.textAlign = "left"; ctx.fillText(state === "idle" ? "60.0" : Math.max(0, timeLeft).toFixed(1), 14, 32); ctx.font = "11px sans-serif"; ctx.fillStyle = "rgba(255,255,255,.9)"; ctx.textAlign = "right"; ctx.fillText("STEALS " + steals + " • FOULS " + fouls, W - 14, 32); // Dying (stolen) handlers: spin + fade dying.forEach(function (d) { ctx.save(); ctx.globalAlpha = Math.max(0, 1 - d.t / 0.55); ctx.translate(d.x, d.y); ctx.rotate(d.t * 9); ctx.translate(-d.x, -d.y); if (Fig) { Fig.top(ctx, { x: d.x, y: d.y, r: 13, dir: d.dir, jersey: d.jersey, trim: "#fff", num: d.num, skin: d.skin, hair: d.hair, hairColor: d.hairColor, ball: false, t: animT }); } else drawFallbackTop(d.x, d.y, 13, d.jersey, null); ctx.restore(); }); ctx.globalAlpha = 1; // Handlers handlers.forEach(function (h) { var open = windowOpen(h); var flash = open && Math.floor(animT * 10) % 2 === 0; var ring = open ? (flash ? "#ffd700" : "#fff176") : null; if (Fig) { Fig.top(ctx, { x: h.x, y: h.y, r: 13, dir: h.dir, jersey: h.jersey, trim: "#ffffff", num: h.num, skin: h.skin, hair: h.hair, hairColor: h.hairColor, ball: true, ring: ring, t: animT }); } else { if (ring) { // Ring closes in as the steal window runs out (0.55s). var frac = Math.max(0, Math.min(1, (h.windowUntil - animT) / 0.55)); ctx.strokeStyle = ring; ctx.lineWidth = 2.4; ctx.beginPath(); ctx.arc(h.x, h.y, 14 + 8 * frac, 0, 7); ctx.stroke(); } drawFallbackTop(h.x, h.y, 13, h.jersey, null); } if (open) { // Loose ball popped out beside the handler. var bx = h.x + 20, by = h.y + 10 + Math.sin(animT * 18) * 2; if (Fig && Fig.ball) Fig.ball(ctx, bx, by, 6); else { ctx.fillStyle = "#e25822"; ctx.beginPath(); ctx.arc(bx, by, 6, 0, 7); ctx.fill(); } ctx.fillStyle = "#ffd700"; ctx.font = "bold 9px sans-serif"; ctx.textAlign = "center"; ctx.fillText("STEAL!", h.x, h.y - 24); } }); // Defender var stunned = animT < def.stunnedUntil; var recovering = animT < def.whiffUntil; var defRing = stunned ? "#9e9e9e" : recovering ? "#bdbdbd" : "#ffd700"; if (Fig) { Fig.top(ctx, { x: def.x, y: def.y, r: 13, dir: def.dir, jersey: "#14418f", trim: "#ffffff", num: "9", skin: DEF_APPEAR.skin, hair: DEF_APPEAR.hair, hairColor: DEF_APPEAR.hairColor, ball: false, ring: defRing, label: "YOU", t: animT }); } else { ctx.strokeStyle = defRing; ctx.lineWidth = 2.4; ctx.beginPath(); ctx.arc(def.x, def.y, 18, 0, 7); ctx.stroke(); drawFallbackTop(def.x, def.y, 13, "#14418f", "YOU"); } if (stunned) { ctx.fillStyle = "#eee"; ctx.font = "bold 10px sans-serif"; ctx.textAlign = "center"; ctx.fillText("STUNNED", def.x, def.y + 30); } // Floaters + scored flash floaters.forEach(function (f) { ctx.globalAlpha = Math.max(0, f.life); ctx.fillStyle = "#ffd700"; ctx.font = "bold 15px sans-serif"; ctx.textAlign = "center"; ctx.fillText(f.text, f.x, f.y); ctx.globalAlpha = 1; }); if (flashT > 0) { ctx.fillStyle = "rgba(200,16,46,.85)"; ctx.font = "bold 24px sans-serif"; ctx.textAlign = "center"; ctx.fillText(flashText, W / 2, 120); } if (state === "idle") { ctx.fillStyle = "rgba(0,0,0,.55)"; ctx.fillRect(0, 186, W, 92); ctx.fillStyle = "#fff"; ctx.font = "bold 23px sans-serif"; ctx.textAlign = "center"; ctx.fillText("🛡️ FULL-COURT PRESS", W / 2, 222); ctx.font = "14px sans-serif"; ctx.fillText("60 seconds. Steal on the yellow flash — never before.", W / 2, 246); } if (state === "done") { ctx.fillStyle = "rgba(0,0,0,.72)"; ctx.fillRect(0, 158, W, 140); ctx.fillStyle = "#fff"; ctx.font = "bold 24px sans-serif"; ctx.textAlign = "center"; ctx.fillText("🏁 Full time", W / 2, 194); ctx.font = "16px sans-serif"; ctx.fillText("Final score: " + score + " • " + steals + " steals • " + allowed + " allowed", W / 2, 222); ctx.font = "bold 15px sans-serif"; ctx.fillStyle = "#ffd700"; ctx.fillText(verdict(), W / 2, 248); ctx.font = "13px sans-serif"; ctx.fillStyle = "#fff"; ctx.fillText("Enter your name below and Save Score!", W / 2, 274); } } var lastFrame = Date.now(); function loop() { var now = Date.now(); var dt = Math.min(0.05, (now - lastFrame) / 1000); lastFrame = now; animT += dt; if (state === "playing") { elapsed += dt; timeLeft = GAME_LEN - elapsed; if (timeLeft <= 0) { timeLeft = 0; endGame(); } else { // Defender movement: drag target takes priority, else keys. var stunned = animT < def.stunnedUntil; var speed = stunned ? 110 : 260; var mvx = 0, mvy = 0; if (drag) { var ddx = drag.x - def.x, ddy = drag.y - def.y; var dd = Math.sqrt(ddx * ddx + ddy * ddy); if (dd > 4) { mvx = ddx / dd; mvy = ddy / dd; if (dd < speed * dt) { def.x = drag.x; def.y = drag.y; mvx = 0; mvy = 0; } } } else { if (keys.left) mvx -= 1; if (keys.right) mvx += 1; if (keys.up) mvy -= 1; if (keys.down) mvy += 1; var ml = Math.sqrt(mvx * mvx + mvy * mvy); if (ml > 0) { mvx /= ml; mvy /= ml; } } if (mvx || mvy) { def.x += mvx * speed * dt; def.y += mvy * speed * dt; def.dir = Math.atan2(mvy, mvx); } else if (handlers.length) { // Idle: face the nearest handler. var nh = handlers[0], nd = 1e9; handlers.forEach(function (h) { var d2 = (h.x - def.x) * (h.x - def.x) + (h.y - def.y) * (h.y - def.y); if (d2 < nd) { nd = d2; nh = h; } }); def.dir = Math.atan2(nh.y - def.y, nh.x - def.x); } if (def.x < 18) def.x = 18; if (def.x > W - 18) def.x = W - 18; if (def.y < 18) def.y = 18; if (def.y > H - 18) def.y = H - 18; // Spawning spawnT -= dt; if (spawnT <= 0) { if (handlers.length < maxConcurrent()) spawnHandler(); spawnT = 0.9 + Math.random() * 0.9; } // Handlers advance + weave + exposure rhythm for (var i = handlers.length - 1; i >= 0; i--) { var h = handlers[i]; h.y += h.speed * dt; h.weavePhase += dt * 2.2; h.x = h.baseX + Math.sin(h.weavePhase) * h.weaveAmp; if (h.x < 28) h.x = 28; if (h.x > W - 28) h.x = W - 28; h.dir = Math.PI / 2 + Math.cos(h.weavePhase) * 0.35; h.cycleT += dt; if (h.windowUntil > 0 && animT >= h.windowUntil) { h.windowUntil = -1; h.cycleT = 0; h.nextWindowIn = 1.1 + Math.random() * 1.0; } else if (h.windowUntil <= 0 && h.cycleT >= h.nextWindowIn) { h.windowUntil = animT + 0.55; } if (h.y >= RIM.y) handlerScores(h); } } dying.forEach(function (d) { d.t += dt; }); dying = dying.filter(function (d) { return d.t < 0.55; }); if (flashT > 0) flashT -= dt; floaters.forEach(function (f) { f.life -= dt * 0.9; f.y -= 26 * dt; }); floaters = floaters.filter(function (f) { return f.life > 0; }); if ((loop.frame = (loop.frame || 0) + 1) % 10 === 0) updateUI(); } draw(); requestAnimationFrame(loop); } /* ================= INPUT ================= */ function canvasPos(e) { var r = cv.getBoundingClientRect(); return { x: (e.clientX - r.left) * (W / r.width), y: (e.clientY - r.top) * (H / r.height) }; } cv.addEventListener("pointerdown", function (e) { e.preventDefault(); var p = canvasPos(e); /* Tap-to-steal: a tap on or within 64px of a handler is a steal attempt on that handler (clean steal / reach-in foul / whiff by the usual ranges) — it does not start a shadow drag. Taps anywhere else keep the drag-shadow control. */ if (state === "playing") { var tapH = null, tapD = 1e9; handlers.forEach(function (h) { var dx = h.x - p.x, dy = h.y - p.y; var d = Math.sqrt(dx * dx + dy * dy); if (d < tapD) { tapD = d; tapH = h; } }); if (tapH && tapD <= 64) { trySteal(tapH); return; } } drag = p; if (cv.setPointerCapture && e.pointerId !== undefined) { try { cv.setPointerCapture(e.pointerId); } catch (err) {} } }); cv.addEventListener("pointermove", function (e) { if (!drag) return; e.preventDefault(); drag = canvasPos(e); }); function endDrag() { drag = null; } cv.addEventListener("pointerup", endDrag); cv.addEventListener("pointercancel", endDrag); cv.addEventListener("pointerleave", endDrag); el.action.addEventListener("pointerdown", function (e) { e.preventDefault(); trySteal(); if (el.action.blur) el.action.blur(); }); window.addEventListener("keydown", function (e) { var inField = document.activeElement && /INPUT/.test(document.activeElement.tagName); if (e.code === "Space") { if (inField) return; // Never let Space re-trigger a focused button (Start/Save) mid-game. if (document.activeElement && document.activeElement.tagName === "BUTTON") document.activeElement.blur(); e.preventDefault(); if (e.repeat) return; if (state === "playing") trySteal(); return; } if (inField) return; if (e.code === "ArrowLeft" || e.code === "KeyA") { keys.left = true; e.preventDefault(); } else if (e.code === "ArrowRight" || e.code === "KeyD") { keys.right = true; e.preventDefault(); } else if (e.code === "ArrowUp" || e.code === "KeyW") { keys.up = true; e.preventDefault(); } else if (e.code === "ArrowDown" || e.code === "KeyS") { keys.down = true; e.preventDefault(); } }); window.addEventListener("keyup", function (e) { if (e.code === "ArrowLeft" || e.code === "KeyA") keys.left = false; else if (e.code === "ArrowRight" || e.code === "KeyD") keys.right = false; else if (e.code === "ArrowUp" || e.code === "KeyW") keys.up = false; else if (e.code === "ArrowDown" || e.code === "KeyS") keys.down = false; }); el.start.addEventListener("click", function () { startGame(); if (el.start.blur) el.start.blur(); }); el.save.addEventListener("click", function () { saveScore(el.name.value, score, el.msg, el.board); if (el.save.blur) el.save.blur(); }); loadBoard(el.board); reset(); draw(); loop(); })();