Files
Robot-Clash/game/online.js
Benjamin Oezcan 4535ac7d8a refactor(game): split game.js into sfx, pages, online and workshop modules (P4-5)
Modules are classic-script factories RC.Game<Part>(G); G gives live access to the shared state.
Guarded by new browser tests for every moved page and workshop tool (tests/e2e/screens.spec.js).
2026-11-19 09:58:53 +01:00

258 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 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.<name>; 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(`<h2>${t('reload_title')}</h2><p>${t('e_OUTDATED')}</p><div class="row"><button class="primary" id="rNow">${t('reload_now')}</button></div>`, { 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
? `<label>${t('f_name')}</label><input type="text" id="oName" maxlength="18" autocomplete="username">
<label>${t('f_email_opt')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email">`
: `<label>${t('f_login')}</label><input type="text" id="oLogin" autocomplete="username" autocapitalize="off" autocorrect="off" spellcheck="false">`;
card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
<div class="form">${f}
<label>${t('f_pass')}</label><input type="password" id="oPass" autocomplete="${reg ? 'new-password' : 'current-password'}"></div>
${reg ? `<label class="chk"><input type="checkbox" id="oConsent"> ${t('consent_pre')} <button type="button" class="link" id="oPriv">${t('legal_privacy')}</button></label>` : ''}
<div class="err" id="oErr">${errKey ? errText(errKey) : ''}</div>
<div class="row"><button id="oBack">${t('back')}</button><button class="primary" id="oGo">${reg ? t('register_go') : t('login')}</button></div>
<p class="muted">${reg ? '' : t('no_account') + ' '}<button class="link" id="oToggle">${reg ? t('login') : t('register')}</button></p>
${next === 'online' ? `<div class="row"><button id="oAnon">👤 ${t('online_guest')}</button></div>` : ''}`, { 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 => `<option value="${f}" ${f === myFlag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('');
const room = (f, label, flag) => `<button class="rroom ${G.lobbyRoom === f ? 'on' : ''} ${f === mine ? 'joined' : ''}" data-f="${f}"><span class="rfl">${flag ? flagHtml(f) : ''}</span><span class="rn">${label}${f === mine ? ' <span class="rhere">📍</span>' : ''}</span><span class="cnt ${cnt(f) ? 'live' : ''}">${f === 'all' ? total : cnt(f)}</span></button>`;
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 ? `<button class="chal" data-uid="${esc(r.uid)}">${t('challenge')}</button>` : `<span class="pbusy">${r.state === 'idle' ? '' : t('busy')}</span>`);
const prow = (r, me) => `<div class="prow ${me ? 'me' : ''}" ${me ? '' : `data-uid="${esc(r.uid)}"`}><span class="pf">${flagHtml(me ? G.save.flag : r.flag)}</span><span class="pn">${esc(me ? playerName() : r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}</span><span class="pfame">⭐ ${Kit.fmt((me ? G.save.fame : r.fame) | 0)}</span>${me ? '<span class="pbusy"></span>' : action(r)}</div>`;
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 ? `<p class="muted" style="margin:6px 0 0">${t('net_connecting')}</p>` : '';
overlay.innerHTML = `<div class="lobbyfull">
<div class="lobbyL"><div class="lobbyLh">🌍 ${t('lobby')}</div><div class="roomlist">${rooms}</div></div>
<div class="lobbyR">
<div class="lobbyRh">${title} <span class="muted">(${here.length + (showMe ? 1 : 0)})</span><span class="grow"></span>
<label class="flagpick">${t('your_flag')} <select id="lFlag">${flagOpts}</select></label></div>
<div class="plist">${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `<div class="muted" style="padding:16px;text-align:center">${t('lobby_empty')}</div>`)}</div>
${out ? `<p class="muted" style="margin:6px 0 0">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''}
${offline}<p class="err" id="lMsg" style="margin:4px 0 0"></p>
<div class="row" style="margin-top:8px"><button id="lBack">${t('back')}</button><button class="primary" id="lQuick">${t('quick_match')}</button></div>
</div></div>`;
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(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p>
<div class="row"><button id="cNo">${t('decline')}</button><button class="primary" id="cYes">${t('accept')}</button></div>`);
$('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]) => `<span>${t(k)}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
const ach = (rw.ach || []).map(a => ({ id: a.id, reward: a.reward }));
hud();
setScreen('result');
card(`<h1>${title}</h1><p>${esc(G.F.opp.name)} ${G.F.oppAway ? t('peer_left') : ''}</p>
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(sm.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(sm.taken)}</span>${rows}
${rw.fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(rw.fame)}</span>` : ''}</div>
${achHtml(ach)}
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`,
{ 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(`<h2>${t('net_lost')}</h2><p>${t('match_lost')}</p>
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button></div>`, { 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);