Pinball Game in JavaScript: Free HTML5 Canvas Pinball
Carnival Pinball Game · Games · Plain HTML, CSS & JS · Live preview
About this UI Snippet
Carnival Pinball: Canvas Pinball With Missions, Multiball, Perks and Four Modes

Carnival Pinball is a complete pinball table in the browser, drawn on canvas with its own physics and no libraries, images or sound files. Charge the plunger, aim for the lit top lane, work the flippers and use the centre hole to start missions. For other arcade games in the library try Breakout Brick Game or Asteroids Blaster.
The table
Three pop bumpers, two slingshots, a drop target bank on the left, a second bank on the right, S-K-Y rollover lanes, a spinner, a centre hole, inlanes, outlanes and kickbacks. Flipping rotates the lit top lanes, so you can steer the one you still need under the ball.
Scoring, missions and multiball
Clearing the left bank raises the playfield multiplier up to 5, and lighting S-K-Y raises the end-of-ball bonus multiplier up to 6. The centre hole starts one of four timed missions. Clearing the right bank twice lights the lock for three-ball multiball with jackpots, and every third mission starts Carnival, a 30 second round where everything scores five times more. Shots in quick succession build combos, and an extra ball arrives at 150,000.
Perks and modes
Each finished mission offers three perks and you keep one: a post between the flippers, longer flippers, kickbacks, gentler gravity and more. Classic gives three balls, Blitz gives two minutes with endless balls, Zen never ends, and Daily seeds the perk offers, mission order and skill shots from the date.
How the physics works
The simulation runs in fixed steps of 1/600 of a second, so a fast ball cannot pass through a wall. Walls and flippers are line segments and bumpers are circles. A moving flipper passes the speed of its surface to the ball, which is why a tip shot goes further than one near the hinge.
Best scores are kept in localStorage where the browser allows it. Sandboxed previews block storage, so scores there last only until the page reloads.
What's included
Features
Step by step
How to Use
- 1LaunchHold Space, or hold a finger on the table, and release. More charge means a faster ball. Hit the flashing top lane for the skill shot.
- 2FlipZ and / or the left and right arrows. Shift keys also work. On touch screens, tap the left or right half.
- 3Nudge with carePress the up arrow, X or the Nudge button to shove the table. Too many nudges in a row tilts it and ends the ball without bonus.
- 4Start missionsShoot the centre hole, then complete the shown goal before the timer ends to score 25,000 and pick a perk.
- 5Chase multiballLight all three right targets, twice, then shoot the centre hole.
- 6Pause or muteP or Escape pauses, M mutes everything, and the Music button turns off only the tune.
Real-world uses
Common Use Cases
Got questions?
Frequently Asked Questions
Z or left arrow for the left flipper, / or right arrow for the right, Space to launch, up arrow or X to nudge, P to pause and M to mute. On touch screens tap each half of the table.
Hit all three right-side targets to complete the bank, do it a second time to light the lock, then shoot the centre hole.
The table tilted from too much nudging. Flippers return on the next ball.
The mission order, perk offers and skill lane come from the date. Ball movement still depends on your timing and has small random variation.
No. The collision and movement code is part of the snippet.
Copy & paste
Source Code
<div class="cp">
<aside class="cp-panel">
<h1>Carnival <span>Pinball</span></h1>
<div class="cp-score">
<small>Score</small>
<strong id="score">0</strong>
</div>
<div class="cp-stats">
<div><small id="ballsLabel">Ball</small><b id="balls">1</b></div>
<div><small>Multiplier</small><b id="multi">x1</b></div>
<div><small>Best</small><b id="best">0</b></div>
</div>
<div class="cp-card cp-mission">
<small>Mission</small>
<b id="missionName">Shoot the centre hole</b>
<p id="missionText">Start a mission to earn a perk</p>
<div class="cp-bar"><i id="missionBar"></i></div>
</div>
<div class="cp-card cp-perks"><small>Perks</small><p id="perkNames">None yet</p></div>
<p class="cp-keys"><kbd>Z</kbd> <kbd>/</kbd> or <kbd>←</kbd> <kbd>→</kbd> flip · <kbd>Space</kbd> launch · <kbd>↑</kbd> nudge · <kbd>P</kbd> pause</p>
<div class="cp-buttons">
<button type="button" id="nudgeBtn">Nudge</button>
<button type="button" id="pauseBtn">Pause</button>
<button type="button" id="soundBtn">Sound on</button>
<button type="button" id="musicBtn">Music on</button>
<button type="button" id="menuBtn">Modes</button>
</div>
<p id="message" class="cp-sr" aria-live="polite"></p>
</aside>
<main class="cp-play" id="playArea">
<canvas id="table" tabindex="0" aria-label="Pinball table"></canvas>
<div class="cp-overlay" id="menu">
<div class="cp-box">
<h2>Carnival Pinball</h2>
<p>Missions, multiball and a perk to pick after every mission.</p>
<button type="button" class="cp-main" id="playBtn">Play</button>
<div class="cp-modes">
<button type="button" id="blitzBtn"><b>Blitz</b><span>2 minutes, endless balls</span></button>
<button type="button" id="zenBtn"><b>Zen</b><span>Never game over</span></button>
<button type="button" id="dailyBtn"><b>Daily</b><span>Same perks for everyone today</span></button>
</div>
<p class="cp-help">Keys: <b>Z</b> and <b>/</b> flip, <b>Space</b> launches. Touch: tap left or right side.</p>
<p class="cp-help" id="bests"></p>
</div>
</div>
<div class="cp-overlay" id="perkPick" hidden>
<div class="cp-box">
<h2>Pick a perk</h2>
<div class="cp-perklist" id="perkList"></div>
</div>
</div>
<div class="cp-overlay" id="pauseBox" hidden>
<div class="cp-box">
<h2>Paused</h2>
<button type="button" class="cp-main" id="resumeBtn">Resume</button>
<button type="button" class="cp-link" id="quitBtn">Quit to modes</button>
</div>
</div>
<div class="cp-overlay" id="gameOver" hidden>
<div class="cp-box">
<h2 class="cp-title" id="overTitle">Game over</h2>
<p class="cp-final" id="overScore">0</p>
<p id="overNote"></p>
<button type="button" class="cp-main" id="againBtn">Play again</button>
<button type="button" class="cp-link" id="modesBtn">Change mode</button>
</div>
</div>
</main>
</div>* { box-sizing: border-box; }
html, body { height: 100%; }
body { margin: 0; overflow: hidden; font-family: 'Trebuchet MS', 'Segoe UI', Arial, sans-serif; color: #2b2d5c; background: #fff3dc; }
.cp { display: flex; justify-content: center; gap: 18px; height: 100%; min-height: 360px; padding: 10px; background: radial-gradient(circle at 20% 15%, #d4efff, transparent 55%), radial-gradient(circle at 85% 90%, #ffd9d2, transparent 55%), #fff3dc; }
.cp-panel { display: flex; flex-direction: column; justify-content: center; gap: 9px; width: 250px; flex: none; min-height: 0; }
.cp-panel h1 { margin: 0; font-size: 30px; line-height: 1; text-transform: uppercase; }
.cp-panel h1 span { display: block; color: #ff6b6b; }
.cp small { display: block; font-size: 10px; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: #7a7c9f; }
.cp-score { padding: 8px 14px; border-radius: 14px; background: #2b2d5c; color: #fff; }
.cp-score small { color: #b9bbe0; }
.cp-score strong { display: block; font-size: 32px; font-variant-numeric: tabular-nums; color: #ffc93c; }
.cp-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; }
.cp-stats div, .cp-card { padding: 7px 11px; border-radius: 12px; background: #fff; box-shadow: 0 3px 0 rgba(43,45,92,0.1); }
.cp-stats div:last-child { grid-column: 1 / -1; }
.cp-stats b { font-size: 15px; font-variant-numeric: tabular-nums; }
.cp-card b { display: block; font-size: 15px; }
.cp-card p { margin: 2px 0 0; font-size: 12px; color: #5a5c82; }
.cp-bar { height: 6px; margin-top: 6px; border-radius: 6px; background: #eef0f8; overflow: hidden; }
.cp-bar i { display: block; height: 100%; width: 0; background: #12b5a5; transition: width 0.2s; }
.cp-keys { margin: 0; font-size: 11px; line-height: 1.9; color: #5a5c82; }
kbd { padding: 1px 5px; border-radius: 4px; background: #fff; border: 1px solid #d5d6e8; font: 700 10px monospace; }
.cp-buttons { display: flex; flex-wrap: wrap; gap: 6px; }
.cp button { font-family: inherit; color: inherit; cursor: pointer; }
.cp-buttons button { padding: 6px 10px; font-size: 12px; font-weight: 700; background: #fff; border: 2px solid #2b2d5c; border-radius: 99px; }
.cp button:focus-visible { outline: 3px solid #4d9de0; outline-offset: 2px; }
.cp-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.cp-play { position: relative; flex: 0 1 470px; display: flex; align-items: center; justify-content: center; min-width: 0; min-height: 0; touch-action: none; user-select: none; -webkit-user-select: none; -webkit-tap-highlight-color: transparent; }
.cp-play canvas { display: block; border-radius: 18px; box-shadow: 0 14px 34px rgba(43,45,92,0.28); outline: none; }
.cp-overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 10px; overflow: auto; background: rgba(43,45,92,0.45); border-radius: 18px; }
.cp-overlay[hidden] { display: none; }
.cp-box { width: 100%; max-width: 300px; max-height: 100%; overflow: auto; padding: 18px; text-align: center; background: #fff8ec; border: 3px solid #2b2d5c; border-radius: 18px; box-shadow: 0 8px 0 rgba(43,45,92,0.35); }
.cp-box h2 { margin: 0 0 6px; font-size: 24px; text-transform: uppercase; color: #ff6b6b; }
.cp-box p { margin: 0 0 10px; font-size: 13px; }
.cp-main { width: 100%; padding: 11px; font-size: 18px; font-weight: 900; text-transform: uppercase; background: #ffc93c; border: 3px solid #2b2d5c; border-radius: 99px; box-shadow: 0 4px 0 #2b2d5c; }
.cp-main:active { transform: translateY(3px); box-shadow: 0 1px 0 #2b2d5c; }
.cp-link { margin-top: 10px; font-size: 13px; text-decoration: underline; background: none; border: 0; }
.cp-modes { display: grid; gap: 7px; margin: 12px 0 10px; }
.cp-modes button { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 8px 12px; text-align: left; background: #fff; border: 2px solid #2b2d5c; border-radius: 12px; }
.cp-modes span { font-size: 11px; color: #5a5c82; text-align: right; }
.cp-box .cp-help { margin: 4px 0 0; font-size: 11px; color: #5a5c82; }
.cp-perklist { display: grid; gap: 8px; }
.cp-perklist button { display: grid; grid-template-columns: 34px 1fr auto; column-gap: 10px; align-items: center; padding: 9px 10px; text-align: left; background: #fff; border: 2px solid #2b2d5c; border-radius: 14px; }
.cp-perklist button:hover { background: #fff1c2; }
.cp-perklist i { grid-row: span 2; display: grid; place-items: center; height: 34px; border-radius: 50%; background: #12b5a5; color: #fff; font-style: normal; font-size: 18px; }
.cp-perklist b { font-size: 14px; }
.cp-perklist span { grid-column: 2; font-size: 11px; color: #5a5c82; }
.cp-perklist kbd { grid-column: 3; grid-row: 1 / span 2; }
.cp-final { font-size: 36px !important; font-weight: 900; margin: 4px 0 !important; }
@media (max-width: 640px) {
.cp { flex-direction: column; gap: 6px; padding: 6px; }
.cp-panel { width: 100%; flex-direction: row; flex-wrap: wrap; align-items: stretch; gap: 6px; }
.cp-panel h1, .cp-keys, .cp-perks, .cp-mission { display: none; }
.cp-score { flex: 1; padding: 4px 10px; }
.cp-score strong { font-size: 20px; }
.cp-stats { display: flex; gap: 6px; }
.cp-stats div { padding: 4px 8px; }
.cp-stats b { font-size: 12px; white-space: nowrap; }
.cp-stats div:last-child { display: none; }
.cp-buttons { width: 100%; justify-content: center; flex-wrap: nowrap; gap: 4px; }
.cp-buttons button { padding: 4px 7px; font-size: 11px; white-space: nowrap; }
.cp-play { flex: 1; }
}
@media (min-width: 641px) and (max-height: 600px) {
.cp-panel { gap: 6px; width: 220px; }
.cp-panel h1 { font-size: 20px; }
.cp-keys, .cp-perks { display: none; }
.cp-score strong { font-size: 24px; }
}(function () {
'use strict';
var W = 420, H = 760, R = 9, GRAV = 1100, STEP = 1 / 600, MAXV = 1650;
var INK = '#2b2d5c', CORAL = '#ff6b6b', TEAL = '#12b5a5', SUN = '#ffc93c', SKY = '#4d9de0', PLUM = '#9b5de5', CREAM = '#fff8ec';
function $(id) { return document.getElementById(id); }
var cv = $('table'), g = cv.getContext('2d');
var calm = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* ---------- saved best scores (storage can be blocked in sandboxed frames) ---------- */
var best = {};
try { best = JSON.parse(localStorage.getItem('carnival-pinball-v1')) || {}; } catch (e) { best = {}; }
function save() { try { localStorage.setItem('carnival-pinball-v1', JSON.stringify(best)); } catch (e) {} }
/* ---------- sound: everything is synthesised, no files ---------- */
var ac = null, muted = false, musicOn = true, musicTimer = null, beat = 0;
function audio() {
if (muted) return null;
try {
if (!ac) ac = new (window.AudioContext || window.webkitAudioContext)();
if (ac.state === 'suspended') ac.resume();
} catch (e) { return null; }
return ac;
}
function tone(freq, dur, type, vol, slide, delay) {
if (state === 'menu') return;
var a = audio();
if (!a || a.state !== 'running') return;
try {
var t = a.currentTime + (delay || 0), o = a.createOscillator(), gain = a.createGain();
o.type = type || 'square';
o.frequency.setValueAtTime(freq, t);
if (slide) o.frequency.exponentialRampToValueAtTime(slide, t + dur);
gain.gain.setValueAtTime(vol || 0.06, t);
gain.gain.exponentialRampToValueAtTime(0.001, t + dur);
o.connect(gain);
gain.connect(a.destination);
o.start(t);
o.stop(t + dur + 0.02);
} catch (e) {}
}
function noise(dur, vol) {
if (state === 'menu') return;
var a = audio();
if (!a || a.state !== 'running') return;
try {
var n = Math.floor(a.sampleRate * dur), buf = a.createBuffer(1, n, a.sampleRate), d = buf.getChannelData(0);
for (var i = 0; i < n; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / n);
var s = a.createBufferSource(), gain = a.createGain();
s.buffer = buf;
gain.gain.value = vol || 0.08;
s.connect(gain);
gain.connect(a.destination);
s.start();
} catch (e) {}
}
var sfx = {
flip: function () { noise(0.04, 0.09); tone(150, 0.05, 'triangle', 0.08, 90); },
bumper: function () { tone(520 + Math.random() * 80, 0.09, 'square', 0.05, 1040); noise(0.03, 0.05); },
sling: function () { tone(300, 0.08, 'sawtooth', 0.05, 600); },
target: function () { tone(880, 0.07, 'triangle', 0.09); tone(1320, 0.09, 'triangle', 0.07, null, 0.05); },
lane: function () { tone(660, 0.1, 'sine', 0.09, 990); },
spin: function () { tone(1200, 0.025, 'square', 0.03); },
launch: function (p) { tone(120, 0.3, 'sawtooth', 0.07, 500 + p * 500); },
saucer: function () { [392, 494, 587, 784].forEach(function (f, i) { tone(f, 0.13, 'triangle', 0.08, null, i * 0.08); }); },
fanfare: function () { [523, 659, 784, 1047, 784, 1047].forEach(function (f, i) { tone(f, 0.16, 'square', 0.05, null, i * 0.1); }); },
drain: function () { tone(330, 0.7, 'sawtooth', 0.08, 55); },
tilt: function () { tone(90, 0.5, 'square', 0.12, 60); },
perk: function () { tone(700, 0.25, 'sine', 0.1, 1400); }
};
function music() {
if (musicTimer) { clearInterval(musicTimer); musicTimer = null; }
if (!musicOn) return;
var bass = [131, 131, 175, 175, 147, 147, 196, 196];
var tune = [523, 0, 659, 784, 698, 0, 880, 698, 587, 0, 698, 880, 784, 659, 587, 0];
musicTimer = setInterval(function () {
if (state !== 'play' || paused || document.hidden) return;
var fast = ball.multi || mission.wizard;
if (beat % 2 === 0) tone(bass[Math.floor(beat / 4) % 8], 0.18, 'triangle', 0.045);
if (tune[beat % 16]) tone(tune[beat % 16] * (fast ? 1.5 : 1), 0.09, 'square', 0.012);
beat++;
}, 190);
}
/* ---------- table geometry ---------- */
var walls = [];
function wall(x1, y1, x2, y2, e) { walls.push({ x1: x1, y1: y1, x2: x2, y2: y2, e: e === undefined ? 0.42 : e }); }
(function build() {
wall(14, 770, 14, 206);
var i, a0, a1;
for (i = 0; i < 36; i++) {
a0 = Math.PI + i * Math.PI / 36;
a1 = Math.PI + (i + 1) * Math.PI / 36;
wall(210 + 196 * Math.cos(a0), 206 + 196 * Math.sin(a0), 210 + 196 * Math.cos(a1), 206 + 196 * Math.sin(a1), 0.25);
}
wall(406, 206, 406, 735);
wall(372, 250, 372, 770);
wall(372, 735, 406, 735, 0.15);
// inlane guides
wall(58, 548, 58, 616); wall(58, 616, 108, 657, 0.2);
wall(328, 548, 328, 616); wall(328, 616, 278, 657, 0.2);
// slingshot backs (the kicking faces are handled separately)
wall(88, 540, 88, 598); wall(88, 598, 122, 624);
wall(298, 540, 298, 598); wall(298, 598, 264, 624);
// top lane dividers
[130, 172, 214, 256].forEach(function (x) { wall(x, 98, x, 138, 0.5); });
// caps above the side targets, and the spinner lane guide
wall(14, 296, 36, 316); wall(372, 296, 350, 316);
wall(70, 205, 70, 268, 0.5);
}());
var oneWay = { x1: 372, y1: 250, x2: 406, y2: 214, e: 0.5 };
var slings = [
{ x1: 88, y1: 540, x2: 122, y2: 624, nx: 0.927, ny: -0.375, lit: 0 },
{ x1: 298, y1: 540, x2: 264, y2: 624, nx: -0.927, ny: -0.375, lit: 0 }
];
var bumpers = [{ x: 135, y: 232, r: 24, lit: 0, c: CORAL }, { x: 251, y: 232, r: 24, lit: 0, c: SKY }, { x: 193, y: 306, r: 24, lit: 0, c: PLUM }];
var posts = [{ x: 62, y: 470, r: 7 }, { x: 324, y: 470, r: 7 }];
var drops = [330, 362, 394].map(function (y) { return { x: 37, y: y, down: false }; });
var stands = [330, 362, 394].map(function (y) { return { x: 349, y: y, lit: false, flash: 0 }; });
var lanes = [151, 193, 235].map(function (x, i) { return { x: x, y: 118, lit: false, label: 'SKY'.charAt(i) }; });
var saucer = { x: 193, y: 428, hold: null, wait: 0, cool: 0 };
var spinner = { x: 42, y: 245, speed: 0, angle: 0, acc: 0 };
var flippers = [
{ px: 113, py: 672, a: 0.52, rest: 0.52, up: -0.52, dir: 1, w: 0, on: false },
{ px: 273, py: 672, a: Math.PI - 0.52, rest: Math.PI - 0.52, up: Math.PI + 0.52, dir: -1, w: 0, on: false }
];
/* ---------- perks and missions ---------- */
var PERKS = [
{ id: 'post', icon: '●', name: 'Safety Post', text: 'A post between the flippers for the rest of the game' },
{ id: 'wide', icon: '↔', name: 'Long Flippers', text: 'Flippers reach further' },
{ id: 'super', icon: '✦', name: 'Super Bumpers', text: 'Bumpers score triple' },
{ id: 'save', icon: '♥', name: 'Big Ball Save', text: '12 more seconds of ball save' },
{ id: 'kick', icon: '↑', name: 'Kickbacks', text: 'Both side lanes kick the ball back after every launch' },
{ id: 'slow', icon: '☾', name: 'Moon Gravity', text: 'The ball falls more gently' },
{ id: 'bonus', icon: '×', name: 'Double Bonus', text: 'End of ball bonus is doubled' },
{ id: 'spin', icon: '↻', name: 'Gold Spinner', text: 'Spinner scores five times more' },
{ id: 'extra', icon: '+', name: 'Extra Ball', text: 'One more ball, right now' }
];
var MISSIONS = [
{ id: 'bump', name: 'Bumper Frenzy', goal: 12, time: 35, text: 'Hit the bumpers' },
{ id: 'target', name: 'Target Practice', goal: 5, time: 40, text: 'Hit side targets' },
{ id: 'spin', name: 'Spin Cycle', goal: 20, time: 40, text: 'Spin the left spinner' },
{ id: 'lane', name: 'Sky Climber', goal: 3, time: 45, text: 'Roll through top lanes' }
];
var MODES = {
classic: { name: 'Classic', balls: 3 },
blitz: { name: 'Blitz', balls: 99, time: 120 },
zen: { name: 'Zen', balls: 99 },
daily: { name: 'Daily', balls: 3 }
};
/* ---------- game state ---------- */
var state = 'menu', paused = false, mode = 'classic', rnd = Math.random;
var score = 0, ballsLeft = 3, ballNo = 1, perks = {}, bonus = 0, mult = 1, playMult = 1;
var ball = { list: [], multi: false };
var mission = { cur: null, left: 0, count: 0, next: 0, done: 0, wizard: false };
var saveTime = 0, clockLeft = 0, tilt = 0, tilted = false, kickL = false, kickR = false;
var charge = 0, charging = false, skill = 0, skillLive = false, lockProgress = 0, lockLit = false;
var combo = 0, comboTime = 0, gotExtra = false, shake = 0, particles = [], floats = [], banner = '', bannerTime = 0;
var queue = [], gameTime = 0, perkPending = false, newBestShown = false;
function later(sec, fn) { queue.push({ at: gameTime + sec, fn: fn }); }
function say(text, sec) { banner = text; bannerTime = sec || 2; $('message').textContent = text; }
function burst(x, y, color, n) {
if (calm) return;
for (var i = 0; i < n; i++) {
var a = Math.random() * 6.283, s = 50 + Math.random() * 220;
particles.push({ x: x, y: y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, life: 0.35 + Math.random() * 0.4, c: color });
}
}
function add(points, x, y, quiet) {
if (state !== 'play') return;
var v = Math.round(points * playMult * (mission.wizard ? 5 : 1));
score += v;
if (x !== undefined && !quiet) floats.push({ x: x, y: y, text: v.toLocaleString('en-US'), life: 0.9 });
if (!gotExtra && score >= 150000 && mode !== 'zen' && mode !== 'blitz') {
gotExtra = true;
ballsLeft++;
say('EXTRA BALL!', 2.5);
sfx.fanfare();
}
hud();
}
function newBall(x, y, vx, vy, inLane) {
return { x: x, y: y, vx: vx, vy: vy, lane: inLane, trail: [], still: 0 };
}
function serve() {
ball.list = [newBall(389, 724 - R, 0, 0, true)];
ball.multi = false;
if (drops.every(function (d) { return d.down; })) drops.forEach(function (d) { d.down = false; });
tilted = false;
tilt = 0;
saveTime = 0;
charge = 0;
charging = false;
skillLive = true;
skill = Math.floor(rnd() * 3);
kickL = true;
kickR = !!perks.kick;
say('Hold and release to launch. Lit lane = skill shot', 4);
}
function start(m) {
mode = m;
var seed = 0, d = new Date();
if (m === 'daily') {
seed = d.getFullYear() * 10000 + (d.getMonth() + 1) * 100 + d.getDate();
rnd = function () {
seed = (seed + 0x6D2B79F5) | 0;
var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
} else rnd = Math.random;
score = 0; ballNo = 1; ballsLeft = MODES[m].balls; perks = {}; bonus = 0; mult = 1; playMult = 1;
mission = { cur: null, left: 0, count: 0, next: Math.floor(rnd() * 4), done: 0, wizard: false };
clockLeft = MODES[m].time || 0;
lockProgress = 0; lockLit = false; combo = 0; gotExtra = false; queue = []; particles = []; floats = [];
perkPending = false; newBestShown = false; paused = false;
drops.forEach(function (t) { t.down = false; });
stands.forEach(function (t) { t.lit = false; });
lanes.forEach(function (t) { t.lit = false; });
saucer.hold = null; saucer.cool = 0; spinner.speed = 0;
state = 'play';
['menu', 'perkPick', 'gameOver', 'pauseBox'].forEach(function (id) { $(id).hidden = true; });
serve();
hud();
audio();
music();
}
function gameOver() {
if (state === 'over') return;
state = 'over';
ball.list = [];
var record = score > (best[mode] || 0);
if (record) { best[mode] = score; save(); }
$('overTitle').textContent = record ? 'New best score!' : 'Game over';
$('overScore').textContent = score.toLocaleString('en-US');
$('overNote').textContent = MODES[mode].name + ' mode · ' + mission.done + ' missions completed · best ' + (best[mode] || 0).toLocaleString('en-US');
$('gameOver').hidden = false;
sfx[record ? 'fanfare' : 'drain']();
hud();
}
function menu() {
state = 'menu';
paused = false;
['perkPick', 'gameOver', 'pauseBox'].forEach(function (id) { $(id).hidden = true; });
$('menu').hidden = false;
$('bests').textContent = Object.keys(MODES).filter(function (m) { return best[m]; })
.map(function (m) { return MODES[m].name + ' ' + best[m].toLocaleString('en-US'); }).join(' · ');
// attract mode: the machine plays itself behind the menu
ball.list = [newBall(100, 130, 120, 0, false)];
perks = {};
}
function offerPerks() {
var pool = PERKS.filter(function (p) {
if (p.id === 'extra') return mode === 'classic' || mode === 'daily';
return !perks[p.id];
});
if (!pool.length) return;
var picks = [];
while (picks.length < 3 && pool.length) picks.push(pool.splice(Math.floor(rnd() * pool.length), 1)[0]);
var box = $('perkList');
box.innerHTML = '';
picks.forEach(function (p, i) {
var b = document.createElement('button');
b.type = 'button';
b.innerHTML = '<i>' + p.icon + '</i><b>' + p.name + '</b><span>' + p.text + '</span><kbd>' + (i + 1) + '</kbd>';
b.addEventListener('click', function () { takePerk(p); });
box.appendChild(b);
});
state = 'perk';
releaseAll();
$('perkPick').hidden = false;
box.firstChild.focus();
}
function takePerk(p) {
if (state !== 'perk') return;
if (p.id === 'extra') ballsLeft++;
else perks[p.id] = true;
if (p.id === 'kick') { kickL = true; kickR = true; }
$('perkPick').hidden = true;
state = 'play';
say(p.name + ' activated', 2);
sfx.perk();
hud();
cv.focus();
}
/* ---------- missions, multiball ---------- */
function startMission() {
var m = MISSIONS[mission.next % MISSIONS.length];
mission.next++;
mission.cur = m;
mission.left = m.time;
mission.count = 0;
if (m.id === 'lane') lanes.forEach(function (l) { l.lit = false; });
say('MISSION: ' + m.name, 2.5);
sfx.fanfare();
}
function progress(id, n) {
var m = mission.cur;
if (!m || m.id !== id) return;
mission.count += n || 1;
if (mission.count >= m.goal) {
mission.cur = null;
mission.done++;
add(25000);
say(m.name + ' complete!', 2.5);
sfx.fanfare();
burst(193, 300, SUN, 60);
if (mission.done % 3 === 0) later(1.2, wizard);
perkPending = true;
later(1, function () { if (state === 'play' && perkPending) { perkPending = false; offerPerks(); } });
}
hud();
}
function multiball(extra) {
ball.multi = true;
saveTime = Math.max(saveTime, 12);
for (var i = 0; i < extra; i++) {
later(0.5 + i * 0.7, function () {
ball.list.push(newBall(389, 700, 0, -1500, true));
sfx.launch(1);
});
}
}
function wizard() {
if (state !== 'play') return;
mission.wizard = true;
say('★ CARNIVAL! Everything x5 ★', 4);
multiball(2);
later(30, function () { mission.wizard = false; say('Carnival over', 2); hud(); });
}
/* ---------- hits ---------- */
function hitBumper(b, bl) {
b.lit = 0.18;
add(perks.super ? 300 : 100, b.x, b.y - 28);
bonus++;
progress('bump');
sfx.bumper();
burst(bl.x, bl.y, b.c, 7);
shake = Math.max(shake, 2);
}
function hitDrop(t) {
t.down = true;
add(500, t.x + 30, t.y);
bonus += 2;
progress('target');
sfx.target();
if (drops.every(function (d) { return d.down; })) {
add(5000, 90, 362);
playMult = Math.min(5, playMult + 1);
say('Target bank! Playfield x' + playMult, 2.5);
kickL = true;
later(1.2, function () { drops.forEach(function (d) { d.down = false; }); });
}
}
function hitStand(t) {
if (t.flash > 0) return;
t.flash = 0.3;
add(250, t.x - 34, t.y);
bonus++;
progress('target');
sfx.target();
t.lit = true;
if (stands.every(function (s) { return s.lit; })) {
lockProgress++;
add(3000, 300, 362);
kickR = true;
stands.forEach(function (s) { s.lit = false; });
if (lockProgress >= 2 && !ball.multi) { lockLit = true; lockProgress = 0; say('LOCK IS LIT. Shoot the centre hole!', 3); }
else say('Right bank complete. Once more lights multiball', 2.5);
}
}
function hitLane(i) {
var l = lanes[i];
if (skillLive) {
skillLive = false;
if (i === skill) { add(10000, l.x, 90); say('SKILL SHOT!', 2.5); sfx.fanfare(); burst(l.x, l.y, SUN, 30); }
}
add(300, l.x, 160);
progress('lane');
sfx.lane();
l.lit = true;
if (lanes.every(function (q) { return q.lit; })) {
mult = Math.min(6, mult + 1);
add(3000);
say('S-K-Y! Bonus x' + mult, 2);
lanes.forEach(function (q) { q.lit = false; });
hud();
}
}
function comboShot(x, y) {
combo = comboTime > 0 ? combo + 1 : 1;
comboTime = 5;
if (combo > 1) { add(2000 * combo, x, y); say('COMBO x' + combo, 1.5); }
}
function hitSaucer(bl) {
saucer.hold = bl;
saucer.wait = 1.3;
bl.x = saucer.x; bl.y = saucer.y; bl.vx = 0; bl.vy = 0; bl.trail = [];
sfx.saucer();
burst(saucer.x, saucer.y, PLUM, 25);
bonus += 3;
comboShot(saucer.x, saucer.y - 30);
if (ball.multi) { add(20000, saucer.x, saucer.y - 40); say('JACKPOT!', 2); sfx.fanfare(); }
else if (lockLit) { lockLit = false; add(5000, saucer.x, saucer.y - 30); say('MULTIBALL!', 3); multiball(2); }
else if (state === 'play' && !mission.cur) { add(1000, saucer.x, saucer.y - 30); startMission(); saucer.wait = 1.8; }
else add(2000, saucer.x, saucer.y - 30);
}
/* ---------- physics ---------- */
function closest(x, y, x1, y1, x2, y2) {
var dx = x2 - x1, dy = y2 - y1, t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);
t = t < 0 ? 0 : t > 1 ? 1 : t;
return { x: x1 + dx * t, y: y1 + dy * t, t: t };
}
// Pushes the ball out of a point and reflects its velocity. Returns the impact speed, or -1 for no contact
function bounce(b, cx, cy, radius, e, svx, svy) {
var dx = b.x - cx, dy = b.y - cy, d2 = dx * dx + dy * dy, min = R + radius;
if (d2 >= min * min || d2 === 0) return -1;
var d = Math.sqrt(d2), nx = dx / d, ny = dy / d;
b.x = cx + nx * min;
b.y = cy + ny * min;
var vn = (b.vx - (svx || 0)) * nx + (b.vy - (svy || 0)) * ny;
if (vn >= 0) return 0;
// very soft contacts do not bounce, so a ball can rest and roll
var k = (1 + (vn > -50 ? 0 : e)) * vn;
b.vx -= k * nx;
b.vy -= k * ny;
return -vn;
}
function segment(b, s, radius) {
var p = closest(b.x, b.y, s.x1, s.y1, s.x2, s.y2);
return bounce(b, p.x, p.y, radius || 2, s.e);
}
function flipperLength() { return perks.wide ? 70 : 63; }
function moveFlippers(dt) {
flippers.forEach(function (f) {
var goal = f.on && !tilted ? f.up : f.rest, speed = f.on ? 20 : 14;
var diff = goal - f.a, move = Math.max(-speed * dt, Math.min(speed * dt, diff));
f.a += move;
f.w = move / dt;
});
}
function stepBall(b, dt) {
if (saucer.hold === b) return;
var gy = GRAV * (perks.slow ? 0.82 : 1);
b.vy += gy * dt;
var sp = Math.hypot(b.vx, b.vy);
if (sp > MAXV) { b.vx *= MAXV / sp; b.vy *= MAXV / sp; }
var px = b.x, py = b.y;
b.x += b.vx * dt;
b.y += b.vy * dt;
var i;
for (i = 0; i < walls.length; i++) segment(b, walls[i]);
// launch lane: once out, a gate closes behind the ball
if (b.lane && b.x < 366) b.lane = false;
if (!b.lane && b.x > 340 && b.y < 262) segment(b, oneWay);
for (i = 0; i < 2; i++) {
var s = slings[i], p = closest(b.x, b.y, s.x1, s.y1, s.x2, s.y2);
var hit = bounce(b, p.x, p.y, 3, 0.4);
if (hit > 90 && p.t > 0.08 && p.t < 0.92 && !tilted) {
b.vx = s.nx * 430 + b.vx * 0.25;
b.vy = s.ny * 430 - 90;
s.lit = 0.15;
add(20, p.x, p.y - 14);
sfx.sling();
}
}
for (i = 0; i < 3; i++) {
var bm = bumpers[i];
if (bounce(b, bm.x, bm.y, bm.r, 0.6) >= 0 && !tilted) {
var dx = b.x - bm.x, dy = b.y - bm.y, d = Math.hypot(dx, dy) || 1;
b.vx = dx / d * 480 + (Math.random() - 0.5) * 60;
b.vy = dy / d * 480;
hitBumper(bm, b);
}
}
for (i = 0; i < posts.length; i++) bounce(b, posts[i].x, posts[i].y, posts[i].r, 0.65);
if (perks.post) bounce(b, 193, 722, 7, 0.65);
for (i = 0; i < 3; i++) {
var dt3 = drops[i];
if (!dt3.down && segment(b, { x1: dt3.x, y1: dt3.y - 12, x2: dt3.x, y2: dt3.y + 12, e: 0.5 }, 3) > 60) hitDrop(dt3);
var st = stands[i];
var v = segment(b, { x1: st.x, y1: st.y - 12, x2: st.x, y2: st.y + 12, e: 0.65 }, 3);
if (v > 60) hitStand(st);
}
for (i = 0; i < 2; i++) {
var f = flippers[i], len = flipperLength();
var ex = f.px + Math.cos(f.a) * len, ey = f.py + Math.sin(f.a) * len;
var c = closest(b.x, b.y, f.px, f.py, ex, ey);
var rad = 10 - 4 * c.t;
// velocity of the flipper surface at the contact point
bounce(b, c.x, c.y, rad, 0.28, -f.w * (c.y - f.py), f.w * (c.x - f.px));
}
// lanes and spinner are sensors the ball rolls through
for (i = 0; i < 3; i++) {
var l = lanes[i];
if (Math.abs(b.x - l.x) < 18 && (py - l.y) * (b.y - l.y) < 0) hitLane(i);
}
if (b.x < 70 && (py - spinner.y) * (b.y - spinner.y) < 0) {
spinner.speed = Math.min(60, Math.abs(b.vy) / 22);
if (b.vy < -250) comboShot(80, 230);
if (skillLive) skillLive = false;
}
if (saucer.cool <= 0 && !saucer.hold && Math.hypot(b.x - saucer.x, b.y - saucer.y) < 12 && Math.hypot(b.vx, b.vy) < 900) hitSaucer(b);
// kickbacks in the outer lanes
if (b.y > 690 && b.y < 715 && b.vy > 0 && !tilted) {
if (b.x < 56 && kickL) { b.vy = -1300; b.vx = 4; kickL = false; say('Kickback!', 1.2); sfx.launch(1); }
else if (b.x > 330 && b.x < 372 && kickR) { b.vy = -1300; b.vx = -4; kickR = false; say('Kickback!', 1.2); sfx.launch(1); }
}
// free a ball that has stopped somewhere it cannot leave
var cradled = (flippers[0].on || flippers[1].on) && b.y > 600;
if (!b.lane && !cradled && Math.hypot(b.x - px, b.y - py) / dt < 14) {
b.still += dt;
if (b.still > 1.5) { b.vx = (Math.random() - 0.5) * 300; b.vy = -260; b.still = 0; }
} else b.still = 0;
}
function collideBalls() {
var l = ball.list;
for (var i = 0; i < l.length; i++) for (var j = i + 1; j < l.length; j++) {
var a = l[i], b = l[j];
if (a === saucer.hold || b === saucer.hold || a.lane || b.lane) continue;
var dx = b.x - a.x, dy = b.y - a.y, d = Math.hypot(dx, dy);
if (d >= R * 2 || d === 0) continue;
var nx = dx / d, ny = dy / d, push = (R * 2 - d) / 2;
a.x -= nx * push; a.y -= ny * push; b.x += nx * push; b.y += ny * push;
var rel = (b.vx - a.vx) * nx + (b.vy - a.vy) * ny;
if (rel < 0) { a.vx += rel * nx; a.vy += rel * ny; b.vx -= rel * nx; b.vy -= rel * ny; sfx.spin(); }
}
}
function launch() {
var b = null;
ball.list.forEach(function (q) { if (q.lane && q.y > 690) b = q; });
charging = false;
if (!b) return;
var power = Math.max(0.12, charge);
b.vy = -(1060 + 560 * power);
charge = 0;
saveTime = 10 + (perks.save ? 12 : 0);
sfx.launch(power);
}
function drained(b) {
ball.list.splice(ball.list.indexOf(b), 1);
if (state === 'menu') { ball.list.push(newBall(60 + Math.random() * 250, 130, 100, 0, false)); return; }
if (saveTime > 0 && !tilted) {
say('Ball saved!', 1.5);
sfx.perk();
later(0.6, function () {
if (ball.multi) ball.list.push(newBall(389, 700, 0, -1500, true));
else { ball.list.push(newBall(389, 724 - R, 0, 0, true)); }
});
if (!ball.multi) saveTime = 0;
return;
}
if (ball.list.length > 0) {
if (ball.list.length === 1) { ball.multi = false; say('Multiball over', 1.5); }
return;
}
if (queue.some(function (q) { return q.fn.serves; })) return;
sfx.drain();
shake = 6;
ball.multi = false;
mission.cur = null;
mission.wizard = false;
queue = [];
var total = tilted ? 0 : bonus * 100 * mult * (perks.bonus ? 2 : 1);
score += total;
say(tilted ? 'TILT. No bonus' : 'Bonus ' + total.toLocaleString('en-US'), 2.2);
bonus = 0; mult = 1; playMult = 1;
if (mode === 'classic' || mode === 'daily') ballsLeft--;
if (mode === 'blitz') clockLeft = Math.max(0, clockLeft - 5);
hud();
var next = function () {
if (ballsLeft <= 0 || (mode === 'blitz' && clockLeft <= 0)) { gameOver(); return; }
ballNo++;
serve();
hud();
if (perkPending) { perkPending = false; offerPerks(); }
};
next.serves = true;
later(2.2, next);
}
function nudge(dir) {
if (state !== 'play' || paused || tilted) return;
tilt += 1;
shake = 8;
noise(0.1, 0.12);
ball.list.forEach(function (b) {
if (b.lane || b === saucer.hold) return;
b.vx += dir * 120 + (Math.random() - 0.5) * 40;
b.vy -= 130;
});
if (tilt > 3) {
tilted = true;
saveTime = 0;
kickL = false; kickR = false;
say('TILT!', 3);
sfx.tilt();
} else if (tilt > 2) say('Careful... tilt warning', 1.5);
}
function autopilot() {
flippers.forEach(function (f, i) {
f.on = ball.list.some(function (b) {
return b.y > 640 && b.y < 700 && b.vy > -50 && (i === 0 ? b.x > 105 && b.x < 195 : b.x >= 191 && b.x < 282);
});
});
}
var accumulator = 0;
function update(dt) {
if (state === 'perk' || state === 'over' || paused) return;
gameTime += dt;
if (state === 'menu') autopilot();
else {
if (charging) charge = Math.min(1, charge + dt * 0.9);
if (saveTime > 0 && !ball.list.some(function (b) { return b.lane; })) saveTime -= dt;
if (comboTime > 0) comboTime -= dt;
tilt = Math.max(0, tilt - dt * 0.45);
if (mission.cur) {
mission.left -= dt;
if (mission.left <= 0) { say(mission.cur.name + ' failed', 1.5); mission.cur = null; }
}
if (mode === 'blitz') {
clockLeft -= dt;
if (clockLeft <= 0) { clockLeft = 0; gameOver(); return; }
}
for (var q = queue.length - 1; q >= 0; q--) {
if (queue[q] && queue[q].at <= gameTime) { var job = queue.splice(q, 1)[0]; job.fn(); }
}
if (state !== 'play') return;
}
if (saucer.hold) {
saucer.wait -= dt;
if (saucer.wait <= 0) {
var h = saucer.hold;
saucer.hold = null;
saucer.cool = 0.8;
h.vx = (Math.random() < 0.5 ? -1 : 1) * (120 + Math.random() * 60);
h.vy = 120;
sfx.sling();
}
}
saucer.cool -= dt;
accumulator += dt;
while (accumulator >= STEP) {
accumulator -= STEP;
moveFlippers(STEP);
for (var i = ball.list.length - 1; i >= 0; i--) {
var b = ball.list[i];
if (!b) continue;
stepBall(b, STEP);
if (b.y > H + 20) drained(b);
}
collideBalls();
}
ball.list.forEach(function (b) {
b.trail.unshift([b.x, b.y]);
if (b.trail.length > 8) b.trail.pop();
});
if (spinner.speed > 0.4) {
spinner.angle += spinner.speed * dt;
spinner.acc += spinner.speed * dt;
while (spinner.acc > Math.PI) {
spinner.acc -= Math.PI;
if (state === 'play') { add(perks.spin ? 500 : 100, 62, 210, true); progress('spin'); bonus++; sfx.spin(); }
}
spinner.speed *= Math.pow(0.28, dt);
}
bumpers.concat(slings).forEach(function (o) { o.lit = Math.max(0, o.lit - dt); });
stands.forEach(function (o) { o.flash = Math.max(0, o.flash - dt); });
particles = particles.filter(function (p) { p.life -= dt; p.x += p.vx * dt; p.y += p.vy * dt; p.vy += 300 * dt; return p.life > 0; });
floats = floats.filter(function (f) { f.life -= dt; f.y -= 34 * dt; return f.life > 0; });
shake = Math.max(0, shake - dt * 30);
bannerTime -= dt;
}
/* ---------- drawing ---------- */
function circle(x, y, r, fill, stroke, width) {
g.beginPath();
g.arc(x, y, r, 0, 6.283);
if (fill) { g.fillStyle = fill; g.fill(); }
if (stroke) { g.strokeStyle = stroke; g.lineWidth = width || 2; g.stroke(); }
}
function line(x1, y1, x2, y2, color, width) {
g.beginPath();
g.moveTo(x1, y1);
g.lineTo(x2, y2);
g.strokeStyle = color;
g.lineWidth = width;
g.lineCap = 'round';
g.stroke();
}
function text(s, x, y, size, color, outline) {
g.font = '900 ' + size + 'px "Trebuchet MS", Arial, sans-serif';
g.textAlign = 'center';
g.textBaseline = 'middle';
if (outline) { g.lineWidth = 4; g.strokeStyle = outline; g.lineJoin = 'round'; g.strokeText(s, x, y); }
g.fillStyle = color;
g.fillText(s, x, y);
}
function tablePath() {
g.beginPath();
g.moveTo(14, 760);
g.lineTo(14, 206);
g.arc(210, 206, 196, Math.PI, Math.PI * 2);
g.lineTo(406, 760);
g.closePath();
}
function draw(time) {
var ratio = cv.width / W, i;
g.setTransform(ratio, 0, 0, ratio, 0, 0);
g.fillStyle = INK;
g.fillRect(0, 0, W, H);
if (shake > 0 && !calm) g.translate((Math.random() - 0.5) * shake, (Math.random() - 0.5) * shake);
var sky = g.createLinearGradient(0, 0, 0, H);
sky.addColorStop(0, mission.wizard ? '#ffe3f1' : '#bfe6ff');
sky.addColorStop(0.55, CREAM);
sky.addColorStop(1, mission.wizard ? '#fff0b8' : '#ffe6c7');
tablePath();
g.fillStyle = sky;
g.fill();
// printed art: sun rays, clouds and a big wheel
g.save();
g.clip();
g.translate(193, 428);
g.rotate(calm ? 0 : time / (mission.wizard ? 1500 : 14000));
g.fillStyle = 'rgba(255,201,60,0.16)';
for (i = 0; i < 12; i++) {
g.rotate(Math.PI / 6);
g.beginPath(); g.moveTo(0, 0); g.lineTo(400, -50); g.lineTo(400, 50); g.fill();
}
g.restore();
circle(193, 428, 78, null, 'rgba(43,45,92,0.12)', 3);
for (i = 0; i < 8; i++) {
var a = i * Math.PI / 4;
line(193, 428, 193 + Math.cos(a) * 78, 428 + Math.sin(a) * 78, 'rgba(43,45,92,0.09)', 2);
circle(193 + Math.cos(a) * 78, 428 + Math.sin(a) * 78, 7, 'rgba(255,107,107,0.25)');
}
g.fillStyle = 'rgba(255,255,255,0.75)';
[[90, 520], [292, 160], [300, 545]].forEach(function (c) {
circle(c[0], c[1], 14, g.fillStyle); circle(c[0] + 16, c[1] - 7, 17, g.fillStyle); circle(c[0] + 33, c[1], 13, g.fillStyle);
});
text('CARNIVAL', 193, 575, 30, 'rgba(43,45,92,0.14)');
text('PINBALL', 193, 603, 20, 'rgba(43,45,92,0.14)');
tablePath();
g.strokeStyle = CORAL;
g.lineWidth = 10;
g.stroke();
// lanes
for (i = 0; i < 3; i++) {
var l = lanes[i], flash = skillLive && state === 'play' && i === skill && Math.floor(time / 220) % 2 === 0;
circle(l.x, l.y, 14, l.lit || flash ? SUN : '#fff', INK, 2);
text(l.label, l.x, l.y + 1, 14, INK);
}
walls.forEach(function (w, n) { if (n > 0 && (n < 1 || n > 36)) line(w.x1, w.y1, w.x2, w.y2, INK, 5); });
line(oneWay.x1, oneWay.y1, oneWay.x2, oneWay.y2, 'rgba(43,45,92,0.3)', 2);
// slingshots
[[[88, 540], [88, 598], [122, 624]], [[298, 540], [298, 598], [264, 624]]].forEach(function (t, n) {
g.beginPath(); g.moveTo(t[0][0], t[0][1]); g.lineTo(t[1][0], t[1][1]); g.lineTo(t[2][0], t[2][1]); g.closePath();
g.fillStyle = slings[n].lit > 0 ? SUN : TEAL;
g.fill();
g.strokeStyle = INK; g.lineWidth = 3; g.lineJoin = 'round'; g.stroke();
line(t[0][0], t[0][1], t[2][0], t[2][1], slings[n].lit > 0 ? '#fff' : CORAL, 4);
});
posts.forEach(function (p) { circle(p.x, p.y, p.r, CORAL, INK, 2.5); });
if (perks.post) circle(193, 722, 7, SUN, INK, 2.5);
bumpers.forEach(function (b) {
var grow = b.lit > 0 ? 4 : 0;
circle(b.x + 3, b.y + 5, b.r, 'rgba(43,45,92,0.18)');
circle(b.x, b.y, b.r + grow, b.lit > 0 ? '#fff' : b.c, INK, 3);
circle(b.x, b.y, 16, '#fff');
circle(b.x, b.y, 10, perks.super ? SUN : b.c);
for (var k = 0; k < 8; k++) circle(b.x + Math.cos(k * 0.785) * 20, b.y + Math.sin(k * 0.785) * 20, 2, b.lit > 0 ? b.c : '#fff');
});
drops.forEach(function (t) {
if (t.down) line(t.x - 6, t.y - 11, t.x - 6, t.y + 11, 'rgba(43,45,92,0.25)', 3);
else { line(t.x, t.y - 12, t.x, t.y + 12, INK, 10); line(t.x, t.y - 12, t.x, t.y + 12, SUN, 6); }
});
stands.forEach(function (t) {
line(t.x, t.y - 12, t.x, t.y + 12, INK, 10);
line(t.x, t.y - 12, t.x, t.y + 12, t.flash > 0 ? '#fff' : t.lit ? SKY : '#d9e6f2', 6);
});
// spinner
var h = Math.abs(Math.cos(spinner.angle)) * 11 + 2;
line(16, spinner.y, 68, spinner.y, INK, 2);
g.fillStyle = Math.cos(spinner.angle) > 0 ? CORAL : SUN;
g.fillRect(24, spinner.y - h, 36, h * 2);
g.strokeStyle = INK; g.lineWidth = 2; g.strokeRect(24, spinner.y - h, 36, h * 2);
// saucer
var hot = lockLit || ball.multi || (!mission.cur && state === 'play');
circle(saucer.x, saucer.y, 21, hot && Math.floor(time / 300) % 2 === 0 ? SUN : '#fff', INK, 3);
circle(saucer.x, saucer.y, 12, INK);
text(ball.multi ? 'JACKPOT' : lockLit ? 'LOCK' : mission.cur ? 'BONUS' : 'MISSION', saucer.x, saucer.y + 34, 11, INK);
// kickback lamps
[[36, kickL], [350, kickR]].forEach(function (k) {
g.fillStyle = k[1] ? TEAL : 'rgba(43,45,92,0.15)';
g.beginPath(); g.moveTo(k[0], 672); g.lineTo(k[0] + 9, 688); g.lineTo(k[0] - 9, 688); g.fill();
});
if (saveTime > 0) text('BALL SAVE', 193, 650, 12, TEAL);
// flippers
var len = flipperLength();
flippers.forEach(function (f) {
var ex = f.px + Math.cos(f.a) * len, ey = f.py + Math.sin(f.a) * len;
var nx = -Math.sin(f.a), ny = Math.cos(f.a);
g.beginPath();
g.arc(f.px, f.py, 10, f.a + Math.PI / 2, f.a - Math.PI / 2);
g.lineTo(ex - nx * 6, ey - ny * 6);
g.arc(ex, ey, 6, f.a - Math.PI / 2, f.a + Math.PI / 2);
g.closePath();
g.fillStyle = tilted ? '#b9b9c9' : CORAL;
g.fill();
g.strokeStyle = INK; g.lineWidth = 3; g.stroke();
circle(f.px, f.py, 3.5, '#fff');
});
// plunger
var top = 724 + (charge * 8);
line(389, top + 3, 389, 756, '#9a9cc0', 4);
for (i = 0; i < 4; i++) line(383, top + 8 + i * (748 - top - 8) / 4, 395, top + 8 + i * (748 - top - 8) / 4, '#9a9cc0', 2);
line(378, top + 1, 400, top + 1, INK, 5);
if (charging) {
g.fillStyle = 'rgba(43,45,92,0.15)'; g.fillRect(376, 590, 8, 100);
g.fillStyle = charge > 0.8 ? CORAL : TEAL; g.fillRect(376, 690 - charge * 100, 8, charge * 100);
}
// balls
ball.list.forEach(function (b) {
if (!calm) b.trail.forEach(function (p, n) { circle(p[0], p[1], R - n, 'rgba(77,157,224,' + (0.22 - n * 0.026) + ')'); });
circle(b.x + 3, b.y + 4, R, 'rgba(43,45,92,0.22)');
var m = g.createRadialGradient(b.x - 3, b.y - 4, 1, b.x, b.y, R);
m.addColorStop(0, '#ffffff');
m.addColorStop(0.45, '#cfd6ea');
m.addColorStop(1, '#5b6288');
circle(b.x, b.y, R, m);
});
particles.forEach(function (p) { g.globalAlpha = Math.min(1, p.life * 2.5); circle(p.x, p.y, 3, p.c); });
g.globalAlpha = 1;
floats.forEach(function (f) { g.globalAlpha = Math.min(1, f.life * 2); text(f.text, Math.max(50, Math.min(330, f.x)), f.y, 15, INK, '#fff'); });
g.globalAlpha = 1;
if (bannerTime > 0 && state === 'play') {
g.globalAlpha = Math.min(1, bannerTime * 2);
g.font = '900 16px "Trebuchet MS", Arial, sans-serif';
var size = Math.min(16, 16 * 320 / g.measureText(banner).width);
g.fillStyle = INK;
g.fillRect(24, 465, 338, 34);
text(banner, 193, 483, size, '#fff');
g.globalAlpha = 1;
}
if (mission.cur) text(mission.cur.name.toUpperCase() + ' ' + mission.count + '/' + mission.cur.goal + ' ' + Math.ceil(mission.left) + 's', 193, 168, 13, INK, '#fff');
}
/* ---------- panel ---------- */
function setText(id, value) { var el = $(id); if (el.textContent !== value) el.textContent = value; }
function hud() {
setText('score', score.toLocaleString('en-US'));
setText('best', Math.max(best[mode] || 0, score).toLocaleString('en-US'));
var timed = mode === 'blitz';
setText('ballsLabel', timed ? 'Time' : 'Ball');
setText('balls', timed ? Math.ceil(clockLeft) + 's' : mode === 'zen' ? ballNo + ' · ∞' : Math.min(ballNo, ballNo + ballsLeft - 1) + ' of ' + (ballNo + ballsLeft - 1));
setText('multi', 'x' + playMult + (mult > 1 ? ' · bonus x' + mult : ''));
setText('missionName', mission.wizard ? 'Carnival!' : mission.cur ? mission.cur.name : 'Shoot the centre hole');
setText('missionText', mission.wizard ? 'Everything scores x5' : mission.cur ? mission.cur.text + ': ' + mission.count + ' of ' + mission.cur.goal + ' (' + Math.ceil(mission.left) + 's)' : 'Start a mission to earn a perk');
$('missionBar').style.width = (mission.cur ? mission.count / mission.cur.goal * 100 : 0) + '%';
var list = PERKS.filter(function (p) { return perks[p.id]; }).map(function (p) { return p.icon + ' ' + p.name; }).join(' ');
setText('perkNames', list || 'None yet');
}
/* ---------- input ---------- */
function flip(i, on) {
var f = flippers[i];
if (state !== 'play' || paused) { f.on = false; return; }
if (on && !f.on && !tilted) {
sfx.flip();
// flipping also rotates the lit top lanes
if (i === 0) { var a = lanes[0].lit; lanes[0].lit = lanes[1].lit; lanes[1].lit = lanes[2].lit; lanes[2].lit = a; }
else { var c = lanes[2].lit; lanes[2].lit = lanes[1].lit; lanes[1].lit = lanes[0].lit; lanes[0].lit = c; }
}
f.on = on;
}
function plunge(down) {
if (state !== 'play' || paused) { charging = false; return; }
if (down) { if (ball.list.some(function (b) { return b.lane && b.y > 690; })) charging = true; }
else if (charging) launch();
}
function releaseAll() {
flippers[0].on = false;
flippers[1].on = false;
charging = false;
charge = 0;
held = {};
}
function pause(on) {
if (state !== 'play') return;
paused = on === undefined ? !paused : on;
releaseAll();
$('pauseBox').hidden = !paused;
}
var LEFT = ['KeyZ', 'ArrowLeft', 'ShiftLeft', 'KeyA'], RIGHT = ['Slash', 'ArrowRight', 'ShiftRight', 'KeyL', 'KeyD'];
window.addEventListener('keydown', function (e) {
if (e.ctrlKey || e.metaKey || e.altKey) return;
var c = e.code;
if (state === 'perk' && /^Digit[123]$/.test(c)) { var b = $('perkList').children[+c.charAt(5) - 1]; if (b) b.click(); return; }
if (c === 'KeyP' || c === 'Escape') { pause(); return; }
if (c === 'KeyM') { toggleSound(); return; }
if (state !== 'play') return;
if (LEFT.indexOf(c) >= 0 || RIGHT.indexOf(c) >= 0 || c === 'Space' || c === 'ArrowDown' || c === 'ArrowUp' || c === 'KeyX' || c === 'Enter') e.preventDefault();
if (e.repeat) return;
if (LEFT.indexOf(c) >= 0) flip(0, true);
else if (RIGHT.indexOf(c) >= 0) flip(1, true);
else if (c === 'Space' || c === 'ArrowDown' || c === 'Enter') plunge(true);
else if (c === 'ArrowUp' || c === 'KeyX') nudge(Math.random() < 0.5 ? -1 : 1);
});
window.addEventListener('keyup', function (e) {
var c = e.code;
if (LEFT.indexOf(c) >= 0) flip(0, false);
else if (RIGHT.indexOf(c) >= 0) flip(1, false);
else if (c === 'Space' || c === 'ArrowDown' || c === 'Enter') plunge(false);
});
// Touch and mouse: left half is the left flipper, right half the right one. While the ball waits, holding anywhere charges
var held = {};
var area = $('playArea');
area.addEventListener('pointerdown', function (e) {
if (state !== 'play' || paused || e.target.closest('button')) return;
e.preventDefault();
audio();
var r = area.getBoundingClientRect(), side = e.clientX < r.left + r.width / 2 ? 0 : 1;
var waiting = ball.list.some(function (b) { return b.lane && b.y > 690; }) && ball.list.length === 1;
held[e.pointerId] = waiting ? 2 : side;
if (waiting) plunge(true); else flip(side, true);
});
function lift(e) {
var what = held[e.pointerId];
if (what === undefined) return;
delete held[e.pointerId];
if (what === 2) plunge(false);
else if (!Object.keys(held).some(function (k) { return held[k] === what; })) flip(what, false);
}
window.addEventListener('pointerup', lift);
window.addEventListener('pointercancel', lift);
area.addEventListener('contextmenu', function (e) { e.preventDefault(); });
function toggleSound() {
muted = !muted;
$('soundBtn').textContent = muted ? 'Sound off' : 'Sound on';
}
$('soundBtn').addEventListener('click', function () { toggleSound(); this.blur(); });
$('musicBtn').addEventListener('click', function () {
musicOn = !musicOn;
this.textContent = musicOn ? 'Music on' : 'Music off';
music();
this.blur();
});
$('pauseBtn').addEventListener('click', function () { pause(); this.blur(); });
$('nudgeBtn').addEventListener('click', function () { nudge(Math.random() < 0.5 ? -1 : 1); this.blur(); });
$('menuBtn').addEventListener('click', function () { menu(); this.blur(); });
$('resumeBtn').addEventListener('click', function () { pause(false); this.blur(); });
$('quitBtn').addEventListener('click', menu);
$('againBtn').addEventListener('click', function () { start(mode); this.blur(); });
$('modesBtn').addEventListener('click', menu);
$('playBtn').addEventListener('click', function () { start('classic'); this.blur(); });
['blitz', 'zen', 'daily'].forEach(function (m) {
$(m + 'Btn').addEventListener('click', function () { start(m); this.blur(); });
});
document.addEventListener('visibilitychange', function () { if (document.hidden) pause(true); });
window.addEventListener('blur', function () { releaseAll(); });
/* ---------- sizing and loop ---------- */
function resize() {
var box = area.getBoundingClientRect();
var k = Math.min(box.width / W, box.height / H);
if (!(k > 0)) return;
var ratio = Math.min(window.devicePixelRatio || 1, 2);
cv.style.width = Math.floor(W * k) + 'px';
cv.style.height = Math.floor(H * k) + 'px';
cv.width = Math.round(W * k * ratio);
cv.height = Math.round(H * k * ratio);
}
window.addEventListener('resize', resize);
var last = 0, hudTick = 0;
function frame(time) {
var dt = Math.min(0.033, (time - last) / 1000 || 0);
last = time;
update(dt);
draw(time);
hudTick += dt;
if (hudTick > 0.25) { hudTick = 0; if (state === 'play') hud(); }
requestAnimationFrame(frame);
}
/*debug*/
resize();
menu();
hud();
requestAnimationFrame(frame);
}());
/* wdp-share:start */
(function () {
var TITLE = 'Carnival Pinball Game', URL = 'https://webdevpuneet.com/ui-snippets/carnival-pinball-game/';
if (window.__wdpShare) return;
window.__wdpShare = true;
var blob = null, file = null, lastInfo = null;
/* ---- UI ---- */
var st = document.createElement('style');
st.textContent =
'.wdps-in,.wdps-btn,.wdps-box{touch-action:manipulation;-webkit-tap-highlight-color:transparent}.wdps-in{display:block;margin:12px auto 0;border:0;border-radius:12px;padding:11px 22px;font:800 15px/1 system-ui,sans-serif;background:#16a34a;color:#fff;cursor:pointer;box-shadow:0 3px 0 #11793a;pointer-events:auto;position:relative;z-index:5}' +
'.wdps-in:hover{background:#15803d}.wdps-in:active{transform:translateY(2px);box-shadow:0 1px 0 #11793a}' +
'.wdps-btn{position:fixed;right:12px;bottom:12px;z-index:2147483000;border:0;border-radius:99px;padding:9px 16px;font:700 13px/1 system-ui,sans-serif;background:#16a34a;color:#fff;cursor:pointer;box-shadow:0 3px 12px rgba(0,0,0,.3)}' +
'.wdps-btn.wdps-hot{animation:wdps-p 1.4s ease-in-out infinite}' +
'@keyframes wdps-p{0%,100%{box-shadow:0 0 0 0 rgba(22,163,74,.6),0 3px 12px rgba(0,0,0,.3)}50%{box-shadow:0 0 0 9px rgba(22,163,74,0),0 3px 12px rgba(0,0,0,.3)}}' +
'.wdps-btn:active{transform:translateY(1px)}' +
'.wdps-in[hidden],.wdps-btn[hidden],.wdps-box[hidden],.wdps-box [hidden]{display:none}' +
'.wdps-box{position:fixed;left:50%;bottom:12px;transform:translateX(-50%);z-index:2147483001;width:max-content;max-width:calc(100vw - 24px);box-sizing:border-box;background:#fff;color:#64748b;border:1px solid #d5e2ee;border-radius:12px;padding:8px 12px;font:700 12px/1.4 system-ui,sans-serif;box-shadow:0 8px 26px rgba(15,23,42,.25);display:flex;flex-wrap:wrap;gap:8px;align-items:center}' +
'.wdps-box button,.wdps-box a{border:1px solid #d5e2ee;background:#f8fafc;color:#1e293b;border-radius:99px;padding:5px 12px;font:700 12px system-ui,sans-serif;text-decoration:none;cursor:pointer}' +
'.wdps-box .wdps-x{border:0;background:none;font-size:19px;line-height:1;padding:0 4px;margin-left:auto;color:#475569}' +
'@media (max-width:700px){.wdps-box{width:calc(100vw - 24px);justify-content:center;padding:10px 12px}.wdps-box>span{width:100%;text-align:center}.wdps-box button,.wdps-box a{padding:9px 14px;font-size:13px}.wdps-box .wdps-x{position:absolute;top:4px;right:4px}.wdps-in{width:100%;max-width:320px}}';
document.head.appendChild(st);
var pill = document.createElement('button');
pill.type = 'button'; pill.className = 'wdps-btn'; pill.textContent = 'Share result';
var inl = document.createElement('button');
inl.type = 'button'; inl.className = 'wdps-in'; inl.textContent = 'Share result'; inl.hidden = true;
var box = document.createElement('div');
box.className = 'wdps-box'; box.hidden = true;
box.setAttribute('role', 'dialog'); box.setAttribute('aria-label', 'Share your result');
box.innerHTML =
'<span data-a="msg">Share your result:</span>' +
'<button type="button" data-a="copy">Copy image</button>' +
'<a data-a="dl" download="result.png">Download image</a>' +
'<button type="button" data-a="more" hidden>More…</button>' +
'<a data-a="wa" target="_blank" rel="noopener">WhatsApp</a>' +
'<a data-a="x" target="_blank" rel="noopener">X</a>' +
'<a data-a="fb" target="_blank" rel="noopener">Facebook</a>' +
'<button type="button" class="wdps-x" data-a="close" aria-label="Close share options">×</button>';
document.body.appendChild(box);
document.body.appendChild(pill);
function q(a) { return box.querySelector('[data-a="' + a + '"]'); }
function ours(el) { return el === inl || el === pill || !!el.closest('.wdps-box'); }
/* ---- reading the result from the screen ---- */
function shown(el) {
if (!el || !el.getClientRects().length) return false;
for (var n = el; n && n !== document.body; n = n.parentElement) {
var cs = getComputedStyle(n);
if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) < 0.1) return false;
if (n.hidden || n.getAttribute('aria-hidden') === 'true') return false;
}
return true;
}
function txt(el) { return (el.textContent || '').replace(/\s+/g, ' ').trim(); }
function sig(el) { return ((el.id || '') + ' ' + (typeof el.className === 'string' ? el.className : '')).toLowerCase(); }
var OUTCOME = /(you win|you won|win!|wins|victory|game over|time.?s up|cleared|complete|solved|defeat|you lose|you lost|lost|draw|crash|failed|success|congrat|score|result|finished|beat|all matched|well done|perfect|new best)/i;
var HEADSIG = /(title|headline|msg|message|banner|result|verdict|status)/;
var WIN = /(you win|you won|win!|wins|victory|cleared|complete|solved|success|congrat|beat|matched|perfect|new best|record)/i;
var LOSS = /(game over|time.?s up|defeat|you lose|you lost|lost|crash|failed|out of)/i;
var BOX = /(overlay|modal|banner|result|over|end|dialog|screen|popup|panel|card|finish|win)/;
function readResult() {
var head = '', sub = '', root = null, headEl = null;
var all = document.body.querySelectorAll('h1,h2,h3,h4,p,strong,div,span');
for (var i = 0; i < all.length && !head; i++) {
var el = all[i];
if (ours(el) || el.children.length > 2) continue;
if (!HEADSIG.test(sig(el))) continue;
/* a banner that holds its own title: use the title inside it instead */
var inner = false;
for (var c = 0; c < el.children.length; c++) if (HEADSIG.test(sig(el.children[c]))) inner = true;
if (inner) continue;
var t = txt(el);
if (t.length < 3 || t.length > 70 || !OUTCOME.test(t) || !shown(el)) continue;
head = t; headEl = el; root = el.parentElement;
}
if (root) {
var kids = root.querySelectorAll('p,span,div');
for (var j = 0; j < kids.length && !sub; j++) {
var k = kids[j];
if (ours(k) || k.children.length > 2 || !/(sub|text|summary|note|desc|detail)/.test(sig(k))) continue;
var tt = txt(k);
if (tt && tt !== head && tt.length >= 5 && tt.length <= 160 && shown(k)) sub = tt;
}
}
/* the result screen the button goes into: the nearest overlay / banner / result box around the headline */
var host = null;
for (var n = headEl, d = 0; n && n !== document.body && d < 4; n = n.parentElement, d++) {
if (d > 0 && BOX.test(sig(n)) && n.tagName !== 'BUTTON') { host = n; break; }
}
return { head: head, sub: sub, host: host };
}
var STATRE = /(score|moves|time|wpm|best|level|streak|accuracy|combo|coins|distance|height|points|stars|lives|wins|attempt|guess)/;
function readStats() {
var out = [], seen = {};
var all = document.body.querySelectorAll('span,strong,b,div,p,output');
for (var i = 0; i < all.length && out.length < 4; i++) {
var el = all[i];
if (ours(el) || el.children.length > 1) continue;
if (!STATRE.test(sig(el))) continue;
var t = txt(el);
if (!t || t.length > 28 || !/[0-9]/.test(t) || !shown(el)) continue;
if (!/[a-zA-Z]/.test(t) && el.parentElement) {
var parts = [], ch = el.parentElement.childNodes;
for (var p = 0; p < ch.length; p++) { var pv = (ch[p].textContent || '').replace(/\s+/g, ' ').trim(); if (pv) parts.push(pv); }
var pt = parts.join(' ');
if (pt.length <= 30 && /[a-zA-Z]/.test(pt)) t = pt;
}
var key = t.toLowerCase();
if (seen[key]) continue;
seen[key] = 1; out.push(t);
}
return out;
}
function bestCanvas() {
var cs = document.querySelectorAll('canvas'), best = null, area = 0;
for (var i = 0; i < cs.length; i++) {
var r = cs[i].getBoundingClientRect(), a = r.width * r.height;
if (a > area && a > 8000 && shown(cs[i])) { area = a; best = cs[i]; }
}
return best;
}
/* ---- show the button when a result is on screen ---- */
var lastHost = null, timer = 0;
function sync() {
timer = 0;
var r = readResult();
if (r.head && r.host) {
if (inl.parentElement !== r.host) r.host.appendChild(inl);
if (inl.hidden) inl.hidden = false;
if (!pill.hidden) pill.hidden = true;
} else {
if (!inl.hidden) inl.hidden = true;
if (pill.hidden) pill.hidden = false;
pill.classList.toggle('wdps-hot', !!r.head);
}
if (lastHost && !r.head && !box.hidden) box.hidden = true;
lastHost = r.head ? (r.host || document.body) : null;
}
function later() { if (!timer) timer = setTimeout(sync, 200); }
try {
new MutationObserver(function (list) {
for (var i = 0; i < list.length; i++) {
var t = list[i].target;
if (t.nodeType !== 1) t = t.parentElement;
if (t && !ours(t)) { later(); return; }
}
}).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['class', 'style', 'hidden'] });
} catch (e) {}
setInterval(later, 1500);
later();
/* ---- the card (1080 x 1080, drawn in memory, light like Pocket Artillery's) ---- */
var outline = 0;
function put(g, t, x, y) { if (outline) { g.lineJoin = 'round'; g.lineWidth = outline; g.strokeStyle = 'rgba(8,12,28,.85)'; g.strokeText(t, x, y); } g.fillText(t, x, y); }
function wrap(g, text, x, y, maxW, lh, maxLines) {
var words = text.split(' '), line = '', n = 0;
for (var i = 0; i < words.length; i++) {
var tst = line ? line + ' ' + words[i] : words[i];
if (g.measureText(tst).width > maxW && line) {
put(g, line, x, y); y += lh; n++; line = words[i];
if (n >= maxLines - 1) { line = words.slice(i).join(' '); break; }
} else line = tst;
}
if (line) {
while (line.length > 3 && g.measureText(line).width > maxW) line = line.slice(0, -2);
put(g, line, x, y); y += lh;
}
return y;
}
/* Biggest-screenshot card: the game frame fills the whole image, the text sits on top of it as an overlay. */
function bgOf(el) {
for (var n = el; n; n = n.parentElement) {
var c = getComputedStyle(n).backgroundColor;
if (c && c !== 'transparent' && c.slice(-4) !== ', 0)') return c;
}
return '#0f172a';
}
function drawBig(info, cv) {
var W = 1080, r = cv.width / cv.height, H = Math.max(810, Math.min(1350, Math.round(W / r)));
var c = document.createElement('canvas'); c.width = W; c.height = H;
var g = c.getContext('2d');
g.fillStyle = bgOf(cv.parentElement || cv); g.fillRect(0, 0, W, H);
var w = W, h = w / r;
if (h > H) { h = H; w = h * r; }
g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high';
try { g.drawImage(cv, (W - w) / 2, (H - h) / 2, w, h); } catch (e) { return null; }
/* dark fades under the text so it stays readable on any game colours */
var g1 = g.createLinearGradient(0, 0, 0, H * 0.55); g1.addColorStop(0, 'rgba(8,12,28,.74)'); g1.addColorStop(1, 'rgba(8,12,28,0)');
g.fillStyle = g1; g.fillRect(0, 0, W, H * 0.55);
var g2 = g.createLinearGradient(0, H - 200, 0, H); g2.addColorStop(0, 'rgba(8,12,28,0)'); g2.addColorStop(1, 'rgba(8,12,28,.85)');
g.fillStyle = g2; g.fillRect(0, H - 200, W, 200);
var head = info.head || 'Can you beat me?';
var kind = /draw|tie/i.test(head) ? 'draw' : LOSS.test(head) && !WIN.test(head) ? 'loss' : 'win';
g.textAlign = 'center';
var y = 36;
g.fillStyle = 'rgba(255,255,255,.93)'; g.font = '800 34px system-ui, sans-serif'; outline = 7;
y = wrap(g, TITLE.toUpperCase(), W / 2, y + 34, 1000, 42, 1);
g.fillStyle = kind === 'draw' ? '#e2e8f0' : kind === 'loss' ? '#9db8ff' : '#ffc233';
var big = head.length > 22 ? 84 : 112; g.font = '900 ' + big + 'px system-ui, sans-serif'; outline = 16;
y = wrap(g, head, W / 2, y + big * 0.85, 1000, big * 1.05, 2);
if (info.sub) { g.fillStyle = '#fff'; g.font = '700 40px system-ui, sans-serif'; outline = 9; y = wrap(g, info.sub, W / 2, y + 6, 980, 50, 2); }
outline = 0;
if (info.stats.length) {
g.font = '800 38px system-ui, sans-serif';
var gap = 16, pad = 26, ws = [], tot = -gap;
for (var i = 0; i < info.stats.length; i++) { ws.push(g.measureText(info.stats[i]).width + pad * 2); tot += ws[i] + gap; }
var sc = tot > 960 ? 960 / tot : 1, px = (W - tot * sc) / 2, py = y + 14;
for (var k = 0; k < info.stats.length; k++) {
var w0 = ws[k] * sc;
g.fillStyle = 'rgba(8,12,28,.72)'; g.strokeStyle = 'rgba(255,255,255,.55)'; g.lineWidth = 3;
g.beginPath();
if (g.roundRect) g.roundRect(px, py, w0, 68, 34); else g.rect(px, py, w0, 68);
g.fill(); g.stroke();
g.fillStyle = '#fff'; g.font = '800 ' + Math.round(38 * sc) + 'px system-ui, sans-serif';
g.fillText(info.stats[k], px + w0 / 2, py + 47);
px += w0 + gap * sc;
}
}
outline = 8;
g.fillStyle = '#fff'; g.font = '900 52px system-ui, sans-serif'; put(g, 'Can you beat it?', W / 2, H - 84);
g.fillStyle = 'rgba(255,255,255,.92)'; g.font = '700 34px system-ui, sans-serif'; outline = 6; put(g, 'Play free at webdevpuneet.com', W / 2, H - 34);
outline = 0;
return c;
}
function finish(c, cb) {
var dataUrl = '';
try { dataUrl = c.toDataURL('image/png'); } catch (e) {}
try { c.toBlob(function (b) { cb(b, dataUrl); }, 'image/png'); } catch (e) { cb(null, dataUrl); }
}
function makeCard(info, cb) {
var cv0 = bestCanvas();
if (cv0) { var bc = drawBig(info, cv0); if (bc) { finish(bc, cb); return; } }
var S = 1080, c = document.createElement('canvas');
c.width = S; c.height = S;
var g = c.getContext('2d');
var gr = g.createLinearGradient(0, 0, 0, S);
gr.addColorStop(0, '#eaf4ff'); gr.addColorStop(1, '#fff3ef');
g.fillStyle = gr; g.fillRect(0, 0, S, S);
var cv = bestCanvas();
var head = info.head || 'Can you beat me?';
var kind = /draw|tie/i.test(head) ? 'draw' : LOSS.test(head) && !WIN.test(head) ? 'loss' : 'win';
g.textAlign = 'center';
g.fillStyle = '#1e293b'; g.font = '800 60px system-ui, sans-serif';
var y = wrap(g, TITLE, S / 2, cv ? 120 : 200, 980, 68, 1);
g.fillStyle = kind === 'draw' ? '#475569' : kind === 'loss' ? '#3b63e0' : '#e8553a';
g.font = '800 ' + (head.length > 22 ? 76 : 100) + 'px system-ui, sans-serif';
y = wrap(g, head, S / 2, y + (head.length > 22 ? 70 : 90), 980, head.length > 22 ? 84 : 108, 2);
if (info.sub) { g.fillStyle = '#475569'; g.font = '700 38px system-ui, sans-serif'; y = wrap(g, info.sub, S / 2, y + 4, 940, 48, 2); }
if (info.stats.length) {
g.font = '800 36px system-ui, sans-serif';
var gap = 18, pad = 26, ws = [], tot = -gap;
for (var i = 0; i < info.stats.length; i++) { ws.push(g.measureText(info.stats[i]).width + pad * 2); tot += ws[i] + gap; }
var sc = tot > 1000 ? 1000 / tot : 1, px = (S - tot * sc) / 2, py = y + 14;
for (var k = 0; k < info.stats.length; k++) {
var w0 = ws[k] * sc;
g.fillStyle = '#ffffff'; g.strokeStyle = '#d5e2ee'; g.lineWidth = 3;
g.beginPath();
if (g.roundRect) g.roundRect(px, py, w0, 64, 32); else g.rect(px, py, w0, 64);
g.fill(); g.stroke();
g.fillStyle = '#1e293b'; g.font = '800 ' + Math.round(36 * sc) + 'px system-ui, sans-serif';
g.fillText(info.stats[k], px + w0 / 2, py + 44);
px += w0 + gap * sc;
}
y = py + 64 + 10;
}
if (cv) {
try {
var maxW = 960, maxH = Math.max(180, 930 - y - 30), r = cv.width / cv.height;
var w = maxW, h = w / r;
if (h > maxH) { h = maxH; w = h * r; }
var x = (S - w) / 2, yy = y + 20 + Math.max(0, (maxH - h) / 2);
g.save(); g.shadowColor = 'rgba(60,100,140,0.3)'; g.shadowBlur = 30; g.shadowOffsetY = 10;
g.fillStyle = '#fff'; g.fillRect(x - 8, yy - 8, w + 16, h + 16); g.restore();
g.drawImage(cv, x, yy, w, h);
} catch (e) {}
}
g.fillStyle = '#1e293b'; g.font = '800 46px system-ui, sans-serif';
g.fillText('Can you beat it?', S / 2, 1000);
g.fillStyle = '#64748b'; g.font = '700 34px system-ui, sans-serif';
g.fillText('Play free at webdevpuneet.com', S / 2, 1050);
var dataUrl = '';
try { dataUrl = c.toDataURL('image/png'); } catch (e) {}
try { c.toBlob(function (b) { cb(b, dataUrl); }, 'image/png'); } catch (e) { cb(null, dataUrl); }
}
function shareText(info) {
var bits = [];
if (info.head) bits.push(info.head);
if (info.stats.length) bits.push(info.stats.join(', '));
return TITLE + ': ' + (bits.length ? bits.join(' - ') + '. ' : '') + 'Can you beat it? ' + URL;
}
function msg(t) { q('msg').textContent = t; }
function openFallback() {
var t = encodeURIComponent(shareText(lastInfo));
q('wa').href = 'https://wa.me/?text=' + t;
q('x').href = 'https://twitter.com/intent/tweet?text=' + t;
q('fb').href = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(URL) + '"e=' + t;
box.hidden = false;
}
function nativeShare() {
/* a user cancel does nothing; anything else (blocked in an iframe, no permission) shows Copy / Download / links */
try {
navigator.share({ files: [file], title: TITLE, text: shareText(lastInfo) }).catch(function (e) { if (!e || e.name !== 'AbortError') openFallback(); });
} catch (e) { openFallback(); }
}
function onShare() {
var info = readResult(); info.stats = readStats();
lastInfo = info;
msg('Share your result:');
makeCard(info, function (b, dataUrl) {
blob = b; file = null;
if (b) { try { file = new File([b], 'result.png', { type: 'image/png' }); } catch (e) {} }
if (dataUrl) q('dl').href = dataUrl;
q('dl').hidden = !dataUrl;
var canNative = !!(file && navigator.share && navigator.canShare && navigator.canShare({ files: [file] }));
var touch = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
q('more').hidden = !canNative;
if (canNative && touch) nativeShare();
else openFallback();
});
}
/* Games often have document/window level touch and pointer handlers (some call preventDefault, which cancels the tap's
click on phones, others restart the game on touchstart). So: keep every pointer event on our controls away from the
game, and fire on touchend as well as click (guarded so one tap shares once). */
var busy = 0;
function trigger() { if (busy) return; busy = 1; setTimeout(function () { busy = 0; }, 700); onShare(); }
function guard(el, act) {
var evs = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'touchstart', 'touchend', 'click'];
for (var i = 0; i < evs.length; i++) el.addEventListener(evs[i], function (e) { e.stopPropagation(); });
if (act) {
el.addEventListener('touchend', function (e) { if (e.cancelable) e.preventDefault(); act(); });
el.addEventListener('click', function () { act(); });
}
}
guard(pill, trigger);
guard(inl, trigger);
guard(box);
q('more').addEventListener('click', function () { if (file) nativeShare(); });
q('close').addEventListener('click', function () { box.hidden = true; });
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !box.hidden) box.hidden = true; });
q('copy').addEventListener('click', function () {
try {
navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).then(
function () { msg('Image copied. Paste it into your chat or post.'); },
function () { msg('Could not copy here. Try Download image.'); }
);
} catch (e) { msg('Copying images is not supported here. Try Download image.'); }
});
})();
/* wdp-share:end */Extend with AI
Take This Snippet Further With AI
Start by asking an AI assistant to explain the fixed time step and how the flipper surface velocity is added in the bounce function, because those two decide how the table feels. Good next changes are a second table layout chosen from the menu, a ramp that carries the ball over the playfield, or a saved list of top five scores with initials.
Prompt to recreate it
Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:
Build a complete pinball game in plain HTML, CSS and JavaScript on canvas, with no libraries, images or audio files.
Requirements:
- A 420x760 logical table scaled to fit, bright carnival palette, side panel with score, ball, multiplier, best, mission, perks and buttons; compact top bar on phones.
- Fixed 1/600 s physics: gravity, segment walls with a curved top, circle bumpers, and two rotating tapered flippers that pass surface velocity to the ball. Support several balls with ball-to-ball collision.
- Charged plunger with a one-way gate, three pop bumpers, two slingshots, left drop target bank (raises playfield multiplier), right target bank (lights multiball lock), three rollover lanes that rotate with the flippers (bonus multiplier), spinner, centre hole, kickbacks and drain.
- Skill shot, ball save, combos, end-of-ball bonus, extra ball, nudge with tilt.
- Centre hole starts four timed missions; each win offers a choice of three perks from nine; every third mission starts a 30 second five-times multiball round.
- Modes: Classic (3 balls), Blitz (120 s), Zen (endless), Daily (date-seeded choices). Best score per mode in localStorage inside try/catch.
- Web Audio effects and a simple looping tune with mute and music toggles, particles, floating scores, screen shake, attract-mode autoplay behind the menu.
- Keyboard and multi-touch input, pause and auto-pause, respect prefers-reduced-motion.Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.