-
Notifications
You must be signed in to change notification settings - Fork 7
/
GameRoom.js
1804 lines (1563 loc) · 57.4 KB
/
GameRoom.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
/**
* # Game Room
* Copyright(c) 2020 Stefano Balietti <[email protected]>
* MIT Licensed
*
* Game room representation
*
* http://www.nodegame.org
*/
"use strict";
// ## Global scope
module.exports = GameRoom;
const path = require('path');
const fs = require('fs-extra');
const ngc = require('nodegame-client');
const GameStage = ngc.GameStage;
const stepRules = ngc.stepRules;
const publishLevels = ngc.constants.publishLevels;
const DONE = ngc.constants.stageLevels.DONE;
const J = require('JSUS').JSUS;
const Room = require('./Room');
GameRoom.prototype.__proto__ = Room.prototype;
GameRoom.prototype.constructor = GameRoom;
/**
* ## GameRoom constructor
*
* Creates a new game room
*
* @param {object} config Configuration options
*
* @see Room
*/
function GameRoom(config) {
var that, node, settings;
Room.call(this, 'Game', config);
if (!this.logicPath) this.logicPath = './rooms/game.room';
if (config.treatmentName && 'string' !== typeof config.treatmentName) {
throw new TypeError('GameRoom: config.treatmentName must be ' +
'undefined or string. Found: ' +
config.treatmentName);
}
if (config.runtimeConf && 'object' !== typeof config.runtimeConf) {
throw new TypeError('GameRoom: config.runtimeConf must be object. ' +
'Found: ' + config.runtimeConf);
}
/**
* ### GameRoom.treatmentName
*
* The name of the treatment played, or 'standard' if not defined
*/
this.treatmentName = config.treatmentName || 'standard';
settings = this.gameLevel ?
this.game.levels[this.gameLevel].settings : this.game.settings;
if (!settings[this.treatmentName]) {
throw new Error('GameRoom: game ' + this.gameName + ' treatment ' +
'not found: ' + this.treatmentName);
}
/**
* ### GameRoom.gameTreatment
*
* Actual settings for current game based on treatment and runtime conf
*
* @see GameRoom.runtimeConf
* @see GameRoom.setupGame
*/
this.gameTreatment = settings[this.treatmentName];
if (this.runtimeConf) J.mixin(this.gameTreatment, this.runtimeConf);
/**
* ### GameRoom.clientTypes
*
* Client types for the room (level checked)
*/
this.clientTypes = this.gameLevel ?
this.game.levels[this.gameLevel].clientTypes : this.game.clientTypes;
/**
* ### GameRoom.dataDir
*
* Path to the data directory
*
* @see ServerChannel.getGameDir
*/
if (config.ownDataDir || this.channel.roomOwnDataDir) {
this.dataDir = path.resolve(this.channel.getGameDir(),
'data', this.name);
// TODO: warning if it already exists.
fs.ensureDir(this.dataDir);
}
else {
this.dataDir = path.resolve(this.channel.getGameDir(), 'data');
}
// Configure disconnect/reconnect policy.
that = this;
node = this.node;
/**
* ## GameRoom.wrongNumOfPlayers
*
* Default listener for `onWronPlayerNum` on logics
*
* This listener is added as default stager property `onWrongPlayerNum`
* to all `logic` client types by method `GameRoom.getClientType`,
* if no other is already defined.
*
* The listener is invoked when there is a "wrong" number of players.
* The number of players is "wrong" if it has been defined any
* min|max|exactPlayers property in current game step.
*
* Default behavior:
*
* 1 - Immediately pauses all connected players. A message is displayed
* with information.
* 2 - A timer is started for the value specified in settings.WAIT_TIME,
* or 30 seconds otherwise.
* 3 - If timer expires, game is resumed and, if a custom callback is
* is defined, it is executed.
*
* The listener is then invoked with `node.game` context.
*
* @param {string} type The type of "wrong" number: 'min', 'max', 'exact'
* @param {function} customCb Optional. A callback to be executed in
* in case the timer expires.
* @param {object} player Optional. The player object that triggered
* the listener by either connecting or disconnecting (if available)
*
* @see GameRoom.correctNumOfPlayersAgain
* @see GameRoom.getClientType
*/
this.wrongNumOfPlayers = function(type, customCb, player) {
var node;
var waitTime, msgToClients;
node = this.node;
// If the default value (30) is changed the documentation
// on the wiki needs to be updated too (Disconnections page).
waitTime = 'number' === typeof this.settings.WAIT_TIME ?
this.settings.WAIT_TIME : 30;
if (type === 'min') {
msgToClients = this.settings.WAIT_TIME_TEXT ||
'One or more players disconnected. We are waiting ' +
'<span id="ng_pause_timer">' + waitTime +
'</span> seconds to see if they reconnect.';
node.warn('warning: not enough players!!');
}
else if (type === 'max') {
msgToClients = this.settings.WAIT_TIME_TEXT ||
'Too many players connected. We are waiting ' +
'<span id="ng_pause_timer">' + waitTime + '</span> ' +
'seconds to see if the right number of players is restored.';
node.warn('warning: too many players!!');
}
else {
msgToClients = this.settings.WAIT_TIME_TEXT ||
'Wrong number of connected players detected. We are waiting' +
'<span id="ng_pause_timer">' + waitTime + '</span> ' +
'seconds to see if the right number of players is restored.';
node.warn('warning: wrong number of players!!');
}
if (!node.game.isPaused()) {
// Pause connected players.
node.remoteCommand('pause', 'ROOM', msgToClients);
node.game.pause();
}
that.countdown = setTimeout(function() {
node.warn('Disconnection Countdown fired: ' + node.nodename);
node.remoteCommand('resume', 'ROOM');
node.game.resume();
if (customCb) customCb.call(node.game, player);
setTimeout(function() {
if (node.game.shouldStep()) node.game.step();
}, 100);
}, waitTime * 1000);
};
/**
* ## GameRoom.correctNumOfPlayersAgain
*
* Listener invoked at any time the correct number of players is recovered
*
* The number of players is "wrong" if it has been defined any
* min|max|exactPlayers property in current game step.
*
* Default behavior:
*
* 1 - Immediately resumes all connected players that have been
* paused by callback `wrongNumOfPlayers`
* 2 - The timer defined by `wrongNumOfPlayers` is cleared
* 3 - If any custom callback was defined, it gets executed
*
* This listener is added as default stager property `onCorrectPlayerNum`
* to all `logic` client types by method `GameRoom.getClientType`,
* if no othe is already defined.
*
* The listener is then invoked with `node.game` context.
*
* @param {string} type The type of "wrong" number: 'min', 'max', 'exact'
* @param {function} customCb Optional. A callback to be executed in
* in case the timer expires.
* @param {object} player Optional. The player object that triggered
* the listener by either connecting or disconnecting (if available)
*
* @see GameRoom.wrongNumOfPlayers
* @see GameRoom.getClientType
*/
this.correctNumOfPlayersAgain = function(type, customCb, player) {
var node;
node = this.node;
if (type === 'min') {
node.warn('warning: enough players again!!');
}
else if (type === 'max') {
node.warn('warning: number of players below maximum again!!');
}
else {
node.warn('warning: correct number of players again!!');
}
// Delete countdown to terminate the game.
clearTimeout(that.countdown);
that.countdown = null;
// Player can reconnect during the countdown or after.
// If after, then the game won't be paused.
if (node.game.isPaused()) {
node.game.resume();
// Resume other players.
setTimeout(function() {
node.game.pl.each(function(p) {
if (player.id !== p.id) {
node.remoteCommand('resume', p.id);
}
});
}, 100);
}
if (customCb) customCb.call(node.game, player);
};
// Logs connections.
node.on.pconnect(function(p) {
that.logClientEvent(p, 'connect');
});
// Some players are already there, and do not fire pconnect.
node.once('INIT', function() {
// Avoid the whole loop.
if (!that.logClients) return;
node.game.pl.each(function(p) {
that.logClientEvent(p, 'connect');
});
});
// Logs disconnection.
node.on.pdisconnect(function(p) {
console.log('Disconnection: ' + p.id + ' (server stage: ' +
node.player.stage + ')');
that.logClientEvent(p, 'disconnect');
});
// Player reconnecting.
// This function is called first, and it invokes any
// min/max/exact handler accordingly.
node.on.preconnect(function(p) {
var code, discoStage, discoStageLevel, curStage, reconCb, res;
var compareSteps, reconOptions;
var milliseconds, resetTime;
var setup, msgs;
that.logClientEvent(p, 'reconnect');
node.warn('Oh...somebody reconnected!', p);
code = that.channel.registry.getClient(p.id);
discoStage = code.disconnectedStage;
curStage = node.game.getCurrentGameStage();
compareSteps = GameStage.compare(discoStage, curStage);
// Check if only within stage reconnections are allowed.
if (that.sameStepReconnectionOnly && compareSteps) {
node.err('GameRoom: player reconnected from another step. ' +
'Not allowed. Player: ' + p.id);
disposeClient(node, p);
return;
}
// Setup client.
that.setupClient(p.id);
if (code.lang.name !== 'English') {
// If lang is different from Eng, remote setup it.
// TRUE: sets also the URI prefix.
node.remoteSetup('lang', p.id, [code.lang, true]);
}
// Start the game on the reconnecting client.
// Need to give step: false, we just init it.
node.remoteCommand('start', p.id, { step: false });
// Create the reconnection options object.
reconOptions = { plot: {} };
// Roles/partner are assigned in this step if matcher is truthy.
if (node.game.getProperty('matcher')) {
// Check if had role and partner.
// Get old setup for re-connecting player.
setup = node.game.matcher.getSetupFor(p.id);
if (setup) {
if (setup.role) reconOptions.plot.role = setup.role;
if (setup.partner) reconOptions.plot.partner = setup.partner;
}
}
// Mark the state as DONE, if this is the case.
// Important!
// IF the client was DONE, and waiting for other players,
// and the STEP command is sent right before its disconnection,
// THEN the willBeDone option is applied to the next step, which
// is the wrong thing to do. So we add willBeDone only on same
// stage, or if the client is ahead.
discoStageLevel = code.disconnectedStageLevel;
if (compareSteps <= 0 && discoStageLevel === DONE) {
reconOptions.willBeDone = true;
// Temporarily remove the done callback.
reconOptions.plot.done = null;
reconOptions.plot.autoSet = null;
}
else {
// Resend messages
}
// Sets the timer on reconnecting client if milliseconds is found.
milliseconds = node.game.timer.milliseconds;
if ('number' === typeof milliseconds) {
// Time left to play in stage.
resetTime = Math.max(milliseconds -
node.timer.getTimeSince('step', true), 0);
reconOptions.plot.timer = resetTime;
}
reconCb = this.plot.getProperty(curStage, 'reconnect');
if (reconCb === true) {
// Get messages sent to client in current step.
if (node.socket.journal.to[p.id]) {
msgs = node.socket.journal.to[p.id].fetch();
if (msgs.length) setup.msgs = msgs;
}
}
else if ('function' === typeof reconCb) {
// Res contains the reconnect options for the step,
// or false to abort reconnection.
res = reconCb.call(this, code, reconOptions);
if (res === false) {
node.warn('Reconnect Cb returned false');
disposeClient(node, p);
return;
}
}
// Add player to player list.
node.game.pl.add(p);
// Start the step on reconnecting client.
// Unless differently specified by the reconnect callback,
// target step is what is more advanced between the logic step,
// and the step when the client disconnected.
if (!reconOptions.targetStep) {
// console.log(compareSteps, curStage, code.stage);
// -1 means first param is ahead in game stage.
// compareSteps = GameStage.compare(code.stage, curStage);
if (compareSteps < 0) reconOptions.targetStep = discoStage;
else reconOptions.targetStep = curStage;
}
node.remoteCommand('goto_step', p.id, reconOptions);
// See if we have enough players now.
res = node.game.sizeManager.changeHandler('pconnect', p);
// If we are still missing more players pause reconnecting player.
if (!res) node.remoteCommand('pause', p.id);
});
// Create sequence in the stager.
(() => {
let gameStages;
// Get the right stages.
if (this.gameLevel) {
gameStages = this.game.levels[this.gameLevel].gameStages;
}
else {
gameStages = this.game.gameStages;
}
// Setup is not cloned.
let mySetup = this.game.setup;
// Settings are cloned.
let gameSettings = J.clone(this.gameTreatment);
let stager = ngc.getStager();
if (gameStages.length === 2) {
console.log('***v7 deprecation warning: game.stages function ' +
'should accept 5 parameters: ' +
'treatmentName, settings, stager, setup, gameRoom');
gameStages(stager, gameSettings);
}
else {
gameStages(this.treatmentName, gameSettings, stager, mySetup, this);
}
this.stager = stager;
})();
this.registerRoom();
}
// ## GameRoom static functions
/**
* ### GameRoom.checkParams
*
* Type-check the parameters given to setup/start/pause/resume/stopGame
*
* @param {boolean} doLogic If TRUE, sends a command to the logic as well
* @param {array|string} clientList List of client IDs to which to send the
* command, or one of the following strings:
* 'all' (all clients), 'players' (all players), 'admins' (all admins).
* @param {boolean} force If TRUE, skip the check
*
* @return {null|string} NULL for valid parameters, error string for bad ones.
*/
GameRoom.checkParams = function(doLogic, clientList, force) {
if ('boolean' !== typeof doLogic && 'undefined' !== typeof doLogic) {
return 'doLogic must be boolean or undefined';
}
if (!J.isArray(clientList) &&
('string' !== typeof clientList ||
(clientList !== 'all' &&
clientList !== 'players' &&
clientList !== 'admins')) &&
'undefined' !== typeof clientList) {
return "clientList must be array, 'all', 'players', 'admins' " +
'or undefined';
}
if ('boolean' !== typeof force && 'undefined' !== typeof force) {
return 'force must be boolean or undefined';
}
return null;
};
// ## GameRoom methods
/**
* ### GameRoom.sendRemoteCommand
*
* Utility method for sending a remote command to given recipients
*
* @param {string} command The command to send
* @param {array|string} clientList List of client IDs to which to send the
* command, or one of the following strings:
* 'all' (all clients), 'players' (all players), 'admins' (all admins)
*
* @private
*/
GameRoom.prototype.sendRemoteCommand = function(command, clientList) {
var node;
node = this.node;
// TODO: Don't send to logic!
if (J.isArray(clientList)) {
node.remoteCommand(command, clientList);
}
else {
if (clientList === 'all' || clientList === 'players') {
this.clients.player.each(function(p) {
node.remoteCommand(command, p.id);
});
}
if (clientList === 'all' || clientList === 'admins') {
this.clients.admin.each(function(p) {
node.remoteCommand(command, p.id);
});
}
}
};
/**
* ### GameRoom.setupGame
*
* Setups logic and clients in the room
*
* @param {object} mixinConf Optional. Additional options to pass to the node
* instance of the room. Overrides the returned game configuration from the
* require statement.
* @param {boolean} doLogic Optional. If TRUE, sets up the logic as well.
* Default: TRUE.
* @param {array|string} clientList Optional. List of client IDs to set up,
* or one of the following strings:
* 'all' (all clients), 'players' (all players), 'admins' (all admins).
* Default: 'players'.
* @param {boolean} force Optional. If TRUE, skip the check. Default: FALSE.
*
* @see GameRoom.runtimeConf
*/
GameRoom.prototype.setupGame = function(mixinConf, doLogic, clientList, force) {
var rc;
// Check parameters.
rc = GameRoom.checkParams(doLogic, clientList, force);
if (rc !== null) throw new TypeError('GameRoom.setupGame: ' + rc + '.');
if (mixinConf && 'object' !== typeof mixinConf) {
throw new TypeError('GameRoom.setupGame: mixinConf must be object or ' +
'undefined.');
}
if ('undefined' !== typeof clientList &&
!J.isArray(clientList) &&
clientList !== 'all' &&
clientList !== 'players' &&
clientList !== 'admins') {
throw new TypeError("GameRoom.setupGame: clientList must be " +
"undefined, array, or one of 'all', 'players' " +
" or 'admins'");
}
// Apply defaults.
if ('undefined' === typeof doLogic) doLogic = true;
if ('undefined' === typeof clientList) clientList = 'players';
if ('undefined' === typeof force) force = false;
// Set up logic.
if (doLogic) setupLogic.call(this, mixinConf);
// At this point clientList should be an array of client IDs.
setupClients.call(this, clientList, mixinConf);
};
/**
* ### GameRoom.startGame
*
* Starts the game for the logic and/or other clients
*
* @param {boolean} doLogic Optional. If TRUE, sends a start command to the
* logic as well. Default: TRUE.
* @param {array|string} clientList Optional. List of client IDs to which to
* send the start command, or one of the following strings:
* 'all' (all clients), 'players' (all players), 'admins' (all admins).
* Default: 'all'.
* @param {boolean} force Optional. If TRUE, skip the startable check.
* Default: FALSE.
*/
GameRoom.prototype.startGame = function(doLogic, clientList, force) {
var node;
var rc;
node = this.node;
// Check parameters.
rc = GameRoom.checkParams(doLogic, clientList, force);
if (rc !== null) throw new TypeError('GameRoom.startGame: ' + rc + '.');
// Apply defaults.
if ('undefined' === typeof doLogic) doLogic = true;
if ('undefined' === typeof clientList) clientList = 'all';
if ('undefined' === typeof force) force = false;
// Check startability.
if (!force && !node.game.isStartable()) {
this.channel.sysLogger.log(
'GameRoom.startGame: game cannot be started.', 'warn');
return;
}
// Start.
if (doLogic) node.game.start();
this.sendRemoteCommand('start', clientList);
};
/**
* ### GameRoom.pauseGame
*
* Pauses the game for the logic and/or other clients
*
* @param {boolean} doLogic Optional. If TRUE, sends a pause command to the
* logic as well. Default: TRUE.
* @param {array|string} clientList Optional. List of client IDs to which to
* send the pause command, or one of the following strings:
* 'all' (all clients), 'players' (all players), 'admins' (all admins).
* Default: 'all'.
* @param {boolean} force Optional. If TRUE, skip the pauseable check.
* Default: FALSE.
*/
GameRoom.prototype.pauseGame = function(doLogic, clientList, force) {
var node;
var rc;
node = this.node;
// Check parameters.
rc = GameRoom.checkParams(doLogic, clientList, force);
if (rc !== null) throw new TypeError('GameRoom.pauseGame: ' + rc + '.');
// Apply defaults.
if ('undefined' === typeof doLogic) doLogic = true;
if ('undefined' === typeof clientList) clientList = 'all';
if ('undefined' === typeof force) force = false;
// Check pausability.
if (!force && !node.game.isPausable()) {
this.channel.sysLogger.log(
'GameRoom.pauseGame: game cannot be paused.', 'warn');
return;
}
// Pause.
if (doLogic) node.game.pause();
this.sendRemoteCommand('pause', clientList);
};
/**
* ### GameRoom.resumeGame
*
* Resumes the game for the logic and/or other clients
*
* @param {boolean} doLogic Optional. If TRUE, sends a resume command to the
* logic as well. Default: TRUE.
* @param {array|string} clientList Optional. List of client IDs to which to
* send the resume command, or one of the following strings:
* 'all' (all clients), 'players' (all players), 'admins' (all admins).
* Default: 'all'.
* @param {boolean} force Optional. If TRUE, skip the resumeable check.
* Default: FALSE.
*/
GameRoom.prototype.resumeGame = function(doLogic, clientList, force) {
var node;
var rc;
node = this.node;
// Check parameters.
rc = GameRoom.checkParams(doLogic, clientList, force);
if (rc !== null) throw new TypeError('GameRoom.resumeGame: ' + rc + '.');
// Apply defaults.
if ('undefined' === typeof doLogic) doLogic = true;
if ('undefined' === typeof clientList) clientList = 'all';
if ('undefined' === typeof force) force = false;
// Check resumability.
if (!force && !node.game.isResumable()) {
this.channel.sysLogger.log(
'GameRoom.resumeGame: game cannot be resumed.', 'warn');
return;
}
// Resume.
if (doLogic) node.game.resume();
this.sendRemoteCommand('resume', clientList);
};
/**
* ### GameRoom.stopGame
*
* Stops the game for the logic and/or other clients
*
* @param {boolean} doLogic Optional. If TRUE, sends a stop command to the logic
* as well. Default: TRUE.
* @param {array|string} clientList Optional. List of client IDs to which to
* send the stop command, or one of the following strings:
* 'all' (all clients), 'players' (all players), 'admins' (all admins).
* Default: 'all'.
* @param {boolean} force Optional. If TRUE, skip the stopable check.
* Default: FALSE.
*/
GameRoom.prototype.stopGame = function(doLogic, clientList, force) {
var node;
var rc;
node = this.node;
// Check parameters.
rc = GameRoom.checkParams(doLogic, clientList, force);
if (rc !== null) throw new TypeError('GameRoom.stopGame: ' + rc + '.');
// Apply defaults.
if ('undefined' === typeof doLogic) doLogic = true;
if ('undefined' === typeof clientList) clientList = 'all';
if ('undefined' === typeof force) force = false;
// Check stoppability.
if (!force && !node.game.isStoppable()) {
this.channel.sysLogger.log(
'GameRoom.stopGame: game cannot be stopped.', 'warn');
return;
}
// Stop.
if (doLogic) node.game.stop();
this.sendRemoteCommand('stop', clientList);
};
/**
* ### GameRoom.getClientType
*
* Loads a specified client type
*
* @param {string} type The name of the client type
* @param {object} mixinConf Optional. Additional configuration options
* that will be mixed-in with the final game object
* @param {NodeGameClient} gameNode Optional. The nodeGame client
* object that this client type will configure (only for local clients,
* such as bots and logics).
*
* @return {object} The built client type
*/
GameRoom.prototype.getClientType = function(type, mixinConf, gameNode) {
var game, settings, stager, setup;
var properties, stepRule;
if (!this.clientTypes[type]) {
throw new Error('GameRoom.getClientType: unknown type: ' + type);
}
if (mixinConf && 'object' !== typeof mixinConf) {
throw new Error('GameRoom.getClientType: mixinConf must ' +
'be object. Found: ' + mixinConf);
}
// ORIGINAL CODE
// Get the right stager.
// if (this.gameLevel) {
// stager = ngc.getStager(
// this.game.levels[this.gameLevel].stager.getState());
// }
// else {
// stager = ngc.getStager(this.game.stager.getState());
// }
// experimental.
////////////////
// Insulates the stager across client types.
stager = ngc.getStager(this.stager.getState());
// Start adding default properties by client type.
stepRule = stager.getDefaultStepRule();
properties = stager.getDefaultProperties();
// For both logic and other client types.
if ('undefined' === typeof properties.timer) {
stager.setDefaultProperty('timer', function() {
var timer, stepId;
stepId = this.getCurrentStep().id;
timer = this.settings.TIMER[stepId];
// If it is a function must be executed.
// Other values will be parsed later.
if ('function' === typeof timer) timer = timer.call(this);
return timer || null;
});
}
if ('undefined' === typeof properties.onWrongNumOfPlayers) {
stager.setDefaultProperty('onWrongPlayerNum',
this.wrongNumOfPlayers);
}
if ('undefined' === typeof properties.onCorrectNumOfPlayers) {
stager.setDefaultProperty('onCorrectPlayerNum',
this.correctNumOfPlayersAgain);
}
// Set different defaults for logic and other client types.
if (type === 'logic') {
if ('undefined' === typeof properties.publishLevel) {
properties.publishLevel = 0;
}
if ('undefined' === typeof properties.syncStepping) {
properties.syncStepping = true;
}
if ('undefined' === typeof properties.autoSet) {
properties.autoSet = false;
}
if (stepRule === stepRules.SOLO) {
stager.setDefaultStepRule(stepRules.OTHERS_SYNC_STEP);
}
if ('undefined' === typeof properties.timeup) {
// If moved into another file update documentation page.
stager.setDefaultProperty('timeup', function() {
var conf, gameStage;
gameStage = this.getCurrentGameStage();
conf = this.plot.getProperty(gameStage, 'pushClients');
if (!conf) return;
this.pushManager.startTimer(conf);
});
}
}
else {
if ('undefined' === typeof properties.publishLevel) {
properties.publishLevel = publishLevels.REGULAR;
}
if ('undefined' === typeof properties.autoSet) {
properties.autoSet = true;
}
if (stepRule === stepRules.SOLO) {
stager.setDefaultStepRule(stepRules.WAIT);
}
if ('undefined' === typeof properties.timeup) {
stager.setDefaultProperty('timeup', function() {
this.node.done();
});
}
}
// Setup is not cloned.
setup = this.game.setup;
// Settings are cloned.
settings = J.clone(this.gameTreatment);
// Experimental code.
// Shared settings for all stager requires (for all client types).
(() => {
let treatmentName = this.treatmentName;
let node = gameNode;
let gameRoom = this;
// stager.__shared = { settings, treatmentName, setup, gameRoom, node };
stager.share({ settings, treatmentName, setup, gameRoom, node });
})();
game = this.clientTypes[type](this.treatmentName, settings, stager,
setup, this, gameNode);
// If nothing is returned creates the obj.
if ('undefined' === typeof game) {
game = { plot: stager.getState() };
}
else if ('object' !== typeof game) {
throw new Error('GameRoom.getClientType: room ' + this.name +
': type "' + type + '" must return undefined or a ' +
'valid game object. Found: ' + game);
}
// Add defaults from setup.
if ('undefined' === typeof game.debug) game.debug = setup.debug;
if ('undefined' === typeof game.verbosity) game.verbosity = setup.verbosity;
if (type === 'logic') {
// Logic gets room name.
if ('undefined' === typeof game.nodename) game.nodename = this.name;
if ('undefined' === typeof game.verbosity) {
game.verbosity = ngc.constants.verbosity_levels.warn;
}
}
// Add window setup if not logic or bot.
if (type !== 'bot' && type !== 'logic') {
if ('undefined' === typeof game.window) game.window = setup.window;
}
// Add treatment settings.
game.settings = settings;
// Mixin-in nodeGame options.
if (mixinConf) J.mixin(game, mixinConf);
// Here we just add the frame property where missing.
preprocessGame(this, type, game);
return game;
};
/**
* ## GameRoom.setupClient
*
* Setups a client based on its id
*
* Retrieves the client object, checks its client type, and run the
* appropriate setup command depending if the client it is a bot or
* a remote client.
*
* @param {string} clientId The id of the client
* @param {object} mixinConf Optional. Additional configuration options
* @param {object} cache Optional. A cache object from where retrieving
* client types
*
* @return {boolean} TRUE on success
*
* @see GameRoom.getClientType
*/
GameRoom.prototype.setupClient = function(clientId, mixinConf, cache) {
var clientObj, gameNode, type;
var game;
clientObj = tryToGetClient.call(this, clientId);
if (!clientObj) {
this.channel.sysLogger.log('GameRoom.setupClient: client not found: ' +
clientId, 'error');
return;
}
// Fake cache.
cache = cache || {};
// See if the client is local or remote.
gameNode = this.channel.bots[clientId];
// Client type.
type = clientObj.clientType;
// Get the client type, check cache (bots are never cached).
if (!gameNode && cache[type]) {
game = cache[type];
}
else {
game = this.getClientType(type, mixinConf, gameNode);
mixinGameMetadata.call(this, game);
cache[type] = game;
}
// Setup the client.
// Local client (bot).
if (gameNode) {
// Can't remoteSetup here because serializing the plot methods
// would make them lose their context (node etc.).
if (gameNode.game.isStoppable()) gameNode.game.stop();
gameNode.setup('nodegame', game);
}
// Remote client.
else {
this.node.remoteCommand('stop', clientId);
this.node.remoteSetup('nodegame', clientId, game);
}
return true;
};
/**
* ## GameRoom.getMemoryDb
*
* Returns all items in the database of the logic
*
* @return {array} The database of the logic
*
* @see GameRoom.node
*/
GameRoom.prototype.getMemoryDb = function() {
return this.node ? this.node.game.memory.db : [];
};