Files
breakout/index.html
T
michael 212b5d81a9 Eigener Chip-Tune-Soundtrack im Commander-Keen-Stil, prozedural über WebAudio
- audioBus() mit getrennten Busen: sfxGain für Effekt-Töne, musicGain für Musik
- Level-Theme 148 BPM (D-Moll, Puls-Lead, 16tel-Bass-Arpeggio, Noise-Hi-Hat),
  ruhiges Theme 96 BPM für Ready/Pause/Continue/Levelübergang,
  Game-Over-Kadenz über eigenen Gain-Knoten
- Scheduler mit 16tel-Raster und Vorlaufplanung im Animationsloop, Fadings beim
  Trackwechsel, Audio-Entsperrung beim ersten Klick/Tastendruck
- Option "Musik (Chip-Tune)" und Taste M, Persistenz in breakout.options
- Headless-Regressionstest ins Repo aufgenommen: test/pu-test.js (68 Checks)
- README um Musik, Continue/Checkpoint, Level-Varianten, Debug und Test ergänzt
2026-10-14 15:58:59 +00:00

1825 lines
80 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Breakout · Neon Clone</title>
<style>
:root {
--bg: #05070f;
--panel: #10172a;
--chip: #0b1224;
--border: rgba(140,160,200,0.18);
--border-2: rgba(140,160,200,0.32);
--text: #eaf0fb;
--muted: #9fb0cb;
--dim: #7d8ca6;
--green: #5DCAA5;
--purple: #AFA9EC;
--blue: #85B7EB;
--amber: #EF9F27;
--red: #F09595;
--radius: 16px;
--font: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
/* --pw = Spielfeld-Breite (JS), --s = UI-Skalierung (JS) */
--pw: 760px;
--s: 1;
--ls: 1;
--fieldH: 100%;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); font-family: var(--font); }
html { height: 100%; }
body {
min-height: 100vh; min-height: 100dvh;
display: flex; flex-direction: column; align-items: center; justify-content: center;
padding: clamp(6px, 1.2vw, 18px) clamp(6px, 1vw, 16px);
}
#panel {
width: min(100%, var(--pw));
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: clamp(10px, 1.4vw, 18px);
}
#head { display: flex; align-items: flex-start; gap: 12px; flex-wrap: wrap; margin-bottom: 10px; }
#title { font-size: calc(16px * var(--s)); font-weight: 500; letter-spacing: .04em; }
#sub { font-size: calc(11px * var(--s)); color: var(--muted); margin-top: 3px; }
kbd {
font-family: var(--font); font-size: calc(10.5px * var(--s)); padding: 2px 6px;
border: 1px solid var(--border-2); border-bottom-width: 2px;
border-radius: 5px; background: var(--chip); color: var(--text);
}
#strip { display: flex; gap: 8px; flex-wrap: wrap; margin-left: auto; }
.pill {
display: flex; gap: 6px; align-items: baseline;
background: var(--chip); border: 1px solid var(--border);
border-radius: 999px; padding: calc(5px * var(--s)) calc(11px * var(--s));
font-size: calc(11.5px * var(--s)); color: var(--muted);
}
.pill b { font-size: calc(13.5px * var(--s)); font-weight: 500; font-variant-numeric: tabular-nums; }
#score b { color: var(--green); } #best b { color: var(--purple); }
#level b { color: var(--blue); } #combo b { color: var(--amber); }
#lives { display: flex; gap: 6px; align-items: center; }
#lives i { width: calc(9px * var(--s)); height: calc(9px * var(--s)); border-radius: 50%; background: var(--red); display: block; }
#lives i.off { background: var(--border); }
#fxbar { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; min-height: calc(24px * var(--s)); margin-bottom: 8px; }
#fxbar .lbl { font-size: calc(10.5px * var(--s)); color: var(--dim); }
.fx {
display: flex; align-items: center; gap: 7px; border-radius: 8px;
padding: calc(3.5px * var(--s)) calc(9px * var(--s)) calc(3.5px * var(--s)) calc(6px * var(--s));
font-size: calc(11px * var(--s)); color: var(--muted);
border: 1px solid var(--border-2); background: var(--chip);
animation: fxin .22s ease;
}
.fx .glyph {
width: calc(16px * var(--s)); height: calc(16px * var(--s)); border-radius: 5px;
display: grid; place-items:center;
font-size: calc(10px * var(--s)); font-weight: 700; color: #08111f; flex: none;
}
.fx.bad .glyph { color: #fff; }
.fx .bar { width: calc(42px * var(--s)); height: 3px; border-radius: 2px; background: var(--border); overflow: hidden; }
.fx .bar span { display: block; height: 100%; }
@keyframes fxin { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
#wrap {
position: relative; width: 100%; aspect-ratio: 680 / 470;
border-radius: 12px; overflow: hidden; background: #070b16;
cursor: none; touch-action: none; user-select: none;
border: 1px solid var(--border);
}
#cv { display: block; width: 100%; height: 100%; }
#msg {
position: absolute; inset: 0; display: flex; flex-direction: column;
align-items: center; justify-content: center; gap: 10px; text-align: center;
background: rgba(7,11,22,.62); pointer-events: none; transition: opacity .25s ease;
}
#msg.hidden { opacity: 0; }
#opts {
position: absolute; inset: 0; z-index: 5; display: flex; flex-direction: column;
align-items: center; justify-content: center; gap: 8px; cursor: default;
background: rgba(7,11,22,.9);
}
#opts.hidden { display: none; }
#opts .ttl { font-size: calc(20px * var(--s)); font-weight: 500; color: #fff; margin-bottom: 4px; }
#opts button.opt {
width: min(340px, 84%); display: flex; justify-content: space-between; align-items: center;
}
#opts button.opt b { color: var(--green); }
#opts button.opt.off b { color: var(--muted); }
#msg .big { font-size: calc(27px * var(--s)); font-weight: 500; color: #fff; letter-spacing: .02em; }
#msg .small { font-size: calc(12px * var(--s)); color: #a9b6cf; max-width: 72%; line-height: 1.5; }
#msg .accent { color: var(--green); }
#msg .stats { display: flex; flex-direction: column; align-items: center; gap: 5px; margin-top: 2px; }
#msg .strow { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 5px; max-width: 80%; }
#msg .strow .lbl { font-size: calc(10px * var(--s)); color: #fff; opacity: .75; letter-spacing: .08em; text-transform: uppercase; }
#msg .stk {
display: inline-flex; align-items: center; gap: 5px; padding: 2px 7px;
font-size: calc(10.5px * var(--s)); color: var(--muted);
border: 1px solid var(--border-2); border-radius: 7px; background: rgba(255,255,255,.04);
}
#msg .stk b { color: #fff; font-weight: 500; font-variant-numeric: tabular-nums; }
#msg .stk i {
width: 13px; height: 13px; border-radius: 4px; font-style: normal;
font-size: 9px; line-height: 13px; text-align: center; color: #fff;
}
#dims { font-variant-numeric: tabular-nums; color: var(--dim); }
#foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: calc(11.5px * var(--s)); color: var(--muted); flex-wrap: nowrap; }
#foot .info { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#actions { margin-left: auto; display: flex; gap: 8px; flex: none; white-space: nowrap; }
#dbg { display: flex; align-items: center; gap: 6px; flex: none; white-space: nowrap; }
#dbg.hidden { display: none; }
#dbg input {
width: 56px; font-family: var(--font); font-size: calc(11.5px * var(--s)); color: var(--text);
background: var(--chip); border: 1px solid var(--border-2); border-radius: 8px;
padding: calc(5px * var(--s)) calc(8px * var(--s));
}
#dbg input:focus { outline: none; border-color: var(--green); }
#dbg .var { font-size: calc(11px * var(--s)); color: var(--green); }
button {
font-family: var(--font); font-size: calc(11.5px * var(--s)); color: var(--text);
background: var(--chip); border: 1px solid var(--border-2);
border-radius: 8px; padding: calc(6px * var(--s)) calc(12px * var(--s));
cursor: pointer; transition: all .18s ease;
}
button:hover { background: #16203a; border-color: var(--green); }
button:active { transform: translateY(1px); }
#main { display: block; }
#side { margin-bottom: 8px; }
#rail { margin-top: 10px; }
body.cols #main { display: flex; align-items: flex-start; gap: 10px; }
body.cols #side { flex: none; width: calc(148px * var(--s)); margin: 0; max-height: var(--fieldH); overflow: hidden auto; }
body.cols #rail { flex: none; width: calc(238px * var(--s)); margin: 0; max-height: var(--fieldH); overflow: hidden auto; }
body.cols #strip { flex-direction: column; align-items: stretch; gap: calc(6px * var(--s)); margin-left: 0; }
body.cols .pill { border-radius: 10px; justify-content: space-between; }
body.cols #wrap { flex: 1 1 0; min-width: 0; width: auto; }
body.cols #pu-legend { grid-template-columns: 1fr; gap: calc(6px * var(--ls)); margin-top: calc(8px * var(--ls)); }
body.cols .card { padding: calc(7px * var(--ls)) calc(9px * var(--ls)); gap: calc(8px * var(--ls)); border-radius: calc(9px * var(--ls)); }
body.cols .card .n { font-size: calc(11.5px * var(--ls)); }
body.cols .card .d { font-size: calc(10px * var(--ls)); line-height: 1.3; }
body.cols .card .glyph { width: calc(18px * var(--ls)); height: calc(18px * var(--ls)); }
body.cols #fxbar { flex-direction: column; align-items: flex-start; gap: calc(6px * var(--s)); }
body.cols.tight .card .d { display: none; }
body.cols.tight .card { padding: calc(5px * var(--ls)) calc(8px * var(--ls)); }
#legend .ltitle { font-size: calc(12px * var(--s)); color: var(--muted); margin: 4px 0 6px; }
#pu-legend { display: grid; grid-template-columns: repeat(auto-fill, minmax(168px, 1fr)); gap: 8px; margin-top: 10px; }
.card {
display: flex; gap: 9px; align-items: center;
background: var(--chip); border: 1px solid var(--border);
border-radius: 10px; padding: 9px 11px;
}
.card .glyph {
width: calc(21px * var(--s)); height: calc(21px * var(--s)); border-radius: 6px;
display: grid; place-items: center;
font-size: calc(11px * var(--s)); font-weight: 700; color: #08111f; flex: none;
}
.card.bad .glyph { color: #fff; }
.card .n { font-size: calc(12px * var(--s)); font-weight: 500; }
.card .d { font-size: calc(11px * var(--s)); color: var(--dim); margin-top: 2px; }
/* sehr niedrige Fenster: Kopf/Links ausblenden, Spielfeld bekommt den Platz */
body.compact #sub, body.compact #foot, body.compact #rail { display: none; }
body.compact #fxbar { min-height: 22px; }
body.compact #head { margin-bottom: 6px; }
body.compact { padding-top: 6px; padding-bottom: 6px; }
</style>
</head>
<body>
<div id="panel">
<div id="head">
<div>
<div id="title">Breakout · Neon Clone</div>
<div id="sub">Maus klickt ins Spielfeld und wird dort gefangen · <kbd>ESC</kbd> gibt sie frei · Klick / Leertaste schießt · <kbd>P</kbd> pausiert · <kbd>R</kbd> Neustart</div>
</div>
</div>
<div id="main">
<aside id="side">
<div id="strip">
<span class="pill" id="score">Punkte <b>0</b></span>
<span class="pill" id="best">Bestwert <b>0</b></span>
<span class="pill" id="level">Level <b>1</b></span>
<span class="pill" id="combo">Combo <b>×1,0</b></span>
<span class="pill" id="cont">Continues <b>3</b></span>
<span class="pill" id="lives">Leben <span id="hearts"></span></span>
</div>
</aside>
<div id="wrap">
<canvas id="cv"></canvas>
<div id="msg">
<div class="big">Breakout</div>
<div class="small">Klick ins Spielfeld zum Starten. Zerstörte Steine lassen gelegentlich Power-ups fallen — <span class="accent">goldene, grüne und helle einsammeln, rote meiden.</span></div>
</div>
<div id="opts" class="hidden">
<div class="ttl">Optionen</div>
<button class="opt" id="optRound"><span>Rundes Paddle</span><b>AN</b></button>
<button class="opt" id="optAuto"><span>Auto-Feuer (Laser)</span><b>AN</b></button>
<button class="opt" id="optPU"><span>Power-ups</span><b>AN</b></button>
<button class="opt" id="optMusic"><span>Musik (Chip-Tune)</span><b>AN</b></button>
<button class="opt" id="optDebug"><span>Debug: Level-Wahl</span><b>OFF</b></button>
<button id="optClose">Schließen</button>
</div>
</div>
<aside id="rail">
<div id="fxbar"><span class="lbl">Aktive Power-ups</span></div>
<div id="legend">
<div class="ltitle">Power-ups &amp; Legende</div>
<div id="pu-legend"></div>
</div>
</aside>
</div>
<div id="foot">
<span class="info">Pfeiltasten links/rechts gehen auch · beim Power-up „Freies Paddle“ auch hoch/runter · <span id="laserhint">Laser feuert automatisch</span> · <span id="dims"></span></span>
<div id="dbg" class="hidden" title="Level wählen: Eingabe, - und + oder Tasten [ und ]">
<button id="dbgDown" title="Vorheriges Level">-</button>
<input id="dbgLvl" type="number" min="1" max="99" step="1" value="1">
<button id="dbgUp" title="Nächstes Level">+</button>
<span id="dbgVar" class="var">normal</span>
</div>
<div id="actions">
<button id="options">Optionen</button>
<button id="sound">Ton an</button>
<button id="restart">Neustart</button>
</div>
</div>
</div>
<script>
(function () {
var W = 680, H = 470;
var SIDE = 24, TOP = 58, GAP = 6, COLS = 12, BH = 22;
var PW = 112, PH = 14, PY = H - 34, PAD = 18, BR = 7;
var PY_TOP = 96; /* oberster Grenzwert für das frei bewegliche Paddle */
var ARC = 0.45; /* max. Neigung (rad) der Paddle-Bogenfläche */
var ARC_V = 4; /* sichtbare Wölbung des Paddles in px */
var wrap = document.getElementById('wrap');
var canvas = document.getElementById('cv');
var ctx = canvas.getContext('2d');
var msg = document.getElementById('msg');
var fxbar = document.getElementById('fxbar');
var elScore = document.querySelector('#score b');
var elBest = document.querySelector('#best b');
var elLevel = document.querySelector('#level b');
var elCombo = document.querySelector('#combo b');
var elCont = document.querySelector('#cont b');
var elHearts = document.getElementById('hearts');
var btnSound = document.getElementById('sound');
var btnRestart = document.getElementById('restart');
var btnOptions = document.getElementById('options');
var optsPanel = document.getElementById('opts');
var optRound = document.getElementById('optRound');
var optAuto = document.getElementById('optAuto');
var optPU = document.getElementById('optPU');
var optMusic = document.getElementById('optMusic');
var optDebug = document.getElementById('optDebug');
var optClose = document.getElementById('optClose');
var dbgBox = document.getElementById('dbg');
var dbgLvl = document.getElementById('dbgLvl');
var dbgUp = document.getElementById('dbgUp');
var dbgDown = document.getElementById('dbgDown');
var dbgVar = document.getElementById('dbgVar');
var laserHint = document.getElementById('laserhint');
var optionsOpen = false;
var PAL = [
['#534AB7', '#AFA9EC'], ['#185FA5', '#85B7EB'], ['#0F6E56', '#5DCAA5'],
['#854F0B', '#EF9F27'], ['#993C1D', '#F0997B'], ['#993556', '#ED93B1'],
['#3B6D11', '#97C459'], ['#A32D2D', '#F09595']
];
/* ---------------- power-ups ---------------- */
var PU = [
{ id:'expand', icon:'E', c:'#1D9E75', c2:'#5DCAA5', name:'Breites Paddle', desc:'12 s, +60 % Fläche', good:true, dur:12, w:16 },
{ id:'multi', icon:'M', c:'#378ADD', c2:'#85B7EB', name:'Dreifach-Ball', desc:'2 Extrabälle', good:true, dur:0, w:12 },
{ id:'laser', icon:'L', c:'#BA7517', c2:'#EF9F27', name:'Laser', desc:'8 s, auto-Feuer', good:true, dur:8, w:12 },
{ id:'slow', icon:'≈', c:'#7F77DD', c2:'#AFA9EC', name:'Zeitlupe', desc:'9 s, Ball langsamer', good:true, dur:9, w:12 },
{ id:'sticky', icon:'C', c:'#D4537E', c2:'#ED93B1', name:'Fangball', desc:'10 s, Ball haftet', good:true, dur:10, w:10 },
{ id:'drill', icon:'◆', c:'#0F6E56', c2:'#5DCAA5', name:'Durchschlag', desc:'6 s, Steine durchbohren', good:true, dur:6, w:8 },
{ id:'free', icon:'✥', c:'#1C7AA6', c2:'#79C7E5', name:'Freies Paddle', desc:'9 s, Paddle frei über das Feld', good:true, dur:9, w:8 },
{ id:'life', icon:'+', c:'#639922', c2:'#97C459', name:'+1 Leben', desc:'sofort', good:true, dur:0, w:5 },
{ id:'shrink', icon:'i', c:'#A32D2D', c2:'#F09595', name:'Schmales Paddle', desc:'8 s Malus', good:false, dur:8, w:10 },
{ id:'fast', icon:'»', c:'#993C1D', c2:'#F0997B', name:'Turbo', desc:'9 s Malus, Ball schneller', good:false, dur:9, w:9 }
];
var sx = 1, rectCache = null;
var bricks = [], particles = [], powerups = [], bullets = [], notes = [], balls = [];
var paddle = { x: W / 2 - PW / 2, vx: 0, prevX: W / 2 - PW / 2, y: PY, vy: 0, prevY: PY, w: PW, axis: 'h', dirIn: 0 };
var padR = { x: W - PAD - PH, prevX: W - PAD - PH, y: H / 2, prevY: H / 2, vx: 0, vy: 0, w: PW, axis: 'v', dirIn: 1 };
var pads = [paddle];
var PAD_TOP = 40, PAD_BOT = H - 32;
function padRect(p) {
return p.axis === 'v' ? { x: p.x, y: p.y, w: PH, h: p.w } : { x: p.x, y: p.y, w: p.w, h: PH };
}
function clampPadY(p) { p.y = clamp(p.y, PAD_TOP, PAD_BOT - p.w); }
function setupPads() {
if (variant === 'split') {
var len = clamp(PW * 1.2, 60, PAD_BOT - PAD_TOP - 20);
paddle.axis = 'v'; paddle.dirIn = -1; paddle.w = len;
paddle.x = PAD; paddle.prevX = PAD; paddle.vx = 0;
paddle.y = (PAD_TOP + PAD_BOT) / 2 - len / 2; paddle.prevY = paddle.y; paddle.vy = 0;
padR.axis = 'v'; padR.dirIn = 1; padR.w = len;
padR.x = W - PAD - PH; padR.prevX = padR.x; padR.vx = 0;
padR.y = paddle.y; padR.prevY = paddle.y; padR.vy = 0;
pads = [paddle, padR];
} else {
paddle.axis = 'h'; paddle.dirIn = 0; pads = [paddle];
paddle.x = clamp(W / 2 - paddle.w / 2, PAD, W - PAD - paddle.w);
paddle.prevX = paddle.x; paddle.vx = 0;
}
}
function attachPos(b) {
var p = b.pad || paddle;
if (p.axis === 'v') {
return { x: p.dirIn < 0 ? p.x + PH + b.r + 2 : p.x - b.r - 2,
y: clamp(p.y + p.w / 2 + b.off, PAD_TOP + b.r, PAD_BOT - b.r) };
}
return { x: p.x + p.w / 2 + b.off, y: p.y - b.r - 2 };
}
function syncAttach(b) { var q = attachPos(b); b.x = q.x; b.y = q.y; }
var keys = { left: false, right: false, up: false, down: false };
var fx = { expand: 0, shrink: 0, slow: 0, fast: 0, laser: 0, sticky: 0, drill: 0, free: 0 };
var laserCd = 0;
var state = 'ready', score = 0, best = 0, level = 1, lives = 3;
var combo = 0, comboT = 0, shake = 0, shakeX = 0, shakeY = 0, levelTimer = 0;
var CHECKPOINT_EVERY = 5, MAX_CONTINUES = 3, CONTINUE_TIME = 10, START_LIVES = 3;
var continues = MAX_CONTINUES, checkpoint = 1, continueT = 0, ccUsed = 0, contTick = 0;
var stats = { blk: {}, down: 0, hits: 0, pu: {} };
function resetStats() { stats = { blk: {}, down: 0, hits: 0, pu: {} }; }
var sound = true, ac = null, fxSig = '';
var scores = [];
try { scores = JSON.parse(localStorage.getItem('breakout.scores') || '[]'); } catch (e) { scores = []; }
try { var oldBest = Number(localStorage.getItem('breakout.best')) || 0; if (oldBest > 0) scores.push(oldBest); } catch (e) {}
scores = scores.filter(function (v) { return typeof v === 'number' && isFinite(v) && v > 0; });
scores.sort(function (a, b) { return b - a; });
scores = scores.slice(0, 5);
best = scores[0] || 0;
var scoreCC = {};
try { scoreCC = JSON.parse(localStorage.getItem('breakout.scoreCC') || '{}') || {}; } catch (e) { scoreCC = {}; }
function ccMark(v) { return scoreCC[String(v)] > 0 ? ' (' + scoreCC[String(v)] + ' CC)' : ''; }
function top5Html() {
if (!scores.length) return 'Noch keine Ergebnisse';
return scores.map(function (v, i) { return (i + 1) + '. ' + v.toLocaleString('de-DE') + ccMark(v); }).join(' · ');
}
function statsHtml() {
var hps = Object.keys(stats.blk).map(Number).sort(function (a, b) { return a - b; });
var chips = hps.map(function (k) { return '<span class="stk">' + k + '×-Block <b>' + stats.blk[k] + '</b></span>'; });
if (!chips.length) chips.push('<span class="stk">keine Blöcke zerstört</span>');
chips.push('<span class="stk tot">zerstört <b>' + stats.down + '</b></span>');
chips.push('<span class="stk tot">Treffer <b>' + stats.hits + '</b></span>');
var pc = [];
PU.forEach(function (p) {
if (!stats.pu[p.id]) return;
pc.push('<span class="stk" style="border-color:' + p.c2 + '"><i style="background:' + p.c + '">' + p.icon + '</i>' +
p.name + ' <b>' + stats.pu[p.id] + '</b></span>');
});
if (!pc.length) pc.push('<span class="stk">keine Power-ups</span>');
return '<div class="stats">' +
'<div class="strow"><span class="lbl">Blöcke</span>' + chips.join('') + '</div>' +
'<div class="strow"><span class="lbl">Power-ups</span>' + pc.join('') + '</div></div>';
}
var opts = { round: true, autoFire: true, pu: true, debug: false, music: true };
try {
var ov = JSON.parse(localStorage.getItem('breakout.options') || 'null');
if (ov && typeof ov === 'object') {
opts.round = ov.round !== false;
opts.autoFire = ov.autoFire !== false;
opts.pu = ov.pu !== false;
opts.debug = ov.debug === true;
opts.music = ov.music !== false;
}
} catch (e) {}
function saveOpts() { try { localStorage.setItem('breakout.options', JSON.stringify(opts)); } catch (e) {} }
function legend() {
var html = '';
PU.forEach(function (p) {
html += '<div class="card' + (p.good ? '' : ' bad') + '">'
+ '<div class="glyph" style="background:' + (p.good ? p.c2 : p.c) + '">' + p.icon + '</div>'
+ '<div><div class="n">' + p.name + (p.good ? '' : ' · Malus') + '</div>'
+ '<div class="d">' + (p.id === 'laser' && !opts.autoFire ? '8 s, Feuer per Klick/Leertaste' : p.desc) + '</div></div></div>';
});
document.getElementById('pu-legend').innerHTML = html;
}
/* ---------------- sound ---------------- */
function audioBus() {
if (!ac) ac = new (window.AudioContext || window.webkitAudioContext)();
if (!sfxGain) { sfxGain = ac.createGain(); sfxGain.gain.value = 0.9; sfxGain.connect(ac.destination); }
if (!musGain) { musGain = ac.createGain(); musGain.gain.value = 0; musGain.connect(ac.destination); }
if (!noiseBuf) {
noiseBuf = ac.createBuffer(1, Math.max(1, Math.floor(ac.sampleRate * 0.4)), ac.sampleRate);
var d = noiseBuf.getChannelData(0);
for (var i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
}
if (ac.state === 'suspended') ac.resume();
return ac;
}
function beep(freq, dur, type, gain) {
if (!sound) return;
try {
audioBus();
if (ac.state === 'suspended') ac.resume();
var o = ac.createOscillator(), g = ac.createGain();
o.type = type || 'square'; o.frequency.value = freq;
o.connect(g); g.connect(sfxGain || ac.destination);
var t = ac.currentTime, v = gain || 0.05, d = dur || 0.07;
g.gain.setValueAtTime(v, t);
g.gain.exponentialRampToValueAtTime(0.0001, t + d);
o.start(t); o.stop(t + d + 0.02);
} catch (e) {}
}
/* ---------------- musik: eigene Komposition im Chip-Tune-Stil ---------------- */
var BPM_LEVEL = 148, BPM_CALM = 96, MUS_STEPS = 128;
var ARP_L = [0, 7, 12, 7], BASS_L = [38, 41, 36, 38]; /* Dm - F - C - Dm */
var MEL_A = [[0,62,2],[2,65,2],[4,69,2],[6,74,2],[8,69,4],[12,67,4],
[16,65,2],[18,69,2],[20,72,2],[22,69,2],[24,65,8],
[32,60,2],[34,67,2],[36,72,2],[38,67,2],[40,60,4],[44,62,4],
[48,62,2],[50,65,2],[52,69,2],[54,74,2],[56,77,4],[60,74,4]];
var MEL_B = [[0,74,2],[2,72,2],[4,69,2],[6,65,2],[8,62,8],
[16,57,2],[18,65,2],[20,69,2],[22,74,2],[24,72,8],
[32,65,4],[36,69,4],[40,74,8],
[48,62,2],[50,69,2],[52,74,2],[54,69,2],[56,62,8]];
var ARP_C = [0, 7, 12], BASS_C = [45, 41, 36, 43]; /* Am - F - C - G */
var MEL_CALM = [[0,69,8],[8,72,8],[16,76,8],[24,72,8],[32,65,8],[40,60,8],[48,67,8],[56,69,8]];
var musTrack = 'none', musStep = 0, musAt = 0;
var sfxGain = null, musGain = null, noiseBuf = null;
function midiHz(m) { return 440 * Math.pow(2, (m - 69) / 12); }
function tone(t, midi, type, dur, gain, detune, bus) {
var out = bus || musGain;
var o = ac.createOscillator(), g = ac.createGain();
o.type = type; o.frequency.value = midiHz(midi);
g.gain.setValueAtTime(0.0001, t);
g.gain.linearRampToValueAtTime(gain, t + 0.008);
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
o.connect(g); g.connect(out);
o.start(t); o.stop(t + dur + 0.02);
if (detune) { /* zweite Stimme für Druck */
var o2 = ac.createOscillator(), g2 = ac.createGain();
o2.type = type; o2.frequency.value = midiHz(midi); o2.detune.value = -detune;
g2.gain.setValueAtTime(0.0001, t);
g2.gain.linearRampToValueAtTime(gain * 0.65, t + 0.012);
g2.gain.exponentialRampToValueAtTime(0.0001, t + dur);
o2.connect(g2); g2.connect(out); o2.start(t); o2.stop(t + dur + 0.02);
}
}
function hat(t, gain) {
var s = ac.createBufferSource(); s.buffer = noiseBuf;
var f = ac.createBiquadFilter(); f.type = 'highpass'; f.frequency.value = 7000;
var g = ac.createGain();
g.gain.setValueAtTime(gain, t); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.05);
s.connect(f); f.connect(g); g.connect(musGain);
s.start(t); s.stop(t + 0.06);
}
function playStep(tr, s, t, sd) {
var bar = Math.floor(s / 16) % 4;
if (tr === 'level') {
tone(t, BASS_L[bar] + ARP_L[s % 4], 'square', sd * 0.9, 0.10);
if (s % 2 === 0) hat(t, s % 8 === 0 ? 0.09 : 0.045);
var mel = s < 64 ? MEL_A : MEL_B, off = s % 64;
for (var i = 0; i < mel.length; i++) if (mel[i][0] === off) tone(t, mel[i][1], 'square', mel[i][2] * sd * 0.85, 0.062, 8);
} else {
if (s % 2 === 0) tone(t, BASS_C[bar] + ARP_C[(s / 2) % 3], 'triangle', sd * 1.7, 0.085);
var mc = MEL_CALM, ofc = s % 64;
for (var j = 0; j < mc.length; j++) if (mc[j][0] === ofc) tone(t, mc[j][1], 'triangle', mc[j][2] * sd * 1.5, 0.05, 6);
if (s % 8 === 0) hat(t, 0.022);
}
}
function trackForState() {
if (!sound || !opts.music) return 'none';
if (state === 'playing') return 'level';
if (state === 'over') return 'none';
return 'calm';
}
function musGainTo(v, inSec) {
if (!musGain || !ac) return;
var t = ac.currentTime;
musGain.gain.cancelScheduledValues(t);
musGain.gain.setValueAtTime(musGain.gain.value, t);
musGain.gain.linearRampToValueAtTime(v, t + inSec);
}
function setTrack(tr) {
if (tr === musTrack) return;
musTrack = tr; musStep = 0;
musGainTo(tr === 'level' ? 0.16 : (tr === 'calm' ? 0.115 : 0), 0.3);
if (ac) musAt = ac.currentTime + 0.06;
}
function musicTick() {
if (!ac || !musGain) return;
var want = trackForState();
if (want !== musTrack) setTrack(want);
if (musTrack === 'none') return;
var sd = 60 / (musTrack === 'level' ? BPM_LEVEL : BPM_CALM) / 4;
if (musAt < ac.currentTime) musAt = ac.currentTime + 0.02;
for (var guard = 0; musAt < ac.currentTime + 0.35 && guard < 64; guard++) {
playStep(musTrack, musStep, musAt, sd);
musStep = (musStep + 1) % MUS_STEPS;
musAt += sd;
}
}
function playCadence() {
if (!ac || !sound || !opts.music) return;
var cg = ac.createGain(); cg.gain.value = 0.15; cg.connect(ac.destination);
var t = ac.currentTime + 0.06, sd = 0.25;
[74, 72, 69, 65].forEach(function (n, i) { tone(t + i * sd, n, 'square', sd * 1.3, 0.075, 8, cg); });
tone(t + 4 * sd, 62, 'square', sd * 3, 0.08, 8, cg);
tone(t, 38, 'triangle', sd * 5, 0.12, 0, cg);
tone(t + 4 * sd, 31, 'square', sd * 6, 0.09, 8, cg);
cg.gain.setValueAtTime(0.15, t + 2.2);
cg.gain.linearRampToValueAtTime(0.0001, t + 3.2);
}
/* ---------------- helpers ---------------- */
var rootEl = document.documentElement;
var headEl = document.getElementById('head');
var footEl = document.getElementById('foot');
var sideEl = document.getElementById('side');
var railEl = document.getElementById('rail');
var bodyCols = false;
var dimsEl = document.getElementById('dims');
var ASPECT = W / H; /* 680 / 470 */
function num(v) { var n = parseFloat(v); return isNaN(n) ? 0 : n; }
function padPair(el, a, b) {
var cs = getComputedStyle(el);
return num(cs[a]) + num(cs[b]);
}
function viewportH() {
var vv = window.visualViewport;
if (vv && vv.height) return vv.height;
return document.documentElement.clientHeight || window.innerHeight || 600;
}
/* chrome-Höhe: Spaltenmodus nur Kopf+Fuß, sonst plus Seiten- und Legendenblock */
function chromeH() {
var h = headEl.offsetHeight + footEl.offsetHeight;
if (!bodyCols) h += sideEl.offsetHeight + railEl.offsetHeight;
return h;
}
function measurePads() {
var bodyPadY = padPair(document.body, 'paddingTop', 'paddingBottom');
var bodyPadX = padPair(document.body, 'paddingLeft', 'paddingRight');
var panelPadY = padPair(document.getElementById('panel'), 'paddingTop', 'paddingBottom');
var panelPadX = padPair(document.getElementById('panel'), 'paddingLeft', 'paddingRight');
return { padY: bodyPadY + panelPadY, padX: bodyPadX + panelPadX };
}
/* Canvas intern an CSS-Größe + devicePixelRatio koppeln. Abgesichert: sx darf
nie 0 oder NaN werden (sonst malt drawBg() nichts -> blankes Feld). */
var lastFieldW = 720;
function resize() {
var dpr = Math.min(2, window.devicePixelRatio || 1);
var cw = wrap.clientWidth;
if (!isFinite(cw) || cw < 200) cw = lastFieldW; /* Fallback auf bekannten Wert */
cw = Math.max(220, cw);
lastFieldW = cw;
var ch = Math.round(cw / ASPECT);
canvas.style.height = ch + 'px';
canvas.width = Math.max(220, Math.round(cw * dpr));
canvas.height = Math.max(160, Math.round(ch * dpr));
sx = canvas.width / W;
if (!isFinite(sx) || sx <= 0) sx = 1;
rectCache = null;
return { w: cw, h: ch };
}
/* resize() leert das Canvas: sofort neu zeichnen, damit das Spielfeld nach
Layout-Anpassungen nie blank stehen bleibt. */
var drawReady = false;
function redraw() { if (drawReady) draw(); }
/* Viewport-Breite UND -Höhe gemeinsam auflösen und UI proportional einpassen.
Löst die Kopplung (Skala -> chrome-Höhe -> Feldbreite) iterativ, damit das
Panel nie über den Viewport ragt. */
var S_MIN = 0.8, S_MAX = 1.34;
/* Einmal neutral (Panel volle Breite, s=1) die festen Abstände messen.
Danach wird die Feldgröße NUR rechnerisch bestimmt – ohne clientWidth nach
dem Setzen von --pw zurückzulesen (das war die instabile Rückkopplung). */
function measureChromeBase() {
rootEl.style.setProperty('--pw', '100%');
rootEl.style.setProperty('--s', '1');
var vv = window.visualViewport;
var vw = (vv && vv.width) ? vv.width
: (document.documentElement.clientWidth || window.innerWidth || 720);
var panelFull = document.getElementById('panel').getBoundingClientRect().width;
if (!isFinite(panelFull) || panelFull < 240) panelFull = vw;
var sideW1 = bodyCols ? (sideEl.offsetWidth + railEl.offsetWidth + 20) : 0;
var content1 = wrap.clientWidth + sideW1;
var bodyPadY = padPair(document.body, 'paddingTop', 'paddingBottom');
var panelPadY = padPair(document.getElementById('panel'), 'paddingTop', 'paddingBottom');
return { vw: vw, panelFull: panelFull, sideW1: sideW1,
extra: Math.max(8, panelFull - content1),
chrome1: chromeH(), padY: bodyPadY + panelPadY };
}
function fitField(base) {
/* chrome skaliert ungefähr mit s; löse fieldW = (availH - chrome(s)) * ASPECT.
Im Spaltenmodus kosten die Seiten zusätzlich Breite (sideW1 * s). */
var s = 1, fieldW = 0, pw = 0;
for (var it = 0; it < 14; it++) {
var chromeAtS = base.chrome1 * s;
var availH = base.vw ? (viewportH() - base.padY - chromeAtS) : 470;
var byH = Math.max(240, availH) * ASPECT;
var byW = Math.max(240, base.panelFull - base.extra - base.sideW1 * s);
fieldW = Math.min(byW, byH);
s = clamp(fieldW / 720, S_MIN, S_MAX);
pw = Math.min(base.panelFull, fieldW + base.extra + base.sideW1 * s);
/* Stabilitätskriterium: geänderte Skala ->chrome ändert -> erneut */
if (it > 0 && Math.abs(pw - lastPw) < 1) { rootEl.style.setProperty('--pw', pw.toFixed(1) + 'px'); break; }
lastPw = pw;
rootEl.style.setProperty('--pw', pw.toFixed(1) + 'px');
rootEl.style.setProperty('--s', s.toFixed(3));
}
/* letzte sichere Anwendung, falls Loop divergiert */
var pwf = Math.min(base.panelFull, fieldW + base.extra + base.sideW1 * s);
rootEl.style.setProperty('--pw', pwf.toFixed(1) + 'px');
rootEl.style.setProperty('--s', s.toFixed(3));
return { s: s, pw: pwf };
}
var lastPw = 0;
function layout() {
var vh = viewportH();
/* Niedrige Fenster: kompakt (Legende/Sides unten ausgeblendet) */
document.body.classList.toggle('compact', vh < 600);
S_MAX = document.body.classList.contains('compact') ? 1.18 : 1.34;
/* Breites Fenster: Statuswerte links, Power-ups rechts als Spalten */
var vw = document.documentElement.clientWidth || window.innerWidth || 720;
bodyCols = vw >= 940 && vh >= 600;
document.body.classList.toggle('cols', bodyCols);
document.body.classList.remove('tight');
rootEl.style.setProperty('--ls', '1');
var base = measureChromeBase();
var fit = fitField(base);
var s = fit.s;
/* Seitenhöhen analytisch an die Feldhöhe anpassen (Legende skaliert mit --ls).
Leicht konservativ rechnen, damit das Nachmessen nicht nachjustieren muss. */
if (bodyCols) {
var natural = Math.max(railEl.scrollHeight, sideEl.scrollHeight, 1);
var wrapH0 = wrap.clientHeight || 1;
var ls = clamp(0.97 * wrapH0 / natural, 0.6, 1);
rootEl.style.setProperty('--ls', ls.toFixed(3));
if (natural * Math.max(0.6, ls) > wrapH0 + 6) document.body.classList.add('tight');
}
/* Nur resize(), wenn sich tatsächlich etwas geändert hat: jedes resize()
leert das Canvas – wiederholtes Layout ohne Änderung ließ das Feld leer. */
var sig = bodyCols + '|' + fit.pw.toFixed(1) + '|' + s.toFixed(3) + '|' +
rootEl.style.getPropertyValue('--ls') + '|' + document.body.classList.contains('tight');
if (sig === lastLayoutSig) {
rootEl.style.setProperty('--fieldH', Math.max(120, wrap.clientHeight || 1) + 'px');
return;
}
lastLayoutSig = sig;
var dim = resize();
redraw();
if (dimsEl) dimsEl.textContent = dim.w + ' × ' + dim.h + ' px';
/* Nachprüfung: Seitenhöhen dürfen das Spielfeld nicht überragen; die
Feldhöhe ist harte Obergrenze (--fieldH), chrome1 wird nicht verbogen. */
for (var guard = 0; guard < 2; guard++) {
var wrapH = wrap.clientHeight || 1;
rootEl.style.setProperty('--fieldH', Math.max(120, wrapH) + 'px');
var over = bodyCols ? Math.max(railEl.scrollHeight, sideEl.scrollHeight) - wrapH : 0;
if (over <= 2) break;
if (bodyCols) {
rootEl.style.setProperty('--ls', clamp((parseFloat(rootEl.style.getPropertyValue('--ls')) || 1) * 0.9, 0.6, 1).toFixed(3));
document.body.classList.add('tight');
} else {
base.chrome1 = Math.max(40, chromeH());
fit = fitField(base);
s = fit.s;
}
dim = resize();
redraw();
if (dimsEl) dimsEl.textContent = dim.w + ' × ' + dim.h + ' px';
}
}
var lastLayoutSig = '';
var layoutQueued = false;
function requestLayout() {
if (layoutQueued) return;
layoutQueued = true;
requestAnimationFrame(function () {
layoutQueued = false;
layout();
});
}
function clamp(v, a, b) { return v < a ? a : (v > b ? b : v); }
function rr(x, y, w, h, r) {
r = Math.min(r, w / 2, h / 2); ctx.beginPath();
if (ctx.roundRect) { ctx.roundRect(x, y, w, h, r); return; }
ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r); ctx.closePath();
}
function note(text, color) {
notes.push({ t: 2.0, text: text, color: color });
if (notes.length > 3) notes.shift();
}
/* ---------------- level ---------------- */
var VARIANTS = ['pyramid', 'upside', 'fort', 'split'];
var VSHORT = { pyramid: 'Pyramide', upside: 'Kopf', fort: 'Festung', split: 'Paddel' };
var VTITLE = { pyramid: 'Pyramide', upside: 'Überkopf', fort: 'Festung', split: 'Zwei Paddel' };
var VINFO = {
pyramid: 'Spezial-Level Pyramide: schmale Spitze oben, breite Basis',
upside: 'Spezial-Level Überkopf: Steine unten, Paddle oben',
fort: 'Spezial-Level Festung: harter Rahmen, weicher Kern',
split: 'Spezial-Level Zwei Paddel: Steine in der Mitte, Paddle links und rechts'
};
var FRAMEPAL = ['#33415C', '#9FB3C8'];
var variant = 'normal', flip = false;
function variantOf(l) { return l % 4 === 0 ? VARIANTS[((l / 4 - 1) % VARIANTS.length)] : 'normal'; }
function rowHp(r, rows) { return 1 + Math.floor((rows - 1 - r) / 2); }
function addBrick(x, y, w, h, hp, col) {
bricks.push({ x: x, y: y, w: w, h: h, hp: hp, max: hp, c: col[0], c2: col[1], flash: 0 });
}
function buildNormal(rows, bw) {
for (var r = 0; r < rows; r++) {
var hp = rowHp(r, rows), col = PAL[r % PAL.length];
for (var c = 0; c < COLS; c++) {
if (level > 1 && r > 0 && r < rows - 1 && Math.random() < 0.12) continue;
addBrick(SIDE + c * (bw + GAP), TOP + r * (BH + GAP), bw, BH, hp, col);
}
}
}
function buildPyramid(rows, bw) {
for (var r = 0; r < rows; r++) {
var half = (r + 1) * COLS / (2 * rows);
var hp = rowHp(r, rows), col = PAL[r % PAL.length];
for (var c = 0; c < COLS; c++) {
if (Math.abs(c - (COLS - 1) / 2) > half) continue;
addBrick(SIDE + c * (bw + GAP), TOP + r * (BH + GAP), bw, BH, hp, col);
}
}
}
function buildFort(rows, bw) {
var hard = 2 + Math.floor(rows / 4);
for (var r = 0; r < rows; r++) {
for (var c = 0; c < COLS; c++) {
var edge = (r === 0 || r === rows - 1 || c === 0 || c === COLS - 1);
if (edge) addBrick(SIDE + c * (bw + GAP), TOP + r * (BH + GAP), bw, BH, hard, FRAMEPAL);
else {
if (Math.random() < 0.22) continue;
addBrick(SIDE + c * (bw + GAP), TOP + r * (BH + GAP), bw, BH, 1, PAL[(r + 2) % PAL.length]);
}
}
}
}
function buildSplit(rows, bw) {
var sr = Math.min(3 + Math.floor(level / 6), 5);
var sc = 8, cw = W * 0.58;
var bw2 = (cw - (sc - 1) * GAP) / sc;
var x0 = (W - cw) / 2;
var y0 = Math.round((H - (sr * (BH + GAP) - GAP)) / 2);
for (var r = 0; r < sr; r++) {
var hp = rowHp(r, sr), col = PAL[(r + 2) % PAL.length];
for (var c = 0; c < sc; c++) {
if (level > 4 && Math.random() < 0.1) continue;
addBrick(x0 + c * (bw2 + GAP), y0 + r * (BH + GAP), bw2, BH, hp, col);
}
}
}
function buildLevel() {
variant = variantOf(level);
flip = (variant === 'upside');
var rows = Math.min(4 + level, 8);
var bw = (W - 2 * SIDE - (COLS - 1) * GAP) / COLS;
bricks = [];
if (variant === 'pyramid') buildPyramid(rows, bw);
else if (variant === 'fort') buildFort(rows, bw);
else if (variant === 'split') buildSplit(rows, bw);
else buildNormal(rows, bw);
setupPads();
}
function baseSpeed() { return 320 + (level - 1) * 26; }
function makeBall(x, y, vx, vy) {
return { x: x, y: y, vx: vx, vy: vy, r: BR, speed: baseSpeed(), trail: [], attached: false, at: 0, off: 0, pad: paddle };
}
function resetBall() {
var p = pads[0];
if (p.axis === 'h') { paddle.y = PY; paddle.prevY = PY; paddle.vy = 0; }
var b0 = makeBall(p.x + p.w / 2, p.y - BR - 2, 0, 0);
b0.attached = true; b0.at = 0; b0.pad = p; b0.off = (Math.random() * 0.5 - 0.25) * p.w;
syncAttach(b0);
balls = [ b0 ];
combo = 0; comboT = 0;
bullets = []; powerups = []; laserCd = 0;
state = 'ready';
showMsg('Level ' + level + (variant === 'normal' ? '' : ' · ' + VTITLE[variant]),
(variant === 'normal' ? '' : VINFO[variant] + ' · ') + (lives > 0 ? 'Klicken zum Starten' : 'Klicken für Neustart'));
}
function showMsg(t, s, extra) {
msg.innerHTML = '<div class="big">' + t + '</div><div class="small">' + s + '</div>' + (extra || '');
msg.classList.remove('hidden');
}
function hideMsg() { msg.classList.add('hidden'); }
function launchBall(b) {
var p = b.pad || paddle;
var a = (b.attached ? clamp(b.off / (p.w / 2), -1, 1) * 0.6 : Math.random() * 0.7 - 0.35);
if (p.axis === 'v') { b.vx = -p.dirIn * Math.cos(a) * b.speed; b.vy = Math.sin(a) * b.speed; }
else { b.vx = Math.sin(a) * b.speed; b.vy = -Math.cos(a) * b.speed; }
b.attached = false; b.at = 0;
}
function launchAll() {
for (var i = 0; i < balls.length; i++) launchBall(balls[i]);
state = 'playing'; hideMsg(); beep(420, 0.08, 'triangle', 0.06);
}
function startOrRestart() { if (lives > 0) launchAll(); else newGame(); }
function newGame() {
score = 0; level = 1; lives = START_LIVES; particles = [];
continues = MAX_CONTINUES; checkpoint = 1; continueT = 0; ccUsed = 0;
resetStats();
for (var k in fx) fx[k] = 0;
applyPaddle();
buildLevel(); resetBall(); hud(); hudFx(true);
}
/* ---------------- power-up logic ---------------- */
function dropPowerup(bx, by) {
if (!opts.pu) return;
if (Math.random() > 0.24) return;
var splitLv = (variant === 'split');
var pool = PU.filter(function (p) { return !splitLv || (p.id !== 'free' && p.id !== 'laser'); });
var total = 0; pool.forEach(function (p) { total += p.w; });
var roll = Math.random() * total, acc = 0, pick = pool[0];
for (var i = 0; i < pool.length; i++) { acc += pool[i].w; if (roll <= acc) { pick = pool[i]; break; } }
powerups.push({ x: bx, y: by, vy: splitLv ? 0 : 130 + level * 10,
vx: splitLv ? (bx < W / 2 ? -70 : 70) : 0, t: 0, p: pick });
}
function applyPaddle() {
var w = PW;
if (fx.expand > 0) w *= 1.6;
if (fx.shrink > 0) w *= 0.62;
if (variant === 'split') w = clamp(PW * 1.2, 60, PAD_BOT - PAD_TOP - 20) * (w / PW);
paddle.w = w;
for (var i = 1; i < pads.length; i++) { pads[i].w = w; clampPadY(pads[i]); }
if (variant === 'split') clampPadY(paddle);
}
function grab(p, x, y) {
stats.pu[p.id] = (stats.pu[p.id] || 0) + 1;
if (p.id === 'multi') {
var src = balls[0];
for (var i = 0; i < 2; i++) {
var a = (i === 0 ? -0.45 : 0.45);
var nb = makeBall(x, y - 14, Math.sin(a) * src.speed, -Math.cos(a) * src.speed);
balls.push(nb);
}
if (balls.length > 6) balls.length = 6;
} else if (p.id === 'life') {
lives = Math.min(5, lives + 1);
} else {
fx[p.id] = p.dur;
applyPaddle();
}
notes.length = 0;
note((p.good ? '★ ' : '⚠ ') + p.name, p.c2);
for (var j = 0; j < 12; j++) {
var a2 = Math.random() * Math.PI * 2, s = 40 + Math.random() * 160;
particles.push({ x: x, y: y, vx: Math.cos(a2) * s, vy: Math.sin(a2) * s - 30,
life: 0.5, max: 0.5, size: 2 + Math.random() * 3, col: p.c2 });
}
if (p.good) { beep(660, 0.10, 'triangle', 0.07); setTimeout(function () { beep(990, 0.12, 'triangle', 0.06); }, 90); }
else beep(160, 0.22, 'sawtooth', 0.06);
hudFx(true);
}
function tickEffects(dt) {
var changed = false;
for (var k in fx) {
if (fx[k] > 0) {
fx[k] -= dt;
if (fx[k] <= 0) {
fx[k] = 0; changed = true;
if (k === 'expand' || k === 'shrink') applyPaddle();
}
}
}
if (changed) hudFx(true);
}
function speedFactor() {
var f = 1;
if (fx.slow > 0) f *= 0.72;
if (fx.fast > 0) f *= 1.3;
return f;
}
function fireVolley() {
if (fx.laser <= 0) return false;
bullets.push({ x: paddle.x + 7, y: paddle.y - 2 });
bullets.push({ x: paddle.x + paddle.w - 7, y: paddle.y - 2 });
beep(1100, 0.05, 'square', 0.035);
return true;
}
function burst(b, color) {
for (var i = 0; i < 16; i++) {
var a = Math.random() * Math.PI * 2, s = 40 + Math.random() * 210;
particles.push({ x: b.x + b.w / 2, y: b.y + b.h / 2, vx: Math.cos(a) * s, vy: Math.sin(a) * s - 40,
life: 0.45 + Math.random() * 0.4, max: 0.85, size: 2 + Math.random() * 4, col: color });
}
}
/* ---------------- scoring ---------------- */
function hitBrick(b) {
b.hp--; b.flash = 1;
stats.hits++;
if (b.hp <= 0) {
stats.down++;
stats.blk[b.max] = (stats.blk[b.max] || 0) + 1;
burst(b, b.c2); shake = Math.min(9, shake + 4);
beep(210 + Math.min(combo, 12) * 42 + b.max * 18, 0.09, 'square', 0.05);
dropPowerup(b.x + b.w / 2, b.y + b.h / 2);
} else beep(240, 0.04, 'sine', 0.04);
var mult = 1 + Math.min(combo, 8) * 0.5;
score += Math.round((25 + b.max * 25) * level * mult / 5) * 5;
combo++; comboT = 1.6;
hud();
}
/* ---------------- collisions ---------------- */
function collideBricks(b) {
for (var i = 0; i < bricks.length; i++) {
var br = bricks[i]; if (br.hp <= 0) continue;
var cx = clamp(b.x, br.x, br.x + br.w), cy = clamp(b.y, br.y, br.y + br.h);
var dx = b.x - cx, dy = b.y - cy;
if (dx * dx + dy * dy > b.r * b.r) continue;
hitBrick(br);
if (fx.drill > 0) return true;
var len = Math.sqrt(dx * dx + dy * dy), nx, ny;
if (len < 0.0001) {
var ox = Math.min(b.x - br.x, br.x + br.w - b.x), oy = Math.min(b.y - br.y, br.y + br.h - b.y);
if (ox < oy) { nx = (b.x < br.x + br.w / 2) ? -1 : 1; ny = 0; }
else { nx = 0; ny = (b.y < br.y + br.h / 2) ? -1 : 1; }
} else { nx = dx / len; ny = dy / len; }
var dot = b.vx * nx + b.vy * ny;
if (dot < 0) { b.vx -= 2 * dot * nx; b.vy -= 2 * dot * ny; }
b.x = cx + nx * (b.r + 0.6); b.y = cy + ny * (b.r + 0.6);
if (Math.abs(b.vy) < b.speed * 0.22) b.vy = (b.vy < 0 ? -1 : 1) * b.speed * 0.22;
return true;
}
return false;
}
function collidePaddle(b, pad) {
pad = pad || paddle;
var vert = pad.axis === 'v';
var rw = vert ? PH : pad.w, rh = vert ? pad.w : PH;
/* nur Bälle, die aufs Paddle zulaufen, werden abgefangen */
if (!b.attached) {
if (!vert && b.vy <= 0 && fx.free <= 0) return false;
if (vert && b.vx * pad.dirIn <= 0) return false;
}
var cx = clamp(b.x, pad.x, pad.x + rw), cy = clamp(b.y, pad.y, pad.y + rh);
var dx = b.x - cx, dy = b.y - cy;
if (dx * dx + dy * dy > b.r * b.r) return false;
var half = pad.w / 2;
var off = clamp((vert ? b.y - (pad.y + half) : b.x - (pad.x + half)) / half, -1, 1);
b.pad = pad.src || pad;
if (fx.sticky > 0) {
b.attached = true; b.at = 0; b.off = off * (half - 6);
b.vx = 0; b.vy = 0; combo = 0; hud();
beep(200, 0.05, 'sine', 0.05);
return true;
}
/* Ruck des Paddels: begrenzt, damit ein Maussprung dem Ball keinen Wahnsinnsspeed gibt */
var pvx = clamp(pad.vx, -820, 820), pvy = clamp(pad.vy, -820, 820);
/* Abprall: von der Schlagseite weg */
var dir = vert ? -pad.dirIn : (b.y <= pad.y + PH / 2 ? -1 : 1);
b.speed = Math.max(baseSpeed(), Math.min(b.speed + 6, baseSpeed() + 190));
if (opts.round) {
var tilt = off * ARC, nx, ny;
if (vert) { nx = dir * Math.cos(tilt); ny = Math.sin(tilt); }
else { nx = Math.sin(tilt); ny = dir * Math.cos(tilt); }
var dot = b.vx * nx + b.vy * ny;
if (dot < 0) { b.vx -= 2 * dot * nx; b.vy -= 2 * dot * ny; }
if (vert) { if (b.vx * dir < 0) b.vx = -b.vx; } else if (b.vy * dir < 0) b.vy = -b.vy;
} else {
var ang = off * 1.02;
if (vert) { b.vy = Math.sin(ang) * b.speed + pvy * 0.22; b.vx = dir * Math.cos(ang) * b.speed; }
else { b.vx = Math.sin(ang) * b.speed + pvx * 0.22; b.vy = dir * Math.cos(ang) * b.speed; }
}
var m = Math.sqrt(b.vx * b.vx + b.vy * b.vy) || 1;
b.vx *= b.speed / m; b.vy *= b.speed / m;
if (vert) { b.vy += pvy * 0.22; b.vx += pvx * 0.16; }
else { b.vx += pvx * 0.22; b.vy += pvy * 0.16; }
if (vert) {
if (dir < 0 && b.vx > -b.speed * 0.26) b.vx = -b.speed * 0.26;
if (dir > 0 && b.vx < b.speed * 0.26) b.vx = b.speed * 0.26;
} else {
if (dir < 0 && b.vy > -b.speed * 0.26) b.vy = -b.speed * 0.26;
if (dir > 0 && b.vy < b.speed * 0.26) b.vy = b.speed * 0.26;
}
/* Tempo-Deckel: Stöße aus Paddelbewegung dürfen den Ball nicht aufheizen */
var m2 = Math.sqrt(b.vx * b.vx + b.vy * b.vy) || 1, capS = baseSpeed() + 210;
if (m2 > capS) { var kk = capS / m2; b.vx *= kk; b.vy *= kk; b.speed = capS; }
if (vert) b.x = dir > 0 ? pad.x + rw + b.r + 0.6 : pad.x - b.r - 0.6;
else b.y = dir < 0 ? pad.y - b.r - 0.6 : pad.y + PH + b.r + 0.6;
combo = 0; comboT = 0; hud();
beep(140, 0.05, 'sine', 0.05);
return true;
}
/* ---------------- update ---------------- */
var SPLIT_TOP = TOP - 26, SPLIT_BOT = H - 24;
function sweepPad(p, fr) {
return { src: p, axis: p.axis, dirIn: p.dirIn, w: p.w, vx: p.vx, vy: p.vy,
x: p.prevX + (p.x - p.prevX) * fr, y: p.prevY + (p.y - p.prevY) * fr };
}
function moveBall(b, dt) {
var f = speedFactor();
if (b.attached) {
b.at += dt;
syncAttach(b);
b.trail.length = 0;
if (b.at > 1.3) launchBall(b);
return false;
}
var dist = b.speed * f * dt;
/* Paddle-Bewegung mit abzweigen: sonst tunneln Bälle durch ein schnell gefahrenes Paddle */
var dxp = paddle.x - paddle.prevX, dyp = paddle.y - paddle.prevY;
var travel = dist + Math.abs(dxp) + Math.abs(dyp);
var steps = Math.max(1, Math.min(240, Math.ceil(travel / 3.5))), sdt = dt * f / steps;
var split = (variant === 'split');
for (var s = 0; s < steps; s++) {
var fr = (s + 1) / steps;
b.x += b.vx * sdt; b.y += b.vy * sdt;
if (split) {
if (b.y - b.r < SPLIT_TOP) { b.y = SPLIT_TOP + b.r; b.vy = Math.abs(b.vy); combo = 0; beep(520, 0.04, 'sine', 0.04); }
else if (b.y + b.r > SPLIT_BOT) { b.y = SPLIT_BOT - b.r; b.vy = -Math.abs(b.vy); combo = 0; beep(520, 0.04, 'sine', 0.04); }
} else {
if (b.x - b.r < PAD) { b.x = PAD + b.r; b.vx = Math.abs(b.vx); combo = 0; beep(520, 0.04, 'sine', 0.04); }
else if (b.x + b.r > W - PAD) { b.x = W - PAD - b.r; b.vx = -Math.abs(b.vx); combo = 0; beep(520, 0.04, 'sine', 0.04); }
if (b.y - b.r < SPLIT_TOP) { b.y = SPLIT_TOP + b.r; b.vy = Math.abs(b.vy); beep(520, 0.04, 'sine', 0.04); }
}
if (collideBricks(b)) break;
if (collidePaddle(b, sweepPad(pads[0], fr))) break;
if (pads[1] && collidePaddle(b, sweepPad(pads[1], fr))) break;
}
b.trail.push({ x: b.x, y: b.y });
if (b.trail.length > 20) b.trail.shift();
if (split) return b.x + b.r < 0 || b.x - b.r > W;
return b.y - b.r > H;
}
function update(dt) {
tickEffects(dt);
if (variant === 'split') {
var dvy = (keys.down ? 1 : 0) - (keys.up ? 1 : 0);
if (dvy) {
for (var pi = 0; pi < pads.length; pi++) pads[pi].y = clamp(pads[pi].y + dvy * 560 * dt, PAD_TOP, PAD_BOT - pads[pi].w);
}
} else {
if (keys.left || keys.right) {
var d = (keys.right ? 1 : 0) - (keys.left ? 1 : 0);
paddle.x = clamp(paddle.x + d * 720 * dt, PAD, W - PAD - paddle.w);
}
if (fx.free > 0) {
var dv = (keys.down ? 1 : 0) - (keys.up ? 1 : 0);
if (dv) paddle.y = clamp(paddle.y + dv * 560 * dt, PY_TOP, PY);
} else if (paddle.y < PY) {
paddle.y = Math.min(PY, paddle.y + 460 * dt);
}
if (paddle.y > PY) paddle.y = PY;
}
for (var i = balls.length - 1; i >= 0; i--) {
if (moveBall(balls[i], dt)) {
burst({ x: clamp(balls[i].x, 10, W - 22), y: variant === 'split' ? clamp(balls[i].y, 14, H - 26) : H - 12, w: 12, h: 12 }, '#F09595');
balls.splice(i, 1);
}
}
if (balls.length === 0) { loseLife(); return; }
if (fx.laser > 0 && opts.autoFire && pads[0].axis === 'h') {
laserCd -= dt;
if (laserCd <= 0) { laserCd = 0.34; fireVolley(); }
}
for (var j = bullets.length - 1; j >= 0; j--) {
var bu = bullets[j]; bu.y -= 520 * dt;
if (bu.y < TOP - 26) { bullets.splice(j, 1); continue; }
for (var k = 0; k < bricks.length; k++) {
var br = bricks[k]; if (br.hp <= 0) continue;
if (bu.x >= br.x && bu.x <= br.x + br.w && bu.y <= br.y + br.h && bu.y >= br.y) {
hitBrick(br); bullets.splice(j, 1); break;
}
}
}
var splitLv = (variant === 'split');
for (var m = powerups.length - 1; m >= 0; m--) {
var pu = powerups[m]; pu.t += dt;
if (splitLv) {
pu.x += (pu.vx || 0) * dt;
if (pu.x < -24 || pu.x > W + 24 || pu.t > 14) { powerups.splice(m, 1); continue; }
} else {
pu.y += pu.vy * dt;
if (pu.y > H + 20) { powerups.splice(m, 1); continue; }
}
var got = null;
for (var pi2 = 0; pi2 < pads.length; pi2++) {
var pr = padRect(pads[pi2]);
if (pu.x >= pr.x - 10 && pu.x <= pr.x + pr.w + 10 && pu.y >= pr.y - 10 && pu.y <= pr.y + pr.h + 10) { got = pr; break; }
}
if (got) { grab(pu.p, got.x + got.w / 2, got.y + got.h / 2); powerups.splice(m, 1); }
}
if (comboT > 0) { comboT -= dt; if (comboT <= 0) { combo = 0; hud(); } }
var left = 0;
for (var q = 0; q < bricks.length; q++) if (bricks[q].hp > 0) left++;
if (left === 0 && state === 'playing') {
state = 'levelclear'; levelTimer = 1.5; score += 250 * level; hud();
showMsg('Level ' + level + ' geschafft', '+250 Bonus · Power-ups bleiben erhalten');
beep(660, 0.12, 'triangle', 0.06);
setTimeout(function () { beep(880, 0.16, 'triangle', 0.06); }, 110);
}
}
function loseLife() {
lives--; shake = 14; hud();
beep(90, 0.35, 'sawtooth', 0.07);
fx.shrink = 0; fx.fast = 0; applyPaddle();
if (lives <= 0) {
if (continues > 0) {
state = 'continue'; continueT = CONTINUE_TIME; contTick = 0;
hud(); showContinue(); hudFx(true);
beep(300, 0.3, 'triangle', 0.05);
return;
}
gameOver();
} else resetBall();
}
function showContinue() {
showMsg('Continue? ' + Math.ceil(continueT),
'Neustart auf Level ' + checkpoint + ' mit ' + START_LIVES + ' Leben, Punkte bleiben<br>Klick oder Taste C nutzen · ESC gibt auf · noch ' + continues + ' Continue');
}
function doContinue() {
if (state !== 'continue' || continues <= 0) return;
continues--; ccUsed++;
level = checkpoint; lives = START_LIVES;
for (var k in fx) fx[k] = 0;
applyPaddle();
powerups.length = 0; bullets.length = 0; notes.length = 0; particles.length = 0;
combo = 0; comboT = 0; continueT = 0;
hud(); hudFx(true); buildLevel(); resetBall();
beep(520, 0.12, 'triangle', 0.06);
setTimeout(function () { beep(780, 0.14, 'triangle', 0.06); }, 100);
}
function gameOver() {
state = 'over'; continueT = 0;
if (score > 0) {
scores.push(score);
scores.sort(function (a, b) { return b - a; });
scores = scores.slice(0, 5);
best = scores[0];
if (ccUsed > 0) scoreCC[String(score)] = ccUsed;
}
var keep = {};
scores.forEach(function (v) { if (scoreCC[String(v)] > 0) keep[String(v)] = scoreCC[String(v)]; });
scoreCC = keep;
try {
localStorage.setItem('breakout.scores', JSON.stringify(scores));
localStorage.setItem('breakout.scoreCC', JSON.stringify(scoreCC));
} catch (e) {}
hud();
showMsg('Game Over', 'Erreicht: ' + score.toLocaleString('de-DE') + ' Punkte' + (ccUsed ? ' · ' + ccUsed + ' Continue genutzt' : '') +
'<br>Top 5: ' + top5Html(), statsHtml() + '<div class="small">Klick für neues Spiel</div>');
hudFx(true);
playCadence();
}
/* ---------------- draw ---------------- */
function draw() {
ctx.setTransform(sx, 0, 0, sx, 0, 0);
ctx.save();
if (flip) { ctx.translate(0, H); ctx.scale(1, -1); } /* Überkopf-Level: Physik gleich, Ansicht gespiegelt */
drawBg();
ctx.save(); ctx.translate(shakeX, shakeY);
drawBricks(); drawPowerups(); drawBullets();
for (var i = 0; i < balls.length; i++) drawTrail(balls[i]);
for (var j = 0; j < balls.length; j++) drawBall(balls[j]);
for (var q = 0; q < pads.length; q++) drawPad(pads[q]);
drawParticles();
ctx.restore();
ctx.restore();
drawNotes();
}
function drawBg() {
var g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, '#0b1224'); g.addColorStop(1, '#05070f');
ctx.fillStyle = g; ctx.fillRect(-30, -30, W + 60, H + 60);
ctx.strokeStyle = 'rgba(255,255,255,0.035)'; ctx.lineWidth = 1;
for (var x = SIDE; x <= W - SIDE; x += 40) { ctx.beginPath(); ctx.moveTo(x, TOP - 26); ctx.lineTo(x, H); ctx.stroke(); }
for (var y = TOP - 26; y <= H; y += 40) { ctx.beginPath(); ctx.moveTo(SIDE, y); ctx.lineTo(W - SIDE, y); ctx.stroke(); }
var r1 = ctx.createRadialGradient(W * 0.3, TOP + 10, 10, W * 0.3, TOP + 10, 260);
r1.addColorStop(0, 'rgba(83,74,183,0.30)'); r1.addColorStop(1, 'rgba(83,74,183,0)');
ctx.fillStyle = r1; ctx.fillRect(0, 0, W, H);
var r2 = ctx.createRadialGradient(W * 0.75, TOP + 40, 10, W * 0.75, TOP + 40, 240);
r2.addColorStop(0, 'rgba(29,158,117,0.22)'); r2.addColorStop(1, 'rgba(29,158,117,0)');
ctx.fillStyle = r2; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = 'rgba(140,160,200,0.22)'; ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(PAD, TOP - 26); ctx.lineTo(PAD, H);
ctx.moveTo(W - PAD, TOP - 26); ctx.lineTo(W - PAD, H);
ctx.moveTo(PAD, TOP - 26); ctx.lineTo(W - PAD, TOP - 26);
ctx.stroke();
ctx.strokeStyle = 'rgba(240,149,149,0.35)'; ctx.setLineDash([6, 7]); ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(PAD, PY + PH + 16); ctx.lineTo(W - PAD, PY + PH + 16); ctx.stroke();
ctx.setLineDash([]);
}
function drawBricks() {
for (var i = 0; i < bricks.length; i++) {
var b = bricks[i]; if (b.hp <= 0) continue;
var t = b.max > 1 ? (b.hp - 1) / (b.max - 1) : 0;
var grad = ctx.createLinearGradient(b.x, b.y, b.x, b.y + b.h);
grad.addColorStop(0, b.c2); grad.addColorStop(1, b.c);
ctx.save();
ctx.shadowColor = b.c2; ctx.shadowBlur = 12 + b.flash * 22;
ctx.globalAlpha = 0.85 + t * 0.15;
rr(b.x, b.y, b.w, b.h, 6); ctx.fillStyle = grad; ctx.fill();
ctx.restore();
ctx.globalAlpha = 0.9;
ctx.fillStyle = b.max > 1 ? 'rgba(255,255,255,' + (0.22 + t * 0.42) + ')' : 'rgba(255,255,255,0.18)';
rr(b.x + 4, b.y + 4, b.w - 8, 4, 2); ctx.fill();
if (b.hp < b.max) {
ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 1.2;
ctx.beginPath();
ctx.moveTo(b.x + b.w * 0.32, b.y + 3); ctx.lineTo(b.x + b.w * 0.44, b.y + b.h - 4);
if (b.max - b.hp > 1) { ctx.moveTo(b.x + b.w * 0.68, b.y + 4); ctx.lineTo(b.x + b.w * 0.58, b.y + b.h - 3); }
ctx.stroke();
}
ctx.globalAlpha = 1;
b.flash = Math.max(0, b.flash - 0.06);
}
}
function drawPowerups() {
for (var i = 0; i < powerups.length; i++) {
var p = powerups[i], pw = p.p, wob = Math.sin(p.t * 7) * 3;
ctx.save();
ctx.shadowColor = pw.c2; ctx.shadowBlur = 16;
ctx.translate(p.x + wob, p.y);
ctx.rotate(Math.sin(p.t * 3) * 0.22);
rr(-15, -11, 30, 22, 7); ctx.fillStyle = pw.good ? pw.c2 : pw.c; ctx.fill();
ctx.shadowBlur = 0;
rr(-13, -9, 26, 7, 3); ctx.fillStyle = 'rgba(255,255,255,0.35)'; ctx.fill();
ctx.fillStyle = pw.good ? '#08111f' : '#ffffff';
ctx.font = '700 13px system-ui, sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(pw.icon, 0, 2);
ctx.restore();
}
}
function drawBullets() {
for (var i = 0; i < bullets.length; i++) {
var b = bullets[i];
ctx.save();
ctx.shadowColor = '#EF9F27'; ctx.shadowBlur = 14;
ctx.strokeStyle = '#FAEEDA'; ctx.lineWidth = 2.4; ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(b.x, b.y); ctx.lineTo(b.x, b.y + 16); ctx.stroke();
ctx.restore();
}
}
function drawTrail(b) {
if (b.trail.length < 2) return;
for (var i = 1; i < b.trail.length; i++) {
var a = i / b.trail.length;
ctx.strokeStyle = 'rgba(93,202,165,' + (a * (fx.drill > 0 ? 0.6 : 0.45)).toFixed(3) + ')';
ctx.lineWidth = 1 + a * 4; ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(b.trail[i - 1].x, b.trail[i - 1].y); ctx.lineTo(b.trail[i].x, b.trail[i].y); ctx.stroke();
}
}
function drawBall(b) {
var q = b.attached ? attachPos(b) : null;
var x = q ? q.x : b.x;
var y = q ? q.y : b.y;
ctx.save();
ctx.shadowColor = fx.drill > 0 ? '#5DCAA5' : '#EAF3DE'; ctx.shadowBlur = 22;
var g = ctx.createRadialGradient(x - 2, y - 2, 1, x, y, b.r + 2);
if (fx.drill > 0) { g.addColorStop(0, '#ffffff'); g.addColorStop(0.5, '#BDE7D5'); g.addColorStop(1, '#1D9E75'); }
else { g.addColorStop(0, '#ffffff'); g.addColorStop(0.55, '#DCEFE2'); g.addColorStop(1, '#5DCAA5'); }
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x, y, b.r, 0, Math.PI * 2); ctx.fill();
if (fx.drill > 0) {
ctx.shadowBlur = 0; ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.lineWidth = 1.4;
ctx.beginPath(); ctx.moveTo(x - 5, y - 5); ctx.lineTo(x + 5, y + 5);
ctx.moveTo(x + 5, y - 5); ctx.lineTo(x - 5, y + 5); ctx.stroke();
}
ctx.restore();
}
function padFill(p) {
var g = p.axis === 'v' ? ctx.createLinearGradient(p.x, p.y, p.x, p.y + p.w)
: ctx.createLinearGradient(p.x, p.y, p.x + p.w, p.y + PH);
if (fx.shrink > 0) { g.addColorStop(0, '#A32D2D'); g.addColorStop(1, '#F09595'); }
else if (fx.expand > 0) { g.addColorStop(0, '#1D9E75'); g.addColorStop(0.5, '#5DCAA5'); g.addColorStop(1, '#97C459'); }
else if (fx.free > 0) { g.addColorStop(0, '#1C7AA6'); g.addColorStop(0.5, '#79C7E5'); g.addColorStop(1, '#1C7AA6'); }
else { g.addColorStop(0, '#378ADD'); g.addColorStop(0.5, '#AFA9EC'); g.addColorStop(1, '#1D9E75'); }
return g;
}
function drawPad(p) {
if (p.axis === 'v') { drawPadV(p); return; }
var py = p.y;
ctx.save();
ctx.shadowColor = fx.shrink > 0 ? '#F09595' : (fx.free > 0 ? '#79C7E5' : '#85B7EB'); ctx.shadowBlur = 20;
var g = padFill(p);
if (opts.round) {
ctx.beginPath();
ctx.moveTo(p.x, py + PH);
ctx.lineTo(p.x, py);
ctx.quadraticCurveTo(p.x + p.w / 2, py - 2 * ARC_V, p.x + p.w, py);
ctx.lineTo(p.x + p.w, py + PH);
ctx.closePath();
ctx.fillStyle = g; ctx.fill();
ctx.restore();
ctx.strokeStyle = 'rgba(255,255,255,0.5)'; ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.moveTo(p.x + 8, py + 1);
ctx.quadraticCurveTo(p.x + p.w / 2, py - 2 * ARC_V + 5, p.x + p.w - 8, py + 1);
ctx.stroke();
} else {
rr(p.x, py, p.w, PH, 7); ctx.fillStyle = g; ctx.fill();
ctx.restore();
ctx.fillStyle = 'rgba(255,255,255,0.55)';
rr(p.x + 6, py + 3, p.w - 12, 2.5, 1.5); ctx.fill();
}
if (fx.free > 0 && py < PY) {
/* Marker: freies Paddle + Lots zur Stammposition */
ctx.save();
ctx.shadowBlur = 0;
ctx.strokeStyle = 'rgba(121,199,229,0.5)'; ctx.lineWidth = 1.4; ctx.setLineDash([5, 6]);
ctx.beginPath();
ctx.moveTo(p.x + p.w / 2, py + PH); ctx.lineTo(p.x + p.w / 2, PY);
ctx.stroke();
ctx.setLineDash([]);
ctx.strokeStyle = '#79C7E5'; ctx.lineWidth = 1.6;
rr(p.x - 4, py - 4, p.w + 8, PH + 8, 9); ctx.stroke();
ctx.fillStyle = 'rgba(121,199,229,0.9)';
ctx.font = '700 12px DM Sans, sans-serif'; ctx.textAlign = 'center';
ctx.fillText('✥', p.x + p.w / 2, py - 10);
ctx.restore();
}
if (fx.laser > 0) {
ctx.save(); ctx.shadowColor = '#EF9F27'; ctx.shadowBlur = 12; ctx.fillStyle = '#FAEEDA';
rr(p.x + 2, py - 4, 10, 4, 2); ctx.fill();
rr(p.x + p.w - 12, py - 4, 10, 4, 2); ctx.fill();
ctx.restore();
}
if (fx.sticky > 0) {
ctx.fillStyle = 'rgba(237,147,177,0.85)';
for (var i = 0; i < 5; i++) {
var t = (10 + i * (p.w - 20) / 4) / p.w;
var dy = opts.round ? 4 * ARC_V * t * (1 - t) : 0;
ctx.beginPath();
ctx.arc(p.x + 10 + i * (p.w - 20) / 4, py - dy, 2.2, 0, Math.PI * 2);
ctx.fill();
}
}
}
function drawPadV(p) {
ctx.save();
ctx.shadowColor = fx.shrink > 0 ? '#F09595' : '#79C7E5'; ctx.shadowBlur = 20;
rr(p.x, p.y, PH, p.w, 7); ctx.fillStyle = padFill(p); ctx.fill();
ctx.restore();
/* Schlagseite zum Spielfeld hin */
ctx.fillStyle = 'rgba(255,255,255,0.55)';
rr(p.dirIn < 0 ? p.x + PH - 4 : p.x + 1.5, p.y + 6, 2.5, p.w - 12, 1.5); ctx.fill();
ctx.strokeStyle = 'rgba(121,199,229,0.45)'; ctx.lineWidth = 1.2; ctx.setLineDash([5, 6]);
ctx.beginPath();
var mx = p.dirIn < 0 ? p.x + PH + 8 : p.x - 8;
ctx.moveTo(mx, p.y + 8); ctx.lineTo(mx, p.y + p.w - 8);
ctx.stroke(); ctx.setLineDash([]);
if (fx.sticky > 0) {
ctx.fillStyle = 'rgba(237,147,177,0.85)';
for (var i = 0; i < 5; i++) {
ctx.beginPath();
ctx.arc(p.dirIn < 0 ? p.x + PH - 2 : p.x + 2, p.y + 10 + i * (p.w - 20) / 4, 2.2, 0, Math.PI * 2);
ctx.fill();
}
}
}
function drawParticles() {
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
ctx.globalAlpha = Math.max(0, p.life / p.max);
ctx.fillStyle = p.col;
ctx.beginPath(); ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2); ctx.fill();
}
ctx.globalAlpha = 1;
}
function drawNotes() {
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
for (var i = 0; i < notes.length; i++) {
var n = notes[i], a = Math.min(1, n.t / 0.6);
ctx.save(); ctx.globalAlpha = a;
ctx.font = '500 16px system-ui, sans-serif';
var wTxt = ctx.measureText(n.text).width + 24;
ctx.shadowColor = n.color; ctx.shadowBlur = 18;
ctx.fillStyle = 'rgba(255,255,255,0.92)';
rr(W / 2 - wTxt / 2, TOP - 6 + i * 30, wTxt, 24, 8); ctx.fill();
ctx.shadowBlur = 0; ctx.fillStyle = '#08111f';
ctx.fillText(n.text, W / 2, TOP + 6 + i * 30);
ctx.restore();
}
}
/* ---------------- HUD ---------------- */
function hud() {
if (score > best) best = score;
elScore.textContent = score.toLocaleString('de-DE');
elBest.textContent = best.toLocaleString('de-DE');
elLevel.textContent = variant === 'normal' ? level : level + ' · ' + VSHORT[variant];
elLevel.title = variant === 'normal' ? 'Level' : VINFO[variant];
elCombo.textContent = '×' + (1 + Math.min(combo, 8) * 0.5).toFixed(1).replace('.', ',');
elCont.textContent = continues;
var h = '';
for (var i = 0; i < Math.max(3, lives); i++) h += '<i class="' + (i < lives ? '' : 'off') + '"></i>';
elHearts.innerHTML = h;
if (opts.debug) dbgSync();
}
var fxChips = {};
function hudFx() {
/* Chips bleiben bestehen, nur Balkenbreite aktualisiert -> kein Flackern */
var changed = false;
if (!fxChips.lbl) {
var lbl = fxbar.querySelector('.lbl');
if (!lbl) {
lbl = document.createElement('span'); lbl.className = 'lbl'; lbl.textContent = 'Aktive Power-ups';
fxbar.appendChild(lbl);
}
fxChips.lbl = { el: lbl };
}
var live = { lbl: true };
for (var i = 0; i < PU.length; i++) {
var p = PU[i];
if (!fx[p.id] || fx[p.id] <= 0) continue;
live[p.id] = true;
var e = fxChips[p.id];
if (!e) {
var chip = document.createElement('span'); chip.className = 'fx' + (p.good ? '' : ' bad');
var glyph = document.createElement('span'); glyph.className = 'glyph'; glyph.textContent = p.icon;
glyph.style.background = p.good ? p.c2 : p.c;
var label = document.createElement('span'); label.textContent = p.name;
var bar = document.createElement('span'); bar.className = 'bar';
var fill = document.createElement('span'); fill.style.background = p.c2;
bar.appendChild(fill);
chip.appendChild(glyph); chip.appendChild(label); chip.appendChild(bar);
fxbar.appendChild(chip);
e = fxChips[p.id] = { el: chip, fill: fill };
changed = true;
}
var pct = Math.max(0, Math.min(100, fx[p.id] / p.dur * 100));
e.fill.style.width = pct.toFixed(1) + '%';
}
if (balls.length > 1) {
live.balls = true;
var eb = fxChips.balls;
if (!eb) {
var chip2 = document.createElement('span'); chip2.className = 'fx';
var g2 = document.createElement('span'); g2.className = 'glyph'; g2.textContent = 'M'; g2.style.background = '#85B7EB';
var c2 = document.createElement('span'); c2.textContent = balls.length + ' Bälle';
chip2.appendChild(g2); chip2.appendChild(c2);
fxbar.appendChild(chip2);
eb = fxChips.balls = { el: chip2, cnt: c2 };
changed = true;
}
eb.cnt.textContent = balls.length + ' Bälle';
}
for (var k in fxChips) if (!live[k]) { fxbar.removeChild(fxChips[k].el); delete fxChips[k]; changed = true; }
/* Nur bei echter Chip-Änderung neu layouten (fxbar kann umbrechen -> Höhe ändert sich) */
if (changed) requestLayout();
}
/* ---------------- input ---------------- */
function localX(clientX) {
if (!rectCache) rectCache = canvas.getBoundingClientRect();
return (clientX - rectCache.left) * W / rectCache.width;
}
function localY(clientY) {
if (!rectCache) rectCache = canvas.getBoundingClientRect();
return (clientY - rectCache.top) * H / rectCache.height;
}
function launchAttached() {
var any = false;
for (var i = 0; i < balls.length; i++) if (balls[i].attached) { launchBall(balls[i]); any = true; }
return any;
}
/* Pointer-Lock: Klick fängt die Maus im Spielfeld ein, ESC gibt sie frei */
var pointerLocked = false;
function canvasRequestLock() {
if (!canvas.requestPointerLock || pointerLocked) return;
try { var r = canvas.requestPointerLock(); if (r && r.catch) r.catch(function () {}); } catch (e) {}
}
function canvasExitLock() {
if (document.exitPointerLock) { try { document.exitPointerLock(); } catch (e) {} }
}
document.addEventListener('pointerlockchange', function () {
pointerLocked = document.pointerLockElement === canvas;
rectCache = null;
wrap.style.cursor = pointerLocked ? 'none' : 'default';
if (!pointerLocked && state === 'playing') {
state = 'paused';
showMsg('Maus freigegeben', 'Klick ins Spielfeld fängt die Maus wieder ein');
}
});
document.addEventListener('pointerlockerror', function () { pointerLocked = false; });
function paddleLive() { return state === 'playing' || state === 'ready'; }
function movePadsTo(centerY) {
var y = clamp(centerY - paddle.w / 2, PAD_TOP, PAD_BOT - paddle.w);
for (var i = 0; i < pads.length; i++) pads[i].y = y;
}
/* ny =Mauspunkt: seitliche Paddel werden darauf zentriert, das Boden-Paddle liegt eine halbe Dicke darunter */
function movePaddleTo(nx, ny) {
if (!paddleLive()) return false; /* Pause/Levelübergang/Continue/Game Over: Paddle steht still */
if (variant === 'split') {
if (ny === undefined) return false;
movePadsTo(ny);
return true;
}
paddle.x = clamp(nx, PAD, W - PAD - paddle.w);
if (ny !== undefined && fx.free > 0) paddle.y = clamp(ny - PH / 2, PY_TOP, PY);
return true;
}
/* Pointer-Lock: relative Mausbewegung */
function nudgePaddle(dx, dy) {
if (!paddleLive()) return false;
if (variant === 'split') { movePadsTo(paddle.y + paddle.w / 2 + dy); return true; }
paddle.x = clamp(paddle.x + dx, PAD, W - PAD - paddle.w);
if (fx.free > 0) paddle.y = clamp(paddle.y + dy, PY_TOP, PY);
return true;
}
wrap.addEventListener('pointermove', function (e) {
if (!paddleLive()) return;
if (pointerLocked) {
if (!rectCache) rectCache = canvas.getBoundingClientRect();
var scale = rectCache.width ? W / rectCache.width : 1;
nudgePaddle((e.movementX || 0) * scale, (e.movementY || 0) * scale * (flip ? -1 : 1));
} else {
var cy = flip ? H - localY(e.clientY) : localY(e.clientY);
movePaddleTo(localX(e.clientX) - paddle.w / 2, cy);
}
});
wrap.addEventListener('pointerdown', function (e) {
try { audioBus(); } catch (err) {}
if (e.pointerType !== 'mouse' && wrap.setPointerCapture) { try { wrap.setPointerCapture(e.pointerId); } catch (err) {} }
if (e.pointerType === 'mouse' && !pointerLocked) canvasRequestLock();
if (state === 'continue') { doContinue(); return; }
if (state === 'levelclear') return;
if (state === 'playing') { launchAttached(); fireVolley(); return; }
if (state === 'paused') { state = 'playing'; hideMsg(); last = performance.now(); return; }
startOrRestart();
});
window.addEventListener('keydown', function (e) {
try { audioBus(); } catch (err) {}
if (e.key === 'm' || e.key === 'M') {
opts.music = !opts.music; saveOpts(); renderOpts();
if (!opts.music) { musGainTo(0, 0.2); musTrack = 'none'; }
return;
}
if (e.key === 'Escape') { if (optionsOpen) closeOptions(); if (state === 'continue') gameOver(); canvasExitLock(); return; }
if (optionsOpen) return;
if (opts.debug && (e.key === '[' || e.key === ']')) { debugStep(e.key === ']' ? 1 : -1); e.preventDefault(); return; }
if (e.key === 'ArrowLeft') { keys.left = true; e.preventDefault(); }
if (e.key === 'ArrowRight') { keys.right = true; e.preventDefault(); }
if (e.key === 'ArrowUp') { keys.up = true; e.preventDefault(); }
if (e.key === 'ArrowDown') { keys.down = true; e.preventDefault(); }
if (e.code === 'Space' || e.key === 'Enter') {
e.preventDefault();
if (state === 'continue') { doContinue(); return; }
if (state === 'levelclear') return;
if (state === 'paused') { state = 'playing'; hideMsg(); last = performance.now(); return; }
if (state === 'playing') { launchAttached(); fireVolley(); return; }
startOrRestart();
}
if (e.key === 'c' || e.key === 'C') { if (state === 'continue') doContinue(); return; }
if (e.key === 'p' || e.key === 'P') {
if (state === 'playing') { state = 'paused'; showMsg('Pause', 'Klick oder P zum weiterspielen'); }
else if (state === 'paused') { state = 'playing'; hideMsg(); last = performance.now(); }
}
if (e.key === 'r' || e.key === 'R') newGame();
});
window.addEventListener('keyup', function (e) {
if (e.key === 'ArrowLeft') keys.left = false;
if (e.key === 'ArrowRight') keys.right = false;
if (e.key === 'ArrowUp') keys.up = false;
if (e.key === 'ArrowDown') keys.down = false;
});
btnRestart.addEventListener('click', function () { newGame(); });
btnSound.addEventListener('click', function () { sound = !sound; btnSound.textContent = sound ? 'Ton an' : 'Ton aus'; });
function paintOpt(btn, on) {
var b = btn.querySelector('b');
if (b) b.textContent = on ? 'AN' : 'OFF';
btn.classList.toggle('off', !on);
}
function dbgSync() {
if (!dbgBox) return;
dbgBox.classList.toggle('hidden', !opts.debug);
if (!opts.debug) return;
if (dbgLvl && document.activeElement !== dbgLvl) dbgLvl.value = level;
if (dbgVar) dbgVar.textContent = variant === 'normal' ? 'normal' : VTITLE[variant];
}
function setLevel(n) {
var target = clamp(Math.round(Number(n)) || 1, 1, 99);
level = target;
if (lives <= 0) { lives = START_LIVES; if (continues <= 0) continues = MAX_CONTINUES; }
hud(); buildLevel(); resetBall();
if (level % CHECKPOINT_EVERY === 0) {
checkpoint = level;
showMsg('Level ' + level + (variant === 'normal' ? '' : ' · ' + VTITLE[variant]) + ' · Checkpoint',
'Continue gesichert (' + continues + ') · Klick zum Starten');
}
hud(); dbgSync();
}
function debugStep(d) { if (opts.debug) setLevel(level + d); }
function renderOpts() {
paintOpt(optRound, opts.round); paintOpt(optAuto, opts.autoFire); paintOpt(optPU, opts.pu);
paintOpt(optDebug, opts.debug); paintOpt(optMusic, opts.music);
dbgSync();
if (laserHint) laserHint.textContent = opts.autoFire ? 'Laser feuert automatisch' : 'Laser: Salve per Klick/Leertaste';
}
function openOptions() {
optionsOpen = true;
canvasExitLock();
if (state === 'playing') state = 'paused';
hideMsg();
optsPanel.classList.remove('hidden');
}
function closeOptions() {
optionsOpen = false;
optsPanel.classList.add('hidden');
if (state === 'paused') showMsg('Pause', 'Klick oder P zum weiterspielen');
else if (state === 'ready' && lives > 0) showMsg('Level ' + level, 'Klicken zum Starten');
}
optRound.addEventListener('click', function () { opts.round = !opts.round; saveOpts(); renderOpts(); });
optAuto.addEventListener('click', function () { opts.autoFire = !opts.autoFire; laserCd = 0; saveOpts(); renderOpts(); legend(); });
optPU.addEventListener('click', function () {
opts.pu = !opts.pu; saveOpts(); renderOpts();
if (!opts.pu) { powerups.length = 0; for (var k in fx) fx[k] = 0; applyPaddle(); hudFx(true); }
});
optDebug.addEventListener('click', function () { opts.debug = !opts.debug; saveOpts(); renderOpts(); });
optMusic.addEventListener('click', function () {
opts.music = !opts.music; saveOpts(); renderOpts();
if (!opts.music) { musGainTo(0, 0.2); musTrack = 'none'; }
});
dbgUp.addEventListener('click', function () { debugStep(1); if (dbgLvl.blur) dbgLvl.blur(); });
dbgDown.addEventListener('click', function () { debugStep(-1); if (dbgLvl.blur) dbgLvl.blur(); });
dbgLvl.addEventListener('change', function () { setLevel(dbgLvl.value); });
dbgLvl.addEventListener('keydown', function (e) {
e.stopPropagation();
if (e.key === 'Enter') { setLevel(dbgLvl.value); if (dbgLvl.blur) dbgLvl.blur(); }
});
optClose.addEventListener('click', closeOptions);
btnOptions.addEventListener('click', function () { if (optionsOpen) closeOptions(); else openOptions(); });
optsPanel.addEventListener('pointerdown', function (e) { e.stopPropagation(); });
window.addEventListener('resize', requestLayout);
window.addEventListener('orientationchange', requestLayout);
if (window.visualViewport) window.visualViewport.addEventListener('resize', requestLayout);
document.addEventListener('visibilitychange', function () {
if (document.hidden && state === 'playing') { state = 'paused'; showMsg('Pause', 'Klick zum weiterspielen'); }
});
canvas.addEventListener('contextmenu', function (e) { e.preventDefault(); });
window.addEventListener('pointerup', function () { rectCache = null; });
/* ---------------- loop ---------------- */
var last = performance.now();
function frame(now) {
var dt = Math.min(1 / 30, (now - last) / 1000); last = now;
for (var fi = 0; fi < pads.length; fi++) {
pads[fi].vx = (pads[fi].x - pads[fi].prevX) / Math.max(dt, 0.001);
pads[fi].vy = (pads[fi].y - pads[fi].prevY) / Math.max(dt, 0.001);
}
/* Ready/Pause: gehaltene Bälle bleiben klebend am Paddle, auch wenn man es bewegt */
if (state === 'ready' || state === 'paused') {
for (var ri = 0; ri < balls.length; ri++) if (balls[ri].attached) syncAttach(balls[ri]);
}
if (state === 'playing') update(dt);
if (state === 'levelclear') {
levelTimer -= dt;
if (levelTimer <= 0) {
powerups.length = 0;
level++;
if (lives < 5 && level % 2 === 0) lives++;
if (level % CHECKPOINT_EVERY === 0) checkpoint = level;
hud(); buildLevel(); resetBall();
if (checkpoint === level) {
showMsg('Level ' + level + (variant === 'normal' ? '' : ' · ' + VTITLE[variant]) + ' · Checkpoint', 'Continue gesichert (' + continues + ') · Klick zum Starten');
beep(720, 0.14, 'triangle', 0.06);
}
}
}
if (state === 'continue') {
continueT -= dt; contTick -= dt;
if (contTick <= 0) { contTick = 0.2; showContinue(); }
if (continueT <= 0) { continueT = 0; gameOver(); }
}
for (var i = 0; i < notes.length; i++) notes[i].t -= dt;
for (var j = notes.length - 1; j >= 0; j--) if (notes[j].t <= 0) notes.splice(j, 1);
for (var p2 = particles.length - 1; p2 >= 0; p2--) {
var p = particles[p2]; p.life -= dt;
if (p.life <= 0) { particles.splice(p2, 1); continue; }
p.vy += 520 * dt; p.x += p.vx * dt; p.y += p.vy * dt;
}
if (shake > 0.2) {
shake *= 0.86;
shakeX = (Math.random() - 0.5) * shake; shakeY = (Math.random() - 0.5) * shake;
} else { shake = 0; shakeX = 0; shakeY = 0; }
hudFx(false);
musicTick();
draw();
/* Paddle-Endposition dieses Frames merken: fürs Abfrage-Scanning des nächsten Frames */
for (var pj = 0; pj < pads.length; pj++) { pads[pj].prevX = pads[pj].x; pads[pj].prevY = pads[pj].y; }
requestAnimationFrame(frame);
}
/* Debug-Start: ?level=16 oder ?variant=split (pyramid|upside|fort|split), ?debug=1 schaltet die Wahl ein */
var startupLevel = 0;
try {
var pm = {};
((window.location && window.location.search) || '').replace(/^\?/, '').split('&').forEach(function (kv) {
if (!kv) return;
var p = kv.split('=');
pm[p[0]] = decodeURIComponent(p[1] || '');
});
if (pm.debug === '1' || pm.level || pm.variant) opts.debug = true;
if (pm.level) startupLevel = clamp(parseInt(pm.level, 10) || 1, 1, 99);
if (pm.variant) {
for (var li = 1; li <= 40; li++) { if (variantOf(li) === pm.variant) { startupLevel = li; break; } }
}
} catch (e) {}
legend(); renderOpts(); layout(); buildLevel(); resetBall(); hud(); hudFx(true);
if (startupLevel > 1) setLevel(startupLevel);
drawReady = true;
redraw();
/* Layout finalisieren nachdem Fonts/Box-Messung stabil sind */
if (document.fonts && document.fonts.ready) document.fonts.ready.then(requestLayout);
setTimeout(requestLayout, 80);
setTimeout(requestLayout, 400);
requestAnimationFrame(frame);
})();
</script>
</body>
</html>