/
Timer.js
1950 lines (1747 loc) · 59.2 KB
/
Timer.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
/**
* # Timer
* Copyright(c) 2021 Stefano Balietti
* MIT Licensed
*
* Timing-related utility functions
*/
(function(exports, parent) {
"use strict";
// ## Global scope
var J = parent.JSUS;
// Exposing Timer constructor
exports.Timer = Timer;
/**
* ## Timer constructor
*
* Creates a new instance of Timer
*
* @param {NodeGameClient} node. A valid NodeGameClient object
* @param {object} settings Optional. A configuration object
*/
function Timer(node, settings) {
var that;
this.node = node;
this.settings = settings || {};
/**
* ### Timer.timers
*
* Collection of currently active timers created by `Timer.createTimer`
* @see Timer.createTimer
*/
this.timers = {};
/**
* ### Timer._stepTimers
*
* Collection of temporary timers created in current step
*
* All references are cleared after each step.
*
* Notice: might not be updated, if user manually destroys a timer.
*
* @private
*/
this._stepTimers = [];
/**
* ### Timer._stageTimers
*
* Collection of temporary timers created in current stage
*
* All references are cleared after each stage.
*
* Notice: might not be updated, if user manually destroys a timer.
*
* @private
*/
this._stageTimers = [];
/**
* ### Timer.timestamps
*
* Named timestamp collection
*
* Maps names to numbers (milliseconds since epoch)
*
* @see Timer.setTimestamp
* @see Timer.getTimestamp
* @see Timer.getTimeSince
*/
this.timestamps = {};
/**
* ### Timer.pausedTimestamps
*
* Collection of timestamps existing while game is paused
*
* Will be cleared on resume
*
* @see Timer.setTimestamp
* @see Timer.getTimestamp
* @see Timer.getTimeSince
*/
this._pausedTimestamps = {};
/**
* ### Timer.cumulPausedTimestamps
*
* List of timestamps that had a paused time in between
*
* Persists after resume
*
* @see Timer.setTimestamp
* @see Timer.getTimestamp
* @see Timer.getTimeSince
*/
this._cumulPausedTimestamps = {};
/**
* ### Timer._effectiveDiffs
*
* List of time differences between timestamps minus paused time
*
* Persists after resume
*
* @see Timer.setTimestamp
* @see Timer.getTimestamp
* @see Timer.getTimeSince
*/
this._effectiveDiffs = {};
that = this;
this.node.on('PAUSED', function() {
var i, ts;
ts = that.getTimestamp('paused');
for (i in that.timestamps) {
if (that.timestamps.hasOwnProperty(i)) {
that._pausedTimestamps[i] = ts;
}
}
});
this.node.on('RESUMED', function() {
var i, time, pt, cpt, pausedTime;
pt = that._pausedTimestamps;
cpt = that._cumulPausedTimestamps;
time = J.now();
for (i in pt) {
if (pt[i] && pt.hasOwnProperty(i)) {
pausedTime = time - pt[i];
if (!cpt[i]) cpt[i] = pausedTime;
else cpt[i] += pausedTime;
}
}
that._pausedTimestamps = {};
});
/**
* ### Timer.random | Timer.wait
*
* Setups an object exposing multiple random handlers.
*
* Respects pausing / resuming. If the game has not started yet, it waits
* until the `PLAYING` event is fired to start the random handler.
*
* Additional parameters are passed to each handler accordingly.
*
* @param {number} maxWait Optional. The maximum time (in milliseconds)
* to wait before emitting the event. Default: 5000
* @param {number} minWait Optional. The minimum time (in milliseconds)
* to wait before executing the callback. Default: 1000
*
* @return {object} Object containing different random handlers
*
* ### Timer.random.done
*
* Randomly calls `node.done`
*
* ### Timer.random.emit
*
* Randomly emits an event
*
* @param {string} event The name of the event
*
* ### Timer.random.exec
*
* Randomly executs a function
*
* @param {function} func The callback function to execute
* @param {object|function} ctx Optional. The context of execution of
* of the callback function. Default node.game
*
* @see randomFire
*/
(function(that) {
var _minWait, _maxWait, _prob;
var args, i, len;
// Init certain probability.
_prob = 1;
/**
* ### randomFire
*
* Common handler for firing/emitting
*
* @param {string} method The name of the method invoking randomFire
* @param {string|function} hook The function to call or the
* event to emit
* @param {boolean} emit TRUE, if it is an event to emit
* @param {object|function} ctx Optional. The context of
* execution for the function
*/
function randomFire(method, hook, emit, ctx, args) {
var that;
var waitTime;
var callback;
var timerObj;
var tentativeName;
that = this;
if ('undefined' === typeof _maxWait) {
_maxWait = 5000;
}
else if ('number' !== typeof _maxWait) {
resetWaits();
throw new TypeError('Timer.' + method + ': maxWait must ' +
'be number or undefined. Found: ' +
_maxWait);
}
if ('undefined' === typeof _minWait) {
_minWait = _maxWait < 1000 ? 0 : 1000;
}
else if ('number' !== typeof _minWait) {
resetWaits();
throw new TypeError('Timer.' + method + ': minWait must ' +
'be number or undefined. Found: ' +
_minWait);
}
waitTime = J.randomInt(_minWait, _maxWait);
// Timeup callback: Emit.
if (emit) {
callback = function() {
that.destroyTimer(timerObj);
if (args) {
that.node.emit.apply(that.node.events,
[hook].concat(args));
}
else {
that.node.emit(hook);
}
};
}
// Timeup callback: Exec.
else {
callback = function() {
that.destroyTimer(timerObj);
hook.apply(ctx, args);
};
}
tentativeName = method + '_' + hook + '_' +
J.randomInt(0, 1000000);
// Create and run timer:
timerObj = this.createTimer({
milliseconds: waitTime,
timeup: callback,
name: J.uniqueKey(this.timers, tentativeName)
});
// TODO: check if this condition is ok.
if (this.node.game && this.node.game.isReady()) {
timerObj.start();
}
else {
// TODO: this is not enough. Does not cover all use cases.
this.node.once('PLAYING', function() {
timerObj.start();
});
}
resetWaits();
}
function resetWaits() {
// Reset min and max wait to default.
// Need to do it here, because user can access the random
// and wait functions without executing them.
_maxWait = 5000;
_minWait = 1000;
}
function done(param) {
// Probalistic abort.
if (!evaluateProb()) return;
randomFire.call(that, 'done', node.done, false, node, [param]);
}
function emit(event) {
if ('string' !== typeof event) {
throw new TypeError('Timer.emit: event must be ' +
'string. Found: ' + event);
}
// Probalistic abort.
if (!evaluateProb()) return;
len = arguments.length;
if (len === 2) {
args = [arguments[1]];
}
else if (len === 3) {
args = [arguments[2], arguments[1]];
}
else if (len > 3) {
i = -1, len = (len-1);
args = new Array(len);
for ( ; ++i < len ; ) {
args[i] = arguments[i+1];
}
}
randomFire.call(that, 'emit', event, true, null, args);
}
function exec(func, ctx) {
if ('function' !== typeof func) {
throw new TypeError('Timer.exec: func must ' +
'be function. Found: ' + func);
}
if ('undefined' === typeof ctx) {
ctx = node.game;
}
else if ('object' !== typeof ctx && 'function' !== typeof ctx) {
throw new TypeError('Timer.exec: ctx must be ' +
'object, function or undefined. ' +
'Found: ' + ctx);
}
// Probalistic abort.
if (!evaluateProb()) return;
len = arguments.length;
if (len === 3) {
args = [arguments[2]];
}
else if (len === 4) {
args = [arguments[3], arguments[2]];
}
else if (len > 4) {
i = -1, len = (len-2);
args = new Array(len);
for ( ; ++i < len ; ) {
args[i] = arguments[i+2];
}
}
randomFire.call(that, 'exec', func, false, ctx, args);
}
function timeup(param) {
// Probalistic abort.
if (!evaluateProb()) return;
randomFire.call(that, 'timeup',
function() { node.game.timer.doTimeUp(); },
false, node.game, [param]);
}
function evaluateProb() {
var p;
// Get current value and resets it to 1.
p = _prob;
_prob = 1;
if ('number' === typeof p) return Math.random() <= p;
// It is either number of function.
return !!p.call(node.game);
}
function prob(prob) {
var tmp;
if ('undefined' === typeof prob) {
_prob = 0.5;
}
else if ('function' === typeof prob) {
_prob = prob;
}
else {
tmp = J.isNumber(prob, 0, 1, true, true);
if (tmp === false) {
throw new Error('Timer.prob: ' +
'prob must be a number between 0 and ' +
'1, undefined or function. Found: ' +
prob);
}
_prob = tmp;
}
return {
done: done,
emit: emit,
exec: exec,
timeup: timeup
};
}
// Random and Wait functions.
function random(maxWait, minWait) {
_maxWait = maxWait;
_minWait = minWait;
return {
done: done,
emit: emit,
exec: exec,
timeup: timeup,
prob: prob
};
}
function wait(wait) {
return random(wait, wait);
}
// Make the handlers properties of the random and wait functions.
random.done = done;
random.emit = emit;
random.exec = exec;
random.prob = prob;
random.timeup = timeup;
wait.done = done;
wait.emit = emit;
wait.exec = exec;
wait.prob = prob;
wait.timeup = timeup;
// Assign random and wait functions to Timer.
that.random = random;
that.wait = wait;
})(this);
}
// ## Timer methods
/**
* ### Timer.setTimeout
*
* Wrapper for createTimer with same syntax as JS setTimeout
*
* @param {function|string} timeup A callback function or an event to emit
* when the timeout is fired
* @param {number} milliseconds The delay for the timeout in milliseconds.
* Default: 1 (because zero would fire immediately and we want to keep
* the same behavior of JS setTimeout)
* @param {string} validity The validity of the timeout. Default: validity
* changes depending on where the timeout is created (game, stage, step).
*
* @return {GameTimer} The game timer
*
* @see GameTimer
*/
Timer.prototype.setTimeout = function(timeup, milliseconds, validity) {
return this.createTimer({
milliseconds: milliseconds || 1,
timeup: timeup,
validity: validity
}).start();
};
/**
* ### Timer.createTimer | Timer.create
*
* Returns a new GameTimer
*
* The GameTimer instance is automatically paused and resumed on
* the respective events.
*
* Timer creation is flexible, and input parameter can be a full
* configuration object, the number of milliseconds or nothing. In the
* latter case, the new timer will need to be configured manually. If
* only the number of milliseconds is passed the timer will fire a 'TIMEUP'
* event once the time expires.
*
* @param {mixed} options The configuration object passed to the GameTimer
* constructor. Alternatively, it is possible to pass directly the number
* of milliseconds and the remaining settings will be added, or to leave
* it undefined.
*
* @return {GameTimer} timer The requested timer
*
* @see GameTimer
*/
Timer.prototype.create = Timer.prototype.createTimer = function(options) {
var gameTimer, pausedCb, resumedCb;
var ee, val;
if (options &&
('object' !== typeof options && 'number' !== typeof options)) {
throw new TypeError('Timer.createTimer: options must be ' +
'undefined, object or number. Found: ' +
options);
}
if ('number' === typeof options) options = { milliseconds: options };
options = options || {};
options.name = options.name ||
J.uniqueKey(this.timers, 'timer_' + J.randomInt(0, 10000000));
if (this.timers[options.name]) {
throw new Error('Timer.createTimer: timer name already in use: ' +
options.name);
}
// Retrieve the event emitter where the listeners are registered
// based on options `validity` or the currently active event emitter.
// If validity is 'step' or 'stage', a reference will be added to
// the corresponding temporary array of timers (below).
val = options.validity;
if (!val) {
ee = this.node.getCurrentEventEmitter();
}
else {
ee = this.node.events.ee[val];
if (!ee) {
throw new Error('Timer.createTimer: validity must be "ng", ' +
'"game", "stage", "step". Found: ' + val);
}
}
options.eventEmitterName = ee.name;
// If game is paused add options startPaused, unless user
// specified a value in the options object.
if (this.node.game && this.node.game.paused) {
if ('undefined' === typeof options.startPaused) {
options.startPaused = true;
}
}
// Create the GameTimer:
gameTimer = new GameTimer(this.node, options);
// Attach pause / resume listeners:
pausedCb = function() {
if (!gameTimer.isPaused()) {
gameTimer.pause();
}
};
resumedCb = function() {
// startPaused=true also counts as a "paused" state:
if (gameTimer.isPaused() || gameTimer.startPaused) {
gameTimer.resume();
}
};
ee.on('PAUSED', pausedCb);
ee.on('RESUMED', resumedCb);
// Attach listener handlers to GameTimer object so they can be
// unregistered later:
gameTimer.timerPausedCallback = pausedCb;
gameTimer.timerResumedCallback = resumedCb;
// Add a reference into this.timers.
this.timers[gameTimer.name] = gameTimer;
// Add reference to stage and step temporary timers.
if (ee.name === 'step') this._stepTimers.push(gameTimer);
else if (ee.name === 'stage') this._stageTimers.push(gameTimer);
return gameTimer;
};
/**
* ### Timer.destroyTimer
*
* Stops and removes a GameTimer
*
* The event handlers listening on PAUSED/RESUMED that are attached to
* the given GameTimer object are removed.
*
* @param {object|string} gameTimer The gameTimer object or the name of
* the gameTimer created with Timer.createTimer
*/
Timer.prototype.destroyTimer = function(gameTimer) {
var eeName;
if ('string' === typeof gameTimer) {
if (!this.timers[gameTimer]) {
throw new Error('node.timer.destroyTimer: gameTimer not ' +
'found: ' + gameTimer);
}
gameTimer = this.timers[gameTimer];
}
if ('object' !== typeof gameTimer) {
throw new Error('node.timer.destroyTimer: gameTimer must be ' +
'string or object. Found: ' + gameTimer);
}
// Stop timer.
if (!gameTimer.isStopped()) {
gameTimer.stop();
}
eeName = gameTimer.eventEmitterName;
// Detach listeners.
if (eeName) {
// We know where the timer was registered.
this.node.events.ee[eeName].remove('PAUSED',
gameTimer.timerPausedCallback);
this.node.events.ee[eeName].remove('RESUMED',
gameTimer.timerResumedCallback);
}
else {
// We try to unregister from all.
this.node.off('PAUSED', gameTimer.timerPausedCallback);
this.node.off('RESUMED', gameTimer.timerResumedCallback);
}
// Remove listener syncing with stager (if any).
gameTimer.syncWithStager(false);
// Set status to DESTROYED and make object unusable
// (in case external references to the object still exists).
gameTimer.status = GameTimer.DESTROYED;
// Delete reference in this.timers.
delete this.timers[gameTimer.name];
};
/**
* ### Timer.destroyStepTimers
*
* Stops and removes all timers registered in current step
*/
Timer.prototype.destroyStepTimers = function() {
destroyTempTimers(this, '_stepTimers');
};
/**
* ### Timer.destroyStageTimers
*
* Stops and removes all timers registered in current stage
*/
Timer.prototype.destroyStageTimers = function() {
destroyTempTimers(this, '_stageTimers');
};
/**
* ### Timer.destroyAllTimers
*
* Stops and removes all registered GameTimers
*
* By default, node.game.timer is not removed.
*
* @param {boolean} all Removes really all timers, including
* node.game.timer
*/
Timer.prototype.destroyAllTimers = function(all) {
var i;
for (i in this.timers) {
if (this.timers.hasOwnProperty(i)) {
// Skip node.game.timer, unless so specified.
if (!all && i === this.node.game.timer.name) continue;
this.destroyTimer(this.timers[i]);
}
}
// Clear temporary timers.
this._stepTimers = [];
this._stageTimers = [];
};
/**
* ### Timer.getTimer
*
* Returns a reference to a previosly registered game timer.
*
* @param {string} name The name of the timer
*
* @return {GameTimer|null} The game timer with the given name, or
* null if none is found
*/
Timer.prototype.getTimer = function(name) {
if ('string' !== typeof name) {
throw new TypeError('Timer.getTimer: name must be string. Found: ' +
name);
}
return this.timers[name] || null;
};
/**
* ### Timer.setTimestamp
*
* Adds or changes a named timestamp
*
* @param {string} name The name of the timestamp
* @param {number|undefined} time Optional. The time in ms as returned by
* Date.getTime(). Default: Current time.
*
* @return {number} time The value of the timestamp set
*
* @see Timer.getTimestamp
*/
Timer.prototype.setTimestamp = function(name, time) {
var i;
// Default time: Current time
if ('undefined' === typeof time) time = J.now();
// Check inputs:
if ('string' !== typeof name) {
throw new Error('Timer.setTimestamp: name must be a string. ' +
'Found: ' + name);
}
if ('number' !== typeof time) {
throw new Error('Timer.setTimestamp: time must be a number or ' +
'undefined. Found: ' + time);
}
// We had at least one pause.
if (this.node.game.pauseCounter) {
// Remove records of paused timestamps.
if (this._pausedTimestamps[name]) {
this._pausedTimestamps[name] = null;
}
if (this._cumulPausedTimestamps[name]) {
this._cumulPausedTimestamps[name] = null;
}
// Mark timestamp as paused since the beginning, if game is paused.
if (this.node.game.isPaused()) this._pausedTimestamps[name] = time;
// Diffs are updated immediately.
this._effectiveDiffs[name] = {};
for (i in this.timestamps) {
if (this.timestamps.hasOwnProperty(i)) {
this._effectiveDiffs[name][i] = this.getTimeSince(i, true);
}
}
}
this.timestamps[name] = time;
return time;
};
/**
* ### Timer.getTimestamp
*
* Retrieves a named timestamp
*
* @param {string} name The name of the timestamp
*
* @return {number|null} The time associated with the timestamp,
* NULL if it doesn't exist
*/
Timer.prototype.getTimestamp = function(name) {
// Check input:
if ('string' !== typeof name) {
throw new Error('Timer.getTimestamp: name must be a string. ' +
'Found: ' + name);
}
if (this.timestamps.hasOwnProperty(name)) return this.timestamps[name];
else return null;
};
/**
* ### Timer.getAllTimestamps
*
* Returns the map with all timestamps
*
* Do not change the returned object.
*
* @return {object} The timestamp map
*/
Timer.prototype.getAllTimestamps = function() {
return this.timestamps;
};
/**
* ### Timer.getTimeSince
*
* Gets the time in ms since a timestamp
*
* @param {string} name The name of the timestamp
* @param {boolean} effective Optional. If set, effective time
* is returned, i.e. time minus paused time. Default: false.
*
* @return {number|null} The time since the timestamp in ms,
* NULL if it doesn't exist
*
* @see Timer.getTimeDiff
*/
Timer.prototype.getTimeSince = function(name, effective) {
var currentTime;
// Get current time:
currentTime = J.now();
// Check input:
if ('string' !== typeof name) {
throw new TypeError('Timer.getTimeSince: name must be string. ' +
'Found: ' + name);
}
if (this.timestamps.hasOwnProperty(name)) {
if (effective) {
if (this._pausedTimestamps[name]) {
currentTime -= (currentTime - this._pausedTimestamps[name]);
}
if (this._cumulPausedTimestamps[name]) {
currentTime -= this._cumulPausedTimestamps[name];
}
}
return currentTime - this.timestamps[name];
}
else {
return null;
}
};
/**
* ### Timer.getTimeDiff
*
* Returns the time difference between two registered timestamps
*
* @param {string} nameFrom The name of the first timestamp
* @param {string} nameTo The name of the second timestamp
* @param {boolean} effective Optional. If set, effective time
* is returned, i.e. time diff minus paused time. Default: false.
*
* @return {number} The time difference between the timestamps
*/
Timer.prototype.getTimeDiff = function(nameFrom, nameTo, effective) {
var timeFrom, timeTo, ed;
// Check input:
if ('string' !== typeof nameFrom) {
throw new TypeError('Timer.getTimeDiff: nameFrom must be string.' +
'Found: ' + nameFrom);
}
if ('string' !== typeof nameTo) {
throw new TypeError('Timer.getTimeDiff: nameTo must be string. ' +
'Found: ' + nameTo);
}
timeFrom = this.timestamps[nameFrom];
if ('undefined' === typeof timeFrom || timeFrom === null) {
throw new Error('Timer.getTimeDiff: nameFrom does not resolve to ' +
'a valid timestamp: ' + nameFrom);
}
timeTo = this.timestamps[nameTo];
if ('undefined' === typeof timeTo || timeTo === null) {
throw new Error('Timer.getTimeDiff: nameTo does not resolve to ' +
'a valid timestamp: ' + nameTo);
}
if (effective) {
ed = this._effectiveDiffs;
if (ed[nameFrom] && ed[nameFrom][nameTo]) {
return ed[nameFrom][nameTo];
}
else if (ed[nameTo] && ed[nameTo][nameFrom]) {
return ed[nameTo][nameFrom];
}
}
return timeTo - timeFrom;
};
/**
* ## Timer.parseInput
*
* Resolves an unknown value to a valid time quantity (number >=0)
*
* Valid types and operation:
* - number (as is),
* - string (casted),
* - object (property _name_ is parsed),
* - function (will be invoked with `node.game` context)
*
* Parsed value must be a number >= 0
*
* @param {string} name The name of the property if value is object
* @param {number} value The value to parse
* @param {string} methodName Optional. The name of the method invoking
* the function for the error messsage. Default: Timer.parseInput
*
* @param {number} The parsed value
*/
Timer.prototype.parseInput = function(name, value, methodName) {
var typeofValue, num;
if ('string' !== typeof name) {
throw new TypeError((methodName || 'Timer.parseInput') +
': name must be string. Found: ' + name);
}
typeofValue = typeof value;
switch (typeofValue) {
case 'number':
num = value;
break;
case 'object':
if (null !== value) {
if ('function' === typeof value[name]) {
num = value[name].call(this.node.game);
}
}
break;
case 'function':
num = value.call(this.node.game);
break;
case 'string':
num = Number(value);
break;
}
if ('number' !== typeof num || num < 0) {
throw new Error((methodName || 'Timer.parseInput') +
': ' + name + ' must be number >= 0. Found: ' +
num);
}
return num;
};
// ## Helper Methods.
/**
* ### destroyTempTimers
*
* Common handler for randomEmit, randomExec, randomDone
*
* @param {Timer} that A live Timer instance
* @param {string} timers The tname of the collection of temp timers
*/
function destroyTempTimers(that, timers) {
var i, len, t;
len = that[timers].length;
for (i = 0; i < len; i++) {
t = that[timers][i];
if (t.status !== GameTimer.DESTROYED) that.destroyTimer(t);
}
that[timers] = [];
}
/**
* # GameTimer
*
* Copyright(c) 2016 Stefano Balietti
* MIT Licensed
*
* Creates a controllable timer object for nodeGame.
*/
exports.GameTimer = GameTimer;
/**
* ### GameTimer status levels
* Numerical levels representing the state of the GameTimer
*
* @see GameTimer.status
*/
GameTimer.STOPPED = -5;
GameTimer.PAUSED = -3;
GameTimer.UNINITIALIZED = -1;
GameTimer.INITIALIZED = 0;
GameTimer.LOADING = 3;
GameTimer.RUNNING = 5;
GameTimer.DESTROYED = 10;
/**
* ## GameTimer constructor
*
* Creates an instance of GameTimer
*
* @param {object} options. Optional. A configuration object
*/
function GameTimer(node, options) {
options = options || {};
// ## Public properties
/**
* ### node
*
* Internal reference to node
*/
this.node = node;
/**
* ### name
*
* Internal name of the timer
*/
this.name = options.name || 'timer_' + J.randomInt(0, 1000000);
/**
* ### GameTimer.status
*
* Numerical index keeping the current the state of the GameTimer obj
*/
this.status = GameTimer.UNINITIALIZED;
/**
* ### GameTimer.options
*