main init
This commit is contained in:
134
game/ai.js
Normal file
134
game/ai.js
Normal file
@@ -0,0 +1,134 @@
|
||||
/* Robot Clash - opponent AI and league roster (no DOM). Needs parts.js, robot.js, combat.js.
|
||||
|
||||
const brain = RC.AI.create({ style: 'brawler' | 'flanker' | 'pusher' | 'gunner' | 'dummy', skill: 0..1, seed });
|
||||
input = brain.think(s, me, enemy, dt) -> { throttle, turn, fire, fire2 }
|
||||
RC.LEAGUE -> 8 opponents { id, name, style, skill, prize, build, paint } (style/description texts: lang.js) */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || {});
|
||||
const A = () => RC.ARENA;
|
||||
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
|
||||
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
|
||||
|
||||
function danger(s, x, z, me) {
|
||||
const ar = A(), m = 0.35;
|
||||
if (s.left < ar.pitOpensAt + 2 && Math.abs(x - ar.pit.x) < ar.pit.hw + me.st.rad && Math.abs(z - ar.pit.z) < ar.pit.hd + me.st.rad) return 3;
|
||||
for (const h of ar.saws) if (RC.hazardOn(h, s.t + 0.4) && Math.hypot(x - h.x, z - h.z) < h.r + me.st.rad) return 2;
|
||||
for (const h of ar.flames) if (RC.hazardOn(h, s.t + 0.4) && Math.abs(x - h.x) < h.hw + m && Math.abs(z - h.z) < h.hd + m) return 2;
|
||||
for (const g of [ar.press, ar.crane]) if (Math.abs(x - g.x) < g.hw + m && Math.abs(z - g.z) < g.hd + m) return 2;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function create(opt) {
|
||||
const style = opt.style || 'brawler', skill = clamp(opt.skill == null ? 0.5 : opt.skill, 0, 1);
|
||||
let seed = (opt.seed || 7) >>> 0;
|
||||
const rand = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };
|
||||
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);
|
||||
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;
|
||||
return { turn, throttle };
|
||||
}
|
||||
|
||||
function think(s, me, e, dt) {
|
||||
wait -= dt;
|
||||
const w = me.st.weapon, t = me.st.tower, dist = Math.hypot(e.x - me.x, e.z - me.z);
|
||||
// continuous weapon triggers (every tick, so reach checks are fresh)
|
||||
const inZ = RC.Combat.inZone(s, me, e);
|
||||
if (wait > 0) return withWeapons(hold, s, me, e, dist, inZ);
|
||||
wait = react * (0.6 + rand() * 0.8);
|
||||
if (style === 'dummy') { wob += 0.4; hold = { throttle: 0.35, turn: Math.sin(wob) * 0.6, fire: false, fire2: false }; return hold; }
|
||||
|
||||
// skilled robots aim where the enemy will be
|
||||
const lead = skill * 0.35;
|
||||
let tx = e.x + e.vx * lead, tz = e.z + e.vz * lead;
|
||||
const err = (1 - skill) * 0.9;
|
||||
tx += (rand() - 0.5) * err; tz += (rand() - 0.5) * err;
|
||||
if (style === 'flanker' && dist > 2.2) { // go for side / rear
|
||||
const back = e.a + Math.PI + (rand() < 0.5 ? 0.9 : -0.9);
|
||||
tx = e.x + Math.cos(back) * 1.8; tz = e.z + Math.sin(back) * 1.8;
|
||||
} else if (style === 'pusher') { // line up enemy -> pit (or press corner) and shove
|
||||
const ar = A(), goal = s.pitOpen >= 1 ? ar.pit : ar.press;
|
||||
const gx = goal.x - e.x, gz = goal.z - e.z, gl = Math.hypot(gx, gz) || 1;
|
||||
const bx = e.x - gx / gl * 1.6, bz = e.z - gz / gl * 1.6;
|
||||
const lined = Math.hypot(me.x - bx, me.z - bz) < 1.0 || dist < me.st.rad + e.st.rad + 0.25;
|
||||
if (!lined && dist > 1.1) { tx = bx; tz = bz; }
|
||||
} else if (style === 'gunner' && t) { // keep distance, circle
|
||||
const want = t.type === 'flamer' ? 1.8 : 4.2;
|
||||
if (dist < want) {
|
||||
const away = Math.atan2(me.z - e.z, me.x - e.x) + 0.9;
|
||||
tx = e.x + Math.cos(away) * want; tz = e.z + Math.sin(away) * want;
|
||||
}
|
||||
}
|
||||
let cmd = steer(me, tx, tz, 0.75 + skill * 0.25);
|
||||
|
||||
// avoid hazards in front (skilled robots look further)
|
||||
const look = 0.9 + skill * 1.0, fx = Math.cos(me.a), fz = Math.sin(me.a);
|
||||
const dng = danger(s, me.x + fx * look, me.z + fz * look, me);
|
||||
// enemy right in front and closer than the hazard: keep attacking (it lands in there, not me)
|
||||
const enemyAhead = dist < look + me.st.rad + e.st.rad && Math.abs(wrap(Math.atan2(e.z - me.z, e.x - me.x) - me.a)) < 0.6;
|
||||
if (dng && !enemyAhead && (dng === 3 || dist > 2.2) && rand() < 0.3 + skill * 0.6) {
|
||||
const l = danger(s, me.x + Math.cos(me.a - 0.9) * look, me.z + Math.sin(me.a - 0.9) * look, me);
|
||||
cmd = { throttle: dng === 3 ? -0.5 : 0.25, turn: l ? 1 : -1 };
|
||||
}
|
||||
// unstick after pushing a wall for a while
|
||||
const sp = Math.hypot(me.vx, me.vz);
|
||||
stuck = cmd.throttle > 0.5 && sp < 0.4 ? stuck + react : 0;
|
||||
if (stuck > 1.2) { unstick = 0.7; stuck = 0; }
|
||||
if (unstick > 0) { unstick -= react; cmd = { throttle: -0.8, turn: 0.8 }; }
|
||||
// rammers: after a moment of shoving, back off and charge again (impact speed = damage)
|
||||
const rammer = !w || w.type === 'wedge';
|
||||
const pushing = style === 'pusher' && s.pitOpen >= 1;
|
||||
contact = rammer && !pushing && dist < me.st.rad + e.st.rad + 0.3 ? contact + react : 0;
|
||||
if (contact > 0.45 && retreat <= 0 && rand() < 0.25 + skill * 0.7) { retreat = 0.35 + rand() * 0.3; contact = 0; }
|
||||
if (retreat > 0) { retreat -= react; cmd = { throttle: -1, turn: cmd.turn * 0.3 }; }
|
||||
|
||||
hold = { throttle: cmd.throttle, turn: cmd.turn, fire: false, fire2: false };
|
||||
return withWeapons(hold, s, me, e, dist, inZ);
|
||||
}
|
||||
|
||||
function withWeapons(h, s, me, e, dist, inZ) {
|
||||
const w = me.st.weapon, t = me.st.tower;
|
||||
const out = { throttle: h.throttle, turn: h.turn, fire: false, fire2: false };
|
||||
if (style === 'dummy') return out;
|
||||
if (w) {
|
||||
if (w.type === 'spinner') out.fire = dist < 6;
|
||||
else if (w.type === 'saw') out.fire = dist < 2.6;
|
||||
else if (w.type === 'wedge') out.fire = dist > 1.6 && dist < 4.5 && Math.abs(wrap(Math.atan2(e.z - me.z, e.x - me.x) - me.a)) < 0.25 && rand() < 0.08 + skill * 0.1;
|
||||
else out.fire = inZ && rand() < 0.25 + skill * 0.7;
|
||||
}
|
||||
if (t) out.fire2 = dist < t.range * (t.type === 'flamer' ? 1.05 : 0.9);
|
||||
return out;
|
||||
}
|
||||
return { think };
|
||||
}
|
||||
|
||||
const pal = (body, accent) => ({ body, accent });
|
||||
RC.LEAGUE = [
|
||||
{ id: 'rustbucket', name: 'Rustbucket', style: 'brawler', skill: 0.15, prize: 180,
|
||||
build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x8a5a3a, 0xd9a066) },
|
||||
{ id: 'tintoad', name: 'Tin Toad', style: 'pusher', skill: 0.25, prize: 240,
|
||||
build: { chassis: 'doorstop', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x5d8a3a, 0xc8e070) },
|
||||
{ id: 'buzzkill', name: 'Buzzkill', style: 'brawler', skill: 0.35, prize: 320,
|
||||
build: { chassis: 'crate', motor: 'hornet', wheels: 'rubber', battery: 'nicd', armour: 'steel', weapon: 'saw', tower: null }, paint: pal(0xd8b020, 0x202020) },
|
||||
{ id: 'flapjack', name: 'Flapjack', style: 'flanker', skill: 0.45, prize: 420,
|
||||
build: { chassis: 'doorstop', motor: 'hornet', wheels: 'bigtyre', battery: 'nicd', armour: 'steel', weapon: 'flipper', tower: null }, paint: pal(0x2a6fd8, 0xffffff) },
|
||||
{ id: 'pincer', name: 'Pincer', style: 'pusher', skill: 0.55, prize: 540,
|
||||
build: { chassis: 'bulwark', motor: 'bulldog', wheels: 'tracks', battery: 'nicd', armour: 'steel', weapon: 'crusher', tower: null }, paint: pal(0xc0392b, 0xf0c040) },
|
||||
{ id: 'thunderclap', name: 'Thunderclap', style: 'brawler', skill: 0.65, prize: 680,
|
||||
build: { chassis: 'bulwark', motor: 'hornet', wheels: 'bigtyre', battery: 'nicd', armour: 'titan', weapon: 'hammer', tower: 'flamer' }, paint: pal(0x6a3fb0, 0xffa020) },
|
||||
{ id: 'gravedigger', name: 'Gravedigger', style: 'gunner', skill: 0.8, prize: 860,
|
||||
build: { chassis: 'scarab', motor: 'hornet', wheels: 'tracks', battery: 'lipo', armour: 'titan', weapon: 'wedge', tower: 'rockets' }, paint: pal(0x2b2f36, 0x50e080) },
|
||||
{ id: 'overlord', name: 'Overlord', style: 'flanker', skill: 0.95, prize: 1200,
|
||||
build: { chassis: 'scarab', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: 'steel', weapon: 'spinner', tower: null }, paint: pal(0x101418, 0xff3030) },
|
||||
];
|
||||
RC.DUMMY = { id: 'dummy', name: 'Dummy', style: 'dummy', skill: 0, prize: 0,
|
||||
build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: 'steel', weapon: null, tower: null }, paint: pal(0x8c8c8c, 0xff7a1a) };
|
||||
|
||||
RC.AI = { create, danger };
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
428
game/combat.js
Normal file
428
game/combat.js
Normal file
@@ -0,0 +1,428 @@
|
||||
/* Robot Clash - combat simulation (no DOM, deterministic with a seed). Needs parts.js + robot.js.
|
||||
|
||||
const s = RC.Combat.create({ robots: [statsA, statsB], seed: 1, names: ['A','B'] });
|
||||
RC.Combat.step(s, dt, [inputA, inputB]) input = { throttle: -1..1, turn: -1..1, fire: bool, fire2: bool }
|
||||
s.events -> [{ type, x, z, ... }] appended each step; the caller empties it after reading
|
||||
s.result -> null while running, then { winner: 0 | 1 | -1 (draw), reason: 'ko' | 'pit' | 'time' }
|
||||
RC.Combat.inZone(s, me, enemy) -> enemy inside my weapon reach (used by the AI)
|
||||
RC.ARENA -> layout (half size, hazards, guardians, pit), read by render3d.js
|
||||
|
||||
World: x/z floor plane, y up, metres. Robot heading a: forward = (cos a, sin a). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || {});
|
||||
|
||||
const ARENA = (RC.ARENA = {
|
||||
half: 8, // floor from -8..8
|
||||
duration: 120, // seconds
|
||||
pitOpensAt: 60, // seconds left when the pit opens
|
||||
pit: { x: 0, z: 4.6, hw: 1.35, hd: 1.35 },
|
||||
saws: [{ x: -3.2, z: -3.4, r: 0.95, period: 6, on: 2.2, phase: 0 }, { x: 3.2, z: -3.4, r: 0.95, period: 6, on: 2.2, phase: 3 }],
|
||||
flames: [{ x: -2.7, z: 3.3, hw: 0.9, hd: 0.9, period: 7, on: 1.8, phase: 1 }, { x: 2.7, z: 3.3, hw: 0.9, hd: 0.9, period: 7, on: 1.8, phase: 4.5 }],
|
||||
press: { x: 6.25, z: -6.25, hw: 1.6, hd: 1.6 }, // guardian 1: forge press (corner)
|
||||
crane: { x: -6.25, z: 6.25, hw: 1.6, hd: 1.6 }, // guardian 2: magnet crane (corner)
|
||||
starts: [{ x: -5, z: 1.5, a: 0 }, { x: 5, z: 1.5, a: Math.PI }],
|
||||
});
|
||||
|
||||
const G = 22; // gravity
|
||||
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
|
||||
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
|
||||
function rng(seed) { // mulberry32
|
||||
let s = seed >>> 0 || 1;
|
||||
return () => { s = (s + 0x6d2b79f5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
||||
}
|
||||
const inRect = (o, x, z, m = 0) => Math.abs(x - o.x) < o.hw + m && Math.abs(z - o.z) < o.hd + m;
|
||||
const hazardOn = (h, t) => ((t + h.phase) % h.period) < h.on;
|
||||
RC.hazardOn = hazardOn;
|
||||
|
||||
function makeRobot(st, i, name) {
|
||||
const p = ARENA.starts[i];
|
||||
return {
|
||||
i, name, st, x: p.x, z: p.z, a: p.a, vx: 0, vz: 0, av: 0, y: 0, vy: 0,
|
||||
hp: st.hp, maxHp: st.hp, dead: false, out: null, fall: 0,
|
||||
flipped: 0, stun: 0, lifted: 0, grabbedBy: null, grab: 0,
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
function create(opt) {
|
||||
const s = {
|
||||
t: 0, left: ARENA.duration, pitOpen: 0, rand: rng(opt.seed || 1),
|
||||
robots: opt.robots.map((st, i) => makeRobot(st, i, (opt.names || [])[i] || 'Robot ' + (i + 1))),
|
||||
rockets: [], events: [], result: null, endIn: 0,
|
||||
press: { st: 'idle', t: 0, y: 1 }, // idle | warn | slam | up ; y 1 = top, 0 = floor
|
||||
crane: { st: 'idle', t: 0, who: -1, tx: 0, tz: 0, x: ARENA.crane.x, z: ARENA.crane.z },
|
||||
pitAlarm: false,
|
||||
};
|
||||
return s;
|
||||
}
|
||||
|
||||
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);
|
||||
return [dx * c + dz * sn, -dx * sn + dz * c];
|
||||
}
|
||||
function inZone(s, me, e, extra = 0) {
|
||||
if (e.out || me.out) return false;
|
||||
const w = me.st.weapon; 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;
|
||||
}
|
||||
|
||||
// where on the target the hit lands: front 0.8 (+chassis front armour), side 1, rear 1.3
|
||||
function zoneMul(target, sx, sz) {
|
||||
const ang = Math.abs(wrap(Math.atan2(sz - target.z, sx - target.x) - target.a));
|
||||
if (ang < 0.8) return 0.8 * (1 - target.st.frontArmour);
|
||||
if (ang > 2.35) return 1.3;
|
||||
return 1;
|
||||
}
|
||||
|
||||
function damage(s, target, amount, src, opt = {}) {
|
||||
if (target.dead || target.out || amount <= 0 || s.result) return 0;
|
||||
let d = amount * (1 - target.st.reduce * (1 - (opt.pierce || 0)));
|
||||
const from = opt.from || src; // where the hit comes from (rockets: impact point)
|
||||
if (from && !opt.noZone) d *= zoneMul(target, from.x, from.z);
|
||||
d = Math.min(d, target.hp);
|
||||
target.hp -= d; target.taken += d;
|
||||
// judges: hazard damage counts for the opponent (pushing into traps pays off)
|
||||
if (src) src.dealt += d; else s.robots[1 - target.i].dealt += d;
|
||||
if (d >= 0.5 || opt.tick) s.events.push({ type: 'dmg', who: target.i, amount: d, x: target.x, z: target.z, tick: !!opt.tick, kind: opt.kind || 'hit' });
|
||||
if (target.hp <= 0.001) {
|
||||
target.hp = 0; target.dead = true;
|
||||
s.events.push({ type: 'ko', who: target.i, x: target.x, z: target.z });
|
||||
finish(s, 1 - target.i, 'ko');
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
function finish(s, winner, reason) {
|
||||
if (s.result) return;
|
||||
s.result = { winner, reason };
|
||||
s.endIn = 2.2;
|
||||
s.events.push({ type: 'end', winner, reason });
|
||||
}
|
||||
|
||||
function step(s, dt, inputs) {
|
||||
if (s.endIn > 0) { s.endIn -= dt; }
|
||||
s.t += dt;
|
||||
if (!s.result) s.left = Math.max(0, ARENA.duration - s.t);
|
||||
const R = s.robots;
|
||||
|
||||
// pit: opens at half time
|
||||
if (s.left <= ARENA.pitOpensAt) {
|
||||
if (!s.pitAlarm) { s.pitAlarm = true; s.events.push({ type: 'pit_open' }); }
|
||||
s.pitOpen = Math.min(1, s.pitOpen + dt * 0.8);
|
||||
}
|
||||
|
||||
for (let k = 0; k < 2; k++) drive(s, R[k], R[1 - k], (s.result ? null : inputs[k]) || {}, dt);
|
||||
collide(s, R[0], R[1], dt);
|
||||
for (let k = 0; k < 2; k++) weapons(s, R[k], R[1 - k], (s.result ? null : inputs[k]) || {}, dt);
|
||||
rockets(s, dt);
|
||||
hazards(s, dt);
|
||||
|
||||
if (!s.result && s.left <= 0) {
|
||||
const [a, b] = R;
|
||||
let w = a.dealt > b.dealt + 0.5 ? 0 : b.dealt > a.dealt + 0.5 ? 1 : -1;
|
||||
if (w === -1) { const pa = a.hp / a.maxHp, pb = b.hp / b.maxHp; w = pa > pb + 0.01 ? 0 : pb > pa + 0.01 ? 1 : -1; }
|
||||
finish(s, w, 'time');
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
if (r.out) { r.fall += dt; r.y -= dt * (1 + r.fall * 6); return; }
|
||||
if (r.flipped > 0) {
|
||||
r.flipped -= dt;
|
||||
if (r.flipped <= 0) { r.flipped = 0; s.events.push({ type: 'righted', who: r.i, x: r.x, z: r.z }); }
|
||||
}
|
||||
const st = r.st, grounded = r.y <= 0.001 && r.vy <= 0;
|
||||
const held = r.lifted > 0 || r.grabbedBy !== null;
|
||||
const canDrive = !r.dead && !held && r.stun <= 0 && grounded && (r.flipped <= 0 || st.invertible);
|
||||
const [fx, fz] = fwd(r);
|
||||
let vf = r.vx * fx + r.vz * fz, vs = -r.vx * fz + r.vz * fx;
|
||||
if (canDrive) {
|
||||
const thr = clamp(inp.throttle || 0, -1, 1), trn = clamp(inp.turn || 0, -1, 1);
|
||||
let top = st.top * (r.boost > 0 ? 1.65 : 1) * (r.grab > 0 ? 0.6 : 1) * (thr < 0 ? 0.75 : 1);
|
||||
const target = thr * top, acc = st.accel * (r.boost > 0 ? 2 : 1);
|
||||
const braking = Math.abs(target) < Math.abs(vf) || target * vf < 0;
|
||||
const rate = acc * (braking ? 1.6 : 1) * dt;
|
||||
vf += clamp(target - vf, -rate, rate);
|
||||
r.av += (trn * st.turn - r.av) * Math.min(1, 12 * dt);
|
||||
} else {
|
||||
r.av *= Math.max(0, 1 - 6 * dt);
|
||||
}
|
||||
if (grounded && !held) {
|
||||
vs *= Math.max(0, 1 - st.grip * dt);
|
||||
if (!canDrive) vf *= Math.max(0, 1 - 2.5 * dt);
|
||||
else if (!(inp.throttle)) vf *= Math.max(0, 1 - 3 * dt);
|
||||
}
|
||||
r.vx = vf * fx - vs * fz; r.vz = vf * fz + vs * fx;
|
||||
if (!held) { r.a = wrap(r.a + r.av * dt); r.x += r.vx * dt; r.z += r.vz * dt; }
|
||||
|
||||
// vertical (flips, crane drops)
|
||||
if (!held && (r.y > 0 || r.vy > 0)) {
|
||||
r.vy -= G * dt; r.y += r.vy * dt;
|
||||
if (r.y <= 0) {
|
||||
const hard = -r.vy;
|
||||
r.y = 0; r.vy = 0;
|
||||
if (hard > 4) {
|
||||
s.events.push({ type: 'land', who: r.i, x: r.x, z: r.z, hard });
|
||||
damage(s, r, (hard - 4) * 1.6, null, { kind: 'land' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// spike walls
|
||||
const lim = ARENA.half - st.rad * 0.9;
|
||||
for (const ax of ['x', 'z']) {
|
||||
const vk = ax === 'x' ? 'vx' : 'vz';
|
||||
if (Math.abs(r[ax]) > lim) {
|
||||
const sgn = Math.sign(r[ax]), vn = r[vk] * sgn;
|
||||
r[ax] = sgn * lim;
|
||||
if (vn > 0) {
|
||||
if (vn > 1.8 && !r.out) {
|
||||
s.events.push({ type: 'wall', who: r.i, x: r.x, z: r.z, speed: vn });
|
||||
damage(s, r, (vn - 1.8) * 4.5, null, { kind: 'spikes' });
|
||||
}
|
||||
r[vk] = -r[vk] * 0.45;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function collide(s, a, b) {
|
||||
if (a.out || b.out || Math.abs(a.y - b.y) > 0.5) return;
|
||||
if (a.grabbedBy !== null || b.grabbedBy !== null) return;
|
||||
let dx = b.x - a.x, dz = b.z - a.z, d = Math.hypot(dx, dz);
|
||||
const minD = a.st.rad + b.st.rad;
|
||||
if (d >= minD) return;
|
||||
if (d < 1e-4) { dx = 1; dz = 0; d = 1; }
|
||||
const nx = dx / d, nz = dz / d;
|
||||
const ma = a.st.mass * a.st.push * (a.lifted || a.flipped ? 0.4 : 1), mb = b.st.mass * b.st.push * (b.lifted || b.flipped ? 0.4 : 1);
|
||||
const over = minD - d, ia = 1 / ma, ib = 1 / mb, sum = ia + ib;
|
||||
a.x -= nx * over * ia / sum; a.z -= nz * over * ia / sum;
|
||||
b.x += nx * over * ib / sum; b.z += nz * over * ib / sum;
|
||||
const vrel = (b.vx - a.vx) * nx + (b.vz - a.vz) * nz;
|
||||
if (vrel >= 0) return;
|
||||
const j = -(1 + 0.3) * vrel / sum;
|
||||
a.vx -= j * ia * nx; a.vz -= j * ia * nz;
|
||||
b.vx += j * ib * nx; b.vz += j * ib * nz;
|
||||
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
|
||||
for (const [me, e, sx, sz] of [[a, b, nx, nz], [b, a, -nx, -nz]]) {
|
||||
const [fx, fz] = fwd(me);
|
||||
const facing = fx * sx + fz * sz;
|
||||
const myV = me.vx * sx + me.vz * sz;
|
||||
if (facing > 0.55 && myV > 1.2) {
|
||||
const w = me.st.weapon;
|
||||
const ram = w && w.type === 'wedge' ? w.ram : 1;
|
||||
damage(s, e, (impact - 1) * 2.2 * ram, me, { kind: 'ram' });
|
||||
if (w && w.type === 'wedge' && e.y < 0.05 && !e.st.lowProfile) { e.vy = 2.6; e.stun = Math.max(e.stun, 0.25); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function weapons(s, r, e, inp, dt) {
|
||||
const ok = !r.dead && !r.out && r.lifted <= 0 && r.grabbedBy === null && r.flipped <= 0;
|
||||
const w = r.st.weapon, [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); }
|
||||
}
|
||||
}
|
||||
if (r.grab > 0) { // crusher holds the enemy
|
||||
r.grab -= dt;
|
||||
if (!ok || e.out || r.grab <= 0) release(s, r, e);
|
||||
else {
|
||||
const d = r.st.len / 2 + 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) {
|
||||
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 }); }
|
||||
break;
|
||||
case 'flipper':
|
||||
if (inp.fire && r.cd <= 0) {
|
||||
r.cd = w.cd; r.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) {
|
||||
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;
|
||||
e.av += (s.rand() - 0.5) * 6;
|
||||
damage(s, e, w.dmg, r, { kind: 'flip' });
|
||||
if (!e.st.invertible && s.rand() < (e.st.lowProfile ? 0.3 : 0.55)) e.flipped = 3.5;
|
||||
}
|
||||
}
|
||||
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 }); }
|
||||
break;
|
||||
case 'saw':
|
||||
if (inp.fire) {
|
||||
r.sawOn = true;
|
||||
if (inZone(s, r, e)) {
|
||||
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 }); }
|
||||
}
|
||||
}
|
||||
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;
|
||||
s.events.push({ type: 'grab', who: r.i, x: e.x, z: e.z });
|
||||
}
|
||||
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);
|
||||
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;
|
||||
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') r.spin = Math.max(0, r.spin - dt * 0.5);
|
||||
|
||||
// turret: turns towards the enemy by itself
|
||||
const t = r.st.tower;
|
||||
if (!t) return;
|
||||
const want = Math.atan2(e.z - r.z, e.x - r.x), diff = wrap(want - r.turretA);
|
||||
r.turretA = wrap(r.turretA + clamp(diff, -3.2 * dt, 3.2 * dt));
|
||||
if (!ok || !inp.fire2) return;
|
||||
const dist = Math.hypot(e.x - r.x, e.z - r.z), aimed = Math.abs(wrap(want - r.turretA));
|
||||
if (t.type === 'flamer') {
|
||||
r.flameOn = true;
|
||||
if (dist < t.range + e.st.rad && aimed < t.cone && !e.out) damage(s, e, t.dps * dt, r, { pierce: 0.5, noZone: true, kind: 'fire', tick: true });
|
||||
} else if (t.type === 'minigun') {
|
||||
r.gunOn = aimed < 0.25;
|
||||
if (r.gunOn && dist < t.range && !e.out) {
|
||||
damage(s, e, t.dps * dt, r, { kind: 'bullet', tick: true });
|
||||
r.fx -= dt; if (r.fx <= 0) { r.fx = 0.08; s.events.push({ type: 'sparks', x: e.x, z: e.z, n: 2, y: 0.4 }); }
|
||||
}
|
||||
} else if (t.type === 'rockets' && r.cd2 <= 0) {
|
||||
r.cd2 = t.cd;
|
||||
s.rockets.push({ owner: r.i, x: r.x, z: r.z, y: r.st.h + 0.45, a: r.turretA, t: 3.2, sp: 6.5 });
|
||||
s.events.push({ type: 'launch', who: r.i, x: r.x, z: r.z });
|
||||
}
|
||||
}
|
||||
|
||||
function release(s, r, e) {
|
||||
r.grab = 0;
|
||||
if (e.grabbedBy === r.i) { e.grabbedBy = null; }
|
||||
}
|
||||
|
||||
function rockets(s, dt) {
|
||||
for (let i = s.rockets.length - 1; i >= 0; i--) {
|
||||
const k = s.rockets[i], tgt = s.robots[1 - k.owner], own = s.robots[k.owner];
|
||||
k.t -= dt;
|
||||
const want = Math.atan2(tgt.z - k.z, tgt.x - k.x);
|
||||
if (!tgt.out) k.a = wrap(k.a + clamp(wrap(want - k.a), -2.4 * dt, 2.4 * dt));
|
||||
k.sp = Math.min(11, k.sp + dt * 6);
|
||||
k.x += Math.cos(k.a) * k.sp * dt; k.z += Math.sin(k.a) * k.sp * dt;
|
||||
k.y += ((tgt.y + 0.35) - k.y) * Math.min(1, dt * 3);
|
||||
const hit = !tgt.out && Math.hypot(tgt.x - k.x, tgt.z - k.z) < tgt.st.rad + 0.1;
|
||||
const wall = Math.abs(k.x) > ARENA.half || Math.abs(k.z) > ARENA.half;
|
||||
if (hit || wall || k.t <= 0) {
|
||||
s.events.push({ type: 'boom', x: k.x, z: k.z, y: k.y });
|
||||
if (hit) {
|
||||
damage(s, tgt, own.st.tower.dmg, own, { from: { x: k.x - Math.cos(k.a), z: k.z - Math.sin(k.a) }, kind: 'rocket' });
|
||||
tgt.vx += Math.cos(k.a) * 1.6; tgt.vz += Math.sin(k.a) * 1.6;
|
||||
}
|
||||
s.rockets.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function hazards(s, dt) {
|
||||
const A = ARENA, R = s.robots;
|
||||
for (const r of R) {
|
||||
if (r.out) continue;
|
||||
const ground = r.y < 0.15 && r.lifted <= 0;
|
||||
// floor saws
|
||||
for (const h of A.saws) {
|
||||
if (ground && hazardOn(h, s.t) && Math.hypot(r.x - h.x, r.z - h.z) < h.r + r.st.rad * 0.45) {
|
||||
damage(s, r, 22 * dt, null, { pierce: 0.3, kind: 'saw', tick: true });
|
||||
r.vx += (s.rand() - 0.5) * 18 * dt; r.vz += (s.rand() - 0.5) * 18 * dt;
|
||||
r.fx -= dt; if (r.fx <= 0) { r.fx = 0.07; s.events.push({ type: 'sparks', x: r.x, z: r.z, n: 5 }); }
|
||||
}
|
||||
}
|
||||
// flame grilles
|
||||
for (const h of A.flames) if (ground && hazardOn(h, s.t) && inRect(h, r.x, r.z, r.st.rad * 0.3)) damage(s, r, 14 * dt, null, { pierce: 0.5, kind: 'fire', tick: true });
|
||||
// pit
|
||||
if (s.pitOpen >= 1 && ground && r.grabbedBy === null && inRect(A.pit, r.x, r.z, -0.15)) {
|
||||
r.out = 'pit'; r.vx *= 0.2; r.vz *= 0.2;
|
||||
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);
|
||||
finish(s, 1 - r.i, 'pit');
|
||||
}
|
||||
r.pressT = inRect(A.press, r.x, r.z) && ground ? r.pressT + dt : 0;
|
||||
r.craneT = inRect(A.crane, r.x, r.z) && ground && r.grabbedBy === null ? r.craneT + dt : 0;
|
||||
}
|
||||
|
||||
// guardian 1: forge press - stay in its corner too long and it comes down
|
||||
const p = s.press;
|
||||
p.t -= dt;
|
||||
if (p.st === 'idle' && R.some(r => r.pressT > 0.6 && !r.out)) { p.st = 'warn'; p.t = 0.7; s.events.push({ type: 'press_warn' }); }
|
||||
else if (p.st === 'warn' && p.t <= 0) { p.st = 'slam'; p.t = 0.12; }
|
||||
else if (p.st === 'slam') {
|
||||
p.y = Math.max(0, p.t / 0.12);
|
||||
if (p.t <= 0) {
|
||||
p.y = 0; p.st = 'up'; p.t = 1.6;
|
||||
s.events.push({ type: 'press', x: A.press.x, z: A.press.z });
|
||||
for (const r of R) if (!r.out && inRect(A.press, r.x, r.z, r.st.rad * 0.3) && r.y < 0.4) {
|
||||
damage(s, r, 28, null, { pierce: 0.5, kind: 'press' }); r.stun = Math.max(r.stun, 1.1);
|
||||
}
|
||||
}
|
||||
} else if (p.st === 'up') { p.y = Math.min(1, 1 - p.t / 1.6 + 0.05); if (p.t <= 0) { p.st = 'idle'; p.y = 1; } }
|
||||
|
||||
// guardian 2: magnet crane - picks a robot up and drops it somewhere (maybe over the pit)
|
||||
const c = s.crane;
|
||||
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);
|
||||
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;
|
||||
c.tx = toPit ? A.pit.x + (s.rand() - 0.5) * 3.5 : (s.rand() - 0.5) * 8;
|
||||
c.tz = toPit ? A.pit.z - 2.4 : (s.rand() - 0.5) * 8 - 1;
|
||||
s.events.push({ type: 'crane', who: r.i, x: r.x, z: r.z });
|
||||
}
|
||||
} else {
|
||||
const r = R[c.who];
|
||||
if (c.st === 'lift') { r.y = Math.min(1.7, r.y + dt * 3); c.x = r.x; c.z = r.z; if (c.t <= 0) { c.st = 'carry'; c.t = 1.4; } }
|
||||
else if (c.st === 'carry') {
|
||||
const k = Math.min(1, dt * 1.6);
|
||||
r.x += (c.tx - r.x) * k; r.z += (c.tz - r.z) * k; r.a = wrap(r.a + dt * 1.5); c.x = r.x; c.z = r.z;
|
||||
if (c.t <= 0) {
|
||||
c.st = 'idle'; c.t = 2.5; r.lifted = 0; r.vy = 0; r.craneT = 0;
|
||||
s.events.push({ type: 'drop', who: r.i, x: r.x, z: r.z });
|
||||
damage(s, r, 8, null, { kind: 'drop' });
|
||||
if (!r.st.invertible && s.rand() < 0.5) r.flipped = 3.5;
|
||||
c.who = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RC.Combat = { create, step, inZone, local };
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
440
game/game.js
Normal file
440
game/game.js
Normal file
@@ -0,0 +1,440 @@
|
||||
/* Robot Clash - game frame: menu, workshop, league ladder, fight, result, saving, audio, scores.
|
||||
Logic lives in parts.js / robot.js / combat.js / ai.js (no DOM), the 3D view in render3d.js,
|
||||
the workshop panel in garage.js. Texts: lang.js via t('key'). Credits line stays in the menu. */
|
||||
(function () {
|
||||
'use strict';
|
||||
const $ = Kit.$;
|
||||
const W = 960, H = 540; // design size of the stage
|
||||
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 = '';
|
||||
|
||||
// Credits (standard for every game): shown in the menu, links open in the normal browser
|
||||
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
|
||||
const CREDITS = `© 2026 Michael Media · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`;
|
||||
|
||||
// ---------------------------------------------------------------- services
|
||||
const L = Kit.i18n(window.LANG, { prefix: ID });
|
||||
const t = L.t;
|
||||
const slot = Kit.saveSlot(ID + '.save', () => ({
|
||||
money: 400, 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', name: '', tutorialSeen: false,
|
||||
}));
|
||||
let save = slot.load();
|
||||
const persist = () => slot.save(save);
|
||||
const audio = Kit.createAudio({
|
||||
prefix: ID,
|
||||
files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_win', 'sfx_lose', 'music_garage', 'music_fight'],
|
||||
});
|
||||
const scores = Kit.scores({ url: DB_URL });
|
||||
const DEV = new URLSearchParams(location.search);
|
||||
const fx = Kit.fx();
|
||||
|
||||
const input = Kit.input({
|
||||
keys: {
|
||||
ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right',
|
||||
' ': 'fire', Shift: 'fire2', e: 'fire2', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok',
|
||||
},
|
||||
onPress(a) {
|
||||
if (a === 'pause') togglePause();
|
||||
else if (a === 'mute') toggleMute();
|
||||
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
|
||||
},
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- sound (synth until ComfyGen clips exist)
|
||||
const last = {};
|
||||
const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; };
|
||||
const SFX = {
|
||||
click() { audio.sfx('sfx_click'); audio.tone(660, 0.05, 'square', 0.08); },
|
||||
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.1); },
|
||||
deny() { audio.tone(160, 0.15, 'square', 0.12, -40); },
|
||||
beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); },
|
||||
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09); },
|
||||
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.12); },
|
||||
event(e) {
|
||||
switch (e.type) {
|
||||
case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break;
|
||||
case 'wall': if (every('wall', 120)) { audio.noise(0.2, 0.35, 1600); audio.tone(190, 0.15, 'sawtooth', 0.1, -90); } break;
|
||||
case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break;
|
||||
case 'swing': audio.noise(0.15, 0.12, 900); break;
|
||||
case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break;
|
||||
case 'spinhit': audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break;
|
||||
case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break;
|
||||
case 'boom': audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
|
||||
case 'ko': audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break;
|
||||
case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break;
|
||||
case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break;
|
||||
case 'press': audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break;
|
||||
case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break;
|
||||
case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break;
|
||||
case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break;
|
||||
case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break;
|
||||
case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break;
|
||||
case 'boost': audio.noise(0.4, 0.25, 1800); break;
|
||||
}
|
||||
},
|
||||
loops(s) { // continuous weapons as short repeated bursts
|
||||
for (const r of s.robots) {
|
||||
if (r.sawOn && every('saw' + r.i, 110)) audio.tone(900 + Math.random() * 60, 0.1, 'sawtooth', 0.035);
|
||||
if (r.flameOn && every('fl' + r.i, 120)) audio.noise(0.14, 0.12, 900);
|
||||
if (r.gunOn && every('gun' + r.i, 70)) audio.noise(0.04, 0.16, 3500);
|
||||
if (r.spin > 0.2 && every('spin' + r.i, 100)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
const cv = $('cv');
|
||||
let ctx = cv.getContext('2d');
|
||||
let view = null;
|
||||
try { view = RC.Render($('gl'), W, H); } catch (err) { console.error(err); }
|
||||
Kit.fit($('app'), { canvases: [[cv, W, H]], onFit(sc) { ctx = cv.getContext('2d'); if (view) view.resize(sc); } });
|
||||
Kit.host.dragArea(document.body);
|
||||
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
|
||||
|
||||
const garage = RC.Garage({
|
||||
t, getSave: () => save, onSave: persist,
|
||||
onBuild: () => { view.showGarage(save.build, save.paint); garageTitle(); },
|
||||
onPaint: () => { view.showGarage(save.build, save.paint); garageTitle(); },
|
||||
sfx: SFX,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
let mode = 'menu'; // menu | garage | league | fight | pause | result
|
||||
let F = null; // current fight
|
||||
const show = (id, on) => $(id).classList.toggle('hide', !on);
|
||||
const overlay = $('overlay');
|
||||
function card(html) { overlay.innerHTML = `<div class="card">${html}</div>`; overlay.classList.remove('hide'); }
|
||||
function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; }
|
||||
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 : '');
|
||||
|
||||
function hud() {
|
||||
$('hMoney').textContent = Kit.fmt(save.money);
|
||||
$('hFame').textContent = Kit.fmt(save.fame);
|
||||
$('hLeague').textContent = t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length });
|
||||
$('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on');
|
||||
}
|
||||
function garageTitle() {
|
||||
$('gName').textContent = save.robotName;
|
||||
$('gSub').textContent = weaponName(save.build);
|
||||
}
|
||||
function setScreen(m) {
|
||||
mode = m;
|
||||
document.body.classList.toggle('fighting', m === 'fight' || m === 'pause');
|
||||
show('garage', m === 'garage');
|
||||
show('gTitle', m === 'garage');
|
||||
show('fightHud', m === 'fight' || m === 'pause' || m === 'result');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- menu
|
||||
function boardHtml() { return scores.enabled ? `<h2 style="margin-top:14px;font-size:18px">${t('ranking')}</h2><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
|
||||
async function fillBoard(myKey) {
|
||||
const el = $('board');
|
||||
if (!el) return;
|
||||
try {
|
||||
const rows = (await scores.top(10)).filter(r => !Kit.badName(r.name));
|
||||
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('')
|
||||
: `<li class="muted">${t('no_scores')}</li>`;
|
||||
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
|
||||
}
|
||||
|
||||
function showMenu() {
|
||||
setScreen('menu');
|
||||
F = null;
|
||||
if (view) view.showGarage(save.build, save.paint);
|
||||
audio.music('music_garage');
|
||||
if (!view) { card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`); return; }
|
||||
const nameField = scores.enabled ? `<div><input id="name" maxlength="20" placeholder="${esc(t('name_placeholder'))}" value="${esc(save.name)}"></div>` : '';
|
||||
card(`<h1>ROBOT CLASH</h1><p>${t('menu_text')}</p>
|
||||
${nameField}<button class="primary" id="bStart">${save.games ? t('continue_career') : t('play')}</button>
|
||||
<div class="row"><button id="bHelp">${t('how_to')}</button><button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>
|
||||
<button id="bReset">${t('reset')}</button></div>
|
||||
${boardHtml()}<p class="credits">${CREDITS}</p>`);
|
||||
$('bLang').onclick = () => { SFX.click(); L.next(); };
|
||||
$('bHelp').onclick = () => { SFX.click(); showHelp(showMenu); };
|
||||
$('bReset').onclick = () => { SFX.click(); confirmReset(); };
|
||||
const name = $('name'), start = $('bStart');
|
||||
if (name) {
|
||||
const check = () => { const n = Kit.cleanName(name.value); start.disabled = !n || Kit.badName(n); };
|
||||
name.addEventListener('input', check); check();
|
||||
name.addEventListener('keydown', e => { if (e.key === 'Enter' && !start.disabled) start.click(); });
|
||||
}
|
||||
start.onclick = () => {
|
||||
if (name) { save.name = Kit.cleanName(name.value); persist(); }
|
||||
SFX.click();
|
||||
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); showHelp(openGarage); } else openGarage();
|
||||
};
|
||||
fillBoard();
|
||||
}
|
||||
|
||||
function showHelp(back) {
|
||||
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>
|
||||
<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
|
||||
<b>Shift / E</b><span>${t('key_tower')}</span><b>P / Esc</b><span>${t('pause')}</span><b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>
|
||||
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`);
|
||||
$('bOk').onclick = () => { SFX.click(); back(); };
|
||||
}
|
||||
function confirmReset() {
|
||||
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>`);
|
||||
$('bNo').onclick = () => { SFX.click(); showMenu(); };
|
||||
$('bYes').onclick = () => { resetSave(); persist(); hud(); SFX.click(); showMenu(); };
|
||||
}
|
||||
function resetSave() {
|
||||
save.money = 400; save.fame = 0; save.best = 0; save.season = 1; save.beaten = 0; save.wins = 0; save.losses = 0; save.games = 0;
|
||||
save.owned = Object.values(RC.STARTER).filter(Boolean); save.build = Object.assign({}, RC.STARTER);
|
||||
save.paint = { body: 0xff7a1a, accent: 0x15171b }; save.robotName = 'Clank'; save.tutorialSeen = false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- workshop + league
|
||||
function openGarage() {
|
||||
hideOverlay();
|
||||
setScreen('garage');
|
||||
view.showGarage(save.build, save.paint);
|
||||
audio.music('music_garage');
|
||||
garage.render(); garageTitle(); hud();
|
||||
}
|
||||
$('bGMenu').onclick = () => { SFX.click(); showMenu(); };
|
||||
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
|
||||
$('bLeague').onclick = () => { SFX.click(); showLeague(); };
|
||||
|
||||
function showLeague() {
|
||||
setScreen('league');
|
||||
const rows = RC.LEAGUE.map((o, i) => {
|
||||
const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked';
|
||||
return `<li class="${cls}"><span>${i < save.beaten ? '✓' : i + 1}</span><span><span class="nm">${o.name}</span><br><span class="muted">${t('style_' + o.style)}</span></span>
|
||||
<span class="muted">${weaponName(o.build)}</span><span class="pz">${Kit.fmt(Math.round(o.prize * seasonMul()))}</span></li>`;
|
||||
}).join('');
|
||||
card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><ol class="ladder">${rows}</ol>
|
||||
<div class="row"><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button><button id="bBack">${t('back')}</button></div>`);
|
||||
$('bFight').onclick = () => { SFX.click(); startFight(RC.LEAGUE[save.beaten], false); };
|
||||
$('bBack').onclick = () => { SFX.click(); openGarage(); };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- fight
|
||||
function startFight(opp, training) {
|
||||
hideOverlay();
|
||||
const stA = RC.stats(save.build), stB = RC.stats(opp.build);
|
||||
const seed = (Date.now() & 0xffff) + save.games * 31;
|
||||
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name] });
|
||||
const skill = Math.min(1, opp.skill + (save.season - 1) * 0.12);
|
||||
F = { s, opp, training, brain: RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4,
|
||||
acc: [0, 0], accT: 0, banner: null, ended: false };
|
||||
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
|
||||
if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
|
||||
if (DEV.has('ff')) {
|
||||
F.count = 0; F.beat = 0;
|
||||
const ai2 = F.auto || RC.AI.create({ style: 'brawler', skill: 0.5, seed });
|
||||
for (let i = 0; i < (+DEV.get('ff') || 20) * 60 && !s.result; i++) {
|
||||
RC.Combat.step(s, 1 / 60, [ai2.think(s, s.robots[0], s.robots[1], 1 / 60), F.brain.think(s, s.robots[1], s.robots[0], 1 / 60)]);
|
||||
s.events.length = 0;
|
||||
}
|
||||
}
|
||||
view.showArena(s, [save.build, opp.build], [save.paint, opp.paint]);
|
||||
$('fN0').textContent = save.robotName; $('fN1').textContent = opp.name;
|
||||
$('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build);
|
||||
$('fH0').style.background = hex(save.paint.body); $('fH1').style.background = hex(opp.paint.body);
|
||||
fx.clear();
|
||||
setScreen('fight');
|
||||
audio.music('music_fight');
|
||||
fightHud();
|
||||
}
|
||||
|
||||
function pad() {
|
||||
const gp = navigator.getGamepads ? Array.from(navigator.getGamepads()).find(Boolean) : null;
|
||||
if (!gp) return null;
|
||||
const dz = v => (Math.abs(v) < 0.18 ? 0 : v);
|
||||
const b = i => !!(gp.buttons[i] && gp.buttons[i].pressed);
|
||||
if (b(9) && every('gpStart', 400)) togglePause();
|
||||
return { throttle: -dz(gp.axes[1] || 0) + (b(12) ? 1 : 0) - (b(13) ? 1 : 0), turn: dz(gp.axes[0] || 0) + (b(15) ? 1 : 0) - (b(14) ? 1 : 0),
|
||||
fire: b(0) || b(7), fire2: b(1) || b(2) || b(6) };
|
||||
}
|
||||
function playerInput() {
|
||||
const k = {
|
||||
throttle: (input.down('up') ? 1 : 0) - (input.down('down') ? 1 : 0),
|
||||
turn: (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0),
|
||||
fire: input.down('fire'), fire2: input.down('fire2'),
|
||||
};
|
||||
const g = pad();
|
||||
if (g) {
|
||||
k.throttle = Kit.clamp(k.throttle + g.throttle, -1, 1); k.turn = Kit.clamp(k.turn + g.turn, -1, 1);
|
||||
k.fire = k.fire || g.fire; k.fire2 = k.fire2 || g.fire2;
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
|
||||
|
||||
function update(dt) {
|
||||
fx.update(dt);
|
||||
if (mode !== 'fight' || !F) return;
|
||||
if (F.count > 0) {
|
||||
F.count -= dt;
|
||||
const n = Math.ceil(F.count);
|
||||
if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } }
|
||||
return;
|
||||
}
|
||||
const s = F.s, [me, en] = s.robots;
|
||||
RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]);
|
||||
for (const e of s.events) {
|
||||
SFX.event(e);
|
||||
if (e.type === 'dmg') F.acc[e.who] += e.amount;
|
||||
else if (e.type === 'pit_open') banner(t('pit_open'), '#ff4a3a', 2);
|
||||
else if (e.type === 'pit') banner(t('into_pit'), '#ff4a3a', 2.2);
|
||||
else if (e.type === 'ko') banner(t('knockout'), '#ff7a1a', 2.2);
|
||||
}
|
||||
view.events(s.events);
|
||||
s.events.length = 0;
|
||||
SFX.loops(s);
|
||||
// damage numbers, grouped
|
||||
F.accT -= dt;
|
||||
if (F.accT <= 0) {
|
||||
F.accT = 0.3;
|
||||
for (let i = 0; i < 2; i++) if (F.acc[i] >= 1) {
|
||||
const r = s.robots[i], p = view.project(r.x, r.y + 1.1, r.z);
|
||||
fx.float(p.x, p.y, '-' + Math.round(F.acc[i]), i === 0 ? '#ff6a5a' : '#ffd060', 16 + Math.min(14, F.acc[i] / 3));
|
||||
F.acc[i] = 0;
|
||||
}
|
||||
}
|
||||
if (s.left <= 10 && !s.result && Math.ceil(s.left) !== F.tick) { F.tick = Math.ceil(s.left); audio.tone(1200, 0.05, 'square', 0.06); }
|
||||
if (s.result && s.endIn <= 0 && !F.ended) { F.ended = true; endFight(); }
|
||||
}
|
||||
|
||||
function fightHud() {
|
||||
if (!F) return;
|
||||
const s = F.s;
|
||||
for (let i = 0; i < 2; i++) $('fH' + i).style.width = (s.robots[i].hp / s.robots[i].maxHp * 100).toFixed(1) + '%';
|
||||
const sec = Math.ceil(s.left);
|
||||
$('fTime').textContent = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
|
||||
$('fTime').classList.toggle('low', sec <= 10);
|
||||
const me = s.robots[0];
|
||||
let st = '';
|
||||
if (me.lifted) st = t('st_lifted'); else if (me.grabbedBy !== null) st = t('st_grabbed');
|
||||
else if (me.flipped > 0 && !me.st.invertible) st = t('st_flipped'); else if (me.stun > 0) st = t('st_stunned');
|
||||
else if (s.pitAlarm) st = t('pit_is_open'); else if (s.left - RC.ARENA.pitOpensAt < 10 && s.left > RC.ARENA.pitOpensAt) st = t('pit_soon');
|
||||
$('fState').textContent = st;
|
||||
}
|
||||
|
||||
function endFight() {
|
||||
const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp);
|
||||
const won = res.winner === 0, me = s.robots[0];
|
||||
const lines = [];
|
||||
let money = 0, fame = 0, champion = false;
|
||||
if (!F.training) {
|
||||
const prize = Math.round(opp.prize * seasonMul());
|
||||
save.games++;
|
||||
if (won) {
|
||||
const bonus = res.reason === 'pit' ? 0.3 : res.reason === 'ko' ? 0.2 : 0;
|
||||
money += prize; lines.push([t('r_prize'), prize]);
|
||||
if (bonus) { const b = Math.round(prize * bonus); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
|
||||
fame = (idx + 1) * 50 * save.season + (res.reason === 'pit' ? 40 : res.reason === 'ko' ? 25 : 0);
|
||||
save.wins++;
|
||||
if (idx === save.beaten) save.beaten++;
|
||||
if (save.beaten >= RC.LEAGUE.length) {
|
||||
champion = true;
|
||||
const cb = 1500 * save.season; money += cb; fame += 500 * save.season; lines.push([t('r_champion'), cb]);
|
||||
save.season++; save.beaten = 0;
|
||||
}
|
||||
} else {
|
||||
const ap = Math.round(prize * 0.2); money += ap; lines.push([t('r_appearance'), ap]);
|
||||
save.losses++;
|
||||
}
|
||||
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.12 + (res.reason === 'pit' && !won ? me.st.value * 0.05 : 0));
|
||||
const paid = Math.min(repair, save.money + money);
|
||||
if (paid) lines.push([t('r_repair'), -paid]);
|
||||
money -= paid;
|
||||
save.money += money; save.fame += fame;
|
||||
persist();
|
||||
}
|
||||
hud();
|
||||
(won ? SFX.win : SFX.lose)();
|
||||
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
|
||||
const why = t('why_' + res.reason + (res.winner === -1 ? '_draw' : won ? '_win' : '_lose'), { name: opp.name });
|
||||
const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
|
||||
const stats = `<span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(me.taken)}</span>`;
|
||||
setScreen('result');
|
||||
card(`<h1>${title}</h1><p>${why}</p>
|
||||
${champion ? `<h2>${t('champion_title', { s: save.season - 1 })}</h2><p>${t('champion_text')}</p>` : ''}
|
||||
<div class="res">${stats}${rows}${!F.training && fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
|
||||
${F.training ? `<p class="muted">${t('training_note')}</p>` : ''}
|
||||
<div class="row"><button class="primary" id="bGarage">${t('to_garage')}</button>${!F.training && !won ? `<button id="bRetry">${t('retry')}</button>` : ''}</div>${boardHtml()}`);
|
||||
$('bGarage').onclick = () => { SFX.click(); openGarage(); };
|
||||
if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false); };
|
||||
if (!F.training && save.fame > save.best) {
|
||||
save.best = save.fame; persist();
|
||||
scores.submit({ name: save.name || save.robotName, score: save.fame, level: save.season }).then(fillBoard);
|
||||
} else fillBoard();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loop
|
||||
let lastNow = 0;
|
||||
function render(alpha, now) {
|
||||
const dt = Math.min(0.05, lastNow ? (now - lastNow) / 1000 : 0.016); lastNow = now;
|
||||
if (view) view.frame(mode === 'pause' ? 0 : dt, now);
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
if (F && (mode === 'fight' || mode === 'pause' || mode === 'result')) {
|
||||
fightHud();
|
||||
fx.apply(ctx); fx.draw(ctx); ctx.restore();
|
||||
const b = F.banner;
|
||||
if (b && b.t > 0) {
|
||||
if (mode !== 'pause') b.t -= dt;
|
||||
const k = b.t / b.max, sc = 1 + Math.max(0, k - 0.75) * 2;
|
||||
ctx.save();
|
||||
ctx.globalAlpha = Math.min(1, k * 3);
|
||||
ctx.translate(W / 2, H * 0.42); ctx.scale(sc, sc);
|
||||
ctx.font = '64px "Russo One", "Segoe UI Black", "Arial Black", Impact, sans-serif';
|
||||
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
ctx.lineWidth = 8; ctx.strokeStyle = '#000'; ctx.strokeText(b.text, 0, 0);
|
||||
ctx.fillStyle = b.color; ctx.fillText(b.text, 0, 0);
|
||||
ctx.restore();
|
||||
}
|
||||
if (mode === 'fight' && F.s.t < 7 && F.count <= 0) {
|
||||
ctx.font = '13px "Segoe UI", sans-serif'; ctx.textAlign = 'center'; ctx.fillStyle = 'rgba(232,235,242,.75)';
|
||||
ctx.fillText(t('fight_hint'), W / 2, H - 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
const loop = Kit.loop({ step: 1000 / 60, update, render }).start();
|
||||
|
||||
function togglePause() {
|
||||
if (mode === 'fight') {
|
||||
mode = 'pause'; loop.pause();
|
||||
card(`<h2>${t('pause')}</h2><div class="row"><button class="primary" id="bGo">${t('continue')}</button><button id="bQuit">${t('give_up')}</button></div>`);
|
||||
$('bGo').onclick = togglePause;
|
||||
$('bQuit').onclick = () => {
|
||||
mode = 'fight'; loop.resume(); hideOverlay();
|
||||
if (F && !F.s.result) { F.s.robots[0].hp = 0; F.s.robots[0].dead = true; F.s.result = { winner: 1, reason: 'ko' }; F.s.endIn = 0; }
|
||||
};
|
||||
} else if (mode === 'pause') { mode = 'fight'; hideOverlay(); loop.resume(); }
|
||||
}
|
||||
function toggleMute() { audio.toggleMute(); hud(); }
|
||||
$('bMute').onclick = toggleMute;
|
||||
$('bPause').onclick = togglePause;
|
||||
$('bLangTop').onclick = () => { SFX.click(); L.next(); };
|
||||
addEventListener('blur', () => { if (mode === 'fight') togglePause(); });
|
||||
// language switch: static texts update themselves (data-i18n), dynamic screens are drawn again
|
||||
L.onChange(() => {
|
||||
hud();
|
||||
if (mode === 'menu') showMenu();
|
||||
else if (mode === 'garage') { garage.render(); garageTitle(); }
|
||||
else if (mode === 'league') showLeague();
|
||||
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
|
||||
});
|
||||
|
||||
if (slot.failed()) console.warn('save failed');
|
||||
// repair saves from older versions: missing parts, invalid ids
|
||||
save.owned = (save.owned || []).filter(id => RC.PARTS[id]);
|
||||
for (const sl of RC.SLOTS) { if (save.build[sl] && !RC.PARTS[save.build[sl]]) save.build[sl] = null; if (save.build[sl] && !save.owned.includes(save.build[sl])) save.owned.push(save.build[sl]); }
|
||||
for (const sl of Object.keys(RC.REQUIRED)) if (!save.build[sl]) { save.build[sl] = RC.STARTER[sl]; if (!save.owned.includes(RC.STARTER[sl])) save.owned.push(RC.STARTER[sl]); }
|
||||
save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1);
|
||||
hud();
|
||||
// dev: index.html?play = straight into the workshop, ?fight = training fight
|
||||
if (view && DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true);
|
||||
else if (view && DEV.has('play')) openGarage(); else showMenu();
|
||||
})();
|
||||
95
game/garage.js
Normal file
95
game/garage.js
Normal file
@@ -0,0 +1,95 @@
|
||||
/* Robot Clash - workshop panel (#garage in index.html): slot tabs, buy / equip / sell parts,
|
||||
weight + power meters, paint. Needs parts.js, robot.js, kit-core.js.
|
||||
|
||||
const gar = RC.Garage({ t, getSave, onBuild(), onPaint(), onSave(), sfx: { click, buy, deny } });
|
||||
gar.render() redraw everything (after language switch, money change)
|
||||
save fields used: money, owned [ids], build {slot: id|null}, paint {body, accent}, robotName */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = root.RC, $ = Kit.$;
|
||||
RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b];
|
||||
const hex = n => '#' + n.toString(16).padStart(6, '0');
|
||||
const SELL = 0.5;
|
||||
|
||||
RC.Garage = function (opt) {
|
||||
const t = opt.t;
|
||||
let slot = 'weapon';
|
||||
|
||||
function statLine(p) {
|
||||
const s = [];
|
||||
if (p.hp) s.push(t('st_hp', { n: p.hp * RC.HP_SCALE }));
|
||||
if (p.slot === 'motor') s.push(t('st_speed', { n: p.speed.toFixed(1) }), t('st_force', { n: p.force }));
|
||||
if (p.slot === 'wheels') s.push(t('st_grip', { n: p.grip }), t('st_turn', { n: p.turn }), p.invertible ? t('st_invert') : '');
|
||||
if (p.slot === 'armour') s.push(t('st_reduce', { n: Math.round(p.reduce * 100) }));
|
||||
if (p.dmg) s.push(t('st_dmg', { n: p.dmg }));
|
||||
if (p.dps) s.push(t('st_dps', { n: p.dps }));
|
||||
if (p.range) s.push(t('st_range', { n: p.range }));
|
||||
s.push(t('st_weight', { n: p.weight }));
|
||||
if (p.slot === 'battery') s.push(t('st_supply', { n: p.power }));
|
||||
else if (p.power) s.push(t('st_power', { n: p.power }));
|
||||
return s.filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
function render() {
|
||||
const save = opt.getSave(), b = save.build, v = RC.validate(b);
|
||||
// tabs
|
||||
$('tabs').innerHTML = RC.SLOTS.map(sl => `<button data-slot="${sl}" class="${sl === slot ? 'on' : ''} ${RC.REQUIRED[sl] && !b[sl] ? 'miss' : ''}">${t('slot_' + sl)}</button>`).join('');
|
||||
$('tabs').querySelectorAll('button').forEach(el => { el.onclick = () => { slot = el.dataset.slot; opt.sfx.click(); render(); }; });
|
||||
// parts of this slot
|
||||
const rows = [];
|
||||
if (!RC.REQUIRED[slot]) rows.push(`<div class="part ${b[slot] ? '' : 'eq'}"><span class="pn">${t('none')}</span><span class="pb">${b[slot] ? `<button data-act="eq" data-id="">${t('equip')}</button>` : `<span class="muted">${t('equipped')}</span>`}</span><span class="pd">${t('none_' + slot)}</span></div>`);
|
||||
for (const p of RC.partsFor(slot)) {
|
||||
const own = save.owned.includes(p.id), eq = b[slot] === p.id;
|
||||
let btns;
|
||||
if (eq) btns = `<span class="muted">${t('equipped')}</span>`;
|
||||
else if (own) btns = `<button data-act="eq" data-id="${p.id}">${t('equip')}</button><button data-act="sell" data-id="${p.id}">${t('sell', { n: Kit.fmt(Math.round(p.cost * SELL)) })}</button>`;
|
||||
else btns = `<button class="buy" data-act="buy" data-id="${p.id}" ${save.money < p.cost ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(p.cost) })}</button>`;
|
||||
rows.push(`<div class="part ${eq ? 'eq' : ''}"><span class="pn">${p.name}</span><span class="pb">${btns}</span><span class="pd">${t('pd_' + p.id)}</span><span class="ps">${statLine(p)}</span></div>`);
|
||||
}
|
||||
$('parts').innerHTML = rows.join('');
|
||||
$('parts').querySelectorAll('button[data-act]').forEach(el => { el.onclick = () => act(el.dataset.act, el.dataset.id || null); });
|
||||
|
||||
// meters
|
||||
const st = RC.stats(b);
|
||||
const bar = (val, max, over) => `<div class="bar"><i class="${over ? 'over' : ''}" style="width:${Math.min(100, val / max * 100)}%"></i></div>`;
|
||||
$('meters').innerHTML = [
|
||||
[t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, v.weight > RC.WEIGHT_LIMIT), `${v.weight}/${RC.WEIGHT_LIMIT} kg`],
|
||||
[t('m_power'), bar(v.power, Math.max(1, v.supply), v.power > v.supply), `${v.power}/${v.supply}`],
|
||||
[t('m_hp'), bar(st.hp, 175 * RC.HP_SCALE), Math.round(st.hp)],
|
||||
[t('m_armour'), bar(st.reduce, 0.4), Math.round(st.reduce * 100) + '%'],
|
||||
[t('m_speed'), bar(st.top, 7), st.top.toFixed(1) + ' m/s'],
|
||||
[t('m_accel'), bar(st.accel, 30), st.accel.toFixed(1)],
|
||||
[t('m_turn'), bar(st.turn, 3), st.turn.toFixed(1)],
|
||||
].map(r => `<span>${r[0]}</span>${r[1]}<span>${r[2]}</span>`).join('');
|
||||
|
||||
// paint
|
||||
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
|
||||
$(id).innerHTML = `<span style="width:58px">${t('paint_' + key)}</span>` + 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(); }; });
|
||||
}
|
||||
$('gErr').textContent = v.errors.map(e => t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) })).join(' · ');
|
||||
$('bLeague').disabled = !v.ok; $('bTrain').disabled = !v.ok;
|
||||
const name = $('rname');
|
||||
if (document.activeElement !== name) name.value = save.robotName;
|
||||
}
|
||||
|
||||
function act(what, id) {
|
||||
const save = opt.getSave(), p = id ? RC.PARTS[id] : null;
|
||||
if (what === 'buy' && p && save.money >= p.cost && !save.owned.includes(id)) {
|
||||
save.money -= p.cost; save.owned.push(id); save.build[slot] = id; opt.sfx.buy();
|
||||
} else if (what === 'eq') {
|
||||
save.build[slot] = id; opt.sfx.click();
|
||||
} else if (what === 'sell' && p && save.build[slot] !== id) {
|
||||
save.owned = save.owned.filter(x => x !== id); save.money += Math.round(p.cost * SELL); opt.sfx.buy();
|
||||
} else { opt.sfx.deny(); return; }
|
||||
opt.onSave(); opt.onBuild(); render();
|
||||
}
|
||||
|
||||
$('rname').addEventListener('input', () => {
|
||||
const s = opt.getSave(), n = Kit.cleanName($('rname').value).slice(0, 18);
|
||||
if (n && !Kit.badName(n)) { s.robotName = n; opt.onSave(); opt.onPaint(); }
|
||||
});
|
||||
$('rname').addEventListener('keydown', e => { if (e.key === 'Enter') $('rname').blur(); e.stopPropagation(); });
|
||||
return { render, get slot() { return slot; } };
|
||||
};
|
||||
})(window);
|
||||
211
game/index.html
Normal file
211
game/index.html
Normal file
@@ -0,0 +1,211 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>Robot Clash</title>
|
||||
<link rel="icon" href="assets/Sprites/icon.png">
|
||||
<style>
|
||||
:root {
|
||||
--bg: #090b10; --panel: #151920; --panel2: #1c212b; --line: #2d3442; --text: #e8ebf2; --dim: #8d95a8;
|
||||
--accent: #ff7a1a; --good: #6dff9e; --warn: #ff5a4a; --blue: #4fa8ff;
|
||||
--head: "Russo One", "Segoe UI Black", "Arial Black", Impact, sans-serif;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text);
|
||||
font: 15px/1.35 "Segoe UI", system-ui, sans-serif; user-select: none; -webkit-user-select: none; touch-action: none; }
|
||||
body { display: flex; align-items: center; justify-content: center;
|
||||
background: radial-gradient(circle at 50% 25%, #1d1f26 0%, var(--bg) 70%); }
|
||||
|
||||
/* fixed design size, scaled to the window by Kit.fit */
|
||||
#app { position: relative; width: 960px; display: flex; flex-direction: column; gap: 8px; }
|
||||
#hud { display: flex; gap: 8px; align-items: center; }
|
||||
.chip { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 5px 11px; }
|
||||
.chip b { color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
.grow { flex: 1; }
|
||||
.logo { font-family: var(--head); letter-spacing: .06em; color: var(--accent); font-size: 20px; padding: 0 6px; }
|
||||
#stage { position: relative; width: 960px; height: 540px; border: 2px solid var(--line); border-radius: 10px; overflow: hidden; background: #000; }
|
||||
#stage canvas { position: absolute; left: 0; top: 0; display: block; }
|
||||
#cv { pointer-events: none; }
|
||||
|
||||
button { font: inherit; color: var(--text); background: var(--panel2); border: 1px solid var(--line);
|
||||
border-radius: 8px; padding: 6px 12px; cursor: pointer; }
|
||||
button:hover { border-color: var(--accent); }
|
||||
button.primary { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; padding: 10px 24px; font-family: var(--head); letter-spacing: .04em; }
|
||||
button:disabled { opacity: .4; cursor: default; }
|
||||
button:disabled:hover { border-color: var(--line); }
|
||||
|
||||
/* overlays (menus) */
|
||||
#overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
|
||||
background: rgba(5, 6, 10, .62); backdrop-filter: blur(2px); z-index: 5; }
|
||||
#overlay.hide { display: none; }
|
||||
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 22px 30px;
|
||||
min-width: 380px; max-width: 640px; text-align: center; box-shadow: 0 20px 60px #000a; }
|
||||
.card h1 { margin: 0 0 6px; font: 44px var(--head); letter-spacing: .05em; color: var(--accent); text-shadow: 0 3px 0 #5a2600; }
|
||||
.card h2 { margin: 0 0 8px; font: 26px var(--head); letter-spacing: .04em; color: var(--accent); }
|
||||
.card p { color: var(--dim); margin: 6px 0 14px; }
|
||||
.card input { font: inherit; width: 220px; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line);
|
||||
background: #0b0e14; color: var(--text); text-align: center; margin-bottom: 12px; }
|
||||
.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); }
|
||||
.muted { color: var(--dim); font-size: 13px; }
|
||||
.card .row { display: flex; gap: 8px; justify-content: center; margin-top: 12px; flex-wrap: wrap; }
|
||||
.credits { margin: 16px 0 0; font-size: 12px; color: var(--dim); }
|
||||
.credits a { color: var(--accent); text-decoration: none; }
|
||||
.credits a:hover { text-decoration: underline; }
|
||||
.keys { display: grid; grid-template-columns: auto auto; gap: 3px 14px; text-align: left; margin: 10px auto 0; width: max-content; font-size: 13px; color: var(--dim); }
|
||||
.keys b { color: var(--text); }
|
||||
|
||||
/* league ladder */
|
||||
.ladder { list-style: none; padding: 0; margin: 10px 0; text-align: left; }
|
||||
.ladder li { display: grid; grid-template-columns: 26px 1fr 150px 80px; gap: 8px; align-items: center; padding: 5px 10px; border-radius: 8px; }
|
||||
.ladder li.done { color: var(--dim); }
|
||||
.ladder li.next { background: #ff7a1a22; border: 1px solid var(--accent); }
|
||||
.ladder li.locked { opacity: .45; }
|
||||
.ladder .nm { font-family: var(--head); letter-spacing: .03em; }
|
||||
.ladder .pz { text-align: right; color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
.res { display: grid; grid-template-columns: 1fr auto; gap: 4px 20px; text-align: left; margin: 10px auto; width: 300px; font-variant-numeric: tabular-nums; }
|
||||
.res .plus { color: var(--good); } .res .minus { color: var(--warn); }
|
||||
|
||||
/* workshop panel */
|
||||
#garage { position: absolute; right: 0; top: 0; bottom: 0; width: 392px; background: rgba(15, 18, 24, .94);
|
||||
border-left: 1px solid var(--line); padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; z-index: 3; }
|
||||
#garage.hide, #fightHud.hide, #gTitle.hide { display: none; }
|
||||
#garage h3 { margin: 0; font: 15px var(--head); letter-spacing: .05em; color: var(--accent); }
|
||||
.tabs { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
|
||||
.tabs button { padding: 5px 2px; font-size: 12px; }
|
||||
.tabs button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
|
||||
.tabs button.miss { border-color: var(--warn); }
|
||||
#parts { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 5px; padding-right: 2px; }
|
||||
.part { background: var(--panel2); border: 1px solid var(--line); border-radius: 8px; padding: 7px 9px; display: grid;
|
||||
grid-template-columns: 1fr auto; gap: 2px 8px; align-items: center; }
|
||||
.part.eq { border-color: var(--accent); background: #2a1c10; }
|
||||
.part .pn { font-weight: 700; }
|
||||
.part .pd { grid-column: 1 / 2; font-size: 12px; color: var(--dim); }
|
||||
.part .ps { grid-column: 1 / 3; font-size: 11.5px; color: #b6bdcc; font-variant-numeric: tabular-nums; }
|
||||
.part .pb { grid-row: 1 / 3; grid-column: 2; display: flex; flex-direction: column; gap: 3px; align-items: stretch; }
|
||||
.part .pb button { padding: 3px 9px; font-size: 12px; }
|
||||
.part .pb .buy { border-color: var(--accent); color: var(--accent); }
|
||||
.meters { display: grid; grid-template-columns: 70px 1fr 64px; gap: 3px 8px; font-size: 12px; align-items: center; font-variant-numeric: tabular-nums; }
|
||||
.bar { height: 8px; background: #0b0e14; border-radius: 4px; overflow: hidden; border: 1px solid var(--line); }
|
||||
.bar i { display: block; height: 100%; background: var(--accent); }
|
||||
.bar i.over { background: var(--warn); }
|
||||
.paint { display: flex; gap: 4px; align-items: center; font-size: 12px; color: var(--dim); }
|
||||
.paint span.sw { width: 20px; height: 20px; border-radius: 5px; border: 2px solid transparent; cursor: pointer; }
|
||||
.paint span.sw.on { border-color: #fff; }
|
||||
.gbtns { display: flex; gap: 6px; }
|
||||
.gbtns .primary { flex: 1; padding: 9px 8px; }
|
||||
.err { color: var(--warn); font-size: 12px; min-height: 16px; }
|
||||
#rname { width: 100%; font: 18px var(--head); letter-spacing: .04em; background: transparent; border: 1px solid transparent;
|
||||
border-radius: 6px; color: var(--text); padding: 2px 6px; }
|
||||
#rname:hover, #rname:focus { border-color: var(--line); outline: none; background: #0b0e14; }
|
||||
#gTitle { position: absolute; left: 18px; bottom: 16px; z-index: 2; pointer-events: none; text-shadow: 0 2px 6px #000; }
|
||||
#gTitle .big { font: 30px var(--head); letter-spacing: .05em; }
|
||||
#gTitle .sub { color: var(--dim); }
|
||||
|
||||
/* fight HUD */
|
||||
#fightHud { position: absolute; left: 0; right: 0; top: 0; padding: 10px 14px; display: grid; grid-template-columns: 1fr 150px 1fr;
|
||||
gap: 12px; pointer-events: none; z-index: 2; }
|
||||
.fbox { background: rgba(10, 12, 16, .78); border: 1px solid var(--line); border-radius: 10px; padding: 6px 10px; }
|
||||
.fbox .fn { font: 16px var(--head); letter-spacing: .04em; display: flex; justify-content: space-between; }
|
||||
.fbox .fn small { font: 12px "Segoe UI", sans-serif; color: var(--dim); }
|
||||
.hp { height: 12px; background: #0b0e14; border-radius: 6px; overflow: hidden; margin-top: 4px; border: 1px solid #000; }
|
||||
.hp i { display: block; height: 100%; transition: width .15s; }
|
||||
#fRight { text-align: right; } #fRight .fn { flex-direction: row-reverse; }
|
||||
#fMid { text-align: center; }
|
||||
#fTime { font: 34px var(--head); line-height: 1; letter-spacing: .04em; }
|
||||
#fTime.low { color: var(--warn); }
|
||||
#fState { font-size: 12px; color: var(--accent); min-height: 16px; font-weight: 700; letter-spacing: .05em; }
|
||||
|
||||
/* 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: 4; }
|
||||
#pad > div { display: grid; grid-template-columns: repeat(3, 60px); gap: 6px; pointer-events: auto; }
|
||||
#pad button { height: 60px; font-size: 20px; opacity: .7; padding: 0; }
|
||||
#pad .fire { grid-template-columns: repeat(2, 74px); }
|
||||
#pad .fire button { height: 74px; font-size: 14px; font-weight: 700; }
|
||||
@media (pointer: coarse) { body.fighting #pad { display: flex; } }
|
||||
|
||||
/* window buttons: only inside the exe (html.exe set by kit-host.js) */
|
||||
#winctl { position: fixed; top: 8px; right: 8px; display: none; gap: 6px; z-index: 10; }
|
||||
html.exe #winctl { display: flex; }
|
||||
#winctl button { width: 34px; height: 30px; padding: 0; opacity: .75; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="winctl">
|
||||
<button onclick="Kit.host.minimize()" data-i18n-title="win_min">–</button>
|
||||
<button onclick="Kit.host.fullscreen()" data-i18n-title="win_full">▢</button>
|
||||
<button onclick="Kit.host.quit()" data-i18n-title="win_close">✕</button>
|
||||
</div>
|
||||
|
||||
<div id="app">
|
||||
<div id="hud">
|
||||
<div class="logo">ROBOT CLASH</div>
|
||||
<div class="chip"><span data-i18n="hud_money">Credits</span> <b id="hMoney">0</b></div>
|
||||
<div class="chip"><span data-i18n="hud_fame">Fame</span> <b id="hFame">0</b></div>
|
||||
<div class="chip"><span data-i18n="hud_league">League</span> <b id="hLeague">-</b></div>
|
||||
<div class="grow"></div>
|
||||
<button id="bLangTop" title="English / Deutsch">🌐</button>
|
||||
<button id="bMute" title="M">Sound</button>
|
||||
<button id="bPause" title="P / Esc" data-i18n="pause">Pause</button>
|
||||
</div>
|
||||
<div id="stage">
|
||||
<canvas id="gl"></canvas>
|
||||
<canvas id="cv"></canvas>
|
||||
|
||||
<div id="gTitle" class="hide"><div class="big" id="gName"></div><div class="sub" id="gSub"></div></div>
|
||||
|
||||
<div id="garage" class="hide">
|
||||
<input id="rname" maxlength="18" spellcheck="false">
|
||||
<div class="tabs" id="tabs"></div>
|
||||
<div id="parts"></div>
|
||||
<div class="meters" id="meters"></div>
|
||||
<div class="paint" id="paintBody"></div>
|
||||
<div class="paint" id="paintAccent"></div>
|
||||
<div class="err" id="gErr"></div>
|
||||
<div class="gbtns">
|
||||
<button class="primary" id="bLeague" data-i18n="to_league">League</button>
|
||||
<button id="bTrain" data-i18n="training">Training</button>
|
||||
<button id="bGMenu" data-i18n="menu">Menu</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="fightHud" class="hide">
|
||||
<div class="fbox" id="fLeft"><div class="fn"><span id="fN0"></span><small id="fW0"></small></div><div class="hp"><i id="fH0"></i></div></div>
|
||||
<div class="fbox" id="fMid"><div id="fTime">2:00</div><div id="fState"></div></div>
|
||||
<div class="fbox" id="fRight"><div class="fn"><span id="fN1"></span><small id="fW1"></small></div><div class="hp"><i id="fH1"></i></div></div>
|
||||
</div>
|
||||
|
||||
<div id="pad">
|
||||
<div>
|
||||
<span></span><button data-action="up">▲</button><span></span>
|
||||
<button data-action="left">◀</button><button data-action="down">▼</button><button data-action="right">▶</button>
|
||||
</div>
|
||||
<div class="fire">
|
||||
<button data-action="fire2" data-i18n="pad_tower">Tower</button><button data-action="fire" data-i18n="pad_weapon">Weapon</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="overlay" class="hide"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="vendor/three.min.js"></script>
|
||||
<script src="kit/kit-core.js"></script>
|
||||
<script src="kit/kit-audio.js"></script>
|
||||
<script src="kit/kit-loop.js"></script>
|
||||
<script src="kit/kit-input.js"></script>
|
||||
<script src="kit/kit-host.js"></script>
|
||||
<script src="kit/kit-scores.js"></script>
|
||||
<script src="kit/kit-fx.js"></script>
|
||||
<script src="kit/kit-i18n.js"></script>
|
||||
<script src="lang.js"></script>
|
||||
<script src="parts.js"></script>
|
||||
<script src="robot.js"></script>
|
||||
<script src="combat.js"></script>
|
||||
<script src="ai.js"></script>
|
||||
<script src="render3d.js"></script>
|
||||
<script src="garage.js"></script>
|
||||
<script src="game.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
157
game/kit/kit-audio.js
Normal file
157
game/kit/kit-audio.js
Normal file
@@ -0,0 +1,157 @@
|
||||
/* Kit audio (v1) - WebAudio for HTML games. From _Tools\Library\web\kit. Needs kit-core.js.
|
||||
|
||||
const audio = Kit.createAudio({
|
||||
prefix: 'mygame', // localStorage keys mygame.muted / .music / .sfx
|
||||
dir: 'assets/Audio/', ext: '.mp3', // where ComfyGen adopt_audio puts the files
|
||||
files: ['sfx_click', 'sfx_win', 'music_game'],
|
||||
throttle: { sfx_step: 60 }, // optional min gap in ms per clip
|
||||
});
|
||||
audio.sfx('sfx_click') play once (silent if missing / not decoded yet)
|
||||
audio.music('music_game') loop as music (switching tracks fades the old one)
|
||||
const h = audio.loop('sfx_flow', 0.5); h.stop() looping effect
|
||||
audio.tone(880, 0.1) / audio.noise(0.2) synth fallback sounds, no files needed
|
||||
audio.toggleMute() / audio.setVolume(music, sfx) / audio.muted / audio.musicVol / audio.sfxVol
|
||||
|
||||
Best effort everywhere: missing files, a blocked AudioContext or no WebAudio never throw.
|
||||
The context is created on the first pointer/key press (autoplay policy) - nothing to call. */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.createAudio = (opt = {}) => {
|
||||
const st = Kit.store(opt.prefix || 'kit');
|
||||
const dir = opt.dir || 'assets/Audio/', ext = opt.ext || '.mp3';
|
||||
const files = opt.files || [], throttle = opt.throttle || {};
|
||||
let ctx = null, musicGain = null, sfxGain = null, musicSrc = null, musicName = null, wantMusic = null;
|
||||
const buffers = {}, loading = {}, last = {};
|
||||
const api = {
|
||||
muted: st.get('muted', false),
|
||||
musicVol: st.get('music', 0.35),
|
||||
sfxVol: st.get('sfx', 0.8),
|
||||
};
|
||||
// slider 0..1 -> gain; squared so the low end of a slider is fine-grained
|
||||
const g = v => (api.muted ? 0 : v * v);
|
||||
|
||||
function unlock() {
|
||||
if (ctx) { if (ctx.state === 'suspended') ctx.resume().catch(() => {}); return; }
|
||||
try {
|
||||
ctx = new (root.AudioContext || root.webkitAudioContext)();
|
||||
musicGain = ctx.createGain(); musicGain.gain.value = g(api.musicVol); musicGain.connect(ctx.destination);
|
||||
sfxGain = ctx.createGain(); sfxGain.gain.value = g(api.sfxVol); sfxGain.connect(ctx.destination);
|
||||
for (const n of files) load(n);
|
||||
if (wantMusic) api.music(wantMusic);
|
||||
} catch (e) { ctx = null; }
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
for (const ev of ['pointerdown', 'keydown', 'touchstart']) addEventListener(ev, unlock, { capture: true, passive: true });
|
||||
// Android leaves a context suspended after backgrounding unless it is resumed by hand
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) ctx.suspend().catch(() => {}); else ctx.resume().catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
function load(name) {
|
||||
if (!ctx) return Promise.resolve(null);
|
||||
if (buffers[name]) return Promise.resolve(buffers[name]);
|
||||
if (loading[name]) return loading[name];
|
||||
return (loading[name] = Kit.loadBytes(Kit.asset(dir + name + ext))
|
||||
.then(b => ctx.decodeAudioData(b))
|
||||
.then(buf => (buffers[name] = buf))
|
||||
.catch(() => null)
|
||||
.finally(() => { delete loading[name]; }));
|
||||
}
|
||||
|
||||
function start(buf, vol, loop, bus) {
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf; src.loop = loop;
|
||||
const gn = ctx.createGain(); gn.gain.value = vol;
|
||||
src.connect(gn).connect(bus);
|
||||
src.start();
|
||||
src.gainNode = gn;
|
||||
return src;
|
||||
}
|
||||
function fadeStop(src) {
|
||||
if (!src || !ctx) return;
|
||||
try { src.gainNode.gain.setTargetAtTime(0, ctx.currentTime, 0.08); src.stop(ctx.currentTime + 0.4); } catch (e) { /* stopped */ }
|
||||
}
|
||||
|
||||
api.sfx = (name, vol = 1) => {
|
||||
if (!ctx || api.muted) return;
|
||||
if (ctx.state === 'suspended') ctx.resume().catch(() => {});
|
||||
const gap = throttle[name] || 0, now = performance.now();
|
||||
if (gap && now - (last[name] || 0) < gap) return;
|
||||
last[name] = now;
|
||||
// first use of a clip that is still decoding: play it once it is ready instead of dropping it
|
||||
if (buffers[name]) start(buffers[name], vol, false, sfxGain);
|
||||
else load(name).then(b => { if (b && !api.muted) start(b, vol, false, sfxGain); });
|
||||
};
|
||||
|
||||
api.loop = (name, vol = 1) => {
|
||||
const h = { src: null, stopped: false, stop() { h.stopped = true; fadeStop(h.src); h.src = null; } };
|
||||
if (!ctx) return h;
|
||||
load(name).then(b => { if (b && !h.stopped) h.src = start(b, vol, true, sfxGain); });
|
||||
return h;
|
||||
};
|
||||
|
||||
api.music = name => {
|
||||
wantMusic = name;
|
||||
if (!ctx || musicName === name) return;
|
||||
musicName = name;
|
||||
load(name).then(b => {
|
||||
if (!b || musicName !== name) { if (!b && musicName === name) musicName = null; return; }
|
||||
fadeStop(musicSrc);
|
||||
musicSrc = start(b, 1, true, musicGain);
|
||||
});
|
||||
};
|
||||
api.stopMusic = () => { wantMusic = null; musicName = null; fadeStop(musicSrc); musicSrc = null; };
|
||||
|
||||
function apply() {
|
||||
if (musicGain) musicGain.gain.value = g(api.musicVol);
|
||||
if (sfxGain) sfxGain.gain.value = g(api.sfxVol);
|
||||
}
|
||||
api.toggleMute = () => { api.muted = !api.muted; st.set('muted', api.muted); apply(); return api.muted; };
|
||||
api.setVolume = (music, sfx) => {
|
||||
if (music != null) { api.musicVol = Kit.clamp(+music || 0, 0, 1); st.set('music', api.musicVol); }
|
||||
if (sfx != null) { api.sfxVol = Kit.clamp(+sfx || 0, 0, 1); st.set('sfx', api.sfxVol); }
|
||||
if (api.muted && (music > 0 || sfx > 0)) { api.muted = false; st.set('muted', false); }
|
||||
apply();
|
||||
};
|
||||
// duck music under a big moment (ramped, no clicks)
|
||||
api.duck = (on, secs = 0.2) => {
|
||||
if (!ctx || !musicGain) return;
|
||||
const t = ctx.currentTime;
|
||||
musicGain.gain.cancelScheduledValues(t);
|
||||
musicGain.gain.setValueAtTime(musicGain.gain.value, t);
|
||||
musicGain.gain.linearRampToValueAtTime(on ? 0 : g(api.musicVol), t + secs);
|
||||
};
|
||||
api.suspend = () => { if (ctx) ctx.suspend().catch(() => {}); };
|
||||
api.resume = () => { if (ctx && !document.hidden) ctx.resume().catch(() => {}); };
|
||||
api.unlock = unlock;
|
||||
|
||||
// ---- synth (placeholder sounds until ComfyGen clips exist) --------------------------
|
||||
api.tone = (freq, dur = 0.1, type = 'square', vol = 0.3, slide = 0, delay = 0) => {
|
||||
if (!ctx || api.muted) return;
|
||||
const t = ctx.currentTime + delay;
|
||||
const o = ctx.createOscillator(), gn = ctx.createGain();
|
||||
o.type = type; o.frequency.setValueAtTime(freq, t);
|
||||
if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(30, freq + slide), t + dur);
|
||||
gn.gain.setValueAtTime(vol, t); gn.gain.exponentialRampToValueAtTime(0.001, t + dur);
|
||||
o.connect(gn).connect(sfxGain); o.start(t); o.stop(t + dur + 0.02);
|
||||
};
|
||||
api.noise = (dur = 0.2, vol = 0.3, cutoff = 1200, delay = 0) => {
|
||||
if (!ctx || api.muted) return;
|
||||
const t = ctx.currentTime + delay, len = Math.floor(ctx.sampleRate * dur);
|
||||
const buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
|
||||
for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len);
|
||||
const src = ctx.createBufferSource(), f = ctx.createBiquadFilter(), gn = ctx.createGain();
|
||||
src.buffer = buf; f.type = 'lowpass'; f.frequency.value = cutoff; gn.gain.value = vol;
|
||||
src.connect(f).connect(gn).connect(sfxGain); src.start(t);
|
||||
};
|
||||
// little arpeggio: audio.arp([523, 659, 784], 0.12)
|
||||
api.arp = (freqs, step = 0.08, type = 'square', vol = 0.18) =>
|
||||
freqs.forEach((f, i) => api.tone(f, step * 1.6, type, vol, 0, i * step));
|
||||
|
||||
return api;
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
142
game/kit/kit-core.js
Normal file
142
game/kit/kit-core.js
Normal file
@@ -0,0 +1,142 @@
|
||||
/* Kit core (v1) - from D:\Oculusquest\Projekt\_Tools\Library\web\kit.
|
||||
Do not fork this copy inside a project: improve it in the Library and re-copy with
|
||||
new-project.ps1 -UpdateKit. Classic script (no ES module) so the game also runs from file://.
|
||||
|
||||
Kit.$(id) document.getElementById
|
||||
Kit.asset(path) path, or the data: URI the single-file build embedded
|
||||
Kit.loadBytes(url) ArrayBuffer (works for data: URIs and files)
|
||||
Kit.images(names, dir, ext) { name: Image } - img.ok is true once loaded
|
||||
Kit.store(prefix) safe localStorage JSON get/set/del
|
||||
Kit.saveSlot(key, defaults, opt) versioned save with backup copy + defaults merge
|
||||
Kit.rng(seed) seeded random() in [0,1) (mulberry32)
|
||||
Kit.clamp / lerp / shuffle / pick / fmt
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
Kit.version = 1;
|
||||
Kit.$ = id => document.getElementById(id);
|
||||
|
||||
// ---- assets ---------------------------------------------------------------------------
|
||||
// build-web.mjs puts every asset into window.KIT_ASSETS as a data: URI, so the release
|
||||
// HTML works from file:// and on any web host without a folder next to it.
|
||||
Kit.asset = path => (root.KIT_ASSETS && root.KIT_ASSETS[path]) || path;
|
||||
|
||||
Kit.loadBytes = url => {
|
||||
if (url.startsWith('data:')) {
|
||||
const bin = atob(url.slice(url.indexOf(',') + 1));
|
||||
const buf = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
||||
return Promise.resolve(buf.buffer);
|
||||
}
|
||||
return fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(r.status + ' ' + url))));
|
||||
};
|
||||
|
||||
// Missing images are fine: draw a fallback shape while !img.ok.
|
||||
Kit.images = (names, dir = 'assets/Sprites/', ext = '.png') => {
|
||||
const out = {};
|
||||
for (const n of names) {
|
||||
const im = new Image();
|
||||
im.ok = false;
|
||||
im.onload = () => { im.ok = true; };
|
||||
im.src = Kit.asset(dir + n + ext);
|
||||
out[n] = im;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// ---- storage --------------------------------------------------------------------------
|
||||
// Every access is wrapped: private mode, blocked storage or a full quota must not crash.
|
||||
Kit.store = prefix => {
|
||||
const p = prefix ? prefix + '.' : '';
|
||||
return {
|
||||
get(k, d) {
|
||||
try { const v = localStorage.getItem(p + k); return v == null ? d : JSON.parse(v); } catch (e) { return d; }
|
||||
},
|
||||
set(k, v) {
|
||||
try { localStorage.setItem(p + k, JSON.stringify(v)); return true; } catch (e) { return false; }
|
||||
},
|
||||
del(k) { try { localStorage.removeItem(p + k); } catch (e) { /* ignore */ } },
|
||||
};
|
||||
};
|
||||
|
||||
/* Save slot for game progress.
|
||||
const slot = Kit.saveSlot('mygame.save', () => ({ level: 1, best: {} }), { version: 2, migrate })
|
||||
let save = slot.load(); ... slot.save(save);
|
||||
- defaults() is a function so every load gets fresh nested objects.
|
||||
- Loaded data is merged over defaults (one level deep for plain objects), so fields added
|
||||
in a later version exist in old saves.
|
||||
- migrate(data, fromVersion) runs when the stored version is older; return the data.
|
||||
- Every backupEvery-th save also writes a backup; a corrupt primary falls back to it.
|
||||
- slot.failed() turns true once a write failed - tell the player once. */
|
||||
Kit.saveSlot = (key, defaults, opt = {}) => {
|
||||
const version = opt.version || 1, every = opt.backupEvery || 10;
|
||||
let since = 0, failed = false;
|
||||
const isObj = v => v && typeof v === 'object' && !Array.isArray(v);
|
||||
function merge(d, s) {
|
||||
const out = Object.assign({}, d, s);
|
||||
for (const k of Object.keys(d)) if (isObj(d[k]) && isObj(s[k])) out[k] = Object.assign({}, d[k], s[k]);
|
||||
return out;
|
||||
}
|
||||
function read(k) {
|
||||
try {
|
||||
const raw = localStorage.getItem(k);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!isObj(parsed)) return null;
|
||||
const from = typeof parsed._v === 'number' ? parsed._v : 1;
|
||||
let s = merge(defaults(), parsed);
|
||||
if (from < version && opt.migrate) s = opt.migrate(s, from) || s;
|
||||
s._v = version;
|
||||
return s;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
return {
|
||||
load() { return read(key) || read(key + '.bak') || Object.assign(defaults(), { _v: version }); },
|
||||
save(data) {
|
||||
data._v = version;
|
||||
try {
|
||||
const json = JSON.stringify(data);
|
||||
localStorage.setItem(key, json);
|
||||
if (++since >= every) { since = 0; localStorage.setItem(key + '.bak', json); }
|
||||
return true;
|
||||
} catch (e) { failed = true; return false; }
|
||||
},
|
||||
clear() { try { localStorage.removeItem(key); localStorage.removeItem(key + '.bak'); } catch (e) { /* ignore */ } },
|
||||
failed: () => failed,
|
||||
};
|
||||
};
|
||||
|
||||
// ---- math / random --------------------------------------------------------------------
|
||||
Kit.rng = seed => {
|
||||
let a = seed >>> 0 || 1;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
};
|
||||
Kit.clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
||||
Kit.lerp = (a, b, t) => a + (b - a) * t;
|
||||
Kit.pick = (arr, rnd = Math.random) => arr[Math.floor(rnd() * arr.length)];
|
||||
Kit.shuffle = (arr, rnd = Math.random) => {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rnd() * (i + 1));
|
||||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
// 1234567 -> "1.23M" (idle games); below 10 000 plain with thousands separator
|
||||
Kit.fmt = n => {
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
const a = Math.abs(n);
|
||||
if (a < 1e4) return Math.round(n).toLocaleString('en-US');
|
||||
const units = ['K', 'M', 'B', 'T', 'Qa', 'Qi'];
|
||||
let u = -1, v = a;
|
||||
while (v >= 1000 && u < units.length - 1) { v /= 1000; u++; }
|
||||
return (n < 0 ? '-' : '') + (v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)) + units[u];
|
||||
};
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = Kit;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
72
game/kit/kit-fx.js
Normal file
72
game/kit/kit-fx.js
Normal file
@@ -0,0 +1,72 @@
|
||||
/* Kit fx (v1) - small juice helpers for canvas games. From _Tools\Library\web\kit.
|
||||
|
||||
const fx = Kit.fx();
|
||||
fx.burst(x, y, '#ffd83a', 16, 180) particles (count, speed px/s)
|
||||
fx.float(x, y, '+10', '#fff') rising, fading text
|
||||
fx.shake(8) screen shake strength in px (decays)
|
||||
fx.update(dt) in loop update
|
||||
fx.apply(ctx) ... draw world ... ctx.restore() (apply saves + offsets for shake)
|
||||
fx.draw(ctx) particles + texts on top
|
||||
Kit.tween(from, to, t, Kit.ease.outBack) */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.ease = {
|
||||
linear: t => t,
|
||||
outQuad: t => 1 - (1 - t) * (1 - t),
|
||||
inOutQuad: t => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2),
|
||||
outCubic: t => 1 - Math.pow(1 - t, 3),
|
||||
outBack: t => 1 + 2.70158 * Math.pow(t - 1, 3) + 1.70158 * Math.pow(t - 1, 2),
|
||||
outElastic: t => (t === 0 || t === 1 ? t : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * (2 * Math.PI / 3)) + 1),
|
||||
};
|
||||
Kit.tween = (a, b, t, ease = Kit.ease.outQuad) => a + (b - a) * ease(Math.max(0, Math.min(1, t)));
|
||||
|
||||
Kit.fx = () => {
|
||||
const parts = [], texts = [];
|
||||
let shake = 0;
|
||||
return {
|
||||
burst(x, y, color = '#fff', n = 14, speed = 160, life = 0.6) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const a = Math.random() * Math.PI * 2, v = speed * (0.4 + Math.random() * 0.8);
|
||||
parts.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life, max: life, color, r: 2 + Math.random() * 2.5 });
|
||||
}
|
||||
},
|
||||
float(x, y, text, color = '#fff', size = 18) { texts.push({ x, y, text, color, size, life: 0.9, max: 0.9 }); },
|
||||
shake(px) { shake = Math.max(shake, px); },
|
||||
update(dt) {
|
||||
for (let i = parts.length - 1; i >= 0; i--) {
|
||||
const p = parts[i];
|
||||
p.life -= dt; if (p.life <= 0) { parts.splice(i, 1); continue; }
|
||||
p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.96; p.vy = p.vy * 0.96 + 220 * dt;
|
||||
}
|
||||
for (let i = texts.length - 1; i >= 0; i--) {
|
||||
const t = texts[i];
|
||||
t.life -= dt; if (t.life <= 0) { texts.splice(i, 1); continue; }
|
||||
t.y -= 40 * dt;
|
||||
}
|
||||
shake = Math.max(0, shake - 40 * dt);
|
||||
},
|
||||
apply(ctx) {
|
||||
ctx.save();
|
||||
if (shake > 0) ctx.translate((Math.random() * 2 - 1) * shake, (Math.random() * 2 - 1) * shake);
|
||||
},
|
||||
draw(ctx) {
|
||||
for (const p of parts) {
|
||||
ctx.globalAlpha = p.life / p.max;
|
||||
ctx.fillStyle = p.color;
|
||||
ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
for (const t of texts) {
|
||||
ctx.globalAlpha = Math.min(1, t.life / t.max * 2);
|
||||
ctx.font = `bold ${t.size}px system-ui, sans-serif`;
|
||||
ctx.lineWidth = 4; ctx.strokeStyle = 'rgba(0,0,0,.6)'; ctx.strokeText(t.text, t.x, t.y);
|
||||
ctx.fillStyle = t.color; ctx.fillText(t.text, t.x, t.y);
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
},
|
||||
clear() { parts.length = 0; texts.length = 0; shake = 0; },
|
||||
};
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
39
game/kit/kit-host.js
Normal file
39
game/kit/kit-host.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* Kit host (v1) - window control for the desktop exe (WebView2 launcher) and the browser.
|
||||
From _Tools\Library\web\kit.
|
||||
|
||||
Kit.host.exe true inside the launcher (Launcher.csproj); <html> gets class "exe"
|
||||
Kit.host.fullscreen() exe: toggle borderless-maximised; browser: Fullscreen API
|
||||
Kit.host.minimize() / Kit.host.quit() exe only (no-ops in the browser)
|
||||
Kit.host.dragArea(el) mousedown on el itself drags the window, double-click = fullscreen
|
||||
|
||||
The launcher draws no title bar; put minimise/fullscreen/close buttons into the page and
|
||||
show them only for html.exe (template: #winctl). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
const wv = root.chrome && root.chrome.webview;
|
||||
const send = c => { if (wv) wv.postMessage(c); };
|
||||
|
||||
const host = {
|
||||
exe: !!wv,
|
||||
send,
|
||||
fullscreen() {
|
||||
if (wv) return send('maximize');
|
||||
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
|
||||
else document.documentElement.requestFullscreen().catch(() => {});
|
||||
},
|
||||
minimize: () => send('minimize'),
|
||||
quit: () => send('quit'),
|
||||
dragArea(el) {
|
||||
if (!wv) return;
|
||||
el.addEventListener('mousedown', e => { if (e.button === 0 && e.target === el) send('drag'); });
|
||||
el.addEventListener('dblclick', e => { if (e.target === el) send('maximize'); });
|
||||
},
|
||||
};
|
||||
Kit.host = host;
|
||||
if (wv && typeof document !== 'undefined') document.documentElement.classList.add('exe');
|
||||
// F11 in the browser: same toggle as the exe (the launcher handles F11 / Alt+Enter itself)
|
||||
if (!wv && typeof addEventListener !== 'undefined') {
|
||||
addEventListener('keydown', e => { if (e.key === 'F11') { e.preventDefault(); host.fullscreen(); } });
|
||||
}
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
62
game/kit/kit-i18n.js
Normal file
62
game/kit/kit-i18n.js
Normal file
@@ -0,0 +1,62 @@
|
||||
/* Kit i18n (v1) - texts in several languages for HTML games. From _Tools\Library\web\kit.
|
||||
Needs kit-core.js. Dictionaries live in game/lang.js (a script, not JSON: file:// cannot fetch).
|
||||
|
||||
game/lang.js: window.LANG = { en: { play: 'Play', score: 'Score {n}' }, de: { play: 'Spielen' } };
|
||||
const L = Kit.i18n(window.LANG, { prefix: 'mygame' });
|
||||
L.t('score', { n: 5 }) "Score 5" - missing key: English, then the key itself (visible = easy to spot)
|
||||
L.lang / L.langs current language / ['en', 'de']
|
||||
L.set('de') switch + remember; re-fills data-i18n elements, calls onChange listeners
|
||||
L.next() cycle to the next language (one "English / Deutsch" button)
|
||||
L.apply(root) fills [data-i18n="key"] (text), [data-i18n-html] (HTML), [data-i18n-title],
|
||||
[data-i18n-placeholder]; runs once at start and after every set()
|
||||
L.onChange(fn) re-render menus/HUD after a switch
|
||||
Start language: saved choice, else browser language if there is a dictionary, else the first one. */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.i18n = (dicts, opt = {}) => {
|
||||
const langs = Object.keys(dicts || {});
|
||||
if (!langs.length) throw new Error('Kit.i18n: no dictionaries (game/lang.js loaded?)');
|
||||
const st = Kit.store(opt.prefix || 'kit');
|
||||
const fallback = dicts.en ? 'en' : langs[0];
|
||||
const listeners = [];
|
||||
const browser = (typeof navigator !== 'undefined' && (navigator.language || '').slice(0, 2).toLowerCase()) || '';
|
||||
const saved = st.get('lang', null);
|
||||
const api = {
|
||||
langs,
|
||||
lang: langs.includes(saved) ? saved : langs.includes(browser) ? browser : fallback,
|
||||
};
|
||||
|
||||
api.t = (key, vars) => {
|
||||
let s = dicts[api.lang]?.[key] ?? dicts[fallback]?.[key] ?? key;
|
||||
if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
|
||||
return s;
|
||||
};
|
||||
|
||||
api.apply = (scope = typeof document !== 'undefined' ? document : null) => {
|
||||
if (!scope) return;
|
||||
for (const el of scope.querySelectorAll('[data-i18n]')) el.textContent = api.t(el.dataset.i18n);
|
||||
for (const el of scope.querySelectorAll('[data-i18n-html]')) el.innerHTML = api.t(el.dataset.i18nHtml);
|
||||
for (const el of scope.querySelectorAll('[data-i18n-title]')) el.title = api.t(el.dataset.i18nTitle);
|
||||
for (const el of scope.querySelectorAll('[data-i18n-placeholder]')) el.placeholder = api.t(el.dataset.i18nPlaceholder);
|
||||
if (typeof document !== 'undefined') document.documentElement.lang = api.lang;
|
||||
};
|
||||
|
||||
api.set = l => {
|
||||
if (!langs.includes(l) || l === api.lang) return;
|
||||
api.lang = l;
|
||||
st.set('lang', l);
|
||||
api.apply();
|
||||
for (const fn of listeners) fn(l);
|
||||
};
|
||||
api.next = () => api.set(langs[(langs.indexOf(api.lang) + 1) % langs.length]);
|
||||
api.onChange = fn => { listeners.push(fn); };
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.apply());
|
||||
else api.apply();
|
||||
}
|
||||
return api;
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
73
game/kit/kit-input.js
Normal file
73
game/kit/kit-input.js
Normal file
@@ -0,0 +1,73 @@
|
||||
/* Kit input (v1) - keyboard + touch buttons mapped to actions. From _Tools\Library\web\kit.
|
||||
|
||||
const input = Kit.input({
|
||||
keys: { ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left',
|
||||
ArrowRight: 'right', d: 'right', ' ': 'action', p: 'pause', Escape: 'pause', m: 'mute' },
|
||||
onPress(action, e) {}, // first press only (no key repeat)
|
||||
onRelease(action) {},
|
||||
});
|
||||
input.down('left') is it held right now?
|
||||
input.latest(['up','right','down','left']) most recently pressed of these that is still held
|
||||
input.consume('action') true once per press (polling style inside update())
|
||||
|
||||
Touch buttons: any element with data-action="left" works like the key (pointer capture,
|
||||
so sliding off the button releases it). Typing into <input>/<textarea> is ignored.
|
||||
Keys are matched case-insensitively for letters. */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.input = (opt = {}) => {
|
||||
const map = {};
|
||||
for (const [k, a] of Object.entries(opt.keys || {})) map[k.length === 1 ? k.toLowerCase() : k] = a;
|
||||
const held = [], pressed = new Set();
|
||||
const api = {};
|
||||
|
||||
function press(a, e) {
|
||||
const i = held.indexOf(a);
|
||||
if (i >= 0) return; // already held (key repeat)
|
||||
held.push(a); pressed.add(a);
|
||||
opt.onPress && opt.onPress(a, e);
|
||||
}
|
||||
function release(a) {
|
||||
const i = held.indexOf(a);
|
||||
if (i < 0) return;
|
||||
held.splice(i, 1);
|
||||
opt.onRelease && opt.onRelease(a);
|
||||
}
|
||||
const typing = e => e.target && /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName);
|
||||
const keyOf = e => (e.key.length === 1 ? e.key.toLowerCase() : e.key);
|
||||
|
||||
addEventListener('keydown', e => {
|
||||
if (typing(e)) return;
|
||||
const a = map[keyOf(e)];
|
||||
if (!a) return;
|
||||
e.preventDefault();
|
||||
if (!e.repeat) press(a, e);
|
||||
});
|
||||
addEventListener('keyup', e => { const a = map[keyOf(e)]; if (a) release(a); });
|
||||
addEventListener('blur', () => { while (held.length) release(held[held.length - 1]); });
|
||||
|
||||
api.bindButtons = (scope = document) => {
|
||||
scope.querySelectorAll('[data-action]').forEach(b => {
|
||||
if (b._kitBound) return;
|
||||
b._kitBound = true;
|
||||
const a = b.dataset.action;
|
||||
b.addEventListener('pointerdown', e => { e.preventDefault(); b.setPointerCapture(e.pointerId); press(a, e); });
|
||||
b.addEventListener('pointerup', () => release(a));
|
||||
b.addEventListener('pointercancel', () => release(a));
|
||||
b.addEventListener('contextmenu', e => e.preventDefault());
|
||||
});
|
||||
};
|
||||
if (typeof document !== 'undefined') {
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.bindButtons());
|
||||
else api.bindButtons();
|
||||
}
|
||||
|
||||
api.down = a => held.includes(a);
|
||||
api.latest = list => { for (let i = held.length - 1; i >= 0; i--) if (list.includes(held[i])) return held[i]; return null; };
|
||||
api.consume = a => pressed.delete(a);
|
||||
api.clear = () => { held.length = 0; pressed.clear(); };
|
||||
return api;
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
75
game/kit/kit-loop.js
Normal file
75
game/kit/kit-loop.js
Normal file
@@ -0,0 +1,75 @@
|
||||
/* Kit loop + view (v1) - from _Tools\Library\web\kit. Needs kit-core.js.
|
||||
|
||||
Game loop with a fixed simulation step and smooth rendering:
|
||||
const loop = Kit.loop({
|
||||
step: 1000 / 60, // ms per update (fixed: deterministic, replayable)
|
||||
update(dt) { ... }, // dt = step in seconds
|
||||
render(alpha, now) { ... }, // alpha 0..1 between the last two updates (interpolate)
|
||||
});
|
||||
loop.start(); loop.pause(); loop.resume(); loop.paused
|
||||
Pauses itself while the tab is hidden; a long hitch is capped (no spiral of death).
|
||||
|
||||
Fixed-size layout scaled to the window (sharp canvases on hi-DPI screens):
|
||||
Kit.fit(Kit.$('app'), { canvases: [[cv, 960, 540]], onFit(scale) {} })
|
||||
#app is laid out at its natural pixel size and scaled with CSS transform to fill the
|
||||
window; every listed canvas gets a backing store of size * scale * devicePixelRatio
|
||||
and a matching ctx transform, so you always draw in design pixels (960 x 540). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
Kit.loop = opt => {
|
||||
const step = opt.step || 1000 / 60, maxFrame = opt.maxFrame || 250;
|
||||
let acc = 0, last = 0, raf = 0, running = false;
|
||||
const api = { paused: false, ticks: 0 };
|
||||
function frame(now) {
|
||||
raf = requestAnimationFrame(frame);
|
||||
let d = now - last; last = now;
|
||||
if (api.paused || document.hidden) { acc = 0; opt.render && opt.render(1, now); return; }
|
||||
if (d > maxFrame) d = maxFrame;
|
||||
acc += d;
|
||||
while (acc >= step) { acc -= step; api.ticks++; opt.update && opt.update(step / 1000); if (api.paused) { acc = 0; break; } }
|
||||
opt.render && opt.render(acc / step, now);
|
||||
}
|
||||
api.start = () => { if (running) return api; running = true; last = performance.now(); raf = requestAnimationFrame(frame); return api; };
|
||||
api.stop = () => { running = false; cancelAnimationFrame(raf); };
|
||||
api.pause = () => { api.paused = true; };
|
||||
api.resume = () => { api.paused = false; acc = 0; last = performance.now(); };
|
||||
return api;
|
||||
};
|
||||
|
||||
Kit.setRes = (cv, w, h, k) => {
|
||||
cv.width = Math.round(w * k);
|
||||
cv.height = Math.round(h * k);
|
||||
cv.style.width = w + 'px';
|
||||
cv.style.height = h + 'px';
|
||||
const c = cv.getContext('2d');
|
||||
c.setTransform(k, 0, 0, k, 0, 0);
|
||||
return c;
|
||||
};
|
||||
|
||||
Kit.fit = (app, opt = {}) => {
|
||||
const margin = opt.margin == null ? 0.96 : opt.margin, min = opt.min || 0.3, max = opt.max || 4;
|
||||
const canvases = opt.canvases || [];
|
||||
app.style.transformOrigin = 'center center';
|
||||
function fit() {
|
||||
app.style.transform = 'none';
|
||||
const w = app.offsetWidth, h = app.offsetHeight;
|
||||
const sc = Kit.clamp(Math.min(innerWidth * margin / w, innerHeight * margin / h), min, max);
|
||||
app.style.transform = `scale(${sc})`;
|
||||
const k = sc * (root.devicePixelRatio || 1);
|
||||
for (const [cv, cw, ch] of canvases) Kit.setRes(cv, cw, ch, k);
|
||||
opt.onFit && opt.onFit(sc);
|
||||
}
|
||||
addEventListener('resize', fit);
|
||||
if (document.fonts) document.fonts.ready.then(fit);
|
||||
fit();
|
||||
return fit;
|
||||
};
|
||||
|
||||
// Screen position (mouse/touch event) -> design pixels of a canvas laid out by Kit.fit.
|
||||
Kit.toCanvas = (cv, e, w, h) => {
|
||||
const r = cv.getBoundingClientRect();
|
||||
return { x: (e.clientX - r.left) * (w / r.width), y: (e.clientY - r.top) * (h / r.height) };
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
64
game/kit/kit-scores.js
Normal file
64
game/kit/kit-scores.js
Normal file
@@ -0,0 +1,64 @@
|
||||
/* Kit scores (v1) - online highscores via Firebase Realtime Database REST (no SDK, no login).
|
||||
From _Tools\Library\web\kit. Rules to install: template docs/firebase/database.rules.json.
|
||||
|
||||
const scores = Kit.scores({ url: 'https://<project>-default-rtdb.europe-west1.firebasedatabase.app' });
|
||||
if (scores.enabled) {
|
||||
const rows = await scores.top(10); // [{ key, name, score, level, time }] best first
|
||||
const key = await scores.submit({ name, score, level }); // key of the new entry or null
|
||||
}
|
||||
Kit.cleanName(s) -> trimmed, max 20 chars, no control chars / angle brackets
|
||||
Kit.badName(s) -> true for slurs/insults (also l33t spelling); block on entry, hide in lists
|
||||
|
||||
Without a url (or with the placeholder) scores.enabled is false and both calls resolve to
|
||||
[] / null - the game runs offline. The rules only check format and range: anyone can post a
|
||||
fake score by hand. Real protection needs a server check (Cloud Function). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const Kit = (root.Kit = root.Kit || {});
|
||||
|
||||
const BAD_WORDS = ['nigg', 'niga', 'neger', 'negro', 'kike', 'fag', 'cunt', 'fuck', 'fick', 'hitler', 'nazi',
|
||||
'siegheil', 'kkk', 'whore', 'hure', 'fotze', 'wichs', 'schwuchtel', 'spast', 'retard', 'slut', 'bitch',
|
||||
'kanake', 'zigeuner', 'judensau'];
|
||||
Kit.cleanName = s => String(s || '').replace(/[\u0000-\u001f<>]/g, '').trim().slice(0, 20);
|
||||
Kit.badName = s => {
|
||||
const norm = String(s || '').toLowerCase()
|
||||
.replace(/[1!|]/g, 'i').replace(/3/g, 'e').replace(/0/g, 'o').replace(/[4@]/g, 'a')
|
||||
.replace(/[5$]/g, 's').replace(/7/g, 't').replace(/ph/g, 'f')
|
||||
.replace(/[^a-zäöüß]/g, '');
|
||||
return BAD_WORDS.some(w => norm.includes(w));
|
||||
};
|
||||
|
||||
Kit.scores = (opt = {}) => {
|
||||
const url = (opt.url || '').replace(/\/+$/, '');
|
||||
const path = opt.path || 'highscores';
|
||||
const enabled = /^https:\/\/.+firebase(io|database)\.(com|app)$/.test(url);
|
||||
return {
|
||||
enabled,
|
||||
async top(n = 10) {
|
||||
if (!enabled) return [];
|
||||
// fetch spare rows: filtered names must not leave the list short
|
||||
const q = new URLSearchParams({ orderBy: '"score"', limitToLast: String(n + 15) });
|
||||
const res = await fetch(`${url}/${path}.json?${q}`, { cache: 'no-store' });
|
||||
if (!res.ok) throw new Error('scores ' + res.status);
|
||||
const data = (await res.json()) || {};
|
||||
return Object.entries(data)
|
||||
.map(([key, v]) => Object.assign({ key }, v))
|
||||
.filter(v => typeof v.name === 'string' && typeof v.score === 'number' && !Kit.badName(v.name))
|
||||
.sort((a, b) => b.score - a.score || (a.time || 0) - (b.time || 0))
|
||||
.slice(0, n);
|
||||
},
|
||||
async submit({ name, score, level = 1 }) {
|
||||
name = Kit.cleanName(name);
|
||||
if (!enabled || !name || !(score > 0) || Kit.badName(name)) return null;
|
||||
try {
|
||||
const res = await fetch(`${url}/${path}.json`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, score: Math.floor(score), level: Math.floor(level), time: { '.sv': 'timestamp' } }),
|
||||
});
|
||||
return res.ok ? (await res.json()).name : null;
|
||||
} catch (e) { return null; }
|
||||
},
|
||||
};
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
168
game/lang.js
Normal file
168
game/lang.js
Normal file
@@ -0,0 +1,168 @@
|
||||
/* Robot Clash - all visible texts, English + German. Used via L.t('key') in game.js / garage.js and
|
||||
data-i18n="key" in index.html (kit-i18n.js). A new text always gets BOTH languages.
|
||||
Values may contain simple HTML (<b>, <br>) and {placeholders}. Part names (parts.js) are brand
|
||||
names and stay the same in every language; their descriptions are the pd_<id> keys. */
|
||||
window.LANG = {
|
||||
en: {
|
||||
lang_self: 'English',
|
||||
hud_money: 'Credits', hud_fame: 'Fame', hud_league: 'League',
|
||||
league_chip: 'S{s} · {n}/{m}',
|
||||
sound_on: 'Sound on', sound_off: 'Sound off', pause: 'Pause',
|
||||
win_min: 'Minimise', win_full: 'Fullscreen (F11)', win_close: 'Close',
|
||||
no_webgl: 'This game needs WebGL (3D graphics). Please use a current browser or update the graphics driver.',
|
||||
menu_text: 'Build your combat robot from parts, fight your way up the league<br>and send your opponents into the pit.',
|
||||
name_placeholder: 'Your name',
|
||||
play: 'Start career', continue_career: 'Continue',
|
||||
how_to: 'How to play', reset: 'New career',
|
||||
reset_text: 'Delete your robot, credits and league progress and start again?',
|
||||
reset_yes: 'Yes, start over', cancel: 'Cancel', ok: 'OK', back: 'Back', menu: 'Menu',
|
||||
help_text: 'In the <b>workshop</b> you fit one chassis, motor, wheels and battery, plus armour, a weapon and a tower. Keep under <b>100 kg</b>, and the battery must supply enough power. Win fights for credits and buy better parts.',
|
||||
key_drive: 'drive (tank steering)', key_space: 'Space', key_weapon: 'main weapon', key_tower: 'tower weapon',
|
||||
key_pad: 'Gamepad', key_pad_text: 'stick, A = weapon, B = tower',
|
||||
help_arena: 'You win by <b>knockout</b>, by pushing the enemy into the <b>pit</b> (it opens at half time) or on damage when the time runs out. Watch the floor saws, flame grilles, spike walls, the <b>forge press</b> and the <b>magnet crane</b> in the corners!',
|
||||
loading: 'loading…', ranking: 'Fame ranking',
|
||||
no_scores: 'No entries yet - be the first!', scores_offline: 'Ranking offline',
|
||||
// workshop
|
||||
to_league: 'League', training: 'Training', unarmed: 'unarmed',
|
||||
slot_chassis: 'Chassis', slot_motor: 'Motor', slot_wheels: 'Wheels', slot_battery: 'Battery',
|
||||
slot_armour: 'Armour', slot_weapon: 'Weapon', slot_tower: 'Tower',
|
||||
none: 'None', none_armour: 'Bare chassis - light but fragile.', none_weapon: 'No weapon - only ramming.', none_tower: 'No tower weapon.',
|
||||
equipped: 'fitted', equip: 'Fit', sell: 'Sell {n}', buy: 'Buy {n}',
|
||||
st_hp: '{n} HP', st_speed: '{n} m/s', st_force: '{n} N', st_grip: 'grip {n}', st_turn: 'turn {n}', st_invert: 'drives upside down',
|
||||
st_reduce: '-{n}% damage', st_dmg: '{n} dmg', st_dps: '{n} dmg/s', st_range: 'range {n} m', st_weight: '{n} kg',
|
||||
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',
|
||||
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.',
|
||||
pd_scarab: 'Domed shell, strong front armour.',
|
||||
pd_sparky: 'Starter motor. Gets you moving.',
|
||||
pd_hornet: 'Faster all-rounder.',
|
||||
pd_bulldog: 'Huge torque for pushing.',
|
||||
pd_comet: 'Top speed for hit and run.',
|
||||
pd_rubber: 'Four small wheels, nimble.',
|
||||
pd_bigtyre: 'Taller than the robot: keeps driving when flipped.',
|
||||
pd_tracks: 'Massive grip, wins every shoving match.',
|
||||
pd_lead: 'Heavy, but it works.',
|
||||
pd_nicd: 'More power, less weight.',
|
||||
pd_lipo: 'Light and powerful.',
|
||||
pd_steel: 'Basic plates, absorb some damage.',
|
||||
pd_titan: 'Light and tough.',
|
||||
pd_hardox: 'Wear plate - the toughest skin money can buy.',
|
||||
pd_wedge: 'Ramming plate. Space = turbo boost.',
|
||||
pd_flipper: 'Launches robots into the air and onto their backs.',
|
||||
pd_hammer: 'Overhead axe, ignores half the armour.',
|
||||
pd_saw: 'Hold Space to cut through anything in front.',
|
||||
pd_crusher: 'Grabs and crushes - drag them into the hazards!',
|
||||
pd_spinner: 'Hold Space to spin up, release the energy on contact.',
|
||||
pd_flamer: 'Short-range fire, burns through armour.',
|
||||
pd_minigun: 'Steady rivet fire from range.',
|
||||
pd_rockets: 'Homing rockets every few seconds.',
|
||||
// league
|
||||
league_title: 'League - season {s}',
|
||||
league_text: 'Beat the opponents one after another. Each season they get tougher and pay more.',
|
||||
fight_vs: 'Fight {name}',
|
||||
style_brawler: 'Brawler - straight at you', style_flanker: 'Flanker - goes for your back', style_pusher: 'Pusher - loves the pit',
|
||||
style_gunner: 'Gunner - keeps its distance', style_dummy: 'Training dummy',
|
||||
// fight
|
||||
pad_weapon: 'Weapon', pad_tower: 'Tower',
|
||||
fight_go: 'ACTIVATE!', pit_open: 'PIT OPEN!', into_pit: 'INTO THE PIT!', knockout: 'KNOCKOUT!',
|
||||
fight_hint: 'W A S D drive · Space weapon · Shift / E tower · P pause',
|
||||
st_lifted: 'MAGNET!', st_grabbed: 'GRABBED!', st_flipped: 'UPSIDE DOWN!', st_stunned: 'STUNNED', pit_is_open: 'PIT IS OPEN', pit_soon: 'pit opens soon',
|
||||
continue: 'Continue', give_up: 'Give up',
|
||||
// result
|
||||
victory: 'VICTORY', defeat: 'DEFEAT', draw: 'DRAW',
|
||||
why_ko_win: '{name} is knocked out.', why_ko_lose: 'Your robot was knocked out by {name}.',
|
||||
why_pit_win: '{name} went into the pit!', why_pit_lose: 'Your robot fell into the pit.',
|
||||
why_time_win: 'Time! You dealt more damage than {name}.', why_time_lose: 'Time! {name} dealt more damage.', why_time_draw: 'Time! Nobody was better.',
|
||||
r_prize: 'Prize money', r_bonus_ko: 'Knockout bonus', r_bonus_pit: 'Pit bonus', r_appearance: 'Appearance fee', r_repair: 'Repairs',
|
||||
r_champion: 'Champion bonus', r_dealt: 'Damage dealt', r_taken: 'Damage taken',
|
||||
champion_title: 'Champion of season {s}!',
|
||||
champion_text: 'The league starts again - harder opponents, higher prizes.',
|
||||
training_note: 'Training: no prize money, free repairs.',
|
||||
to_garage: 'Workshop', retry: 'Rematch',
|
||||
},
|
||||
de: {
|
||||
lang_self: 'Deutsch',
|
||||
hud_money: 'Credits', hud_fame: 'Ruhm', hud_league: 'Liga',
|
||||
league_chip: 'S{s} · {n}/{m}',
|
||||
sound_on: 'Sound an', sound_off: 'Sound aus', pause: 'Pause',
|
||||
win_min: 'Minimieren', win_full: 'Vollbild (F11)', win_close: 'Schließen',
|
||||
no_webgl: 'Dieses Spiel braucht WebGL (3D-Grafik). Bitte einen aktuellen Browser nutzen oder den Grafiktreiber aktualisieren.',
|
||||
menu_text: 'Bau deinen Kampfroboter aus Teilen, kämpf dich durch die Liga<br>und schick deine Gegner in die Grube.',
|
||||
name_placeholder: 'Dein Name',
|
||||
play: 'Karriere starten', continue_career: 'Weiter',
|
||||
how_to: 'Anleitung', reset: 'Neue Karriere',
|
||||
reset_text: 'Roboter, Credits und Liga-Fortschritt löschen und neu anfangen?',
|
||||
reset_yes: 'Ja, neu anfangen', cancel: 'Abbrechen', ok: 'OK', back: 'Zurück', menu: 'Menü',
|
||||
help_text: 'In der <b>Werkstatt</b> baust du je ein Chassis, einen Motor, Räder und eine Batterie ein, dazu Panzerung, Waffe und Turm. Bleib unter <b>100 kg</b>, und die Batterie muss genug Strom liefern. Siege bringen Credits für bessere Teile.',
|
||||
key_drive: 'fahren (Panzersteuerung)', key_space: 'Leertaste', key_weapon: 'Hauptwaffe', key_tower: 'Turmwaffe',
|
||||
key_pad: 'Gamepad', key_pad_text: 'Stick, A = Waffe, B = Turm',
|
||||
help_arena: 'Du gewinnst durch <b>K.o.</b>, indem du den Gegner in die <b>Grube</b> schiebst (öffnet zur Halbzeit) oder nach Schaden, wenn die Zeit abläuft. Achtung vor Bodensägen, Flammengittern, Stachelwänden, der <b>Schmiedepresse</b> und dem <b>Magnetkran</b> in den Ecken!',
|
||||
loading: 'lädt…', ranking: 'Ruhmesliste',
|
||||
no_scores: 'Noch keine Einträge – sei der Erste!', scores_offline: 'Rangliste offline',
|
||||
// workshop
|
||||
to_league: 'Liga', training: 'Training', unarmed: 'unbewaffnet',
|
||||
slot_chassis: 'Chassis', slot_motor: 'Motor', slot_wheels: 'Räder', slot_battery: 'Batterie',
|
||||
slot_armour: 'Panzer', slot_weapon: 'Waffe', slot_tower: 'Turm',
|
||||
none: 'Keine', none_armour: 'Nacktes Chassis – leicht, aber empfindlich.', none_weapon: 'Keine Waffe – nur rammen.', none_tower: 'Keine Turmwaffe.',
|
||||
equipped: 'eingebaut', equip: 'Einbauen', sell: 'Verkaufen {n}', buy: 'Kaufen {n}',
|
||||
st_hp: '{n} LP', st_speed: '{n} m/s', st_force: '{n} N', st_grip: 'Grip {n}', st_turn: 'Wendig {n}', st_invert: 'fährt auch auf dem Kopf',
|
||||
st_reduce: '-{n}% Schaden', st_dmg: '{n} Schaden', st_dps: '{n} Schaden/s', st_range: 'Reichweite {n} m', st_weight: '{n} kg',
|
||||
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',
|
||||
pd_crate: 'Einfache Stahlkiste. Billig und ehrlich.',
|
||||
pd_doorstop: 'Flacher Keil – schwer umzudrehen.',
|
||||
pd_bulwark: 'Schwerer Rahmen mit vielen Lebenspunkten.',
|
||||
pd_scarab: 'Kuppelpanzer, starke Front.',
|
||||
pd_sparky: 'Startmotor. Bringt dich in Bewegung.',
|
||||
pd_hornet: 'Schnellerer Allrounder.',
|
||||
pd_bulldog: 'Riesiges Drehmoment zum Schieben.',
|
||||
pd_comet: 'Höchsttempo für Angriff und Rückzug.',
|
||||
pd_rubber: 'Vier kleine Räder, wendig.',
|
||||
pd_bigtyre: 'Höher als der Roboter: fährt auch umgedreht weiter.',
|
||||
pd_tracks: 'Enormer Grip, gewinnt jedes Schiebeduell.',
|
||||
pd_lead: 'Schwer, aber sie tut es.',
|
||||
pd_nicd: 'Mehr Strom, weniger Gewicht.',
|
||||
pd_lipo: 'Leicht und stark.',
|
||||
pd_steel: 'Einfache Platten, schlucken etwas Schaden.',
|
||||
pd_titan: 'Leicht und zäh.',
|
||||
pd_hardox: 'Verschleißblech – die härteste Haut, die es zu kaufen gibt.',
|
||||
pd_wedge: 'Rammkeil. Leertaste = Turbo.',
|
||||
pd_flipper: 'Schleudert Roboter in die Luft und auf den Rücken.',
|
||||
pd_hammer: 'Axt von oben, ignoriert die halbe Panzerung.',
|
||||
pd_saw: 'Leertaste halten und alles vor dir zersägen.',
|
||||
pd_crusher: 'Packt zu und quetscht – zieh sie in die Fallen!',
|
||||
pd_spinner: 'Leertaste halten zum Hochdrehen, die Energie entlädt sich beim Treffer.',
|
||||
pd_flamer: 'Feuer auf kurze Distanz, brennt durch Panzerung.',
|
||||
pd_minigun: 'Stetiges Nietenfeuer aus der Ferne.',
|
||||
pd_rockets: 'Zielsuchende Raketen alle paar Sekunden.',
|
||||
// league
|
||||
league_title: 'Liga – Saison {s}',
|
||||
league_text: 'Besiege die Gegner nacheinander. Jede Saison werden sie härter und zahlen mehr.',
|
||||
fight_vs: 'Kampf gegen {name}',
|
||||
style_brawler: 'Raufbold – kommt direkt auf dich zu', style_flanker: 'Flankierer – will an dein Heck', style_pusher: 'Schieber – liebt die Grube',
|
||||
style_gunner: 'Schütze – hält Abstand', style_dummy: 'Trainingsroboter',
|
||||
// fight
|
||||
pad_weapon: 'Waffe', pad_tower: 'Turm',
|
||||
fight_go: 'AKTIVIEREN!', pit_open: 'GRUBE OFFEN!', into_pit: 'IN DIE GRUBE!', knockout: 'K.O.!',
|
||||
fight_hint: 'W A S D fahren · Leertaste Waffe · Shift / E Turm · P Pause',
|
||||
st_lifted: 'MAGNET!', st_grabbed: 'GEPACKT!', st_flipped: 'AUF DEM KOPF!', st_stunned: 'BETÄUBT', pit_is_open: 'GRUBE IST OFFEN', pit_soon: 'Grube öffnet gleich',
|
||||
continue: 'Weiter', give_up: 'Aufgeben',
|
||||
// result
|
||||
victory: 'SIEG', defeat: 'NIEDERLAGE', draw: 'UNENTSCHIEDEN',
|
||||
why_ko_win: '{name} ist k.o.', why_ko_lose: 'Dein Roboter wurde von {name} ausgeschaltet.',
|
||||
why_pit_win: '{name} ist in der Grube gelandet!', why_pit_lose: 'Dein Roboter ist in die Grube gefallen.',
|
||||
why_time_win: 'Zeit! Du hast mehr Schaden gemacht als {name}.', why_time_lose: 'Zeit! {name} hat mehr Schaden gemacht.', why_time_draw: 'Zeit! Keiner war besser.',
|
||||
r_prize: 'Preisgeld', r_bonus_ko: 'K.o.-Bonus', r_bonus_pit: 'Gruben-Bonus', r_appearance: 'Antrittsgeld', r_repair: 'Reparatur',
|
||||
r_champion: 'Meister-Bonus', r_dealt: 'Schaden ausgeteilt', r_taken: 'Schaden eingesteckt',
|
||||
champion_title: 'Meister der Saison {s}!',
|
||||
champion_text: 'Die Liga beginnt von vorn – härtere Gegner, höhere Preise.',
|
||||
training_note: 'Training: kein Preisgeld, Reparatur gratis.',
|
||||
to_garage: 'Werkstatt', retry: 'Revanche',
|
||||
},
|
||||
};
|
||||
66
game/parts.js
Normal file
66
game/parts.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/* Robot Clash - parts catalogue (no DOM). Loaded as a classic script (window.RC.PARTS) and in Node
|
||||
(require('./parts.js') returns RC).
|
||||
|
||||
Slots: chassis, motor, wheels, battery (required, exactly one each), armour, weapon, tower (optional).
|
||||
Common fields: id, slot, name (brand name, not translated), cost, weight (kg), power (draw; battery: supply).
|
||||
Texts for each part: lang.js key 'pd_<id>' (short description, en + de). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || {});
|
||||
|
||||
RC.WEIGHT_LIMIT = 100; // kg, single weight class in v1
|
||||
RC.SLOTS = ['chassis', 'motor', 'wheels', 'battery', 'armour', 'weapon', 'tower'];
|
||||
RC.REQUIRED = { chassis: true, motor: true, wheels: true, battery: true };
|
||||
|
||||
const P = [
|
||||
// chassis: hp, body size (len along forward, wid, h), shape for the 3D model
|
||||
{ id: 'crate', slot: 'chassis', name: 'Crate Mk1', cost: 150, weight: 22, hp: 100, len: 1.3, wid: 1.0, h: 0.42, shape: 'box' },
|
||||
{ id: 'doorstop', slot: 'chassis', name: 'Doorstop', cost: 380, weight: 25, hp: 105, len: 1.45, wid: 1.05, h: 0.34, shape: 'wedge', lowProfile: true },
|
||||
{ id: 'bulwark', slot: 'chassis', name: 'Bulwark', cost: 720, weight: 34, hp: 150, len: 1.5, wid: 1.2, h: 0.5, shape: 'box' },
|
||||
{ id: 'scarab', slot: 'chassis', name: 'Scarab', cost: 1150, weight: 30, hp: 135, len: 1.4, wid: 1.15, h: 0.46, shape: 'dome', frontArmour: 0.15 },
|
||||
|
||||
// motor: force (N), top speed (m/s)
|
||||
{ id: 'sparky', slot: 'motor', name: 'Sparky 2kW', cost: 100, weight: 8, power: 3, force: 650, speed: 4.0 },
|
||||
{ id: 'hornet', slot: 'motor', name: 'Hornet 3kW', cost: 420, weight: 10, power: 5, force: 850, speed: 5.0 },
|
||||
{ id: 'bulldog', slot: 'motor', name: 'Bulldog Torque', cost: 680, weight: 14, power: 6, force: 1250, speed: 4.3 },
|
||||
{ id: 'comet', slot: 'motor', name: 'Comet 5kW', cost: 1250, weight: 12, power: 8, force: 1150, speed: 6.2 },
|
||||
|
||||
// wheels: speed factor, lateral grip, turn rate (rad/s), push factor; invertible = drives upside down
|
||||
{ id: 'rubber', slot: 'wheels', name: 'Rubber 4x', cost: 60, weight: 4, speedMul: 1.0, grip: 7, turn: 2.8, push: 1.0, kind: 'small' },
|
||||
{ id: 'bigtyre', slot: 'wheels', name: 'Big Tyres', cost: 280, weight: 7, speedMul: 1.1, grip: 7.5, turn: 2.5, push: 1.05, kind: 'big', invertible: true },
|
||||
{ id: 'tracks', slot: 'wheels', name: 'Crawler Tracks', cost: 540, weight: 11, speedMul: 0.86, grip: 12, turn: 2.2, push: 1.45, kind: 'tracks' },
|
||||
|
||||
// battery: power = supply
|
||||
{ id: 'lead', slot: 'battery', name: 'Lead 12V', cost: 80, weight: 10, power: 9 },
|
||||
{ id: 'nicd', slot: 'battery', name: 'NiCd Pack', cost: 320, weight: 7, power: 13 },
|
||||
{ id: 'lipo', slot: 'battery', name: 'LiPo Stack', cost: 760, weight: 5, power: 19 },
|
||||
|
||||
// armour: reduce = share of damage absorbed, hp bonus
|
||||
{ id: 'steel', slot: 'armour', name: 'Steel Plates', cost: 220, weight: 12, reduce: 0.15, hp: 10, tint: 0x8a9099 },
|
||||
{ id: 'titan', slot: 'armour', name: 'Titanium Skin', cost: 680, weight: 9, reduce: 0.25, hp: 15, tint: 0xa9b8c9 },
|
||||
{ id: 'hardox', slot: 'armour', name: 'Hardox Shell', cost: 1150, weight: 18, reduce: 0.38, hp: 25, tint: 0xc9a845 },
|
||||
|
||||
// weapons (Space): type decides the behaviour in combat.js
|
||||
{ id: 'wedge', slot: 'weapon', name: 'Steel Wedge', cost: 80, weight: 6, power: 0, type: 'wedge', reach: 0.35, ram: 1.7, cd: 4 },
|
||||
{ id: 'flipper', slot: 'weapon', name: 'Pneumatic Flipper', cost: 480, weight: 14, power: 6, type: 'flipper', reach: 0.55, dmg: 8, launch: 7.5, cd: 2.2 },
|
||||
{ id: 'hammer', slot: 'weapon', name: 'Axe Hammer', cost: 560, weight: 12, power: 5, type: 'hammer', reach: 0.8, dmg: 22, cd: 1.5 },
|
||||
{ id: 'saw', slot: 'weapon', name: 'Circular Saw', cost: 420, weight: 9, power: 5, type: 'saw', reach: 0.4, dps: 24 },
|
||||
{ id: 'crusher', slot: 'weapon', name: 'Hydraulic Jaws', cost: 780, weight: 15, power: 7, type: 'crusher', reach: 0.5, dps: 20, hold: 2.2, cd: 3.5 },
|
||||
{ id: 'spinner', slot: 'weapon', name: 'Bar Spinner', cost: 950, weight: 18, power: 9, type: 'spinner', reach: 0.6, dmg: 34, spinup: 1.4 },
|
||||
|
||||
// towers (Shift / E): auto-aiming turret on top
|
||||
{ id: 'flamer', slot: 'tower', name: 'Flame Nozzle', cost: 360, weight: 6, power: 3, type: 'flamer', range: 2.8, dps: 10, cone: 0.4 },
|
||||
{ id: 'minigun', slot: 'tower', name: 'Rivet Minigun', cost: 520, weight: 7, power: 4, type: 'minigun', range: 9, dps: 8 },
|
||||
{ id: 'rockets', slot: 'tower', name: 'Seeker Pod', cost: 840, weight: 10, power: 5, type: 'rockets', range: 14, dmg: 17, cd: 2.4 },
|
||||
];
|
||||
|
||||
RC.PARTS = {};
|
||||
for (const p of P) RC.PARTS[p.id] = p;
|
||||
RC.PART_LIST = P;
|
||||
RC.partsFor = slot => P.filter(p => p.slot === slot);
|
||||
|
||||
// starter robot: owned on a new save
|
||||
RC.STARTER = { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null };
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
666
game/render3d.js
Normal file
666
game/render3d.js
Normal file
@@ -0,0 +1,666 @@
|
||||
/* Robot Clash - 3D view with three.js (vendor/three.min.js, r149, classic script). Needs parts.js,
|
||||
robot.js, combat.js (RC.ARENA).
|
||||
|
||||
const view = RC.Render(canvas, 960, 540);
|
||||
view.resize(scale) after Kit.fit (CSS scale of #app)
|
||||
view.showGarage(build, paint) workshop scene with the robot on a turntable
|
||||
view.showArena(state, builds, paints) arena scene for a fight (state from RC.Combat.create)
|
||||
view.events(list) combat events -> sparks, explosions, camera shake
|
||||
view.frame(dt, now) animate + render the active scene
|
||||
view.project(x, y, z) world -> design pixels { x, y } (for floating texts)
|
||||
All meshes are procedural (no image files needed). */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = root.RC, T = root.THREE;
|
||||
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
|
||||
const lerp = (a, b, k) => a + (b - a) * k;
|
||||
|
||||
// ---------------------------------------------------------------- textures (canvas)
|
||||
function canvasTex(w, h, draw, repeat) {
|
||||
const c = document.createElement('canvas'); c.width = w; c.height = h;
|
||||
draw(c.getContext('2d'), w, h);
|
||||
const t = new T.CanvasTexture(c);
|
||||
t.encoding = T.sRGBEncoding;
|
||||
t.anisotropy = 4;
|
||||
if (repeat) { t.wrapS = t.wrapT = T.RepeatWrapping; t.repeat.set(repeat[0], repeat[1]); }
|
||||
return t;
|
||||
}
|
||||
function stripes(ctx, x, y, w, h, size = 16) {
|
||||
ctx.save(); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
|
||||
ctx.fillStyle = '#f2b51c'; ctx.fillRect(x, y, w, h);
|
||||
ctx.fillStyle = '#16181c';
|
||||
for (let k = -h; k < w + h; k += size * 2) {
|
||||
ctx.beginPath(); ctx.moveTo(x + k, y); ctx.lineTo(x + k + size, y); ctx.lineTo(x + k + size - h, y + h); ctx.lineTo(x + k - h, y + h); ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
const stripeTex = () => canvasTex(128, 32, (c, w, h) => stripes(c, 0, 0, w, h, 12));
|
||||
const dotTex = () => canvasTex(64, 64, (c) => {
|
||||
const g = c.createRadialGradient(32, 32, 0, 32, 32, 32);
|
||||
g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.35, 'rgba(255,255,255,.75)'); g.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
c.fillStyle = g; c.fillRect(0, 0, 64, 64);
|
||||
});
|
||||
|
||||
function floorTex() {
|
||||
const A = RC.ARENA, S = 64, N = A.half * 2 * S; // 64 px per metre
|
||||
const P = (x, z) => [(x + A.half) * S, (z + A.half) * S];
|
||||
return canvasTex(N, N, (c) => {
|
||||
// steel plates 2 m
|
||||
for (let i = 0; i < A.half; i++) for (let j = 0; j < A.half; j++) {
|
||||
const v = 52 + ((i * 7 + j * 13) % 5) * 4;
|
||||
c.fillStyle = `rgb(${v},${v + 3},${v + 8})`; c.fillRect(i * 128, j * 128, 128, 128);
|
||||
c.strokeStyle = '#1b1d22'; c.lineWidth = 3; c.strokeRect(i * 128 + 1.5, j * 128 + 1.5, 125, 125);
|
||||
c.strokeStyle = 'rgba(255,255,255,.07)'; c.lineWidth = 1; c.strokeRect(i * 128 + 4, j * 128 + 4, 120, 120);
|
||||
c.fillStyle = '#25272c';
|
||||
for (const [rx, ry] of [[10, 10], [118, 10], [10, 118], [118, 118]]) { c.beginPath(); c.arc(i * 128 + rx, j * 128 + ry, 3, 0, 7); c.fill(); }
|
||||
}
|
||||
// scratches + oil
|
||||
let seed = 5; const r = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
|
||||
for (let k = 0; k < 340; k++) {
|
||||
c.strokeStyle = `rgba(${r() < 0.5 ? '255,255,255' : '0,0,0'},${0.04 + r() * 0.07})`; c.lineWidth = 0.5 + r() * 1.5;
|
||||
const x = r() * N, y = r() * N, a = r() * 6.3, l = 10 + r() * 60;
|
||||
c.beginPath(); c.moveTo(x, y); c.lineTo(x + Math.cos(a) * l, y + Math.sin(a) * l); c.stroke();
|
||||
}
|
||||
for (let k = 0; k < 18; k++) { c.fillStyle = `rgba(10,8,6,${0.12 + r() * 0.15})`; c.beginPath(); c.ellipse(r() * N, r() * N, 10 + r() * 40, 8 + r() * 26, r() * 3, 0, 7); c.fill(); }
|
||||
// guardian corners + pit: hazard stripes
|
||||
for (const z of [A.press, A.crane, A.pit]) {
|
||||
const [x0, y0] = P(z.x - z.hw, z.z - z.hd), w = z.hw * 2 * S, h = z.hd * 2 * S, b = 14;
|
||||
stripes(c, x0, y0, w, b); stripes(c, x0, y0 + h - b, w, b); stripes(c, x0, y0, b, h); stripes(c, x0 + w - b, y0, b, h);
|
||||
if (z === A.pit) { c.fillStyle = '#030303'; c.fillRect(x0 + b, y0 + b, w - 2 * b, h - 2 * b); }
|
||||
else { c.fillStyle = 'rgba(0,0,0,.25)'; c.fillRect(x0 + b, y0 + b, w - 2 * b, h - 2 * b); }
|
||||
}
|
||||
// saw slots
|
||||
for (const h of A.saws) {
|
||||
const [x, y] = P(h.x, h.z);
|
||||
c.fillStyle = '#121316'; c.beginPath(); c.arc(x, y, h.r * S * 0.95, 0, 7); c.fill();
|
||||
c.strokeStyle = '#d33'; c.lineWidth = 4; c.setLineDash([12, 10]); c.beginPath(); c.arc(x, y, h.r * S + 8, 0, 7); c.stroke(); c.setLineDash([]);
|
||||
}
|
||||
// centre mark
|
||||
const [cx, cy] = P(0, 0);
|
||||
c.strokeStyle = 'rgba(255,122,26,.35)'; c.lineWidth = 5; c.beginPath(); c.arc(cx, cy, 1.4 * S, 0, 7); c.stroke();
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- particles
|
||||
function Particles(scene, max, size, additive, tex) {
|
||||
const pos = new Float32Array(max * 3), col = new Float32Array(max * 4);
|
||||
const vel = new Float32Array(max * 3), life = new Float32Array(max), life0 = new Float32Array(max), base = new Float32Array(max * 3);
|
||||
const geo = new T.BufferGeometry();
|
||||
geo.setAttribute('position', new T.BufferAttribute(pos, 3));
|
||||
geo.setAttribute('color', new T.BufferAttribute(col, 4));
|
||||
const mat = new T.PointsMaterial({ size, map: tex, vertexColors: true, transparent: true, depthWrite: false,
|
||||
blending: additive ? T.AdditiveBlending : T.NormalBlending, sizeAttenuation: true });
|
||||
const pts = new T.Points(geo, mat);
|
||||
pts.frustumCulled = false;
|
||||
scene.add(pts);
|
||||
let next = 0;
|
||||
for (let i = 0; i < max; i++) pos[i * 3 + 1] = -100;
|
||||
return {
|
||||
pts,
|
||||
spawn(x, y, z, vx, vy, vz, l, r, g, b) {
|
||||
const i = next; next = (next + 1) % max;
|
||||
pos[i * 3] = x; pos[i * 3 + 1] = y; pos[i * 3 + 2] = z;
|
||||
vel[i * 3] = vx; vel[i * 3 + 1] = vy; vel[i * 3 + 2] = vz;
|
||||
life[i] = life0[i] = l; base[i * 3] = r; base[i * 3 + 1] = g; base[i * 3 + 2] = b;
|
||||
},
|
||||
update(dt, grav, drag) {
|
||||
for (let i = 0; i < max; i++) {
|
||||
if (life[i] <= 0) continue;
|
||||
life[i] -= dt;
|
||||
const k = Math.max(0, life[i] / life0[i]);
|
||||
if (life[i] <= 0) { pos[i * 3 + 1] = -100; col[i * 4 + 3] = 0; continue; }
|
||||
vel[i * 3 + 1] -= grav * dt;
|
||||
const d = Math.max(0, 1 - drag * dt);
|
||||
vel[i * 3] *= d; vel[i * 3 + 1] *= d; vel[i * 3 + 2] *= d;
|
||||
pos[i * 3] += vel[i * 3] * dt; pos[i * 3 + 1] += vel[i * 3 + 1] * dt; pos[i * 3 + 2] += vel[i * 3 + 2] * dt;
|
||||
if (pos[i * 3 + 1] < 0.02 && grav > 0) { pos[i * 3 + 1] = 0.02; vel[i * 3 + 1] *= -0.35; vel[i * 3] *= 0.6; vel[i * 3 + 2] *= 0.6; }
|
||||
col[i * 4] = base[i * 3]; col[i * 4 + 1] = base[i * 3 + 1] * (additive ? k : 1); col[i * 4 + 2] = base[i * 3 + 2] * (additive ? k * k : 1);
|
||||
col[i * 4 + 3] = additive ? k : k * 0.55;
|
||||
}
|
||||
geo.attributes.position.needsUpdate = true; geo.attributes.color.needsUpdate = true;
|
||||
},
|
||||
clear() { for (let i = 0; i < max; i++) { life[i] = 0; pos[i * 3 + 1] = -100; col[i * 4 + 3] = 0; } },
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- robot model
|
||||
const M = {};
|
||||
function mats() {
|
||||
if (M.dark) return M;
|
||||
M.dark = new T.MeshStandardMaterial({ color: 0x2a2d33, metalness: 0.6, roughness: 0.5 });
|
||||
M.steel = new T.MeshStandardMaterial({ color: 0xb8bec7, metalness: 0.85, roughness: 0.3 });
|
||||
M.rubber = new T.MeshStandardMaterial({ color: 0x15161a, metalness: 0, roughness: 0.92 });
|
||||
M.hub = new T.MeshStandardMaterial({ color: 0x9aa1aa, metalness: 0.8, roughness: 0.35 });
|
||||
M.glowW = new T.MeshStandardMaterial({ color: 0xffffff, emissive: 0xfff2c0, emissiveIntensity: 1.5 });
|
||||
M.stripe = new T.MeshStandardMaterial({ map: stripeTex(), metalness: 0.3, roughness: 0.6 });
|
||||
M.flame = new T.MeshBasicMaterial({ color: 0xff3a08, transparent: true, opacity: 0.42, blending: T.AdditiveBlending, depthWrite: false, side: T.DoubleSide });
|
||||
M.trackTex = canvasTex(64, 16, (c, w, h) => { c.fillStyle = '#17181b'; c.fillRect(0, 0, w, h); c.fillStyle = '#2c2e33'; for (let x = 0; x < w; x += 8) c.fillRect(x, 0, 4, h); }, [6, 1]);
|
||||
M.track = new T.MeshStandardMaterial({ map: M.trackTex, roughness: 0.85, metalness: 0.2 });
|
||||
return M;
|
||||
}
|
||||
const box = (w, h, d, m) => { const o = new T.Mesh(new T.BoxGeometry(w, h, d), m); o.castShadow = true; o.receiveShadow = true; return o; };
|
||||
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; };
|
||||
|
||||
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;
|
||||
const L = st.len, Wd = st.wid, H = st.h;
|
||||
const body = new T.MeshStandardMaterial({ color: paint.body, metalness: 0.45, roughness: 0.42 });
|
||||
const accent = new T.MeshStandardMaterial({ color: paint.accent, metalness: 0.3, roughness: 0.45 });
|
||||
const armour = ar ? new T.MeshStandardMaterial({ color: ar.tint, metalness: 0.9, roughness: 0.28 }) : null;
|
||||
const root = new T.Group(), tilt = new T.Group();
|
||||
root.add(tilt);
|
||||
const out = { root, tilt, body, st, build, roll: 0, flash: 0, spinA: 0, sawA: 0, gunA: 0, smokeT: 0 };
|
||||
const big = wh && wh.kind === 'big';
|
||||
const c = big ? 0.12 : 0.1; // ground clearance
|
||||
out.c = c;
|
||||
|
||||
// chassis
|
||||
let top = c + H;
|
||||
if (ch.shape === 'wedge') {
|
||||
const s = new T.Shape();
|
||||
s.moveTo(-L / 2, 0); s.lineTo(L / 2, 0); s.lineTo(L / 2, H * 0.22); s.lineTo(-L / 2 + L * 0.38, H); s.lineTo(-L / 2, H); s.closePath();
|
||||
const g = new T.ExtrudeGeometry(s, { depth: Wd, bevelEnabled: true, bevelSize: 0.015, bevelThickness: 0.015, bevelSegments: 1 });
|
||||
g.translate(0, 0, -Wd / 2);
|
||||
const o = new T.Mesh(g, body); o.position.y = c; o.castShadow = o.receiveShadow = true; tilt.add(o);
|
||||
const st1 = box(L * 0.32, 0.02, Wd * 0.8, m.stripe); st1.position.set(-L / 2 + L * 0.19, top + 0.012, 0); tilt.add(st1);
|
||||
} else if (ch.shape === 'dome') {
|
||||
const o = box(L, H * 0.5, Wd, body); o.position.y = c + H * 0.25; tilt.add(o);
|
||||
const d = new T.Mesh(new T.SphereGeometry(1, 28, 12, 0, Math.PI * 2, 0, Math.PI / 2), body);
|
||||
d.scale.set(L * 0.5, H * 0.75, Wd * 0.5); d.position.y = c + H * 0.5; d.castShadow = true; tilt.add(d);
|
||||
const ring = new T.Mesh(new T.TorusGeometry(1, 0.035, 8, 32), accent);
|
||||
ring.rotation.x = Math.PI / 2; ring.scale.set(L * 0.5, Wd * 0.5, 1); ring.position.y = c + H * 0.5; tilt.add(ring);
|
||||
top = c + H * 1.2;
|
||||
} else {
|
||||
const o = box(L, H, Wd, body); o.position.y = c + H / 2; tilt.add(o);
|
||||
const s1 = box(L * 0.86, 0.02, Wd * 0.22, accent); s1.position.set(0, top + 0.01, 0); tilt.add(s1);
|
||||
const s2 = box(0.06, H * 0.6, Wd * 1.002, m.stripe); s2.position.set(-L / 2 + 0.08, c + H / 2, 0); tilt.add(s2);
|
||||
}
|
||||
out.top = top;
|
||||
|
||||
// armour plates (sides + rear), bolts
|
||||
if (armour) {
|
||||
for (const sz of [-1, 1]) {
|
||||
const p = box(L * 0.9, H * 0.78, 0.05, armour); p.position.set(0, c + H * 0.42, sz * (Wd / 2 + 0.028)); tilt.add(p);
|
||||
for (const bx of [-0.36, 0, 0.36]) { const b = cyl(0.025, 0.025, 0.03, m.dark, 8); b.rotation.x = Math.PI / 2; b.position.set(bx * L, c + H * 0.55, sz * (Wd / 2 + 0.06)); tilt.add(b); }
|
||||
}
|
||||
const r = box(0.05, H * 0.78, Wd * 0.95, armour); r.position.set(-L / 2 - 0.028, c + H * 0.42, 0); tilt.add(r);
|
||||
}
|
||||
|
||||
// wheels
|
||||
out.wheels = [];
|
||||
const side = Wd / 2 + (armour ? 0.13 : 0.08);
|
||||
if (wh.kind === 'tracks') {
|
||||
for (const sz of [-1, 1]) {
|
||||
const t = box(L * 1.02, 0.3, 0.2, m.track); t.position.set(0, 0.15, sz * side); tilt.add(t);
|
||||
for (const bx of [-0.42, 0.42]) { const w = cyl(0.15, 0.15, 0.21, m.hub, 14); w.rotation.x = Math.PI / 2; w.position.set(bx * L, 0.15, sz * side); tilt.add(w); }
|
||||
}
|
||||
} else if (big) {
|
||||
const r = (c + H) / 2 + 0.09;
|
||||
for (const sz of [-1, 1]) {
|
||||
const w = new T.Group(); w.position.set(-L * 0.12, (c + H) / 2, sz * (side + 0.04));
|
||||
const tyre = cyl(r, r, 0.2, m.rubber, 22); tyre.rotation.x = Math.PI / 2; w.add(tyre);
|
||||
const hub = cyl(r * 0.45, r * 0.45, 0.22, m.hub, 12); hub.rotation.x = Math.PI / 2; w.add(hub);
|
||||
tilt.add(w); out.wheels.push(w);
|
||||
}
|
||||
out.wheelR = r;
|
||||
} else {
|
||||
for (const sx of [-1, 1]) for (const sz of [-1, 1]) {
|
||||
const w = new T.Group(); w.position.set(sx * L * 0.32, 0.16, sz * side);
|
||||
const tyre = cyl(0.16, 0.16, 0.12, m.rubber, 16); tyre.rotation.x = Math.PI / 2; w.add(tyre);
|
||||
const hub = cyl(0.07, 0.07, 0.13, m.hub, 8); hub.rotation.x = Math.PI / 2; w.add(hub);
|
||||
tilt.add(w); out.wheels.push(w);
|
||||
}
|
||||
out.wheelR = 0.16;
|
||||
}
|
||||
|
||||
// headlights + antenna
|
||||
for (const sz of [-0.3, 0.3]) { const l = box(0.03, 0.05, 0.1, m.glowW); l.position.set(L / 2 + 0.005, c + H * 0.62, sz * Wd); tilt.add(l); }
|
||||
const ant = cyl(0.01, 0.01, 0.45, m.dark, 6); ant.position.set(-L / 2 + 0.12, top + 0.22, Wd / 2 - 0.12); tilt.add(ant);
|
||||
const tip = new T.Mesh(new T.SphereGeometry(0.035, 8, 6), new T.MeshStandardMaterial({ color: paint.accent, emissive: paint.accent, emissiveIntensity: 0.9 }));
|
||||
tip.position.set(-L / 2 + 0.12, top + 0.46, Wd / 2 - 0.12); tilt.add(tip);
|
||||
|
||||
// main weapon (front = +x)
|
||||
const w = st.weapon;
|
||||
if (w) {
|
||||
if (w.type === 'wedge') {
|
||||
const p = box(0.55, 0.04, Wd * 1.05, m.steel); p.position.set(L / 2 + 0.22, c * 0.5 + 0.08, 0); p.rotation.z = -0.42; tilt.add(p);
|
||||
} else if (w.type === 'flipper') {
|
||||
const piv = new T.Group(); piv.position.set(L / 2 - 0.08, c + H * 0.3, 0); tilt.add(piv);
|
||||
const p = box(0.62, 0.05, Wd * 0.92, m.steel); p.position.x = 0.31; piv.add(p);
|
||||
const s = box(0.6, 0.012, Wd * 0.3, accent); s.position.set(0.31, 0.03, 0); piv.add(s);
|
||||
out.flipper = piv;
|
||||
} else if (w.type === 'hammer') {
|
||||
const piv = new T.Group(); piv.position.set(-L * 0.08, top + 0.06, 0); tilt.add(piv);
|
||||
const post = box(0.12, 0.14, 0.18, m.dark); post.position.set(-L * 0.08, top + 0.03, 0); tilt.add(post);
|
||||
const arm = box(L * 0.72, 0.07, 0.07, m.dark); arm.position.x = L * 0.36; piv.add(arm);
|
||||
const head = box(0.1, 0.34, 0.06, m.steel); head.position.set(L * 0.72, -0.1, 0); piv.add(head);
|
||||
const back = box(0.14, 0.12, 0.12, accent); back.position.set(L * 0.72, 0.08, 0); piv.add(back);
|
||||
out.hammer = piv;
|
||||
} else if (w.type === 'saw') {
|
||||
const arm = box(0.35, 0.08, 0.08, m.dark); arm.position.set(L / 2 + 0.05, c + H * 0.55, 0); tilt.add(arm);
|
||||
const g = new T.Group(); g.position.set(L / 2 + 0.2, c + H * 0.55, 0); tilt.add(g);
|
||||
const d = cyl(0.3, 0.3, 0.025, m.steel, 28); d.rotation.x = Math.PI / 2; g.add(d);
|
||||
for (let k = 0; k < 14; k++) { const t = box(0.07, 0.04, 0.026, m.steel); const a = k / 14 * Math.PI * 2; t.position.set(Math.cos(a) * 0.31, Math.sin(a) * 0.31, 0); t.rotation.z = a + 0.6; g.add(t); }
|
||||
const hub = cyl(0.06, 0.06, 0.04, accent, 10); hub.rotation.x = Math.PI / 2; g.add(hub);
|
||||
out.saw = g;
|
||||
} else if (w.type === 'spinner') {
|
||||
const post = cyl(0.07, 0.07, 0.25, m.dark, 10); post.position.set(L / 2 + 0.02, c + H * 0.35, 0); tilt.add(post);
|
||||
const g = new T.Group(); g.position.set(L / 2 + 0.02, c + H * 0.32, 0); tilt.add(g);
|
||||
const bar = box(1.25, 0.07, 0.16, m.steel); g.add(bar);
|
||||
for (const sx of [-1, 1]) { const t = box(0.1, 0.09, 0.2, accent); t.position.x = sx * 0.6; g.add(t); }
|
||||
out.spinner = g;
|
||||
} else if (w.type === 'crusher') {
|
||||
out.jaws = [];
|
||||
for (const sz of [-1, 1]) {
|
||||
const piv = new T.Group(); piv.position.set(L / 2 - 0.02, c + H * 0.45, sz * Wd * 0.34); tilt.add(piv);
|
||||
const j = box(0.58, 0.14, 0.08, m.steel); j.position.x = 0.29; piv.add(j);
|
||||
const tooth = box(0.08, 0.14, 0.14, accent); tooth.position.set(0.56, 0, -sz * 0.05); piv.add(tooth);
|
||||
piv.userData.side = sz; out.jaws.push(piv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tower on top
|
||||
const tw = st.tower;
|
||||
if (tw) {
|
||||
const g = new T.Group(); g.position.set(-L * 0.05, top, 0); tilt.add(g);
|
||||
const base = cyl(0.2, 0.24, 0.12, m.dark, 16); base.position.y = 0.06; g.add(base);
|
||||
if (tw.type === 'flamer') {
|
||||
const tank = cyl(0.08, 0.08, 0.26, new T.MeshStandardMaterial({ color: 0xc0392b, metalness: 0.4, roughness: 0.4 }), 12); tank.position.set(-0.08, 0.25, 0); g.add(tank);
|
||||
const n = cyl(0.045, 0.06, 0.42, m.steel, 10); n.rotation.z = -Math.PI / 2; n.position.set(0.24, 0.18, 0); g.add(n);
|
||||
const f = new T.Mesh(new T.ConeGeometry(0.42, 2.6, 14, 1, true), M.flame);
|
||||
f.rotation.z = Math.PI / 2; f.position.set(0.45 + 1.3, 0.18, 0); f.visible = false; g.add(f);
|
||||
out.flame = f;
|
||||
} else if (tw.type === 'minigun') {
|
||||
const hous = box(0.22, 0.16, 0.2, accent); hous.position.y = 0.2; g.add(hous);
|
||||
const brl = new T.Group(); brl.position.set(0.1, 0.2, 0); g.add(brl);
|
||||
for (let k = 0; k < 4; k++) { const b = cyl(0.022, 0.022, 0.5, m.steel, 6); b.rotation.z = -Math.PI / 2; const a = k / 4 * Math.PI * 2; b.position.set(0.25, Math.cos(a) * 0.045, Math.sin(a) * 0.045); brl.add(b); }
|
||||
out.gun = brl;
|
||||
const fl = new T.Mesh(new T.SphereGeometry(0.09, 8, 6), new T.MeshBasicMaterial({ color: 0xffd060, transparent: true, blending: T.AdditiveBlending, depthWrite: false }));
|
||||
fl.position.set(0.62, 0.2, 0); fl.visible = false; g.add(fl); out.muzzle = fl;
|
||||
} else if (tw.type === 'rockets') {
|
||||
const pod = box(0.38, 0.26, 0.36, accent); pod.position.set(0.02, 0.27, 0); g.add(pod);
|
||||
for (const [y, z] of [[0.2, -0.09], [0.2, 0.09], [0.34, -0.09], [0.34, 0.09]]) { const t = cyl(0.05, 0.05, 0.06, m.dark, 10); t.rotation.z = Math.PI / 2; t.position.set(0.22, y, z); g.add(t); }
|
||||
}
|
||||
out.turret = g;
|
||||
}
|
||||
root.traverse(o => { if (o.isMesh && !o.material.transparent) { o.castShadow = true; } });
|
||||
return out;
|
||||
}
|
||||
|
||||
// per-frame robot animation from the combat state
|
||||
function poseRobot(R, r, dt) {
|
||||
const w = R.st.weapon;
|
||||
R.root.position.set(r.x, r.y, r.z);
|
||||
R.root.rotation.y = -r.a;
|
||||
// upside down when flipped
|
||||
const want = r.flipped > 0 ? Math.PI : 0;
|
||||
if (r.y > 0.05 && !r.lifted) R.roll += dt * 9; else R.roll = lerp(R.roll, want, Math.min(1, dt * 10));
|
||||
if (r.y <= 0.05 && Math.abs(R.roll - want) < 0.02) R.roll = want;
|
||||
R.roll %= Math.PI * 2;
|
||||
R.tilt.rotation.x = R.roll;
|
||||
const h = R.c + R.st.h;
|
||||
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.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.z = -R.sawA; }
|
||||
if (R.spinner) { R.spinA += dt * r.spin * 38; R.spinner.rotation.y = 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) { R.flame.visible = r.flameOn; if (r.flameOn) { const f = 0.85 + Math.random() * 0.3; R.flame.scale.set(f, 1, f); } }
|
||||
if (R.gun) { if (r.gunOn) R.gunA += dt * 30; R.gun.rotation.x = R.gunA; R.muzzle.visible = r.gunOn && Math.random() < 0.6; }
|
||||
R.flash = Math.max(0, R.flash - dt * 4);
|
||||
R.body.emissive.setRGB(R.flash * 0.9, R.flash * 0.15, 0);
|
||||
R.root.visible = r.y > -1.6;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- arena
|
||||
function buildArena(scene) {
|
||||
const A = RC.ARENA, m = mats(), half = A.half;
|
||||
const out = {};
|
||||
scene.background = new T.Color(0x07090d);
|
||||
scene.fog = new T.Fog(0x07090d, 26, 60);
|
||||
|
||||
// lights: one shadow-casting key light + floodlight colours
|
||||
scene.add(new T.HemisphereLight(0x8fa6c8, 0x1a140f, 0.55));
|
||||
const key = new T.DirectionalLight(0xfff1dc, 1.25);
|
||||
key.position.set(6, 16, 9); key.castShadow = true;
|
||||
key.shadow.mapSize.set(2048, 2048);
|
||||
Object.assign(key.shadow.camera, { left: -11, right: 11, top: 11, bottom: -11, near: 1, far: 40 });
|
||||
key.shadow.bias = -0.0008;
|
||||
scene.add(key);
|
||||
const rimA = new T.PointLight(0xff7a1a, 1.1, 22); rimA.position.set(-9, 5, 9); scene.add(rimA);
|
||||
const rimB = new T.PointLight(0x4fa8ff, 0.9, 22); rimB.position.set(9, 5, -9); scene.add(rimB);
|
||||
out.flashLight = new T.PointLight(0xffaa55, 0, 9); scene.add(out.flashLight);
|
||||
|
||||
// floor
|
||||
const floor = new T.Mesh(new T.PlaneGeometry(half * 2, half * 2), new T.MeshStandardMaterial({ map: floorTex(), metalness: 0.55, roughness: 0.62 }));
|
||||
floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
|
||||
const outer = new T.Mesh(new T.PlaneGeometry(80, 80), new T.MeshStandardMaterial({ color: 0x0d0f13, roughness: 1 }));
|
||||
outer.rotation.x = -Math.PI / 2; outer.position.y = -0.02; outer.receiveShadow = true; scene.add(outer);
|
||||
|
||||
// spike walls (instanced spikes)
|
||||
const wallMat = new T.MeshStandardMaterial({ color: 0x30343b, metalness: 0.7, roughness: 0.45 });
|
||||
const n = Math.round(half * 2 / 0.5);
|
||||
const spikes = new T.InstancedMesh(new T.ConeGeometry(0.07, 0.28, 8), m.steel, n * 4);
|
||||
const dm = new T.Object3D(); let si = 0;
|
||||
for (const [nx, nz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
|
||||
const wall = box(nz ? half * 2 + 0.5 : 0.25, 0.55, nz ? 0.25 : half * 2 + 0.5, wallMat);
|
||||
wall.position.set(nx * (half + 0.12), 0.275, nz * (half + 0.12)); scene.add(wall);
|
||||
const strip = box(nz ? half * 2 + 0.5 : 0.26, 0.08, nz ? 0.26 : half * 2 + 0.5, m.stripe);
|
||||
strip.position.set(nx * (half + 0.12), 0.58, nz * (half + 0.12)); scene.add(strip);
|
||||
for (let k = 0; k < n; k++) {
|
||||
const t = -half + 0.25 + k * 0.5;
|
||||
dm.position.set(nx ? nx * (half - 0.02) : t, 0.3, nz ? nz * (half - 0.02) : t);
|
||||
dm.rotation.set(0, 0, 0);
|
||||
if (nx) dm.rotation.z = nx > 0 ? Math.PI / 2 : -Math.PI / 2; else dm.rotation.x = nz > 0 ? -Math.PI / 2 : Math.PI / 2;
|
||||
dm.updateMatrix(); spikes.setMatrixAt(si++, dm.matrix);
|
||||
}
|
||||
}
|
||||
spikes.castShadow = true; scene.add(spikes);
|
||||
|
||||
// glass + posts + floodlight rigs
|
||||
const glass = new T.MeshStandardMaterial({ color: 0x9fc3ff, transparent: true, opacity: 0.07, metalness: 0.1, roughness: 0.05, depthWrite: false, side: T.DoubleSide });
|
||||
for (const [nx, nz] of [[-1, 0], [0, -1]]) {
|
||||
const g = new T.Mesh(new T.PlaneGeometry(half * 2 + 0.6, 2.6), glass);
|
||||
g.position.set(nx * (half + 0.3), 1.9, nz * (half + 0.3)); g.rotation.y = nx ? Math.PI / 2 : 0; scene.add(g);
|
||||
}
|
||||
for (const [px, pz] of [[-1, -1], [1, -1], [-1, 1]]) {
|
||||
const post = box(0.22, 3.4, 0.22, wallMat); post.position.set(px * (half + 0.35), 1.7, pz * (half + 0.35)); scene.add(post);
|
||||
const lamp = box(0.5, 0.3, 0.3, m.glowW); lamp.position.set(px * (half + 0.2), 3.5, pz * (half + 0.2)); scene.add(lamp);
|
||||
}
|
||||
// audience stands behind the back walls
|
||||
const seats = new T.InstancedMesh(new T.BoxGeometry(0.32, 0.5, 0.32), new T.MeshStandardMaterial({ roughness: 0.9 }), 900);
|
||||
const col = new T.Color(); let ci = 0; let sd = 11;
|
||||
const rnd = () => { sd = (sd * 16807) % 2147483647; return sd / 2147483647; };
|
||||
for (const [nx, nz] of [[-1, 0], [0, -1]]) for (let row = 0; row < 5; row++) {
|
||||
const step = box(nz ? half * 2 + 6 : 1, 0.6, nz ? 1 : half * 2 + 6, new T.MeshStandardMaterial({ color: 0x14161b, roughness: 1 }));
|
||||
const d = half + 1.6 + row * 1.0;
|
||||
step.position.set(nx * d, 0.3 + row * 0.6, nz * d); scene.add(step);
|
||||
for (let k = 0; k < 44 && ci < 900; k++) {
|
||||
if (rnd() < 0.3) continue;
|
||||
const t = -half - 2 + k * 0.45 + rnd() * 0.1;
|
||||
dm.position.set(nx ? nx * d : t, 0.85 + row * 0.6, nz ? nz * d : t); dm.rotation.set(0, rnd(), 0);
|
||||
dm.scale.set(1, 0.8 + rnd() * 0.5, 1); dm.updateMatrix(); seats.setMatrixAt(ci, dm.matrix);
|
||||
col.setHSL(rnd(), 0.3, 0.07 + rnd() * 0.08); seats.setColorAt(ci, col); ci++;
|
||||
}
|
||||
}
|
||||
seats.count = ci; dm.scale.set(1, 1, 1); scene.add(seats);
|
||||
|
||||
// floor saws
|
||||
out.saws = A.saws.map(h => {
|
||||
const g = new T.Group(); g.position.set(h.x, 0.005, h.z); scene.add(g);
|
||||
const d = cyl(h.r * 0.85, h.r * 0.85, 0.035, m.steel, 32); g.add(d);
|
||||
for (let k = 0; k < 18; k++) { const t = box(0.14, 0.035, 0.07, m.steel); const a = k / 18 * Math.PI * 2; t.position.set(Math.cos(a) * h.r * 0.88, 0, Math.sin(a) * h.r * 0.88); t.rotation.y = -a + 0.6; g.add(t); }
|
||||
const hub = cyl(0.12, 0.12, 0.06, m.dark, 12); g.add(hub);
|
||||
return { h, g, a: 0 };
|
||||
});
|
||||
// flame grilles
|
||||
const grille = canvasTex(64, 64, (c, w) => { c.clearRect(0, 0, w, w); c.strokeStyle = '#3a3e45'; c.lineWidth = 5; for (let x = 4; x < w; x += 12) { c.beginPath(); c.moveTo(x, 0); c.lineTo(x, w); c.stroke(); c.beginPath(); c.moveTo(0, x); c.lineTo(w, x); c.stroke(); } }, [3, 3]);
|
||||
out.flames = A.flames.map(h => {
|
||||
const base = new T.Mesh(new T.PlaneGeometry(h.hw * 2, h.hd * 2), new T.MeshStandardMaterial({ color: 0x1a0e08, emissive: 0x000000 }));
|
||||
base.rotation.x = -Math.PI / 2; base.position.set(h.x, 0.006, h.z); base.receiveShadow = true; scene.add(base);
|
||||
const gr = new T.Mesh(new T.PlaneGeometry(h.hw * 2, h.hd * 2), new T.MeshStandardMaterial({ map: grille, transparent: true, metalness: 0.6, roughness: 0.5 }));
|
||||
gr.rotation.x = -Math.PI / 2; gr.position.set(h.x, 0.012, h.z); scene.add(gr);
|
||||
const cones = [];
|
||||
for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) {
|
||||
const f = new T.Mesh(new T.ConeGeometry(0.22, 1.2, 10, 1, true), M.flame);
|
||||
f.position.set(h.x + (i - 1) * h.hw * 0.62, 0.6, h.z + (j - 1) * h.hd * 0.62); f.visible = false; scene.add(f); cones.push(f);
|
||||
}
|
||||
return { h, base, cones };
|
||||
});
|
||||
|
||||
// guardian 1: forge press
|
||||
const P = A.press, frameMat = new T.MeshStandardMaterial({ color: 0x3b3f47, metalness: 0.7, roughness: 0.4 });
|
||||
for (const [sx, sz] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) {
|
||||
const post = box(0.16, 3.4, 0.16, frameMat); post.position.set(P.x + sx * (P.hw + 0.05), 1.7, P.z + sz * (P.hd + 0.05)); scene.add(post);
|
||||
}
|
||||
const beam = box(P.hw * 2 + 0.4, 0.25, P.hd * 2 + 0.4, frameMat); beam.position.set(P.x, 3.45, P.z); scene.add(beam);
|
||||
const head = new T.Group(); scene.add(head);
|
||||
const hb = box(P.hw * 1.8, 0.5, P.hd * 1.8, new T.MeshStandardMaterial({ color: 0x4a4f58, metalness: 0.85, roughness: 0.3 })); head.add(hb);
|
||||
const hs = box(P.hw * 1.82, 0.12, P.hd * 1.82, m.stripe); hs.position.y = 0.2; head.add(hs);
|
||||
const ram = cyl(0.16, 0.16, 3, m.steel, 12); ram.position.y = 1.7; head.add(ram);
|
||||
out.press = head;
|
||||
out.pressLamp = new T.Mesh(new T.SphereGeometry(0.16, 12, 8), new T.MeshStandardMaterial({ color: 0x550000, emissive: 0xff2020, emissiveIntensity: 0 }));
|
||||
out.pressLamp.position.set(P.x, 3.7, P.z); scene.add(out.pressLamp);
|
||||
|
||||
// guardian 2: magnet crane (post outside the corner, boom, trolley, magnet)
|
||||
const C = A.crane;
|
||||
const cpost = box(0.35, 4.6, 0.35, frameMat); cpost.position.set(C.x - 2.4, 2.3, C.z + 2.4); scene.add(cpost);
|
||||
const boom = box(1, 0.22, 0.22, new T.MeshStandardMaterial({ color: 0xe0a020, metalness: 0.5, roughness: 0.5 })); boom.position.y = 4.4; scene.add(boom);
|
||||
const cable = box(0.03, 1, 0.03, m.dark); scene.add(cable);
|
||||
const mag = new T.Group(); scene.add(mag);
|
||||
const md = cyl(0.42, 0.42, 0.18, new T.MeshStandardMaterial({ color: 0x2b2e34, metalness: 0.8, roughness: 0.35 }), 20); mag.add(md);
|
||||
const mr = cyl(0.43, 0.43, 0.06, m.stripe, 20); mr.position.y = 0.08; mag.add(mr);
|
||||
out.crane = { post: cpost, boom, cable, mag, px: C.x - 2.4, pz: C.z + 2.4 };
|
||||
|
||||
// pit doors + warning lights
|
||||
const pit = A.pit;
|
||||
out.pitDoors = [-1, 1].map(sx => {
|
||||
const d = box(pit.hw, 0.05, pit.hd * 2, new T.MeshStandardMaterial({ color: 0x3d4148, metalness: 0.8, roughness: 0.4 }));
|
||||
d.position.set(pit.x + sx * pit.hw / 2, 0.025, pit.z); d.userData.sx = sx; scene.add(d); return d;
|
||||
});
|
||||
out.pitLamps = [[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz]) => {
|
||||
const l = new T.Mesh(new T.SphereGeometry(0.09, 10, 6), new T.MeshStandardMaterial({ color: 0x400000, emissive: 0xff1a1a, emissiveIntensity: 0 }));
|
||||
l.position.set(pit.x + sx * (pit.hw + 0.12), 0.08, pit.z + sz * (pit.hd + 0.12)); scene.add(l); return l;
|
||||
});
|
||||
// rockets
|
||||
out.rocketGeo = new T.CylinderGeometry(0.05, 0.05, 0.32, 8); out.rocketGeo.rotateZ(Math.PI / 2);
|
||||
out.rocketMat = new T.MeshStandardMaterial({ color: 0xdddddd, emissive: 0x331100 });
|
||||
out.rocketMeshes = [];
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- garage
|
||||
function buildGarage(scene) {
|
||||
scene.background = new T.Color(0x0c0f15);
|
||||
scene.add(new T.HemisphereLight(0x9fb4d8, 0x1c160f, 0.6));
|
||||
const spot = new T.SpotLight(0xfff0d8, 2.2, 14, 0.62, 0.45);
|
||||
spot.position.set(1.6, 5, 2.6); spot.target.position.set(0, 0, 0); spot.castShadow = true; spot.shadow.mapSize.set(1024, 1024);
|
||||
scene.add(spot); scene.add(spot.target);
|
||||
const rim = new T.PointLight(0xff7a1a, 1.2, 8); rim.position.set(-2.5, 1.2, -1.5); scene.add(rim);
|
||||
const rim2 = new T.PointLight(0x4fa8ff, 0.8, 8); rim2.position.set(2.5, 1.0, -2); scene.add(rim2);
|
||||
const floor = new T.Mesh(new T.PlaneGeometry(30, 30), new T.MeshStandardMaterial({ color: 0x1a1d23, metalness: 0.3, roughness: 0.8 }));
|
||||
floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
|
||||
const turntable = new T.Group(); scene.add(turntable);
|
||||
const disc = cyl(1.5, 1.6, 0.12, new T.MeshStandardMaterial({ color: 0x3a3e46, metalness: 0.8, roughness: 0.35 }), 48);
|
||||
disc.position.y = 0.06; disc.receiveShadow = true; turntable.add(disc);
|
||||
const ring = new T.Mesh(new T.TorusGeometry(1.56, 0.03, 8, 64), new T.MeshStandardMaterial({ color: 0xff7a1a, emissive: 0xff7a1a, emissiveIntensity: 0.6 }));
|
||||
ring.rotation.x = Math.PI / 2; ring.position.y = 0.12; scene.add(ring);
|
||||
const wallMat = new T.MeshStandardMaterial({ map: canvasTex(256, 128, (c, w, h) => {
|
||||
c.fillStyle = '#171a20'; c.fillRect(0, 0, w, h); c.fillStyle = '#0d0f13';
|
||||
for (let x = 8; x < w; x += 16) for (let y = 8; y < h; y += 16) { c.beginPath(); c.arc(x, y, 2.5, 0, 7); c.fill(); }
|
||||
}, [6, 2]), roughness: 0.9 });
|
||||
const wall = new T.Mesh(new T.PlaneGeometry(24, 8), wallMat); wall.position.set(0, 4, -4); wall.receiveShadow = true; scene.add(wall);
|
||||
const st = box(24, 0.3, 0.05, mats().stripe); st.position.set(0, 0.4, -3.97); scene.add(st);
|
||||
// a few crates
|
||||
for (const [x, z, s] of [[-3.2, -3.2, 0.7], [-2.5, -3.4, 0.5], [3.4, -3.1, 0.8]]) {
|
||||
const b = box(s, s, s, new T.MeshStandardMaterial({ color: 0x4b3a26, roughness: 0.9 })); b.position.set(x, s / 2, z); scene.add(b);
|
||||
}
|
||||
return { turntable };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
RC.Render = function (canvas, W, H) {
|
||||
const renderer = new T.WebGLRenderer({ canvas, antialias: true });
|
||||
renderer.outputEncoding = T.sRGBEncoding;
|
||||
renderer.toneMapping = T.ACESFilmicToneMapping;
|
||||
renderer.toneMappingExposure = 1.15;
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = T.PCFSoftShadowMap;
|
||||
|
||||
const arenaScene = new T.Scene(), garageScene = new T.Scene();
|
||||
const arena = buildArena(arenaScene), garage = buildGarage(garageScene);
|
||||
const tex = dotTex();
|
||||
// orthographic camera: point sizes are screen pixels (x pixel ratio), not metres
|
||||
const sparks = Particles(arenaScene, 900, 6, true, tex);
|
||||
const smoke = Particles(arenaScene, 300, 34, false, tex);
|
||||
const fire = Particles(arenaScene, 300, 18, true, tex);
|
||||
|
||||
const VIEW = 15.4, asp = W / H;
|
||||
const cam = new T.OrthographicCamera(-VIEW * asp / 2, VIEW * asp / 2, VIEW / 2, -VIEW / 2, 0.1, 120);
|
||||
const camBase = new T.Vector3(15.2, 15.5, 15.2), camLook = new T.Vector3(-1.25, 0, -1.25);
|
||||
cam.position.copy(camBase); cam.lookAt(camLook);
|
||||
const gcam = new T.PerspectiveCamera(34, asp, 0.1, 60);
|
||||
gcam.position.set(2.9, 1.8, 3.4); gcam.lookAt(0, 0.35, 0);
|
||||
gcam.setViewOffset(W, H, 170, 20, W, H);
|
||||
|
||||
let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0;
|
||||
|
||||
const api = {
|
||||
get mode() { return mode; },
|
||||
resize(scale) {
|
||||
renderer.setPixelRatio(Math.min(3, scale * (root.devicePixelRatio || 1)));
|
||||
renderer.setSize(W, H);
|
||||
},
|
||||
showGarage(build, paint) {
|
||||
mode = 'garage';
|
||||
if (gRobot) garage.turntable.remove(gRobot.root);
|
||||
gRobot = buildRobot(build, paint);
|
||||
gRobot.root.position.y = 0.12;
|
||||
garage.turntable.add(gRobot.root);
|
||||
},
|
||||
setPaint(paint) { if (gRobot) { gRobot.body.color.setHex(paint.body); } },
|
||||
showArena(s, builds, paints) {
|
||||
mode = 'arena'; state = s;
|
||||
for (const R of robots) arenaScene.remove(R.root);
|
||||
robots = builds.map((b, i) => { const R = buildRobot(b, paints[i]); arenaScene.add(R.root); return R; });
|
||||
sparks.clear(); smoke.clear(); fire.clear(); shake = 0;
|
||||
for (const m of arena.rocketMeshes) arenaScene.remove(m);
|
||||
arena.rocketMeshes = [];
|
||||
},
|
||||
events(list) {
|
||||
for (const e of list) {
|
||||
const y = e.y || 0.35;
|
||||
switch (e.type) {
|
||||
case 'sparks': burst(e.x, y, e.z, e.n || 6, 4, [1, 0.85, 0.4]); break;
|
||||
case 'dmg':
|
||||
if (!e.tick && robots[e.who]) robots[e.who].flash = Math.min(1, 0.4 + e.amount / 25);
|
||||
if (!e.tick && e.amount > 4) { burst(e.x, 0.4, e.z, 10 + e.amount, 5, [1, 0.8, 0.35]); shake = Math.max(shake, Math.min(0.35, e.amount / 60)); }
|
||||
break;
|
||||
case 'wall': burst(e.x, 0.3, e.z, 14, 4, [1, 0.8, 0.4]); shake = Math.max(shake, 0.12); break;
|
||||
case 'bump': burst(e.x, 0.3, e.z, Math.round(e.speed * 3), 3, [1, 0.9, 0.6]); break;
|
||||
case 'smash': burst(e.x, 0.1, e.z, 18, 4, [1, 0.85, 0.5]); puff(e.x, e.z, 4); shake = Math.max(shake, 0.2); break;
|
||||
case 'flip': puff(e.x, e.z, 3); break;
|
||||
case 'land': puff(e.x, e.z, 6); shake = Math.max(shake, 0.15); break;
|
||||
case 'spinhit': burst(e.x, 0.3, e.z, 30, 7, [1, 0.9, 0.5]); shake = Math.max(shake, 0.3 * e.k); break;
|
||||
case 'boom': explode(e.x, e.y || 0.4, e.z, 0.6); break;
|
||||
case 'press': puff(e.x, e.z, 14); burst(e.x, 0.1, e.z, 24, 5, [1, 0.8, 0.4]); shake = Math.max(shake, 0.45); break;
|
||||
case 'drop': puff(e.x, e.z, 8); shake = Math.max(shake, 0.2); break;
|
||||
case 'ko': explode(e.x, 0.5, e.z, 1.2); break;
|
||||
case 'boost': for (let k = 0; k < 6; k++) fire.spawn(e.x, 0.3, e.z, (Math.random() - 0.5), 0.6, (Math.random() - 0.5), 0.4, 1, 0.6, 0.2); break;
|
||||
}
|
||||
}
|
||||
},
|
||||
project(x, y, z) {
|
||||
const v = new T.Vector3(x, y, z).project(cam);
|
||||
return { x: (v.x + 1) / 2 * W, y: (1 - v.y) / 2 * H };
|
||||
},
|
||||
frame(dt, now) {
|
||||
if (mode === 'garage') {
|
||||
garage.turntable.rotation.y += dt * 0.45;
|
||||
renderer.render(garageScene, gcam);
|
||||
return;
|
||||
}
|
||||
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;
|
||||
cam.position.set(camBase.x + sx, camBase.y, camBase.z + sz);
|
||||
cam.lookAt(camLook.x + sx, camLook.y, camLook.z + sz);
|
||||
flashT = Math.max(0, flashT - dt * 3);
|
||||
arena.flashLight.intensity = flashT * 4;
|
||||
renderer.render(arenaScene, cam);
|
||||
},
|
||||
};
|
||||
|
||||
function burst(x, y, z, n, sp, c) {
|
||||
for (let k = 0; k < n; k++) {
|
||||
const a = Math.random() * Math.PI * 2, v = sp * (0.3 + Math.random());
|
||||
sparks.spawn(x, y, z, Math.cos(a) * v, 1 + Math.random() * sp, Math.sin(a) * v, 0.25 + Math.random() * 0.45, c[0], c[1], c[2]);
|
||||
}
|
||||
}
|
||||
function puff(x, z, n) {
|
||||
for (let k = 0; k < n; k++) { const a = Math.random() * 6.28; smoke.spawn(x + Math.cos(a) * 0.3, 0.15, z + Math.sin(a) * 0.3, Math.cos(a) * 1.2, 0.4, Math.sin(a) * 1.2, 0.9 + Math.random() * 0.6, 0.55, 0.52, 0.48); }
|
||||
}
|
||||
function explode(x, y, z, k) {
|
||||
burst(x, y, z, Math.round(40 * k), 6 * k, [1, 0.7, 0.25]);
|
||||
for (let i = 0; i < 20 * k; i++) { const a = Math.random() * 6.28, v = Math.random() * 2 * k; fire.spawn(x, y, z, Math.cos(a) * v, 1 + Math.random() * 2, Math.sin(a) * v, 0.5 + Math.random() * 0.4, 1, 0.55, 0.15); }
|
||||
puff(x, z, Math.round(10 * k));
|
||||
arena.flashLight.position.set(x, 1.2, z); flashT = 1; shake = Math.max(shake, 0.3 * k);
|
||||
}
|
||||
|
||||
function animateArena(dt, now) {
|
||||
const s = state; if (!s) return;
|
||||
const A = RC.ARENA;
|
||||
robots.forEach((R, i) => {
|
||||
const r = s.robots[i];
|
||||
poseRobot(R, r, dt);
|
||||
// damaged robots smoke, dead ones burn
|
||||
const hp = r.hp / r.maxHp;
|
||||
R.smokeT -= dt;
|
||||
if (!r.out && hp < 0.45 && R.smokeT <= 0) {
|
||||
R.smokeT = r.dead ? 0.05 : 0.08 + hp * 0.4;
|
||||
const y = r.y + R.top + 0.1;
|
||||
smoke.spawn(r.x, y, r.z, (Math.random() - 0.5) * 0.3, 0.9, (Math.random() - 0.5) * 0.3, 1.6, r.dead ? 0.12 : 0.35, r.dead ? 0.12 : 0.34, r.dead ? 0.12 : 0.33);
|
||||
if (r.dead || hp < 0.2) fire.spawn(r.x, y, r.z, (Math.random() - 0.5) * 0.4, 0.8, (Math.random() - 0.5) * 0.4, 0.4, 1, 0.5, 0.1);
|
||||
}
|
||||
if (r.flameOn && Math.random() < 0.7) {
|
||||
const a = r.turretA + (Math.random() - 0.5) * 0.5, v = 5 + Math.random() * 2;
|
||||
fire.spawn(r.x + Math.cos(r.turretA) * 0.6, r.y + R.top + 0.18, r.z + Math.sin(r.turretA) * 0.6, Math.cos(a) * v, 0.3, Math.sin(a) * v, 0.45, 1, 0.55, 0.15);
|
||||
}
|
||||
});
|
||||
// saws
|
||||
for (const S of arena.saws) {
|
||||
const on = RC.hazardOn(S.h, s.t), warn = RC.hazardOn(S.h, s.t + 0.6);
|
||||
S.g.position.y = lerp(S.g.position.y, on ? 0.09 : warn ? 0.04 : 0.005, Math.min(1, dt * 12));
|
||||
if (on) S.a += dt * 25; S.g.rotation.y = S.a;
|
||||
}
|
||||
for (const F of arena.flames) {
|
||||
const on = RC.hazardOn(F.h, s.t), warn = RC.hazardOn(F.h, s.t + 0.7);
|
||||
F.base.material.emissive.setRGB(on ? 1 : warn ? 0.35 : 0, on ? 0.3 : warn ? 0.08 : 0, 0);
|
||||
for (const c of F.cones) { c.visible = on; if (on) { const f = 0.7 + Math.random() * 0.6; c.scale.set(f, 0.7 + Math.random() * 0.7, f); c.position.y = c.scale.y * 0.6; } }
|
||||
if (on && Math.random() < 0.5) fire.spawn(F.h.x + (Math.random() - 0.5) * F.h.hw * 2, 0.2, F.h.z + (Math.random() - 0.5) * F.h.hd * 2, 0, 3, 0, 0.5, 1, 0.5, 0.12);
|
||||
}
|
||||
// press
|
||||
const p = s.press, ph = arena.press;
|
||||
ph.position.set(A.press.x + (p.st === 'warn' ? (Math.random() - 0.5) * 0.04 : 0), 0.25 + p.y * 2.65, A.press.z);
|
||||
arena.pressLamp.material.emissiveIntensity = p.st === 'warn' || p.st === 'slam' ? (Math.sin(now / 60) > 0 ? 3 : 0.3) : 0.15;
|
||||
// crane
|
||||
const c = s.crane, C = arena.crane;
|
||||
const dx = c.x - C.px, dz = c.z - C.pz, len = Math.hypot(dx, dz);
|
||||
C.boom.scale.x = len + 0.4; C.boom.position.set(C.px + dx / 2, 4.4, C.pz + dz / 2); C.boom.rotation.y = -Math.atan2(dz, dx);
|
||||
let my = 2.6;
|
||||
if (c.who >= 0) { const r = s.robots[c.who]; my = r.y + robots[c.who].top + 0.12; }
|
||||
C.mag.position.set(c.x, my, c.z);
|
||||
const cl = 4.3 - my; C.cable.scale.y = Math.max(0.05, cl); C.cable.position.set(c.x, my + cl / 2, c.z);
|
||||
// pit
|
||||
const o = s.pitOpen;
|
||||
for (const d of arena.pitDoors) { d.position.x = A.pit.x + d.userData.sx * (A.pit.hw / 2 + o * A.pit.hw * 1.02); d.position.y = 0.025 + o * 0.01; }
|
||||
for (const l of arena.pitLamps) l.material.emissiveIntensity = s.pitAlarm ? (Math.sin(now / 150) > 0 ? 2.5 : 0.4) : 0;
|
||||
// rockets
|
||||
while (arena.rocketMeshes.length < s.rockets.length) { const m = new T.Mesh(arena.rocketGeo, arena.rocketMat); arenaScene.add(m); arena.rocketMeshes.push(m); }
|
||||
arena.rocketMeshes.forEach((m, i) => {
|
||||
const k = s.rockets[i];
|
||||
m.visible = !!k;
|
||||
if (k) {
|
||||
m.position.set(k.x, k.y, k.z); m.rotation.y = -k.a;
|
||||
fire.spawn(k.x - Math.cos(k.a) * 0.2, k.y, k.z - Math.sin(k.a) * 0.2, 0, 0.2, 0, 0.3, 1, 0.6, 0.2);
|
||||
if (Math.random() < 0.5) smoke.spawn(k.x, k.y, k.z, 0, 0.2, 0, 0.8, 0.5, 0.5, 0.5);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
api.resize(1);
|
||||
return api;
|
||||
};
|
||||
})(window);
|
||||
58
game/robot.js
Normal file
58
game/robot.js
Normal file
@@ -0,0 +1,58 @@
|
||||
/* Robot Clash - workshop rules and robot stats from parts (no DOM). Needs parts.js.
|
||||
|
||||
RC.validate(build) -> { ok, errors: ['need_chassis' | 'overweight' | 'no_power' ...], weight, power, supply }
|
||||
RC.stats(build) -> combat stats { hp, reduce, mass, accel, top, turn, grip, push, len, wid, h, rad,
|
||||
weapon, tower, invertible, lowProfile, frontArmour, value }
|
||||
build = { chassis: id, motor: id, wheels: id, battery: id, armour: id|null, weapon: id|null, tower: id|null } */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {}));
|
||||
|
||||
const part = (b, slot) => (b && b[slot] ? RC.PARTS[b[slot]] || null : null);
|
||||
|
||||
RC.HP_SCALE = 3; // catalogue hp x this = hit points in the arena
|
||||
|
||||
RC.validate = build => {
|
||||
const errors = [];
|
||||
let weight = 0, power = 0, supply = 0;
|
||||
for (const slot of RC.SLOTS) {
|
||||
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 += p.weight;
|
||||
if (slot === 'battery') supply += p.power; else power += p.power || 0;
|
||||
}
|
||||
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 };
|
||||
};
|
||||
|
||||
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');
|
||||
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; }
|
||||
const len = ch ? ch.len : 1.3, wid = ch ? ch.wid : 1.0;
|
||||
return {
|
||||
hp: ((ch ? ch.hp : 80) + (ar ? ar.hp : 0)) * RC.HP_SCALE,
|
||||
reduce: ar ? ar.reduce : 0,
|
||||
mass,
|
||||
accel: (mo ? mo.force : 500) / mass * (wh ? Math.min(1.2, wh.grip / 8) : 1),
|
||||
top: (mo ? mo.speed : 3.5) * (wh ? wh.speedMul : 1) * (1.12 - mass / 900),
|
||||
turn: (wh ? wh.turn : 2.5) * (1.15 - mass / 650),
|
||||
grip: wh ? wh.grip : 6,
|
||||
push: wh ? wh.push : 1,
|
||||
len, wid, h: ch ? ch.h : 0.42,
|
||||
rad: Math.hypot(len, wid) / 2 * 0.82,
|
||||
weapon: we, tower: to,
|
||||
invertible: !!(wh && wh.invertible),
|
||||
lowProfile: !!(ch && ch.lowProfile),
|
||||
frontArmour: ch && ch.frontArmour ? ch.frontArmour : 0,
|
||||
value,
|
||||
};
|
||||
};
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
6
game/vendor/three.min.js
vendored
Normal file
6
game/vendor/three.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user