/* Robot Clash - online play in the browser: server-checked workshop actions (act), online save sync, login card, lobby, live fight start/end. Part of game.js (split for size): created once by game.js with the shared context G. Live state (save, mode, F, ...) is read as G.; services/helpers are taken from G at creation. */ (function (root) { 'use strict'; const RC = (root.RC = root.RC || {}); RC.GameOnline = function (G) { const { $, FLAGS, SFX, accounts, achHtml, card, ensureFlag, enterAccount, esc, fbAcc, flagHtml, hideOverlay, hud, img, layer, loadSave, lobby, net, openGarage, overlay, paintObj, persist, playerName, prepOpp, refreshDev, renderWeaponEditor, repairSave, setMode, setScreen, shop, showLegal, showTitle, startFight, t } = G; // ---- online save: the server is the authority for money, fame, parts and robots ------------------- // act(): every workshop change goes through RC.Eco (game/eco.js). Applied locally at once; online the same // action is sent to the server (one at a time, in order) and the server's answer replaces our economy fields. let actQueue = Promise.resolve(); function act(a) { const r = RC.Eco.apply(G.save, a); if (!r.ok) return r; if (G.gameMode === 'online' && net.enabled && net.uid) { actQueue = actQueue.then(() => net.api('POST', '/api/online/action', a)).then(res => { if (!res || !res.save) return; if (!res.ok || econDiffers(res.save)) { adoptEconomy(res.save); afterEconomy(); } }, () => {}); } return r; } const econKey = s => JSON.stringify([s.money, s.fame, s.owned, s.active, (s.robots || []).map(r => r.build)]); const econDiffers = srv => econKey(srv) !== econKey(G.save); // keepLooks: robot names/paint are client-owned - keep ours (they may not be uploaded yet) function adoptEconomy(srv, keepLooks = true) { const looks = keepLooks && G.save.robots ? G.save.robots.map(r => ({ name: r.name, paint: r.paint })) : []; for (const k of RC.Eco.ECONOMY) if (srv[k] !== undefined) G.save[k] = srv[k]; if (keepLooks && looks.length === G.save.robots.length) G.save.robots.forEach((r, i) => { r.name = looks[i].name; r.paint = looks[i].paint; }); RC.Eco.mirror(G.save); G.slot.save(G.save); } function afterEconomy() { hud(); if (G.mode === 'garage') { shop.render(); G.view.showGarage(G.save.build, paintObj()); if (G.editorOpen) renderWeaponEditor(); } } // cosmetics (names, paint, flag, ...) are client-owned: debounced upload, the server keeps only those fields let pushTimer = null; const cosmetics = () => { const c = {}; for (const k of RC.Eco.COSMETIC) if (G.save[k] !== undefined) c[k] = G.save[k]; c.robots = G.save.robots.map(r => ({ name: r.name, paint: r.paint })); return c; }; function onlinePush() { clearTimeout(pushTimer); pushTimer = setTimeout(onlineFlush, 1500); } function onlineFlush() { clearTimeout(pushTimer); if (G.gameMode === 'online' && G.save && net.uid) net.api('PUT', '/api/online/save', cosmetics()); } // after login / page load: economy from the server; cosmetics from whichever copy is newer function onlinePull() { if (G.gameMode !== 'online' || !net.uid) return; const uid = net.uid; net.api('GET', '/api/online').then(srv => { if (!srv || !G.save || G.gameMode !== 'online' || net.uid !== uid) return; const serverNewer = (+srv.ts || 0) > (+G.save.ts || 0); if (serverNewer) { for (const k of RC.Eco.COSMETIC) if (srv[k] !== undefined) G.save[k] = srv[k]; } adoptEconomy(srv, !serverNewer); repairSave(); RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); }); if (!serverNewer) onlinePush(); afterEconomy(); }); } // ---------------------------------------------------------------- online lobby // The server owns presence, challenges and fights (server/lobby.js). This draws its state and forwards clicks. const myRoom = () => G.joinedRoom || (FLAGS.includes(G.save.flag) ? G.save.flag : 'XX'); const pendingOut = () => (lobby ? lobby.pending : null); function wireLobby() { lobby.onList(rows => { G.lobbyRows = rows; if (G.mode === 'lobby') renderLobby(); }); lobby.onIncoming(c => { if (G.mode === 'lobby' || G.mode === 'garage') showIncoming(c); }); lobby.onMatch(m => startOnlineFight(m)); lobby.onEnd(m => onlineFightEnded(m)); lobby.onCancel(c => { if (G.mode === 'lobby') { renderLobby(); if (c.outgoing) SFX.deny(); } else if (!c.outgoing && $('cYes')) hideOverlay(); // the challenger gave up while I was asked }); lobby.onError(code => { SFX.deny(); if (G.mode === 'lobby') { renderLobby(); const el = $('lMsg'); if (el) el.textContent = errText(code); } else if (G.mode === 'garage') $('mechTip').textContent = errText(code); }); net.socket.on('outdated', () => { card(`

${t('reload_title')}

${t('e_OUTDATED')}

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

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

${t('online_login_text')}

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

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

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

${t('net_connecting')}

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

${t('waiting_accept')}

` : ''} ${offline}

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

${t('challenge_in')}

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

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

${title}

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

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

${t('net_lost')}

${t('match_lost')}

`, { bg: 'bg_lose.jpg' }); $('bLobby').onclick = () => { SFX.click(); onlinePull(); showLobby(); }; } return { actQueue, act, econKey, econDiffers, adoptEconomy, afterEconomy, pushTimer, cosmetics, onlinePush, onlineFlush, onlinePull, myRoom, pendingOut, wireLobby, startOnline, joinAnon, errText, showOnlineLogin, showLobby, renderLobby, showIncoming, startOnlineFight, onlineFightEnded, endOnlineFight, onlineFightLost }; }; })(window);