-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.js
711 lines (575 loc) · 18.2 KB
/
client.js
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
// @ts-check
const events = require("events");
const { joinLobby } = require("./auth.js");
const Constants = require("./constants.js");
class Client extends events {
/**
* @class
* @param {Object} [options] - Options the client should use
* @param {String} [options.name] - The username the bot should join with
* @param {Array} [options.avatar] - The avatar the bot should join with
* @param {String} [options.lobbyCode] - The lobby code to join with
* @param {Boolean} [options.createPrivateRoom] - If a private room should be created. Not supported with the lobbyCode option.
* @param {Number} [options.language] - The langauge code to look for servers with. Not needed if a lobby code is set. Can be a number 1-27.
* @param {string} [options.serverURL] - The server to log into. This can be used in combination with a Proxy or a custom Server
* @param {Object} [options.httpHeaders] - HTTP headers to use
* @param {Object} [options.socketOptions] - Options to use for socket.io-client
* @throws {TypeError}
*/
constructor(options = {}) {
super();
if(typeof options !== "object") throw TypeError("Client options is not an object.");
if(typeof options.httpHeaders !== "object") options.httpHeaders = {};
if(options.createPrivateRoom && options.lobbyCode) throw TypeError("Cannot create a private room with a lobby code.");
if(!options.language) options.language = 0;
if(!Array.isArray(options.avatar)) options.avatar = [
Math.floor(100 * Math.random()) % 26,
Math.floor(100 * Math.random()) % 57,
Math.floor(100 * Math.random()) % 51,
-1
];
this.options = options;
this.init();
}
options = {};
socket = null;
connected = false;
lobbyId = null;
settings = {};
state = null;
round = 0;
userId = null;
ownerId = null;
lobbyType = null;
players = [];
time = 0;
currentDrawer = null;
availableWords = [];
canvas = [];
word = "";
async init() {
if(this.socket) throw Error("Client has already initialized.");
const socket = await joinLobby(this.options);
// @ts-expect-error
this.socket = socket;
this.connected = true;
let disconnectReason;
let joinErr;
socket.on("joinerr", (data) => {
joinErr = data;
});
socket.on("reason", (data) => {
disconnectReason = data;
});
socket.on("disconnect", (transportDisconnectReason) => {
this.connected = false;
this.emit("disconnect", {
reason: disconnectReason,
joinErr,
transportDisconnectReason
});
});
// Start listening for packets
socket.on("data", (message) => {
// Make sure 'id' exist on the data event to prevent a crash from trying to destructure an invalid type
if(!message?.id) return;
const { id, data } = message;
if(data === null) return;
switch(id) {
case Constants.Packets.PLAYER_JOIN: {
if(typeof data !== "object") return console.log(`Received invalid packet. ID: 1.`);
this.players.push(data);
this.emit("playerJoin", data);
break;
}
case Constants.Packets.PLAYER_LEAVE: {
if(
typeof data?.id !== "number" ||
typeof data.reason !== "number"
) return console.log(`Received invalid packet. ID: 2.`);
const index = this.players.findIndex(plr => plr.id === data.id);
if(index === -1) break;
const player = this.players.splice(index, 1)[0];
this.emit("playerLeave", {
player: player,
reason: data.reason
});
break;
}
case Constants.Packets.VOTEKICK: {
if(
!Array.isArray(data) ||
typeof data[0] !== "number" ||
typeof data[1] !== "number" ||
typeof data[2] !== "number" ||
typeof data[3] !== "number"
) return console.log(`Received invalid packet. ID: 2.`);
// Get the player that voted to kick, and who they voted for
const voter = this.players.find(plr => plr.id === data[0]);
const votee = this.players.find(plr => plr.id === data[1]);
if(!voter) break;
if(!votee) break;
this.emit("votekick", {
voter,
votee,
currentVotes: data[2],
requiredVotes: data[3]
});
break;
}
case Constants.Packets.VOTE: {
if(
typeof data?.id !== "number" ||
typeof data?.vote !== "number"
) return console.log(`Received invalid packet. ID: 8.`);
const player = this.players.find(plr => plr.id === data.id);
if(!player) break;
this.emit("vote", {
player,
vote: data.vote
});
break;
}
case Constants.Packets.LOBBY_DATA:
if(
!Array.isArray(data?.settings) ||
!Array.isArray(data?.users)
) return console.log(`Received invalid packet. ID: 10.`);
this.lobbyId = data.id;
this.settings = {
language: data.settings[0],
maxPlayers: data.settings[1],
maxDrawTime: data.settings[2],
maxRounds: data.settings[3],
wordCount: data.settings[4],
maxHints: data.settings[5],
wordMode: data.settings[6],
useCustomWords: data.settings[7] ? true : false
};
this.state = data.state?.id;
this.round = data.round + 1;
this.userId = data.me;
this.ownerId = data.owner;
this.lobbyType = data.type;
this.players = data.users;
this.time = data.state?.time;
this.currentDrawer = this.players.find(plr => plr.id === data.state?.data?.id);
this.canvas = this.canvas.concat(data.state?.data?.drawCommands);
if(Array.isArray(data.state?.data?.word)) {
for(const length of data.state.data.word) {
this.word += `${"_".repeat(length)} `;
}
this.word = this.word.trim();
}
if(Array.isArray(data.state?.data?.hints)) {
const characters = this.word.split("");
for(const hint of data.state.data.hints) {
if(!Array.isArray(hint)) continue;
characters[hint[0]] = hint[1];
}
this.word = characters.join("");
}
this.emit("connect");
break;
case Constants.Packets.UPDATE_GAME_DATA: {
if(
typeof data?.id !== "number" ||
typeof data?.time !== "number"
) return console.log(`Received invalid packet. ID: 11.`);
this.state = data.id;
this.time = data.time;
// Handle game state
switch(data.id) {
// Pass through
case Constants.GameState.GAME_STARTING_SOON:
case Constants.GameState.WAITING_FOR_PLAYERS: {
this.emit("stateUpdate", {
state: data.id
});
break;
}
case Constants.GameState.CURRENT_ROUND: {
if(typeof data.data !== "number") return console.log(`Received invalid packet. ID: 11`);
// @ts-ignore
this.round = data.data + 1;
// Scores are reset
if(this.round === 1) {
for(const player of this.players) {
player.score = 0;
}
}
this.emit("stateUpdate", {
state: data.id,
round: this.round
});
break;
}
case Constants.GameState.USER_PICKING_WORD: {
if(typeof data.data?.id !== "number") return console.log(`Received invalid packet. ID: 11`);
this.currentDrawer = this.players.find(plr => plr.id === data.data.id);
this.availableWords = data.data.words;
this.emit("stateUpdate", {
state: data.id,
drawer: this.currentDrawer,
// The following field will be undefined if the Client is not the one who will be drawing
words: this.availableWords
});
break;
}
case Constants.GameState.CAN_DRAW: {
if(typeof data.data !== "object") return console.log(`Received invalid packet. ID: 11`);
this.canvas = [];
this.availableWords = [];
this.currentDrawer = this.players.find(plr => plr.id === data.data?.id);
if(Array.isArray(data.data.word)) {
for(const length of data.data.word) {
this.word += `${"_".repeat(length)} `;
}
this.word = this.word.trim();
} else {
this.word = data.data.word;
}
this.emit("stateUpdate", {
state: data.id,
drawer: this.currentDrawer,
word: this.word
});
break;
}
case Constants.GameState.DRAW_RESULTS: {
if(!Array.isArray(data.data?.scores)) return console.log(`Received invalid packet. ID: 11`);
this.word = "";
const stateUpdate = {
state: data.id,
reason: data.data.reason,
word: data.data.word,
newScores: {}
};
let counter = 0;
for(const player of this.players) {
player.guessed = false;
player.score = data.data.scores[(counter * 3) + 1];
stateUpdate.newScores[player.name] = player.score;
counter++;
}
this.emit("stateUpdate", stateUpdate);
break;
}
case Constants.GameState.GAME_RESULTS: {
if(!Array.isArray(data.data)) return console.log(`Received invalid packet. ID: 11`);
const leaderboard = [];
for(const player of data.data) {
if(!Array.isArray(player)) break;
/**
* player[0] = Player ID
* player[1] = Leaderboard position
* player[2] = Unknown
*/
leaderboard[player[1]] = this.players.find(plr => plr.id === player[0]);
}
this.emit("stateUpdate", {
state: data.id,
leaderboard
});
break;
}
// When a private lobby's game ends, reset all the player's scores
case Constants.GameState.IN_GAME_WAITING_ROOM: {
this.canvas = [];
this.round = 0;
for(const player of this.players) {
player.score = 0;
}
this.emit("stateUpdate", {
state: data.id
});
}
}
break;
}
case Constants.Packets.UPDATE_SETTINGS: {
if(
typeof data?.id !== "number" ||
typeof data?.val !== "number"
) return console.log(`Received invalid packet. ID: 12.`);
const setting = Object.keys(this.settings)[data.id];
if(!setting) break;
if(setting === "useCustomWords") data.val = data.val ? true : false;
this.settings[setting] = data.val;
break;
}
case Constants.Packets.REVEAL_HINT: {
if(!Array.isArray(data)) return console.log(`Received invalid packet. ID: 13.`);
const characters = this.word.split("");
for(const hint of data) {
if(!Array.isArray(hint)) continue;
/**
* hint[0] is the position of the word where the letter belongs
* hint[1] is the letter
*/
characters[hint[0]] = hint[1];
}
this.word = characters.join("");
this.emit("hintRevealed", data);
break;
}
case Constants.Packets.UPDATE_TIME:
if(typeof data !== "number") return console.log(`Received invalid packet. ID: 14.`);
this.time = data - 1;
break;
case Constants.Packets.PLAYER_GUESSED: {
if(typeof data?.id !== "number") return console.log(`Received invalid packet. ID: 15.`);
const player = this.players.find(plr => plr.id === data.id);
if(!player) break;
player.guessed = true;
if(data.word) this.word = data.word;
this.emit("playerGuessed", {
player,
// Can be undefined
word: data.word
});
break;
}
case Constants.Packets.CLOSE_WORD:
if(typeof data !== "string") return console.log(`Received invalid packet. ID: 16.`);
this.emit("closeWord", data);
break;
case Constants.Packets.SET_OWNER: {
if(typeof data !== "number") return console.log(`Received invalid packet. ID: 17.`);
const player = this.players.find(plr => plr.id === data);
if(!player) break;
// @ts-expect-error
this.ownerId = data;
this.emit("newOwner", {
player
});
break;
}
case Constants.Packets.DRAW:
this.canvas.push(...data);
this.emit("draw", data);
break;
case Constants.Packets.CLEAR_CANVAS:
this.canvas = [];
this.emit("clearCanvas");
break;
case Constants.Packets.UNDO: {
if(typeof data !== "number") return console.log(`Received invalid packet. ID: 21.`);
this.canvas.splice(data);
this.emit("undo", data);
break;
}
case Constants.Packets.TEXT: {
if(
typeof data?.id !== "number" ||
typeof data?.msg !== "string"
) return console.log(`Received invalid packet. ID: 30.`);
const player = this.players.find(plr => plr.id === data.id);
if(!player) break;
this.emit("text", {
player: player,
msg: data.msg
});
break;
}
case Constants.Packets.GAME_START_ERROR: {
if(typeof data?.id !== "number") return console.log(`Received invalid packet. ID: 31.`);
this.emit("startError", {
reason: data.id,
// The following field is only sent if the start error reason is 100
time: data.data
});
break;
}
default:
this.emit(id, data);
}
this.emit("packet", {id, data});
});
const interval = setInterval(() => {
if(!this.connected) return clearInterval(interval);
if(this.time && this.time > 0) this.time--;
}, 1000);
}
/**
* @name sendPacket
* @description Sends a data packet to the server
* @param {Number} id - The packet ID
* @param {any} [data] - Packet data to send
* @throws
*/
sendPacket(id, data) {
// @ts-expect-error
if(!this.socket?.connected) throw Error("Socket isnt initialized or is disconnected.");
// @ts-expect-error
this.socket.emit("data", {
id,
data
});
}
/**
* @name hostKick
* @description If you are the host of a lobby, this will kick the player out of the lobby
* @param {Number} userId - The ID of the user who will be getting votekicked
* @throws
*/
hostKick(userId) {
if(typeof userId !== "number") throw TypeError("Expected userId to be type of Number");
this.sendPacket(3, userId);
}
/**
* @name hostBan
* @description If you are the host of a lobby, this will ban the player's IP from ever joining that lobby
* @param {Number} userId - The ID of the user to ban
* @throws
*/
hostBan(userId) {
if(typeof userId !== "number") throw TypeError("Expected userId to be type of Number");
this.sendPacket(4, userId);
}
/**
* @name votekick
* @description Votekick a user. If the player gets enough votes, they will be kicked.
* @param {Number} userId - The ID of the user who will be getting votekicked
* @throws
*/
votekick(userId) {
if(typeof userId !== "number") throw TypeError("Expected userId to be type of Number");
this.sendPacket(5, userId);
}
/**
* @name vote
* @description Vote on an image
* @param {Number | String} id - Can be either 0, 1, like or dislike
* @throws
*/
vote(id) {
if(typeof id !== "number" && typeof id !== "string") throw TypeError("Expected id to be type of String or Number");
if(id === "dislike") id = 0;
else if(id === "like") id = 1;
// @ts-expect-error
if(id < 0 || id > 1) throw Error("Invalid vote option");
this.sendPacket(8, id);
}
/**
* @name updateRoomSettings
* @description Change the private room settings if you are the owner
* @param {String | Number} settingId - ID of the setting to change
* @param {String | Number} val - What the value of the setting should be
* @throws
*/
updateRoomSettings(settingId, val) {
if(typeof settingId !== "string" && typeof settingId !== "number") throw TypeError("Expected settingId to be type of String or Number");
if(typeof val !== "string" && typeof settingId !== "number") throw TypeError("Expected val to be type of String or Number");
this.sendPacket(12, {
id: String(settingId),
val: String(val)
});
}
/**
* @name selectWord
* @description The word to select to draw. You can listen to the stateUpdate event and wait for a state id of 3. The event will provide an array of all the possible words. The exact word or the array index number are accepted
* @param {Number | String} word - The word to select
* @throws
*/
selectWord(word) {
if(typeof word !== "number" && typeof word !== "string") throw TypeError("Expected word to be type of Number or String");
if(typeof word === "string") {
for(let i = 0; i < this.availableWords.length + 1; i++) {
if(this.availableWords[i] === word) {
word = i;
break;
}
}
}
this.sendPacket(18, word);
}
/**
* @name draw
* @description Draw on the canvas
* @param {Array[]} data - Draw Data. If the array has more then 8 items, the server simply ignores the packet
* @throws
*/
draw(data) {
if(!Array.isArray(data)) throw TypeError("Expected data to be an array");
this.canvas.push(...data);
this.sendPacket(19, data);
}
/**
* @name clearCanvas
* @description Clear the canvas if you are the current drawer
* @throws
*/
clearCanvas() {
this.canvas = [];
this.sendPacket(20);
}
/**
* @name undo
* @description Undo a draw event
* @param {Number} [id]
* @throws
*/
undo(id) {
if(!id) id = this.canvas.length - 1;
if(this.canvas.length === 1) return this.clearCanvas();
this.canvas.splice(id, 1);
this.sendPacket(21, id);
}
/**
* @name startGame
* @description Start the game if you are the owner of the private lobby
* @param {Array} [customWords] - Custom words to use. Note: If there are less then 10 custom words, the server does not use the custom word list
* @returns {Promise<Number | String>} startError
* @async
* @throws
*/
async startGame(customWords = []) {
if(!Array.isArray(customWords)) throw TypeError("Expected customWords to be an array");
this.sendPacket(22, customWords.join(", "));
return new Promise((resolve) => {
let resolved;
this.once("startError", (error) => {
resolved = true;
resolve(error);
});
// If we havent recieved a startError event after 2.5 seconds, most likely it succeeded
setTimeout(() => {
if(!resolved) resolve("OK");
}, 2500);
});
}
/**
* @name endGame
* @description End the game if you are the host of the private lobby
* @throws
*/
endGame() {
this.sendPacket(23);
}
/**
* @name sendMessage
* @description Send a message in the lobby
* @param {String} msg - The message to send
* @throws
*/
sendMessage(msg) {
if(typeof msg !== "string") throw TypeError("Expected msg to be type of String");
this.sendPacket(30, msg);
}
/**
* @name disconnect
* @description Disconnects you from the lobby
* @throws
*/
disconnect() {
// @ts-expect-error
if(!this.socket?.connected) throw Error("Socket is already disconnected");
this.connected = false;
// @ts-expect-error
this.socket.disconnect();
}
}
module.exports = {
Client
};