-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathgamecore.js
3361 lines (3004 loc) · 105 KB
/
gamecore.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
/**
* gamecore.js - Copyright 2012 Playcraft Labs, Inc. (see licence.txt)
*/
window.gamecore =
{
hasOwn:Object.prototype.hasOwnProperty,
isFunction:function (obj)
{
// return Object.prototype.toString.call(obj) === "[object Function]";
return !!(obj && obj.constructor && obj.call && obj.apply);
},
isWindow:function (obj)
{
return !!(obj && obj.setInterval);
},
isArray:Array.isArray || function (obj)
{
return (obj.constructor === Array);
},
isString:function (obj)
{
return (typeof obj == 'string');
},
isObject:function (obj)
{
return obj === Object(obj);
},
isPlainObject:function (obj)
{
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || this.isObject(obj) || obj.nodeType || this.isWindow(obj))
return false;
try
{
// Not own constructor property must be Object
if (obj.constructor && !this.hasOwn.call(obj, "constructor") && !this.hasOwn.call(obj.constructor.prototype, "isPrototypeOf"))
return false;
} catch (e)
{
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// own properties are enumerated firstly, so to speed up, if last one is own, then all properties are own.
var key;
for (key in obj)
{
}
return key === undefined || this.hasOwn.call(obj, key);
},
extend:function ()
{
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean")
{
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !gamecore.isFunction(target))
target = {};
if (length === i)
{
target = this;
--i;
}
for (; i < length; i++)
{
// Only deal with non-null/undefined values
if ((options = arguments[ i ]) != null)
{
// Extend the base object
for (name in options)
{
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if (target === copy)
{
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && ( this.isPlainObject(copy) || (copyIsArray = this.isArray(copy)) ))
{
if (copyIsArray)
{
copyIsArray = false;
clone = src && this.isArray(src) ? src : [];
} else
{
clone = src && this.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = this.extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined)
{
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
}
};
gamecore.push = Array.prototype.push;
gamecore.merge = function (first, second)
{
var i = first.length, j = 0;
if (typeof second.length === "number")
{
for (var l = second.length; j < l; j++)
first[ i++ ] = second[ j ];
} else
{
while (second[j] !== undefined)
first[ i++ ] = second[ j++ ];
}
first.length = i;
return first;
};
gamecore.makeArray = function (array, results)
{
var ret = results || [];
if (array != null)
{
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
if (array.length == null || gamecore.isString(array) || gamecore.isFunction(array) || gamecore.isWindow(array))
gamecore.push.call(ret, array);
else
gamecore.merge(ret, array);
}
return ret;
};
gamecore.each = function (object, callback, args)
{
var name, i = 0,
length = object.length,
isObj = length === undefined || gamecore.isFunction(object);
if (args)
{
if (isObj)
{
for (name in object)
{
if (callback.apply(object[ name ], args) === false)
{
break;
}
}
} else
{
for (; i < length;)
{
if (callback.apply(object[ i++ ], args) === false)
{
break;
}
}
}
// A special, fast, case for the most common use of each
} else
{
if (isObj)
{
for (name in object)
{
if (callback.call(object[ name ], name, object[ name ]) === false)
{
break;
}
}
} else
{
for (; i < length;)
{
if (callback.call(object[ i ], i, object[ i++ ]) === false)
{
break;
}
}
}
}
return object;
};
gamecore._flagsCache = {};
gamecore.createFlags = function (flags)
{
var object = gamecore._flagsCache[ flags ] = {}, i, length;
flags = flags.split(/\s+/);
for (i = 0, length = flags.length; i < length; i++)
object[ flags[i] ] = true;
return object;
};
gamecore.Callbacks = function (flags)
{
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( gamecore._flagsCache[ flags ] || gamecore.createFlags(flags) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function (args)
{
var i, length, elem, actual;
for (i = 0, length = args.length; i < length; i++)
{
elem = args[ i ];
if (gamecore.isArray(elem))
{
// Inspect recursively
add(elem);
} else if (gamecore.isFunction(elem))
{
// Add if not in unique mode and callback is not in
if (!flags.unique || !self.has(elem))
{
list.push(elem);
}
}
}
},
// Fire callbacks
fire = function (context, args)
{
args = args || [];
memory = !flags.memory || [ context, args ];
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for (; list && firingIndex < firingLength; firingIndex++)
{
if (list[ firingIndex ].apply(context, args) === false && flags.stopOnFalse)
{
memory = true; // Mark as halted
break;
}
}
firing = false;
if (list)
{
if (!flags.once)
{
if (stack && stack.length)
{
memory = stack.shift();
self.fireWith(memory[ 0 ], memory[ 1 ]);
}
} else if (memory === true)
{
self.disable();
} else
{
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add:function ()
{
if (list)
{
var length = list.length;
add(arguments);
// Do we need to add the callbacks to the
// current firing batch?
if (firing)
{
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if (memory && memory !== true)
{
firingStart = length;
fire(memory[ 0 ], memory[ 1 ]);
}
}
return this;
},
// Remove a callback from the list
remove:function ()
{
if (list)
{
var args = arguments,
argIndex = 0,
argLength = args.length;
for (; argIndex < argLength; argIndex++)
{
for (var i = 0; i < list.length; i++)
{
if (args[ argIndex ] === list[ i ])
{
// Handle firingIndex and firingLength
if (firing)
{
if (i <= firingLength)
{
firingLength--;
if (i <= firingIndex)
{
firingIndex--;
}
}
}
// Remove the element
list.splice(i--, 1);
// If we have some unicity property then
// we only need to do this once
if (flags.unique)
{
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has:function (fn)
{
if (list)
{
var i = 0,
length = list.length;
for (; i < length; i++)
{
if (fn === list[ i ])
{
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty:function ()
{
list = [];
return this;
},
// Have the list do nothing anymore
disable:function ()
{
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled:function ()
{
return !list;
},
// Lock the list in its current state
lock:function ()
{
stack = undefined;
if (!memory || memory === true)
{
self.disable();
}
return this;
},
// Is it locked?
locked:function ()
{
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith:function (context, args)
{
if (stack)
{
if (firing)
{
if (!flags.once)
{
stack.push([ context, args ]);
}
} else if (!( flags.once && memory ))
{
fire(context, args);
}
}
return this;
},
// Call all the callbacks with the given arguments
fire:function ()
{
self.fireWith(this, arguments);
return this;
},
// To know if the callbacks have already been called at least once
fired:function ()
{
return !!memory;
}
};
return self;
};
gamecore.extend({
Deferred:function (func)
{
var doneList = gamecore.Callbacks("once memory"),
failList = gamecore.Callbacks("once memory"),
progressList = gamecore.Callbacks("memory"),
state = "pending",
lists = {
resolve:doneList,
reject:failList,
notify:progressList
},
promise = {
done:doneList.add,
fail:failList.add,
progress:progressList.add,
state:function ()
{
return state;
},
// Deprecated
isResolved:doneList.fired,
isRejected:failList.fired,
then:function (doneCallbacks, failCallbacks, progressCallbacks)
{
deferred.done(doneCallbacks).fail(failCallbacks).progress(progressCallbacks);
return this;
},
always:function ()
{
deferred.done.apply(deferred, arguments).fail.apply(deferred, arguments);
return this;
},
pipe:function (fnDone, fnFail, fnProgress)
{
return gamecore.Deferred(function (newDefer)
{
gamecore.each({
done:[ fnDone, "resolve" ],
fail:[ fnFail, "reject" ],
progress:[ fnProgress, "notify" ]
}, function (handler, data)
{
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if (gamecore.isFunction(fn))
{
deferred[ handler ](function ()
{
returned = fn.apply(this, arguments);
if (returned && gamecore.isFunction(returned.promise))
{
returned.promise().then(newDefer.resolve, newDefer.reject, newDefer.notify);
} else
{
newDefer[ action + "With" ](this === deferred ? newDefer : this, [ returned ]);
}
});
} else
{
deferred[ handler ](newDefer[ action ]);
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise:function (obj)
{
if (obj == null)
{
obj = promise;
} else
{
for (var key in promise)
{
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for (key in lists)
{
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done(function ()
{
state = "resolved";
}, failList.disable, progressList.lock).fail(function ()
{
state = "rejected";
}, doneList.disable, progressList.lock);
// Call given func if any
if (func)
{
func.call(deferred, deferred);
}
// All done!
return deferred;
},
// Deferred helper
when:function (firstParam)
{
var // Static reference to slice
sliceDeferred = [].slice;
var args = sliceDeferred.call(arguments, 0),
i = 0,
length = args.length,
pValues = new Array(length),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && gamecore.isFunction(firstParam.promise) ?
firstParam :
gamecore.Deferred(),
promise = deferred.promise();
function resolveFunc(i)
{
return function (value)
{
args[ i ] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value;
if (!( --count ))
{
deferred.resolveWith(deferred, args);
}
};
}
function progressFunc(i)
{
return function (value)
{
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value;
deferred.notifyWith(promise, pValues);
};
}
if (length > 1)
{
for (; i < length; i++)
{
if (args[ i ] && args[ i ].promise && gamecore.isFunction(args[ i ].promise))
{
args[ i ].promise().then(resolveFunc(i), deferred.reject, progressFunc(i));
} else
{
--count;
}
}
if (!count)
{
deferred.resolveWith(deferred, args);
}
} else if (deferred !== firstParam)
{
deferred.resolveWith(deferred, length ? [ firstParam ] : []);
}
return promise;
}
});
/**
* gamecore.js - Copyright 2012 Playcraft Labs, Inc. (see licence.txt)
* class.js
* Classes and objects
*/
/**
* @Class
* A modified version of class.js to cater to static inheritance and deep object cloning
* Based almost completely on class.js (Javascript MVC -- Justin Meyer, Brian Moschel, Michael Mayer and others)
* (http://javascriptmvc.com/contribute.html)
* Some portions adapted from Prototype JavaScript framework, version 1.6.0.1 (c) 2005-2007 Sam Stephenson
* Some portions extracted from jQuery 1.7
* <p>
* Class system for javascript
* <p>
* <code>
* var Fighter = gamecore.Base.extend('Fighter',
* {
* // static (this is inherited as well)
* firingSpeed: 1000
* },
* {
* // instance
*
* hp: 0,
* lastFireTime: 0,
*
* init: function(hp)
* {
* this.hp = hp;
* },
*
* fire: function()
* {
* this._super(); // super methods!
*
* // do firing!
* }
* });
*
* var gunship = new Fighter(100);
* </code>
*
* Introspection:
* <code>
* gamecore.Base.extend(‘Fighter.Gunship’);
* Fighter.Gunship.shortName; // ‘Gunship’
* Fighter.Gunship.fullName; // ‘Fighter.Gunship’
* Fighter.Gunship.namespace; // ‘Fighter’
* </code>
* <p>
* Setup method will be called prior to any init -- nice if you want to do things without needing the
* users to call _super in the init, as well as for normalizing parameters.
* <code>
* setup: function()
* {
* this.objectId = this.Class.totalObjects++;
* this.uniqueId = this.Class.fullName + ':' + this.objectId;
* }
* </code>
*/
(function (gc)
{
var regs = {
undHash:/_|-/,
colons:/::/,
words:/([A-Z]+)([A-Z][a-z])/g,
lowUp:/([a-z\d])([A-Z])/g,
dash:/([a-z\d])([A-Z])/g,
replacer:/\{([^\}]+)\}/g,
dot:/\./
},
getNext = function (current, nextPart, add)
{
return current[nextPart] || ( add && (current[nextPart] = {}) );
},
isContainer = function (current)
{
var type = typeof current;
return type && ( type == 'function' || type == 'object' );
},
getObject = function (objectName, roots, add)
{
var parts = objectName ? objectName.split(regs.dot) : [],
length = parts.length,
currents = gc.isArray(roots) ? roots : [roots || window],
current,
ret,
i,
c = 0,
type;
if (length == 0)
{
return currents[0];
}
while (current = currents[c++])
{
for (i = 0; i < length - 1 && isContainer(current); i++)
{
current = getNext(current, parts[i], add);
}
if (isContainer(current))
{
ret = getNext(current, parts[i], add);
if (ret !== undefined)
{
if (add === false)
{
delete current[parts[i]];
}
return ret;
}
}
}
},
/**
* A collection of useful string helpers.
*/
str = gc.String = {
/**
* @function
* Gets an object from a string.
* @param {String} name the name of the object to look for
* @param {Array} [roots] an array of root objects to look for the name
* @param {Boolean} [add] true to add missing objects to
* the path. false to remove found properties. undefined to
* not modify the root object
*/
getObject:getObject,
/**
* Capitalizes a string
* @param {String} s the string.
* @return {String} a string with the first character capitalized.
*/
capitalize:function (s, cache)
{
return s.charAt(0).toUpperCase() + s.substr(1);
},
/**
* Capitalizes a string from something undercored. Examples:
* @codestart
* gamecore.String.camelize("one_two") //-> "oneTwo"
* "three-four".camelize() //-> threeFour
* @codeend
* @param {String} s
* @return {String} a the camelized string
*/
camelize:function (s)
{
s = str.classize(s);
return s.charAt(0).toLowerCase() + s.substr(1);
},
/**
* Like camelize, but the first part is also capitalized
* @param {String} s
* @return {String} the classized string
*/
classize:function (s, join)
{
var parts = s.split(regs.undHash),
i = 0;
for (; i < parts.length; i++)
{
parts[i] = str.capitalize(parts[i]);
}
return parts.join(join || '');
},
/**
* Like [gamecore.String.classize|classize], but a space separates each 'word'
* @codestart
* gamecore.String.niceName("one_two") //-> "One Two"
* @codeend
* @param {String} s
* @return {String} the niceName
*/
niceName:function (s)
{
return str.classize(s, ' ');
},
/**
* Underscores a string.
* @codestart
* gamecore.String.underscore("OneTwo") //-> "one_two"
* @codeend
* @param {String} s
* @return {String} the underscored string
*/
underscore:function (s)
{
return s.replace(regs.colons, '/').replace(regs.words, '$1_$2').replace(regs.lowUp, '$1_$2').replace(regs.dash, '_').toLowerCase();
},
/**
* Returns a string with {param} replaced values from data.
*
* gamecore.String.sub("foo {bar}",{bar: "far"})
* //-> "foo far"
*
* @param {String} s The string to replace
* @param {Object} data The data to be used to look for properties. If it's an array, multiple
* objects can be used.
* @param {Boolean} [remove] if a match is found, remove the property from the object
*/
sub:function (s, data, remove)
{
var obs = [];
obs.push(s.replace(regs.replacer, function (whole, inside)
{
//convert inside to type
var ob = getObject(inside, data, typeof remove == 'boolean' ? !remove : remove),
type = typeof ob;
if ((type === 'object' || type === 'function') && type !== null)
{
obs.push(ob);
return "";
} else
{
return "" + ob;
}
}));
return obs.length <= 1 ? obs[0] : obs;
}
}
})(gamecore);
(function (gc)
{
// if we are initializing a new class
var initializing = false,
makeArray = gc.makeArray,
isFunction = gc.isFunction,
isArray = gc.isArray,
extend = gc.extend,
cloneObject = function (object)
{
if (!object || typeof(object) != 'object')
return object;
// special case handling of array (deep copy them)
if (object instanceof Array)
{
var clone = [];
for (var c = 0; c < object.length; c++)
clone[c] = cloneObject(object[c]);
return clone;
}
else // otherwise, it's a normal object, clone it's properties
{
var cloneObj = {};
for (var prop in object)
cloneObj[prop] = cloneObject(object[prop]);
return cloneObj;
}
},
concatArgs = function (arr, args)
{
return arr.concat(makeArray(args));
},
// tests if we can get super in .toString()
fnTest = /xyz/.test(function ()
{
xyz;
}) ? /\b_super\b/ : /.*/,
inheritProps = function (newProps, oldProps, addTo)
{
// overwrites an object with methods, sets up _super
// newProps - new properties
// oldProps - where the old properties might be
// addTo - what we are adding to
addTo = addTo || newProps
for (var name in newProps)
{
// Check if we're overwriting an existing function
addTo[name] = isFunction(newProps[name]) &&
isFunction(oldProps[name]) &&
fnTest.test(newProps[name]) ? (function (name, fn)
{
return function ()
{
var tmp = this._super, ret;
// Add a new ._super() method that is the same method but on the super-class
this._super = oldProps[name];
// The method only need to be bound temporarily, so we remove it when we're done executing
ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, newProps[name]) : newProps[name];
}
},
clss = gc.Class = function ()
{
if (arguments.length)
{
return clss.extend.apply(clss, arguments);
}
};
/* @Static*/
extend(clss, {
callback:function (funcs)
{
//args that should be curried
var args = makeArray(arguments),
self;
funcs = args.shift();
if (!isArray(funcs))
{
funcs = [funcs];
}
self = this;
return function class_cb()
{
var cur = concatArgs(args, arguments),
isString,
length = funcs.length,
f = 0,
func;
for (; f < length; f++)
{
func = funcs[f];
if (!func)
continue;
isString = typeof func == "string";
if (isString && self._set_called)
self.called = func;