ROBOT CLASH
@@ -265,6 +317,7 @@
@@ -305,7 +358,11 @@
+
+
+
+
diff --git a/game/lang.js b/game/lang.js
index ec737a1..43d0652 100644
--- a/game/lang.js
+++ b/game/lang.js
@@ -17,7 +17,7 @@ window.LANG = {
reset_text: 'Delete your robot, credits and league progress and start again?',
reset_yes: 'Yes, start over', cancel: 'Cancel', ok: 'OK', back: 'Back', menu: 'Menu',
help_text: 'In the
workshop you fit one chassis, motor, wheels and battery, plus armour, a weapon and a tower. Keep under
100 kg, and the battery must supply enough power. Win fights for credits and buy better parts.',
- key_drive: 'drive (tank steering)', key_space: 'Space', key_weapon: 'main weapon', key_tower: 'tower weapon',
+ key_drive: 'drive (simple: screen direction, tank: turn + throttle)', key_space: 'Space', key_weapon: 'main weapon', key_tower: 'tower weapon',
key_pad: 'Gamepad', key_pad_text: 'stick, A = weapon, B = tower',
help_arena: 'You win by
knockout, by pushing the enemy into the
pit (it opens at half time) or on damage when the time runs out. Watch the floor saws, flame grilles, spike walls, the
forge press and the
magnet crane in the corners!',
loading: 'loading…', ranking: 'Fame ranking',
@@ -69,7 +69,7 @@ window.LANG = {
// fight
pad_weapon: 'Weapon', pad_tower: 'Tower',
fight_go: 'ACTIVATE!', pit_open: 'PIT OPEN!', into_pit: 'INTO THE PIT!', knockout: 'KNOCKOUT!',
- fight_hint: 'W A S D drive · Space weapon · Shift / E tower · P pause',
+ fight_hint: 'W/S drive · A/D turn · Space weapon · Shift / E tower · C camera · P pause',
st_lifted: 'MAGNET!', st_grabbed: 'GRABBED!', st_flipped: 'UPSIDE DOWN!', st_stunned: 'STUNNED', pit_is_open: 'PIT IS OPEN', pit_soon: 'pit opens soon',
continue: 'Continue', give_up: 'Give up',
// result
@@ -102,16 +102,62 @@ window.LANG = {
s_screen: 'Display', s_controls: 'Controls', s_career: 'Career', on: 'On', off: 'Off',
gfx_low: 'Low', gfx_medium: 'Medium', gfx_high: 'High',
// paint booth
+ // online lobby + live PvP
+ rotate_hint: 'Turn your device sideways for a bigger picture',
+ s_account: 'Account',
+ s_arena: 'Arena', arena_random: 'Random', arena_workshop: 'Workshop Pit', arena_foundry: 'The Foundry', arena_arena64: 'Mega Dome',
+ peer_back: 'Opponent is back', no_pause_online: 'No pause in live fights',
+ r_draw_prize: 'Draw prize',
+ online_guest: 'Join as guest (no e-mail)', online_short: '🌍 Online',
+ room_title: '{room} lobby', room_count: '{n} in this room', other_rooms: 'Other countries', you: 'you',
+ pick_room: 'Pick your country - then you see who is sitting in that lobby.',
+ cc_DE: 'Germany',
+ cc_AT: 'Austria',
+ cc_CH: 'Switzerland',
+ cc_GB: 'United Kingdom',
+ cc_US: 'USA',
+ cc_FR: 'France',
+ cc_ES: 'Spain',
+ cc_IT: 'Italy',
+ cc_NL: 'Netherlands',
+ cc_PL: 'Poland',
+ cc_TR: 'Turkey',
+ cc_RU: 'Russia',
+ cc_BR: 'Brazil',
+ cc_JP: 'Japan',
+ cc_KR: 'Korea',
+ cc_XX: 'International',
+ online_play: 'Play online', online_login_text: 'One account for your career and the online lobby - your robot and progress go with it.',
+ f_email: 'E-mail',
+ lobby: 'Global lobby', lobby_empty: 'Nobody else online right now. Keep this open - players show up here.',
+ your_flag: 'Your flag:', challenge: 'Challenge', busy: 'in a fight', quick_match: 'Quick match',
+ waiting_accept: 'Waiting for the other player...', challenge_in: 'Challenge!', wants_fight: 'wants to fight you!',
+ accept: 'Accept', decline: 'Decline', back_to_lobby: 'Back to lobby',
+ peer_lost: 'Connection to opponent lost - AI takes over', peer_left: '(left the fight)',
+ e_EMAIL_EXISTS: 'That e-mail is already registered.', e_EMAIL_NOT_FOUND: 'No account with that e-mail.',
+ e_INVALID_PASSWORD: 'Wrong password.', e_INVALID_LOGIN_CREDENTIALS: 'Wrong e-mail or password.',
+ e_WEAK_PASSWORD: 'Password needs at least 6 characters.', e_INVALID_EMAIL: 'That is not a valid e-mail.',
+ e_MISSING_PASSWORD: 'Please enter a password.', e_OPERATION_NOT_ALLOWED: 'Guest login is off - use e-mail.',
+ e_OFFLINE: 'Online is not set up yet.', e_ERROR: 'Something went wrong. Try again.',
pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front',
pt_view_top: 'Top', pt_view_right: 'Right', pt_view_left: 'Left', pt_view_front: 'Front', pt_view_free: 'Turn',
pt_brush: 'Brush', pt_spray: 'Spray', pt_erase: 'Eraser', pt_stamp: 'Stamp', pt_text: 'Text', pt_fill: 'Fill',
pt_mirror: 'Mirror both sides', pt_size: 'Size', pt_undo: 'Undo', pt_clear: 'Clear all', pt_done: 'Done', pt_text_ph: 'Text or number',
+ s_cam: 'Camera', cam_iso: 'Arena', cam_chase: 'Chase', cam_fpv: 'Cockpit', key_cam: 'switch camera',
+ // easier play + income
+ s_diff: 'Difficulty', diff_easy: 'Easy', diff_normal: 'Normal', diff_hard: 'Hard',
+ s_steer: 'Steering', steer_simple: 'Simple', steer_tank: 'Tank',
+ s_autofire: 'Weapon helper',
+ fight_hint_simple: 'W A S D: drive in that direction · Space weapon · Shift / E tower · C camera · P pause',
+ exhibition_hint: 'Tip: click a beaten opponent for an exhibition fight - half the prize, as often as you like.',
+ exhibition_note: 'Exhibition fight: half prize money, no league progress.',
+ exhibition_btn: 'Exhibition fight!', r_exhibition: 'Exhibition prize', r_dmg_bonus: 'Damage bonus',
// shop
owned: 'owned', need_money: '{n} credits missing', fight_go_btn: 'Into the arena!',
tip_bought: '{name}? Good choice. Let me bolt that on.',
tip_overweight: 'Too heavy! The judges weigh every robot - drop a part or pick lighter armour.',
tip_power: 'Your battery can\'t feed all that. Buy a stronger battery or a weapon that needs less power.',
- tip_0: 'Welcome to the workshop! Pick a category on top and click a part to see what it does.',
+ tip_0: 'Welcome to the workshop! Pick a category on top and click a part to see what it does. Tip: a flipper is a great first buy.',
tip_1: 'The white bar in the stats shows how your robot changes with the selected part.',
tip_2: 'A wedge plus a strong motor is cheap and nasty - shove them into the saws!',
tip_3: 'Big tyres keep you driving when a flipper turns you over.',
@@ -119,7 +165,10 @@ window.LANG = {
tip_5: 'Stay out of the corners: the forge press and the magnet crane don\'t care whose robot it is.',
tip_6: 'Tracks win every shoving match, but they are slow.',
tip_7: 'Hammers ignore half of the armour. Great against heavy plates.',
- tip_8: 'Lost a fight? You still get an appearance fee - repairs come off your winnings.',
+ tip_8: 'Lost a fight? You still get an appearance fee and a bonus for every hit.',
+ tip_9: 'Short on credits? Beat an old opponent again in an exhibition fight.',
+ tip_10: 'Too hard? Settings: difficulty Easy, weapon helper on.',
+ tip_11: 'Your 800 starting credits buy a flipper right away - it beats saw robots easily.',
},
de: {
lang_self: 'Deutsch',
@@ -135,7 +184,7 @@ window.LANG = {
reset_text: 'Roboter, Credits und Liga-Fortschritt löschen und neu anfangen?',
reset_yes: 'Ja, neu anfangen', cancel: 'Abbrechen', ok: 'OK', back: 'Zurück', menu: 'Menü',
help_text: 'In der
Werkstatt baust du je ein Chassis, einen Motor, Räder und eine Batterie ein, dazu Panzerung, Waffe und Turm. Bleib unter
100 kg, und die Batterie muss genug Strom liefern. Siege bringen Credits für bessere Teile.',
- key_drive: 'fahren (Panzersteuerung)', key_space: 'Leertaste', key_weapon: 'Hauptwaffe', key_tower: 'Turmwaffe',
+ key_drive: 'fahren (einfach: Bildschirmrichtung, Panzer: drehen + Gas)', key_space: 'Leertaste', key_weapon: 'Hauptwaffe', key_tower: 'Turmwaffe',
key_pad: 'Gamepad', key_pad_text: 'Stick, A = Waffe, B = Turm',
help_arena: 'Du gewinnst durch
K.o., indem du den Gegner in die
Grube schiebst (öffnet zur Halbzeit) oder nach Schaden, wenn die Zeit abläuft. Achtung vor Bodensägen, Flammengittern, Stachelwänden, der
Schmiedepresse und dem
Magnetkran in den Ecken!',
loading: 'lädt…', ranking: 'Ruhmesliste',
@@ -187,7 +236,7 @@ window.LANG = {
// fight
pad_weapon: 'Waffe', pad_tower: 'Turm',
fight_go: 'AKTIVIEREN!', pit_open: 'GRUBE OFFEN!', into_pit: 'IN DIE GRUBE!', knockout: 'K.O.!',
- fight_hint: 'W A S D fahren · Leertaste Waffe · Shift / E Turm · P Pause',
+ fight_hint: 'W/S fahren · A/D drehen · Leertaste Waffe · Shift / E Turm · C Kamera · P Pause',
st_lifted: 'MAGNET!', st_grabbed: 'GEPACKT!', st_flipped: 'AUF DEM KOPF!', st_stunned: 'BETÄUBT', pit_is_open: 'GRUBE IST OFFEN', pit_soon: 'Grube öffnet gleich',
continue: 'Weiter', give_up: 'Aufgeben',
// result
@@ -220,16 +269,62 @@ window.LANG = {
s_screen: 'Anzeige', s_controls: 'Steuerung', s_career: 'Karriere', on: 'An', off: 'Aus',
gfx_low: 'Niedrig', gfx_medium: 'Mittel', gfx_high: 'Hoch',
// paint booth
+ // online lobby + live PvP
+ rotate_hint: 'Dreh dein Gerät quer für ein größeres Bild',
+ s_account: 'Konto',
+ s_arena: 'Arena', arena_random: 'Zufällig', arena_workshop: 'Werkstatt-Grube', arena_foundry: 'Die Gießerei', arena_arena64: 'Mega-Dome',
+ peer_back: 'Gegner ist wieder da', no_pause_online: 'Keine Pause im Live-Kampf',
+ r_draw_prize: 'Unentschieden-Preis',
+ online_guest: 'Als Gast beitreten (ohne E-Mail)', online_short: '🌍 Online',
+ room_title: 'Lobby {room}', room_count: '{n} in diesem Raum', other_rooms: 'Andere Länder', you: 'du',
+ pick_room: 'Wähl dein Land - dann siehst du, wer in dieser Lobby sitzt.',
+ cc_DE: 'Deutschland',
+ cc_AT: 'Österreich',
+ cc_CH: 'Schweiz',
+ cc_GB: 'Großbritannien',
+ cc_US: 'USA',
+ cc_FR: 'Frankreich',
+ cc_ES: 'Spanien',
+ cc_IT: 'Italien',
+ cc_NL: 'Niederlande',
+ cc_PL: 'Polen',
+ cc_TR: 'Türkei',
+ cc_RU: 'Russland',
+ cc_BR: 'Brasilien',
+ cc_JP: 'Japan',
+ cc_KR: 'Korea',
+ cc_XX: 'International',
+ online_play: 'Online spielen', online_login_text: 'Ein Konto für Karriere und Online-Lobby - dein Roboter und Fortschritt gehören dazu.',
+ f_email: 'E-Mail',
+ lobby: 'Globale Lobby', lobby_empty: 'Gerade ist niemand sonst online. Lass das Fenster offen - Spieler erscheinen hier.',
+ your_flag: 'Deine Flagge:', challenge: 'Herausfordern', busy: 'im Kampf', quick_match: 'Schnelles Match',
+ waiting_accept: 'Warte auf den anderen Spieler...', challenge_in: 'Herausforderung!', wants_fight: 'will gegen dich kämpfen!',
+ accept: 'Annehmen', decline: 'Ablehnen', back_to_lobby: 'Zurück zur Lobby',
+ peer_lost: 'Verbindung zum Gegner weg - KI übernimmt', peer_left: '(hat den Kampf verlassen)',
+ e_EMAIL_EXISTS: 'Diese E-Mail ist schon registriert.', e_EMAIL_NOT_FOUND: 'Kein Konto mit dieser E-Mail.',
+ e_INVALID_PASSWORD: 'Falsches Passwort.', e_INVALID_LOGIN_CREDENTIALS: 'E-Mail oder Passwort falsch.',
+ e_WEAK_PASSWORD: 'Passwort braucht mindestens 6 Zeichen.', e_INVALID_EMAIL: 'Das ist keine gültige E-Mail.',
+ e_MISSING_PASSWORD: 'Bitte ein Passwort eingeben.', e_OPERATION_NOT_ALLOWED: 'Gast-Login ist aus - nimm E-Mail.',
+ e_OFFLINE: 'Online ist noch nicht eingerichtet.', e_ERROR: 'Etwas ist schiefgelaufen. Nochmal versuchen.',
pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne',
pt_view_top: 'Oben', pt_view_right: 'Rechts', pt_view_left: 'Links', pt_view_front: 'Vorne', pt_view_free: 'Drehen',
pt_brush: 'Pinsel', pt_spray: 'Spray', pt_erase: 'Radierer', pt_stamp: 'Stempel', pt_text: 'Text', pt_fill: 'Füllen',
pt_mirror: 'Beide Seiten spiegeln', pt_size: 'Größe', pt_undo: 'Zurück', pt_clear: 'Alles löschen', pt_done: 'Fertig', pt_text_ph: 'Text oder Nummer',
+ s_cam: 'Kamera', cam_iso: 'Arena', cam_chase: 'Verfolger', cam_fpv: 'Cockpit', key_cam: 'Kamera wechseln',
+ // easier play + income
+ s_diff: 'Schwierigkeit', diff_easy: 'Leicht', diff_normal: 'Normal', diff_hard: 'Schwer',
+ s_steer: 'Steuerung', steer_simple: 'Einfach', steer_tank: 'Panzer',
+ s_autofire: 'Waffen-Hilfe',
+ fight_hint_simple: 'W A S D: in diese Richtung fahren · Leertaste Waffe · Shift / E Turm · C Kamera · P Pause',
+ exhibition_hint: 'Tipp: Klick einen besiegten Gegner für einen Schaukampf – halbes Preisgeld, so oft du willst.',
+ exhibition_note: 'Schaukampf: halbes Preisgeld, kein Liga-Fortschritt.',
+ exhibition_btn: 'Schaukampf!', r_exhibition: 'Schaukampf-Preis', r_dmg_bonus: 'Schadensbonus',
// shop
owned: 'im Besitz', need_money: 'Es fehlen {n} Credits', fight_go_btn: 'Ab in die Arena!',
tip_bought: '{name}? Gute Wahl. Ich schraub das gleich dran.',
tip_overweight: 'Zu schwer! Jeder Roboter wird gewogen – lass ein Teil weg oder nimm leichtere Panzerung.',
tip_power: 'Deine Batterie schafft das nicht. Kauf eine stärkere oder nimm eine Waffe mit weniger Strombedarf.',
- tip_0: 'Willkommen in der Werkstatt! Wähl oben eine Kategorie und klick ein Teil an, um zu sehen, was es kann.',
+ tip_0: 'Willkommen in der Werkstatt! Wähl oben eine Kategorie und klick ein Teil an, um zu sehen, was es kann. Tipp: Ein Flipper ist ein super erster Kauf.',
tip_1: 'Der weiße Balken bei den Werten zeigt, wie sich dein Roboter mit dem gewählten Teil ändert.',
tip_2: 'Keil plus starker Motor: billig und gemein – schieb sie in die Sägen!',
tip_3: 'Große Reifen fahren weiter, wenn dich ein Flipper umdreht.',
@@ -237,6 +332,9 @@ window.LANG = {
tip_5: 'Bleib aus den Ecken: Schmiedepresse und Magnetkran ist egal, wessen Roboter da steht.',
tip_6: 'Ketten gewinnen jedes Schiebeduell, sind aber langsam.',
tip_7: 'Hämmer ignorieren die halbe Panzerung. Ideal gegen dicke Platten.',
- tip_8: 'Kampf verloren? Antrittsgeld gibt es trotzdem – die Reparatur geht davon ab.',
+ tip_8: 'Kampf verloren? Antrittsgeld gibt es trotzdem, dazu einen Bonus für jeden Treffer.',
+ tip_9: 'Knapp bei Kasse? Besieg einen alten Gegner nochmal im Schaukampf.',
+ tip_10: 'Zu schwer? Einstellungen: Schwierigkeit Leicht, Waffen-Hilfe an.',
+ tip_11: 'Mit deinen 800 Start-Credits kannst du sofort einen Flipper kaufen – der schlägt Säge-Roboter locker.',
},
};
diff --git a/game/lobby.js b/game/lobby.js
new file mode 100644
index 0000000..0c191dd
--- /dev/null
+++ b/game/lobby.js
@@ -0,0 +1,132 @@
+/* Robot Clash - online lobby: presence, player list, challenges, match creation. No DOM.
+ Needs net.js (RC.Net). Transport is Firebase RTDB (net.db). All cosmetic/casual, see docs/firebase.
+
+ const lobby = RC.Lobby({ net, getProfile: () => ({ name, flag, build, paint, fame }) });
+ lobby.enter() announce presence, start heartbeat, watch list + incoming challenges
+ lobby.leave() remove presence, stop everything
+ lobby.onList(fn) fn([{ uid, name, flag, state, fame }]) - online players except me, newest first
+ lobby.onIncoming(fn) fn({ from, fromName, fromFlag, build, paint, seed }) - someone challenges me
+ lobby.onMatch(fn) fn({ id, host (bool), opp: { uid, name, flag, build, paint }, seed }) - fight on
+ lobby.onCancel(fn) fn() - a pending challenge I sent/got fell through
+ await lobby.challenge(uid) invite a player (writes to their inbox, waits for accept)
+ await lobby.accept(from) accept an incoming challenge -> creates the match
+ lobby.decline(from) reject an incoming challenge
+ lobby.cancel() withdraw the challenge I sent
+
+ Presence TTL: entries older than STALE ms count as offline (no SDK onDisconnect). */
+(function (root) {
+ 'use strict';
+ const RC = (root.RC = root.RC || {});
+ const HEARTBEAT = 4000, STALE = 12000;
+ const now = () => Date.now();
+ // match id = both uids sorted + join -> same id on both sides; lower uid hosts (authority)
+ const matchId = (a, b) => [a, b].sort().join('_');
+ const isHost = (a, b) => a < b;
+
+ RC.Lobby = (opt) => {
+ const net = opt.net, db = net.db;
+ const cbs = { list: [], incoming: [], match: [], cancel: [] };
+ const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { /* ignore */ } });
+ let hb = null, subList = null, subIn = null, subMatch = null;
+ let outgoing = null; // uid I challenged
+ let inMatch = null; // active match id
+
+ const me = () => net.uid;
+ const prof = () => opt.getProfile();
+
+ 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' } });
+ }
+
+ function watchList() {
+ subList = db.stream('lobby', data => {
+ const t = now(), mine = me();
+ const rows = Object.entries(data || {})
+ .map(([uid, v]) => Object.assign({ uid }, v))
+ .filter(v => v.uid !== mine && v.name && (t - (v.ts || 0)) < STALE)
+ .sort((a, b) => (b.ts || 0) - (a.ts || 0));
+ emit('list', rows);
+ });
+ }
+
+ // incoming challenges land under challenges/
/
+ function watchIncoming() {
+ subIn = db.stream(`challenges/${me()}`, data => {
+ const entries = Object.entries(data || {}).filter(([, v]) => v && v.from && (now() - (v.ts || 0)) < STALE);
+ if (!entries.length) return;
+ const [, c] = entries[0];
+ emit('incoming', { from: c.from, fromName: c.fromName, fromFlag: c.fromFlag, build: c.build, paint: c.paint, seed: c.seed });
+ });
+ }
+
+ // the match node appears for both players once created (host writes it on accept)
+ function watchMatch(id, oppUid, host) {
+ cleanupMatch();
+ inMatch = id;
+ subMatch = db.stream(`matches/${id}/meta`, meta => {
+ // wait until BOTH players have written their robot (each side patches its own entry)
+ if (!meta || inMatch !== id || meta.seed == null || !meta[oppUid] || !meta[me()]) return;
+ emit('match', { id, host, opp: { uid: oppUid, name: meta[oppUid] && meta[oppUid].name, flag: meta[oppUid] && meta[oppUid].flag, build: meta[oppUid] && meta[oppUid].build, paint: meta[oppUid] && meta[oppUid].paint }, seed: meta.seed });
+ if (subMatch) { subMatch.close(); subMatch = null; } // meta is fixed; stop watching
+ });
+ }
+ function cleanupMatch() { if (subMatch) { subMatch.close(); subMatch = null; } }
+
+ async function challenge(uid) {
+ if (outgoing) return;
+ outgoing = uid;
+ const p = prof();
+ await beat('searching');
+ await db.put(`challenges/${uid}/${me()}`, { from: me(), fromName: p.name, fromFlag: p.flag || 'XX', build: p.build, paint: p.paint, seed: (Math.random() * 1e9) | 0, ts: { '.sv': 'timestamp' } });
+ // wait for the other side to create the match (they host if their uid < mine)
+ const id = matchId(me(), uid), host = isHost(me(), uid);
+ const give = setTimeout(() => { if (outgoing === uid) { emit('cancel'); cancel(); } }, STALE);
+ const watch = db.stream(`matches/${id}/meta/seed`, seed => {
+ if (seed == null) return;
+ clearTimeout(give); watch.close(); outgoing = null;
+ createMatch(uid); // add my own robot to the match meta
+ watchMatch(id, uid, host);
+ });
+ }
+
+ async function accept(from) {
+ const id = matchId(me(), from), host = isHost(me(), from);
+ await db.del(`challenges/${me()}/${from}`);
+ await createMatch(from);
+ watchMatch(id, from, host);
+ }
+ function decline(from) { db.del(`challenges/${me()}/${from}`); }
+ function cancel() { if (outgoing) { db.del(`challenges/${outgoing}/${me()}`); outgoing = null; beat('idle'); } }
+
+ async function createMatch(oppUid) {
+ const id = matchId(me(), oppUid), p = prof();
+ const seed = (parseInt(id.slice(-6), 36) % 1e9) || 1; // same on both sides
+ // meta holds both players' robots; written once, guarded so the first writer wins
+ await db.patch(`matches/${id}/meta`, { seed, [me()]: { name: p.name, flag: p.flag || 'XX', build: p.build, paint: p.paint } });
+ await beat('inmatch');
+ }
+
+ return {
+ onList: fn => cbs.list.push(fn),
+ onIncoming: fn => cbs.incoming.push(fn),
+ onMatch: fn => cbs.match.push(fn),
+ onCancel: fn => cbs.cancel.push(fn),
+ challenge, accept, decline, cancel,
+ async enter() {
+ if (!net.enabled || !me()) return;
+ await beat('idle');
+ hb = setInterval(() => db.patch(`lobby/${me()}`, { ts: { '.sv': 'timestamp' }, state: outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle' }), HEARTBEAT);
+ watchList(); watchIncoming();
+ },
+ refresh() { if (me()) beat(outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle'); },
+ endMatch() { const id = inMatch; inMatch = null; cleanupMatch(); if (id) db.del(`matches/${id}`); if (me()) beat('idle'); },
+ leave() {
+ clearInterval(hb); hb = null;
+ if (subList) subList.close(); if (subIn) subIn.close(); cleanupMatch();
+ if (me()) db.del(`lobby/${me()}`);
+ },
+ matchId, isHost,
+ };
+ };
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/game/looks.js b/game/looks.js
new file mode 100644
index 0000000..02ae445
--- /dev/null
+++ b/game/looks.js
@@ -0,0 +1,101 @@
+/* Robot Clash - opponent looks: makes the 3D league robots resemble their ComfyGen portraits
+ (assets/Sprites/opp_.png). A look = a painted skin layer (same 512x256 layout as the player's
+ own drawing: left half top view, right half side view, front to the right) + a few extra model
+ parts that render3d.js adds (eyes, cab, bumps, track covers).
+
+ RC.LOOKS[id] = { pattern, accent2, eyes, cab, bumps, tracksLook, wheelScale }
+ RC.lookLayer(look, paint) -> canvas (cached per id), used as paint.layer with paint.drawn = true */
+(function (root) {
+ 'use strict';
+ const RC = root.RC;
+ const LW = 512, LH = 256;
+ const css = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
+
+ RC.LOOKS = {
+ rustbucket: { pattern: 'rust', cab: true, wheelScale: 1.35, eyes: 0xffb040 },
+ tintoad: { pattern: 'rivets', bumps: true, eyes: 0xd8ff60 },
+ buzzkill: { pattern: 'hazard', tracksLook: true, eyes: 0xff3a20 },
+ flapjack: { pattern: 'twotone', accent2: 0xf2f2f2, eyes: 0x9fd8ff },
+ pincer: { pattern: 'twotone', accent2: 0xe0b030, eyes: 0xffd040 },
+ thunderclap: { pattern: 'scratches', eyes: 0xffa020 },
+ gravedigger: { pattern: 'dark', eyes: 0x50ff80 },
+ overlord: { pattern: 'redstripe', accent2: 0xd02020, eyes: 0xff2020 },
+ };
+
+ const cache = {};
+ RC.lookLayer = (id, paint) => {
+ if (cache[id]) return cache[id];
+ const look = RC.LOOKS[id];
+ if (!look || typeof document === 'undefined') return null;
+ const cv = document.createElement('canvas'); cv.width = LW; cv.height = LH;
+ const c = cv.getContext('2d');
+ let seed = 1; for (const ch of id) seed = (seed * 31 + ch.charCodeAt(0)) >>> 0;
+ const r = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };
+ const halves = fn => { for (const h of [0, 1]) { c.save(); c.beginPath(); c.rect(h * 256, 0, 256, 256); c.clip(); c.translate(h * 256, 0); fn(h); c.restore(); } };
+ const scratches = (n, a) => {
+ for (let i = 0; i < n; i++) {
+ c.strokeStyle = `rgba(${r() < 0.6 ? '255,255,255' : '0,0,0'},${a * (0.5 + r())})`; c.lineWidth = 0.6 + r() * 1.6;
+ const x = r() * LW, y = r() * LH, ang = r() * 6.3, l = 6 + r() * 34;
+ c.beginPath(); c.moveTo(x, y); c.lineTo(x + Math.cos(ang) * l, y + Math.sin(ang) * l); c.stroke();
+ }
+ };
+ const rivets = (step, col) => halves(() => {
+ c.fillStyle = col;
+ for (let x = 12; x < 256; x += step) for (const y of [12, 244]) { c.beginPath(); c.arc(x, y, 3.2, 0, 7); c.fill(); }
+ for (let y = 12; y < 256; y += step) for (const x of [12, 244]) { c.beginPath(); c.arc(x, y, 3.2, 0, 7); c.fill(); }
+ });
+
+ switch (look.pattern) {
+ case 'rust': // brown base with orange rust blotches and dark holes
+ for (let i = 0; i < 90; i++) {
+ c.fillStyle = `rgba(${150 + r() * 70 | 0},${60 + r() * 40 | 0},${20 + r() * 20 | 0},${0.25 + r() * 0.4})`;
+ c.beginPath(); c.ellipse(r() * LW, r() * LH, 6 + r() * 28, 4 + r() * 18, r() * 3, 0, 7); c.fill();
+ }
+ for (let i = 0; i < 40; i++) { c.fillStyle = `rgba(30,18,10,${0.3 + r() * 0.4})`; c.beginPath(); c.arc(r() * LW, r() * LH, 1 + r() * 4, 0, 7); c.fill(); }
+ rivets(40, 'rgba(40,25,15,.8)'); scratches(120, 0.12);
+ break;
+ case 'rivets': // panel lines + rivet rows
+ halves(() => {
+ c.strokeStyle = 'rgba(0,0,0,.35)'; c.lineWidth = 3;
+ for (const x of [86, 170]) { c.beginPath(); c.moveTo(x, 0); c.lineTo(x, 256); c.stroke(); }
+ c.beginPath(); c.moveTo(0, 128); c.lineTo(256, 128); c.stroke();
+ });
+ rivets(22, 'rgba(20,30,10,.85)'); scratches(80, 0.1);
+ break;
+ case 'hazard': // yellow/black stripes, darker band in the middle of the top
+ halves(h => {
+ c.fillStyle = '#16181c';
+ for (let k = -256; k < 512; k += 64) { c.beginPath(); c.moveTo(k, 0); c.lineTo(k + 32, 0); c.lineTo(k + 32 - 256, 256); c.lineTo(k - 256, 256); c.fill(); }
+ if (h === 0) { c.fillStyle = 'rgba(20,22,26,.9)'; c.fillRect(0, 96, 256, 64); }
+ });
+ scratches(140, 0.12);
+ break;
+ case 'twotone': // second colour on the top and as a band on the sides
+ c.fillStyle = css(look.accent2); c.fillRect(20, 30, 216, 196);
+ c.fillRect(256, 0, 256, 92);
+ c.fillStyle = 'rgba(0,0,0,.25)'; c.fillRect(256, 90, 256, 6);
+ rivets(32, 'rgba(0,0,0,.45)'); scratches(90, 0.1);
+ break;
+ case 'scratches':
+ scratches(260, 0.16); rivets(36, 'rgba(0,0,0,.5)');
+ break;
+ case 'dark': // dark hex plates with faint green seams
+ halves(() => {
+ c.strokeStyle = 'rgba(80,255,128,.18)'; c.lineWidth = 2;
+ for (let y = 0; y < 280; y += 36) for (let x = (y / 36) % 2 ? 0 : 21; x < 280; x += 42) {
+ c.beginPath(); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; c.lineTo(x + Math.cos(a) * 20, y + Math.sin(a) * 20); } c.closePath(); c.stroke();
+ }
+ });
+ scratches(70, 0.1);
+ break;
+ case 'redstripe': // racing stripe along the top, red band on the sides
+ c.fillStyle = css(look.accent2); c.fillRect(0, 100, 256, 56);
+ c.fillStyle = 'rgba(255,255,255,.8)'; c.fillRect(0, 96, 256, 4); c.fillRect(0, 156, 256, 4);
+ c.fillStyle = css(look.accent2); c.fillRect(256, 120, 256, 36);
+ scratches(110, 0.12);
+ break;
+ }
+ cache[id] = cv;
+ return cv;
+ };
+})(window);
diff --git a/game/net.js b/game/net.js
new file mode 100644
index 0000000..4966185
--- /dev/null
+++ b/game/net.js
@@ -0,0 +1,175 @@
+/* Robot Clash - Firebase over plain REST (no SDK, classic script, runs from file://).
+ Auth = Identity Toolkit REST, database = Realtime Database REST + Server-Sent-Events for push.
+
+ const net = RC.Net({ apiKey: '...', dbUrl: 'https://-default-rtdb.firebaseio.com' });
+ net.enabled false without a full config -> game stays offline
+ await net.auth.register(email, pass, name) -> { ok, error } (error: 'EMAIL_EXISTS' | 'WEAK_PASSWORD' | ...)
+ await net.auth.login(email, pass) -> { ok, error } ('EMAIL_NOT_FOUND' | 'INVALID_PASSWORD' | ...)
+ await net.auth.guest(name) -> { ok, error } (anonymous sign-in, must be enabled in Firebase)
+ net.auth.resume() -> true if a saved session was restored (async refresh follows)
+ net.auth.logout() / net.auth.current -> { uid, name, email, guest } | null
+ net.auth.onChange(fn) called after login/logout/refresh
+
+ await net.db.get(path) -> value | null
+ await net.db.put(path, value) -> ok (PUT, replaces)
+ await net.db.patch(path, obj) -> ok (PATCH, merges)
+ await net.db.push(path, value) -> key | null (POST, new child)
+ await net.db.del(path) -> ok
+ const sub = net.db.stream(path, onValue) -> { close() } push updates via EventSource
+ onValue(value) fires with the whole subtree on connect and on every change.
+
+ All DB calls carry the id token (?auth=). Token auto-refreshes before it expires.
+ Every call is best effort: on error db.get -> null, writes -> false, never throws. */
+(function (root) {
+ 'use strict';
+ const RC = (root.RC = root.RC || {});
+ const AUTH = 'https://identitytoolkit.googleapis.com/v1/accounts:';
+ const TOKEN = 'https://securetoken.googleapis.com/v1/token';
+
+ RC.Net = (cfg = {}) => {
+ const apiKey = cfg.apiKey || '';
+ const dbUrl = (cfg.dbUrl || '').replace(/\/+$/, '');
+ const enabled = /^AIza[\w-]+$/.test(apiKey) && /^https:\/\/.+firebase(io|database)\.(com|app)$/.test(dbUrl);
+ const store = Kit.store('robotclash.net');
+
+ let session = null; // { idToken, refreshToken, uid, name, email, guest, exp }
+ const listeners = [];
+ const fire = () => listeners.forEach(fn => { try { fn(cur()); } catch (e) { /* ignore */ } });
+ function cur() { return session ? { uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null; }
+
+ async function postJson(url, body) {
+ const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) { const msg = (data.error && data.error.message) || ('HTTP_' + res.status); const e = new Error(msg); e.code = msg.split(/[ :]/)[0]; throw e; }
+ return data;
+ }
+
+ function save() { store.set('session', session ? { refreshToken: session.refreshToken, uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null); }
+
+ function setAuth(d, name, guest) {
+ session = {
+ idToken: d.idToken || d.id_token, refreshToken: d.refreshToken || d.refresh_token,
+ uid: d.localId || d.user_id, name: name || (session && session.name) || '', email: d.email || (session && session.email) || '', guest: !!guest,
+ exp: Date.now() + (+(d.expiresIn || d.expires_in || 3600) - 60) * 1000,
+ };
+ save(); fire();
+ }
+
+ async function refresh() {
+ if (!session || !session.refreshToken) return false;
+ try {
+ const d = await postJson(`${TOKEN}?key=${apiKey}`, { grant_type: 'refresh_token', refresh_token: session.refreshToken });
+ session.idToken = d.id_token; session.refreshToken = d.refresh_token; session.uid = d.user_id;
+ session.exp = Date.now() + (+d.expires_in - 60) * 1000; save(); return true;
+ } catch (e) { session = null; save(); fire(); return false; }
+ }
+ async function token() {
+ if (!session) return null;
+ if (Date.now() >= session.exp) { if (!await refresh()) return null; }
+ return session.idToken;
+ }
+
+ const auth = {
+ get current() { return cur(); },
+ onChange(fn) { listeners.push(fn); },
+ async register(email, pass, name) {
+ if (!enabled) return { ok: false, error: 'OFFLINE' };
+ email = String(email || '').trim().toLowerCase();
+ try {
+ const d = await postJson(`${AUTH}signUp?key=${apiKey}`, { email, password: pass, returnSecureToken: true });
+ setAuth(d, Kit.cleanName(name) || email.split('@')[0], false);
+ await dbWrite('PUT', `users/${session.uid}/name`, session.name); // name for later logins
+ return { ok: true };
+ } catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
+ },
+ async login(email, pass) {
+ if (!enabled) return { ok: false, error: 'OFFLINE' };
+ email = String(email || '').trim().toLowerCase();
+ try {
+ const d = await postJson(`${AUTH}signInWithPassword?key=${apiKey}`, { email, password: pass, returnSecureToken: true });
+ setAuth(d, email.split('@')[0], false);
+ const name = await dbGet(`users/${session.uid}/name`); // needs the token -> after setAuth
+ if (typeof name === 'string' && name) { session.name = name; save(); fire(); }
+ return { ok: true };
+ } catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
+ },
+ async guest(name) {
+ if (!enabled) return { ok: false, error: 'OFFLINE' };
+ try {
+ const d = await postJson(`${AUTH}signUp?key=${apiKey}`, { returnSecureToken: true });
+ setAuth(d, Kit.cleanName(name) || 'Guest', true);
+ return { ok: true };
+ } catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
+ },
+ resume() {
+ const s = store.get('session', null);
+ if (!s || !s.refreshToken) return false;
+ session = Object.assign({ idToken: '', exp: 0 }, s);
+ refresh().then(ok => { if (ok) fire(); });
+ return true;
+ },
+ logout() { session = null; save(); fire(); },
+ };
+
+ async function dbGet(path) {
+ if (!enabled) return null;
+ const t = await token();
+ try {
+ const res = await fetch(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`, { cache: 'no-store' });
+ return res.ok ? await res.json() : null;
+ } catch (e) { return null; }
+ }
+ async function dbWrite(method, path, value) {
+ if (!enabled) return false;
+ const t = await token();
+ try {
+ const res = await fetch(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`, {
+ method, headers: { 'Content-Type': 'application/json' }, body: value === undefined ? undefined : JSON.stringify(value),
+ });
+ return res.ok ? (method === 'POST' ? (await res.json()).name : true) : false;
+ } catch (e) { return false; }
+ }
+
+ const db = {
+ get: dbGet,
+ put: (p, v) => dbWrite('PUT', p, v),
+ patch: (p, v) => dbWrite('PATCH', p, v),
+ push: (p, v) => dbWrite('POST', p, v),
+ del: p => dbWrite('DELETE', p),
+ // EventSource push stream. RTDB sends 'put' (whole subtree at /) and 'patch' (partial) events.
+ stream(path, onValue) {
+ if (!enabled || typeof EventSource === 'undefined') return { close() {} };
+ let es = null, closed = false, value = null, retry = null;
+ const open = async () => {
+ if (closed) return;
+ const t = await token();
+ es = new EventSource(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`);
+ // 'put' = replace the value at d.path; 'patch' = merge d.data's children into d.path
+ const setAt = (keys, data) => {
+ if (!keys.length) { value = data; return; }
+ if (value == null || typeof value !== 'object') value = {};
+ let o = value;
+ for (let i = 0; i < keys.length - 1; i++) { if (o[keys[i]] == null || typeof o[keys[i]] !== 'object') o[keys[i]] = {}; o = o[keys[i]]; }
+ if (data == null) delete o[keys[keys.length - 1]]; else o[keys[keys.length - 1]] = data;
+ };
+ const apply = ev => {
+ let d; try { d = JSON.parse(ev.data); } catch (e) { return; }
+ if (!d || typeof d.path !== 'string') return;
+ const keys = d.path.split('/').filter(Boolean);
+ if (ev.type === 'patch' && d.data && typeof d.data === 'object') {
+ for (const [k, v] of Object.entries(d.data)) setAt(keys.concat(k.split('/').filter(Boolean)), v);
+ } else setAt(keys, d.data);
+ try { onValue(value); } catch (e) { /* ignore */ }
+ };
+ es.addEventListener('put', apply);
+ es.addEventListener('patch', apply);
+ es.onerror = () => { if (closed) return; es.close(); retry = setTimeout(open, 1500); };
+ };
+ open();
+ return { close() { closed = true; clearTimeout(retry); if (es) es.close(); } };
+ },
+ };
+
+ return { enabled, auth, db, get uid() { return session ? session.uid : null; }, token };
+ };
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/game/netfight.js b/game/netfight.js
new file mode 100644
index 0000000..f967967
--- /dev/null
+++ b/game/netfight.js
@@ -0,0 +1,138 @@
+/* Robot Clash - live PvP sync over an existing deterministic fight. Needs net.js, combat.js, ai.js.
+ Robot 0 is always the local player, robot 1 the opponent (both clients see it that way, so the host
+ mirrors indices when it publishes). The lower-uid player is the host (authority): it runs the real
+ RC.Combat.step and publishes snapshots; the guest renders them and only sends its input.
+
+ const nf = RC.NetFight({ net, id, host, mySeat, oppStyle, oppSkill, onPeerLost(wasHost) });
+ nf.start()
+ HOST each tick, instead of the normal step:
+ nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events
+ GUEST each frame, instead of step:
+ nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play
+ nf.peerAlive false once the peer went silent > GRACE (AI takes over)
+ nf.stop()
+
+ mySeat: 0 if I am meta[myUid] rendered as robot 0 (always true locally). The host publishes with robots
+ ordered [host, guest]; each side maps so that *its* robot is index 0. */
+(function (root) {
+ 'use strict';
+ const RC = (root.RC = root.RC || {});
+ const PUB = 1 / 15, GRACE = 4000; // ms without news before the AI covers for the peer
+ // robot fields the view / HUD / sound read - kept small for the wire
+ const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'boost', 'dead', 'out'];
+ const packRobot = r => { const o = {}; for (const k of RF) o[k] = r[k]; return o; };
+ const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
+
+ RC.NetFight = (opt) => {
+ const net = opt.net, db = net.db, id = opt.id, host = opt.host;
+ const base = `matches/${id}`;
+ let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = [];
+ let remoteInput = { throttle: 0, turn: 0, fire: false, fire2: false };
+ let started = false, lastPeer = Date.now(), peerAlive = true, ai = null, subIn = null, subState = null, subPing = null, lastState = null, stateApplied = -1;
+
+ function start() {
+ if (host) {
+ // host reads the guest's input stream
+ subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } });
+ } else {
+ // guest reads the host's state stream
+ subState = db.stream(`${base}/state`, v => { if (v && typeof v.seq === 'number') { lastState = v; lastPeer = Date.now(); } });
+ subPing = db.stream(`${base}/ping`, v => { if (v) lastPeer = Date.now(); }); // host alive during the countdown
+ }
+ }
+
+ function checkPeer() {
+ if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock
+ if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); }
+ if (peerAlive && Date.now() - lastPeer > GRACE) {
+ peerAlive = false;
+ if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 });
+ if (opt.onPeerLost) opt.onPeerLost(host);
+ }
+ }
+
+ // HOST: step with [local, guest-or-AI], publish robots as [host, guest] but return a state where
+ // index 0 is the LOCAL player (so game.js renders identically on both sides).
+ function hostStep(s, localInput, dt) {
+ checkPeer();
+ const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt);
+ RC.Combat.step(s, dt, [localInput, guestInput]);
+ if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest
+ pubT -= dt;
+ if (pubT <= 0) {
+ pubT = PUB;
+ db.put(`${base}/state`, {
+ seq: ++seq, t: s.t, left: s.left, pitOpen: s.pitOpen, pitAlarm: s.pitAlarm,
+ press: { st: s.press.st, y: s.press.y }, crane: { st: s.crane.st, x: s.crane.x, z: s.crane.z, who: s.crane.who },
+ rockets: s.rockets.map(k => ({ x: k.x, z: k.z, y: k.y, a: k.a })),
+ r: [packRobot(s.robots[0]), packRobot(s.robots[1])],
+ ev: evBuf.slice(-24), result: s.result, endIn: s.endIn,
+ });
+ evBuf.length = 0;
+ }
+ return s.events;
+ }
+
+ // GUEST: no simulation. Ease local robots toward the latest snapshot; snap flags/hp; play its events once.
+ function guestFrame(s, localInput, dt) {
+ checkPeer();
+ // send my input (I am robot 0 locally = guest = snapshot index 1)
+ sendT -= dt;
+ beatT -= dt;
+ // send on change, and at least every 0.5 s as a heartbeat (otherwise the host thinks I am gone)
+ if (sendT <= 0 && (changed(localInput) || beatT <= 0)) {
+ sendT = PUB; beatT = 0.5; lastInSeq++;
+ db.put(`${base}/in`, { seq: lastInSeq, throttle: localInput.throttle || 0, turn: localInput.turn || 0, fire: !!localInput.fire, fire2: !!localInput.fire2 });
+ prevInput = localInput;
+ }
+ const ev = [];
+ if (lastState) {
+ const snap = lastState;
+ s.t = snap.t; s.left = snap.left; s.pitOpen = snap.pitOpen; s.pitAlarm = snap.pitAlarm;
+ s.press.st = snap.press.st; s.press.y = snap.press.y;
+ s.crane.st = snap.crane.st; s.crane.x = snap.crane.x; s.crane.z = snap.crane.z; s.crane.who = snap.crane.who;
+ syncRockets(s, snap.rockets);
+ s.result = snap.result; s.endIn = snap.endIn;
+ // snapshot order [host, guest]; locally guest must be index 0 -> swap
+ applyRobot(s.robots[0], snap.r[1], dt); // me (guest)
+ applyRobot(s.robots[1], snap.r[0], dt); // host
+ if (snap.seq !== stateApplied) {
+ stateApplied = snap.seq;
+ for (const e of snap.ev || []) { const c = Object.assign({}, e); if (c.who === 0) c.who = 1; else if (c.who === 1) c.who = 0; ev.push(c); }
+ }
+ }
+ return ev;
+ }
+
+ function applyRobot(r, d, dt) {
+ if (!d) return;
+ const k = Math.min(1, dt * 14); // ease position/angle, snap the rest
+ r.x += (d.x - r.x) * k; r.z += (d.z - r.z) * k; r.y += (d.y - r.y) * k;
+ r.a += wrap(d.a - r.a) * k;
+ r.turretA += wrap(d.turretA - r.turretA) * k;
+ for (const f of ['hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'boost', 'dead', 'out']) r[f] = d[f];
+ }
+ function syncRockets(s, list) {
+ list = list || [];
+ s.rockets.length = list.length;
+ for (let i = 0; i < list.length; i++) s.rockets[i] = Object.assign(s.rockets[i] || { owner: 1, sp: 6, t: 3 }, list[i]);
+ }
+
+ let prevInput = null;
+ function changed(inp) { return !prevInput || inp.throttle !== prevInput.throttle || inp.turn !== prevInput.turn || inp.fire !== prevInput.fire || inp.fire2 !== prevInput.fire2; }
+
+ return {
+ start, hostStep, guestFrame,
+ // during the countdown: keep the line alive (guest sends a neutral input, host an empty state ping)
+ idle(dt) {
+ sendT -= dt;
+ if (sendT > 0) return;
+ sendT = 0.5;
+ if (host) db.patch(`${base}/ping`, { h: Date.now() });
+ else { lastInSeq++; db.put(`${base}/in`, { seq: lastInSeq, throttle: 0, turn: 0, fire: false, fire2: false }); }
+ },
+ get peerAlive() { return peerAlive; },
+ stop() { if (subIn) subIn.close(); if (subState) subState.close(); if (subPing) subPing.close(); },
+ };
+ };
+})(typeof window !== 'undefined' ? window : globalThis);
diff --git a/game/render3d.js b/game/render3d.js
index 935a2f5..acc0c34 100644
--- a/game/render3d.js
+++ b/game/render3d.js
@@ -41,8 +41,8 @@
c.fillStyle = g; c.fillRect(0, 0, 64, 64);
});
- function floorTex() {
- const A = RC.ARENA, S = 64, N = A.half * 2 * S; // 64 px per metre
+ function floorTex(A) {
+ const S = 64, N = A.half * 2 * S; // 64 px per metre
const P = (x, z) => [(x + A.half) * S, (z + A.half) * S];
let plate = null; // tex_floor.jpg from ComfyGen (make_tileable)
const tex = canvasTex(N, N, draw);
@@ -105,6 +105,20 @@
}
}
+ // image from assets/Sprites as a WebGL texture; skipped quietly where file:// taints it (release embeds data: URIs)
+ function loadTex(file, onReady) {
+ const im = new Image();
+ im.onload = () => {
+ const probe = document.createElement('canvas').getContext('2d');
+ probe.drawImage(im, 0, 0, 1, 1);
+ try { probe.getImageData(0, 0, 1, 1); } catch (e) { return; }
+ const tex = new T.Texture(im);
+ tex.encoding = T.sRGBEncoding; tex.anisotropy = 4; tex.needsUpdate = true;
+ onReady(tex);
+ };
+ im.src = Kit.asset('assets/Sprites/' + file);
+ }
+
// ---------------------------------------------------------------- particles
function Particles(scene, max, size, additive, tex) {
const pos = new Float32Array(max * 3), col = new Float32Array(max * 4);
@@ -161,6 +175,8 @@
M.flame = new T.MeshBasicMaterial({ color: 0xff3a08, transparent: true, opacity: 0.42, blending: T.AdditiveBlending, depthWrite: false, side: T.DoubleSide });
M.trackTex = canvasTex(64, 16, (c, w, h) => { c.fillStyle = '#17181b'; c.fillRect(0, 0, w, h); c.fillStyle = '#2c2e33'; for (let x = 0; x < w; x += 8) c.fillRect(x, 0, 4, h); }, [6, 1]);
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 });
return M;
}
const box = (w, h, d, m) => { const o = new T.Mesh(new T.BoxGeometry(w, h, d), m); o.castShadow = true; o.receiveShadow = true; return o; };
@@ -216,10 +232,16 @@
root.add(tilt);
const out = { root, tilt, body, skin, st, build, roll: 0, flash: 0, spinA: 0, sawA: 0, gunA: 0, smokeT: 0 };
const sk = (geo, w, h, d, y0) => { const o = new T.Mesh(skinUV(geo, w, d, h, y0), body); o.castShadow = o.receiveShadow = true; return o; };
+ const look = paint.look || {}; // opponent look (looks.js), cosmetic only
const big = wh && wh.kind === 'big';
- const c = big ? 0.12 : 0.1; // ground clearance
+ const ws = look.wheelScale || 1;
+ const c = big ? 0.12 : 0.1 * ws; // ground clearance
out.c = c;
+ // every piece gets userData.part = slot (lets tools/partshot.html render one part alone)
+ let from = 0;
+ const mark = part => { for (let i = from; i < tilt.children.length; i++) tilt.children[i].userData.part = part; from = tilt.children.length; };
+
// chassis
let top = c + H;
if (ch.shape === 'wedge') {
@@ -243,7 +265,21 @@
const s2 = box(0.06, H * 0.6, Wd * 1.002, m.stripe); s2.position.set(-L / 2 + 0.08, c + H / 2, 0); tilt.add(s2);
}
}
+ // look extras: raised cab with window slit, eye bumps (like the portraits)
+ if (look.cab) {
+ const cw = L * 0.4, chh = H * 0.62, cd = Wd * 0.64;
+ const cab = sk(new T.BoxGeometry(cw, chh, cd), cw, chh, cd, -chh / 2); cab.position.set(-L * 0.16, top + chh / 2, 0); tilt.add(cab);
+ const win = box(0.02, chh * 0.25, cd * 0.8, m.dark); win.position.set(-L * 0.16 + cw / 2 + 0.005, top + chh * 0.62, 0); tilt.add(win);
+ top += chh;
+ }
+ if (look.bumps) {
+ for (const sz of [-1, 1]) {
+ const b = sk(new T.SphereGeometry(1, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), 2, 1, 2, 0);
+ b.scale.set(0.13, 0.11, 0.13); b.position.set(L * 0.18, top - (ch.shape === 'wedge' ? H * 0.45 : 0), sz * Wd * 0.26); tilt.add(b);
+ }
+ }
out.top = top;
+ mark('chassis');
// armour plates (sides + rear), bolts
if (armour) {
@@ -255,10 +291,12 @@
const r = box(0.05, H * 0.78, Wd * 0.95, armour); r.position.set(-L / 2 - 0.028, c + H * 0.42, 0); tilt.add(r);
}
+ mark('armour');
+
// wheels
out.wheels = [];
const side = Wd / 2 + (armour ? 0.13 : 0.08);
- if (wh.kind === 'tracks') {
+ if (wh.kind === 'tracks' || look.tracksLook) {
for (const sz of [-1, 1]) {
const t = box(L * 1.02, 0.3, 0.2, m.track); t.position.set(0, 0.15, sz * side); tilt.add(t);
for (const bx of [-0.42, 0.42]) { const w = cyl(0.15, 0.15, 0.21, m.hub, 14); w.rotation.x = Math.PI / 2; w.position.set(bx * L, 0.15, sz * side); tilt.add(w); }
@@ -274,61 +312,83 @@
out.wheelR = r;
} else {
for (const sx of [-1, 1]) for (const sz of [-1, 1]) {
- const w = new T.Group(); w.position.set(sx * L * 0.32, 0.16, sz * side);
- const tyre = cyl(0.16, 0.16, 0.12, m.rubber, 16); tyre.rotation.x = Math.PI / 2; w.add(tyre);
- const hub = cyl(0.07, 0.07, 0.13, m.hub, 8); hub.rotation.x = Math.PI / 2; w.add(hub);
+ const wr = 0.16 * ws;
+ const w = new T.Group(); w.position.set(sx * L * 0.32, wr, sz * (side + (ws - 1) * 0.08));
+ const tyre = cyl(wr, wr, 0.12 * ws, m.rubber, 16); tyre.rotation.x = Math.PI / 2; w.add(tyre);
+ const hub = cyl(wr * 0.44, wr * 0.44, 0.13 * ws, m.hub, 8); hub.rotation.x = Math.PI / 2; w.add(hub);
tilt.add(w); out.wheels.push(w);
}
- out.wheelR = 0.16;
+ out.wheelR = 0.16 * ws;
}
- // headlights + antenna
- for (const sz of [-0.3, 0.3]) { const l = box(0.03, 0.05, 0.1, m.glowW); l.position.set(L / 2 + 0.005, c + H * 0.62, sz * Wd); tilt.add(l); }
+ mark('wheels');
+
+ // headlights, or glowing eyes for opponents with a look
+ if (look.eyes) {
+ const eyeMat = new T.MeshStandardMaterial({ color: look.eyes, emissive: look.eyes, emissiveIntensity: 2.2 });
+ for (const sz of [-1, 1]) {
+ const e = new T.Mesh(new T.SphereGeometry(0.055, 12, 8), eyeMat);
+ e.position.set(L / 2 + 0.01, c + H * (ch.shape === 'wedge' ? 0.3 : 0.7), sz * Wd * 0.24); tilt.add(e);
+ }
+ } else for (const sz of [-0.3, 0.3]) { const l = box(0.03, 0.05, 0.1, m.glowW); l.position.set(L / 2 + 0.005, c + H * 0.62, sz * Wd); tilt.add(l); }
const ant = cyl(0.01, 0.01, 0.45, m.dark, 6); ant.position.set(-L / 2 + 0.12, top + 0.22, Wd / 2 - 0.12); tilt.add(ant);
const tip = new T.Mesh(new T.SphereGeometry(0.035, 8, 6), new T.MeshStandardMaterial({ color: paint.accent, emissive: paint.accent, emissiveIntensity: 0.9 }));
tip.position.set(-L / 2 + 0.12, top + 0.46, Wd / 2 - 0.12); tilt.add(tip);
+ mark('lights');
+
// main weapon (front = +x)
const w = st.weapon;
if (w) {
+ const WS = m.wsteel, ED = m.wedge, HZ = m.stripe; // weapon steel, edge, hazard stripe
if (w.type === 'wedge') {
- const p = box(0.55, 0.04, Wd * 1.05, m.steel); p.position.set(L / 2 + 0.22, c * 0.5 + 0.08, 0); p.rotation.z = -0.42; tilt.add(p);
+ // short ramp plate at the front (as before - stays close to the body so it does not poke through)
+ const p = box(0.5, 0.05, Wd * 1.05, ED); p.position.set(L / 2 + 0.18, c * 0.5 + 0.08, 0); p.rotation.z = -0.42; tilt.add(p);
+ const edge = box(0.12, 0.16, Wd * 1.06, HZ); edge.position.set(L / 2 + 0.34, 0.02, 0); tilt.add(edge);
} else if (w.type === 'flipper') {
- const piv = new T.Group(); piv.position.set(L / 2 - 0.08, c + H * 0.3, 0); tilt.add(piv);
- const p = box(0.62, 0.05, Wd * 0.92, m.steel); p.position.x = 0.31; piv.add(p);
- const s = box(0.6, 0.012, Wd * 0.3, accent); s.position.set(0.31, 0.03, 0); piv.add(s);
+ const piv = new T.Group(); piv.position.set(L / 2 - 0.1, c + H * 0.22, 0); tilt.add(piv);
+ const p = box(0.78, 0.09, Wd * 0.95, WS); p.position.x = 0.39; piv.add(p);
+ const s = box(0.78, 0.03, Wd * 0.4, accent); s.position.set(0.39, 0.06, 0); piv.add(s);
+ const edge = box(0.12, 0.14, Wd * 0.98, HZ); edge.position.set(0.78, 0, 0); piv.add(edge);
+ const pist = cyl(0.05, 0.05, 0.4, m.hub, 8); pist.rotation.z = 1.0; pist.position.set(0.2, -0.16, 0); tilt.add(pist); // ram
out.flipper = piv;
} else if (w.type === 'hammer') {
- const piv = new T.Group(); piv.position.set(-L * 0.08, top + 0.06, 0); tilt.add(piv);
- const post = box(0.12, 0.14, 0.18, m.dark); post.position.set(-L * 0.08, top + 0.03, 0); tilt.add(post);
- const arm = box(L * 0.72, 0.07, 0.07, m.dark); arm.position.x = L * 0.36; piv.add(arm);
- const head = box(0.1, 0.34, 0.06, m.steel); head.position.set(L * 0.72, -0.1, 0); piv.add(head);
- const back = box(0.14, 0.12, 0.12, accent); back.position.set(L * 0.72, 0.08, 0); piv.add(back);
+ const post = box(0.16, 0.26, 0.24, m.dark); post.position.set(-L * 0.1, top + 0.11, 0); tilt.add(post);
+ const piv = new T.Group(); piv.position.set(-L * 0.1, top + 0.16, 0); tilt.add(piv);
+ const arm = box(L * 0.82, 0.1, 0.1, m.dark); arm.position.x = L * 0.41; piv.add(arm);
+ const head = box(0.26, 0.42, 0.26, WS); head.position.set(L * 0.82, -0.12, 0); piv.add(head); // big mallet head
+ const face = box(0.1, 0.44, 0.28, HZ); face.position.set(L * 0.82 + 0.17, -0.12, 0); piv.add(face);
+ const spike = box(0.18, 0.12, 0.12, accent); spike.position.set(L * 0.82, 0.12, 0); piv.add(spike);
out.hammer = piv;
} else if (w.type === 'saw') {
- const arm = box(0.35, 0.08, 0.08, m.dark); arm.position.set(L / 2 + 0.05, c + H * 0.55, 0); tilt.add(arm);
- const g = new T.Group(); g.position.set(L / 2 + 0.2, c + H * 0.55, 0); tilt.add(g);
- const d = cyl(0.3, 0.3, 0.025, m.steel, 28); d.rotation.x = Math.PI / 2; g.add(d);
- for (let k = 0; k < 14; k++) { const t = box(0.07, 0.04, 0.026, m.steel); const a = k / 14 * Math.PI * 2; t.position.set(Math.cos(a) * 0.31, Math.sin(a) * 0.31, 0); t.rotation.z = a + 0.6; g.add(t); }
- const hub = cyl(0.06, 0.06, 0.04, accent, 10); hub.rotation.x = Math.PI / 2; g.add(hub);
+ const arm = box(0.4, 0.12, 0.12, m.dark); arm.position.set(L / 2 + 0.06, c + H * 0.5, 0); tilt.add(arm);
+ const guard = new T.Mesh(new T.TorusGeometry(0.42, 0.05, 8, 20, Math.PI), accent); // orange guard over the top
+ guard.position.set(L / 2 + 0.28, c + H * 0.5, 0); tilt.add(guard);
+ const g = new T.Group(); g.position.set(L / 2 + 0.28, c + H * 0.5, 0); tilt.add(g);
+ const d = cyl(0.38, 0.38, 0.04, WS, 32); d.rotation.x = Math.PI / 2; g.add(d);
+ for (let k = 0; k < 16; k++) { const t = box(0.11, 0.06, 0.05, WS); const a = k / 16 * Math.PI * 2; t.position.set(Math.cos(a) * 0.4, Math.sin(a) * 0.4, 0); t.rotation.z = a + 0.6; g.add(t); }
+ const hub = cyl(0.09, 0.09, 0.07, accent, 12); hub.rotation.x = Math.PI / 2; g.add(hub);
out.saw = g;
} else if (w.type === 'spinner') {
- const post = cyl(0.07, 0.07, 0.25, m.dark, 10); post.position.set(L / 2 + 0.02, c + H * 0.35, 0); tilt.add(post);
- const g = new T.Group(); g.position.set(L / 2 + 0.02, c + H * 0.32, 0); tilt.add(g);
- const bar = box(1.25, 0.07, 0.16, m.steel); g.add(bar);
- for (const sx of [-1, 1]) { const t = box(0.1, 0.09, 0.2, accent); t.position.x = sx * 0.6; g.add(t); }
+ const post = cyl(0.1, 0.12, 0.3, m.dark, 12); post.position.set(L / 2 + 0.04, c + H * 0.32, 0); tilt.add(post);
+ const g = new T.Group(); g.position.set(L / 2 + 0.04, c + H * 0.3, 0); tilt.add(g);
+ const bar = box(1.5, 0.12, 0.22, WS); g.add(bar);
+ const stripe = box(1.5, 0.13, 0.08, HZ); g.add(stripe);
+ for (const sx of [-1, 1]) { const t = box(0.18, 0.16, 0.32, accent); t.position.x = sx * 0.72; g.add(t); }
out.spinner = g;
} else if (w.type === 'crusher') {
out.jaws = [];
for (const sz of [-1, 1]) {
- const piv = new T.Group(); piv.position.set(L / 2 - 0.02, c + H * 0.45, sz * Wd * 0.34); tilt.add(piv);
- const j = box(0.58, 0.14, 0.08, m.steel); j.position.x = 0.29; piv.add(j);
- const tooth = box(0.08, 0.14, 0.14, accent); tooth.position.set(0.56, 0, -sz * 0.05); piv.add(tooth);
+ const piv = new T.Group(); piv.position.set(L / 2 - 0.02, c + H * 0.45, sz * Wd * 0.32); tilt.add(piv);
+ const j = box(0.68, 0.2, 0.14, WS); j.position.x = 0.34; piv.add(j);
+ for (let k = 0; k < 3; k++) { const tooth = box(0.1, 0.18, 0.14, accent); tooth.position.set(0.3 + k * 0.18, -sz * 0.02, -sz * 0.07); tooth.rotation.z = -sz * 0.25; piv.add(tooth); }
piv.userData.side = sz; out.jaws.push(piv);
}
}
}
+ mark('weapon');
+
// tower on top
const tw = st.tower;
if (tw) {
@@ -353,6 +413,7 @@
}
out.turret = g;
}
+ mark('tower');
root.traverse(o => { if (o.isMesh && !o.material.transparent) { o.castShadow = true; } });
return out;
}
@@ -392,38 +453,77 @@
}
// ---------------------------------------------------------------- arena
- function buildArena(scene) {
- const A = RC.ARENA, m = mats(), half = A.half;
- const out = {};
- scene.background = new T.Color(0x07090d);
- scene.fog = new T.Fog(0x07090d, 26, 60);
+ // theme colours per arena (combat.js arena.theme)
+ const THEME = {
+ steel: { bg: 0x07090d, fog: 0x07090d, rimA: 0xff7a1a, rimB: 0x4fa8ff, hazard: 0xd33 },
+ lava: { bg: 0x0d0604, fog: 0x1a0a06, rimA: 0xff5a1a, rimB: 0xff2a10, hazard: 0xff6020 },
+ blue: { bg: 0x05080f, fog: 0x070d1a, rimA: 0x3aa0ff, rimB: 0x9a60ff, hazard: 0x40c0ff },
+ };
- // lights: one shadow-casting key light + floodlight colours
+ // persistent lights (reused across arena rebuilds)
+ function buildArena(scene) {
+ const out = {};
scene.add(new T.HemisphereLight(0x8fa6c8, 0x1a140f, 0.55));
const key = new T.DirectionalLight(0xfff1dc, 1.25);
key.position.set(6, 16, 9); key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
- Object.assign(key.shadow.camera, { left: -11, right: 11, top: 11, bottom: -11, near: 1, far: 40 });
+ Object.assign(key.shadow.camera, { left: -11, right: 11, top: 11, bottom: -11, near: 1, far: 50 });
key.shadow.bias = -0.0008;
scene.add(key);
- const rimA = new T.PointLight(0xff7a1a, 1.1, 22); rimA.position.set(-9, 5, 9); scene.add(rimA);
- const rimB = new T.PointLight(0x4fa8ff, 0.9, 22); rimB.position.set(9, 5, -9); scene.add(rimB);
+ const rimA = new T.PointLight(0xff7a1a, 1.1, 22); scene.add(rimA);
+ const rimB = new T.PointLight(0x4fa8ff, 0.9, 22); scene.add(rimB);
out.lights = { key, rimA, rimB, hemi: scene.children.find(o => o.isHemisphereLight) };
out.flashLight = new T.PointLight(0xffaa55, 0, 9); scene.add(out.flashLight);
+ out.scene = scene; out.group = null; out.id = null;
+ out.rocketGeo = new T.CylinderGeometry(0.05, 0.05, 0.32, 8); out.rocketGeo.rotateZ(Math.PI / 2);
+ out.rocketMat = new T.MeshStandardMaterial({ color: 0xdddddd, emissive: 0x331100 });
+ out.rocketMeshes = [];
+ buildArenaGeo(out, RC.ARENA);
+ return out;
+ }
+ function disposeGroup(g) {
+ g.traverse(o => {
+ if (o.geometry) o.geometry.dispose();
+ if (o.material) [].concat(o.material).forEach(mm => { if (mm.map && mm.map.dispose) mm.map.dispose(); mm.dispose(); });
+ });
+ }
+
+ // (re)build all arena geometry for arena def A into a fresh group
+ function buildArenaGeo(out, A) {
+ const m = mats(), half = A.half, th = THEME[A.theme] || THEME.steel;
+ const scene = out.scene;
+ if (out.group) { scene.remove(out.group); disposeGroup(out.group); }
+ const group = new T.Group(); scene.add(group); out.group = group; out.id = A.id;
+ const scene_add = o => group.add(o);
+ scene.background = new T.Color(th.bg);
+ scene.fog = new T.Fog(th.fog, half * 3, half * 5.5);
+ const { key, rimA, rimB, flashLight } = out.lights;
+ const sc = Math.max(11, half + 3);
+ Object.assign(key.shadow.camera, { left: -sc, right: sc, top: sc, bottom: -sc }); key.shadow.camera.updateProjectionMatrix();
+ rimA.color.setHex(th.rimA); rimA.position.set(-half - 1, 5, half + 1); rimA.distance = half * 2.6;
+ rimB.color.setHex(th.rimB); rimB.position.set(half + 1, 5, -half - 1); rimB.distance = half * 2.6;
+ out.hazardCol = th.hazard;
+ { const scene = { add: scene_add }; buildArenaBody(scene, out, A, m, half, th); }
+ }
+
+ function buildArenaBody(scene, out, A, m, half, th) {
// floor
- const floor = new T.Mesh(new T.PlaneGeometry(half * 2, half * 2), new T.MeshStandardMaterial({ map: floorTex(), metalness: 0.55, roughness: 0.62 }));
+ const floor = new T.Mesh(new T.PlaneGeometry(half * 2, half * 2), new T.MeshStandardMaterial({ map: floorTex(A), metalness: 0.55, roughness: 0.62 }));
floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
const outer = new T.Mesh(new T.PlaneGeometry(80, 80), new T.MeshStandardMaterial({ color: 0x0d0f13, roughness: 1 }));
outer.rotation.x = -Math.PI / 2; outer.position.y = -0.02; outer.receiveShadow = true; scene.add(outer);
// spike walls (instanced spikes)
const wallMat = new T.MeshStandardMaterial({ color: 0x30343b, metalness: 0.7, roughness: 0.45 });
+ // ComfyGen wall panels (tex_wall.jpg) on the arena walls, if the browser lets the image into WebGL
+ const panelMat = new T.MeshStandardMaterial({ color: 0x30343b, metalness: 0.6, roughness: 0.5 });
+ loadTex('tex_wall.jpg', tex => { tex.wrapS = T.RepeatWrapping; tex.repeat.set(5, 1); panelMat.map = tex; panelMat.color.set(0xb0b4bc); panelMat.needsUpdate = true; });
const n = Math.round(half * 2 / 0.5);
const spikes = new T.InstancedMesh(new T.ConeGeometry(0.07, 0.28, 8), m.steel, n * 4);
const dm = new T.Object3D(); let si = 0;
for (const [nx, nz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
- const wall = box(nz ? half * 2 + 0.5 : 0.25, 0.55, nz ? 0.25 : half * 2 + 0.5, wallMat);
+ const wall = box(nz ? half * 2 + 0.5 : 0.25, 0.55, nz ? 0.25 : half * 2 + 0.5, panelMat);
wall.position.set(nx * (half + 0.12), 0.275, nz * (half + 0.12)); scene.add(wall);
const strip = box(nz ? half * 2 + 0.5 : 0.26, 0.08, nz ? 0.26 : half * 2 + 0.5, m.stripe);
strip.position.set(nx * (half + 0.12), 0.58, nz * (half + 0.12)); scene.add(strip);
@@ -522,11 +622,6 @@
const l = new T.Mesh(new T.SphereGeometry(0.09, 10, 6), new T.MeshStandardMaterial({ color: 0x400000, emissive: 0xff1a1a, emissiveIntensity: 0 }));
l.position.set(pit.x + sx * (pit.hw + 0.12), 0.08, pit.z + sz * (pit.hd + 0.12)); scene.add(l); return l;
});
- // rockets
- out.rocketGeo = new T.CylinderGeometry(0.05, 0.05, 0.32, 8); out.rocketGeo.rotateZ(Math.PI / 2);
- out.rocketMat = new T.MeshStandardMaterial({ color: 0xdddddd, emissive: 0x331100 });
- out.rocketMeshes = [];
- return out;
}
// ---------------------------------------------------------------- garage
@@ -550,6 +645,8 @@
}
// ---------------------------------------------------------------- view
+ RC.buildRobotModel = buildRobot;
+
RC.Render = function (canvas, W, H) {
const renderer = new T.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setClearColor(0x000000, 0);
@@ -567,9 +664,18 @@
const smoke = Particles(arenaScene, 300, 34, false, tex);
const fire = Particles(arenaScene, 300, 18, true, tex);
- const VIEW = 15.4, asp = W / H;
- const cam = new T.OrthographicCamera(-VIEW * asp / 2, VIEW * asp / 2, VIEW / 2, -VIEW / 2, 0.1, 120);
+ const asp = W / H;
+ const cam = new T.OrthographicCamera(-1, 1, 1, -1, 0.1, 200);
const camBase = new T.Vector3(15.2, 15.5, 15.2), camLook = new T.Vector3(-1.25, 0, -1.25);
+ // fit the orthographic camera to an arena of half-size h
+ function fitCam(h) {
+ const VIEW = h * 1.95;
+ cam.left = -VIEW * asp / 2; cam.right = VIEW * asp / 2; cam.top = VIEW / 2; cam.bottom = -VIEW / 2;
+ cam.updateProjectionMatrix();
+ const d = h * 1.9;
+ camBase.set(d, h * 1.95, d); camLook.set(-h * 0.16, 0, -h * 0.16);
+ }
+ fitCam(RC.ARENA.half);
cam.position.copy(camBase); cam.lookAt(camLook);
const gcam = new T.PerspectiveCamera(34, asp, 0.1, 60);
gcam.position.set(3.7, 2.5, 4.4); gcam.lookAt(0, 0.3, 0);
@@ -578,7 +684,7 @@
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;
- let quality = 'high', fxMul = 1;
+ let quality = 'high', fxMul = 1, camMode = 'iso', chaseInit = false;
const PX = [6, 34, 18], WORLD = [0.07, 0.7, 0.32]; // particle sizes: ortho px / perspective m
const pointMode = persp => [sparks, smoke, fire].forEach((p, i) => { p.pts.material.size = persp ? WORLD[i] : PX[i]; });
@@ -602,7 +708,7 @@
},
// intro fly-over, then a slow orbit behind the title screen; skip() jumps to the orbit
showIntro(builds, paints) {
- api.showArena(RC.Combat.create({ robots: builds.map(b => RC.stats(b)), seed: 3 }), builds, paints);
+ api.showArena(RC.Combat.create({ robots: builds.map(b => RC.stats(b)), seed: 3, arena: 'workshop' }), builds, paints);
mode = 'intro'; introT = 0; pointMode(true);
},
skipIntro() { if (mode === 'intro' && introT < INTRO_END) introT = INTRO_END; },
@@ -625,9 +731,28 @@
// turntable angle that points the robot's side (+z = right) at the camera
garage.turntable.rotation.y = Math.atan2(gcam.position.x, gcam.position.z) + a; hold = 1e9;
},
+ portrait(build, paint) {
+ api.showGarage(build, paint);
+ garage.turntable.rotation.y = 0.55;
+ gcam.clearViewOffset(); gcam.position.set(1.75, 1.3, 2.1); gcam.lookAt(0, 0.4, 0);
+ renderer.render(garageScene, gcam);
+ let url = '';
+ try { url = canvas.toDataURL('image/png'); } catch (e) { /* tainted canvas: no picture */ }
+ gcam.setViewOffset(W, H, 300, 40, W, H); api.paintCam(false);
+ return url;
+ },
paintCam(on) { gcam.position.set(on ? 2.6 : 3.7, on ? 2.2 : 2.5, on ? 3.1 : 4.4); gcam.lookAt(0, 0.3, 0); },
+ // rebuild the arena scene if the fight uses a different one; rescale the camera
+ setArena(A) {
+ if (!A || arena.id === A.id) { if (A) fitCam(A.half); return; }
+ RC.setArena(A.id);
+ robots.forEach(R => arenaScene.remove(R.root)); robots = [];
+ buildArenaGeo(arena, A);
+ fitCam(A.half);
+ },
showArena(s, builds, paints) {
- mode = 'arena'; state = s; pointMode(false); lightsOn(1);
+ api.setArena(s.arena);
+ mode = 'arena'; state = s; pointMode(camMode !== 'iso'); lightsOn(1); chaseInit = false;
for (const R of robots) arenaScene.remove(R.root);
robots = builds.map((b, i) => { const R = buildRobot(b, paints[i]); arenaScene.add(R.root); return R; });
sparks.clear(); smoke.clear(); fire.clear(); shake = 0;
@@ -657,8 +782,18 @@
}
}
},
+ // fight camera: 'iso' (whole arena) | 'chase' (behind robot 0) | 'fpv' (cockpit of robot 0)
+ get camMode() { return camMode; },
+ setCam(m) {
+ camMode = m; chaseInit = false;
+ pcam.fov = m === 'fpv' ? 72 : 55; pcam.updateProjectionMatrix();
+ if (mode === 'arena') pointMode(m !== 'iso');
+ if (robots[0] && robots[0].turret) robots[0].turret.visible = m !== 'fpv';
+ },
project(x, y, z) {
- const v = new T.Vector3(x, y, z).project(cam);
+ const v = new T.Vector3(x, y, z).project(mode === 'arena' && camMode !== 'iso' ? pcam : cam);
+ // 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 };
},
frame(dt, now) {
@@ -679,14 +814,40 @@
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);
const sx = (Math.random() - 0.5) * shake, sz = (Math.random() - 0.5) * shake;
- cam.position.set(camBase.x + sx, camBase.y, camBase.z + sz);
- cam.lookAt(camLook.x + sx, camLook.y, camLook.z + sz);
flashT = Math.max(0, flashT - dt * 3);
arena.flashLight.intensity = flashT * 4;
+ if (camMode !== 'iso' && state && robots[0]) {
+ followCam(dt, sx, sz);
+ renderer.render(arenaScene, pcam);
+ return;
+ }
+ cam.position.set(camBase.x + sx, camBase.y, camBase.z + sz);
+ cam.lookAt(camLook.x + sx, camLook.y, camLook.z + sz);
renderer.render(arenaScene, cam);
},
};
+ // 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();
+ 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);
+ let px, py, pz, lx, ly, lz;
+ if (camMode === 'fpv') {
+ const k = R.st.len * 0.08;
+ px = r.x + fx * k; pz = r.z + fz * k; py = Math.max(0.25, r.y) + R.top + 0.55;
+ lx = px + fx * 6; lz = pz + fz * 6; ly = py - 1.25;
+ cpos.set(px + sx * 0.3, py, pz + sz * 0.3); clook.set(lx, ly, lz);
+ } 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);
+ }
+ pcam.position.copy(cpos); pcam.lookAt(clook);
+ }
+
// ---- intro: dark arena -> floodlights flicker on -> camera sweeps up -> two robots are lowered in
const INTRO_END = RC.INTRO_END = 7.5;
const ease = u => (u < 0.5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2);
@@ -744,7 +905,7 @@
function animateArena(dt, now) {
const s = state; if (!s) return;
- const A = RC.ARENA;
+ const A = state.arena || RC.ARENA;
robots.forEach((R, i) => {
const r = s.robots[i];
poseRobot(R, r, dt);
diff --git a/game/robot.js b/game/robot.js
index b42ed3a..7458703 100644
--- a/game/robot.js
+++ b/game/robot.js
@@ -45,7 +45,7 @@
grip: wh ? wh.grip : 6,
push: wh ? wh.push : 1,
len, wid, h: ch ? ch.h : 0.42,
- rad: Math.hypot(len, wid) / 2 * 0.82,
+ rad: Math.hypot(len, wid) / 2 * 0.9, // close to the body corners so robots do not clip through each other
weapon: we, tower: to,
invertible: !!(wh && wh.invertible),
lowProfile: !!(ch && ch.lowProfile),
diff --git a/game/shop.js b/game/shop.js
index 91d6d2b..7830758 100644
--- a/game/shop.js
+++ b/game/shop.js
@@ -96,7 +96,7 @@
['armour', t('m_armour'), bar(st.reduce, 0.4, false, alt && alt.reduce), Math.round(st.reduce * 100) + '%'],
['speed', t('m_speed'), bar(st.top, 7, false, alt && alt.top), st.top.toFixed(1) + ' m/s'],
['accel', t('m_accel'), bar(st.accel, 30, false, alt && alt.accel), st.accel.toFixed(1)],
- ['turn', t('m_turn'), bar(st.turn, 3, false, alt && alt.turn), st.turn.toFixed(1)],
+ ['turn', t('m_turn'), bar(st.turn, 3.6, false, alt && alt.turn), st.turn.toFixed(1)],
].map(r => `${ico(r[0])}${r[2]}${r[3]}`).join('');
// paint
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..e15987f
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,132 @@
+{
+ "name": "robot-clash",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "robot-clash",
+ "version": "1.0.0",
+ "devDependencies": {
+ "terser": "^5.46.1"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
+ "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/source-map": {
+ "version": "0.3.11",
+ "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",
+ "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.25"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/acorn": {
+ "version": "8.19.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
+ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/buffer-from": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/commander": {
+ "version": "2.20.3",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/source-map-support": {
+ "version": "0.5.21",
+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "source-map": "^0.6.0"
+ }
+ },
+ "node_modules/terser": {
+ "version": "5.51.2",
+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz",
+ "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@jridgewell/source-map": "^0.3.3",
+ "acorn": "^8.15.0",
+ "commander": "^2.20.0",
+ "source-map-support": "~0.5.20"
+ },
+ "bin": {
+ "terser": "bin/terser"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..5db252c
--- /dev/null
+++ b/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "robot-clash",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Robot Clash - build helpers only (the game itself needs no build step).",
+ "devDependencies": {
+ "terser": "^5.46.1"
+ }
+}
diff --git a/sprite-generator/gen.cmd b/sprite-generator/gen.cmd
index b837c44..8095095 100644
--- a/sprite-generator/gen.cmd
+++ b/sprite-generator/gen.cmd
@@ -18,7 +18,14 @@ if /i "%SCRIPT%"=="generate_voice" set PY="%TOOLS%\.venv-tts\Scripts\python.exe
if /i "%SCRIPT%"=="make_voice_refs" set PY="%TOOLS%\.venv-tts\Scripts\python.exe"
set PYTHONIOENCODING=utf-8
pushd "%HERE%"
-%PY% "%TOOLS%\%SCRIPT%.py" %1 %2 %3 %4 %5 %6 %7 %8 %9
+set ARGS=
+:collect
+if "%~1"=="" goto run
+set ARGS=%ARGS% %1
+shift
+goto collect
+:run
+%PY% "%TOOLS%\%SCRIPT%.py"%ARGS%
set RC=%ERRORLEVEL%
popd
exit /b %RC%
diff --git a/sprite-generator/prompts.py b/sprite-generator/prompts.py
index d575a94..5e4fd64 100644
--- a/sprite-generator/prompts.py
+++ b/sprite-generator/prompts.py
@@ -22,8 +22,9 @@ _SCENE = "digital painting, cinematic lighting, high detail, dark industrial moo
PROMPTS = [
# app icon
- ("icon", "game app icon: a fierce armoured battle robot for arena fights, heavy riveted steel box body with a huge raised front flipper plate and a spinning saw, angry glowing orange eyes on the front armour, chunky, not a car, no windows, no arms, no legs, "
- "orange and black hazard paint, sparks flying, bold silhouette, plain solid black background"),
+ ("icon", "game app icon: a low flat wedge-shaped battle robot shaped like a steel doorstop on hidden wheels, seen from the front at an angle, "
+ "huge raised front flipper plate, two glowing orange eye lights in the armour, orange and black hazard paint, sparks flying, "
+ "bold simple silhouette, centred, plain solid black background"),
# scenes (not cut out)
("bg_workshop", f"interior of a cluttered robot workshop garage at night, workbenches with tools, welding sparks, "
@@ -85,9 +86,9 @@ PROMPTS = [
("opp_buzzkill", f"yellow and black striped robot with a big front circular saw, {_ROBOT}"),
("opp_flapjack", f"blue and white low robot with a huge flipper plate and big tyres, {_ROBOT}"),
("opp_pincer", f"red and gold heavy robot on tank tracks with hydraulic crushing jaws, {_ROBOT}"),
- ("opp_thunderclap", f"purple robot with an overhead axe hammer and a flamethrower turret, {_ROBOT}"),
+ ("opp_thunderclap", f"purple low flat armoured box robot on four wheels with a long axe arm hinged on top lying along its back and a small flamethrower nozzle turret, {_ROBOT}"),
("opp_gravedigger", f"black domed robot with green lights, tank tracks and a rocket pod turret, {_ROBOT}"),
- ("opp_overlord", f"menacing black and red domed robot with a heavy horizontal spinning bar weapon, {_ROBOT}"),
+ ("opp_overlord", f"menacing black and red round dome shell robot like an upturned wok on hidden wheels, long horizontal spinning steel bar across the front at floor height, {_ROBOT}"),
# shop mechanic (original character)
("npc_mechanic", "game character portrait, gruff middle-aged robot mechanic with welding goggles pushed up on the forehead, "
diff --git a/sprite-generator/variants.py b/sprite-generator/variants.py
new file mode 100644
index 0000000..4135b40
--- /dev/null
+++ b/sprite-generator/variants.py
@@ -0,0 +1,53 @@
+"""Robot Clash - shop images made from the real 3D parts (generate_variants.py, Flux.2 Klein + ReferenceLatent).
+
+Reference r3d_ = the part exactly as the game builds it (tools/partshots.ps1 renders them into output/).
+Flux keeps shape, proportions and viewing angle and paints it in the sprite style, so the shop picture
+matches what ends up on the robot.
+
+ ..\\tools\\partshots.ps1 3D renders -> output/r3d__raw_00001_.png
+ gen generate_variants all part images (part_)
+ gen adopt --size 192 part_
+
+VARIANTS = [(name, ref_name, prompt)]
+"""
+STYLE = (
+ "keep exactly the same object, the same shape, proportions, parts and viewing angle as the reference image; "
+ "render it as a detailed game sprite: scratched painted steel, bolts and rivets, small yellow and black hazard stripe details, "
+ "soft studio lighting, crisp edges, high detail, centred single subject, plain solid black background, no text"
+)
+
+_P = {
+ 'crate': "a plain rectangular steel robot chassis box with a raised accent strip on top",
+ 'doorstop': "a low wedge-shaped steel robot chassis, flat sloped front, hazard stripes on the flat rear deck",
+ 'bulwark': "a large heavy rectangular steel robot chassis box with a raised accent strip on top",
+ 'scarab': "a robot chassis base plate with a smooth round steel dome shell and an accent ring around the dome",
+ 'rubber': "a set of four small rubber robot wheels with steel hubs",
+ 'bigtyre': "a pair of huge chunky rubber tyres with steel hubs",
+ 'tracks': "a pair of long tank crawler tracks with round end wheels",
+ 'steel': "a U-shaped set of three plain grey riveted steel armour plates (two side plates and a rear plate)",
+ 'titan': "a U-shaped set of three light blue-grey titanium armour panels with bolts",
+ 'hardox': "a U-shaped set of three thick yellowish hardened steel wear plates with heavy bolts",
+ 'wedge': "a flat angled steel ramming wedge plate",
+ 'flipper': "a flat steel flipper plate with an accent stripe, hinged at its rear edge",
+ 'hammer': "a robot axe hammer: long steel arm on a pivot block with an axe head pointing down at the end",
+ 'saw': "a large circular saw blade on a short motor arm",
+ 'crusher': "two hydraulic crusher jaw arms side by side with sharp teeth at the tips",
+ 'spinner': "a long horizontal steel spinner bar with hardened teeth blocks at both ends on a central hub",
+ 'flamer': "a small robot turret base with a red fuel tank and a steel flamethrower nozzle",
+ 'minigun': "a small robot turret base with a housing and a rotating multi-barrel minigun",
+ 'rockets': "a small robot turret base carrying a box-shaped rocket pod with four tubes",
+}
+
+VARIANTS = [(f"part_{k}", f"r3d_{k}", v) for k, v in _P.items()]
+
+# motor + battery are not visible on the 3D robot: restyle the existing picture (reference = itself)
+_INNER = {
+ 'sparky': "a small cheap electric motor with a few wires",
+ 'hornet': "a sleek electric motor with cooling fins",
+ 'bulldog': "a massive high torque gear motor with a big gearbox",
+ 'comet': "a high speed racing electric motor with a glowing blue cooling ring",
+ 'lead': "a heavy old lead acid battery block with two terminals",
+ 'nicd': "a pack of green battery cells strapped together",
+ 'lipo': "a slim modern lithium battery stack with small charge lights",
+}
+VARIANTS += [(f"part_{k}", f"part_{k}", v) for k, v in _INNER.items()]
diff --git a/tests/online.test.js b/tests/online.test.js
new file mode 100644
index 0000000..b195275
--- /dev/null
+++ b/tests/online.test.js
@@ -0,0 +1,84 @@
+// Live test against the real Firebase project (needs network): node --experimental-eventsource tests/online.test.js
+// Creates two throw-away accounts, runs lobby -> challenge -> match -> state/input sync, then deletes everything.
+'use strict';
+const path = require('path');
+const mem = {};
+global.window = globalThis;
+global.Kit = { store: () => ({ get: (k, d) => (k in mem ? mem[k] : d), set: (k, v) => { mem[k] = v; } }), cleanName: s => String(s || '').slice(0, 20) };
+for (const f of ['parts.js', 'robot.js', 'combat.js', 'ai.js', 'net.js', 'lobby.js', 'netfight.js']) require(path.join(__dirname, '..', 'game', f));
+const RC = globalThis.RC;
+const CFG = { apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w', dbUrl: 'https://robot-clash-aa37b-default-rtdb.firebaseio.com' };
+const sleep = ms => new Promise(r => setTimeout(r, ms));
+let fails = 0;
+const ok = (c, msg) => { console.log((c ? 'ok ' : 'FAIL ') + msg); if (!c) fails++; };
+
+(async () => {
+ const stamp = Date.now();
+ const A = RC.Net(CFG), B = RC.Net(CFG);
+ ok(A.enabled, 'config accepted');
+ const ra = await A.auth.register(`rc-test-a-${stamp}@example.com`, 'test-pass-123', 'TestA');
+ const rb = await B.auth.register(`rc-test-b-${stamp}@example.com`, 'test-pass-123', 'TestB');
+ ok(ra.ok && rb.ok, `register two accounts ${ra.error || ''} ${rb.error || ''}`);
+ if (!ra.ok || !rb.ok) process.exit(1);
+ const again = RC.Net(CFG); const rl = await again.auth.login(`RC-TEST-A-${stamp}@example.com `, 'test-pass-123');
+ ok(rl.ok && again.auth.current.name === 'TestA', `login again shows the real name (${again.auth.current && again.auth.current.name}), e-mail case/space tolerant`);
+ const G = RC.Net(CFG); const rg = await G.auth.guest('GastTest');
+ ok(rg.ok && G.auth.current.guest, 'anonymous guest sign-in ' + (rg.error || ''));
+ const LG = RC.Lobby({ net: G, getProfile: () => ({ name: 'GastTest', flag: 'DE', build: RC.STARTER, paint: { body: 1, accent: 2 }, fame: 0 }) });
+ await LG.enter();
+ const wrong = await RC.Net(CFG).auth.login(`rc-test-a-${stamp}@example.com`, 'nope-nope');
+ ok(!wrong.ok, 'wrong password rejected: ' + wrong.error);
+
+ const prof = n => () => ({ name: n, flag: 'DE', build: RC.STARTER, paint: { body: 1, accent: 2 }, fame: 5 });
+ const LA = RC.Lobby({ net: A, getProfile: prof('TestA') }), LB = RC.Lobby({ net: B, getProfile: prof('TestB') });
+ let listA = [], incomingB = null, matchA = null, matchB = null;
+ LA.onList(r => { listA = r; }); LB.onIncoming(c => { incomingB = c; });
+ LA.onMatch(m => { matchA = m; }); LB.onMatch(m => { matchB = m; });
+ await LA.enter(); await LB.enter();
+ await sleep(2500);
+ ok(listA.some(r => r.uid === B.uid && r.name === 'TestB' && r.flag === 'DE'), 'A sees B in the lobby (push stream)');
+ ok(listA.some(r => r.uid === G.uid && r.name === 'GastTest'), 'A sees the anonymous guest in the lobby');
+ LG.leave();
+
+ LA.challenge(B.uid);
+ await sleep(2500);
+ ok(incomingB && incomingB.from === A.uid, 'B receives the challenge');
+ const t0 = Date.now();
+ if (incomingB) await LB.accept(A.uid);
+ while (!(matchA && matchB) && Date.now() - t0 < 12000) await sleep(100);
+ console.log(` match start took ${Date.now() - t0} ms (A ${!!matchA}, B ${!!matchB})`);
+ ok(matchA && matchB && matchA.id === matchB.id, 'both sides get the match');
+ ok(matchA && matchB && matchA.host !== matchB.host, 'exactly one host');
+ ok(matchA && matchA.opp.name === 'TestB' && matchB.opp.name === 'TestA', 'opponent data arrives');
+
+ if (matchA && matchB) {
+ const host = matchA.host ? A : B, guest = matchA.host ? B : A, id = matchA.id;
+ const mk = () => RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: matchA.seed });
+ const sH = mk(), sG = mk();
+ const nfH = RC.NetFight({ net: host, id, host: true }), nfG = RC.NetFight({ net: guest, id, host: false });
+ nfH.start(); nfG.start();
+ for (let i = 0; i < 35; i++) { nfH.idle(0.1); nfG.idle(0.1); await sleep(100); } // 3.5 s countdown like the game
+ for (let i = 0; i < 180; i++) { // 3 s real time
+ nfH.hostStep(sH, { throttle: 1, turn: 0 }, 1 / 60); sH.events.length = 0;
+ nfG.guestFrame(sG, { throttle: 1, turn: 0.5, fire: false, fire2: false }, 1 / 60);
+ await sleep(16);
+ }
+ await sleep(800);
+ nfG.guestFrame(sG, { throttle: 1, turn: 0.5, fire: false, fire2: false }, 1 / 60);
+ ok(sG.t > 1, `guest receives host snapshots (t=${sG.t.toFixed(2)})`);
+ ok(Math.abs(sG.robots[1].x - sH.robots[0].x) < 1.5, `guest sees host robot near its real place (${sG.robots[1].x.toFixed(2)} vs ${sH.robots[0].x.toFixed(2)})`);
+ ok(Math.abs(sH.robots[1].a - Math.PI) > 0.2, `host applies guest input (guest robot turned, a=${sH.robots[1].a.toFixed(2)})`);
+ ok(nfH.peerAlive && nfG.peerAlive, 'both peers alive');
+ // rules: guest must not be able to write the state, a stranger must not read the match
+ ok((await guest.db.put(`matches/${id}/state`, { seq: 1 })) === false, 'rule: guest cannot write host state');
+ nfH.stop(); nfG.stop();
+ }
+ // cleanup: lobby, match, challenge, accounts
+ LA.endMatch(); LB.endMatch(); await sleep(500); LA.leave(); LB.leave(); await sleep(800);
+ for (const n of [A, B, G]) {
+ const t = await n.token();
+ await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:delete?key=${CFG.apiKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ idToken: t }) });
+ }
+ console.log(fails ? `${fails} failure(s)` : 'all ok');
+ process.exit(fails ? 1 : 0);
+})();
diff --git a/tools/partshot.html b/tools/partshot.html
new file mode 100644
index 0000000..6a73f44
--- /dev/null
+++ b/tools/partshot.html
@@ -0,0 +1,56 @@
+
+
+partshot
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tools/partshots.ps1 b/tools/partshots.ps1
new file mode 100644
index 0000000..f9a6262
--- /dev/null
+++ b/tools/partshots.ps1
@@ -0,0 +1,26 @@
+# Renders every visible robot part (chassis, armour, wheels, weapon, tower) with tools/partshot.html
+# into sprite-generator/output/r3d__raw_00001_.png - references for the shop images:
+# .\tools\partshots.ps1 all parts
+# .\tools\partshots.ps1 flipper one part
+# Then in sprite-generator: gen generate_variants (variants.py), gen adopt --size 192 part_
+param([string[]]$Ids)
+$ErrorActionPreference = 'Stop'
+$root = Split-Path $PSScriptRoot -Parent
+$chrome = @("$env:ProgramFiles\Google\Chrome\Application\chrome.exe", "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe") |
+ Where-Object { Test-Path $_ } | Select-Object -First 1
+if (-not $chrome) { throw 'Chrome or Edge not found' }
+if (-not $Ids) {
+ $Ids = 'crate', 'doorstop', 'bulwark', 'scarab', 'rubber', 'bigtyre', 'tracks', 'steel', 'titan', 'hardox',
+ 'wedge', 'flipper', 'hammer', 'saw', 'crusher', 'spinner', 'flamer', 'minigun', 'rockets'
+}
+$out = Join-Path $root 'sprite-generator\output'
+New-Item -ItemType Directory -Force $out | Out-Null
+$profileDir = Join-Path $env:TEMP 'robotclash-partshot'
+$page = 'file:///' + ((Join-Path $root 'tools\partshot.html') -replace '\\', '/' -replace ' ', '%20')
+$ErrorActionPreference = 'Continue' # Chrome reports "bytes written" on stderr
+foreach ($id in $Ids) {
+ $png = Join-Path $out "r3d_${id}_raw_00001_.png"
+ & $chrome --headless=new --use-angle=swiftshader --enable-unsafe-swiftshader --hide-scrollbars --window-size=768,768 `
+ --virtual-time-budget=3000 --user-data-dir="$profileDir" --screenshot="$png" "${page}?id=$id&size=768" 2>&1 | Out-Null
+ if (Test-Path $png) { " r3d_$id -> $png" } else { " r3d_$id FAILED" }
+}
diff --git a/tools/uishots.ps1 b/tools/uishots.ps1
new file mode 100644
index 0000000..cd487a5
--- /dev/null
+++ b/tools/uishots.ps1
@@ -0,0 +1,27 @@
+# Layout check: screenshots of every screen (Chrome headless) into tools\shots\.
+# .\tools\uishots.ps1 desktop 1280x800
+# .\tools\uishots.ps1 -Tablet tablet landscape 1024x768 + portrait 768x1024 (touch emulation)
+param([switch]$Tablet)
+$root = Split-Path $PSScriptRoot -Parent
+$chrome = @("$env:ProgramFiles\Google\Chrome\Application\chrome.exe", "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe") |
+ Where-Object { Test-Path $_ } | Select-Object -First 1
+if (-not $chrome) { throw 'Chrome or Edge not found' }
+$out = Join-Path $PSScriptRoot 'shots'
+New-Item -ItemType Directory -Force $out | Out-Null
+$page = 'file:///' + ((Join-Path $root 'game\index.html') -replace '\\', '/' -replace ' ', '%20')
+$screens = [ordered]@{
+ title = 'title'; shop_weapon = 'play'; shop_chassis = 'play&tab=chassis'; shop_wheels = 'play&tab=wheels'; shop_tower = 'play&tab=tower'
+ paint = 'play&paint'; league = 'play&screen=league'; vs = 'play&screen=vs'; settings = 'play&screen=settings'
+ help = 'play&screen=help'; lobby = 'play&screen=lobby'; fight_fpv = 'fight=3&ff=4'; fight_iso = 'fight=3&ff=4&cam=iso'
+}
+$sizes = if ($Tablet) { @(@{n='tabL';s='1024,768'}, @{n='tabP';s='768,1024'}) } else { @(@{n='desk';s='1280,800'}) }
+foreach ($sz in $sizes) {
+ foreach ($k in $screens.Keys) {
+ $png = Join-Path $out "$($sz.n)_$k.png"
+ $cargs = @('--headless=new', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--hide-scrollbars', "--window-size=$($sz.s)",
+ '--virtual-time-budget=5000', "--user-data-dir=$env:TEMP\robotclash-uishots", "--screenshot=$png")
+ if ($Tablet) { $cargs += '--touch-events=enabled'; $cargs += '--blink-settings=primaryPointerType=2,availablePointerTypes=2,primaryHoverType=1,availableHoverTypes=1' }
+ & $chrome @cargs "${page}?$($screens[$k])" 2>&1 | Out-Null
+ " $($sz.n)_$k"
+ }
+}