Compare commits

...

4 Commits

Author SHA1 Message Date
a494290548 fix(net): interpolate between snapshots to absorb jitter (P1-6)
netfight eased to the newest snapshot with no buffer, so a jittery
client's robot stalled then jumped. Render ~120 ms in the past between
the two bracketing snapshots instead. Dev params ?netlag/?interp/
?netprobe reproduce it; unit test for the interp math + a Playwright
lag test (tests/e2e/netlag.spec.js).
2026-11-19 19:46:54 +01:00
Benjamin Oezcan
2bf5a40ebc fix(ui): F3 overlay was always shown as an empty box and could not be closed 2026-11-19 15:28:23 +01:00
Benjamin Oezcan
90f1c9c37e build(deploy): ship tools/ so the test bot can run on the server 2026-11-19 15:14:56 +01:00
Benjamin Oezcan
c99881e63a docs: test bot and F3 network overlay 2026-11-19 14:35:05 +01:00
11 changed files with 215 additions and 41 deletions

View File

@@ -143,6 +143,10 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
`npm --prefix server run db:reset` (DB frisch + Testkonten), `npm run deploy` (= `bash server/deploy/deploy.sh`,
`-- --reset-db` setzt die DB zurück), `npm run smoke -- https://roboclash.michael-media.de` (nach jedem Deploy).
Zwei Spieler lokal: `?online&slot=1` und `?online&slot=2` in zwei Tabs.
`npm run bot -- --url <server> --pattern circle|zigzag|spin|charge|idle [--challenge <name>]` = dummer Testgegner
(nimmt Herausforderungen an, fährt ein Muster, löscht sich bei Strg+C). **F3** im Spiel (oder `?net`) = Netz-Overlay:
Ping-Verlauf, Gegner-Ping (vom Server gemessen), Snapshot-Abstand, Tasten-Verzögerung, Server-Last + Klartext-Urteil
(`game/netstats.js` rechnet, `game/netoverlay.js` zeigt). Bot **auf dem Server** starten = Gegner mit ~0 ms Ping.
`npm run e2e` = Playwright-Browsertests (`tests/e2e/`, nutzt das installierte Chrome, startet eigenen Server auf
:8099 mit frischer DB): zwei Browser spielen online gegeneinander, Shop gegen Server, Kampagne über `file://`.
- Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG),

View File

