/* ===================================================================== LANE BANDIT — Sport on Earth Games arcade Single-file canvas game in the Family Arcade house style. EMBED (inline):
CONTROLS: tap / click a passing lane on the court, use the lane buttons, or press 1–4 as the pass is released. RULES: the opposing ball-handler runs set after set for 60 seconds. His receivers fan out along four visible lanes. Watch his eyes — the target lane flashes gold a beat before the release — then jump that lane WHILE the ball is in flight and inside the middle of the lane: a pick. Jump before the release, jump the wrong lane, or get there late and the pass completes and the offence scores. SCORING: clean pick +3 • perfect pick (dead centre of the lane) +5 • a streak of 3+ picks pays a +2 streak bonus on every pick. A completed pass resets the streak. Pass speed climbs all game. The passing team and players are the real club rosters (Sleeper snapshot: data/sleeper-rosters.json + data/sleeper-players.json); if the snapshot cannot load, generic labels step in and the game still runs. ===================================================================== */ (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 "lane-bandit" 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 = "lane-bandit"; 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) ================= */ var LB_CSS = ".hoops-arcade .lb-lanes{display:flex;gap:6px;justify-content:center;margin:8px 0}" + ".hoops-arcade .lb-lanes .arcade-btn{flex:1;padding:9px 2px;font-size:.78rem;white-space:nowrap;overflow:hidden}"; 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}" + LB_CSS; document.head.appendChild(st); } else if (!document.getElementById("hoopsLaneBanditCss")) { var st2 = document.createElement("style"); st2.id = "hoopsLaneBanditCss"; st2.textContent = LB_CSS; document.head.appendChild(st2); } /* 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 • Picks: 0 • Streak: 0
    ' + '
    Loading the league snapshot…
    ' + '
    ' + '' + '' + '' + '' + "
    " + '
    ' + '
    Watch the passer\u2019s eyes — the target lane flashes gold — then jump that lane (tap it, tap its button, or press 1–4) while the ball is in flight!
    ' + '
    ' + '
    ' + "
    " + '

    Leaderboard — Lane Bandit

    1. Loading…
    '; var cv = mount.querySelector("canvas"), ctx = cv.getContext("2d"); var el = { score: mount.querySelector(".sc"), round: mount.querySelector(".round"), picks: mount.querySelector(".picks"), streak: mount.querySelector(".streak"), match: mount.querySelector(".lb-match"), msg: mount.querySelector(".arcade-msg"), start: mount.querySelector(".start"), name: mount.querySelector(".arcade-name input"), save: mount.querySelector(".save"), board: mount.querySelector(".arcade-board ol"), lanes: [ mount.querySelector(".lane-0"), mount.querySelector(".lane-1"), mount.querySelector(".lane-2"), mount.querySelector(".lane-3") ] }; 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) {} /* ================= LEAGUE SNAPSHOT (real club names) ================= Same join as fantasy-faceoff.js: rosters carry Sleeper player ids, the players db maps id -> {n, p, t}. One cast entry per club: the first five starters — [0] handles the ball, [1..4] run the lanes. Any failure falls back to generic labels and the game still runs. */ var FALLBACK_CAST = [ { team: "The Opposition", players: ["Point Guard", "Wing One", "Wing Two", "Corner Man", "Big Trail"] }, { team: "The Visitors", players: ["Floor General", "Left Wing", "Right Wing", "Baseline Runner", "Trail Big"] } ]; var CAST = FALLBACK_CAST.slice(); var castReady = false; function lastName(name) { var parts = String(name || "").trim().split(/\s+/); return parts.length ? parts[parts.length - 1] : "Player"; } function buildCast(rosters, playersDb) { var out = []; ((rosters && rosters.teams) || []).forEach(function (t) { var starters = (t.starters || []).filter(function (p) { return p && String(p) !== "0"; }).map(String); var names = starters.slice(0, 5).map(function (id) { var info = playersDb[id]; return info && info.n ? info.n : "Unknown Player"; }); while (names.length < 5) names.push(["Point Guard", "Wing One", "Wing Two", "Corner Man", "Big Trail"][names.length]); if (names.length >= 5) out.push({ team: t.name || "Club", players: names }); }); return out; } if (typeof fetch === "function") { Promise.all([ fetch("/data/sleeper-rosters.json").then(function (r) { if (!r.ok) throw 0; return r.json(); }), fetch("/data/sleeper-players.json").then(function (r) { if (!r.ok) throw 0; return r.json(); }) ]).then(function (res) { var built = buildCast(res[0], res[1] || {}); if (built.length) { CAST = built; castReady = true; } refreshCastLine(); }).catch(function () { castReady = false; refreshCastLine(); }); } /* ================= GAME ================= */ var Fig = window.HoopsFig || null; var W = 400, H = 480; var GAME_LEN = 60; var PASSER = { x: 200, y: 84 }; var RECEIVERS = [ { x: 52, y: 396 }, { x: 142, y: 414 }, { x: 258, y: 414 }, { x: 348, y: 396 } ]; var HOME = { x: 200, y: 258 }; var PALETTE = ["#c8102e", "#e67e22", "#2e7d32", "#6a1b9a", "#00838f", "#4e342e", "#283593"]; /* The pick only counts while the ball is in the middle of its lane. */ var ZONE_LO = 0.12, ZONE_HI = 0.82, PERF_LO = 0.38, PERF_HI = 0.62; var state = "idle"; // idle | playing | done var paused = false; var score = 0, picks = 0, completions = 0, streak = 0, bestStreak = 0; var elapsed = 0, timeLeft = GAME_LEN; var phase = "tell"; // tell | flight | pause (inside a set) var phaseT = 0, tellDur = 1.4, flightDur = 0.6; var castIdx = -1, curCast = CAST[0], target = 0, jumped = -1, jumpEarly = false, resolved = false; var def = { x: HOME.x, y: HOME.y, tx: HOME.x, ty: HOME.y, dir: -Math.PI / 2 }; var ball = null; // {x, y} while in flight / held var floaters = []; var animT = 0; var defAppear = Fig ? Fig.appearance("lane-bandit-you") : { skin: "#f0bd8e", hair: "short", hairColor: "#17130e" }; function tellDuration() { return Math.max(0.8, 1.5 - elapsed * 0.011); } function flightDuration() { return Math.max(0.34, 0.62 - elapsed * 0.0045); } function verdict() { if (score >= 36) return "🕵️ LANE BANDIT SUPREME — every pass was yours"; if (score >= 27) return "🧤 All-Defensive hands — a genuine bandit"; if (score >= 18) return "👀 Great reads, real anticipation"; if (score >= 9) return "Sticky in spurts — the reads are coming"; if (score >= 1) return "A pick is a pick. Build from there"; return "Picked apart. Watch the eyes next time."; } function refreshCastLine() { if (state === "playing" || state === "done") return; el.match.textContent = castReady ? "Real club offences loaded — " + CAST.length + " clubs will run their sets at you." : "League snapshot unavailable — generic offences tonight."; } function refreshLaneButtons() { for (var i = 0; i < 4; i++) { el.lanes[i].textContent = (i + 1) + " · " + lastName(curCast.players[i + 1]); } } function reset() { state = "idle"; paused = false; score = 0; picks = 0; completions = 0; streak = 0; bestStreak = 0; elapsed = 0; timeLeft = GAME_LEN; phase = "tell"; phaseT = 0; target = 0; jumped = -1; jumpEarly = false; resolved = false; def.x = HOME.x; def.y = HOME.y; def.tx = HOME.x; def.ty = HOME.y; def.dir = -Math.PI / 2; ball = null; floaters = []; updateUI(); } function updateUI() { el.score.textContent = score; el.round.textContent = state === "idle" ? "60.0" : Math.max(0, timeLeft).toFixed(1); el.picks.textContent = picks; el.streak.textContent = streak; } function startGame() { reset(); state = "playing"; el.start.textContent = "Restart"; newSet(true); el.msg.textContent = "First set — watch the eyes, jump the gold lane as the ball flies!"; updateUI(); } function newSet(first) { castIdx = CAST.length > 1 ? Math.floor(Math.random() * CAST.length) : 0; if (!first && CAST.length > 1 && curCast === CAST[castIdx]) castIdx = (castIdx + 1) % CAST.length; curCast = CAST[castIdx]; target = Math.floor(Math.random() * 4); jumped = -1; jumpEarly = false; resolved = false; phase = "tell"; phaseT = 0; tellDur = tellDuration(); flightDur = flightDuration(); def.tx = HOME.x; def.ty = HOME.y; ball = { x: PASSER.x, y: PASSER.y }; el.match.innerHTML = "" + escapeHtml(curCast.team) + " ball — " + escapeHtml(curCast.players[0]) + " at the top, lanes: " + [1, 2, 3, 4].map(function (n) { return n + " " + escapeHtml(lastName(curCast.players[n])); }).join(" · "); refreshLaneButtons(); } function lanePoint(lane, p) { var r = RECEIVERS[lane]; return { x: PASSER.x + (r.x - PASSER.x) * p, y: PASSER.y + (r.y - PASSER.y) * p }; } function completePass(why) { if (resolved) return; resolved = true; ball = { x: RECEIVERS[target].x, y: RECEIVERS[target].y }; // the catch completions++; if (streak > 0) { /* streak dies on any completion */ } streak = 0; floaters.push({ x: RECEIVERS[target].x, y: RECEIVERS[target].y - 26, text: why || "COMPLETE", life: 1 }); el.msg.textContent = (why === "EARLY!" ? "Too early — you jumped before the release and " : why === "WRONG LANE!" ? "Wrong lane — " : why === "LATE!" ? "A beat late — " : "No jump — ") + curCast.players[target + 1] + " hauls it in. The offence scores; your streak is gone."; phase = "pause"; phaseT = 0; updateUI(); } function intercept(p) { if (resolved) return; resolved = true; picks++; streak++; if (streak > bestStreak) bestStreak = streak; var perfect = p >= PERF_LO && p <= PERF_HI; var pts = perfect ? 5 : 3; var bonus = streak >= 3 ? 2 : 0; score += pts + bonus; ball = { x: def.x, y: def.y }; // the pick: ball ends in the defender's hands floaters.push({ x: def.x, y: def.y - 28, text: (perfect ? "PERFECT PICK +" : "PICK! +") + pts + (bonus ? " +2 STREAK" : ""), life: 1.1 }); el.msg.textContent = (perfect ? "🎯 PERFECT PICK! " : "🖐️ PICK! ") + "You jumped " + curCast.players[target + 1] + "\u2019s lane dead on time — +" + (pts + bonus) + (streak >= 3 ? " (streak bonus live at " + streak + ")" : "") + "."; phase = "pause"; phaseT = 0; updateUI(); } function jumpLane(lane) { if (state !== "playing" || paused) return; if (phase === "pause" || jumped !== -1) return; jumped = lane; /* Lunge: the defender dives to the middle of the chosen lane. */ var mid = lanePoint(lane, 0.52); def.tx = mid.x; def.ty = mid.y; def.dir = Math.atan2(mid.y - def.y, mid.x - def.x); if (phase === "tell") { jumpEarly = true; floaters.push({ x: def.x, y: def.y - 26, text: "EARLY!", life: 0.9 }); return; // resolution lands when the pass completes } if (phase === "flight") { var p = phaseT / flightDur; if (lane !== target) { completePass("WRONG LANE!"); return; } if (p < ZONE_LO) { jumpEarly = true; completePass("EARLY!"); return; } if (p > ZONE_HI) { completePass("LATE!"); return; } intercept(p); } } function endGame() { state = "done"; ball = null; el.msg.textContent = "Full time — final score " + score + " (" + picks + " picks, " + completions + " completions, best streak " + bestStreak + "). " + 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); 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(); /* The four passing lanes, always visible. */ for (var i = 0; i < 4; i++) { var r = RECEIVERS[i]; var isTarget = state === "playing" && i === target; var tellOn = isTarget && phase === "tell" && phaseT >= tellDur - 0.38; var flown = isTarget && phase === "flight"; ctx.strokeStyle = tellOn ? "#ffd700" : flown ? "rgba(255,215,0,.75)" : "rgba(255,255,255,.38)"; ctx.lineWidth = tellOn ? 5 : 2.5; ctx.setLineDash(tellOn || flown ? [] : [7, 6]); ctx.beginPath(); ctx.moveTo(PASSER.x, PASSER.y); ctx.lineTo(r.x, r.y); ctx.stroke(); ctx.setLineDash([]); /* Jump zone band across every lane. */ var z0 = lanePoint(i, ZONE_LO), z1 = lanePoint(i, ZONE_HI); ctx.strokeStyle = "rgba(46,204,64,.55)"; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(z0.x - 9, z0.y); ctx.lineTo(z0.x + 9, z0.y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(z1.x - 9, z1.y); ctx.lineTo(z1.x + 9, z1.y); ctx.stroke(); /* Lane number at the receiver end. */ ctx.fillStyle = "#fff"; ctx.font = "bold 13px sans-serif"; ctx.textAlign = "center"; ctx.fillText(String(i + 1), r.x, r.y + 34); } } function drawFigure(x, y, dir, jersey, num, seed, label, ring, withBall) { if (Fig) { var ap = Fig.appearance(seed); Fig.top(ctx, { x: x, y: y, r: 13, dir: dir, jersey: jersey, trim: "#ffffff", num: num, skin: ap.skin, hair: ap.hair, hairColor: ap.hairColor, ball: !!withBall, ring: ring || undefined, label: label || undefined, t: animT }); } else { if (ring) { ctx.strokeStyle = ring; ctx.lineWidth = 2.4; ctx.beginPath(); ctx.arc(x, y, 18, 0, 7); ctx.stroke(); } drawFallbackTop(x, y, 13, jersey, label); if (withBall && Fig && Fig.ball) Fig.ball(ctx, x + 18, y + 8, 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("PICKS " + picks + " • STREAK " + streak, W - 14, 32); /* Set + team line */ ctx.font = "bold 12px sans-serif"; ctx.textAlign = "center"; ctx.fillStyle = "#fff"; if (state === "playing") { ctx.fillText(curCast.team, W / 2, 32); } /* Receivers */ for (var i = 0; i < 4; i++) { var r = RECEIVERS[i]; drawFigure(r.x, r.y, -Math.PI / 2, PALETTE[i % PALETTE.length], String(i + 1), "lane-bandit-recv-" + curCast.team + "-" + i, lastName(curCast.players[i + 1]), null, false); } /* Passer (holds the ball until the release) */ drawFigure(PASSER.x, PASSER.y, Math.PI / 2, "#283593", "1", "lane-bandit-passer-" + curCast.team, lastName(curCast.players[0]), null, state === "playing" && phase === "tell"); /* Ball in flight */ if (state === "playing" && phase === "flight" && ball) { if (Fig && Fig.ball) Fig.ball(ctx, ball.x, ball.y, 7); else { ctx.fillStyle = "#e25822"; ctx.beginPath(); ctx.arc(ball.x, ball.y, 7, 0, 7); ctx.fill(); } } /* Defender (you) */ if (Fig) { Fig.top(ctx, { x: def.x, y: def.y, r: 13, dir: def.dir, jersey: "#14418f", trim: "#ffffff", num: "9", skin: defAppear.skin, hair: defAppear.hair, hairColor: defAppear.hairColor, ball: state === "playing" && phase === "pause" && resolved && ball && ball.x === def.x, ring: "#ffd700", label: "YOU", t: animT }); } else drawFallbackTop(def.x, def.y, 13, "#14418f", "YOU"); /* Floaters */ 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 (paused && state === "playing") { ctx.fillStyle = "rgba(0,0,0,.6)"; ctx.fillRect(0, 206, W, 68); ctx.fillStyle = "#fff"; ctx.font = "bold 22px sans-serif"; ctx.textAlign = "center"; ctx.fillText("⏸ PAUSED", W / 2, 248); } 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("🕵️ LANE BANDIT", W / 2, 222); ctx.font = "14px sans-serif"; ctx.fillText("60 seconds. Read the eyes, jump the lane, take the ball.", 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 + " • " + picks + " picks • " + completions + " completions", 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" && !paused) { elapsed += dt; timeLeft = GAME_LEN - elapsed; if (timeLeft <= 0) { timeLeft = 0; endGame(); } else { phaseT += dt; /* Defender lunge / return glide */ var dx = def.tx - def.x, dy = def.ty - def.y; var dd = Math.sqrt(dx * dx + dy * dy); if (dd > 1) { var step = Math.min(dd, 620 * dt); def.x += dx / dd * step; def.y += dy / dd * step; } if (phase === "tell" && phaseT >= tellDur) { phase = "flight"; phaseT = 0; if (jumpEarly) { /* an early jump is already beaten — but the ball still flies */ } } else if (phase === "flight") { var p = Math.min(1, phaseT / flightDur); var pt = lanePoint(target, p); ball = { x: pt.x, y: pt.y }; if (phaseT >= flightDur) { if (!resolved) completePass(jumpEarly ? "EARLY!" : null); else { phase = "pause"; phaseT = 0; } } } else if (phase === "pause" && phaseT >= 0.75) { newSet(false); } } 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) }; } function laneFromPoint(pt) { /* Nearest lane by angle from the passer (lanes fan out from him). */ var ang = Math.atan2(pt.y - PASSER.y, pt.x - PASSER.x); var best = 0, bestD = 1e9; for (var i = 0; i < 4; i++) { var la = Math.atan2(RECEIVERS[i].y - PASSER.y, RECEIVERS[i].x - PASSER.x); var d = Math.abs(la - ang); if (d < bestD) { bestD = d; best = i; } } return best; } cv.addEventListener("pointerdown", function (e) { e.preventDefault(); if (state !== "playing") return; jumpLane(laneFromPoint(canvasPos(e))); }); el.lanes.forEach(function (btn, i) { btn.addEventListener("pointerdown", function (e) { e.preventDefault(); jumpLane(i); if (btn.blur) btn.blur(); }); btn.addEventListener("click", function (e) { e.preventDefault(); if (btn.blur) btn.blur(); }); }); window.addEventListener("keydown", function (e) { var inField = document.activeElement && /INPUT/.test(document.activeElement.tagName); if (inField) return; var lane = -1; if (e.code === "Digit1" || e.code === "Numpad1") lane = 0; else if (e.code === "Digit2" || e.code === "Numpad2") lane = 1; else if (e.code === "Digit3" || e.code === "Numpad3") lane = 2; else if (e.code === "Digit4" || e.code === "Numpad4") lane = 3; if (lane >= 0) { if (document.activeElement && document.activeElement.tagName === "BUTTON") document.activeElement.blur(); e.preventDefault(); if (!e.repeat) jumpLane(lane); } }); /* Cheap auto-pause: a hidden tab freezes the sets, not the clock. */ document.addEventListener("visibilitychange", function () { if (state !== "playing") return; paused = document.hidden === true; if (!paused) lastFrame = Date.now(); }); 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(); refreshCastLine(); draw(); loop(); })();