big update
This commit is contained in:
11
game/ai.js
11
game/ai.js
@@ -30,11 +30,14 @@
|
||||
let hold = { throttle: 0, turn: 0, fire: false, fire2: false }, wait = 0, stuck = 0, unstick = 0, contact = 0, retreat = 0, wob = rand() * 6;
|
||||
const react = 0.32 - skill * 0.26; // seconds between decisions
|
||||
|
||||
function steer(me, tx, tz, speed = 1) {
|
||||
const want = Math.atan2(tz - me.z, tx - me.x), diff = wrap(want - me.a);
|
||||
// aim=true: orient so the weapon (which may sit on the back/side) faces the target, else aim the front
|
||||
function steer(me, tx, tz, speed = 1, aim = false) {
|
||||
const mA = aim ? (me.st.mountA || 0) : 0;
|
||||
const want = wrap(Math.atan2(tz - me.z, tx - me.x) - mA), diff = wrap(want - me.a);
|
||||
const turn = clamp(diff * 2.2, -1, 1);
|
||||
const ad = Math.abs(diff);
|
||||
const throttle = ad < 0.5 ? speed : ad < 1.4 ? speed * 0.45 : ad > 2.6 && Math.hypot(tx - me.x, tz - me.z) < 2 ? -0.6 : 0.1;
|
||||
const dir = Math.cos(mA) < -0.5 ? -1 : 1; // rear-mounted weapon: reverse to bring it onto the enemy
|
||||
const throttle = (ad < 0.5 ? speed : ad < 1.4 ? speed * 0.45 : ad > 2.6 && Math.hypot(tx - me.x, tz - me.z) < 2 ? -0.6 : 0.1) * dir;
|
||||
return { turn, throttle };
|
||||
}
|
||||
|
||||
@@ -64,7 +67,7 @@
|
||||
} else if (style === 'gunner' && t) { // face the enemy (fixed turret), hold the range
|
||||
tx = e.x; tz = e.z;
|
||||
}
|
||||
let cmd = steer(me, tx, tz, 0.75 + skill * 0.25);
|
||||
let cmd = steer(me, tx, tz, 0.75 + skill * 0.25, style !== 'pusher');
|
||||
// gunner too close: back off but keep the nose (and the turret) on the enemy
|
||||
if (style === 'gunner' && t && dist < ((t.type === 'flamer' || t.type === 'zapper') ? 1.4 : 2.8)) cmd = { turn: cmd.turn, throttle: -0.7 };
|
||||
|
||||
|
||||
BIN
game/assets/Sprites/part_orb.png
Normal file
BIN
game/assets/Sprites/part_orb.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
BIN
game/assets/Sprites/part_pico.png
Normal file
BIN
game/assets/Sprites/part_pico.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
game/assets/Sprites/part_slab.png
Normal file
BIN
game/assets/Sprites/part_slab.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
game/assets/Sprites/part_titandrive.png
Normal file
BIN
game/assets/Sprites/part_titandrive.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
BIN
game/assets/Sprites/part_tower.png
Normal file
BIN
game/assets/Sprites/part_tower.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
BIN
game/assets/Sprites/part_turbine.png
Normal file
BIN
game/assets/Sprites/part_turbine.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
52
game/cloudsave.js
Normal file
52
game/cloudsave.js
Normal file
@@ -0,0 +1,52 @@
|
||||
/* Robot Clash - cloud save for registered accounts (no DOM). Needs net.js.
|
||||
|
||||
The whole save still lives in localStorage (fast cache); for a real e-mail account it is also mirrored to
|
||||
Firebase RTDB at saves/<uid> so it survives a device change and is harder to fake than localStorage.
|
||||
Honest limit: the owner can still write their own node - rules only cap ranges. No hard copy protection.
|
||||
|
||||
const cloud = RC.CloudSave(net);
|
||||
cloud.pull(uid) -> the cloud save object, or null (best effort, never throws)
|
||||
cloud.push(uid, save) -> debounced write (~2.5 s after the last change)
|
||||
cloud.flush(uid, save) -> write now (fight result, leaving garage, logout, unload)
|
||||
RC.CloudSave.newer(cloud, local) -> true if the cloud copy should win (by ts) */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || {});
|
||||
|
||||
// cloud wins when it is at least as new as local (shared copy is the source once it exists)
|
||||
function newer(cloud, local) {
|
||||
if (!cloud || typeof cloud !== 'object') return false;
|
||||
const ct = +cloud.ts || 0, lt = (local && +local.ts) || 0;
|
||||
return ct >= lt;
|
||||
}
|
||||
|
||||
RC.CloudSave = function (net) {
|
||||
let timer = null, sending = false, pending = null, pendingUid = null;
|
||||
const clone = s => { try { return JSON.parse(JSON.stringify(s)); } catch (e) { return null; } };
|
||||
|
||||
async function write(uid, save) {
|
||||
sending = true;
|
||||
try { await net.db.put('saves/' + uid, save); } catch (e) { /* best effort */ }
|
||||
sending = false;
|
||||
if (pending) { const s = pending, u = pendingUid; pending = null; pendingUid = null; write(u, s); }
|
||||
}
|
||||
function doPush(uid, save) {
|
||||
if (!net || !net.enabled || !uid || !save) return;
|
||||
if (sending) { pending = save; pendingUid = uid; return; } // one request at a time; keep only the latest
|
||||
write(uid, save);
|
||||
}
|
||||
|
||||
return {
|
||||
newer,
|
||||
async pull(uid) {
|
||||
if (!net || !net.enabled || !uid) return null;
|
||||
try { return await net.db.get('saves/' + uid); } catch (e) { return null; }
|
||||
},
|
||||
push(uid, save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(uid, snap), 2500); },
|
||||
flush(uid, save) { clearTimeout(timer); doPush(uid, clone(save)); },
|
||||
};
|
||||
};
|
||||
RC.CloudSave.newer = newer;
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
170
game/combat.js
170
game/combat.js
@@ -141,6 +141,9 @@
|
||||
g3: false, // last gadget button state (for one-shot gadgets)
|
||||
cd: 0, cd2: 0, spin: 0, swing: 0, flipAnim: 0, boost: 0, sawOn: false, flameOn: false, gunOn: false,
|
||||
turretA: p.a, dealt: 0, taken: 0, pressT: 0, craneT: 0, fx: 0,
|
||||
// per-weapon runtime (one entry per mounted weapon) + per-weapon broken flag
|
||||
W: (st.weapons || []).map(() => ({ cd: 0, spin: 0, swing: 0, grab: 0, fx: 0, flipAnim: 0, sawOn: false, fire: 0 })),
|
||||
lostW: (st.weapons || []).map(() => false),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -158,38 +161,58 @@
|
||||
}
|
||||
|
||||
// a part that broke off no longer works (and bare metal takes more damage)
|
||||
const weaponOf = r => (r.lost.weapon ? null : r.st.weapon);
|
||||
const weaponOf = r => (r.lostW && r.lostW[0] ? null : (r.st.weapons && r.st.weapons[0] && r.st.weapons[0].part) || null);
|
||||
const towerOf = r => (r.lost.tower ? null : r.st.tower);
|
||||
const reduceOf = r => (r.lost.armour ? r.st.reduce * 0.3 : r.st.reduce);
|
||||
|
||||
// battle damage: at these shares of health the next hit tears a part off (no randomness,
|
||||
// so both sides of an online fight and the tests see exactly the same thing)
|
||||
const BREAK_AT = [['armour', 0.6], ['wheels', 0.4], ['weapon', 0.25], ['tower', 0.18]];
|
||||
const BREAK_AT = [['armour', 0.6], ['wheels', 0.4], ['tower', 0.18]];
|
||||
const WEAPON_BREAK = [0.25, 0.17, 0.11]; // weapons tear off one by one as health drops
|
||||
function breakCheck(s, r) {
|
||||
if (r.dead || r.out) return;
|
||||
const f = r.hp / r.maxHp;
|
||||
for (const [part, at] of BREAK_AT) {
|
||||
if (r.lost[part] || f >= at) continue;
|
||||
if (part === 'armour' && !r.st.armour) continue;
|
||||
if (part === 'weapon' && !r.st.weapon) continue;
|
||||
if (part === 'tower' && !r.st.tower) continue;
|
||||
r.lost[part] = true;
|
||||
if (part === 'weapon') { r.spin = 0; r.swing = 0; if (r.grab > 0) release(s, r, s.robots[1 - r.i]); }
|
||||
s.events.push({ type: 'broke', who: r.i, part, x: r.x, z: r.z });
|
||||
}
|
||||
const list = r.st.weapons || [];
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (r.lostW[i] || f >= (WEAPON_BREAK[i] || 0.1)) continue;
|
||||
r.lostW[i] = true;
|
||||
const W = r.W[i]; W.spin = 0; W.swing = 0; if (W.grab > 0) release(s, r, s.robots[1 - r.i], i);
|
||||
s.events.push({ type: 'broke', who: r.i, part: 'weapon' + i, x: r.x, z: r.z });
|
||||
}
|
||||
}
|
||||
|
||||
const fwd = r => [Math.cos(r.a), Math.sin(r.a)];
|
||||
// enemy position in my frame: [forward, side]
|
||||
function local(me, e) {
|
||||
const dx = e.x - me.x, dz = e.z - me.z, c = Math.cos(me.a), sn = Math.sin(me.a);
|
||||
// direction weapon i points: robot forward turned by that weapon's mount angle (front 0, back pi, sides +-pi/2)
|
||||
const wdirI = (r, i) => { const m = r.st.weapons[i], a = r.a + (m ? m.mountA : 0); return [Math.cos(a), Math.sin(a)]; };
|
||||
const alongI = (r, i) => { const m = r.st.weapons[i]; return ((m && m.mountAxis === 'wid') ? r.st.wid : r.st.len) / 2; }; // body half-extent toward weapon i
|
||||
const wdir = r => wdirI(r, 0); // lead weapon (ram bonus, compat)
|
||||
// enemy position in my frame about angle `a`: [along, side]
|
||||
function localAt(me, e, a) {
|
||||
const dx = e.x - me.x, dz = e.z - me.z, c = Math.cos(a), sn = Math.sin(a);
|
||||
return [dx * c + dz * sn, -dx * sn + dz * c];
|
||||
}
|
||||
function inZone(s, me, e, extra = 0) {
|
||||
function local(me, e) { return localAt(me, e, me.a); }
|
||||
// is the enemy inside weapon i's reach (reach runs along that weapon's mounted axis)?
|
||||
function inZoneI(s, me, e, i, extra = 0) {
|
||||
if (e.out || me.out) return false;
|
||||
const w = weaponOf(me); if (!w) return false;
|
||||
const [lf, ls] = local(me, e);
|
||||
return lf > 0 && lf < me.st.len / 2 + w.reach + e.st.rad * 0.75 + extra && Math.abs(ls) < me.st.wid / 2 + e.st.rad * 0.55;
|
||||
const m = me.st.weapons[i]; if (!m || (me.lostW && me.lostW[i])) return false;
|
||||
const [lf, ls] = localAt(me, e, me.a + m.mountA);
|
||||
const along = (m.mountAxis === 'wid' ? me.st.wid : me.st.len) / 2;
|
||||
const perp = (m.mountAxis === 'wid' ? me.st.len : me.st.wid) / 2;
|
||||
return lf > 0 && lf < along + m.part.reach + e.st.rad * 0.75 + extra && Math.abs(ls) < perp + e.st.rad * 0.55;
|
||||
}
|
||||
// any weapon in range (AI fire decision, player weapon-assist)
|
||||
function inZone(s, me, e, extra = 0) {
|
||||
const list = me.st.weapons || [];
|
||||
for (let i = 0; i < list.length; i++) if (inZoneI(s, me, e, i, extra)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// where on the target the hit lands: front 0.8 (+chassis front armour), side 1, rear 1.3
|
||||
@@ -256,8 +279,8 @@
|
||||
}
|
||||
|
||||
function drive(s, r, e, inp, dt) {
|
||||
r.cd = Math.max(0, r.cd - dt); r.cd2 = Math.max(0, r.cd2 - dt);
|
||||
r.stun = Math.max(0, r.stun - dt); r.boost = Math.max(0, r.boost - dt); r.flipAnim = Math.max(0, r.flipAnim - dt);
|
||||
r.cd2 = Math.max(0, r.cd2 - dt);
|
||||
r.stun = Math.max(0, r.stun - dt); r.boost = Math.max(0, r.boost - dt);
|
||||
if (r.out) { r.fall += dt; r.y -= dt * (1 + r.fall * 6); return; }
|
||||
if (r.flipped > 0) {
|
||||
r.flipped -= dt;
|
||||
@@ -272,7 +295,7 @@
|
||||
const thr = clamp(inp.throttle || 0, -1, 1), trn = clamp(inp.turn || 0, -1, 1);
|
||||
const hurt = r.lost.wheels ? 0.75 : 1; // burst wheel: slower, clumsier
|
||||
const oil = r.onOil ? 0.55 : 1; // oil slick: hardly any steering
|
||||
let top = st.top * hurt * (r.boost > 0 ? 1.65 : 1) * (r.grab > 0 ? 0.6 : 1) * (thr < 0 ? 0.75 : 1);
|
||||
let top = st.top * hurt * (r.boost > 0 ? 1.65 : 1) * (grabbing(r) ? 0.6 : 1) * (thr < 0 ? 0.75 : 1);
|
||||
const target = thr * top, acc = st.accel * (r.lost.wheels ? 0.85 : 1) * (r.boost > 0 ? 2 : 1);
|
||||
const braking = Math.abs(target) < Math.abs(vf) || target * vf < 0;
|
||||
const rate = acc * (braking ? 1.6 : 1) * dt;
|
||||
@@ -352,9 +375,9 @@
|
||||
const impact = -vrel;
|
||||
if (impact < 1.2) return;
|
||||
s.events.push({ type: 'bump', x: (a.x + b.x) / 2, z: (a.z + b.z) / 2, speed: impact });
|
||||
// ramming: the robot whose front drives into the other does the damage
|
||||
// ramming: the robot whose weapon side drives into the other does the damage
|
||||
for (const [me, e, sx, sz] of [[a, b, nx, nz], [b, a, -nx, -nz]]) {
|
||||
const [fx, fz] = fwd(me);
|
||||
const [fx, fz] = wdir(me);
|
||||
const facing = fx * sx + fz * sz;
|
||||
const myV = me.vx * sx + me.vz * sz;
|
||||
if (facing > 0.55 && myV > 1.2) {
|
||||
@@ -374,36 +397,49 @@
|
||||
}
|
||||
}
|
||||
|
||||
// each mounted weapon runs its own logic with its own state (r.W[i]) and mount direction
|
||||
function weapons(s, r, e, inp, dt) {
|
||||
r.sawOn = false; // aggregate for sound; per-weapon render flags on r.W[i]
|
||||
const list = r.st.weapons || [];
|
||||
for (let i = 0; i < list.length; i++) meleeWeapon(s, r, e, inp, dt, i);
|
||||
towerFire(s, r, e, inp, dt);
|
||||
}
|
||||
|
||||
function meleeWeapon(s, r, e, inp, dt, i) {
|
||||
const W = r.W[i];
|
||||
if (r.lostW[i]) { W.spin = 0; W.sawOn = false; return; }
|
||||
const inst = r.st.weapons[i], w = inst.part;
|
||||
const ok = !r.dead && !r.out && r.lifted <= 0 && r.grabbedBy === null && r.flipped <= 0;
|
||||
const w = weaponOf(r), [fx, fz] = fwd(r);
|
||||
r.sawOn = false; r.flameOn = false; r.gunOn = false;
|
||||
if (r.swing > 0) { // hammer comes down
|
||||
r.swing -= dt;
|
||||
if (r.swing <= 0 && ok) {
|
||||
s.events.push({ type: 'smash', who: r.i, x: r.x + fx * (r.st.len / 2 + 0.6), z: r.z + fz * (r.st.len / 2 + 0.6) });
|
||||
if (inZone(s, r, e, 0.15)) { damage(s, e, w.dmg, r, { pierce: 0.5, noZone: true, kind: 'smash' }); e.stun = Math.max(e.stun, 0.35); }
|
||||
const [fx, fz] = wdirI(r, i), reach0 = alongI(r, i);
|
||||
const inZ = (ex = 0) => inZoneI(s, r, e, i, ex);
|
||||
W.cd = Math.max(0, W.cd - dt); W.flipAnim = Math.max(0, W.flipAnim - dt); W.fire = Math.max(0, W.fire - dt);
|
||||
W.sawOn = false;
|
||||
if (W.swing > 0) { // hammer comes down
|
||||
W.swing -= dt;
|
||||
if (W.swing <= 0 && ok) {
|
||||
s.events.push({ type: 'smash', who: r.i, x: r.x + fx * (reach0 + 0.6), z: r.z + fz * (reach0 + 0.6) });
|
||||
if (inZ(0.15)) { damage(s, e, w.dmg, r, { pierce: 0.5, noZone: true, kind: 'smash' }); e.stun = Math.max(e.stun, 0.35); }
|
||||
}
|
||||
}
|
||||
if (r.grab > 0) { // crusher holds the enemy
|
||||
r.grab -= dt;
|
||||
if (!ok || e.out || r.grab <= 0) release(s, r, e);
|
||||
if (W.grab > 0) { // crusher holds the enemy
|
||||
W.grab -= dt;
|
||||
if (!ok || e.out || W.grab <= 0) release(s, r, e, i);
|
||||
else {
|
||||
const d = r.st.len / 2 + e.st.rad * 0.85;
|
||||
const d = reach0 + e.st.rad * 0.85;
|
||||
e.x = r.x + fx * d; e.z = r.z + fz * d; e.vx = r.vx; e.vz = r.vz; e.y = 0;
|
||||
damage(s, e, w.dps * dt, r, { kind: 'crush', tick: true });
|
||||
}
|
||||
}
|
||||
if (w && ok) {
|
||||
if (ok) {
|
||||
switch (w.type) {
|
||||
case 'wedge':
|
||||
if (inp.fire && r.cd <= 0) { r.boost = 0.8; r.cd = w.cd; s.events.push({ type: 'boost', who: r.i, x: r.x, z: r.z }); }
|
||||
if (inp.fire && W.cd <= 0) { r.boost = 0.8; W.cd = w.cd; W.fire = 0.8; s.events.push({ type: 'boost', who: r.i, x: r.x, z: r.z }); }
|
||||
break;
|
||||
case 'flipper':
|
||||
if (inp.fire && r.cd <= 0) {
|
||||
r.cd = w.cd; r.flipAnim = 0.35;
|
||||
if (inp.fire && W.cd <= 0) {
|
||||
W.cd = w.cd; W.flipAnim = 0.35;
|
||||
s.events.push({ type: 'flip', who: r.i, x: r.x + fx, z: r.z + fz });
|
||||
if (inZone(s, r, e) && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
|
||||
if (inZ() && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
|
||||
const light = Math.sqrt(70 / e.st.mass);
|
||||
e.vy = w.launch * light * (e.st.lowProfile ? 0.65 : 1);
|
||||
e.vx += fx * 3 * light; e.vz += fz * 3 * light;
|
||||
@@ -414,29 +450,29 @@
|
||||
}
|
||||
break;
|
||||
case 'hammer':
|
||||
if (inp.fire && r.cd <= 0 && r.swing <= 0) { r.swing = 0.28; r.cd = w.cd; s.events.push({ type: 'swing', who: r.i }); }
|
||||
if (inp.fire && W.cd <= 0 && W.swing <= 0) { W.swing = 0.28; W.cd = w.cd; s.events.push({ type: 'swing', who: r.i }); }
|
||||
break;
|
||||
case 'saw':
|
||||
if (inp.fire) {
|
||||
r.sawOn = true;
|
||||
if (inZone(s, r, e)) {
|
||||
W.sawOn = true; r.sawOn = true;
|
||||
if (inZ()) {
|
||||
damage(s, e, w.dps * dt, r, { kind: 'saw', tick: true });
|
||||
r.fx -= dt; if (r.fx <= 0) { r.fx = 0.06; s.events.push({ type: 'sparks', x: r.x + fx * (r.st.len / 2 + 0.3), z: r.z + fz * (r.st.len / 2 + 0.3), n: 6 }); }
|
||||
W.fx -= dt; if (W.fx <= 0) { W.fx = 0.06; s.events.push({ type: 'sparks', x: r.x + fx * (reach0 + 0.3), z: r.z + fz * (reach0 + 0.3), n: 6 }); }
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'crusher':
|
||||
if (inp.fire && r.cd <= 0 && r.grab <= 0 && inZone(s, r, e) && e.grabbedBy === null && e.y < 0.2 && e.lifted <= 0) {
|
||||
r.grab = w.hold; r.cd = w.cd; e.grabbedBy = r.i;
|
||||
if (inp.fire && W.cd <= 0 && W.grab <= 0 && inZ() && e.grabbedBy === null && e.y < 0.2 && e.lifted <= 0) {
|
||||
W.grab = w.hold; W.cd = w.cd; e.grabbedBy = r.i;
|
||||
s.events.push({ type: 'grab', who: r.i, x: e.x, z: e.z });
|
||||
}
|
||||
break;
|
||||
case 'lifter':
|
||||
// scoop: tips the enemy up again and again (short cooldown) - made for shoving into the pit
|
||||
if (inp.fire && r.cd <= 0) {
|
||||
r.cd = w.cd; r.flipAnim = 0.3;
|
||||
if (inp.fire && W.cd <= 0) {
|
||||
W.cd = w.cd; W.flipAnim = 0.3;
|
||||
s.events.push({ type: 'flip', who: r.i, x: r.x + fx, z: r.z + fz });
|
||||
if (inZone(s, r, e) && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
|
||||
if (inZ() && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
|
||||
const light = Math.sqrt(70 / e.st.mass);
|
||||
e.vy = Math.max(e.vy, w.launch * light * 0.8);
|
||||
e.vx += fx * 1.6 * light; e.vz += fz * 1.6 * light;
|
||||
@@ -447,32 +483,36 @@
|
||||
break;
|
||||
case 'vspinner':
|
||||
// vertical disc: throws the enemy into the air instead of sideways
|
||||
r.spin = inp.fire ? Math.min(1, r.spin + dt / w.spinup) : Math.max(0, r.spin - dt * 0.35);
|
||||
if (r.spin > 0.25 && r.cd <= 0 && inZone(s, r, e)) {
|
||||
const k = r.spin, light = Math.sqrt(70 / e.st.mass);
|
||||
W.spin = inp.fire ? Math.min(1, W.spin + dt / w.spinup) : Math.max(0, W.spin - dt * 0.35);
|
||||
if (W.spin > 0.25 && W.cd <= 0 && inZ()) {
|
||||
const k = W.spin, light = Math.sqrt(70 / e.st.mass);
|
||||
damage(s, e, w.dmg * k, r, { kind: 'spin' });
|
||||
e.vy = Math.max(e.vy, 6.5 * k * light);
|
||||
e.vx += fx * 1.5 * k; e.vz += fz * 1.5 * k; e.av += 7 * k;
|
||||
if (!e.st.invertible && s.rand() < 0.5 * k * (e.st.topHeavy || 1)) e.flipped = 2.2;
|
||||
r.spin *= 0.3; r.cd = 0.35;
|
||||
W.spin *= 0.3; W.cd = 0.35;
|
||||
s.events.push({ type: 'spinhit', who: r.i, x: (r.x + e.x) / 2, z: (r.z + e.z) / 2, k });
|
||||
}
|
||||
break;
|
||||
case 'spinner':
|
||||
r.spin = inp.fire ? Math.min(1, r.spin + dt / w.spinup) : Math.max(0, r.spin - dt * 0.35);
|
||||
if (r.spin > 0.25 && r.cd <= 0 && inZone(s, r, e)) {
|
||||
const k = r.spin, light = Math.sqrt(70 / e.st.mass);
|
||||
W.spin = inp.fire ? Math.min(1, W.spin + dt / w.spinup) : Math.max(0, W.spin - dt * 0.35);
|
||||
if (W.spin > 0.25 && W.cd <= 0 && inZ()) {
|
||||
const k = W.spin, light = Math.sqrt(70 / e.st.mass);
|
||||
damage(s, e, w.dmg * k, r, { kind: 'spin' });
|
||||
e.vx += (fx * 5 + -fz * 2) * k * light; e.vz += (fz * 5 + fx * 2) * k * light;
|
||||
e.vy = Math.max(e.vy, 2.5 * k * light); e.av += 5 * k;
|
||||
r.vx -= fx * 2.5 * k; r.vz -= fz * 2.5 * k;
|
||||
r.spin *= 0.35; r.cd = 0.3;
|
||||
W.spin *= 0.35; W.cd = 0.3;
|
||||
s.events.push({ type: 'spinhit', who: r.i, x: (r.x + e.x) / 2, z: (r.z + e.z) / 2, k });
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else if (w && (w.type === 'spinner' || w.type === 'vspinner')) r.spin = Math.max(0, r.spin - dt * 0.5);
|
||||
} else if (w.type === 'spinner' || w.type === 'vspinner') W.spin = Math.max(0, W.spin - dt * 0.5);
|
||||
}
|
||||
|
||||
function towerFire(s, r, e, inp, dt) {
|
||||
r.flameOn = false; r.gunOn = false;
|
||||
const ok = !r.dead && !r.out && r.lifted <= 0 && r.grabbedBy === null && r.flipped <= 0;
|
||||
// turret is bolted facing forward: you aim it by turning the robot, it does not track the enemy
|
||||
const t = towerOf(r);
|
||||
if (!t) return;
|
||||
@@ -514,10 +554,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
function release(s, r, e) {
|
||||
r.grab = 0;
|
||||
if (e.grabbedBy === r.i) { e.grabbedBy = null; }
|
||||
function release(s, r, e, i) {
|
||||
if (i == null) { for (const W of r.W) W.grab = 0; } else if (r.W[i]) r.W[i].grab = 0;
|
||||
if (e.grabbedBy === r.i) e.grabbedBy = null;
|
||||
}
|
||||
const grabbing = r => r.W.some(W => W.grab > 0); // is any of my weapons holding the enemy?
|
||||
|
||||
// gadgets (input.fire3): one-shot abilities on a cooldown
|
||||
function gadgets(s, r, e, inp, dt) {
|
||||
@@ -674,7 +715,7 @@
|
||||
s.events.push({ type: 'pit', who: r.i, x: r.x, z: r.z });
|
||||
const other = R[1 - r.i];
|
||||
if (other.grabbedBy === r.i) other.grabbedBy = null;
|
||||
if (r.grab > 0) release(s, r, other);
|
||||
if (grabbing(r)) release(s, r, other);
|
||||
finish(s, 1 - r.i, 'pit');
|
||||
}
|
||||
r.pressT = inRect(A.press, r.x, r.z) && ground ? r.pressT + dt : 0;
|
||||
@@ -702,7 +743,7 @@
|
||||
c.t -= dt;
|
||||
if (c.st === 'idle') {
|
||||
c.x += (A.crane.x - c.x) * Math.min(1, dt * 2); c.z += (A.crane.z - c.z) * Math.min(1, dt * 2);
|
||||
const r = R.find(q => q.craneT > 0.8 && !q.out && !q.dead && q.grab <= 0);
|
||||
const r = R.find(q => q.craneT > 0.8 && !q.out && !q.dead && !grabbing(q));
|
||||
if (r && c.t <= 0) {
|
||||
c.st = 'lift'; c.t = 0.6; c.who = r.i; r.lifted = 1; r.vx = r.vz = 0;
|
||||
const toPit = s.pitOpen >= 1 && s.rand() < 0.35;
|
||||
@@ -731,19 +772,20 @@
|
||||
// p = share of the cooldown still running (1 = just used, 0 = ready), on = doing its thing right now,
|
||||
// n = charges left where a part has them (repair kit).
|
||||
function cooldowns(r) {
|
||||
const out = [], w = r.st.weapon, t = r.st.tower, g = r.st.gadget;
|
||||
const out = [], t = r.st.tower, g = r.st.gadget;
|
||||
const broke = k => (r.lost && r.lost[k]) || false;
|
||||
const frac = (left, full) => (full > 0 ? clamp(left / full, 0, 1) : 0);
|
||||
if (w) {
|
||||
const e = { slot: 'weapon', id: w.id, p: 0, on: false, broke: broke('weapon') };
|
||||
if (w.type === 'saw') e.on = !!r.sawOn;
|
||||
else if (w.type === 'spinner' || w.type === 'vspinner') { e.p = 1 - clamp(r.spin, 0, 1); e.on = r.spin > 0.25; }
|
||||
(r.st.weapons || []).forEach((inst, i) => {
|
||||
const w = inst.part, W = r.W[i];
|
||||
const c = { slot: 'weapon', idx: i, id: w.id, p: 0, on: false, broke: !!(r.lostW && r.lostW[i]) };
|
||||
if (w.type === 'saw') c.on = !!W.sawOn;
|
||||
else if (w.type === 'spinner' || w.type === 'vspinner') { c.p = 1 - clamp(W.spin, 0, 1); c.on = W.spin > 0.25; }
|
||||
else {
|
||||
e.p = frac(r.cd, w.cd);
|
||||
e.on = (w.type === 'hammer' && r.swing > 0) || (w.type === 'crusher' && r.grab > 0) || (w.type === 'wedge' && r.boost > 0);
|
||||
c.p = frac(W.cd, w.cd);
|
||||
c.on = (w.type === 'hammer' && W.swing > 0) || (w.type === 'crusher' && W.grab > 0) || (w.type === 'wedge' && W.fire > 0);
|
||||
}
|
||||
out.push(e);
|
||||
}
|
||||
out.push(c);
|
||||
});
|
||||
if (t) {
|
||||
const e = { slot: 'tower', id: t.id, p: 0, on: false, broke: broke('tower') };
|
||||
if (t.type === 'rockets' || t.type === 'mortar' || t.type === 'swarm') e.p = frac(r.cd2, t.cd);
|
||||
|
||||
409
game/game.js
409
game/game.js
@@ -8,14 +8,12 @@
|
||||
const W = 1280, H = 720; // design size of the stage (16:9, higher res = denser UI)
|
||||
const ID = 'robotclash'; // localStorage prefix
|
||||
|
||||
// Paste the Firebase Realtime Database URL here to switch the online fame ranking on
|
||||
// (docs/firebase/README.md). Empty = offline.
|
||||
const DB_URL = 'https://robot-clash-aa37b-default-rtdb.firebaseio.com';
|
||||
// Online lobby + live PvP: paste the Web API key (Firebase console -> Project settings -> Web API key).
|
||||
// Empty key -> leaderboard still works, but no login/lobby (menu hides 'Online').
|
||||
const NET_CFG = { apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w', dbUrl: DB_URL };
|
||||
// dev/test: ?netkey=<API key> tries online without editing the file; ?online jumps to the lobby/login
|
||||
if (new URLSearchParams(location.search).get('netkey')) NET_CFG.apiKey = new URLSearchParams(location.search).get('netkey');
|
||||
// Own backend (server/): auth + saves + ranks + lobby + live PvP. Empty serverUrl = same origin as the page,
|
||||
// so when the game is served by the Node server it just works. file:// (double-click) stays offline.
|
||||
const NET_CFG = { serverUrl: '' };
|
||||
// dev/test: ?server=http://localhost:8080 points at a server on another origin; ?online jumps to login/lobby
|
||||
{ const s = new URLSearchParams(location.search).get('server'); if (s) NET_CFG.serverUrl = s; }
|
||||
const DB_URL = (NET_CFG.serverUrl || '') + '/db'; // ranking (Kit.scores) via the same server
|
||||
|
||||
// Credits (standard for every game): shown on the title screen, links open in the normal browser
|
||||
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
|
||||
@@ -42,8 +40,10 @@
|
||||
+ (BUILD ? ` · <span class="build">${BUILD}</span>` : '');
|
||||
// Soft domain lock: the published build only runs on our own site. Local file, localhost and the
|
||||
// exe always run. This stops a lazy re-upload, nothing more - the file itself can always be copied.
|
||||
const HOSTS = ['michael-media.de', 'www.michael-media.de', 'localhost', '127.0.0.1', ''];
|
||||
const HOSTS = ['localhost', '127.0.0.1', ''];
|
||||
// own hosts: any subdomain of michael-media.de (roboclash.michael-media.de) plus the Hetzner IP
|
||||
const hostOk = () => location.protocol === 'file:' || HOSTS.includes(location.hostname)
|
||||
|| /(^|\.)michael-media\.de$/.test(location.hostname) || location.hostname === '91.99.166.238'
|
||||
|| (Kit.host && Kit.host.exe) || document.documentElement.classList.contains('exe');
|
||||
|
||||
// ---------------------------------------------------------------- services
|
||||
@@ -53,7 +53,7 @@
|
||||
const t = L.t;
|
||||
const store = Kit.store(ID);
|
||||
// steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach
|
||||
const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', autofire: true, cam: 'fpv', arena: 'random', quiet: false }, store.get('settings', {}));
|
||||
const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', autofire: true, cam: 'fpv', arena: 'random', quiet: false, comfort: true }, store.get('settings', {}));
|
||||
// v2: Michael found "simple" steering worse -> tank is the default again, old saved choice reset once
|
||||
// v3: fights start in first person (cockpit) -> old saved camera reset once
|
||||
if (!settings.v || settings.v < 2) settings.steer = 'tank';
|
||||
@@ -67,7 +67,7 @@
|
||||
const newSave = () => ({
|
||||
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', tutorialSeen: false, ach: {}, tour: null, cls: 'medium', leagues: null,
|
||||
paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', flag: 'XX', flagSet: false, tutorialSeen: false, ach: {}, tour: null, cls: 'medium', leagues: null,
|
||||
robots: [], active: 0, // hangar: saved robot builds; the active one mirrors build/paint/robotName
|
||||
});
|
||||
const MAX_ROBOTS = 6;
|
||||
@@ -82,7 +82,7 @@
|
||||
// the active class's league progress lives in save.beaten/season while you play,
|
||||
// and is written back to its own slot on every save (same idea as the active robot)
|
||||
const syncClass = () => { if (save && save.leagues && save.cls) save.leagues[save.cls] = { beaten: save.beaten | 0, season: save.season || 1 }; };
|
||||
const persist = () => { if (slot && save) { syncActive(); syncClass(); slot.save(save); } };
|
||||
const persist = () => { if (slot && save) { syncActive(); syncClass(); save.ts = Date.now(); slot.save(save); if (fbAcc()) cloud.push(cloudId(), save); } };
|
||||
const audio = Kit.createAudio({
|
||||
prefix: ID,
|
||||
files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_saw', 'sfx_boom', 'sfx_win', 'sfx_lose', 'music_title', 'music_garage', 'music_fight'],
|
||||
@@ -90,13 +90,26 @@
|
||||
});
|
||||
// first start (nothing saved yet): start very quiet; gain is squared, so these are low
|
||||
if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35);
|
||||
const scores = Kit.scores({ url: DB_URL });
|
||||
const scores = Kit.scores({ url: DB_URL }); // legacy (Firebase-only, disabled on the own server)
|
||||
const DEV = new URLSearchParams(location.search);
|
||||
if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop
|
||||
const net = RC.Net(NET_CFG);
|
||||
const rank = RC.Ranking(net); // live ranking over the own server (ranks/<uid> + SSE)
|
||||
const rankRow = () => ({ uid: (fbAcc() && fbAcc().uid) || net.uid, name: playerName(), fame: save.fame, flag: save.flag, cls: save.cls, season: save.season });
|
||||
const cloud = RC.CloudSave(net); // mirrors a registered account's save to the server (best effort)
|
||||
// cloud path per mode: saves/<uid>/<campaign|online> - keeps the two games fully separate in the cloud too
|
||||
// (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.
|
||||
let isDev = false;
|
||||
function refreshDev() {
|
||||
if (!net.enabled || !fbAcc()) { isDev = false; return; }
|
||||
net.token().then(tk => { if (!tk) return; fetch((NET_CFG.serverUrl || '') + '/api/me?auth=' + tk).then(r => r.json()).then(d => { isDev = !!(d && d.admin); }).catch(() => {}); });
|
||||
}
|
||||
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
|
||||
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
|
||||
const lobby = net.enabled ? RC.Lobby({ net, getProfile: () => ({ name: playerName(), flag: save.flag || 'XX', build: save.build, paint: { body: save.paint.body, accent: save.paint.accent }, fame: save.fame | 0 }) }) : null;
|
||||
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 fx = Kit.fx();
|
||||
|
||||
const input = Kit.input({
|
||||
@@ -186,6 +199,16 @@
|
||||
onPaint: () => view.setPaint(paintObj()),
|
||||
onPreview: b => { if (mode === 'garage') view.showGarage(b, paintObj()); }, // show the selected part on the robot
|
||||
onHangarView: el => renderHangar(el), // Hangar tab content
|
||||
onSlot: slot => { const on = slot === 'weapon'; if (on !== editorOpen) { editorOpen = on; view.freeze(on); } if (on) view.setEditWeapon(editSel); else { const wp = $('wplace'); if (wp) wp.classList.add('hide'); } },
|
||||
onWeaponTab: () => renderWeaponEditor(), // weapon tab fills #cards with the catalog + #wplace with placement
|
||||
weaponPreview: () => { // build with the PICKED weapon added, so the warning shows before buying
|
||||
if (!save) return null;
|
||||
const weps = save.build.weapons || [];
|
||||
if (!wPrev || weps.length >= RC.MAX_WEAPONS) return null; // picking = intent to mount -> preview the added cost
|
||||
return Object.assign({}, save.build, { weapons: weps.concat([{ id: wPrev, side: 'front', up: 0 }]) });
|
||||
},
|
||||
onPaintTab: el => paintTab(el), // paint tab: 3 slots + colours + the inline painter
|
||||
onPaintLeave: () => paintLeave(),
|
||||
locked: id => LIVE.locked('parts', id), // event/unlock: part not released yet
|
||||
sfx: SFX,
|
||||
});
|
||||
@@ -204,12 +227,171 @@
|
||||
},
|
||||
onCancel: () => view.showGarage(save.build, paintObj()),
|
||||
});
|
||||
$('bPaint').onclick = () => { SFX.click(); painter.open(); view.showGarage(save.build, paintObj()); };
|
||||
// drag on the robot turns it
|
||||
let drag = null;
|
||||
$('gl').addEventListener('pointerdown', e => { if (mode === 'garage') { drag = e.clientX; $('gl').setPointerCapture(e.pointerId); } });
|
||||
$('gl').addEventListener('pointermove', e => { if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; } });
|
||||
$('gl').addEventListener('pointerup', () => { drag = null; });
|
||||
if ($('bPaint')) $('bPaint').onclick = () => { SFX.click(); painter.open(); view.showGarage(save.build, paintObj()); };
|
||||
// drag on the robot turns it; in the build editor, grab a weapon to place it instead
|
||||
let drag = null, wdrag = false, editorOpen = false, editSel = 0, wPrev = null;
|
||||
$('gl').addEventListener('pointerdown', e => {
|
||||
if (mode !== 'garage') return;
|
||||
if (editorOpen && save) {
|
||||
const hit = view.pickWeaponAt(e.clientX, e.clientY);
|
||||
if (hit >= 0) { editSel = hit; wPrev = save.build.weapons[hit] && save.build.weapons[hit].id; view.setEditWeapon(editSel); wdrag = true; $('gl').setPointerCapture(e.pointerId); renderWeaponEditor(); return; }
|
||||
}
|
||||
drag = e.clientX; $('gl').setPointerCapture(e.pointerId);
|
||||
});
|
||||
$('gl').addEventListener('pointermove', e => {
|
||||
if (wdrag) {
|
||||
const mnt = view.dragWeapon(e.clientX, e.clientY);
|
||||
if (mnt && save && save.build.weapons[editSel]) { save.build.weapons[editSel].side = mnt.side; save.build.weapons[editSel].up = mnt.up; }
|
||||
return;
|
||||
}
|
||||
if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; }
|
||||
});
|
||||
$('gl').addEventListener('pointerup', () => { if (wdrag) { wdrag = false; persist(); refreshEditorRobot(); renderWeaponEditor(); } drag = null; });
|
||||
addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } });
|
||||
|
||||
// ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ----
|
||||
function refreshEditorRobot() { view.showGarage(save.build, paintObj()); view.freeze(true); view.setEditWeapon(editSel); }
|
||||
function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor
|
||||
|
||||
// weapon detail chips (mirrors the shop's part chips, weapon stats only)
|
||||
function wChips(p) {
|
||||
const s = [];
|
||||
if (p.dmg) s.push(`<span>${t('st_dmg', { n: p.dmg })}</span>`);
|
||||
if (p.dps) s.push(`<span>${t('st_dps', { n: p.dps })}</span>`);
|
||||
if (p.range) s.push(`<span>${t('st_range', { n: p.range })}</span>`);
|
||||
s.push(`<span class="key">⌨ ${t('hk_weapon')}</span>`);
|
||||
s.push(`<span>⚖️ ${p.weight} kg</span>`);
|
||||
if (p.power) s.push(`<span>⚡ ${p.power}</span>`);
|
||||
return s.join('');
|
||||
}
|
||||
// show the clicked weapon live on the robot (a mounted one, else a temporary front preview)
|
||||
function previewWeapon(id) {
|
||||
const weps = save.build.weapons || [];
|
||||
const idx = weps.findIndex(w => w.id === id);
|
||||
if (idx >= 0) { editSel = idx; refreshEditorRobot(); }
|
||||
else {
|
||||
const pv = Object.assign({}, save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) });
|
||||
view.showGarage(pv, paintObj()); view.freeze(true); view.setEditWeapon(weps.length);
|
||||
}
|
||||
}
|
||||
function renderWeaponEditor() {
|
||||
const cards = $('cards'), wp = $('wplace'); if (!save || !cards) return;
|
||||
const b = save.build, weps = b.weapons || [];
|
||||
editSel = Math.min(editSel, Math.max(0, weps.length - 1));
|
||||
const cat = RC.partsFor('weapon');
|
||||
const canAdd = weps.length < RC.MAX_WEAPONS;
|
||||
if (!wPrev || !RC.PARTS[wPrev]) wPrev = (weps[editSel] && weps[editSel].id) || cat[0].id;
|
||||
// right (#cards): the weapon catalog, same card grid as the other slots — click = preview
|
||||
cards.className = '';
|
||||
cards.innerHTML = cat.map(p => {
|
||||
const mounted = weps.filter(w => w.id === p.id).length;
|
||||
const badge = mounted ? `<span class="badge own">×${mounted}</span>` : '';
|
||||
const price = `<div class="pr ${save.money < p.cost ? 'no' : ''}">🪙 ${Kit.fmt(p.cost)}</div>`;
|
||||
return `<div class="item ${p.id === wPrev ? 'sel' : ''}" data-prev="${p.id}">${badge}${RC.pic('part_' + p.id, GLYPH_SLOT.weapon)}<div class="nm">${p.name}</div>${price}</div>`;
|
||||
}).join('');
|
||||
cards.querySelectorAll('[data-prev]').forEach(x => x.onclick = () => { wPrev = x.dataset.prev; SFX.click(); previewWeapon(wPrev); renderWeaponEditor(); });
|
||||
// detail panel: previewed weapon + Montieren / Entfernen (like the other slots)
|
||||
const dp = $('detail'), pv = RC.PARTS[wPrev];
|
||||
if (dp && pv) {
|
||||
const mounted = weps.filter(w => w.id === wPrev).length, poor = save.money < pv.cost;
|
||||
let act = `<button class="primary" data-wact="add" ${(!canAdd || poor) ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(pv.cost) })}</button>`;
|
||||
if (mounted) act += `<button data-wact="rem">${t('sell', { n: Kit.fmt(Math.round(pv.cost * 0.5)) })}</button>`;
|
||||
if (!canAdd) act += `<span class="muted">${t('ed_max', { n: RC.MAX_WEAPONS })}</span>`;
|
||||
dp.innerHTML = `${RC.pic('part_' + wPrev, GLYPH_SLOT.weapon)}
|
||||
<div><div class="nm">${pv.name}${mounted ? ` <span class="badge own">×${mounted}</span>` : ''}</div>
|
||||
<div class="ds">${t('pd_' + wPrev)}</div><div class="chips">${wChips(pv)}</div></div>
|
||||
<div class="act">${act}</div>`;
|
||||
dp.querySelectorAll('button[data-wact]').forEach(x => x.onclick = () => {
|
||||
if (x.dataset.wact === 'add') addWeapon(wPrev);
|
||||
else { const i = weps.map(w => w.id).lastIndexOf(wPrev); if (i >= 0) removeWeapon(i); }
|
||||
});
|
||||
}
|
||||
// left (#wplace): placement of the active mounted weapon + shape (no sell list)
|
||||
if (wp) {
|
||||
const sel = weps[editSel];
|
||||
const sides = [['front', t('mt_front')], ['back', t('mt_back')], ['left', t('mt_left')], ['right', t('mt_right')]];
|
||||
const srow = (key, label, lo, hi) => { const val = (b.body && b.body[key]) || 1; return `<div class="wprow"><span>${t('des_' + label)}</span><input type="range" data-body="${key}" min="${lo}" max="${hi}" step="0.05" value="${val}"><span class="dv">${Math.round(val * 100)}%</span></div>`; };
|
||||
wp.classList.remove('hide');
|
||||
wp.innerHTML =
|
||||
`<div class="wphead">${t('ed_weapons')} ${weps.length}/${RC.MAX_WEAPONS}</div>`
|
||||
+ (sel ? `<div class="wphead">${t('ed_place')} — ${RC.PARTS[sel.id].name}</div>`
|
||||
+ `<div class="wpsides">${sides.map(([k, lb]) => `<button data-side="${k}" class="${sel.side === k ? 'on' : ''}">${lb}</button>`).join('')}</div>`
|
||||
+ `<div class="wprow"><span>${t('des_height')}</span><input type="range" id="edUp" min="-0.3" max="0.6" step="0.05" value="${sel.up || 0}"><span class="dv">${Math.round(((sel.up || 0) + 0.3) / 0.9 * 100)}%</span></div>`
|
||||
: `<span class="edhint">${t('ed_noweapons')}</span>`)
|
||||
+ `<div class="wphead">${t('s_body')}</div>${srow('hx', 'height', 0.7, 1.6)}${srow('wx', 'width', 0.8, 1.4)}${srow('lx', 'length', 0.8, 1.3)}`;
|
||||
wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; sel.side = x.dataset.side; SFX.click(); reDrawEditor(); });
|
||||
if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } };
|
||||
if ($('edUp')) $('edUp').onchange = () => reDrawEditor();
|
||||
wp.querySelectorAll('[data-body]').forEach(x => {
|
||||
x.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); };
|
||||
x.onchange = () => reDrawEditor();
|
||||
});
|
||||
}
|
||||
if (weps[editSel] && weps[editSel].id === wPrev) view.setEditWeapon(editSel);
|
||||
}
|
||||
function addWeapon(id) {
|
||||
const p = RC.PARTS[id];
|
||||
if (!p || save.build.weapons.length >= RC.MAX_WEAPONS || save.money < p.cost) { SFX.deny(); return; }
|
||||
save.money -= p.cost; save.build.weapons.push({ id, side: 'front', up: 0 });
|
||||
editSel = save.build.weapons.length - 1; wPrev = id; view.setEditWeapon(editSel);
|
||||
SFX.buy(); reDrawEditor();
|
||||
}
|
||||
function removeWeapon(i) {
|
||||
const w = save.build.weapons[i]; if (!w) return;
|
||||
const p = RC.PARTS[w.id]; if (p) save.money += Math.round(p.cost * 0.5);
|
||||
save.build.weapons.splice(i, 1);
|
||||
if (editSel >= save.build.weapons.length) editSel = Math.max(0, save.build.weapons.length - 1);
|
||||
view.setEditWeapon(editSel);
|
||||
SFX.buy(); reDrawEditor();
|
||||
}
|
||||
|
||||
// ---- paint tab: 3 save slots + quick colours + the inline painter (all inside #cards) ----
|
||||
const phex = c => '#' + (c >>> 0).toString(16).padStart(6, '0');
|
||||
function paintTab(el) {
|
||||
let hdr = $('paintHdr');
|
||||
if (!hdr) { el.innerHTML = ''; hdr = document.createElement('div'); hdr.id = 'paintHdr'; hdr.className = 'phdr'; el.appendChild(hdr); }
|
||||
$('shop').classList.add('paintmode'); // hide category tabs / detail / fitted bar while painting
|
||||
renderPaintHeader(hdr);
|
||||
if (!painter.isOpen) painter.open(el); // mount the painter inline, below the header
|
||||
}
|
||||
function paintLeave() {
|
||||
$('shop').classList.remove('paintmode');
|
||||
if (!painter.isOpen) return;
|
||||
const art = painter.hasArt();
|
||||
save.paint.decal = art ? layer.toDataURL('image/png') : null; save.paint.drawn = art;
|
||||
painter.close(); persist();
|
||||
const hdr = $('paintHdr'); if (hdr) hdr.remove();
|
||||
}
|
||||
function renderPaintHeader(hdr) {
|
||||
const slots = save.paintSlots || [];
|
||||
hdr.innerHTML =
|
||||
`<div class="pslots">${slots.map((s, i) => `<div class="pslot ${i === save.paintSlot ? 'on' : ''}" data-load="${i}" style="background:${phex(s.body)}"><i class="acc" style="background:${phex(s.accent)}"></i>${s.decal ? '<span class="dmark">🖌</span>' : ''}<button class="sv" data-save="${i}">💾</button></div>`).join('')}</div>`
|
||||
+ `<div class="psec"><h4>${t('paint_body')}</h4><div class="pgrid" id="paintBody"></div></div>`
|
||||
+ `<div class="psec"><h4>${t('paint_accent')}</h4><div class="pgrid" id="paintAccent"></div></div>`
|
||||
+ `<div class="psec"><h4>${t('paint_schemes')}</h4><div class="pgrid wide" id="paintSchemes"></div></div>`;
|
||||
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
|
||||
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${save.paint[key] === c ? 'on' : ''}" data-c="${c}" style="background:${phex(c)}"></span>`).join('');
|
||||
$(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint[key] = +sw.dataset.c; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
|
||||
}
|
||||
$('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = save.paint.body === b2 && save.paint.accent === a2; return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${phex(b2)}"></i><i style="background:${phex(a2)}"></i></span>`; }).join('');
|
||||
$('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint.body = +sw.dataset.b; save.paint.accent = +sw.dataset.a; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
|
||||
hdr.querySelectorAll('[data-load]').forEach(x => x.onclick = e => { if (e.target.dataset.save) return; loadPaintSlot(+x.dataset.load); });
|
||||
hdr.querySelectorAll('[data-save]').forEach(x => x.onclick = e => { e.stopPropagation(); savePaintSlot(+x.dataset.save); });
|
||||
}
|
||||
function loadPaintSlot(i) {
|
||||
const s = save.paintSlots[i]; if (!s) return;
|
||||
save.paintSlot = i;
|
||||
save.paint.body = s.body; save.paint.accent = s.accent; save.paint.decal = s.decal || null; save.paint.drawn = !!s.drawn;
|
||||
SFX.click(); persist();
|
||||
RC.layerFromData(layer, save.paint.decal, () => { view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); });
|
||||
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
|
||||
}
|
||||
function savePaintSlot(i) {
|
||||
const art = painter.hasArt();
|
||||
save.paintSlots[i] = { body: save.paint.body, accent: save.paint.accent, decal: art ? layer.toDataURL('image/png') : (save.paint.decal || null), drawn: art || !!save.paint.drawn };
|
||||
save.paintSlot = i; SFX.buy(); persist();
|
||||
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
let mode = 'intro'; // intro | title | account | garage | league | fight | pause | result
|
||||
@@ -227,9 +409,16 @@
|
||||
function overlayEnter() { overlay.classList.add('enter'); clearTimeout(enterT); enterT = setTimeout(() => overlay.classList.remove('enter'), 220); }
|
||||
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const seasonMul = () => 1 + (save.season - 1) * 0.5;
|
||||
const weaponName = b => (b.weapon ? RC.PARTS[b.weapon].name : t('unarmed')) + (b.tower ? ' + ' + RC.PARTS[b.tower].name : '');
|
||||
const weaponName = b => { const ws = RC.weaponsOf(b); const main = ws.length ? ws[0].part.name + (ws.length > 1 ? ' ×' + ws.length : '') : t('unarmed'); return main + (b.tower ? ' + ' + RC.PARTS[b.tower].name : ''); };
|
||||
// league robots dressed like their ComfyGen portraits (looks.js)
|
||||
const oppPaint = o => (RC.LOOKS && RC.LOOKS[o.id] ? Object.assign({}, o.paint, { layer: RC.lookLayer(o.id, o.paint), drawn: true, look: RC.LOOKS[o.id] }) : o.paint);
|
||||
// decode an online opponent's own drawing (data URL) into a canvas before the arena is built, so it shows on their robot
|
||||
const oppDecalCv = (() => { const c = document.createElement('canvas'); c.width = 512; c.height = 256; return c; })();
|
||||
function prepOpp(opp, done) {
|
||||
const d = opp && opp.paint && opp.paint.decal;
|
||||
if (!d) { done(); return; }
|
||||
RC.layerFromData(oppDecalCv, d, () => { opp.paint.layer = oppDecalCv; opp.paint.drawn = true; done(); });
|
||||
}
|
||||
const fbUser = () => (net && net.enabled ? net.auth.current : null);
|
||||
const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account
|
||||
const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
|
||||
@@ -276,6 +465,9 @@
|
||||
}
|
||||
function setScreen(m) {
|
||||
if (m !== 'garage' && painter.isOpen) painter.close();
|
||||
if (mode === 'garage' && m !== 'garage') cloudFlush(); // settle the cloud save when leaving the workshop
|
||||
if (m !== 'garage' && editorOpen) { editorOpen = false; view.freeze(false); }
|
||||
if (m !== 'title' && titleRankSub) { titleRankSub.close(); titleRankSub = null; } // stop the title's live ranking
|
||||
if (m !== mode) overlayEnter();
|
||||
mode = m;
|
||||
document.body.dataset.mode = m; // CSS shows/places the HUD per screen
|
||||
@@ -352,8 +544,8 @@
|
||||
<div class="hazbar"></div>
|
||||
<div class="tmenu">${btns}</div>
|
||||
<div class="trow2"><button id="bSet">⚙ ${t('settings')}</button><button id="bHelp">${t('how_to')}</button>
|
||||
<button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>${save ? `<button id="bAch">🏅 ${t('achievements')}</button>` : ''}${scores.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}</div>
|
||||
<p class="credits">${CREDITS}</p></div></div>`;
|
||||
<button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>${save ? `<button id="bAch">🏅 ${t('achievements')}</button>` : ''}${rank.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}</div>
|
||||
<p class="credits">${CREDITS}</p></div>${rank.enabled ? `<div class="trank"><h3>🏆 ${t('ranking')} <span class="livedot">● ${t('rank_live')}</span></h3><ol id="trankList"><li class="trmuted">${t('loading')}</li></ol></div>` : ''}</div>`;
|
||||
overlay.classList.remove('hide'); overlay.classList.add('clear'); overlay.style.backgroundImage = '';
|
||||
const on = (id, f) => { const el = $(id); if (el) el.onclick = () => { SFX.click(); f(); }; };
|
||||
on('bPlay', () => enterAccount());
|
||||
@@ -368,12 +560,28 @@
|
||||
on('bAch', () => showAchievements(showTitle));
|
||||
on('bRank', () => showRanking(showTitle));
|
||||
hud();
|
||||
if (rank.enabled) startTitleRank();
|
||||
}
|
||||
// right-side live ranking on the title: names fade in from the bottom up, re-triggered on every live update
|
||||
function startTitleRank() {
|
||||
const el = $('trankList'); if (!el) return;
|
||||
if (titleRankSub) titleRankSub.close();
|
||||
titleRankSub = rank.watch(rows => {
|
||||
if (mode !== 'title') return;
|
||||
const list = $('trankList'); if (!list) return;
|
||||
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
|
||||
const r8 = rows.slice(0, 8), n = r8.length;
|
||||
list.innerHTML = n ? r8.map((r, i) => `<li class="trow ${r.key === myUid ? 'me' : ''}" style="animation-delay:${((n - 1 - i) * 0.08).toFixed(2)}s">`
|
||||
+ `<span class="trk">${i + 1}</span><span class="trf">${flagHtml(r.flag || 'XX')}</span>`
|
||||
+ `<span class="trn">${esc(r.name)}</span><span class="trv">⭐ ${Kit.fmt(r.fame)}</span></li>`).join('')
|
||||
: `<li class="trmuted">${t('no_scores')}</li>`;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- online lobby
|
||||
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker)
|
||||
let ntour = null, inNetTour = false; // live multiplayer tournament
|
||||
async function startOnline() {
|
||||
async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page)
|
||||
if (!net.enabled) return;
|
||||
if (gameMode !== 'online') { setMode('online'); if (save) { loadSave(); hud(); } } // online uses its own save
|
||||
if (!net.auth.current) {
|
||||
@@ -385,10 +593,10 @@
|
||||
lobby.enter(); onlineReady = true;
|
||||
lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); });
|
||||
lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); });
|
||||
lobby.onMatch(m => startFight({ name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }, false, false, { id: m.id, host: m.host, seed: m.seed }));
|
||||
lobby.onMatch(m => { const opp = { name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }; prepOpp(opp, () => startFight(opp, false, false, { id: m.id, host: m.host, seed: m.seed })); });
|
||||
lobby.onCancel(() => { pendingOut = null; if (mode === 'lobby') { renderLobby(); SFX.deny(); } });
|
||||
}
|
||||
showLobby();
|
||||
ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby
|
||||
}
|
||||
async function joinAnon() {
|
||||
if (!save) { accounts.guest(); loadSave(); }
|
||||
@@ -524,7 +732,7 @@
|
||||
}
|
||||
function startNetTourMatch(info) {
|
||||
const opp = { name: info.opp.name || 'Rival', build: info.opp.build, paint: info.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: info.opp.flag };
|
||||
startFight(opp, false, false, { id: info.id, host: info.host, seed: info.seed, tourney: { round: info.round, pair: info.pairIndex, oppUid: info.oppUid } });
|
||||
prepOpp(opp, () => startFight(opp, false, false, { id: info.id, host: info.host, seed: info.seed, tourney: { round: info.round, pair: info.pairIndex, oppUid: info.oppUid } }));
|
||||
}
|
||||
function endNetTourFight(res, won, me) {
|
||||
if (ntour) ntour.reportWin(F.online.tourney.round, F.online.tourney.pair, won ? net.auth.current.uid : F.online.tourney.oppUid);
|
||||
@@ -599,19 +807,40 @@
|
||||
save = slot.load();
|
||||
repairSave();
|
||||
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
|
||||
cloudPull();
|
||||
}
|
||||
// registered account: fetch the cloud save; take it if newer, else push the local copy up (first migration)
|
||||
function cloudPull() {
|
||||
const a = fbAcc(); if (!a) return;
|
||||
const id = cloudId(), m = gameMode; // this mode's cloud slot
|
||||
cloud.pull(id).then(cl => {
|
||||
const cur = fbAcc();
|
||||
if (!save || !cur || cur.uid !== a.uid || gameMode !== m) return; // account or mode changed while we waited
|
||||
if (cl && RC.CloudSave.newer(cl, save)) {
|
||||
save = cl; repairSave(); slot.save(save); hud(); shop.reset();
|
||||
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
|
||||
if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); }
|
||||
} else {
|
||||
cloud.flush(id, save);
|
||||
}
|
||||
});
|
||||
}
|
||||
function enterAccount(fresh) {
|
||||
loadSave();
|
||||
refreshDev();
|
||||
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
|
||||
if (fresh && who) save.robotName = who.name.slice(0, 18);
|
||||
persist();
|
||||
hud();
|
||||
shop.reset();
|
||||
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); startTutorial(openGarage); } else openGarage();
|
||||
ensureFlag(() => { // pick a country first, then tutorial / workshop
|
||||
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); startTutorial(openGarage); } else openGarage();
|
||||
});
|
||||
}
|
||||
// saves from older versions: missing parts, invalid ids, hangar migration
|
||||
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
|
||||
// weight classes: an older save has one league - that progress becomes the medium class
|
||||
if (!save.leagues) {
|
||||
save.leagues = { light: { beaten: 0, season: 1 },
|
||||
@@ -629,7 +858,13 @@
|
||||
}
|
||||
save.active = Kit.clamp(save.active | 0, 0, save.robots.length - 1);
|
||||
const fixBuild = b => {
|
||||
// migrate single weapon (+ Plan-10 mount) to the weapons list; then drop the old fields
|
||||
if (!Array.isArray(b.weapons)) b.weapons = RC.weaponsOf(b).map(w => ({ id: w.id, side: w.side, up: w.up }));
|
||||
delete b.weapon; delete b.mount;
|
||||
b.weapons = b.weapons.filter(w => w && RC.PARTS[w.id] && RC.PARTS[w.id].slot === 'weapon').slice(0, RC.MAX_WEAPONS);
|
||||
for (const w of b.weapons) { if (!RC.MOUNTS[w.side]) w.side = 'front'; w.up = Math.max(-0.3, Math.min(0.6, +w.up || 0)); }
|
||||
for (const sl of RC.SLOTS) {
|
||||
if (sl === 'weapon') continue;
|
||||
if (b[sl] && !RC.PARTS[b[sl]]) b[sl] = null;
|
||||
if (b[sl] && !save.owned.includes(b[sl])) save.owned.push(b[sl]);
|
||||
}
|
||||
@@ -640,6 +875,13 @@
|
||||
const a = save.robots[save.active];
|
||||
save.build = a.build; save.paint = a.paint; save.robotName = a.name;
|
||||
save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1);
|
||||
// 3 paint save slots (account-wide presets); first slot seeds from the current paint
|
||||
if (!Array.isArray(save.paintSlots) || save.paintSlots.length !== 3) {
|
||||
const base = { body: save.paint.body, accent: save.paint.accent };
|
||||
save.paintSlots = [{ ...base, decal: save.paint.decal || null, drawn: !!save.paint.drawn },
|
||||
{ ...base, decal: null, drawn: false }, { ...base, decal: null, drawn: false }];
|
||||
}
|
||||
save.paintSlot = Kit.clamp(save.paintSlot | 0, 0, 2);
|
||||
}
|
||||
// hangar: switch / add / delete robot slots (owned parts are shared)
|
||||
function switchRobot(i) {
|
||||
@@ -668,7 +910,7 @@
|
||||
}
|
||||
// hangar management (shop top-tab): list of robots with weapon, switch / delete + add button
|
||||
function renderHangar(el) {
|
||||
el = el || $('hangarView'); if (!el) return;
|
||||
el = el || $('cards'); if (!el) return;
|
||||
const rows = save.robots.map((r, i) => `<div class="hmrow ${i === save.active ? 'on' : ''}" data-i="${i}">
|
||||
<div><div class="hmn">${esc(r.name)}</div><div class="hmw">${esc(weaponName(r.build))}</div></div>
|
||||
${i === save.active ? `<span class="muted" style="font-size:12px">${t('active_robot')}</span>` : `<button data-use="${i}">${t('use')}</button>`}
|
||||
@@ -681,6 +923,7 @@
|
||||
}
|
||||
function signOut() {
|
||||
persist();
|
||||
cloudFlush(); // push now, while we still have the auth token
|
||||
if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; }
|
||||
if (ntour) { ntour.leave(); inNetTour = false; }
|
||||
if (net && net.enabled) net.auth.logout();
|
||||
@@ -708,7 +951,7 @@
|
||||
const item = (label, ctl) => `<span class="sl">${label}</span>${ctl}`;
|
||||
card(`<h2>${t('settings')}</h2><div class="set2">
|
||||
${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))}
|
||||
${item(t('s_mute'), seg('sMute', audio.muted ? '1' : '0', [['0', t('on')], ['1', t('off')]]))}
|
||||
${save ? item(t('s_country'), `<select id="sCountry" class="selset">${FLAGS.map(f => `<option value="${f}" ${f === save.flag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('')}</select>`) : ''}
|
||||
${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)}
|
||||
${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
|
||||
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
|
||||
@@ -719,6 +962,9 @@
|
||||
${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))}
|
||||
${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
|
||||
</div>
|
||||
${isDev ? `<div class="setdev"><span class="sl">🛠 Dev · Coins</span><div class="row">
|
||||
<button data-coin="10000">+10k</button><button data-coin="100000">+100k</button>
|
||||
<button data-coin="1000000">+1M</button><button data-coin="set800">Reset 800</button></div></div>` : ''}
|
||||
<div class="setacc"><span class="sl">${t('s_account')}</span>
|
||||
<span class="who">${who ? '👤 <b>' + esc(who.name) + '</b>' + (who.email ? ' <span class="muted">' + esc(who.email) + '</span>' : '') : '👤 ' + t('guest')}</span>
|
||||
${save ? `<button id="sOut">${who ? t('logout') : t('to_title')}</button>` : ''}</div>
|
||||
@@ -726,7 +972,6 @@
|
||||
${save ? `<button id="sReset">${t('reset')}</button>` : ''}<button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
|
||||
const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; });
|
||||
segOn('sLang', v => { L.set(v); showSettings(back); });
|
||||
segOn('sMute', v => { if ((v === '1') !== audio.muted) audio.toggleMute(); hud(); });
|
||||
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(); });
|
||||
@@ -734,10 +979,16 @@
|
||||
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
|
||||
segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); });
|
||||
segOn('sArena', v => { settings.arena = v; saveSettings(); });
|
||||
if ($('sCountry')) $('sCountry').onchange = e => { save.flag = e.target.value; save.flagSet = true; persist(); if (lobby) lobby.refresh(); hud(); };
|
||||
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
|
||||
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
|
||||
$('sSfx').onchange = () => SFX.click();
|
||||
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
|
||||
if (isDev && save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => {
|
||||
SFX.buy(); const v = b.dataset.coin;
|
||||
save.money = v === 'set800' ? 800 : Math.min(1e9, (save.money | 0) + (+v || 0));
|
||||
persist(); hud(); showSettings(back);
|
||||
});
|
||||
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
|
||||
if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); };
|
||||
$('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); };
|
||||
@@ -767,6 +1018,18 @@
|
||||
step();
|
||||
}
|
||||
|
||||
// first start: pick the country whose flag shows on the ranking / in the lobby (changeable later in settings)
|
||||
function chooseFlag(done) {
|
||||
overlayEnter();
|
||||
let pick = (save && FLAGS.includes(save.flag)) ? save.flag : 'XX';
|
||||
card(`<h2>🌍 ${t('country_title')}</h2><p>${t('country_text')}</p>
|
||||
<div class="flaggrid">${FLAGS.map(f => `<button class="flagbtn ${f === pick ? 'on' : ''}" data-f="${f}">${flagHtml(f)}<span>${t('cc_' + f)}</span></button>`).join('')}</div>
|
||||
<div class="row"><button class="primary" id="cfGo">${t('country_go')}</button></div>`, { bg: 'bg_title.jpg', wide: true });
|
||||
overlay.querySelectorAll('.flagbtn').forEach(b => b.onclick = () => { pick = b.dataset.f; SFX.click(); overlay.querySelectorAll('.flagbtn').forEach(x => x.classList.toggle('on', x.dataset.f === pick)); });
|
||||
$('cfGo').onclick = () => { if (save) { save.flag = pick; save.flagSet = true; persist(); } if (lobby) lobby.refresh(); SFX.click(); done(); };
|
||||
}
|
||||
const ensureFlag = done => { if (save && !save.flagSet) chooseFlag(done); else done(); };
|
||||
|
||||
// one line for the running event and one for the admin's message
|
||||
function liveBanner() {
|
||||
const out = [];
|
||||
@@ -808,11 +1071,54 @@
|
||||
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`, { bg: 'bg_title.jpg' });
|
||||
$('bOk').onclick = () => { SFX.click(); back(); };
|
||||
}
|
||||
let rankSub = null, titleRankSub = null, boardFame = {}, boardIdx = {};
|
||||
const closeRank = () => { if (rankSub) { rankSub.close(); rankSub = null; } };
|
||||
function showRanking(back) {
|
||||
overlayEnter();
|
||||
card(`<h2>🏆 ${t('ranking')}</h2><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol><div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { bg: 'bg_title.jpg' });
|
||||
$('bBack').onclick = () => { SFX.click(); back(); };
|
||||
fillBoard();
|
||||
card(`<h2>🏆 ${t('ranking')} ${rank.enabled ? '<span class="livedot">● ' + t('rank_live') + '</span>' : ''}</h2>
|
||||
<ol class="board live" id="board"><li class="muted">${t('loading')}</li></ol>
|
||||
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { bg: 'bg_title.jpg' });
|
||||
$('bBack').onclick = () => { SFX.click(); closeRank(); back(); };
|
||||
boardFame = {}; boardIdx = {};
|
||||
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
|
||||
closeRank();
|
||||
if (rank.enabled) rankSub = rank.watch(rows => drawBoard($('board'), rows, myUid));
|
||||
else drawBoard($('board'), [], myUid);
|
||||
}
|
||||
// animated live board: FLIP row reordering, fame bars, count-up numbers, rank ▲/▼
|
||||
function animNum(el, from, to) {
|
||||
if (!el) return; const t0 = performance.now(), dur = 520;
|
||||
(function step(now) {
|
||||
const k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3);
|
||||
el.textContent = Kit.fmt(Math.round(from + (to - from) * e));
|
||||
if (k < 1 && el.isConnected) requestAnimationFrame(step);
|
||||
})(t0);
|
||||
}
|
||||
function drawBoard(el, rows, myUid) {
|
||||
if (!el) return;
|
||||
if (!rows.length) { el.innerHTML = `<li class="muted">${t('no_scores')}</li>`; boardFame = {}; boardIdx = {}; return; }
|
||||
const max = Math.max(1, rows[0].fame);
|
||||
const prevTop = {};
|
||||
el.querySelectorAll('.brow').forEach(li => { prevTop[li.dataset.key] = li.getBoundingClientRect().top; });
|
||||
el.innerHTML = rows.map((r, i) => {
|
||||
const me = r.key === myUid;
|
||||
const was = boardIdx[r.key];
|
||||
const arr = (was != null && was !== i) ? (i < was ? '<span class="arrow up">▲</span>' : '<span class="arrow dn">▼</span>') : '';
|
||||
return `<li class="brow ${me ? 'me' : ''}" data-key="${r.key}" data-fame="${r.fame}">
|
||||
<span class="rk">${i + 1}</span><span class="fl">${flagHtml(r.flag || 'XX')}</span>
|
||||
<span class="nm">${esc(r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}${arr}</span>
|
||||
<span class="val"><i class="fill" style="width:${(r.fame / max * 100).toFixed(1)}%"></i><b>0</b></span></li>`;
|
||||
}).join('');
|
||||
el.querySelectorAll('.brow').forEach(li => {
|
||||
const key = li.dataset.key, to = +li.dataset.fame, from = boardFame[key] != null ? boardFame[key] : to;
|
||||
animNum(li.querySelector('.val b'), from, to); boardFame[key] = to;
|
||||
if (prevTop[key] != null) {
|
||||
const d = prevTop[key] - li.getBoundingClientRect().top;
|
||||
if (d) { li.style.transform = `translateY(${d}px)`; li.style.transition = 'none';
|
||||
requestAnimationFrame(() => { li.style.transition = 'transform .45s cubic-bezier(.2,.8,.2,1)'; li.style.transform = ''; }); }
|
||||
}
|
||||
});
|
||||
boardIdx = {}; rows.forEach((r, i) => boardIdx[r.key] = i);
|
||||
}
|
||||
function confirmReset(back) {
|
||||
card(`<h2>${t('reset')}</h2><p>${t('reset_text')}</p><div class="row"><button id="bYes">${t('reset_yes')}</button><button class="primary" id="bNo">${t('cancel')}</button></div>`);
|
||||
@@ -835,14 +1141,15 @@
|
||||
showSettings(back);
|
||||
};
|
||||
|
||||
function boardHtml() { return scores.enabled ? `<h3>${t('ranking')}</h3><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
|
||||
async function fillBoard(myKey) {
|
||||
function boardHtml() { return (rank.enabled && gameMode === 'online') ? `<h3>${t('ranking')}</h3><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
|
||||
async function fillBoard() {
|
||||
const el = $('board');
|
||||
if (!el) return;
|
||||
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
|
||||
try {
|
||||
const rows = (await scores.top(10)).filter(r => !Kit.badName(r.name));
|
||||
const rows = await rank.once(10);
|
||||
el.innerHTML = rows.length
|
||||
? rows.map((r, i) => `<li class="${r.key === myKey ? 'me' : ''}"><span>${i + 1}.</span><span class="nm">${esc(r.name)}</span><span>${Kit.fmt(r.score)}</span></li>`).join('')
|
||||
? rows.map((r, i) => `<li class="${r.key === myUid ? 'me' : ''}"><span>${i + 1}.</span><span class="nm">${esc(r.name)}</span><span>${Kit.fmt(r.fame)}</span></li>`).join('')
|
||||
: `<li class="muted">${t('no_scores')}</li>`;
|
||||
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
|
||||
}
|
||||
@@ -862,12 +1169,14 @@
|
||||
const onlineUsable = () => !!(net && net.enabled && !LIVE.onlineOff);
|
||||
if (!onlineUsable()) $('bGMode').style.display = 'none';
|
||||
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
|
||||
$('bLeague').onclick = () => { SFX.click(); if (gameMode === 'online') { persist(); startOnline(); } else showLeague(); };
|
||||
$('bLeague').onclick = () => { SFX.click(); if (gameMode === 'online') { persist(); startOnline('lobby'); } else showLeague(); };
|
||||
if ($('bRankG')) $('bRankG').onclick = () => { SFX.click(); showRanking(openGarage); };
|
||||
function updateShopBar() {
|
||||
const on = gameMode === 'online';
|
||||
$('bGMode').style.display = onlineUsable() ? '' : 'none';
|
||||
$('bGMode').textContent = on ? '🏆 ' + t('mode_campaign') : '🌍 ' + t('mode_online');
|
||||
$('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
|
||||
}
|
||||
|
||||
function applyClass(id) {
|
||||
@@ -1208,11 +1517,13 @@
|
||||
`<b class="k">${CD_KEY[c.slot]}</b>${c.n === undefined ? '' : `<b class="n">${c.n}</b>`}</div>`).join('');
|
||||
}
|
||||
// condition panel: every part that can be torn off, shown per robot and greyed out when it is gone
|
||||
const BREAKABLE = ['armour', 'wheels', 'weapon', 'tower'];
|
||||
const BREAKABLE = ['armour', 'wheels', 'tower'];
|
||||
function buildDmg(i, build) {
|
||||
const weps = (build.weapons || []).map((w, wi) =>
|
||||
`<span class="pt" data-part="weapon${wi}" title="${t('slot_weapon')}">${RC.pic('part_' + w.id, GLYPH_SLOT.weapon)}</span>`).join('');
|
||||
const icons = BREAKABLE.filter(k => build[k]).map(k =>
|
||||
`<span class="pt" data-part="${k}" title="${t('slot_' + k)}">${RC.pic('part_' + build[k], GLYPH_SLOT[k])}</span>`).join('');
|
||||
$('fD' + i).innerHTML = `<span class="hpn"></span><span class="pts">${icons}</span>`;
|
||||
$('fD' + i).innerHTML = `<span class="hpn"></span><span class="pts">${weps}${icons}</span>`;
|
||||
}
|
||||
const GLYPH_SLOT = { armour: '🛡️', wheels: '🛞', weapon: '🪓', tower: '🔥' };
|
||||
|
||||
@@ -1237,7 +1548,10 @@
|
||||
const el = $('fD' + i), hpn = el.querySelector('.hpn');
|
||||
const txt = `${Math.ceil(r.hp)}/${Math.round(r.maxHp)}`;
|
||||
if (hpn && hpn.textContent !== txt) hpn.textContent = txt;
|
||||
for (const ps of el.querySelectorAll('.pt')) ps.classList.toggle('gone', !!(r.lost && r.lost[ps.dataset.part]));
|
||||
for (const ps of el.querySelectorAll('.pt')) {
|
||||
const p = ps.dataset.part, gone = /^weapon\d/.test(p) ? !!(r.lostW && r.lostW[+p.slice(6)]) : !!(r.lost && r.lost[p]);
|
||||
ps.classList.toggle('gone', gone);
|
||||
}
|
||||
}
|
||||
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;
|
||||
@@ -1341,8 +1655,9 @@
|
||||
if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false, F.exhibition); };
|
||||
if (!F.training && save.fame > save.best) {
|
||||
save.best = save.fame; persist();
|
||||
scores.submit({ name: playerName(), score: save.fame, level: save.season }).then(fillBoard);
|
||||
} else fillBoard();
|
||||
if (gameMode === 'online') { rank.submit(rankRow()).then(fillBoard); return; } // global board = online fame only
|
||||
}
|
||||
fillBoard();
|
||||
}
|
||||
|
||||
// a tournament round: the bracket moves on, the round prize is paid, then back to the bracket
|
||||
@@ -1404,7 +1719,7 @@
|
||||
const gotAch = awardAch({ 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 });
|
||||
hud();
|
||||
if (save.fame > save.best) { save.best = save.fame; persist(); scores.submit({ name: playerName(), score: save.fame, level: save.season }); }
|
||||
if (save.fame > save.best) { save.best = save.fame; persist(); rank.submit(rankRow()); }
|
||||
const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
|
||||
setScreen('result');
|
||||
card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}</p>
|
||||
@@ -1521,7 +1836,7 @@
|
||||
}
|
||||
setMode('online'); // every page load starts in online play
|
||||
accounts.resume();
|
||||
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); if (mode === 'title') showTitle(); }); }
|
||||
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); refreshDev(); if (mode === 'title') showTitle(); }); }
|
||||
hud();
|
||||
if (!hostOk()) {
|
||||
card(`<h1>Robot Clash</h1><p>${t('wrong_host')}</p><p class="credits">${CREDITS}</p>`);
|
||||
|
||||
217
game/index.html
217
game/index.html
@@ -116,6 +116,25 @@
|
||||
.board { list-style: none; padding: 0; margin: 14px 0 0; text-align: left; font-variant-numeric: tabular-nums; max-height: 150px; overflow: auto; }
|
||||
.board li { display: flex; gap: 10px; padding: 2px 0; }
|
||||
.board li .nm { flex: 1; } .board li.me { color: var(--good); }
|
||||
/* live animated ranking board */
|
||||
.livedot { font: 12px var(--head); color: var(--good); letter-spacing: .06em; vertical-align: middle; animation: pulse 1.6s ease-in-out infinite; }
|
||||
@keyframes pulse { 50% { opacity: .35; } }
|
||||
.board.live { max-height: 340px; margin-top: 10px; }
|
||||
.board.live .brow { display: flex; align-items: center; gap: 9px; padding: 5px 8px; border-radius: 8px;
|
||||
background: var(--panel2); border: 1px solid var(--line); margin-bottom: 5px; will-change: transform; }
|
||||
.board.live .brow.me { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
|
||||
.board.live .rk { width: 22px; text-align: center; font: 14px var(--head); color: var(--dim); }
|
||||
.board.live .brow:nth-child(1) .rk { color: #f2c230; } .board.live .brow:nth-child(2) .rk { color: #cfd6e0; } .board.live .brow:nth-child(3) .rk { color: #d08a4a; }
|
||||
.board.live .fl { width: 20px; flex: none; }
|
||||
.board.live .nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.board.live .arrow { font-size: 10px; margin-left: 5px; animation: arrpop .9s ease-out; }
|
||||
.board.live .arrow.up { color: var(--good); } .board.live .arrow.dn { color: #e5593b; }
|
||||
@keyframes arrpop { 0% { transform: translateY(4px); opacity: 0; } 30% { opacity: 1; } 100% { opacity: .6; } }
|
||||
.board.live .val { position: relative; width: 108px; flex: none; display: flex; align-items: center; justify-content: flex-end;
|
||||
padding: 2px 8px; border-radius: 6px; overflow: hidden; background: #0d1016; }
|
||||
.board.live .val .fill { position: absolute; left: 0; top: 0; bottom: 0; background: linear-gradient(90deg, var(--accent), #ffb060);
|
||||
opacity: .3; transition: width .5s cubic-bezier(.2,.8,.2,1); }
|
||||
.board.live .val b { position: relative; font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.muted { color: var(--dim); font-size: 13px; }
|
||||
.row { display: flex; gap: 8px; justify-content: center; margin-top: 12px; flex-wrap: wrap; }
|
||||
.credits { margin: 14px 0 0; font-size: 12px; color: var(--dim); }
|
||||
@@ -142,6 +161,21 @@
|
||||
.trow2 { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.trow2 button { flex: 1 1 auto; font-size: 13px; min-height: 36px; padding: 4px 10px; }
|
||||
.title .credits { margin-top: 10px; }
|
||||
/* title: live ranking on the right, names fade in from the bottom up */
|
||||
.trank { position: absolute; right: 40px; top: 50%; transform: translateY(-50%); width: 300px; max-width: 36vw;
|
||||
background: rgba(12,14,19,.82); border: 1px solid var(--line); border-radius: 14px; padding: 13px 16px; box-shadow: var(--hl), 0 8px 30px #000a; }
|
||||
.trank h3 { margin: 0 0 9px; font: 15px var(--head); letter-spacing: .05em; color: var(--accent); display: flex; align-items: center; gap: 8px; }
|
||||
.trank ol { list-style: none; margin: 0; padding: 0; }
|
||||
.trank .trow { display: grid; grid-template-columns: 18px 20px 1fr auto; gap: 8px; align-items: center; padding: 5px 2px; font-size: 13px;
|
||||
font-variant-numeric: tabular-nums; border-bottom: 1px solid rgba(255,255,255,.06); opacity: 0; animation: trankin .5s ease-out both; }
|
||||
.trank .trow:last-child { border-bottom: none; }
|
||||
.trank .trow.me { color: var(--accent); font-weight: 700; }
|
||||
.trank .trk { text-align: center; color: var(--dim); font-weight: 700; }
|
||||
.trank .trow:nth-child(1) .trk { color: #f2c230; } .trank .trow:nth-child(2) .trk { color: #cfd6e0; } .trank .trow:nth-child(3) .trk { color: #d08a4a; }
|
||||
.trank .trn { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.trank .trmuted { color: var(--dim); font-size: 13px; list-style: none; }
|
||||
@keyframes trankin { from { opacity: 0; transform: translateY(18px); } to { opacity: 1; transform: translateY(0); } }
|
||||
@media (max-width: 720px) { .trank { display: none; } } /* too narrow -> hide, title stays usable */
|
||||
.skip { position: absolute; right: 16px; bottom: 12px; font-size: 12px; color: rgba(255,255,255,.55); }
|
||||
.form { width: 320px; margin: 0 auto; text-align: left; display: flex; flex-direction: column; gap: 8px; }
|
||||
.form label { font-size: 13px; color: var(--dim); }
|
||||
@@ -156,13 +190,24 @@
|
||||
.seg button { flex: 1 1 56px; padding: 5px 8px; font-size: 13px; }
|
||||
.seg button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
|
||||
/* compact settings: two columns of label + control */
|
||||
.set2 { display: grid; grid-template-columns: 96px 1fr 96px 1fr; gap: 7px 12px; align-items: center; text-align: left; min-width: 680px; }
|
||||
.set2 .sl, .setacc .sl { font-size: 13px; color: var(--dim); }
|
||||
.set2 .seg button { padding: 6px 4px; font-size: 12px; min-height: 34px; }
|
||||
.set2 input[type=range] { width: 100%; accent-color: var(--accent); height: 28px; }
|
||||
.setacc { display: grid; grid-template-columns: 96px 1fr auto; gap: 12px; align-items: center; text-align: left; margin-top: 12px;
|
||||
padding-top: 10px; border-top: 1px solid var(--line); }
|
||||
.setacc .who { font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.set2 { display: grid; grid-template-columns: 88px 1fr 88px 1fr; gap: 5px 10px; align-items: center; text-align: left; min-width: 620px; }
|
||||
.set2 .sl, .setacc .sl, .setdev .sl { font-size: 12px; color: var(--dim); }
|
||||
.setdev { display: grid; grid-template-columns: 88px 1fr; gap: 8px; align-items: center; text-align: left; margin-top: 8px;
|
||||
padding-top: 8px; border-top: 1px solid var(--line); }
|
||||
.setdev .row { display: flex; gap: 6px; } .setdev .row button { flex: 1; min-height: 34px; font-size: 12px; }
|
||||
.set2 .seg button { padding: 4px 4px; font-size: 11.5px; min-height: 34px; }
|
||||
.set2 input[type=range] { width: 100%; accent-color: var(--accent); height: 24px; }
|
||||
.setacc { display: grid; grid-template-columns: 88px 1fr auto; gap: 10px; align-items: center; text-align: left; margin-top: 8px;
|
||||
padding-top: 8px; border-top: 1px solid var(--line); }
|
||||
.setacc .who { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.selset { width: 100%; min-height: 34px; padding: 5px 8px; background: var(--panel2); color: var(--text); border: 1px solid var(--line); border-radius: 8px; font-size: 12.5px; }
|
||||
/* first-start country picker */
|
||||
.flaggrid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 12px 0 6px; }
|
||||
.flagbtn { display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 8px 4px; min-height: 48px;
|
||||
background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; cursor: pointer; color: var(--text); font-size: 12px; }
|
||||
.flagbtn .fl { width: 34px; height: 22px; }
|
||||
.flagbtn.on { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; background: rgba(255,122,26,.14); }
|
||||
@media (hover: hover) { .flagbtn:hover { border-color: var(--accent); } }
|
||||
|
||||
/* league */
|
||||
/* tournament bracket */
|
||||
@@ -204,11 +249,14 @@
|
||||
.res .plus { color: var(--good); } .res .minus { color: var(--warn); }
|
||||
|
||||
/* shop */
|
||||
#shop { position: absolute; inset: 44px 0 0; display: grid; grid-template-columns: 300px 1fr; z-index: 3; pointer-events: none; }
|
||||
#shop { position: absolute; inset: 44px 0 0; display: grid; grid-template-columns: 1fr 560px; z-index: 3; pointer-events: none; }
|
||||
#shop.hide, #fightHud.hide { display: none; }
|
||||
#shop > * { pointer-events: auto; }
|
||||
#sLeft { display: flex; flex-direction: column; padding: 12px; gap: 8px; pointer-events: none; }
|
||||
/* left grid cell = the free area left of the shop panel; robot renders centered behind it */
|
||||
#sLeft { position: relative; pointer-events: none; }
|
||||
#sLeft > * { pointer-events: auto; }
|
||||
.slTL { position: absolute; left: 14px; top: 12px; width: 230px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.slBottom { position: absolute; left: 50%; transform: translateX(-50%); bottom: 14px; width: min(96%, 660px); display: flex; flex-direction: column; align-items: center; gap: 6px; }
|
||||
/* hangar: robot slots at the top of the shop */
|
||||
.hangar { display: flex; gap: 5px; flex-wrap: wrap; margin-bottom: 4px; }
|
||||
.hslot { display: inline-flex; align-items: center; gap: 5px; padding: 4px 9px; font-size: 12px; max-width: 120px; }
|
||||
@@ -218,16 +266,17 @@
|
||||
.hslot .hdel:hover { background: rgba(0,0,0,.25); opacity: 1; }
|
||||
.hadd { padding: 4px 11px; font-size: 15px; font-weight: 700; color: var(--accent); }
|
||||
/* name plate riveted to the robot, always readable (not only on hover) */
|
||||
#rname { width: 100%; font: 20px var(--head); letter-spacing: .04em; background: rgba(11,14,20,.82);
|
||||
#rname { width: 100%; font: 18px var(--head); letter-spacing: .04em; background: rgba(11,14,20,.82);
|
||||
border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: var(--r2);
|
||||
color: var(--text); padding: 4px 10px; text-shadow: 0 2px 6px #000; box-shadow: var(--hl); }
|
||||
#rname:hover, #rname:focus { border-color: var(--accent); outline: none; }
|
||||
.mech { display: flex; gap: 8px; align-items: flex-end; }
|
||||
.mech .pic { width: 42px; height: 50px; font-size: 28px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,.35); border: 1px solid var(--line); }
|
||||
.mech .bubble { background: rgba(250,246,238,.95); color: #1b1d22; border-radius: 10px 10px 10px 2px; padding: 5px 8px; font-size: 11.5px; max-width: 210px; box-shadow: 0 4px 14px #0008; }
|
||||
.mech .bubble { background: rgba(250,246,238,.95); color: #1b1d22; border-radius: 10px 10px 10px 2px; padding: 6px 9px; font-size: 12px; line-height: 1.3; max-width: 240px; box-shadow: 0 4px 14px #0008; }
|
||||
.spacer { flex: 1; pointer-events: none !important; }
|
||||
.stats { background: rgba(12,14,19,.8); border: 1px solid var(--line); border-radius: 10px; padding: 6px 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 3px 10px; font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.stats .st { display: grid; grid-template-columns: 18px 1fr 54px; gap: 5px; align-items: center; }
|
||||
.stats { background: rgba(12,14,19,.88); border: 1px solid var(--line); border-radius: 12px; padding: 7px 12px; width: 100%;
|
||||
display: flex; flex-wrap: wrap; justify-content: center; gap: 4px 16px; font-size: 12px; font-variant-numeric: tabular-nums; box-shadow: var(--hl); }
|
||||
.stats .st { flex: 1 1 120px; display: grid; grid-template-columns: 18px 1fr 50px; gap: 6px; align-items: center; }
|
||||
.stats .st > span:last-child { text-align: right; }
|
||||
#shop.painting .mech, #shop.painting .stats { display: none; }
|
||||
.stats .pic { width: 18px; height: 18px; font-size: 16px; }
|
||||
@@ -235,11 +284,20 @@
|
||||
.bar i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
|
||||
.bar i.ghost { background: rgba(255,255,255,.35); }
|
||||
.bar i.over { background: var(--warn); }
|
||||
/* over-limit meter (weight / power) flashes so the problem is obvious at a glance */
|
||||
.st.warn { animation: meterpulse 0.7s ease-in-out 4; border-radius: 6px; }
|
||||
.st.warn .pic, .st.warn > span:last-child { color: var(--warn); font-weight: 700; }
|
||||
.st.warn .bar i.over { animation: barpulse 0.7s ease-in-out infinite; }
|
||||
@keyframes meterpulse { 0%, 100% { filter: none; } 50% { filter: brightness(1.9); } }
|
||||
@keyframes barpulse { 0%, 100% { opacity: 1; } 50% { opacity: .45; } }
|
||||
.gbar .err.alert { color: #fff; background: var(--warn); border-radius: 6px; padding: 3px 8px; font-size: 10.5px; font-weight: 700; line-height: 1.25;
|
||||
box-shadow: 0 0 0 1px #000 inset, 0 2px 10px #0008; animation: errblink 0.46s steps(1, end) 6; }
|
||||
@keyframes errblink { 0%, 100% { background: var(--warn); color: #fff; } 50% { background: #5a1410; color: #ffb9a6; } }
|
||||
.paint { display: flex; gap: 3px; align-items: center; font-size: 11px; color: var(--dim); }
|
||||
.paint span.sw { width: 15px; height: 15px; border-radius: 4px; border: 2px solid transparent; cursor: pointer; }
|
||||
.paint span.sw.on { border-color: #fff; }
|
||||
.paint .lb { width: 46px; }
|
||||
#sRight { background: rgba(14,16,22,.9); border-left: 1px solid var(--line); display: flex; flex-direction: column; padding: 10px 12px; gap: 8px; min-height: 0; }
|
||||
#sRight { background: rgba(14,16,22,.9); border-left: 1px solid var(--line); display: flex; flex-direction: column; padding: 10px 12px; gap: 8px; min-height: 0; width: 100%; max-width: 560px; margin-left: auto; }
|
||||
#buildView { display: flex; flex-direction: column; gap: 8px; flex: 1; min-height: 0; }
|
||||
#buildView.hide, #paintView.hide, #hangarView.hide { display: none; }
|
||||
#paintView, #hangarView { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; }
|
||||
@@ -250,6 +308,12 @@
|
||||
/* zoom bar under the preview */
|
||||
.zoombar { display: flex; align-items: center; justify-content: center; gap: 10px; font-size: 12px; color: var(--dim); margin-bottom: 2px; }
|
||||
.zoombar button { width: 30px; height: 26px; padding: 0; font-size: 16px; font-weight: 700; }
|
||||
.placebtn { width: 100%; min-height: 40px; font: 13px var(--head); letter-spacing: .03em; border-left: 3px solid var(--accent); }
|
||||
.placebtn::before { content: '🔧 '; }
|
||||
.placebtn.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); }
|
||||
.placehint { font-size: 11.5px; color: var(--dim); background: rgba(8,10,14,.7); border: 1px solid var(--line);
|
||||
border-radius: 8px; padding: 5px 8px; line-height: 1.3; }
|
||||
.placehint.hide { display: none; }
|
||||
/* fitted parts strip (bottom of the parts view): 7 compact chips, does not cover the robot preview */
|
||||
.fittedwrap { border-top: 1px solid var(--line); padding-top: 5px; }
|
||||
.flabel { font: 10px var(--head); letter-spacing: .12em; text-transform: uppercase; color: var(--dim); margin-bottom: 3px; }
|
||||
@@ -294,21 +358,23 @@
|
||||
#designer .drow { display: grid; grid-template-columns: 48px 1fr 34px; gap: 8px; align-items: center; font-size: 11px; margin: 2px 0; }
|
||||
#designer .drow input[type=range] { width: 100%; accent-color: var(--accent); height: 20px; }
|
||||
#designer .drow .dv { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
|
||||
#cards { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(8, 1fr); gap: 5px;
|
||||
align-content: start; padding: 7px; background: rgba(0,0,0,.26); border: 1px solid var(--line); border-top: none;
|
||||
#cards { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(86px, 1fr)); gap: 6px;
|
||||
align-content: start; padding: 8px; background: rgba(0,0,0,.26); border: 1px solid var(--line); border-top: none;
|
||||
border-radius: 0 0 var(--r2) var(--r2); }
|
||||
.item { background: linear-gradient(#252b37, #171b23); border: 1px solid #39414f; border-radius: var(--r2);
|
||||
padding: 4px 4px 3px; cursor: pointer; text-align: center; position: relative;
|
||||
box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.45); }
|
||||
padding: 16px 4px 5px; cursor: pointer; text-align: center; position: relative; min-width: 0;
|
||||
display: flex; flex-direction: column; gap: 2px; box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.45); }
|
||||
@media (hover: hover) { .item:hover { border-color: #5a6478; } }
|
||||
.item.sel { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.3); }
|
||||
.item > .pic { width: 100%; height: 40px; font-size: 30px; }
|
||||
.item .nm { font-size: 11px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.item > .pic { width: 100%; height: 42px; font-size: 30px; }
|
||||
.item .nm { font-size: 11px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
|
||||
.item .pr { font-size: 11px; color: var(--gold); display: flex; gap: 3px; justify-content: center; align-items: center;
|
||||
font-variant-numeric: tabular-nums; background: rgba(0,0,0,.3); border-radius: var(--r1); padding: 0 4px; margin: 2px auto 0; width: fit-content; }
|
||||
.item .pr .pic { width: 14px; height: 14px; }
|
||||
.item .pr.no { color: var(--warn); }
|
||||
.item .badge { position: absolute; top: 5px; left: 5px; font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 6px; background: var(--accent); color: #1a0c02; }
|
||||
/* badge as a thin ribbon across the top so it never overlaps the image */
|
||||
.item .badge { position: absolute; top: 3px; left: 3px; right: 3px; text-align: center; font-size: 9px; font-weight: 700;
|
||||
letter-spacing: .02em; padding: 1px 0; border-radius: 5px; background: var(--accent); color: #1a0c02; white-space: nowrap; overflow: hidden; }
|
||||
.item .badge.own { background: #3c4556; color: var(--text); }
|
||||
#detail { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 6px 9px; display: grid; grid-template-columns: 46px 1fr auto; gap: 9px; align-items: center; min-height: 56px; }
|
||||
#detail > .pic { width: 46px; height: 46px; font-size: 32px; }
|
||||
@@ -357,17 +423,18 @@
|
||||
.achrow .ad { font-size: 11.5px; color: var(--dim); font-weight: 400; }
|
||||
.achrow .am { font-size: 16px; text-align: center; }
|
||||
|
||||
/* paint tab: proper colour chips instead of tiny dots */
|
||||
#paintView { gap: 10px; }
|
||||
.psec h4 { margin: 0 0 6px; font: 12px var(--head); letter-spacing: .1em; text-transform: uppercase; color: var(--dim); }
|
||||
.pgrid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 7px; }
|
||||
.pgrid.wide { grid-template-columns: repeat(8, 1fr); }
|
||||
.pgrid .sw { position: relative; height: 40px; border-radius: var(--r2); border: 2px solid #000a;
|
||||
/* paint tab: compact colour chips (must fit without scrolling) */
|
||||
#shop.paintmode #tabs, #shop.paintmode #detail, #shop.paintmode #fittedwrap { display: none !important; }
|
||||
.psec { margin: 0 0 2px; }
|
||||
.psec h4 { margin: 0 0 2px; font: 8.5px var(--head); letter-spacing: .08em; text-transform: uppercase; color: var(--dim); }
|
||||
.pgrid { display: grid; grid-template-columns: repeat(16, 1fr); gap: 3px; }
|
||||
.pgrid.wide { grid-template-columns: repeat(10, 1fr); }
|
||||
.pgrid .sw { position: relative; height: 16px; border-radius: var(--r1); border: 1.5px solid #000a;
|
||||
cursor: pointer; box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.4); transition: transform .1s; }
|
||||
@media (hover: hover) { .pgrid .sw:hover { transform: translateY(-2px); } }
|
||||
.pgrid .sw.on { border-color: #fff; box-shadow: 0 0 0 2px var(--accent); }
|
||||
.pgrid .sw.on::after { content: '✓'; position: absolute; inset: 0; display: flex; align-items: center;
|
||||
justify-content: center; color: #fff; font-size: 19px; font-weight: 700; text-shadow: 0 1px 3px #000; }
|
||||
justify-content: center; color: #fff; font-size: 10px; font-weight: 700; text-shadow: 0 1px 3px #000; }
|
||||
.pgrid .duo { display: flex; overflow: hidden; }
|
||||
.pgrid .duo i { flex: 1; }
|
||||
.pcustom { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: center;
|
||||
@@ -533,6 +600,70 @@
|
||||
#gate.open .gh-top { transform: translateY(-100%); }
|
||||
#gate.open .gh-bot { transform: translateY(100%); }
|
||||
|
||||
/* build editor: fills the shop panel in place of the parts view (robot stays on the left) */
|
||||
/* weapon placement + shape: small panel, top-right of the live-view area */
|
||||
#wplace { position: absolute; right: 14px; top: 12px; width: 198px; background: rgba(12,14,19,.9); border: 1px solid var(--line);
|
||||
border-radius: 10px; padding: 7px 9px; display: flex; flex-direction: column; gap: 4px; box-shadow: var(--hl); }
|
||||
#wplace.hide { display: none; }
|
||||
#wplace .wphead { font: 10px var(--head); letter-spacing: .06em; text-transform: uppercase; color: var(--accent); margin-top: 2px; }
|
||||
#wplace .wpsides { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
|
||||
#wplace .wpsides button { min-height: 30px; font-size: 11px; padding: 2px; }
|
||||
#wplace .wpsides button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
|
||||
#wplace .wprow { display: grid; grid-template-columns: 54px 1fr 36px; gap: 6px; align-items: center; font-size: 11px; }
|
||||
#wplace .wprow input[type=range] { width: 100%; accent-color: var(--accent); height: 16px; }
|
||||
#wplace .wprow .dv { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
|
||||
#wplace .weplist { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
#wplace .wepchip { display: flex; align-items: center; gap: 4px; padding: 2px 6px; min-height: 26px; border: 1px solid var(--line); border-radius: 7px; background: #141922; cursor: pointer; font-size: 11px; }
|
||||
#wplace .wepchip.on { border-color: var(--accent); background: #2a1c10; }
|
||||
#wplace .wepchip .pic { width: 16px; height: 16px; }
|
||||
#wplace .wepchip .x { color: var(--warn); font-weight: 700; padding: 0 1px; font-size: 12px; }
|
||||
#wplace .edhint { font-size: 10.5px; color: var(--dim); }
|
||||
.item.dim { opacity: .5; }
|
||||
.pbtn { width: 100%; min-height: 44px; font-size: 16px; }
|
||||
|
||||
/* paint / hangar / weapon editor all render inside #cards; override the parts grid */
|
||||
#cards.wedit { display: flex; flex-direction: column; grid-template-columns: none; gap: 7px; padding: 9px; }
|
||||
#cards.pcards { display: flex; flex-direction: column; grid-template-columns: none; gap: 6px; padding: 7px; overflow: hidden; }
|
||||
#cards.hcards { display: flex; flex-direction: column; grid-template-columns: none; gap: 6px; padding: 10px; }
|
||||
/* paint tab: 3 save slots + inline painter */
|
||||
.phdr { display: flex; flex-direction: column; gap: 4px; }
|
||||
.pslots { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; }
|
||||
.pslot { position: relative; height: 22px; border-radius: 6px; border: 2px solid #000a; cursor: pointer; overflow: hidden; }
|
||||
.pslot.on { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent); }
|
||||
.pslot .acc { position: absolute; left: 0; right: 0; bottom: 0; height: 7px; }
|
||||
.pslot .dmark { position: absolute; top: 1px; left: 4px; font-size: 11px; text-shadow: 0 1px 2px #000; }
|
||||
.pslot .sv { position: absolute; top: 2px; right: 2px; min-height: 0; padding: 0 4px; font-size: 10px; line-height: 1.3; }
|
||||
#painter.inline { position: static; grid-column: auto; grid-row: auto; background: none; border: none; padding: 0; gap: 6px; }
|
||||
#painter.inline .pt-head { display: none; }
|
||||
#painter.inline #ptCancel, #painter.inline #ptDone { display: none; }
|
||||
#painter.inline .pt-canvas canvas { width: 100%; height: auto; max-height: 184px; aspect-ratio: 2 / 1; margin: 0 auto; }
|
||||
#painter.inline .pt-tools button, #painter.inline .pt-colors .sw, #painter.inline .gbar button { padding: 3px 6px; font-size: 11px; }
|
||||
#painter.inline .pt-row { margin: 2px 0; }
|
||||
#painter.inline .gbar { border-top: none; padding-top: 0; }
|
||||
.wedit .edsec { background: var(--panel2); border: 1px solid var(--line); border-radius: 9px; padding: 7px 9px; }
|
||||
.wedit .edlabel { font: 10px var(--head); letter-spacing: .08em; text-transform: uppercase; color: var(--dim); margin-bottom: 5px; }
|
||||
.wedit .weplist { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
.wedit .wepchip { display: flex; align-items: center; gap: 5px; padding: 3px 7px; min-height: 30px; border: 1px solid var(--line);
|
||||
border-radius: 8px; background: #141922; cursor: pointer; font-size: 12px; }
|
||||
.wedit .wepchip.on { border-color: var(--accent); background: #2a1c10; }
|
||||
.wedit .wepchip .pic { width: 18px; height: 18px; }
|
||||
.wedit .wepchip .x { color: var(--warn); font-weight: 700; padding: 0 2px; font-size: 13px; }
|
||||
.wedit .addrow { display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; margin-top: 6px; }
|
||||
.wedit .addrow button { min-height: 36px; font-size: 9.5px; padding: 3px 2px; display: flex; flex-direction: column; align-items: center; gap: 1px; line-height: 1.1; }
|
||||
.wedit .addrow button .pic { width: 18px; height: 18px; }
|
||||
.wedit .addrow button .pr { color: var(--gold); font-size: 9px; }
|
||||
.wedit .addrow button:disabled { opacity: .4; }
|
||||
.wedit .sides { display: grid; grid-template-columns: repeat(4, 1fr); gap: 5px; }
|
||||
.wedit .sides button { min-height: 34px; font-size: 11.5px; }
|
||||
.wedit .sides button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
|
||||
.wedit .erow { display: grid; grid-template-columns: 50px 1fr 38px; gap: 8px; align-items: center; font-size: 11px; margin: 3px 0; }
|
||||
.wedit .erow input[type=range] { width: 100%; accent-color: var(--accent); height: 18px; }
|
||||
.wedit .erow .dv { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
|
||||
.wedit .edhint { font-size: 11px; color: var(--dim); line-height: 1.3; }
|
||||
.wedit .edmeters { display: flex; flex-wrap: wrap; gap: 7px; font-size: 11.5px; }
|
||||
.wedit .edmeters b { color: var(--text); }
|
||||
.wedit .edmeters .over { color: var(--warn); }
|
||||
|
||||
/* touch pad: only on touch screens */
|
||||
#pad { position: absolute; left: 14px; right: 14px; bottom: 14px; display: none; justify-content: space-between; pointer-events: none; z-index: 5; }
|
||||
#pad > div { display: grid; grid-template-columns: repeat(3, 60px); gap: 6px; pointer-events: auto; }
|
||||
@@ -573,11 +704,15 @@
|
||||
|
||||
<div id="shop" class="hide">
|
||||
<div id="sLeft">
|
||||
<input id="rname" maxlength="18" spellcheck="false">
|
||||
<div class="zoombar"><button id="zOut" title="Zoom -">-</button><span data-i18n="zoom">Zoom</span><button id="zIn" title="Zoom +">+</button></div>
|
||||
<div class="spacer"></div>
|
||||
<div class="stats" id="meters"></div>
|
||||
<div class="mech"><span class="pic" data-f="🧔" id="mechPic"></span><div class="bubble" id="mechTip"></div></div>
|
||||
<div class="slTL">
|
||||
<input id="rname" maxlength="18" spellcheck="false">
|
||||
<div class="mech"><span class="pic" data-f="🧔" id="mechPic"></span><div class="bubble" id="mechTip"></div></div>
|
||||
</div>
|
||||
<div id="wplace" class="hide"></div>
|
||||
<div class="slBottom">
|
||||
<div class="zoombar"><button id="zOut" title="Zoom -">-</button><span data-i18n="zoom">Zoom</span><button id="zIn" title="Zoom +">+</button></div>
|
||||
<div class="stats" id="meters"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sRight">
|
||||
<div class="shoptabs" id="shopTabs"></div>
|
||||
@@ -586,23 +721,13 @@
|
||||
<div id="cards"></div>
|
||||
<div id="detail"></div>
|
||||
<div id="designer" class="hide"></div>
|
||||
<div class="fittedwrap"><div class="flabel" data-i18n="fitted_parts">Fitted</div><div id="fitted" class="fitted"></div></div>
|
||||
<div id="fittedwrap" class="fittedwrap"><div class="flabel" data-i18n="fitted_parts">Fitted</div><div id="fitted" class="fitted"></div></div>
|
||||
</div>
|
||||
<div id="paintView" class="hide">
|
||||
<div class="psec"><h4 data-i18n="paint_body">Body</h4><div class="pgrid" id="paintBody"></div></div>
|
||||
<div class="psec"><h4 data-i18n="paint_accent">Accent</h4><div class="pgrid" id="paintAccent"></div></div>
|
||||
<div class="psec"><h4 data-i18n="paint_schemes">Schemes</h4><div class="pgrid wide" id="paintSchemes"></div></div>
|
||||
<div class="spacer"></div>
|
||||
<div class="pcustom">
|
||||
<div class="pct"><b data-i18n="pt_open">Paint it yourself</b><span class="muted" data-i18n="paint_hint">Pick quick colours above, or paint your own design.</span></div>
|
||||
<button id="bPaint" class="primary">🎨</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="hangarView" class="hide"></div>
|
||||
<div class="gbar">
|
||||
<div class="err" id="gErr"></div>
|
||||
<button id="bGMenu" data-i18n="menu">Menu</button>
|
||||
<button id="bGMode">Kampagne</button>
|
||||
<button id="bRankG" style="display:none">🏆</button>
|
||||
<button id="bTrain" data-i18n="training">Training</button>
|
||||
<button class="primary" id="bLeague">League</button>
|
||||
</div>
|
||||
@@ -664,6 +789,8 @@
|
||||
<script src="ai.js"></script>
|
||||
<script src="profiles.js"></script>
|
||||
<script src="net.js"></script>
|
||||
<script src="cloudsave.js"></script>
|
||||
<script src="ranking.js"></script>
|
||||
<script src="lobby.js"></script>
|
||||
<script src="looks.js"></script>
|
||||
<script src="render3d.js"></script>
|
||||
|
||||
20
game/lang.js
20
game/lang.js
@@ -36,6 +36,7 @@ window.LANG = {
|
||||
ach_garage: 'Full Garage', achd_garage: 'Keep 3 robots',
|
||||
ach_artist: 'Own Colours', achd_artist: 'Paint your own design',
|
||||
mode_online: 'Online', mode_campaign: 'Campaign', mode_pvp: 'vs. players', to_lobby: 'Lobby',
|
||||
to_campaign: 'To campaign', to_online: 'To online', rank_live: 'LIVE',
|
||||
mode_switched: 'Separate game - own money and parts',
|
||||
click_start: 'Click or press any key to start',
|
||||
tut_title: 'Quick start', tut_next: 'Next', tut_skip: 'Skip', tut_go: "Let's build",
|
||||
@@ -69,7 +70,7 @@ window.LANG = {
|
||||
st_supply: 'supplies {n} power', st_power: 'needs {n} power',
|
||||
m_weight: 'Weight', m_power: 'Power', m_hp: 'Hit points', m_armour: 'Armour', m_speed: 'Speed', m_accel: 'Accel.', m_turn: 'Turning',
|
||||
paint_body: 'Paint', paint_accent: 'Accent',
|
||||
err_need: '{slot} missing', err_bad: '{slot} invalid', err_overweight: 'Too heavy (max 100 kg)', err_no_power: 'Battery too weak',
|
||||
err_need: '{slot} missing', err_bad: '{slot} invalid', err_overweight: 'Too heavy (max {n} kg)', err_no_power: 'Battery too weak - stronger battery or less draw', err_too_many_weapons: 'Too many weapons (max 3)',
|
||||
pd_crate: 'Simple steel box. Cheap and honest.',
|
||||
pd_doorstop: 'Low wedge shape - hard to flip.',
|
||||
pd_bulwark: 'Heavy frame with lots of hit points.',
|
||||
@@ -175,7 +176,8 @@ window.LANG = {
|
||||
e_pass_short: 'Password needs at least 4 characters.', e_pass_match: 'Passwords do not match.',
|
||||
e_unknown: 'No account with this name.', e_wrong_pass: 'Wrong password.',
|
||||
// settings
|
||||
s_lang: 'Language', s_music: 'Music', s_sfx: 'Effects', s_mute: 'Sound', s_gfx: 'Graphics', s_intro: 'Intro at start',
|
||||
s_lang: 'Language', s_country: 'Country', s_music: 'Music', s_sfx: 'Effects', s_mute: 'Sound', s_gfx: 'Graphics', s_intro: 'Intro at start',
|
||||
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',
|
||||
// paint booth
|
||||
@@ -230,6 +232,10 @@ window.LANG = {
|
||||
s_steer: 'Steering', steer_simple: 'Simple', steer_tank: 'Tank',
|
||||
s_autofire: 'Weapon helper', s_quiet: 'Quiet mode',
|
||||
s_body: 'Shape', des_height: 'Height', des_width: 'Width', des_length: 'Length', des_reset: 'Reset',
|
||||
place_weapon: 'Build / weapons', place_done: 'Done',
|
||||
place_hint: 'Drag a weapon on the robot — front, back or a side; drag up/down for height. Turn the robot by dragging the floor.',
|
||||
ed_title: 'Build your robot', ed_weapons: 'Weapons (up to 3, same allowed)', ed_place: 'Placement', ed_noweapons: 'No weapons yet — pick one and mount it.', ed_max: 'Max {n} weapons',
|
||||
mt_front: 'Front', mt_back: 'Back', mt_left: 'Left', mt_right: 'Right',
|
||||
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.',
|
||||
@@ -285,6 +291,7 @@ window.LANG = {
|
||||
ach_garage: 'Volle Halle', achd_garage: 'Halte 3 Roboter',
|
||||
ach_artist: 'Eigene Farben', achd_artist: 'Male ein eigenes Design',
|
||||
mode_online: 'Online', mode_campaign: 'Kampagne', mode_pvp: 'gegen Spieler', to_lobby: 'Lobby',
|
||||
to_campaign: 'Zur Kampagne', to_online: 'Zum Online', rank_live: 'LIVE',
|
||||
mode_switched: 'Eigenes Spiel – eigenes Geld und eigene Teile',
|
||||
click_start: 'Klicken oder Taste drücken zum Starten',
|
||||
tut_title: 'Kurzanleitung', tut_next: 'Weiter', tut_skip: 'Überspringen', tut_go: 'Los bauen',
|
||||
@@ -318,7 +325,7 @@ window.LANG = {
|
||||
st_supply: 'liefert {n} Strom', st_power: 'braucht {n} Strom',
|
||||
m_weight: 'Gewicht', m_power: 'Strom', m_hp: 'Lebenspunkte', m_armour: 'Panzerung', m_speed: 'Tempo', m_accel: 'Beschl.', m_turn: 'Wendigkeit',
|
||||
paint_body: 'Lack', paint_accent: 'Akzent',
|
||||
err_need: '{slot} fehlt', err_bad: '{slot} ungültig', err_overweight: 'Zu schwer (max. 100 kg)', err_no_power: 'Batterie zu schwach',
|
||||
err_need: '{slot} fehlt', err_bad: '{slot} ungültig', err_overweight: 'Zu schwer (max. {n} kg)', err_no_power: 'Batterie zu schwach – stärkere Batterie oder weniger Verbrauch', err_too_many_weapons: 'Zu viele Waffen (max. 3)',
|
||||
pd_crate: 'Einfache Stahlkiste. Billig und ehrlich.',
|
||||
pd_doorstop: 'Flacher Keil – schwer umzudrehen.',
|
||||
pd_bulwark: 'Schwerer Rahmen mit vielen Lebenspunkten.',
|
||||
@@ -424,7 +431,8 @@ window.LANG = {
|
||||
e_pass_short: 'Das Passwort braucht mindestens 4 Zeichen.', e_pass_match: 'Die Passwörter stimmen nicht überein.',
|
||||
e_unknown: 'Kein Konto mit diesem Namen.', e_wrong_pass: 'Falsches Passwort.',
|
||||
// settings
|
||||
s_lang: 'Sprache', s_music: 'Musik', s_sfx: 'Effekte', s_mute: 'Ton', s_gfx: 'Grafik', s_intro: 'Intro beim Start',
|
||||
s_lang: 'Sprache', s_country: 'Land', s_music: 'Musik', s_sfx: 'Effekte', s_mute: 'Ton', s_gfx: 'Grafik', s_intro: 'Intro beim Start',
|
||||
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',
|
||||
// paint booth
|
||||
@@ -479,6 +487,10 @@ window.LANG = {
|
||||
s_steer: 'Steuerung', steer_simple: 'Einfach', steer_tank: 'Panzer',
|
||||
s_autofire: 'Waffen-Hilfe', s_quiet: 'Leiser Modus',
|
||||
s_body: 'Form', des_height: 'Höhe', des_width: 'Breite', des_length: 'Länge', des_reset: 'Zurücksetzen',
|
||||
place_weapon: 'Bauen / Waffen', place_done: 'Fertig',
|
||||
place_hint: 'Zieh eine Waffe auf den Roboter — vorne, hinten oder an eine Seite; hoch/runter für die Höhe. Den Roboter drehst du, indem du den Boden ziehst.',
|
||||
ed_title: 'Roboter bauen', ed_weapons: 'Waffen (bis 3, auch gleiche)', ed_place: 'Platzierung', ed_noweapons: 'Noch keine Waffe — eine wählen und montieren.', ed_max: 'Max. {n} Waffen',
|
||||
mt_front: 'Vorne', mt_back: 'Hinten', mt_left: 'Links', mt_right: 'Rechts',
|
||||
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.',
|
||||
|
||||
43
game/net.js
43
game/net.js
@@ -23,13 +23,11 @@
|
||||
(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 base = (cfg.serverUrl || '').replace(/\/+$/, ''); // '' = same origin as the page
|
||||
const API = base + '/api', DB = base + '/db';
|
||||
// online when served over http(s) (own server) or given an explicit serverUrl; file:// stays offline
|
||||
const enabled = cfg.enabled !== false && typeof fetch !== 'undefined' && (!!base || /^https?:$/.test(location.protocol));
|
||||
const store = Kit.store('robotclash.net');
|
||||
|
||||
let session = null; // { idToken, refreshToken, uid, name, email, guest, exp }
|
||||
@@ -40,7 +38,7 @@
|
||||
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; }
|
||||
if (!res.ok) { const msg = (data.error && (data.error.message || data.error)) || ('HTTP_' + res.status); const e = new Error(msg); e.code = String(msg).split(/[ :]/)[0]; throw e; }
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -49,7 +47,7 @@
|
||||
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,
|
||||
uid: d.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();
|
||||
@@ -58,9 +56,9 @@
|
||||
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;
|
||||
const d = await postJson(`${API}/auth/refresh`, { refreshToken: session.refreshToken });
|
||||
session.idToken = d.idToken; session.refreshToken = d.refreshToken; session.uid = d.uid;
|
||||
session.exp = Date.now() + (+(d.expiresIn || 3600) - 60) * 1000; save(); return true;
|
||||
} catch (e) { session = null; save(); fire(); return false; }
|
||||
}
|
||||
async function token() {
|
||||
@@ -76,9 +74,8 @@
|
||||
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
|
||||
const d = await postJson(`${API}/auth/register`, { email, pass, name: Kit.cleanName(name) || email.split('@')[0] });
|
||||
setAuth(d, d.name || Kit.cleanName(name) || email.split('@')[0], false);
|
||||
return { ok: true };
|
||||
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
|
||||
},
|
||||
@@ -86,18 +83,16 @@
|
||||
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(); }
|
||||
const d = await postJson(`${API}/auth/login`, { email, pass });
|
||||
setAuth(d, d.name || email.split('@')[0], false);
|
||||
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);
|
||||
const d = await postJson(`${API}/auth/guest`, { name: Kit.cleanName(name) || 'Guest' });
|
||||
setAuth(d, d.name || Kit.cleanName(name) || 'Guest', true);
|
||||
return { ok: true };
|
||||
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
|
||||
},
|
||||
@@ -108,14 +103,14 @@
|
||||
refresh().then(ok => { if (ok) fire(); });
|
||||
return true;
|
||||
},
|
||||
logout() { session = null; save(); fire(); },
|
||||
logout() { const r = session && session.refreshToken; session = null; save(); fire(); if (r) fetch(`${API}/auth/logout`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: r }) }).catch(() => {}); },
|
||||
};
|
||||
|
||||
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' });
|
||||
const res = await fetch(`${DB}/${path}.json${t ? '?auth=' + t : ''}`, { cache: 'no-store' });
|
||||
return res.ok ? await res.json() : null;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
@@ -123,7 +118,7 @@
|
||||
if (!enabled) return false;
|
||||
const t = await token();
|
||||
try {
|
||||
const res = await fetch(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`, {
|
||||
const res = await fetch(`${DB}/${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;
|
||||
@@ -143,7 +138,7 @@
|
||||
const open = async () => {
|
||||
if (closed) return;
|
||||
const t = await token();
|
||||
es = new EventSource(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`);
|
||||
es = new EventSource(`${DB}/${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; }
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
let tool = 'brush', color = '#ffffff', size = 14, stamp = '★', text = '', mirror = true;
|
||||
let undo = [], drawing = null, panel = null, before = null, pending = false;
|
||||
|
||||
function build() {
|
||||
function build(host) {
|
||||
panel = document.createElement('div');
|
||||
panel.id = 'painter';
|
||||
panel.innerHTML = `
|
||||
@@ -45,7 +45,7 @@
|
||||
<div class="pt-colors" id="ptColors">${COLORS.map(c => `<span class="sw" data-c="${c}" style="background:${c}"></span>`).join('')}<input type="color" id="ptPick" value="${color}"></div>
|
||||
<div class="gbar"><button id="ptUndo">↶ ${t('pt_undo')}</button><button id="ptClear">${t('pt_clear')}</button><div class="grow"></div>
|
||||
<button id="ptCancel">${t('cancel')}</button><button class="primary" id="ptDone">✓ ${t('pt_done')}</button></div>`;
|
||||
$('shop').appendChild(panel);
|
||||
(host || $('shop')).appendChild(panel);
|
||||
const cv = $('ptCv');
|
||||
cv.addEventListener('pointerdown', down);
|
||||
cv.addEventListener('pointermove', move);
|
||||
@@ -157,19 +157,24 @@
|
||||
});
|
||||
}
|
||||
|
||||
function open() {
|
||||
if (!panel) build();
|
||||
function open(mountEl) {
|
||||
const inline = !!mountEl;
|
||||
if (!panel) build(mountEl || $('shop'));
|
||||
else if (mountEl && panel.parentNode !== mountEl) mountEl.appendChild(panel);
|
||||
panel.classList.toggle('inline', inline);
|
||||
before = lc.getImageData(0, 0, LW, LH);
|
||||
undo = [];
|
||||
panel.style.display = '';
|
||||
$('sRight').style.display = 'none'; $('shop').classList.add('painting');
|
||||
if (!inline) { $('sRight').style.display = 'none'; $('shop').classList.add('painting'); }
|
||||
opt.view.paintCam(true);
|
||||
refresh(); live();
|
||||
}
|
||||
function close() {
|
||||
if (!panel) return;
|
||||
const inline = panel.classList.contains('inline');
|
||||
panel.style.display = 'none';
|
||||
$('sRight').style.display = ''; $('shop').classList.remove('painting');
|
||||
if (!inline) $('sRight').style.display = '';
|
||||
$('shop').classList.remove('painting');
|
||||
opt.view.paintCam(false); opt.view.face(null);
|
||||
}
|
||||
// anything drawn at all? (decides stock stripes vs. own artwork on the model)
|
||||
@@ -178,6 +183,6 @@
|
||||
for (let i = 3; i < d.length; i += 16) if (d[i] > 8) return true;
|
||||
return false;
|
||||
}
|
||||
return { open, close, hasArt, get isOpen() { return !!panel && panel.style.display !== 'none'; } };
|
||||
return { open, close, hasArt, sync() { if (panel && panel.style.display !== 'none') { live(); refresh(); } }, get isOpen() { return !!panel && panel.style.display !== 'none'; } };
|
||||
};
|
||||
})(window);
|
||||
|
||||
51
game/ranking.js
Normal file
51
game/ranking.js
Normal file
@@ -0,0 +1,51 @@
|
||||
/* Robot Clash - online ranking over the own server (ranks/<uid>, public read, owner write).
|
||||
One row per account (dedupe by key is implicit); live push via net.db.stream (SSE).
|
||||
Needs net.js + kit-core.js (Kit.badName). DOM-free; RC.Ranking.rank is a pure function (Node-testable).
|
||||
|
||||
const rank = RC.Ranking(net);
|
||||
if (rank.enabled) {
|
||||
await rank.submit({ uid, name, fame, flag, cls, season }); // best effort, never throws
|
||||
const sub = rank.watch(rows => draw(rows)); // { close() } live, rows best first
|
||||
const rows = await rank.once(20); // one-shot fallback (no stream)
|
||||
}
|
||||
RC.Ranking.rank(data, n) // { key: {name,fame,...} } -> sorted array, bad names out, capped */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || {});
|
||||
const Kit = root.Kit || {};
|
||||
const bad = s => (Kit.badName ? Kit.badName(s) : false);
|
||||
|
||||
// pure: raw ranks object -> clean, sorted (fame desc, newer first on tie), capped list
|
||||
RC.Ranking = function (net) {
|
||||
const api = {
|
||||
enabled: !!(net && net.enabled),
|
||||
async submit(row) {
|
||||
if (!api.enabled || !row || !row.uid) return false;
|
||||
const name = String(row.name || '').slice(0, 20);
|
||||
if (!name || bad(name) || !(row.fame > 0)) return false;
|
||||
const r = await net.db.put('ranks/' + row.uid, {
|
||||
name, fame: Math.floor(row.fame) | 0, flag: row.flag || 'XX',
|
||||
cls: row.cls || 'medium', season: row.season | 0, ts: { '.sv': 'timestamp' },
|
||||
});
|
||||
return !!r;
|
||||
},
|
||||
watch(cb, n) {
|
||||
if (!api.enabled) { cb([]); return { close() {} }; }
|
||||
return net.db.stream('ranks', data => cb(RC.Ranking.rank(data, n)));
|
||||
},
|
||||
async once(n) {
|
||||
if (!api.enabled) return [];
|
||||
return RC.Ranking.rank(await net.db.get('ranks'), n);
|
||||
},
|
||||
};
|
||||
return api;
|
||||
};
|
||||
|
||||
RC.Ranking.rank = function (data, n = 20) {
|
||||
const rows = Object.entries(data || {})
|
||||
.map(([key, v]) => Object.assign({ key }, v))
|
||||
.filter(v => v && typeof v.name === 'string' && typeof v.fame === 'number' && !bad(v.name));
|
||||
rows.sort((a, b) => b.fame - a.fame || (b.ts || 0) - (a.ts || 0));
|
||||
return rows.slice(0, n);
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
233
game/render3d.js
233
game/render3d.js
@@ -182,9 +182,9 @@
|
||||
return M;
|
||||
}
|
||||
// shop: the robot is framed in the left column, not in the middle of the stage
|
||||
const GARAGE_OFF_X = 455, GARAGE_OFF_Y = 16;
|
||||
const GARAGE_OFF_X = 300, GARAGE_OFF_Y = 16; // robot centered in the free area left of the shop panel
|
||||
// shop zoom: 0.6 = furthest out (the default, whole robot in frame), 1.9 = closest
|
||||
const GZ_MIN = 0.6, GZ_MAX = 1.9, GZ_DEF = GZ_MIN;
|
||||
const GZ_MIN = 0.6, GZ_MAX = 1.9, GZ_DEF = 0.72; // default framing of the robot in the shop
|
||||
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; };
|
||||
const cyl = (r1, r2, h, m, seg = 20) => { const o = new T.Mesh(new T.CylinderGeometry(r1, r2, h, seg), m); o.castShadow = true; return o; };
|
||||
|
||||
@@ -237,6 +237,20 @@
|
||||
return g;
|
||||
}
|
||||
|
||||
// position the weapon-mount group from the robot's mount (front/back/left/right + height).
|
||||
// weapons are built along +x; this turns that onto the chosen side and pulls side mounts in to the hull edge.
|
||||
function placeMount(g, st, L, Wd) {
|
||||
const th = -(st.mountA || 0), dx0 = ((st.mountAxis === 'wid' ? Wd : L) / 2) - L / 2;
|
||||
g.rotation.y = th;
|
||||
g.position.set(Math.cos(th) * dx0, st.mountUp || 0, -Math.sin(th) * dx0);
|
||||
}
|
||||
|
||||
// pointer (client px) -> normalised device coords on the garage canvas
|
||||
function ndcOf(canvas, cx, cy) {
|
||||
const b = canvas.getBoundingClientRect();
|
||||
return new T.Vector2(((cx - b.left) / b.width) * 2 - 1, -((cy - b.top) / b.height) * 2 + 1);
|
||||
}
|
||||
|
||||
function buildRobot(build, paint) {
|
||||
const m = mats(), st = RC.stats(build), P = RC.PARTS;
|
||||
const ch = P[build.chassis], wh = P[build.wheels], ar = build.armour ? P[build.armour] : null;
|
||||
@@ -245,7 +259,8 @@
|
||||
const drawn = !!(paint.layer && paint.drawn); // own artwork: no stock stripes, painted armour
|
||||
const accent = new T.MeshStandardMaterial({ color: paint.accent, metalness: 0.3, roughness: 0.45 });
|
||||
const armour = ar ? (drawn ? body : new T.MeshStandardMaterial({ color: ar.tint, metalness: 0.9, roughness: 0.28 })) : null;
|
||||
const root = new T.Group(), tilt = new T.Group();
|
||||
const root = new T.Group();
|
||||
let tilt = new T.Group(); // let: the weapon block points it at a mount group, then restores it
|
||||
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; };
|
||||
@@ -459,18 +474,25 @@
|
||||
|
||||
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
|
||||
// main weapons: each built facing +x, then rotated/moved to its mounted side + height
|
||||
const WS = m.wsteel, ED = m.wedge, HZ = m.stripe; // weapon steel, edge, hazard stripe
|
||||
out.weapons = []; out.st = st;
|
||||
const _tilt = tilt;
|
||||
for (let wi = 0; wi < (st.weapons || []).length; wi++) {
|
||||
const inst = st.weapons[wi], w = inst.part, wo = {};
|
||||
const wmount = new T.Group();
|
||||
placeMount(wmount, { mountA: inst.mountA, mountAxis: inst.mountAxis, mountUp: inst.mountUp }, L, Wd);
|
||||
_tilt.add(wmount); wo.wmount = wmount; out.weapons[wi] = wo;
|
||||
tilt = wmount;
|
||||
if (w.type === 'wedge') {
|
||||
if (w.id === 'lance') {
|
||||
// long spike lance on a sleeve - it thrusts forward when fired (poseRobot drives out.lance.position.x)
|
||||
const g = new T.Group(); g.position.set(L / 2, c + H * 0.4, 0); g.userData.baseX = L / 2; tilt.add(g);
|
||||
const sleeve = cyl(0.07, 0.08, 0.3, m.steel, 10); sleeve.rotation.z = Math.PI / 2; sleeve.position.x = -0.05; tilt.add(sleeve);
|
||||
// long spike lance on a sleeve - retracted at rest, thrusts forward when fired (poseRobot drives out.lance.position.x)
|
||||
const baseX = L / 2 - 0.45; // rest: tip sits just past the body, not poking far out
|
||||
const g = new T.Group(); g.position.set(baseX, c + H * 0.4, 0); g.userData.baseX = baseX; tilt.add(g);
|
||||
const sleeve = cyl(0.08, 0.1, 0.42, m.steel, 10); sleeve.rotation.z = Math.PI / 2; sleeve.position.set(L / 2 - 0.3, c + H * 0.4, 0); tilt.add(sleeve);
|
||||
const shaft = cyl(0.05, 0.05, 0.85, m.dark, 8); shaft.rotation.z = Math.PI / 2; shaft.position.x = 0.42; g.add(shaft);
|
||||
const tip = cyl(0.001, 0.13, 0.42, HZ, 12); tip.rotation.z = -Math.PI / 2; tip.position.x = 0.95; g.add(tip);
|
||||
out.lance = g;
|
||||
wo.lance = g;
|
||||
} else {
|
||||
// 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);
|
||||
@@ -483,7 +505,7 @@
|
||||
const s = box(0.78 * lf, 0.03, Wd * 0.4, accent); s.position.set(0.39 * lf, 0.06, 0); piv.add(s);
|
||||
const edge = box(0.12, 0.14, Wd * 0.98 * wf, HZ); edge.position.set(0.78 * lf, 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;
|
||||
wo.flipper = piv;
|
||||
} else if (w.type === 'hammer') {
|
||||
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);
|
||||
@@ -496,7 +518,7 @@
|
||||
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;
|
||||
wo.hammer = piv;
|
||||
} else if (w.type === 'saw') {
|
||||
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);
|
||||
if (w.id === 'drill') {
|
||||
@@ -504,7 +526,7 @@
|
||||
const g = new T.Group(); g.position.set(L / 2 + 0.42, c + H * 0.5, 0); tilt.add(g);
|
||||
const cone = cyl(0.001, 0.2, 0.72, WS, 14); cone.rotation.z = -Math.PI / 2; cone.castShadow = true; g.add(cone);
|
||||
for (let k = 0; k < 3; k++) { const fl = box(0.6, 0.03, 0.06, HZ); fl.position.x = -0.1; fl.rotation.x = k / 3 * Math.PI * 2; g.add(fl); }
|
||||
out.saw = g; out.sawAxis = 'x';
|
||||
wo.saw = g; wo.sawAxis = 'x';
|
||||
} else {
|
||||
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);
|
||||
@@ -512,7 +534,7 @@
|
||||
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;
|
||||
wo.saw = g;
|
||||
}
|
||||
} else if (w.type === 'spinner') {
|
||||
if (w.id === 'drum') {
|
||||
@@ -520,14 +542,14 @@
|
||||
const g = new T.Group(); g.position.set(L / 2 + 0.12, c + H * 0.34, 0); tilt.add(g);
|
||||
const drum = cyl(0.3, 0.3, 0.52, WS, 20); drum.castShadow = true; g.add(drum);
|
||||
for (const sx of [-1, 1]) { const tb = box(0.14, 0.54, 0.12, HZ); tb.position.set(sx * 0.3, 0, 0); g.add(tb); }
|
||||
out.spinner = g;
|
||||
wo.spinner = g;
|
||||
} else {
|
||||
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;
|
||||
wo.spinner = g;
|
||||
}
|
||||
} else if (w.type === 'lifter') {
|
||||
const piv = new T.Group(); piv.position.set(L / 2 - 0.08, c + H * 0.16, 0); tilt.add(piv);
|
||||
@@ -536,7 +558,7 @@
|
||||
const prong = box(0.85, 0.07, Wd * 0.26, WS); prong.position.set(0.46, 0, sz * Wd * 0.3); piv.add(prong);
|
||||
const tip = box(0.16, 0.1, Wd * 0.28, HZ); tip.position.set(0.9, 0.015, sz * Wd * 0.3); piv.add(tip);
|
||||
}
|
||||
out.flipper = piv;
|
||||
wo.flipper = piv;
|
||||
} else if (w.type === 'vspinner') {
|
||||
const arm = box(0.3, 0.14, 0.14, m.dark); arm.position.set(L / 2 + 0.02, c + H * 0.45, 0); tilt.add(arm);
|
||||
const g = new T.Group(); g.position.set(L / 2 + 0.32, c + H * 0.42, 0); tilt.add(g);
|
||||
@@ -546,19 +568,20 @@
|
||||
tth.position.set(Math.cos(a) * 0.45, Math.sin(a) * 0.45, 0); tth.rotation.z = a; g.add(tth);
|
||||
}
|
||||
const hub = cyl(0.1, 0.1, 0.14, accent, 12); hub.rotation.x = Math.PI / 2; g.add(hub);
|
||||
out.vspin = g;
|
||||
wo.vspin = g;
|
||||
} else if (w.type === 'crusher') {
|
||||
out.jaws = [];
|
||||
wo.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.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);
|
||||
piv.userData.side = sz; wo.jaws.push(piv);
|
||||
}
|
||||
}
|
||||
tilt = _tilt; // restore before the next weapon / the tower
|
||||
mark('weapon' + wi); // tag this weapon's mount group so breakPart can hide just it
|
||||
}
|
||||
|
||||
mark('weapon');
|
||||
out.wmount = out.weapons[0] && out.weapons[0].wmount; // editor drag targets a weapon (default the first)
|
||||
|
||||
// tower on top
|
||||
const tw = st.tower;
|
||||
@@ -636,23 +659,28 @@
|
||||
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);
|
||||
if (R.flipper) R.flipper.rotation.z = -0.32 + (r.flipAnim > 0 ? Math.sin((1 - r.flipAnim / 0.35) * Math.PI) * 1.5 : 0);
|
||||
if (R.lance) {
|
||||
// boost is set for 0.8 s when the lance fires -> fast stab out and back
|
||||
const k = r.boost > 0 ? r.boost / 0.8 : 0;
|
||||
R.lance.position.x = R.lance.userData.baseX + Math.sin(Math.min(1, (1 - k) * 2.2) * Math.PI) * 0.55;
|
||||
// animate each mounted weapon from its own state r.W[i]
|
||||
const wlist = R.weapons || [];
|
||||
for (let i = 0; i < wlist.length; i++) {
|
||||
const wo = wlist[i], W = (r.W && r.W[i]) || {}, w = R.st.weapons[i] && R.st.weapons[i].part;
|
||||
if (!wo || !w) continue;
|
||||
if (wo.flipper) wo.flipper.rotation.z = -0.32 + ((W.flipAnim || 0) > 0 ? Math.sin((1 - W.flipAnim / 0.35) * Math.PI) * 1.5 : 0);
|
||||
if (wo.lance) { // W.fire runs 0.8s on a thrust -> fast, deep stab out and back
|
||||
const k = (W.fire || 0) > 0 ? W.fire / 0.8 : 0;
|
||||
wo.lance.position.x = wo.lance.userData.baseX + Math.sin(Math.min(1, (1 - k) * 2.2) * Math.PI) * 0.95;
|
||||
}
|
||||
if (wo.hammer) {
|
||||
let ang = 1.9;
|
||||
if ((W.swing || 0) > 0) { const k = 1 - W.swing / 0.28; ang = lerp(1.9, -0.25, k * k); }
|
||||
else if (W.cd > w.cd - 0.28 - 0.15) ang = -0.25;
|
||||
else if (W.cd > 0) ang = lerp(-0.25, 1.9, clamp((w.cd - 0.43 - W.cd) / 0.5, 0, 1));
|
||||
wo.hammer.rotation.z = ang;
|
||||
}
|
||||
if (wo.saw) { if (W.sawOn) wo.sawA = (wo.sawA || 0) + dt * 40; wo.saw.rotation[wo.sawAxis || 'z'] = -(wo.sawA || 0); }
|
||||
if (wo.spinner) { wo.spinA = (wo.spinA || 0) + dt * (W.spin || 0) * 38; wo.spinner.rotation.y = wo.spinA; }
|
||||
if (wo.vspin) { wo.spinA = (wo.spinA || 0) + dt * (W.spin || 0) * 40; wo.vspin.rotation.z = -wo.spinA; }
|
||||
if (wo.jaws) for (const j of wo.jaws) j.rotation.y = j.userData.side * ((W.grab || 0) > 0 ? -0.18 : 0.45);
|
||||
}
|
||||
if (R.hammer) {
|
||||
let ang = 1.9;
|
||||
if (r.swing > 0) { const k = 1 - r.swing / 0.28; ang = lerp(1.9, -0.25, k * k); }
|
||||
else if (w && r.cd > w.cd - 0.28 - 0.15) ang = -0.25;
|
||||
else if (w && r.cd > 0) ang = lerp(-0.25, 1.9, clamp((w.cd - 0.43 - r.cd) / 0.5, 0, 1));
|
||||
R.hammer.rotation.z = ang;
|
||||
}
|
||||
if (R.saw) { if (r.sawOn) R.sawA += dt * 40; R.saw.rotation[R.sawAxis || 'z'] = -R.sawA; }
|
||||
if (R.spinner) { R.spinA += dt * r.spin * 38; R.spinner.rotation.y = R.spinA; }
|
||||
if (R.vspin) { R.spinA += dt * r.spin * 40; R.vspin.rotation.z = -R.spinA; }
|
||||
if (R.jaws) for (const j of R.jaws) j.rotation.y = j.userData.side * (r.grab > 0 ? -0.18 : 0.45);
|
||||
if (R.turret) R.turret.rotation.y = -(r.turretA - r.a);
|
||||
if (R.flame) {
|
||||
const tw2 = R.st.tower, beam = r.flameOn || (tw2 && tw2.type === 'zapper' && r.gunOn);
|
||||
@@ -1038,7 +1066,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;
|
||||
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 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
|
||||
@@ -1047,17 +1075,19 @@
|
||||
const R = gRobot; if (!R) return;
|
||||
demoT += dt;
|
||||
const c = demoT % 3; // one signature move every 3 s
|
||||
if (R.saw) { R.sawA += dt * 26; R.saw.rotation[R.sawAxis || 'z'] = -R.sawA; }
|
||||
if (R.spinner) { R.spinA += dt * 17; R.spinner.rotation.y = R.spinA; }
|
||||
if (R.vspin) { R.spinA += dt * 19; R.vspin.rotation.z = -R.spinA; }
|
||||
if (R.hammer) {
|
||||
const k = c < 0.35 ? c / 0.35 : c < 1.2 ? 1 - (c - 0.35) / 0.85 : 0;
|
||||
R.hammer.rotation.z = lerp(1.9, -0.25, k);
|
||||
}
|
||||
if (R.flipper) R.flipper.rotation.z = -0.32 + (c < 0.3 ? Math.sin(c / 0.3 * Math.PI) * 1.5 : 0);
|
||||
if (R.jaws) {
|
||||
const k = c < 1.2 ? Math.abs(Math.sin(c / 1.2 * Math.PI)) : 0;
|
||||
for (const j of R.jaws) j.rotation.y = j.userData.side * (0.45 - k * 0.63);
|
||||
for (const wo of R.weapons || []) {
|
||||
if (wo.saw) { wo.sawA = (wo.sawA || 0) + dt * 26; wo.saw.rotation[wo.sawAxis || 'z'] = -wo.sawA; }
|
||||
if (wo.spinner) { wo.spinA = (wo.spinA || 0) + dt * 17; wo.spinner.rotation.y = wo.spinA; }
|
||||
if (wo.vspin) { wo.spinA = (wo.spinA || 0) + dt * 19; wo.vspin.rotation.z = -wo.spinA; }
|
||||
if (wo.hammer) {
|
||||
const k = c < 0.35 ? c / 0.35 : c < 1.2 ? 1 - (c - 0.35) / 0.85 : 0;
|
||||
wo.hammer.rotation.z = lerp(1.9, -0.25, k);
|
||||
}
|
||||
if (wo.flipper) wo.flipper.rotation.z = -0.32 + (c < 0.3 ? Math.sin(c / 0.3 * Math.PI) * 1.5 : 0);
|
||||
if (wo.jaws) {
|
||||
const k = c < 1.2 ? Math.abs(Math.sin(c / 1.2 * Math.PI)) : 0;
|
||||
for (const j of wo.jaws) j.rotation.y = j.userData.side * (0.45 - k * 0.63);
|
||||
}
|
||||
}
|
||||
if (R.gun) { R.gunA += dt * 16; R.gun.rotation.x = R.gunA; }
|
||||
const shooting = c > 1.5 && c < 2.3;
|
||||
@@ -1096,7 +1126,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, arena: 'workshop' }), builds, paints);
|
||||
mode = 'intro'; introT = 0; pointMode(true);
|
||||
mode = 'intro'; introT = 0; introLightK = 0; pointMode(true);
|
||||
// compile every shader up front, otherwise the first seconds stutter while they are built
|
||||
try { renderer.compile(arenaScene, pcam); } catch (e) { /* older three: just carry on */ }
|
||||
},
|
||||
@@ -1108,6 +1138,39 @@
|
||||
gRobot.root.position.y = 0.12;
|
||||
garage.turntable.add(gRobot.root);
|
||||
},
|
||||
// editor: stop / resume the turntable auto-spin so the robot holds still
|
||||
freeze(on) { hold = on ? 1e9 : 0; },
|
||||
setEditWeapon(i) { editSel = i | 0; },
|
||||
// which weapon (index) is under the pointer, or -1
|
||||
pickWeaponAt(cx, cy) {
|
||||
if (!gRobot || !gRobot.weapons) return -1;
|
||||
const r = new T.Raycaster(); r.setFromCamera(ndcOf(canvas, cx, cy), gcam);
|
||||
for (let i = 0; i < gRobot.weapons.length; i++) {
|
||||
const wo = gRobot.weapons[i];
|
||||
if (wo && wo.wmount && r.intersectObject(wo.wmount, true).length) return i;
|
||||
}
|
||||
return -1;
|
||||
},
|
||||
// drag the selected weapon: snap to the nearest side + set height; returns { side, up } or null
|
||||
dragWeapon(cx, cy) {
|
||||
if (!gRobot || !gRobot.weapons || !gRobot.weapons[editSel]) return null;
|
||||
const wo = gRobot.weapons[editSel], st = gRobot.st, inst = st.weapons[editSel];
|
||||
const clamp = x => Math.max(-0.3, Math.min(0.6, x));
|
||||
gRobot.root.updateWorldMatrix(true, false);
|
||||
const center = new T.Vector3(); gRobot.root.getWorldPosition(center); center.y += st.h * 0.5;
|
||||
const r = new T.Raycaster(); r.setFromCamera(ndcOf(canvas, cx, cy), gcam);
|
||||
const hz = new T.Vector3();
|
||||
if (!r.ray.intersectPlane(new T.Plane(new T.Vector3(0, 1, 0), -center.y), hz)) return null;
|
||||
const loc = gRobot.root.worldToLocal(hz.clone()), ang = Math.atan2(loc.z, loc.x);
|
||||
const side = Math.abs(ang) < Math.PI / 4 ? 'front' : Math.abs(ang) > 3 * Math.PI / 4 ? 'back' : ang > 0 ? 'right' : 'left';
|
||||
let up = inst.mountUp || 0;
|
||||
const n = new T.Vector3().subVectors(gcam.position, center); n.y = 0; n.normalize();
|
||||
const vp = new T.Vector3();
|
||||
if (r.ray.intersectPlane(new T.Plane(n, -n.dot(center)), vp)) up = clamp(vp.y - center.y);
|
||||
inst.mountA = RC.MOUNTS[side].a; inst.mountAxis = RC.MOUNTS[side].axis; inst.mountUp = up;
|
||||
placeMount(wo.wmount, inst, st.len, st.wid);
|
||||
return { side, up };
|
||||
},
|
||||
// live update while painting (colour or drawing changed, no rebuild)
|
||||
setPaint(paint) { if (gRobot) gRobot.skin.redraw(paint); },
|
||||
// camera for the paint booth: closer, robot centred in the left part
|
||||
@@ -1189,10 +1252,12 @@
|
||||
get camMode() { return camMode; },
|
||||
setCam(m) {
|
||||
camMode = m; chaseInit = false;
|
||||
pcam.fov = m === 'fpv' ? 72 : 55; pcam.updateProjectionMatrix();
|
||||
pcam.fov = m === 'fpv' ? (comfort ? 62 : 70) : 55; pcam.updateProjectionMatrix(); // narrower fpv fov = less vection
|
||||
if (mode === 'arena') pointMode(m !== 'iso');
|
||||
if (robots[0] && robots[0].turret) robots[0].turret.visible = m !== 'fpv';
|
||||
},
|
||||
// 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);
|
||||
// behind the camera (chase / cockpit): off screen
|
||||
@@ -1217,7 +1282,8 @@
|
||||
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);
|
||||
const sx = (Math.random() - 0.5) * shake, sz = (Math.random() - 0.5) * shake;
|
||||
const sk = comfort ? 0.4 : 1; // comfort: soften camera shake
|
||||
const sx = (Math.random() - 0.5) * shake * sk, sz = (Math.random() - 0.5) * shake * sk;
|
||||
flashT = Math.max(0, flashT - dt * 3);
|
||||
arena.flashLight.intensity = flashT * 4;
|
||||
if (camMode !== 'iso' && state && robots[0]) {
|
||||
@@ -1241,7 +1307,11 @@
|
||||
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);
|
||||
// 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);
|
||||
} 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;
|
||||
@@ -1261,21 +1331,27 @@
|
||||
if (L.hemi) L.hemi.intensity = 0.55 * (0.12 + 0.88 * k);
|
||||
M.lamp.emissiveIntensity = 1.5 * k;
|
||||
}
|
||||
const smoother = u => u * u * u * (u * (u * 6 - 15) + 10); // smootherstep: zero velocity at both ends
|
||||
function introScript(dt) {
|
||||
const t = introT, s = state;
|
||||
// floodlights: off, flicker, on
|
||||
lightsOn(t < 0.25 ? 0.12 : t < 0.4 ? 1 : t < 0.55 ? 0.15 : t < 0.7 ? 0.9 : t < 0.85 ? 0.3 : 1);
|
||||
// camera path, then a slow orbit
|
||||
// floodlights: dark -> two quick flickers -> full; softened by easing the intensity toward the target
|
||||
const target = t < 0.25 ? 0.12 : t < 0.4 ? 1 : t < 0.52 ? 0.2 : t < 0.64 ? 1 : t < 0.78 ? 0.45 : 1;
|
||||
introLightK += (target - introLightK) * Math.min(1, dt * 16);
|
||||
lightsOn(introLightK);
|
||||
// one continuous cinematic dolly: low & close -> rise and pull back to a hero 3/4, with a gentle orbit throughout
|
||||
const orbit = t * 0.05;
|
||||
let ang, r, h, lx, lz;
|
||||
if (t < INTRO_END) {
|
||||
const e = ease(Math.min(1, t / INTRO_END));
|
||||
ang = lerp(-2.4, Math.PI / 4, e); r = lerp(9, 20.5, e); h = lerp(2.4, 13.5, Math.pow(e, 1.4));
|
||||
lx = lerp(RC.ARENA.pit.x, -0.6, e); lz = lerp(RC.ARENA.pit.z, -0.6, e);
|
||||
const u = smoother(Math.min(1, t / INTRO_END));
|
||||
ang = lerp(-2.4, Math.PI / 4, u) + orbit;
|
||||
r = lerp(8.2, 19.5, u);
|
||||
h = lerp(1.7, 13, u);
|
||||
lx = lerp(RC.ARENA.pit.x * 0.5, -0.3, u); lz = lerp(RC.ARENA.pit.z * 0.5, -0.3, u);
|
||||
} else {
|
||||
ang = Math.PI / 4 + (t - INTRO_END) * 0.05; r = 20.5; h = 13.5; lx = lz = 0;
|
||||
ang = Math.PI / 4 + orbit; r = 19.5; h = 13; lx = -0.3; lz = -0.3; // seamless: matches the sweep's end
|
||||
}
|
||||
pcam.position.set(Math.cos(ang) * r, h, Math.sin(ang) * r);
|
||||
pcam.lookAt(lx, 0.3, lz);
|
||||
pcam.lookAt(lx, 0.45, lz);
|
||||
// robots lowered in from above, landing with sparks
|
||||
s.t = t + 2; // trap timing: flames ignite once the lights are on
|
||||
s.robots.forEach((rb, i) => {
|
||||
@@ -1342,7 +1418,7 @@
|
||||
const main = kill[0];
|
||||
for (const o of kill) if (o !== main) o.visible = false;
|
||||
dropPiece(main);
|
||||
if (part === 'weapon') { R.saw = null; R.spinner = null; R.hammer = null; R.flipper = null; R.jaws = null; }
|
||||
if (/^weapon\d/.test(part)) { const wi = +part.slice(6); if (R.weapons && R.weapons[wi]) R.weapons[wi] = null; } // stop animating the torn-off weapon
|
||||
if (part === 'tower') { R.turret = null; R.flame = null; R.gun = null; R.muzzle = null; }
|
||||
}
|
||||
|
||||
@@ -1353,21 +1429,20 @@
|
||||
robots.forEach((R, i) => {
|
||||
const r = s.robots[i];
|
||||
poseRobot(R, r, dt);
|
||||
// long front weapons must stop at the enemy, not stab through it
|
||||
if (R.lance) {
|
||||
const e = s.robots[1 - i];
|
||||
if (e && !e.out) {
|
||||
const dx = e.x - r.x, dz = e.z - r.z, d = Math.hypot(dx, dz) || 1;
|
||||
const fx = Math.cos(r.a), fz = Math.sin(r.a), facing = (dx * fx + dz * fz) / d;
|
||||
if (facing > 0.55) {
|
||||
const reach = d - e.st.rad * 0.85, base = R.st.len / 2 + 0.95;
|
||||
const maxThrust = Math.max(0, reach - base), bx = R.lance.userData.baseX;
|
||||
if (R.lance.position.x - bx > maxThrust) {
|
||||
const hit = R.lance.position.x - bx - maxThrust > 0.04;
|
||||
R.lance.position.x = bx + maxThrust;
|
||||
if (hit && Math.random() < 0.6) burst(e.x - fx * e.st.rad, 0.4, e.z - fz * e.st.rad, 10, 5, [1, 0.8, 0.4]);
|
||||
}
|
||||
}
|
||||
// each lance must stop at the enemy (in its own mount direction), not stab through it
|
||||
const e = s.robots[1 - i];
|
||||
for (let wi = 0; e && !e.out && wi < (R.weapons || []).length; wi++) {
|
||||
const wo = R.weapons[wi]; if (!wo || !wo.lance) continue;
|
||||
const inst = R.st.weapons[wi];
|
||||
const dx = e.x - r.x, dz = e.z - r.z, d = Math.hypot(dx, dz) || 1;
|
||||
const a = r.a + (inst ? inst.mountA : 0), fx = Math.cos(a), fz = Math.sin(a), facing = (dx * fx + dz * fz) / d;
|
||||
if (facing <= 0.55) continue;
|
||||
const reach = d - e.st.rad * 0.85, bx = wo.lance.userData.baseX;
|
||||
const maxThrust = reach - (bx + 0.95); // may be negative -> pull the lance back into the sleeve
|
||||
if (wo.lance.position.x - bx > maxThrust) {
|
||||
const hit = wo.lance.position.x - bx - maxThrust > 0.04;
|
||||
wo.lance.position.x = bx + Math.max(-0.45, maxThrust);
|
||||
if (hit && Math.random() < 0.6) burst(e.x - fx * e.st.rad, 0.4, e.z - fz * e.st.rad, 10, 5, [1, 0.8, 0.4]);
|
||||
}
|
||||
}
|
||||
// damaged robots smoke, dead ones burn
|
||||
|
||||
@@ -15,6 +15,32 @@
|
||||
const d = (b && b.body) || {};
|
||||
return { hx: clamp(+d.hx || 1, 0.7, 1.6), wx: clamp(+d.wx || 1, 0.8, 1.4), lx: clamp(+d.lx || 1, 0.8, 1.3) };
|
||||
};
|
||||
// where the main weapon is bolted on: front (default), back, left or right.
|
||||
// a = angle offset from the robot's forward (+x); axis = which body half-extent reaches that way.
|
||||
RC.MOUNTS = { front: { a: 0, axis: 'len' }, back: { a: Math.PI, axis: 'len' }, left: { a: Math.PI / 2, axis: 'wid' }, right: { a: -Math.PI / 2, axis: 'wid' } };
|
||||
RC.mountOf = b => {
|
||||
const d = (b && b.mount && b.mount.weapon) || {};
|
||||
const side = RC.MOUNTS[d.side] ? d.side : 'front';
|
||||
return { side, a: RC.MOUNTS[side].a, axis: RC.MOUNTS[side].axis, up: clamp(+d.up || 0, -0.3, 0.6) };
|
||||
};
|
||||
RC.MAX_WEAPONS = 3;
|
||||
// a robot carries up to 3 weapons (same id allowed), each with its own side + height.
|
||||
// new builds use build.weapons = [{id,side,up}]; old builds (single build.weapon + build.mount) are read too.
|
||||
RC.weaponsOf = b => {
|
||||
let list = [];
|
||||
if (b && Array.isArray(b.weapons)) list = b.weapons;
|
||||
else if (b && b.weapon) { const m = b.mount && b.mount.weapon; list = [{ id: b.weapon, side: m && m.side, up: m && m.up }]; }
|
||||
const out = [];
|
||||
for (const w of list) {
|
||||
const p = w && RC.PARTS[w.id];
|
||||
if (!p || p.slot !== 'weapon') continue;
|
||||
const side = RC.MOUNTS[w.side] ? w.side : 'front';
|
||||
out.push({ id: w.id, part: p, side, up: clamp(+w.up || 0, -0.3, 0.6), a: RC.MOUNTS[side].a, axis: RC.MOUNTS[side].axis });
|
||||
if (out.length >= RC.MAX_WEAPONS) break;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
RC.weaponCount = b => (b && Array.isArray(b.weapons) ? b.weapons.filter(w => w && RC.PARTS[w.id] && RC.PARTS[w.id].slot === 'weapon').length : (b && b.weapon ? 1 : 0));
|
||||
const sizeFactor = bo => bo.hx * bo.wx * bo.lx;
|
||||
|
||||
RC.HP_SCALE = 3; // catalogue hp x this = hit points in the arena
|
||||
@@ -23,12 +49,15 @@
|
||||
const errors = [];
|
||||
let weight = 0, power = 0, supply = 0;
|
||||
for (const slot of RC.SLOTS) {
|
||||
if (slot === 'weapon') continue; // weapons are a list now, summed below
|
||||
const p = part(build, slot);
|
||||
if (!p) { if (RC.REQUIRED[slot]) errors.push('need_' + slot); continue; }
|
||||
if (p.slot !== slot) { errors.push('bad_' + slot); continue; }
|
||||
weight += slot === 'chassis' ? Math.round(p.weight * (0.4 + 0.6 * sizeFactor(RC.bodyOf(build)))) : p.weight;
|
||||
if (slot === 'battery') supply += p.power; else power += p.power || 0;
|
||||
}
|
||||
for (const inst of RC.weaponsOf(build)) { weight += inst.part.weight; power += inst.part.power || 0; }
|
||||
if (RC.weaponCount(build) > RC.MAX_WEAPONS) errors.push('too_many_weapons');
|
||||
if (weight > RC.WEIGHT_LIMIT) errors.push('overweight');
|
||||
if (supply && power > supply) errors.push('no_power');
|
||||
return { ok: errors.length === 0, errors, weight, power, supply };
|
||||
@@ -36,15 +65,22 @@
|
||||
|
||||
RC.stats = build => {
|
||||
const ch = part(build, 'chassis'), mo = part(build, 'motor'), wh = part(build, 'wheels');
|
||||
const ar = part(build, 'armour'), we = part(build, 'weapon'), to = part(build, 'tower'), gd = part(build, 'gadget');
|
||||
const ar = part(build, 'armour'), to = part(build, 'tower'), gd = part(build, 'gadget');
|
||||
const v = RC.validate(build);
|
||||
const mass = Math.max(30, v.weight);
|
||||
let value = 0;
|
||||
for (const slot of RC.SLOTS) { const p = part(build, slot); if (p) value += p.cost; }
|
||||
for (const slot of RC.SLOTS) { if (slot === 'weapon') continue; const p = part(build, slot); if (p) value += p.cost; }
|
||||
const weps = RC.weaponsOf(build);
|
||||
for (const w of weps) value += w.part.cost;
|
||||
// per-weapon mount info; combat/render iterate this list, lead weapon kept on st.weapon/mountA for compat
|
||||
const weapons = weps.map(w => ({ id: w.id, part: w.part, side: w.side, mountA: w.a, mountAxis: w.axis, mountUp: w.up }));
|
||||
const lead = weapons[0] || null;
|
||||
const bo = RC.bodyOf(build), size = sizeFactor(bo);
|
||||
const len = (ch ? ch.len : 1.3) * bo.lx, wid = (ch ? ch.wid : 1.0) * bo.wx;
|
||||
return {
|
||||
body: bo,
|
||||
weapons,
|
||||
mountA: lead ? lead.mountA : 0, mountAxis: lead ? lead.mountAxis : 'len', mountUp: lead ? lead.mountUp : 0,
|
||||
topHeavy: bo.hx / ((bo.wx + bo.lx) / 2), // tall + narrow = easier to tip over
|
||||
hp: (Math.round((ch ? ch.hp : 80) * (0.6 + 0.4 * size)) + (ar ? ar.hp : 0)) * RC.HP_SCALE,
|
||||
reduce: ar ? ar.reduce : 0,
|
||||
@@ -56,7 +92,7 @@
|
||||
push: wh ? wh.push : 1,
|
||||
len, wid, h: (ch ? ch.h : 0.42) * bo.hx,
|
||||
rad: Math.hypot(len, wid) / 2 * 0.95, // body corners - bigger = robots keep more distance, less clipping
|
||||
weapon: we, tower: to, gadget: gd, armour: ar,
|
||||
weapon: lead ? lead.part : null, tower: to, gadget: gd, armour: ar,
|
||||
invertible: !!(wh && wh.invertible),
|
||||
lowProfile: !!(ch && ch.lowProfile),
|
||||
frontArmour: ch && ch.frontArmour ? ch.frontArmour : 0,
|
||||
|
||||
172
game/shop.js
172
game/shop.js
@@ -25,7 +25,7 @@
|
||||
|
||||
RC.Shop = function (opt) {
|
||||
const t = opt.t;
|
||||
let slot = 'weapon', sel = undefined, tipN = 0, topTab = 'build', designerOpen = false;
|
||||
let slot = 'chassis', sel = undefined, tipN = 0, topTab = 'build';
|
||||
|
||||
function chipsFor(p) {
|
||||
const s = [];
|
||||
@@ -63,125 +63,125 @@
|
||||
const save = opt.getSave(), b = save.build, v = RC.validate(b);
|
||||
if (sel === undefined || (sel && RC.PARTS[sel].slot !== slot)) sel = b[slot] || null;
|
||||
|
||||
// category tiles
|
||||
$('tabs').innerHTML = RC.SLOTS.map(sl => `<div class="tab ${sl === slot ? 'on' : ''} ${RC.REQUIRED[sl] && !b[sl] ? 'miss' : ''}" data-slot="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span>${t('slot_' + sl)}</span></div>`).join('');
|
||||
$('tabs').querySelectorAll('.tab').forEach(el => { el.onclick = () => { slot = el.dataset.slot; sel = b[slot] || null; opt.sfx.click(); render(); }; });
|
||||
renderTopTabs(); // draw the 3 top tabs (Parts / Paint / Hangar)
|
||||
if (topTab !== 'paint' && opt.onPaintLeave) opt.onPaintLeave(); // close the inline painter when leaving
|
||||
const parts = topTab === 'build';
|
||||
let editing = false;
|
||||
// category tabs + detail + fitted belong to the Parts tab only
|
||||
$('tabs').classList.toggle('hide', !parts);
|
||||
$('fittedwrap').classList.toggle('hide', !parts);
|
||||
{ const d = $('designer'); if (d) d.classList.add('hide'); }
|
||||
|
||||
// part cards
|
||||
const locked = opt.locked || (() => false); // event/unlock: hide parts not released yet
|
||||
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).filter(p => !locked(p.id)).map(p => p.id));
|
||||
$('cards').innerHTML = items.map(id => {
|
||||
const p = id && RC.PARTS[id], eq = b[slot] === id, own = !id || save.owned.includes(id);
|
||||
const badge = eq ? `<span class="badge">${t('equipped')}</span>` : own && id ? `<span class="badge own">${t('owned')}</span>` : '';
|
||||
const price = !p || own ? `<div class="pr"> </div>` : `<div class="pr ${save.money < p.cost ? 'no' : ''}">${ico('money')}${Kit.fmt(p.cost)}</div>`;
|
||||
return `<div class="item ${id === sel ? 'sel' : ''}" data-id="${id || ''}">${badge}${RC.pic(p ? 'part_' + id : null, p ? GLYPH[slot] : '✖')}<div class="nm">${p ? p.name : t('none')}</div>${price}</div>`;
|
||||
}).join('');
|
||||
$('cards').querySelectorAll('.item').forEach(el => { el.onclick = () => { sel = el.dataset.id || null; opt.sfx.click(); render(); }; });
|
||||
|
||||
// detail of the selected card
|
||||
const p = sel && RC.PARTS[sel], eq = b[slot] === sel, own = !sel || save.owned.includes(sel);
|
||||
let act;
|
||||
if (eq) act = `<button disabled>${t('equipped')}</button>`;
|
||||
else if (own) act = `<button class="primary" data-act="eq">${t('equip')}</button>`;
|
||||
else act = `<button class="primary" data-act="buy" ${save.money < p.cost ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(p.cost) })}</button>`;
|
||||
if (p && own && !eq) act += `<button data-act="sell">${t('sell', { n: Kit.fmt(Math.round(p.cost * SELL)) })}</button>`;
|
||||
if (p && !own && save.money < p.cost) act += `<span class="muted">${t('need_money', { n: Kit.fmt(p.cost - save.money) })}</span>`;
|
||||
$('detail').innerHTML = `${RC.pic(p ? 'part_' + sel : null, p ? GLYPH[slot] : '✖')}
|
||||
<div><div class="nm">${p ? p.name : t('none')}</div><div class="ds">${p ? t('pd_' + sel) : t('none_' + slot)}</div>
|
||||
<div class="chips">${p ? chipsFor(p) : ''}</div><div class="chips" style="margin-top:4px">${deltas(b, sel)}</div></div>
|
||||
<div class="act">${act}</div>`;
|
||||
$('detail').querySelectorAll('button[data-act]').forEach(el => { el.onclick = () => act2(el.dataset.act); });
|
||||
if (parts) {
|
||||
// category tiles; the weapon tab shows the build editor inside the cards area (tabs stay visible)
|
||||
$('tabs').innerHTML = RC.SLOTS.map(sl => `<div class="tab ${sl === slot ? 'on' : ''} ${RC.REQUIRED[sl] && !b[sl] ? 'miss' : ''}" data-slot="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span>${t('slot_' + sl)}</span></div>`).join('');
|
||||
$('tabs').querySelectorAll('.tab').forEach(el => { el.onclick = () => { slot = el.dataset.slot; sel = b[slot] || null; opt.sfx.click(); render(); }; });
|
||||
editing = slot === 'weapon';
|
||||
if (opt.onSlot) opt.onSlot(slot); // game.js: freeze the robot while on the weapon tab
|
||||
$('cards').className = ''; // weapon catalog uses the same card grid as parts
|
||||
$('detail').classList.remove('hide'); // weapon tab also shows the detail/preview panel
|
||||
if (editing) {
|
||||
if (opt.onWeaponTab) opt.onWeaponTab($('cards')); // game.js fills #cards + #detail with the weapon editor
|
||||
} else {
|
||||
const locked = opt.locked || (() => false); // event/unlock: hide parts not released yet
|
||||
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).filter(p => !locked(p.id)).map(p => p.id));
|
||||
$('cards').innerHTML = items.map(id => {
|
||||
const p = id && RC.PARTS[id], eq = b[slot] === id, own = !id || save.owned.includes(id);
|
||||
const badge = eq ? `<span class="badge">${t('equipped')}</span>` : own && id ? `<span class="badge own">${t('owned')}</span>` : '';
|
||||
const price = !p || own ? `<div class="pr"> </div>` : `<div class="pr ${save.money < p.cost ? 'no' : ''}">${ico('money')}${Kit.fmt(p.cost)}</div>`;
|
||||
return `<div class="item ${id === sel ? 'sel' : ''}" data-id="${id || ''}">${badge}${RC.pic(p ? 'part_' + id : null, p ? GLYPH[slot] : '✖')}<div class="nm">${p ? p.name : t('none')}</div>${price}</div>`;
|
||||
}).join('');
|
||||
$('cards').querySelectorAll('.item').forEach(el => { el.onclick = () => { sel = el.dataset.id || null; opt.sfx.click(); render(); }; });
|
||||
const p = sel && RC.PARTS[sel], eq = b[slot] === sel, own = !sel || save.owned.includes(sel);
|
||||
let act;
|
||||
if (eq) act = `<button disabled>${t('equipped')}</button>`;
|
||||
else if (own) act = `<button class="primary" data-act="eq">${t('equip')}</button>`;
|
||||
else act = `<button class="primary" data-act="buy" ${save.money < p.cost ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(p.cost) })}</button>`;
|
||||
if (p && own && !eq) act += `<button data-act="sell">${t('sell', { n: Kit.fmt(Math.round(p.cost * SELL)) })}</button>`;
|
||||
if (p && !own && save.money < p.cost) act += `<span class="muted">${t('need_money', { n: Kit.fmt(p.cost - save.money) })}</span>`;
|
||||
$('detail').innerHTML = `${RC.pic(p ? 'part_' + sel : null, p ? GLYPH[slot] : '✖')}
|
||||
<div><div class="nm">${p ? p.name : t('none')}</div><div class="ds">${p ? t('pd_' + sel) : t('none_' + slot)}</div>
|
||||
<div class="chips">${p ? chipsFor(p) : ''}</div><div class="chips" style="margin-top:4px">${deltas(b, sel)}</div></div>
|
||||
<div class="act">${act}</div>`;
|
||||
$('detail').querySelectorAll('button[data-act]').forEach(el => { el.onclick = () => act2(el.dataset.act); });
|
||||
}
|
||||
} else if (topTab === 'paint') {
|
||||
if (opt.onSlot) opt.onSlot(''); // leave weapon mode / unfreeze
|
||||
$('detail').classList.add('hide');
|
||||
$('cards').className = 'pcards';
|
||||
if (opt.onPaintTab) opt.onPaintTab($('cards')); // game.js: slots + colours + inline painter
|
||||
} else { // hangar
|
||||
if (opt.onSlot) opt.onSlot('');
|
||||
$('detail').classList.add('hide');
|
||||
$('cards').className = 'hcards';
|
||||
if (opt.onHangarView) opt.onHangarView($('cards'));
|
||||
}
|
||||
|
||||
// robot stats (white ghost bar = value with the selected part)
|
||||
const st = RC.stats(b), alt = sel !== b[slot] ? RC.stats(Object.assign({}, b, { [slot]: sel })) : null;
|
||||
const st = RC.stats(b), alt = (parts && !editing && sel !== b[slot]) ? RC.stats(Object.assign({}, b, { [slot]: sel })) : null;
|
||||
const valt = alt ? RC.validate(Object.assign({}, b, { [slot]: sel })) : null;
|
||||
const bar = (val, max, over, ghost) => `<div class="bar">${ghost != null ? `<i class="ghost" style="width:${Math.min(100, ghost / max * 100)}%"></i>` : ''}<i class="${over ? 'over' : ''}" style="width:${Math.min(100, val / max * 100)}%;${ghost != null && ghost < val ? 'opacity:.55' : ''}"></i></div>`;
|
||||
// warn about the build you are PREVIEWING (selected part card / picked weapon) before you commit it, else the current build
|
||||
let shownB = b;
|
||||
if (parts && !editing && sel && sel !== b[slot]) shownB = Object.assign({}, b, { [slot]: sel });
|
||||
else if (editing && opt.weaponPreview) { const pb = opt.weaponPreview(); if (pb) shownB = pb; }
|
||||
const vWarn = shownB === b ? v : RC.validate(shownB);
|
||||
const overW = vWarn.weight > RC.WEIGHT_LIMIT, overP = vWarn.power > vWarn.supply;
|
||||
$('meters').innerHTML = [
|
||||
['weight', t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, v.weight > RC.WEIGHT_LIMIT, valt && valt.weight), `${v.weight}/${RC.WEIGHT_LIMIT} kg`],
|
||||
['power', t('m_power'), bar(v.power, Math.max(1, v.supply), v.power > v.supply, valt && valt.power), `${v.power}/${v.supply}`],
|
||||
['weight', t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, overW, valt && valt.weight), `${v.weight}/${RC.WEIGHT_LIMIT} kg`, overW],
|
||||
['power', t('m_power'), bar(v.power, Math.max(1, v.supply), overP, valt && valt.power), `${v.power}/${v.supply}`, overP],
|
||||
['hp', t('m_hp'), bar(st.hp, 175 * RC.HP_SCALE, false, alt && alt.hp), Math.round(st.hp)],
|
||||
['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.6, false, alt && alt.turn), st.turn.toFixed(1)],
|
||||
].map(r => `<span class="st" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join('');
|
||||
].map(r => `<span class="st ${r[5] ? 'warn' : ''}" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join('');
|
||||
|
||||
// paint
|
||||
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
|
||||
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${save.paint[key] === c ? 'on' : ''}" data-c="${c}" style="background:${hex(c)}"></span>`).join('');
|
||||
$(id).querySelectorAll('.sw').forEach(el => { el.onclick = () => { save.paint[key] = +el.dataset.c; opt.sfx.click(); opt.onSave(); opt.onPaint(); render(); }; });
|
||||
}
|
||||
// ready-made two-colour schemes
|
||||
const sc = $('paintSchemes');
|
||||
if (sc) {
|
||||
sc.innerHTML = RC.SCHEMES.map(([b2, a2]) => {
|
||||
const on = save.paint.body === b2 && save.paint.accent === a2;
|
||||
return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${hex(b2)}"></i><i style="background:${hex(a2)}"></i></span>`;
|
||||
}).join('');
|
||||
sc.querySelectorAll('.sw').forEach(el => {
|
||||
el.onclick = () => { save.paint.body = +el.dataset.b; save.paint.accent = +el.dataset.a; opt.sfx.click(); opt.onSave(); opt.onPaint(); render(); };
|
||||
});
|
||||
}
|
||||
$('gErr').textContent = v.errors.map(e => t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) })).join(' · ');
|
||||
// build problem -> a loud, blinking message naming exactly what is too weak (battery / weight / motor)
|
||||
const gErr = $('gErr');
|
||||
if (vWarn.errors.length) {
|
||||
const msg = vWarn.errors.map(e => {
|
||||
if (e === 'overweight') return t('err_overweight', { n: RC.WEIGHT_LIMIT });
|
||||
if (e === 'no_power') return t('err_no_power');
|
||||
if (e === 'too_many_weapons') return t('err_too_many_weapons');
|
||||
return t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) });
|
||||
}).join(' · ');
|
||||
gErr.innerHTML = '⚠ ' + msg;
|
||||
gErr.classList.remove('alert'); void gErr.offsetWidth; gErr.classList.add('alert'); // restart the blink on every change/click
|
||||
} else { gErr.textContent = ''; gErr.classList.remove('alert'); }
|
||||
$('bLeague').disabled = !v.ok; $('bTrain').disabled = !v.ok;
|
||||
const name = $('rname');
|
||||
if (document.activeElement !== name) name.value = save.robotName;
|
||||
if (!$('mechTip').textContent) tip();
|
||||
renderTopTabs(); renderFitted(); renderDesigner();
|
||||
renderFitted();
|
||||
// live preview: show the selected part on the 3D robot (even parts you can't afford yet)
|
||||
if (opt.onPreview) opt.onPreview(topTab === 'build' && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b);
|
||||
if (opt.onPreview) opt.onPreview(parts && !editing && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b);
|
||||
}
|
||||
|
||||
// proportions designer (height / width / length) - only on the chassis slot
|
||||
function renderDesigner() {
|
||||
const el = $('designer');
|
||||
if (!el) return;
|
||||
if (slot !== 'chassis') { el.classList.add('hide'); return; }
|
||||
el.classList.remove('hide');
|
||||
el.classList.toggle('open', designerOpen);
|
||||
el.classList.toggle('shut', !designerOpen);
|
||||
const save = opt.getSave(), b = save.build;
|
||||
if (!b.body) b.body = { hx: 1, wx: 1, lx: 1 };
|
||||
const row = (key, label, lo, hi) => `<div class="drow"><span>${t('des_' + label)}</span>`
|
||||
+ `<input type="range" data-k="${key}" min="${lo}" max="${hi}" step="0.05" value="${b.body[key] || 1}">`
|
||||
+ `<span class="dv" id="dv_${key}">${Math.round((b.body[key] || 1) * 100)}%</span></div>`;
|
||||
// collapsed by default: only the header; click the title to expand the three sliders
|
||||
el.innerHTML = `<div class="dh"><span class="dtitle" id="dToggle"><span class="caret">${designerOpen ? '▾' : '▸'}</span>${t('s_body')}</span>${designerOpen ? `<button id="dReset">${t('des_reset')}</button>` : ''}</div>`
|
||||
+ (designerOpen ? row('hx', 'height', 0.7, 1.6) + row('wx', 'width', 0.8, 1.4) + row('lx', 'length', 0.8, 1.3) : '');
|
||||
$('dToggle').onclick = () => { designerOpen = !designerOpen; opt.sfx.click(); renderDesigner(); };
|
||||
if (!designerOpen) return;
|
||||
el.querySelectorAll('input[type=range]').forEach(inp => {
|
||||
inp.oninput = () => {
|
||||
b.body[inp.dataset.k] = +inp.value;
|
||||
$('dv_' + inp.dataset.k).textContent = Math.round(inp.value * 100) + '%';
|
||||
opt.onSave(); opt.onPreview(b); // live 3D while dragging
|
||||
};
|
||||
inp.onchange = () => render(); // on release: refresh weight bar + stats
|
||||
});
|
||||
$('dReset').onclick = () => { b.body = { hx: 1, wx: 1, lx: 1 }; opt.sfx.click(); opt.onSave(); opt.onPreview(b); render(); };
|
||||
}
|
||||
// proportions (height/width/length) now live in the build editor (game.js), not here
|
||||
|
||||
// top mode tabs: Parts / Paint / Hangar
|
||||
// top mode tabs: Parts / Paint / Hangar - all render into #cards (render() routes the content)
|
||||
function renderTopTabs() {
|
||||
const tabs = [['build', '🔧 ' + t('tab_build')], ['paint', '🎨 ' + t('tab_paint')], ['hangar', '🚗 ' + t('tab_hangar')]];
|
||||
$('shopTabs').innerHTML = tabs.map(([k, label]) => `<button class="${k === topTab ? 'on' : ''}" data-tab="${k}">${label}</button>`).join('');
|
||||
$('shopTabs').querySelectorAll('button').forEach(bt => { bt.onclick = () => { setTab(bt.dataset.tab); opt.sfx.click(); }; });
|
||||
$('buildView').classList.toggle('hide', topTab !== 'build');
|
||||
$('paintView').classList.toggle('hide', topTab !== 'paint');
|
||||
$('hangarView').classList.toggle('hide', topTab !== 'hangar');
|
||||
if (topTab === 'hangar' && opt.onHangarView) opt.onHangarView($('hangarView'));
|
||||
}
|
||||
function setTab(k) { topTab = k; renderTopTabs(); }
|
||||
function setTab(k) { topTab = k; render(); }
|
||||
|
||||
// fitted parts summary (left column): every slot with the equipped part + quick remove/jump
|
||||
function renderFitted() {
|
||||
const save = opt.getSave(), b = save.build;
|
||||
$('fitted').innerHTML = RC.SLOTS.map(sl => {
|
||||
if (sl === 'weapon') { // weapons are a list -> open the editor
|
||||
const ws = RC.weaponsOf(b), label = ws.length ? ws[0].part.name + (ws.length > 1 ? ' ×' + ws.length : '') : t('none');
|
||||
return `<div class="frow" data-edit="1">${RC.pic('slot_weapon', GLYPH.weapon)}<span class="fn ${ws.length ? '' : 'empty'}">${label}</span><span class="frm">🔧</span></div>`;
|
||||
}
|
||||
const id = b[sl], p = id && RC.PARTS[id];
|
||||
const rm = p && !RC.REQUIRED[sl] ? `<span class="frm" data-rm="${sl}">✕</span>` : '<span></span>';
|
||||
return `<div class="frow" data-goto="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span class="fn ${p ? '' : 'empty'}">${p ? p.name : t('none')}</span>${rm}</div>`;
|
||||
}).join('');
|
||||
$('fitted').querySelectorAll('.frow').forEach(el => { el.onclick = e => {
|
||||
if (el.dataset.edit) { slot = 'weapon'; opt.sfx.click(); render(); return; }
|
||||
if (e.target.dataset.rm) { const s = e.target.dataset.rm; opt.getSave().build[s] = null; opt.sfx.click(); opt.onSave(); opt.onBuild(); render(); return; }
|
||||
slot = el.dataset.goto; sel = opt.getSave().build[slot] || null; topTab = 'build'; opt.sfx.click(); render();
|
||||
}; });
|
||||
@@ -216,6 +216,6 @@
|
||||
});
|
||||
$('rname').addEventListener('keydown', e => { if (e.key === 'Enter') $('rname').blur(); e.stopPropagation(); });
|
||||
$('mechPic').innerHTML = `<img src="${Kit.asset('assets/Sprites/npc_mechanic.png')}" alt="" onerror="this.classList.add('missing')">`;
|
||||
return { render, tip, setTab, reset() { sel = undefined; topTab = 'build'; } };
|
||||
return { render, tip, setTab, weaponTab() { slot = 'weapon'; render(); }, reset() { sel = undefined; topTab = 'build'; } };
|
||||
};
|
||||
})(window);
|
||||
|
||||
Reference in New Issue
Block a user