/* ===================================================================== DUNK CONTEST — Sport on Earth Games arcade Single-file canvas game in the Family Arcade house style. EMBED (inline):
CONTROLS: hold the ACTION button (or hold Space) to start the run-up, release inside the striped takeoff zone to launch, then press ACTION / Space once during the flight to lock your trick on the timing bar. Start / Restart with the Start button. SCORING: each dunk = round(takeoff quality x 20 + trick base + timing bonus), capped at 50. Trick bases: 360 Windmill 20, Between the Legs 16, Windmill 12, Two-Hand Jam 8, Basic Jam 5. Timing bonus up to 10 for a dead-centre lock. Overrunning the zone caps the dunk at 18; a takeoff quality under 0.15 rims out. Three dunks, max total 150. FIXES (Oct 14 PM): flight slowed to 1.0s and the gold window widened to ±7.5% so the trick lock is hittable on touch; a pointer released outside the canvas/button now still takes off (window-level pointerup); Start/Save buttons blur after click so Space/Enter can never re-trigger them mid-contest; the ACTION button label follows the phase, the run-up calls the takeoff zone as you enter/leave it, and the judges add a one-line verdict. ===================================================================== */ (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 "dunk-contest" 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 = "dunk-contest"; 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 = '' + '
    ' + '
    Total: 0/150 • Dunk: –/3 • Last dunk: –
    ' + '
    ' + '
    Hold ACTION (or Space) to start your run-up — release inside the takeoff zone!
    ' + '
    ' + '
    ' + "
    " + '

    Leaderboard — Dunk Contest

    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 FLOOR = 430; var RIM = { x: 352, y: 208 }; var ZONE = { x0: 262, x1: 296, cx: 279 }; var BAR = { x0: 50, x1: 350, y: 398, cx: 200 }; var MAXSCORE = 150; var APPEAR = Fig ? Fig.appearance("dunk-contest-player") : { skin: "#f0bd8e", hair: "short", hairColor: "#17130e" }; var state = "idle"; // idle | playing | done var phase = "ready"; // ready | run | flight | judges var dunk = 0; // 0..2 current dunk index var score = 0, lastDunk = null; var dunkScores = []; var playerX = 56, runT = 0, held = false; var flightT = 0, flightDur = 1.0, startX = 56, q = 0, overrun = false; var zoneCue = ""; // "" | "in" | "past" — run-up cue transitions var lift = 0, playerY = FLOOR; var trickName = null, trickBase = 0, lockOffset = null, locked = false; var judges = null, judgesT = 0; var ballAnim = null; // {kind:'make'|'miss', t, x, y, vx, vy} var netJiggle = 0, floaters = [], animT = 0; function verdict() { if (score >= 135) return "Perfect-50 threat — contest LEGEND"; if (score >= 115) return "🏆 Contest champion material!"; if (score >= 95) return "⭐ High-flyer — the crowd loved it"; if (score >= 70) return "Solid dunker, short of the final"; if (score >= 40) return "A few posters, a few bricks"; return "The rim won tonight."; } function reset() { state = "idle"; phase = "ready"; zoneCue = ""; setActionLabel(); dunk = 0; score = 0; lastDunk = null; dunkScores = []; playerX = 56; runT = 0; held = false; flightT = 0; q = 0; overrun = false; lift = 0; playerY = FLOOR; trickName = null; trickBase = 0; lockOffset = null; locked = false; judges = null; judgesT = 0; ballAnim = null; netJiggle = 0; floaters = []; updateUI(); } function updateUI() { el.score.textContent = score; el.round.textContent = (state === "idle" ? "–" : Math.min(3, dunk + 1)) + "/3"; el.pts.textContent = lastDunk === null ? "–" : (lastDunk + " pts"); } function setActionLabel() { el.action.textContent = phase === "flight" ? "TAP — LOCK TRICK!" : "HOLD — ACTION"; } function newDunk() { phase = "ready"; zoneCue = ""; setActionLabel(); playerX = 56; runT = 0; held = false; flightT = 0; q = 0; overrun = false; lift = 0; playerY = FLOOR; trickName = null; trickBase = 0; lockOffset = null; locked = false; judges = null; ballAnim = null; el.msg.textContent = "Dunk " + (dunk + 1) + " of 3 — hold ACTION (or Space) to start your run-up — release inside the takeoff zone!"; updateUI(); } function startGame() { reset(); state = "playing"; el.start.textContent = "Restart"; newDunk(); } function pressAction() { if (state !== "playing") return; if (phase === "ready") { held = true; phase = "run"; runT = 0; el.msg.textContent = "Running… release inside the striped takeoff zone!"; } else if (phase === "flight" && !locked) { lockTrick(); } } function releaseAction() { if (state !== "playing") return; if (phase === "run" && held) { held = false; takeoff(playerX, false); } } function takeoff(releaseX, isOverrun) { startX = releaseX; overrun = !!isOverrun; q = 1 - Math.abs(releaseX - ZONE.cx) / 60; if (q < 0) q = 0; if (q > 1) q = 1; if (overrun) q = Math.min(q, 0.5); phase = "flight"; setActionLabel(); flightT = 0; flightDur = overrun ? 0.6 : 1.0; locked = false; lockOffset = null; trickName = null; trickBase = 0; el.msg.textContent = overrun ? "Overrun! Weak attempt…" : "Airborne! Press ACTION / Space to lock your trick!"; } function lockTrick() { // Timing bar sweeps once across the flight: marker mirrors flight progress. var marker = BAR.x0 + (flightT / flightDur) * (BAR.x1 - BAR.x0); lockOffset = (marker - BAR.cx) / (BAR.x1 - BAR.x0); locked = true; var a = Math.abs(lockOffset); if (a <= 0.075) { trickName = "360 Windmill"; trickBase = 20; } else if (a <= 0.16) { trickName = "Between the Legs"; trickBase = 16; } else if (a <= 0.30) { trickName = "Windmill"; trickBase = 12; } else { trickName = "Two-Hand Jam"; trickBase = 8; } el.msg.textContent = "Locked: " + trickName + "!"; } function splitJudges(total) { // Split the total into 3 plausible parts summing to the total. var base = Math.floor(total / 3), rem = total - base * 3; var parts = [base, base, base]; for (var i = 0; i < rem; i++) parts[i % 3]++; // Small plausible wobble that preserves the sum (keeps parts >= 0). if (total >= 6) { var w = 1 + Math.floor(Math.random() * 2); if (parts[0] - w >= 0) { parts[0] -= w; parts[1] += w; } } // Shuffle so the high card is not always first. for (var j = parts.length - 1; j > 0; j--) { var k = Math.floor(Math.random() * (j + 1)); var tmp = parts[j]; parts[j] = parts[k]; parts[k] = tmp; } return parts; } function resolveDunk() { var missed = q < 0.15 && !overrun; var total; if (missed) { total = Math.round(q * 10); trickName = trickName || "Basic Jam"; ballAnim = { kind: "miss", t: 0, x: RIM.x, y: RIM.y, vx: -90, vy: -120 }; floaters.push({ x: RIM.x - 30, y: RIM.y - 34, text: "RIMS OUT!", life: 1 }); el.msg.textContent = "It rims out — the judges boo politely. Only " + total + " points."; } else { if (!locked) { trickName = "Basic Jam"; trickBase = 5; lockOffset = 0.5; } var timingBonus = locked ? 10 * (1 - Math.abs(lockOffset) / 0.30) : 0; if (timingBonus < 0) timingBonus = 0; total = Math.round(q * 20 + trickBase + timingBonus); if (total > 50) total = 50; if (overrun && total > 18) total = 18; ballAnim = { kind: "make", t: 0, x: RIM.x, y: RIM.y }; netJiggle = 14; floaters.push({ x: RIM.x - 36, y: RIM.y - 34, text: trickName + "! +" + total, life: 1 }); el.msg.textContent = trickName + "! The judges are scoring it…"; } lastDunk = total; dunkScores.push(total); score += total; judges = splitJudges(total); judgesT = 1.9; phase = "judges"; setActionLabel(); updateUI(); } function advance() { if (dunk >= 2) { state = "done"; phase = "ready"; el.msg.textContent = "Contest over — final total " + score + " of " + MAXSCORE + ". " + verdict() + " Save it to the board!"; updateUI(); return; } dunk++; newDunk(); } function drawFallbackFigure(x, y, pose) { ctx.fillStyle = "rgba(0,0,0,.2)"; ctx.beginPath(); ctx.ellipse(x, FLOOR + 2, 15, 4, 0, 0, 7); ctx.fill(); ctx.fillStyle = "#14418f"; ctx.beginPath(); ctx.arc(x, y - 58 - lift, 13, 0, 7); ctx.fill(); ctx.fillStyle = APPEAR.skin; ctx.beginPath(); ctx.arc(x, y - 80 - lift, 7, 0, 7); ctx.fill(); if (pose !== "flight") { ctx.fillStyle = "#e25822"; ctx.beginPath(); ctx.arc(x + 14, y - 44 - lift, 7, 0, 7); ctx.fill(); } } function drawPlayer() { var pose = "idle"; if (phase === "run") pose = "run"; else if (phase === "flight") pose = "shoot"; else if (phase === "judges" && ballAnim && ballAnim.kind === "make") pose = "celebrate"; else if (phase === "ready") pose = "dribble"; var px = playerX; if (phase === "flight" || phase === "judges") { // Horizontal position follows the flight parabola toward the rim. var ft = Math.min(1, flightT / flightDur); px = startX + (RIM.x - 18 - startX) * ft; } var showBall = phase !== "flight" && phase !== "judges"; if (Fig) { Fig.draw(ctx, { x: px, y: FLOOR, s: 1, flip: false, pose: pose, t: animT, lift: lift, jersey: "#c8102e", trim: "#ffffff", shorts: "#14161c", num: "23", skin: APPEAR.skin, hair: APPEAR.hair, hairColor: APPEAR.hairColor, ball: showBall }); } else { drawFallbackFigure(px, FLOOR, pose); } // Separate ball on a make / miss once the dunk resolves. if (ballAnim) { var bx, by; if (ballAnim.kind === "make") { bx = RIM.x; by = RIM.y + 4 + ballAnim.t * 90; if (by > FLOOR - 8) by = FLOOR - 8; } else { bx = ballAnim.x + ballAnim.vx * ballAnim.t; by = ballAnim.y + ballAnim.vy * ballAnim.t + 340 * ballAnim.t * ballAnim.t; if (by > FLOOR - 8) { by = FLOOR - 8; } } ctx.fillStyle = "#e25822"; ctx.beginPath(); ctx.arc(bx, by, 8, 0, 7); ctx.fill(); ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(bx, by, 8, 0, 7); ctx.stroke(); } else if (phase === "flight") { // Ball travels with the shooter toward the rim. var ft2 = Math.min(1, flightT / flightDur); var bx2 = px + 12, by2 = FLOOR - lift - 100 + ft2 * 20; ctx.fillStyle = "#e25822"; ctx.beginPath(); ctx.arc(bx2, by2, 8, 0, 7); ctx.fill(); ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(bx2, by2, 8, 0, 7); ctx.stroke(); } } function drawCourt() { // Arena / crowd band ctx.fillStyle = "#5b3a17"; ctx.fillRect(0, 0, W, 66); ctx.fillStyle = "rgba(255,255,255,.13)"; for (var i = 0; i < 30; i++) ctx.fillRect((i * 41) % W, 10 + (i * 11) % 42, 5, 5); ctx.fillStyle = "#2a2a3a"; ctx.fillRect(0, 66, W, FLOOR - 66); ctx.fillStyle = "rgba(255,255,255,.06)"; for (var c = 0; c < 36; c++) ctx.fillRect((c * 53) % W, 76 + (c * 17) % 90, 4, 4); // Floor ctx.fillStyle = "#b57e3e"; ctx.fillRect(0, FLOOR, W, H - FLOOR); ctx.fillStyle = "rgba(0,0,0,.08)"; ctx.fillRect(0, FLOOR, W, 3); ctx.fillStyle = "rgba(0,0,0,.05)"; for (var x = 24; x < W; x += 44) ctx.fillRect(x, FLOOR, 2, H - FLOOR); // Painted key under the hoop ctx.fillStyle = "rgba(200,16,46,.20)"; ctx.fillRect(304, 330, 96, 100); ctx.strokeStyle = "rgba(255,255,255,.75)"; ctx.lineWidth = 2; ctx.strokeRect(304, 330, 96, 100); // Takeoff zone stripes var inZone = playerX >= ZONE.x0 && playerX <= ZONE.x1; ctx.fillStyle = inZone ? "rgba(46,204,64,.65)" : "rgba(255,215,0,.45)"; ctx.fillRect(ZONE.x0, FLOOR, ZONE.x1 - ZONE.x0, H - FLOOR); ctx.strokeStyle = "rgba(255,255,255,.9)"; ctx.lineWidth = 1.5; for (var sx = ZONE.x0 + 5; sx < ZONE.x1; sx += 9) { ctx.beginPath(); ctx.moveTo(sx, FLOOR + 42); ctx.lineTo(sx + 6, FLOOR + 8); ctx.stroke(); } ctx.fillStyle = "#fff"; ctx.font = "bold 9px sans-serif"; ctx.textAlign = "center"; ctx.fillText("TAKEOFF", ZONE.cx, FLOOR + 47); // Backboard / rim / net (side view, hoop at right) ctx.fillStyle = "#f4f4f4"; ctx.fillRect(368, 150, 10, 84); ctx.strokeStyle = "#c8102e"; ctx.lineWidth = 2; ctx.strokeRect(368, 150, 10, 84); ctx.strokeStyle = "#e25822"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(RIM.x - 16, RIM.y); ctx.lineTo(RIM.x + 16, RIM.y); ctx.stroke(); // Support arm ctx.strokeStyle = "#888"; ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(378, 160); ctx.lineTo(398, 140); ctx.stroke(); ctx.strokeStyle = "rgba(255,255,255,.9)"; ctx.lineWidth = 1.5; var jig = netJiggle > 0 ? Math.sin(netJiggle * 1.4) * 3 : 0; for (var n = -1; n <= 1; n++) { ctx.beginPath(); ctx.moveTo(RIM.x + n * 12, RIM.y + 2); ctx.lineTo(RIM.x + n * 6 + jig, RIM.y + 24); ctx.stroke(); } } function drawTimingBar() { if (phase !== "flight") return; ctx.fillStyle = "rgba(0,0,0,.45)"; ctx.fillRect(BAR.x0, BAR.y, BAR.x1 - BAR.x0, 16); var half = BAR.x1 - BAR.x0; // Zones: gold ±7.5%, then ±16%, then ±30% of bar width from centre. ctx.fillStyle = "#3a7bd5"; ctx.fillRect(BAR.cx - half * 0.30, BAR.y, half * 0.60, 16); ctx.fillStyle = "#2ecc40"; ctx.fillRect(BAR.cx - half * 0.16, BAR.y, half * 0.32, 16); ctx.fillStyle = "#ffd700"; ctx.fillRect(BAR.cx - half * 0.075, BAR.y, half * 0.15, 16); ctx.strokeStyle = "rgba(255,255,255,.7)"; ctx.lineWidth = 1.5; ctx.strokeRect(BAR.x0, BAR.y, half, 16); var marker = locked ? BAR.cx + lockOffset * half : BAR.x0 + (flightT / flightDur) * half; ctx.fillStyle = locked ? "#fff" : "#ffd700"; ctx.beginPath(); ctx.moveTo(marker, BAR.y - 10); ctx.lineTo(marker - 6, BAR.y - 20); ctx.lineTo(marker + 6, BAR.y - 20); ctx.closePath(); ctx.fill(); ctx.fillRect(marker - 1.5, BAR.y - 10, 3, 26); ctx.fillStyle = "#fff"; ctx.font = "10px sans-serif"; ctx.textAlign = "center"; ctx.fillText("TRICK — press ACTION in the gold!", W / 2, BAR.y - 26); } function draw() { ctx.clearRect(0, 0, W, H); drawCourt(); drawPlayer(); drawTimingBar(); // Dunk pips for (var i = 0; i < 3; i++) { ctx.fillStyle = dunkScores[i] !== undefined ? (dunkScores[i] >= 30 ? "#2ecc40" : dunkScores[i] >= 15 ? "#ffd700" : "#c8102e") : i === dunk && state === "playing" ? "#ffd700" : "rgba(255,255,255,.35)"; ctx.beginPath(); ctx.arc(176 + i * 24, 462, 6, 0, 7); ctx.fill(); } // Judges' cards if (phase === "judges" && judges) { ctx.fillStyle = "rgba(0,0,0,.72)"; ctx.fillRect(40, 268, 320, 88); ctx.fillStyle = "#ffd700"; ctx.font = "bold 13px sans-serif"; ctx.textAlign = "center"; ctx.fillText("JUDGES", W / 2, 288); ctx.fillStyle = "#fff"; ctx.font = "bold 22px sans-serif"; ctx.fillText(judges[0] + " • " + judges[1] + " • " + judges[2] + " = " + lastDunk, W / 2, 320); ctx.font = "bold 12px sans-serif"; ctx.fillStyle = "#ffd700"; ctx.fillText(lastDunk >= 45 ? "PERFECT-50 WATCH! 🔥" : lastDunk >= 35 ? "The judges LOVE it!" : lastDunk >= 25 ? "Solid dunk." : lastDunk >= 15 ? "The judges shrug." : "Ouch. Tough crowd.", W / 2, 342); } floaters.forEach(function (f) { ctx.globalAlpha = Math.max(0, f.life); ctx.fillStyle = "#ffd700"; ctx.font = "bold 17px sans-serif"; ctx.textAlign = "center"; ctx.fillText(f.text, f.x, f.y); ctx.globalAlpha = 1; }); if (state === "idle") { ctx.fillStyle = "rgba(0,0,0,.55)"; ctx.fillRect(0, 180, W, 92); ctx.fillStyle = "#fff"; ctx.font = "bold 23px sans-serif"; ctx.textAlign = "center"; ctx.fillText("🏀 DUNK CONTEST", W / 2, 216); ctx.font = "14px sans-serif"; ctx.fillText("Three dunks. One takeoff zone. Fifty is perfect.", W / 2, 240); } if (state === "done") { ctx.fillStyle = "rgba(0,0,0,.72)"; ctx.fillRect(0, 150, W, 140); ctx.fillStyle = "#fff"; ctx.font = "bold 24px sans-serif"; ctx.textAlign = "center"; ctx.fillText("🏁 Contest over", W / 2, 186); ctx.font = "16px sans-serif"; ctx.fillText("Final total: " + score + " / " + MAXSCORE + " (" + dunkScores.join(" + ") + ")", W / 2, 214); ctx.font = "bold 15px sans-serif"; ctx.fillStyle = "#ffd700"; ctx.fillText(verdict(), W / 2, 240); ctx.font = "13px sans-serif"; ctx.fillStyle = "#fff"; ctx.fillText("Enter your name below and Save Score!", W / 2, 266); } } 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") { if (phase === "run") { runT += dt; var speed = 120 + (300 - 120) * Math.min(1, runT / 1.2); playerX += speed * dt; // Call the zone as the runner crosses it (transition-only cues). if (zoneCue === "" && playerX >= ZONE.x0 && playerX <= ZONE.x1) { zoneCue = "in"; el.msg.textContent = "You're in the zone — RELEASE!"; } else if (zoneCue === "in" && playerX > ZONE.x1) { zoneCue = "past"; el.msg.textContent = "Past the zone — let go now or it's an overrun!"; } if (playerX >= 310) { playerX = 310; held = false; takeoff(310, true); } } else if (phase === "flight") { flightT += dt; var ft = Math.min(1, flightT / flightDur); // Parabola: peak lift scaled by takeoff quality (overrun = small hop). var peak = overrun ? 70 : 120 + q * 105; lift = Math.sin(ft * Math.PI) * peak; if (flightT >= flightDur) { lift = 0; resolveDunk(); } } else if (phase === "judges") { if (ballAnim) ballAnim.t += dt; judgesT -= dt; if (judgesT <= 0) { ballAnim = null; advance(); } } if (phase !== "judges" && ballAnim) ballAnim = null; if (netJiggle > 0) netJiggle--; 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) % 15 === 0) updateUI(); } draw(); requestAnimationFrame(loop); } /* ================= INPUT ================= */ function onDown(e) { if (e && e.preventDefault) e.preventDefault(); pressAction(); } function onUp(e) { if (e && e.preventDefault) e.preventDefault(); releaseAction(); if (el.action.blur) el.action.blur(); } el.action.addEventListener("pointerdown", onDown); el.action.addEventListener("pointerup", onUp); el.action.addEventListener("pointerleave", function () { if (phase === "run" && held) releaseAction(); }); el.action.addEventListener("pointercancel", function () { if (phase === "run" && held) releaseAction(); }); cv.addEventListener("pointerdown", onDown); cv.addEventListener("pointerup", onUp); /* Touch overhaul: sliding your finger 40px+ across the court during the run-up also releases the takeoff — a swipe instead of a lift. */ var dunkSwipe = null; cv.addEventListener("pointerdown", function (e) { dunkSwipe = { x: e.clientX, y: e.clientY, used: false }; }); cv.addEventListener("pointermove", function (e) { if (!dunkSwipe || dunkSwipe.used) return; var dx = e.clientX - dunkSwipe.x, dy = e.clientY - dunkSwipe.y; if (dx * dx + dy * dy >= 40 * 40) { dunkSwipe.used = true; if (phase === "run" && held) releaseAction(); } }); // Releasing the pointer anywhere (e.g. finger slid off the canvas) // must still end the hold — otherwise the run sticks until overrun. window.addEventListener("pointerup", function () { if (phase === "run" && held) releaseAction(); }); window.addEventListener("pointercancel", function () { if (phase === "run" && held) releaseAction(); }); window.addEventListener("keydown", function (e) { if (e.code === "Space") { if (document.activeElement && /INPUT/.test(document.activeElement.tagName)) 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; pressAction(); } }); window.addEventListener("keyup", function (e) { if (e.code === "Space") { if (document.activeElement && /INPUT/.test(document.activeElement.tagName)) return; e.preventDefault(); releaseAction(); } }); 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(); })();