Repository navigation
Expand file tree
/
Copy pathclasses.js
More file actions
2663 lines (2380 loc) · 81.5 KB
/
Copy pathclasses.js
File metadata and controls
2663 lines (2380 loc) · 81.5 KB
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
//#region types
/** The result of the operation.
* @typedef {Object} Result
* @property {boolean} success - Indicates whether the operation was successful.
* @property {*} result
*/
/**
* @typedef {"%" | "px" | "rem" | "vw" | "vh"} numberExtention
*/
/** Represents a pair of coordinates in the game.
* @typedef {Array<number, number>} GameCoords
*/
/** data of a Entity
* @typedef {Object} EntityData
* @property {Stat} speed - The movement speed of the entity, defining how far it can move with each step.
* @property {GameCoords} position - The starting position of the entity.
* @property {Stat} health - The health property of the entity.
* @property {Stat} specialPoints - Points used for special abilities.
* @property {{ health: Stat, specialPoints: Stat }} regen - The regeneration rate for health and special points per second.
* @property {Stat} attackStrength - The natural damage dealt by the entity.
* @property {Object} buffs - Any active buffs affecting the entity.
* @property {Object<string, Upgrade[]} upgrades - Any upgrades applied to the entity.
* @property {number} revives - The number of times the entity can be revived.
* @property {Array<Ability | Stat>} tracked - the tracked Stats and Abilities
*/
/** Valid event names
* @typedef {"health:0" | "health:25" | "health:50" | "damage" | "heal" | "collided" | "status"} EventName
*/
/**
* @typedef {Object} DamageSource
* @property {Entity | Projectile | undefined} attacker - The source of the damage, such as an entity or projectile.
* @property {"explosion" | "blont" | "stabing" | undefined} type - The type of damage dealt.
*/
/**
* @typedef {{type: string, number: number}} Upgrade
*/
/**
* @callback eventFunction
* @param {Entity} entity
* @param {...any} args
* @returns {Result}
*/
/** ability handler
* @callback abilityHanbler
* @param {Ability} ability
* @param {...any} args
* @returns {void}
*/
/** ability initelizer
* @callback abilityInitelizer
* @param {Ability} ability
* @returns {void}
*/
/**
* @callback descriptor
* @returns {String}
*/
/**@typedef {"none" | "random" | "aggressive" | "scared" | "chase" | "flee" | "wander" | "patrol" | "player"} AIType*/
/** Custom behavior data for the AI.
* @typedef {object} AIBehavior
* @property {number | Function} agro
* @property {number | Function} fear
* @property {number | Function} range
* @property {Object<number, number>} priority
* @property {Function | undefined} randomFunction
* @property {[number, number][]} patrolPoints
* @property {Entity} targeting
*/
/**@typedef {"common" | "uncommon" | "rare" | "epic" | "legendary" | "godly"} Rarity*/
//#region presets
/** JSON data
* @typedef {{
* entityPresets: Object<string, EntityPreset>,
* htmlPresets: Object<string, HtmlPreset>,
* abilityPresets: Object<string, AbilityPreset>}} JSONData
*/
/** JSON entity preset
* @typedef {Object} EntityPreset
* @property {"Player" | "none" | "AI"} entityType - the type of entity
* @property {Object} visual - Visual representation of the entity.
* @property {HTMLData} visual.html
* @property {HTMLData[]} visual.children
* @property {JSONEntityData} data - Data representing the entity's stats and abilities.
*/
/** JSON HTML element preset
* @typedef {Object} HtmlPreset
* @property {HTMLData} visual - Visual representation of the HTML element.
* @property {HTMLData[]} children
*/
/** HTML data
* @typedef {Object} HTMLData
* @property {string | number} name
* @property {string | number} id - ID of the HTML element.
* @property {string} type - Type of the HTML element (e.g., "div").
* @property {[number, number, numberExtention]} size - Size of the element [width, height, unit].
* @property {{top: number, left: number, right: number, bottom: number, z: number types: numberExtention | Object<string, numberExtention>}} position
* @property {Object} style - CSS styles for the element.
* @property {Object} attributes
* @property {string} text
* @property {string} label - a input label
* @property {HTMLData[]} content
*/
/**entity data
* @typedef {Object} JSONEntityData
* @property {Object<string, {value: number, min:number, max:number}} stats - Statistics of the entity.
* @property {string[]} abilities - Abilities assigned to the entity.
* @property {object} ai - the logic controler of the entity
* @property {AIType} ai.aiType - the type of ai
* @property {AIBehavior | "empty"} ai.behavior
*/
/** JSON ability preset
* @typedef {Object} AbilityPreset
* @property {string} name - The name of the ability.
* @property {number} cooldownTime - The cooldown time in milliseconds.
* @property {Rarity} rarity - how rare the ability is
* @property {Object} data - Data representing the ability's properties.
* @property {string | descriptor} description - Description of the ability (instance)
* @property {Object} logic - Logic for the ability's behavior.
* @property {Object} logic.call - Function call logic for the ability.
* @property {string} logic.call.type - The type of the function.
* @property {Object} logic.call.params - Parameters for the function.
* @property {string} logic.call.params.ability - The ability parameter.
* @property {string} logic.call.params.user - The user parameter.
* @property {string} logic.call.code - The code to execute.
* @property {Object} logic.initialize - Initialization logic for the ability.
* @property {string} logic.initialize.type - The type of the function.
* @property {string} logic.initialize.description - Description of the function.
* @property {Object} logic.initialize.params - Parameters for the function.
* @property {string} logic.initialize.params.ability - The ability parameter.
* @property {string} logic.initialize.code - The code to execute.
*/
/** JSON callebal construction data
* @typedef {Object} CallebolConstructionData
* @property {string} description - Description of the function.
* @property {Object} params - Parameters for the function.
* @property {string} code - The code to execute.
*
*/
//#endregion
//#endregion
//#region classes
/** Represents an entity in the game.*/
class Entity {
//#region propertys
#isPlayer = false
#active = true
#position
#size = [NaN, NaN]
facing = "up"
currentAngle = 0
abilitys = {} //name: function
/**@type {Object<string, Weapon>} */
sides = {left: undefined, right: undefined, top: undefined, down: undefined}// aqipment
/**@type {Object<string, eventFunction>}*/
#events = {}
/** @type {EntityData}*/
data
static nonEntity = new Entity("null") // domie instance
//#endregion
/**
* @param {string|number} html_element_id - The ID of the HTML element representing the entity.
* @param {EntityData} [data={}] - Additional data for the entity.
* @param {boolean} [isPlayer=false] - Indicates if the entity is controlled by a player.
*/
constructor(html_element_id, data = {}, isPlayer = false) {
if (html_element_id === "null") {// dummie instance
this.id = "null";
this.element = null;
this.#position = [0, 0];
this.#size = [0, 0];
this.data = {};
this.#isPlayer = false;
this.style = {}
return;
}
const GAME = Game.instance
if (!Game.Active) throw new Error("game is not active");
if (typeof html_element_id !== "string" && typeof html_element_id !== "number")
{throw new Error("Invalid ID");}
const entity = this
this.element = document.getElementById(html_element_id);
const element = this.element
if (!element) throw new Error(`Element with ID "${html_element_id}" not found.`);
//#region propertys
this.id = html_element_id;
this.#position = [element.offsetLeft, element.offsetTop];
this.#size = [element.offsetWidth, element.offsetHeight];
this.#isPlayer = isPlayer;
this.style = element.style;
this.data = { speed: new Stat("speed", 10, [NaN, 0]), ...data };
this.style.position = "absolute";
//#endregion
// Logic
const {minSize, maxSize} = GAME;
this.#size = this.#size.map((dim) => {
if (dim > maxSize) return maxSize;
if (dim < minSize) return minSize;
return Math.round(dim);
});
this.width = this.#size[0]
this.height = this.#size[1]
//#region data prosesing
//#region position preset
if (data.position){
this.goTo(...data.position)
delete data.position
}
//#endregion
//#region style
if (data.style){
for (const style in data.style) this.style[style] = data.style[style];
delete data.style
}
//#endregion
//#region health
if (data.health){
let {health, maxHealth} = data
if(!(health instanceof Stat) && (typeof health != "number" || health <= 0 || isNaN(health)))
throw new TypeError("invalid healt value")
if(typeof health == "number") health = new Stat(
"hp", //name
health, //value
[
Math.max(maxHealth ?? health, health), //max
0,// min
]
)
health.onChange = () => entity.checkHealt()
this.data.health = health
}
//#endregion
//#region move speed
if(data.speed){
let {moveSpeed} = data.speed
if(!(moveSpeed instanceof Stat) && typeof moveSpeed != "number" || isNaN(moveSpeed))
throw new TypeError("invalid moveSpeed value")
if(typeof moveSpeed === "number") moveSpeed = new Stat("speed", moveSpeed)
console.debug(`moveSpeed of ${this.id} = ${moveSpeed}`);
this.data.speed = moveSpeed
}
else console.debug(`${this.id}'s speed has not been set as its given movespeed is: ${data.speed}`);
//#endregion
//#endregion
GAME.addEntity(this)
}
//#region getters & setters
get isPlayer() {return this.#isPlayer;}
get position() {return this.#position;}
get borderCords() {// returns the cords of the border
const offset = this.size.map((size => size/2))
return{
"left": this.position[0] - offset[0],
"right": this.position[0] + offset[0],
"top": this.position[1] - offset[1],
"bottom": this.position[1] + offset[1],
}
}
get hitbox(){
return Math.min(...this.size) * 0.75
}
get width() {return parseFloat(this.style.width) || 0;}
set width(width) {
if (typeof width !== "number") throw new Error("Width must be a number");
this.style.width = `${width}px`;
}
get height() {return parseFloat(this.style.height) || 0;}
set height(height) {
if (typeof height !== "number") throw new Error("Height must be a number");
this.style.height = `${height}px`;
}
get size() {return this.#size;}
set size(size) {
if (!Array.isArray(size)) {
if (typeof size === "number") {
if(Math.min(size) < Math.max(size)/2) return
size = [size, size];
} else {
console.warn("Size must be a number or an array of two numbers.");
return;
}
}
if (size.length !== 2 || size.some(dim => typeof dim !== "number")) {
console.warn("Array must contain exactly two numbers.");
return;
}
this.#size = size;
this.style.width = `${size[0]}px`;
this.style.height = `${size[1]}px`;
}
get closestEntity() {
let otherEntity = Entity.nonEntity; // To store the closest entity
// Loop through all entities
Game.instance.entities.forEach((entity) => {
if(!(entity instanceof Entity)) throw new Error("a Object has been found that is not a instance of the Entity class")
if (entity === this || entity === Entity.nonEntity || !entity) return; // Skip itself
if (!Entity.isEntity(otherEntity)) {
otherEntity = entity
return
}
let distance = this.getDistanceToEntity(entity);
if (!otherEntity || distance < this.getDistanceToEntity(otherEntity)) otherEntity = entity;
});
if(otherEntity == Entity.nonEntity) throw new Error("no valid entity was returned");
return otherEntity;
}
//#endregion
//#region events
get events(){
const entity = this
return new Proxy(this.#events, {
get: (target, prop) => target[prop],
set: (_, eventType, handler) => {entity.addEvent(eventType, handler)},
deleteProperty: (_, prop) => {entity.removeEvent(prop)}
})
}
/**Adds an event handler to the entity.
* @param {EventName} eventName - The name of the event to add.
* @param {eventFunction} handler - The function to execute when the event is triggered.
* @throws {TypeError} - If the event type is not a string, or if the handler is not a function.
*/
addEvent(eventName, handler) {
if (typeof eventName !== "string") throw new TypeError("Invalid event type: must be a string.");
if (typeof handler !== "function") throw new TypeError("Invalid handler: must be a function.");
// Add the event handler to the internal #events object.
this.#events[eventName] = handler;
}
/** Removes an event handler from the entity.
* @param {EventName} eventName - The name of the event to remove.
* @throws `TypeError` - If the event type is not a string.
* @warns if the event dusent exist
*/
removeEvent(eventName) {
if (typeof eventName !== "string") throw new TypeError("Invalid event type: must be a string.");
// Check if the event exists before attempting to delete.
if (!this.#events[eventName]) {
console.warn(`Event "${eventName}" does not exist.`);
return;
}
// Remove the event handler from the internal #events object.
delete this.#events[eventName];
}
/**
* @param {EventName} eventName
* @param {...any} args
* @returns {result}
*/
triggerEvent(eventName, ...args) {
if (!this.#events[eventName]) return {success: false, result: undefined};
const result = this.#events[eventName](this, ...args);
return {success: true, result: result};
}
//#endregion
//#region movement
move(x = 0, y = 0) {
if (!this.#active) return;
if(typeof x != "number" || typeof y != "number" || ![x,y].map((cord) => isNaN(cord)))
throw new TypeError(`invalid values:x: ${x}, y: ${y}`)
// Update position
this.#position[0] += Math.round(x);
this.#position[1] += Math.round(y);
// Update facing direction based on movement
if (x !== 0 || y !== 0) this.updateFacingDirection(x, y);
// Ensure entity stays within bounds
this.checkBounds();
}
goTo(x = 0, y = 0, bounded=false) {
// Update position
this.#position = [x, y];
// Since goTo does not involve incremental movement, keep the current facing direction
if(bounded) this.checkBounds()
}
updateFacingDirection(x, y) {
const directions = Game.directions.object;
const directionVector = [x, y].map((value) => (value > 0 ? 1 : value < 0 ? -1 : 0));
let newFacing = "none"; // Default facing
for (const dir in directions) {
if (JSON.stringify(directions[dir]) === JSON.stringify(directionVector)) {
newFacing = dir;
break;
}
}
if (this.facing !== newFacing) {
this.facing = newFacing;
this.updateRotation(); // Update rotation smoothly
}
}
updateRotation() {
const angles = {
up: 0,
right: 90,
down: 180,
left: 270,
upRight: 45,
downRight: 135,
downLeft: 225,
upLeft: 315,
};
this.currentAngle >=0 ? this.currentAngle = -1000 : void 0
const targetAngle = angles[this.facing] ?? 0; // Get target angle for the new facing
const angleDiff = ((targetAngle - this.currentAngle + 540) % 360) - 180; // Shortest rotation path
this.currentAngle += angleDiff; // Update current angle
//console.log(targetAngle, angleDiff, this.currentAngle);
// Apply rotation
this.style.rotate = `${this.currentAngle}deg`;
}
updatePosition() {
const zero = Game.instance.zero; // The center of the game window
this.style.left = `${zero[0] + this.#position[0]}px`; // Convert gameCords to DOM position
this.style.top = `${zero[1] + this.#position[1]}px`;
}
checkBounds() {
const gameBorder = Game.instance.borderCords; // New object each time
const entityBorder = this.borderCords;
const offset = [this.width / 2, this.height / 2];
// Adjust the border for offsets
let i = 0;
for (const cord in gameBorder) {
i++;
if (i % 2 === 1) gameBorder[cord] -= i > 2 ? offset[0] : offset[1]; // Adjust left and top
else gameBorder[cord] += i > 2 ? offset[0] : offset[1]; // Adjust right and bottom
}
// Update entity position if it exceeds game bounds
if (entityBorder.left < gameBorder.left)
this.#position[0] = gameBorder.left + offset[0];
if (entityBorder.right > gameBorder.right)
this.#position[0] = gameBorder.right - offset[0];
if (entityBorder.top < gameBorder.top)
this.#position[1] = gameBorder.top + offset[1];
if (entityBorder.bottom > gameBorder.bottom)
this.#position[1] = gameBorder.bottom - offset[1];
// Check collisions
Game.instance.checkColision();
}
//#endregion
//#region health
/**@returns {boolean}*/
checkHealt(recheck=0){
const {health} = this.data
const healthLevel = this.healthLevel
/**@type {Number} */
this.oldHealtLevel = this.oldHealtLevel ?? 100
if(!health) return void 0// checks if the entity has a healt stat
if(healthLevel <=50 && this.oldHealtLevel > 50){
console.log(`${this.id}'s health has droped to 50%`);
this.triggerEvent("health:50")
}
if(healthLevel <= 25 && this.oldHealtLevel > 25){
console.log(`${this.id}'s health has droped to 25%`);
this.triggerEvent("health:25")
}
if(healthLevel <= 10 && this.oldHealtLevel > 10){
console.log(`${this.id}'s health has droped to 10%`);
this.triggerEvent("health:1")
}
if(healthLevel === 0 || health.value === 0){
console.log(`entity(${this.id})'s healt has reachd 0%`)
this.triggerEvent("health:0")
return false
}
this.oldHealtLevel = health.value
if(recheck) this.checkHealt(recheck--)
return true
}
get healthLevel(){
const health = this.data.health
if(!(health instanceof Stat)) {
console.warn(`${this.id}'s health stat is a ${typeof health} instead of a Stat instance`);
return NaN
}
return health.level
}
/**
* @param {number} damage
* @param {DamageSource} sourch
*/
damage(damage, sourch=undefined) {
if (typeof damage !== "number" || isNaN(damage))
throw new Error("Invalid damage: must be a number.", typeof damage);
// Trigger the "damage" event and allow handlers to modify the damage.
const { success, result } = this.triggerEvent("damage", damage, sourch);
//console.log(damage);
if (success) {
if (typeof result?.damage === "number" && result.damage >= 0) damage = result.damage;
else console.warn("Damage event handler did not return a valid damage value.");
}
//console.log(damage);
if (!this.data.health) return; // Skip if the entity has no health property.
// Ensure damage does not exceed current health or go negative.
damage = Math.min(Math.max(damage, 0), this.data.health);
// Apply the damage.
const health = this.data.health
if(!(health instanceof Stat)) return
health.value -= damage;
//console.log(`${this.id} took ${damage} damage, remaining health: ${health.value}`);
}
//#endregion
//#region helper functions
/**
* @param {Entity} otherEntity
* @returns {number} the distance in pixels
*/
getDistanceToEntity(otherEntity) {
if (!(otherEntity instanceof Entity))
throw new Error("The argument must be an instance of Entity.");
const distance = this.getDistanceToPoint(otherEntity.position)
return distance;
}
getDistanceToPoint(point){
if (!Array.isArray(point) || point.length !== 2 || typeof point[0] !== "number" || typeof point[1] !== "number")
throw new TypeError("Invalid position");
const [x1, y1] = this.position;
const [x2, y2] = point;
return Math.hypot(x2 - x1, y2 - y1);
}
getDirection(x, y, debug = false) {
const differences = [x, y].map((coord, index) => {
const diff = coord - this.position[index];
return diff > 0 ? 1 : diff < 0 ? -1 : 0;
});
if (debug) console.log(differences);
return differences;
}
/** delets the entity*/
destroy(gameEnd=false){
if(this instanceof NPC) this.ai.stop()
if(!gameEnd)console.log(`${this.id} has been defetet`);
this.#active = false
Game.instance.romoveEntity(this.id)
if(this instanceof NPC) delete this.ai
try {
this.element.remove()
} catch (error) {
if(!document.getElementById(this.id)) return
else throw new Error(error);
}
}
//#endregion
//#region defalt events
/**
* @param {EventName} eventName
* @returns {eventFunction}
*/
static defaultEvent(eventName){
switch (eventName) {
case "health:0":return (entity) => entity.destroy()
default:throw new TypeError("invalid eventName");
}
}
//#endregion
//#region static
/** returns weater the entity is a entity
* @param {Entity} entity
* @returns {Boolean}
*/
static isEntity(entity){return (entity && entity !== Entity.nonEntity)}
//#endregion
}
/** Represents a Non-Player Character (NPC) with AI-driven behavior. */
class NPC extends Entity {
/**
* @param {string} id - The unique identifier for the NPC.
* @param {AI} ai - The AI instance controlling the NPC.
* @param {Object} [data={ moveSpeed: 10 }] - Additional configuration for the NPC.
* @throws {Error} Throws if `ai` is not an instance of AI.
*/
constructor(id, ai, data = { moveSpeed: 10 }) {
if (!(ai instanceof AI)) throw new Error("An NPC requires a valid AI instance.");
super(id, data);
this.ai = ai;
ai.entity = this;
}
/**
* Executes the AI-driven movement logic for the NPC.
* Ensures the NPC's position is updated visually and logically.
*/
ComputerMove() {
if (this === window) {
console.error("Entity cannot be the window object.");
return;
}
// Check if AI is defined
if (!this.ai) {
console.error("AI is not defined for this NPC.");
return;
}
// Get movement direction from AI
const direction = this.ai.direction();
if (!Array.isArray(direction) || direction.length !== 2) {
console.error("AI provided an invalid direction. Expected [x, y].");
return;
}
// Apply movement, scaling by moveSpeed
this.move(...direction.map((cord) => cord * (this.data.speed || 1)));
// Update the visual position
this.updatePosition();
// Trigger any external updates, if required
if (typeof updateOutput === "function") updateOutput();
}
}
/** Represents the Player.
* Extending the `Entity` class.
* Enforces a singleton pattern to ensure only one player instance exists.
*/
class Player extends Entity {
/** the loded player instance
* @type {Player}
*/
static instance;
static userData = {
name: "player",
score: 0,
abilities: {move: undefined},// abilities: keybord key, function
entity: undefined, //new Player
settings: {
movement: {
left: "a",
right: "d",
up: "w",
down: "s"
},
playerColor: "blue",
},
/**@type {key} */
keyPresses: {},
rewards: {upgrades: [], abilities: [], healhs: 0, length:0}
}
cords = [0,0]
#active = false;
/**
* @param {} data
* @param {EntityData} mods
* @returns
*/
constructor(mods = {}, ...{data = {}}) {
if (Player.instance instanceof Player) return Player.instance;
super("player", {
health: 200,
}, true);
Player.instance = this;
if(data.ai) this.controler = data.ai
else
this.controler = new AI("player", {
movement: { c: Ability.getAbility("dash"),
" ": Ability.getAbility("shoot") },
});
this.controler.entity = this;
// Initialization
this.#active = true;
this.data.onCooldown = {};
this.addEvent("damage", (entity, damage, source) => {
if (typeof damage !== "number") throw new TypeError("Damage must be a number.");
this.data.health.value -= damage
});
this.addEvent("health:0", (player) => {
if (!(player instanceof Player)) throw new Error("Invalid player instance.");
player.active = false;
if(player){}
});
this.sides.top = Weapon.defaultWeapon(this)
// Apply styles
this.style.backgroundColor = Player.userData.settings.backgroundColor;
}
//#region static functions
/** Updates the player's state based on user inputs or AI controls. */
static updatePlayer() {
if (!(Player.instance instanceof Player)) {
console.log("Waiting for player to load...");
setTimeout(Player.updatePlayer, 500);
return;
}
const user = Player.instance;
const directions = Game.directions.object;
const controls = Player.userData.settings.movement;
// Map keys to actions
const keyList = Object.entries(controls).reduce((acc, [action, key]) => {
acc[key] = action;
return acc;
}, {});
const moves = { ...user.controler.behavior.moves, ...keyList };
const player = Player.userData
const {keyPresses} = player
let directionToMoveIn = { left: 0, right: 0, up: 0, down: 0 };
let hasMoved = false;
// Handle pressed keys
Object.keys(keyPresses).forEach((key) => {
if (!moves[key]) return; // Skip undefined actions
const action = moves[key];
if (Object.values(controls).includes(key) && !player.moveOnCooldown) {
// Handle movement
hasMoved = Player.handleMovement(action, directionToMoveIn) || hasMoved;
} else if (!Object.values(controls).includes(key)) {
// Handle abilities
Player.handleAbility(action, user);
}
});
if (hasMoved) {
let toMove = [0, 0];
toMove[0] -= (directionToMoveIn.left ?? 0) - (directionToMoveIn.right ?? 0);
toMove[1] -= (directionToMoveIn.up ?? 0) - (directionToMoveIn.down ?? 0);
if (toMove[0] && toMove[1]) toMove = toMove.map((cord) => cord / 2);
user.move(toMove);
player.moveOnCooldown = true;
setTimeout(() => (player.moveOnCooldown = false), 50);
}
}
/** Handles directional movement.
* @param {string} action - The action (e.g., "left", "right", "up", "down").
* @param {Object} directionToMoveIn - Tracks the active directions.
* @returns {boolean} Whether movement was handled.
*/
static handleMovement(action, directionToMoveIn) {
switch (action) {
case "left":
directionToMoveIn.left = 1;
return true;
case "right":
directionToMoveIn.right = 1;
return true;
case "up":
directionToMoveIn.up = 1;
return true;
case "down":
directionToMoveIn.down = 1;
return true;
default:
console.warn(`Unknown movement action: ${action}`);
return false;
}
}
/** Handles ability usage.
* @param {object|string} action - The ability or invalid action.
* @param {Player} user - The player using the ability.
*/
static handleAbility(action, user) {
if (typeof action === "object" && typeof action.use === "function") action.use(user);
else console.warn(`Invalid or undefined ability action: ${action}`);
}
//#endregion
/** Moves the player in a given direction, applying speed.
* @param {number[]} direction - The [x, y] movement vector.
*/
move(direction) {super.move(...direction.map((cord) => cord * this.data.speed));}
/** Applies player-specific settings (e.g., color). */
applySettings() {this.style.backgroundColor = Player.settings.playerColor;}
/**
* @param {Stat | Ability} toAd
*/
addToHub(toAd){
}
//#region getters and setters
/** Whether the player is active.
* @returns {boolean}
*/
get active() {return this.#active;}
set active(bool) {
if(!(typeof bool == "boolean")) throw new TypeError("active has to be a bool");
this.#active = bool
}
//#endregion
static setupKeyListeners() {
const keyPresses = Player.userData.keyPresses
window.addEventListener("keydown", (e) => {
const key = e.key.toLowerCase();
if (!key.includes("f") || key === "f") keyPresses[key] = true;
});
window.addEventListener("keyup", (e) => {
delete keyPresses[e.key.toLowerCase()];
});
Player.instance.updateIntervale = setInterval(Player.updatePlayer, 26)
}
}
/** Represents a projectile in the game. */
class Projectile {
/**A list of all active projectiles in the game.
* @type {Projectile[]}
*/static activeProjectiles = [];
/**Default stats for projectiles.*/
static get defaultStats() {return {
speed: new Stat("speed", 20, [200, 0]),
atk: new Stat("ATK", 10),
hp: new Stat("health", 1, [1, 1]),
drag: new Stat("drag", 0), // Reduces speed over time by this amount
range: new Stat("range", 10)
};
}
#stats = Projectile.defaultStats
#onHit = Ability.getAbility("explode", {damage: 10, range: 10})
target = { type: "direction", data: "up" }; // Type: [entity, direction, point]
position = [0, 0];
/**
* @param {Entity} owner - The entity that owns this projectile.
* @param {Object<string, Stat>} stats - Custom stats for the projectile.
* @param {number[]} position - Initial position of the projectile as [x, y].
* @param {Object} target - The target of the projectile (type and data). `valid types` - [direction, point, entity]
* @param {Object} data - Additional metadata.
* @throws {TypeError} If the owner is not a valid `Entity` or stats are invalid.
*/
constructor(owner = Entity.nonEntity, stats = Projectile.defaultStats, position = [NaN], target, data = {}) {
if (!(owner instanceof Entity) && owner !== Entity.nonEntity) {
throw new TypeError("Owner has to be an Entity or Entity.nonEntity");
}
for (const statKey in stats) {
if (!(stats[statKey] instanceof Stat)) {
throw new TypeError(`Invalid stat: ${statKey}`);
}
}
this.owner = owner;
this.#stats = { ...Projectile.defaultStats, ...stats };
this.target = target;
// Create visual representation
this.element = document.createElement("div");
this.style = this.element.style;
this.style.width = "2.5px";
this.style.height = "2.5px";
this.style.backgroundColor = "red";
this.style.position = "absolute";
if (!isNaN(position[0] && !isNaN(position[1])) && Array.isArray(position)) {
this.position = position;
//console.debug("Projectile has valid coordinates");
} else {
this.position = this.elementPosition;
//console.debug("Projectile has invalid coordinates");
}
Game.instance.window.appendChild(this.element);
Projectile.activeProjectiles.push(this);
// Start movement
this.moveInterval = setInterval(() => this.updatePosition(), 64);
}
//#region getters and setters
/**The stats of the projectile.*/
get stats() {return this.#stats;}
/**The ability triggered upon collision or destruction.*/
get onHit() {
//console.debug(this.#onHit);
return this.#onHit;
}
/**Sets the on-hit ability.*/
set onHit(ability) {
if (!(ability instanceof Ability)) {
throw new TypeError("onHit must be an instance of Ability");
}
this.#onHit = ability;
}
/**The current position of the `Projectile` element in game coordinates as [`x`, `y`].*/
get elementPosition() {return Game.instance.gamePosition(this.element);}
set elementPosition(newCords) {
if (!Array.isArray(newCords) || newCords.length !== 2 ||
typeof newCords[0] !== "number" || typeof newCords[1] !== "number") {
throw new TypeError("newCords must be an array of two numbers [x, y]");
}
this.position = newCords;
newCords = newCords.map(cord => Game.instance.size / 2 + cord);
this.style.left = `${newCords[0]}px`;
this.style.top = `${newCords[1]}px`;
}
/**
* @returns True if the projectile is out of game bounds.
*/
get isOutOfBounds() {
return (
this.position[0] < Game.instance.borderCords.left ||
this.position[0] > Game.instance.borderCords.right ||
this.position[1] < Game.instance.borderCords.top ||
this.position[1] > Game.instance.borderCords.bottom
);
}
//#endregion
/**Updates the projectile's position based on its target and speed.*/
updatePosition() {
const { speed, drag } = this.#stats;
let directionVector = [0, 0];
switch (this.target.type) {
case "direction":
directionVector = Game.directions.object[this.target.data];
break;
case "point":
case "entity":
const targetPos = this.target.type === "point" ? this.target.data : this.target.data.position;
const dx = targetPos[0] - this.position[0];
const dy = targetPos[1] - this.position[1];
const magnitude = Math.sqrt(dx ** 2 + dy ** 2) || 1;
directionVector = [dx / magnitude, dy / magnitude];
break;
default:
console.warn("Invalid target type");
}
speed.value -= drag / 60;
this.position = this.position.map((cord, index) => {
return cord + (directionVector[index] * speed);