Compare commits
3 Commits
3dc770e34a
...
695cf77afc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
695cf77afc | ||
|
|
a8d6158384 | ||
|
|
593d69714b |
@@ -122,6 +122,10 @@
|
|||||||
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
|
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
|
||||||
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
|
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
|
||||||
const lobby = net.enabled ? RC.Lobby({ net }) : null;
|
const lobby = net.enabled ? RC.Lobby({ net }) : null;
|
||||||
|
// F3 (or ?net): network overlay - ping graph + where lag comes from (netstats.js / netoverlay.js)
|
||||||
|
const netStats = RC.NetStats();
|
||||||
|
const netOverlay = net.enabled ? RC.NetOverlay({ stats: netStats, net, t, mount: $('stage') }) : null;
|
||||||
|
if (netOverlay && DEV.has('net')) netOverlay.toggle(true);
|
||||||
const fx = Kit.fx();
|
const fx = Kit.fx();
|
||||||
|
|
||||||
const input = Kit.input({
|
const input = Kit.input({
|
||||||
@@ -764,7 +768,7 @@
|
|||||||
const count = online ? Math.max(0, +online.countdown || 0) : 3.5;
|
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,
|
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 };
|
acc: [0, 0], accT: 0, banner: null, ended: false, oppAway: false };
|
||||||
if (online) F.nf = RC.NetFight({ net, seat: online.seat }); // the server runs the fight, we show it
|
if (online) { netStats.reset(); F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats }); } // the server runs the fight, we show it
|
||||||
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
|
// 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('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
|
||||||
if (DEV.has('ff')) {
|
if (DEV.has('ff')) {
|
||||||
|
|||||||
@@ -34,6 +34,17 @@
|
|||||||
/* fixed design size, scaled to the window by Kit.fit */
|
/* fixed design size, scaled to the window by Kit.fit */
|
||||||
#app { position: relative; width: 1280px; display: flex; flex-direction: column; }
|
#app { position: relative; width: 1280px; display: flex; flex-direction: column; }
|
||||||
/* HUD lives INSIDE the stage (full-screen game look), above the overlay so menus keep it reachable */
|
/* HUD lives INSIDE the stage (full-screen game look), above the overlay so menus keep it reachable */
|
||||||
|
/* network overlay (F3) */
|
||||||
|
#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 .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); }
|
||||||
|
#netov .nvleg i { display: inline-block; width: 10px; height: 3px; margin-right: 3px; vertical-align: middle; }
|
||||||
|
#netov .nvrows { display: grid; grid-template-columns: auto 1fr; gap: 1px 10px; }
|
||||||
|
#netov .nvrows b { text-align: right; font-weight: normal; }
|
||||||
|
#netov .nvv { margin-top: 5px; border-top: 1px solid var(--line); padding-top: 4px; }
|
||||||
#hud { position: absolute; left: 0; right: 0; top: 0; z-index: 7; display: flex; gap: 8px; align-items: center;
|
#hud { position: absolute; left: 0; right: 0; top: 0; z-index: 7; display: flex; gap: 8px; align-items: center;
|
||||||
height: 44px; padding: 0 12px; pointer-events: none;
|
height: 44px; padding: 0 12px; pointer-events: none;
|
||||||
background: linear-gradient(rgba(6,8,12,.9) 35%, rgba(6,8,12,0)); }
|
background: linear-gradient(rgba(6,8,12,.9) 35%, rgba(6,8,12,0)); }
|
||||||
@@ -830,6 +841,8 @@
|
|||||||
<script src="looks.js"></script>
|
<script src="looks.js"></script>
|
||||||
<script src="render3d.js"></script>
|
<script src="render3d.js"></script>
|
||||||
<script src="netfight.js"></script>
|
<script src="netfight.js"></script>
|
||||||
|
<script src="netstats.js"></script>
|
||||||
|
<script src="netoverlay.js"></script>
|
||||||
<script src="shop.js"></script>
|
<script src="shop.js"></script>
|
||||||
<script src="painter.js"></script>
|
<script src="painter.js"></script>
|
||||||
<script src="uicheck.js"></script>
|
<script src="uicheck.js"></script>
|
||||||
|
|||||||
18
game/lang.js
18
game/lang.js
@@ -243,6 +243,15 @@ window.LANG = {
|
|||||||
e_MISSING_PASSWORD: 'Please enter a password.', e_OPERATION_NOT_ALLOWED: 'Guest login is off - use e-mail.',
|
e_MISSING_PASSWORD: 'Please enter a password.', e_OPERATION_NOT_ALLOWED: 'Guest login is off - use e-mail.',
|
||||||
e_OFFLINE: 'Online is not set up yet.', e_ERROR: 'Something went wrong. Try again.',
|
e_OFFLINE: 'Online is not set up yet.', e_ERROR: 'Something went wrong. Try again.',
|
||||||
f_login: 'Name or e-mail', f_email_opt: 'E-mail (optional)',
|
f_login: 'Name or e-mail', f_email_opt: 'E-mail (optional)',
|
||||||
|
net_title: 'Network (F3 hides)', net_ping: 'Your ping', net_ping_srv: 'Server measures you', net_ping_opp: 'Opponent ping',
|
||||||
|
net_snaps: 'Snapshots', net_late: 'late', net_input: 'Key to server', net_server: 'Server step',
|
||||||
|
net_l_ping: 'your ping', net_l_opp: 'opponent', net_l_gap: 'snapshot gap', net_l_input: 'key delay',
|
||||||
|
nv_ok: 'Connection looks fine', nv_nofight: 'Not in a fight - only your ping is measured',
|
||||||
|
nv_me_slow: 'Your ping is high ({n} ms) - your connection or the route to the server',
|
||||||
|
nv_me_jitter: 'Your connection is unsteady (snapshots arrive irregularly, ±{n} ms)',
|
||||||
|
nv_opp_slow: 'Opponent has a high ping ({n} ms) - their connection',
|
||||||
|
nv_server: 'Server is slow ({n} ms per step)', nv_queue: 'Keys take {n} ms - data piles up on the way',
|
||||||
|
nv_lost: 'No snapshots for {n} s',
|
||||||
e_INVALID_LOGIN: 'Wrong name or password.', e_NAME_EXISTS: 'That name is already taken.', e_BAD_NAME: 'The name needs at least 3 letters or digits.',
|
e_INVALID_LOGIN: 'Wrong name or password.', e_NAME_EXISTS: 'That name is already taken.', e_BAD_NAME: 'The name needs at least 3 letters or digits.',
|
||||||
e_RATE_LIMIT: 'Too many tries - please wait a minute.', e_INVALID_ROBOT: 'Your robot is not ready to fight - check weight and power in the workshop.',
|
e_RATE_LIMIT: 'Too many tries - please wait a minute.', e_INVALID_ROBOT: 'Your robot is not ready to fight - check weight and power in the workshop.',
|
||||||
e_OPPONENT_INVALID: 'The other robot is not ready to fight.', e_BUSY: 'That player is busy right now.', e_NOT_AVAILABLE: 'That player is not available.',
|
e_OPPONENT_INVALID: 'The other robot is not ready to fight.', e_BUSY: 'That player is busy right now.', e_NOT_AVAILABLE: 'That player is not available.',
|
||||||
@@ -523,6 +532,15 @@ window.LANG = {
|
|||||||
e_MISSING_PASSWORD: 'Bitte ein Passwort eingeben.', e_OPERATION_NOT_ALLOWED: 'Gast-Login ist aus - nimm E-Mail.',
|
e_MISSING_PASSWORD: 'Bitte ein Passwort eingeben.', e_OPERATION_NOT_ALLOWED: 'Gast-Login ist aus - nimm E-Mail.',
|
||||||
e_OFFLINE: 'Online ist noch nicht eingerichtet.', e_ERROR: 'Etwas ist schiefgelaufen. Nochmal versuchen.',
|
e_OFFLINE: 'Online ist noch nicht eingerichtet.', e_ERROR: 'Etwas ist schiefgelaufen. Nochmal versuchen.',
|
||||||
f_login: 'Name oder E-Mail', f_email_opt: 'E-Mail (optional)',
|
f_login: 'Name oder E-Mail', f_email_opt: 'E-Mail (optional)',
|
||||||
|
net_title: 'Netzwerk (F3 blendet aus)', net_ping: 'Dein Ping', net_ping_srv: 'Server misst dich', net_ping_opp: 'Gegner-Ping',
|
||||||
|
net_snaps: 'Snapshots', net_late: 'zu spät', net_input: 'Taste bis Server', net_server: 'Server-Schritt',
|
||||||
|
net_l_ping: 'dein Ping', net_l_opp: 'Gegner', net_l_gap: 'Snapshot-Abstand', net_l_input: 'Tasten-Verzögerung',
|
||||||
|
nv_ok: 'Verbindung sieht gut aus', nv_nofight: 'Kein Kampf - nur dein Ping wird gemessen',
|
||||||
|
nv_me_slow: 'Dein Ping ist hoch ({n} ms) - deine Leitung oder der Weg zum Server',
|
||||||
|
nv_me_jitter: 'Deine Verbindung schwankt (Snapshots kommen unregelmäßig, ±{n} ms)',
|
||||||
|
nv_opp_slow: 'Der Gegner hat hohen Ping ({n} ms) - seine Leitung',
|
||||||
|
nv_server: 'Server ist langsam ({n} ms pro Schritt)', nv_queue: 'Tasten brauchen {n} ms - unterwegs staut es sich',
|
||||||
|
nv_lost: 'Seit {n} s keine Snapshots',
|
||||||
e_INVALID_LOGIN: 'Name oder Passwort falsch.', e_NAME_EXISTS: 'Dieser Name ist schon vergeben.', e_BAD_NAME: 'Der Name braucht mindestens 3 Buchstaben oder Ziffern.',
|
e_INVALID_LOGIN: 'Name oder Passwort falsch.', e_NAME_EXISTS: 'Dieser Name ist schon vergeben.', e_BAD_NAME: 'Der Name braucht mindestens 3 Buchstaben oder Ziffern.',
|
||||||
e_RATE_LIMIT: 'Zu viele Versuche - bitte eine Minute warten.', e_INVALID_ROBOT: 'Dein Roboter ist nicht kampfbereit - prüfe Gewicht und Strom in der Werkstatt.',
|
e_RATE_LIMIT: 'Zu viele Versuche - bitte eine Minute warten.', e_INVALID_ROBOT: 'Dein Roboter ist nicht kampfbereit - prüfe Gewicht und Strom in der Werkstatt.',
|
||||||
e_OPPONENT_INVALID: 'Der andere Roboter ist nicht kampfbereit.', e_BUSY: 'Dieser Spieler ist gerade beschäftigt.', e_NOT_AVAILABLE: 'Dieser Spieler ist nicht verfügbar.',
|
e_OPPONENT_INVALID: 'Der andere Roboter ist nicht kampfbereit.', e_BUSY: 'Dieser Spieler ist gerade beschäftigt.', e_NOT_AVAILABLE: 'Dieser Spieler ist nicht verfügbar.',
|
||||||
|
|||||||
@@ -129,6 +129,7 @@
|
|||||||
s.onopen = () => s.send(JSON.stringify({ t: 'hello', v: RC.Proto.VERSION, token: t }));
|
s.onopen = () => s.send(JSON.stringify({ t: 'hello', v: RC.Proto.VERSION, token: t }));
|
||||||
s.onmessage = ev => {
|
s.onmessage = ev => {
|
||||||
let msg; try { msg = JSON.parse(ev.data); } catch (e) { return; }
|
let msg; try { msg = JSON.parse(ev.data); } catch (e) { return; }
|
||||||
|
msg._bytes = ev.data.length; // for the network overlay (bandwidth)
|
||||||
if (msg.t === 'welcome') { isOpen = true; backoff = 1000; emit('open', msg); }
|
if (msg.t === 'welcome') { isOpen = true; backoff = 1000; emit('open', msg); }
|
||||||
if (msg.t === 'error' && (msg.code === 'OUTDATED' || msg.code === 'REPLACED')) { want = false; emit(msg.code === 'OUTDATED' ? 'outdated' : 'replaced', msg); }
|
if (msg.t === 'error' && (msg.code === 'OUTDATED' || msg.code === 'REPLACED')) { want = false; emit(msg.code === 'OUTDATED' ? 'outdated' : 'replaced', msg); }
|
||||||
if (msg.t === 'error' && msg.code === 'UNAUTH' && session) session.exp = 0; // refresh before the retry
|
if (msg.t === 'error' && msg.code === 'UNAUTH' && session) session.exp = 0; // refresh before the retry
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat;
|
/* 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").
|
this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me").
|
||||||
|
|
||||||
const nf = RC.NetFight({ net, seat })
|
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
|
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
|
the newest snapshot, return the events of snapshots not seen yet
|
||||||
nf.oppAway true while the opponent is disconnected (server tells us)
|
nf.oppAway true while the opponent is disconnected (server tells us)
|
||||||
@@ -17,14 +17,18 @@
|
|||||||
RC.NetFight = (opt) => {
|
RC.NetFight = (opt) => {
|
||||||
const sock = opt.net.socket, seat = opt.seat;
|
const sock = opt.net.socket, seat = opt.seat;
|
||||||
let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
|
let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
|
||||||
const off = sock.on('snap', m => { latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now(); });
|
const stats = opt.stats || null; // RC.NetStats for the F3 overlay (optional)
|
||||||
|
const off = sock.on('snap', m => {
|
||||||
|
latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now();
|
||||||
|
if (stats) stats.snap(latest, m._bytes, performance.now());
|
||||||
|
});
|
||||||
|
|
||||||
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
|
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
|
||||||
function sendInput(inp, dt) {
|
function sendInput(inp, dt) {
|
||||||
sendT -= dt; keepT -= dt;
|
sendT -= dt; keepT -= dt;
|
||||||
if (sendT > 0 || (!changed(inp) && keepT > 0)) return;
|
if (sendT > 0 || (!changed(inp) && keepT > 0)) return;
|
||||||
const i = RC.Proto.input(inp);
|
const i = RC.Proto.input(inp);
|
||||||
if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; }
|
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) {
|
function applyRobot(r, d, k) {
|
||||||
|
|||||||
73
game/netoverlay.js
Normal file
73
game/netoverlay.js
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
/* Robot Clash - network overlay (F3 or ?net): ping graph of the last 10 s and a plain-language reading of
|
||||||
|
where lag comes from (your line, the opponent's line, the server). Measurements: netstats.js.
|
||||||
|
|
||||||
|
const ov = RC.NetOverlay({ stats, net, t, mount }) mount = #stage; pings the server once a second
|
||||||
|
ov.toggle() / ov.visible */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
const SECS = 10, MAX_MS = 300, W = 300, H = 84;
|
||||||
|
const COL = { ping: '#ff7a1a', opp: '#4aa8ff', gap: '#6dff9e', input: '#e8ebf2' };
|
||||||
|
const LEVEL = { ok: '#6dff9e', warn: '#ffc940', bad: '#ff5a4a' };
|
||||||
|
|
||||||
|
RC.NetOverlay = function (opt) {
|
||||||
|
const { stats, net, t } = opt;
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.id = 'netov';
|
||||||
|
el.className = 'hide';
|
||||||
|
el.innerHTML = `<div class="nvh"></div><canvas width="${W}" height="${H}"></canvas><div class="nvleg"></div><div class="nvrows"></div><div class="nvv"></div>`;
|
||||||
|
opt.mount.appendChild(el);
|
||||||
|
const cv = el.querySelector('canvas'), cx = cv.getContext('2d');
|
||||||
|
let visible = false, drawT = null;
|
||||||
|
|
||||||
|
// my ping: one tiny message per second while connected (also when hidden, so the history is there)
|
||||||
|
setInterval(() => { if (net.enabled && net.socket.connected) net.socket.send({ t: 'ping', t0: performance.now() }); }, 1000);
|
||||||
|
net.socket.on('pong', m => { if (typeof m.t0 === 'number') { const now = performance.now(); stats.pong(now - m.t0, now); } });
|
||||||
|
|
||||||
|
function graph(now) {
|
||||||
|
cx.clearRect(0, 0, W, H);
|
||||||
|
cx.fillStyle = 'rgba(0,0,0,.35)'; cx.fillRect(0, 0, W, H);
|
||||||
|
cx.strokeStyle = 'rgba(255,255,255,.12)'; cx.lineWidth = 1;
|
||||||
|
for (const ms of [50, 100, 200]) { const y = H - ms / MAX_MS * H; cx.beginPath(); cx.moveTo(0, y); cx.lineTo(W, y); cx.stroke(); }
|
||||||
|
cx.fillStyle = 'rgba(255,255,255,.35)'; cx.font = '9px monospace';
|
||||||
|
for (const ms of [50, 100, 200]) cx.fillText(ms + 'ms', 2, H - ms / MAX_MS * H - 2);
|
||||||
|
const pts = stats.series(now, SECS);
|
||||||
|
for (const k of ['gap', 'input', 'opp', 'ping']) {
|
||||||
|
cx.strokeStyle = COL[k]; cx.lineWidth = k === 'ping' ? 2 : 1.2; cx.beginPath();
|
||||||
|
let first = true;
|
||||||
|
for (const p of pts) {
|
||||||
|
if (p[k] === undefined) continue;
|
||||||
|
const x = W - (now - p.t) / (SECS * 1000) * W, y = H - Math.min(MAX_MS, p[k]) / MAX_MS * H;
|
||||||
|
if (first) { cx.moveTo(x, y); first = false; } else cx.lineTo(x, y);
|
||||||
|
}
|
||||||
|
cx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
const now = performance.now(), s = stats.summary(now);
|
||||||
|
el.querySelector('.nvh').textContent = t('net_title');
|
||||||
|
el.querySelector('.nvleg').innerHTML = ['ping', 'opp', 'gap', 'input'].map(k => `<span><i style="background:${COL[k]}"></i>${t('net_l_' + k)}</span>`).join('');
|
||||||
|
const row = (label, val) => `<span>${label}</span><b>${val}</b>`;
|
||||||
|
el.querySelector('.nvrows').innerHTML =
|
||||||
|
row(t('net_ping'), s.ping ? `${s.ping} ms <small>(max ${s.pingMax})</small>` : '–')
|
||||||
|
+ (s.fight ? row(t('net_ping_srv'), `${s.serverPing} ms`)
|
||||||
|
+ row(t('net_ping_opp'), `${s.oppPing} ms`)
|
||||||
|
+ row(t('net_snaps'), `${s.gap} ms ±${s.jitter}${s.late ? ` · ${s.late} ${t('net_late')}` : ''}`)
|
||||||
|
+ row(t('net_input'), s.input ? `${s.input} ms` : '–')
|
||||||
|
+ row(t('net_server'), `${s.tickMs} ms · ${s.kbps} kbit/s`) : '');
|
||||||
|
el.querySelector('.nvv').innerHTML = RC.NetStats.verdict(s)
|
||||||
|
.map(v => `<div style="color:${LEVEL[v.level]}">${v.level === 'ok' ? '✔' : v.level === 'warn' ? '⚠' : '✖'} ${t(v.key, { n: v.n })}</div>`).join('');
|
||||||
|
graph(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(on) {
|
||||||
|
visible = on === undefined ? !visible : !!on;
|
||||||
|
el.classList.toggle('hide', !visible);
|
||||||
|
clearInterval(drawT);
|
||||||
|
if (visible) { draw(); drawT = setInterval(draw, 250); }
|
||||||
|
}
|
||||||
|
addEventListener('keydown', e => { if (e.key === 'F3') { e.preventDefault(); e.stopPropagation(); toggle(); } }, true);
|
||||||
|
return { toggle, get visible() { return visible; } };
|
||||||
|
};
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
78
game/netstats.js
Normal file
78
game/netstats.js
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
/* Robot Clash - network measurements for the F3 overlay. No DOM (Node-testable).
|
||||||
|
|
||||||
|
const st = RC.NetStats()
|
||||||
|
st.pong(rttMs, now) my ping, measured by the client (ping/pong over the WebSocket)
|
||||||
|
st.snap(localSnap, bytes, now) a snapshot arrived (already RC.Proto.toLocal'ed: rtt = [me, opponent])
|
||||||
|
st.inputSent(seq, now) input seq left the client
|
||||||
|
st.summary(now) -> { ping, pingMax, serverPing, oppPing, gap, jitter, late, input, tickMs, kbps, snapAge, fight }
|
||||||
|
st.series(now, seconds) -> samples for the graph [{ t, ping, opp, gap, input }]
|
||||||
|
RC.NetStats.verdict(summary) -> [{ key, level: 'ok'|'warn'|'bad', n }] (lang keys nv_*)
|
||||||
|
|
||||||
|
How to read it: ping = you <-> server. oppPing = the opponent <-> server (the server measures it).
|
||||||
|
gap/jitter = how evenly the 20 snapshots/s reach YOU (unsteady = your line). input = key press until the
|
||||||
|
server confirms it (~ping + up to one server step; much more = queueing somewhere). tickMs = server load. */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
const KEEP = 20000; // ms of history
|
||||||
|
|
||||||
|
RC.NetStats = function () {
|
||||||
|
const pings = [], snaps = [], inputs = new Map(), delays = [];
|
||||||
|
let lastSnapAt = 0;
|
||||||
|
const trim = (arr, now) => { while (arr.length && now - arr[0].t > KEEP) arr.shift(); };
|
||||||
|
const avg = a => (a.length ? a.reduce((s, x) => s + x, 0) / a.length : 0);
|
||||||
|
const recent = (arr, now, ms) => arr.filter(x => now - x.t <= ms);
|
||||||
|
|
||||||
|
return {
|
||||||
|
pong(rtt, now) { pings.push({ t: now, v: rtt }); trim(pings, now); },
|
||||||
|
inputSent(seq, now) { inputs.set(seq, now); if (inputs.size > 400) inputs.delete(inputs.keys().next().value); },
|
||||||
|
snap(s, bytes, now) {
|
||||||
|
const gap = lastSnapAt ? now - lastSnapAt : 0;
|
||||||
|
lastSnapAt = now;
|
||||||
|
snaps.push({ t: now, gap, bytes: bytes || 0, opp: s.rtt ? s.rtt[1] : 0, srv: s.rtt ? s.rtt[0] : 0, tickMs: s.tickMs || 0 });
|
||||||
|
trim(snaps, now);
|
||||||
|
// server confirmed every input up to s.ack: the oldest unconfirmed send time gives the delay
|
||||||
|
if (s.ack) for (const [seq, at] of inputs) { if (seq > s.ack) break; if (seq === s.ack) delays.push({ t: now, v: now - at }); inputs.delete(seq); }
|
||||||
|
trim(delays, now);
|
||||||
|
},
|
||||||
|
summary(now) {
|
||||||
|
const p = recent(pings, now, 5000).map(x => x.v), sn = recent(snaps, now, 5000), d = recent(delays, now, 5000).map(x => x.v);
|
||||||
|
const gaps = sn.map(x => x.gap).filter(g => g > 0), g = avg(gaps);
|
||||||
|
const jitter = gaps.length ? Math.sqrt(avg(gaps.map(x => (x - g) ** 2))) : 0;
|
||||||
|
const last = sn[sn.length - 1];
|
||||||
|
return {
|
||||||
|
ping: Math.round(avg(p)), pingMax: Math.round(p.length ? Math.max(...p) : 0),
|
||||||
|
serverPing: last ? last.srv : 0, oppPing: last ? last.opp : 0,
|
||||||
|
gap: Math.round(g), jitter: Math.round(jitter), late: gaps.filter(x => x > 110).length,
|
||||||
|
input: Math.round(avg(d)), tickMs: last ? last.tickMs : 0,
|
||||||
|
kbps: Math.round(sn.reduce((s, x) => s + x.bytes, 0) * 8 / 5 / 1000),
|
||||||
|
snapAge: lastSnapAt ? now - lastSnapAt : Infinity, fight: !!(lastSnapAt && now - lastSnapAt < 3000),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
series(now, seconds = 10) {
|
||||||
|
const from = now - seconds * 1000, out = [];
|
||||||
|
for (const x of snaps) if (x.t >= from) out.push({ t: x.t, gap: x.gap, opp: x.opp });
|
||||||
|
for (const x of pings) if (x.t >= from) out.push({ t: x.t, ping: x.v });
|
||||||
|
for (const x of delays) if (x.t >= from) out.push({ t: x.t, input: x.v });
|
||||||
|
return out.sort((a, b) => a.t - b.t);
|
||||||
|
},
|
||||||
|
reset() { snaps.length = 0; delays.length = 0; inputs.clear(); lastSnapAt = 0; },
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// plain-language reading of a summary; thresholds tuned for a 20 Hz action game
|
||||||
|
RC.NetStats.verdict = function (s) {
|
||||||
|
const out = [];
|
||||||
|
if (s.ping > 150) out.push({ key: 'nv_me_slow', level: s.ping > 250 ? 'bad' : 'warn', n: s.ping });
|
||||||
|
if (s.fight) {
|
||||||
|
if (s.jitter > 30 || s.late > 3) out.push({ key: 'nv_me_jitter', level: s.jitter > 60 || s.late > 10 ? 'bad' : 'warn', n: s.jitter });
|
||||||
|
if (s.oppPing > 150) out.push({ key: 'nv_opp_slow', level: s.oppPing > 250 ? 'bad' : 'warn', n: s.oppPing });
|
||||||
|
if (s.tickMs > 4) out.push({ key: 'nv_server', level: s.tickMs > 10 ? 'bad' : 'warn', n: s.tickMs });
|
||||||
|
if (s.input > s.ping + 150 && s.input > 200) out.push({ key: 'nv_queue', level: 'warn', n: s.input });
|
||||||
|
} else if (s.snapAge !== Infinity && s.snapAge > 3000 && s.snapAge < 30000) out.push({ key: 'nv_lost', level: 'bad', n: Math.round(s.snapAge / 1000) });
|
||||||
|
if (!out.length) out.push({ key: s.fight ? 'nv_ok' : 'nv_nofight', level: 'ok', n: 0 });
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
// client -> server message schemas: field -> check
|
// client -> server message schemas: field -> check
|
||||||
const C2S = {
|
const C2S = {
|
||||||
hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) },
|
hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) },
|
||||||
ping: { t: v => v === undefined || isNum(v) },
|
ping: { t0: v => v === undefined || isNum(v) }, // (t is the message type itself)
|
||||||
room: { room: v => FLAGS.includes(v) || v === 'all' },
|
room: { room: v => FLAGS.includes(v) || v === 'all' },
|
||||||
challenge: { to: v => isStr(v) },
|
challenge: { to: v => isStr(v) },
|
||||||
'challenge.cancel': {},
|
'challenge.cancel': {},
|
||||||
@@ -89,6 +89,7 @@
|
|||||||
robots,
|
robots,
|
||||||
ack: snap.ack ? snap.ack[seat] : 0,
|
ack: snap.ack ? snap.ack[seat] : 0,
|
||||||
away: snap.away ? (seat === 0 ? snap.away.slice() : [snap.away[1], snap.away[0]]) : undefined,
|
away: snap.away ? (seat === 0 ? snap.away.slice() : [snap.away[1], snap.away[0]]) : undefined,
|
||||||
|
rtt: snap.rtt ? (seat === 0 ? snap.rtt.slice() : [snap.rtt[1], snap.rtt[0]]) : undefined, // ping of [me, opponent]
|
||||||
result: localResult(seat, snap.result),
|
result: localResult(seat, snap.result),
|
||||||
crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }),
|
crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }),
|
||||||
rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })),
|
rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })),
|
||||||
|
|||||||
@@ -15,7 +15,8 @@
|
|||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"dev": "npm --prefix server run dev",
|
"dev": "npm --prefix server run dev",
|
||||||
"build:web": "node build-web.mjs",
|
"build:web": "node build-web.mjs",
|
||||||
"e2e": "playwright test"
|
"e2e": "playwright test",
|
||||||
|
"bot": "node tools/bot.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
|
|||||||
@@ -104,6 +104,7 @@ function createLobby({ runner, economy, matches, now = () => Date.now() }) {
|
|||||||
id, seed,
|
id, seed,
|
||||||
players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })),
|
players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })),
|
||||||
send: (seat, msg) => tell(seats[seat].uid, msg),
|
send: (seat, msg) => tell(seats[seat].uid, msg),
|
||||||
|
rttOf: seat => { const p = players.get(seats[seat].uid); return p ? p.rtt : 0; },
|
||||||
onEnd: finish,
|
onEnd: finish,
|
||||||
});
|
});
|
||||||
if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now());
|
if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now());
|
||||||
@@ -143,10 +144,13 @@ function createLobby({ runner, economy, matches, now = () => Date.now() }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ping of a player, measured by the hub (WebSocket ping/pong)
|
||||||
|
function setRtt(uid, ms) { const p = players.get(uid); if (p) p.rtt = p.rtt ? p.rtt * 0.7 + ms * 0.3 : ms; }
|
||||||
|
|
||||||
// the profile changed (robot, flag, fame): show it to everyone
|
// the profile changed (robot, flag, fame): show it to everyone
|
||||||
function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); }
|
function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); }
|
||||||
|
|
||||||
return { join, leave, handle, refresh, startMatch, players, pending, inMatch };
|
return { join, leave, handle, refresh, setRtt, startMatch, players, pending, inMatch };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { createLobby, CHALLENGE_TTL };
|
module.exports = { createLobby, CHALLENGE_TTL };
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ class Room {
|
|||||||
this.seed = opt.seed || 1;
|
this.seed = opt.seed || 1;
|
||||||
this.players = opt.players; // [{ uid, name, build, paint, flag }]
|
this.players = opt.players; // [{ uid, name, build, paint, flag }]
|
||||||
this.send = opt.send || (() => {});
|
this.send = opt.send || (() => {});
|
||||||
|
this.rttOf = opt.rttOf || (() => 0); // seat -> ping in ms (measured by the WebSocket hub)
|
||||||
this.onEnd = opt.onEnd || (() => {});
|
this.onEnd = opt.onEnd || (() => {});
|
||||||
const ids = RC.ARENAS.map(a => a.id);
|
const ids = RC.ARENAS.map(a => a.id);
|
||||||
this.arena = opt.arena || ids[this.seed % ids.length];
|
this.arena = opt.arena || ids[this.seed % ids.length];
|
||||||
@@ -80,7 +81,10 @@ class Room {
|
|||||||
for (const k of [0, 1]) if (this.away[k]) this.away[k]++;
|
for (const k of [0, 1]) if (this.away[k]) this.away[k]++;
|
||||||
if (this.tickN <= COUNTDOWN) return;
|
if (this.tickN <= COUNTDOWN) return;
|
||||||
const s = this.s;
|
const s = this.s;
|
||||||
|
const t0 = process.hrtime.bigint();
|
||||||
RC.Combat.step(s, DT, [this.inputFor(0), this.inputFor(1)]);
|
RC.Combat.step(s, DT, [this.inputFor(0), this.inputFor(1)]);
|
||||||
|
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
|
||||||
|
this.tickMs = this.tickMs ? this.tickMs * 0.9 + ms * 0.1 : ms; // smoothed cost of one step (server load)
|
||||||
if (!this.evBuf) this.evBuf = [];
|
if (!this.evBuf) this.evBuf = [];
|
||||||
if (s.events.length) this.evBuf.push(...s.events);
|
if (s.events.length) this.evBuf.push(...s.events);
|
||||||
s.events.length = 0;
|
s.events.length = 0;
|
||||||
@@ -95,7 +99,10 @@ class Room {
|
|||||||
const snap = RC.Proto.packSnap(s, this.tickN, this.acks);
|
const snap = RC.Proto.packSnap(s, this.tickN, this.acks);
|
||||||
s.events = []; this.evBuf.length = 0;
|
s.events = []; this.evBuf.length = 0;
|
||||||
const away = [!!this.away[0], !!this.away[1]];
|
const away = [!!this.away[0], !!this.away[1]];
|
||||||
for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away }, snap));
|
// network diagnostics for the F3 overlay: each player's ping to the server (measured here) + server step cost
|
||||||
|
const rtt = [0, 1].map(k => Math.round(this.rttOf(k) || 0));
|
||||||
|
const tickMs = Math.round((this.tickMs || 0) * 100) / 100;
|
||||||
|
for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away, rtt, tickMs, sent: Date.now() }, snap));
|
||||||
}
|
}
|
||||||
|
|
||||||
finish(result) {
|
finish(result) {
|
||||||
|
|||||||
40
server/test/bot.test.js
Normal file
40
server/test/bot.test.js
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test, before, after } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { startServer, fastForward } = require('./helpers');
|
||||||
|
const { startBot, PATTERNS } = require('../../tools/bot');
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
let S;
|
||||||
|
before(async () => { S = await startServer(); });
|
||||||
|
after(() => S.close());
|
||||||
|
|
||||||
|
test('every bot pattern gives valid inputs', () => {
|
||||||
|
for (const [name, f] of Object.entries(PATTERNS)) for (const t of [0, 1.3, 7.9]) {
|
||||||
|
const i = RC.Proto.input(f(t));
|
||||||
|
assert.ok(RC.Proto.check(Object.assign({ t: 'input', seq: 1 }, i)).ok, name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the bot accepts a challenge, drives its pattern, and deletes itself on stop', async () => {
|
||||||
|
const bot = await startBot({ url: S.base, pattern: 'circle', quiet: true });
|
||||||
|
const me = await S.account();
|
||||||
|
const c = await S.client(me.idToken);
|
||||||
|
await c.next('lobby.join', m => m.player.uid === bot.uid).catch(() => {});
|
||||||
|
c.send({ t: 'challenge', to: bot.uid });
|
||||||
|
const st = await c.next('match.start', () => true, 5000);
|
||||||
|
assert.equal(st.robots[1 - st.seat].uid, bot.uid);
|
||||||
|
|
||||||
|
// let the real 60 Hz runner play a bit after the countdown: the bot's robot must move
|
||||||
|
const room = S.runner.get(st.matchId);
|
||||||
|
const botSeat = 1 - st.seat, x0 = room.s.robots[botSeat].x, a0 = room.s.robots[botSeat].a;
|
||||||
|
await new Promise(r => setTimeout(r, (st.countdown + 1.2) * 1000));
|
||||||
|
const moved = Math.abs(room.s.robots[botSeat].x - x0) + Math.abs(room.s.robots[botSeat].a - a0);
|
||||||
|
assert.ok(moved > 0.1, 'bot robot moves (circle pattern)');
|
||||||
|
|
||||||
|
fastForward(S.runner);
|
||||||
|
await c.next('match.end', () => true, 5000);
|
||||||
|
await bot.stop();
|
||||||
|
assert.ok(!(await S.json('GET', '/api/ranks')).body.some(r => r.uid === bot.uid), 'bot account is gone');
|
||||||
|
c.close();
|
||||||
|
});
|
||||||
@@ -46,6 +46,16 @@ test('old protocol version is told to reload', async () => {
|
|||||||
assert.equal((await c.closed).code, 4002);
|
assert.equal((await c.closed).code, 4002);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('ping is answered with pong (for the latency overlay)', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const c = await S.client(a.idToken);
|
||||||
|
c.send({ t: 'ping', t0: 42 });
|
||||||
|
const p = await c.next('pong');
|
||||||
|
assert.equal(p.t0, 42);
|
||||||
|
assert.equal(typeof p.serverTime, 'number');
|
||||||
|
c.close();
|
||||||
|
});
|
||||||
|
|
||||||
test('invalid messages get an error, the socket stays open', async () => {
|
test('invalid messages get an error, the socket stays open', async () => {
|
||||||
const a = await S.account();
|
const a = await S.account();
|
||||||
const c = await S.client(a.idToken);
|
const c = await S.client(a.idToken);
|
||||||
@@ -112,7 +122,11 @@ test('full live match over WebSocket: both get start, snapshots, and mirrored re
|
|||||||
const winner = la === 0 ? ea : lb === 0 ? eb : null;
|
const winner = la === 0 ? ea : lb === 0 ? eb : null;
|
||||||
if (winner) assert.ok(winner.reward.ach.some(x => x.id === 'first_win'), 'first win pays out');
|
if (winner) assert.ok(winner.reward.ach.some(x => x.id === 'first_win'), 'first win pays out');
|
||||||
assert.equal(eb.save.games, 1);
|
assert.equal(eb.save.games, 1);
|
||||||
assert.ok(ca.inbox.some(m => m.t === 'snap'), 'snapshots arrived before the end');
|
const snap = ca.inbox.find(m => m.t === 'snap');
|
||||||
|
assert.ok(snap, 'snapshots arrived before the end');
|
||||||
|
assert.ok(Array.isArray(snap.rtt) && snap.rtt.length === 2, 'snapshot carries both pings');
|
||||||
|
assert.equal(typeof snap.tickMs, 'number', 'snapshot carries the server step cost');
|
||||||
|
assert.equal(typeof snap.sent, 'number');
|
||||||
|
|
||||||
// rewards were booked on the server
|
// rewards were booked on the server
|
||||||
const sA = await S.json('GET', '/api/online', undefined, a.idToken);
|
const sA = await S.json('GET', '/api/online', undefined, a.idToken);
|
||||||
|
|||||||
@@ -7,15 +7,20 @@ const auth = require('../auth');
|
|||||||
|
|
||||||
const HELLO_MS = 5000;
|
const HELLO_MS = 5000;
|
||||||
const RATE = 80; // messages per second per socket (inputs ~30/s + lobby)
|
const RATE = 80; // messages per second per socket (inputs ~30/s + lobby)
|
||||||
const PING_MS = 15000;
|
const PING_MS = 2000; // ws ping every 2 s: keepalive + ping measurement
|
||||||
|
const DEAD_MS = 15000; // no pong for this long -> connection is dead
|
||||||
|
|
||||||
function attach(server, { lobby }) {
|
function attach(server, { lobby }) {
|
||||||
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG });
|
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG });
|
||||||
|
|
||||||
wss.on('connection', ws => {
|
wss.on('connection', ws => {
|
||||||
let user = null, tokens = RATE, last = Date.now();
|
let user = null, tokens = RATE, last = Date.now();
|
||||||
ws.alive = true;
|
ws.lastPong = Date.now();
|
||||||
ws.on('pong', () => { ws.alive = true; });
|
ws.on('pong', () => {
|
||||||
|
ws.lastPong = Date.now();
|
||||||
|
if (ws.pingSent && user) lobby.setRtt(user.uid, Number(process.hrtime.bigint() - ws.pingSent) / 1e6);
|
||||||
|
ws.pingSent = 0n;
|
||||||
|
});
|
||||||
const send = msg => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); };
|
const send = msg => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); };
|
||||||
const bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } };
|
const bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } };
|
||||||
const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS);
|
const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS);
|
||||||
@@ -48,7 +53,10 @@ function attach(server, { lobby }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const beat = setInterval(() => {
|
const beat = setInterval(() => {
|
||||||
for (const ws of wss.clients) { if (!ws.alive) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) { /* closed */ } }
|
for (const ws of wss.clients) {
|
||||||
|
if (Date.now() - ws.lastPong > DEAD_MS) { ws.terminate(); continue; }
|
||||||
|
try { ws.pingSent = process.hrtime.bigint(); ws.ping(); } catch (e) { /* closed */ }
|
||||||
|
}
|
||||||
}, PING_MS);
|
}, PING_MS);
|
||||||
if (beat.unref) beat.unref();
|
if (beat.unref) beat.unref();
|
||||||
wss.on('close', () => clearInterval(beat));
|
wss.on('close', () => clearInterval(beat));
|
||||||
|
|||||||
56
tests/netstats.test.js
Normal file
56
tests/netstats.test.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const path = require('path');
|
||||||
|
require(path.join(__dirname, '..', 'game', 'netstats.js'));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
// feed a steady fight: snapshots every `gap` ms (+ jitter), pings, inputs acked after `inDelay`
|
||||||
|
function feed({ ping = 30, gap = 50, jit = 0, opp = 40, tickMs = 0.5, inDelay = 60, secs = 6 } = {}) {
|
||||||
|
const st = RC.NetStats();
|
||||||
|
let t = 1000, seq = 0;
|
||||||
|
const sent = [];
|
||||||
|
for (let i = 0; i < secs * 20; i++) {
|
||||||
|
t += gap + (i % 2 ? jit : -jit);
|
||||||
|
if (i % 20 === 0) st.pong(ping, t);
|
||||||
|
st.inputSent(++seq, t); sent.push({ seq, at: t });
|
||||||
|
const acked = sent.filter(x => t - x.at >= inDelay).pop();
|
||||||
|
st.snap({ rtt: [ping, opp], tickMs, ack: acked ? acked.seq : 0 }, 900, t);
|
||||||
|
}
|
||||||
|
return { st, now: t };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a good connection reads as ok', () => {
|
||||||
|
const { st, now } = feed();
|
||||||
|
const s = st.summary(now);
|
||||||
|
assert.equal(s.ping, 30);
|
||||||
|
assert.equal(s.gap, 50);
|
||||||
|
assert.equal(s.oppPing, 40);
|
||||||
|
assert.ok(s.input >= 50 && s.input <= 120, 'input delay measured: ' + s.input);
|
||||||
|
assert.ok(s.kbps > 100 && s.kbps < 200, 'bandwidth ~ 900 B x 20/s = 144 kbit/s: ' + s.kbps);
|
||||||
|
assert.deepEqual(RC.NetStats.verdict(s).map(v => v.key), ['nv_ok']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('each cause is told apart: my ping, my jitter, opponent, server', () => {
|
||||||
|
const keys = o => { const { st, now } = feed(o); return RC.NetStats.verdict(st.summary(now)).map(v => v.key); };
|
||||||
|
assert.deepEqual(keys({ ping: 220 }), ['nv_me_slow']);
|
||||||
|
assert.deepEqual(keys({ jit: 45 }), ['nv_me_jitter']);
|
||||||
|
assert.deepEqual(keys({ opp: 300 }), ['nv_opp_slow']);
|
||||||
|
assert.deepEqual(keys({ tickMs: 12 }), ['nv_server']);
|
||||||
|
assert.ok(keys({ inDelay: 500 }).includes('nv_queue'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('outside a fight only the ping counts; a silent server is reported', () => {
|
||||||
|
const st = RC.NetStats();
|
||||||
|
st.pong(25, 1000);
|
||||||
|
assert.deepEqual(RC.NetStats.verdict(st.summary(1500)).map(v => v.key), ['nv_nofight']);
|
||||||
|
st.snap({ rtt: [25, 25], tickMs: 0.4 }, 500, 2000);
|
||||||
|
assert.deepEqual(RC.NetStats.verdict(st.summary(9000)).map(v => v.key), ['nv_lost']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('series gives graph points of the last seconds only', () => {
|
||||||
|
const { st, now } = feed({ secs: 15 });
|
||||||
|
const pts = st.series(now, 10);
|
||||||
|
assert.ok(pts.length > 100);
|
||||||
|
assert.ok(pts.every(p => now - p.t <= 10000));
|
||||||
|
});
|
||||||
@@ -10,6 +10,8 @@ test('check accepts valid client messages', () => {
|
|||||||
assert.ok(P.check({ t: 'hello', v: 1, token: 'abc' }).ok);
|
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', to: 'u1' }).ok);
|
||||||
assert.ok(P.check({ t: 'challenge.cancel' }).ok);
|
assert.ok(P.check({ t: 'challenge.cancel' }).ok);
|
||||||
|
assert.ok(P.check({ t: 'ping', t0: 123.4 }).ok, 'ping with a timestamp (regression: t was checked instead of t0)');
|
||||||
|
assert.ok(P.check({ t: 'ping' }).ok);
|
||||||
assert.ok(P.check({ t: 'room', room: 'DE' }).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);
|
assert.ok(P.check({ t: 'input', seq: 3, throttle: 1, turn: -0.5, fire: true, fire2: false, fire3: false }).ok);
|
||||||
});
|
});
|
||||||
@@ -34,7 +36,7 @@ test('input clamps ranges and coerces flags', () => {
|
|||||||
|
|
||||||
function fakeSnap() {
|
function fakeSnap() {
|
||||||
return {
|
return {
|
||||||
tick: 10, ack: [4, 7], away: [false, true], time: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0,
|
tick: 10, ack: [4, 7], away: [false, true], rtt: [20, 140], time: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0,
|
||||||
result: { winner: 0, reason: 'ko' },
|
result: { winner: 0, reason: 'ko' },
|
||||||
press: { st: 'idle', y: 1 }, crane: { st: 'grab', x: 0, z: 0, who: 1 },
|
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 }],
|
rockets: [{ kind: 'rocket', owner: 0, x: 1, z: 2, y: 0.5, a: 0 }],
|
||||||
@@ -62,6 +64,7 @@ test('toLocal for seat 1 mirrors every robot index', () => {
|
|||||||
assert.equal(l.result.winner, 1, 'seat 0 won -> for seat 1 the winner is the opponent (local 1)');
|
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.ack, 7);
|
||||||
assert.deepEqual(l.away, [true, false], 'own connection first');
|
assert.deepEqual(l.away, [true, false], 'own connection first');
|
||||||
|
assert.deepEqual(l.rtt, [140, 20], 'own ping first');
|
||||||
assert.equal(l.crane.who, 0);
|
assert.equal(l.crane.who, 0);
|
||||||
assert.equal(l.rockets[0].owner, 1);
|
assert.equal(l.rockets[0].owner, 1);
|
||||||
assert.equal(l.mines[0].owner, 0);
|
assert.equal(l.mines[0].owner, 0);
|
||||||
|
|||||||
136
tools/bot.js
Normal file
136
tools/bot.js
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/* Robot Clash test bot - a dumb fake player for testing online play alone. No AI: it drives a fixed pattern.
|
||||||
|
It logs in as a guest, waits in the lobby and ACCEPTS every challenge (or challenges a player by name),
|
||||||
|
fights, and goes back to the lobby. Ctrl+C deletes its guest account again.
|
||||||
|
|
||||||
|
npm run bot local server, circles
|
||||||
|
npm run bot -- --url https://roboclash.michael-media.de --pattern zigzag
|
||||||
|
npm run bot -- --url https://roboclash.michael-media.de --challenge benni
|
||||||
|
Options:
|
||||||
|
--url <server> default http://localhost:8080
|
||||||
|
--name <name> lobby name (default Bot-<pattern>)
|
||||||
|
--pattern <p> circle | zigzag | spin | charge | idle (default circle)
|
||||||
|
--challenge <name> challenge this player whenever both are idle (default: only accept)
|
||||||
|
--fights <n> stop after n fights (default: run until Ctrl+C)
|
||||||
|
Diagnosis tip: run the bot ON the server (ssh, then node tools/bot.js --url http://127.0.0.1:8080) - it then has
|
||||||
|
~0 ms ping, so any lag you see comes from your own connection or the server, not from the opponent.
|
||||||
|
|
||||||
|
Also usable as a module (tests): const bot = await startBot({ url, pattern }); ... await bot.stop(); */
|
||||||
|
'use strict';
|
||||||
|
const path = require('path');
|
||||||
|
const WebSocket = require(path.join(__dirname, '..', 'server', 'node_modules', 'ws'));
|
||||||
|
require(path.join(__dirname, '..', 'game', 'protocol.js'));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
// input per pattern at time t (seconds since the fight started)
|
||||||
|
const PATTERNS = {
|
||||||
|
circle: () => ({ throttle: 0.75, turn: 0.55, fire: false }),
|
||||||
|
zigzag: t => ({ throttle: 1, turn: Math.sin(t * 1.6) > 0 ? 0.8 : -0.8, fire: false }),
|
||||||
|
spin: () => ({ throttle: 0, turn: 1, fire: false }),
|
||||||
|
charge: t => ({ throttle: (t % 4) < 2.5 ? 1 : -0.6, turn: (t % 4) < 2.5 ? 0 : 0.9, fire: (t % 4) < 2.5 }),
|
||||||
|
idle: () => ({ throttle: 0, turn: 0, fire: false }),
|
||||||
|
};
|
||||||
|
|
||||||
|
function args(argv) {
|
||||||
|
const o = { url: 'http://localhost:8080', pattern: 'circle', name: null, challenge: null, fights: 0 };
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const k = argv[i].replace(/^--/, ''), v = argv[i + 1];
|
||||||
|
if (k in o) { o[k] = k === 'fights' ? +v : v; i++; }
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startBot(opt) {
|
||||||
|
const url = (opt.url || 'http://localhost:8080').replace(/\/+$/, '');
|
||||||
|
const pattern = PATTERNS[opt.pattern] ? opt.pattern : 'circle';
|
||||||
|
const drive = PATTERNS[pattern];
|
||||||
|
const log = opt.quiet ? () => {} : (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
|
||||||
|
const api = async (method, p, body, token) => {
|
||||||
|
const r = await fetch(url + p, { method, headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}), body: body && JSON.stringify(body) });
|
||||||
|
return r.json().catch(() => null);
|
||||||
|
};
|
||||||
|
const acc = await api('POST', '/api/auth/guest', { name: opt.name || 'Bot-' + pattern });
|
||||||
|
if (!acc || !acc.idToken) throw new Error('guest login failed: ' + JSON.stringify(acc));
|
||||||
|
log(`logged in as ${acc.name} (${pattern}) at ${url}`);
|
||||||
|
|
||||||
|
const ws = new WebSocket(url.replace(/^http/, 'ws') + '/ws');
|
||||||
|
const send = m => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); };
|
||||||
|
const players = new Map();
|
||||||
|
let match = null, timer = null, fights = 0, stopped = false, seq = 0, challengeT = null;
|
||||||
|
const stats = { snaps: 0, gaps: [], last: 0 };
|
||||||
|
const done = new Promise(res => { ws.on('close', res); });
|
||||||
|
|
||||||
|
function tryChallenge() {
|
||||||
|
if (!opt.challenge || match || stopped) return;
|
||||||
|
const target = [...players.values()].find(p => p.name.toLowerCase() === opt.challenge.toLowerCase() && p.state === 'idle');
|
||||||
|
if (target) { log(`challenging ${target.name}`); send({ t: 'challenge', to: target.uid }); }
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.on('open', () => send({ t: 'hello', v: RC.Proto.VERSION, token: acc.idToken }));
|
||||||
|
ws.on('message', raw => {
|
||||||
|
const m = JSON.parse(raw);
|
||||||
|
switch (m.t) {
|
||||||
|
case 'welcome': log('connected - waiting in the lobby' + (opt.challenge ? ` for ${opt.challenge}` : ' (accepts every challenge)')); break;
|
||||||
|
case 'lobby': players.clear(); for (const p of m.players) players.set(p.uid, p); tryChallenge(); break;
|
||||||
|
case 'lobby.join': case 'lobby.state': players.set(m.player.uid, m.player); tryChallenge(); break;
|
||||||
|
case 'lobby.leave': players.delete(m.uid); break;
|
||||||
|
case 'challenge.in': log(`challenged by ${m.name} - accepting`); setTimeout(() => send({ t: 'challenge.accept', from: m.from }), 800); break;
|
||||||
|
case 'challenge.gone': log(`challenge gone (${m.reason || 'gone'})`); clearTimeout(challengeT); challengeT = setTimeout(tryChallenge, 3000); break;
|
||||||
|
case 'match.start': {
|
||||||
|
match = m; seq = 0; stats.snaps = 0; stats.gaps = []; stats.last = 0;
|
||||||
|
const opp = m.robots[1 - m.seat];
|
||||||
|
log(`fight vs ${opp.name} in ${m.arena} (seat ${m.seat}), countdown ${m.countdown.toFixed(1)} s`);
|
||||||
|
const start = Date.now() + m.countdown * 1000;
|
||||||
|
clearInterval(timer);
|
||||||
|
timer = setInterval(() => { // 20 inputs per second, like a player holding keys
|
||||||
|
const t = (Date.now() - start) / 1000;
|
||||||
|
if (t < 0) return;
|
||||||
|
const i = RC.Proto.input(drive(t));
|
||||||
|
send(Object.assign({ t: 'input', seq: ++seq }, i));
|
||||||
|
}, 50);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'snap': {
|
||||||
|
const now = Date.now();
|
||||||
|
if (stats.last) stats.gaps.push(now - stats.last);
|
||||||
|
stats.last = now; stats.snaps++;
|
||||||
|
if (stats.snaps % 200 === 0) {
|
||||||
|
const g = stats.gaps.slice(-200), avg = g.reduce((a, b) => a + b, 0) / g.length;
|
||||||
|
const jit = Math.sqrt(g.reduce((a, b) => a + (b - avg) ** 2, 0) / g.length);
|
||||||
|
const me = RC.Proto.toLocal(match.seat, m);
|
||||||
|
log(` snapshots every ${avg.toFixed(0)} ms (jitter ${jit.toFixed(0)} ms) · ping bot ${me.rtt[0]} ms, opponent ${me.rtt[1]} ms · server step ${m.tickMs} ms`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'match.end': {
|
||||||
|
clearInterval(timer); fights++;
|
||||||
|
const r = RC.Proto.localResult(m.seat, m.result);
|
||||||
|
log(`fight over: ${r.winner === -1 ? 'draw' : r.winner === 0 ? 'bot won' : 'bot lost'} (${m.result.reason})`);
|
||||||
|
match = null;
|
||||||
|
if (opt.fights && fights >= opt.fights) stop(); else { clearTimeout(challengeT); challengeT = setTimeout(tryChallenge, 4000); }
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'error': log('server says:', m.code); break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function stop() {
|
||||||
|
if (stopped) return;
|
||||||
|
stopped = true;
|
||||||
|
clearInterval(timer); clearTimeout(challengeT);
|
||||||
|
try { ws.close(); } catch (e) { /* closed */ }
|
||||||
|
await api('DELETE', '/api/me', undefined, acc.idToken).catch(() => {});
|
||||||
|
log('bot account deleted, bye');
|
||||||
|
}
|
||||||
|
return { uid: acc.uid, name: acc.name, stop, done, get fights() { return fights; }, get inMatch() { return !!match; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { startBot, PATTERNS };
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
const o = args(process.argv.slice(2));
|
||||||
|
startBot(o).then(bot => {
|
||||||
|
process.on('SIGINT', () => bot.stop().then(() => process.exit(0)));
|
||||||
|
bot.done.then(() => { if (o.fights) process.exit(0); });
|
||||||
|
}).catch(e => { console.error(e.message); process.exit(1); });
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user