From 347701d66fbbe33eb75a9e6dfa4afdee768eb663 Mon Sep 17 00:00:00 2001 From: Michi Date: Thu, 19 Nov 2026 00:55:39 +0100 Subject: [PATCH] onlinemodus fix failed --- game/game.js | 136 ++++++++++++++++++++++++++++++++++++++-------- game/index.html | 43 +++++++++++++-- game/lang.js | 38 +++++++++++++ game/lobby.js | 2 +- game/missions.js | 96 ++++++++++++++++++++++++++++++++ game/render3d.js | 86 ++++++++++++++++++++++------- game/shop.js | 6 +- server/app.js | 9 ++- server/db.js | 15 ++++- tests/sim.test.js | 36 +++++++++++- 10 files changed, 414 insertions(+), 53 deletions(-) create mode 100644 game/missions.js diff --git a/game/game.js b/game/game.js index 1576a68..9b5ae20 100644 --- a/game/game.js +++ b/game/game.js @@ -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 => ``; - 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 @@ + `

${t('paint_body')}

` + `

${t('paint_accent')}

` + `

${t('paint_schemes')}

`; + const lockP = c => (RC.PAINT_REWARDS || []).includes(c) && !(save.unlockedPaints || []).includes(c); // reward colour, not earned yet for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) { - $(id).innerHTML = RC.PAINTS.map(c => ``).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 => `${lockP(c) ? '🔒' : ''}`).join(''); + $(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { if (sw.classList.contains('locked')) { SFX.deny && SFX.deny(); return; } save.paint[key] = +sw.dataset.c; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); } $('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = save.paint.body === b2 && save.paint.accent === a2; return ``; }).join(''); $('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint.body = +sw.dataset.b; save.paint.accent = +sw.dataset.a; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); @@ -544,7 +548,7 @@
${btns}
- ${save ? `` : ''}${rank.enabled ? `` : ''}
+ ${save ? `` : ''}${rank.enabled ? `` : ''}

${CREDITS}

${rank.enabled ? `

🏆 ${t('ranking')} ● ${t('rank_live')}

  1. ${t('loading')}
` : ''}`; 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(`