@@ -27,7 +27,7 @@ Shop-Kauf landet in der Server-DB, Kampagne offline über `file://` (headless +
- Admin-Seite läuft jetzt unter `/admin/` auf dem Server; `admin/cleanup.js`/`setcoins.js` (Firebase) gelöscht.
**Offen / nächste Schritte:** P2-6 (Online-Turnier), P3-1 Rest (SSH-Nutzer `deploy`, Passwort-Login aus), P3-5
(Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-1 voller Bot-Client, P4-3 Lasttest,
(Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-3 Lasttest (Bot ist da: mehrere `npm run bot` parallel),
P4-4 Vorhersage (erst nach Spieltest), `tests/sim.test.js:442` (halber Test).
Hinweis: Der Smoke-Test legt Gastkonten an (`SmokeA`/`SmokeB`), die in der Rangliste auftauchen können →
`--reset-db` beim Deploy räumt auf.
@@ -211,6 +211,15 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
- [x] **P1-6 Client `netfight.js` neu:** Eingaben senden, Snapshots interpolieren, `match.end` anzeigen;
`game.js` nimmt das Ergebnis vom Server statt `s.result` selbst zu werten. *AK:* Zwei Browser-Fenster
(oder Playwright, P4-2) spielen einen Kampf; beide sehen dasselbe Ergebnis aus ihrer Sicht.
- **BEFUND 2026-11-19 (Michi laggt, Benni nicht):** `netfight.js` hat **keinen Jitter-Puffer** umgesetzt – es
zog den lokalen Zustand nur zum *neuesten* Snapshot (`k = dt*14`), nicht wie hier geplant „zwischen den zwei
letzten Snapshots (~100 ms Puffer)" (Zeile 151). Bei ungleichmäßiger Snapshot-Ankunft (Jitter/Bufferbloat,
auch über Kabel) bremst der Roboter und springt dann → F3 meldet `jitter`/`late`. Benni (gleichmäßige Leitung)
merkt nichts. **Fix (P4-x):** echte Entity-Interpolation mit ~100 ms Puffer; Render bei `now - INTERP_DELAY`
zwischen den zwei umgebenden Snapshots. **Reproduzierbar:** Dev-Param `?netlag=<basis>,<jitter>` verzögert
eingehende Snapshots geseedet; Node-Test `tests/netfight.test.js` (reine Interp-Mathe) + Playwright-Test misst
die Positions-Sprünge mit/ohne `netlag`. Erkenntnis für Benni: das Springen war ein Client-Interp-Problem,
kein Server-/Leitungsproblem.
- [x] **P1-7 Disconnect/Reconnect:** Gnadenfrist, KI-Übernahme, Wiederverbinden. *AK:* Test trennt einen Client
mitten im Kampf; Kampf endet trotzdem mit Ergebnis; Reconnect innerhalb 10 s übernimmt wieder.
- [x] **P1-8 Alt-Code entfernen:** `server/rtdb.js`, `server/rules.js`, `/db`-Routen, `game/lobby.js` (alt),
@@ -287,7 +296,7 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
### Phase 4 – Absicherung und Feinschliff
- [ ] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`.
- [x] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`.
Nutzbar für Smoke-Tests und als Gegner auf dem Dev-Server. *AK:* `node tools/bot.js --url … --count 20` spielt 10 Matches parallel.
- [x] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`,
beide sehen spiegelbildliches Ergebnis. Läuft in CI gegen einen lokal gestarteten Server.

View File

@@ -99,6 +99,7 @@
if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35);
const DEV = new URLSearchParams(location.search);
if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop
const netProbe = DEV.has('netprobe') ? (window.__probe = []) : null; // dev: records opponent robot pos for the lag test
const net = RC.Net(NET_CFG);
const rank = RC.Ranking(net); // online ranking, computed by the server
const cloud = RC.CloudSave(net); // campaign copy for registered accounts (online saves live on the server)
@@ -768,7 +769,12 @@
const count = online ? Math.max(0, +online.countdown || 0) : 3.5;
F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count, beat: Math.ceil(count) + 1,
acc: [0, 0], accT: 0, banner: null, ended: false, oppAway: false };
if (online) { netStats.reset(); F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats }); } // the server runs the fight, we show it
if (online) { // the server runs the fight, we show it (interpolated); dev: ?netlag=base,jit[,seed], ?interp=ms
netStats.reset();
let lag = null; const nl = DEV.get('netlag');
if (nl) { const [b, j, sd] = nl.split(',').map(Number); lag = { base: b || 0, jit: j || 0, seed: sd || 1 }; }
F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats, interp: +DEV.get('interp') || 0, lag });
}
// 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')) {
@@ -916,6 +922,7 @@
let events;
if (F.online) {
events = F.nf.frame(s, playerInput(), dt);
if (netProbe) { netProbe.push({ t: performance.now(), x: s.robots[1].x, z: s.robots[1].z }); if (netProbe.length > 2000) netProbe.shift(); }
if (F.nf.oppAway !== F.oppAway) { F.oppAway = F.nf.oppAway; banner(t(F.oppAway ? 'peer_lost' : 'peer_back'), F.oppAway ? '#ff4a3a' : '#6dff9e', 2.2); }
// no word from the server for 20 s (and no result yet - a hidden tab may simply have slept through the end)
if (!F.serverEnd && F.nf.silentFor > 20 && !F.ended) { F.ended = true; onlineFightLost(); return; }

View File

@@ -38,6 +38,7 @@
#netov { position: absolute; left: 8px; bottom: 12px; z-index: 9; width: 316px; padding: 8px; border-radius: 6px;
background: rgba(10,12,16,.86); border: 1px solid var(--line); box-shadow: var(--hl); font: 12px/1.35 Consolas, monospace;
color: var(--text); pointer-events: none; }
#netov.hide { display: none; } /* #netov beats the generic .hide rule - hide it explicitly */
#netov .nvh { font-weight: bold; color: var(--accent); margin-bottom: 4px; }
#netov canvas { display: block; width: 300px; height: 84px; }
#netov .nvleg { display: flex; gap: 8px; flex-wrap: wrap; margin: 3px 0 5px; font-size: 11px; color: var(--dim, #8d95a8); }

View File

@@ -1,26 +1,62 @@
/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat;
this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me").
const nf = RC.NetFight({ net, seat, stats }) stats = RC.NetStats() (optional, F3 overlay)
nf.frame(s, input, dt) send input (on change, max 30/s, at least every 0.25 s), ease the local state toward
the newest snapshot, return the events of snapshots not seen yet
nf.oppAway true while the opponent is disconnected (server tells us)
nf.silentFor seconds since the last snapshot (connection trouble)
nf.stop() */
Entity interpolation: snapshots (20 Hz) are buffered and rendered ~INTERP_DELAY ms in the past, between the two
snapshots bracketing the render time. This absorbs jitter (uneven arrival) so the robot does not jump - the old
"ease to the newest snapshot" had no buffer and jumped whenever a snapshot arrived late.
const nf = RC.NetFight({ net, seat, stats, interp, lag })
interp interpolation delay in ms (default 100); lag = { base, jit, seed } delays incoming snapshots (dev only)
nf.frame(s, input, dt) send input, show the interpolated world, return not-yet-seen events
nf.oppAway / nf.silentFor / nf.stop()
Pure, Node-testable: RC.NetFight.pickFrames(buf, renderTime), RC.NetFight.lerpRobot(da, db, k) */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25;
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25, INTERP_DEFAULT = 120, BUF_MAX = 30;
const EASE = ['x', 'z', 'y'], ANG = ['a', 'turretA'];
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
const mul = s => { let a = (s >>> 0) || 1; return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
// buf = [{ at, tick, snap }] sorted by at/tick ascending. Pick the snapshot reached by renderTime (a) and the
// next one (b), with the fraction between them. Past the newest -> hold the newest (a === b, frac 1).
function pickFrames(buf, renderTime) {
if (!buf.length) return null;
let a = buf[0], b = null;
for (let i = 0; i < buf.length; i++) { if (buf[i].at <= renderTime) a = buf[i]; else { b = buf[i]; break; } }
const span = b ? (b.at - a.at) : 0;
const frac = b && span > 0 ? Math.min(1, Math.max(0, (renderTime - a.at) / span)) : (b ? 0 : 1);
return { a, b: b || a, frac };
}
// blend two robot snapshots: positions/angles interpolate, discrete fields come from the reached snapshot (da)
function lerpRobot(da, db, k) {
const r = {};
for (const f of (RC.Proto ? RC.Proto.RF : Object.keys(da))) if (da[f] !== undefined && !EASE.includes(f) && !ANG.includes(f)) r[f] = da[f];
for (const f of EASE) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + (db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
for (const f of ANG) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + wrap(db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
r.lost = Object.assign({}, da.lost); r.lostW = (da.lostW || []).slice(); r.W = (da.W || []).map(w => Object.assign({}, w));
return r;
}
RC.NetFight = (opt) => {
const sock = opt.net.socket, seat = opt.seat;
let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
const stats = opt.stats || null; // RC.NetStats for the F3 overlay (optional)
const DELAY = opt.interp > 0 ? opt.interp : INTERP_DEFAULT;
const lag = opt.lag && opt.lag.base >= 0 ? opt.lag : null, rng = lag ? mul(lag.seed || 1) : null;
const stats = opt.stats || null;
const buf = []; // in-order snapshot buffer
let newest = null, lastTick = -1, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
function accept(m) { // a snapshot arrived (possibly delayed by the dev lag injector)
const snap = RC.Proto.toLocal(seat, m);
lastSnap = Date.now(); newest = snap;
if (stats) stats.snap(snap, m._bytes, performance.now());
if (m.tick <= lastTick) return; // out of order (rare) -> drop, keep the buffer monotonic
lastTick = m.tick;
buf.push({ at: Date.now(), tick: m.tick, snap });
while (buf.length > BUF_MAX) buf.shift();
}
const off = sock.on('snap', m => {
latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now();
if (stats) stats.snap(latest, m._bytes, performance.now());
if (!lag) return accept(m);
setTimeout(() => accept(m), Math.max(0, lag.base + (rng() * 2 - 1) * lag.jit));
});
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
@@ -31,38 +67,36 @@
if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; if (stats) stats.inputSent(seq, performance.now()); }
}
function applyRobot(r, d, k) {
for (const f of EASE) if (typeof d[f] === 'number') r[f] += (d[f] - r[f]) * k;
for (const f of ANG) if (typeof d[f] === 'number') r[f] += wrap(d[f] - r[f]) * k;
for (const f of RC.Proto.RF) if (!EASE.includes(f) && !ANG.includes(f) && d[f] !== undefined) r[f] = d[f];
if (d.lost) r.lost = Object.assign(r.lost || {}, d.lost);
if (d.lostW) r.lostW = d.lostW.slice();
if (d.W && r.W) d.W.forEach((w, i) => { if (r.W[i]) Object.assign(r.W[i], w); });
}
const applyRobot = (r, d) => { Object.assign(r, d); };
const syncList = (dst, src, def) => { dst.length = src.length; for (let i = 0; i < src.length; i++) dst[i] = Object.assign(dst[i] || Object.assign({}, def), src[i]); };
function frame(s, inp, dt) {
sendInput(inp, dt);
if (!latest) return [];
const n = latest, k = Math.min(1, dt * 14);
s.t = n.time; s.left = n.left; s.pitOpen = n.pitOpen; s.pitAlarm = n.pitAlarm; s.endIn = n.endIn;
s.press.st = n.press.st; s.press.y = n.press.y;
Object.assign(s.crane, n.crane);
syncList(s.rockets, n.rockets, { sp: 6, t: 3 });
syncList(s.mines, n.mines, { r: 0.85 });
applyRobot(s.robots[0], n.robots[0], k);
applyRobot(s.robots[1], n.robots[1], k);
if (n.result) s.result = n.result;
if (n.tick === seenTick) return [];
seenTick = n.tick;
return n.ev || [];
if (!buf.length) return [];
const renderTime = Date.now() - DELAY;
const fr = pickFrames(buf, renderTime), na = fr.a.snap, nb = fr.b.snap, k = fr.frac;
s.t = na.time; s.left = na.left; s.pitOpen = na.pitOpen; s.pitAlarm = na.pitAlarm; s.endIn = na.endIn;
s.press.st = na.press.st; s.press.y = na.press.y;
Object.assign(s.crane, na.crane);
syncList(s.rockets, na.rockets, { sp: 6, t: 3 });
syncList(s.mines, na.mines, { r: 0.85 });
applyRobot(s.robots[0], lerpRobot(na.robots[0], nb.robots[0], k));
applyRobot(s.robots[1], lerpRobot(na.robots[1], nb.robots[1], k));
if (na.result) s.result = na.result;
while (buf.length > 2 && buf[1].at <= renderTime) buf.shift(); // keep one snapshot older than renderTime
if (fr.a.tick === seenTick) return [];
seenTick = fr.a.tick;
return na.ev || [];
}
return {
frame,
get oppAway() { return !!(latest && latest.away && latest.away[1]); },
get oppAway() { return !!(newest && newest.away && newest.away[1]); },
get silentFor() { return (Date.now() - lastSnap) / 1000; },
stop() { off(); },
};
};
RC.NetFight.pickFrames = pickFrames;
RC.NetFight.lerpRobot = lerpRobot;
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -8,7 +8,7 @@ leitet an den Node-Dienst weiter, WebSocket `/ws` inklusive). Alle Befehle aus d
```
/opt/robotclash/
releases/<zeit>-<commit>/ je Deploy ein vollständiges Release (game/, server/, admin/), die letzten 5 bleiben
releases/<zeit>-<commit>/ je Deploy ein vollständiges Release (game/, server/, admin/, tools/), die letzten 5 bleiben
current -> releases/... aktives Release (Symlink)
shared/.env PORT, JWT_SECRET, DB_FILE (bleibt über Deploys erhalten, nur root/Dienst lesbar)
shared/data.sqlite Datenbank
@@ -54,3 +54,12 @@ curl -s https://roboclash.michael-media.de/healthz
Eigener SSH-Nutzer `deploy` statt root (P3-1), Deploy aus Gitea Actions bei Push auf `main` (P3-6), Produktion als
zweite Umgebung erst nach T-4.
## Test-Bot auf dem Server (Gegner mit ~0 ms Ping)
```bash
ssh root@roboclash.michael-media.de "cd /opt/robotclash/current && node tools/bot.js --url http://127.0.0.1:8080 --pattern circle"
```
Dann im Browser herausfordern, F3 drücken. Ruckelt es trotzdem, liegt es an deiner Leitung oder am Server – nicht am
Gegner. Strg+C beendet den Bot und löscht sein Gastkonto.

View File

@@ -19,13 +19,13 @@ while [ $# -gt 0 ]; do
done
cd "$(git rev-parse --show-toplevel)"
git diff --quiet HEAD -- game server admin || echo "!! uncommitted changes in game/server/admin are NOT deployed (only $REF)"
git diff --quiet HEAD -- game server admin tools || echo "!! uncommitted changes in game/server/admin are NOT deployed (only $REF)"
SHA=$(git rev-parse --short "$REF")
REL="$(date -u +%Y%m%d-%H%M%S)-$SHA"
TAR="$(mktemp -t rc-XXXXXX).tgz"
trap 'rm -f "$TAR"' EXIT
echo ">> release $REL -> $HOST"
git archive --format=tar.gz -o "$TAR" "$REF" game server admin
git archive --format=tar.gz -o "$TAR" "$REF" game server admin tools
scp -q "$TAR" "$HOST:/tmp/rc-$REL.tgz"
tr -d '\r' < server/deploy/remote-release.sh | ssh "$HOST" bash -s -- "$REL" "$SHA" "$RESET"

View File

@@ -5,8 +5,8 @@ const { expect } = require('@playwright/test');
const mode = page => page.locator('body').getAttribute('data-mode');
// open the game in online mode and log in with name + password through the login card
async function login(page, name, pass) {
await page.goto('/?online');
async function login(page, name, pass, query = '') {
await page.goto('/?online' + query);
await page.locator('#oLogin').fill(name);
await page.locator('#oPass').fill(pass);
await page.locator('#oGo').click();

48
tests/e2e/netlag.spec.js Normal file
View File

@@ -0,0 +1,48 @@
// Repeatable lag test: one client gets a seeded snapshot delay+jitter (?netlag). The opponent robot must still
// move SMOOTHLY on that client (entity interpolation), i.e. no large per-step jumps - the bug Michi reported.
'use strict';
const { test, expect } = require('@playwright/test');
const { login, toLobby } = require('./helpers');
test('a jittery client still sees the opponent move smoothly (interpolation buffer)', async ({ browser }) => {
const ctxA = await browser.newContext(), ctxB = await browser.newContext();
const a = await ctxA.newPage(), b = await ctxB.newPage();
const errors = [];
for (const p of [a, b]) p.on('pageerror', e => errors.push(e.message));
// michi gets a repeatable snapshot delay + jitter (80 ms +/- 40 ms, seeded) + the position probe
await login(a, 'michi', 'Michi2000!', '&netlag=80,40,7&netprobe');
await login(b, 'benni', 'Benni2000!');
await toLobby(a); await toLobby(b);
await a.locator('.prow', { hasText: 'benni' }).locator('.chal').click();
await expect(b.locator('#cYes')).toBeVisible();
await b.locator('#cYes').click();
await expect(a.locator('body')).toHaveAttribute('data-mode', 'fight');
await expect(b.locator('body')).toHaveAttribute('data-mode', 'fight');
await a.waitForTimeout(4200); // countdown
await a.evaluate(() => { globalThis.__probe.length = 0; });
await b.keyboard.down('w'); // benni drives so his robot moves across michi's screen
await a.keyboard.down('a'); // michi turns a bit (keeps both sides active)
await a.waitForTimeout(2600);
await b.keyboard.up('w'); await a.keyboard.up('a');
const probe = await a.evaluate(() => globalThis.__probe.slice());
// consider only samples while the opponent was actually moving
const deltas = [];
let moved = 0;
for (let i = 1; i < probe.length; i++) {
const dx = probe[i].x - probe[i - 1].x, dz = probe[i].z - probe[i - 1].z;
const d = Math.hypot(dx, dz);
deltas.push(d); moved += d;
}
expect(probe.length, 'probe collected samples').toBeGreaterThan(30);
expect(moved, 'the opponent actually moved (test is meaningful)').toBeGreaterThan(0.8);
const maxJump = Math.max(...deltas);
// at ~5 m/s over a 60 Hz step a smooth move is ~0.08/step; a snapshot-jump would be several times that.
expect(maxJump, 'no large per-step jump despite jitter (smooth interpolation)').toBeLessThan(0.35);
expect(errors, 'no JavaScript errors').toEqual([]);
await ctxA.close(); await ctxB.close();
});

View File

@@ -88,3 +88,16 @@ test('shop purchase is checked and stored by the server', async ({ browser }) =>
expect((await cheat.json()).money).toBe(after);
await ctx.close();
});
test('F3 network overlay: hidden at start, F3 shows it with content, F3 hides it again', async ({ page }) => {
await login(page, 'benni', 'Benni2000!');
const ov = page.locator('#netov');
await expect(ov).toBeHidden(); // regression: an empty box was always on screen
await page.keyboard.press('F3');
await expect(ov).toBeVisible();
await expect(ov).toContainText(/ping/i);
await page.keyboard.press('F3');
await expect(ov).toBeHidden(); // regression: it could not be closed again
await page.keyboard.press('F3');
await expect(ov).toBeVisible();
});

49
tests/netfight.test.js Normal file
View File

@@ -0,0 +1,49 @@
'use strict';
// Entity-interpolation math for the live fight (the jitter buffer that stops the robot from jumping).
const { test } = require('node:test');
const assert = require('node:assert');
const path = require('path');
require(path.join(__dirname, '..', 'game', 'protocol.js'));
require(path.join(__dirname, '..', 'game', 'netfight.js'));
const RC = globalThis.RC;
const { pickFrames, lerpRobot } = RC.NetFight;
test('pickFrames: brackets the render time and gives the fraction between the two snapshots', () => {
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
const fr = pickFrames(buf, 50);
assert.strictEqual(fr.a.tick, 1);
assert.strictEqual(fr.b.tick, 2);
assert.ok(Math.abs(fr.frac - 0.5) < 1e-9);
});
test('pickFrames: past the newest snapshot holds it (no extrapolation jump)', () => {
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
const fr = pickFrames(buf, 500);
assert.strictEqual(fr.a.tick, 2);
assert.strictEqual(fr.b.tick, 2);
assert.strictEqual(fr.frac, 1);
});
test('pickFrames: empty buffer -> null', () => {
assert.strictEqual(pickFrames([], 0), null);
});
test('lerpRobot: positions interpolate linearly', () => {
const r = lerpRobot({ x: 0, z: 0, y: 0, hp: 100 }, { x: 10, z: -4, y: 2, hp: 50 }, 0.5);
assert.ok(Math.abs(r.x - 5) < 1e-9);
assert.ok(Math.abs(r.z + 2) < 1e-9);
assert.ok(Math.abs(r.y - 1) < 1e-9);
});
test('lerpRobot: angles take the shortest path across the +/-PI seam', () => {
const r = lerpRobot({ a: 3.0 }, { a: -3.0 }, 0.5);
// short way is +0.28 rad across PI, not -6 rad the long way
assert.ok(r.a > 3.0 || r.a < -3.0, 'wrapped past PI, not back toward 0');
assert.ok(Math.abs(Math.abs(r.a) - Math.PI) < 0.2, 'lands near the seam');
});
test('lerpRobot: discrete fields come from the reached (older) snapshot, not the newer one', () => {
const r = lerpRobot({ x: 0, hp: 100, dead: false }, { x: 10, hp: 0, dead: true }, 0.5);
assert.strictEqual(r.hp, 100);
assert.strictEqual(r.dead, false);
});