-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbots.mjs
92 lines (77 loc) · 3.05 KB
/
bots.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import {Command, Option} from 'commander';
import ClientToServerConnection from './client/js/connection.mjs';
import ws from 'ws';
global.WebSocket = ws;
const program = new Command();
program.version('0.0.1')
.addOption(new Option('-n, --count <count>', 'The number of bots to add').default(1))
.addOption(new Option('-g, --gameid <id>', 'The id of the game').makeOptionMandatory())
.addOption(new Option('-u, --url <url>', 'The url to the service').makeOptionMandatory())
.addOption(new Option('-b, --behaviours <behaviours...>', 'The behaviour each bot use').default(['guess']).choices(['guess', 'reconnect']))
.parse();
class Bot {
constructor(name, connection, gameId, behaviours) {
this._name = name;
this._connection = connection;
this._gameId = gameId;
this._behaviours = behaviours;
this._gameStarted = false;
}
async init() {
let result = await this._connection.connect(this._gameId, this._name);
this._clientId = result.clientId;
this._listen();
if (this._behaviours.includes('reconnect')) {
setTimeout(() => this._reconnect(), this._randomDelay() * 2);
}
}
_listen() {
this._connection.onQuestionStart().then(async () => {
this._gameStarted = true;
this._guess();
});
this._connection.onQuestionEnd().then(async () => {});
this._connection.onGameEnd().then(async () => {});
}
async _reconnect() {
try {
if (this._connection.connected()) {
this._connection.close();
console.log(`${this._name} disconnected`);
} else {
if (this._gameStarted) {
await this._connection.reconnect(this._gameId, this._clientId);
} else {
let result = await this._connection.connect(this._gameId, this._name);
this._clientId = result.clientId;
}
console.log(`${this._name} connected`);
this._listen();
}
} catch (e) {
console.log(`${this._name} failed to reconnect: ${e.message}`);
}
setTimeout(() => this._reconnect(), this._randomDelay() * 2);
}
_guess() {
if (!this._behaviours.includes('guess')) {
return;
}
setTimeout(() => {
let guess = ['A', 'B', 'C', 'D'][Math.floor(Math.random() * 4)];
this._connection.guess(guess).then(() => console.log(`${this._name} guessed ${guess}`)).catch((e) => {});
}, this._randomDelay());
}
_randomDelay() {
return Math.floor(Math.random() * 10000);
}
}
async function createBots(count, gameId, url, behaviours) {
for (var i = 0; i < count; i++) {
let conn = new ClientToServerConnection(url, () => crypto.randomUUID());
let bot = new Bot(`Bot ${i + 1}`, conn, gameId, behaviours);
await bot.init();
}
}
let opts = program.opts();
createBots(opts.count, opts.gameid, opts.url, opts.behaviours);