-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmantra.js
3319 lines (3119 loc) · 192 KB
/
mantra.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.MANTRA = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _Component2 = _interopRequireDefault(require("./Component.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var ActionRateLimiter = /*#__PURE__*/function (_Component) {
_inherits(ActionRateLimiter, _Component);
var _super = _createSuper(ActionRateLimiter);
function ActionRateLimiter(name, owner) {
var _this;
_classCallCheck(this, ActionRateLimiter);
_this = _super.call(this, name, owner);
_this.entityActions = new Map(); // Store last action times per entity
return _this;
}
// Record an action for a specific entity
_createClass(ActionRateLimiter, [{
key: "recordAction",
value: function recordAction(entityId, actionName) {
var actions = this.entityActions.get(entityId) || new Map();
actions.set(actionName, Date.now());
this.entityActions.set(entityId, actions);
}
// Get the last time an action was performed for a specific entity
}, {
key: "getLastActionTime",
value: function getLastActionTime(entityId, actionName) {
var actions = this.entityActions.get(entityId);
return actions ? actions.get(actionName) || 0 : 0;
}
}]);
return ActionRateLimiter;
}(_Component2["default"]);
var _default = exports["default"] = ActionRateLimiter;
},{"./Component.js":2}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
// Component.js - Marak Squires 2023
var Component = /*#__PURE__*/function () {
function Component(name, game) {
_classCallCheck(this, Component);
this.name = name;
this.data = {};
this.game = game;
}
_createClass(Component, [{
key: "set",
value: function set(key, value) {
var entityId = Array.isArray(key) ? key[0] : key;
// Check if the property is locked
if (this.game) {
var lockedProps = this.game.components['lockedProperties'].get(entityId);
if (this.isLocked(lockedProps, this.name)) {
// console.log(`Property ${key} is locked and cannot be updated.`);
return; // Do not update if the property is locked
}
}
if (Array.isArray(key)) {
// Ensure nested structure exists
var current = this.data;
for (var i = 0; i < key.length - 1; i++) {
if (!current[key[i]]) {
current[key[i]] = {};
}
current = current[key[i]];
}
current[key[key.length - 1]] = value;
} else {
this.data[key] = value;
}
// After setting the value, update the corresponding entity in the game.entities
if (this.game && this.game.entities && this.game.entities.has(entityId)) {
var existing = this.game.entities.get(entityId);
existing[this.name] = this.get(entityId);
}
}
}, {
key: "get",
value: function get(key) {
if (Array.isArray(key)) {
var current = this.data;
for (var i = 0; i < key.length; i++) {
if (current[key[i]] === undefined) {
return null;
}
current = current[key[i]];
}
return current;
}
if (typeof this.data[key] === 'undefined' || this.data[key] === null) {
return null;
}
return this.data[key];
}
}, {
key: "remove",
value: function remove(key) {
if (Array.isArray(key)) {
var current = this.data;
for (var i = 0; i < key.length - 1; i++) {
if (current[key[i]] === undefined) {
return;
}
current = current[key[i]];
}
delete current[key[key.length - 1]];
} else {
delete this.data[key];
}
}
// Helper method to check if a property or sub-property is locked
}, {
key: "isLocked",
value: function isLocked(lockedProps, key) {
if (!lockedProps) return false;
if (Array.isArray(key)) {
var current = lockedProps;
for (var i = 0; i < key.length; i++) {
if (current[key[i]] === undefined) {
return false; // Property not locked
}
current = current[key[i]];
}
return true; // Property is locked
}
return lockedProps[key] !== undefined;
}
}]);
return Component;
}();
var _default = exports["default"] = Component;
},{}],3:[function(require,module,exports){
"use strict";
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _Component2 = _interopRequireDefault(require("./Component.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var TimersComponent = /*#__PURE__*/function (_Component) {
_inherits(TimersComponent, _Component);
var _super = _createSuper(TimersComponent);
function TimersComponent(name, owner) {
var _this;
_classCallCheck(this, TimersComponent);
_this = _super.call(this, name, owner);
_this.timers = {}; // Object to hold named timers
return _this;
}
// Set a timer with a specific duration, with optional interval flag
_createClass(TimersComponent, [{
key: "setTimer",
value: function setTimer(name, duration) {
var isInterval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
this.timers[name] = {
startTime: Date.now(),
duration: duration * 1000,
// Convert to milliseconds
isInterval: isInterval,
completed: false
};
}
}, {
key: "getTimer",
value: function getTimer(name) {
return this.timers[name];
}
}, {
key: "checkTimer",
value: function checkTimer(name) {
if (!this.timers[name]) return false;
var timer = this.timers[name];
var now = Date.now();
if (!timer.completed && now >= timer.startTime + timer.duration) {
if (timer.isInterval) {
this.resetTimer(name); // Reset for intervals
return 'intervalCompleted'; // Indicate interval completion
} else {
timer.completed = true;
return true; // Indicate one-time timer completion
}
}
return false; // Timer has not completed yet
}
// Reset a timer
}, {
key: "resetTimer",
value: function resetTimer(name) {
if (this.timers[name]) {
this.timers[name].startTime = Date.now();
this.timers[name].completed = false;
}
}
// Remove a timer
}, {
key: "removeTimer",
value: function removeTimer(name) {
delete this.timers[name];
}
}]);
return TimersComponent;
}(_Component2["default"]);
var _default = exports["default"] = TimersComponent;
},{"./Component.js":2}],4:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Game = void 0;
var _Component = _interopRequireDefault(require("./Component/Component.js"));
var _construct = _interopRequireDefault(require("./lib/Game/construct.js"));
var _use = _interopRequireDefault(require("./lib/Game/use.js"));
var _start = _interopRequireDefault(require("./lib/Game/start.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } // MANTRA - Yantra Works 2023
// Game.js - Marak Squires 2023
// The Game class is the main entry point for Mantra games
var Game = exports.Game = /*#__PURE__*/function () {
function Game() {
var customConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Game);
// Default configuration
var defaultConfig = {
// game modes
isClient: true,
isEdgeClient: false,
isServer: false,
isOfflineMode: undefined,
plugins: {},
// Plugin Classes that will be bound to the game instance
// game options
showLoadingScreen: true,
minLoadTime: 330,
// minimum time to show loading screen
loadDefaultPlugins: true,
// auto-loads default plugins based on pluginsConfig
width: 800,
height: 600,
fieldOfView: 1600,
useFoV: true,
// game systems / auto-load based on pluginsConfig
physics: 'matter',
graphics: ['css'],
collisions: true,
camera: {},
gravity: {},
keyboard: true,
mouse: true,
gamepad: true,
virtualGamepad: true,
editor: true,
sutra: true,
lifetime: true,
defaultMovement: true,
// data compression
protobuf: false,
msgpack: false,
deltaCompression: false,
deltaEncoding: true,
defaultPlayer: true,
options: {},
mode: 'topdown',
// default entity input and movement mode defined as Sutras
multiplexGraphicsHorizontally: false,
// default behavior is multiple graphics plugins will be horizontally stacked
addLifecycleHooksToAllPlugins: true // default behavior is to add lifecycle hooks to all plugin methods
};
// Merge custom configuration with defaults
var config = _objectSpread(_objectSpread({}, defaultConfig), customConfig);
// Override for server-specific defaults
if (config.isServer) {
config.showLoadingScreen = false;
config.isClient = false;
}
// Assigning the final configuration to this.config
this.config = config;
// Game.use('PluginName') is a helper function for loading plugins
// must be defined before construct() is called
this.use = (0, _use["default"])(this, config.plugins);
// Additional construction logic
(0, _construct["default"])(this, config.plugins);
// Plugin handling
this.start = _start["default"].bind(this);
}
_createClass(Game, [{
key: "update",
value: function update(deltaTime) {
// Call update method of SystemsManager, which delegate to all Systems which have an update method
this.systemsManager.update(deltaTime);
}
}, {
key: "render",
value: function render() {
// Call render method of SystemsManager, which will delegate to all Graphics systems
this.systemsManager.render();
}
//
// Component APIs
//
}, {
key: "addComponent",
value: function addComponent(entityId, componentType, data) {
if (!this.components[componentType]) {
this.components[componentType] = new _Component["default"](componentType, this);
}
// Initialize an empty map for the actionRateLimiter component
// TODO: remove this hard-coded check for actionRateLimiter
if (componentType === 'actionRateLimiter') {
data = new Map();
}
if (data == null) {
return;
}
this.components[componentType].set(entityId, data);
}
}, {
key: "getComponent",
value: function getComponent(entityId, componentType) {
if (this.components.hasOwnProperty(componentType)) {
return this.components[componentType].get(entityId);
}
return null;
}
//
// System APIs
//
}, {
key: "addSystem",
value: function addSystem(systemName, system) {
return this.systemsManager.addSystem(systemName, system);
}
}, {
key: "getSystem",
value: function getSystem(systemName) {
return this.systemsManager.getSystem(systemName);
}
}, {
key: "removeSystem",
value: function removeSystem(systemName) {
return this.systemsManager.removeSystem(systemName.toLowerCase());
}
}, {
key: "updateGraphic",
value: function updateGraphic(entityData) {
this.graphics.forEach(function (graphicsInterface) {
graphicsInterface.updateGraphic(entityData);
});
}
//
// Plugin APIs
//
}, {
key: "loadPluginScript",
value: function loadPluginScript(scriptUrl) {
console.log('Loading', scriptUrl);
return new Promise(function (resolve, reject) {
var script = document.createElement('script');
script.src = scriptUrl;
//script.async = true;
script.defer = true;
script.onload = function () {
return resolve();
};
script.onerror = function () {
return reject(new Error("Failed to load script: ".concat(scriptUrl)));
};
document.head.appendChild(script);
});
}
}, {
key: "removePlugin",
value: function removePlugin(pluginName) {
var plugin = this._plugins[pluginName];
if (plugin) {
// check to see if plugin is a system, if so remove the system
if (this.systems[plugin.id]) {
this.removeSystem(plugin.id);
}
// next see if plugin has unload method, if so call it
if (typeof plugin.unload === 'function') {
plugin.unload();
}
delete this._plugins[pluginName];
}
}
}, {
key: "setControls",
value: function setControls(controls) {
var game = this;
game.controls = controls;
if (game.systems['entity-input']) {
// TODO: update instead of replace?
game.systems['entity-input'].controlMappings = controls;
}
}
}, {
key: "setSize",
value: function setSize(width, height) {
this.width = width;
this.height = height;
}
//
// Player specific APIs
//
}, {
key: "setPlayerId",
value: function setPlayerId(playerId) {
console.log('setting playerID', playerId);
this.currentPlayerId = playerId;
}
}, {
key: "getCurrentPlayer",
value: function getCurrentPlayer() {
return this.getEntity(this.currentPlayerId);
}
// TODO: doesn't need to be player, can be ent
// rename: getEntityFieldOfView
}, {
key: "getPlayerFieldOfView",
value: function getPlayerFieldOfView(entId) {
var distance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
var mergeData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var ent;
if (_typeof(entId) === 'object') {
ent = entId;
} else {
ent = this.getEntity(entId);
}
if (!ent) {
console.log('Warning: no entity found for entId', entId);
return [];
}
var centerPosition = ent.position;
var query = {
minX: centerPosition.x - distance,
minY: centerPosition.y - distance,
maxX: centerPosition.x + distance,
maxY: centerPosition.y + distance
};
if (this.systems.rbush) {
return this.systems.rbush.search(query, mergeData);
} else {
console.log('Warning: no rbush system found, cannot perform getPlayerFieldOfView query');
}
}
//
// Containers
//
}, {
key: "createContainer",
value: function createContainer(entityData) {
// helper method for containers
entityData.type = 'CONTAINER';
entityData.style = entityData.style || {};
entityData.style.layout = entityData.layout || 'none';
entityData.style.grid = entityData.grid || {};
entityData.items = entityData.items || [];
return this.createEntity(entityData);
}
//
// Audio / Multimedia APIs
//
}, {
key: "playNote",
value: function playNote(note, duration) {
console.log('Tone Plugin not loaded. Cannot play tone note.');
}
//
// Physics Engine APIs
//
}, {
key: "setGravity",
value: function setGravity() {
var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
if (this.physics) {
this.physics.setGravity(x, y, z);
}
}
}, {
key: "setPosition",
value: function setPosition(entityId, position) {
this.physics.setPosition(entityId, position);
}
}, {
key: "applyForce",
value: function applyForce(entityId, force) {
// const body = this.bodyMap[entityId];
this.physics.applyForce(entityId, force);
// this.components.velocity[entityId] = { x: body.velocity.x, y: body.velocity.y };
}
}, {
key: "applyPosition",
value: function applyPosition(entityId, position) {
// const body = this.bodyMap[entityId];
// takes the current position and adds the new position
var newPosition = {
x: body.position.x + position.x,
y: body.position.y + position.y
};
this.physics.setPosition(entityId, newPosition);
}
}, {
key: "rotate",
value: function rotate(entityId, rotation) {
var rotationSpeed = 0.022; // TODO: config
var rotationAmount = rotation * rotationSpeed;
// const body = this.bodyMap[entityId];
this.physics.rotateBody(entityId, rotationAmount);
}
//
// Camera APIs
//
}, {
key: "rotateCamera",
value: function rotateCamera(angle) {
// not implemented directly, Graphics plugin will hoist this
}
}, {
key: "setZoom",
value: function setZoom() {// TODO: remove setZoom, use delegation to camera.zoom() instead of hoisting
// not implemented directly, Graphics plugin will hoist this
}
}, {
key: "zoom",
value: function zoom(scale) {
if (this.camera && this.camera.zoom) {
this.camera.zoom(scale);
} else {
console.log('warning: no camera.zoom method found');
}
}
}, {
key: "shakeCamera",
value: function shakeCamera(intensity, duration) {
this.graphics.forEach(function (graphicsInterface) {
if (graphicsInterface.cameraShake) {
graphicsInterface.shakeCamera(intensity, duration);
}
});
}
}, {
key: "isTouchDevice",
value: function isTouchDevice() {
return 'ontouchstart' in window || navigator.maxTouchPoints;
}
//
// Asset and Styling APIs
//
}, {
key: "addAsset",
value: function addAsset(url, type, key, options) {
// game::ready event / game.start(cb) will wait for all assets to be loaded
if (this.preloader) {
this.preloader.addAsset(url, type, key, options);
} else {
this.queuedAssets[key] = path;
}
}
}, {
key: "addAssets",
value: function addAssets(assets) {
for (var a in assets) {
var asset = assets[a];
this.addAsset(asset.url, asset.type, a, asset);
}
}
}, {
key: "setBackground",
value: function setBackground(color) {
// not implemented directly, Graphics plugin will handle this
}
}, {
key: "createBorder",
value: function createBorder(_ref) {
var width = _ref.width,
height = _ref.height,
_ref$thickness = _ref.thickness,
thickness = _ref$thickness === void 0 ? 8 : _ref$thickness,
color = _ref.color;
var game = this;
if (game.systems.border) {
game.systems.border.createBorder({
width: game.width,
height: game.height,
thickness: thickness
});
} else {
game.use('Border', {}, function () {
game.systems.border.createBorder({
width: game.width,
height: game.height,
thickness: thickness
});
});
}
}
//
// Time APIs / ChronoControl
//
}, {
key: "stop",
value: function stop() {
var client = this.getSystem('client');
client.stop();
}
}, {
key: "pause",
value: function pause() {
if (this.systems['chrono-control']) {
this.systems['chrono-control'].pause();
}
}
}, {
key: "rewind",
value: function rewind(ticks) {
if (this.systems['chrono-control']) {
this.systems['chrono-control'].rewind(ticks);
}
}
}, {
key: "reset",
value: function reset(mode) {
var clearSutra = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
// reset all Sutra rules
if (clearSutra) {
this.rules = this.createSutra();
}
// remap the keyboard mappings to Sutra by default
if (this.systems.sutra) {
this.systems.sutra.bindInputsToSutraConditions();
}
// reset the Field of View use to default ( off )
this.config.useFoV = false;
// reset the default player controls
this.setControls({});
// set the default movement sutra
if (this.systems.sutra) {
this.systems.sutra.bindDefaultMovementSutra(mode);
}
// reset any deffered entities
this.deferredEntities = {};
// reset the camera offsets ( in case user has dragged or scrolled camera )
game.viewportCenterOffsetX = 0; // TODO: scope these onto game.data.camera.viewPortOffset
game.viewportCenterOffsetY = 0;
// defaults camera back to 1x zoom
game.zoom(1);
}
//
// Sutra Behavior Tree APIs
//
}, {
key: "useSutra",
value: function useSutra(subSutra, name) {
if (this.rules) {
this.rules.use(subSutra, name);
if (this.systems['gui-sutra']) {
this.systems['gui-sutra'].setRules(this.rules);
}
} else {
console.log('Warning: no rules engine found, cannot use sutra', subSutra, name);
}
}
}, {
key: "setActions",
value: function setActions(actions) {
var game = this;
var actionNames = Object.keys(actions);
actionNames.forEach(function (actionName) {
var action = actions[actionName];
game.rules.on(actionName, action);
});
}
//
// Networking APIs
//
}, {
key: "connect",
value: function connect(url) {
var game = this;
// Wait for all systems to be ready before starting the game loop
if (game.loadingPluginsCount > 0) {
setTimeout(function () {
game.connect(url);
}, 4);
return;
} else {
console.log('All Plugins are ready! Starting Mantra Game Client...');
var client = this.getSystem('client');
client.connect(url);
}
}
}, {
key: "disconnect",
value: function disconnect() {
var client = this.getSystem('client');
client.disconnect();
}
}]);
return Game;
}();
},{"./Component/Component.js":2,"./lib/Game/construct.js":10,"./lib/Game/start.js":11,"./lib/Game/use.js":12}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _eventEmitter = _interopRequireDefault(require("../lib/eventEmitter.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } // TODO: add events
var SystemsManager = /*#__PURE__*/function () {
function SystemsManager(game) {
_classCallCheck(this, SystemsManager);
this.game = game;
this.systems = new Map();
}
_createClass(SystemsManager, [{
key: "addSystem",
value: function addSystem(systemId, system) {
var _this = this;
if (this.systems.has(systemId)) {
// throw new Error(`System with name ${systemId} already exists!`);
console.log("Warning: System with name ".concat(systemId, " already exists!"));
return;
}
/*
All Plugins are event emitters feature ( DISABLED )
// Remark: Defaulting all Plugins to event emitters is disabled for now by default
// This is disabled for performance reasons, some of these methods are high frequency
// and there is wildcard search logic enabled by default? It's a bit much on performance for all enabled
// In the future we can add a config option per Plugin and per Plugin method to enable/disable this
// This will enable all plugin methods as emitted events
// eventEmitter.bindClass(system, systemId)
*/
// All Plugins have Lifecycle Hooks feature ( ENABLED DEFAULT )
// Remark: See: ./Game/Lifecyle.js for Mantra Lifecycle Hooks
// register the system methods as Lifecycle hooks
if (this.game.config.addLifecycleHooksToAllPlugins) {
var allProps = Object.getOwnPropertyNames(Object.getPrototypeOf(system));
var _iterator = _createForOfIteratorHelper(allProps),
_step;
try {
var _loop = function _loop() {
var propName = _step.value;
var originalMethod = system[propName];
if (typeof originalMethod === 'function' && propName === 'fireBullet') {
// Found the method
// console.log(`Method ${propName} found.`);
// Initialize hooks if they don't already exist
_this.game.lifecycle.hooks["before.".concat(systemId, ".").concat(propName)] = _this.game.lifecycle.hooks["before.".concat(systemId, ".").concat(propName)] || [];
_this.game.lifecycle.hooks["after.".concat(systemId, ".").concat(propName)] = _this.game.lifecycle.hooks["after.".concat(systemId, ".").concat(propName)] || [];
// Wrap the original method in a function that includes the lifecycle hooks
system[propName] = function () {
var arg1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var arg2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var arg3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
// Trigger the 'before' hook with up to three arguments
this.game.lifecycle.triggerHook("before.".concat(systemId, ".").concat(propName), arg1, arg2, arg3);
// Call the original method with up to three arguments
var result = originalMethod.call(this, arg1, arg2, arg3);
// Trigger the 'after' hook with up to three arguments
this.game.lifecycle.triggerHook("after.".concat(systemId, ".").concat(propName), arg1, arg2, arg3);
// Return the original method's result
return result;
}.bind(system); // Ensure 'this' within the wrapped function refers to the system object
}
};
for (_iterator.s(); !(_step = _iterator.n()).done;) {
_loop();
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
// binds system to local instance Map
this.systems.set(systemId, system);
// binds system to game.systems scope for convenience
this.game.systems[systemId] = system;
//console.log(`system[${systemId}] = new ${system.name}()`);
//console.log(`game.use(new ${system.name}())`);
}
}, {
key: "removeSystem",
value: function removeSystem(systemId) {
if (!this.systems.has(systemId)) {
//throw new Error(`System with name ${systemId} does not exist!`);
console.log("Warning: System with name ".concat(systemId, " does not exist!"));
return;
}
// call the system.unload method if it exists
var system = this.systems.get(systemId);
if (typeof system.unload === "function") {
system.unload();
}
this.systems["delete"](systemId);
// Remark: Special scope used for plugins, we can probably remove this or rename it
if (this.game._plugins[systemId]) {
delete this.game._plugins[systemId];
}
// we may want to remove the extra game.systems scope? or reference directly to the map?
delete this.game.systems[systemId];
}
}, {
key: "getSystem",
value: function getSystem(systemId) {
if (this.systems.has(systemId)) {
return this.systems.get(systemId);
}
throw new Error("System with name ".concat(systemId, " does not exist! Perhaps try running \"game.use(new plugins.").concat(systemId, "())\" first?"));
}
}, {
key: "update",
value: function update(deltaTime) {
var _iterator2 = _createForOfIteratorHelper(this.systems),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
_ = _step2$value[0],
system = _step2$value[1];
if (typeof system.update === "function") {
// check to see if the game is paused, if not, skip updates for systems without flag
if (this.game.paused) {
continue;
}
system.update(deltaTime);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
// Remark: Render control is being handled by graphics and each adapter
// TODO: Add test coverage and formalize rendering through this method, it is required for helpers developers customizerendering
}, {
key: "render",
value: function render() {
/*
const renderSystem = this.systems.get('render');
if (renderSystem && typeof renderSystem.render === "function") {
renderSystem.render();
}
*/
}
}]);
return SystemsManager;
}();
var _default = exports["default"] = SystemsManager;
},{"../lib/eventEmitter.js":14}],6:[function(require,module,exports){
"use strict";
var MANTRA = {};
MANTRA.Game = require('./Game.js').Game;
MANTRA.plugins = {}; // empty plugin scope, may be populated by using plugins
module.exports = MANTRA;
},{"./Game.js":4}],7:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
// Lifecycle.js - Marak Squires 2024
var Lifecycle = exports["default"] = /*#__PURE__*/function () {
function Lifecycle() {
_classCallCheck(this, Lifecycle);
this.hooks = {
// TODO: all all lifecycle events
'before.update': [],
'after.update': [],
//beforeRender: [],