feat(net): shared wire protocol with seat mapping (P1-1)

This commit is contained in:
Benjamin Oezcan
2026-11-19 01:45:26 +01:00
parent 4a14b1de76
commit bbe206004a
2 changed files with 200 additions and 0 deletions

111
game/protocol.js Normal file
View File

@@ -0,0 +1,111 @@
/* Robot Clash - wire protocol shared by client (classic script) and server (require). No DOM.
One WebSocket per player, JSON messages { t: '<type>', ... }.
RC.Proto.VERSION bump on every incompatible change (server rejects older clients)
RC.Proto.check(msg) -> { ok, error } validates a client->server message (type, ranges, sizes)
RC.Proto.input(raw) -> clean input { throttle, turn, fire, fire2, fire3 } (clamped)
RC.Proto.packSnap(s, tick, ack) -> compact snapshot of a fight state (server side, seat order)
RC.Proto.toLocal(seat, snap) -> copy of the snapshot as seen by `seat`: own robot at index 0,
every robot index inside (events, grabs, crane, owners, winner) mirrored.
THE ONLY PLACE where seat <-> local index mapping happens.
RC.Proto.localResult(seat, result) -> result with the winner as a local index (0 = me) */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const VERSION = 1;
const MAX_MSG = 8 * 1024; // bytes per client message
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const isStr = (v, max = 64) => typeof v === 'string' && v.length > 0 && v.length <= max;
const isNum = v => typeof v === 'number' && Number.isFinite(v);
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
// client -> server message schemas: field -> check
const C2S = {
hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) },
ping: { t: v => v === undefined || isNum(v) },
room: { room: v => FLAGS.includes(v) || v === 'all' },
challenge: { to: v => isStr(v) },
'challenge.cancel': {},
'challenge.accept': { from: v => isStr(v) },
'challenge.decline': { from: v => isStr(v) },
input: {
seq: v => Number.isInteger(v) && v >= 0,
throttle: isNum, turn: isNum,
fire: v => typeof v === 'boolean', fire2: v => typeof v === 'boolean', fire3: v => typeof v === 'boolean',
},
'match.leave': {},
};
function check(msg) {
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return { ok: false, error: 'BAD_MESSAGE' };
const schema = C2S[msg.t];
if (!schema) return { ok: false, error: 'UNKNOWN_TYPE' };
for (const k of Object.keys(schema)) if (!schema[k](msg[k])) return { ok: false, error: 'BAD_FIELD:' + k };
return { ok: true };
}
const input = raw => ({
throttle: clamp(isNum(raw && raw.throttle) ? raw.throttle : 0, -1, 1),
turn: clamp(isNum(raw && raw.turn) ? raw.turn : 0, -1, 1),
fire: !!(raw && raw.fire), fire2: !!(raw && raw.fire2), fire3: !!(raw && raw.fire3),
});
// ---- snapshots ---------------------------------------------------------------------------------
// robot fields the view / HUD / sound / result screen read
const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin',
'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'dead', 'out', 'dealt', 'taken', 'onOil'];
const WF = ['cd', 'spin', 'swing', 'grab', 'sawOn', 'fire', 'flipAnim'];
const rnd = v => (typeof v === 'number' ? Math.round(v * 1000) / 1000 : v);
const pick = (o, keys) => { const r = {}; for (const k of keys) if (o[k] !== undefined) r[k] = rnd(o[k]); return r; };
const packRobot = r => Object.assign(pick(r, RF), {
lost: Object.assign({}, r.lost), lostW: (r.lostW || []).slice(), W: (r.W || []).map(w => pick(w, WF)),
});
function packSnap(s, tick, ack) {
return {
tick, ack: ack || [0, 0],
t: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: !!s.pitAlarm, endIn: rnd(s.endIn),
result: s.result ? { winner: s.result.winner, reason: s.result.reason } : null,
press: { st: s.press.st, y: rnd(s.press.y) },
crane: { st: s.crane.st, x: rnd(s.crane.x), z: rnd(s.crane.z), who: s.crane.who },
rockets: s.rockets.map(k => ({ kind: k.kind, owner: k.owner, x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })),
mines: s.mines.map(k => ({ owner: k.owner, x: rnd(k.x), z: rnd(k.z), arm: rnd(k.arm) })),
robots: [packRobot(s.robots[0]), packRobot(s.robots[1])],
ev: s.events.map(e => Object.assign({}, e)),
};
}
// seat index -> local index (0 = me). -1 / null stay as they are.
const mapper = seat => i => (i === 0 || i === 1) ? (seat === 0 ? i : 1 - i) : i;
function toLocal(seat, snap) {
if (!snap) return snap;
const m = mapper(seat);
const robots = (seat === 0 ? snap.robots : [snap.robots[1], snap.robots[0]])
.map(r => Object.assign({}, r, { grabbedBy: r.grabbedBy == null ? r.grabbedBy : m(r.grabbedBy) }));
return Object.assign({}, snap, {
robots,
ack: snap.ack ? snap.ack[seat] : 0,
result: localResult(seat, snap.result),
crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }),
rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })),
mines: snap.mines.map(k => Object.assign({}, k, { owner: m(k.owner) })),
ev: (snap.ev || []).map(e => {
const c = Object.assign({}, e);
if ('who' in c) c.who = m(c.who);
if ('winner' in c) c.winner = m(c.winner);
return c;
}),
});
}
function localResult(seat, result) {
if (!result) return result;
return Object.assign({}, result, { winner: mapper(seat)(result.winner) });
}
RC.Proto = { VERSION, MAX_MSG, FLAGS, check, input, packSnap, toLocal, localResult, RF };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

