diff --git a/CLAUDE.md b/CLAUDE.md index ee80f81..edc08bc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -129,7 +129,13 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz. Front jeweils rechts), 3D-Vorschau live; gespeichert als PNG-Data-URL in `save.paint.decal` · `game/looks.js` Aussehen der Liga-Gegner passend zu ihren Porträts (Skin-Muster + Augen, Kabine, Höcker, Ketten-Optik) · `game/profiles.js` lokale Konten für die Offline-Kampagne (Name + Passwort-Hash, je Konto eigener Spielstand) - · `game/game.js` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen. + · `game/game.js` Kern + Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Gast → Shop → Liga/VS → Kampf → Ergebnis. + Aufgeteilt (klassische Skripte, kein Build): `game/sfx.js` Sound · `game/pages.js` Menüseiten (Einstellungen, + Hilfe, Tutorial, Land, Erfolge, Missionen, Rechtliches, Rangliste) · `game/online.js` Online (act(), Abgleich mit + dem Server, Login-Karte, Lobby, Online-Kampfende) · `game/workshop.js` Waffen-Editor, Lack, Hangar. Jedes Modul + ist eine Fabrik `RC.Game(G)`; `G` (Ende von game.js) liefert per Getter den **aktuellen** Zustand (`G.save`, + `G.mode`, `G.F` …) und per Setter das Zurückschreiben. Neue gemeinsame Variable → in `G` eintragen. Aufrufe aus + game.js laufen über kurze Weiterleitungen (`function x(...a) { return GM..x(...a); }`). - `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten). - Kommandos (Repo-Root): `npm run setup` (einmal), `npm test` (alle Tests: `tests/*.test.js` Regeln/Kämpfe ohne NaN/ Grube + `server/test/*.test.js` echter Server mit In-Memory-DB), `npm run lint` (ESLint), `npm run balance` diff --git a/docs/MULTIPLAYER-PLAN.md b/docs/MULTIPLAYER-PLAN.md index f53d8a7..cc723a2 100644 --- a/docs/MULTIPLAYER-PLAN.md +++ b/docs/MULTIPLAYER-PLAN.md @@ -11,7 +11,8 @@ Stand der Analyse: 2026-11-19 (Commit `347701d`). ## Umsetzungsstand (2026-11-19) **Erledigt:** Phase 0, Phase 1, Phase 2 (außer P2-6), aus Phase 3: P3-1b, P3-2, P3-3 (+ Teile von P3-1), aus Phase 4: -Smoke-Test (`npm run smoke -- `, Vorstufe von P4-1). **Live** auf `https://roboclash.michael-media.de` (Dev). +Smoke-Test (`npm run smoke -- `, Vorstufe von P4-1), P4-2 Playwright (9 Browser-Tests, `npm run e2e`), +P4-5 `game.js` aufgeteilt (1996 → ~1380 Zeilen + `sfx.js`, `pages.js`, `online.js`, `workshop.js`). **Live** auf `https://roboclash.michael-media.de` (Dev). Geprüft: 46 automatische Tests, Smoke-Test gegen den Dev-Server (WebSocket über Caddy/TLS, 20 Snapshots/s, gespiegeltes Ergebnis), zwei Browser-Tabs michi gegen benni lokal (Kampf, Ergebnis, Belohnung, Hintergrund-Tab), Shop-Kauf landet in der Server-DB, Kampagne offline über `file://` (headless + `&uicheck`). @@ -27,7 +28,7 @@ Shop-Kauf landet in der Server-DB, Kampagne offline über `file://` (headless + **Offen / nächste Schritte:** P2-6 (Online-Turnier), P3-1 Rest (SSH-Nutzer `deploy`, Passwort-Login aus), P3-5 (Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-1 voller Bot-Client, P4-3 Lasttest, -P4-4 Vorhersage (erst nach Spieltest), P4-5 `game.js` aufteilen (~2000 Zeilen), `tests/sim.test.js:442` (halber Test). +P4-4 Vorhersage (erst nach Spieltest), `tests/sim.test.js:442` (halber Test). Hinweis: Der Smoke-Test legt Gastkonten an (`SmokeA`/`SmokeB`), die in der Rangliste auftauchen können → `--reset-db` beim Deploy räumt auf. @@ -293,7 +294,7 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau. - [ ] **P4-3 Lasttest:** 100 Bots / 50 Matches auf dem Dev-Server; Tick-Dauer und CPU dokumentieren. - [ ] **P4-4 Latenz-Komfort:** Vorhersage für den eigenen Roboter (Eingabe sofort lokal anwenden, mit Server-Snapshot abgleichen), Ping-Anzeige im HUD. Nur wenn Spieltests Verzögerung bemängeln. -- [ ] **P4-5 `game.js` aufteilen** (> 1500 Zeilen, Regel aus CLAUDE.md): `online-ui.js` (Lobby, Login), +- [x] **P4-5 `game.js` aufteilen** (> 1500 Zeilen, Regel aus CLAUDE.md): `online-ui.js` (Lobby, Login), `fight.js` (Kampfablauf), `results.js`. Ohne Verhaltensänderung, abgesichert durch `&uicheck` + E2E. --- diff --git a/game/game.js b/game/game.js index 28a8b01..2a0ad72 100644 --- a/game/game.js +++ b/game/game.js @@ -51,6 +51,7 @@ // first start (no saved choice yet): default to English, not the browser language if (Kit.store(ID).get('lang', null) === null) L.set('en'); const t = L.t; + const GM = {}; // feature modules, created at the end (see 'feature modules') const store = Kit.store(ID); // steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', autofire: true, cam: 'fpv', arena: 'random', quiet: false, comfort: true }, store.get('settings', {})); @@ -106,63 +107,18 @@ let isDev = false; function refreshDev() { isDev = !fbUser() ? true : !!fbUser().admin; } - // ---- online save: the server is the authority for money, fame, parts and robots ------------------- - // act(): every workshop change goes through RC.Eco (game/eco.js). Applied locally at once; online the same - // action is sent to the server (one at a time, in order) and the server's answer replaces our economy fields. - let actQueue = Promise.resolve(); - function act(a) { - const r = RC.Eco.apply(save, a); - if (!r.ok) return r; - if (gameMode === 'online' && net.enabled && net.uid) { - actQueue = actQueue.then(() => net.api('POST', '/api/online/action', a)).then(res => { - if (!res || !res.save) return; - if (!res.ok || econDiffers(res.save)) { adoptEconomy(res.save); afterEconomy(); } - }, () => {}); - } - return r; - } - const econKey = s => JSON.stringify([s.money, s.fame, s.owned, s.active, (s.robots || []).map(r => r.build)]); - const econDiffers = srv => econKey(srv) !== econKey(save); - // keepLooks: robot names/paint are client-owned - keep ours (they may not be uploaded yet) - function adoptEconomy(srv, keepLooks = true) { - const looks = keepLooks && save.robots ? save.robots.map(r => ({ name: r.name, paint: r.paint })) : []; - for (const k of RC.Eco.ECONOMY) if (srv[k] !== undefined) save[k] = srv[k]; - if (keepLooks && looks.length === save.robots.length) save.robots.forEach((r, i) => { r.name = looks[i].name; r.paint = looks[i].paint; }); - RC.Eco.mirror(save); - slot.save(save); - } - function afterEconomy() { - hud(); - if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); if (editorOpen) renderWeaponEditor(); } - } - // cosmetics (names, paint, flag, ...) are client-owned: debounced upload, the server keeps only those fields - let pushTimer = null; - const cosmetics = () => { - const c = {}; - for (const k of RC.Eco.COSMETIC) if (save[k] !== undefined) c[k] = save[k]; - c.robots = save.robots.map(r => ({ name: r.name, paint: r.paint })); - return c; - }; - function onlinePush() { clearTimeout(pushTimer); pushTimer = setTimeout(onlineFlush, 1500); } - function onlineFlush() { - clearTimeout(pushTimer); - if (gameMode === 'online' && save && net.uid) net.api('PUT', '/api/online/save', cosmetics()); - } - // after login / page load: economy from the server; cosmetics from whichever copy is newer - function onlinePull() { - if (gameMode !== 'online' || !net.uid) return; - const uid = net.uid; - net.api('GET', '/api/online').then(srv => { - if (!srv || !save || gameMode !== 'online' || net.uid !== uid) return; - const serverNewer = (+srv.ts || 0) > (+save.ts || 0); - if (serverNewer) { for (const k of RC.Eco.COSMETIC) if (srv[k] !== undefined) save[k] = srv[k]; } - adoptEconomy(srv, !serverNewer); - repairSave(); - RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); - if (!serverNewer) onlinePush(); - afterEconomy(); - }); - } + // ---------------------------------------------------------------- online (game/online.js) + function act(...a) { return GM.online.act(...a); } + function endOnlineFight(...a) { return GM.online.endOnlineFight(...a); } + function onlineFightLost(...a) { return GM.online.onlineFightLost(...a); } + function onlineFlush(...a) { return GM.online.onlineFlush(...a); } + function onlinePull(...a) { return GM.online.onlinePull(...a); } + function onlinePush(...a) { return GM.online.onlinePush(...a); } + function renderLobby(...a) { return GM.online.renderLobby(...a); } + function showLobby(...a) { return GM.online.showLobby(...a); } + function showOnlineLogin(...a) { return GM.online.showOnlineLogin(...a); } + function startOnline(...a) { return GM.online.startOnline(...a); } + const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX']; const flagHtml = c => ``; const lobby = net.enabled ? RC.Lobby({ net }) : null; @@ -182,57 +138,11 @@ }, }); - // ---------------------------------------------------------------- sound (ComfyGen clips + synth fallback) - const last = {}; - const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; }; - const SFX = { - click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); }, - buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); }, - deny() { audio.tone(160, 0.15, 'square', 0.12, -40); }, - beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); }, - clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); }, - gate() { // metal garage door rolling open - audio.noise(1.0, 0.4, 1500); audio.noise(0.9, 0.3, 500, 0.05); // metal roll rumble - audio.tone(110, 0.9, 'sawtooth', 0.1, 70); // servo whir rising - for (let k = 0; k < 6; k++) audio.tone(170 + k * 28, 0.05, 'square', 0.07, 0, k * 0.11); // chain clanks - audio.noise(0.25, 0.55, 300, 0.9); audio.tone(58, 0.4, 'sine', 0.5, -22, 0.9); // heavy end clunk - }, - win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); }, - lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); }, - event(e) { - switch (e.type) { - case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break; - case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break; - case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break; - case 'swing': audio.noise(0.15, 0.12, 900); break; - case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break; - case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break; - case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break; - case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break; - case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break; - case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break; - case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break; - case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break; - case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break; - case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break; - case 'broke': audio.sfx('sfx_hit'); audio.noise(0.45, 0.5, 900); audio.tone(240, 0.35, 'sawtooth', 0.22, -190); break; - case 'mine_drop': audio.tone(520, 0.08, 'square', 0.12, -160); audio.noise(0.06, 0.12, 2200); break; - case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break; - case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break; - case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break; - case 'boost': audio.noise(0.4, 0.25, 1800); break; - } - }, - loops(s) { // continuous weapons as short repeated bursts - for (const r of s.robots) { - const q = settings.quiet ? 0.3 : 1, slow = settings.quiet ? 1.7 : 1; // quiet mode: softer + less often - if (r.sawOn && every('saw' + r.i, 200 * slow)) { if (!settings.quiet) audio.sfx('sfx_saw', 0.35); audio.tone(360 + Math.random() * 40, 0.12, 'triangle', 0.02 * q); } - if (r.flameOn && every('fl' + r.i, 120 * slow)) audio.noise(0.14, 0.12 * q, 900); - if (r.gunOn && every('gun' + r.i, 70 * slow)) audio.noise(0.04, 0.16 * q, 3500); - if (r.spin > 0.2 && every('spin' + r.i, 100 * slow)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin * q); - } - }, - }; + // ---------------------------------------------------------------- sound (game/sfx.js) + const SFX = RC.GameSfx(audio, settings); + // rate limit for repeating inputs (gamepad start button) + const lastT = {}; + const every = (k, ms) => { const n = performance.now(); if (lastT[k] && n - lastT[k] < ms) return false; lastT[k] = n; return true; }; // ---------------------------------------------------------------- view const cv = $('cv'); @@ -309,146 +219,13 @@ }); addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } }); - // ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ---- - function refreshEditorRobot() { view.showGarage(save.build, paintObj()); view.freeze(true); view.setEditWeapon(editSel); } - function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor + // ---------------------------------------------------------------- workshop (game/workshop.js) + function paintLeave(...a) { return GM.workshop.paintLeave(...a); } + function paintTab(...a) { return GM.workshop.paintTab(...a); } + function refreshEditorRobot(...a) { return GM.workshop.refreshEditorRobot(...a); } + function renderHangar(...a) { return GM.workshop.renderHangar(...a); } + function renderWeaponEditor(...a) { return GM.workshop.renderWeaponEditor(...a); } - // weapon detail chips (mirrors the shop's part chips, weapon stats only) - function wChips(p) { - const s = []; - if (p.dmg) s.push(`${t('st_dmg', { n: p.dmg })}`); - if (p.dps) s.push(`${t('st_dps', { n: p.dps })}`); - if (p.range) s.push(`${t('st_range', { n: p.range })}`); - s.push(`⌨ ${t('hk_weapon')}`); - s.push(`⚖️ ${p.weight} kg`); - if (p.power) s.push(`⚡ ${p.power}`); - return s.join(''); - } - // show the clicked weapon live on the robot (a mounted one, else a temporary front preview) - function previewWeapon(id) { - const weps = save.build.weapons || []; - const idx = weps.findIndex(w => w.id === id); - if (idx >= 0) { editSel = idx; refreshEditorRobot(); } - else { - const pv = Object.assign({}, save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) }); - view.showGarage(pv, paintObj()); view.freeze(true); view.setEditWeapon(weps.length); - } - } - function renderWeaponEditor() { - const cards = $('cards'), wp = $('wplace'); if (!save || !cards) return; - const b = save.build, weps = b.weapons || []; - editSel = Math.min(editSel, Math.max(0, weps.length - 1)); - const cat = RC.partsFor('weapon'); - const canAdd = weps.length < RC.MAX_WEAPONS; - if (!wPrev || !RC.PARTS[wPrev]) wPrev = (weps[editSel] && weps[editSel].id) || cat[0].id; - // right (#cards): the weapon catalog, same card grid as the other slots — click = preview - cards.className = ''; - cards.innerHTML = cat.map(p => { - const mounted = weps.filter(w => w.id === p.id).length; - const badge = mounted ? `×${mounted}` : ''; - const price = `
🪙 ${Kit.fmt(p.cost)}
`; - return `
${badge}${RC.pic('part_' + p.id, GLYPH_SLOT.weapon)}
${p.name}
${price}
`; - }).join(''); - cards.querySelectorAll('[data-prev]').forEach(x => x.onclick = () => { wPrev = x.dataset.prev; SFX.click(); previewWeapon(wPrev); renderWeaponEditor(); }); - // detail panel: previewed weapon + Montieren / Entfernen (like the other slots) - const dp = $('detail'), pv = RC.PARTS[wPrev]; - if (dp && pv) { - const mounted = weps.filter(w => w.id === wPrev).length, poor = save.money < pv.cost; - let act = ``; - if (mounted) act += ``; - if (!canAdd) act += `${t('ed_max', { n: RC.MAX_WEAPONS })}`; - dp.innerHTML = `${RC.pic('part_' + wPrev, GLYPH_SLOT.weapon)} -
${pv.name}${mounted ? ` ×${mounted}` : ''}
-
${t('pd_' + wPrev)}
${wChips(pv)}
-
${act}
`; - dp.querySelectorAll('button[data-wact]').forEach(x => x.onclick = () => { - if (x.dataset.wact === 'add') addWeapon(wPrev); - else { const i = weps.map(w => w.id).lastIndexOf(wPrev); if (i >= 0) removeWeapon(i); } - }); - } - // left (#wplace): placement of the active mounted weapon + shape (no sell list) - if (wp) { - const sel = weps[editSel]; - const sides = [['front', t('mt_front')], ['back', t('mt_back')], ['left', t('mt_left')], ['right', t('mt_right')]]; - const srow = (key, label, lo, hi) => { const val = (b.body && b.body[key]) || 1; return `
${t('des_' + label)}${Math.round(val * 100)}%
`; }; - wp.classList.remove('hide'); - wp.innerHTML = - `
${t('ed_weapons')} ${weps.length}/${RC.MAX_WEAPONS}
` - + (sel ? `
${t('ed_place')} — ${RC.PARTS[sel.id].name}
` - + `
${sides.map(([k, lb]) => ``).join('')}
` - + `
${t('des_height')}${Math.round(((sel.up || 0) + 0.3) / 0.9 * 100)}%
` - : `${t('ed_noweapons')}`) - + `
${t('s_body')}
${srow('hx', 'height', 0.7, 1.6)}${srow('wx', 'width', 0.8, 1.4)}${srow('lx', 'length', 0.8, 1.3)}`; - wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; act({ type: 'weaponPlace', index: editSel, side: x.dataset.side }); SFX.click(); reDrawEditor(); }); - if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; // live preview while dragging - if ($('edUp')) $('edUp').onchange = e => { if (sel) act({ type: 'weaponPlace', index: editSel, up: +e.target.value }); reDrawEditor(); }; - wp.querySelectorAll('[data-body]').forEach(x => { - x.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); }; - x.onchange = e => { act({ type: 'body', [e.target.dataset.body]: +e.target.value }); reDrawEditor(); }; - }); - } - if (weps[editSel] && weps[editSel].id === wPrev) view.setEditWeapon(editSel); - } - function addWeapon(id) { - if (!act({ type: 'weaponAdd', part: id }).ok) { SFX.deny(); return; } - editSel = save.build.weapons.length - 1; wPrev = id; view.setEditWeapon(editSel); - SFX.buy(); reDrawEditor(); - } - function removeWeapon(i) { - if (!act({ type: 'weaponRemove', index: i }).ok) { SFX.deny(); return; } - if (editSel >= save.build.weapons.length) editSel = Math.max(0, save.build.weapons.length - 1); - view.setEditWeapon(editSel); - SFX.buy(); reDrawEditor(); - } - - // ---- paint tab: 3 save slots + quick colours + the inline painter (all inside #cards) ---- - const phex = c => '#' + (c >>> 0).toString(16).padStart(6, '0'); - function paintTab(el) { - let hdr = $('paintHdr'); - if (!hdr) { el.innerHTML = ''; hdr = document.createElement('div'); hdr.id = 'paintHdr'; hdr.className = 'phdr'; el.appendChild(hdr); } - $('shop').classList.add('paintmode'); // hide category tabs / detail / fitted bar while painting - renderPaintHeader(hdr); - if (!painter.isOpen) painter.open(el); // mount the painter inline, below the header - } - function paintLeave() { - $('shop').classList.remove('paintmode'); - if (!painter.isOpen) return; - const art = painter.hasArt(); - save.paint.decal = art ? layer.toDataURL('image/png') : null; save.paint.drawn = art; - painter.close(); persist(); - const hdr = $('paintHdr'); if (hdr) hdr.remove(); - } - function renderPaintHeader(hdr) { - const slots = save.paintSlots || []; - hdr.innerHTML = - `
${slots.map((s, i) => `
${s.decal ? '🖌' : ''}
`).join('')}
` - + `

${t('paint_body')}

` - + `

${t('paint_accent')}

` - + `

${t('paint_schemes')}

`; - const lockP = c => (RC.PAINT_REWARDS || []).includes(c) && !(save.unlockedPaints || []).includes(c); // reward colour, not earned yet - for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) { - $(id).innerHTML = RC.PAINTS.map(c => `${lockP(c) ? '🔒' : ''}`).join(''); - $(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { if (sw.classList.contains('locked')) { SFX.deny && SFX.deny(); return; } save.paint[key] = +sw.dataset.c; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); - } - $('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = save.paint.body === b2 && save.paint.accent === a2; return ``; }).join(''); - $('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint.body = +sw.dataset.b; save.paint.accent = +sw.dataset.a; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); - hdr.querySelectorAll('[data-load]').forEach(x => x.onclick = e => { if (e.target.dataset.save) return; loadPaintSlot(+x.dataset.load); }); - hdr.querySelectorAll('[data-save]').forEach(x => x.onclick = e => { e.stopPropagation(); savePaintSlot(+x.dataset.save); }); - } - function loadPaintSlot(i) { - const s = save.paintSlots[i]; if (!s) return; - save.paintSlot = i; - save.paint.body = s.body; save.paint.accent = s.accent; save.paint.decal = s.decal || null; save.paint.drawn = !!s.drawn; - SFX.click(); persist(); - RC.layerFromData(layer, save.paint.decal, () => { view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); }); - const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr); - } - function savePaintSlot(i) { - const art = painter.hasArt(); - save.paintSlots[i] = { body: save.paint.body, accent: save.paint.accent, decal: art ? layer.toDataURL('image/png') : (save.paint.decal || null), drawn: art || !!save.paint.drawn }; - save.paintSlot = i; SFX.buy(); persist(); - const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr); - } // ---------------------------------------------------------------- state let mode = 'intro'; // intro | title | account | garage | league | fight | pause | result @@ -636,151 +413,8 @@ }); } - // ---------------------------------------------------------------- online lobby - // The server owns presence, challenges and fights (server/lobby.js). This draws its state and forwards clicks. let onlineReady = false, lobbyRows = [], lobbyRoom = null; // lobbyRoom = country code or 'all' (which room I view) let joinedRoom = null; // the country room I am present in (others see me there, with MY flag); default = my flag - const myRoom = () => joinedRoom || (FLAGS.includes(save.flag) ? save.flag : 'XX'); - const pendingOut = () => (lobby ? lobby.pending : null); - function wireLobby() { - lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); }); - lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); }); - lobby.onMatch(m => startOnlineFight(m)); - lobby.onEnd(m => onlineFightEnded(m)); - lobby.onCancel(c => { - if (mode === 'lobby') { renderLobby(); if (c.outgoing) SFX.deny(); } - else if (!c.outgoing && $('cYes')) hideOverlay(); // the challenger gave up while I was asked - }); - lobby.onError(code => { - SFX.deny(); - if (mode === 'lobby') { renderLobby(); const el = $('lMsg'); if (el) el.textContent = errText(code); } - else if (mode === 'garage') $('mechTip').textContent = errText(code); - }); - net.socket.on('outdated', () => { - card(`

${t('reload_title')}

${t('e_OUTDATED')}

`, { bg: 'bg_title.jpg' }); - $('rNow').onclick = () => location.reload(); - }); - net.socket.on('replaced', () => { if (mode === 'lobby') { const el = $('lMsg'); if (el) el.textContent = t('e_REPLACED'); } }); - } - async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page) - if (!net.enabled) return; - if (gameMode !== 'online') { setMode('online'); if (save) { loadSave(); hud(); } } // online uses its own save - if (!net.auth.current) { - if (save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously - showOnlineLogin(false, null, 'online'); return; - } - if (!save || !slot) { if (!fbAcc()) accounts.guest(); loadSave(); } - if (!onlineReady) { wireLobby(); onlineReady = true; } - lobby.enter(); - ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby - } - async function joinAnon() { - if (!save) { accounts.guest(); loadSave(); } - const r = await net.auth.guest(playerName() || t('guest')); - if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; } - hud(); refreshDev(); loadSave(); startOnline(); - } - const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')'); - function showOnlineLogin(reg, errKey, next) { - next = next || 'career'; - setScreen('account'); - const f = reg - ? ` - ` - : ``; - card(`

${reg ? t('register') : t('login')}

${t('online_login_text')}

-
${f} -
- ${reg ? `` : ''} -
${errKey ? errText(errKey) : ''}
-
-

${reg ? '' : t('no_account') + ' '}

- ${next === 'online' ? `
` : ''}`, { bg: 'bg_title.jpg' }); - if ($('oAnon')) $('oAnon').onclick = () => { SFX.click(); joinAnon(); }; - if ($('oPriv')) $('oPriv').onclick = () => { SFX.click(); showLegal(() => showOnlineLogin(true, null, next), 'privacy'); }; - $('oBack').onclick = () => { SFX.click(); showTitle(); }; - $('oToggle').onclick = () => { SFX.click(); showOnlineLogin(!reg, null, next); }; - $('oGo').onclick = async () => { - if (reg && $('oConsent') && !$('oConsent').checked) { SFX.deny(); $('oErr').textContent = t('consent_required'); return; } - $('oGo').disabled = true; - const r = reg ? await net.auth.register($('oName').value, $('oPass').value, $('oMail').value) - : await net.auth.login($('oLogin').value, $('oPass').value); - if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; } - SFX.click(); hud(); refreshDev(); - if (next === 'online') { loadSave(); startOnline(); } else enterAccount(reg); - }; - overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') $('oGo').click(); })); - setTimeout(() => { const el = $(reg ? 'oName' : 'oLogin'); if (el) el.focus(); }, 50); - } - function showLobby() { - if (!lobbyRoom) lobbyRoom = 'all'; // filter: 'all' or a country code - setScreen('lobby'); renderLobby(); - } - // two-pane lobby: country rooms on the left, players of the chosen room on the right (own style, not copied art) - function renderLobby() { - const code = r => { const c = r.room || r.flag; return FLAGS.includes(c) ? c : 'XX'; }; // group by the room a player JOINED, not their flag - const all = lobbyRows; - const myFlag = FLAGS.includes(save.flag) ? save.flag : 'XX', mine = myRoom(); - // I am in the lobby too: count myself in the room I joined (and in "all"), and only list me there - const total = all.length + 1; - const cnt = f => all.filter(r => code(r) === f).length + (f === mine ? 1 : 0); - const here = lobbyRoom === 'all' ? all : all.filter(r => code(r) === lobbyRoom); - const showMe = lobbyRoom === 'all' || lobbyRoom === mine; - const out = pendingOut(); - const flagOpts = FLAGS.map(f => ``).join(''); - const room = (f, label, flag) => ``; - const rooms = room('all', t('all_countries'), false) + FLAGS.map(f => room(f, t('cc_' + f), true)).join(''); - const action = r => (r.state === 'idle' && !out ? `` : `${r.state === 'idle' ? '' : t('busy')}`); - const prow = (r, me) => `
${flagHtml(me ? save.flag : r.flag)}${esc(me ? playerName() : r.name)}${me ? ` (${t('you')})` : ''}⭐ ${Kit.fmt((me ? save.fame : r.fame) | 0)}${me ? '' : action(r)}
`; - const list = here.map(r => prow(r, false)).join(''); - const title = lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(lobbyRoom) + ' ' + t('cc_' + lobbyRoom); - const offline = lobby && !lobby.connected ? `

${t('net_connecting')}

` : ''; - overlay.innerHTML = `
-
🌍 ${t('lobby')}
${rooms}
-
-
${title} (${here.length + (showMe ? 1 : 0)}) -
-
${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `
${t('lobby_empty')}
`)}
- ${out ? `

${t('waiting_accept')}

` : ''} - ${offline}

-
-
`; - overlay.classList.remove('hide'); overlay.classList.remove('clear'); - overlay.style.backgroundImage = `linear-gradient(rgba(5,6,10,.6), rgba(5,6,10,.8)), url("${img('bg_title.jpg')}")`; - overlay.querySelectorAll('.rroom').forEach(b => { b.onclick = () => { - SFX.click(); lobbyRoom = b.dataset.f; - if (lobbyRoom !== 'all') { joinedRoom = lobbyRoom; if (lobby) lobby.setRoom(joinedRoom); } // joining a country = be present there - renderLobby(); - }; }); - $('lFlag').onchange = e => { save.flag = e.target.value; persist(); onlineFlush(); renderLobby(); }; - overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); lobby.challenge(b.dataset.uid); renderLobby(); }; }); - if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); renderLobby(); }; - $('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle') || all.find(r => r.state === 'idle'); if (idle && !pendingOut()) { SFX.click(); lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); }; - $('lBack').onclick = () => { SFX.click(); if (save) openGarage(); else showTitle(); }; - } - function showIncoming(c) { - card(`

${t('challenge_in')}

${flagHtml(c.fromFlag)} ${esc(c.fromName)} ${t('wants_fight')}

-
`); - $('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); }; - $('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (mode === 'lobby') renderLobby(); else hideOverlay(); }; - } - // server says: fight on (also after a reconnect into a running fight) - function startOnlineFight(m) { - const mine = m.robots[m.seat], other = m.robots[1 - m.seat]; - const opp = { name: other.name, build: other.build, paint: other.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: other.flag }; - prepOpp(opp, () => startFight(opp, false, false, { id: m.matchId, seat: m.seat, seed: m.seed, arena: m.arena, countdown: m.countdown, myBuild: mine.build })); - } - // server result + rewards (the fight on screen ends with it; if we missed the fight, just take the new save) - function onlineFightEnded(m) { - if (F && F.online && F.online.id === m.matchId && !F.ended) { - F.serverEnd = m; - F.s.result = RC.Proto.localResult(m.seat, m.result); - F.s.endIn = 0; - return; - } - if (m.save && gameMode === 'online') { adoptEconomy(m.save); afterEconomy(); } - } - // ---------------------------------------------------------------- accounts function showLogin(errKey) { setScreen('account'); @@ -920,41 +554,6 @@ } save.paintSlot = Kit.clamp(save.paintSlot | 0, 0, 2); } - // hangar: switch / add / delete robot slots (owned parts are shared) - function switchRobot(i) { - if (i === save.active || !save.robots[i]) return; - syncActive(); - if (!act({ type: 'robotSwitch', index: i }).ok) return; - persist(); - RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); - shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar(); - } - function addRobot() { - syncActive(); - if (!act({ type: 'robotNew', name: t('robot_n', { n: save.robots.length + 1 }) }).ok) { SFX.deny(); return; } - persist(); - RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); - shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar(); - SFX.buy(); - } - function delRobot(i) { - syncActive(); - if (!act({ type: 'robotDelete', index: i }).ok) { SFX.deny(); return; } - persist(); RC.layerFromData(layer, save.paint.decal, () => {}); shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar(); - } - // hangar management (shop top-tab): list of robots with weapon, switch / delete + add button - function renderHangar(el) { - el = el || $('cards'); if (!el) return; - const rows = save.robots.map((r, i) => `
-
${esc(r.name)}
${esc(weaponName(r.build))}
- ${i === save.active ? `${t('active_robot')}` : ``} - ${save.robots.length > 1 ? `` : ''}
`).join(''); - el.innerHTML = `
${rows}
- ${save.robots.length < MAX_ROBOTS ? `` : `

${t('hangar_full')}

`}`; - el.querySelectorAll('[data-use]').forEach(b => { b.onclick = () => { SFX.click(); switchRobot(+b.dataset.use); shop.setTab('build'); } ; }); - el.querySelectorAll('[data-del]').forEach(b => { b.onclick = () => { SFX.click(); delRobot(+b.dataset.del); renderHangar(); } ; }); - if ($('hAdd')) $('hAdd').onclick = () => { addRobot(); shop.setTab('build'); }; - } function signOut() { persist(); cloudFlush(); // push now, while we still have the auth token @@ -975,256 +574,20 @@ }; function currentBack() { return mode === 'garage' ? openGarage : mode === 'league' ? showLeague : mode === 'result' ? openGarage : mode === 'title' ? showTitle : save ? openGarage : showTitle; } - // ---------------------------------------------------------------- settings / help / ranking - function showSettings(back) { - overlayEnter(); - const prev = mode; - const seg = (id, val, opts) => `
${opts.map(([v, label]) => ``).join('')}
`; - const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null); - const item = (label, ctl) => `${label}${ctl}`; - card(`

${t('settings')}

- ${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))} - ${save ? item(t('s_country'), ``) : ''} - ${item(t('s_music'), ``)} - ${item(t('s_sfx'), ``)} - ${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))} - ${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))} - ${item(t('s_comfort'), seg('sComfort', settings.comfort ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} - ${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))} - ${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} - ${item(t('s_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))} - ${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))} - ${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} -
- ${isDev && save ? `
🛠 Dev · Coins
- -
` : ''} -
${t('s_account')} - ${who ? '👤 ' + esc(who.name) + '' + (who.email ? ' ' + esc(who.email) + '' : '') : '👤 ' + t('guest')} - ${save ? `` : ''}
-
- ${save ? `` : ''}
`, { wide: true, clear: prev === 'title' || prev === 'intro' }); - const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; }); - segOn('sLang', v => { L.set(v); showSettings(back); }); - segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); }); - segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); }); - segOn('sSteer', v => { settings.steer = v; saveSettings(); }); - segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); }); - segOn('sComfort', v => { settings.comfort = v === '1'; saveSettings(); if (view && view.setComfort) view.setComfort(settings.comfort); }); - segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); }); - segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); }); - segOn('sArena', v => { settings.arena = v; saveSettings(); }); - if ($('sCountry')) $('sCountry').onchange = e => { save.flag = e.target.value; save.flagSet = true; persist(); hud(); }; - $('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol); - $('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value); - $('sSfx').onchange = () => SFX.click(); - $('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); }; - if (isDev && save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => { - SFX.buy(); const v = b.dataset.coin; - act({ type: 'devCoins', money: v === 'set800' ? 800 : Math.min(1e9, (save.money | 0) + (+v || 0)) }); - persist(); hud(); showSettings(back); - }); - if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); }; - if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); }; - $('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); }; - if ($('sLegal')) $('sLegal').onclick = () => { SFX.click(); showLegal(() => showSettings(back)); }; - $('bBack').onclick = () => { SFX.click(); back(); }; - } - function keysHtml() { - return `
W A S D / ↑ ← ↓ →${t('key_drive')}${t('key_space')}${t('key_weapon')} - Shift / E${t('key_tower')}C${t('key_cam')}P / Esc${t('pause')}M${t('sound_on')} / ${t('sound_off')} - ${t('key_pad')}${t('key_pad_text')}
`; - } - // first start: four short cards instead of the full help page - const TUT = ['tut_1', 'tut_2', 'tut_3', 'tut_4']; - function startTutorial(done) { - let i = 0; - const step = () => { - if (i >= TUT.length) { done(); return; } - const n = i + 1; - overlayEnter(); - card(`

${t('tut_title')} ${n}/${TUT.length}

-

${t(TUT[i])}

-
-
`, - { bg: 'bg_workshop.jpg' }); - $('tNext').onclick = () => { SFX.click(); i++; step(); }; - $('tSkip').onclick = () => { SFX.click(); done(); }; - }; - step(); - } + // ---------------------------------------------------------------- pages (game/pages.js) + function ensureFlag(...a) { return GM.pages.ensureFlag(...a); } + function boardHtml(...a) { return GM.pages.boardHtml(...a); } + function fillBoard(...a) { return GM.pages.fillBoard(...a); } + function liveBanner(...a) { return GM.pages.liveBanner(...a); } + function showAchievements(...a) { return GM.pages.showAchievements(...a); } + function showHelp(...a) { return GM.pages.showHelp(...a); } + function showLegal(...a) { return GM.pages.showLegal(...a); } + function showMissions(...a) { return GM.pages.showMissions(...a); } + function showRanking(...a) { return GM.pages.showRanking(...a); } + function showSettings(...a) { return GM.pages.showSettings(...a); } + function startTutorial(...a) { return GM.pages.startTutorial(...a); } - // first start: pick the country whose flag shows on the ranking / in the lobby (changeable later in settings) - function chooseFlag(done) { - overlayEnter(); - let pick = (save && FLAGS.includes(save.flag)) ? save.flag : 'XX'; - card(`

🌍 ${t('country_title')}

${t('country_text')}

-
${FLAGS.map(f => ``).join('')}
-
`, { bg: 'bg_title.jpg', wide: true }); - overlay.querySelectorAll('.flagbtn').forEach(b => b.onclick = () => { pick = b.dataset.f; SFX.click(); overlay.querySelectorAll('.flagbtn').forEach(x => x.classList.toggle('on', x.dataset.f === pick)); }); - $('cfGo').onclick = () => { if (save) { save.flag = pick; save.flagSet = true; persist(); } SFX.click(); done(); }; - } - const ensureFlag = done => { if (save && !save.flagSet) chooseFlag(done); else done(); }; - - // one line for the running event and one for the admin's message - function liveBanner() { - const out = []; - if (LIVE.event) { - const n = liveText(LIVE.event.name) || t('event_running'); - const extra = LIVE.event.prizeMul !== 1 ? ` · ${t('event_prize', { n: LIVE.event.prizeMul })}` : ''; - out.push(`
${t('event')}${esc(n)}${extra}
`); - } - const m = liveText(LIVE.motd); - if (m) out.push(`

${esc(m)}

`); - return out.join(''); - } - - function showAchievements(back) { - overlayEnter(); - const P = RC.Progress, r = P.rankOf(save.fame); - const pct = Math.round(r.pct * 100); - const nextLine = r.next - ? t('rank_next', { n: t('rank_' + r.next.key), f: Kit.fmt(r.next.at - save.fame) }) - : t('rank_top'); - const rows = P.ACHIEVEMENTS.map(a => { - const done = !!(save.ach && save.ach[a.id]); - return `
${done ? '🏅' : '🔒'} - ${t('ach_' + a.id)}
${t('achd_' + a.id)}
- ${Kit.fmt(a.reward)}
`; - }).join(''); - card(`

🏅 ${t('achievements')}

-
${t('rank_' + r.key)}${nextLine}
-
-

${t('ach_done', { n: P.earned(save), m: P.total })}

-
${rows}
-
`, { wide: true, bg: 'bg_title.jpg' }); - $('bBack').onclick = () => { SFX.click(); back(); }; - } - - // campaign missions page: 3 daily + 1 weekly with progress bars + reset countdown - function showMissions(back) { - overlayEnter(); - ensureMissions(); - const daily = (save.missions && save.missions.daily) || [], weekly = (save.missions && save.missions.weekly) || []; - const hrs = ms => Math.max(1, Math.ceil(ms / 3600000)); - const toDay = 86400000 - (Date.now() % 86400000), toWeek = 604800000 - (Date.now() % 604800000); - const row = m => { - const prog = Math.min(m.prog || 0, m.goal), pct = Math.round(prog / m.goal * 100); - const rew = `🪙 ${Kit.fmt(m.reward)}${m.fame ? ' · ⭐' + m.fame : ''}${typeof m.unlock === 'number' ? ' · 🎨' : ''}`; - return `
${m.done ? '✅' : '🎯'} -
${t('mission_' + m.id)}
${t('missd_' + m.id)}
-
-
${rew}${prog}/${m.goal}
`; - }; - card(`

🎯 ${t('missions')}

-

${t('miss_daily')} · ${t('miss_reset_in', { n: hrs(toDay) })}

-
${daily.map(row).join('')}
-

${t('miss_weekly')} · ${t('miss_reset_in', { n: hrs(toWeek) })}

-
${weekly.map(row).join('')}
-
`, { wide: true, bg: 'bg_title.jpg' }); - $('bBack').onclick = () => { SFX.click(); back(); }; - } - - function showHelp(back) { - overlayEnter(); - card(`

${t('how_to')}

${t('help_text')}

${keysHtml()} -

${t('help_arena')}

`, { bg: 'bg_title.jpg' }); - $('bOk').onclick = () => { SFX.click(); back(); }; - } - // legal pages (Impressum / Datenschutz) — placeholders, Michael fills his data in lang.js - function showLegal(back, which) { - overlayEnter(); - which = which === 'privacy' ? 'privacy' : 'impressum'; - const seg = ['impressum', 'privacy'].map(k => ``).join(''); - card(`

${t('legal')}

${seg}
-
${t(which + '_text')}
-
`, { wide: true, bg: 'bg_title.jpg' }); - overlay.querySelectorAll('.legalseg button').forEach(b => b.onclick = () => { SFX.click(); showLegal(back, b.dataset.l); }); - $('bOk').onclick = () => { SFX.click(); back(); }; - } let rankSub = null, titleRankSub = null, boardFame = {}, boardIdx = {}; - const closeRank = () => { if (rankSub) { rankSub.close(); rankSub = null; } }; - function showRanking(back) { - overlayEnter(); - card(`

🏆 ${t('ranking')} ${rank.enabled ? '● ' + t('rank_live') + '' : ''}

-
  1. ${t('loading')}
-
`, { bg: 'bg_title.jpg' }); - $('bBack').onclick = () => { SFX.click(); closeRank(); back(); }; - boardFame = {}; boardIdx = {}; - const myUid = (fbAcc() && fbAcc().uid) || net.uid; - closeRank(); - if (rank.enabled) rankSub = rank.watch(rows => drawBoard($('board'), rows, myUid)); - else drawBoard($('board'), [], myUid); - } - // animated live board: FLIP row reordering, fame bars, count-up numbers, rank ▲/▼ - function animNum(el, from, to) { - if (!el) return; const t0 = performance.now(), dur = 520; - (function step(now) { - const k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3); - el.textContent = Kit.fmt(Math.round(from + (to - from) * e)); - if (k < 1 && el.isConnected) requestAnimationFrame(step); - })(t0); - } - function drawBoard(el, rows, myUid) { - if (!el) return; - if (!rows.length) { el.innerHTML = `
  • ${t('no_scores')}
  • `; boardFame = {}; boardIdx = {}; return; } - const max = Math.max(1, rows[0].fame); - const prevTop = {}; - el.querySelectorAll('.brow').forEach(li => { prevTop[li.dataset.key] = li.getBoundingClientRect().top; }); - el.innerHTML = rows.map((r, i) => { - const me = r.key === myUid; - const was = boardIdx[r.key]; - const arr = (was != null && was !== i) ? (i < was ? '▲' : '▼') : ''; - return `
  • - ${i + 1}${flagHtml(r.flag || 'XX')} - ${esc(r.name)}${me ? ` (${t('you')})` : ''}${arr} - 0
  • `; - }).join(''); - el.querySelectorAll('.brow').forEach(li => { - const key = li.dataset.key, to = +li.dataset.fame, from = boardFame[key] != null ? boardFame[key] : to; - animNum(li.querySelector('.val b'), from, to); boardFame[key] = to; - if (prevTop[key] != null) { - const d = prevTop[key] - li.getBoundingClientRect().top; - if (d) { li.style.transform = `translateY(${d}px)`; li.style.transition = 'none'; - requestAnimationFrame(() => { li.style.transition = 'transform .45s cubic-bezier(.2,.8,.2,1)'; li.style.transform = ''; }); } - } - }); - boardIdx = {}; rows.forEach((r, i) => boardIdx[r.key] = i); - } - function confirmReset(back) { - card(`

    ${t('reset')}

    ${t('reset_text')}

    `); - $('bNo').onclick = () => { SFX.click(); back(); }; - $('bYes').onclick = () => { Object.assign(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); }; - } - // the rank badge opens the achievements page - $('hTour').onclick = () => { SFX.click(); if (gameMode === 'campaign') { if (tourState()) showTournament(); else showLeague(); } }; // online tournament: server-side later (plan P2-6) - $('chipFame').onclick = () => { - if (!save || mode === 'intro' || mode === 'title') return; - if (mode === 'fight') togglePause(); - SFX.click(); - showAchievements(mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack()); - }; - $('bSettings').onclick = () => { - if (mode === 'fight') togglePause(); - if (mode === 'intro') skipIntro(); - SFX.click(); - const back = mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack(); - showSettings(back); - }; - - function boardHtml() { return (rank.enabled && gameMode === 'online') ? `

    ${t('ranking')}

    1. ${t('loading')}
    ` : ''; } - async function fillBoard() { - const el = $('board'); - if (!el) return; - const myUid = (fbAcc() && fbAcc().uid) || net.uid; - try { - const rows = await rank.once(10); - el.innerHTML = rows.length - ? rows.map((r, i) => `
  • ${i + 1}.${esc(r.name)}${Kit.fmt(r.fame)}
  • `).join('') - : `
  • ${t('no_scores')}
  • `; - } catch (e) { el.innerHTML = `
  • ${t('scores_offline')}
  • `; } - } - // ---------------------------------------------------------------- shop + league function openGarage() { hideOverlay(); @@ -1791,37 +1154,6 @@ $('bTour').onclick = () => { SFX.click(); showTournament(); }; } - // live fight over: the server already booked prize, repairs and achievements - show them and take its save - function endOnlineFight(res, won, me) { - if (F.nf) F.nf.stop(); - const m = F.serverEnd, rw = (m && m.reward) || { money: 0, fame: 0, lines: [], ach: [] }; - if (m && m.save) { adoptEconomy(m.save); persist(); } - (won ? SFX.win : SFX.lose)(); - const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat'); - const sm = (m && m.summary) || { dealt: me.dealt, taken: me.taken }; - const rows = rw.lines.map(([k, v]) => `${t(k)}${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}`).join(''); - const ach = (rw.ach || []).map(a => ({ id: a.id, reward: a.reward })); - hud(); - setScreen('result'); - card(`

    ${title}

    ${esc(F.opp.name)} ${F.oppAway ? t('peer_left') : ''}

    -
    ${t('r_dealt')}${Math.round(sm.dealt)}${t('r_taken')}${Math.round(sm.taken)}${rows} - ${rw.fame ? `${t('hud_fame')}+${Kit.fmt(rw.fame)}` : ''}
    - ${achHtml(ach)} -
    `, - { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' }); - $('bLobby').onclick = () => { SFX.click(); showLobby(); }; - $('bShopO').onclick = () => { SFX.click(); openGarage(); }; - } - // the server went silent mid-fight: leave the arena; the result (if any) is booked server-side anyway - function onlineFightLost() { - if (F && F.nf) F.nf.stop(); - SFX.deny(); - setScreen('result'); - card(`

    ${t('net_lost')}

    ${t('match_lost')}

    -
    `, { bg: 'bg_lose.jpg' }); - $('bLobby').onclick = () => { SFX.click(); onlinePull(); showLobby(); }; - } - // ---------------------------------------------------------------- loop let lastNow = 0, fpsN = 0, fpsT = 0, fpsVal = 0; function render(alpha, now) { @@ -1912,6 +1244,47 @@ if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); } }); + // ---------------------------------------------------------------- feature modules + // game.js was split by topic (pages.js, online.js, workshop.js). They share this context: getters always + // return the CURRENT value (save, mode, F change all the time), setters write back into game.js. + const G = { + get $() { return $; }, get CAMS() { return CAMS; }, get FLAGS() { return FLAGS; }, + get GLYPH_SLOT() { return GLYPH_SLOT; }, get L() { return L; }, get MAX_ROBOTS() { return MAX_ROBOTS; }, + get SFX() { return SFX; }, get accounts() { return accounts; }, get achHtml() { return achHtml; }, + get act() { return act; }, get audio() { return audio; }, get card() { return card; }, + get currentBack() { return currentBack; }, get ensureFlag() { return ensureFlag; }, + get ensureMissions() { return ensureMissions; }, get enterAccount() { return enterAccount; }, + get esc() { return esc; }, get fbAcc() { return fbAcc; }, get flagHtml() { return flagHtml; }, + get hideOverlay() { return hideOverlay; }, get hud() { return hud; }, get img() { return img; }, + get layer() { return layer; }, get liveText() { return liveText; }, get loadSave() { return loadSave; }, + get lobby() { return lobby; }, get logout() { return logout; }, get net() { return net; }, + get newSave() { return newSave; }, get openGarage() { return openGarage; }, get overlay() { return overlay; }, + get overlayEnter() { return overlayEnter; }, get paintObj() { return paintObj; }, + get painter() { return painter; }, get persist() { return persist; }, get playerName() { return playerName; }, + get prepOpp() { return prepOpp; }, get rank() { return rank; }, get refreshDev() { return refreshDev; }, + get renderWeaponEditor() { return renderWeaponEditor; }, get repairSave() { return repairSave; }, + get saveSettings() { return saveSettings; }, get setMode() { return setMode; }, + get setScreen() { return setScreen; }, get settings() { return settings; }, get shop() { return shop; }, + get showLeague() { return showLeague; }, get showLegal() { return showLegal; }, + get showTitle() { return showTitle; }, get showTournament() { return showTournament; }, + get skipIntro() { return skipIntro; }, get startFight() { return startFight; }, + get syncActive() { return syncActive; }, get t() { return t; }, get togglePause() { return togglePause; }, + get tourState() { return tourState; }, get weaponName() { return weaponName; }, get F() { return F; }, + get LIVE() { return LIVE; }, get boardFame() { return boardFame; }, set boardFame(v) { boardFame = v; }, + get boardIdx() { return boardIdx; }, set boardIdx(v) { boardIdx = v; }, get editSel() { return editSel; }, + set editSel(v) { editSel = v; }, get editorOpen() { return editorOpen; }, get gameMode() { return gameMode; }, + get isDev() { return isDev; }, get joinedRoom() { return joinedRoom; }, set joinedRoom(v) { joinedRoom = v; }, + get lobbyRoom() { return lobbyRoom; }, set lobbyRoom(v) { lobbyRoom = v; }, + get lobbyRows() { return lobbyRows; }, set lobbyRows(v) { lobbyRows = v; }, get mode() { return mode; }, + set mode(v) { mode = v; }, get onlineReady() { return onlineReady; }, set onlineReady(v) { onlineReady = v; }, + get rankSub() { return rankSub; }, set rankSub(v) { rankSub = v; }, get save() { return save; }, + get slot() { return slot; }, get view() { return view; }, get wPrev() { return wPrev; }, + set wPrev(v) { wPrev = v; }, + }; + GM.pages = RC.GamePages(G); + GM.online = RC.GameOnline(G); + GM.workshop = RC.GameWorkshop(G); + // ---------------------------------------------------------------- start // backend settings; applied as soon as they arrive and whenever the admin changes them RC.Live.load(net, v => { diff --git a/game/index.html b/game/index.html index 2f67595..1911457 100644 --- a/game/index.html +++ b/game/index.html @@ -833,6 +833,10 @@ + + + + diff --git a/game/online.js b/game/online.js new file mode 100644 index 0000000..78cd70e --- /dev/null +++ b/game/online.js @@ -0,0 +1,257 @@ +/* Robot Clash - online play in the browser: server-checked workshop actions (act), online save sync, login card, lobby, live fight start/end. + Part of game.js (split for size): created once by game.js with the shared context G. + Live state (save, mode, F, ...) is read as G.; services/helpers are taken from G at creation. */ +(function (root) { + 'use strict'; + const RC = (root.RC = root.RC || {}); + RC.GameOnline = function (G) { + const { + $, FLAGS, SFX, accounts, achHtml, card, ensureFlag, enterAccount, esc, fbAcc, flagHtml, hideOverlay, hud, + img, layer, loadSave, lobby, net, openGarage, overlay, paintObj, persist, playerName, prepOpp, + refreshDev, renderWeaponEditor, repairSave, setMode, setScreen, shop, showLegal, showTitle, startFight, + t + } = G; + + // ---- online save: the server is the authority for money, fame, parts and robots ------------------- + // act(): every workshop change goes through RC.Eco (game/eco.js). Applied locally at once; online the same + // action is sent to the server (one at a time, in order) and the server's answer replaces our economy fields. + let actQueue = Promise.resolve(); + function act(a) { + const r = RC.Eco.apply(G.save, a); + if (!r.ok) return r; + if (G.gameMode === 'online' && net.enabled && net.uid) { + actQueue = actQueue.then(() => net.api('POST', '/api/online/action', a)).then(res => { + if (!res || !res.save) return; + if (!res.ok || econDiffers(res.save)) { adoptEconomy(res.save); afterEconomy(); } + }, () => {}); + } + return r; + } + const econKey = s => JSON.stringify([s.money, s.fame, s.owned, s.active, (s.robots || []).map(r => r.build)]); + const econDiffers = srv => econKey(srv) !== econKey(G.save); + // keepLooks: robot names/paint are client-owned - keep ours (they may not be uploaded yet) + function adoptEconomy(srv, keepLooks = true) { + const looks = keepLooks && G.save.robots ? G.save.robots.map(r => ({ name: r.name, paint: r.paint })) : []; + for (const k of RC.Eco.ECONOMY) if (srv[k] !== undefined) G.save[k] = srv[k]; + if (keepLooks && looks.length === G.save.robots.length) G.save.robots.forEach((r, i) => { r.name = looks[i].name; r.paint = looks[i].paint; }); + RC.Eco.mirror(G.save); + G.slot.save(G.save); + } + function afterEconomy() { + hud(); + if (G.mode === 'garage') { shop.render(); G.view.showGarage(G.save.build, paintObj()); if (G.editorOpen) renderWeaponEditor(); } + } + // cosmetics (names, paint, flag, ...) are client-owned: debounced upload, the server keeps only those fields + let pushTimer = null; + const cosmetics = () => { + const c = {}; + for (const k of RC.Eco.COSMETIC) if (G.save[k] !== undefined) c[k] = G.save[k]; + c.robots = G.save.robots.map(r => ({ name: r.name, paint: r.paint })); + return c; + }; + function onlinePush() { clearTimeout(pushTimer); pushTimer = setTimeout(onlineFlush, 1500); } + function onlineFlush() { + clearTimeout(pushTimer); + if (G.gameMode === 'online' && G.save && net.uid) net.api('PUT', '/api/online/save', cosmetics()); + } + // after login / page load: economy from the server; cosmetics from whichever copy is newer + function onlinePull() { + if (G.gameMode !== 'online' || !net.uid) return; + const uid = net.uid; + net.api('GET', '/api/online').then(srv => { + if (!srv || !G.save || G.gameMode !== 'online' || net.uid !== uid) return; + const serverNewer = (+srv.ts || 0) > (+G.save.ts || 0); + if (serverNewer) { for (const k of RC.Eco.COSMETIC) if (srv[k] !== undefined) G.save[k] = srv[k]; } + adoptEconomy(srv, !serverNewer); + repairSave(); + RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); }); + if (!serverNewer) onlinePush(); + afterEconomy(); + }); + } + + // ---------------------------------------------------------------- online lobby + // The server owns presence, challenges and fights (server/lobby.js). This draws its state and forwards clicks. + + const myRoom = () => G.joinedRoom || (FLAGS.includes(G.save.flag) ? G.save.flag : 'XX'); + const pendingOut = () => (lobby ? lobby.pending : null); + function wireLobby() { + lobby.onList(rows => { G.lobbyRows = rows; if (G.mode === 'lobby') renderLobby(); }); + lobby.onIncoming(c => { if (G.mode === 'lobby' || G.mode === 'garage') showIncoming(c); }); + lobby.onMatch(m => startOnlineFight(m)); + lobby.onEnd(m => onlineFightEnded(m)); + lobby.onCancel(c => { + if (G.mode === 'lobby') { renderLobby(); if (c.outgoing) SFX.deny(); } + else if (!c.outgoing && $('cYes')) hideOverlay(); // the challenger gave up while I was asked + }); + lobby.onError(code => { + SFX.deny(); + if (G.mode === 'lobby') { renderLobby(); const el = $('lMsg'); if (el) el.textContent = errText(code); } + else if (G.mode === 'garage') $('mechTip').textContent = errText(code); + }); + net.socket.on('outdated', () => { + card(`

    ${t('reload_title')}

    ${t('e_OUTDATED')}

    `, { bg: 'bg_title.jpg' }); + $('rNow').onclick = () => location.reload(); + }); + net.socket.on('replaced', () => { if (G.mode === 'lobby') { const el = $('lMsg'); if (el) el.textContent = t('e_REPLACED'); } }); + } + async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page) + if (!net.enabled) return; + if (G.gameMode !== 'online') { setMode('online'); if (G.save) { loadSave(); hud(); } } // online uses its own save + if (!net.auth.current) { + if (G.save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously + showOnlineLogin(false, null, 'online'); return; + } + if (!G.save || !G.slot) { if (!fbAcc()) accounts.guest(); loadSave(); } + if (!G.onlineReady) { wireLobby(); G.onlineReady = true; } + lobby.enter(); + ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby + } + async function joinAnon() { + if (!G.save) { accounts.guest(); loadSave(); } + const r = await net.auth.guest(playerName() || t('guest')); + if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; } + hud(); refreshDev(); loadSave(); startOnline(); + } + const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')'); + function showOnlineLogin(reg, errKey, next) { + next = next || 'career'; + setScreen('account'); + const f = reg + ? ` + ` + : ``; + card(`

    ${reg ? t('register') : t('login')}

    ${t('online_login_text')}

    +
    ${f} +
    + ${reg ? `` : ''} +
    ${errKey ? errText(errKey) : ''}
    +
    +

    ${reg ? '' : t('no_account') + ' '}

    + ${next === 'online' ? `
    ` : ''}`, { bg: 'bg_title.jpg' }); + if ($('oAnon')) $('oAnon').onclick = () => { SFX.click(); joinAnon(); }; + if ($('oPriv')) $('oPriv').onclick = () => { SFX.click(); showLegal(() => showOnlineLogin(true, null, next), 'privacy'); }; + $('oBack').onclick = () => { SFX.click(); showTitle(); }; + $('oToggle').onclick = () => { SFX.click(); showOnlineLogin(!reg, null, next); }; + $('oGo').onclick = async () => { + if (reg && $('oConsent') && !$('oConsent').checked) { SFX.deny(); $('oErr').textContent = t('consent_required'); return; } + $('oGo').disabled = true; + const r = reg ? await net.auth.register($('oName').value, $('oPass').value, $('oMail').value) + : await net.auth.login($('oLogin').value, $('oPass').value); + if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; } + SFX.click(); hud(); refreshDev(); + if (next === 'online') { loadSave(); startOnline(); } else enterAccount(reg); + }; + overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') $('oGo').click(); })); + setTimeout(() => { const el = $(reg ? 'oName' : 'oLogin'); if (el) el.focus(); }, 50); + } + function showLobby() { + if (!G.lobbyRoom) G.lobbyRoom = 'all'; // filter: 'all' or a country code + setScreen('lobby'); renderLobby(); + } + // two-pane lobby: country rooms on the left, players of the chosen room on the right (own style, not copied art) + function renderLobby() { + const code = r => { const c = r.room || r.flag; return FLAGS.includes(c) ? c : 'XX'; }; // group by the room a player JOINED, not their flag + const all = G.lobbyRows; + const myFlag = FLAGS.includes(G.save.flag) ? G.save.flag : 'XX', mine = myRoom(); + // I am in the lobby too: count myself in the room I joined (and in "all"), and only list me there + const total = all.length + 1; + const cnt = f => all.filter(r => code(r) === f).length + (f === mine ? 1 : 0); + const here = G.lobbyRoom === 'all' ? all : all.filter(r => code(r) === G.lobbyRoom); + const showMe = G.lobbyRoom === 'all' || G.lobbyRoom === mine; + const out = pendingOut(); + const flagOpts = FLAGS.map(f => ``).join(''); + const room = (f, label, flag) => ``; + const rooms = room('all', t('all_countries'), false) + FLAGS.map(f => room(f, t('cc_' + f), true)).join(''); + const action = r => (r.state === 'idle' && !out ? `` : `${r.state === 'idle' ? '' : t('busy')}`); + const prow = (r, me) => `
    ${flagHtml(me ? G.save.flag : r.flag)}${esc(me ? playerName() : r.name)}${me ? ` (${t('you')})` : ''}⭐ ${Kit.fmt((me ? G.save.fame : r.fame) | 0)}${me ? '' : action(r)}
    `; + const list = here.map(r => prow(r, false)).join(''); + const title = G.lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(G.lobbyRoom) + ' ' + t('cc_' + G.lobbyRoom); + const offline = lobby && !lobby.connected ? `

    ${t('net_connecting')}

    ` : ''; + overlay.innerHTML = `
    +
    🌍 ${t('lobby')}
    ${rooms}
    +
    +
    ${title} (${here.length + (showMe ? 1 : 0)}) +
    +
    ${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `
    ${t('lobby_empty')}
    `)}
    + ${out ? `

    ${t('waiting_accept')}

    ` : ''} + ${offline}

    +
    +
    `; + overlay.classList.remove('hide'); overlay.classList.remove('clear'); + overlay.style.backgroundImage = `linear-gradient(rgba(5,6,10,.6), rgba(5,6,10,.8)), url("${img('bg_title.jpg')}")`; + overlay.querySelectorAll('.rroom').forEach(b => { b.onclick = () => { + SFX.click(); G.lobbyRoom = b.dataset.f; + if (G.lobbyRoom !== 'all') { G.joinedRoom = G.lobbyRoom; if (lobby) lobby.setRoom(G.joinedRoom); } // joining a country = be present there + renderLobby(); + }; }); + $('lFlag').onchange = e => { G.save.flag = e.target.value; persist(); onlineFlush(); renderLobby(); }; + overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); lobby.challenge(b.dataset.uid); renderLobby(); }; }); + if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); renderLobby(); }; + $('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle') || all.find(r => r.state === 'idle'); if (idle && !pendingOut()) { SFX.click(); lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); }; + $('lBack').onclick = () => { SFX.click(); if (G.save) openGarage(); else showTitle(); }; + } + function showIncoming(c) { + card(`

    ${t('challenge_in')}

    ${flagHtml(c.fromFlag)} ${esc(c.fromName)} ${t('wants_fight')}

    +
    `); + $('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); }; + $('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (G.mode === 'lobby') renderLobby(); else hideOverlay(); }; + } + // server says: fight on (also after a reconnect into a running fight) + function startOnlineFight(m) { + const mine = m.robots[m.seat], other = m.robots[1 - m.seat]; + const opp = { name: other.name, build: other.build, paint: other.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: other.flag }; + prepOpp(opp, () => startFight(opp, false, false, { id: m.matchId, seat: m.seat, seed: m.seed, arena: m.arena, countdown: m.countdown, myBuild: mine.build })); + } + // server result + rewards (the fight on screen ends with it; if we missed the fight, just take the new save) + function onlineFightEnded(m) { + if (G.F && G.F.online && G.F.online.id === m.matchId && !G.F.ended) { + G.F.serverEnd = m; + G.F.s.result = RC.Proto.localResult(m.seat, m.result); + G.F.s.endIn = 0; + return; + } + if (m.save && G.gameMode === 'online') { adoptEconomy(m.save); afterEconomy(); } + } + + + // live fight over: the server already booked prize, repairs and achievements - show them and take its save + function endOnlineFight(res, won, me) { + if (G.F.nf) G.F.nf.stop(); + const m = G.F.serverEnd, rw = (m && m.reward) || { money: 0, fame: 0, lines: [], ach: [] }; + if (m && m.save) { adoptEconomy(m.save); persist(); } + (won ? SFX.win : SFX.lose)(); + const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat'); + const sm = (m && m.summary) || { dealt: me.dealt, taken: me.taken }; + const rows = rw.lines.map(([k, v]) => `${t(k)}${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}`).join(''); + const ach = (rw.ach || []).map(a => ({ id: a.id, reward: a.reward })); + hud(); + setScreen('result'); + card(`

    ${title}

    ${esc(G.F.opp.name)} ${G.F.oppAway ? t('peer_left') : ''}

    +
    ${t('r_dealt')}${Math.round(sm.dealt)}${t('r_taken')}${Math.round(sm.taken)}${rows} + ${rw.fame ? `${t('hud_fame')}+${Kit.fmt(rw.fame)}` : ''}
    + ${achHtml(ach)} +
    `, + { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' }); + $('bLobby').onclick = () => { SFX.click(); showLobby(); }; + $('bShopO').onclick = () => { SFX.click(); openGarage(); }; + } + // the server went silent mid-fight: leave the arena; the result (if any) is booked server-side anyway + function onlineFightLost() { + if (G.F && G.F.nf) G.F.nf.stop(); + SFX.deny(); + setScreen('result'); + card(`

    ${t('net_lost')}

    ${t('match_lost')}

    +
    `, { bg: 'bg_lose.jpg' }); + $('bLobby').onclick = () => { SFX.click(); onlinePull(); showLobby(); }; + } + + + return { + actQueue, act, econKey, econDiffers, adoptEconomy, afterEconomy, pushTimer, cosmetics, onlinePush, + onlineFlush, onlinePull, myRoom, pendingOut, wireLobby, startOnline, joinAnon, errText, showOnlineLogin, + showLobby, renderLobby, showIncoming, startOnlineFight, onlineFightEnded, endOnlineFight, + onlineFightLost + }; + }; +})(window); diff --git a/game/pages.js b/game/pages.js new file mode 100644 index 0000000..1ec1fc3 --- /dev/null +++ b/game/pages.js @@ -0,0 +1,271 @@ +/* Robot Clash - menu pages: settings, help, tutorial, country, achievements, missions, legal, ranking board. + Part of game.js (split for size): created once by game.js with the shared context G. + Live state (save, mode, F, ...) is read as G.; services/helpers are taken from G at creation. */ +(function (root) { + 'use strict'; + const RC = (root.RC = root.RC || {}); + RC.GamePages = function (G) { + const { + $, CAMS, FLAGS, L, SFX, accounts, act, audio, card, currentBack, ensureMissions, esc, fbAcc, flagHtml, + hud, layer, liveText, logout, net, newSave, openGarage, overlay, overlayEnter, persist, rank, + saveSettings, settings, shop, showLeague, showTournament, skipIntro, t, togglePause, tourState + } = G; + + // ---------------------------------------------------------------- settings / help / ranking + function showSettings(back) { + overlayEnter(); + const prev = G.mode; + const seg = (id, val, opts) => `
    ${opts.map(([v, label]) => ``).join('')}
    `; + const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null); + const item = (label, ctl) => `${label}${ctl}`; + card(`

    ${t('settings')}

    + ${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))} + ${G.save ? item(t('s_country'), ``) : ''} + ${item(t('s_music'), ``)} + ${item(t('s_sfx'), ``)} + ${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))} + ${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))} + ${item(t('s_comfort'), seg('sComfort', settings.comfort ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} + ${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))} + ${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} + ${item(t('s_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))} + ${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))} + ${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} +
    + ${G.isDev && G.save ? `
    🛠 Dev · Coins
    + +
    ` : ''} +
    ${t('s_account')} + ${who ? '👤 ' + esc(who.name) + '' + (who.email ? ' ' + esc(who.email) + '' : '') : '👤 ' + t('guest')} + ${G.save ? `` : ''}
    +
    + ${G.save ? `` : ''}
    `, { wide: true, clear: prev === 'title' || prev === 'intro' }); + const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; }); + segOn('sLang', v => { L.set(v); showSettings(back); }); + segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (G.view) G.view.setQuality(v); }); + segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); }); + segOn('sSteer', v => { settings.steer = v; saveSettings(); }); + segOn('sCam', v => { settings.cam = v; saveSettings(); if (G.view) G.view.setCam(v); }); + segOn('sComfort', v => { settings.comfort = v === '1'; saveSettings(); if (G.view && G.view.setComfort) G.view.setComfort(settings.comfort); }); + segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); }); + segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); }); + segOn('sArena', v => { settings.arena = v; saveSettings(); }); + if ($('sCountry')) $('sCountry').onchange = e => { G.save.flag = e.target.value; G.save.flagSet = true; persist(); hud(); }; + $('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol); + $('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value); + $('sSfx').onchange = () => SFX.click(); + $('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); }; + if (G.isDev && G.save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => { + SFX.buy(); const v = b.dataset.coin; + act({ type: 'devCoins', money: v === 'set800' ? 800 : Math.min(1e9, (G.save.money | 0) + (+v || 0)) }); + persist(); hud(); showSettings(back); + }); + if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); }; + if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); }; + $('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); }; + if ($('sLegal')) $('sLegal').onclick = () => { SFX.click(); showLegal(() => showSettings(back)); }; + $('bBack').onclick = () => { SFX.click(); back(); }; + } + function keysHtml() { + return `
    W A S D / ↑ ← ↓ →${t('key_drive')}${t('key_space')}${t('key_weapon')} + Shift / E${t('key_tower')}C${t('key_cam')}P / Esc${t('pause')}M${t('sound_on')} / ${t('sound_off')} + ${t('key_pad')}${t('key_pad_text')}
    `; + } + // first start: four short cards instead of the full help page + const TUT = ['tut_1', 'tut_2', 'tut_3', 'tut_4']; + function startTutorial(done) { + let i = 0; + const step = () => { + if (i >= TUT.length) { done(); return; } + const n = i + 1; + overlayEnter(); + card(`

    ${t('tut_title')} ${n}/${TUT.length}

    +

    ${t(TUT[i])}

    +
    +
    `, + { bg: 'bg_workshop.jpg' }); + $('tNext').onclick = () => { SFX.click(); i++; step(); }; + $('tSkip').onclick = () => { SFX.click(); done(); }; + }; + step(); + } + + // first start: pick the country whose flag shows on the ranking / in the lobby (changeable later in settings) + function chooseFlag(done) { + overlayEnter(); + let pick = (G.save && FLAGS.includes(G.save.flag)) ? G.save.flag : 'XX'; + card(`

    🌍 ${t('country_title')}

    ${t('country_text')}

    +
    ${FLAGS.map(f => ``).join('')}
    +
    `, { bg: 'bg_title.jpg', wide: true }); + overlay.querySelectorAll('.flagbtn').forEach(b => b.onclick = () => { pick = b.dataset.f; SFX.click(); overlay.querySelectorAll('.flagbtn').forEach(x => x.classList.toggle('on', x.dataset.f === pick)); }); + $('cfGo').onclick = () => { if (G.save) { G.save.flag = pick; G.save.flagSet = true; persist(); } SFX.click(); done(); }; + } + function ensureFlag(done) { if (G.save && !G.save.flagSet) chooseFlag(done); else done(); } + + // one line for the running event and one for the admin's message + function liveBanner() { + const out = []; + if (G.LIVE.event) { + const n = liveText(G.LIVE.event.name) || t('event_running'); + const extra = G.LIVE.event.prizeMul !== 1 ? ` · ${t('event_prize', { n: G.LIVE.event.prizeMul })}` : ''; + out.push(`
    ${t('event')}${esc(n)}${extra}
    `); + } + const m = liveText(G.LIVE.motd); + if (m) out.push(`

    ${esc(m)}

    `); + return out.join(''); + } + + function showAchievements(back) { + overlayEnter(); + const P = RC.Progress, r = P.rankOf(G.save.fame); + const pct = Math.round(r.pct * 100); + const nextLine = r.next + ? t('rank_next', { n: t('rank_' + r.next.key), f: Kit.fmt(r.next.at - G.save.fame) }) + : t('rank_top'); + const rows = P.ACHIEVEMENTS.map(a => { + const done = !!(G.save.ach && G.save.ach[a.id]); + return `
    ${done ? '🏅' : '🔒'} + ${t('ach_' + a.id)}
    ${t('achd_' + a.id)}
    + ${Kit.fmt(a.reward)}
    `; + }).join(''); + card(`

    🏅 ${t('achievements')}

    +
    ${t('rank_' + r.key)}${nextLine}
    +
    +

    ${t('ach_done', { n: P.earned(G.save), m: P.total })}

    +
    ${rows}
    +
    `, { wide: true, bg: 'bg_title.jpg' }); + $('bBack').onclick = () => { SFX.click(); back(); }; + } + + // campaign missions page: 3 daily + 1 weekly with progress bars + reset countdown + function showMissions(back) { + overlayEnter(); + ensureMissions(); + const daily = (G.save.missions && G.save.missions.daily) || [], weekly = (G.save.missions && G.save.missions.weekly) || []; + const hrs = ms => Math.max(1, Math.ceil(ms / 3600000)); + const toDay = 86400000 - (Date.now() % 86400000), toWeek = 604800000 - (Date.now() % 604800000); + const row = m => { + const prog = Math.min(m.prog || 0, m.goal), pct = Math.round(prog / m.goal * 100); + const rew = `🪙 ${Kit.fmt(m.reward)}${m.fame ? ' · ⭐' + m.fame : ''}${typeof m.unlock === 'number' ? ' · 🎨' : ''}`; + return `
    ${m.done ? '✅' : '🎯'} +
    ${t('mission_' + m.id)}
    ${t('missd_' + m.id)}
    +
    +
    ${rew}${prog}/${m.goal}
    `; + }; + card(`

    🎯 ${t('missions')}

    +

    ${t('miss_daily')} · ${t('miss_reset_in', { n: hrs(toDay) })}

    +
    ${daily.map(row).join('')}
    +

    ${t('miss_weekly')} · ${t('miss_reset_in', { n: hrs(toWeek) })}

    +
    ${weekly.map(row).join('')}
    +
    `, { wide: true, bg: 'bg_title.jpg' }); + $('bBack').onclick = () => { SFX.click(); back(); }; + } + + function showHelp(back) { + overlayEnter(); + card(`

    ${t('how_to')}

    ${t('help_text')}

    ${keysHtml()} +

    ${t('help_arena')}

    `, { bg: 'bg_title.jpg' }); + $('bOk').onclick = () => { SFX.click(); back(); }; + } + // legal pages (Impressum / Datenschutz) — placeholders, Michael fills his data in lang.js + function showLegal(back, which) { + overlayEnter(); + which = which === 'privacy' ? 'privacy' : 'impressum'; + const seg = ['impressum', 'privacy'].map(k => ``).join(''); + card(`

    ${t('legal')}

    ${seg}
    +
    ${t(which + '_text')}
    +
    `, { wide: true, bg: 'bg_title.jpg' }); + overlay.querySelectorAll('.legalseg button').forEach(b => b.onclick = () => { SFX.click(); showLegal(back, b.dataset.l); }); + $('bOk').onclick = () => { SFX.click(); back(); }; + } + + const closeRank = () => { if (G.rankSub) { G.rankSub.close(); G.rankSub = null; } }; + function showRanking(back) { + overlayEnter(); + card(`

    🏆 ${t('ranking')} ${rank.enabled ? '● ' + t('rank_live') + '' : ''}

    +
    1. ${t('loading')}
    +
    `, { bg: 'bg_title.jpg' }); + $('bBack').onclick = () => { SFX.click(); closeRank(); back(); }; + G.boardFame = {}; G.boardIdx = {}; + const myUid = (fbAcc() && fbAcc().uid) || net.uid; + closeRank(); + if (rank.enabled) G.rankSub = rank.watch(rows => drawBoard($('board'), rows, myUid)); + else drawBoard($('board'), [], myUid); + } + // animated live board: FLIP row reordering, fame bars, count-up numbers, rank ▲/▼ + function animNum(el, from, to) { + if (!el) return; const t0 = performance.now(), dur = 520; + (function step(now) { + const k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3); + el.textContent = Kit.fmt(Math.round(from + (to - from) * e)); + if (k < 1 && el.isConnected) requestAnimationFrame(step); + })(t0); + } + function drawBoard(el, rows, myUid) { + if (!el) return; + if (!rows.length) { el.innerHTML = `
  • ${t('no_scores')}
  • `; G.boardFame = {}; G.boardIdx = {}; return; } + const max = Math.max(1, rows[0].fame); + const prevTop = {}; + el.querySelectorAll('.brow').forEach(li => { prevTop[li.dataset.key] = li.getBoundingClientRect().top; }); + el.innerHTML = rows.map((r, i) => { + const me = r.key === myUid; + const was = G.boardIdx[r.key]; + const arr = (was != null && was !== i) ? (i < was ? '▲' : '▼') : ''; + return `
  • + ${i + 1}${flagHtml(r.flag || 'XX')} + ${esc(r.name)}${me ? ` (${t('you')})` : ''}${arr} + 0
  • `; + }).join(''); + el.querySelectorAll('.brow').forEach(li => { + const key = li.dataset.key, to = +li.dataset.fame, from = G.boardFame[key] != null ? G.boardFame[key] : to; + animNum(li.querySelector('.val b'), from, to); G.boardFame[key] = to; + if (prevTop[key] != null) { + const d = prevTop[key] - li.getBoundingClientRect().top; + if (d) { li.style.transform = `translateY(${d}px)`; li.style.transition = 'none'; + requestAnimationFrame(() => { li.style.transition = 'transform .45s cubic-bezier(.2,.8,.2,1)'; li.style.transform = ''; }); } + } + }); + G.boardIdx = {}; rows.forEach((r, i) => G.boardIdx[r.key] = i); + } + function confirmReset(back) { + card(`

    ${t('reset')}

    ${t('reset_text')}

    `); + $('bNo').onclick = () => { SFX.click(); back(); }; + $('bYes').onclick = () => { Object.assign(G.save, newSave()); RC.layerFromData(layer, null); G.save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); }; + } + // the rank badge opens the achievements page + $('hTour').onclick = () => { SFX.click(); if (G.gameMode === 'campaign') { if (tourState()) showTournament(); else showLeague(); } }; // online tournament: server-side later (plan P2-6) + $('chipFame').onclick = () => { + if (!G.save || G.mode === 'intro' || G.mode === 'title') return; + if (G.mode === 'fight') togglePause(); + SFX.click(); + showAchievements(G.mode === 'pause' ? () => { G.mode = 'fight'; togglePause(); } : currentBack()); + }; + $('bSettings').onclick = () => { + if (G.mode === 'fight') togglePause(); + if (G.mode === 'intro') skipIntro(); + SFX.click(); + const back = G.mode === 'pause' ? () => { G.mode = 'fight'; togglePause(); } : currentBack(); + showSettings(back); + }; + + function boardHtml() { return (rank.enabled && G.gameMode === 'online') ? `

    ${t('ranking')}

    1. ${t('loading')}
    ` : ''; } + async function fillBoard() { + const el = $('board'); + if (!el) return; + const myUid = (fbAcc() && fbAcc().uid) || net.uid; + try { + const rows = await rank.once(10); + el.innerHTML = rows.length + ? rows.map((r, i) => `
  • ${i + 1}.${esc(r.name)}${Kit.fmt(r.fame)}
  • `).join('') + : `
  • ${t('no_scores')}
  • `; + } catch (e) { el.innerHTML = `
  • ${t('scores_offline')}
  • `; } + } + + + return { + showSettings, keysHtml, TUT, startTutorial, chooseFlag, ensureFlag, liveBanner, showAchievements, + showMissions, showHelp, showLegal, closeRank, showRanking, animNum, drawBoard, confirmReset, boardHtml, + fillBoard + }; + }; +})(window); diff --git a/game/sfx.js b/game/sfx.js new file mode 100644 index 0000000..b767134 --- /dev/null +++ b/game/sfx.js @@ -0,0 +1,60 @@ +/* Robot Clash - sound effects: ComfyGen clips where they exist, synth tones as fallback (never silent, never crashes). + const SFX = RC.GameSfx(audio, settings) audio = Kit.createAudio(...), settings.quiet = softer weapon loops */ +(function (root) { + 'use strict'; + const RC = (root.RC = root.RC || {}); + RC.GameSfx = function (audio, settings) { + const last = {}; + const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; }; + const SFX = { + click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); }, + buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); }, + deny() { audio.tone(160, 0.15, 'square', 0.12, -40); }, + beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); }, + clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); }, + gate() { // metal garage door rolling open + audio.noise(1.0, 0.4, 1500); audio.noise(0.9, 0.3, 500, 0.05); // metal roll rumble + audio.tone(110, 0.9, 'sawtooth', 0.1, 70); // servo whir rising + for (let k = 0; k < 6; k++) audio.tone(170 + k * 28, 0.05, 'square', 0.07, 0, k * 0.11); // chain clanks + audio.noise(0.25, 0.55, 300, 0.9); audio.tone(58, 0.4, 'sine', 0.5, -22, 0.9); // heavy end clunk + }, + win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); }, + lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); }, + event(e) { + switch (e.type) { + case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break; + case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break; + case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break; + case 'swing': audio.noise(0.15, 0.12, 900); break; + case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break; + case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break; + case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break; + case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break; + case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break; + case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break; + case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break; + case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break; + case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break; + case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break; + case 'broke': audio.sfx('sfx_hit'); audio.noise(0.45, 0.5, 900); audio.tone(240, 0.35, 'sawtooth', 0.22, -190); break; + case 'mine_drop': audio.tone(520, 0.08, 'square', 0.12, -160); audio.noise(0.06, 0.12, 2200); break; + case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break; + case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break; + case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break; + case 'boost': audio.noise(0.4, 0.25, 1800); break; + } + }, + loops(s) { // continuous weapons as short repeated bursts + for (const r of s.robots) { + const q = settings.quiet ? 0.3 : 1, slow = settings.quiet ? 1.7 : 1; // quiet mode: softer + less often + if (r.sawOn && every('saw' + r.i, 200 * slow)) { if (!settings.quiet) audio.sfx('sfx_saw', 0.35); audio.tone(360 + Math.random() * 40, 0.12, 'triangle', 0.02 * q); } + if (r.flameOn && every('fl' + r.i, 120 * slow)) audio.noise(0.14, 0.12 * q, 900); + if (r.gunOn && every('gun' + r.i, 70 * slow)) audio.noise(0.04, 0.16 * q, 3500); + if (r.spin > 0.2 && every('spin' + r.i, 100 * slow)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin * q); + } + }, + }; + + return SFX; + }; +})(window); diff --git a/game/workshop.js b/game/workshop.js new file mode 100644 index 0000000..1866a3f --- /dev/null +++ b/game/workshop.js @@ -0,0 +1,196 @@ +/* Robot Clash - workshop extras: weapon/shape editor, paint tab with paint slots, hangar (several robots). + Part of game.js (split for size): created once by game.js with the shared context G. + Live state (save, mode, F, ...) is read as G.; services/helpers are taken from G at creation. */ +(function (root) { + 'use strict'; + const RC = (root.RC = root.RC || {}); + RC.GameWorkshop = function (G) { + const { + $, GLYPH_SLOT, MAX_ROBOTS, SFX, act, esc, hud, layer, paintObj, painter, persist, shop, syncActive, t, + weaponName + } = G; + + // ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ---- + function refreshEditorRobot() { G.view.showGarage(G.save.build, paintObj()); G.view.freeze(true); G.view.setEditWeapon(G.editSel); } + function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor + + // weapon detail chips (mirrors the shop's part chips, weapon stats only) + function wChips(p) { + const s = []; + if (p.dmg) s.push(`${t('st_dmg', { n: p.dmg })}`); + if (p.dps) s.push(`${t('st_dps', { n: p.dps })}`); + if (p.range) s.push(`${t('st_range', { n: p.range })}`); + s.push(`⌨ ${t('hk_weapon')}`); + s.push(`⚖️ ${p.weight} kg`); + if (p.power) s.push(`⚡ ${p.power}`); + return s.join(''); + } + // show the clicked weapon live on the robot (a mounted one, else a temporary front preview) + function previewWeapon(id) { + const weps = G.save.build.weapons || []; + const idx = weps.findIndex(w => w.id === id); + if (idx >= 0) { G.editSel = idx; refreshEditorRobot(); } + else { + const pv = Object.assign({}, G.save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) }); + G.view.showGarage(pv, paintObj()); G.view.freeze(true); G.view.setEditWeapon(weps.length); + } + } + function renderWeaponEditor() { + const cards = $('cards'), wp = $('wplace'); if (!G.save || !cards) return; + const b = G.save.build, weps = b.weapons || []; + G.editSel = Math.min(G.editSel, Math.max(0, weps.length - 1)); + const cat = RC.partsFor('weapon'); + const canAdd = weps.length < RC.MAX_WEAPONS; + if (!G.wPrev || !RC.PARTS[G.wPrev]) G.wPrev = (weps[G.editSel] && weps[G.editSel].id) || cat[0].id; + // right (#cards): the weapon catalog, same card grid as the other slots — click = preview + cards.className = ''; + cards.innerHTML = cat.map(p => { + const mounted = weps.filter(w => w.id === p.id).length; + const badge = mounted ? `×${mounted}` : ''; + const price = `
    🪙 ${Kit.fmt(p.cost)}
    `; + return `
    ${badge}${RC.pic('part_' + p.id, GLYPH_SLOT.weapon)}
    ${p.name}
    ${price}
    `; + }).join(''); + cards.querySelectorAll('[data-prev]').forEach(x => x.onclick = () => { G.wPrev = x.dataset.prev; SFX.click(); previewWeapon(G.wPrev); renderWeaponEditor(); }); + // detail panel: previewed weapon + Montieren / Entfernen (like the other slots) + const dp = $('detail'), pv = RC.PARTS[G.wPrev]; + if (dp && pv) { + const mounted = weps.filter(w => w.id === G.wPrev).length, poor = G.save.money < pv.cost; + let act = ``; + if (mounted) act += ``; + if (!canAdd) act += `${t('ed_max', { n: RC.MAX_WEAPONS })}`; + dp.innerHTML = `${RC.pic('part_' + G.wPrev, GLYPH_SLOT.weapon)} +
    ${pv.name}${mounted ? ` ×${mounted}` : ''}
    +
    ${t('pd_' + G.wPrev)}
    ${wChips(pv)}
    +
    ${act}
    `; + dp.querySelectorAll('button[data-wact]').forEach(x => x.onclick = () => { + if (x.dataset.wact === 'add') addWeapon(G.wPrev); + else { const i = weps.map(w => w.id).lastIndexOf(G.wPrev); if (i >= 0) removeWeapon(i); } + }); + } + // left (#wplace): placement of the active mounted weapon + shape (no sell list) + if (wp) { + const sel = weps[G.editSel]; + const sides = [['front', t('mt_front')], ['back', t('mt_back')], ['left', t('mt_left')], ['right', t('mt_right')]]; + const srow = (key, label, lo, hi) => { const val = (b.body && b.body[key]) || 1; return `
    ${t('des_' + label)}${Math.round(val * 100)}%
    `; }; + wp.classList.remove('hide'); + wp.innerHTML = + `
    ${t('ed_weapons')} ${weps.length}/${RC.MAX_WEAPONS}
    ` + + (sel ? `
    ${t('ed_place')} — ${RC.PARTS[sel.id].name}
    ` + + `
    ${sides.map(([k, lb]) => ``).join('')}
    ` + + `
    ${t('des_height')}${Math.round(((sel.up || 0) + 0.3) / 0.9 * 100)}%
    ` + : `${t('ed_noweapons')}`) + + `
    ${t('s_body')}
    ${srow('hx', 'height', 0.7, 1.6)}${srow('wx', 'width', 0.8, 1.4)}${srow('lx', 'length', 0.8, 1.3)}`; + wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; act({ type: 'weaponPlace', index: G.editSel, side: x.dataset.side }); SFX.click(); reDrawEditor(); }); + if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; // live preview while dragging + if ($('edUp')) $('edUp').onchange = e => { if (sel) act({ type: 'weaponPlace', index: G.editSel, up: +e.target.value }); reDrawEditor(); }; + wp.querySelectorAll('[data-body]').forEach(x => { + x.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); }; + x.onchange = e => { act({ type: 'body', [e.target.dataset.body]: +e.target.value }); reDrawEditor(); }; + }); + } + if (weps[G.editSel] && weps[G.editSel].id === G.wPrev) G.view.setEditWeapon(G.editSel); + } + function addWeapon(id) { + if (!act({ type: 'weaponAdd', part: id }).ok) { SFX.deny(); return; } + G.editSel = G.save.build.weapons.length - 1; G.wPrev = id; G.view.setEditWeapon(G.editSel); + SFX.buy(); reDrawEditor(); + } + function removeWeapon(i) { + if (!act({ type: 'weaponRemove', index: i }).ok) { SFX.deny(); return; } + if (G.editSel >= G.save.build.weapons.length) G.editSel = Math.max(0, G.save.build.weapons.length - 1); + G.view.setEditWeapon(G.editSel); + SFX.buy(); reDrawEditor(); + } + + // ---- paint tab: 3 save slots + quick colours + the inline painter (all inside #cards) ---- + const phex = c => '#' + (c >>> 0).toString(16).padStart(6, '0'); + function paintTab(el) { + let hdr = $('paintHdr'); + if (!hdr) { el.innerHTML = ''; hdr = document.createElement('div'); hdr.id = 'paintHdr'; hdr.className = 'phdr'; el.appendChild(hdr); } + $('shop').classList.add('paintmode'); // hide category tabs / detail / fitted bar while painting + renderPaintHeader(hdr); + if (!painter.isOpen) painter.open(el); // mount the painter inline, below the header + } + function paintLeave() { + $('shop').classList.remove('paintmode'); + if (!painter.isOpen) return; + const art = painter.hasArt(); + G.save.paint.decal = art ? layer.toDataURL('image/png') : null; G.save.paint.drawn = art; + painter.close(); persist(); + const hdr = $('paintHdr'); if (hdr) hdr.remove(); + } + function renderPaintHeader(hdr) { + const slots = G.save.paintSlots || []; + hdr.innerHTML = + `
    ${slots.map((s, i) => `
    ${s.decal ? '🖌' : ''}
    `).join('')}
    ` + + `

    ${t('paint_body')}

    ` + + `

    ${t('paint_accent')}

    ` + + `

    ${t('paint_schemes')}

    `; + const lockP = c => (RC.PAINT_REWARDS || []).includes(c) && !(G.save.unlockedPaints || []).includes(c); // reward colour, not earned yet + for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) { + $(id).innerHTML = RC.PAINTS.map(c => `${lockP(c) ? '🔒' : ''}`).join(''); + $(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { if (sw.classList.contains('locked')) { SFX.deny && SFX.deny(); return; } G.save.paint[key] = +sw.dataset.c; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); + } + $('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = G.save.paint.body === b2 && G.save.paint.accent === a2; return ``; }).join(''); + $('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { G.save.paint.body = +sw.dataset.b; G.save.paint.accent = +sw.dataset.a; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); + hdr.querySelectorAll('[data-load]').forEach(x => x.onclick = e => { if (e.target.dataset.save) return; loadPaintSlot(+x.dataset.load); }); + hdr.querySelectorAll('[data-save]').forEach(x => x.onclick = e => { e.stopPropagation(); savePaintSlot(+x.dataset.save); }); + } + function loadPaintSlot(i) { + const s = G.save.paintSlots[i]; if (!s) return; + G.save.paintSlot = i; + G.save.paint.body = s.body; G.save.paint.accent = s.accent; G.save.paint.decal = s.decal || null; G.save.paint.drawn = !!s.drawn; + SFX.click(); persist(); + RC.layerFromData(layer, G.save.paint.decal, () => { G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); }); + const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr); + } + function savePaintSlot(i) { + const art = painter.hasArt(); + G.save.paintSlots[i] = { body: G.save.paint.body, accent: G.save.paint.accent, decal: art ? layer.toDataURL('image/png') : (G.save.paint.decal || null), drawn: art || !!G.save.paint.drawn }; + G.save.paintSlot = i; SFX.buy(); persist(); + const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr); + } + + // hangar: switch / add / delete robot slots (owned parts are shared) + function switchRobot(i) { + if (i === G.save.active || !G.save.robots[i]) return; + syncActive(); + if (!act({ type: 'robotSwitch', index: i }).ok) return; + persist(); + RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); }); + shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar(); + } + function addRobot() { + syncActive(); + if (!act({ type: 'robotNew', name: t('robot_n', { n: G.save.robots.length + 1 }) }).ok) { SFX.deny(); return; } + persist(); + RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); }); + shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar(); + SFX.buy(); + } + function delRobot(i) { + syncActive(); + if (!act({ type: 'robotDelete', index: i }).ok) { SFX.deny(); return; } + persist(); RC.layerFromData(layer, G.save.paint.decal, () => {}); shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar(); + } + // hangar management (shop top-tab): list of robots with weapon, switch / delete + add button + function renderHangar(el) { + el = el || $('cards'); if (!el) return; + const rows = G.save.robots.map((r, i) => `
    +
    ${esc(r.name)}
    ${esc(weaponName(r.build))}
    + ${i === G.save.active ? `${t('active_robot')}` : ``} + ${G.save.robots.length > 1 ? `` : ''}
    `).join(''); + el.innerHTML = `
    ${rows}
    + ${G.save.robots.length < MAX_ROBOTS ? `` : `

    ${t('hangar_full')}

    `}`; + el.querySelectorAll('[data-use]').forEach(b => { b.onclick = () => { SFX.click(); switchRobot(+b.dataset.use); shop.setTab('build'); } ; }); + el.querySelectorAll('[data-del]').forEach(b => { b.onclick = () => { SFX.click(); delRobot(+b.dataset.del); renderHangar(); } ; }); + if ($('hAdd')) $('hAdd').onclick = () => { addRobot(); shop.setTab('build'); }; + } + + return { + refreshEditorRobot, reDrawEditor, wChips, previewWeapon, renderWeaponEditor, addWeapon, removeWeapon, + phex, paintTab, paintLeave, renderPaintHeader, loadPaintSlot, savePaintSlot, switchRobot, addRobot, + delRobot, renderHangar + }; + }; +})(window); diff --git a/tests/e2e/helpers.js b/tests/e2e/helpers.js index 7cf8ecb..e22e7cf 100644 --- a/tests/e2e/helpers.js +++ b/tests/e2e/helpers.js @@ -26,6 +26,12 @@ async function toLobby(page) { await expect(page.locator('body')).toHaveAttribute('data-mode', 'lobby'); } -const credits = async page => Number((await page.locator('#hMoney').textContent()).replace(/[^\d]/g, '')); +// the header shows big amounts short like Kit.fmt does ("10.8K", "1.20M", "3B") +const UNIT = { K: 1e3, M: 1e6, B: 1e9 }; +const parseCredits = text => { + const m = String(text).replace(/[,\s]/g, '').match(/([\d.]+)([KMB]?)/i); + return m ? Math.round(parseFloat(m[1]) * (UNIT[(m[2] || '').toUpperCase()] || 1)) : NaN; +}; +const credits = async page => parseCredits(await page.locator('#hMoney').textContent()); -module.exports = { mode, login, chooseCountry, toLobby, credits }; +module.exports = { mode, login, chooseCountry, toLobby, credits, parseCredits }; diff --git a/tests/e2e/offline.spec.js b/tests/e2e/offline.spec.js index e61400d..a56c937 100644 --- a/tests/e2e/offline.spec.js +++ b/tests/e2e/offline.spec.js @@ -3,6 +3,7 @@ const { test, expect } = require('@playwright/test'); const path = require('path'); const { pathToFileURL } = require('url'); +const { credits } = require('./helpers'); const file = pathToFileURL(path.join(__dirname, '..', '..', 'game', 'index.html')).href; @@ -19,7 +20,7 @@ test('campaign runs from file:// : training fight with the AI pilot, layout chec test('campaign workshop: buying a part works offline', async ({ page }) => { await page.goto(file + '?play'); await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage'); - const money = async () => Number((await page.locator('#hMoney').textContent()).replace(/[^\d]/g, '')); + const money = () => credits(page); const before = await money(); await page.locator('.tab[data-slot="armour"]').click(); await page.locator('#cards .item:not(:has(.badge)):not(:has(.pr.no))').first().click(); diff --git a/tests/e2e/screens.spec.js b/tests/e2e/screens.spec.js new file mode 100644 index 0000000..4a1494c --- /dev/null +++ b/tests/e2e/screens.spec.js @@ -0,0 +1,89 @@ +// Every menu page and workshop tool once, in the real browser, offline (file://) - guards the game.js split: +// a missing reference between the modules shows up here as a JavaScript error. +'use strict'; +const { test, expect } = require('@playwright/test'); +const path = require('path'); +const { pathToFileURL } = require('url'); + +const file = pathToFileURL(path.join(__dirname, '..', '..', 'game', 'index.html')).href; +const { credits: money } = require('./helpers'); + +test.beforeEach(async ({ page }) => { + page.errors = []; + page.on('pageerror', e => page.errors.push(e.message)); + await page.goto(file + '?play'); + await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage'); +}); +test.afterEach(async ({ page }) => { expect(page.errors, 'no JavaScript errors').toEqual([]); }); + +test('menu pages: settings, controls, legal, achievements, missions', async ({ page }) => { + await page.locator('#bSettings').click(); + await expect(page.locator('#sKeys')).toBeVisible(); + await page.locator('#sKeys').click(); // controls page from settings + await page.locator('#bOk').click(); + await expect(page.locator('#sLegal')).toBeVisible(); // back in settings + await page.locator('#sLegal').click(); + await page.locator('#bOk').click(); + await page.locator('#bBack').click(); + await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage'); + + await page.locator('#chipFame').click(); // achievements + await expect(page.locator('.achlist')).toBeVisible(); + await page.locator('#bBack').click(); + + await page.locator('#bMissions').click(); // campaign missions + await expect(page.locator('.misslist').first()).toBeVisible(); + await page.locator('#bBack').click(); +}); + +test('guest via the title: country, tutorial, then dev coins go through the economy', async ({ page }) => { + await page.goto(file + '?title'); + await page.locator('#bGuest').click(); + await page.locator('#cfGo').click(); // country card + await page.locator('#tSkip').click(); // tutorial cards + await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage'); + await page.locator('#bSettings').click(); + await page.locator('[data-coin="10000"]').click(); + await page.locator('#bBack').click(); + expect(await money(page)).toBeGreaterThanOrEqual(10800); +}); + +test('weapon editor: buy, place, sell a weapon', async ({ page }) => { + const start = await money(page); + await page.locator('.tab[data-slot="weapon"]').click(); + await expect(page.locator('#wplace')).toBeVisible(); + const before = await page.locator('.wphead').first().textContent(); + await page.locator('#cards .item:not(:has(.pr.no))').first().click(); + await page.locator('#detail button[data-wact="add"]').click(); + expect(await money(page)).toBeLessThan(start); + await expect(page.locator('.wphead').first()).not.toHaveText(before); // weapon count went up + await page.locator('[data-side="left"]').click(); + await expect(page.locator('[data-side="left"]')).toHaveClass(/on/); + await page.locator('#detail button[data-wact="rem"]').click(); +}); + +test('paint tab: colour, scheme, paint slots', async ({ page }) => { + await page.locator('#shopTabs [data-tab="paint"]').click(); + await expect(page.locator('#paintHdr')).toBeVisible(); + await page.locator('#paintBody .sw:not(.locked)').nth(2).click(); + await expect(page.locator('#paintBody .sw.on')).toHaveCount(1); + await page.locator('#paintSchemes .sw').nth(1).click(); + await page.locator('[data-save="1"]').click(); // store into slot 2 + await page.locator('[data-load="0"]').click(); // load slot 1 + await expect(page.locator('.pslot.on')).toHaveCount(1); + await page.locator('#shopTabs [data-tab="build"]').click(); + await expect(page.locator('#paintHdr')).toHaveCount(0); +}); + +test('hangar: new robot, switch, delete', async ({ page }) => { + await page.locator('#shopTabs [data-tab="hangar"]').click(); + await expect(page.locator('.hmrow')).toHaveCount(1); + await page.locator('#hAdd').click(); + await page.locator('#shopTabs [data-tab="hangar"]').click(); + await expect(page.locator('.hmrow')).toHaveCount(2); + await page.locator('[data-use="0"]').click(); + await page.locator('#shopTabs [data-tab="hangar"]').click(); + await expect(page.locator('.hmrow.on')).toHaveAttribute('data-i', '0'); + await page.locator('[data-del="1"]').click(); + await expect(page.locator('.hmrow')).toHaveCount(1); +});