#!/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 default http://localhost:8080 --name lobby name (default Bot-) --pattern

circle | zigzag | spin | charge | idle (default circle) --challenge challenge this player whenever both are idle (default: only accept) --fights 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); }); }