Breakout: HTML/Canvas-Clone mit Power-ups und automatischer Fensterskalierung

This commit is contained in:
Athena committed 2026-10-12 21:41:58 +02:00
commit 2f57748e0c
1 file changed
+985
+985
View File
@@ -0,0 +1,985 @@
<!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;
}
* { 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; }
#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); }
#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: wrap; }
#actions { margin-left: auto; display: flex; gap: 8px; }
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); }
details { margin-top: 10px; }
summary { font-size: calc(12px * var(--s)); color: var(--muted); cursor: pointer; }
#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 details { 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">Paddle folgt der Maus · Klick / Leertaste schießt · <kbd>P</kbd> pausiert · <kbd>R</kbd> Neustart</div>
</div>
<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="lives">Leben <span id="hearts"></span></span>
</div>
</div>
<div id="fxbar"><span class="lbl">Aktive Power-ups</span></div>
<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>
<div id="foot">
<span>← → Pfeiltasten gehen auch · Laser feuert automatisch · <span id="dims"></span></span>
<div id="actions">
<button id="sound">Ton an</button>
<button id="restart">Neustart</button>
</div>
</div>
<details>
<summary>Power-ups &amp; Legende</summary>
<div id="pu-legend"></div>
</details>
</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 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 elHearts = document.getElementById('hearts');
var btnSound = document.getElementById('sound');
var btnRestart = document.getElementById('restart');
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:'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, w: PW };
var keys = { left: false, right: false };
var fx = { expand: 0, shrink: 0, slow: 0, fast: 0, laser: 0, sticky: 0, drill: 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 sound = true, ac = null, fxSig = '';
try { best = Number(localStorage.getItem('breakout.best')) || 0; } catch (e) { best = 0; }
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.desc + '</div></div></div>';
});
document.getElementById('pu-legend').innerHTML = html;
}
/* ---------------- sound ---------------- */
function beep(freq, dur, type, gain) {
if (!sound) return;
try {
if (!ac) ac = new (window.AudioContext || window.webkitAudioContext)();
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(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) {}
}
/* ---------------- helpers ---------------- */
var rootEl = document.documentElement;
var headEl = document.getElementById('head');
var footEl = document.getElementById('foot');
var detailsEl = document.querySelector('details');
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 (Kopf + Power-up-Leiste + Fuß + optional Legende) */
function chromeH() {
var h = headEl.offsetHeight + fxbar.offsetHeight + footEl.offsetHeight;
if (detailsEl && detailsEl.open) h += detailsEl.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 };
}
/* 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 maxFieldW = Math.max(240, wrap.clientWidth || (vw - 60));
var bodyPadY = padPair(document.body, 'paddingTop', 'paddingBottom');
var panelPadY = padPair(document.getElementById('panel'), 'paddingTop', 'paddingBottom');
var chrome1 = headEl.offsetHeight + fxbar.offsetHeight + footEl.offsetHeight
+ (detailsEl && detailsEl.open ? detailsEl.offsetHeight : 0);
return { vw: vw, panelFull: panelFull, maxFieldW: maxFieldW,
panelExtraX: Math.max(0, panelFull - maxFieldW),
chrome1: chrome1, padY: bodyPadY + panelPadY };
}
function fitField(base) {
/* chrome skaliert ungefähr mit s; löse fieldW = (availH - chrome(s)) * ASPECT */
var s = 1, fieldW = 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;
fieldW = Math.min(base.maxFieldW, byH);
s = clamp(fieldW / 720, S_MIN, S_MAX);
var pw = Math.min(fieldW + base.panelExtraX, base.panelFull);
/* 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(fieldW + base.panelExtraX, base.panelFull);
rootEl.style.setProperty('--pw', pwf.toFixed(1) + 'px');
rootEl.style.setProperty('--s', s.toFixed(3));
}
var lastPw = 0;
function layout() {
var vh = viewportH();
/* Niedrige Fenster: Kopfzeilen/Legende ausblenden, damit das Feld wächst */
document.body.classList.toggle('compact', vh < 600);
S_MAX = document.body.classList.contains('compact') ? 1.18 : 1.34;
var base = measureChromeBase();
fitField(base);
var dim = resize();
if (dimsEl) dimsEl.textContent = dim.w + ' × ' + dim.h + ' px';
}
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 ---------------- */
function buildLevel() {
var rows = Math.min(4 + level, 8);
var bw = (W - 2 * SIDE - (COLS - 1) * GAP) / COLS;
bricks = [];
for (var r = 0; r < rows; r++) {
var hp = 1 + Math.floor((rows - 1 - r) / 2);
var 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;
bricks.push({ x: SIDE + c * (bw + GAP), y: TOP + r * (BH + GAP), w: bw, h: BH,
hp: hp, max: hp, c: col[0], c2: col[1], flash: 0 });
}
}
}
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 };
}
function resetBall() {
balls = [ makeBall(paddle.x + paddle.w / 2, PY - BR - 2, 0, 0) ];
combo = 0; comboT = 0;
bullets = []; powerups = []; laserCd = 0;
state = 'ready';
showMsg('Level ' + level, lives > 0 ? 'Klicken zum Starten' : 'Klicken für Neustart');
}
function showMsg(t, s) {
msg.innerHTML = '<div class="big">' + t + '</div><div class="small">' + s + '</div>';
msg.classList.remove('hidden');
}
function hideMsg() { msg.classList.add('hidden'); }
function launchBall(b) {
var a = (b.attached ? clamp(b.off / (paddle.w / 2), -1, 1) * 0.6 : Math.random() * 0.7 - 0.35);
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 = 3; particles = [];
for (var k in fx) fx[k] = 0;
applyPaddle();
buildLevel(); resetBall(); hud();
}
/* ---------------- power-up logic ---------------- */
function dropPowerup(bx, by) {
if (Math.random() > 0.24) return;
var total = 0; PU.forEach(function (p) { total += p.w; });
var roll = Math.random() * total, acc = 0, pick = PU[0];
for (var i = 0; i < PU.length; i++) { acc += PU[i].w; if (roll <= acc) { pick = PU[i]; break; } }
powerups.push({ x: bx, y: by, vy: 130 + level * 10, t: 0, p: pick });
}
function applyPaddle() {
var w = PW;
if (fx.expand > 0) w *= 1.6;
if (fx.shrink > 0) w *= 0.62;
paddle.w = w;
}
function grab(p, x, y) {
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 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;
if (b.hp <= 0) {
burst(b, b.c2); shake = Math.min(9, shake + 4);
beep(180 + b.max * 130, 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) {
if (b.vy <= 0 && !b.attached) return false;
var cx = clamp(b.x, paddle.x, paddle.x + paddle.w), cy = clamp(b.y, PY, PY + PH);
var dx = b.x - cx, dy = b.y - cy;
if (dx * dx + dy * dy > b.r * b.r) return false;
var off = clamp((b.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2), -1, 1);
if (fx.sticky > 0) {
b.attached = true; b.at = 0; b.off = off * (paddle.w / 2 - 6);
b.vx = 0; b.vy = 0; combo = 0; hud();
beep(200, 0.05, 'sine', 0.05);
return true;
}
var ang = off * 1.02;
b.speed = Math.max(baseSpeed(), Math.min(b.speed + 6, baseSpeed() + 190));
b.vx = Math.sin(ang) * b.speed + paddle.vx * 0.22;
b.vy = -Math.cos(ang) * b.speed;
b.y = PY - b.r - 0.6;
combo = 0; comboT = 0; hud();
beep(140, 0.05, 'sine', 0.05);
return true;
}
/* ---------------- update ---------------- */
function moveBall(b, dt) {
var f = speedFactor();
if (b.attached) {
b.at += dt;
b.x = paddle.x + paddle.w / 2 + b.off; b.y = PY - b.r - 2;
b.trail.length = 0;
if (b.at > 1.3) launchBall(b);
return false;
}
var dist = b.speed * f * dt;
var steps = Math.max(1, Math.ceil(dist / 4.5)), sdt = dt / steps;
for (var s = 0; s < steps; s++) {
b.x += b.vx * sdt; b.y += b.vy * sdt;
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 < TOP - 26) { b.y = TOP - 26 + b.r; b.vy = Math.abs(b.vy); beep(520, 0.04, 'sine', 0.04); }
if (collideBricks(b)) break;
if (collidePaddle(b)) break;
}
b.trail.push({ x: b.x, y: b.y });
if (b.trail.length > 20) b.trail.shift();
return b.y - b.r > H;
}
function update(dt) {
tickEffects(dt);
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);
}
for (var i = balls.length - 1; i >= 0; i--) {
if (moveBall(balls[i], dt)) {
burst({ x: balls[i].x - 6, y: H - 12, w: 12, h: 12 }, '#F09595');
balls.splice(i, 1);
}
}
if (balls.length === 0) { loseLife(); return; }
if (fx.laser > 0) {
laserCd -= dt;
if (laserCd <= 0) {
laserCd = 0.34;
bullets.push({ x: paddle.x + 7, y: PY - 2 });
bullets.push({ x: paddle.x + paddle.w - 7, y: PY - 2 });
beep(1100, 0.05, 'square', 0.035);
}
}
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;
}
}
}
for (var m = powerups.length - 1; m >= 0; m--) {
var pu = powerups[m]; pu.t += dt; pu.y += pu.vy * dt;
if (pu.y > H + 20) { powerups.splice(m, 1); continue; }
if (pu.y + 9 >= PY && pu.y - 9 <= PY + PH && pu.x >= paddle.x - 10 && pu.x <= paddle.x + paddle.w + 10) {
grab(pu.p, paddle.x + paddle.w / 2, PY - 6);
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) {
state = 'over';
try { localStorage.setItem('breakout.best', String(best)); } catch (e) {}
showMsg('Game Over', 'Erreicht: ' + score.toLocaleString('de-DE') + ' Punkte · Klick für neues Spiel');
hudFx(true);
} else resetBall();
}
/* ---------------- draw ---------------- */
function draw() {
ctx.setTransform(sx, 0, 0, sx, 0, 0);
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]);
drawPaddle(); drawParticles();
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 x = b.attached ? paddle.x + paddle.w / 2 + b.off : b.x;
var y = b.attached ? PY - BR - 2 : 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 drawPaddle() {
ctx.save();
ctx.shadowColor = fx.shrink > 0 ? '#F09595' : '#85B7EB'; ctx.shadowBlur = 20;
var g = ctx.createLinearGradient(paddle.x, PY, paddle.x + paddle.w, PY + 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 { g.addColorStop(0, '#378ADD'); g.addColorStop(0.5, '#AFA9EC'); g.addColorStop(1, '#1D9E75'); }
rr(paddle.x, PY, paddle.w, PH, 7); ctx.fillStyle = g; ctx.fill();
ctx.restore();
ctx.fillStyle = 'rgba(255,255,255,0.55)';
rr(paddle.x + 6, PY + 3, paddle.w - 12, 2.5, 1.5); ctx.fill();
if (fx.laser > 0) {
ctx.save(); ctx.shadowColor = '#EF9F27'; ctx.shadowBlur = 12; ctx.fillStyle = '#FAEEDA';
rr(paddle.x + 2, PY - 4, 10, 4, 2); ctx.fill();
rr(paddle.x + paddle.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++) {
ctx.beginPath();
ctx.arc(paddle.x + 10 + i * (paddle.w - 20) / 4, PY, 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 ---------------- */
var storeCd = 0;
function hud() {
if (score > best) {
best = score;
storeCd -= 1;
if (storeCd <= 0) { storeCd = 8; try { localStorage.setItem('breakout.best', String(best)); } catch (e) {} }
}
elScore.textContent = score.toLocaleString('de-DE');
elBest.textContent = best.toLocaleString('de-DE');
elLevel.textContent = level;
elCombo.textContent = '×' + (1 + Math.min(combo, 8) * 0.5).toFixed(1).replace('.', ',');
var h = '';
for (var i = 0; i < Math.max(3, lives); i++) h += '<i class="' + (i < lives ? '' : 'off') + '"></i>';
elHearts.innerHTML = h;
}
function hudFx(force) {
var sig = '';
for (var k in fx) if (fx[k] > 0) sig += k + Math.ceil(fx[k]) + '|';
if (!force && sig === fxSig) return;
fxSig = sig;
var html = '<span class="lbl">Aktive Power-ups</span>';
for (var i = 0; i < PU.length; i++) {
var p = PU[i]; if (!fx[p.id] || fx[p.id] <= 0) continue;
var pct = Math.max(0, Math.min(100, fx[p.id] / p.dur * 100));
html += '<span class="fx' + (p.good ? '' : ' bad') + '">'
+ '<span class="glyph" style="background:' + (p.good ? p.c2 : p.c) + '">' + p.icon + '</span>'
+ p.name
+ '<span class="bar"><span style="width:' + pct.toFixed(0) + '%;background:' + p.c2 + '"></span></span>'
+ '</span>';
}
if (balls.length > 1) html += '<span class="fx"><span class="glyph" style="background:#85B7EB">M</span>' + balls.length + ' Bälle</span>';
fxbar.innerHTML = html;
/* Kein Layout mitten im Spiel – fxbar hat reservierte Höhe; Layout nur bei
echter Größenänderung des Fensters (vermeidet instabile Neuberechnung). */
}
/* ---------------- input ---------------- */
function localX(clientX) {
if (!rectCache) rectCache = canvas.getBoundingClientRect();
return (clientX - rectCache.left) * W / rectCache.width;
}
function launchAttached() {
var any = false;
for (var i = 0; i < balls.length; i++) if (balls[i].attached) { launchBall(balls[i]); any = true; }
return any;
}
wrap.addEventListener('pointermove', function (e) {
if (state !== 'playing' && state !== 'ready' && state !== 'paused') return;
paddle.x = clamp(localX(e.clientX) - paddle.w / 2, PAD, W - PAD - paddle.w);
});
wrap.addEventListener('pointerdown', function (e) {
if (e.pointerType !== 'mouse' && wrap.setPointerCapture) { try { wrap.setPointerCapture(e.pointerId); } catch (err) {} }
if (state === 'playing') { launchAttached(); return; }
if (state === 'paused') { state = 'playing'; hideMsg(); last = performance.now(); return; }
startOrRestart();
});
window.addEventListener('keydown', function (e) {
if (e.key === 'ArrowLeft') keys.left = true;
if (e.key === 'ArrowRight') keys.right = true;
if (e.code === 'Space' || e.key === 'Enter') {
e.preventDefault();
if (state === 'paused') { state = 'playing'; hideMsg(); last = performance.now(); return; }
if (state === 'playing') { launchAttached(); return; }
startOrRestart();
}
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;
});
btnRestart.addEventListener('click', function () { newGame(); });
btnSound.addEventListener('click', function () { sound = !sound; btnSound.textContent = sound ? 'Ton an' : 'Ton aus'; });
window.addEventListener('resize', requestLayout);
window.addEventListener('orientationchange', requestLayout);
if (window.visualViewport) window.visualViewport.addEventListener('resize', requestLayout);
if (detailsEl) detailsEl.addEventListener('toggle', 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;
paddle.vx = (paddle.x - paddle.prevX) / Math.max(dt, 0.001); paddle.prevX = paddle.x;
if (state === 'playing') update(dt);
if (state === 'levelclear') {
levelTimer -= dt;
if (levelTimer <= 0) {
powerups.length = 0;
level++;
if (lives < 5 && level % 2 === 0) lives++;
hud(); buildLevel(); resetBall();
}
}
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);
draw();
requestAnimationFrame(frame);
}
legend(); layout(); buildLevel(); resetBall(); hud(); hudFx(true);
/* 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>