89
tests/protocol.test.js Normal file
View File

@@ -0,0 +1,89 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('path');
for (const f of ['parts.js', 'robot.js', 'combat.js', 'ai.js', 'protocol.js']) require(path.join(__dirname, '..', 'game', f));
const RC = globalThis.RC;
const P = RC.Proto;
test('check accepts valid client messages', () => {
assert.ok(P.check({ t: 'hello', v: 1, token: 'abc' }).ok);
assert.ok(P.check({ t: 'challenge', to: 'u1' }).ok);
assert.ok(P.check({ t: 'challenge.cancel' }).ok);
assert.ok(P.check({ t: 'room', room: 'DE' }).ok);
assert.ok(P.check({ t: 'input', seq: 3, throttle: 1, turn: -0.5, fire: true, fire2: false, fire3: false }).ok);
});
test('check rejects bad messages', () => {
assert.equal(P.check(null).ok, false);
assert.equal(P.check([]).ok, false);
assert.equal(P.check({ t: 'nope' }).error, 'UNKNOWN_TYPE');
assert.equal(P.check({ t: 'hello', v: '1', token: 'x' }).error, 'BAD_FIELD:v');
assert.equal(P.check({ t: 'hello', v: 1, token: '' }).error, 'BAD_FIELD:token');
assert.equal(P.check({ t: 'challenge', to: 'x'.repeat(65) }).error, 'BAD_FIELD:to');
assert.equal(P.check({ t: 'room', room: 'ZZ' }).error, 'BAD_FIELD:room');
assert.equal(P.check({ t: 'input', seq: -1, throttle: 0, turn: 0, fire: false, fire2: false, fire3: false }).error, 'BAD_FIELD:seq');
assert.equal(P.check({ t: 'input', seq: 1, throttle: NaN, turn: 0, fire: false, fire2: false, fire3: false }).error, 'BAD_FIELD:throttle');
assert.equal(P.check({ t: 'input', seq: 1, throttle: 0, turn: 0, fire: 1, fire2: false, fire3: false }).error, 'BAD_FIELD:fire');
});
test('input clamps ranges and coerces flags', () => {
assert.deepEqual(P.input({ throttle: 5, turn: -9, fire: 1 }), { throttle: 1, turn: -1, fire: true, fire2: false, fire3: false });
assert.deepEqual(P.input(null), { throttle: 0, turn: 0, fire: false, fire2: false, fire3: false });
});
function fakeSnap() {
return {
tick: 10, ack: [4, 7], t: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0,
result: { winner: 0, reason: 'ko' },
press: { st: 'idle', y: 1 }, crane: { st: 'grab', x: 0, z: 0, who: 1 },
rockets: [{ kind: 'rocket', owner: 0, x: 1, z: 2, y: 0.5, a: 0 }],
mines: [{ owner: 1, x: 0, z: 0, arm: 1 }],
robots: [{ x: 1, hp: 50, grabbedBy: null, dealt: 30 }, { x: 2, hp: 0, grabbedBy: 0, dealt: 5 }],
ev: [{ type: 'dmg', who: 1, amount: 3 }, { type: 'end', winner: 0, reason: 'ko' }, { type: 'pit_open' }],
};
}
test('toLocal for seat 0 keeps order and indices', () => {
const l = P.toLocal(0, fakeSnap());
assert.equal(l.robots[0].x, 1);
assert.equal(l.result.winner, 0);
assert.equal(l.ack, 4);
assert.equal(l.crane.who, 1);
assert.equal(l.ev[0].who, 1);
});
test('toLocal for seat 1 mirrors every robot index', () => {
const l = P.toLocal(1, fakeSnap());
assert.equal(l.robots[0].x, 2, 'own robot first');
assert.equal(l.robots[0].dealt, 5);
assert.equal(l.robots[0].grabbedBy, 1, 'grabbed by the other robot = local index 1');
assert.equal(l.robots[1].grabbedBy, null);
assert.equal(l.result.winner, 1, 'seat 0 won -> for seat 1 the winner is the opponent (local 1)');
assert.equal(l.ack, 7);
assert.equal(l.crane.who, 0);
assert.equal(l.rockets[0].owner, 1);
assert.equal(l.mines[0].owner, 0);
assert.equal(l.ev[0].who, 0);
assert.equal(l.ev[1].winner, 1);
assert.ok(!('who' in l.ev[2]));
});
test('draw stays a draw for both seats; mirrored results always disagree on the winner', () => {
assert.equal(P.localResult(0, { winner: -1, reason: 'time' }).winner, -1);
assert.equal(P.localResult(1, { winner: -1, reason: 'time' }).winner, -1);
for (const w of [0, 1]) {
const a = P.localResult(0, { winner: w }).winner, b = P.localResult(1, { winner: w }).winner;
assert.notEqual(a === 0, b === 0, 'exactly one seat sees itself as the winner');
}
});
test('packSnap of a real fight carries what the result screen needs', () => {
const s = RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: 3 });
RC.Combat.step(s, 1 / 60, [P.input({ throttle: 1 }), P.input({})]);
const snap = P.packSnap(s, 1, [0, 0]);
assert.equal(snap.robots.length, 2);
for (const k of ['x', 'z', 'a', 'hp', 'maxHp', 'dealt', 'taken']) assert.equal(typeof snap.robots[0][k], 'number', k);
assert.ok(Array.isArray(snap.robots[0].W));
assert.ok(JSON.stringify(snap).length < 6000, 'snapshot stays small');
});