-
Notifications
You must be signed in to change notification settings - Fork 7
/
WaitingRoom.js
1620 lines (1413 loc) · 51 KB
/
WaitingRoom.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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* # WaitinRoom
* Copyright(c) 2017 Stefano Balietti <ste@nodegame.org>
* MIT Licensed
*
* Waiting room.
*
* http://www.nodegame.org
*/
"use strict";
// ## Global scope
module.exports = WaitingRoom;
var J = require('JSUS').JSUS;
var path = require('path');
var ngt = require('nodegame-game-template');
var PlayerList = require('nodegame-client').PlayerList;
var HostRoom = require('./HostRoom');
/* Inherit from HostRoom.
Same effect as `WaitingRoom.prototype.__proto__ = HostRoom.prototype;`
without relying on non-standard `__proto__`
*/
WaitingRoom.prototype = Object.create(HostRoom.prototype);
WaitingRoom.prototype.constructor = WaitingRoom;
/**
* ## WaitingRoom.sortingCallbacks
*
* Predefined callbacks to sort the list of players before dispatching
*/
WaitingRoom.sortingCallbacks = {
// ### timesNotSelected
// Gives priority to players which have been left out in previous dispatch
timesNotSelected: function(a, b) {
if ((a.timesNotSelected || 0) < b.timesNotSelected) {
return -1;
}
else if ((a.timesNotSelected || 0) > b.timesNotSelected) {
return 1;
}
return 0;
}
};
/**
* ## WaitingRoom.treatmentCallbacks
*
* Names of callbacks for assigning treatments to groups of players
*/
WaitingRoom.treatmentCallbacks = {
// Keep treatment_ in front to minimize risk of collision
// with real treatment names.
// ### treatment_rotate
// Rotates across all treatments sequentially
'treatment_rotate': true,
// ### random
// Selects a random treatment (with re-sampling)
'treatment_random': true
};
/**
* ## WaitingRoom.dispatchStates
*
* States of the dispatching method
*
* - NONE: no dispatching called
* - INITING: dispatching called, but can return if params are not correct
* - DISPATCHING: dispatching a group of players
* - NOTIFYING: dispatching is ending by notifying not selected players
*
* @see WaitingRoom.dispatch
*/
WaitingRoom.dispatchStates = {
NONE: 'NONE',
INITING: 'INITING',
DISPATCHING: 'DISPATCHING',
NOTIFYING: 'NOTIFYING'
};
/**
* ## WaitingRoom constructor
*
* Creates a new instance of WaitingRoom
*
* @param {object} config Configuration object
*
* @see HostRoom
*/
function WaitingRoom(config) {
// Supercall
HostRoom.call(this, 'Waiting', config);
if (!this.logicPath) this.logicPath = ngt.resolve('waitroom/waitroom.js');
/**
* ### WaitingRoom.roomOpen
*
* Flag indicating whether the room is open
*/
this.roomOpen = config.roomOpen || true;
/**
* ### WaitingRoom.dispatching
*
* Numeric flag indicating whether the room is dispatching a new game
*
*
*/
this.dispatching = 0;
/**
* ### WaitingRoom.timeOuts
*
* Array of setTimeout return values indexed by playerIDs
*/
this.timeOuts = {};
/**
* ### WaitingRoom.notifyTimeout
*
* A timeout to notify players about updates in the number of players
*
* @see WaitingRoom.notifyPlayers
*/
this.notifyTimeout = null;
/**
* ### WaitingRoom.numberOfDispatches
*
* Non-negative integer indicating the number of game dispatches
*/
this.numberOfDispatches = config.numberOfDispatches || 0;
/**
* ### WaitingRoom.lastGameRoom
*
* Reference to the last created game room
*/
this.lastGameRoom = null;
/**
* ### WaitingRoom.GROUP_SIZE
*
* Positive non-zero integer indicating the size of each group
*/
this.GROUP_SIZE = null;
/**
* ### WaitingRoom.POOL_SIZE
*
* Positive non-zero integer indicating number of clients for group forming
*/
this.POOL_SIZE = null;
/**
* ### WaitingRoom.DISCONNECT_IF_NOT_SELECTED
*
* Boolean or null, indicating whether unselected players are disconnected
*/
this.DISCONNECT_IF_NOT_SELECTED = null;
/**
* ### WaitingRoom.timeOuts
*
* Array of setTimeout return values indexed by playerIDs
*/
this.N_GAMES = null;
/**
* ### WaitingRoom.START_DATE
*
* Time and date of game start
*
* Must be valid input for `Date` constructor
*/
this.START_DATE = null;
/**
* ### WaitingRoom.EXECUTION_MODE
*
* String indicating execution mode
*
* In the execution mode ´'TIMEOUT'´, one waits until the time is up, then
* it will be checked whether enough players are there to start the game.
* In the execution mode ´'WAIT_FOR_N_PLAYERS'´, the game starts right away
* if there are the desired number of players. Otherwise, when the time is
* up, it will be checked if there are at least a certain minimum number of
* players to start the game.
*/
this.EXECUTION_MODE = null;
/**
* ### WaitingRoom.MAX_WAIT_TIME
*
* Positive non-zero integer indicating max number of milliseconds to start
*
* Cannot be defined at the same time as `WaitingRoom.START_DATE`
*/
this.MAX_WAIT_TIME = null;
/**
* ### WaitingRoom.ON_TIMEOUT
*
* Callback to be executed client-side after waiting time has elapsed
*/
this.ON_TIMEOUT = null;
/**
* ### WaitingRoom.ON_TIMEOUT_SERVER
*
* Callback to be executed after a timeout has expired
*/
this.ON_TIMEOUT_SERVER = null;
/**
* ### WaitingRoom.ON_OPEN
*
* Callback to be executed when the waiting room becomes open
*/
this.ON_OPEN = null;
/**
* ### WaitingRoom.ON_CLOSE
*
* Callback to be executed when the waiting room becomes close
*/
this.ON_CLOSE = null;
/**
* ### WaitingRoom.ON_CONNECT
*
* Callback to be executed when a player connects
*/
this.ON_CONNECT = null;
/**
* ### WaitingRoom.ON_DISCONNECT
*
* Callback to be executed when a player disconnects
*/
this.ON_DISCONNECT = null;
/**
* ### WaitingRoom.ON_INIT
*
* Callback to be executed after the settings have been parsed
*/
this.ON_INIT = null;
/**
* ### WaitingRoom.ON_DISPATCH
*
* Callback to be executed just before starting dispatching
*
* Receives the options of the dispatch call as second param
*/
this.ON_DISPATCH = null;
/**
* ### WaitingRoom.ON_DISPATCHED
*
* Callback to be executed at the end of a dispatch call
*/
this.ON_DISPATCHED = null;
/**
* ### WaitingRoom.ON_FAILED_DISPATCH
*
* Callback to be executed if a dispatch attempt failed
*/
this.ON_FAILED_DISPATCH = null;
/**
* ### WaitingRoom.CHOSEN_TREATMENT
*
* String or undefined indicating chosen treatment
*/
this.CHOSEN_TREATMENT = null;
/**
* ### WaitingRoom.PLAYER_SORTING
*
* Callback to sort the list of players before dispatching
*
* If NULL, random sorting takes place. Default: 'timesNotSelected'
*/
this.PLAYER_SORTING = WaitingRoom.sortingCallbacks.timesNotSelected;
/**
* ### WaitingRoom.PING_BEFORE_DISPATCH
*
* If TRUE, all players are pinged before a dispatch (Default: TRUE)
*
* Non-responding clients are disconnected.
*
* If only one player is needed and mode is 'WAIT_FOR_N_PLAYERS',
* pinging is skipped.
*
* @see PING_MAX_REPLY_TIME
*/
this.PING_BEFORE_DISPATCH = true;
/**
* ### WaitingRoom.PING_MAX_REPLY_TIME
*
* The time to wait to receive a ping back
*
* Clients will be disconnected if they do not reply in time.
*
* @see PING_BEFORE_DISPATCH
*/
this.PING_MAX_REPLY_TIME = 3000;
/**
* ### WaitingRoom.PING_DISPATCH_ANYWAY
*
* If TRUE, dispatch continues even if disconnections occur during PING
*
* @see PING_BEFORE_DISPATCH
* @see PING_MAX_REPLY_TIME
*/
this.PING_DISPATCH_ANYWAY = false;
/**
* ### WaitingRoom.TEXTS
*
* List of texts replacing default ones in WaitingRoom widget
*
* @see WaitingRoom.texts (widget)
*/
this.TEXTS = {};
/**
* ### WaitingRoom.SOUNDS
*
* List of paths to sounds replacing default ones in WaitingRoom widget
*
* @see WaitingRoom.sounds (widget)
*/
this.SOUNDS = {};
/**
* ### WaitingRoom.PAGE_TITLE
*
* Sets the page title, optionally adds to page
*
*/
this.PAGE_TITLE = { title: 'Welcome!', addToBody: true };
/**
* ### WaitingRoom.isPingInProgress
*
* Flag to indicate whether currently pinging for unresponsive players
*/
this.isPingInProgress = false;
/**
* ### WaitingRoom.suspendedPings
*
* Flag to indicate whether currently pinging for unresponsive players
*/
this.suspendedPings = [];
/**
* ### WaitingRoom.closeAfterDispatch
*
* Flag that the waiting room will close after next dispatch
*
* Note: waiting room can dispatch multiple groups, and then will close
*/
this.closeAfterDispatch = false;
/**
* ### WaitingRoom.NOTIFY_INTERVAL
*
* The number of milliseconds to wait before sending a player-update message
*
* @see WaitingRoom.notifyPlayerUpdate
*/
this.NOTIFY_INTERVAL = 200;
}
/**
* ## WaitingRoom.dispatchWithBots
*
* Dispatches waiting players to new gamerooms and connects bot to each room.
*/
WaitingRoom.prototype.dispatchWithBots = function() {
var neededBots, botOptions, dispatchList, pId, gameRoom, treatmentName;
var i = -1, j = -1, gameNumber = -1;
this.PING_BEFORE_DISPATCH = false;
dispatchList = this.clients.player.db;
// fill reset of group with bots.
neededBots = this.GROUP_SIZE - dispatchList.length;
for (; ++j < neededBots;) {
gameNumber++;
botOptions = {
room: this,
clientType: 'bot',
setup: {}
};
this.channel.connectBot(botOptions);
}
};
/**
* ## WaitingRoom.parseSettings
*
* Validates settings and appends values to `this`
*
* @param {object} settings Configuration object
*/
WaitingRoom.prototype.parseSettings = function(settings) {
var d, where, gameName;
var that = this;
gameName = this.channel.gameInfo.info.name + ' ';
where = gameName + 'WaitingRoom.parseSettings: ';
if ('object' !== typeof settings) {
throw new TypeError(where + 'settings must be object. Found: ' +
settings);
}
if ('number' === typeof settings.GROUP_SIZE) {
checkPositiveInteger(settings, 'GROUP_SIZE', where);
this.GROUP_SIZE = settings.GROUP_SIZE;
}
else {
throw new TypeError(where + 'GROUP_SIZE must be a positive number. ' +
'Found: ' + settings.GROUP_SIZE);
}
if ('undefined' !== typeof settings.POOL_SIZE) {
if ('number' === typeof settings.POOL_SIZE) {
checkPositiveInteger(settings, 'POOL_SIZE', where);
this.POOL_SIZE = settings.POOL_SIZE;
}
else {
throw new TypeError(where + 'POOL_SIZE must be a positive ' +
'number or undefined. Found: ' +
settings.POOL_SIZE);
}
}
else {
this.POOL_SIZE = settings.GROUP_SIZE;
}
if (this.POOL_SIZE < this.GROUP_SIZE) {
throw new TypeError(where + 'POOL_SIZE should be larger or equal ' +
'to GROUP_SIZE. Found: ' + this.POOL_SIZE + ', ' +
this.GROUP_SIZE);
}
if ('undefined' !== typeof settings.N_GAMES) {
if ('number' === typeof settings.POOL_SIZE) {
checkPositiveInteger(settings, 'N_GAMES', where);
this.N_GAMES = settings.N_GAMES;
}
else {
throw new TypeError(where + 'N_GAMES must be a positive number ' +
'or undefined. Found: ' + settings.N_GAMES);
}
}
if ('undefined' !== typeof settings.NOTIFY_INTERVAL) {
if ('number' === typeof settings.NOTIFY_INTERVAL) {
checkPositiveInteger(settings, 'NOTIFY_INTRVAL', where);
this.NOTIFY_INTERVAL = settings.NOTIFY_INTERVAL;
}
else {
throw new TypeError(where + 'NOTIFY_INTERVAL must be a positive ' +
'number or undefined. Found: ' +
settings.NOTIFY_INTERVAL);
}
}
if ('undefined' !== typeof settings.DISCONNECT_IF_NOT_SELECTED) {
if ('boolean' === typeof settings.DISCONNECT_IF_NOT_SELECTED) {
this.DISCONNECT_IF_NOT_SELECTED =
settings.DISCONNECT_IF_NOT_SELECTED;
}
else {
throw new TypeError(where + 'DISCONNECT_IF_NOT_SELECTED must ' +
'be boolean or undefined. Found: ' +
settings.DISCONNECT_IF_NOT_SELECTED );
}
}
if ('undefined' !== typeof settings.DISPATCH_TO_SAME_ROOM) {
if ('boolean' === typeof settings.DISPATCH_TO_SAME_ROOM) {
this.DISPATCH_TO_SAME_ROOM = settings.DISPATCH_TO_SAME_ROOM;
}
else {
throw new TypeError(where + 'DISPATCH_TO_SAME_ROOM must ' +
'be boolean or undefined. Found: ' +
settings.DISPATCH_TO_SAME_ROOM );
}
}
if ('string' !== typeof settings.EXECUTION_MODE) {
throw new TypeError(where + 'EXECUTION_MODE must be string. Found: ' +
settings.EXECUTION_MODE);
}
else {
if (settings.EXECUTION_MODE !== 'TIMEOUT' &&
settings.EXECUTION_MODE !== 'WAIT_FOR_N_PLAYERS') {
throw new Error(where + 'Invalid execution mode: ' +
settings.EXECUTION_MODE);
}
this.EXECUTION_MODE = settings.EXECUTION_MODE;
}
if ('undefined' !== typeof settings.START_DATE) {
if (this.EXECUTION_MODE === 'WAIT_FOR_N_PLAYERS') {
throw new Error(where + 'Execution mode ' + this.EXECUTION_MODE +
' cannot have a START_DATE');
}
d = new Date(settings.START_DATE);
if (isNaN(d.getTime())) {
throw new Error (where + 'START_DATE must be valid argument ' +
'for Date constructor. Found: ' +
settings.START_DATE);
}
if ('undefined' !== typeof settings.MAX_WAIT_TIME) {
throw new Error(where + 'Cannot define both MAX_WAIT_TIME and ' +
'START_DATE.');
}
this.START_DATE = settings.START_DATE;
}
else if ('undefined' !== typeof settings.MAX_WAIT_TIME) {
if ('number' === typeof settings.MAX_WAIT_TIME) {
checkPositiveInteger(settings, 'MAX_WAIT_TIME', where);
this.MAX_WAIT_TIME = settings.MAX_WAIT_TIME;
}
else {
throw new TypeError(where + 'MAX_WAIT_TIME must be ' +
'number or undefined. Found: ' +
settings.MAX_WAIT_TIME);
}
}
else {
if (this.EXECUTION_MODE === 'TIMEOUT') {
throw new Error(where + 'For EXECUTION_MODE="TIMEOUT" either ' +
'MAX_WAIT_TIME or START_DATE must be defined.');
}
}
assignIfFunction('ON_TIMEOUT', this, settings);
assignIfFunction('ON_TIMEOUT_SERVER', this, settings);
assignIfFunction('ON_OPEN', this, settings);
assignIfFunction('ON_CLOSE', this, settings);
assignIfFunction('ON_INIT', this, settings);
assignIfFunction('ON_CONNECT', this, settings);
assignIfFunction('ON_DISCONNECT', this, settings);
assignIfFunction('ON_DISPATCH', this, settings);
assignIfFunction('ON_DISPATCHED', this, settings);
assignIfFunction('ON_FAILED_DISPATCH', this, settings);
this.CHOSEN_TREATMENT = this.validateTreatment(settings.CHOSEN_TREATMENT,
where + ' CHOSEN_TREATMENT');
if ('undefined' !== typeof settings.PLAYER_SORTING) {
if ('string' === typeof settings.PLAYER_SORTING &&
!WaitingRoom.sortingCallbacks[settings.PLAYER_SORTING]) {
throw new TypeError(where + 'PLAYER_SORTING algorithm ' +
'not found: ' + settings.PLAYER_SORTING);
}
else if ('function' !== typeof settings.PLAYER_SORTING &&
null !== settings.PLAYER_SORTING) {
throw new TypeError(where + 'PLAYER_SORTING must be string, ' +
'function, null or undefined. Found: ' +
settings.PLAYER_SORTING);
}
this.PLAYER_SORTING = settings.PLAYER_SORTING;
}
if ('undefined' !== typeof settings.PLAYER_GROUPING) {
if ('function' !== typeof settings.PLAYER_GROUPING &&
null !== settings.PLAYER_GROUPING) {
throw new TypeError(where + 'PLAYER_GROUPING must be function, ' +
'null or undefined. Found: ' +
settings.PLAYER_GROUPING);
}
this.PLAYER_GROUPING = settings.PLAYER_GROUPING;
}
if ('undefined' !== typeof settings.PING_BEFORE_DISPATCH) {
if ('boolean' !== typeof settings.PING_BEFORE_DISPATCH) {
throw new TypeError(where + 'PING_BEFORE_DISPATCH must ' +
'be boolean or undefined. Found: ' +
settings.PING_BEFORE_DISPATCH);
}
this.PING_BEFORE_DISPATCH = settings.PING_BEFORE_DISPATCH;
}
if ('undefined' !== typeof settings.PING_MAX_REPLY_TIME) {
if ('number' === typeof settings.PING_MAX_REPLY_TIME) {
checkPositiveInteger(settings, 'PING_MAX_REPLY_TIME', where);
this.PING_MAX_REPLY_TIME = settings.PING_MAX_REPLY_TIME;
}
else {
throw new TypeError(where + 'PING_MAX_REPLY_TIME must be a ' +
'positive number or undefined. Found: ' +
settings.PING_MAX_REPLY_TIME);
}
}
if ('undefined' !== typeof settings.PING_DISPATCH_ANYWAY) {
if ('boolean' !== typeof settings.PING_DISPATCH_ANYWAY) {
throw new TypeError(where + 'PING_DISPATCH_ANYWAY must ' +
'be boolean or undefined. Found: ' +
settings.PING_DISPATCH_ANYWAY);
}
this.PING_DISPATCH_ANYWAY = settings.PING_DISPATCH_ANYWAY;
}
if ('undefined' !== typeof settings.PAGE_TITLE) {
if ('object' !== typeof settings.PAGE_TITLE) {
throw new TypeError(where + 'PAGE_TITLE must ' +
'be object or undefined. Found: ' +
settings.PAGE_TITLE);
}
if ('string' !== typeof settings.PAGE_TITLE.title) {
throw new TypeError(where + 'PAGE_TITLE.title must ' +
'be string. Found: ' +
settings.PAGE_TITLE.title);
}
this.PAGE_TITLE = settings.PAGE_TITLE;
}
if ('undefined' != typeof settings.ALLOW_PLAY_WITH_BOTS) {
this.ALLOW_PLAY_WITH_BOTS = settings.ALLOW_PLAY_WITH_BOTS;
}
else {
this.ALLOW_PLAY_WITH_BOTS = false;
}
if (this.ALLOW_PLAY_WITH_BOTS) {
this.node.on.data("PLAYWITHBOT", function (msg) {
var pid = msg.id;
that.channel.sysLogger.log("Bot dispatch started by player " + pid);
that.dispatchWithBots();
});
}
assignIfStringLikeObj('TEXTS', this, settings);
assignIfStringLikeObj('SOUNDS', this, settings);
// Executes ON_INIT, if found.
if (this.ON_INIT) this.ON_INIT(this);
};
/**
* ### WaitingRoom.validateTreatment
*
* Validates if a treatment parameter is found amongst existing options
*
* The action taken in case of failing to validate and the return value
* depend on the second parameter `doThrow`.
*
* @param {string|function} Optional. The name of the treatment
* (undefined is a valid value).
* @param {string|boolean} doThrow Optional. If truthy and the treatment
* does not pass validation, an error will be thrown. If doThrow is a
* string, it is used as the beginning of the sentence for
* the error message. Default: 'WaitingRoom.validateTreatment: treatment'
*
* @return {string|boolean} The validated treatment name|function.
*/
WaitingRoom.prototype.validateTreatment = function(treatment, doThrow) {
var t, err;
if ('undefined' !== typeof treatment) {
if (doThrow) {
if ('boolean' === typeof doThrow) {
doThrow = 'WaitingRoom.validateTreatment: treatment';
}
else if ('string' !== typeof doThrow) {
throw new TypeError('WaitingRoom.validateTreatment: doThrow ' +
'must be boolean, string or undefined. ' +
'Found: ' + doThrow);
}
}
if ('string' === typeof treatment) {
if (!WaitingRoom.treatmentCallbacks[treatment]) {
if (this.gameLevel) {
// Treatments are not yet parsed.
t = this.game.levels[this.gameLevel].settings.treatments;
}
else {
// Treatments are already parsed at this point.
t = this.game.settings;
}
if (!t[treatment]) err = ' not found: ' + treatment;
}
}
else if ('function' !== typeof treatment) {
err = 'must be string, function or ' +
'undefined. Found: ' + treatment;
}
}
if (doThrow) {
if (err) throw new Error(doThrow + err);
else return treatment;
}
return !err;
};
/**
* ## WaitingRoom.makeWidgetConfig
*
* Creates an object to configure the `WaitingRoom` widget
*
* @return {object} The configuration object
*/
WaitingRoom.prototype.makeWidgetConfig = function() {
return {
groupSize: this.GROUP_SIZE,
poolSize: this.POOL_SIZE,
disconnectIfNotSelected: this.DISCONNECT_IF_NOT_SELECTED,
nGames: this.N_GAMES,
startDate: this.START_DATE,
executionMode: this.EXECUTION_MODE,
maxWaitTime: this.MAX_WAIT_TIME,
onTimeout: this.ON_TIMEOUT,
chosenTreatment: this.CHOSEN_TREATMENT,
playWithBotOption: this.ALLOW_PLAY_WITH_BOTS
};
};
/**
* ## WaitingRoom.isRoomOpen
*
* Returns flag indicating whether the `WaitingRoom` is open
*
* @return {boolean} Flag indicating whether `this` is open
*/
WaitingRoom.prototype.isRoomOpen = function() {
return this.roomOpen;
};
/**
* ## WaitingRoom.closeRoom
*
* Changes state of `this` to closed
*
* @param {string} mod Optional. Modifies the behavior of closeRoom.
* Available options:
*
* - 'now': (default)
* - 'afterDispatch': true/false
*
* @param {mixed} param Optional. Parameter for modifier
*/
WaitingRoom.prototype.closeRoom = function(mod, param) {
if (mod && mod !== 'now') {
if (mod === 'afterDispatch') {
this.closeAfterDispatch = true;
return;
}
else {
throw new Error('WaitingRoom.closeRoom: unknown modifier: ' + mod);
}
}
this.roomOpen = false;
if (this.ON_CLOSE) this.ON_CLOSE(this);
};
/**
* ## WaitingRoom.openRoom
*
* Changes state of `this` to open
*/
WaitingRoom.prototype.openRoom = function() {
this.roomOpen = true;
if (this.ON_OPEN) this.ON_OPEN(this);
};
/**
* ### WaitingRoom.shouldDispatchMoreGames
*
* Checks whether another game can be dispatched
*/
WaitingRoom.prototype.shouldDispatchMoreGames = function() {
if (!this.roomOpen) return false;
if (this.N_GAMES) return this.numberOfDispatches < this.N_GAMES;
// TODO: Maybe check other conditions?
return true;
};
/**
* ### WaitingRoom.kickUnresponsivePlayers
*
* Pings all players and kicks those who fail to respond
*
* @param {function} callback Callback to be executed when pinging
* is completed with WaitingRoom as context.
* @param {object} options Options object. Accepted values:
*
* - callbackArgs: (array) arguments to be passed to the callback.
* Property pList is automatically added and contains the
* players that have responded to ping.
* - timeToWaitForPing: Wait time before kicking in milliseconds.
* Default: WaitingRoom.PING_MAX_REPLY_TIME || 3000
* - doCallback: if TRUE, the callback is executed also if some
* players are disconnected.
* Default: WaitingRoom.PING_DISPATCH_ANYWAY || false
*/
WaitingRoom.prototype.kickUnresponsivePlayers = function(callback, options) {
var cb, that;
var i, timeToWaitForPing;
var timeout, pingReturnedCb, doCallback, totPingReturned;
var players, p, pList, pLen;
var where;
where = 'WaitingRoom.kickUnresponsivePlayers';
that = this;
if (this.isPingInProgress) {
console.log('Warning: Suspending call to ' + where +
' because kicking is still in progress.');
this.suspendedPings.push([callback, options]);
return;
}
// Check parameters.
if ('function' !== typeof callback) {
throw new TypeError(where + ': callback must be function. Found: ' +
callback);
}
options = options || {};
timeToWaitForPing = options.timeToWaitForPing || this.PING_MAX_REPLY_TIME;
if ('number' !== typeof timeToWaitForPing || timeToWaitForPing < 1) {
throw new TypeError(where + ': timeToWaitForPing must be ' +
'a positive number or undefined. Found: ' +
timeToWaitForPing);
}
if ('undefined' !== typeof options.doCallback) {
doCallback = !!options.doCallback;
}
else {
doCallback = this.PING_DISPATCH_ANYWAY;
}
// Lock this function.
this.isPingInProgress = true;
// Setup variables for pinging all players.
// Manual copy of player list.
players = this.clients.player.db;
pList = new PlayerList();
pLen = players.length;
// Need to update pcounter because we use .insert below.
pList.pcounter = pLen;
// Create callback that will be executed if all players return from PING.
cb = function() {
var pSize;
// When done, unlock function.
that.isPingInProgress = false;
pSize = pList.size();
// Call the callback: if required so and at least one player
// is still connected, or if all players returned the PING.
if ((doCallback && pSize) || (pSize === pLen)) {
// Add list of pinged players to dispatch options.
options.callbackArgs.pList = pList;
callback.call(that, options.callbackArgs);
}
else {
console.log('Not enough players:' + pList.size(), pLen);
}
// Execute suspended calls.
if (that.suspendedPings.length > 0) {
// Cancel suspended pings if waiting room is closed.
if (!that.shouldDispatchMoreGames()) {
console.log('Warning: room is closed. Clearing previously ' +
'suspended pings.');
that.suspendedPings = [];
}
else if (that.clients.player.size() < that.POOL_SIZE) {
console.log('Warning: not enough players now. ' +
'Aborting previously suspended pings.');
that.suspendedPings = [];
}
else {
that.kickUnresponsivePlayers.apply(that,
that.suspendedPings.pop());
}
}
};
// Count how many pings returned.
totPingReturned = 0;
// Callback to execute when a ping-back is returned.
pingReturnedCb = function() {
totPingReturned++;
if (totPingReturned === pLen) {
clearTimeout(timeout);
cb();
}
};
// Start pinging.
for (i = 0; i < players.length; ++i) {
p = players[i];
// Call .insert, not .add (saves some operations).
pList.insert(p);
console.log('Pinging player ' + p.id, timeToWaitForPing);
that.node.get('PING', pingReturnedCb, p.id, {
timeout: timeToWaitForPing,
executeOnce: true,
// The callback on failure.
timeoutCb: (function(p, i) {
return function() {
// This marks the PING failed.
pList.remove(p.id);
console.log('Player %s unresponsive. Kicking.', p.id);
that.node.disconnectClient(p);
};
})(p, i)
});
}
// At the end of this timeout, we will check how many players
// have responded. If all players have responded (or doCallback = TRUE)
// the callback is executed. In any case, we set pingInProgress = FALSE.
timeout = setTimeout(cb, timeToWaitForPing + 500);
};
/**
* ## WaitingRoom.dispatch
*
* Initiates the start of the game
*
* It is assumed that it is called only after connected players > POOL_SIZE.
*
* @param {object} opts Optional. Configuration options for the method.
* Available options:
*
* - numberOfGames: sets the number of games to dispatch
* - closeAfterDispatch: closes the waiting room after this dispatch
* - msg: dispatch-message to send to all players. Default:
* { action: 'AllPlayersConnected', exit: 0 }
*/
WaitingRoom.prototype.dispatch = (function() {
var doDispatch, where, parseGroupSizeOptions, checkShouldDispatch;
where = 'WaitingRoom.dispatch: ';
checkShouldDispatch = function() {
// Check if we are still allowed to dispatch games.
if (!this.shouldDispatchMoreGames()) {
this.channel.sysLogger.log(where + ' waiting room is closed. ' +
'Dispatches: ' +
this.numberOfDispatches + '/' +
this.N_GAMES +