${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($('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 => ``).join(''); - const room = (f, label, flag) => ``; + 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 list = here.map(r => prow(r, false)).join(''); @@ -663,7 +673,11 @@ `; 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 @@
+

${t('local_note')}

`, { 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'), ``)} ${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))} ${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))} + ${item(t('s_comfort'), seg('sComfort', settings.comfort ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} ${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))} ${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} ${item(t('s_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))} ${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))} ${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))} - ${isDev ? `
🛠 Dev · Coins
+ ${isDev && save ? `
🛠 Dev · Coins
` : ''}
${t('s_account')} ${who ? '👤 ' + esc(who.name) + '' + (who.email ? ' ' + esc(who.email) + '' : '') : '👤 ' + t('guest')} ${save ? `` : ''}
- ${save ? `` : ''}
`, { wide: true, clear: prev === 'title' || prev === 'intro' }); + ${save ? `` : ''}
`, { wide: true, clear: prev === 'title' || prev === 'intro' }); const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; }); segOn('sLang', v => { L.set(v); showSettings(back); }); segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); }); segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); }); segOn('sSteer', v => { settings.steer = v; saveSettings(); }); segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); }); + segOn('sComfort', v => { settings.comfort = v === '1'; saveSettings(); if (view && view.setComfort) view.setComfort(settings.comfort); }); segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); }); segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); }); segOn('sArena', v => { settings.arena = v; saveSettings(); }); @@ -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 `
${m.done ? '✅' : '🎯'} +
${t('mission_' + m.id)}
${t('missd_' + m.id)}
+
+
${rew}${prog}/${m.goal}
`; + }; + card(`

🎯 ${t('missions')}

+

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

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

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

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

${t('how_to')}

${t('help_text')}

${keysHtml()}

${t('help_arena')}

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

${t('legal')}

${seg}
+
${t(which + '_text')}
+
`, { wide: true, bg: 'bg_title.jpg' }); + overlay.querySelectorAll('.legalseg button').forEach(b => b.onclick = () => { SFX.click(); showLegal(back, b.dataset.l); }); + $('bOk').onclick = () => { SFX.click(); back(); }; + } let rankSub = null, titleRankSub = null, boardFame = {}, boardIdx = {}; const closeRank = () => { if (rankSub) { rankSub.close(); rankSub = null; } }; function showRanking(back) { @@ -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 @@ `
🏅 ${t('ach_new')}` + got.map(a => `
${t('ach_' + a.id)}+${Kit.fmt(a.reward)}
`).join('') + '
'); + // 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 ? '' : + `
🎯 ${t('miss_complete')}` + done.map(m => + `
${t('mission_' + m.id)}+${Kit.fmt(m.reward)}${m.fame ? ' ⭐' + m.fame : ''}
`).join('') + '
'); + 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(`

${title}

${why}

${champion ? `

${t('champion_title', { s: save.season - 1 })}

${t('champion_text')}

` : ''}
${stats}${rows}${!F.training && fame ? `${t('hud_fame')}+${Kit.fmt(fame)}` : ''}
- ${achHtml(gotAch)} + ${achHtml(gotAch)}${missHtml(gotMiss)} ${F.training ? `

${t('training_note')}

` : ''}
${!F.training && !won ? `` : ''}
${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; diff --git a/game/index.html b/game/index.html index 786c040..16bfd2e 100644 --- a/game/index.html +++ b/game/index.html @@ -84,8 +84,8 @@ input:focus { outline: none; border-color: var(--accent); } /* menus fade in once per screen (#overlay.enter is removed again, so live lists do not flicker) */ - @keyframes cardIn { from { opacity: 0; transform: scale(.96); } to { opacity: 1; transform: none; } } - #overlay.enter > * { animation: cardIn .14s ease-out; } + @keyframes cardIn { from { opacity: 0; transform: translateY(10px) scale(.975); } to { opacity: 1; transform: none; } } + #overlay.enter > * { animation: cardIn .2s cubic-bezier(.2,.7,.2,1) both; will-change: transform, opacity; } .tab, .item, .fitted .frow, .rroom, .prow { transition: border-color .1s, background-color .1s, transform .1s; } @media (hover: hover) { .item:hover { transform: translateY(-2px); } } @media (prefers-reduced-motion: reduce) { @@ -150,10 +150,17 @@ background: linear-gradient(90deg, rgba(4,5,8,.93) 0%, rgba(4,5,8,.8) 30%, rgba(4,5,8,0) 62%); } .tpanel { width: 420px; padding: 0 20px 0 44px; display: flex; flex-direction: column; gap: 10px; text-align: left; } .tlogoimg { width: 100%; max-height: 170px; object-fit: contain; object-position: left center; - filter: drop-shadow(0 6px 18px #000); animation: logoglow 3.6s ease-in-out infinite; } - @keyframes logoglow { 50% { filter: drop-shadow(0 6px 18px #000) drop-shadow(0 0 14px rgba(255,122,26,.45)); } } + transform-origin: left center; will-change: transform, filter; + filter: drop-shadow(0 6px 18px #000); animation: logoglow 3.6s ease-in-out infinite, logofloat 5s ease-in-out infinite, logoin .7s cubic-bezier(.2,1.3,.3,1) both; } + @keyframes logoglow { 50% { filter: drop-shadow(0 6px 18px #000) drop-shadow(0 0 16px rgba(255,122,26,.55)); } } + /* gentle idle motion: slow bob + slight tilt + breath (small amplitude, comfort-safe) */ + @keyframes logofloat { 0%, 100% { transform: translateY(0) rotate(-0.6deg) scale(1); } 50% { transform: translateY(-7px) rotate(0.6deg) scale(1.02); } } + @keyframes logoin { 0% { opacity: 0; transform: translateY(18px) scale(.86); } 100% { opacity: 1; transform: translateY(0) scale(1); } } .title .big { font: 62px var(--head); letter-spacing: .05em; color: var(--accent); line-height: .98; - text-shadow: 0 5px 0 #5a2600, 0 0 40px rgba(255,122,26,.5); } + transform-origin: left center; will-change: transform; + text-shadow: 0 5px 0 #5a2600, 0 0 40px rgba(255,122,26,.5); + animation: logofloat 5s ease-in-out infinite, bigglow 3.6s ease-in-out infinite, logoin .7s cubic-bezier(.2,1.3,.3,1) both; } + @keyframes bigglow { 50% { text-shadow: 0 5px 0 #5a2600, 0 0 64px rgba(255,122,26,.85); } } .title .tag { color: #c9cfdc; margin: 0; text-shadow: 0 2px 4px #000; } .hazbar { height: 5px; border-radius: 3px; background: var(--hazard); opacity: .9; } .tmenu { display: flex; flex-direction: column; gap: 8px; margin-top: 4px; } @@ -422,6 +429,28 @@ .achrow .an { font-weight: 700; } .achrow .ad { font-size: 11.5px; color: var(--dim); font-weight: 400; } .achrow .am { font-size: 16px; text-align: center; } + /* missions page */ + .misslist { display: flex; flex-direction: column; gap: 6px; margin: 4px 0 12px; text-align: left; } + .missrow { display: grid; grid-template-columns: 24px 1fr auto; gap: 10px; align-items: center; background: var(--panel2); + border: 1px solid var(--line); border-radius: 10px; padding: 7px 10px; } + .missrow.done { border-color: var(--good); } + .missrow .mm { font-size: 18px; text-align: center; } + .missrow .mn { font-weight: 700; font-size: 13px; } + .missrow .md { font-size: 11.5px; color: var(--dim); margin: 1px 0 4px; } + .missrow .mi .bar { height: 7px; } + .missrow .mr { text-align: right; display: flex; flex-direction: column; gap: 2px; font-size: 12px; white-space: nowrap; } + .missrow .mp { font-variant-numeric: tabular-nums; color: var(--dim); font-size: 11px; } + #bMissions { position: relative; } + #bMissions.alert::after { content: ''; position: absolute; top: 3px; right: 5px; width: 7px; height: 7px; border-radius: 50%; + background: var(--accent); box-shadow: 0 0 6px var(--accent); } + /* legal pages (Impressum / Datenschutz) */ + .legalseg { margin: 6px auto 10px; max-width: 360px; } + .legaltext { max-height: 48vh; overflow: auto; text-align: left; font-size: 13px; line-height: 1.5; color: var(--text); + background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 10px 14px; } + .legaltext p { margin: 0 0 9px; color: inherit; } + .legaltext b { color: var(--accent); } + .pgrid .sw.locked { cursor: not-allowed; opacity: .55; } + .pgrid .sw .lk { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 10px; text-shadow: 0 1px 2px #000; } /* paint tab: compact colour chips (must fit without scrolling) */ #shop.paintmode #tabs, #shop.paintmode #detail, #shop.paintmode #fittedwrap { display: none !important; } @@ -508,6 +537,8 @@ .rroom .cnt.live { color: var(--good); font-weight: 700; } .rroom.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; } .rroom.on .cnt { color: #1a0c02; } + .rroom.joined:not(.on) { border-color: var(--accent); } + .rroom .rhere { font-size: 10px; } .lobbyRh { display: flex; align-items: center; gap: 8px; font: 18px var(--head); letter-spacing: .03em; margin-bottom: 8px; } .lobbyRh .grow { flex: 1; } .lobbyRh .flagpick { font: 12px "Segoe UI", sans-serif; color: var(--dim); display: flex; gap: 6px; align-items: center; } @@ -728,6 +759,7 @@ +
@@ -791,6 +823,7 @@ + diff --git a/game/lang.js b/game/lang.js index 6743f3d..d4356fd 100644 --- a/game/lang.js +++ b/game/lang.js @@ -177,6 +177,25 @@ window.LANG = { e_unknown: 'No account with this name.', e_wrong_pass: 'Wrong password.', // settings s_lang: 'Language', s_country: 'Country', s_music: 'Music', s_sfx: 'Effects', s_mute: 'Sound', s_gfx: 'Graphics', s_intro: 'Intro at start', + s_comfort: 'Comfort (less motion)', + missions: 'Missions', miss_daily: 'Daily', miss_weekly: 'Weekly', miss_reset_in: 'resets in {n}h', miss_complete: 'Mission complete!', paint_locked: 'Locked - earn it from a mission', + mission_d_win3: 'Win streak', missd_d_win3: 'Win 3 fights', + mission_d_play5: 'Warm-up', missd_d_play5: 'Fight 5 battles', + mission_d_dmg800: 'Heavy hitter', missd_d_dmg800: 'Deal 800 damage', + mission_d_ko2: 'Double K.O.', missd_d_ko2: 'K.O. 2 opponents', + mission_d_pit1: 'Into the pit', missd_d_pit1: 'Win 1 fight by pit', + mission_d_flaw1: 'Untouched', missd_d_flaw1: 'Win keeping every part (>=90% HP)', + mission_d_foundry: 'Foundry duel', missd_d_foundry: 'Win in the Foundry', + mission_d_colosseum: 'Colosseum', missd_d_colosseum: 'Win in the Colosseum', + mission_d_spin: 'Spin to win', missd_d_spin: 'Win with a spinner weapon', + mission_d_hammer: 'Hammer time', missd_d_hammer: 'Win with a hammer/axe', + mission_w_win15: 'Veteran week', missd_w_win15: 'Win 15 fights', + mission_w_dmg6000: 'Demolition week', missd_w_dmg6000: 'Deal 6000 damage', + mission_w_ko8: 'Knockout artist', missd_w_ko8: 'K.O. 8 opponents', + mission_w_flaw3: 'Flawless run', missd_w_flaw3: 'Win 3 flawless fights', + legal: 'Legal', legal_impressum: 'Imprint', legal_privacy: 'Privacy', consent_pre: 'I accept the', consent_required: 'Please accept the privacy policy.', + impressum_text: '

Information pursuant to § 5 DDG (German law)

[Name / provider]
[Address – e.g. c/o imprint service]
[Postcode, City]

Contact
Email: [contact@your-domain]

Note: fill in your real data. A deliverable address suffices (e.g. via an imprint / c-o service) — a private home address is not required.

', + privacy_text: '

Privacy policy

Controller: [Name], [contact email].

What data? On registration: your email and an encrypted password hash; while playing: your save data, chosen country flag and — online — your lobby presence (name, status). The server keeps access data (IP address, time) in log files for technical reasons.

Why? To run your account, store progress, the online lobby/ranking and to secure the server (Art. 6(1)(b) and (f) GDPR).

Hosting: The server is hosted at Hetzner in Germany under a data-processing agreement.

Storage: Account/save until you delete it; server logs only briefly.

Cookies/tracking: Only technically necessary storage (localStorage, login token) — no tracking, no ads, no sharing with third parties.

Your rights: access, rectification, erasure, objection and complaint to a supervisory authority. Contact: [contact email].

Template — please have it reviewed (lawyer / generator) and add your own data.

', country_title: 'Choose your country', country_text: 'Your flag shows on the ranking and in the lobby. You can change it later in the settings.', country_go: 'Let\'s go', s_screen: 'Display', s_controls: 'Controls', s_career: 'Career', on: 'On', off: 'Off', gfx_low: 'Low', gfx_medium: 'Medium', gfx_high: 'High', @@ -432,6 +451,25 @@ window.LANG = { e_unknown: 'Kein Konto mit diesem Namen.', e_wrong_pass: 'Falsches Passwort.', // settings s_lang: 'Sprache', s_country: 'Land', s_music: 'Musik', s_sfx: 'Effekte', s_mute: 'Ton', s_gfx: 'Grafik', s_intro: 'Intro beim Start', + s_comfort: 'Komfort (weniger Bewegung)', + missions: 'Missionen', miss_daily: 'Täglich', miss_weekly: 'Wöchentlich', miss_reset_in: 'neu in {n} h', miss_complete: 'Mission geschafft!', paint_locked: 'Gesperrt – über eine Mission freischalten', + mission_d_win3: 'Siegesserie', missd_d_win3: 'Gewinne 3 Kämpfe', + mission_d_play5: 'Aufwärmen', missd_d_play5: 'Bestreite 5 Kämpfe', + mission_d_dmg800: 'Draufhauer', missd_d_dmg800: 'Mach 800 Schaden', + mission_d_ko2: 'Doppel-K.o.', missd_d_ko2: 'Schlage 2 Gegner K.o.', + mission_d_pit1: 'Ab in die Grube', missd_d_pit1: 'Gewinne 1 Kampf per Grube', + mission_d_flaw1: 'Unberührt', missd_d_flaw1: 'Sieg ohne Teileverlust (≥90% LP)', + mission_d_foundry: 'Gießerei-Duell', missd_d_foundry: 'Gewinne in der Gießerei', + mission_d_colosseum: 'Kolosseum', missd_d_colosseum: 'Gewinne im Kolosseum', + mission_d_spin: 'Dreh dich', missd_d_spin: 'Sieg mit einer Spinner-Waffe', + mission_d_hammer: 'Hammerzeit', missd_d_hammer: 'Sieg mit Hammer/Axt', + mission_w_win15: 'Veteranenwoche', missd_w_win15: 'Gewinne 15 Kämpfe', + mission_w_dmg6000: 'Abrisswoche', missd_w_dmg6000: 'Mach 6000 Schaden', + mission_w_ko8: 'K.o.-Künstler', missd_w_ko8: 'Schlage 8 Gegner K.o.', + mission_w_flaw3: 'Makellos', missd_w_flaw3: 'Gewinne 3 makellose Kämpfe', + legal: 'Rechtliches', legal_impressum: 'Impressum', legal_privacy: 'Datenschutz', consent_pre: 'Ich akzeptiere die', consent_required: 'Bitte die Datenschutzerklärung akzeptieren.', + impressum_text: '

Angaben gemäß § 5 DDG

[Name / Anbieter]
[Anschrift – z. B. c/o Impressums-Dienst]
[PLZ Ort]

Kontakt
E-Mail: [kontakt@deine-domain]

Hinweis: Bitte echte Daten eintragen. Es genügt eine ladungsfähige Anschrift (z. B. über einen Impressums-/c-o-Dienst) – keine Privatadresse nötig.

', + privacy_text: '

Datenschutzerklärung

Verantwortlich: [Name], [Kontakt-E-Mail].

Welche Daten? Bei der Registrierung deine E-Mail-Adresse und ein verschlüsselter Passwort-Hash; beim Spielen dein Spielstand, die gewählte Länderflagge und – online – deine Lobby-Präsenz (Name, Status). Der Server speichert technisch bedingt Zugriffsdaten (IP-Adresse, Zeitpunkt) in Logdateien.

Wozu? Zum Betrieb des Kontos, Speichern des Fortschritts, der Online-Lobby/Rangliste und zur Absicherung des Servers (Art. 6 Abs. 1 b und f DSGVO).

Hosting: Der Server steht bei Hetzner in Deutschland; es besteht ein Auftragsverarbeitungsvertrag.

Speicherung: Konto/Spielstand bis zur Löschung durch dich; Server-Logs nur kurzzeitig.

Cookies/Tracking: Es werden nur technisch notwendige Speicher (localStorage, Login-Token) genutzt – kein Tracking, keine Werbung, keine Weitergabe an Dritte.

Deine Rechte: Auskunft, Berichtigung, Löschung, Widerspruch und Beschwerde bei einer Aufsichtsbehörde. Kontakt: [Kontakt-E-Mail].

Vorlage – bitte anwaltlich/über einen Generator prüfen und eigene Daten eintragen.

', country_title: 'Wähle dein Land', country_text: 'Deine Flagge erscheint in der Rangliste und in der Lobby. Du kannst sie später in den Einstellungen ändern.', country_go: 'Los geht\'s', s_screen: 'Anzeige', s_controls: 'Steuerung', s_career: 'Karriere', on: 'An', off: 'Aus', gfx_low: 'Niedrig', gfx_medium: 'Mittel', gfx_high: 'Hoch', diff --git a/game/lobby.js b/game/lobby.js index 9bc704a..b124118 100644 --- a/game/lobby.js +++ b/game/lobby.js @@ -36,7 +36,7 @@ async function beat(state) { const p = prof(); - await db.put(`lobby/${me()}`, { name: p.name, flag: p.flag || 'XX', fame: p.fame | 0, ver: 2, state: state || 'idle', ts: { '.sv': 'timestamp' } }); + 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() { diff --git a/game/missions.js b/game/missions.js new file mode 100644 index 0000000..1c3d41d --- /dev/null +++ b/game/missions.js @@ -0,0 +1,96 @@ +/* Robot Clash - campaign missions (no DOM, runs in Node for the tests). Needs parts.js. + Rotating objectives: 3 daily + 1 weekly, stored in the save (per mode, so campaign keeps its own). + Reward = credits + fame, some weekly ones unlock a special paint / scheme. + + RC.Missions.ensure(save, now, baseSeed) -> rolls/resets save.missions when the day/week changed + RC.Missions.apply(m, ctx) -> advance one mission from a fight ctx, true if newly done + RC.Missions.active(save) -> [ ...daily, weekly ] for UI / iteration + ctx (same as awardAch): { won, reason, hpPct, lost, dealt, arenaId, weaponType } + Texts: lang.js keys 'mission_' (name) and 'missd_' (what to do). */ +(function (root) { + 'use strict'; + const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {})); + + const DAY = 86400000, WEEK = 7 * DAY; + const dayIndex = now => Math.floor((now || 0) / DAY); + const weekIndex = now => Math.floor((now || 0) / WEEK); + + // deterministic RNG (mulberry32) so a given seed always rolls the same set + function rng(seed) { + let a = (seed >>> 0) || 1; + return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; + } + const mix = (a, b) => (Math.imul((a >>> 0) ^ 0x9e3779b9, 0x85ebca6b) ^ ((b >>> 0) + 0x165667b1)) >>> 0; + + // daily pool (small goals). type decides how a fight advances it. + const DAILY = [ + { id: 'd_win3', type: 'win', goal: 3, reward: 180, fame: 30 }, + { id: 'd_play5', type: 'play', goal: 5, reward: 120, fame: 15 }, + { id: 'd_dmg800', type: 'damage', goal: 800, reward: 160, fame: 20 }, + { id: 'd_ko2', type: 'ko', goal: 2, reward: 200, fame: 30 }, + { id: 'd_pit1', type: 'pit', goal: 1, reward: 180, fame: 30 }, + { id: 'd_flaw1', type: 'flawless', goal: 1, reward: 220, fame: 40 }, + { id: 'd_foundry', type: 'arena:foundry', goal: 1, reward: 200, fame: 30 }, + { id: 'd_colosseum', type: 'arena:colosseum', goal: 1, reward: 220, fame: 35 }, + { id: 'd_spin', type: 'weapon:spinner', goal: 1, reward: 200, fame: 30 }, + { id: 'd_hammer', type: 'weapon:hammer', goal: 1, reward: 200, fame: 30 }, + ]; + // weekly pool (bigger goals, often an unlock). unlock: paint hex or 'scheme:' + const WEEKLY = [ + { id: 'w_win15', type: 'win', goal: 15, reward: 700, fame: 120, unlock: 0x39ff14 }, + { id: 'w_dmg6000', type: 'damage', goal: 6000, reward: 600, fame: 100, unlock: 0xc0c0c0 }, + { id: 'w_ko8', type: 'ko', goal: 8, reward: 800, fame: 140, unlock: 0xff1e8e }, + { id: 'w_flaw3', type: 'flawless', goal: 3, reward: 900, fame: 160, unlock: 0x7b2fff }, + ]; + + const inst = o => ({ id: o.id, type: o.type, goal: o.goal, reward: o.reward, fame: o.fame, unlock: o.unlock || null, prog: 0, done: false }); + + // pick n distinct objectives from a pool, deterministically from seed + function pick(pool, seed, n) { + const r = rng(seed), idx = pool.map((_, i) => i); + for (let i = idx.length - 1; i > 0; i--) { const j = (r() * (i + 1)) | 0; const t = idx[i]; idx[i] = idx[j]; idx[j] = t; } + return idx.slice(0, Math.min(n, pool.length)).map(i => inst(pool[i])); + } + const daily = (seed, n = 3) => pick(DAILY, seed, n); + const weekly = (seed, n = 1) => pick(WEEKLY, seed, n); + + // roll or reset the mission set when the calendar day / week rolled over + function ensure(save, now, baseSeed) { + const d = dayIndex(now), w = weekIndex(now), base = (baseSeed >>> 0) || 1; + let m = save.missions; + if (!m || m.day !== d) m = Object.assign(m || {}, { day: d, daily: daily(mix(base, d)) }); + if (m.week !== w) { m.week = w; m.weekly = weekly(mix(base, 1000003 + w)); } + save.missions = m; + return m; + } + + // how much a single fight advances a mission of this type + function gain(type, ctx) { + const c = ctx || {}; + if (type === 'play') return 1; + if (type === 'damage') return Math.max(0, Math.round(c.dealt || 0)); + if (!c.won) return 0; // the rest only count on a win + if (type === 'win') return 1; + if (type === 'ko') return c.reason === 'ko' ? 1 : 0; + if (type === 'pit') return c.reason === 'pit' ? 1 : 0; + if (type === 'flawless') return (c.lost === 0 && (c.hpPct || 0) >= 0.9) ? 1 : 0; + if (type.startsWith('arena:')) return c.arenaId === type.slice(6) ? 1 : 0; + if (type.startsWith('weapon:')) return c.weaponType === type.slice(7) ? 1 : 0; + return 0; + } + + // advance one mission; returns true the moment it is newly completed + function apply(m, ctx) { + if (!m || m.done) return false; + const add = gain(m.type, ctx); + if (add <= 0) return false; + m.prog = Math.min(m.goal, (m.prog || 0) + add); + if (m.prog >= m.goal) { m.done = true; return true; } + return false; + } + + const active = save => (save && save.missions) ? [].concat(save.missions.daily || [], save.missions.weekly || []) : []; + + RC.Missions = { DAILY, WEEKLY, dayIndex, weekIndex, daily, weekly, ensure, apply, gain, active }; + if (typeof module !== 'undefined' && module.exports) module.exports = RC; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/render3d.js b/game/render3d.js index 1a7520c..02a2c78 100644 --- a/game/render3d.js +++ b/game/render3d.js @@ -163,6 +163,18 @@ // ---------------------------------------------------------------- robot model const M = {}; + const sharedMat = new Set(); // the cached palette materials must never be disposed + // free a replaced robot's GPU resources (unique per build) so browsing parts / many fights does not leak + function disposeRobot(R) { + if (!R || !R.root) return; + const gs = new Set(), ms = new Set(); + R.root.traverse(o => { + if (o.geometry && !gs.has(o.geometry)) { gs.add(o.geometry); o.geometry.dispose(); } + if (o.material) for (const m of [].concat(o.material)) { + if (m && !sharedMat.has(m) && !ms.has(m)) { ms.add(m); if (m.map && m.map.isTexture) m.map.dispose(); m.dispose(); } + } + }); + } function mats() { if (M.dark) return M; M.dark = new T.MeshStandardMaterial({ color: 0x2a2d33, metalness: 0.6, roughness: 0.5 }); @@ -179,6 +191,7 @@ M.track = new T.MeshStandardMaterial({ map: M.trackTex, roughness: 0.85, metalness: 0.2 }); M.wsteel = new T.MeshStandardMaterial({ color: 0xd2d7de, metalness: 0.95, roughness: 0.22 }); // bright weapon steel M.wedge = new T.MeshStandardMaterial({ color: 0x9aa0a8, metalness: 0.85, roughness: 0.35 }); + for (const k in M) if (M[k] && M[k].isMaterial) sharedMat.add(M[k]); // protect the shared palette from disposal return M; } // shop: the robot is framed in the left column, not in the middle of the stage @@ -641,6 +654,8 @@ } mark('gadget'); root.traverse(o => { if (o.isMesh && !o.material.transparent) { o.castShadow = true; } }); + // full height (incl. tower/antenna) so a flipped robot rests on its roof, never clips through the floor + const bb = new T.Box3().setFromObject(tilt); out.topY = Math.max(0.3, bb.max.y); return out; } @@ -655,7 +670,7 @@ if (r.y <= 0.05 && Math.abs(R.roll - want) < 0.02) R.roll = want; R.roll %= Math.PI * 2; R.tilt.rotation.x = R.roll; - const h = R.c + R.st.h; + const h = R.topY || (R.c + R.st.h); // lift by the real top so nothing sinks under the floor when flipped R.tilt.position.y = (1 - Math.cos(R.roll)) / 2 * h; const sp = Math.hypot(r.vx, r.vz) * (Math.cos(r.a) * r.vx + Math.sin(r.a) * r.vz >= 0 ? 1 : -1); for (const wl of R.wheels) wl.rotation.z -= sp * dt / (R.wheelR || 0.16); @@ -1066,7 +1081,7 @@ // intro / title: perspective camera flying over the arena const pcam = new T.PerspectiveCamera(40, asp, 0.1, 120); - let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0, introT = 0, scale = 1, hold = 0, editSel = 0, introLightK = 0, comfort = true; + let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0, introT = 0, scale = 1, hold = 0, editSel = 0, introLightK = 0, comfort = true, titleT = 0, garageSig = null; let quality = 'high', fxMul = 1, camMode = 'iso', chaseInit = false, gcamZoom = GZ_DEF; placeGarageCam(); // after gcamZoom exists: start fully zoomed out // workshop: show what the fitted weapon / turret actually does, on a short loop @@ -1133,7 +1148,10 @@ skipIntro() { if (mode === 'intro' && introT < INTRO_END) introT = INTRO_END; }, showGarage(build, paint) { mode = 'garage'; - if (gRobot) garage.turntable.remove(gRobot.root); + const sig = JSON.stringify(build); + if (gRobot && sig === garageSig) { gRobot.skin.redraw(paint); return; } // same robot -> just repaint, no rebuild (smoother) + garageSig = sig; + if (gRobot) { garage.turntable.remove(gRobot.root); disposeRobot(gRobot); } gRobot = buildRobot(build, paint); gRobot.root.position.y = 0.12; garage.turntable.add(gRobot.root); @@ -1211,7 +1229,7 @@ showArena(s, builds, paints) { api.setArena(s.arena); mode = 'arena'; state = s; pointMode(camMode !== 'iso'); lightsOn(1); chaseInit = false; - for (const R of robots) arenaScene.remove(R.root); + for (const R of robots) { arenaScene.remove(R.root); disposeRobot(R); } robots = builds.map((b, i) => { const R = buildRobot(b, paints[i]); arenaScene.add(R.root); return R; }); sparks.clear(); smoke.clear(); fire.clear(); clearDebris(); shake = 0; for (const m of arena.rocketMeshes) arenaScene.remove(m); @@ -1259,7 +1277,7 @@ // comfort mode: smoother cockpit follow, narrower fov, weaker shake (reduces motion sickness) setComfort(on) { comfort = !!on; pcam.fov = camMode === 'fpv' ? (comfort ? 62 : 70) : 55; pcam.updateProjectionMatrix(); }, project(x, y, z) { - const v = new T.Vector3(x, y, z).project(mode === 'arena' && camMode !== 'iso' ? pcam : cam); + const v = _pv.set(x, y, z).project(mode === 'arena' && camMode !== 'iso' ? pcam : cam); // reuse one vector (no per-call GC) // behind the camera (chase / cockpit): off screen if (v.z > 1) return { x: -999, y: -999 }; return { x: (v.x + 1) / 2 * W, y: (1 - v.y) / 2 * H }; @@ -1279,6 +1297,7 @@ renderer.render(arenaScene, pcam); return; } + if (mode === 'title') titleIdle(dt); // gently animate the two robots behind the title menu animateArena(dt, now); sparks.update(dt, 9, 1.2); smoke.update(dt, -0.6, 1.4); fire.update(dt, -2.5, 2); shake = Math.max(0, shake - dt * 1.2); @@ -1298,7 +1317,7 @@ }; // chase: smooth camera behind and above robot 0 · fpv: eyes at the front edge of its top - const cpos = new T.Vector3(), clook = new T.Vector3(); + const cpos = new T.Vector3(), clook = new T.Vector3(), _ta = new T.Vector3(), _tb = new T.Vector3(), _pv = new T.Vector3(); function followCam(dt, sx, sz) { const r = state.robots[0], R = robots[0], half = (state.arena || RC.ARENA).half; const fx = Math.cos(r.a), fz = Math.sin(r.a); @@ -1310,14 +1329,14 @@ // smooth the eye + aim instead of snapping 1:1 to the robot's yaw/bounce -> the main motion-sickness fix const sm = chaseInit ? Math.min(1, dt * (comfort ? 9 : 16)) : 1; chaseInit = true; - cpos.lerp(new T.Vector3(px + sx * 0.3, py, pz + sz * 0.3), sm); - clook.lerp(new T.Vector3(lx, ly, lz), sm); + cpos.lerp(_ta.set(px + sx * 0.3, py, pz + sz * 0.3), sm); + clook.lerp(_tb.set(lx, ly, lz), sm); } else { px = Kit.clamp(r.x - fx * 3.6, -half - 1.2, half + 1.2); pz = Kit.clamp(r.z - fz * 3.6, -half - 1.2, half + 1.2); py = 2.2 + r.y * 0.5; lx = r.x + fx * 1.6; lz = r.z + fz * 1.6; ly = 0.3 + r.y * 0.5; const k = chaseInit ? Math.min(1, dt * 5) : 1; chaseInit = true; - cpos.lerp(new T.Vector3(px + sx, py, pz + sz), k); clook.lerp(new T.Vector3(lx, ly, lz), k); + cpos.lerp(_ta.set(px + sx, py, pz + sz), k); clook.lerp(_tb.set(lx, ly, lz), k); } pcam.position.copy(cpos); pcam.lookAt(clook); } @@ -1366,6 +1385,19 @@ }); } + // title screen: keep the two intro robots alive — spinners turning, turrets swaying, a soft hover bob + function titleIdle(dt) { + const s = state; if (!s || !s.robots) return; + titleT += dt; + s.robots.forEach((rb, i) => { + rb.lifted = 1; // no tumbling physics + rb.spin = 1; rb.sawOn = false; + rb.turretA = rb.a + Math.sin(titleT * 0.55 + i * 2.1) * 0.35; + rb.y = 0.02 + Math.sin(titleT * 1.0 + i * 1.7) * 0.025; // gentle hover + rb.flameOn = Math.sin(titleT * 0.8 + i * 2) > 0.985; // rare flame flick + }); + } + function burst(x, y, z, n, sp, c) { n = Math.max(1, Math.round(n * fxMul)); for (let k = 0; k < n; k++) { @@ -1390,21 +1422,37 @@ obj.getWorldPosition(wp); obj.getWorldQuaternion(wq); arenaScene.add(obj); obj.position.copy(wp); obj.quaternion.copy(wq); - debris.push({ o: obj, vx: (Math.random() - 0.5) * 3.5, vy: 2.2 + Math.random() * 1.8, vz: (Math.random() - 0.5) * 3.5, - rx: (Math.random() - 0.5) * 9, rz: (Math.random() - 0.5) * 9, t: 9 }); - while (debris.length > 10) { const d = debris.shift(); arenaScene.remove(d.o); } + const bb = new T.Box3().setFromObject(obj); + const half = Math.max(0.05, (bb.max.y - bb.min.y) / 2); // rest height so the piece sits ON the floor, not through it + debris.push({ o: obj, half, vx: (Math.random() - 0.5) * 3.5, vy: 2.2 + Math.random() * 1.8, vz: (Math.random() - 0.5) * 3.5, + rx: (Math.random() - 0.5) * 9, rz: (Math.random() - 0.5) * 9, settle: 0 }); + while (debris.length > 12) { freeDebris(debris.shift()); } // keep the last few lying around } function updateDebris(dt) { + const ah = (state && state.arena ? state.arena.half : (RC.ARENA ? RC.ARENA.half : 10)); for (let i = debris.length - 1; i >= 0; i--) { - const d = debris[i]; - d.t -= dt; d.vy -= 22 * dt; - d.o.position.x += d.vx * dt; d.o.position.y += d.vy * dt; d.o.position.z += d.vz * dt; - if (d.o.position.y < 0.07) { d.o.position.y = 0.07; d.vy = -d.vy * 0.3; d.vx *= 0.6; d.vz *= 0.6; d.rx *= 0.5; d.rz *= 0.5; } - d.o.rotation.x += d.rx * dt; d.o.rotation.z += d.rz * dt; - if (d.t <= 0) { arenaScene.remove(d.o); debris.splice(i, 1); } + const d = debris[i], o = d.o, rest = d.half; + d.vy -= 22 * dt; + o.position.x += d.vx * dt; o.position.y += d.vy * dt; o.position.z += d.vz * dt; + if (o.position.y <= rest) { // on the ground: bounce a little, then settle flat + o.position.y = rest; + if (d.vy < 0) d.vy = -d.vy * 0.25; + d.vx *= 0.7; d.vz *= 0.7; d.rx *= 0.4; d.rz *= 0.4; + if (Math.abs(d.vy) < 0.3 && Math.hypot(d.vx, d.vz) < 0.2) { d.vy = 0; d.settle = Math.min(1, d.settle + dt * 2); } + } else d.settle = 0; + o.position.x = Math.max(-ah + rest, Math.min(ah - rest, o.position.x)); // stay inside the arena + o.position.z = Math.max(-ah + rest, Math.min(ah - rest, o.position.z)); + if (state && state.robots) for (const rb of state.robots) { // robots shove fallen parts aside + if (rb.out) continue; + const dx = o.position.x - rb.x, dz = o.position.z - rb.z, dd = Math.hypot(dx, dz), reach = (rb.st.rad || 0.8) + rest + 0.1; + if (dd < reach && dd > 0.001) { const push = reach - dd, nx = dx / dd, nz = dz / dd; o.position.x += nx * push; o.position.z += nz * push; d.vx += nx * 7; d.vz += nz * 7; d.settle = 0; } + } + o.rotation.x += d.rx * dt; o.rotation.z += d.rz * dt; + if (d.settle >= 1) { const k = 1 - Math.min(1, dt * 3); d.rx *= k; d.rz *= k; } } } - function clearDebris() { for (const d of debris) arenaScene.remove(d.o); debris.length = 0; } + const freeDebris = d => { arenaScene.remove(d.o); d.o.traverse(o => { if (o.geometry) o.geometry.dispose(); }); }; + function clearDebris() { for (const d of debris) freeDebris(d); debris.length = 0; } // combat.js says a part broke off -> take it off the model (one piece tumbles away) function breakPart(R, part) { if (!R) return; diff --git a/game/shop.js b/game/shop.js index 00137ea..42447df 100644 --- a/game/shop.js +++ b/game/shop.js @@ -9,7 +9,9 @@ (function (root) { 'use strict'; const RC = root.RC, $ = Kit.$; - RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b]; + RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b, + 0x39ff14, 0xc0c0c0, 0xff1e8e, 0x7b2fff]; // last 4 are mission rewards (locked until earned) + RC.PAINT_REWARDS = [0x39ff14, 0xc0c0c0, 0xff1e8e, 0x7b2fff]; // ready-made [body, accent] combinations RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230], [0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]]; @@ -20,7 +22,7 @@ const ICO = { hp: ['ico_hp', '❤️'], armour: ['ico_armour', '🛡️'], speed: ['ico_speed', '⏱️'], weight: ['ico_weight', '⚖️'], power: ['ico_power', '⚡'], money: ['ico_credits', '🪙'], fame: ['ico_fame', '⭐'], accel: [null, '🚀'], turn: [null, '↻'] }; RC.pic = (name, glyph = '', cls = '') => - `${name ? `` : ''}`; + `${name ? `` : ''}`; const ico = k => RC.pic(ICO[k][0], ICO[k][1]); RC.Shop = function (opt) { diff --git a/server/app.js b/server/app.js index 2a6500b..c68cea9 100644 --- a/server/app.js +++ b/server/app.js @@ -72,7 +72,14 @@ app.delete(/^\/db\/(.*)\.json$/, (req, res) => { }); // --- static game (same origin: no CORS, no mixed content) ------------------------------------------ -app.use(express.static(path.join(__dirname, '..', 'game'))); +app.use(express.static(path.join(__dirname, '..', 'game'), { + etag: true, + setHeaders(res, p) { + // images / fonts / audio rarely change -> cache hard (fast re-renders, no re-fetch flicker) + if (/\.(png|jpe?g|webp|gif|svg|woff2?|ttf|otf|mp3|ogg|wav|m4a)$/i.test(p)) res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); + else res.setHeader('Cache-Control', 'no-cache'); // code/html: revalidate so deploys show up + }, +})); const PORT = process.env.PORT || 8080; app.listen(PORT, () => console.log('Robot Clash server on :' + PORT)); diff --git a/server/db.js b/server/db.js index 6f6c38f..d62cd58 100644 --- a/server/db.js +++ b/server/db.js @@ -29,13 +29,26 @@ function resolveSV(v) { } // --- RTDB-like tree over the nodes table --------------------------------------------------------- +// objects are stored as ONE json node, so a deep path (e.g. matches//meta/seed) has no own row - +// read it from the nearest ancestor blob by descending into its parsed json (Firebase-like deep reads) +function readInside(p) { + const seg = p.split('/'); + for (let i = seg.length - 1; i >= 1; i--) { + const row = db.prepare('SELECT data FROM nodes WHERE path = ?').get(seg.slice(0, i).join('/')); + if (!row) continue; + let v = parse(row.data); + for (let j = i; j < seg.length; j++) { if (v && typeof v === 'object' && !Array.isArray(v)) v = v[seg[j]]; else { v = undefined; break; } } + return v === undefined ? null : v; + } + return null; +} function getTree(p) { p = norm(p); const like = p ? p + '/%' : '%'; const rows = p ? db.prepare('SELECT path, data FROM nodes WHERE path = ? OR path LIKE ?').all(p, like) : db.prepare('SELECT path, data FROM nodes').all(); - if (!rows.length) return null; + if (!rows.length) return p ? readInside(p) : null; let result; rows.sort((a, b) => a.path.length - b.path.length); for (const row of rows) { diff --git a/tests/sim.test.js b/tests/sim.test.js index bd511d8..7c93f05 100644 --- a/tests/sim.test.js +++ b/tests/sim.test.js @@ -2,7 +2,7 @@ 'use strict'; const path = require('path'); const g = p => require(path.join(__dirname, '..', 'game', p)); -g('parts.js'); g('robot.js'); g('combat.js'); g('ai.js'); g('progress.js'); g('tourney.js'); g('live.js'); g('ltourney.js'); g('cloudsave.js'); g('ranking.js'); +g('parts.js'); g('robot.js'); g('combat.js'); g('ai.js'); g('progress.js'); g('tourney.js'); g('live.js'); g('ltourney.js'); g('cloudsave.js'); g('ranking.js'); g('missions.js'); const RC = globalThis.RC; let fails = 0; const ok = (c, msg) => { if (!c) { fails++; console.log('FAIL', msg); } }; @@ -130,6 +130,40 @@ ok(wins.overlord >= wins.rustbucket, 'top robot beats bottom robot more often'); ok(R(null).length === 0, 'ranking handles empty'); } +// missions: roll / reset / progress +{ + const M = RC.Missions; + const now = 1_700_000_000_000, save = {}; + M.ensure(save, now, 12345); + ok(save.missions.daily.length === 3, 'missions: 3 daily'); + ok(save.missions.weekly.length === 1, 'missions: 1 weekly'); + const ids = save.missions.daily.map(m => m.id); + ok(new Set(ids).size === 3, 'missions: daily are distinct'); + // deterministic for the same seed + day + const s2 = {}; M.ensure(s2, now, 12345); + ok(s2.missions.daily.map(m => m.id).join() === ids.join(), 'missions: deterministic roll'); + // same day re-ensure keeps progress + save.missions.daily[0].prog = 1; M.ensure(save, now + 1000, 12345); + ok(save.missions.daily[0].prog === 1, 'missions: same day keeps progress'); + // next day re-rolls daily + M.ensure(save, now + 86400000, 12345); + ok(save.missions.daily[0].prog === 0, 'missions: new day resets daily'); + // progress: a win mission + const wm = { id: 'x', type: 'win', goal: 2, prog: 0, done: false }; + ok(M.apply(wm, { won: false }) === false && wm.prog === 0, 'missions: loss does not advance win'); + ok(M.apply(wm, { won: true }) === false && wm.prog === 1, 'missions: win advances'); + ok(M.apply(wm, { won: true }) === true && wm.done, 'missions: completes at goal'); + ok(M.apply(wm, { won: true }) === false, 'missions: done stays done'); + // damage accumulates and caps + const dm = { id: 'd', type: 'damage', goal: 500, prog: 0, done: false }; + M.apply(dm, { dealt: 300 }); ok(dm.prog === 300, 'missions: damage adds'); + const c = M.apply(dm, { dealt: 999 }); ok(dm.prog === 500 && c === true, 'missions: damage caps + completes'); + // typed wins + ok(M.gain('arena:foundry', { won: true, arenaId: 'foundry' }) === 1, 'missions: arena win counts'); + ok(M.gain('arena:foundry', { won: true, arenaId: 'crucible' }) === 0, 'missions: wrong arena no count'); + ok(M.gain('weapon:spinner', { won: true, weaponType: 'spinner' }) === 1, 'missions: weapon win counts'); +} + // gadgets ok(RC.validate({ ...RC.STARTER, gadget: 'turbo' }).ok, 'gadget build valid'); ok(RC.stats({ ...RC.STARTER, gadget: 'emp' }).gadget.type === 'emp', 'gadget in stats');