diff --git a/game/cloudsave.js b/game/cloudsave.js index 5e171ba..6c62ea9 100644 --- a/game/cloudsave.js +++ b/game/cloudsave.js @@ -1,13 +1,13 @@ -/* Robot Clash - cloud save for registered accounts (no DOM). Needs net.js. +/* Robot Clash - cloud copy of the offline CAMPAIGN for registered accounts (no DOM). Needs net.js. + The online game does not use this: its save lives on the server (server/economy.js). - The whole save still lives in localStorage (fast cache); for a real e-mail account it is also mirrored to - Firebase RTDB at saves/ so it survives a device change and is harder to fake than localStorage. - Honest limit: the owner can still write their own node - rules only cap ranges. No hard copy protection. + The campaign still lives in localStorage (fast cache); with a real account it is mirrored to + /api/campaign so it survives a device change. Client-trusted - it is the offline game. const cloud = RC.CloudSave(net); - cloud.pull(uid) -> the cloud save object, or null (best effort, never throws) - cloud.push(uid, save) -> debounced write (~2.5 s after the last change) - cloud.flush(uid, save) -> write now (fight result, leaving garage, logout, unload) + cloud.pull() -> the cloud save object, or null (best effort, never throws) + cloud.push(save) -> debounced write (~2.5 s after the last change) + cloud.flush(save) -> write now (fight result, leaving garage, logout, unload) RC.CloudSave.newer(cloud, local) -> true if the cloud copy should win (by ts) */ (function (root) { 'use strict'; @@ -21,29 +21,29 @@ } RC.CloudSave = function (net) { - let timer = null, sending = false, pending = null, pendingUid = null; + let timer = null, sending = false, pending = null; const clone = s => { try { return JSON.parse(JSON.stringify(s)); } catch (e) { return null; } }; - async function write(uid, save) { + async function write(save) { sending = true; - try { await net.db.put('saves/' + uid, save); } catch (e) { /* best effort */ } + try { await net.api('PUT', '/api/campaign', save); } catch (e) { /* best effort */ } sending = false; - if (pending) { const s = pending, u = pendingUid; pending = null; pendingUid = null; write(u, s); } + if (pending) { const s = pending; pending = null; write(s); } } - function doPush(uid, save) { - if (!net || !net.enabled || !uid || !save) return; - if (sending) { pending = save; pendingUid = uid; return; } // one request at a time; keep only the latest - write(uid, save); + function doPush(save) { + if (!net || !net.enabled || !save) return; + if (sending) { pending = save; return; } // one request at a time; keep only the latest + write(save); } return { newer, - async pull(uid) { - if (!net || !net.enabled || !uid) return null; - try { return await net.db.get('saves/' + uid); } catch (e) { return null; } + async pull() { + if (!net || !net.enabled) return null; + try { return await net.api('GET', '/api/campaign'); } catch (e) { return null; } }, - push(uid, save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(uid, snap), 2500); }, - flush(uid, save) { clearTimeout(timer); doPush(uid, clone(save)); }, + push(save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(snap), 2500); }, + flush(save) { clearTimeout(timer); doPush(clone(save)); }, }; }; RC.CloudSave.newer = newer; diff --git a/game/eco.js b/game/eco.js index f27179f..d51cff5 100644 --- a/game/eco.js +++ b/game/eco.js @@ -179,8 +179,8 @@ } // which fields of a save the server owns (economy) vs. takes from the client as they are (cosmetics) - const ECONOMY = ['money', 'fame', 'best', 'games', 'wins', 'losses', 'owned', 'robots', 'active', 'build', 'paint', 'robotName']; - const COSMETIC = ['flag', 'flagSet', 'tutorialSeen', 'ach', 'paintSlots', 'paintSlot', 'unlockedPaints', 'unlockedSchemes', 'cls']; + const ECONOMY = ['money', 'fame', 'best', 'games', 'wins', 'losses', 'owned', 'robots', 'active', 'build', 'paint', 'robotName', 'ach']; + const COSMETIC = ['ts', 'flag', 'flagSet', 'tutorialSeen', 'paintSlots', 'paintSlot', 'unlockedPaints', 'unlockedSchemes', 'cls']; const isColor = v => Number.isInteger(v) && v >= 0 && v <= 0xffffff; // robot name / paint are cosmetic too, but live inside robots[] -> merged per robot, never adds or removes robots function mergeCosmetics(save, incoming) { diff --git a/game/game.js b/game/game.js index 9b5ae20..aa5e961 100644 --- a/game/game.js +++ b/game/game.js @@ -8,12 +8,12 @@ const W = 1280, H = 720; // design size of the stage (16:9, higher res = denser UI) const ID = 'robotclash'; // localStorage prefix - // Own backend (server/): auth + saves + ranks + lobby + live PvP. Empty serverUrl = same origin as the page, - // so when the game is served by the Node server it just works. file:// (double-click) stays offline. + // Own backend (server/): accounts, online save + shop (server-authoritative), ranking, lobby + live fights over + // WebSocket. Empty serverUrl = same origin as the page, so when the Node server serves the game it just works. + // file:// (double-click) stays offline = campaign only. const NET_CFG = { serverUrl: '' }; // dev/test: ?server=http://localhost:8080 points at a server on another origin; ?online jumps to login/lobby { const s = new URLSearchParams(location.search).get('server'); if (s) NET_CFG.serverUrl = s; } - const DB_URL = (NET_CFG.serverUrl || '') + '/db'; // ranking (Kit.scores) via the same server // Credits (standard for every game): shown on the title screen, links open in the normal browser const DISCORD = 'https://discord.gg/Ej4JPmCZva'; @@ -83,7 +83,12 @@ // the active class's league progress lives in save.beaten/season while you play, // and is written back to its own slot on every save (same idea as the active robot) const syncClass = () => { if (save && save.leagues && save.cls) save.leagues[save.cls] = { beaten: save.beaten | 0, season: save.season || 1 }; }; - const persist = () => { if (slot && save) { syncActive(); syncClass(); save.ts = Date.now(); slot.save(save); if (fbAcc()) cloud.push(cloudId(), save); } }; + // local cache always; online: cosmetics go to the server (economy only via act()); campaign: cloud copy for accounts + const persist = () => { + if (!slot || !save) return; + syncActive(); syncClass(); save.ts = Date.now(); slot.save(save); + if (gameMode === 'online') onlinePush(); else if (fbAcc()) cloud.push(save); + }; const audio = Kit.createAudio({ prefix: ID, files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_saw', 'sfx_boom', 'sfx_win', 'sfx_lose', 'music_title', 'music_garage', 'music_fight'], @@ -91,28 +96,76 @@ }); // first start (nothing saved yet): start very quiet; gain is squared, so these are low if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35); - const scores = Kit.scores({ url: DB_URL }); // legacy (Firebase-only, disabled on the own server) const DEV = new URLSearchParams(location.search); if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop const net = RC.Net(NET_CFG); - const rank = RC.Ranking(net); // live ranking over the own server (ranks/ + SSE) - const rankRow = () => ({ uid: (fbAcc() && fbAcc().uid) || net.uid, name: playerName(), fame: save.fame, flag: save.flag, cls: save.cls, season: save.season }); - const cloud = RC.CloudSave(net); // mirrors a registered account's save to the server (best effort) - // cloud path per mode: saves// - keeps the two games fully separate in the cloud too - // (server rule canWrite('saves/$uid/...') still holds: segment[1] stays the uid) - const cloudId = () => { const a = fbAcc(); return a ? a.uid + '/' + (gameMode === 'online' ? 'online' : 'campaign') : null; }; - const cloudFlush = () => { if (fbAcc() && save) cloud.flush(cloudId(), save); }; - // dev menu (coins): guests get it too for now; registered accounts only if admin (server tells us via /api/me). + const rank = RC.Ranking(net); // online ranking, computed by the server + const cloud = RC.CloudSave(net); // campaign copy for registered accounts (online saves live on the server) + const cloudFlush = () => { if (!save) return; if (gameMode === 'online') onlineFlush(); else if (fbAcc()) cloud.flush(save); }; + // dev menu (coins): local guests always; server accounts only if admin (the server checks again) let isDev = false; - function refreshDev() { - if (!fbAcc()) { isDev = true; return; } // guest -> dev coins allowed (local money only) - isDev = false; // registered: wait for the admin check - if (!net.enabled) return; - net.token().then(tk => { if (!tk) return; fetch((NET_CFG.serverUrl || '') + '/api/me?auth=' + tk).then(r => r.json()).then(d => { isDev = !!(d && d.admin); }).catch(() => {}); }); + 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(); + }); } 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, getProfile: () => ({ name: playerName(), flag: save.flag || 'XX', room: myRoom(), build: save.build, paint: { body: save.paint.body, accent: save.paint.accent, decal: save.paint.decal || null, drawn: !!save.paint.drawn }, fame: save.fame | 0 }) }) : null; + const lobby = net.enabled ? RC.Lobby({ net }) : null; const fx = Kit.fx(); const input = Kit.input({ @@ -198,6 +251,7 @@ const shop = RC.Shop({ t, getSave: () => save, onSave: () => { persist(); hud(); }, // buy/sell/rename -> header + act: a => act(a), // economy changes (buy/sell/equip) - server-checked online onBuild: () => view.showGarage(save.build, paintObj()), onPaint: () => view.setPaint(paintObj()), onPreview: b => { if (mode === 'garage') view.showGarage(b, paintObj()); }, // show the selected part on the robot @@ -249,7 +303,10 @@ } if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; } }); - $('gl').addEventListener('pointerup', () => { if (wdrag) { wdrag = false; persist(); refreshEditorRobot(); renderWeaponEditor(); } drag = null; }); + $('gl').addEventListener('pointerup', () => { + if (wdrag) { wdrag = false; const w = save.build.weapons[editSel]; if (w) act({ type: 'weaponPlace', index: editSel, side: w.side, up: w.up }); persist(); refreshEditorRobot(); renderWeaponEditor(); } + drag = null; + }); addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } }); // ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ---- @@ -298,7 +355,7 @@ if (dp && pv) { const mounted = weps.filter(w => w.id === wPrev).length, poor = save.money < pv.cost; let act = ``; - if (mounted) 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}` : ''}
@@ -322,27 +379,23 @@ + `
${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; sel.side = x.dataset.side; SFX.click(); reDrawEditor(); }); - if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; - if ($('edUp')) $('edUp').onchange = () => reDrawEditor(); + 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 = () => reDrawEditor(); + 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) { - const p = RC.PARTS[id]; - if (!p || save.build.weapons.length >= RC.MAX_WEAPONS || save.money < p.cost) { SFX.deny(); return; } - save.money -= p.cost; save.build.weapons.push({ id, side: 'front', up: 0 }); + 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) { - const w = save.build.weapons[i]; if (!w) return; - const p = RC.PARTS[w.id]; if (p) save.money += Math.round(p.cost * 0.5); - save.build.weapons.splice(i, 1); + 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(); @@ -584,10 +637,31 @@ } // ---------------------------------------------------------------- online lobby - let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker, = which room I view) + // 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'); - let ntour = null, inNetTour = false; // live multiplayer tournament + 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 @@ -596,30 +670,26 @@ showOnlineLogin(false, null, 'online'); return; } if (!save || !slot) { if (!fbAcc()) accounts.guest(); loadSave(); } - if (!onlineReady) { - lobby.enter(); onlineReady = true; - lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); }); - lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); }); - lobby.onMatch(m => { const opp = { name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }; prepOpp(opp, () => startFight(opp, false, false, { id: m.id, host: m.host, seed: m.seed })); }); - lobby.onCancel(() => { pendingOut = null; if (mode === 'lobby') { renderLobby(); SFX.deny(); } }); - } + 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(); startOnline(); + 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} +
${f}
${reg ? `` : ''}
${errKey ? errText(errKey) : ''}
@@ -633,19 +703,19 @@ $('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($('oMail').value.trim(), $('oPass').value, $('oName') ? $('oName').value : '') - : await net.auth.login($('oMail').value.trim(), $('oPass').value); + 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(); - if (next === 'online') startOnline(); else enterAccount(reg); + 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(); } - // compact one-view lobby: country filter + flag dropdowns, slim player list // 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 @@ -656,107 +726,37 @@ 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 prow = (r, me) => `
${flagHtml(me ? save.flag : r.flag)}${esc(me ? playerName() : r.name)}${me ? ` (${t('you')})` : ''}\u2B50 ${Kit.fmt((me ? save.fame : r.fame) | 0)}${me ? '' : (r.state === 'idle' ? `` : `${t('busy')}`)}
`; + 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')}
`)}
- ${pendingOut ? `

${t('waiting_accept')}

` : ''} -
+ ${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.refresh(); } // joining a country = be present there (with my own flag) + 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(); if (lobby) lobby.refresh(); renderLobby(); }; - overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); pendingOut = b.dataset.uid; lobby.challenge(b.dataset.uid); renderLobby(); }; }); - if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); pendingOut = null; renderLobby(); }; - $('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle') || all.find(r => r.state === 'idle'); if (idle) { SFX.click(); pendingOut = idle.uid; lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); }; + $('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(); }; - $('lTour').onclick = () => { SFX.click(); openNetTourney(); }; - } - - // ---------------------------------------------------------------- live multiplayer tournament - function openNetTourney() { - if (!(net && net.enabled && net.auth.current)) { showOnlineLogin(false, null, 'online'); return; } - const u = net.auth.current; - if (!ntour) ntour = RC.NetTourney(net, { uid: u.uid, name: u.name || playerName(), flag: save.flag || 'XX' }, { - onView: v => { if (inNetTour) renderNetTourney(v); }, - startMatch: info => startNetTourMatch(info), - }); - inNetTour = true; - ntour.join(save.build, paintObj()); - renderNetTourney(ntour.view()); - } - function leaveNetTourney() { - inNetTour = false; - if (ntour) { ntour.leave(); } - } - function renderNetTourney(v) { - if (!inNetTour) return; - const pls = v.players.map(p => `
${flagHtml(p.flag)}` - + `${esc(p.name)}${p.me ? ` (${t('you')})` : ''}` - + `${p.ready ? '✔ ' + t('ltour_ready') : t('ltour_waiting')}
`).join('') - || `

${t('ltour_empty')}

`; - let body, buttons = ''; - if (v.phase === 'running' || v.phase === 'done') { - body = netBracketHtml(v); - if (v.me.match) buttons = ``; - else if (v.me.champion) body += `

🏆 ${t('tour_won')}

`; - else if (v.me.out) body += `

${t('tour_out')}

`; - else body += `

${t('ltour_wait_round')}

`; - } else { - const me = v.players.find(p => p.me); - body = `

${v.phase === 'countdown' ? t('ltour_countdown', { n: v.countdown }) : t('ltour_lobby', { n: v.readyCount })}

` - + `
${pls}
`; - buttons = me ? `` : ''; - } - card(`

🏆 ${t('ltour_title')}

${body} -
${buttons}
`, { wide: true, bg: 'bg_title.jpg' }); - if ($('ntReady')) $('ntReady').onclick = () => { SFX.click(); const me = v.players.find(p => p.me); ntour.setReady(!(me && me.ready)); }; - if ($('ntFight')) $('ntFight').onclick = () => { SFX.click(); if (v.me.match && v.me.match.opp == null) return; /* bye */ }; - $('ntBack').onclick = () => { SFX.click(); leaveNetTourney(); showLobby(); }; - } - function netBracketHtml(v) { - if (!v.order) return ''; - const rounds = RC.LTourney.rounds(v.order, v.results); - const name = u => (u ? (v.players.find(p => p.uid === u) || {}).name || u.slice(0, 5) : '—'); - let cols = ''; - for (let r = 0; r < rounds.length; r++) { - const col = rounds[r]; if (col.length < 2 && r) continue; - let rows = ''; - for (let i = 0; i < col.length; i += 2) { - rows += `
${[col[i], col[i + 1]].map(u => { - const mine = u === net.auth.current.uid; - return `
${esc(name(u))}
`; }).join('')}
`; - } - cols += `
${t('tour_round_' + (RC.Tourney.ROUND_KEY[r] || 'final'))}
${rows}
`; - } - return `
${cols}
`; - } - function startNetTourMatch(info) { - const opp = { name: info.opp.name || 'Rival', build: info.opp.build, paint: info.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: info.opp.flag }; - prepOpp(opp, () => startFight(opp, false, false, { id: info.id, host: info.host, seed: info.seed, tourney: { round: info.round, pair: info.pairIndex, oppUid: info.oppUid } })); - } - function endNetTourFight(res, won, me) { - if (ntour) ntour.reportWin(F.online.tourney.round, F.online.tourney.pair, won ? net.auth.current.uid : F.online.tourney.oppUid); - save.games++; if (won) save.wins++; else save.losses++; - save.fame += won ? 120 : 30; persist(); hud(); - (won ? SFX.win : SFX.lose)(); - setScreen('result'); - card(`

${won ? t('victory') : t('defeat')}

${esc(F.opp.name)}

-
`, { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' }); - $('ntRes').onclick = () => { SFX.click(); inNetTour = true; renderNetTourney(ntour.view()); }; } function showIncoming(c) { card(`

${t('challenge_in')}

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

@@ -764,6 +764,22 @@ $('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) { @@ -824,13 +840,13 @@ save = slot.load(); repairSave(); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); - cloudPull(); + if (gameMode === 'online') onlinePull(); else cloudPull(); } - // registered account: fetch the cloud save; take it if newer, else push the local copy up (first migration) + // campaign + registered account: fetch the cloud copy; take it if newer, else push the local copy up function cloudPull() { - const a = fbAcc(); if (!a) return; - const id = cloudId(), m = gameMode; // this mode's cloud slot - cloud.pull(id).then(cl => { + const a = fbAcc(); if (!a || gameMode !== 'campaign') return; + const m = gameMode; + cloud.pull().then(cl => { const cur = fbAcc(); if (!save || !cur || cur.uid !== a.uid || gameMode !== m) return; // account or mode changed while we waited if (cl && RC.CloudSave.newer(cl, save)) { @@ -838,7 +854,7 @@ RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); } } else { - cloud.flush(id, save); + cloud.flush(save); } }); } @@ -908,25 +924,22 @@ function switchRobot(i) { if (i === save.active || !save.robots[i]) return; syncActive(); - save.active = i; - const a = save.robots[i]; - save.build = a.build; save.paint = a.paint; save.robotName = a.name; + 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() { - if (save.robots.length >= MAX_ROBOTS) { SFX.deny(); return; } syncActive(); - save.robots.push(newRobotDef(t('robot_n', { n: save.robots.length + 1 }))); - switchRobot(save.robots.length - 1); + 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) { - if (save.robots.length <= 1) { SFX.deny(); return; } - save.robots.splice(i, 1); - save.active = Kit.clamp(save.active >= i ? save.active - (save.active === i ? 0 : 1) : save.active, 0, save.robots.length - 1); - const a = save.robots[save.active]; save.build = a.build; save.paint = a.paint; save.robotName = a.name; + 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 @@ -945,8 +958,7 @@ function signOut() { persist(); cloudFlush(); // push now, while we still have the auth token - if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; } - if (ntour) { ntour.leave(); inNetTour = false; } + if (lobby) { lobby.leave(); lobbyRows = []; } if (net && net.enabled) net.auth.logout(); accounts.logout(); save = null; slot = null; F = null; hud(); } @@ -1002,14 +1014,14 @@ 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(); if (lobby) lobby.refresh(); hud(); }; + 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; - save.money = v === 'set800' ? 800 : Math.min(1e9, (save.money | 0) + (+v || 0)); + 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)); }; @@ -1050,7 +1062,7 @@
${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(); } if (lobby) lobby.refresh(); SFX.click(); done(); }; + $('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(); }; @@ -1185,7 +1197,7 @@ $('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(); openNetTourney(); }; + $('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(); @@ -1372,7 +1384,8 @@ function startFight(opp, training, exhibition, online, tour) { hideOverlay(); const D = BASE; - const stA = RC.stats(save.build), stB = RC.stats(opp.build); + const myBuild = online ? online.myBuild : save.build; // live: exactly the robot the server fights with + const stA = RC.stats(myBuild), stB = RC.stats(opp.build); if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP const seed = online ? online.seed : (Date.now() & 0xffff) + save.games * 31; // arena: league scales with the opponent, online derives from the shared seed, training uses the setting @@ -1380,17 +1393,15 @@ const bySize = RC.ARENAS.slice().sort((a, b) => a.half - b.half).map(a => a.id); // small -> big for league progression const arenaId = DEV.get('arena') ? DEV.get('arena') : (LIVE.event && LIVE.event.arena && !online) ? LIVE.event.arena - : online ? ids[seed % ids.length] + : online ? online.arena : idx >= 0 ? bySize[Math.min(bySize.length - 1, Math.floor(idx * bySize.length / RC.LEAGUE.length))] : settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena; const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId }); const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1); - F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4, - acc: [0, 0], accT: 0, banner: null, ended: false }; - if (online) { - F.nf = RC.NetFight({ net, id: online.id, host: online.host, oppStyle: 'brawler', oppSkill: 0.6, onPeerLost: () => banner(t('peer_lost'), '#ff4a3a', 2.5), onPeerBack: () => banner(t('peer_back'), '#6dff9e', 1.6) }); - F.nf.start(); - } + const count = online ? Math.max(0, +online.countdown || 0) : 3.5; + F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count, beat: Math.ceil(count) + 1, + acc: [0, 0], accT: 0, banner: null, ended: false, oppAway: false }; + if (online) F.nf = RC.NetFight({ net, seat: online.seat }); // the server runs the fight, we show it // dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing) if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 }); if (DEV.has('ff')) { @@ -1401,7 +1412,7 @@ s.events.length = 0; } } - view.showArena(s, [save.build, opp.build], [paintObj(), oppPaint(opp)]); + view.showArena(s, [myBuild, opp.build], [paintObj(), oppPaint(opp)]); if (view.setComfort) view.setComfort(settings.comfort); view.setCam(DEV.get('cam') || settings.cam); // dev: &cam=chase|fpv $('fN0').textContent = save.robotName; $('fN1').textContent = opp.name; @@ -1524,14 +1535,11 @@ function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; } - let ntourT = 0; function update(dt) { - if (ntour && inNetTour) { ntourT -= dt; if (ntourT <= 0) { ntourT = 2; ntour.tick(); } } fx.update(dt); introTick(); if (mode !== 'fight' || !F) return; if (F.count > 0) { - if (F.nf) F.nf.idle(dt); F.count -= dt; const n = Math.ceil(F.count); if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } } @@ -1540,7 +1548,10 @@ const s = F.s, [me, en] = s.robots; let events; if (F.online) { - events = F.online.host ? F.nf.hostStep(s, playerInput(), dt) : F.nf.guestFrame(s, playerInput(), dt); + events = F.nf.frame(s, playerInput(), dt); + if (F.nf.oppAway !== F.oppAway) { F.oppAway = F.nf.oppAway; banner(t(F.oppAway ? 'peer_lost' : 'peer_back'), F.oppAway ? '#ff4a3a' : '#6dff9e', 2.2); } + // no word from the server for 20 s (and no result yet - a hidden tab may simply have slept through the end) + if (!F.serverEnd && F.nf.silentFor > 20 && !F.ended) { F.ended = true; onlineFightLost(); return; } } else { RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]); events = s.events; @@ -1567,7 +1578,8 @@ } } if (s.left <= 10 && !s.result && Math.ceil(s.left) !== F.tick) { F.tick = Math.ceil(s.left); audio.tone(1200, 0.05, 'square', 0.06); } - if (s.result && s.endIn <= 0 && !F.ended) { F.ended = true; endFight(); } + // live: the fight is over when the server says so (match.end carries the booked rewards) + if (s.result && s.endIn <= 0 && !F.ended && (!F.online || F.serverEnd)) { F.ended = true; endFight(); } } // cooldown chips for the parts actually fitted (built once, only --p changes per frame) @@ -1682,7 +1694,6 @@ function endFight() { const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp); const won = res.winner === 0, me = s.robots[0]; - if (F.online && F.online.tourney) { endNetTourFight(res, won, me); return; } if (F.online) { endOnlineFight(res, won, me); return; } if (F.tour) { endTourFight(res, won, me); return; } const lines = []; @@ -1724,7 +1735,7 @@ const fightCtx = { won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt, lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length, training: F.training, exhibition: F.exhibition, champion }; - const gotAch = awardAch(fightCtx); + const gotAch = gameMode === 'online' ? [] : awardAch(fightCtx); // online: achievements pay out on the server only const gotMiss = updateMissions(fightCtx); // campaign missions: progress + pay hud(); (won ? SFX.win : SFX.lose)(); @@ -1742,10 +1753,7 @@ { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' }); $('bGarage').onclick = () => { SFX.click(); openGarage(); }; if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false, F.exhibition); }; - if (!F.training && save.fame > save.best) { - save.best = save.fame; persist(); - if (gameMode === 'online') { rank.submit(rankRow()).then(fillBoard); return; } // global board = online fame only - } + if (!F.training && save.fame > save.best) { save.best = save.fame; persist(); } fillBoard(); } @@ -1783,43 +1791,36 @@ $('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(); - if (lobby) lobby.endMatch(); + 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'); - // online rewards: prize (win) / half (draw) / appearance fee (loss) + damage bonus - repairs; fame on a win - const PVP = 600, lines = []; - let money = 0, fame = 0; - const draw = res.winner === -1; - if (won) { money += PVP; lines.push([t('r_prize'), PVP]); fame = 150 + (res.reason === 'ko' ? 40 : res.reason === 'pit' ? 60 : 0); } - else if (draw) { money += PVP / 2; lines.push([t('r_draw_prize'), PVP / 2]); fame = 40; } - else { const ap = Math.round(PVP * 0.35); money += ap; lines.push([t('r_appearance'), ap]); } - if (won && res.reason !== 'time') { const b = Math.round(PVP * (res.reason === 'pit' ? 0.3 : 0.2)); money += b; lines.push([t('r_bonus_' + res.reason), b]); } - const db = Math.round(me.dealt * 0.6); - if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); } - const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06); - money = applyEvent(money, lines); - const paid = Math.min(repair, save.money + money); - if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); } - save.money += money; save.fame += fame; save.games++; - if (won) save.wins++; else if (!draw) save.losses++; - persist(); - const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt, - lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length }); + 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(); - if (save.fame > save.best) { save.best = save.fame; persist(); rank.submit(rankRow()); } - const rows = lines.map(([k, v]) => `${k}${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}`).join(''); setScreen('result'); - card(`

${title}

${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}

-
${t('r_dealt')}${Math.round(me.dealt)}${t('r_taken')}${Math.round(me.taken)}${rows} - ${fame ? `${t('hud_fame')}+${Kit.fmt(fame)}` : ''}
- ${achHtml(gotAch)} + 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; diff --git a/game/index.html b/game/index.html index 16bfd2e..2f67595 100644 --- a/game/index.html +++ b/game/index.html @@ -817,6 +817,8 @@ + + @@ -828,7 +830,6 @@ - diff --git a/game/lang.js b/game/lang.js index d4356fd..a7ca6c9 100644 --- a/game/lang.js +++ b/game/lang.js @@ -236,12 +236,18 @@ window.LANG = { your_flag: 'Your flag:', challenge: 'Challenge', busy: 'in a fight', quick_match: 'Quick match', waiting_accept: 'Waiting for the other player...', challenge_in: 'Challenge!', wants_fight: 'wants to fight you!', accept: 'Accept', decline: 'Decline', back_to_lobby: 'Back to lobby', - peer_lost: 'Connection to opponent lost - AI takes over', peer_left: '(left the fight)', + peer_lost: 'Opponent disconnected - the AI takes over in 10 s', peer_left: '(left the fight)', e_EMAIL_EXISTS: 'That e-mail is already registered.', e_EMAIL_NOT_FOUND: 'No account with that e-mail.', e_INVALID_PASSWORD: 'Wrong password.', e_INVALID_LOGIN_CREDENTIALS: 'Wrong e-mail or password.', - e_WEAK_PASSWORD: 'Password needs at least 6 characters.', e_INVALID_EMAIL: 'That is not a valid e-mail.', + e_WEAK_PASSWORD: 'Password needs at least 8 characters.', e_INVALID_EMAIL: 'That is not a valid e-mail.', e_MISSING_PASSWORD: 'Please enter a password.', e_OPERATION_NOT_ALLOWED: 'Guest login is off - use e-mail.', e_OFFLINE: 'Online is not set up yet.', e_ERROR: 'Something went wrong. Try again.', + f_login: 'Name or e-mail', f_email_opt: 'E-mail (optional)', + e_INVALID_LOGIN: 'Wrong name or password.', e_NAME_EXISTS: 'That name is already taken.', e_BAD_NAME: 'The name needs at least 3 letters or digits.', + e_RATE_LIMIT: 'Too many tries - please wait a minute.', e_INVALID_ROBOT: 'Your robot is not ready to fight - check weight and power in the workshop.', + e_OPPONENT_INVALID: 'The other robot is not ready to fight.', e_BUSY: 'That player is busy right now.', e_NOT_AVAILABLE: 'That player is not available.', + e_OUTDATED: 'A new version is out - please reload the page.', e_REPLACED: 'You are now playing in another window.', + net_connecting: 'Connecting to the server...', net_lost: 'Connection lost', match_lost: 'No word from the server - the fight is counted there. Back to the lobby.', pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front', pt_view_top: 'Top', pt_view_right: 'Right', pt_view_left: 'Left', pt_view_front: 'Front', pt_view_free: 'Turn', pt_brush: 'Brush', pt_spray: 'Spray', pt_erase: 'Eraser', pt_stamp: 'Stamp', pt_text: 'Text', pt_fill: 'Fill', @@ -510,12 +516,18 @@ window.LANG = { your_flag: 'Deine Flagge:', challenge: 'Herausfordern', busy: 'im Kampf', quick_match: 'Schnelles Match', waiting_accept: 'Warte auf den anderen Spieler...', challenge_in: 'Herausforderung!', wants_fight: 'will gegen dich kämpfen!', accept: 'Annehmen', decline: 'Ablehnen', back_to_lobby: 'Zurück zur Lobby', - peer_lost: 'Verbindung zum Gegner weg - KI übernimmt', peer_left: '(hat den Kampf verlassen)', + peer_lost: 'Gegner getrennt - in 10 s übernimmt die KI', peer_left: '(hat den Kampf verlassen)', e_EMAIL_EXISTS: 'Diese E-Mail ist schon registriert.', e_EMAIL_NOT_FOUND: 'Kein Konto mit dieser E-Mail.', e_INVALID_PASSWORD: 'Falsches Passwort.', e_INVALID_LOGIN_CREDENTIALS: 'E-Mail oder Passwort falsch.', - e_WEAK_PASSWORD: 'Passwort braucht mindestens 6 Zeichen.', e_INVALID_EMAIL: 'Das ist keine gültige E-Mail.', + e_WEAK_PASSWORD: 'Passwort braucht mindestens 8 Zeichen.', e_INVALID_EMAIL: 'Das ist keine gültige E-Mail.', e_MISSING_PASSWORD: 'Bitte ein Passwort eingeben.', e_OPERATION_NOT_ALLOWED: 'Gast-Login ist aus - nimm E-Mail.', e_OFFLINE: 'Online ist noch nicht eingerichtet.', e_ERROR: 'Etwas ist schiefgelaufen. Nochmal versuchen.', + f_login: 'Name oder E-Mail', f_email_opt: 'E-Mail (optional)', + e_INVALID_LOGIN: 'Name oder Passwort falsch.', e_NAME_EXISTS: 'Dieser Name ist schon vergeben.', e_BAD_NAME: 'Der Name braucht mindestens 3 Buchstaben oder Ziffern.', + e_RATE_LIMIT: 'Zu viele Versuche - bitte eine Minute warten.', e_INVALID_ROBOT: 'Dein Roboter ist nicht kampfbereit - prüfe Gewicht und Strom in der Werkstatt.', + e_OPPONENT_INVALID: 'Der andere Roboter ist nicht kampfbereit.', e_BUSY: 'Dieser Spieler ist gerade beschäftigt.', e_NOT_AVAILABLE: 'Dieser Spieler ist nicht verfügbar.', + e_OUTDATED: 'Es gibt eine neue Version - bitte die Seite neu laden.', e_REPLACED: 'Du spielst jetzt in einem anderen Fenster.', + net_connecting: 'Verbinde mit dem Server...', net_lost: 'Verbindung verloren', match_lost: 'Keine Antwort vom Server - der Kampf wird dort gewertet. Zurück zur Lobby.', pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne', pt_view_top: 'Oben', pt_view_right: 'Rechts', pt_view_left: 'Links', pt_view_front: 'Vorne', pt_view_free: 'Drehen', pt_brush: 'Pinsel', pt_spray: 'Spray', pt_erase: 'Radierer', pt_stamp: 'Stempel', pt_text: 'Text', pt_fill: 'Füllen', diff --git a/game/live.js b/game/live.js index 36605ca..a7ad955 100644 --- a/game/live.js +++ b/game/live.js @@ -1,4 +1,4 @@ -/* Robot Clash - live settings from the backend (Firebase node /live). +/* Robot Clash - live settings from the own server (GET /api/live, admin writes PUT /api/admin/live). The pure part has no DOM and no network, so the tests can run it in Node. RC.Live.parse(data, now, build) -> { @@ -8,7 +8,7 @@ needsReload, // this copy is older than build.min locked(kind, id), // true when the admin has not released this part/arena/class yet } - RC.Live.load(net, onChange) reads /live once, then keeps listening, and remembers the last + RC.Live.load(net, onChange) reads /api/live, polls it every minute, and remembers the last answer in localStorage so the game still works offline. Everything is best effort: no config, broken JSON or no network simply means "nothing special @@ -74,10 +74,11 @@ const fire = data => { if (data) remember(data); onChange(parse(data, Date.now(), build)); }; fire(cached()); // show something immediately if (!net || !net.enabled) return { close() {} }; - net.db.get('live').then(d => { if (d) fire(d); }, () => {}); - let sub = null; - try { sub = net.db.stream('live', d => { if (d) fire(d); }); } catch (e) { sub = null; } - return { close() { if (sub) sub.close(); } }; + // the admin changes these rarely: read now, then poll every minute + const pull = () => net.api('GET', '/api/live').then(d => { if (d) fire(d); }, () => {}); + pull(); + const timer = setInterval(pull, 60000); + return { close() { clearInterval(timer); } }; } RC.Live = { parse, load, KEY }; diff --git a/game/lobby.js b/game/lobby.js index b124118..a9b932e 100644 --- a/game/lobby.js +++ b/game/lobby.js @@ -1,138 +1,65 @@ -/* Robot Clash - online lobby: presence, player list, challenges, match creation. No DOM. - Needs net.js (RC.Net). Transport is Firebase RTDB (net.db). All cosmetic/casual, see docs/firebase. +/* Robot Clash - online lobby over the server WebSocket (net.socket). No DOM. The server owns presence, + challenges and matches; this just mirrors its state and forwards clicks. - const lobby = RC.Lobby({ net, getProfile: () => ({ name, flag, build, paint, fame }) }); - lobby.enter() announce presence, start heartbeat, watch list + incoming challenges - lobby.leave() remove presence, stop everything - lobby.onList(fn) fn([{ uid, name, flag, state, fame }]) - online players except me, newest first - lobby.onIncoming(fn) fn({ from, fromName, fromFlag, build, paint, seed }) - someone challenges me - lobby.onMatch(fn) fn({ id, host (bool), opp: { uid, name, flag, build, paint }, seed }) - fight on - lobby.onCancel(fn) fn() - a pending challenge I sent/got fell through - await lobby.challenge(uid) invite a player (writes to their inbox, waits for accept) - await lobby.accept(from) accept an incoming challenge -> creates the match - lobby.decline(from) reject an incoming challenge - lobby.cancel() withdraw the challenge I sent - - Presence TTL: entries older than STALE ms count as offline (no SDK onDisconnect). */ + const lobby = RC.Lobby({ net }) + lobby.enter() / leave() + lobby.onList(fn) fn([{ uid, name, flag, fame, state, room }]) everyone online except me + lobby.onIncoming(fn) fn({ from, fromName, fromFlag }) someone challenges me + lobby.onCancel(fn) fn({ reason }) my challenge / an incoming one fell through + lobby.onMatch(fn) fn(matchStartMsg) fight on (also after a reconnect) + lobby.onEnd(fn) fn(matchEndMsg) server result + rewards + new save + lobby.onError(fn) fn(code) BUSY | INVALID_ROBOT | ... + lobby.challenge(uid) / accept(from) / decline(from) / cancel() / setRoom(code|'all') + lobby.pending uid I challenged (or null) */ (function (root) { 'use strict'; const RC = (root.RC = root.RC || {}); - const HEARTBEAT = 4000, STALE = 12000; - const now = () => Date.now(); - // match id = both uids sorted + join -> same id on both sides; lower uid hosts (authority) - const matchId = (a, b) => [a, b].sort().join('_'); - const isHost = (a, b) => a < b; RC.Lobby = (opt) => { - const net = opt.net, db = net.db; - const cbs = { list: [], incoming: [], match: [], cancel: [] }; - const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { /* ignore */ } }); - let hb = null, subList = null, subIn = null, subMatch = null; - let outgoing = null; // uid I challenged - let inMatch = null; // active match id + const net = opt.net, sock = net.socket; + const cbs = { list: [], incoming: [], cancel: [], match: [], end: [], error: [] }; + const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { console.error(e); } }); + const players = new Map(); + let me = null, pending = null, offs = [], incomingFrom = null; - const me = () => net.uid; - const prof = () => opt.getProfile(); + const list = () => emit('list', [...players.values()].sort((a, b) => (b.fame | 0) - (a.fame | 0) || String(a.name).localeCompare(b.name))); - async function beat(state) { - const p = prof(); - await db.put(`lobby/${me()}`, { name: p.name, flag: p.flag || 'XX', room: p.room || p.flag || 'XX', fame: p.fame | 0, ver: 2, state: state || 'idle', ts: { '.sv': 'timestamp' } }); - } - - function watchList() { - subList = db.stream('lobby', data => { - const t = now(), mine = me(); - const rows = Object.entries(data || {}) - .map(([uid, v]) => Object.assign({ uid }, v)) - .filter(v => v.uid !== mine && v.name && (t - (v.ts || 0)) < STALE) - .sort((a, b) => (b.ts || 0) - (a.ts || 0)); - emit('list', rows); - }); - } - - // incoming challenges land under challenges// - function watchIncoming() { - subIn = db.stream(`challenges/${me()}`, data => { - const entries = Object.entries(data || {}).filter(([, v]) => v && v.from && (now() - (v.ts || 0)) < STALE); - if (!entries.length) return; - const [, c] = entries[0]; - emit('incoming', { from: c.from, fromName: c.fromName, fromFlag: c.fromFlag, build: c.build, paint: c.paint, seed: c.seed }); - }); - } - - // the match node appears for both players once created (host writes it on accept) - function watchMatch(id, oppUid, host) { - cleanupMatch(); - inMatch = id; - subMatch = db.stream(`matches/${id}/meta`, meta => { - // wait until BOTH players have written their robot (each side patches its own entry) - if (!meta || inMatch !== id || meta.seed == null || !meta[oppUid] || !meta[me()]) return; - emit('match', { id, host, opp: { uid: oppUid, name: meta[oppUid] && meta[oppUid].name, flag: meta[oppUid] && meta[oppUid].flag, build: meta[oppUid] && meta[oppUid].build, paint: meta[oppUid] && meta[oppUid].paint }, seed: meta.seed }); - if (subMatch) { subMatch.close(); subMatch = null; } // meta is fixed; stop watching - }); - } - function cleanupMatch() { if (subMatch) { subMatch.close(); subMatch = null; } } - - async function challenge(uid) { - if (outgoing) return; - outgoing = uid; - const p = prof(); - // a rematch reuses the match id, so clear whatever a crashed fight left behind - - // otherwise the waiting side would pick up the old seed (and the old arena) at once - await db.del(`matches/${matchId(me(), uid)}`); - await beat('searching'); - await db.put(`challenges/${uid}/${me()}`, { from: me(), fromName: p.name, fromFlag: p.flag || 'XX', build: p.build, paint: p.paint, seed: (Math.random() * 1e9) | 0, ts: { '.sv': 'timestamp' } }); - // wait for the other side to create the match (they host if their uid < mine) - const id = matchId(me(), uid), host = isHost(me(), uid); - const give = setTimeout(() => { if (outgoing === uid) { emit('cancel'); cancel(); } }, STALE); - const watch = db.stream(`matches/${id}/meta/seed`, seed => { - if (seed == null) return; - clearTimeout(give); watch.close(); outgoing = null; - createMatch(uid, false); // add my own robot; the seed is already set by the other side - watchMatch(id, uid, host); - }); - } - - async function accept(from) { - const id = matchId(me(), from), host = isHost(me(), from); - await db.del(`challenges/${me()}/${from}`); - await createMatch(from, true); // whoever accepts rolls the seed (and with it the arena) - watchMatch(id, from, host); - } - function decline(from) { db.del(`challenges/${me()}/${from}`); } - function cancel() { if (outgoing) { db.del(`challenges/${outgoing}/${me()}`); outgoing = null; beat('idle'); } } - - // setSeed: only the side that accepts writes the seed, so both read the exact same value. - // It is rolled fresh for every match - a seed derived from the match id would hand the same - // pair of players the same arena for ever. - async function createMatch(oppUid, setSeed) { - const id = matchId(me(), oppUid), p = prof(); - const meta = { [me()]: { name: p.name, flag: p.flag || 'XX', build: p.build, paint: p.paint } }; - if (setSeed) meta.seed = ((Math.random() * 1e9) | 0) || 1; - await db.patch(`matches/${id}/meta`, meta); - await beat('inmatch'); + function wire() { + offs = [ + sock.on('lobby', m => { players.clear(); for (const p of m.players) players.set(p.uid, p); me = m.you; list(); }), + sock.on('lobby.join', m => { players.set(m.player.uid, m.player); list(); }), + sock.on('lobby.state', m => { if (m.player.uid === net.uid) { me = m.player; return; } players.set(m.player.uid, m.player); list(); }), + sock.on('lobby.leave', m => { players.delete(m.uid); list(); }), + sock.on('challenge.in', m => { incomingFrom = m.from; emit('incoming', { from: m.from, fromName: m.name, fromFlag: m.flag, fame: m.fame }); }), + sock.on('challenge.gone', m => { + if (m.to && m.to === pending) { pending = null; emit('cancel', { reason: m.reason || 'gone', outgoing: true }); } + if (m.from && m.from === incomingFrom) { incomingFrom = null; emit('cancel', { reason: m.reason || 'gone', outgoing: false }); } + }), + sock.on('match.start', m => { pending = null; incomingFrom = null; emit('match', m); }), + sock.on('match.end', m => emit('end', m)), + sock.on('error', m => { if (['BUSY', 'NOT_AVAILABLE', 'INVALID_ROBOT', 'OPPONENT_INVALID'].includes(m.code)) pending = null; emit('error', m.code); }), + sock.on('close', () => { players.clear(); pending = null; list(); }), + ]; } return { onList: fn => cbs.list.push(fn), onIncoming: fn => cbs.incoming.push(fn), - onMatch: fn => cbs.match.push(fn), onCancel: fn => cbs.cancel.push(fn), - challenge, accept, decline, cancel, - async enter() { - if (!net.enabled || !me()) return; - await beat('idle'); - hb = setInterval(() => db.patch(`lobby/${me()}`, { ts: { '.sv': 'timestamp' }, state: outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle' }), HEARTBEAT); - watchList(); watchIncoming(); - }, - refresh() { if (me()) beat(outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle'); }, - endMatch() { const id = inMatch; inMatch = null; cleanupMatch(); if (id) db.del(`matches/${id}`); if (me()) beat('idle'); }, - leave() { - clearInterval(hb); hb = null; - if (subList) subList.close(); if (subIn) subIn.close(); cleanupMatch(); - if (me()) db.del(`lobby/${me()}`); - }, - matchId, isHost, + onMatch: fn => cbs.match.push(fn), + onEnd: fn => cbs.end.push(fn), + onError: fn => cbs.error.push(fn), + get pending() { return pending; }, + get me() { return me; }, + get connected() { return sock.connected; }, + enter() { if (!net.enabled || !net.uid) return; if (!offs.length) wire(); sock.connect(); }, + leave() { offs.forEach(off => off()); offs = []; sock.close(); players.clear(); pending = null; }, + challenge(uid) { if (pending) return; pending = uid; if (!sock.send({ t: 'challenge', to: uid })) pending = null; }, + cancel() { if (!pending) return; sock.send({ t: 'challenge.cancel' }); pending = null; }, + accept(from) { incomingFrom = null; sock.send({ t: 'challenge.accept', from }); }, + decline(from) { incomingFrom = null; sock.send({ t: 'challenge.decline', from }); }, + setRoom(room) { sock.send({ t: 'room', room: room || 'all' }); }, + leaveMatch() { sock.send({ t: 'match.leave' }); }, }; }; })(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/net.js b/game/net.js index ee58f9a..169947f 100644 --- a/game/net.js +++ b/game/net.js @@ -1,170 +1,155 @@ -/* Robot Clash - Firebase over plain REST (no SDK, classic script, runs from file://). - Auth = Identity Toolkit REST, database = Realtime Database REST + Server-Sent-Events for push. +/* Robot Clash - client side of the own server (server/): REST + one WebSocket. Classic script, no SDK. + Offline (file://, no server) everything is disabled and the game runs as the campaign only. - const net = RC.Net({ apiKey: '...', dbUrl: 'https://-default-rtdb.firebaseio.com' }); - net.enabled false without a full config -> game stays offline - await net.auth.register(email, pass, name) -> { ok, error } (error: 'EMAIL_EXISTS' | 'WEAK_PASSWORD' | ...) - await net.auth.login(email, pass) -> { ok, error } ('EMAIL_NOT_FOUND' | 'INVALID_PASSWORD' | ...) - await net.auth.guest(name) -> { ok, error } (anonymous sign-in, must be enabled in Firebase) - net.auth.resume() -> true if a saved session was restored (async refresh follows) - net.auth.logout() / net.auth.current -> { uid, name, email, guest } | null - net.auth.onChange(fn) called after login/logout/refresh + const net = RC.Net({ serverUrl: '' }) '' = same origin as the page + net.enabled false on file:// -> offline + await net.auth.register(name, pass, email?) -> { ok, error } error: NAME_EXISTS | WEAK_PASSWORD | BAD_NAME | ... + await net.auth.login(nameOrEmail, pass) -> { ok, error } INVALID_LOGIN | RATE_LIMIT | ... + await net.auth.guest(name) -> { ok, error } + net.auth.resume() / logout() / current {uid,name,email,guest,admin} / onChange(fn) + await net.api(method, path, body) -> parsed JSON or null (never throws); 401 -> one refresh + retry + net.socket.connect() / close() / send(msg) / on(type, fn) / connected + events: every server message type ('lobby', 'snap', 'match.end', ...) + 'open' | 'close' | 'outdated' - await net.db.get(path) -> value | null - await net.db.put(path, value) -> ok (PUT, replaces) - await net.db.patch(path, obj) -> ok (PATCH, merges) - await net.db.push(path, value) -> key | null (POST, new child) - await net.db.del(path) -> ok - const sub = net.db.stream(path, onValue) -> { close() } push updates via EventSource - onValue(value) fires with the whole subtree on connect and on every change. - - All DB calls carry the id token (?auth=). Token auto-refreshes before it expires. - Every call is best effort: on error db.get -> null, writes -> false, never throws. */ + Session: refresh tokens rotate (each works once). Refresh is single-flight, and the session is shared + through localStorage, so two tabs never burn the same refresh token and log each other out. + Dev: ?slot=2 keeps a second session in the same browser (test PvP with two accounts in two tabs). */ (function (root) { 'use strict'; const RC = (root.RC = root.RC || {}); + RC.Net = (cfg = {}) => { - const base = (cfg.serverUrl || '').replace(/\/+$/, ''); // '' = same origin as the page - const API = base + '/api', DB = base + '/db'; - // online when served over http(s) (own server) or given an explicit serverUrl; file:// stays offline + const base = (cfg.serverUrl || '').replace(/\/+$/, ''); const enabled = cfg.enabled !== false && typeof fetch !== 'undefined' && (!!base || /^https?:$/.test(location.protocol)); - const store = Kit.store('robotclash.net'); + const slot = (typeof location !== 'undefined' && new URLSearchParams(location.search).get('slot')) || ''; + const store = Kit.store('robotclash.net' + (slot ? '.' + slot : '')); - let session = null; // { idToken, refreshToken, uid, name, email, guest, exp } + let session = null; // { idToken, exp, refreshToken, uid, name, email, guest, admin } const listeners = []; - const fire = () => listeners.forEach(fn => { try { fn(cur()); } catch (e) { /* ignore */ } }); - function cur() { return session ? { uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null; } + const cur = () => (session ? { uid: session.uid, name: session.name, email: session.email, guest: !!session.guest, admin: !!session.admin } : null); + const fire = () => listeners.forEach(fn => { try { fn(cur()); } catch (e) { /* listener bug */ } }); + const persist = () => store.set('session', session); + const stored = () => store.get('session', null); - async function postJson(url, body) { - const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); + function setSession(d) { + session = { + idToken: d.idToken, refreshToken: d.refreshToken, exp: Date.now() + ((+d.expiresIn || 3600) - 60) * 1000, + uid: d.uid, name: d.name || '', email: d.email || '', guest: !!d.guest, admin: !!d.admin, + }; + persist(); fire(); + } + + async function post(path, body) { + const res = await fetch(base + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const data = await res.json().catch(() => ({})); - if (!res.ok) { const msg = (data.error && (data.error.message || data.error)) || ('HTTP_' + res.status); const e = new Error(msg); e.code = String(msg).split(/[ :]/)[0]; throw e; } + if (!res.ok) { const e = new Error(data.error || 'HTTP_' + res.status); e.code = data.error || 'HTTP_' + res.status; throw e; } return data; } - function save() { store.set('session', session ? { refreshToken: session.refreshToken, uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null); } - - function setAuth(d, name, guest) { - session = { - idToken: d.idToken || d.id_token, refreshToken: d.refreshToken || d.refresh_token, - uid: d.uid || d.localId || d.user_id, name: name || (session && session.name) || '', email: d.email || (session && session.email) || '', guest: !!guest, - exp: Date.now() + (+(d.expiresIn || d.expires_in || 3600) - 60) * 1000, - }; - save(); fire(); + // another tab may already have refreshed: take its newer session instead of burning ours + function adoptStored() { + const s = stored(); + if (s && session && s.uid === session.uid && s.refreshToken !== session.refreshToken && s.exp > Date.now()) { session = s; return true; } + return false; } - - async function refresh() { - if (!session || !session.refreshToken) return false; - try { - const d = await postJson(`${API}/auth/refresh`, { refreshToken: session.refreshToken }); - session.idToken = d.idToken; session.refreshToken = d.refreshToken; session.uid = d.uid; - session.exp = Date.now() + (+(d.expiresIn || 3600) - 60) * 1000; save(); return true; - } catch (e) { session = null; save(); fire(); return false; } + let refreshing = null; + function refresh() { + if (!session || !session.refreshToken) return Promise.resolve(false); + if (refreshing) return refreshing; // single flight + refreshing = (async () => { + if (adoptStored()) return true; + try { const d = await post('/api/auth/refresh', { refreshToken: session.refreshToken }); setSession(d); return true; } catch (e) { + if (adoptStored()) return true; // lost the race against another tab + if (e.code === 'INVALID_REFRESH') { session = null; persist(); fire(); } + return false; + } + })().finally(() => { refreshing = null; }); + return refreshing; } async function token() { if (!session) return null; - if (Date.now() >= session.exp) { if (!await refresh()) return null; } - return session.idToken; + if (Date.now() >= session.exp && !(await refresh())) return null; + return session ? session.idToken : null; } + const authCall = async fn => { + if (!enabled) return { ok: false, error: 'OFFLINE' }; + try { setSession(await fn()); return { ok: true }; } catch (e) { return { ok: false, error: e.code || 'ERROR' }; } + }; const auth = { get current() { return cur(); }, onChange(fn) { listeners.push(fn); }, - async register(email, pass, name) { - if (!enabled) return { ok: false, error: 'OFFLINE' }; - email = String(email || '').trim().toLowerCase(); - try { - const d = await postJson(`${API}/auth/register`, { email, pass, name: Kit.cleanName(name) || email.split('@')[0] }); - setAuth(d, d.name || Kit.cleanName(name) || email.split('@')[0], false); - return { ok: true }; - } catch (e) { return { ok: false, error: e.code || 'ERROR' }; } - }, - async login(email, pass) { - if (!enabled) return { ok: false, error: 'OFFLINE' }; - email = String(email || '').trim().toLowerCase(); - try { - const d = await postJson(`${API}/auth/login`, { email, pass }); - setAuth(d, d.name || email.split('@')[0], false); - return { ok: true }; - } catch (e) { return { ok: false, error: e.code || 'ERROR' }; } - }, - async guest(name) { - if (!enabled) return { ok: false, error: 'OFFLINE' }; - try { - const d = await postJson(`${API}/auth/guest`, { name: Kit.cleanName(name) || 'Guest' }); - setAuth(d, d.name || Kit.cleanName(name) || 'Guest', true); - return { ok: true }; - } catch (e) { return { ok: false, error: e.code || 'ERROR' }; } - }, + register: (name, pass, email) => authCall(() => post('/api/auth/register', { name: Kit.cleanName(name), pass, email: String(email || '').trim() })), + login: (login, pass) => authCall(() => post('/api/auth/login', { login: String(login || '').trim(), pass })), + guest: name => authCall(() => post('/api/auth/guest', { name: Kit.cleanName(name) || 'Guest' })), resume() { - const s = store.get('session', null); + const s = stored(); if (!s || !s.refreshToken) return false; - session = Object.assign({ idToken: '', exp: 0 }, s); - refresh().then(ok => { if (ok) fire(); }); + session = s; + if (Date.now() >= (s.exp || 0)) refresh().then(ok => { if (ok) fire(); }); else fire(); return true; }, - logout() { const r = session && session.refreshToken; session = null; save(); fire(); if (r) fetch(`${API}/auth/logout`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: r }) }).catch(() => {}); }, - }; - - async function dbGet(path) { - if (!enabled) return null; - const t = await token(); - try { - const res = await fetch(`${DB}/${path}.json${t ? '?auth=' + t : ''}`, { cache: 'no-store' }); - return res.ok ? await res.json() : null; - } catch (e) { return null; } - } - async function dbWrite(method, path, value) { - if (!enabled) return false; - const t = await token(); - try { - const res = await fetch(`${DB}/${path}.json${t ? '?auth=' + t : ''}`, { - method, headers: { 'Content-Type': 'application/json' }, body: value === undefined ? undefined : JSON.stringify(value), - }); - return res.ok ? (method === 'POST' ? (await res.json()).name : true) : false; - } catch (e) { return false; } - } - - const db = { - get: dbGet, - put: (p, v) => dbWrite('PUT', p, v), - patch: (p, v) => dbWrite('PATCH', p, v), - push: (p, v) => dbWrite('POST', p, v), - del: p => dbWrite('DELETE', p), - // EventSource push stream. RTDB sends 'put' (whole subtree at /) and 'patch' (partial) events. - stream(path, onValue) { - if (!enabled || typeof EventSource === 'undefined') return { close() {} }; - let es = null, closed = false, value = null, retry = null; - const open = async () => { - if (closed) return; - const t = await token(); - es = new EventSource(`${DB}/${path}.json${t ? '?auth=' + t : ''}`); - // 'put' = replace the value at d.path; 'patch' = merge d.data's children into d.path - const setAt = (keys, data) => { - if (!keys.length) { value = data; return; } - if (value == null || typeof value !== 'object') value = {}; - let o = value; - for (let i = 0; i < keys.length - 1; i++) { if (o[keys[i]] == null || typeof o[keys[i]] !== 'object') o[keys[i]] = {}; o = o[keys[i]]; } - if (data == null) delete o[keys[keys.length - 1]]; else o[keys[keys.length - 1]] = data; - }; - const apply = ev => { - let d; try { d = JSON.parse(ev.data); } catch (e) { return; } - if (!d || typeof d.path !== 'string') return; - const keys = d.path.split('/').filter(Boolean); - if (ev.type === 'patch' && d.data && typeof d.data === 'object') { - for (const [k, v] of Object.entries(d.data)) setAt(keys.concat(k.split('/').filter(Boolean)), v); - } else setAt(keys, d.data); - try { onValue(value); } catch (e) { /* ignore */ } - }; - es.addEventListener('put', apply); - es.addEventListener('patch', apply); - es.onerror = () => { if (closed) return; es.close(); retry = setTimeout(open, 1500); }; - }; - open(); - return { close() { closed = true; clearTimeout(retry); if (es) es.close(); } }; + logout() { + const r = session && session.refreshToken; + socket.close(); session = null; persist(); fire(); + if (r) fetch(base + '/api/auth/logout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: r }) }).catch(() => {}); }, }; - return { enabled, auth, db, get uid() { return session ? session.uid : null; }, token }; + async function api(method, path, body) { + if (!enabled) return null; + for (let attempt = 0; attempt < 2; attempt++) { + const t = await token(); + try { + const res = await fetch(base + path, { + method, cache: 'no-store', + headers: Object.assign({ 'Content-Type': 'application/json' }, t ? { Authorization: 'Bearer ' + t } : {}), + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (res.status === 401 && attempt === 0 && session) { session.exp = 0; continue; } // token died early: refresh once + return res.ok ? await res.json() : null; + } catch (e) { return null; } + } + return null; + } + + // ---- one WebSocket with reconnect ------------------------------------------------------------- + const handlers = {}; + const emit = (type, msg) => (handlers[type] || []).slice().forEach(fn => { try { fn(msg); } catch (e) { console.error(e); } }); + let ws = null, want = false, retry = null, backoff = 1000, isOpen = false; + const wsUrl = () => { + const b = base || location.origin; + return b.replace(/^http/, 'ws') + '/ws'; + }; + async function open() { + if (!want || ws) return; + const t = await token(); + if (!t || !want || ws) { if (want) schedule(); return; } + const s = ws = new WebSocket(wsUrl()); + s.onopen = () => s.send(JSON.stringify({ t: 'hello', v: RC.Proto.VERSION, token: t })); + s.onmessage = ev => { + let msg; try { msg = JSON.parse(ev.data); } catch (e) { return; } + if (msg.t === 'welcome') { isOpen = true; backoff = 1000; emit('open', msg); } + if (msg.t === 'error' && (msg.code === 'OUTDATED' || msg.code === 'REPLACED')) { want = false; emit(msg.code === 'OUTDATED' ? 'outdated' : 'replaced', msg); } + if (msg.t === 'error' && msg.code === 'UNAUTH' && session) session.exp = 0; // refresh before the retry + emit(msg.t, msg); + }; + s.onclose = () => { + const was = isOpen; ws = null; isOpen = false; + if (was) emit('close', {}); + if (want) schedule(); + }; + s.onerror = () => {}; + } + function schedule() { clearTimeout(retry); retry = setTimeout(open, backoff); backoff = Math.min(10000, backoff * 2); } + const socket = { + get connected() { return isOpen; }, + connect() { if (!enabled) return; want = true; open(); }, + close() { want = false; clearTimeout(retry); if (ws) { try { ws.close(); } catch (e) { /* closed */ } } ws = null; isOpen = false; }, + send(msg) { if (ws && isOpen && ws.readyState === 1) { ws.send(JSON.stringify(msg)); return true; } return false; }, + on(type, fn) { (handlers[type] = handlers[type] || []).push(fn); return () => { handlers[type] = handlers[type].filter(f => f !== fn); }; }, + }; + + return { enabled, auth, api, socket, token, get uid() { return session ? session.uid : null; } }; }; })(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/netfight.js b/game/netfight.js index 378e8a7..28ccda3 100644 --- a/game/netfight.js +++ b/game/netfight.js @@ -1,162 +1,64 @@ -/* Robot Clash - live PvP sync over an existing deterministic fight. Needs net.js, combat.js, ai.js. - Robot 0 is always the local player, robot 1 the opponent (both clients see it that way, so the host - mirrors indices when it publishes). The lower-uid player is the host (authority): it runs the real - RC.Combat.step and publishes snapshots; the guest renders them and only sends its input. +/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat; + this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me"). - const nf = RC.NetFight({ net, id, host, mySeat, oppStyle, oppSkill, onPeerLost(wasHost) }); - nf.start() - HOST each tick, instead of the normal step: - nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events - GUEST each frame, instead of step: - nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play - nf.peerAlive false once the peer went silent > GRACE (AI takes over) - nf.stop() - - mySeat: 0 if I am meta[myUid] rendered as robot 0 (always true locally). The host publishes with robots - ordered [host, guest]; each side maps so that *its* robot is index 0. */ + const nf = RC.NetFight({ net, seat }) + nf.frame(s, input, dt) send input (on change, max 30/s, at least every 0.25 s), ease the local state toward + the newest snapshot, return the events of snapshots not seen yet + nf.oppAway true while the opponent is disconnected (server tells us) + nf.silentFor seconds since the last snapshot (connection trouble) + nf.stop() */ (function (root) { 'use strict'; const RC = (root.RC = root.RC || {}); - const PUB = 1 / 15, GRACE = 4000; // ms without news before the AI covers for the peer - // robot fields the view / HUD / sound read - kept small for the wire - const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out']; - const rnd = v => (typeof v === 'number' ? Math.round(v * 1000) / 1000 : v); - const packRobot = r => { const o = {}; for (const k of RF) o[k] = rnd(r[k]); return o; }; + const SEND_MIN = 1 / 30, SEND_KEEP = 0.25; + const EASE = ['x', 'z', 'y'], ANG = ['a', 'turretA']; const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; }; RC.NetFight = (opt) => { - const net = opt.net, db = net.db, id = opt.id, host = opt.host; - const base = `matches/${id}`; - let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = []; - let sending = false, slow = 0; // one write at a time; back off while the line is slow - let remoteInput = { throttle: 0, turn: 0, fire: false, fire2: false, fire3: false }; - let started = false, lastPeer = Date.now(), peerAlive = true, ai = null, subIn = null, subState = null, subPing = null, lastState = null, stateApplied = -1; + const sock = opt.net.socket, seat = opt.seat; + let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now(); + const off = sock.on('snap', m => { latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now(); }); - function start() { - if (host) { - // host reads the guest's input stream - subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } }); - } else { - // guest reads the host's state stream - subState = db.stream(`${base}/state`, v => { if (v && typeof v.seq === 'number') { lastState = v; lastPeer = Date.now(); } }); - subPing = db.stream(`${base}/ping`, v => { if (v) lastPeer = Date.now(); }); // host alive during the countdown - } + const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3; + function sendInput(inp, dt) { + sendT -= dt; keepT -= dt; + if (sendT > 0 || (!changed(inp) && keepT > 0)) return; + const i = RC.Proto.input(inp); + if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; } } - function checkPeer() { - if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock - if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); } - if (peerAlive && Date.now() - lastPeer > GRACE) { - peerAlive = false; - if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 }); - if (opt.onPeerLost) opt.onPeerLost(host); - } + function applyRobot(r, d, k) { + for (const f of EASE) if (typeof d[f] === 'number') r[f] += (d[f] - r[f]) * k; + for (const f of ANG) if (typeof d[f] === 'number') r[f] += wrap(d[f] - r[f]) * k; + for (const f of RC.Proto.RF) if (!EASE.includes(f) && !ANG.includes(f) && d[f] !== undefined) r[f] = d[f]; + if (d.lost) r.lost = Object.assign(r.lost || {}, d.lost); + if (d.lostW) r.lostW = d.lostW.slice(); + if (d.W && r.W) d.W.forEach((w, i) => { if (r.W[i]) Object.assign(r.W[i], w); }); } + const syncList = (dst, src, def) => { dst.length = src.length; for (let i = 0; i < src.length; i++) dst[i] = Object.assign(dst[i] || Object.assign({}, def), src[i]); }; - // HOST: step with [local, guest-or-AI], publish robots as [host, guest] but return a state where - // index 0 is the LOCAL player (so game.js renders identically on both sides). - function hostStep(s, localInput, dt) { - checkPeer(); - const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt); - RC.Combat.step(s, dt, [localInput, guestInput]); - if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest - pubT -= dt; - // publish only when the previous write came back - otherwise slow uploads queue up and the host stutters - if (pubT <= 0 && !sending) { - pubT = PUB + slow; - sending = true; - const t0 = Date.now(); - const payload = { - seq: ++seq, t: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: s.pitAlarm, - press: { st: s.press.st, y: rnd(s.press.y) }, crane: { st: s.crane.st, x: rnd(s.crane.x), z: rnd(s.crane.z), who: s.crane.who }, - rockets: s.rockets.map(k => ({ x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })), - mines: s.mines.map(k => ({ x: rnd(k.x), z: rnd(k.z), arm: rnd(k.arm) })), - r: [packRobot(s.robots[0]), packRobot(s.robots[1])], - ev: evBuf.slice(-24), result: s.result, endIn: rnd(s.endIn), - }; - evBuf.length = 0; - const done = () => { - sending = false; - const ms = Date.now() - t0; // slow line: send less often instead of piling up - slow = ms > 400 ? 0.2 : ms > 180 ? 0.08 : 0; - }; - try { Promise.resolve(db.put(`${base}/state`, payload)).then(done, done); } catch (e) { done(); } - } - return s.events; + function frame(s, inp, dt) { + sendInput(inp, dt); + if (!latest) return []; + const n = latest, k = Math.min(1, dt * 14); + s.t = n.time; s.left = n.left; s.pitOpen = n.pitOpen; s.pitAlarm = n.pitAlarm; s.endIn = n.endIn; + s.press.st = n.press.st; s.press.y = n.press.y; + Object.assign(s.crane, n.crane); + syncList(s.rockets, n.rockets, { sp: 6, t: 3 }); + syncList(s.mines, n.mines, { r: 0.85 }); + applyRobot(s.robots[0], n.robots[0], k); + applyRobot(s.robots[1], n.robots[1], k); + if (n.result) s.result = n.result; + if (n.tick === seenTick) return []; + seenTick = n.tick; + return n.ev || []; } - // GUEST: no simulation. Ease local robots toward the latest snapshot; snap flags/hp; play its events once. - function guestFrame(s, localInput, dt) { - checkPeer(); - // send my input (I am robot 0 locally = guest = snapshot index 1) - sendT -= dt; - beatT -= dt; - // send on change, and at least every 0.5 s as a heartbeat (otherwise the host thinks I am gone) - if (sendT <= 0 && !sending && (changed(localInput) || beatT <= 0)) { - sendT = PUB; beatT = 0.5; lastInSeq++; - sending = true; - const fin = () => { sending = false; }; - try { - Promise.resolve(db.put(`${base}/in`, { seq: lastInSeq, throttle: rnd(localInput.throttle || 0), turn: rnd(localInput.turn || 0), - fire: !!localInput.fire, fire2: !!localInput.fire2, fire3: !!localInput.fire3 })).then(fin, fin); - } catch (e) { fin(); } - prevInput = localInput; - } - const ev = []; - if (lastState) { - const snap = lastState; - s.t = snap.t; s.left = snap.left; s.pitOpen = snap.pitOpen; s.pitAlarm = snap.pitAlarm; - s.press.st = snap.press.st; s.press.y = snap.press.y; - s.crane.st = snap.crane.st; s.crane.x = snap.crane.x; s.crane.z = snap.crane.z; s.crane.who = snap.crane.who; - syncRockets(s, snap.rockets); - syncMines(s, snap.mines); - s.result = snap.result; s.endIn = snap.endIn; - // snapshot order [host, guest]; locally guest must be index 0 -> swap - applyRobot(s.robots[0], snap.r[1], dt); // me (guest) - applyRobot(s.robots[1], snap.r[0], dt); // host - if (snap.seq !== stateApplied) { - stateApplied = snap.seq; - for (const e of snap.ev || []) { const c = Object.assign({}, e); if (c.who === 0) c.who = 1; else if (c.who === 1) c.who = 0; ev.push(c); } - } - } - return ev; - } - - function applyRobot(r, d, dt) { - if (!d) return; - const k = Math.min(1, dt * 14); // ease position/angle, snap the rest - r.x += (d.x - r.x) * k; r.z += (d.z - r.z) * k; r.y += (d.y - r.y) * k; - r.a += wrap(d.a - r.a) * k; - r.turretA += wrap(d.turretA - r.turretA) * k; - for (const f of ['hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out']) if (d[f] !== undefined) r[f] = d[f]; - } - function syncRockets(s, list) { - list = list || []; - s.rockets.length = list.length; - for (let i = 0; i < list.length; i++) s.rockets[i] = Object.assign(s.rockets[i] || { owner: 1, sp: 6, t: 3 }, list[i]); - } - - function syncMines(s, list) { - list = list || []; - s.mines.length = list.length; - for (let i = 0; i < list.length; i++) s.mines[i] = Object.assign(s.mines[i] || { owner: 0, r: 0.85 }, list[i]); - } - - let prevInput = null; - function changed(inp) { return !prevInput || inp.throttle !== prevInput.throttle || inp.turn !== prevInput.turn || inp.fire !== prevInput.fire || inp.fire2 !== prevInput.fire2 || inp.fire3 !== prevInput.fire3; } - return { - start, hostStep, guestFrame, - // during the countdown: keep the line alive (guest sends a neutral input, host an empty state ping) - idle(dt) { - sendT -= dt; - if (sendT > 0) return; - sendT = 0.5; - if (host) db.patch(`${base}/ping`, { h: Date.now() }); - else { lastInSeq++; db.put(`${base}/in`, { seq: lastInSeq, throttle: 0, turn: 0, fire: false, fire2: false, fire3: false }); } - }, - get peerAlive() { return peerAlive; }, - stop() { if (subIn) subIn.close(); if (subState) subState.close(); if (subPing) subPing.close(); }, + frame, + get oppAway() { return !!(latest && latest.away && latest.away[1]); }, + get silentFor() { return (Date.now() - lastSnap) / 1000; }, + stop() { off(); }, }; }; })(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/netourney.js b/game/netourney.js deleted file mode 100644 index 559a71d..0000000 --- a/game/netourney.js +++ /dev/null @@ -1,121 +0,0 @@ -/* Robot Clash - live multiplayer tournament over Firebase (needs net.js + ltourney.js). - Players register, tick "ready", a 30 s countdown starts once >=2 are ready, then the bracket is - frozen and each pairing is played as a normal live PvP match (game.js supplies startMatch). - No server: the bracket is computed the same way on every client from the frozen list + seed - (RC.LTourney), results are shared through /tourney/results, a missing opponent is a walkover. - - const T = RC.NetTourney(net, { uid, name, flag }, { - onView(v){} // v = { phase, players, readyCount, countdown, order, results, me:{match,champion,out} } - startMatch(info){} // info = { id, host, seed, opp:{uid,name,build,paint,flag} } -> game starts the fight - }); - T.join(build, paint) / T.leave() / T.setReady(bool) / T.tick(dt) / T.reportWin(round, pair, uid) - T.close() - - /tourney in Firebase: - reg/ = { name, flag, build, paint, ready, ts } (each writes only their own) - meta = { phase:'open'|'countdown'|'running'|'done', startAt, seed, frozen:[uid...] } - results// = winnerUid */ -(function (root) { - 'use strict'; - const RC = (root.RC = root.RC || {}); - const COUNTDOWN = 30000, WALKOVER = 60000, STALE = 15000; - - RC.NetTourney = function (net, me, opt) { - const db = net.db, cb = opt || {}; - let reg = {}, meta = {}, results = {}; - let inMatch = false, roundStart = 0, lastRound = -1, wroteRun = false, wroteCount = false; - const subs = []; - - subs.push(db.stream('tourney/reg', v => { reg = v || {}; emit(); })); - subs.push(db.stream('tourney/meta', v => { meta = v || {}; emit(); })); - subs.push(db.stream('tourney/results', v => { results = v || {}; emit(); })); - - const now = () => Date.now(); - const readyUids = () => Object.keys(reg).filter(u => reg[u] && reg[u].ready && now() - (reg[u].ts || 0) < STALE * 3); - const frozen = () => (meta.frozen && meta.frozen.length ? meta.frozen : null); - - function view() { - const phase = meta.phase || 'open'; - const players = Object.keys(reg).map(u => ({ uid: u, name: reg[u].name, flag: reg[u].flag, ready: !!reg[u].ready, me: u === me.uid })); - const v = { phase, players, readyCount: readyUids().length, countdown: null, order: null, results: results, me: {} }; - if (phase === 'countdown' && meta.startAt) v.countdown = Math.max(0, Math.ceil((meta.startAt - now()) / 1000)); - const fr = frozen(); - if (fr && (phase === 'running' || phase === 'done')) { - const ord = RC.LTourney.order(fr, meta.seed || 1); - v.order = ord; - const m = RC.LTourney.myMatch(ord, results, me.uid); - if (!m) v.me.out = true; - else if (m.done) v.me.champion = m.champion; - else v.me.match = m; - } - return v; - } - function emit() { if (cb.onView) cb.onView(view()); drive(); } - - // my own registration row (heartbeat keeps it fresh) - let myRow = null; - function writeRow() { - if (!myRow) return; - db.put('tourney/reg/' + me.uid, Object.assign({ ts: now() }, myRow)); - } - function join(build, paint) { - myRow = { name: me.name, flag: me.flag || 'XX', ready: false, build: build, paint: paint }; - writeRow(); - } - function leave() { myRow = null; db.del('tourney/reg/' + me.uid); } - function setReady(on) { if (myRow) { myRow.ready = !!on; writeRow(); } } - - // state machine - every client runs it, writes are guarded so the first one wins - function drive() { - const phase = meta.phase || 'open'; - if (phase === 'open' && readyUids().length >= 2 && !wroteCount) { - wroteCount = true; - db.patch('tourney/meta', { phase: 'countdown', startAt: now() + COUNTDOWN, seed: (Math.random() * 1e9) | 0 }); - } - if (phase === 'countdown') { - wroteCount = true; - if (meta.startAt && now() >= meta.startAt && !wroteRun) { - wroteRun = true; - db.patch('tourney/meta', { phase: 'running', frozen: readyUids().sort() }); - } - } - if (phase === 'running') { - const fr = frozen(); if (!fr) return; - const ord = RC.LTourney.order(fr, meta.seed || 1); - const m = RC.LTourney.myMatch(ord, results, me.uid); - if (!m || m.done) { if (m && m.done && !meta.doneWrote) db.patch('tourney/meta', { phase: 'done' }); return; } - if (m.round !== lastRound) { lastRound = m.round; roundStart = now(); } - if (m.opp == null) return; // bye: bracket advances by itself - if (inMatch) return; - // opponent gone / never there -> walkover after the timer - const oppReg = reg[m.opp]; - const oppGone = !oppReg || now() - (oppReg.ts || 0) > STALE; - if (oppGone && now() - roundStart > WALKOVER) { reportWin(m.round, m.pairIndex, me.uid); return; } - // both present -> the host kicks the match off once (guest joins the same match id) - if (!oppReg) return; - inMatch = true; - const id = [me.uid, m.opp].sort().join('_'); - if (cb.startMatch) cb.startMatch({ id: id, host: m.host, seed: (meta.seed || 1) + m.round * 7, - round: m.round, pairIndex: m.pairIndex, oppUid: m.opp, - opp: { uid: m.opp, name: oppReg.name, build: oppReg.build, paint: oppReg.paint, flag: oppReg.flag } }); - } - } - - function reportWin(round, pair, uid) { - inMatch = false; - db.patch('tourney/results/' + round, { [pair]: uid }); - } - function matchDone() { inMatch = false; } - - return { - join, leave, setReady, reportWin, matchDone, - tick() { /* heartbeat + state progress */ writeRow(); drive(); }, - view, - // host-only admin reset (clears everything for a fresh tournament) - reset() { db.del('tourney'); }, - close() { subs.forEach(s => s && s.close()); }, - }; - }; - - if (typeof module !== 'undefined' && module.exports) module.exports = RC; -})(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/protocol.js b/game/protocol.js index cd8170e..5d8845b 100644 --- a/game/protocol.js +++ b/game/protocol.js @@ -88,6 +88,7 @@ return Object.assign({}, snap, { robots, ack: snap.ack ? snap.ack[seat] : 0, + away: snap.away ? (seat === 0 ? snap.away.slice() : [snap.away[1], snap.away[0]]) : undefined, result: localResult(seat, snap.result), crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }), rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })), diff --git a/game/ranking.js b/game/ranking.js index c5f9cf2..a91ee33 100644 --- a/game/ranking.js +++ b/game/ranking.js @@ -1,50 +1,41 @@ -/* Robot Clash - online ranking over the own server (ranks/, public read, owner write). - One row per account (dedupe by key is implicit); live push via net.db.stream (SSE). - Needs net.js + kit-core.js (Kit.badName). DOM-free; RC.Ranking.rank is a pure function (Node-testable). +/* Robot Clash - online ranking. The server computes it from the online saves (fame only changes through + server-booked fights), so the client only reads: GET /api/ranks, polled while a board is open. + DOM-free; RC.Ranking.rank is a pure function (Node-testable). const rank = RC.Ranking(net); if (rank.enabled) { - await rank.submit({ uid, name, fame, flag, cls, season }); // best effort, never throws - const sub = rank.watch(rows => draw(rows)); // { close() } live, rows best first - const rows = await rank.once(20); // one-shot fallback (no stream) + const sub = rank.watch(rows => draw(rows)); // { close() } rows best first, refreshed every 15 s + const rows = await rank.once(20); } - RC.Ranking.rank(data, n) // { key: {name,fame,...} } -> sorted array, bad names out, capped */ + RC.Ranking.rank(data, n) // [{uid,name,fame,flag}] or { key: {...} } -> sorted array, bad names out, capped */ (function (root) { 'use strict'; const RC = (root.RC = root.RC || {}); const Kit = root.Kit || {}; const bad = s => (Kit.badName ? Kit.badName(s) : false); + const POLL = 15000; - // pure: raw ranks object -> clean, sorted (fame desc, newer first on tie), capped list RC.Ranking = function (net) { - const api = { - enabled: !!(net && net.enabled), - async submit(row) { - if (!api.enabled || !row || !row.uid) return false; - const name = String(row.name || '').slice(0, 20); - if (!name || bad(name) || !(row.fame > 0)) return false; - const r = await net.db.put('ranks/' + row.uid, { - name, fame: Math.floor(row.fame) | 0, flag: row.flag || 'XX', - cls: row.cls || 'medium', season: row.season | 0, ts: { '.sv': 'timestamp' }, - }); - return !!r; - }, + const enabled = !!(net && net.enabled); + const fetchRows = async n => RC.Ranking.rank(await net.api('GET', '/api/ranks?n=' + (n || 20)), n); + return { + enabled, watch(cb, n) { - if (!api.enabled) { cb([]); return { close() {} }; } - return net.db.stream('ranks', data => cb(RC.Ranking.rank(data, n))); - }, - async once(n) { - if (!api.enabled) return []; - return RC.Ranking.rank(await net.db.get('ranks'), n); + if (!enabled) { cb([]); return { close() {} }; } + let alive = true; + const tick = () => fetchRows(n).then(rows => { if (alive) cb(rows); }); + tick(); + const timer = setInterval(tick, POLL); + return { close() { alive = false; clearInterval(timer); } }; }, + once: n => (enabled ? fetchRows(n) : Promise.resolve([])), }; - return api; }; RC.Ranking.rank = function (data, n = 20) { - const rows = Object.entries(data || {}) - .map(([key, v]) => Object.assign({ key }, v)) - .filter(v => v && typeof v.name === 'string' && typeof v.fame === 'number' && !bad(v.name)); + const list = Array.isArray(data) ? data.map(v => Object.assign({ key: v.uid }, v)) + : Object.entries(data || {}).map(([key, v]) => Object.assign({ key }, v)); + const rows = list.filter(v => v && typeof v.name === 'string' && typeof v.fame === 'number' && !bad(v.name)); rows.sort((a, b) => b.fame - a.fame || (b.ts || 0) - (a.ts || 0)); return rows.slice(0, n); }; diff --git a/game/shop.js b/game/shop.js index f231b0a..e13c71a 100644 --- a/game/shop.js +++ b/game/shop.js @@ -15,7 +15,6 @@ // ready-made [body, accent] combinations RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230], [0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]]; - const SELL = 0.5; const HOTKEY = { weapon: 'hk_weapon', tower: 'hk_tower', gadget: 'hk_gadget' }; const GLYPH = { chassis: '🧱', motor: '⚙️', wheels: '🛞', battery: '🔋', armour: '🛡️', weapon: '🪓', tower: '🔥', gadget: '🧰' }; const ICO = { hp: ['ico_hp', '❤️'], armour: ['ico_armour', '🛡️'], speed: ['ico_speed', '⏱️'], weight: ['ico_weight', '⚖️'], @@ -98,7 +97,7 @@ if (eq) act = ``; else if (own) act = ``; else act = ``; - if (p && own && !eq) act += ``; + if (p && own && !eq) act += ``; if (p && !own && save.money < p.cost) act += `${t('need_money', { n: Kit.fmt(p.cost - save.money) })}`; $('detail').innerHTML = `${RC.pic(p ? 'part_' + sel : null, p ? GLYPH[slot] : '✖')}
${p ? p.name : t('none')}
${p ? t('pd_' + sel) : t('none_' + slot)}
@@ -183,21 +182,18 @@ }).join(''); $('fitted').querySelectorAll('.frow').forEach(el => { el.onclick = e => { if (el.dataset.edit) { slot = 'weapon'; opt.sfx.click(); render(); return; } - if (e.target.dataset.rm) { const s = e.target.dataset.rm; opt.getSave().build[s] = null; opt.sfx.click(); opt.onSave(); opt.onBuild(); render(); return; } + if (e.target.dataset.rm) { const s = e.target.dataset.rm; if (!opt.act({ type: 'equip', slot: s, part: null }).ok) { opt.sfx.deny(); return; } opt.sfx.click(); opt.onSave(); opt.onBuild(); render(); return; } slot = el.dataset.goto; sel = opt.getSave().build[slot] || null; topTab = 'build'; opt.sfx.click(); render(); }; }); } + // every economy change goes through opt.act (RC.Eco rules; online the server checks the same action) function act2(what) { - const save = opt.getSave(), p = sel ? RC.PARTS[sel] : null; - if (what === 'buy' && p && save.money >= p.cost && !save.owned.includes(sel)) { - save.money -= p.cost; save.owned.push(sel); save.build[slot] = sel; opt.sfx.buy(); - say(t('tip_bought', { name: p.name })); - } else if (what === 'eq') { - save.build[slot] = sel; opt.sfx.click(); - } else if (what === 'sell' && p && save.build[slot] !== sel) { - save.owned = save.owned.filter(x => x !== sel); save.money += Math.round(p.cost * SELL); opt.sfx.buy(); - } else { opt.sfx.deny(); return; } + const p = sel ? RC.PARTS[sel] : null; + const a = what === 'buy' ? { type: 'buy', part: sel } : what === 'eq' ? { type: 'equip', slot, part: sel || null } : what === 'sell' ? { type: 'sell', part: sel } : null; + if (!a || !opt.act(a).ok) { opt.sfx.deny(); return; } + if (what === 'eq') opt.sfx.click(); else opt.sfx.buy(); + if (what === 'buy' && p) say(t('tip_bought', { name: p.name })); opt.onSave(); opt.onBuild(); render(); }