/* ===================================================================== SPORT ON EARTH PINBALL — Sport on Earth arcade Single-file canvas game in the Family Arcade house style. Real pinball: plunger lane, gravity, bumpers, slingshots, flippers, rollover lanes and a multiball bonus — on a table themed for the SPORT you pick: twelve sports, each with its own table colours (primary/secondary below) and its own ball, drawn in-code. EMBED (inline):
CONTROLS: hold Space / ↓, hold the PLUNGE button, or press-and-hold in the plunger lane to pull the plunger back — release to launch. Flippers: Z (left) and / (right), hold the mouse on the left/right half of the lower table, tap the lower-left / lower-right of the table on touch, or hold the ◀ ▶ flipper buttons. RULES: 3 balls per game. Pop bumpers 100 pts, slingshots 50, rollover lanes S-O-E 50 each, standup targets 50. Light all three S-O-E rollovers, or tag all 3 bumpers inside 4 seconds, to light MULTIBALL (a second ball joins; all scoring ×2 while two balls are live). Drain = ball lost. SCORING (leaderboard): final score when ball 3 drains. ===================================================================== */ (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 "pinball" 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 = "pinball"; var LS_KEY = "soeArcade." + GAME_ID; var LS_NAME = "soeArcade.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 PB_CSS = ".hoops-arcade .pb-canvas{max-width:400px;background:#101014}" + ".hoops-arcade .pb-pick{display:flex;align-items:flex-end;gap:8px;justify-content:space-between;margin:10px 0}" + ".hoops-arcade .pb-pick label{font-size:.75rem;font-weight:700;display:block;text-align:left;margin-bottom:4px}" + ".hoops-arcade .pb-pick select{max-width:230px;padding:7px;border:1px solid var(--line,#d8cfc0);border-radius:6px;font-size:.82rem;background:#fff}" + ".hoops-arcade .pb-logo{width:52px;height:52px;object-fit:contain;flex:none}" + ".hoops-arcade .pb-emoji{font-size:38px;line-height:52px;text-align:center}" + ".hoops-arcade .pb-flips{display:flex;gap:8px;justify-content:space-between;margin:8px 0}" + ".hoops-arcade .pb-flip{flex:1;padding:14px 0;font-size:1rem}" + ".hoops-arcade .pb-plunge{width:100%;margin:0 0 4px}" + ".hoops-arcade .pb-help{font-size:.75rem;color:var(--muted,#666);margin:8px 0;text-align:left;line-height:1.45}"; 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}" + PB_CSS; document.head.appendChild(st); } else if (!document.getElementById("hoopsPinballCss")) { /* Another arcade game already injected the shared sheet — add only this game's own classes under a second style id. */ var st2 = document.createElement("style"); st2.id = "hoopsPinballCss"; st2.textContent = PB_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 = '
    ' + '
    ' + '
    ' + '' + "
    " + '' + '
    ' + '
    Loading sports…
    ' + '
    ' + '
    ' + '' + '
    ' + '
    Loading the sports…
    ' + '

    🕹️ Plunge: hold Space / ↓, hold the plunger button, or press-hold in the right-hand lane, then release. Flippers: Z and / keys, mouse-hold on either half of the lower table, touch the lower-left / lower-right of the table, or the flipper buttons. Bumpers 100, slingshots & targets 50, rollovers S-O-E 50 each. Tag all 3 bumpers within 4 seconds — or light S-O-E — for MULTIBALL (2 balls, scoring ×2). 3 balls per game.

    ' + '
    ' + '
    ' + "
    " + '

    Leaderboard — Sport on Earth Pinball

    1. Loading…
    '; var cv = mount.querySelector("canvas"), ctx = cv.getContext("2d"); var el = { teamSel: mount.querySelector(".pb-team"), logo: mount.querySelector(".pb-logo"), hud: mount.querySelector(".pb-hud"), msg: mount.querySelector(".arcade-msg"), start: mount.querySelector(".start"), plungeBtn: mount.querySelector(".pb-plunge"), flipL: mount.querySelector(".pb-flip-l"), flipR: mount.querySelector(".pb-flip-r"), 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) {} /* ================= HELPERS ================= */ function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; } /* slugify — identical to public/js/live-rosters.js / fantasy-faceoff.js */ function slugify(s) { var out = ""; for (var i = 0; i < s.length; i++) { var ch = s[i].toLowerCase(); out += /[a-z0-9]/.test(ch) ? ch : "-"; } return out.replace(/^-+|-+$/g, "").replace(/-+/g, "-"); } function normalizeName(s) { var t = String(s == null ? "" : s).replace(/^\s*Team\s+/i, ""); return t.toLowerCase().replace(/[^a-z0-9]/g, ""); } function shade(hex, f) { var n = parseInt(String(hex).slice(1), 16); if (isNaN(n)) return hex; var r = clamp(Math.round(((n >> 16) & 255) * f), 0, 255), g = clamp(Math.round(((n >> 8) & 255) * f), 0, 255), b = clamp(Math.round((n & 255) * f), 0, 255); return "rgb(" + r + "," + g + "," + b + ")"; } /* ================= TEAM COLOURS BY RANK (fbi_marks.py PAL, as in Faceoff) ================= */ var PALETTE = { 1: ["#569cd6", "#c9a227"], 2: ["#1e5a34", "#eee8cd"], 3: ["#552582", "#fdb927"], 4: ["#d9772b", "#177c74"], 5: ["#c4761e", "#5e3618"], 6: ["#26262a", "#c9a227"], 7: ["#d8a45e", "#fad65a"], 8: ["#105e2c", "#eee8cd"], 9: ["#5e2b6e", "#4a8c3c"], 10: ["#b2202c", "#1e1a1a"], 11: ["#b01c2e", "#faf0d6"], 12: ["#4a2078", "#c9a227"], 13: ["#0e747c", "#e66e28"], 14: ["#18345c", "#a8d8ea"], 15: ["#172854", "#606e8c"], 16: ["#b22878", "#20b2c7"], 17: ["#d0d2d6", "#46464c"], 18: ["#1b2a4a", "#e9b43c"], 19: ["#a8afb6", "#106e6e"], 20: ["#ce202c", "#181616"], 21: ["#6c1c2c", "#c9a227"], 22: ["#b22234", "#283678"], 23: ["#5c2c8c", "#c9a227"], 24: ["#c81e2c", "#141414"], 25: ["#2c2c34", "#c9a227"], 26: ["#6e7882", "#cf572e"], 27: ["#a0141e", "#181414"], 28: ["#ba2830", "#b2b8be"], 29: ["#968cbe", "#787882"], 30: ["#0a6e78", "#faf6ec"], 31: ["#282430", "#5c2c8c"], 32: ["#6e3a22", "#b2202c"] }; var FALLBACK_PAL = ["#14418f", "#c8102e"]; /* ================= DATA LOAD ================= */ var TEAMS = []; var dataReady = false; var team = null; /* chosen club */ var logoImg = null; function applyTeam() { var t = TEAMS[el.teamSel.selectedIndex] || null; team = t; if (!t) return; el.logo.textContent = t.emoji || ""; el.logo.style.visibility = "visible"; logoImg = null; updateHUD(); } el.logo.onerror = function () { this.style.visibility = "hidden"; }; el.teamSel.addEventListener("change", function () { applyTeam(); draw(); }); var SPORT_THEMES = [{"name": "Soccer", "slug": "soccer", "emoji": "\u26bd", "primary": "#1e7a46", "secondary": "#ffffff", "ball": "soccer"}, {"name": "Basketball", "slug": "basketball", "emoji": "\ud83c\udfc0", "primary": "#c65a1e", "secondary": "#20303c", "ball": "basketball"}, {"name": "American Football", "slug": "american-football", "emoji": "\ud83c\udfc8", "primary": "#6e3a22", "secondary": "#f5e9d0", "ball": "amfootball"}, {"name": "Baseball", "slug": "baseball", "emoji": "\u26be", "primary": "#b01c2e", "secondary": "#f4f1e8", "ball": "baseball"}, {"name": "Tennis", "slug": "tennis", "emoji": "\ud83c\udfbe", "primary": "#3f7a2a", "secondary": "#d7e94a", "ball": "tennis"}, {"name": "Ice Hockey", "slug": "ice-hockey", "emoji": "\ud83c\udfd2", "primary": "#1c3a5e", "secondary": "#a8d8ea", "ball": "puck"}, {"name": "Volleyball", "slug": "volleyball", "emoji": "\ud83c\udfd0", "primary": "#1e5a8c", "secondary": "#ffd23e", "ball": "volleyball"}, {"name": "Golf", "slug": "golf", "emoji": "\u26f3", "primary": "#2e7d46", "secondary": "#ffffff", "ball": "golf"}, {"name": "Cricket", "slug": "cricket", "emoji": "\ud83c\udfcf", "primary": "#7a1e2e", "secondary": "#e8dcc0", "ball": "cricket"}, {"name": "Rugby", "slug": "rugby", "emoji": "\ud83c\udfc9", "primary": "#274e13", "secondary": "#ffd23e", "ball": "rugby"}, {"name": "Table Tennis", "slug": "table-tennis", "emoji": "\ud83c\udfd3", "primary": "#14418f", "secondary": "#e23b3b", "ball": "tt"}, {"name": "Handball", "slug": "handball", "emoji": "\ud83e\udd3e", "primary": "#0e747c", "secondary": "#ffd23e", "ball": "handball"}]; Promise.all([Promise.resolve(null), Promise.resolve(null)]).then(function (res) { SPORT_THEMES.forEach(function (s) { TEAMS.push({ name: s.name, rank: 0, primary: s.primary, secondary: s.secondary, slug: s.slug, emoji: s.emoji, ball: s.ball }); }); if (!TEAMS.length) throw 0; el.teamSel.innerHTML = TEAMS.map(function (t, i) { return '"; }).join(""); el.teamSel.disabled = false; el.teamSel.selectedIndex = 0; var youParam = new URLSearchParams(location.search).get("sport"); if (youParam) { for (var yi = 0; yi < TEAMS.length; yi++) { if (TEAMS[yi].slug === youParam) { el.teamSel.selectedIndex = yi; break; } } } dataReady = true; phase = "pregame"; el.start.disabled = false; el.msg.textContent = "All 12 sports loaded. Pick your sport — the table wears its colours and the ball becomes its ball — and press Start Game!"; applyTeam(); draw(); }).catch(function () { el.msg.textContent = "Could not load the sports — reload the page."; el.hud.textContent = "Sports unavailable"; /* Start stays disabled. */ }); /* ================= TABLE GEOMETRY (playfield coords, y offset GLASS_H) ================= */ var W = 400, H = 680, GLASS_H = 70, PF_H = 610; var BALL_R = 9; var GRAV = 950; /* px/s^2 */ var MAXV = 1500; var segs = []; /* {x1,y1,x2,y2,rest,oneWay} oneWay: unit normal; collide only from that side */ var posts = []; /* {x,y,r,rest,kind} */ var bumpers = []; /* {x,y,r,lit,flash} */ var slings = []; /* segments flagged as slingshot kickers */ var rollovers = []; /* {x,y,r,letter,lit,cool} */ var targets = []; /* {x,y,r,lit,flash} standup targets (posts with score) */ function addSeg(x1, y1, x2, y2, rest, oneWay) { var s = { x1: x1, y1: y1, x2: x2, y2: y2, rest: rest == null ? 0.32 : rest, oneWay: oneWay || null }; segs.push(s); return s; } (function buildTable() { var cx = 200, cy = 190, R = 186, i, a1, a2; for (i = 0; i < 12; i++) { /* top orbit arc, 180deg -> 0deg */ a1 = Math.PI - i * Math.PI / 12; a2 = Math.PI - (i + 1) * Math.PI / 12; addSeg(cx + R * Math.cos(a1), cy - R * Math.sin(a1), cx + R * Math.cos(a2), cy - R * Math.sin(a2), 0.3); } addSeg(14, 190, 14, 440, 0.32); /* left wall */ addSeg(386, 190, 386, 610, 0.32); /* right (lane) wall */ addSeg(350, 214, 350, 540, 0.32); /* plunger lane divider */ /* one-way gate at the top of the lane: playfield balls bounce off its left face; a launched ball passes up the lane on its right side. */ addSeg(350, 214, 368, 120, 0.3, { x: -0.98, y: -0.19 }); addSeg(352, 584, 384, 584, 0.2); /* plunger plate */ addSeg(350, 540, 356, 584, 0.2); /* divider foot into the plate */ addSeg(14, 440, 112, 528, 0.32); /* left lower guide */ addSeg(350, 440, 252, 528, 0.32); /* right lower guide */ /* slingshot triangles above the flippers */ slings.push(addSeg(132, 428, 110, 486, 0.4)); addSeg(92, 428, 132, 428, 0.32); addSeg(92, 428, 110, 486, 0.32); slings.push(addSeg(232, 428, 254, 486, 0.4)); addSeg(232, 428, 272, 428, 0.32); addSeg(272, 428, 254, 486, 0.32); posts.push({ x: 92, y: 428, r: 5, rest: 0.5 }, { x: 132, y: 428, r: 5, rest: 0.5 }, { x: 110, y: 486, r: 5, rest: 0.5 }, { x: 232, y: 428, r: 5, rest: 0.5 }, { x: 272, y: 428, r: 5, rest: 0.5 }, { x: 254, y: 486, r: 5, rest: 0.5 }, { x: 60, y: 356, r: 5, rest: 0.5 }, { x: 304, y: 356, r: 5, rest: 0.5 }); bumpers.push({ x: 104, y: 208, r: 21, lit: 0, flash: 0, touch: false }, { x: 262, y: 198, r: 21, lit: 0, flash: 0, touch: false }, { x: 183, y: 296, r: 21, lit: 0, flash: 0, touch: false }); rollovers.push({ x: 81, y: 71, r: 12, letter: "S", lit: false, cool: 0 }, { x: 200, y: 24, r: 12, letter: "O", lit: false, cool: 0 }, { x: 319, y: 71, r: 12, letter: "E", lit: false, cool: 0 }); /* targets sit 23px clear of the side walls/divider — a ball (18px) must never be able to wedge in the gap (found in soak testing). */ targets.push({ x: 44, y: 322, r: 7, lit: 0, flash: 0, rest: 0.55, touch: false }, { x: 320, y: 322, r: 7, lit: 0, flash: 0, rest: 0.55, touch: false }); })(); /* ================= GAME STATE ================= */ var phase = "loading"; // loading | pregame | ready | playing | gameover var balls = []; /* live balls {x,y,vx,vy,inLane} */ var ballNum = 0; /* 1..3 once started */ var score = 0, mult = 1; /* current scoring multiplier */ var gameTime = 0; var bumperHits = []; /* {idx, t} for the 4-second bonus window */ var bonusLit = false; /* multiball already awarded for this set */ var doubleT = 0; /* timed 2x (when multiball can't spawn) */ var floaters = []; var plunging = false, pull = 0; /* plunger pull 0..1 while holding */ var flipL = { pivot: { x: 126, y: 540 }, len: 50, rest: 0.56, up: -0.52, ang: 0.56, held: false, side: -1 }; var flipR = { pivot: { x: 238, y: 540 }, len: 50, rest: 0.56, up: -0.52, ang: 0.56, held: false, side: 1 }; /* flipper angle measured from the inward horizontal; left flipper tip = pivot + len*(cos ang, sin ang); right flipper mirrored. */ var keysDown = {}; var msgT = 0; function segDist(px, py, f) { var tip = flipTip(f); var dx = tip.x - f.pivot.x, dy = tip.y - f.pivot.y; var len2 = dx * dx + dy * dy || 1; var t = clamp(((px - f.pivot.x) * dx + (py - f.pivot.y) * dy) / len2, 0, 1); var cxp = f.pivot.x + dx * t, cyp = f.pivot.y + dy * t; return Math.sqrt((px - cxp) * (px - cxp) + (py - cyp) * (py - cyp)); } function flipTip(f) { var dx = f.side < 0 ? Math.cos(f.ang) : -Math.cos(f.ang); return { x: f.pivot.x + f.len * dx, y: f.pivot.y + f.len * Math.sin(f.ang) }; } function scoreMult() { return balls.length > 1 ? 2 : (doubleT > 0 ? 2 : 1); } function addScore(base, x, y, label) { var pts = base * scoreMult(); score += pts; floaters.push({ x: x, y: y, text: "+" + pts + (label ? " " + label : ""), life: 1 }); updateHUD(); } function say(t) { el.msg.textContent = t; } function serveBall() { balls = [{ x: 368, y: 575, vx: 0, vy: 0, inLane: true, rest: true }]; pull = 0; plunging = false; phase = "ready"; rollovers.forEach(function (r) { r.lit = false; }); bumperHits = []; bonusLit = false; say("Ball " + ballNum + " of 3 — hold to pull the plunger, release to launch! " + (team ? team.name + " table." : "")); updateHUD(); } function startGame() { if (!dataReady || !team) return; score = 0; ballNum = 1; doubleT = 0; floaters = []; flipL.held = flipR.held = false; el.start.textContent = "Restart"; el.teamSel.disabled = true; el.flipL.disabled = el.flipR.disabled = el.plungeBtn.disabled = false; serveBall(); updateHUD(); } function gameOver() { phase = "gameover"; balls = []; el.start.textContent = "Play Again"; el.teamSel.disabled = false; el.flipL.disabled = el.flipR.disabled = el.plungeBtn.disabled = true; flipL.held = flipR.held = false; plunging = false; say("🏁 Game over — final score " + score + " on the " + (team ? team.name : "") + " table! Save it to the board below, or Play Again."); updateHUD(); } function onDrain(ball) { balls.splice(balls.indexOf(ball), 1); if (balls.length > 0) { /* multiball: play continues on the survivor */ say("Ball drained — multiball over, keep the last one alive!"); updateHUD(); return; } if (ballNum >= 3) { gameOver(); return; } ballNum++; serveBall(); } function triggerBonus() { if (balls.length === 1 && phase === "playing") { balls.push({ x: 200, y: 56, vx: (Math.random() < 0.5 ? -50 : 50), vy: 70, inLane: false, rest: false }); say("🪩 MULTIBALL! Two balls live — all scoring ×2 while both survive!"); floaters.push({ x: 200, y: 150, text: "MULTIBALL!", life: 1.4 }); } else { doubleT = 20; addScore(250, 182, 200, "BONUS ×2 20s"); say("⭐ Bonus! Scoring ×2 for 20 seconds!"); } updateHUD(); } function checkBumperWindow() { var now = gameTime, recent = bumperHits.filter(function (h) { return now - h.t <= 4; }); var seen = {}; recent.forEach(function (h) { seen[h.idx] = true; }); if (Object.keys(seen).length >= 3 && !bonusLit) { bonusLit = true; triggerBonus(); } } function checkLetters() { if (rollovers.every(function (r) { return r.lit; }) && !bonusLit) { bonusLit = true; addScore(500, 182, 120, "S-O-E!"); triggerBonus(); } } /* ================= PHYSICS (fixed timestep, substepped) ================= */ var STEP = 1 / 240; function collideSeg(b, s) { var dx = s.x2 - s.x1, dy = s.y2 - s.y1; var len2 = dx * dx + dy * dy || 1; var t = ((b.x - s.x1) * dx + (b.y - s.y1) * dy) / len2; t = clamp(t, 0, 1); var px = s.x1 + dx * t, py = s.y1 + dy * t; var ox = b.x - px, oy = b.y - py; var d = Math.sqrt(ox * ox + oy * oy); if (d >= BALL_R || d === 0) return false; var nx = ox / d, ny = oy / d; if (s.oneWay) { /* collide only when the ball is on the normal's side and moving in */ if (ox * s.oneWay.x + oy * s.oneWay.y < 0) return false; } b.x = px + nx * BALL_R; b.y = py + ny * BALL_R; var vn = b.vx * nx + b.vy * ny; if (vn < 0) { b.vx -= (1 + s.rest) * vn * nx; b.vy -= (1 + s.rest) * vn * ny; if (s.isSling) slingHit(b, nx, ny, s); } return true; } slings.forEach(function (s) { s.isSling = true; }); function slingHit(b, nx, ny, s) { if (s && s.cool > 0) return; /* a resting ball must not farm the sling */ if (s) s.cool = 0.3; b.vx += nx * 240; b.vy += ny * 240 - 40; addScore(50, b.x, b.y - 14, "SLING"); } function collideCircle(b, c, rest, kick) { var ox = b.x - c.x, oy = b.y - c.y; var rr = BALL_R + c.r, d2 = ox * ox + oy * oy; if (d2 >= rr * rr || d2 === 0) return false; var d = Math.sqrt(d2), nx = ox / d, ny = oy / d; b.x = c.x + nx * rr; b.y = c.y + ny * rr; var vn = b.vx * nx + b.vy * ny; if (vn < 0) { b.vx -= (1 + rest) * vn * nx; b.vy -= (1 + rest) * vn * ny; if (kick) { b.vx += nx * kick; b.vy += ny * kick; } } return true; } /* Like collideCircle but reports the contact: {nx, ny, vn} where vn is the ball's velocity along the outward normal BEFORE reflection (negative = impact). Returns null when not touching. */ function circleContact(b, c, rest) { var ox = b.x - c.x, oy = b.y - c.y; var rr = BALL_R + c.r, d2 = ox * ox + oy * oy; if (d2 >= rr * rr || d2 === 0) return null; var d = Math.sqrt(d2), nx = ox / d, ny = oy / d; b.x = c.x + nx * rr; b.y = c.y + ny * rr; var vn = b.vx * nx + b.vy * ny; if (vn < 0) { b.vx -= (1 + rest) * vn * nx; b.vy -= (1 + rest) * vn * ny; } return { nx: nx, ny: ny, vn: vn }; } function collideFlipper(b, f, dtOmega) { var tip = flipTip(f); var seg = { x1: f.pivot.x, y1: f.pivot.y, x2: tip.x, y2: tip.y }; var dx = seg.x2 - seg.x1, dy = seg.y2 - seg.y1; var len2 = dx * dx + dy * dy || 1; var t = clamp(((b.x - seg.x1) * dx + (b.y - seg.y1) * dy) / len2, 0, 1); var px = seg.x1 + dx * t, py = seg.y1 + dy * t; var ox = b.x - px, oy = b.y - py; var rad = BALL_R + 5; var d = Math.sqrt(ox * ox + oy * oy); if (d >= rad || d === 0) return; var nx = ox / d, ny = oy / d; b.x = px + nx * rad; b.y = py + ny * rad; /* surface velocity at the contact point from the flipper's rotation: for the left flipper a decreasing angle swings the tip up; angular velocity about the pivot is omega (signed, canvas coords). */ var omega = dtOmega; /* rad/s, signed in screen space */ var rx = px - f.pivot.x, ry = py - f.pivot.y; var svx = -omega * ry, svy = omega * rx; var rvx = b.vx - svx, rvy = b.vy - svy; var vn = rvx * nx + rvy * ny; if (vn < 0) { var rest = 0.32; rvx -= (1 + rest) * vn * nx; rvy -= (1 + rest) * vn * ny; b.vx = rvx + svx; b.vy = rvy + svy; } } function stepPhysics(dt) { gameTime += dt; if (doubleT > 0) doubleT -= dt; /* flipper motion: fast swing toward held/rest angle */ [flipL, flipR].forEach(function (f) { var target = f.held ? f.up : f.rest; var prev = f.ang; var speed = f.held ? 26 : 15; /* rad/s */ if (f.ang < target) f.ang = Math.min(target, f.ang + speed * dt); else if (f.ang > target) f.ang = Math.max(target, f.ang - speed * dt); /* screen-space angular velocity of the tip's sweep direction: left flipper tip angle = ang; right flipper tip angle = PI - ang. */ f.omega = (f.ang - prev) / dt * (f.side < 0 ? 1 : -1); }); rollovers.forEach(function (r) { if (r.cool > 0) r.cool -= dt; }); segs.forEach(function (s) { if (s.cool > 0) s.cool -= dt; }); bumpers.forEach(function (bp) { if (bp.flash > 0) bp.flash -= dt; }); targets.forEach(function (tg) { if (tg.flash > 0) tg.flash -= dt; }); floaters.forEach(function (fl) { fl.life -= dt * 0.8; fl.y -= 24 * dt; }); floaters = floaters.filter(function (fl) { return fl.life > 0; }); if (phase !== "playing" && phase !== "ready") return; /* plunger pull builds while held */ if (plunging && phase === "ready") pull = clamp(pull + dt / 0.9, 0, 1); for (var bi = balls.length - 1; bi >= 0; bi--) { var b = balls[bi]; if (b.rest) continue; /* sitting on the plunger plate */ b.vy += GRAV * dt; var sp = Math.sqrt(b.vx * b.vx + b.vy * b.vy); if (sp > MAXV) { b.vx *= MAXV / sp; b.vy *= MAXV / sp; } b.x += b.vx * dt; b.y += b.vy * dt; var i; for (i = 0; i < segs.length; i++) collideSeg(b, segs[i]); for (i = 0; i < posts.length; i++) collideCircle(b, posts[i], posts[i].rest, 0); /* Bumpers/targets fire ONCE per fresh, solid contact (contact latch + impact-speed gate): a ball resting, wedged or balance-bouncing on one must not farm it. The bumper kick is latched too. */ for (i = 0; i < targets.length; i++) { var tg = targets[i], ct = circleContact(b, tg, tg.rest); if (ct) { if (!tg.touch && ct.vn < -110) { tg.flash = 0.35; tg.lit = 1; addScore(50, tg.x, tg.y - 14, "TARGET"); } tg.touch = true; } else tg.touch = false; } for (i = 0; i < bumpers.length; i++) { var bp = bumpers[i], cb = circleContact(b, bp, 0.55); if (cb) { if (!bp.touch) { bp.touch = true; bp.flash = 0.3; bp.lit = 1; if (cb.vn < 0) { b.vx += cb.nx * 265; b.vy += cb.ny * 265; } bumperHits.push({ idx: i, t: gameTime }); addScore(100, bp.x, bp.y - 26, ""); checkBumperWindow(); } } else bp.touch = false; } collideFlipper(b, flipL, flipL.omega || 0); collideFlipper(b, flipR, flipR.omega || 0); /* rollover sensors */ for (i = 0; i < rollovers.length; i++) { var r = rollovers[i]; var ox = b.x - r.x, oy = b.y - r.y; if (ox * ox + oy * oy < (r.r + BALL_R) * (r.r + BALL_R) && r.cool <= 0) { r.cool = 0.8; if (!r.lit) { r.lit = true; addScore(50, r.x, r.y + 22, r.letter + "!"); checkLetters(); } } } /* ball–ball (multiball) */ for (var bj = bi + 1; bj < balls.length; bj++) { var o = balls[bj]; if (o.rest) continue; var bx = o.x - b.x, by = o.y - b.y, bd = Math.sqrt(bx * bx + by * by), min = BALL_R * 2; if (bd > 0 && bd < min) { var nx2 = bx / bd, ny2 = by / bd, push = (min - bd) / 2; b.x -= nx2 * push; b.y -= ny2 * push; o.x += nx2 * push; o.y += ny2 * push; var rvn = (o.vx - b.vx) * nx2 + (o.vy - b.vy) * ny2; if (rvn < 0) { b.vx += rvn * nx2; b.vy += rvn * ny2; o.vx -= rvn * nx2; o.vy -= rvn * ny2; } } } /* Stuck-ball rescue: a ball that stays within 8px of one spot in open play for 1.6s gets a nudge (real tables get nudged) — displacement-based, so flipper jiggles in a pocket can't defeat it — except a ball cradled on a flipper being held up. */ if (phase === "playing") { if (b.ax === undefined || Math.sqrt((b.x - b.ax) * (b.x - b.ax) + (b.y - b.ay) * (b.y - b.ay)) > 8) { b.ax = b.x; b.ay = b.y; b.anchorT = 0; } else b.anchorT = (b.anchorT || 0) + dt; } else b.anchorT = 0; if ((b.anchorT || 0) > 1.6) { /* cradled = actually resting on a HELD flipper's face — a ball wedged at a flipper root or beside the other flipper still gets its nudge (soak testing caught the looser rule). */ var cradled = (flipL.held && segDist(b.x, b.y, flipL) < BALL_R + 7) || (flipR.held && segDist(b.x, b.y, flipR) < BALL_R + 7); if (!cradled) { b.anchorT = 0; b.ax = undefined; b.vx += (b.x < 182 ? 1 : -1) * (70 + Math.random() * 60); b.vy = -170; floaters.push({ x: b.x, y: b.y - 16, text: "NUDGE!", life: 0.9 }); } } /* a launched ball that falls back into the lane and settles = re-serve */ if (b.inLane || b.x > 351) { if (b.x > 351 && b.y > 545 && Math.abs(b.vy) < 60 && Math.abs(b.vx) < 30) { b.x = 368; b.y = 575; b.vx = 0; b.vy = 0; b.rest = true; b.inLane = true; if (phase === "playing") phase = "ready"; } } if (b.x < 349) b.inLane = false; /* drain */ if (!b.rest && b.y - BALL_R > PF_H && b.x < 350) { onDrain(b); continue; } if (!b.rest && b.y > PF_H + 30) { onDrain(b); continue; } } } function launch() { if (phase !== "ready" || !balls.length) return; var b = balls[0]; if (!b.rest) return; b.rest = false; b.inLane = true; b.vy = -(560 + pull * 700); b.vx = 0; pull = 0; plunging = false; phase = "playing"; say("Ball " + ballNum + " in play — Z and / work the flippers!"); updateHUD(); } /* ================= HUD ================= */ var lastHud = ""; function updateHUD() { if (!team) { el.hud.textContent = dataReady ? "Pick your sport" : "Loading sports…"; return; } var s = team.name + "|" + score + "|" + ballNum + "|" + balls.length + "|" + phase + "|" + scoreMult(); if (s === lastHud) return; lastHud = s; el.hud.innerHTML = "Score " + score + " • Ball " + Math.max(1, ballNum) + "/3 • " + escapeHtml(team.name) + (scoreMult() > 1 ? " • ×2 BONUS" : ""); } /* ================= DRAW ================= */ function rr(x, y, w, h, r) { ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); } /* Draw the ball as the chosen sport's ball (a steel pinball when no sport is picked yet). Patterns are drawn in-code — no images, no logos. Also used for the backglass emblem. */ function drawBallAt(x, y, r) { var style = team ? team.ball : "steel"; ctx.save(); ctx.beginPath(); ctx.arc(x, y, r, 0, 7); ctx.clip(); function base(c0, c1) { var g = ctx.createRadialGradient(x - r * 0.35, y - r * 0.35, r * 0.15, x, y, r * 1.05); g.addColorStop(0, c0); g.addColorStop(1, c1); ctx.fillStyle = g; ctx.fillRect(x - r, y - r, r * 2, r * 2); } function ring(col, w) { ctx.beginPath(); ctx.arc(x, y, r - (w || 1), 0, 7); ctx.strokeStyle = col; ctx.lineWidth = w || 1.5; ctx.stroke(); } if (style === "basketball") { base("#f39a4b", "#c65a1e"); ctx.strokeStyle = "rgba(40,20,8,.85)"; ctx.lineWidth = Math.max(1, r * 0.09); ctx.beginPath(); ctx.moveTo(x - r, y); ctx.lineTo(x + r, y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x, y - r); ctx.lineTo(x, y + r); ctx.stroke(); ctx.beginPath(); ctx.arc(x - r * 1.25, y, r * 0.95, -0.6, 0.6); ctx.stroke(); ctx.beginPath(); ctx.arc(x + r * 1.25, y, r * 0.95, Math.PI - 0.6, Math.PI + 0.6); ctx.stroke(); ring("rgba(40,20,8,.85)", Math.max(1, r * 0.09)); } else if (style === "soccer") { base("#ffffff", "#c9ccd4"); ctx.fillStyle = "#191919"; function pent(cx, cy, pr) { ctx.beginPath(); for (var i = 0; i < 5; i++) { var a = -Math.PI / 2 + i * 2 * Math.PI / 5; var px = cx + pr * Math.cos(a), py = cy + pr * Math.sin(a); if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.closePath(); ctx.fill(); } pent(x, y, r * 0.42); for (var k = 0; k < 5; k++) { var aa = -Math.PI / 2 + k * 2 * Math.PI / 5; pent(x + Math.cos(aa) * r * 1.05, y + Math.sin(aa) * r * 1.05, r * 0.34); } } else if (style === "baseball") { base("#ffffff", "#d8d3c8"); ctx.strokeStyle = "#c8102e"; ctx.lineWidth = Math.max(1, r * 0.08); ctx.setLineDash([r * 0.16, r * 0.12]); ctx.beginPath(); ctx.arc(x - r * 1.15, y, r * 0.92, -0.65, 0.65); ctx.stroke(); ctx.beginPath(); ctx.arc(x + r * 1.15, y, r * 0.92, Math.PI - 0.65, Math.PI + 0.65); ctx.stroke(); ctx.setLineDash([]); } else if (style === "tennis") { base("#e3ef5a", "#aebd22"); ctx.strokeStyle = "rgba(255,255,255,.92)"; ctx.lineWidth = Math.max(1.2, r * 0.13); ctx.beginPath(); ctx.arc(x - r * 1.3, y, r * 1.02, -0.62, 0.62); ctx.stroke(); ctx.beginPath(); ctx.arc(x + r * 1.3, y, r * 1.02, Math.PI - 0.62, Math.PI + 0.62); ctx.stroke(); } else if (style === "amfootball" || style === "rugby") { base(style === "rugby" ? "#c08b4e" : "#9c5a28", style === "rugby" ? "#8a5a2b" : "#6e3a22"); ctx.strokeStyle = "#fff"; ctx.lineWidth = Math.max(1, r * 0.1); ctx.beginPath(); ctx.moveTo(x - r, y - r * 0.42); ctx.lineTo(x + r, y - r * 0.42); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x - r * 0.34, y + r * 0.3); ctx.lineTo(x + r * 0.34, y + r * 0.3); ctx.stroke(); ctx.lineWidth = Math.max(0.8, r * 0.07); for (var li = -2; li <= 2; li++) { ctx.beginPath(); ctx.moveTo(x + li * r * 0.17, y + r * 0.18); ctx.lineTo(x + li * r * 0.17, y + r * 0.42); ctx.stroke(); } } else if (style === "puck") { base("#3a3f4a", "#101014"); ring("#6b7280", Math.max(1, r * 0.12)); ctx.fillStyle = "rgba(255,255,255,.20)"; ctx.beginPath(); ctx.ellipse(x, y - r * 0.45, r * 0.62, r * 0.2, 0, 0, 7); ctx.fill(); } else if (style === "golf") { base("#ffffff", "#ccd1d8"); ctx.fillStyle = "rgba(120,128,140,.5)"; var offs = [[-0.45, -0.4], [0.05, -0.55], [0.5, -0.3], [-0.2, -0.05], [0.3, 0.05], [-0.5, 0.3], [0, 0.35], [0.45, 0.4], [-0.15, 0.62], [0.25, 0.66]]; offs.forEach(function (o) { ctx.beginPath(); ctx.arc(x + o[0] * r, y + o[1] * r, Math.max(0.7, r * 0.11), 0, 7); ctx.fill(); }); } else if (style === "cricket") { base("#c22733", "#7a1e2e"); ctx.strokeStyle = "rgba(255,255,255,.9)"; ctx.lineWidth = Math.max(0.8, r * 0.06); ctx.setLineDash([r * 0.14, r * 0.1]); ctx.beginPath(); ctx.arc(x, y, r * 0.66, 0, 7); ctx.stroke(); ctx.setLineDash([]); } else if (style === "volleyball") { base("#ffffff", "#cfd6dd"); ctx.fillStyle = "#1e5a8c"; ctx.beginPath(); ctx.moveTo(x, y); ctx.arc(x, y, r, -0.4, 1.1); ctx.closePath(); ctx.fill(); ctx.fillStyle = "#ffd23e"; ctx.beginPath(); ctx.moveTo(x, y); ctx.arc(x, y, r, 1.9, 3.3); ctx.closePath(); ctx.fill(); ring("rgba(30,60,90,.35)", 1); } else if (style === "handball") { base("#2f6fd0", "#1c3f7c"); ctx.fillStyle = "#ffd23e"; ctx.beginPath(); ctx.moveTo(x, y); ctx.arc(x, y, r, 2.6, 4.1); ctx.closePath(); ctx.fill(); ctx.fillStyle = "#ffffff"; ctx.beginPath(); ctx.moveTo(x, y); ctx.arc(x, y, r, -0.9, 0.35); ctx.closePath(); ctx.fill(); } else if (style === "tt") { base("#f6a83c", "#dd7f14"); } else { base("#ffffff", "#7d838e"); } ctx.restore(); ctx.beginPath(); ctx.arc(x, y, r, 0, 7); ctx.strokeStyle = "rgba(0,0,0,.28)"; ctx.lineWidth = 1; ctx.stroke(); } function drawBackglass() { var p = team ? team.primary : "#22242c", s2 = team ? team.secondary : "#c9a227"; ctx.fillStyle = "#14141a"; ctx.fillRect(0, 0, W, GLASS_H); ctx.fillStyle = p; ctx.fillRect(0, GLASS_H - 6, W, 6); if (team) { drawBallAt(38, 35, 25); } ctx.textAlign = "left"; ctx.textBaseline = "alphabetic"; ctx.fillStyle = s2; ctx.font = "bold 11px sans-serif"; ctx.fillText("SPORT ON EARTH PINBALL", 76, 22); ctx.fillStyle = "#fff"; ctx.font = "bold 19px sans-serif"; ctx.fillText(team ? team.name : "Pick your sport", 76, 46); ctx.font = "11px sans-serif"; ctx.fillStyle = "rgba(255,255,255,.75)"; ctx.fillText("BALL " + Math.max(1, ballNum) + " / 3", 76, 62); ctx.textAlign = "right"; ctx.fillStyle = "#ffd700"; ctx.font = "bold 24px sans-serif"; ctx.fillText(String(score), W - 12, 40); ctx.font = "10px sans-serif"; ctx.fillStyle = "rgba(255,255,255,.75)"; ctx.fillText(scoreMult() > 1 ? "×2 BONUS LIVE" : "SCORE", W - 12, 56); ctx.textAlign = "left"; } function drawTable() { var p = team ? team.primary : "#14418f", s2 = team ? team.secondary : "#c8102e"; ctx.fillStyle = shade(p, 0.32); ctx.fillRect(0, 0, W, PF_H); ctx.fillStyle = shade(p, 0.5); ctx.beginPath(); ctx.arc(200, 190, 178, 0, 7); ctx.fill(); ctx.fillStyle = shade(p, 0.32); ctx.fillRect(14, 190, 336, PF_H - 190); /* lane */ ctx.fillStyle = "rgba(0,0,0,.28)"; ctx.fillRect(351, 100, 35, PF_H - 100); /* club name on the playfield */ ctx.save(); ctx.globalAlpha = 0.30; ctx.fillStyle = "#fff"; ctx.font = "bold 21px sans-serif"; ctx.textAlign = "center"; ctx.fillText(team ? team.name.toUpperCase() : "SPORT ON EARTH", 182, 392); ctx.restore(); /* walls */ ctx.strokeStyle = shade(s2, 1); ctx.lineWidth = 3; ctx.lineCap = "round"; segs.forEach(function (sg) { if (sg.oneWay) return; ctx.beginPath(); ctx.moveTo(sg.x1, sg.y1); ctx.lineTo(sg.x2, sg.y2); ctx.stroke(); }); ctx.strokeStyle = "rgba(255,215,0,.85)"; ctx.lineWidth = 2; /* the one-way gate */ ctx.beginPath(); ctx.moveTo(350, 214); ctx.lineTo(368, 120); ctx.stroke(); /* rollovers */ rollovers.forEach(function (r) { ctx.beginPath(); ctx.arc(r.x, r.y, r.r, 0, 7); ctx.fillStyle = r.lit ? "#ffd700" : "rgba(255,255,255,.16)"; ctx.fill(); ctx.strokeStyle = "#fff"; ctx.lineWidth = 1.5; ctx.stroke(); ctx.fillStyle = r.lit ? "#191919" : "#fff"; ctx.font = "bold 12px sans-serif"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(r.letter, r.x, r.y + 0.5); ctx.textBaseline = "alphabetic"; }); /* bumpers */ bumpers.forEach(function (bp) { ctx.beginPath(); ctx.arc(bp.x, bp.y, bp.r + 4, 0, 7); ctx.fillStyle = bp.flash > 0 ? "#ffd700" : shade(s2, 0.8); ctx.fill(); ctx.beginPath(); ctx.arc(bp.x, bp.y, bp.r, 0, 7); ctx.fillStyle = bp.flash > 0 ? "#fff3b0" : p; ctx.fill(); ctx.strokeStyle = "#fff"; ctx.lineWidth = 2; ctx.stroke(); ctx.beginPath(); ctx.arc(bp.x, bp.y, bp.r * 0.45, 0, 7); ctx.fillStyle = "#fff"; ctx.fill(); }); /* slingshot triangles */ ctx.fillStyle = shade(s2, 0.9); [[92, 428, 132, 428, 110, 486], [232, 428, 272, 428, 254, 486]].forEach(function (tr) { ctx.beginPath(); ctx.moveTo(tr[0], tr[1]); ctx.lineTo(tr[2], tr[3]); ctx.lineTo(tr[4], tr[5]); ctx.closePath(); ctx.fill(); }); /* posts + targets */ posts.forEach(function (po) { ctx.beginPath(); ctx.arc(po.x, po.y, po.r, 0, 7); ctx.fillStyle = "#e8e8e8"; ctx.fill(); ctx.strokeStyle = "#333"; ctx.lineWidth = 1; ctx.stroke(); }); targets.forEach(function (tg) { ctx.beginPath(); ctx.arc(tg.x, tg.y, tg.r, 0, 7); ctx.fillStyle = tg.flash > 0 ? "#ffd700" : "#e23b3b"; ctx.fill(); ctx.strokeStyle = "#fff"; ctx.lineWidth = 1.5; ctx.stroke(); }); /* plunger */ var b0 = balls[0]; if (phase === "ready" && b0 && b0.rest) { var py = 584 + pull * 34; ctx.fillStyle = "#c9ccd4"; ctx.fillRect(360, py, 16, 10); ctx.fillStyle = "#8a8f9a"; ctx.fillRect(366, py + 10, 4, PF_H - py - 10); ctx.fillStyle = "rgba(255,255,255,.25)"; ctx.fillRect(352, 540, 32, 6); ctx.font = "bold 9px sans-serif"; ctx.textAlign = "center"; ctx.fillStyle = "#fff"; ctx.fillText("PULL " + Math.round(pull * 100) + "%", 368, 560); } /* flippers */ [flipL, flipR].forEach(function (f) { var tip = flipTip(f); ctx.strokeStyle = "#f4f4f6"; ctx.lineWidth = 10; ctx.lineCap = "round"; ctx.beginPath(); ctx.moveTo(f.pivot.x, f.pivot.y); ctx.lineTo(tip.x, tip.y); ctx.stroke(); ctx.strokeStyle = s2; ctx.lineWidth = 5; ctx.beginPath(); ctx.moveTo(f.pivot.x, f.pivot.y); ctx.lineTo(tip.x, tip.y); ctx.stroke(); ctx.beginPath(); ctx.arc(f.pivot.x, f.pivot.y, 6, 0, 7); ctx.fillStyle = "#222"; ctx.fill(); }); /* balls — drawn as the chosen sport's ball */ balls.forEach(function (b) { drawBallAt(b.x, b.y, BALL_R); }); /* floaters */ floaters.forEach(function (fl) { ctx.globalAlpha = Math.max(0, fl.life); ctx.fillStyle = "#ffd700"; ctx.font = "bold 15px sans-serif"; ctx.textAlign = "center"; ctx.fillText(fl.text, fl.x, fl.y); ctx.globalAlpha = 1; }); } function banner(title, sub) { ctx.fillStyle = "rgba(0,0,0,.66)"; ctx.fillRect(0, GLASS_H + 236, W, 96); ctx.fillStyle = "#ffd700"; ctx.font = "bold 23px sans-serif"; ctx.textAlign = "center"; ctx.fillText(title, W / 2, GLASS_H + 278); if (sub) { ctx.fillStyle = "#fff"; ctx.font = "13.5px sans-serif"; ctx.fillText(sub, W / 2, GLASS_H + 302); } ctx.textAlign = "left"; } function draw() { ctx.clearRect(0, 0, W, H); drawBackglass(); ctx.save(); ctx.translate(0, GLASS_H); ctx.beginPath(); ctx.rect(0, 0, W, PF_H); ctx.clip(); drawTable(); ctx.restore(); if (phase === "loading") banner("🕹️ SPORT ON EARTH PINBALL", "Loading the sports…"); if (phase === "pregame") banner("🕹️ SPORT ON EARTH PINBALL", "Pick your sport and press Start Game!"); if (phase === "gameover") banner("🏁 GAME OVER", "Final score " + score + " — save it below or Play Again!"); } /* ================= LOOP (fixed timestep accumulator) ================= */ var lastFrame = Date.now(), acc = 0; function loop() { var now = Date.now(); var dt = Math.min(0.06, (now - lastFrame) / 1000); lastFrame = now; acc += dt; var n = 0; while (acc >= STEP && n < 40) { stepPhysics(STEP); acc -= STEP; n++; } if (n === 40) acc = 0; draw(); requestAnimationFrame(loop); } /* ================= INPUT ================= */ function toCourt(e) { var rect = cv.getBoundingClientRect(); return { x: (e.clientX - rect.left) * W / rect.width, y: (e.clientY - rect.top) * H / rect.height }; } var ptrSides = {}; /* pointerId -> "L" | "R" | "P" */ function ptrDown(e) { var p = toCourt(e); if (p.y > GLASS_H + 330) { if (p.x > 345) { ptrSides[e.pointerId] = "P"; plunging = true; } else if (p.x < W / 2) { ptrSides[e.pointerId] = "L"; flipL.held = true; } else { ptrSides[e.pointerId] = "R"; flipR.held = true; } } else if (p.x > 345 && p.y > GLASS_H + 90) { ptrSides[e.pointerId] = "P"; plunging = true; } } function ptrUp(e) { var s = ptrSides[e.pointerId]; delete ptrSides[e.pointerId]; if (s === "L") flipL.held = !!keysDown.KeyZ; if (s === "R") flipR.held = !!keysDown.Slash; if (s === "P") { if (plunging) { plunging = false; launch(); } } } cv.addEventListener("pointerdown", function (e) { e.preventDefault(); ptrDown(e); }); cv.addEventListener("pointerup", ptrUp); cv.addEventListener("pointercancel", ptrUp); cv.addEventListener("mousedown", function (e) { if (e.pointerId === undefined) ptrDown({ pointerId: "m", clientX: e.clientX, clientY: e.clientY }); }); cv.addEventListener("mouseup", function (e) { if (e.pointerId === undefined) ptrUp({ pointerId: "m" }); }); function holdBtn(btn, on, off) { var start = function (e) { e.preventDefault(); on(); }; var end = function (e) { if (e) e.preventDefault(); off(); }; btn.addEventListener("pointerdown", start); btn.addEventListener("pointerup", end); btn.addEventListener("pointerleave", end); btn.addEventListener("pointercancel", end); btn.addEventListener("mousedown", start); btn.addEventListener("mouseup", end); btn.addEventListener("click", function () { this.blur(); }); } holdBtn(el.flipL, function () { flipL.held = true; }, function () { flipL.held = !!keysDown.KeyZ; }); holdBtn(el.flipR, function () { flipR.held = true; }, function () { flipR.held = !!keysDown.Slash; }); holdBtn(el.plungeBtn, function () { plunging = true; }, function () { if (plunging) { plunging = false; launch(); } }); window.addEventListener("keydown", function (e) { var ae = document.activeElement; if (ae && /INPUT|TEXTAREA|SELECT/.test(ae.tagName)) return; keysDown[e.code] = true; if (e.code === "KeyZ") flipL.held = true; if (e.code === "Slash") { flipR.held = true; if (phase === "playing" || phase === "ready") e.preventDefault(); } if (e.code === "Space" || e.code === "ArrowDown") { if (ae && ae.tagName === "BUTTON") return; e.preventDefault(); if (!e.repeat && phase === "ready") plunging = true; } }); window.addEventListener("keyup", function (e) { keysDown[e.code] = false; if (e.code === "KeyZ") flipL.held = Object.keys(ptrSides).some(function (k) { return ptrSides[k] === "L"; }); if (e.code === "Slash") flipR.held = Object.keys(ptrSides).some(function (k) { return ptrSides[k] === "R"; }); if (e.code === "Space" || e.code === "ArrowDown") { if (plunging) { plunging = false; launch(); } } }); window.addEventListener("blur", function () { keysDown = {}; flipL.held = flipR.held = false; plunging = false; ptrSides = {}; }); el.start.addEventListener("click", function () { this.blur(); startGame(); }); el.save.addEventListener("click", function () { this.blur(); saveScore(el.name.value, score, el.msg, el.board); }); /* ================= DEBUG HOOK (headless smoke test) ================= */ window.__pinball = { isReady: function () { return dataReady; }, teamCount: function () { return TEAMS.length; }, teamNames: function () { return TEAMS.map(function (t) { return t.name; }); }, selectTeam: function (i) { if (!TEAMS[i]) return; el.teamSel.selectedIndex = i; applyTeam(); }, selectedTeam: function () { return team ? { name: team.name, slug: team.slug, primary: team.primary, secondary: team.secondary } : null; }, start: function () { startGame(); }, plunge: function (power) { if (phase !== "ready") return false; pull = clamp(power == null ? 1 : power, 0, 1); plunging = false; launch(); return phase === "playing"; }, flip: function (side, on) { if (side === "L" || side === "left") flipL.held = !!on; if (side === "R" || side === "right") flipR.held = !!on; }, step: function (n) { for (var i = 0; i < (n || 1); i++) stepPhysics(STEP); draw(); }, placeBall: function (x, y, vx, vy) { /* test-only: teleport the live ball */ if (!balls.length) return false; var b = balls[0]; b.x = x; b.y = y; b.vx = vx || 0; b.vy = vy || 0; b.rest = false; b.inLane = x > 351; if (phase === "ready") phase = "playing"; return true; }, state: function () { return { phase: phase, score: score, ballNum: ballNum, ballsInPlay: balls.length, mult: scoreMult(), pull: pull, flipL: Math.round(flipL.ang * 100) / 100, flipR: Math.round(flipR.ang * 100) / 100, letters: rollovers.map(function (r) { return r.lit; }), balls: balls.map(function (b) { return { x: Math.round(b.x), y: Math.round(b.y), rest: !!b.rest }; }) }; } }; loadBoard(el.board); draw(); loop(); })();