game/app/scripts/simulate_bots.ts
2026-01-01 02:21:09 +08:00

54 lines
1.7 KiB
TypeScript

import { Client } from '@heroiclabs/nakama-js';
import WebSocket from 'ws';
import { v4 as uuidv4 } from 'uuid';
// Polyfill WebSocket for Node.js
global.WebSocket = WebSocket as any;
const startBot = async (idx: number) => {
const client = new Client('defaultkey', 'localhost', '7350', false);
const deviceId = `bot-player-${idx}-${uuidv4()}`;
try {
const session = await client.authenticateDevice(deviceId, true, `Bot-${idx}`);
console.log(`[Bot ${idx}] Authenticated: ${session.user_id}`);
const socket = client.createSocket(false, false);
await socket.connect(session, true);
console.log(`[Bot ${idx}] Socket Connected`);
// Listen for match
socket.onmatchmakermatched = async (matched) => {
// The matched object might have different property names depending on SDK version or response
console.log(`[Bot ${idx}] Matchmaker Matched:`, matched);
const matchId = matched.match_id || (matched as any).matchId;
const token = matched.token;
if (matchId) {
console.log(`[Bot ${idx}] Joining Match ID: ${matchId}`);
const match = await socket.joinMatch(matchId, token);
console.log(`[Bot ${idx}] Joined Match: ${match.match_id}`);
} else {
console.error(`[Bot ${idx}] Match ID missing in matched data`);
}
};
// Start Matchmaking
console.log(`[Bot ${idx}] Joining Matchmaker...`);
await socket.addMatchmaker('*', 4, 4);
} catch (err) {
console.error(`[Bot ${idx}] Error:`, err);
}
};
// Start 3 Bots
console.log('Starting 3 Bots to fill the match...');
for (let i = 1; i <= 3; i++) {
startBot(i);
}
// Keep script running
setInterval(() => {}, 10000);