Web-based prototype for a two-player fighting game in the style of a 1990s arcade beat 'em up. The game runs on a fixed 60 fps timestep and uses a frame-based move system, where each attack is defined by startup, active and recovery frames. Fighters are drawn as procedural stick figures built from a small skeleton of poses, with an optional sprite sheet replacing the drawn figure. The prototype shows a full match loop with rounds, a timer, health bars, hitstop, screen shake, blocking, throws, juggles and special moves such as a fireball, an uppercut and a spinning kick. A simple CPU opponent with three difficulty levels can take over the second player. A side panel exposes tuning parameters and the frame data of every move, and background layers and character sheets can be replaced with own images. The prototype is meant for design exploration of fighting game feel, for teaching frame data and hitbox logic, and as a starting point for further tools.
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>TURBO FIGHT v0.1</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
html,body{margin:0;height:100%;background:#fff;color:#222;font:12px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
body{display:flex;flex-direction:column;align-items:center;justify-content:center}
canvas{display:block;image-rendering:pixelated;image-rendering:crisp-edges;border:1px solid #e2e2e2}
#stage{display:flex;gap:18px;align-items:flex-start;justify-content:center}
#panel{width:292px;max-height:calc(100vh - 150px);overflow:auto;font-size:11px;color:#666;padding-right:8px;box-sizing:border-box}
#panel.off{display:none}
@media (max-width:900px){#panel{display:none}}
.ph{font-weight:600;color:#222;letter-spacing:.08em;margin-bottom:2px}
.pg{margin:14px 0 4px;color:#222;font-weight:600}
.pr{display:grid;grid-template-columns:1fr auto;align-items:center;margin:2px 0}
.pr input[type=range]{grid-column:1/3;width:100%;accent-color:#222;margin:1px 0 3px;height:14px}
.pv{color:#222;font-variant-numeric:tabular-nums}
#panel button,#panel select{font:inherit;border:1px solid #ddd;background:#fff;border-radius:3px;padding:3px 10px;color:#444;cursor:pointer}
#panel button:hover{background:#f4f4f4}
#panel .btns{display:flex;gap:6px;margin-top:14px}
#panel .ar{display:flex;gap:4px;align-items:center;flex-wrap:wrap;margin:3px 0 7px}
#panel .ar b{width:100%;font-weight:600;color:#222}
#panel .ar i{font-style:normal;color:#aaa;font-size:10px}
#panel .ah{color:#999;font-size:10px;line-height:1.4;margin:5px 0}
#panel button.sm{padding:1px 7px;font-size:10px}
#panel input.fnum{width:46px;font:inherit;font-size:10px;border:1px solid #ddd;border-radius:3px;padding:1px 3px;color:#444}
#panel details{margin-top:14px}
#panel summary{cursor:pointer;color:#222;font-weight:600}
#panel table{border-collapse:collapse;width:100%;margin-top:6px}
#panel td,#panel th{padding:1px 1px;text-align:right;font-weight:400}
#panel th{color:#aaa;font-size:10px}
#panel td:first-child,#panel th:first-child{text-align:left;color:#222;font-variant-numeric:tabular-nums}
.mi{width:32px;font:inherit;border:1px solid #e6e6e6;border-radius:2px;padding:1px 2px;text-align:right;color:#222;background:#fff}
.mi:disabled{border-color:transparent;background:none;color:#ccc}
#out{width:100%;height:80px;font:10px monospace;margin-top:6px;display:none}
#legend{display:flex;gap:56px;margin-top:14px;color:#777}
#legend b{color:#222;font-weight:600}
#legend div{white-space:nowrap}
#spec{margin-top:10px;color:#777;font-size:11px;text-align:center}
#spec b{color:#222;font-weight:600}
#foot{margin-top:8px;color:#aaa;font-size:11px}
kbd{font:inherit;border:1px solid #ddd;border-radius:3px;padding:0 4px;color:#444;background:#fafafa}
</style>
</head>
<body>
<div id="stage"><canvas id="c"></canvas><div id="panel"></div></div>
<div id="legend">
<div><b>SPIELER 1</b><br>
<kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> Springen / Laufen / Ducken · weg vom Gegner halten = Blocken<br>
Schlag <kbd>U</kbd> leicht <kbd>I</kbd> mittel <kbd>O</kbd> schwer (Y · X · L)<br>
Tritt <kbd>J</kbd> leicht <kbd>K</kbd> mittel <kbd>L</kbd> schwer (B · A · R)</div>
<div><b>SPIELER 2</b><br>
<kbd>←</kbd><kbd>↑</kbd><kbd>↓</kbd><kbd>→</kbd> Pfeiltasten<br>
Schlag <kbd>Num4</kbd> <kbd>Num5</kbd> <kbd>Num6</kbd> oder <kbd>7</kbd> <kbd>8</kbd> <kbd>9</kbd><br>
Tritt <kbd>Num1</kbd> <kbd>Num2</kbd> <kbd>Num3</kbd> oder <kbd>4</kbd> <kbd>5</kbd> <kbd>6</kbd></div>
</div>
<div id="spec">Spezial (relativ zur Blickrichtung): <b>↓↘→ + Schlag</b> Feuerball · <b>→↓↘ + Schlag</b> Shoryuken (Launcher) · <b>↓↙← + Tritt</b> Wirbeltritt · <b>↓ + schwerer Schlag</b> Uppercut (Juggle) · nah dran: <b>→→ + Schlag/Tritt</b> Dash-Angriff · nah dran: <b>→ + schwerer Schlag/Tritt</b> Wurf nach vorn, <b>←</b> nach hinten (beide gleichzeitig = Konter)</div>
<div id="foot"><kbd>Enter</kbd> 2 Spieler · <kbd>C</kbd> gegen CPU (<kbd>F4</kbd> Schwierigkeit) · <kbd>P</kbd> Pause · <kbd>F1</kbd> Hitboxen · <kbd>F2</kbd>/<kbd>F3</kbd> Tempo · <kbd>T</kbd> Parameter-Panel · USB-Gamepads werden automatisch erkannt (Pad 1 → Spieler 1, Pad 2 → Spieler 2)</div>
<script>
'use strict';
/* =====================================================================
TURBO FIGHT v0.5 – SF2-Turbo-artiges Beat 'em up, eine Datei, keine Abhängigkeiten
Alles ist frame-basiert (60 fps, fester Timestep). Daten der Moves stehen in MOVES.
Koordinaten: x = Welt-x (Pixel), y = Höhe über dem Boden (nach oben positiv).
===================================================================== */
const W = 384, H = 224; // native SF2-Auflösung
const GROUND = 196; // Bildschirm-y der Füße
const STAGE_W = 640; // Stagebreite in Welt-Pixeln
const MAXHP = 144;
// Alle Tuning-Parameter – live im Panel (rechts) änderbar. Sprungparabel: ~44 Frames, ~93 px hoch.
const P = {
speed:1.3, walkF:1.5, walkB:1.2, jumpV:8.4, grav:.38, jumpFwd:2.5, jumpBack:2.1,
pushMul:1, airPushMul:2.2, slide:.88,
hitstunAdd:0, blockstunAdd:0, stopL:5, stopM:8, stopH:11, dmgMul:1,
comboHold:90,
throwRange:34, juggleMax:2, juggleScale:.6, throwFling:1
};
const NAMES = ['lp','mp','hp','lk','mk','hk'];
const cv = document.getElementById('c');
let ctx = cv.getContext('2d');
cv.width = W; cv.height = H; ctx.imageSmoothingEnabled = false;
function fit(){
const pe = document.getElementById('panel'), pw = (pe && pe.offsetWidth) | 0;
const aw = innerWidth - 24 - (pw ? pw + 18 : 0), ah = innerHeight - 140;
const s = Math.max(1, Math.floor(Math.min(aw / W, ah / H)));
cv.style.width = W * s + 'px';
cv.style.height = H * s + 'px';
}
addEventListener('resize', fit); fit();
/* ------------------------------ Audio (winzig, prozedural) ------------------------------ */
let AC = null;
function sfx(type){
if(!AC) return;
const o = AC.createOscillator(), g = AC.createGain(), t = AC.currentTime;
const P = {
hitL:['square',220,70,.09,.10], hitM:['square',180,55,.12,.12], hitH:['sawtooth',150,40,.18,.16],
block:['triangle',420,300,.06,.08], jump:['sine',280,520,.08,.05], ko:['sawtooth',200,30,.7,.2], whiff:['sine',500,300,.05,.03]
}[type];
if(!P) return;
o.type = P[0]; o.frequency.setValueAtTime(P[1], t); o.frequency.exponentialRampToValueAtTime(P[2], t + P[3]);
g.gain.setValueAtTime(P[4], t); g.gain.exponentialRampToValueAtTime(0.0001, t + P[3]);
o.connect(g); g.connect(AC.destination); o.start(t); o.stop(t + P[3] + .02);
}
/* ------------------------------ Eingabe ------------------------------ */
const keys = new Set();
const tapped = new Set(); // Tasten, die seit dem letzten Tick gedrückt wurden
function setSpeed(d){ P.speed = Math.min(2, Math.max(.8, Math.round((P.speed + d) * 100) / 100)); G.toast = 'SPEED x' + P.speed.toFixed(2); G.toastT = 90; syncPanel(); }
// Tastenbelegung. Buttons: 0 LP, 1 MP, 2 HP, 3 LK, 4 MK, 5 HK (SNES: Y X L / B A R)
const BIND = [
{ u:['KeyW'], d:['KeyS'], l:['KeyA'], r:['KeyD'],
b:[['KeyU'],['KeyI'],['KeyO'],['KeyJ'],['KeyK'],['KeyL']] },
{ u:['ArrowUp'], d:['ArrowDown'], l:['ArrowLeft'], r:['ArrowRight'],
b:[['Numpad4','Digit7'],['Numpad5','Digit8'],['Numpad6','Digit9'],['Numpad1','Digit4'],['Numpad2','Digit5'],['Numpad3','Digit6']] }
];
// Gamepad (Standard-Layout): 0=unten(B) 1=rechts(A) 2=links(Y) 3=oben(X) 4=L 5=R
const PADMAP = [2, 3, 4, 0, 1, 5];
const anyKey = a => a.some(k => keys.has(k) || tapped.has(k));
const pads = () => (navigator.getGamepads ? [...navigator.getGamepads()].filter(g => g && g.connected) : []);
addEventListener('keydown', e => {
const tg = e.target; // in Eingabefeldern des Panels keine Spielsteuerung
if(tg && (tg.tagName === 'SELECT' || (tg.tagName === 'INPUT' && tg.type !== 'range'))) return;
if(!AC){ try{ AC = new (window.AudioContext || window.webkitAudioContext)(); }catch(_){} }
if(e.code.startsWith('Arrow') || e.code.startsWith('Numpad') || e.code === 'Space' || e.code === 'F1' || e.code === 'F2' || e.code === 'F3' || e.code === 'F4') e.preventDefault();
if(!e.repeat){
tapped.add(e.code); // auch sehr kurze Anschläge zwischen zwei Ticks gehen nicht verloren
if(e.code === 'F2') setSpeed(-.1);
if(e.code === 'F3') setSpeed(.1);
if(e.code === 'Enter' && (G.mode === 'title' || G.mode === 'match')){ G.cpu = false; syncPanel(); newMatch(); }
if(e.code === 'KeyC' && (G.mode === 'title' || G.mode === 'match')){ G.cpu = true; syncPanel(); newMatch(); }
if(e.code === 'F4'){ AI.lv = (AI.lv + 1) % AILV.length; G.toast = 'CPU: ' + AILV[AI.lv].name; G.toastT = 90; syncPanel(); }
if(e.code === 'KeyT'){ const pe = document.getElementById('panel'); pe.classList.toggle('off'); fit(); }
if(e.code === 'KeyP') G.paused = !G.paused;
if(e.code === 'F1') G.debug = !G.debug;
if(e.code === 'Escape'){ G.mode = 'title'; G.t = 0; p1.reset(); p2.reset(); p1.wins = p2.wins = 0; }
}
keys.add(e.code);
});
addEventListener('keyup', e => keys.delete(e.code));
addEventListener('blur', () => keys.clear());
const newInput = () => ({ u:0, d:0, l:0, r:0, hold:[0,0,0,0,0,0], prev:[0,0,0,0,0,0], buf:[0,0,0,0,0,0] });
const IN = [newInput(), newInput()];
const NEUTRAL = newInput();
function pollInput(p, decay = true){
const B = BIND[p], I = IN[p];
let u = anyKey(B.u), d = anyKey(B.d), l = anyKey(B.l), r = anyKey(B.r);
const h = B.b.map(anyKey);
const gp = pads()[p];
if(gp){
const ax = gp.axes[0] || 0, ay = gp.axes[1] || 0, bt = i => gp.buttons[i] && gp.buttons[i].pressed;
l = l || ax < -.5 || bt(14); r = r || ax > .5 || bt(15); u = u || ay < -.5 || bt(12); d = d || ay > .5 || bt(13);
PADMAP.forEach((bi, k) => { if(bt(bi)) h[k] = true; });
}
if(l && r){ l = r = false; } // links+rechts = neutral
if(u && d){ d = false; } // oben hat Vorrang
I.u = u; I.d = d; I.l = l; I.r = r;
for(let k = 0; k < 6; k++){
// 5 Frames Puffer – während Hitstop läuft er nicht ab, damit Salven/Links beim Einfrieren nicht verloren gehen
I.buf[k] = (h[k] && !I.prev[k]) ? 5 : (decay ? Math.max(0, I.buf[k] - 1) : I.buf[k]);
I.prev[k] = h[k]; I.hold[k] = h[k];
}
}
const firstBuf = inp => { for(let k = 5; k >= 0; k--) if(inp.buf[k] > 0) return k; return -1; };
/* ------------------------------ Globaler Zustand ------------------------------ */
const G = {
mode:'title', t:0, f:0, round:1, timer:99, tf:0, hitstop:0, shake:0,
msg:'', msgT:0, msgCol:'#fff', toast:'', toastT:0, cpu:false, paused:false, debug:false, cam:(STAGE_W - W) / 2, winner:null
};
let sparks = [];
const setMsg = (s, n, c = '#fff') => { G.msg = s; G.msgT = n; G.msgCol = c; };
const setMode = m => { G.mode = m; G.t = 0; };
/* ------------------------------ Posen (prozedurales Skelett) ------------------------------
Lokale Koordinaten: x vorwärts (Blickrichtung), y nach oben, Ursprung = Boden unter der Hüfte.
hx,hy Hüfte · lean Rumpfneigung (rad, + = vor) · hd Kopfneigung
ff/bf = vorderer/hinterer Fuß (absolut) · fh/bh = vordere/hintere Hand (relativ zur Schulter) */
const mk = (hx,hy,lean,ff,bf,fh,bh,hd=0) => ({hx,hy,lean,hd,ffx:ff[0],ffy:ff[1],bfx:bf[0],bfy:bf[1],fhx:fh[0],fhy:fh[1],bhx:bh[0],bhy:bh[1]});
const mixPose = (a, b, t) => { const o = {}; for(const k in a) o[k] = a[k] + (b[k] - a[k]) * t; return o; };
const POSE = {
idle : mk(0,34,.12,[12,0],[-13,0],[13,-3],[7,-9]),
crouch: mk(-4,16,.5,[18,0],[-14,0],[15,-4],[8,-10]),
pre : mk(0,26,.25,[14,0],[-12,0],[12,-4],[6,-9]),
jump : mk(0,36,.05,[10,14],[-6,22],[12,0],[6,-6]),
blockS: mk(-3,34,-.05,[10,0],[-14,0],[11,5],[10,-2]),
blockC: mk(-4,16,.45,[18,0],[-14,0],[12,3],[10,-3]),
hitHi : mk(-6,34,-.32,[12,0],[-12,0],[-6,-12],[-10,-8],-.3),
hitLo : mk(-6,18,.1,[16,0],[-14,0],[-8,-8],[-10,-4],-.3),
down : mk(0,30,-1.15,[12,16],[-6,24],[-14,-6],[-18,0],-.2),
lie : mk(0,7,-1.5,[26,5],[22,2],[-8,-2],[-10,-3]),
win : mk(0,34,0,[10,0],[-12,0],[10,25],[-8,-10])
};
/* ------------------------------ Move-Tabelle ------------------------------
su Startup · ac Active · rc Recovery (Frames) · dmg Schaden · hs Hitstun · bs Blockstun
push Rückstoß (px/Frame, klingt ×0.88 ab) · lv Level (high/mid/low) · box Hitbox [x1,y1,x2,y2] lokal
ps/pa Pose Startup/Active · kd Knockdown · vx Vorwärtsbewegung · crouch = geduckte Hurtbox */
function M(su,ac,rc,dmg,hs,bs,push,lv,box,ps,pa,o={}){
return Object.assign({ su,ac,rc,dmg,hs,bs,push,lv,box,ps,pa, stop: dmg < 8 ? 5 : dmg < 14 ? 8 : 11, crouch:false, kd:false, vx:0 }, o);
}
const MOVES = {
// --- stehend ---
st_lp: M(1,3,3, 5,9,6, 0.5,'high',[10,50,40,63], mk(-2,34,.1,[12,0],[-13,0],[6,-8],[6,-9]), mk(2,34,.22,[13,0],[-13,0],[28,0],[7,-9])),
st_mp: M(4,4,8,11,15,11,1.6,'high',[10,46,46,62], mk(-4,34,0,[12,0],[-14,0],[-4,2],[6,-8]), mk(4,34,.3,[16,0],[-14,0],[27,-1],[6,-8])),
st_hp: M(6,5,13,20,19,14,3.0,'high',[8,44,52,62], mk(-6,34,-.12,[10,0],[-12,0],[-6,6],[2,-12]), mk(8,32,.42,[20,0],[-12,0],[27,1],[2,-12]), {vx:.6}),
st_lk: M(2,3,5, 6,11,8, 0.8,'mid', [8,28,42,42], mk(-2,34,-.05,[12,8],[-13,0],[13,-3],[7,-9]), mk(0,34,-.15,[30,24],[-12,0],[13,-3],[7,-9])),
st_mk: M(5,4,9,12,16,12,1.8,'high',[8,40,46,56], mk(-2,34,-.05,[8,12],[-13,0],[13,-3],[7,-9]), mk(-2,35,-.25,[34,38],[-12,0],[10,-6],[4,-10])),
st_hk: M(8,5,15,22,22,15,3.2,'high',[10,46,50,64], mk(-4,34,-.1,[4,22],[-12,0],[10,-6],[4,-10]), mk(4,36,-.5,[40,50],[-12,0],[-4,-2],[-8,2]), {kd:true,vx:.4}),
// --- geduckt ---
cr_lp: M(1,3,3, 4,9,6, 0.5,'high',[10,28,42,42], mk(-4,16,.5,[18,0],[-14,0],[8,-6],[8,-10]), mk(-2,16,.55,[18,0],[-14,0],[27,0],[8,-10]), {crouch:true}),
cr_mp: M(4,4,8,10,15,11,1.5,'high',[10,28,46,42], mk(-4,16,.5,[18,0],[-14,0],[8,-6],[8,-10]), mk(0,16,.6,[20,0],[-14,0],[27,0],[8,-10]), {crouch:true}),
cr_hp: M(6,5,15,22,20,14,2.6,'high',[2,30,32,84], mk(-4,16,.5,[18,0],[-14,0],[8,-6],[8,-10]), mk(2,26,.15,[16,0],[-14,0],[12,26],[6,-8]), {kd:true,launch:6.8}),
cr_lk: M(2,3,4, 4,10,7, 0.8,'low', [8,0,40,10], mk(-4,16,.5,[18,0],[-14,0],[15,-4],[8,-10]), mk(-4,16,.5,[32,4],[-14,0],[15,-4],[8,-10]), {crouch:true}),
cr_mk: M(5,3,9,10,15,11,1.8,'low', [8,0,46,12], mk(-4,16,.5,[18,0],[-14,0],[15,-4],[8,-10]), mk(0,15,.55,[38,4],[-14,0],[15,-4],[8,-10]), {crouch:true}),
cr_hk: M(6,4,18,16,22,14,2.8,'low', [8,0,52,12], mk(0,14,.7,[30,0],[-14,0],[12,-6],[8,-10]), mk(8,12,.9,[46,2],[-16,0],[14,-8],[8,-10]), {kd:true,crouch:true,vx:.8}),
// --- Sprung (aktiv bis zur Landung) ---
a_lp: M(2,12,0, 6,14,10,1.8,'high',[6,44,36,60], mk(0,36,.1,[8,14],[-6,22],[10,-2],[6,-6]), mk(0,36,.15,[8,14],[-6,22],[27,-4],[6,-6])),
a_mp: M(3,12,0,12,17,12,2.2,'high',[6,42,40,60], mk(0,36,.1,[8,14],[-6,22],[10,-2],[6,-6]), mk(0,36,.25,[8,14],[-6,22],[27,-2],[6,-8])),
a_hp: M(4,12,0,18,20,15,2.6,'high',[4,38,44,60], mk(0,36,.1,[8,14],[-6,22],[10,-2],[6,-6]), mk(2,36,.4,[8,14],[-6,22],[27,-6],[4,-12])),
a_lk: M(2,12,0, 6,14,10,1.8,'high',[6,2,38,24], mk(0,36,.05,[10,14],[-6,22],[12,0],[6,-6]), mk(0,35,-.1,[24,6],[-8,20],[12,0],[6,-6])),
a_mk: M(4,12,0,12,17,12,2.2,'high',[6,2,44,26], mk(0,36,.05,[10,14],[-6,22],[12,0],[6,-6]), mk(0,35,-.15,[28,8],[-8,20],[12,0],[6,-6])),
a_hk: M(5,12,0,18,20,15,2.6,'high',[4,4,48,32], mk(0,36,.05,[10,14],[-6,22],[12,0],[6,-6]), mk(-2,36,-.3,[32,14],[-8,18],[12,0],[6,-6]), {kd:true})
};
// --- Spezialmoves & Würfe (Eingaben siehe Fighter.detectSpecial) ---
Object.assign(MOVES, {
// Feuerball ↓↘→ + Schlag (Projektil, ein Ball gleichzeitig, kleiner Chip-Schaden beim Block)
sp_fb: M(11,1,27, 10,16,12,2.0,'mid',[0,0,0,0], mk(-2,30,.25,[14,0],[-14,0],[4,-4],[2,-6]), mk(4,32,.4,[16,0],[-14,0],[24,0],[22,3]), {proj:true,chip:.2,str:1}),
// Shoryuken →↓↘ + Schlag (unverwundbarer Start, Sprung-Uppercut, Launcher)
sp_dp: M(3,8,26, 18,18,18,2.0,'high',[4,6,38,96], mk(-2,28,.3,[12,0],[-12,0],[4,6],[-6,-10]), mk(2,36,.05,[8,16],[-6,22],[8,36],[-6,-8]), {kd:true,launch:7.6,rise:58,riseDur:24,vx:1.1,invu:4,str:2}),
// Wirbeltritt ↓↙← + Tritt (3 Treffer, fliegt nach vorn)
sp_tt: M(9,24,16, 6,14,12,1.0,'high',[4,6,40,52], mk(0,32,.1,[12,0],[-12,0],[10,0],[10,0]), mk(0,36,-.1,[30,22],[-12,20],[-12,4],[18,-2]), {multi:true,gap:8,vx:1.7,rise:14,riseDur:30,chip:.15,kdLast:true,spin:true,str:1}),
// Dash-Angriffe →→ + Schlag / Tritt : Fighter schnellt nach vorn (vx wirkt während Startup + Aktiv)
dash_p: M(7,5,14, 14,17,12,2.2,'high',[10,44,54,62], mk(5,30,.4,[20,0],[-17,0],[8,-2],[4,-8]), mk(11,32,.58,[25,0],[-15,0],[27,0],[2,-10]), {vx:3.4,dash:true,str:1}),
dash_k: M(8,5,16, 15,18,13,2.6,'mid',[8,34,54,58], mk(5,32,.25,[12,12],[-16,0],[8,-6],[4,-10]), mk(8,34,-.32,[44,32],[-14,0],[6,-4],[2,-8]), {vx:3.8,kd:true,dash:true,str:2}),
// Würfe nah dran: →/← + schwerer Schlag oder Tritt (unblockbar; Start = Startup, Aktiv = Haltedauer)
th_f: M(2,16,18, 20,0,0,0,'throw',[0,0,0,0], mk(2,34,.2,[12,0],[-13,0],[26,8],[24,4]), mk(0,34,-.05,[10,0],[-12,0],[16,26],[14,24]), {thr:true,str:2}),
th_b: M(2,16,18, 22,0,0,0,'throw',[0,0,0,0], mk(2,34,.2,[12,0],[-13,0],[26,8],[24,4]), mk(0,34,-.05,[10,0],[-12,0],[16,26],[14,24]), {thr:true,str:2})
});
for(const k in MOVES){ const t = k.slice(-2); MOVES[k].key = k; if(MOVES[k].str === undefined) MOVES[k].str = (t === 'lp' || t === 'lk') ? 0 : (t === 'mp' || t === 'mk') ? 1 : 2; }
/* ------------------------------ Projektile ------------------------------ */
const PROJ = [];
function spawnProj(f, m){
if(PROJ.some(p => p.owner === f)) return; // nur ein Feuerball pro Spieler
const sp = [2.6, 3.3, 4.1][f.spStr];
PROJ.push({ owner:f, x:f.x + f.face * 26, y:f.y + 42, vx:f.face * sp, dir:f.face, move:m, mul:[.8, 1, 1.2][f.spStr], life:220 });
sfx('jump');
}
function updateProj(){
for(let i = PROJ.length - 1; i >= 0; i--){
const p = PROJ[i], o = p.owner === p1 ? p2 : p1;
p.x += p.vx; p.life--;
let dead = p.life <= 0 || p.x < -20 || p.x > STAGE_W + 20;
const hu = o.hurtbox();
if(!dead && hu){
const hb = { x1:p.x - 9, x2:p.x + 9, y1:p.y - 9, y2:p.y + 9 };
if(hb.x1 < hu.x2 && hb.x2 > hu.x1 && hb.y1 < hu.y2 && hb.y2 > hu.y1){
applyHit({ x:p.x, face:p.dir, st:'proj', spMul:p.mul, hitDone:false, vx:0 }, o, p.move, hb, hu, p.owner);
dead = true;
}
}
if(dead) PROJ.splice(i, 1);
}
}
/* ------------------------------ Kämpfer ------------------------------ */
const PAL = [
{ gi:'#f4f4f8', gi2:'#cfd2de', skin:'#e6b48c', hair:'#2a1f1a', band:'#d9343a', belt:'#1d1d27', glove:'#d9343a', shoe:'#2a2a38' },
{ gi:'#d9483d', gi2:'#a9302a', skin:'#c48d63', hair:'#e0b24a', band:'#ffffff', belt:'#f4f4f8', glove:'#2a2a38', shoe:'#f0f0f0' }
];
class Fighter{
constructor(i, name){ this.i = i; this.name = name; this.pal = PAL[i]; this.wins = 0; this.cur = Object.assign({}, POSE.idle); this.ph = 0; this.reset(); }
reset(){
const side = this.i ? 1 : -1;
this.x = STAGE_W / 2 + side * 60; this.y = 0; this.vx = 0; this.vy = 0;
this.face = this.i ? -1 : 1;
this.st = 'ground'; this.t = 0; this.crouch = false; this.walk = 0; this.dir = 0;
this.move = null; this.airMove = null; this.mt = 0; this.hitDone = false; this.stun = 0; this.inv = 0;
this.hp = MAXHP; this.trail = MAXHP; this.trailDelay = 0; this.ko = false; this.win = false;
this.combo = 0; this.comboT = 0; this.comboDmg = 0; this.comboPulse = 0; this.inp = NEUTRAL;
this.hist = []; this.victim = null; this.heldBy = null; this.throwFwd = true; this.juggle = false; this.jugHits = 0; this.spStr = 1; this.spMul = 1;
Object.assign(this.cur, POSE.idle);
}
faceTo(o){ if(Math.abs(o.x - this.x) > 2) this.face = o.x > this.x ? 1 : -1; }
startAttack(key, inp){
this.move = MOVES[key]; this.st = 'attack'; this.t = 0; this.hitDone = false;
this.crouch = this.move.crouch; this.vx = 0; this.walk = 0; this.spMul = 1; inp.buf.fill(0);
sfx('whiff');
}
startThrow(key, inp){
this.move = MOVES[key]; this.st = 'throw'; this.t = 0; this.victim = null; this.throwFwd = key === 'th_f';
this.crouch = false; this.vx = 0; this.walk = 0; inp.buf.fill(0); this.hist.length = 0; sfx('whiff');
}
startSpecial(key, b, inp){
if(key === 'th_f' || key === 'th_b'){ this.startThrow(key, inp); return; }
this.startAttack(key, inp);
this.spStr = b % 3; this.spMul = (key === 'sp_dp' || key.startsWith('dash_')) ? [.85, 1, 1.15][this.spStr] : 1;
this.inv = this.move.invu || 0; this.hist.length = 0;
}
/* Erkennt Bewegungs-Eingaben aus der Richtungshistorie (relativ zur Blickrichtung) + Würfe */
detectSpecial(b, fw, bk, o){
const h = this.hist, n = h.length;
const F = x => x & 1, B = x => x & 2, D = x => x & 4;
const find = steps => { // Teilfolge in den letzten 20 Frames → Index des letzten Schritts, sonst -1
let i = Math.max(0, n - 20);
for(let s = 0; s < steps.length - 1; s++){ while(i < n && !steps[s](h[i])) i++; if(i >= n) return -1; i++; }
for(let j = n - 1; j >= i; j--) if(steps[steps.length - 1](h[j])) return j;
return -1;
};
const cands = [];
if(b < 3){
cands.push([find([x => F(x), x => D(x) && !F(x), x => D(x) && F(x)]), 'sp_dp', 2]); // →↓↘
cands.push([find([x => D(x) && !F(x) && !B(x), x => D(x) && F(x), x => F(x)]), 'sp_fb', 1]); // ↓↘→
} else cands.push([find([x => D(x) && !B(x) && !F(x), x => D(x) && B(x), x => B(x)]), 'sp_tt', 1]); // ↓↙←
let best = null;
for(const c of cands) if(c[0] >= 0 && c[0] >= n - 8 && (!best || c[0] > best[0] || (c[0] === best[0] && c[2] > best[2]))) best = c;
if(best) return best[1];
// Wurf: nah dran, vor/zurück + schwerer Schlag/Tritt
if((b === 2 || b === 5) && (fw || bk) && o.y <= 0 && o.inv <= 0 && Math.abs(o.x - this.x) <= P.throwRange &&
['ground','block','land','prejump','attack'].includes(o.st)) return fw ? 'th_f' : 'th_b';
// Dash: zweimal kurz nach vorn tippen (Pause dazwischen ohne Richtung), dann Schlag/Tritt
let lastF = -1; for(let j = n - 1; j >= Math.max(0, n - 8); j--) if(F(h[j])){ lastF = j; break; }
if(lastF >= 0){
let k = lastF; while(k >= 0 && F(h[k])) k--;
let gap = 0; while(k >= 0 && !F(h[k])){ if(D(h[k]) || B(h[k])){ gap = -1; break; } gap++; k--; }
if(gap >= 1 && gap <= 10 && k >= 0 && F(h[k])) return b < 3 ? 'dash_p' : 'dash_k';
}
return null;
}
curMove(){ return this.st === 'attack' ? this.move : (this.st === 'air' ? this.airMove : null); }
crouchNow(){ return this.st === 'attack' ? this.move.crouch : this.crouch; }
update(inp, o){
this.inp = inp; this.t++;
if(this.inv > 0) this.inv--;
if(this.trailDelay > 0) this.trailDelay--; else this.trail = Math.max(this.hp, this.trail - .8);
if(this.comboPulse > 0) this.comboPulse--;
if(this.comboT > 0 && --this.comboT === 0){ this.combo = 0; this.comboDmg = 0; }
const fw = this.face === 1 ? inp.r : inp.l, bk = this.face === 1 ? inp.l : inp.r;
this.hist.push((fw ? 1 : 0) | (bk ? 2 : 0) | (inp.d ? 4 : 0) | (inp.u ? 8 : 0));
if(this.hist.length > 24) this.hist.shift();
// Beim Wechsel zurück in 'ground' wird im selben Frame schon die nächste Aktion ausgewertet (kein verlorener Frame)
const before = this.st;
this.step(inp, o, fw, bk);
if(before !== 'ground' && this.st === 'ground') this.step(inp, o, fw, bk);
}
step(inp, o, fw, bk){
switch(this.st){
case 'ground': {
this.faceTo(o); this.vx = 0;
const b = firstBuf(inp);
let sp = inp.spec || null;
if(!sp && b >= 0) sp = this.detectSpecial(b, fw, bk, o);
if(sp){ inp.spec = null; this.startSpecial(sp, b < 0 ? 1 : b, inp); break; }
if(b >= 0){ this.startAttack((inp.d ? 'cr_' : 'st_') + NAMES[b], inp); break; }
if(inp.u){ this.st = 'prejump'; this.t = 0; this.crouch = false; this.walk = 0; break; }
if(inp.d){ this.crouch = true; this.walk = 0; break; }
this.crouch = false;
this.walk = fw ? 1 : bk ? -1 : 0;
this.x += this.walk > 0 ? P.walkF * this.face : this.walk < 0 ? -P.walkB * this.face : 0;
break;
}
case 'prejump':
this.dir = fw ? 1 : bk ? -1 : 0;
if(this.t >= 4){
this.st = 'air'; this.t = 0; this.y = .01; this.vy = P.jumpV;
this.vx = this.dir * (this.dir > 0 ? P.jumpFwd : P.jumpBack) * this.face; // Richtung wird beim Absprung festgelegt
this.airMove = null; this.hitDone = false; this.mt = 0; this.spMul = 1; sfx('jump');
}
break;
case 'air':
this.vy -= P.grav; this.y += this.vy; this.x += this.vx;
if(this.airMove) this.mt++;
else { const b = firstBuf(inp); if(b >= 0){ this.airMove = MOVES['a_' + NAMES[b]]; this.mt = 0; this.hitDone = false; inp.buf.fill(0); sfx('whiff'); } }
if(this.y <= 0 && this.vy < 0){ this.y = 0; this.vx = 0; this.vy = 0; this.airMove = null; this.st = 'land'; this.t = 0; }
break;
case 'land':
this.faceTo(o); if(this.t >= 3) this.st = 'ground';
break;
case 'attack': {
const m = this.move;
if(m.proj && this.t === m.su) spawnProj(this, m);
if(m.multi && this.t > m.su && this.t <= m.su + m.ac && (this.t - m.su - 1) % m.gap === 0) this.hitDone = false; // nächster Treffer
if(m.rise){ const u = Math.min(1, Math.max(0, (this.t - m.su + 1) / m.riseDur)); this.y = m.rise * Math.sin(Math.PI * u); }
if(m.vx && this.t <= m.su + m.ac) this.x += m.vx * this.face;
this.x += this.vx; this.vx *= P.slide;
if(this.t >= m.su + m.ac + m.rc){ this.st = 'ground'; this.move = null; this.vx = 0; this.y = 0; }
break;
}
case 'throw': {
const m = this.move;
if(this.t === m.su){
const ok = o.y <= 0 && o.inv <= 0 && Math.abs(o.x - this.x) <= P.throwRange && ['ground','block','land','prejump','attack'].includes(o.st);
if(o.st === 'throw' && !o.victim && o.t <= o.move.su + 2 && Math.abs(o.x - this.x) <= P.throwRange + 6){
// Wurf-Konter: beide lösen sich voneinander
[[this, o], [o, this]].forEach(([f, g]) => { f.st = 'hit'; f.stun = 16; f.t = 0; f.move = null; f.vx = (Math.sign(f.x - g.x) || -f.face) * 3; });
sparks.push({ x:(this.x + o.x) / 2, y:40, t:0, type:'block' }); sfx('block'); G.hitstop = Math.max(G.hitstop, 6);
break;
}
if(ok){
this.victim = o; o.st = 'held'; o.heldBy = this; o.t = 0; o.move = null; o.airMove = null; o.crouch = false; o.vx = 0; o.vy = 0;
G.hitstop = Math.max(G.hitstop, 6); sparks.push({ x:o.x, y:40, t:0, type:'hit' }); sfx('hitM');
} else this.t = m.su + m.ac - 1; // Fehlwurf: Haltephase überspringen, Recovery bleibt
}
const v = this.victim;
if(v && this.t > m.su && this.t <= m.su + m.ac){
const u = (this.t - m.su) / m.ac;
// → : Gegner bleibt vorn, wird hochgehoben und nach VORN geschleudert · ← : wird über die Schulter nach HINTEN geworfen
v.x = this.x + this.face * (this.throwFwd ? 16 + 10 * u : 16 * Math.cos(Math.PI * u));
v.y = 34 * Math.sin(Math.PI * Math.min(1, u)); v.face = -this.face;
}
if(v && this.t === m.su + m.ac){
const dmg = Math.max(1, Math.round(m.dmg * P.dmgMul));
v.hp = Math.max(0, v.hp - dmg); v.trailDelay = 28; v.ko = v.hp <= 0;
v.st = 'down'; v.t = 0; v.heldBy = null; v.y = Math.max(v.y, 2); v.vy = v.ko ? 6.2 : 5.5; v.juggle = false;
v.vx = this.face * (this.throwFwd ? 1 : -1) * 4.6 * P.throwFling; v.vy = (v.ko ? 7 : 6.4);
this.combo = 1; this.comboDmg = dmg; this.comboPulse = 8; this.comboT = P.comboHold;
this.victim = null; G.hitstop = Math.max(G.hitstop, v.ko ? 26 : 10); G.shake = Math.max(G.shake, 5);
sparks.push({ x:v.x, y:v.y + 30, t:0, type:'hit', big:true }); sfx(v.ko ? 'ko' : 'hitH');
}
if(this.t >= m.su + m.ac + m.rc){ this.st = 'ground'; this.victim = null; this.move = null; }
break;
}
case 'held':
if(!this.heldBy || this.heldBy.st !== 'throw'){ this.st = 'ground'; this.heldBy = null; }
break;
case 'hit': case 'block':
this.x += this.vx; this.vx *= P.slide;
if(--this.stun <= 0){ this.st = 'ground'; this.vx = 0; }
break;
case 'down':
this.vy -= P.grav; this.y += this.vy; this.x += this.vx;
if(this.y <= 0 && this.vy < 0){ this.y = 0; this.vy = 0; this.vx = 0; this.st = 'lie'; this.t = 0; this.juggle = false; G.shake = Math.max(G.shake, 3); }
break;
case 'lie':
if(!this.ko && this.t >= 28){ this.st = 'getup'; this.t = 0; this.inv = 18; }
break;
case 'getup':
if(this.t >= 18){ this.st = 'ground'; this.faceTo(o); }
break;
}
}
hitbox(){
const m = this.curMove(); if(!m || this.hitDone || m.proj || m.thr) return null;
if(this.st === 'attack'){ if(!(this.t > m.su && this.t <= m.su + m.ac)) return null; }
else if(this.mt < m.su) return null;
const b = m.box;
const x1 = this.face > 0 ? this.x + b[0] : this.x - b[2], x2 = this.face > 0 ? this.x + b[2] : this.x - b[0];
return { x1, x2, y1: this.y + b[1], y2: this.y + b[3] };
}
hurtbox(){
if(this.inv > 0 || this.st === 'lie' || this.st === 'getup' || this.st === 'held') return null;
if(this.st === 'down'){ // Juggle: nach einem Launcher noch begrenzt treffbar
if(!(this.juggle && this.y > 10 && this.jugHits < P.juggleMax)) return null;
return { x1:this.x - 12, x2:this.x + 12, y1:this.y + 4, y2:this.y + 60 };
}
if(this.y > 0) return { x1:this.x - 12, x2:this.x + 12, y1:this.y + 6, y2:this.y + 66 };
return { x1:this.x - 13, x2:this.x + 13, y1:0, y2: this.crouchNow() ? 52 : 74 };
}
grounded(){ return this.y <= 0 && !['down','lie','getup','held'].includes(this.st); }
/* Ziel-Pose bestimmen und weich dahin interpolieren */
animate(){
let tg, k = .5;
switch(this.st){
case 'ground':
if(this.win) tg = POSE.win;
else if(this.crouch) tg = POSE.crouch;
else {
tg = Object.assign({}, POSE.idle);
const b = Math.sin(G.f * .07); tg.hy += b * .8; tg.fhy += b * .8;
if(this.walk){
this.ph += .2 * this.walk;
tg.ffx += Math.sin(this.ph) * 8; tg.ffy += Math.max(0, Math.cos(this.ph)) * 5;
tg.bfx -= Math.sin(this.ph) * 8; tg.bfy += Math.max(0, -Math.cos(this.ph)) * 5;
tg.hy -= Math.abs(Math.sin(this.ph)) * 1.2;
}
}
break;
case 'prejump': tg = POSE.pre; break;
case 'air': tg = this.airMove ? (this.mt < this.airMove.su ? this.airMove.ps : this.airMove.pa) : POSE.jump; break;
case 'land': tg = POSE.crouch; break;
case 'attack': {
// Ausfahren ist sofort sichtbar: Startup blendet direkt Richtung Active-Pose, Active schnappt fast ohne Verzögerung
const m = this.move, t = this.t;
if(t <= m.su){ tg = mixPose(m.ps, m.pa, t / m.su); k = m.su <= 2 ? 1 : .85; }
else if(t <= m.su + m.ac + Math.ceil(m.rc * .3)){
tg = m.pa; k = m.su <= 2 ? 1 : .95;
if(m.spin){ const w = Math.sin(t * .9); tg = Object.assign({}, m.pa, { lean:w * .7, ffy:20 + w * 12, bfy:20 - w * 12 }); }
}
else { tg = m.crouch ? POSE.crouch : POSE.idle; k = .5; }
break;
}
case 'throw': { const m = this.move; tg = this.t <= m.su ? m.ps : m.pa; k = .6; break; }
case 'held': {
const hb = this.heldBy, u = hb && hb.move ? Math.min(1, Math.max(0, (hb.t - hb.move.su) / hb.move.ac)) : 0;
tg = Object.assign({}, POSE.down, { lean:-1.2 - u * (hb && hb.throwFwd ? .5 : 2.4), hy:34 }); k = .5; break;
}
case 'hit': tg = this.crouch ? POSE.hitLo : POSE.hitHi; k = .6; break;
case 'block': tg = this.crouch ? POSE.blockC : POSE.blockS; k = .6; break;
case 'down': tg = POSE.down; k = .25; break;
case 'lie': tg = POSE.lie; k = .3; break;
case 'getup': tg = POSE.crouch; break;
}
const c = this.cur;
for(const key in tg) c[key] += (tg[key] - c[key]) * k;
}
}
const p1 = new Fighter(0, 'KAI'), p2 = new Fighter(1, 'MIRA');
const FIGHTERS = [p1, p2];
/* ------------------------------ Hit-Auflösung ------------------------------ */
const bounds = () => ({ lo: Math.max(12, G.cam + 14), hi: Math.min(STAGE_W - 12, G.cam + W - 14) });
const stopFor = m => [P.stopL, P.stopM, P.stopH][m.str];
function applyHit(a, d, m, hb, hu, own = a){
a.hitDone = true;
if(d.victim){ d.victim.st = 'ground'; d.victim.heldBy = null; d.victim = null; } // Wurf wird unterbrochen
const away = Math.sign(d.x - a.x) || -a.face;
const backIn = away > 0 ? d.inp.r : d.inp.l;
const blockable = d.y <= 0 && (d.st === 'ground' || d.st === 'block' || d.st === 'land');
const blocked = blockable && backIn && (m.lv !== 'low' || d.inp.d);
const cx = (Math.max(hb.x1, hu.x1) + Math.min(hb.x2, hu.x2)) / 2;
const cy = (Math.max(hb.y1, hu.y1) + Math.min(hb.y2, hu.y2)) / 2;
const bnd = bounds();
const atWall = (away > 0 && d.x >= bnd.hi - 2) || (away < 0 && d.x <= bnd.lo + 2);
const airHit = a.st === 'air'; // Sprungangriff
const pm = P.pushMul * (airHit ? P.airPushMul : 1); // Rückstoß-Faktor
const jug = d.st === 'down' && d.juggle; // Juggle-Treffer
const dmg = Math.max(1, Math.round(m.dmg * P.dmgMul * (a.spMul || 1) * (jug ? P.juggleScale : 1)));
const heavy = m.str === 2;
if(blocked){
d.crouch = !!d.inp.d; d.st = 'block'; d.stun = Math.max(1, m.bs + P.blockstunAdd); d.t = 0; d.move = null;
d.vx = away * m.push * pm * .8;
if(m.chip){ d.hp = Math.max(1, d.hp - Math.max(1, Math.round(dmg * m.chip))); d.trailDelay = 28; } // Chip-Schaden (Specials)
if(atWall && a.st === 'attack') a.vx = -away * m.push * pm * .8;
G.hitstop = Math.max(G.hitstop, Math.max(2, stopFor(m) - 2));
sparks.push({ x:cx, y:cy, t:0, type:'block' });
sfx('block');
return;
}
const air = d.y > 0, wasHit = d.st === 'hit' || jug;
d.crouch = d.crouchNow();
d.hp = Math.max(0, d.hp - dmg); d.trailDelay = 28;
own.combo = wasHit ? own.combo + 1 : 1; own.comboDmg = wasHit ? own.comboDmg + dmg : dmg;
own.comboPulse = 8; own.comboT = P.comboHold;
const ko = d.hp <= 0;
const kd = m.kd || (m.kdLast && a.st === 'attack' && a.t >= m.su + m.ac - m.gap + 1);
d.move = null; d.airMove = null; d.t = 0;
if(ko || kd || air){
d.st = 'down'; d.ko = ko; d.y = Math.max(d.y, 1);
d.vy = ko ? 6.2 : (air ? 4.4 : 5.4);
d.vx = away * (kd || ko ? 2.4 : 1.6) * (airHit ? Math.max(1, P.airPushMul * .75) : 1);
if(m.launch){ d.vy = m.launch; d.vx = away * .3; d.juggle = true; d.jugHits = 0; } // Launcher (Uppercut/Shoryuken)
else if(jug) d.jugHits++;
} else {
d.st = 'hit'; d.stun = Math.max(1, m.hs + P.hitstunAdd); d.vx = away * m.push * pm;
if(atWall && a.st === 'attack') a.vx = -away * m.push * pm * .9;
}
G.hitstop = Math.max(G.hitstop, ko ? 26 : stopFor(m));
G.shake = Math.max(G.shake, ko ? 7 : heavy ? 4 : m.str === 1 ? 2 : 0);
sparks.push({ x:cx, y:cy, t:0, type:'hit', big:heavy });
sfx(ko ? 'ko' : heavy ? 'hitH' : m.str === 1 ? 'hitM' : 'hitL');
}
function resolveHits(){
const list = [];
[[p1, p2], [p2, p1]].forEach(([a, d]) => {
const hb = a.hitbox(); if(!hb) return;
const hu = d.hurtbox(); if(!hu) return;
if(hb.x1 < hu.x2 && hb.x2 > hu.x1 && hb.y1 < hu.y2 && hb.y2 > hu.y1) list.push([a, d, a.curMove(), hb, hu]);
});
list.forEach(([a, d, m, hb, hu]) => applyHit(a, d, m, hb, hu));
}
/* Pushbox: Körper schieben sich gegenseitig, in der Ecke weicht der Freie aus */
function separate(){
const clampAll = () => { const b = bounds(); FIGHTERS.forEach(f => f.x = Math.min(b.hi, Math.max(b.lo, f.x))); };
clampAll();
if(p1.grounded() && p2.grounded()){
for(let pass = 0; pass < 2; pass++){
const d = p2.x - p1.x, dir = d >= 0 ? 1 : -1, ov = 24 - Math.abs(d);
if(ov <= 0) break;
if(pass === 0){ p1.x -= dir * ov / 2; p2.x += dir * ov / 2; }
else {
const b = bounds();
// einer klebt an der Wand → der andere nimmt den Rest
if(p1.x <= b.lo + .01 || p1.x >= b.hi - .01) p2.x = p1.x + dir * 24;
else p1.x = p2.x - dir * 24;
}
clampAll();
}
}
}
/* ------------------------------ Runden-Ablauf ------------------------------ */
function startRound(){
FIGHTERS.forEach(f => f.reset());
sparks = []; PROJ.length = 0; G.hitstop = 0; G.shake = 0; G.timer = 99; G.tf = 0; G.winner = null;
G.cam = (STAGE_W - W) / 2;
setMode('intro');
setMsg(p1.wins === 1 && p2.wins === 1 ? 'FINAL ROUND' : 'ROUND ' + G.round, 70, '#ffe066');
}
function newMatch(){ p1.wins = p2.wins = 0; G.round = 1; startRound(); }
function endRound(timeup){
let w = null;
if(p1.hp > 0 && p2.hp > 0 || (p1.hp <= 0 && p2.hp <= 0)){
if(timeup) w = p1.hp > p2.hp ? p1 : p2.hp > p1.hp ? p2 : null;
} else w = p1.hp > 0 ? p1 : p2;
G.winner = w;
if(w) w.wins++; else { p1.wins++; p2.wins++; }
setMode('ko'); setMsg(timeup ? 'TIME UP' : 'K.O.', 90, '#ff5a3d');
}
function tick(){
G.f++;
if(G.paused) return;
pollInput(0, G.hitstop <= 0); pollInput(1, G.hitstop <= 0); tapped.clear();
sparks.forEach(s => s.t++); sparks = sparks.filter(s => s.t <= 10);
if(G.shake > 0) G.shake -= .25;
if(G.msgT > 0) G.msgT--;
if(G.toastT > 0) G.toastT--;
if(G.hitstop > 0){ G.hitstop--; return; }
const live = G.mode === 'fight';
p1.update(live ? IN[0] : NEUTRAL, p2);
let in2 = live ? IN[1] : NEUTRAL;
if(live && G.cpu){ aiThink(p2, p1); aiAir(p2, p1); in2 = AI.inp; }
p2.update(in2, p1);
separate();
resolveHits();
updateProj();
FIGHTERS.forEach(f => f.animate());
const tx = Math.min(STAGE_W - W, Math.max(0, (p1.x + p2.x) / 2 - W / 2));
G.cam += (tx - G.cam) * .25;
G.t++;
if(G.mode === 'intro' && G.t >= 70){ setMode('fight'); setMsg('FIGHT!', 50, '#ff6a3d'); }
else if(G.mode === 'fight'){
if(++G.tf >= 60){ G.tf = 0; G.timer--; }
if(p1.hp <= 0 || p2.hp <= 0) endRound(false);
else if(G.timer <= 0) endRound(true);
}
else if(G.mode === 'ko'){
if(G.t === 90){
if(G.winner){ G.winner.win = true; setMsg(G.winner.name + ' WINS', 110, '#ffe066'); }
else setMsg('DRAW GAME', 110, '#ffe066');
}
if(G.t >= 220){
if(p1.wins >= 2 || p2.wins >= 2 || G.round >= 3) setMode('match');
else { G.round++; startRound(); }
}
}
}
/* ------------------------------ CPU-Gegner (einfache Verhaltens-KI für Spieler 2) ------------------------------
Reagiert mit Reaktionsverzögerung auf Angriffe (blockt mit Wahrscheinlichkeit), nutzt Anti-Air gegen Sprünge,
pokt auf mittlerer Distanz, drückt nah mit leichten Normals/Sweeps und springt gelegentlich an. */
const AILV = [
{ name:'EASY', react:14, blockP:.25, aaP:.25, cool:[22, 55], jumpP:.05 },
{ name:'NORMAL', react:9, blockP:.5, aaP:.5, cool:[12, 34], jumpP:.08 },
{ name:'HARD', react:5, blockP:.75, aaP:.75, cool:[6, 20], jumpP:.12 }
];
const AI = { inp:newInput(), lv:1, plan:'approach', planT:0, cool:0, lastMove:null, blockRoll:false, crouchBlock:false, seenAir:false, aaRoll:false, jumpIn:false };
const rr = (a, b) => a + Math.floor(Math.random() * (b - a + 1));
const pickW = list => { let t = list.reduce((s, x) => s + x.w, 0) * Math.random(); for(const x of list){ if((t -= x.w) <= 0) return x; } return list[0]; };
function aiThink(me, o){
const I = AI.inp, L = AILV[AI.lv];
I.u = I.d = I.l = I.r = 0; I.spec = null;
for(let k = 0; k < 6; k++) I.buf[k] = Math.max(0, I.buf[k] - 1);
if(AI.cool > 0) AI.cool--;
const dx = o.x - me.x, dist = Math.abs(dx);
const TW = dx > 0 ? 'r' : 'l', AW = dx > 0 ? 'l' : 'r'; // physisch zum / vom Gegner
const press = (b, d = 0) => { I.buf[b] = 2; I.d = d; AI.cool = rr(L.cool[0], L.cool[1]); };
// --- Gegner-Angriff erkennen (Reaktionszeit!) ---
const om = o.curMove();
if(om !== AI.lastMove){ AI.lastMove = om; AI.blockRoll = Math.random() < L.blockP; AI.crouchBlock = Math.random() < .4; }
if(o.st === 'air' && !AI.seenAir){ AI.seenAir = true; AI.aaRoll = Math.random() < L.aaP; }
if(o.st !== 'air') AI.seenAir = false;
if(me.st === 'prejump' && AI.jumpIn){ I[TW] = 1; return I; } // Sprungrichtung beim Absprung halten
const canAct = me.st === 'ground' || me.st === 'block' || me.st === 'land';
// Anti-Air: Gegner springt an → geduckter schwerer Schlag
if(me.st === 'ground' && o.st === 'air' && !o.airMove && o.y > 12 && AI.aaRoll && dist > 18 && dist < 62 && o.vy < 3){
if(Math.random() < .5){ I.spec = 'sp_dp'; AI.cool = rr(L.cool[0], L.cool[1]); } else press(2, 1);
return AI.inp;
}
// Blocken
const threat = om && ((o.st === 'attack' && o.t >= L.react && dist < 90) || (o.st === 'air' && dist < 70));
if(threat && AI.blockRoll && canAct){
I[AW] = 1; I.d = (om.lv === 'low' || AI.crouchBlock) ? 1 : 0;
if(om.lv === 'low') I.d = 1;
return I;
}
if(!canAct) return I;
// Sprung-Angriff in der Luft
if(me.st === 'air'){ return I; } // (Luftangriffe werden unten im Sprung gesetzt)
// --- Offensive ---
if(me.st === 'ground' && AI.cool <= 0 && !om){
if(dist < P.throwRange - 4 && (o.st === 'block' || Math.random() < .04) && Math.random() < .5){
I.spec = Math.random() < .5 ? 'th_f' : 'th_b'; AI.cool = rr(L.cool[0] + 10, L.cool[1] + 20); return I;
}
if(dist < 46){
const c = pickW([{b:0,d:0,w:30},{b:3,d:0,w:12},{b:1,d:0,w:12},{b:4,d:0,w:7},{b:0,d:1,w:12},{b:3,d:1,w:10},{b:5,d:1,w:6},{b:2,d:0,w:6}]);
press(c.b, c.d); return I;
}
if(dist < 78){
const c = pickW([{b:4,d:0,w:18},{b:4,d:1,w:16},{b:5,d:1,w:12},{b:5,d:0,w:8},{b:-1,d:0,w:24}]);
if(c.b >= 0){ press(c.b, c.d); return I; }
}
}
// Nach der Abwehr: wenn der Gegner Recovery hat, sofort bestrafen
if(me.st === 'block' && !om && dist < 50 && AI.cool <= 0){ press(0, 0); return I; }
// --- Bewegungsplan ---
if(--AI.planT <= 0){
const far = dist > 110;
const c = pickW(far ? [{p:'approach',w:60},{p:'jump',w:L.jumpP * 100},{p:'wait',w:10},{p:'fire',w:14}]
: [{p:'approach',w:45},{p:'wait',w:25},{p:'retreat',w:20},{p:'jump',w:L.jumpP * 100},{p:'fire',w:6}]);
AI.plan = c.p; AI.planT = rr(8, 36);
}
switch(AI.plan){
case 'approach': I[TW] = 1; break;
case 'retreat': I[AW] = 1; break;
case 'fire': if(me.st === 'ground' && !PROJ.some(q => q.owner === me)){ I.spec = 'sp_fb'; AI.cool = rr(30, 60); } AI.plan = 'wait'; AI.planT = 24; break;
case 'jump': if(me.st === 'ground'){ I.u = 1; I[TW] = 1; AI.jumpIn = true; AI.plan = 'wait'; AI.planT = 30; } break;
}
return I;
}
// Luftangriff nachlegen (separat, weil dann me.st === 'air')
function aiAir(me, o){
if(me.st === 'air' && !me.airMove && AI.jumpIn && Math.abs(o.x - me.x) < 70 && me.vy < 2){
AI.inp.buf[[2, 5, 4, 1, 3][rr(0, 4)]] = 2; AI.jumpIn = false;
}
if(me.st !== 'air' && me.st !== 'prejump') AI.jumpIn = AI.jumpIn && me.st === 'ground';
}
/* ------------------------------ Stage ------------------------------ */
const rnd = (() => { let s = 7; return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; }; })();
const ST = { clouds:[], hills:[], crowd:[] };
for(let i = 0; i < 12; i++) ST.clouds.push({ x:rnd() * 520, y:14 + rnd() * 52, w:28 + rnd() * 40 });
for(let x = 0; x < 480; x += 8) ST.hills.push(86 + Math.sin(x * .02) * 14 + Math.sin(x * .071) * 7 + rnd() * 4);
const CROWD_COLS = ['#e8c07a','#c0504d','#5b7fb8','#7aa06a','#d9d3c4','#8a6aa8'];
for(let x = 0; x < 580; x += 9) ST.crowd.push({ x:x + rnd() * 3, h:10 + rnd() * 7, c:CROWD_COLS[(rnd() * CROWD_COLS.length) | 0], ph:rnd() * 6.28 });
const lerpCol = (a, b, t) => `rgb(${a.map((v, i) => Math.round(v + (b[i] - v) * t)).join(',')})`;
const px = (x, y, w, h, c) => { ctx.fillStyle = c; ctx.fillRect(Math.round(x), Math.round(y), Math.round(w), Math.round(h)); };
/* ------------------------------ Parallax-Ebenen ------------------------------
Die Stage besteht aus 5 Ebenen (1–4 hinter den Kämpfern, 5 davor). Jede Ebene ist ein Bild mit Höhe 224 px und der Breite
384 + 256 × Parallax-Faktor (Kamerahub = 256 px). Faktor 0 = steht fest am Bildschirm, 1 = scrollt mit der Kampfebene,
>1 = scrollt schneller (Vordergrund). Eigene PNGs ersetzen die jeweilige Standard-Ebene (Panel → Eigene Grafiken). */
let SW = W; // Breite der Ebene, die gerade gezeichnet wird (beim Export > Bildschirm)
const SCROLL = STAGE_W - W;
const LAYERS = [
{ id:'bg1', name:'Himmel / Ferne', f:.10 },
{ id:'bg2', name:'Horizont', f:.30 },
{ id:'bg3', name:'Mittelgrund', f:.70 },
{ id:'bg4', name:'Kampfebene / Boden', f:1.0 },
{ id:'bg5', name:'Vordergrund (vor den Kaempfern)', f:1.3 }
];
const layerW = f => Math.ceil(W + SCROLL * f);
const BGIMG = [null, null, null, null, null], BGMETA = ['', '', '', '', ''];
const BGCFG = LAYERS.map(L => ({ f:L.f, hide:false }));
const PROC = [
function(){ // 1 Himmel, Sonne, Wolken
for(let i = 0; i < 14; i++) px(0, i * 9, SW, 9, lerpCol([104,184,228], [226,243,252], i / 13));
ctx.fillStyle = '#fff6c9'; ctx.beginPath(); ctx.arc(290, 42, 15, 0, 7); ctx.fill();
ST.clouds.forEach(c => { const x = c.x / 520 * (SW + 60) - 40; px(x, c.y, c.w, 7, '#ffffff'); px(x + 6, c.y - 4, c.w * .6, 5, '#ffffff'); });
},
function(){ // 2 Hügel, Meer, Schiff
ctx.fillStyle = '#9db9d6'; ctx.beginPath(); ctx.moveTo(0, 130);
ST.hills.forEach((h, i) => ctx.lineTo(i * 8, h + 30));
ctx.lineTo(480, 130); ctx.closePath(); ctx.fill();
px(0, 126, SW, 30, '#5b9ec9');
for(let i = 0; i < 6; i++){
const y = 130 + i * 5, off = G.f * .3 * (i % 2 ? 1 : -1) + i * 37;
for(let x = -40; x < SW + 40; x += 48) px(((x + off) % (SW + 80)) - 20, y, 14, 1, '#9fd0ea');
}
const sx = 120;
ctx.fillStyle = '#4b5a6e'; ctx.beginPath(); ctx.moveTo(sx, 128); ctx.lineTo(sx + 150, 128); ctx.lineTo(sx + 136, 144); ctx.lineTo(sx + 14, 144); ctx.closePath(); ctx.fill();
px(sx + 40, 114, 44, 14, '#e8e8ee'); px(sx + 52, 106, 14, 8, '#d9483d'); px(sx + 100, 100, 3, 28, '#6a778a');
for(let i = 0; i < 5; i++) px(sx + 44 + i * 8, 119, 4, 4, '#4b5a6e');
},
function(){ // 3 Publikum, Hafenmauer, Poller
ST.crowd.forEach(p => {
const x = p.x, bob = Math.round(Math.sin(G.f * .08 + p.ph) * 1.5);
if(x > SW + 10) return;
px(x, 146 - p.h + bob, 7, p.h + 6, p.c);
ctx.fillStyle = '#e6b48c'; ctx.beginPath(); ctx.arc(Math.round(x + 3.5), 144 - p.h + bob, 3.2, 0, 7); ctx.fill();
});
px(0, 150, SW, 28, '#a39a90'); px(0, 148, SW, 3, '#cfc6ba');
for(let r = 0; r < 2; r++) for(let x = 0; x < SW + 24; x += 24) px(x + (r ? 12 : 0), 156 + r * 11, 1, 10, '#8a8178');
px(0, 166, SW, 1, '#8a8178');
for(let x = 0; x < STAGE_W; x += 96){ const sx2 = x + 30; if(sx2 < SW){ px(sx2, 142, 7, 8, '#3a3a46'); px(sx2 - 1, 141, 9, 2, '#52525e'); } }
},
function(){ // 4 Boden + Fässer (hier stehen die Kämpfer, Fußlinie y = 196)
px(0, 178, SW, H - 178, '#cba878');
for(let r = 0; r < 6; r++){
const y = 178 + r * 8; px(0, y, SW, 1, '#b48e5f');
for(let x = 0; x < SW + 40; x += 40) px(x + (r % 2 ? 20 : 0), y, 1, 8, '#b48e5f');
}
px(0, 214, SW, 10, '#b48e5f');
[14, 32, STAGE_W - 14, STAGE_W - 32].forEach((x, i) => {
const y = 174 + (i % 2) * 2;
px(x - 8, y, 16, 24, '#8a5a34'); px(x - 8, y + 5, 16, 2, '#4a2f1b'); px(x - 8, y + 16, 16, 2, '#4a2f1b'); px(x - 8, y, 16, 2, '#a6724a');
});
},
function(){ // 5 Vordergrund – nur als Beispiel (im Spiel leer, solange kein eigenes Bild geladen ist)
for(let x = 6; x < SW; x += 46){
const h = 10 + ((x * 13) % 17);
ctx.fillStyle = '#3f6b3a';
ctx.beginPath(); ctx.moveTo(x, H); ctx.lineTo(x + 3, H - h); ctx.lineTo(x + 6, H); ctx.fill();
ctx.beginPath(); ctx.moveTo(x + 4, H); ctx.lineTo(x + 9, H - h * .7); ctx.lineTo(x + 12, H); ctx.fill();
}
px(80, 40, 6, H - 40, '#2a2a38'); px(70, 36, 26, 6, '#2a2a38'); px(72, 42, 22, 3, '#ffe9a0');
}
];
function drawLayer(k){
const cfg = BGCFG[k], img = BGIMG[k];
if(cfg.hide) return;
const ox = Math.round(-G.cam * cfg.f);
if(img){ for(let x = ox; x < W; x += img.width) if(x + img.width > 0) ctx.drawImage(img, x, 0); return; }
if(k === 4) return;
ctx.save(); ctx.translate(ox, 0); SW = layerW(cfg.f); PROC[k](); SW = W; ctx.restore();
}
function drawStage(){
ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, W, H);
for(let k = 0; k < 4; k++) drawLayer(k);
}
/* ---- Export: Beispiel-Ebene (die Standard-Stage) und Schablone (Maße, Raster, Fußlinie, Kamera-Fenster) ---- */
const mkCanvas = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; };
function renderLayerExample(k, f){
const w = layerW(f), c = mkCanvas(w, H), real = ctx;
ctx = c.getContext('2d'); SW = w;
try{ PROC[k](); } finally { ctx = real; SW = W; }
return c;
}
function renderLayerGuide(k, f){
const w = layerW(f), c = mkCanvas(w, H), g = c.getContext('2d');
g.fillStyle = 'rgba(0,170,220,.16)';
for(let x = 32; x < w; x += 32) g.fillRect(x, 0, 1, H);
for(let y = 32; y < H; y += 32) g.fillRect(0, y, w, 1);
g.fillStyle = 'rgba(0,170,220,.45)';
for(let x = 64; x < w; x += 64){ g.fillRect(x, 0, 1, H); text(String(x), x + 3, H - 6, 8, '#0090c0', 'left', null, g); }
for(let y = 64; y < H; y += 64){ g.fillRect(0, y, w, 1); text(String(y), 3, y - 5, 8, '#0090c0', 'left', null, g); }
g.fillStyle = 'rgba(230,40,140,.95)'; g.fillRect(0, GROUND, w, 1);
text('FUSSLINIE Y=' + GROUND, 4, GROUND + 7, 8, '#e6288c', 'left', null, g);
g.strokeStyle = 'rgba(255,140,0,.95)'; g.lineWidth = 1; g.setLineDash([4, 3]);
g.strokeRect(.5, 1.5, W - 1, H - 3);
g.strokeRect(Math.round(SCROLL * f) + .5, 3.5, W - 1, H - 7);
g.setLineDash([]);
text('SICHT KAMERA LINKS', 6, 10, 8, '#e67e00', 'left', null, g);
text('SICHT KAMERA RECHTS', Math.round(SCROLL * f) + 6, 20, 8, '#e67e00', 'left', null, g);
g.strokeStyle = 'rgba(0,170,220,.95)'; g.setLineDash([]); g.strokeRect(.5, .5, w - 1, H - 1);
text('EBENE ' + (k + 1) + ': ' + LAYERS[k].name.toUpperCase(), 6, 38, 8, '#0090c0', 'left', null, g);
text(w + ' X ' + H + ' PX PARALLAX ' + f.toFixed(2), 6, 49, 8, '#0090c0', 'left', null, g);
return c;
}
/* ------------------------------ Figuren zeichnen ------------------------------ */
function ik(a, t, l1, l2, bend){
const dx = t[0] - a[0], dy = t[1] - a[1], d = Math.hypot(dx, dy) || .001;
const dd = Math.min(d, l1 + l2 - .5), ux = dx / d, uy = dy / d;
const aa = (dd * dd + l1 * l1 - l2 * l2) / (2 * dd), h = Math.sqrt(Math.max(0, l1 * l1 - aa * aa));
const mx = a[0] + ux * aa, my = a[1] + uy * aa;
return { k:[mx - uy * h * bend, my + ux * h * bend], end:[a[0] + ux * dd, a[1] + uy * dd] };
}
const OUT = '#1c1a2e';
function seg(a, b, w, col, outline = true){
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
if(outline){ ctx.strokeStyle = OUT; ctx.lineWidth = w + 2.5; ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke(); }
ctx.strokeStyle = col; ctx.lineWidth = w; ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke();
}
function limb(a, b, c, w1, c1, w2, c2){
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
ctx.strokeStyle = OUT; ctx.lineWidth = Math.max(w1, w2) + 2.5;
ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.lineTo(c[0], c[1]); ctx.stroke();
seg(a, b, w1, c1, false); seg(b, c, w2, c2, false);
}
function dot(p, r, col){
ctx.fillStyle = OUT; ctx.beginPath(); ctx.arc(p[0], p[1], r + 1.3, 0, 7); ctx.fill();
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(p[0], p[1], r, 0, 7); ctx.fill();
}
/* Körper aus Pose zeichnen: Ursprung = Boden unter der Hüfte, blickt nach rechts, y zeigt nach oben (Aufrufer: scale(face, -1)) */
function paintBody(P, pal){
const hip = [P.hx, P.hy];
const sh = [hip[0] + Math.sin(P.lean) * 24, hip[1] + Math.cos(P.lean) * 24];
const hl = P.lean + P.hd;
const head = [sh[0] + Math.sin(hl) * 10, sh[1] + Math.cos(hl) * 10];
const legF = ik(hip, [P.ffx, P.ffy], 19, 19, 1), legB = ik(hip, [P.bfx, P.bfy], 19, 19, 1);
const armF = ik(sh, [sh[0] + P.fhx, sh[1] + P.fhy], 13, 13, -1), armB = ik(sh, [sh[0] + P.bhx, sh[1] + P.bhy], 13, 13, -1);
const arm = A => { limb(sh, A.k, A.end, 6, pal.gi, 5, pal.skin); dot(A.end, 3.6, pal.glove); };
const leg = L => { limb(hip, L.k, L.end, 8, pal.gi, 7, pal.gi2); seg([L.end[0] - 2, L.end[1] + 2], [L.end[0] + 6, L.end[1] + 2], 5, pal.shoe); };
arm(armB);
leg(legB);
seg(hip, sh, 13, pal.gi);
seg(hip, [hip[0] + Math.sin(P.lean) * 5, hip[1] + Math.cos(P.lean) * 5], 14, pal.belt, false);
// Kopf
dot([head[0] - 1.2, head[1] + 1], 6.2, pal.hair);
ctx.fillStyle = pal.skin; ctx.beginPath(); ctx.arc(head[0] + 1.6, head[1] - .8, 5.6, 0, 7); ctx.fill();
seg([head[0] - 4, head[1] + 2], [head[0] + 6, head[1] + 2], 2.2, pal.band, false);
seg([head[0] - 4, head[1] + 2], [head[0] - 10, head[1] - 1 + Math.sin(G.f * .2) * 1.5], 1.8, pal.band, false);
ctx.fillStyle = OUT; ctx.fillRect(head[0] + 3, head[1] - 1.5, 1.8, 2.6);
leg(legF);
arm(armF);
}
function drawFighter(f){
const sx = Math.round(f.x - G.cam);
const shd = Math.max(.35, 1 - f.y / 140);
ctx.fillStyle = 'rgba(30,30,50,.28)'; ctx.beginPath(); ctx.ellipse(sx, GROUND + 1, 20 * shd, 3.5 * shd, 0, 0, 7); ctx.fill();
const flash = f.inv > 0 && f.st === 'getup' && (G.f & 2);
const img = SPR[f.i];
if(img && SPRCFG.on[f.i]){
ctx.save(); ctx.translate(sx, Math.round(GROUND - f.y)); ctx.scale(f.face, 1);
if(flash) ctx.globalAlpha = .55;
const ok = drawSprite(f, img);
ctx.restore();
if(ok) return;
}
ctx.save();
ctx.translate(sx, Math.round(GROUND - f.y)); ctx.scale(f.face, -1);
if(flash) ctx.globalAlpha = .55;
paintBody(f.cur, f.pal);
ctx.restore();
}
/* ------------------------------ Spritesheets ------------------------------
Layout: SCOLS Spalten, jede Zeile = eine Animation / ein Move (Reihenfolge siehe SHEET_ROWS). Zelle CW×CH,
Fußlinie bei y = BY, Mitte bei x = BX, Figur blickt nach RECHTS (Spiegelung übernimmt das Spiel).
Attack-Zeilen haben 3 Frames: Startup · Active · Recovery. Eigene Sheets dürfen höher aufgelöst sein (gleiches Raster, ×n). */
const CW = 112, CH = 104, BX = 56, BY = 96, SCOLS = 6;
const ANIM_ROWS = [['idle',4],['walk_fwd',6],['walk_back',6],['crouch',1],['prejump',1],['jump_up',1],['jump_top',1],['jump_down',1],['land',1],
['block_stand',1],['block_crouch',1],['hit_high',2],['hit_low',2],['knocked_air',1],['lying',1],['getup',3],['held',1],['win',1]];
const SHEET_ROWS = ANIM_ROWS.concat(Object.keys(MOVES).map(k => [k, 3]));
const ROW_IDX = {}; SHEET_ROWS.forEach(([n], i) => { ROW_IDX[n] = i; });
const SPR = [null, null], SPRMETA = ['', ''], SPRCFG = { on:[true, true] };
const TAU = Math.PI * 2;
function sheetPose(name, col){
const I = POSE.idle;
const walk = (dir, n) => {
const ph = dir * col / n * TAU, tg = Object.assign({}, I);
tg.ffx += Math.sin(ph) * 8; tg.ffy += Math.max(0, Math.cos(ph)) * 5; tg.bfx -= Math.sin(ph) * 8; tg.bfy += Math.max(0, -Math.cos(ph)) * 5;
tg.hy -= Math.abs(Math.sin(ph)) * 1.2; return tg;
};
switch(name){
case 'idle': { const tg = Object.assign({}, I), b = Math.sin(col / 4 * TAU); tg.hy += b * .8; tg.fhy += b * .8; return tg; }
case 'walk_fwd': return walk(1, 6);
case 'walk_back': return walk(-1, 6);
case 'crouch': case 'land': return POSE.crouch;
case 'prejump': return POSE.pre;
case 'jump_up': return POSE.jump;
case 'jump_top': return mk(0,36,.05,[8,20],[-4,26],[12,0],[6,-6]);
case 'jump_down': return mk(0,36,.05,[12,10],[-8,16],[14,2],[8,-4]);
case 'block_stand': return POSE.blockS;
case 'block_crouch': return POSE.blockC;
case 'hit_high': return col ? mixPose(POSE.hitHi, I, .45) : POSE.hitHi;
case 'hit_low': return col ? mixPose(POSE.hitLo, POSE.crouch, .45) : POSE.hitLo;
case 'knocked_air': return POSE.down;
case 'lying': return POSE.lie;
case 'getup': return [mixPose(POSE.lie, POSE.crouch, .5), POSE.crouch, mixPose(POSE.crouch, I, .5)][col];
case 'held': return Object.assign({}, POSE.down, { lean:-1.5, hy:34 });
case 'win': return POSE.win;
}
const m = MOVES[name];
return [m.ps, m.pa, mixPose(m.pa, m.crouch ? POSE.crouch : I, .5)][col];
}
// Welche Zelle zeigt der Kämpfer gerade? → [Zeilenname, Spalte]
function spriteCell(f){
const m = f.move, t = f.t;
const phase = (mv, el) => el <= mv.su ? 0 : el <= mv.su + mv.ac + Math.ceil(mv.rc * .3) ? 1 : 2;
switch(f.st){
case 'ground':
if(f.win) return ['win', 0];
if(f.crouch) return ['crouch', 0];
if(f.walk) return [f.walk > 0 ? 'walk_fwd' : 'walk_back', Math.floor((((f.ph * f.walk) % TAU) + TAU) % TAU / TAU * 6) % 6];
return ['idle', (G.f >> 4) % 4];
case 'prejump': return ['prejump', 0];
case 'air':
if(f.airMove) return [f.airMove.key, f.mt < f.airMove.su ? 0 : 1];
return [f.vy > 2 ? 'jump_up' : f.vy > -2 ? 'jump_top' : 'jump_down', 0];
case 'land': return ['land', 0];
case 'attack': case 'throw': return m ? [m.key, phase(m, t)] : ['idle', 0];
case 'held': return ['held', 0];
case 'hit': return [f.crouch ? 'hit_low' : 'hit_high', t < 6 ? 0 : 1];
case 'block': return [f.crouch ? 'block_crouch' : 'block_stand', 0];
case 'down': return ['knocked_air', 0];
case 'lie': return ['lying', 0];
case 'getup': return ['getup', Math.min(2, Math.floor(t / 6))];
}
return ['idle', 0];
}
function drawSprite(f, img){
const [name, col] = spriteCell(f), r = ROW_IDX[name];
if(r == null) return false;
const cw = img.width / SCOLS, ch = img.height / SHEET_ROWS.length;
ctx.drawImage(img, Math.round(col * cw), Math.round(r * ch), Math.round(cw), Math.round(ch), -BX, -BY, CW, CH);
return true;
}
function renderSheet(pal){
const c = mkCanvas(SCOLS * CW, SHEET_ROWS.length * CH), real = ctx; ctx = c.getContext('2d');
try{
SHEET_ROWS.forEach(([name, n], r) => { for(let col = 0; col < n; col++){
ctx.save(); ctx.translate(col * CW + BX, r * CH + BY); ctx.scale(1, -1); paintBody(sheetPose(name, col), pal); ctx.restore();
} });
} finally { ctx = real; }
return c;
}
function renderSheetGuide(){
const c = mkCanvas(SCOLS * CW, SHEET_ROWS.length * CH), g = c.getContext('2d');
SHEET_ROWS.forEach(([name, n], r) => { for(let col = 0; col < SCOLS; col++){
const x = col * CW, y = r * CH, used = col < n;
if(!used){ g.fillStyle = 'rgba(120,120,120,.18)'; g.fillRect(x, y, CW, CH); continue; }
g.strokeStyle = 'rgba(0,170,220,.9)'; g.lineWidth = 1; g.strokeRect(x + .5, y + .5, CW - 1, CH - 1);
g.fillStyle = 'rgba(230,40,140,.9)'; g.fillRect(x, y + BY, CW, 1); // Fußlinie
g.fillStyle = 'rgba(0,170,220,.45)'; g.fillRect(x + BX, y, 1, CH); // Mitte
text(name + ' ' + (col + 1) + '/' + n, x + 3, y + 7, 8, '#0090c0', 'left', null, g);
} });
return c;
}
function drawProj(p){
const x = Math.round(p.x - G.cam), y = Math.round(GROUND - p.y);
for(let k = 3; k >= 1; k--){ ctx.fillStyle = `rgba(150,215,255,${.18 * (4 - k)})`; ctx.beginPath(); ctx.arc(x - p.dir * k * 7, y, 8 - k, 0, 7); ctx.fill(); }
ctx.fillStyle = '#7fcfff'; ctx.beginPath(); ctx.arc(x, y, 9 + Math.sin(G.f * .6), 0, 7); ctx.fill();
ctx.fillStyle = '#e8f8ff'; ctx.beginPath(); ctx.arc(x, y, 5, 0, 7); ctx.fill();
ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(x + p.dir * 1.5, y - 1, 2.4, 0, 7); ctx.fill();
}
function drawSpark(s){
const x = Math.round(s.x - G.cam), y = Math.round(GROUND - s.y);
if(s.type === 'hit'){
const r = (s.big ? 14 : 9) * (1 - s.t / 14);
const star = (ro, ri, col, rot) => {
ctx.fillStyle = col; ctx.beginPath();
for(let i = 0; i < 16; i++){ const a = rot + i * Math.PI / 8, rr = i % 2 ? ri : ro; ctx.lineTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr); }
ctx.closePath(); ctx.fill();
};
star(r, r * .45, '#ff9a2e', s.t * .3); star(r * .7, r * .3, '#fff3a0', -s.t * .3); star(r * .3, r * .15, '#ffffff', 0);
} else {
ctx.strokeStyle = '#d4efff'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(x, y, 3 + s.t * 1.1, 0, 7); ctx.stroke();
ctx.strokeStyle = '#ffffff'; ctx.lineWidth = 1;
for(let i = 0; i < 6; i++){ const a = i * 1.047 + .3, r0 = 4 + s.t, r1 = 7 + s.t * 1.5; ctx.beginPath(); ctx.moveTo(x + Math.cos(a) * r0, y + Math.sin(a) * r0); ctx.lineTo(x + Math.cos(a) * r1, y + Math.sin(a) * r1); ctx.stroke(); }
}
}
/* ------------------------------ HUD ------------------------------ */
/* 5x7-Bitmapfont – jedes Pixel ist ein echtes Rechteck, daher immer gestochen scharf (keine Systemschrift, kein Antialiasing) */
const FONT_SRC = {
'A':'01110 10001 10001 11111 10001 10001 10001','B':'11110 10001 10001 11110 10001 10001 11110','C':'01110 10001 10000 10000 10000 10001 01110',
'D':'11110 10001 10001 10001 10001 10001 11110','E':'11111 10000 10000 11110 10000 10000 11111','F':'11111 10000 10000 11110 10000 10000 10000',
'G':'01110 10001 10000 10111 10001 10001 01111','H':'10001 10001 10001 11111 10001 10001 10001','I':'01110 00100 00100 00100 00100 00100 01110',
'J':'00111 00010 00010 00010 00010 10010 01100','K':'10001 10010 10100 11000 10100 10010 10001','L':'10000 10000 10000 10000 10000 10000 11111',
'M':'10001 11011 10101 10101 10001 10001 10001','N':'10001 11001 10101 10011 10001 10001 10001','O':'01110 10001 10001 10001 10001 10001 01110',
'P':'11110 10001 10001 11110 10000 10000 10000','Q':'01110 10001 10001 10001 10101 10010 01101','R':'11110 10001 10001 11110 10100 10010 10001',
'S':'01111 10000 10000 01110 00001 00001 11110','T':'11111 00100 00100 00100 00100 00100 00100','U':'10001 10001 10001 10001 10001 10001 01110',
'V':'10001 10001 10001 10001 10001 01010 00100','W':'10001 10001 10001 10101 10101 10101 01010','X':'10001 10001 01010 00100 01010 10001 10001',
'Y':'10001 10001 01010 00100 00100 00100 00100','Z':'11111 00001 00010 00100 01000 10000 11111',
'0':'01110 10001 10011 10101 11001 10001 01110','1':'00100 01100 00100 00100 00100 00100 01110','2':'01110 10001 00001 00010 00100 01000 11111',
'3':'11110 00001 00001 01110 00001 00001 11110','4':'00010 00110 01010 10010 11111 00010 00010','5':'11111 10000 11110 00001 00001 10001 01110',
'6':'00110 01000 10000 11110 10001 10001 01110','7':'11111 00001 00010 00100 01000 01000 01000','8':'01110 10001 10001 01110 10001 10001 01110',
'9':'01110 10001 10001 01111 00001 00010 01100',
' ':'00000 00000 00000 00000 00000 00000 00000','!':'00100 00100 00100 00100 00100 00000 00100','?':'01110 10001 00001 00110 00100 00000 00100',
'.':'00000 00000 00000 00000 00000 01100 01100',',':'00000 00000 00000 00000 01100 00100 01000',':':'00000 01100 01100 00000 01100 01100 00000',
'-':'00000 00000 00000 11111 00000 00000 00000','+':'00000 00100 00100 11111 00100 00100 00000','=':'00000 00000 11111 00000 11111 00000 00000',
'/':'00001 00010 00010 00100 01000 01000 10000','%':'11001 11010 00010 00100 01000 01011 10011',"'":'00100 00100 01000 00000 00000 00000 00000',
'(':'00010 00100 01000 01000 01000 00100 00010',')':'01000 00100 00010 00010 00010 00100 01000','*':'00000 10101 01110 11111 01110 10101 00000',
'<':'00010 00100 01000 10000 01000 00100 00010','>':'01000 00100 00010 00001 00010 00100 01000','_':'00000 00000 00000 00000 00000 00000 11111',
'#':'01010 01010 11111 01010 11111 01010 01010','x':'00000 00000 10001 01010 00100 01010 10001'
};
const GLY = {}; for(const k in FONT_SRC) GLY[k] = FONT_SRC[k].split(' ').map(r => parseInt(r, 2));
const fontNorm = s => String(s).replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/Ä/g, 'AE').replace(/Ö/g, 'OE').replace(/Ü/g, 'UE').replace(/ß/g, 'SS')
.replace(/[a-z]/g, c => c === 'x' ? 'x' : c.toUpperCase());
const TXT_CACHE = new Map();
function pixText(s, sc, col, stroke){
const key = s + '|' + sc + '|' + col + '|' + stroke, hit = TXT_CACHE.get(key); if(hit) return hit;
const o = stroke ? (sc >= 3 ? 2 : 1) : 0, w = Math.max(1, s.length * 6 - 1) * sc + o * 2, h = 7 * sc + o * 2;
const c = document.createElement('canvas'); c.width = w; c.height = h; const g = c.getContext('2d');
const paint = (ox, oy, colr) => {
g.fillStyle = colr;
for(let n = 0; n < s.length; n++){
const rows = GLY[s[n]] || GLY['?'];
for(let ry = 0; ry < 7; ry++) for(let cx = 0; cx < 5; cx++) if(rows[ry] & (16 >> cx)) g.fillRect(ox + (n * 6 + cx) * sc, oy + ry * sc, sc, sc);
}
};
if(stroke) for(let dy = -o; dy <= o; dy++) for(let dx = -o; dx <= o; dx++) if(dx || dy) paint(o + dx, o + dy, stroke);
paint(o, o, col);
const r = { c, w, h };
if(TXT_CACHE.size > 400) TXT_CACHE.clear();
TXT_CACHE.set(key, r); return r;
}
// size wird auf ganzzahlige Pixelfaktoren abgebildet: <12 → 1×, <19 → 2×, <26 → 3×, sonst 4×
function text(s, x, y, size, col, align = 'center', stroke = '#101018', c2 = ctx){
const sc = size >= 26 ? 4 : size >= 19 ? 3 : size >= 12 ? 2 : 1;
const t = pixText(fontNorm(s), sc, col, stroke);
const dx = align === 'left' ? x : align === 'right' ? x - t.w : x - t.w / 2;
c2.drawImage(t.c, Math.round(dx), Math.round(y - t.h / 2));
}
function drawCombo(f, dir){
if(f.combo < 2) return;
const x = dir < 0 ? 14 : W - 14, al = dir < 0 ? 'left' : 'right';
const col = f.combo >= 6 ? '#ff5a3d' : f.combo >= 4 ? '#ff9a2e' : '#ffe066';
ctx.save();
if(f.comboT < 20) ctx.globalAlpha = Math.max(0, f.comboT / 20);
const sc = 1 + Math.min(f.comboPulse, 8) / 8 * .5;
ctx.translate(x, 76); ctx.scale(sc, sc);
text(String(f.combo), 0, 0, 30, col, al);
ctx.restore();
ctx.save();
if(f.comboT < 20) ctx.globalAlpha = Math.max(0, f.comboT / 20);
text('HIT COMBO', x, 98, 9, '#ffffff', al);
text('DMG ' + f.comboDmg, x, 109, 9, '#ffffff', al);
ctx.restore();
}
function drawHUD(){
const bw = MAXHP;
[[p1, 164, -1], [p2, 220, 1]].forEach(([f, x0, dir]) => {
const bx = dir < 0 ? x0 - bw : x0;
px(bx - 2, 8, bw + 4, 12, '#101018'); px(bx, 10, bw, 8, '#3a2a30');
const bar = (v, c) => { const w = Math.round(v), x = dir < 0 ? x0 - w : x0; px(x, 10, w, 8, c); };
bar(f.trail, '#d6402e'); bar(f.hp, '#f5c82e'); bar(f.hp, '#f5c82e'); px(dir < 0 ? x0 - f.hp : x0, 10, Math.round(f.hp), 2, '#fff1a0');
text(f.name, dir < 0 ? bx : bx + bw, 29, 12, '#ffffff', dir < 0 ? 'left' : 'right');
for(let k = 0; k < 2; k++){
const cx = W / 2 + dir * (9 + k * 10);
ctx.fillStyle = '#101018'; ctx.beginPath(); ctx.arc(cx, 32, 4, 0, 7); ctx.fill();
ctx.fillStyle = f.wins > k ? '#f5c82e' : '#4a4a58'; ctx.beginPath(); ctx.arc(cx, 32, 2.6, 0, 7); ctx.fill();
}
drawCombo(f, dir);
});
text(String(Math.max(0, G.timer)).padStart(2, '0'), W / 2, 16, 20, '#ffe066');
text('KO', W / 2, 33, 7, '#ffffff', 'center');
}
function drawDebug(){
const box = (b, col) => { ctx.strokeStyle = col; ctx.lineWidth = 1; ctx.strokeRect(Math.round(b.x1 - G.cam) + .5, Math.round(GROUND - b.y2) + .5, Math.round(b.x2 - b.x1), Math.round(b.y2 - b.y1)); };
FIGHTERS.forEach(f => {
const hu = f.hurtbox(); if(hu) box(hu, '#2e7bff');
const m = f.curMove();
if(m && f.st === 'attack' && f.t > m.su && f.t <= m.su + m.ac || (f.st === 'air' && m && f.mt >= m.su)){
const b = m.box, x1 = f.face > 0 ? f.x + b[0] : f.x - b[2], x2 = f.face > 0 ? f.x + b[2] : f.x - b[0];
box({ x1, x2, y1:f.y + b[1], y2:f.y + b[3] }, f.hitDone ? '#aa8888' : '#ff2e2e');
}
box({ x1:f.x - 12, x2:f.x + 12, y1:0, y2:3 }, '#27b36a');
});
text(`${p1.st}${p1.move ? ':' + p1.t : ''} ${p2.st}${p2.move ? ':' + p2.t : ''} mode ${G.mode}`, 6, H - 6, 8, '#ffffff', 'left');
}
function draw(){
ctx.save();
const sh = G.shake > 0 ? Math.round((Math.random() - .5) * G.shake * 2) : 0;
ctx.translate(sh, 0);
drawStage();
const order = FIGHTERS.slice().sort((a, b) => ((a.st === 'attack' || (a.st === 'air' && a.airMove)) ? 1 : 0) - ((b.st === 'attack' || (b.st === 'air' && b.airMove)) ? 1 : 0));
order.forEach(drawFighter);
PROJ.forEach(drawProj);
sparks.forEach(drawSpark);
drawLayer(4);
ctx.restore();
if(G.mode !== 'title') drawHUD();
if(G.debug) drawDebug();
if(G.msgT > 0 && G.mode !== 'match'){
const big = G.msg.length > 9 ? 22 : 28;
text(G.msg, W / 2, 96, big, G.msgCol);
}
if(G.mode === 'title'){
ctx.fillStyle = 'rgba(255,255,255,.55)'; ctx.fillRect(0, 50, W, 112);
text('TURBO FIGHT', W / 2, 76, 30, '#ffe066');
text('HYPER EDITION V0.5', W / 2, 106, 12, '#ffffff');
if((G.f >> 5) & 1){ text('ENTER = 2 PLAYERS', W / 2, 128, 12, '#ffffff'); text('C = VS CPU', W / 2, 145, 12, '#ffffff'); }
}
if(G.mode === 'match'){
const msg = p1.wins === p2.wins ? 'DRAW MATCH' : (p1.wins > p2.wins ? p1.name : p2.name) + ' WINS THE MATCH';
ctx.fillStyle = 'rgba(255,255,255,.55)'; ctx.fillRect(0, 70, W, 56);
text(msg, W / 2, 88, 16, '#ffe066');
if((G.f >> 5) & 1) text('ENTER = 2P C = VS CPU', W / 2, 110, 12, '#ffffff');
}
if(G.toastT > 0) text(G.toast, W / 2, H - 12, 12, '#ffffff');
if(G.paused){ ctx.fillStyle = 'rgba(255,255,255,.5)'; ctx.fillRect(0, 0, W, H); text('PAUSE', W / 2, H / 2, 20, '#ffe066'); }
}
/* ------------------------------ Tuning-Panel ------------------------------
Regler für P (global) + Tabelle der Frame-Daten aller Moves. Werte werden im Browser gespeichert. */
const SL = [
['Tempo & Bewegung', [
['speed','Spieltempo',.8,2,.05], ['walkF','Laufen vorwärts',.5,3,.1], ['walkB','Laufen rückwärts',.5,3,.1],
['jumpV','Sprungkraft',6,12,.1], ['grav','Schwerkraft',.2,.7,.01], ['jumpFwd','Sprung vorwärts',1,4,.1], ['jumpBack','Sprung rückwärts',1,4,.1]]],
['Rückstoß', [
['pushMul','Rückstoß gesamt',0,2,.05], ['airPushMul','Rückstoß bei Sprungangriff ×',1,5,.1], ['slide','Ausgleiten (Reibung)',.6,.95,.01]]],
['Treffer-Gefühl', [
['hitstunAdd','Hitstun +Frames',-4,10,1], ['blockstunAdd','Blockstun +Frames',-4,10,1],
['stopL','Hitstop leicht',0,16,1], ['stopM','Hitstop mittel',0,16,1], ['stopH','Hitstop schwer',0,20,1], ['dmgMul','Schaden ×',.25,2,.05]]],
['Würfe & Juggle', [['throwRange','Wurf-Reichweite (px)',20,60,1], ['throwFling','Wurfweite ×',.5,2.5,.1], ['juggleMax','Juggle-Treffer nach Launcher',0,4,1], ['juggleScale','Juggle-Schaden ×',.2,1,.05]]],
['Combo-Zähler', [['comboHold','Anzeige-Dauer (Frames)',30,240,10]]]
];
const MCOLS = [['su','Start'],['ac','Aktiv'],['rc','Erhol.'],['dmg','Schad.'],['hs','Hit'],['bs','Block'],['push','Push']];
const DEFP = Object.assign({}, P), DEFM = {};
for(const k in MOVES){ DEFM[k] = {}; MCOLS.forEach(([c]) => DEFM[k][c] = MOVES[k][c]); }
const LS_KEY = 'turbofight.tuning.v2';
const movesSnap = () => { const o = {}; for(const k in MOVES){ o[k] = {}; MCOLS.forEach(([c]) => o[k][c] = MOVES[k][c]); } return o; };
function saveTuning(){ try{ localStorage.setItem(LS_KEY, JSON.stringify({ P, M:movesSnap(), cpu:G.cpu, lv:AI.lv })); }catch(_){} }
function loadTuning(){
try{
const s = JSON.parse(localStorage.getItem(LS_KEY) || 'null'); if(!s) return;
Object.assign(P, s.P || {});
for(const k in (s.M || {})) if(MOVES[k]) Object.assign(MOVES[k], s.M[k]);
if(typeof s.lv === 'number') AI.lv = s.lv;
}catch(_){}
}
/* ------------------------------ Eigene Grafiken (Hintergrund-Ebenen, Spritesheets) ------------------------------
Bilder werden im Browser (IndexedDB) gespeichert, Einstellungen in localStorage. */
const IDB = {
db:null,
open(){ return new Promise(res => { try{ const r = indexedDB.open('turbofight.assets', 1); r.onupgradeneeded = () => r.result.createObjectStore('f'); r.onsuccess = () => { IDB.db = r.result; res(true); }; r.onerror = () => res(false); }catch(_){ res(false); } }); },
tx(mode, fn){ return new Promise(res => { try{ const t = IDB.db.transaction('f', mode), r = fn(t.objectStore('f')); t.oncomplete = () => res(r && r.result); t.onerror = () => res(null); }catch(_){ res(null); } }); },
put(k, v){ return IDB.db ? IDB.tx('readwrite', st => st.put(v, k)) : Promise.resolve(); },
get(k){ return IDB.db ? IDB.tx('readonly', st => st.get(k)) : Promise.resolve(null); },
del(k){ return IDB.db ? IDB.tx('readwrite', st => st.delete(k)) : Promise.resolve(); }
};
const AS_KEY = 'turbofight.assets.v1';
const saveAssets = () => { try{ localStorage.setItem(AS_KEY, JSON.stringify({ bg:BGCFG, on:SPRCFG.on })); }catch(_){} };
(function loadAssetCfg(){
try{ const a = JSON.parse(localStorage.getItem(AS_KEY) || 'null'); if(!a) return;
(a.bg || []).forEach((c, i) => { if(BGCFG[i]) Object.assign(BGCFG[i], c); }); if(a.on) SPRCFG.on = a.on; }catch(_){}
})();
const blobToImg = blob => new Promise(res => { const im = new Image(); im.onload = () => res(im); im.onerror = () => res(null); im.src = URL.createObjectURL(blob); });
const pickFile = cb => { const i = document.createElement('input'); i.type = 'file'; i.accept = 'image/*'; i.onchange = () => { if(i.files[0]) cb(i.files[0]); }; i.click(); };
const toast = t => { G.toast = t; G.toastT = 150; };
function download(canvas, name){
canvas.toBlob(b => { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = name; document.body.appendChild(a); a.click(); a.remove(); }, 'image/png');
}
async function setBg(k, file){
const im = await blobToImg(file); if(!im){ toast('BILD NICHT LESBAR'); return; }
await IDB.put('bg' + k, file); BGIMG[k] = im; BGCFG[k].hide = false; BGMETA[k] = im.width + 'x' + im.height;
const need = layerW(BGCFG[k].f);
toast(im.height !== H || im.width < need ? 'EBENE ' + (k + 1) + ': ' + im.width + 'x' + im.height + ' (EMPFOHLEN ' + need + 'x' + H + ')' : 'EBENE ' + (k + 1) + ' GELADEN');
saveAssets(); buildPanel();
}
async function setSpr(i, file){
const im = await blobToImg(file); if(!im){ toast('BILD NICHT LESBAR'); return; }
await IDB.put('spr' + i, file); SPR[i] = im; SPRCFG.on[i] = true; SPRMETA[i] = im.width + 'x' + im.height;
const w = SCOLS * CW, h = SHEET_ROWS.length * CH;
toast(im.width % SCOLS || Math.abs(im.width / im.height - w / h) > .02 ? 'SHEET ' + im.width + 'x' + im.height + ' (RASTER ' + w + 'x' + h + ' ODER VIELFACHES)' : 'SPRITES SPIELER ' + (i + 1) + ' GELADEN');
saveAssets(); buildPanel();
}
IDB.open().then(async ok => {
if(!ok) return;
for(let k = 0; k < 5; k++){ const b = await IDB.get('bg' + k); if(b){ const im = await blobToImg(b); if(im){ BGIMG[k] = im; BGMETA[k] = im.width + 'x' + im.height; } } }
for(let i = 0; i < 2; i++){ const b = await IDB.get('spr' + i); if(b){ const im = await blobToImg(b); if(im){ SPR[i] = im; SPRMETA[i] = im.width + 'x' + im.height; } } }
buildPanel();
});
function buildAssetUI(root, el){
const det = el('details'); det.appendChild(el('summary', '', 'Eigene Grafiken (Hintergrund & Charaktere)'));
det.open = BGIMG.some(Boolean) || SPR.some(Boolean);
const btn = (t, fn, title) => { const b = el('button', 'sm', t); if(title) b.title = title; b.addEventListener('click', () => { fn(); b.blur(); }); return b; };
det.appendChild(el('div', 'ah', 'Hintergrund: PNG je Ebene, Höhe 224 px, Breite = 384 + 256 × Parallax (Faktor 0,30 → 461 px). Schmalere Bilder werden gekachelt. Ebene 4 = Kampfebene (Fußlinie y=196), Ebene 5 liegt vor den Kämpfern.'));
LAYERS.forEach((L, k) => {
const cfg = BGCFG[k], row = el('div', 'ar');
row.appendChild(el('b', '', (k + 1) + ' · ' + L.name.replace('Kaempfern', 'Kämpfern') + (BGIMG[k] ? ' — eigenes Bild ' + BGMETA[k] : (k === 4 ? ' — leer' : ' — Standard'))));
const f = document.createElement('input'); f.type = 'number'; f.className = 'fnum'; f.min = 0; f.max = 2; f.step = .05; f.value = cfg.f; f.title = 'Parallax-Faktor';
f.addEventListener('change', () => { const v = parseFloat(f.value); if(!isNaN(v)){ cfg.f = Math.min(2, Math.max(0, v)); saveAssets(); buildPanel(); } });
const hide = document.createElement('input'); hide.type = 'checkbox'; hide.checked = cfg.hide; hide.title = 'Ebene ausblenden';
hide.addEventListener('change', () => { cfg.hide = hide.checked; saveAssets(); hide.blur(); });
row.append(el('i', '', 'Parallax'), f, btn('Bild laden…', () => pickFile(fl => setBg(k, fl))));
if(BGIMG[k]) row.appendChild(btn('Standard', async () => { await IDB.del('bg' + k); BGIMG[k] = null; BGMETA[k] = ''; buildPanel(); }));
row.append(hide, el('i', '', 'aus'),
btn('Beispiel ↓', () => download(renderLayerExample(k, cfg.f), 'ebene' + (k + 1) + '_beispiel.png'), 'Standard-Ebene als PNG speichern'),
btn('Schablone ↓', () => download(renderLayerGuide(k, cfg.f), 'ebene' + (k + 1) + '_schablone.png'), 'Maße, Raster, Fußlinie, Kamera-Fenster'));
det.appendChild(row);
});
det.appendChild(el('div', 'ah', 'Charaktere: Spritesheet mit ' + SCOLS + ' Spalten × ' + SHEET_ROWS.length + ' Zeilen, Zelle ' + CW + '×' + CH + ' px (Sheet ' + SCOLS * CW + '×' + SHEET_ROWS.length * CH + ', auch ×2/×3 möglich). Fußlinie y=' + BY + ', Mitte x=' + BX + ', Figur blickt nach rechts. Eine Zeile = ein Zustand oder Move (idle, walk, … dann alle Moves mit Startup · Aktiv · Recovery).'));
[0, 1].forEach(i => {
const row = el('div', 'ar');
row.appendChild(el('b', '', 'Spieler ' + (i + 1) + ' · ' + FIGHTERS[i].name + (SPR[i] ? ' — Sheet ' + SPRMETA[i] : ' — Strichfigur')));
row.appendChild(btn('Sheet laden…', () => pickFile(fl => setSpr(i, fl))));
if(SPR[i]){
const on = document.createElement('input'); on.type = 'checkbox'; on.checked = SPRCFG.on[i]; on.title = 'Sprites verwenden';
on.addEventListener('change', () => { SPRCFG.on[i] = on.checked; saveAssets(); on.blur(); });
row.append(btn('Standard', async () => { await IDB.del('spr' + i); SPR[i] = null; SPRMETA[i] = ''; buildPanel(); }), on, el('i', '', 'Sprites an'));
}
row.append(btn('Beispiel ↓', () => download(renderSheet(FIGHTERS[i].pal), 'spritesheet_p' + (i + 1) + '_beispiel.png'), 'Aktuelle Strichfigur als fertiges Sheet'),
btn('Schablone ↓', () => download(renderSheetGuide(), 'spritesheet_schablone.png'), 'Raster mit Zeilennamen, Fußlinie, Mitte'));
det.appendChild(row);
});
root.appendChild(det);
}
const sliderRefs = {}; let cpuSel = null;
function syncPanel(){
for(const k in sliderRefs){ sliderRefs[k].inp.value = P[k]; sliderRefs[k].upd(); }
if(cpuSel) cpuSel.value = G.cpu ? String(AI.lv) : 'off';
}
function buildPanel(){
const root = document.getElementById('panel'); if(!root) return;
root.innerHTML = '';
const el = (tag, cls, txt) => { const e = document.createElement(tag); if(cls) e.className = cls; if(txt != null) e.textContent = txt; return e; };
root.appendChild(el('div', 'ph', 'PARAMETER'));
SL.forEach(([title, items]) => {
root.appendChild(el('div', 'pg', title));
items.forEach(([key, label, min, max, step]) => {
const row = el('label', 'pr'), name = el('span', '', label), val = el('span', 'pv');
const inp = document.createElement('input'); inp.type = 'range'; inp.min = min; inp.max = max; inp.step = step; inp.value = P[key];
const dec = step >= 1 ? 0 : step >= .1 ? 1 : 2;
const upd = () => { val.textContent = (+P[key]).toFixed(dec); };
inp.addEventListener('input', () => { P[key] = parseFloat(inp.value); upd(); saveTuning(); });
inp.addEventListener('change', () => inp.blur()); // Fokus zurück ans Spiel (sonst bewegen Pfeiltasten den Regler)
upd(); row.append(name, val, inp); root.appendChild(row); sliderRefs[key] = { inp, upd };
});
});
// CPU
root.appendChild(el('div', 'pg', 'Gegner (Spieler 2)'));
cpuSel = document.createElement('select');
[['off','2 Spieler'], ['0','CPU – easy'], ['1','CPU – normal'], ['2','CPU – hard']].forEach(([v, t]) => { const o = document.createElement('option'); o.value = v; o.textContent = t; cpuSel.appendChild(o); });
cpuSel.addEventListener('change', () => {
if(cpuSel.value === 'off') G.cpu = false; else { G.cpu = true; AI.lv = parseInt(cpuSel.value, 10); }
saveTuning(); cpuSel.blur();
});
root.appendChild(cpuSel);
buildAssetUI(root, el);
// Move-Tabelle
const det = el('details'); det.appendChild(el('summary', '', 'Move-Frame-Daten'));
const tb = document.createElement('table'), hr = document.createElement('tr');
hr.appendChild(el('th', '', ''));
MCOLS.forEach(([c, t]) => hr.appendChild(el('th', '', t)));
tb.appendChild(hr);
const air = k => k.startsWith('a_');
for(const k in MOVES){
const tr = document.createElement('tr'); tr.appendChild(el('td', '', k.replace('dash_', 'dash ').replace('st_', 'st ').replace('cr_', 'cr ').replace('a_', 'air ').replace('sp_', 'special ').replace('th_', 'throw ')));
MCOLS.forEach(([c]) => {
const td = document.createElement('td'), inp = document.createElement('input');
inp.type = 'number'; inp.className = 'mi'; inp.step = c === 'push' ? .1 : 1; inp.value = MOVES[k][c];
if(air(k) && (c === 'ac' || c === 'rc')) inp.disabled = true; // Luftangriffe sind bis zur Landung aktiv
inp.addEventListener('input', () => { const v = parseFloat(inp.value); if(!isNaN(v)){ MOVES[k][c] = v; saveTuning(); } });
td.appendChild(inp); tr.appendChild(td);
});
tb.appendChild(tr);
}
det.appendChild(tb); root.appendChild(det);
det.appendChild(el('div', '', 'Start = Frames bis zum Treffer · Aktiv = Treffer-Fenster · Erhol. = Recovery · Hit/Block = Stun des Gegners · Push = Rückstoß px/Frame'));
// Buttons
const bar = el('div', 'btns'), bReset = el('button', '', 'Zurücksetzen'), bCopy = el('button', '', 'Werte kopieren');
const out = document.createElement('textarea'); out.id = 'out'; out.readOnly = true;
bReset.addEventListener('click', () => {
Object.assign(P, DEFP); for(const k in DEFM) Object.assign(MOVES[k], DEFM[k]);
try{ localStorage.removeItem(LS_KEY); }catch(_){}
buildPanel(); syncPanel();
});
bCopy.addEventListener('click', () => {
const txt = JSON.stringify({ P, moves:movesSnap() }, null, 1);
out.value = txt; out.style.display = 'block'; out.select();
try{ navigator.clipboard.writeText(txt); }catch(_){}
});
bar.append(bReset, bCopy); root.appendChild(bar); root.appendChild(out);
syncPanel();
}
loadTuning(); buildPanel(); fit();
/* ------------------------------ Hauptschleife (fester 60-Hz-Takt) ------------------------------ */
let last = performance.now(), acc = 0;
function frame(now){
acc += Math.min(100, now - last); last = now;
const STEP = 1000 / (60 * P.speed);
while(acc >= STEP){ tick(); acc -= STEP; }
draw();
requestAnimationFrame(frame);
}
// Titelbild: beide Figuren stehen schon in der Arena
FIGHTERS.forEach(f => f.reset());
requestAnimationFrame(frame);
</script>
</body>
</html>