feat(tools): dumb test bot that accepts challenges and drives a pattern (npm run bot) (P4-1)

This commit is contained in:
Benjamin Oezcan
2026-11-19 14:26:50 +01:00
parent 593d69714b
commit a8d6158384
3 changed files with 178 additions and 1 deletions

View File

@@ -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",

40
server/test/bot.test.js Normal file
View 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();
});

136
tools/bot.js Normal file
View 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); });
}