/* ===================================================================== BOARD BATTLE — Sport on Earth Games arcade Single-file canvas game in the Family Arcade house style. EMBED (inline):
CONTROLS: drag under the rim, or move with ◀ ▶ / A D, to position your rebounder. Tap the court, tap JUMP, or press Space to jump. RULES: twenty shots (or 90 seconds, whichever ends first) come off the rim at random angles. The bounce spot lights up as the ball leaves the rim — get there first, box out whichever opponent is chasing it (stand between him and the spot and he stops cold), then time your jump so you are at your peak as the ball arrives. SCORING: clean board +3 • contested board (an opponent within arm's reach) +5 • a live streak adds +1 per board on the streak (3rd straight board pays +2 extra, 4th pays +3…). An opponent board resets the streak. Your rebounder and both opponents are real club big men (PF/C starters from the Sleeper snapshot: data/sleeper-rosters.json + data/sleeper-players.json); if the snapshot cannot load, generic bigs 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 "board-battle" 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 = "board-battle"; 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: 90.0 • Shot: –/20 • Boards: 0
    ' + '
    Loading the league snapshot…
    ' + '
    ' + '
    Drag, ◀ ▶, or swipe ◀ ▶ to get to the lit bounce spot, box out the nearest big, then tap / Space — or SWIPE UP — to jump at the ball\u2019s arrival!
    ' + '
    ' + '
    ' + "
    " + '

    Leaderboard — Board Battle

    1. Loading…
    '; var cv = mount.querySelector("canvas"), ctx = cv.getContext("2d"); var el = { score: mount.querySelector(".sc"), round: mount.querySelector(".round"), shot: mount.querySelector(".shot"), boards: mount.querySelector(".boards"), match: mount.querySelector(".bb-match"), 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) {} /* ================= LEAGUE SNAPSHOT (real club big men) ================= Same join as fantasy-faceoff.js: rosters carry Sleeper player ids, the players db maps id -> {n, p, t}. The big-man pool is every club's PF/C starters. Any failure falls back to generic bigs and the game still runs. */ var FALLBACK_BIGS = ["Your Center", "Rival Big A", "Rival Big B", "The Enforcer", "Glass Eater", "Second Big"]; var BIGS = FALLBACK_BIGS.slice(); var bigsReady = false; function lastName(name) { var parts = String(name || "").trim().split(/\s+/); return parts.length ? parts[parts.length - 1] : "Player"; } function buildBigs(rosters, playersDb) { var out = [], seen = {}; ((rosters && rosters.teams) || []).forEach(function (t) { (t.starters || []).forEach(function (pid) { var info = playersDb[String(pid)]; if (info && (info.p === "PF" || info.p === "C") && info.n && !seen[info.n]) { seen[info.n] = true; out.push(info.n); } }); }); 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 = buildBigs(res[0], res[1] || {}); if (built.length >= 3) { BIGS = built; bigsReady = true; } refreshMatchLine(); }).catch(function () { bigsReady = false; refreshMatchLine(); }); } /* ================= GAME ================= */ var Fig = window.HoopsFig || null; var W = 400, H = 480; var RIM = { x: 200, y: 118 }; var FLOOR = 428; // feet line for every figure var GAME_LEN = 90, MAX_SHOTS = 20; var AIM_DUR = 0.7, FLIGHT_DUR = 0.55, BOUNCE_DUR = 0.9, PAUSE_DUR = 0.85; var JUMP_DUR = 0.55, JUMP_H = 54; var GRAB_RANGE = 48, CONTEST_RANGE = 62, BOX_RANGE = 34; var state = "idle"; // idle | playing | done var paused = false; var score = 0, boards = 0, oppBoards = 0, contestedWins = 0, looseBalls = 0; var streak = 0, bestStreak = 0; var elapsed = 0, timeLeft = GAME_LEN; var shotNum = 0; var phase = "aim"; // aim | flight | bounce | pause var phaseT = 0; var spotX = 200; // where the bounce lands var ball = { x: 96, y: FLOOR - 96, visible: true }; // shooter holds it during aim var shooter = { x: 96, name: "Shooter" }; var you = { x: 200, jumpT: -1, name: BIGS[0], flip: false }; var opps = [ { x: 138, name: BIGS[1], speed: 82, boxed: false }, { x: 262, name: BIGS[2], speed: 94, boxed: false } ]; var keys = {}; var dragX = null; var floaters = []; var animT = 0; var bigIdx = 0; function verdict() { if (score >= 70) return "🧱 GLASS EMPEROR — the paint is yours"; if (score >= 52) return "💪 Elite glass work — a real problem down low"; if (score >= 36) return "🏀 Solid big-man shift on the boards"; if (score >= 18) return "You battled — the timing is coming"; if (score >= 1) return "Out-muscled tonight. Box out earlier!"; return "Shut out on the glass. Brutal night."; } function pickBigs() { /* Rotate: your big changes every shot; the two opponents are the next two distinct names in the pool. */ var n = BIGS.length; you.name = BIGS[bigIdx % n]; opps[0].name = BIGS[(bigIdx + 1) % n]; opps[1].name = BIGS[(bigIdx + 2) % n]; bigIdx++; } function refreshMatchLine() { if (state === "playing") { el.match.innerHTML = "Your big: " + escapeHtml(you.name) + " vs " + escapeHtml(opps[0].name) + " & " + escapeHtml(opps[1].name) + (bigsReady ? "" : " (snapshot unavailable — generic bigs)"); return; } if (state === "done") return; el.match.textContent = bigsReady ? "Real club big men loaded — " + BIGS.length + " PF/C starters will contest the glass." : "League snapshot unavailable — generic bigs tonight."; } function reset() { state = "idle"; paused = false; score = 0; boards = 0; oppBoards = 0; contestedWins = 0; looseBalls = 0; streak = 0; bestStreak = 0; elapsed = 0; timeLeft = GAME_LEN; shotNum = 0; phase = "aim"; phaseT = 0; spotX = 200; you.x = 200; you.jumpT = -1; opps[0].x = 138; opps[0].boxed = false; opps[1].x = 262; opps[1].boxed = false; keys = {}; dragX = null; floaters = []; bigIdx = 0; pickBigs(); ball = { x: shooter.x, y: FLOOR - 96, visible: true }; updateUI(); } function updateUI() { el.score.textContent = score; el.round.textContent = state === "idle" ? "90.0" : Math.max(0, timeLeft).toFixed(1); el.shot.textContent = (shotNum === 0 ? "–" : Math.min(MAX_SHOTS, shotNum)) + "/" + MAX_SHOTS; el.boards.textContent = boards; } function startGame() { reset(); state = "playing"; el.start.textContent = "Restart"; nextShot(); el.msg.textContent = "Shot 1 — watch the bounce spot light up, get there, box out, and time the jump!"; updateUI(); } function nextShot() { if (shotNum >= MAX_SHOTS || timeLeft <= 0) { endGame(); return; } shotNum++; phase = "aim"; phaseT = 0; /* New random carom for this shot (revealed when the ball leaves the rim). */ spotX = 64 + Math.random() * (W - 128); you.jumpT = -1; opps.forEach(function (o) { o.boxed = false; }); pickBigs(); refreshMatchLine(); ball = { x: shooter.x, y: FLOOR - 96, visible: true }; updateUI(); } function jumpHeight(jt) { if (jt < 0 || jt > JUMP_DUR) return 0; var p = jt / JUMP_DUR; return Math.sin(p * Math.PI) * JUMP_H; } function tryJump() { if (state !== "playing" || paused) return; if (you.jumpT >= 0) return; // already airborne — no double jumps you.jumpT = 0; } function nearestOppDist() { var d = 1e9; opps.forEach(function (o) { d = Math.min(d, Math.abs(o.x - spotX)); }); return d; } function resolveBoard() { var youDist = Math.abs(you.x - spotX); var oppDist = nearestOppDist(); var lift = jumpHeight(you.jumpT); /* Near your peak inside the grab range as the ball arrives, the board is yours; a jump that left the floor a beat before arrival still catches it on the rise if you are right on the spot. */ var onTheRise = you.jumpT >= 0 && you.jumpT <= 0.1 && youDist <= 32; var youGotIt = (lift >= JUMP_H * 0.45 || onTheRise) && youDist <= GRAB_RANGE; if (youGotIt) { var contested = oppDist <= CONTEST_RANGE; boards++; streak++; if (streak > bestStreak) bestStreak = streak; if (contested) contestedWins++; var base = contested ? 5 : 3; var bonus = Math.max(0, streak - 2); score += base + bonus; floaters.push({ x: spotX, y: 300, text: (contested ? "CONTESTED BOARD +" : "CLEAN BOARD +") + (base + bonus) + (bonus ? " (streak)" : ""), life: 1.1 }); el.msg.textContent = (contested ? "💪 CONTESTED BOARD! " : "🧲 Clean board! ") + you.name + " skies for it — +" + (base + bonus) + " (streak " + streak + ")."; ball = { x: you.x, y: FLOOR - 108 - lift, visible: true }; } else if (oppDist <= GRAB_RANGE) { var winner = Math.abs(opps[0].x - spotX) <= Math.abs(opps[1].x - spotX) ? opps[0] : opps[1]; oppBoards++; streak = 0; floaters.push({ x: spotX, y: 300, text: "OUT-JUMPED — THEIR BOARD", life: 1 }); el.msg.textContent = "Out-jumped — " + winner.name + " takes the board. " + (youDist > GRAB_RANGE ? "You were " + Math.round(youDist) + "px from the spot." : lift < JUMP_H * 0.55 ? "Your jump peaked too early or late." : "He simply beat you to it."); ball = { x: winner.x, y: FLOOR - 108, visible: true }; } else { looseBalls++; streak = 0; floaters.push({ x: spotX, y: 300, text: "LOOSE BALL!", life: 1 }); el.msg.textContent = "Nobody claims it — the carom bounces loose. Get to the spot first next time!"; ball = { x: spotX, y: FLOOR - 14, visible: true }; } updateUI(); } function endGame() { if (state === "done") return; state = "done"; el.msg.textContent = "Final — " + boards + " boards (" + contestedWins + " contested), " + oppBoards + " opponent boards, best streak " + bestStreak + ". " + verdict() + " Save it to the board!"; updateUI(); } 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); /* Paint + backboard + rim (side / under-rim view) */ ctx.fillStyle = "rgba(200,16,46,.20)"; ctx.fillRect(RIM.x - 84, 150, 168, H - 150); ctx.strokeStyle = "rgba(255,255,255,.75)"; ctx.lineWidth = 2; ctx.strokeRect(RIM.x - 84, 150, 168, H - 150); ctx.fillStyle = "#f4f4f4"; ctx.fillRect(RIM.x - 42, RIM.y - 40, 84, 30); ctx.strokeStyle = "#c8102e"; ctx.lineWidth = 2; ctx.strokeRect(RIM.x - 42, RIM.y - 40, 84, 30); ctx.strokeRect(RIM.x - 12, RIM.y - 29, 24, 16); ctx.strokeStyle = "#e25822"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(RIM.x - 17, RIM.y); ctx.lineTo(RIM.x + 17, RIM.y); ctx.stroke(); ctx.strokeStyle = "rgba(255,255,255,.9)"; ctx.lineWidth = 1.5; for (var i = -1; i <= 1; i++) { ctx.beginPath(); ctx.moveTo(RIM.x + i * 15, RIM.y + 2); ctx.lineTo(RIM.x + i * 8, RIM.y + 26); ctx.stroke(); } ctx.fillStyle = "rgba(255,255,255,.65)"; ctx.font = "11px sans-serif"; ctx.textAlign = "center"; ctx.fillText("THE GLASS", RIM.x, 168); /* Floor line */ ctx.strokeStyle = "rgba(255,255,255,.8)"; ctx.beginPath(); ctx.moveTo(0, FLOOR + 4); ctx.lineTo(W, FLOOR + 4); ctx.stroke(); } function drawSpot() { if (state !== "playing" || (phase !== "bounce" && phase !== "flight")) return; var pulse = 10 + Math.sin(animT * 10) * 2.5; ctx.strokeStyle = "#ffd700"; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(spotX, FLOOR - 44, pulse + 8, 0, 7); ctx.stroke(); ctx.fillStyle = "rgba(255,215,0,.3)"; ctx.beginPath(); ctx.arc(spotX, FLOOR - 44, pulse + 8, 0, 7); ctx.fill(); ctx.fillStyle = "#ffd700"; ctx.font = "bold 10px sans-serif"; ctx.textAlign = "center"; ctx.fillText("BOUNCE", spotX, FLOOR - 70); } function drawBig(x, name, jersey, num, seed, lift, flip, label, labelColor) { if (Fig) { var ap = Fig.appearance(seed); Fig.draw(ctx, { x: x, y: FLOOR, s: 1.05, flip: !!flip, pose: lift > 4 ? "shoot" : "defend", t: animT, lift: lift, jersey: jersey, num: num, skin: ap.skin, hair: ap.hair, hairColor: ap.hairColor, label: label, labelColor: labelColor }); } else { ctx.fillStyle = "rgba(0,0,0,.2)"; ctx.beginPath(); ctx.ellipse(x, FLOOR + 2, 17, 5, 0, 0, 7); ctx.fill(); ctx.fillStyle = jersey; ctx.beginPath(); ctx.arc(x, FLOOR - 42 - lift, 15, 0, 7); ctx.fill(); ctx.fillStyle = "#f0bd8e"; ctx.beginPath(); ctx.arc(x, FLOOR - 66 - lift, 8, 0, 7); ctx.fill(); if (label) { ctx.fillStyle = labelColor || "#fff"; ctx.font = "bold 10px sans-serif"; ctx.textAlign = "center"; ctx.fillText(label, x, FLOOR - 84 - lift); } } } function draw() { ctx.clearRect(0, 0, W, H); drawCourt(); /* Clock + shot counter */ ctx.fillStyle = state === "playing" && timeLeft <= 10 ? "#ff5a4e" : "#fff"; ctx.font = "bold 22px sans-serif"; ctx.textAlign = "left"; ctx.fillText(state === "idle" ? "90.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("BOARDS " + boards + " • STREAK " + streak, W - 14, 32); drawSpot(); /* Shooter (left edge, puts the shot up each rep) */ if (Fig) { var apS = Fig.appearance("board-battle-shooter"); Fig.draw(ctx, { x: shooter.x, y: FLOOR, s: 0.9, pose: phase === "aim" ? "shoot" : "idle", t: animT, jersey: "#4e342e", num: "3", skin: apS.skin, hair: apS.hair, hairColor: apS.hairColor, ball: phase === "aim" }); } /* Opponents */ drawBig(opps[0].x, opps[0].name, "#c8102e", "5", "board-battle-opp-" + opps[0].name, 0, true, lastName(opps[0].name) + (opps[0].boxed ? " · BOXED" : ""), "#ffb3ab"); drawBig(opps[1].x, opps[1].name, "#6a1b9a", "7", "board-battle-opp-" + opps[1].name, 0, false, lastName(opps[1].name) + (opps[1].boxed ? " · BOXED" : ""), "#d7b8f0"); /* You */ var lift = jumpHeight(you.jumpT); drawBig(you.x, you.name, "#14418f", "9", "board-battle-you-" + you.name, lift, you.x > spotX, "YOU · " + lastName(you.name), "#ffd700"); /* You-ring on the floor */ ctx.strokeStyle = "#ffd700"; ctx.lineWidth = 2.4; ctx.beginPath(); ctx.ellipse(you.x, FLOOR + 3, 20, 5, 0, 0, 7); ctx.stroke(); /* Ball */ if (ball.visible) { if (Fig && Fig.ball) Fig.ball(ctx, ball.x, ball.y, 8); else { ctx.fillStyle = "#e25822"; ctx.beginPath(); ctx.arc(ball.x, ball.y, 8, 0, 7); ctx.fill(); } } /* 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("🧱 BOARD BATTLE", W / 2, 222); ctx.font = "14px sans-serif"; ctx.fillText("20 shots off the glass. Own the bounce spot.", W / 2, 246); } if (state === "done") { ctx.fillStyle = "rgba(0,0,0,.72)"; ctx.fillRect(0, 148, W, 158); ctx.fillStyle = "#fff"; ctx.font = "bold 24px sans-serif"; ctx.textAlign = "center"; ctx.fillText("🏁 Final horn", W / 2, 184); ctx.font = "16px sans-serif"; ctx.fillText("Final score: " + score + " • Boards: " + boards + " (" + contestedWins + " contested)", W / 2, 210); ctx.fillText("Opponent boards: " + oppBoards + " • Loose: " + looseBalls + " • Best streak: " + bestStreak, W / 2, 234); ctx.font = "bold 15px sans-serif"; ctx.fillStyle = "#ffd700"; ctx.fillText(verdict(), W / 2, 260); ctx.font = "13px sans-serif"; ctx.fillStyle = "#fff"; ctx.fillText("Enter your name below and Save Score!", W / 2, 284); } } 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; /* Your lateral movement: drag target beats keys. */ var speed = 250; if (dragX !== null) { var dx = dragX - you.x; var step = Math.max(-speed * dt, Math.min(speed * dt, dx)); you.x += step; } else { if (keys.left) you.x -= speed * dt; if (keys.right) you.x += speed * dt; } if (you.x < 26) you.x = 26; if (you.x > W - 26) you.x = W - 26; /* Jump clock */ if (you.jumpT >= 0) { you.jumpT += dt; if (you.jumpT > JUMP_DUR) you.jumpT = -1; } /* Phase flow */ if (phase === "aim" && phaseT >= AIM_DUR) { phase = "flight"; phaseT = 0; } else if (phase === "flight") { var fp = Math.min(1, phaseT / FLIGHT_DUR); ball.x = shooter.x + (RIM.x - shooter.x) * fp; ball.y = (FLOOR - 96) + (RIM.y - (FLOOR - 96)) * fp - Math.sin(fp * Math.PI) * 120; ball.visible = true; if (phaseT >= FLIGHT_DUR) { phase = "bounce"; phaseT = 0; } } else if (phase === "bounce") { var bp = Math.min(1, phaseT / BOUNCE_DUR); ball.x = RIM.x + (spotX - RIM.x) * bp; ball.y = RIM.y + ((FLOOR - 44) - RIM.y) * bp - Math.sin(bp * Math.PI) * 46; ball.visible = true; /* Opponents hunt the spot — unless you box them out. A box-out is standing within BOX_RANGE of a chaser on the spot side of him: he checks up and stops for the rest of the bounce. */ opps.forEach(function (o) { if (Math.abs(you.x - o.x) <= BOX_RANGE && ((spotX - o.x) * (you.x - o.x) > 0)) o.boxed = true; if (o.boxed) return; var odx = spotX - o.x; var omax = o.speed * dt; o.x += Math.max(-omax, Math.min(omax, odx)); }); if (phaseT >= BOUNCE_DUR) { resolveBoard(); phase = "pause"; phaseT = 0; } } else if (phase === "pause" && phaseT >= PAUSE_DUR) { nextShot(); } } 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 ================= */ var dragStartX = 0, dragMoved = false, tapJumpArmed = false; 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); dragX = p.x; if (cv.setPointerCapture && e.pointerId !== undefined) { try { cv.setPointerCapture(e.pointerId); } catch (err) {} } /* A tap is also a jump when the ball is already bouncing — dragging keeps positioning, tapping in place leaps. A press that starts a drag (pointer moves >10px) never jumps. */ dragStartX = p.x; dragMoved = false; tapJumpArmed = state === "playing" && phase === "bounce"; }); cv.addEventListener("pointermove", function (e) { if (dragX === null) return; e.preventDefault(); var p = canvasPos(e); dragX = p.x; if (Math.abs(p.x - dragStartX) > 10) dragMoved = true; }); function endDrag() { if (tapJumpArmed && !dragMoved) tryJump(); tapJumpArmed = false; dragX = null; } cv.addEventListener("pointerup", endDrag); cv.addEventListener("pointercancel", function () { tapJumpArmed = false; dragX = null; }); el.action.addEventListener("pointerdown", function (e) { e.preventDefault(); tryJump(); 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; if (document.activeElement && document.activeElement.tagName === "BUTTON") document.activeElement.blur(); e.preventDefault(); if (e.repeat) return; if (state === "playing") tryJump(); 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(); } }); 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; }); window.addEventListener("blur", function () { keys = {}; dragX = null; tapJumpArmed = false; }); /* Cheap auto-pause: a hidden tab freezes the battle, 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(); refreshMatchLine(); draw(); loop(); })();