• Updated 5 Dec, 01:22 UTC
  • Next run 5 Dec, 05:17 UTCNext 5 Dec 05:17
  • Last 7 days: 7 new models · 66 runs7 d: 7 models · 66 runs
Playable Breakout

Step 5StepFun

Network offOpen alone (new tab)

Run details

Model
stepfun/step-5
Route
OpenRouter API
Served by
StepFun
Effort
max (OpenRouter default)
Limits
60 min · 64,000 output tokens (model max)
Date
4 Dec 2026
Time
7 min 1 s
Size
61 kB
Tokens
97 in, 59,189 out (38,423 thinking)
List price
$0.16 at today's price ($1.00 in / $2.70 out per M)
Paid
$0.16

Raw: output · meta.json

Prompt

Make a Breakout game I can play right now with the keyboard or the mouse. Give it several levels, a score and some juice.

It must be one complete, self-contained HTML file: inline all CSS and JavaScript, and make no network requests of any kind (no CDNs, web fonts or remote images). Reply with the file in a single ```html code block.

Source

61 kB 2,292 lines Raw

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#050711">
<link rel="icon" href="data:,">
<title>Prism Breakout</title>
<style>
  :root {
    --bg: #050711;
    --panel: #0b1020;
    --cyan: #62f5ff;
    --pink: #ff5edb;
    --lime: #b6ff6a;
    --text: #eaf6ff;
    --muted: #71819c;
  }

  * { box-sizing: border-box; }
  [hidden] { display: none !important; }

  html, body {
    margin: 0;
    min-height: 100%;
    background: var(--bg);
  }

  body {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    overflow-x: hidden;
    color: var(--text);
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
    background:
      radial-gradient(circle at 14% 12%, rgba(45, 220, 255, .13), transparent 34%),
      radial-gradient(circle at 86% 84%, rgba(255, 64, 196, .11), transparent 38%),
      radial-gradient(circle at 50% 50%, #0a1020 0%, #050711 70%);
    overscroll-behavior: none;
  }

  body::before {
    content: "";
    position: fixed;
    inset: 0;
    pointer-events: none;
    opacity: .24;
    background-image:
      linear-gradient(rgba(120, 180, 255, .08) 1px, transparent 1px),
      linear-gradient(90deg, rgba(120, 180, 255, .08) 1px, transparent 1px);
    background-size: 48px 48px;
    mask-image: radial-gradient(circle at center, #000 0%, transparent 76%);
  }

  button {
    font: inherit;
    -webkit-tap-highlight-color: transparent;
  }

  .game-shell {
    position: relative;
    width: min(1060px, 100%);
  }

  .topbar {
    display: flex;
    align-items: center;
    gap: 14px;
    padding: 0 4px 14px;
  }

  .brand {
    display: flex;
    align-items: center;
    gap: 11px;
    min-width: max-content;
  }

  .brand-mark {
    width: 38px;
    height: 38px;
    display: grid;
    place-items: center;
    border: 1px solid rgba(98, 245, 255, .5);
    border-radius: 11px;
    color: var(--cyan);
    font-size: 21px;
    background: linear-gradient(145deg, rgba(98, 245, 255, .13), rgba(255, 94, 219, .08));
    box-shadow: 0 0 22px rgba(98, 245, 255, .13), inset 0 0 16px rgba(98, 245, 255, .05);
    text-shadow: 0 0 12px rgba(98, 245, 255, .8);
  }

  .brand-name {
    font-family: Arial Black, Impact, system-ui, sans-serif;
    font-size: 18px;
    font-weight: 900;
    letter-spacing: .11em;
    line-height: 1;
  }

  .brand-name span { color: var(--cyan); }

  .brand-sub {
    margin-top: 5px;
    color: var(--muted);
    font-size: 8px;
    letter-spacing: .32em;
  }

  .hud {
    margin-left: auto;
    display: flex;
    gap: 9px;
  }

  .stat {
    min-width: 88px;
    padding: 8px 12px;
    border: 1px solid rgba(133, 178, 255, .14);
    border-radius: 10px;
    background: linear-gradient(145deg, rgba(17, 26, 48, .78), rgba(8, 13, 28, .78));
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .025);
  }

  .stat span {
    display: block;
    margin-bottom: 3px;
    color: var(--muted);
    font-size: 8px;
    letter-spacing: .2em;
  }

  .stat strong {
    display: block;
    color: #f4fbff;
    font-size: 16px;
    line-height: 1;
    letter-spacing: .06em;
    white-space: nowrap;
  }

  .stat.lives strong {
    color: var(--pink);
    letter-spacing: .12em;
    text-shadow: 0 0 12px rgba(255, 94, 219, .45);
  }

  .actions {
    display: flex;
    gap: 8px;
  }

  .icon-btn {
    min-height: 42px;
    padding: 10px 12px;
    border: 1px solid rgba(133, 178, 255, .18);
    border-radius: 10px;
    color: #b9c8dd;
    background: rgba(11, 17, 33, .8);
    cursor: pointer;
    font-size: 11px;
    letter-spacing: .08em;
    transition: border-color .15s, color .15s, background .15s, transform .15s;
  }

  .icon-btn:hover:not(:disabled) {
    color: var(--cyan);
    border-color: rgba(98, 245, 255, .48);
    background: rgba(18, 31, 54, .9);
    transform: translateY(-1px);
  }

  .icon-btn:disabled {
    opacity: .35;
    cursor: default;
  }

  .stage {
    position: relative;
    width: 100%;
    aspect-ratio: 16 / 10;
    overflow: hidden;
    isolation: isolate;
    border: 1px solid rgba(98, 245, 255, .26);
    border-radius: 18px;
    background: #070b18;
    box-shadow:
      0 0 0 1px rgba(98, 245, 255, .04),
      0 24px 90px rgba(0, 0, 0, .65),
      0 0 70px rgba(98, 245, 255, .07);
  }

  .stage::after {
    content: "";
    position: absolute;
    inset: 0;
    z-index: 3;
    pointer-events: none;
    background: repeating-linear-gradient(
      0deg,
      rgba(255, 255, 255, .022) 0px,
      rgba(255, 255, 255, .022) 1px,
      transparent 1px,
      transparent 4px
    );
    mix-blend-mode: overlay;
  }

  canvas {
    display: block;
    width: 100%;
    height: 100%;
    touch-action: none;
    cursor: crosshair;
  }

  .corner {
    position: absolute;
    z-index: 4;
    width: 18px;
    height: 18px;
    pointer-events: none;
    border-color: rgba(98, 245, 255, .72);
    filter: drop-shadow(0 0 5px rgba(98, 245, 255, .5));
  }

  .corner.tl { top: 10px; left: 10px; border-top: 2px solid; border-left: 2px solid; }
  .corner.tr { top: 10px; right: 10px; border-top: 2px solid; border-right: 2px solid; }
  .corner.bl { bottom: 10px; left: 10px; border-bottom: 2px solid; border-left: 2px solid; }
  .corner.br { bottom: 10px; right: 10px; border-bottom: 2px solid; border-right: 2px solid; }

  .overlay {
    position: absolute;
    inset: 0;
    z-index: 10;
    display: grid;
    place-items: center;
    padding: 20px;
    background:
      radial-gradient(circle at 50% 35%, rgba(33, 64, 105, .28), transparent 58%),
      rgba(3, 6, 15, .74);
    backdrop-filter: blur(7px);
    -webkit-backdrop-filter: blur(7px);
    transition: opacity .25s ease;
  }

  .overlay.hidden {
    opacity: 0;
    pointer-events: none;
  }

  .overlay-card {
    position: relative;
    width: min(520px, 100%);
    padding: 30px 34px;
    text-align: center;
    border: 1px solid rgba(98, 245, 255, .23);
    border-radius: 18px;
    background: linear-gradient(145deg, rgba(15, 23, 43, .94), rgba(7, 11, 24, .96));
    box-shadow:
      0 24px 80px rgba(0, 0, 0, .55),
      0 0 44px rgba(98, 245, 255, .07),
      inset 0 1px 0 rgba(255, 255, 255, .04);
    transition: transform .25s ease;
  }

  .overlay-card::before {
    content: "";
    position: absolute;
    top: -1px;
    left: 18%;
    right: 18%;
    height: 1px;
    background: linear-gradient(90deg, transparent, var(--cyan), transparent);
    box-shadow: 0 0 14px var(--cyan);
  }

  .overlay.hidden .overlay-card {
    transform: translateY(8px) scale(.985);
  }

  .eyebrow {
    margin-bottom: 12px;
    color: var(--cyan);
    font-size: 10px;
    letter-spacing: .28em;
    text-shadow: 0 0 12px rgba(98, 245, 255, .5);
  }

  .overlay-title {
    margin: 0 0 16px;
    color: #f7fbff;
    font-family: Arial Black, Impact, system-ui, sans-serif;
    font-size: clamp(38px, 6vw, 64px);
    font-weight: 900;
    line-height: .86;
    letter-spacing: -.045em;
    text-shadow: 0 4px 26px rgba(0, 0, 0, .55);
  }

  .overlay-title span {
    color: transparent;
    background: linear-gradient(90deg, var(--cyan), #a391ff 52%, var(--pink));
    -webkit-background-clip: text;
    background-clip: text;
    filter: drop-shadow(0 0 16px rgba(98, 245, 255, .18));
  }

  .overlay-text {
    max-width: 400px;
    margin: 0 auto 18px;
    color: #9fb0c9;
    font-size: 13px;
    line-height: 1.6;
  }

  .overlay-stats {
    display: flex;
    justify-content: center;
    gap: 9px;
    margin-bottom: 20px;
  }

  .overlay-stats div {
    flex: 1;
    padding: 10px 8px;
    border: 1px solid rgba(133, 178, 255, .13);
    border-radius: 9px;
    background: rgba(5, 10, 23, .55);
  }

  .overlay-stats span {
    display: block;
    color: var(--muted);
    font-size: 8px;
    letter-spacing: .16em;
  }

  .overlay-stats b {
    display: block;
    margin-top: 5px;
    color: #f4fbff;
    font-size: 15px;
    letter-spacing: .05em;
  }

  .primary-btn,
  .secondary-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 14px;
    padding: 13px 24px;
    border-radius: 10px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 900;
    letter-spacing: .12em;
    transition: transform .15s, box-shadow .15s, border-color .15s, color .15s;
  }

  .primary-btn {
    border: 0;
    color: #04101a;
    background: linear-gradient(90deg, var(--cyan), #8f7cff);
    box-shadow: 0 0 26px rgba(98, 245, 255, .25);
  }

  .primary-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 36px rgba(98, 245, 255, .4);
  }

  .secondary-btn {
    margin-left: 8px;
    border: 1px solid rgba(133, 178, 255, .24);
    color: #b9c8dd;
    background: rgba(8, 14, 29, .7);
  }

  .secondary-btn:hover {
    color: var(--cyan);
    border-color: rgba(98, 245, 255, .5);
    transform: translateY(-2px);
  }

  .primary-btn:focus-visible,
  .secondary-btn:focus-visible,
  .icon-btn:focus-visible {
    outline: 2px solid var(--cyan);
    outline-offset: 3px;
  }

  .overlay-controls {
    margin-top: 18px;
    color: var(--muted);
    font-size: 9px;
    line-height: 1.9;
    letter-spacing: .07em;
  }

  kbd {
    display: inline-block;
    min-width: 18px;
    padding: 1px 5px;
    border: 1px solid rgba(133, 178, 255, .22);
    border-bottom-color: rgba(133, 178, 255, .38);
    border-radius: 4px;
    color: #c8d7ea;
    background: rgba(255, 255, 255, .035);
    font: inherit;
  }

  .serve-hint {
    position: absolute;
    left: 50%;
    bottom: 15%;
    z-index: 6;
    padding: 8px 14px;
    border: 1px solid rgba(98, 245, 255, .25);
    border-radius: 999px;
    color: #9fb0c9;
    background: rgba(5, 10, 23, .76);
    font-size: 10px;
    letter-spacing: .11em;
    white-space: nowrap;
    pointer-events: none;
    opacity: 0;
    transform: translate(-50%, 10px);
    transition: opacity .2s, transform .2s;
  }

  .serve-hint span {
    color: var(--cyan);
    font-weight: 800;
  }

  .serve-hint.show {
    opacity: 1;
    transform: translate(-50%, 0);
    animation: hintPulse 1.8s ease-in-out infinite;
  }

  @keyframes hintPulse {
    0%, 100% { box-shadow: 0 0 0 rgba(98, 245, 255, 0); }
    50% { box-shadow: 0 0 22px rgba(98, 245, 255, .13); }
  }

  .combo-badge {
    position: absolute;
    top: 16px;
    right: 18px;
    z-index: 6;
    padding: 7px 10px;
    border: 1px solid rgba(255, 94, 219, .28);
    border-radius: 8px;
    color: #9fb0c9;
    background: rgba(10, 8, 25, .7);
    font-size: 9px;
    letter-spacing: .12em;
    pointer-events: none;
    opacity: 0;
    transform: translateY(-5px);
    transition: opacity .18s, transform .18s;
  }

  .combo-badge.show {
    opacity: 1;
    transform: translateY(0);
  }

  .combo-badge b {
    color: var(--pink);
    font-size: 14px;
    text-shadow: 0 0 12px rgba(255, 94, 219, .55);
  }

  .combo-badge small {
    color: var(--cyan);
    font-size: 9px;
  }

  .effects {
    position: absolute;
    top: 14px;
    left: 50%;
    z-index: 6;
    display: flex;
    gap: 6px;
    transform: translateX(-50%);
    pointer-events: none;
  }

  .effect-chip {
    padding: 5px 8px;
    border: 1px solid;
    border-radius: 6px;
    background: rgba(5, 10, 23, .78);
    font-size: 9px;
    letter-spacing: .08em;
    white-space: nowrap;
  }

  .effect-chip b { color: #fff; }

  .footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 14px 4px 0;
    color: var(--muted);
    font-size: 9px;
    letter-spacing: .1em;
  }

  .footer-controls span { color: #b9c8dd; }

  .pips {
    display: flex;
    gap: 6px;
  }

  .pip {
    width: 22px;
    height: 4px;
    border-radius: 3px;
    background: rgba(133, 178, 255, .14);
    transition: background .2s, box-shadow .2s;
  }

  .pip.done {
    background: rgba(98, 245, 255, .58);
  }

  .pip.active {
    background: var(--pink);
    box-shadow: 0 0 10px rgba(255, 94, 219, .65);
  }

  .bricks-left {
    min-width: 86px;
    text-align: right;
    color: #b9c8dd;
  }

  @media (max-width: 680px) {
    body { padding: 10px; }
    .topbar { flex-wrap: wrap; gap: 8px; padding-bottom: 10px; }
    .brand-sub { display: none; }
    .hud { order: 3; width: 100%; margin-left: 0; gap: 6px; }
    .stat { flex: 1; min-width: 0; padding: 6px 8px; }
    .stat strong { font-size: 13px; }
    .stat span { font-size: 7px; }
    .actions { margin-left: auto; }
    .stage { border-radius: 12px; }
    .overlay { padding: 10px; }
    .overlay-card { padding: 16px 18px; border-radius: 12px; }
    .overlay-title { font-size: 36px; margin-bottom: 10px; }
    .overlay-text { font-size: 11px; margin-bottom: 12px; }
    .overlay-stats { margin-bottom: 12px; gap: 6px; }
    .overlay-stats div { padding: 7px; }
    .overlay-stats b { font-size: 12px; }
    .overlay-controls { display: none; }
    .primary-btn, .secondary-btn { padding: 10px 14px; font-size: 10px; }
    .footer { padding-top: 10px; }
    .footer-controls { display: none; }
    .combo-badge { top: 10px; right: 10px; font-size: 8px; }
    .effects { top: 8px; }
    .effect-chip { padding: 4px 6px; font-size: 8px; }
  }

  @media (max-width: 420px) {
    .brand-name { font-size: 13px; }
    .brand-mark { width: 30px; height: 30px; font-size: 16px; }
    .icon-btn { min-height: 34px; padding: 8px; font-size: 10px; }
    .overlay-title { font-size: 30px; }
    .overlay-text { font-size: 10px; line-height: 1.4; }
    .overlay-stats { display: none; }
    .overlay-card { padding: 12px 14px; }
    .eyebrow { margin-bottom: 8px; font-size: 8px; }
    .primary-btn, .secondary-btn { padding: 9px 12px; }
    .serve-hint { bottom: 12%; padding: 6px 10px; font-size: 8px; }
  }

  @media (max-width: 360px) {
    .overlay { padding: 6px; }
    .overlay-card { padding: 10px 12px; }
    .overlay-title { font-size: 26px; }
    .overlay-text { display: none; }
  }

  @media (prefers-reduced-motion: reduce) {
    .serve-hint.show { animation: none; }
    .overlay, .overlay-card, .primary-btn, .secondary-btn { transition: none; }
  }
</style>
</head>
<body>
<div class="game-shell">
  <header class="topbar">
    <div class="brand">
      <div class="brand-mark">◈</div>
      <div>
        <div class="brand-name">PRISM <span>BREAKOUT</span></div>
        <div class="brand-sub">NEON ARCADE</div>
      </div>
    </div>

    <div class="hud">
      <div class="stat"><span>SCORE</span><strong id="score">000000</strong></div>
      <div class="stat"><span>SECTOR</span><strong id="level">01 / 07</strong></div>
      <div class="stat lives"><span>LIVES</span><strong id="lives">♥♥♥</strong></div>
    </div>

    <div class="actions">
      <button id="soundBtn" class="icon-btn" type="button" aria-label="Toggle sound" aria-pressed="false">♪ <span id="soundLabel">ON</span></button>
      <button id="pauseBtn" class="icon-btn" type="button" aria-label="Pause game" disabled>Ⅱ</button>
    </div>
  </header>

  <main class="stage" id="stage">
    <canvas id="game" width="960" height="600" aria-label="Prism Breakout game"></canvas>
    <span class="corner tl"></span>
    <span class="corner tr"></span>
    <span class="corner bl"></span>
    <span class="corner br"></span>

    <div id="effects" class="effects"></div>
    <div id="combo" class="combo-badge">CHAIN <b>×2</b></div>
    <div id="serveHint" class="serve-hint"><span>CLICK / TAP / SPACE</span> TO LAUNCH</div>

    <div id="overlay" class="overlay">
      <div class="overlay-card">
        <div id="overlayEyebrow" class="eyebrow"></div>
        <h1 id="overlayTitle" class="overlay-title"></h1>
        <p id="overlayText" class="overlay-text"></p>
        <div id="overlayStats" class="overlay-stats"></div>
        <button id="primaryBtn" class="primary-btn" type="button"></button>
        <button id="secondaryBtn" class="secondary-btn" type="button" hidden></button>
        <div class="overlay-controls">
          <kbd>←</kbd><kbd>→</kbd> or <kbd>A</kbd><kbd>D</kbd> move &nbsp;·&nbsp; mouse / touch steer<br>
          <kbd>SPACE</kbd> launch &nbsp;·&nbsp; <kbd>P</kbd> pause &nbsp;·&nbsp; <kbd>M</kbd> mute
        </div>
      </div>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-controls"><span>MOVE</span> ← → / A D / MOUSE &nbsp; <span>LAUNCH</span> SPACE / CLICK</div>
    <div id="levelPips" class="pips" aria-label="Level progress"></div>
    <div id="bricksLeft" class="bricks-left">48 BRICKS</div>
  </footer>
</div>

<script>
(() => {
  'use strict';

  const W = 960;
  const H = 600;
  const STEP = 1 / 120;
  const BASE_PADDLE_W = 126;
  const PADDLE_SPEED = 720;

  const canvas = document.getElementById('game');
  const ctx = canvas.getContext('2d');
  const stage = document.getElementById('stage');
  const scoreEl = document.getElementById('score');
  const levelEl = document.getElementById('level');
  const livesEl = document.getElementById('lives');
  const bricksLeftEl = document.getElementById('bricksLeft');
  const comboEl = document.getElementById('combo');
  const effectBar = document.getElementById('effects');
  const serveHint = document.getElementById('serveHint');
  const pauseBtn = document.getElementById('pauseBtn');
  const soundBtn = document.getElementById('soundBtn');
  const soundLabel = document.getElementById('soundLabel');
  const overlay = document.getElementById('overlay');
  const overlayEyebrow = document.getElementById('overlayEyebrow');
  const overlayTitle = document.getElementById('overlayTitle');
  const overlayText = document.getElementById('overlayText');
  const overlayStats = document.getElementById('overlayStats');
  const primaryBtn = document.getElementById('primaryBtn');
  const secondaryBtn = document.getElementById('secondaryBtn');
  const levelPips = document.getElementById('levelPips');

  const LEVELS = [
    {
      name: 'FIRST LIGHT', speed: 400, hue: 186, rows: 4,
      pattern: () => 1
    },
    {
      name: 'SPLIT SIGNAL', speed: 430, hue: 286, rows: 5,
      pattern: (r, c) => ((r + c) % 2 ? 2 : 1)
    },
    {
      name: 'THE ASCENT', speed: 465, hue: 150, rows: 6,
      pattern: (r, c, rows, cols) => {
        const d = Math.abs(c - (cols - 1) / 2);
        return r >= Math.floor(d) ? (d > 4 ? 3 : 2) : 0;
      }
    },
    {
      name: 'HARD CIRCUIT', speed: 500, hue: 38, rows: 6,
      pattern: (r, c) => ((r + c) % 3 === 0 ? 3 : (r % 2 ? 2 : 1))
    },
    {
      name: 'PRISM CORE', speed: 535, hue: 322, rows: 7,
      pattern: (r, c, rows, cols) => {
        const d = Math.abs(c - (cols - 1) / 2) + Math.abs(r - (rows - 1) / 2) * .8;
        return d > 6 ? 0 : Math.min(4, 1 + Math.floor(d / 1.7));
      }
    },
    {
      name: 'BLACK ICE', speed: 570, hue: 202, rows: 7,
      pattern: (r, c, rows, cols) => {
        if (r === 0 || r === rows - 1) return 2;
        if (c < 2 || c > cols - 3) return 3;
        if (r > 1 && r < rows - 2 && c > 3 && c < cols - 4) return 4;
        return 2;
      }
    },
    {
      name: 'AFTERGLOW', speed: 610, hue: 265, rows: 8,
      pattern: (r, c) => {
        const n = (r * 7 + c * 3) % 13;
        if (n === 0) return 4;
        if (n < 4) return 3;
        if (n < 8) return 2;
        return 1;
      }
    }
  ];

  const POWER_TYPES = {
    wide:  { color: '#62f5ff', icon: 'W', label: 'WIDE PADDLE', short: 'WIDE', sub: 'PADDLE ENLARGED · 12s' },
    multi: { color: '#ff5edb', icon: 'M', label: 'MULTIBALL', short: 'MULTI', sub: 'THREE BALLS · NO MERCY' },
    slow:  { color: '#9b8cff', icon: 'S', label: 'SLOW FIELD', short: 'SLOW', sub: 'TIME DILATION · 8s' },
    laser: { color: '#ffd166', icon: 'L', label: 'PULSE CANNON', short: 'LASER', sub: 'AUTO-FIRE ENABLED · 10s' },
    life:  { color: '#b6ff6a', icon: '+', label: 'EXTRA LIFE', short: 'LIFE', sub: 'SIGNAL RESTORED' }
  };

  let state = 'menu';
  let pausedFrom = 'playing';
  let score = 0;
  let highScore = 0;
  let lives = 3;
  let levelIndex = 0;
  let combo = 0;
  let bestCombo = 0;
  let bricksRemaining = 0;
  let bricksTotal = 0;
  let levelTime = 0;
  let clearTimer = 0;
  let lifeTimer = 0;
  let lastBonus = 0;
  let totalTime = 0;
  let hitStop = 0;
  let shake = 0;
  let flash = 0;
  let effectUiTimer = 0;
  let announceObj = null;
  let primaryAction = null;
  let secondaryAction = null;

  let bricks = [];
  let balls = [];
  let particles = [];
  let rings = [];
  let floaters = [];
  let powerups = [];
  let lasers = [];
  let stars = [];

  const paddle = {
    x: W / 2,
    y: H - 42,
    w: BASE_PADDLE_W,
    h: 14,
    hit: 0,
    laserTimer: 0
  };

  const keys = { left: false, right: false };
  const pointer = { x: W / 2, active: false };
  const effects = { wide: 0, slow: 0, laser: 0 };

  let audioCtx = null;
  let master = null;
  let muted = false;

  try {
    highScore = parseInt(localStorage.getItem('prism-breakout-best') || '0', 10) || 0;
  } catch (_) {}

  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
  const pad2 = n => String(n).padStart(2, '0');
  const formatScore = n => String(Math.floor(n)).padStart(6, '0');
  const easeOutCubic = t => 1 - Math.pow(1 - t, 3);

  function roundRect(x, y, w, h, r) {
    r = Math.min(r, w / 2, h / 2);
    ctx.beginPath();
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + w - r, y);
    ctx.quadraticCurveTo(x + w, y, x + w, y + r);
    ctx.lineTo(x + w, y + h - r);
    ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
    ctx.lineTo(x + r, y + h);
    ctx.quadraticCurveTo(x, y + h, x, y + h - r);
    ctx.lineTo(x, y + r);
    ctx.quadraticCurveTo(x, y, x + r, y);
    ctx.closePath();
  }

  function circleRect(cx, cy, r, b) {
    const nx = clamp(cx, b.x, b.x + b.w);
    const ny = clamp(cy, b.y, b.y + b.h);
    const dx = cx - nx;
    const dy = cy - ny;
    return dx * dx + dy * dy <= r * r;
  }

  function resizeCanvas() {
    const rect = canvas.getBoundingClientRect();
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    canvas.width = Math.max(1, Math.round(rect.width * dpr));
    canvas.height = Math.max(1, Math.round(rect.height * dpr));
  }

  function saveBest() {
    try {
      localStorage.setItem('prism-breakout-best', String(highScore));
    } catch (_) {}
  }

  function initAudio() {
    if (!audioCtx) {
      const AC = window.AudioContext || window.webkitAudioContext;
      if (!AC) return;
      try {
        audioCtx = new AC();
        master = audioCtx.createGain();
        master.gain.value = muted ? 0 : .22;
        master.connect(audioCtx.destination);
      } catch (_) {
        audioCtx = null;
        master = null;
      }
    }
    if (audioCtx && audioCtx.state === 'suspended') {
      audioCtx.resume().catch(() => {});
    }
  }

  function tone(freq, dur, type = 'sine', vol = .2, slide = 0, delay = 0) {
    if (!audioCtx || muted) return;
    const t0 = audioCtx.currentTime + delay;
    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();
    osc.type = type;
    osc.frequency.setValueAtTime(Math.max(30, freq), t0);
    if (slide) {
      osc.frequency.exponentialRampToValueAtTime(Math.max(30, freq + slide), t0 + dur);
    }
    gain.gain.setValueAtTime(.0001, t0);
    gain.gain.exponentialRampToValueAtTime(Math.max(.0002, vol), t0 + .006);
    gain.gain.exponentialRampToValueAtTime(.0001, t0 + dur);
    osc.connect(gain);
    gain.connect(master);
    osc.start(t0);
    osc.stop(t0 + dur + .03);
  }

  function sfx(name) {
    if (!audioCtx || muted) return;
    switch (name) {
      case 'click':
        tone(620, .045, 'sine', .12, 80);
        break;
      case 'start':
        [330, 440, 660].forEach((f, i) => tone(f, .12, 'triangle', .16, 40, i * .07));
        break;
      case 'launch':
        tone(240, .13, 'triangle', .22, 480);
        break;
      case 'paddle':
        tone(170, .07, 'square', .12, -60);
        break;
      case 'wall':
        tone(460, .03, 'sine', .05, -100);
        break;
      case 'brick':
        tone(520 + Math.min(combo, 20) * 28, .055, 'triangle', .12, 100);
        break;
      case 'destroy':
        tone(720 + Math.min(combo, 20) * 36, .08, 'square', .1, 220);
        tone(1100 + Math.min(combo, 20) * 30, .05, 'sine', .07, 180, .015);
        break;
      case 'power':
        [523, 659, 784, 1047].forEach((f, i) => tone(f, .12, 'triangle', .14, 30, i * .055));
        break;
      case 'laser':
        tone(1200, .035, 'sawtooth', .035, -500);
        break;
      case 'lose':
        tone(240, .4, 'sawtooth', .18, -170);
        tone(120, .5, 'triangle', .12, -60, .05);
        break;
      case 'clear':
        [523, 659, 784, 1047].forEach((f, i) => tone(f, .25, 'triangle', .13, 20, i * .09));
        break;
      case 'victory':
        [523, 659, 784, 1047, 1319].forEach((f, i) => tone(f, .35, 'triangle', .14, 30, i * .11));
        break;
    }
  }

  function toggleMute() {
    muted = !muted;
    if (master && audioCtx) {
      master.gain.setTargetAtTime(muted ? 0 : .22, audioCtx.currentTime, .02);
    }
    soundLabel.textContent = muted ? 'OFF' : 'ON';
    soundBtn.setAttribute('aria-pressed', String(muted));
    sfx('click');
  }

  function createStars() {
    stars = [];
    for (let i = 0; i < 82; i++) {
      stars.push({
        x: Math.random() * W,
        y: Math.random() * H,
        size: .4 + Math.random() * 1.6,
        speed: 6 + Math.random() * 18,
        alpha: .12 + Math.random() * .46,
        phase: Math.random() * Math.PI * 2
      });
    }
  }

  function buildPips() {
    levelPips.innerHTML = '';
    LEVELS.forEach((lv, i) => {
      const pip = document.createElement('span');
      pip.className = 'pip';
      pip.title = lv.name;
      levelPips.appendChild(pip);
    });
  }

  function buildLevel(index) {
    const cfg = LEVELS[index];
    const cols = 12;
    const gapX = 8;
    const gapY = 8;
    const marginX = 50;
    const top = 92;
    const bh = 22;
    const bw = (W - marginX * 2 - gapX * (cols - 1)) / cols;

    bricks = [];
    balls = [];
    particles = [];
    rings = [];
    floaters = [];
    powerups = [];
    lasers = [];
    announceObj = null;
    combo = 0;
    bricksRemaining = 0;
    bricksTotal = 0;
    levelTime = 0;
    clearTimer = 0;
    hitStop = 0;
    shake = 0;
    flash = 0;

    paddle.x = W / 2;
    paddle.w = BASE_PADDLE_W;
    paddle.hit = 0;
    paddle.laserTimer = 0;
    resetEffects();

    for (let r = 0; r < cfg.rows; r++) {
      for (let c = 0; c < cols; c++) {
        const hp = cfg.pattern(r, c, cfg.rows, cols);
        if (!hp) continue;
        bricks.push({
          x: marginX + c * (bw + gapX),
          y: top + r * (bh + gapY),
          w: bw,
          h: bh,
          hp,
          maxHp: hp,
          value: 40 + index * 10 + hp * 15,
          hue: (cfg.hue + r * 9 + c * 1.4) % 360,
          flash: 0,
          appear: -(r + c) * .018
        });
        bricksRemaining++;
        bricksTotal++;
      }
    }

    updateHUD();
  }

  function resetEffects() {
    effects.wide = 0;
    effects.slow = 0;
    effects.laser = 0;
    paddle.w = BASE_PADDLE_W;
    paddle.laserTimer = 0;
    updateEffectBar();
  }

  function getBaseSpeed() {
    return LEVELS[levelIndex].speed;
  }

  function getMultiplier() {
    return Math.min(5, 1 + Math.floor(combo / 4));
  }

  function makeBall(stuck = true, hue = 190) {
    return {
      x: paddle.x,
      y: paddle.y - 10,
      vx: 0,
      vy: 0,
      r: 7,
      stuck,
      trail: [],
      hue
    };
  }

  function changeState(next) {
    state = next;
    syncUI();
  }

  function syncUI() {
    serveHint.classList.toggle('show', state === 'serve');
    pauseBtn.disabled = !(state === 'playing' || state === 'serve' || state === 'paused');
    pauseBtn.textContent = state === 'paused' ? '▶' : 'Ⅱ';
    comboEl.classList.toggle('show', combo >= 2 && (state === 'playing' || state === 'clearing'));
  }

  function updateHUD() {
    scoreEl.textContent = formatScore(score);
    levelEl.textContent = `${pad2(levelIndex + 1)} / ${pad2(LEVELS.length)}`;
    livesEl.textContent = '♥'.repeat(Math.max(0, lives)) + '♡'.repeat(Math.max(0, 3 - lives));
    bricksLeftEl.textContent = `${bricksRemaining} ${bricksRemaining === 1 ? 'BRICK' : 'BRICKS'}`;
    comboEl.innerHTML = `CHAIN <b>×${combo}</b> <small>· ${getMultiplier()}x</small>`;
    comboEl.classList.toggle('show', combo >= 2 && (state === 'playing' || state === 'clearing'));

    [...levelPips.children].forEach((pip, i) => {
      pip.classList.toggle('done', i < levelIndex);
      pip.classList.toggle('active', i === levelIndex);
    });

    updateEffectBar();
  }

  function updateEffectBar() {
    const items = [];
    if (effects.wide > 0) items.push({ ...POWER_TYPES.wide, time: effects.wide });
    if (effects.slow > 0) items.push({ ...POWER_TYPES.slow, time: effects.slow });
    if (effects.laser > 0) items.push({ ...POWER_TYPES.laser, time: effects.laser });

    effectBar.innerHTML = items.map(it => (
      `<span class="effect-chip" style="color:${it.color};border-color:${it.color}55;box-shadow:0 0 12px ${it.color}22">${it.icon} ${it.short} <b>${Math.ceil(it.time)}s</b></span>`
    )).join('');
  }

  function showOverlay(kind) {
    overlay.classList.remove('hidden');
    overlay.setAttribute('aria-hidden', 'false');
    secondaryBtn.hidden = true;
    secondaryAction = null;

    let eyebrow = '';
    let title = '';
    let text = '';
    let stats = '';
    let primary = '';

    if (kind === 'menu') {
      eyebrow = 'NEON ARCADE // 7 SECTORS';
      title = 'PRISM<br><span>BREAKOUT</span>';
      text = 'Shatter the grid. Chain your hits. Catch the power-ups.';
      stats = `
        <div><span>BEST</span><b>${formatScore(highScore)}</b></div>
        <div><span>SECTORS</span><b>07</b></div>
        <div><span>LIVES</span><b>03</b></div>`;
      primary = 'START RUN';
      primaryAction = startGame;
    } else if (kind === 'paused') {
      eyebrow = 'SYSTEM HOLD';
      title = 'PAUSED<br><span>SIGNAL</span>';
      text = 'Take a breath. The grid can wait.';
      stats = `
        <div><span>SCORE</span><b>${formatScore(score)}</b></div>
        <div><span>SECTOR</span><b>${pad2(levelIndex + 1)}</b></div>
        <div><span>BRICKS</span><b>${bricksRemaining}</b></div>`;
      primary = 'RESUME';
      secondaryBtn.hidden = false;
      secondaryBtn.textContent = 'RESTART';
      primaryAction = resumeGame;
      secondaryAction = startGame;
    } else if (kind === 'levelclear') {
      eyebrow = `SECTOR ${pad2(levelIndex + 1)} SECURED`;
      title = 'SECTOR<br><span>CLEAR</span>';
      text = `${LEVELS[levelIndex].name} broken. Bonus banked: +${formatScore(lastBonus)}.`;
      stats = `
        <div><span>SCORE</span><b>${formatScore(score)}</b></div>
        <div><span>BEST CHAIN</span><b>×${bestCombo}</b></div>
        <div><span>BONUS</span><b>+${formatScore(lastBonus)}</b></div>`;
      primary = 'NEXT SECTOR';
      primaryAction = nextLevel;
    } else if (kind === 'gameover') {
      eyebrow = 'CONNECTION TERMINATED';
      title = 'SIGNAL<br><span>LOST</span>';
      text = `The grid survived sector ${pad2(levelIndex + 1)}. Reboot and try again.`;
      stats = `
        <div><span>SCORE</span><b>${formatScore(score)}</b></div>
        <div><span>BEST CHAIN</span><b>×${bestCombo}</b></div>
        <div><span>SECTOR</span><b>${pad2(levelIndex + 1)} / 07</b></div>`;
      primary = 'TRY AGAIN';
      secondaryBtn.hidden = false;
      secondaryBtn.textContent = 'MAIN MENU';
      primaryAction = startGame;
      secondaryAction = goMenu;
    } else if (kind === 'victory') {
      eyebrow = 'ALL SECTORS SECURED';
      title = 'GRID<br><span>BROKEN</span>';
      text = 'Every frequency silenced. The prism is yours.';
      stats = `
        <div><span>FINAL SCORE</span><b>${formatScore(score)}</b></div>
        <div><span>BEST CHAIN</span><b>×${bestCombo}</b></div>
        <div><span>BEST</span><b>${formatScore(highScore)}</b></div>`;
      primary = 'RUN IT BACK';
      secondaryBtn.hidden = false;
      secondaryBtn.textContent = 'MAIN MENU';
      primaryAction = startGame;
      secondaryAction = goMenu;
    }

    overlayEyebrow.textContent = eyebrow;
    overlayTitle.innerHTML = title;
    overlayText.textContent = text;
    overlayStats.innerHTML = stats;
    primaryBtn.innerHTML = `${primary} <span>→</span>`;
  }

  function hideOverlay() {
    overlay.classList.add('hidden');
    overlay.setAttribute('aria-hidden', 'true');
  }

  function startGame() {
    initAudio();
    sfx('start');
    score = 0;
    lives = 3;
    levelIndex = 0;
    bestCombo = 0;
    combo = 0;
    buildLevel(0);
    beginServe();
    hideOverlay();
  }

  function goMenu() {
    saveBest();
    score = 0;
    lives = 3;
    levelIndex = 0;
    combo = 0;
    bestCombo = 0;
    buildLevel(0);
    changeState('menu');
    updateHUD();
    showOverlay('menu');
  }

  function beginServe() {
    resetEffects();
    balls = [makeBall(true)];
    combo = 0;
    changeState('serve');
    announce(`SECTOR ${pad2(levelIndex + 1)}`, LEVELS[levelIndex].name, '#62f5ff', 1.35);
    updateHUD();
  }

  function getServeAngle() {
    return clamp((paddle.x - W / 2) / (W / 2), -1, 1) * 1.02;
  }

  function launchBall() {
    if (state !== 'serve') return;
    initAudio();
    const b = balls[0];
    if (!b) return;
    let angle = getServeAngle();
    if (Math.abs(angle) < .1) angle += (Math.random() - .5) * .12;
    const speed = getBaseSpeed();
    b.stuck = false;
    b.vx = Math.sin(angle) * speed;
    b.vy = -Math.cos(angle) * speed;
    b.trail = [];
    changeState('playing');
    spawnParticles(b.x, b.y, '#62f5ff', 12, 150);
    sfx('launch');
  }

  function pauseGame() {
    if (state !== 'playing' && state !== 'serve') return;
    pausedFrom = state;
    changeState('paused');
    showOverlay('paused');
    sfx('click');
  }

  function resumeGame() {
    if (state !== 'paused') return;
    changeState(pausedFrom);
    hideOverlay();
    sfx('click');
  }

  function nextLevel() {
    if (state !== 'levelclear') return;
    levelIndex++;
    buildLevel(levelIndex);
    beginServe();
    hideOverlay();
    sfx('start');
  }

  function announce(title, sub, color = '#62f5ff', duration = 1.2) {
    announceObj = { title, sub, color, life: duration, max: duration };
  }

  function spawnParticles(x, y, color, count = 10, speed = 180) {
    for (let i = 0; i < count; i++) {
      if (particles.length > 500) break;
      const a = Math.random() * Math.PI * 2;
      const s = speed * (.25 + Math.random() * .75);
      const life = .25 + Math.random() * .45;
      particles.push({
        x, y,
        vx: Math.cos(a) * s,
        vy: Math.sin(a) * s,
        life,
        max: life,
        size: 1.5 + Math.random() * 2.8,
        color,
        gravity: 80 + Math.random() * 120,
        shape: Math.random() < .35 ? 'line' : 'dot'
      });
    }
  }

  function maybeDropPowerup(b) {
    const chance = .14 + levelIndex * .006;
    if (Math.random() > chance) return;
    const roll = Math.random();
    let type;
    if (roll < .26) type = 'wide';
    else if (roll < .48) type = 'multi';
    else if (roll < .68) type = 'slow';
    else if (roll < .88) type = 'laser';
    else type = 'life';

    powerups.push({
      x: b.x + b.w / 2,
      y: b.y + b.h / 2,
      vy: 125,
      size: 26,
      type,
      rot: (Math.random() - .5) * .4
    });
  }

  function hitBrick(index, x, y) {
    if (state !== 'playing' && state !== 'clearing') return;
    const b = bricks[index];
    if (!b) return;

    b.hp--;
    b.flash = 1;
    combo++;
    bestCombo = Math.max(bestCombo, combo);

    const mult = getMultiplier();
    const destroyed = b.hp <= 0;
    const gained = destroyed ? b.value * mult + 25 : 10 * mult;
    score += gained;
    if (score > highScore) highScore = score;

    floaters.push({
      x: b.x + b.w / 2,
      y: b.y + 2,
      text: `+${gained}`,
      color: destroyed ? '#ffffff' : '#a8ddff',
      life: .7,
      max: .7,
      size: destroyed ? 15 : 11
    });

    spawnParticles(x, y, `hsl(${b.hue} 95% 65%)`, destroyed ? 18 : 7, destroyed ? 230 : 120);

    if (destroyed) {
      rings.push({
        x: b.x + b.w / 2,
        y: b.y + b.h / 2,
        r: 4,
        life: .35,
        maxLife: .35,
        color: `hsl(${b.hue} 95% 65%)`
      });
      bricks.splice(index, 1);
      bricksRemaining--;
      shake = Math.min(20, shake + 4.5);
      flash = Math.min(1, flash + .07);
      hitStop = Math.max(hitStop, .018);
      sfx('destroy');
      maybeDropPowerup(b);

      if (combo % 5 === 0) {
        announce(`CHAIN ×${combo}`, `MULTIPLIER ×${getMultiplier()}`, '#ff5edb', 1);
      }

      if (bricksRemaining <= 0) beginClear();
    } else {
      shake = Math.min(12, shake + 1.5);
      sfx('brick');
    }

    updateHUD();
  }

  function resolveBallBrick(ball, b) {
    const cx = b.x + b.w / 2;
    const cy = b.y + b.h / 2;
    const dx = ball.x - cx;
    const dy = ball.y - cy;
    const ox = (b.w / 2 + ball.r) - Math.abs(dx);
    const oy = (b.h / 2 + ball.r) - Math.abs(dy);
    if (ox <= 0 || oy <= 0) return false;

    if (ox < oy) {
      const s = dx === 0 ? (ball.vx < 0 ? -1 : 1) : Math.sign(dx);
      ball.x += s * (ox + .01);
      ball.vx = s * Math.abs(ball.vx);
    } else {
      const s = dy === 0 ? (ball.vy < 0 ? -1 : 1) : Math.sign(dy);
      ball.y += s * (oy + .01);
      ball.vy = s * Math.abs(ball.vy);
    }
    return true;
  }

  function spawnMulti() {
    const src = balls.find(b => !b.stuck);
    if (!src) return;
    if (balls.length >= 4) {
      score += 200;
      if (score > highScore) highScore = score;
      floaters.push({ x: src.x, y: src.y - 12, text: 'MAX BALLS +200', color: '#ff5edb', life: .8, max: .8, size: 12 });
      return;
    }

    const speed = Math.hypot(src.vx, src.vy) || getBaseSpeed();
    const base = Math.atan2(src.vy, src.vx);
    const hues = [320, 265];

    for (let i = 0; i < 2 && balls.length < 4; i++) {
      const a = base + (i === 0 ? -.42 : .42);
      balls.push({
        x: src.x,
        y: src.y,
        vx: Math.cos(a) * speed,
        vy: Math.sin(a) * speed,
        r: src.r,
        stuck: false,
        trail: [],
        hue: hues[i]
      });
    }
  }

  function applyPowerup(type, x, y) {
    const data = POWER_TYPES[type];
    spawnParticles(x, y, data.color, 26, 250);
    rings.push({ x, y, r: 5, life: .45, maxLife: .45, color: data.color });
    shake = Math.min(16, shake + 7);
    flash = Math.min(1, flash + .28);
    sfx('power');

    if (type === 'wide') {
      effects.wide = 12;
    } else if (type === 'multi') {
      spawnMulti();
    } else if (type === 'slow') {
      effects.slow = 8;
    } else if (type === 'laser') {
      effects.laser = 10;
      paddle.laserTimer = 0;
    } else if (type === 'life') {
      if (lives < 5) {
        lives++;
      } else {
        score += 500;
        floaters.push({ x, y: y - 14, text: 'MAX LIVES +500', color: '#b6ff6a', life: .9, max: .9, size: 13 });
      }
    }

    if (score > highScore) highScore = score;
    announce(data.label, data.sub, data.color, 1.15);
    updateHUD();
  }

  function beginClear() {
    if (state !== 'playing') return;
    changeState('clearing');
    clearTimer = 1.15;
    hitStop = 0;
    shake = Math.min(24, shake + 13);
    flash = Math.min(1, flash + .45);
    announce('SECTOR CLEAR', LEVELS[levelIndex].name, '#b6ff6a', 1.1);
    rings.push({ x: W / 2, y: H / 2, r: 10, life: .8, maxLife: .8, color: '#b6ff6a' });
    sfx('clear');
    updateHUD();
  }

  function finishLevel() {
    const timeBonus = Math.max(0, Math.round(360 - levelTime * 14));
    const lifeBonus = lives * 100;
    const sectorBonus = 500 + levelIndex * 100;
    lastBonus = timeBonus + lifeBonus + sectorBonus;
    score += lastBonus;
    if (score > highScore) highScore = score;
    saveBest();
    updateHUD();

    if (levelIndex >= LEVELS.length - 1) {
      changeState('victory');
      showOverlay('victory');
      sfx('victory');
    } else {
      changeState('levelclear');
      showOverlay('levelclear');
    }
  }

  function loseLife() {
    lives--;
    combo = 0;
    resetEffects();
    powerups = [];
    lasers = [];
    paddle.hit = 1;
    shake = 22;
    flash = .85;
    sfx('lose');

    if (lives > 0) {
      announce('SIGNAL LOST', `${lives} ${lives === 1 ? 'LIFE' : 'LIVES'} REMAINING`, '#ff5edb', .85);
    } else {
      announce('RUN ENDED', 'NO SIGNAL REMAINING', '#ff5edb', .85);
    }

    changeState('lifeLost');
    lifeTimer = .9;
    updateHUD();
  }

  function showGameOver() {
    saveBest();
    changeState('gameover');
    showOverlay('gameover');
    updateHUD();
  }

  function updatePaddle(dt) {
    const dir = (keys.right ? 1 : 0) - (keys.left ? 1 : 0);
    if (dir !== 0) {
      paddle.x += dir * PADDLE_SPEED * dt;
      pointer.active = false;
    } else if (pointer.active) {
      paddle.x += (pointer.x - paddle.x) * Math.min(1, dt * 20);
    }

    const half = paddle.w / 2;
    paddle.x = clamp(paddle.x, half + 8, W - half - 8);
  }

  function updateEffects(dt) {
    if (effects.wide > 0) effects.wide = Math.max(0, effects.wide - dt);
    if (effects.slow > 0) effects.slow = Math.max(0, effects.slow - dt);
    if (effects.laser > 0) effects.laser = Math.max(0, effects.laser - dt);

    const targetW = effects.wide > 0 ? BASE_PADDLE_W * 1.55 : BASE_PADDLE_W;
    paddle.w += (targetW - paddle.w) * Math.min(1, dt * 14);

    if (effects.laser > 0 && state === 'playing') {
      paddle.laserTimer -= dt;
      if (paddle.laserTimer <= 0) {
        paddle.laserTimer = .28;
        const y = paddle.y - 6;
        lasers.push({ x: paddle.x - paddle.w * .32, y, vy: -760 });
        lasers.push({ x: paddle.x + paddle.w * .32, y, vy: -760 });
        sfx('laser');
      }
    }

    effectUiTimer -= dt;
    if (effectUiTimer <= 0) {
      effectUiTimer = .1;
      updateEffectBar();
    }
  }

  function updateBalls(dt, clearing = false) {
    for (let i = balls.length - 1; i >= 0; i--) {
      const b = balls[i];

      if (b.stuck) {
        b.x = paddle.x;
        b.y = paddle.y - b.r - 3;
        b.trail.length = 0;
        continue;
      }

      const slow = effects.slow > 0 ? .72 : 1;
      b.x += b.vx * dt * slow;
      b.y += b.vy * dt * slow;

      b.trail.push({ x: b.x, y: b.y });
      if (b.trail.length > 16) b.trail.shift();

      if (b.x - b.r < 0) {
        b.x = b.r;
        b.vx = Math.abs(b.vx);
        spawnParticles(0, b.y, '#62f5ff', 3, 90);
        sfx('wall');
      } else if (b.x + b.r > W) {
        b.x = W - b.r;
        b.vx = -Math.abs(b.vx);
        spawnParticles(W, b.y, '#62f5ff', 3, 90);
        sfx('wall');
      }

      if (b.y - b.r < 0) {
        b.y = b.r;
        b.vy = Math.abs(b.vy);
        spawnParticles(b.x, 0, '#62f5ff', 3, 90);
        sfx('wall');
      }

      if (
        b.vy > 0 &&
        b.y + b.r >= paddle.y &&
        b.y - b.r <= paddle.y + paddle.h &&
        b.x + b.r >= paddle.x - paddle.w / 2 &&
        b.x - b.r <= paddle.x + paddle.w / 2
      ) {
        b.y = paddle.y - b.r - .1;
        const hit = clamp((b.x - paddle.x) / (paddle.w / 2), -1, 1);
        const angle = hit * 1.08;
        const speed = Math.min(760, Math.max(getBaseSpeed(), Math.hypot(b.vx, b.vy)) * 1.012);
        b.vx = Math.sin(angle) * speed;
        b.vy = -Math.cos(angle) * speed;
        paddle.hit = 1;
        combo = 0;
        shake = Math.max(shake, 3);
        spawnParticles(b.x, paddle.y, '#62f5ff', 9, 160);
        sfx('paddle');
        updateHUD();
      }

      for (let j = bricks.length - 1; j >= 0; j--) {
        const br = bricks[j];
        if (circleRect(b.x, b.y, b.r, br)) {
          resolveBallBrick(b, br);
          hitBrick(j, b.x, b.y);
          break;
        }
      }

      if (!clearing && state !== 'playing') return;

      if (b.y - b.r > H + 12) {
        spawnParticles(b.x, H - 4, `hsl(${b.hue} 100% 65%)`, 20, 230);
        balls.splice(i, 1);
      }
    }

    if (!clearing && state === 'playing' && balls.length === 0) {
      loseLife();
    }
  }

  function updatePowerups(dt) {
    for (let i = powerups.length - 1; i >= 0; i--) {
      const p = powerups[i];
      p.y += p.vy * dt;
      p.rot += dt * 1.8;

      if (p.y > paddle.y - 90 && p.y < paddle.y + 20 && Math.abs(p.x - paddle.x) < paddle.w / 2 + 30) {
        p.x += (paddle.x - p.x) * Math.min(1, dt * 5);
      }

      const left = p.x - p.size / 2;
      const right = p.x + p.size / 2;
      const top = p.y - p.size / 2;
      const bottom = p.y + p.size / 2;

      if (
        bottom >= paddle.y &&
        top <= paddle.y + paddle.h &&
        right >= paddle.x - paddle.w / 2 &&
        left <= paddle.x + paddle.w / 2
      ) {
        applyPowerup(p.type, p.x, p.y);
        powerups.splice(i, 1);
        continue;
      }

      if (p.y > H + 30) powerups.splice(i, 1);
    }
  }

  function updateLasers(dt) {
    for (let i = lasers.length - 1; i >= 0; i--) {
      const l = lasers[i];
      l.y += l.vy * dt;

      if (l.y < -24) {
        lasers.splice(i, 1);
        continue;
      }

      let hit = false;
      for (let j = bricks.length - 1; j >= 0; j--) {
        const b = bricks[j];
        if (l.x >= b.x && l.x <= b.x + b.w && l.y <= b.y + b.h && l.y + 18 >= b.y) {
          hitBrick(j, l.x, l.y);
          lasers.splice(i, 1);
          hit = true;
          break;
        }
      }
      if (hit) continue;
    }
  }

  function updateBackground(dt) {
    for (const s of stars) {
      s.y += s.speed * dt;
      if (s.y > H + 2) {
        s.y = -2;
        s.x = Math.random() * W;
      }
    }
  }

  function updateFX(dt) {
    shake *= Math.exp(-9 * dt);
    if (shake < .05) shake = 0;
    flash = Math.max(0, flash - dt * 2.4);
    paddle.hit = Math.max(0, paddle.hit - dt * 6);

    for (let i = particles.length - 1; i >= 0; i--) {
      const p = particles[i];
      p.life -= dt;
      if (p.life <= 0) {
        particles.splice(i, 1);
        continue;
      }
      const drag = Math.exp(-1.8 * dt);
      p.vx *= drag;
      p.vy *= drag;
      p.vy += p.gravity * dt;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
    }

    for (let i = rings.length - 1; i >= 0; i--) {
      const r = rings[i];
      r.life -= dt;
      r.r += 170 * dt;
      if (r.life <= 0) rings.splice(i, 1);
    }

    for (let i = floaters.length - 1; i >= 0; i--) {
      const f = floaters[i];
      f.life -= dt;
      f.y -= 36 * dt;
      if (f.life <= 0) floaters.splice(i, 1);
    }

    if (announceObj) {
      announceObj.life -= dt;
      if (announceObj.life <= 0) announceObj = null;
    }
  }

  function updateBricksVisual(dt) {
    for (const b of bricks) {
      b.flash = Math.max(0, b.flash - dt * 5);
      b.appear = Math.min(1, b.appear + dt * 3.5);
    }
  }

  function update(dt) {
    totalTime += dt;
    updateBackground(dt);
    updateFX(dt);
    updateBricksVisual(dt);

    if (state === 'menu') {
      paddle.x = W / 2 + Math.sin(totalTime * .75) * 150;
      return;
    }

    if (state === 'paused' || state === 'gameover' || state === 'victory' || state === 'levelclear') {
      return;
    }

    updatePaddle(dt);

    if (state === 'serve') {
      for (const b of balls) {
        if (b.stuck) {
          b.x = paddle.x;
          b.y = paddle.y - b.r - 3;
          b.trail.length = 0;
        }
      }
      return;
    }

    if (state === 'lifeLost') {
      lifeTimer -= dt;
      if (lifeTimer <= 0) {
        if (lives > 0) beginServe();
        else showGameOver();
      }
      return;
    }

    if (state === 'playing') {
      updateEffects(dt);
      if (hitStop > 0) {
        hitStop -= dt;
        return;
      }
      levelTime += dt;
      updateBalls(dt, false);
      if (state !== 'playing') return;
      updatePowerups(dt);
      updateLasers(dt);
    } else if (state === 'clearing') {
      updateEffects(dt);
      clearTimer -= dt;
      updateBalls(dt, true);
      updatePowerups(dt);
      updateLasers(dt);
      if (clearTimer <= 0) finishLevel();
    }
  }

  function radialGlow(x, y, r, color) {
    const g = ctx.createRadialGradient(x, y, 0, x, y, r);
    g.addColorStop(0, color);
    g.addColorStop(1, 'rgba(0,0,0,0)');
    ctx.fillStyle = g;
    ctx.fillRect(x - r, y - r, r * 2, r * 2);
  }

  function drawBackground(t) {
    const g = ctx.createLinearGradient(0, 0, W, H);
    g.addColorStop(0, '#070b18');
    g.addColorStop(.5, '#080d1c');
    g.addColorStop(1, '#050812');
    ctx.fillStyle = g;
    ctx.fillRect(0, 0, W, H);

    radialGlow(90, 70, 280, 'rgba(44,220,255,.10)');
    radialGlow(W - 90, H - 70, 320, 'rgba(255,60,200,.085)');

    ctx.save();
    ctx.lineWidth = 1;
    ctx.strokeStyle = 'rgba(115,170,255,.047)';
    const off = (t * 6) % 48;
    ctx.beginPath();
    for (let x = -48 + off; x < W; x += 48) {
      ctx.moveTo(x, 0);
      ctx.lineTo(x, H);
    }
    for (let y = -48 + off; y < H; y += 48) {
      ctx.moveTo(0, y);
      ctx.lineTo(W, y);
    }
    ctx.stroke();
    ctx.restore();

    for (const s of stars) {
      const a = s.alpha * (.6 + .4 * Math.sin(t * 1.5 + s.phase));
      ctx.fillStyle = `rgba(180,225,255,${a})`;
      ctx.fillRect(s.x, s.y, s.size, s.size);
    }

    ctx.strokeStyle = 'rgba(98,245,255,.12)';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(24, H - 24);
    ctx.lineTo(W - 24, H - 24);
    ctx.stroke();
  }

  function drawBricks() {
    for (const b of bricks) {
      const p = easeOutCubic(clamp(b.appear, 0, 1));
      const cx = b.x + b.w / 2;
      const cy = b.y + b.h / 2;

      ctx.save();
      ctx.globalAlpha = p;
      ctx.translate(cx, cy + (1 - p) * 20);
      const sc = 1 + (1 - p) * .08;
      ctx.scale(sc, sc);
      ctx.translate(-cx, -cy);

      const grad = ctx.createLinearGradient(b.x, b.y, b.x, b.y + b.h);
      grad.addColorStop(0, `hsl(${b.hue} 95% 68%)`);
      grad.addColorStop(.45, `hsl(${b.hue} 90% 52%)`);
      grad.addColorStop(1, `hsl(${b.hue} 88% 34%)`);

      ctx.shadowColor = `hsla(${b.hue},95%,60%,${.35 + b.flash * .5})`;
      ctx.shadowBlur = 8 + b.flash * 18;
      ctx.fillStyle = grad;
      roundRect(b.x, b.y, b.w, b.h, 5);
      ctx.fill();
      ctx.shadowBlur = 0;

      ctx.fillStyle = 'rgba(255,255,255,.2)';
      roundRect(b.x + 2, b.y + 2, b.w - 4, 4, 2);
      ctx.fill();

      ctx.fillStyle = 'rgba(0,0,0,.18)';
      roundRect(b.x + 3, b.y + b.h - 5, b.w - 6, 3, 1.5);
      ctx.fill();

      if (b.hp > 1) {
        const pipW = 4;
        const gap = 3;
        const total = b.hp * pipW + (b.hp - 1) * gap;
        ctx.fillStyle = 'rgba(255,255,255,.62)';
        for (let i = 0; i < b.hp; i++) {
          roundRect(cx - total / 2 + i * (pipW + gap), b.y + b.h - 8, pipW, 3, 1.5);
          ctx.fill();
        }
      }

      if (b.flash > 0) {
        ctx.fillStyle = `rgba(255,255,255,${b.flash * .72})`;
        roundRect(b.x, b.y, b.w, b.h, 5);
        ctx.fill();
      }

      ctx.restore();
    }
  }

  function drawPaddle() {
    const w = paddle.w;
    const h = paddle.h;

    ctx.save();
    ctx.translate(paddle.x, paddle.y + h / 2);
    ctx.scale(1 + paddle.hit * .1, 1 - paddle.hit * .28);

    ctx.shadowColor = 'rgba(98,245,255,.85)';
    ctx.shadowBlur = 18 + paddle.hit * 15;
    const g = ctx.createLinearGradient(-w / 2, 0, w / 2, 0);
    g.addColorStop(0, '#2bd7ff');
    g.addColorStop(.5, '#c8fdff');
    g.addColorStop(1, '#7c6cff');
    ctx.fillStyle = g;
    roundRect(-w / 2, -h / 2, w, h, h / 2);
    ctx.fill();
    ctx.shadowBlur = 0;

    ctx.fillStyle = 'rgba(255,255,255,.7)';
    roundRect(-w / 2 + 6, -h / 2 + 2, w - 12, 3, 2);
    ctx.fill();

    ctx.fillStyle = 'rgba(4,16,30,.34)';
    roundRect(-w / 2 + 10, h / 2 - 4, w - 20, 2, 1);
    ctx.fill();

    if (effects.laser > 0) {
      ctx.fillStyle = '#ffd166';
      ctx.shadowColor = '#ffd166';
      ctx.shadowBlur = 12;
      for (const s of [-1, 1]) {
        roundRect(s * w * .32 - 3, -h / 2 - 4, 6, 6, 2);
        ctx.fill();
      }
    }

    ctx.restore();
  }

  function drawBall(b) {
    if (b.trail && b.trail.length > 1) {
      ctx.save();
      ctx.globalCompositeOperation = 'lighter';
      for (let i = 0; i < b.trail.length; i++) {
        const p = b.trail[i];
        const f = (i + 1) / b.trail.length;
        ctx.fillStyle = `hsla(${b.hue},100%,65%,${f * .28})`;
        ctx.beginPath();
        ctx.arc(p.x, p.y, b.r * f * .85, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.restore();
    }

    ctx.save();
    ctx.shadowColor = `hsl(${b.hue} 100% 60%)`;
    ctx.shadowBlur = 20;
    const g = ctx.createRadialGradient(b.x - b.r * .3, b.y - b.r * .3, 0, b.x, b.y, b.r);
    g.addColorStop(0, '#ffffff');
    g.addColorStop(.45, `hsl(${b.hue} 100% 76%)`);
    g.addColorStop(1, `hsl(${b.hue} 100% 50%)`);
    ctx.fillStyle = g;
    ctx.beginPath();
    ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
  }

  function drawPowerups(t) {
    for (const p of powerups) {
      const data = POWER_TYPES[p.type];
      const pulse = 1 + Math.sin(t * 6 + p.x) * .04;

      ctx.save();
      ctx.translate(p.x, p.y);
      ctx.rotate(p.rot);
      ctx.scale(pulse, pulse);
      ctx.shadowColor = data.color;
      ctx.shadowBlur = 16;
      ctx.fillStyle = 'rgba(5,10,23,.92)';
      roundRect(-p.size / 2, -p.size / 2, p.size, p.size, 7);
      ctx.fill();
      ctx.shadowBlur = 0;
      ctx.strokeStyle = data.color;
      ctx.lineWidth = 2;
      roundRect(-p.size / 2, -p.size / 2, p.size, p.size, 7);
      ctx.stroke();

      ctx.fillStyle = data.color;
      ctx.font = '900 14px ui-monospace, monospace';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(data.icon, 0, 1);
      ctx.restore();
    }
  }

  function drawLasers() {
    ctx.save();
    ctx.globalCompositeOperation = 'lighter';
    ctx.lineCap = 'round';
    for (const l of lasers) {
      ctx.shadowColor = '#ffd166';
      ctx.shadowBlur = 14;
      ctx.strokeStyle = '#ffd166';
      ctx.lineWidth = 3;
      ctx.beginPath();
      ctx.moveTo(l.x, l.y);
      ctx.lineTo(l.x, l.y + 18);
      ctx.stroke();
      ctx.shadowBlur = 0;
      ctx.strokeStyle = '#ffffff';
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(l.x, l.y);
      ctx.lineTo(l.x, l.y + 16);
      ctx.stroke();
    }
    ctx.restore();
  }

  function drawParticles() {
    ctx.save();
    ctx.globalCompositeOperation = 'lighter';
    for (const p of particles) {
      const a = clamp(p.life / p.max, 0, 1);
      ctx.globalAlpha = a;
      ctx.fillStyle = p.color;
      ctx.strokeStyle = p.color;
      ctx.shadowColor = p.color;
      ctx.shadowBlur = 6;

      if (p.shape === 'line') {
        ctx.lineWidth = p.size;
        ctx.beginPath();
        ctx.moveTo(p.x, p.y);
        ctx.lineTo(p.x - p.vx * .025, p.y - p.vy * .025);
        ctx.stroke();
      } else {
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.size * a, 0, Math.PI * 2);
        ctx.fill();
      }
    }
    ctx.restore();
  }

  function drawRings() {
    ctx.save();
    ctx.globalCompositeOperation = 'lighter';
    for (const r of rings) {
      ctx.globalAlpha = clamp(r.life / r.maxLife, 0, 1) * .7;
      ctx.strokeStyle = r.color;
      ctx.lineWidth = 2;
      ctx.shadowColor = r.color;
      ctx.shadowBlur = 10;
      ctx.beginPath();
      ctx.arc(r.x, r.y, r.r, 0, Math.PI * 2);
      ctx.stroke();
    }
    ctx.restore();
  }

  function drawFloaters() {
    ctx.save();
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    for (const f of floaters) {
      ctx.globalAlpha = clamp(f.life / f.max, 0, 1);
      ctx.fillStyle = f.color;
      ctx.shadowColor = f.color;
      ctx.shadowBlur = 10;
      ctx.font = `800 ${f.size}px ui-monospace, monospace`;
      ctx.fillText(f.text, f.x, f.y);
    }
    ctx.restore();
  }

  function drawAim() {
    const b = balls[0];
    if (!b) return;
    const a = getServeAngle();
    ctx.save();
    ctx.strokeStyle = 'rgba(98,245,255,.42)';
    ctx.lineWidth = 2;
    ctx.setLineDash([4, 8]);
    ctx.shadowColor = '#62f5ff';
    ctx.shadowBlur = 8;
    ctx.beginPath();
    ctx.moveTo(b.x, b.y - 4);
    ctx.lineTo(b.x + Math.sin(a) * 140, b.y - Math.cos(a) * 140);
    ctx.stroke();
    ctx.restore();
  }

  function drawAnnouncement() {
    if (!announceObj) return;
    const a = announceObj;
    const alpha = Math.min(1, a.life * 4, (a.max - a.life) * 8);
    if (alpha <= 0) return;

    ctx.save();
    ctx.globalAlpha = alpha;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.shadowColor = a.color;
    ctx.shadowBlur = 16;
    ctx.fillStyle = a.color;
    ctx.font = '900 25px Arial Black, Impact, system-ui, sans-serif';
    ctx.fillText(a.title, W / 2, H - 182);
    ctx.shadowBlur = 0;
    ctx.fillStyle = 'rgba(220,235,255,.72)';
    ctx.font = '700 10px ui-monospace, monospace';
    ctx.fillText(a.sub, W / 2, H - 158);
    ctx.restore();
  }

  function render(t) {
    ctx.setTransform(canvas.width / W, 0, 0, canvas.height / H, 0, 0);
    ctx.clearRect(0, 0, W, H);
    drawBackground(t);

    ctx.save();
    if (shake > .1) {
      ctx.translate((Math.random() - .5) * shake * 2, (Math.random() - .5) * shake * 2);
    }

    drawBricks();
    drawPowerups(t);
    drawLasers();
    drawRings();
    drawParticles();
    drawPaddle();

    if (state === 'menu') {
      drawBall({
        x: paddle.x,
        y: paddle.y - 18 + Math.sin(t * 3) * 3,
        r: 7,
        hue: 190,
        trail: []
      });
    } else {
      for (const b of balls) drawBall(b);
    }

    drawFloaters();
    if (state === 'serve') drawAim();
    drawAnnouncement();
    ctx.restore();

    if (flash > 0) {
      ctx.fillStyle = `rgba(255,255,255,${flash * .18})`;
      ctx.fillRect(0, 0, W, H);
    }

    const vg = ctx.createRadialGradient(W / 2, H / 2, H * .2, W / 2, H / 2, W * .7);
    vg.addColorStop(0, 'rgba(0,0,0,0)');
    vg.addColorStop(1, 'rgba(0,0,0,.34)');
    ctx.fillStyle = vg;
    ctx.fillRect(0, 0, W, H);
  }

  function setPointer(e) {
    const rect = canvas.getBoundingClientRect();
    pointer.x = clamp((e.clientX - rect.left) / rect.width * W, 0, W);
    pointer.active = true;
  }

  canvas.addEventListener('pointermove', e => {
    setPointer(e);
    if (e.pointerType === 'touch') e.preventDefault();
  }, { passive: false });

  canvas.addEventListener('pointerdown', e => {
    e.preventDefault();
    initAudio();
    setPointer(e);
    if (state === 'serve') launchBall();
    if (e.pointerType === 'touch') {
      try { canvas.setPointerCapture(e.pointerId); } catch (_) {}
    }
  });

  canvas.addEventListener('pointerup', e => {
    if (e.pointerType === 'touch') pointer.active = false;
  });

  canvas.addEventListener('pointercancel', () => {
    pointer.active = false;
  });

  canvas.addEventListener('pointerleave', e => {
    if (e.pointerType === 'mouse') pointer.active = false;
  });

  window.addEventListener('keydown', e => {
    const code = e.code;
    if (['ArrowLeft', 'ArrowRight', 'Space', 'KeyA', 'KeyD', 'KeyP', 'Escape', 'KeyR', 'KeyM'].includes(code)) {
      e.preventDefault();
    }

    if (code === 'ArrowLeft' || code === 'KeyA') {
      keys.left = true;
      pointer.active = false;
      return;
    }
    if (code === 'ArrowRight' || code === 'KeyD') {
      keys.right = true;
      pointer.active = false;
      return;
    }
    if (e.repeat) return;

    if (code === 'Space') {
      if (state === 'menu') startGame();
      else if (state === 'serve') launchBall();
      else if (state === 'paused') resumeGame();
      else if (state === 'levelclear') nextLevel();
      else if (state === 'gameover' || state === 'victory') startGame();
    } else if (code === 'KeyP' || code === 'Escape') {
      if (state === 'playing' || state === 'serve') pauseGame();
      else if (state === 'paused') resumeGame();
    } else if (code === 'KeyR') {
      if (state === 'paused' || state === 'gameover' || state === 'victory') startGame();
    } else if (code === 'KeyM') {
      initAudio();
      toggleMute();
    }
  });

  window.addEventListener('keyup', e => {
    if (e.code === 'ArrowLeft' || e.code === 'KeyA') keys.left = false;
    if (e.code === 'ArrowRight' || e.code === 'KeyD') keys.right = false;
  });

  window.addEventListener('blur', () => {
    keys.left = false;
    keys.right = false;
    pointer.active = false;
    if (state === 'playing' || state === 'serve') pauseGame();
  });

  document.addEventListener('visibilitychange', () => {
    if (document.hidden && (state === 'playing' || state === 'serve')) pauseGame();
  });

  pauseBtn.addEventListener('click', () => {
    initAudio();
    if (state === 'paused') resumeGame();
    else pauseGame();
  });

  soundBtn.addEventListener('click', () => {
    initAudio();
    toggleMute();
  });

  primaryBtn.addEventListener('click', () => {
    initAudio();
    sfx('click');
    if (primaryAction) primaryAction();
  });

  secondaryBtn.addEventListener('click', () => {
    initAudio();
    sfx('click');
    if (secondaryAction) secondaryAction();
  });

  window.addEventListener('beforeunload', saveBest);
  window.addEventListener('resize', resizeCanvas);

  if ('ResizeObserver' in window) {
    new ResizeObserver(resizeCanvas).observe(stage);
  }

  let lastTime = performance.now();
  let accumulator = 0;

  function frame(now) {
    const dt = Math.min(.05, Math.max(0, (now - lastTime) / 1000));
    lastTime = now;
    accumulator += dt;

    while (accumulator >= STEP) {
      update(STEP);
      accumulator -= STEP;
    }

    render(now / 1000);
    requestAnimationFrame(frame);
  }

  resizeCanvas();
  createStars();
  buildPips();
  buildLevel(0);
  changeState('menu');
  updateHUD();
  showOverlay('menu');
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>

Compare

Other runs