onlinemodus fix failed

This commit is contained in:
2026-11-19 00:55:39 +01:00
parent 64c5b65543
commit 347701d66f
10 changed files with 414 additions and 53 deletions

View File

@@ -68,6 +68,7 @@
money: 800, fame: 0, best: 0, season: 1, beaten: 0, wins: 0, losses: 0, games: 0,
owned: Object.values(RC.STARTER).filter(Boolean), build: Object.assign({}, RC.STARTER),
paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', flag: 'XX', flagSet: false, tutorialSeen: false, ach: {}, tour: null, cls: 'medium', leagues: null,
missions: null, mseed: (Math.random() * 1e9) | 0, unlockedPaints: null, unlockedSchemes: null,
robots: [], active: 0, // hangar: saved robot builds; the active one mirrors build/paint/robotName
});
const MAX_ROBOTS = 6;
@@ -101,15 +102,17 @@
// (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: only the admin account (ADMIN_UID on the server) sees it. The server tells us via /api/me.
// dev menu (coins): guests get it too for now; registered accounts only if admin (server tells us via /api/me).
let isDev = false;
function refreshDev() {
if (!net.enabled || !fbAcc()) { isDev = false; return; }
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(() => {}); });
}
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
const lobby = net.enabled ? RC.Lobby({ net, getProfile: () => ({ name: playerName(), flag: save.flag || 'XX', 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, 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 fx = Kit.fx();
const input = Kit.input({
@@ -182,7 +185,7 @@
const cv = $('cv');
let ctx = cv.getContext('2d');
let view = null;
try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); } catch (err) { console.error(err); }
try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); if (view.setComfort) view.setComfort(settings.comfort); } catch (err) { console.error(err); }
// cap upscaling so the UI does not get huge on big / high-DPI screens (960x540 stage, max ~2x)
Kit.fit($('app'), { max: 2.0, margin: document.documentElement.classList.contains('exe') ? 1 : 0.98,
canvases: [[cv, W, H]], onFit(sc) { ctx = cv.getContext('2d'); if (view) view.resize(sc); } });
@@ -369,9 +372,10 @@
+ `<div class="psec"><h4>${t('paint_body')}</h4><div class="pgrid" id="paintBody"></div></div>`
+ `<div class="psec"><h4>${t('paint_accent')}</h4><div class="pgrid" id="paintAccent"></div></div>`
+ `<div class="psec"><h4>${t('paint_schemes')}</h4><div class="pgrid wide" id="paintSchemes"></div></div>`;
const lockP = c => (RC.PAINT_REWARDS || []).includes(c) && !(save.unlockedPaints || []).includes(c); // reward colour, not earned yet
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${save.paint[key] === c ? 'on' : ''}" data-c="${c}" style="background:${phex(c)}"></span>`).join('');
$(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint[key] = +sw.dataset.c; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${save.paint[key] === c ? 'on' : ''} ${lockP(c) ? 'locked' : ''}" data-c="${c}" style="background:${phex(c)}" title="${lockP(c) ? t('paint_locked') : ''}">${lockP(c) ? '<span class="lk">🔒</span>' : ''}</span>`).join('');
$(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { if (sw.classList.contains('locked')) { SFX.deny && SFX.deny(); return; } save.paint[key] = +sw.dataset.c; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
}
$('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = save.paint.body === b2 && save.paint.accent === a2; return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${phex(b2)}"></i><i style="background:${phex(a2)}"></i></span>`; }).join('');
$('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint.body = +sw.dataset.b; save.paint.accent = +sw.dataset.a; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
@@ -544,7 +548,7 @@
<div class="hazbar"></div>
<div class="tmenu">${btns}</div>
<div class="trow2"><button id="bSet">⚙ ${t('settings')}</button><button id="bHelp">${t('how_to')}</button>
<button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>${save ? `<button id="bAch">🏅 ${t('achievements')}</button>` : ''}${rank.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}</div>
<button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>${save ? `<button id="bAch">🏅 ${t('achievements')}</button>` : ''}${rank.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}<button id="bLegal">§ ${t('legal')}</button></div>
<p class="credits">${CREDITS}</p></div>${rank.enabled ? `<div class="trank"><h3>🏆 ${t('ranking')} <span class="livedot">● ${t('rank_live')}</span></h3><ol id="trankList"><li class="trmuted">${t('loading')}</li></ol></div>` : ''}</div>`;
overlay.classList.remove('hide'); overlay.classList.add('clear'); overlay.style.backgroundImage = '';
const on = (id, f) => { const el = $(id); if (el) el.onclick = () => { SFX.click(); f(); }; };
@@ -559,6 +563,7 @@
on('bLang', () => L.next());
on('bAch', () => showAchievements(showTitle));
on('bRank', () => showRanking(showTitle));
on('bLegal', () => showLegal(showTitle));
hud();
if (rank.enabled) startTitleRank();
}
@@ -579,7 +584,9 @@
}
// ---------------------------------------------------------------- online lobby
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker)
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker, = 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
async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page)
if (!net.enabled) return;
@@ -614,14 +621,17 @@
card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
<div class="form">${f}<label>${t('f_email')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email">
<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($('oMail').value.trim(), $('oPass').value, $('oName') ? $('oName').value : '')
: await net.auth.login($('oMail').value.trim(), $('oPass').value);
@@ -638,16 +648,16 @@
// 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 => (FLAGS.includes(r.flag) ? r.flag : 'XX');
const code = r => { const c = r.room || r.flag; return FLAGS.includes(c) ? c : 'XX'; }; // group by the room a player JOINED, not their flag
const all = lobbyRows;
const myFlag = FLAGS.includes(save.flag) ? save.flag : 'XX';
// I am in the lobby too: count myself in my own country (and in "all"), and only list me there
const myFlag = FLAGS.includes(save.flag) ? save.flag : 'XX', mine = myRoom();
// I am in the lobby too: count myself in the room I joined (and in "all"), and only list me there
const total = all.length + 1;
const cnt = f => all.filter(r => code(r) === f).length + (f === myFlag ? 1 : 0);
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 === myFlag;
const showMe = lobbyRoom === 'all' || lobbyRoom === mine;
const flagOpts = FLAGS.map(f => `<option value="${f}" ${f === myFlag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('');
const room = (f, label, flag) => `<button class="rroom ${lobbyRoom === f ? 'on' : ''}" data-f="${f}"><span class="rfl">${flag ? flagHtml(f) : ''}</span><span class="rn">${label}</span><span class="cnt ${cnt(f) ? 'live' : ''}">${f === 'all' ? total : cnt(f)}</span></button>`;
const room = (f, label, flag) => `<button class="rroom ${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 prow = (r, me) => `<div class="prow ${me ? 'me' : ''}" ${me ? '' : `data-uid="${r.uid}"`}><span class="pf">${flagHtml(me ? save.flag : r.flag)}</span><span class="pn">${esc(me ? playerName() : r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}</span><span class="pfame">\u2B50 ${Kit.fmt((me ? save.fame : r.fame) | 0)}</span>${me ? '<span class="pbusy"></span>' : (r.state === 'idle' ? `<button class="chal" data-uid="${r.uid}">${t('challenge')}</button>` : `<span class="pbusy">${t('busy')}</span>`)}</div>`;
const list = here.map(r => prow(r, false)).join('');
@@ -663,7 +673,11 @@
</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(); lobbyRoom = b.dataset.f; renderLobby(); }; });
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)
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(); };
@@ -781,11 +795,14 @@
<div class="form"><label>${t('f_name')}</label><input type="text" id="fName" maxlength="18" autocomplete="username">
<label>${t('f_pass')}</label><input type="password" id="fPass" autocomplete="new-password">
<label>${t('f_pass2')}</label><input type="password" id="fPass2" autocomplete="new-password"></div>
<label class="chk"><input type="checkbox" id="fConsent"> ${t('consent_pre')} <button type="button" class="link" id="fPriv">${t('legal_privacy')}</button></label>
<div class="err" id="fErr"></div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('register_go')}</button></div>
<p class="muted" style="font-size:11px">${t('local_note')}</p>`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showTitle(); };
$('fPriv').onclick = () => { SFX.click(); showLegal(showRegister, 'privacy'); };
$('bGo').onclick = async () => {
if (!$('fConsent').checked) { SFX.deny(); $('fErr').textContent = t('consent_required'); return; }
if ($('fPass').value !== $('fPass2').value) { SFX.deny(); $('fErr').textContent = t('e_pass_match'); return; }
const r = await accounts.register($('fName').value, $('fPass').value);
if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; }
@@ -841,6 +858,10 @@
function repairSave() {
save.owned = (save.owned || []).filter(id => RC.PARTS[id]);
if (save.flagSet === undefined) save.flagSet = !!(save.flag && save.flag !== 'XX'); // old saves that already picked a flag keep it
if (save.mseed == null) save.mseed = (Math.random() * 1e9) | 0; // stable per-save mission seed
const rewardPaint = c => (RC.PAINT_REWARDS || []).includes(c);
if (!Array.isArray(save.unlockedPaints)) save.unlockedPaints = RC.PAINTS.filter(c => !rewardPaint(c)); // all but the reward colours
if (!Array.isArray(save.unlockedSchemes)) save.unlockedSchemes = RC.SCHEMES.map((_, i) => i); // all schemes free
// weight classes: an older save has one league - that progress becomes the medium class
if (!save.leagues) {
save.leagues = { light: { beaten: 0, season: 1 },
@@ -956,26 +977,28 @@
${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))}
${item(t('s_comfort'), seg('sComfort', settings.comfort ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))}
${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
${item(t('s_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))}
${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))}
${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
</div>
${isDev ? `<div class="setdev"><span class="sl">🛠 Dev · Coins</span><div class="row">
${isDev && save ? `<div class="setdev"><span class="sl">🛠 Dev · Coins</span><div class="row">
<button data-coin="10000">+10k</button><button data-coin="100000">+100k</button>
<button data-coin="1000000">+1M</button><button data-coin="set800">Reset 800</button></div></div>` : ''}
<div class="setacc"><span class="sl">${t('s_account')}</span>
<span class="who">${who ? '👤 <b>' + esc(who.name) + '</b>' + (who.email ? ' <span class="muted">' + esc(who.email) + '</span>' : '') : '👤 ' + t('guest')}</span>
${save ? `<button id="sOut">${who ? t('logout') : t('to_title')}</button>` : ''}</div>
<div class="row"><button id="sFull">⛶ ${t('win_full')}</button><button id="sKeys">🎮 ${t('s_controls')}</button>
${save ? `<button id="sReset">${t('reset')}</button>` : ''}<button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
<button id="sLegal">§ ${t('legal')}</button>${save ? `<button id="sReset">${t('reset')}</button>` : ''}<button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; });
segOn('sLang', v => { L.set(v); showSettings(back); });
segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); });
segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); });
segOn('sSteer', v => { settings.steer = v; saveSettings(); });
segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); });
segOn('sComfort', v => { settings.comfort = v === '1'; saveSettings(); if (view && view.setComfort) view.setComfort(settings.comfort); });
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; saveSettings(); });
@@ -992,6 +1015,7 @@
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); };
$('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); };
if ($('sLegal')) $('sLegal').onclick = () => { SFX.click(); showLegal(() => showSettings(back)); };
$('bBack').onclick = () => { SFX.click(); back(); };
}
function keysHtml() {
@@ -1065,12 +1089,47 @@
$('bBack').onclick = () => { SFX.click(); back(); };
}
// campaign missions page: 3 daily + 1 weekly with progress bars + reset countdown
function showMissions(back) {
overlayEnter();
ensureMissions();
const daily = (save.missions && save.missions.daily) || [], weekly = (save.missions && save.missions.weekly) || [];
const hrs = ms => Math.max(1, Math.ceil(ms / 3600000));
const toDay = 86400000 - (Date.now() % 86400000), toWeek = 604800000 - (Date.now() % 604800000);
const row = m => {
const prog = Math.min(m.prog || 0, m.goal), pct = Math.round(prog / m.goal * 100);
const rew = `🪙 ${Kit.fmt(m.reward)}${m.fame ? ' · ⭐' + m.fame : ''}${typeof m.unlock === 'number' ? ' · 🎨' : ''}`;
return `<div class="missrow ${m.done ? 'done' : ''}"><span class="mm">${m.done ? '✅' : '🎯'}</span>
<div class="mi"><div class="mn">${t('mission_' + m.id)}</div><div class="md">${t('missd_' + m.id)}</div>
<div class="bar"><i style="width:${pct}%"></i></div></div>
<div class="mr"><span class="${m.done ? 'plus' : 'muted'}">${rew}</span><span class="mp">${prog}/${m.goal}</span></div></div>`;
};
card(`<h2>🎯 ${t('missions')}</h2>
<h3>${t('miss_daily')} <span class="muted">· ${t('miss_reset_in', { n: hrs(toDay) })}</span></h3>
<div class="misslist">${daily.map(row).join('')}</div>
<h3>${t('miss_weekly')} <span class="muted">· ${t('miss_reset_in', { n: hrs(toWeek) })}</span></h3>
<div class="misslist">${weekly.map(row).join('')}</div>
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); back(); };
}
function showHelp(back) {
overlayEnter();
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>${keysHtml()}
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`, { bg: 'bg_title.jpg' });
$('bOk').onclick = () => { SFX.click(); back(); };
}
// legal pages (Impressum / Datenschutz) — placeholders, Michael fills his data in lang.js
function showLegal(back, which) {
overlayEnter();
which = which === 'privacy' ? 'privacy' : 'impressum';
const seg = ['impressum', 'privacy'].map(k => `<button data-l="${k}" class="${k === which ? 'on' : ''}">${t('legal_' + k)}</button>`).join('');
card(`<h2>${t('legal')}</h2><div class="seg legalseg">${seg}</div>
<div class="legaltext">${t(which + '_text')}</div>
<div class="row"><button class="primary" id="bOk">${t('ok')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.legalseg button').forEach(b => b.onclick = () => { SFX.click(); showLegal(back, b.dataset.l); });
$('bOk').onclick = () => { SFX.click(); back(); };
}
let rankSub = null, titleRankSub = null, boardFame = {}, boardIdx = {};
const closeRank = () => { if (rankSub) { rankSub.close(); rankSub = null; } };
function showRanking(back) {
@@ -1171,12 +1230,15 @@
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); if (gameMode === 'online') { persist(); startOnline('lobby'); } else showLeague(); };
if ($('bRankG')) $('bRankG').onclick = () => { SFX.click(); showRanking(openGarage); };
if ($('bMissions')) $('bMissions').onclick = () => { SFX.click(); showMissions(openGarage); };
function updateShopBar() {
const on = gameMode === 'online';
$('bGMode').style.display = onlineUsable() ? '' : 'none';
$('bGMode').textContent = on ? '🏆 ' + t('to_campaign') : '🌍 ' + t('to_online');
$('bLeague').textContent = on ? t('to_lobby') : t('to_league');
const rg = $('bRankG'); if (rg) rg.style.display = (on && rank.enabled) ? '' : 'none'; // ranking is online-only
const mb = $('bMissions'); // missions are campaign-only
if (mb) { ensureMissions(); mb.style.display = on ? 'none' : ''; mb.classList.toggle('alert', !on && RC.Missions.active(save).some(m => m.done)); }
}
function applyClass(id) {
@@ -1340,6 +1402,7 @@
}
}
view.showArena(s, [save.build, 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;
$('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build);
@@ -1348,7 +1411,6 @@
setScreen('fight');
audio.music('music_fight');
gateOpen();
banner('📍 ' + t('arena_' + s.arena.id), '#ff7a1a', 2.2);
if (save.games === 0 && !F.online) setTimeout(() => { if (mode === 'fight') banner(t('tut_controls'), '#ffffff', 5); }, 2400);
const pg = $('padGadget'); if (pg) pg.style.display = s.robots[0].st.gadget ? '' : 'none';
buildCds();
@@ -1554,7 +1616,7 @@
}
}
const own = s.robots[0].hp / s.robots[0].maxHp;
$('dmgvig').style.opacity = own < 0.3 && !s.robots[0].out ? ((0.3 - own) / 0.3 * 0.6).toFixed(2) : 0;
$('dmgvig').style.opacity = own < 0.3 && !s.robots[0].out ? ((0.3 - own) / 0.3 * (settings.comfort ? 0.32 : 0.6)).toFixed(2) : 0;
const cds = RC.Combat.cooldowns(s.robots[0]), chips = $('fCds').children;
for (let i = 0; i < chips.length && i < cds.length; i++) {
const ch = chips[i], c = cds[i];
@@ -1592,6 +1654,31 @@
`<div class="achwon"><b>🏅 ${t('ach_new')}</b>` + got.map(a =>
`<div><span>${t('ach_' + a.id)}</span><span class="plus">+${Kit.fmt(a.reward)}</span></div>`).join('') + '</div>');
// campaign missions: roll/reset for the current day/week
function ensureMissions() { return (save && gameMode === 'campaign') ? RC.Missions.ensure(save, Date.now(), save.mseed || 1) : null; }
// advance missions from a finished campaign fight, auto-pay credits/fame + unlock paints
function updateMissions(base) {
if (!save || gameMode !== 'campaign' || (F && F.training)) return [];
ensureMissions();
const ctx = Object.assign({}, base);
if (F && F.s && F.s.arena) ctx.arenaId = F.s.arena.id;
const w0 = (save.build.weapons || [])[0];
ctx.weaponType = w0 && RC.PARTS[w0.id] ? RC.PARTS[w0.id].type : null;
const done = [];
for (const m of RC.Missions.active(save)) {
if (RC.Missions.apply(m, ctx)) {
save.money += m.reward | 0; save.fame += m.fame | 0;
if (typeof m.unlock === 'number' && !save.unlockedPaints.includes(m.unlock)) save.unlockedPaints.push(m.unlock);
done.push(m);
}
}
if (done.length) { persist(); SFX.buy && SFX.buy(); }
return done;
}
const missHtml = done => (!done || !done.length ? '' :
`<div class="achwon"><b>🎯 ${t('miss_complete')}</b>` + done.map(m =>
`<div><span>${t('mission_' + m.id)}</span><span class="plus">+${Kit.fmt(m.reward)}${m.fame ? ' ⭐' + m.fame : ''}</span></div>`).join('') + '</div>');
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];
@@ -1634,9 +1721,11 @@
save.money += money; save.fame += fame;
persist();
}
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
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 });
training: F.training, exhibition: F.exhibition, champion };
const gotAch = awardAch(fightCtx);
const gotMiss = updateMissions(fightCtx); // campaign missions: progress + pay
hud();
(won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
@@ -1647,7 +1736,7 @@
card(`<h1>${title}</h1><p>${why}</p>
${champion ? `<h2>${t('champion_title', { s: save.season - 1 })}</h2><p>${t('champion_text')}</p>` : ''}
<div class="res">${stats}${rows}${!F.training && fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
${achHtml(gotAch)}
${achHtml(gotAch)}${missHtml(gotMiss)}
${F.training ? `<p class="muted">${t('training_note')}</p>` : ''}
<div class="row"><button class="primary" id="bGarage">${t('to_garage')}</button>${!F.training && !won ? `<button id="bRetry">${t('retry')}</button>` : ''}</div>${boardHtml()}`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
@@ -1738,7 +1827,7 @@
// cap rendering: ~60 fps during action, ~16 fps when a static menu covers the arena (saves CPU/GPU on
// high-refresh monitors and in menus). update() stays fixed 60 Hz via the loop, so physics is unaffected.
const active = mode === 'fight' || mode === 'pause' || mode === 'intro' || mode === 'garage';
const minGap = active ? 15.5 : 60;
const minGap = active ? 15.5 : (mode === 'title' ? 33 : 60); // title ~30 fps so the background robots animate smoothly
if (lastNow && now - lastNow < minGap) return;
const dt = Math.min(0.05, lastNow ? (now - lastNow) / 1000 : 0.016); lastNow = now;
if (view) view.frame(mode === 'pause' ? 0 : dt, now);
@@ -1869,6 +1958,7 @@
else if (scr === 'help') showHelp(openGarage);
else if (scr === 'tour') { save.money = 3000; startTournament(); }
else if (scr === 'ach') { save.fame = 1200; save.ach = { first_win: true, ko: true, rich: true }; showAchievements(openGarage); }
else if (scr === 'missions') { if (gameMode !== 'campaign') switchMode('campaign'); if (DEV.has('mreset')) save.missions = null; showMissions(openGarage); }
else if (scr === 'lobby') {
lobbyRows = [{ uid: 'a', name: 'BlechBrecher', flag: 'DE', fame: 1250, state: 'idle' }, { uid: 'b', name: 'SawQueen', flag: 'DE', fame: 430, state: 'inmatch' }, { uid: 'c', name: 'Rostlaube77', flag: 'AT', fame: 90, state: 'idle' }, { uid: 'd', name: 'Flipmaster', flag: 'GB', fame: 600, state: 'idle' }];
lobbyRoom = DEV.get('room') || null;