-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
3046 lines (2600 loc) · 111 KB
/
index.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
const IS_ACTIVE = true;
const DRAWING = {
grid: false,
hitbox: true,
treeSpot: true,
visitedAreas: true,
monsterVision: true,
path: true,
monsterScore: true,
}
dw.debug = true;
let lastPosition = { x: dw.character.x, y: dw.character.y };
let lastMoveTime = Date.now();
let bestTarget = null
const visitedPositions = []
let lastPath = null; // Stores the last computed path
let lastComputationTime = 0; // Stores the timestamp of the last path computation;
/**
* Configuration constants used throughout the code.
* @constant
* @type {Object}
* @property {number} visionConeAngle - The angle of the cone of vision in radians.
* @property {number} visionConeRadius - The radius of the cone of vision.
* @property {number} predictionTime - The number of seconds to predict future positions in the cone of vision.
* @property {number} pathStepSize - The step size for the pathfinding algorithm.
* @property {number} maxPathfindingIterations - The maximum number of iterations allowed in the pathfinding algorithm.
* @property {number} interpolationSteps - The number of interpolation steps for linear interpolation.
* @property {number} gooProximityRange - Radius to check the proximity of "goo" monsters.
* @property {number} monsterProximityRange - Radius to check the proximity of other monsters.
*/
const SETTINGS = {
gameLoopInterval: 400,
globalProximityToAction: 0.5,
globalSafePositioning: 0.2,
pathProximity: 0.7,
visionConeAngle: Math.PI,
visionConeRadius: 3.2,
pathStepSize: 0.75,
maxPathfindingIterations: 500,
interpolationSteps: 20,
gooProximityRange: 1,
monsterProximityRange: 1,
zoneLevelSuicide: 53,
idleTime: 30,
needRecoveryHpTreshold: 0.8,
};
/**
* Configuration flags for various behaviors
*/
const CONFIG = {
plantTree: false,
getResources: false,
optimizePath: true,
exploreNewAreas: true,
removeItems: false,
combineItems: false,
recycleItems: false,
sortItems: true,
suicideAtZoneLevel: false,
suicideUnderground: false,
attackNextScoreMonster: true,
moveToMission: false,
moveToShrub: false,
enableRecoveryDistance: true,
followAllied: false,
};
const SKILLS = {
attack: {
enable: true,
index: 0,
range: 0.7,
},
exertion: {
enable: true,
index: 1,
range: 0.7,
hpThreshold: 24000,
},
conservation: {
enable: false,
index: 1,
range: 0.7,
hpThreshold: 1,
},
shield: {
enable: true,
index: 3,
range: 0.5,
withBomb: false
},
heal: {
enable: true,
index: 2,
range: 0.5,
hpThreshold: 1,
hpThresholdMin: 0.4,
withExertion: true,
withMasochism: false,
withGraft: true
},
heal_alternative: {
enable: false,
index: 2,
range: 0.5,
hpThreshold: 0.6,
withMasochism: false
},
buff: {
enable: true,
index: 6,
range: 0.75,
},
dash: {
enable: true,
index: 4,
range: 2,
minRange: 1.5
},
teleport: {
enable: true,
index: 5,
range: 4.1,
minRange: 0,
minSavedRange: 0
},
graft: {
enable: false,
index: 3,
range: 2.60
},
arrow: {
enable: false,
index: 9,
range: 3
},
taunt: {
enable: true,
index: 5,
range: 0.88
},
aoe: {
enable: false,
index: 9,
range: 0.88
},
}
const ITEMS = {
global: {
min_any_mod_quantity: 6,
min_any_mod_quality: 12,
mods_to_keep: [],
tags_to_keep: [],
mds_to_keep: []
},
weapon: {
mods: [
"physDmgIncLocal",
"physDmgLocal",
"critLocal"
],
conditions: {
operator: "AND",
conditions: [
{
condition: "min_quantity",
value: 2
},
{
condition: "min_quality",
value: 6,
},
{
condition: "min_sum_quality",
value: 8
},
]
}
},
accessory: {
mods: ["dmg", "physDmg"],
conditions: {
operator: "AND",
conditions: [
{
condition: "min_quantity",
value: 2
},
{
condition: "min_quality",
value: 5
},
{
condition: "min_sum_quality",
value: 8
}
]
}
},
belt: {
mods: ["dmg", "physDmg"],
conditions: {
operator: "AND",
conditions: [
{
condition: "min_quantity",
value: 2
},
{
condition: "min_quality",
value: 5
},
{
condition: "min_sum_quality",
value: 8
},
]
}
},
glove: {
mods: ["hp", "physDmg"],
conditions: {
operator: "AND",
conditions: [
{
condition: "min_quantity",
value: 2
},
{
condition: "min_quality",
value: 5
},
{
condition: "min_sum_quality",
value: 8
}
]
}
},
armor: {
mods: ["hp", "mp"],
conditions: {
operator: "AND",
conditions: [
{
condition: "min_quantity",
value: 2
},
{
condition: "min_quality",
value: 5
},
{
condition: "min_sum_quality",
value: 8
}
]
}
},
passive: {
mods: [
"hpInc",
"hpRegenInc",
"gcdr",
"crit", "critMult",
"physDmg", "physDmgInc", "physDmgMore",
"dmg", "dmgInc", "dmgMore",
"fireDmg", "fireDmgInc", "fireDmgMore"
],
conditions: {
operator: "OR",
conditions: [
{
condition: "min_quantity",
value: 2
},
{
condition: "min_quality",
value: 3
},
]
}
},
combine: ["wood", "portalScroll", "essence", "dust"],
remove: ["flax", "rawhide", "linenCloth"]
};
const SCORE = {
monster: {
/**
* Base score for all monsters.
* Ensures that monsters have a starting priority over resources.
*/
baseScore: 15,
missionIdScore: 50,
/**
* Bonus if the monster is injured (current HP < max HP).
* Prioritizes monsters that are easier to defeat due to lower HP.
*/
injuredBonus: 50,
/**
* Large bonus if the monster is specifically targeting the player character.
* Prioritizes immediate threats that are actively engaging the player.
*/
targetCharacterBonus: 500,
/**
* Negative adjustment if the monster is marked as huntable.
* Reduces priority for huntable monsters, which are less urgent to defeat.
*/
canHunt: -100,
/**
* Multiplier for rare monsters based on their rarity level.
* If the rarity or HP exceeds the thresholds, the monster is harder to defeat,
* and should be deprioritized. Higher rarity increases the score unless too difficult.
*/
rareMonsterMultiplier: 15,
/**
* Rarity level threshold. Monsters with rarity above this level are avoided,
* as they are considered too strong to defeat.
*/
rareMonsterLimit: 6,
/**
* HP threshold. Monsters with max HP above this level are avoided,
* as they are considered too tough to handle, even if their rarity is low.
*/
rareMonsterHpThreshold: +Infinity,
/**
* Global HP threshold
*/
hpThreshold: +Infinity,
hpThresholScore: -100,
},
resource: {
/**
* Base score for resources. Generally negative because resources are deprioritized
* compared to monsters, unless gathering resources is specifically required.
*/
baseScore: 0
},
proximity: {
/**
* Negative adjustment for proximity to "goo" monsters.
* This score is applied for EACH goo near the target. Attacking near goo is risky
* because multiple goos can merge to form a much stronger goo monster.
*/
goo: -10,
/**
* Negative adjustment for each nearby monster around the target.
* This penalty is applied for EACH nearby monster, encouraging prioritization of
* safer fights with fewer monsters in close proximity.
*/
nearbyMonster: -30,
/**
* Distance-based multiplier that reduces the score based on the distance to the target.
* Applied for both monsters and resources, with closer targets prioritized over distant ones.
*/
distanceMultiplier: -1
},
levelDifference: {
/**
* Enable or disable score adjustments based on the difference in levels between the player and the monster.
* When enabled, monsters with a level closer to the player's level receive higher priority.
*/
enabled: false,
/**
* Bonus for monsters that are the same level as the player.
* These monsters are considered the most balanced challenges and are prioritized.
*/
sameLevelBonus: 20,
/**
* Adjustment factor applied for each level of difference between the player and the monster.
* Larger level differences, whether higher or lower, decrease the score.
*/
differenceFactor: 5
},
path: {
/**
* Negative adjustment if there are monsters along the path to the target.
* This penalty is applied for EACH monster along the path, as these obstacles
* make it harder to reach the target without facing additional combat.
*/
monstersAlongPath: -20
}
};
const protectList = ["Fireling"];
const healList = [];
const DEBUG = {
lastMessage: null,
log(message) {
if(!DEBUG.lastMessage || message !== DEBUG.lastMessage) {
DEBUG.lastMessage = message
dw.log(message)
}
}
}
/**
* Utility functions for vector and position calculations.
* @namespace
*/
const Util = {
/**
* Calculates the magnitude (length) of a vector.
* @param {Object} vec - The vector with x and y components.
* @returns {number} The magnitude of the vector.
*/
magnitude(vec) {
return Math.sqrt(vec.x * vec.x + vec.y * vec.y);
},
/**
* Calculates the dot product of two vectors.
* @param {Object} v1 - The first vector.
* @param {Object} v2 - The second vector.
* @returns {number} The dot product of the two vectors.
*/
dotProduct(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
},
/**
* Calculates the angle between two vectors in radians.
* @param {Object} v1 - The first vector.
* @param {Object} v2 - The second vector.
* @returns {number} The angle between the vectors in radians.
*/
angleBetween(v1, v2) {
const dot = this.dotProduct(v1, v2);
const mag1 = this.magnitude(v1);
const mag2 = this.magnitude(v2);
return Math.acos(dot / (mag1 * mag2));
},
/**
* Checks if a point is within the vision cone of an observer.
* @param {Object} observer - The observer with position (x, y) and direction (dx, dy).
* @param {Object} point - The target point with position (x, y).
* @returns {boolean} True if the point is within the vision cone, false otherwise.
*/
isPointInCone(observer, point, coneRadius = SETTINGS.visionConeRadius, coneAngle = SETTINGS.visionConeAngle ) {
const observerDir = { x: observer.dx, y: observer.dy };
const toPoint = { x: point.x - observer.x, y: point.y - observer.y };
const angleToPoint = this.angleBetween(observerDir, toPoint);
const distToPoint = this.magnitude(toPoint);
return angleToPoint <= coneAngle / 2 && distToPoint <= coneRadius;
},
/**
* Linearly interpolates between two points.
* @param {Object} p1 - The starting point (x, y).
* @param {Object} p2 - The end point (x, y).
* @param {number} t - Interpolation factor (0 to 1).
* @returns {Object} The interpolated point.
*/
lerp(p1, p2, t) {
return {
x: p1.x + t * (p2.x - p1.x),
y: p1.y + t * (p2.y - p1.y)
};
},
/**
* Predicts the future position of an observer after a certain time.
* @param {Object} observer - The observer with current position (x, y), direction (dx, dy), and movement speed.
* @param {number} time - The future time in seconds.
* @returns {Object} The predicted future position.
*/
getObserverPositionAtTime(observer, time) {
const futureX = observer.x + observer.dx * (observer.moveSpeed || 0.3) * time;
const futureY = observer.y + observer.dy * (observer.moveSpeed || 0.3) * time;
return { ...observer, x: futureX, y: futureY };
},
/**
* Checks if a line between two points is in the vision cone of an observer.
* @param {Object} observer - The observer object.
* @param {Object} startPos - The start point of the line.
* @param {Object} endPos - The end point of the line.
* @returns {boolean} True if the line is in the vision cone, false otherwise.
*/
isLineInConeOfVision(observer, startPos, endPos) {
if (this.isPointInCone(observer, startPos) || this.isPointInCone(observer, endPos)) {
return true;
}
for (let i = 0; i <= SETTINGS.interpolationSteps; i++) {
const lerpT = i / SETTINGS.interpolationSteps;
const currentPos = this.lerp(startPos, endPos, lerpT);
if (this.isPointInCone(observer, currentPos)) {
return true;
}
}
return false;
},
/**
* Checks if a trajectory crosses the vision cone of a monster.
* @param {Object} monster - The monster object.
* @param {Object} startPos - The starting position.
* @returns {boolean} True if the trajectory is in the monster's vision cone, false otherwise.
*/
isTrajectoryInMonsterCone(monster, startPos) {
if (this.isPointInCone(monster, startPos)) return true;
const targetPos = { x: monster.x, y: monster.y };
for (let i = 0; i <= SETTINGS.interpolationSteps; i++) {
const t = i / SETTINGS.interpolationSteps;
const currentPos = this.lerp(startPos, targetPos, t);
if (this.isPointInCone(monster, currentPos)) return true;
}
return false;
},
isPathBlockedByItems(x, y) {
const collisionEntities = dw.findEntities(e => dw.mdInfo[e.md]?.canCollide);
// Check each collision entity to see if the point is inside its hitbox
for (const entity of collisionEntities) {
const hitbox = dw.getHitbox(entity.md);
const entityPosition = { x: entity.x, y: entity.y };
// Check if the given point (x, y) is inside the entity's hitbox
if (Util.isPointInsideHitbox({ x, y, ...dw.getHitbox(dw.c.md) }, entityPosition, hitbox)) {
return true; // The point is blocked by an entity
}
}
return false; // No entities block the point
},
// Helper function to check if a point is inside a hitbox
isPointInsideHitbox(point, entityPosition, hitbox) {
// Calculate the left, right, top, and bottom edges of the entity's hitbox
const hitboxLeft = entityPosition.x - hitbox.w / 2; // Left edge is center minus half the width
const hitboxRight = entityPosition.x + hitbox.w / 2; // Right edge is center plus half the width
const hitboxTop = entityPosition.y - hitbox.h; // Top edge is bottom minus the height of the hitbox
const hitboxBottom = entityPosition.y; // Bottom edge is the entity position's y
// If the point itself has width and height, treat it as a hitbox as well
if (point.w && point.h) {
// Calculate the edges of the point's hitbox
const pointLeft = point.x - point.w / 2;
const pointRight = point.x + point.w / 2;
const pointTop = point.y - point.h;
const pointBottom = point.y;
// Check for hitbox overlap between the entity's hitbox and the point's hitbox
return (
hitboxLeft < pointRight &&
hitboxRight > pointLeft &&
hitboxTop < pointBottom &&
hitboxBottom > pointTop
);
} else {
// If no width or height is provided, treat the point as a single coordinate
return (
point.x >= hitboxLeft &&
point.x <= hitboxRight &&
point.y >= hitboxTop &&
point.y <= hitboxBottom
);
}
},
/**
* Checks if a specific point is blocked by terrain, items, or the character's hitbox.
* @param {Object} point - The point position (x, y).
* @param {Object} [characterHitbox] - Optional. The character's hitbox {w, h} if provided.
* @returns {boolean} True if the point or hitbox is blocked, false otherwise.
*/
isPointBlocked(point, characterHitbox = null) {
const terrainSurface = dw.getTerrainAt(point.x, point.y, dw.c.z);
const terrainUnderground = dw.getTerrainAt(point.x, point.y, dw.c.z -1);
// Check if terrain is blocking
if (terrainSurface !== 0 || terrainUnderground < 1) {
return true;
}
// Check if any items block the path
if (Util.isPathBlockedByItems(point.x, point.y)) {
return true;
}
// If characterHitbox is provided, check if any part of the hitbox is blocked
if (characterHitbox) {
// We loop through the hitbox area to see if any part is blocked by terrain or items
const hitboxLeft = point.x - characterHitbox.w / 2;
const hitboxRight = point.x + characterHitbox.w / 2;
const hitboxTop = point.y - characterHitbox.h;
const hitboxBottom = point.y;
for (let x = hitboxLeft; x < hitboxRight; x++) {
for (let y = hitboxTop; y < hitboxBottom; y++) {
const surface = dw.getTerrainAt(x, y, dw.character.z);
const underground = dw.getTerrainAt(x, y, dw.character.z - 1);
if (surface !== 0 || underground < 1) {
return true;
}
}
}
}
return false;
},
/**
* Checks if there is any terrain blocking the path between two points.
* @param {Object} target - The target position (x, y).
* @param {Object} origin - The origin position (x, y), default is character's current position.
* @returns {boolean} True if the path is blocked, false otherwise.
*/
isPathBlocked(target, origin = dw.c) {
for (let i = 0; i <= SETTINGS.interpolationSteps; i++) {
const t = i / SETTINGS.interpolationSteps;
const point = this.lerp(origin, target, t);
// Use the isPointBlocked function to check if this point is blocked
if (this.isPointBlocked(point, dw.getHitbox(dw.character.md))) {
return true; // If any point along the path is blocked, the path is blocked
}
}
return false; // Path is clear
},
/**
* Determines if a direct line between two points is safe from monster detection.
* @param {Object} target - The target point (x, y).
* @param {Object} origin - The origin point (x, y).
* @returns {boolean} True if the line between the points is safe, false otherwise.
*/
isSafe(target) {
for (const monster of Finder.getMonsters()) {
// Skip monsters that are already targeting the character or aren't aggressive
if (monster.targetId === dw.c.id || monster.bad <= 0) continue;
const hitbox = dw.getHitbox(monster.md);
const monsterPosition = { x: monster.x, y: monster.y };
// Check if the character is already inside cone of view
if (this.isPointInCone(monster, dw.c)) {
true // The point is not safe
}
// Check if the target point is in the monster's cone of vision
if (this.isPointInCone(monster, target)) {
return false; // The point is not safe
}
}
return true; // No monsters detect the target
},
/**
* Determines if a direct line between two points is safe from monster detection.
* @param {Object} target - The target point (x, y).
* @param {Object} origin - The origin point (x, y).
* @returns {boolean} True if the line between the points is safe, false otherwise.
*/
isSafePath(target, origin) {
for (const monster of Finder.getMonsters()) {
// Skip monsters that are already targeting the character or aren't aggressive
if (monster.targetId === dw.c.id || monster.bad <= 0) continue;
const hitbox = dw.getHitbox(monster.md);
const monsterPosition = { x: monster.x, y: monster.y };
// Check if the character is inside the monster's hitbox
if (this.isPointInsideHitbox({ x: dw.character.x, y: dw.character.y, ...dw.getHitbox(dw.c.md) }, monsterPosition, hitbox)) {
continue; // Skip this monster because the character is inside its hitbox
}
// // Check if the character is already inside cone of view
// if (this.isLineInConeOfVision(monster, target, dw.c)) {
// continue; // The point is not safe
// }
// Check if the path between target and origin is in the monster's cone of vision
if (this.isLineInConeOfVision(monster, target, origin)) {
return false; // The path is not safe
}
}
return true; // The path is safe from all monsters
},
/**
* Calculates the distance from the current character position to the target.
* @param {Object} target - The target position (x, y).
* @returns {number} The distance to the target.
*/
distanceToTarget(target) {
return dw.distance(dw.character.x, dw.character.y, target.x, target.y);
},
/**
* Checks the proximity of "goo" monsters around a given monster.
* @param {Object} monster - The monster to check proximity for.
* @returns {number} The number of goo monsters nearby.
*/
checkGooProximity(monster) {
let count = 0;
if (!Array.from(dw.mdInfo[monster.md]?.tag || [] ).includes("goo")) {
return count;
}
Finder.getMonsters().forEach(other => {
if (
other.id !== monster.id &&
Array.from(dw.mdInfo[other.md]?.tag || [] ).includes("goo") &&
dw.distance(monster.x, monster.y, other.x, other.y) <= SETTINGS.gooProximityRange) {
count++;
}
});
return count;
},
/**
* Checks the proximity of other monsters around a given monster.
* @param {Object} monster - The monster to check proximity for.
* @returns {number} The number of monsters nearby.
*/
checkMonsterNearby(monster) {
let count = 0;
Finder.getMonsters().forEach(other => {
if (other.id !== monster.id && dw.distance(monster.x, monster.y, other.x, other.y) <= SETTINGS.monsterProximityRange) {
count++;
}
});
return count;
},
/**
* Counts how many monsters along the path of the given monster are within other monsters' vision cones.
* @param {Object} monster - The monster for which to count the observed monsters.
* @returns {number} The number of monsters along the path in vision cones.
*/
countMonstersAlongPath(monster) {
let count = 0;
const startPos = { x: dw.c.x, y: dw.c.y };
const targetPos = { x: monster.x, y: monster.y };
Finder.getMonsters().forEach(observer => {
if (observer.id !== monster.id && observer.bad > 0 && observer.targetId !== dw.c.id) {
if (this.isLineInConeOfVision(observer, startPos, targetPos)) count++;
}
});
return count;
},
/**
* Calculates the total distance of a given path.
* @param {Array<Object>} path - An array of points (x, y) representing the path.
* @returns {number} The total distance of the path.
*/
calculateTotalDistance(path) {
let totalDistance = 0;
// Iterate over the path and calculate the distance between each consecutive point
for (let i = 0; i < path.length - 1; i++) {
const currentPoint = path[i];
const nextPoint = path[i + 1];
const distance = dw.distance(currentPoint.x, currentPoint.y, nextPoint.x, nextPoint.y);
totalDistance += distance; // Add the distance to the total
}
return totalDistance;
},
/**
* Calculates a safe position behind the target based on the direction it is moving.
* @param {Object} target - The target object (with x, y, dx, dy properties).
* @param {number} safeDistance - The distance to keep behind the target.
* @returns {Object} The new position { x, y } behind the target, maintaining the safe distance.
*/
calculateSafePosition(target, distance, isBehind = true) {
const { x, y, dx = 0, dy = 0 } = target;
// Ensure the direction vector (dx, dy) is valid
const magnitude = Math.sqrt(dx * dx + dy * dy); // Calculate the magnitude of the vector
// If magnitude is 0, the target is stationary, so return the current position
if (magnitude === 0) {
return { x, y };
}
// Normalize the direction vector
const normDx = dx / magnitude;
const normDy = dy / magnitude;
// If isBehind is true, move in the opposite direction; otherwise, move in the same direction
const multiplier = isBehind ? -1 : 1;
// Calculate the new position by moving "distance" units relative to the target's movement
const newX = x + normDx * distance * multiplier;
const newY = y + normDy * distance * multiplier;
return { x: newX, y: newY };
},
/**
* Generates a safe path from the character's position to a target or a point within a certain distance, avoiding monsters.
* If a distance is provided, it finds the closest safe point within that distance and ensures a clear line of sight to the target.
* @param {Object} characterPos - The starting position (x, y).
* @param {Object} targetPos - The target position (x, y, dx, dy) of the monster, including direction.
* @param {number} [maxDistance] - Optional maximum distance to target. If provided, the function will find a safe point within this distance.
* @returns {Array<Object>} The safe path as an array of positions (x, y).
*/
generateSafePath(characterPos, targetPos, maxDistance = null) {
let adjustedTargetPos = targetPos;
if (targetPos.md && dw.mdInfo[targetPos.md].isMonster && targetPos.bad > 0) {
const safePosition = Util.calculateSafePosition(targetPos, SETTINGS.globalProximityToAction);
adjustedTargetPos = {
...targetPos,
x: safePosition.x,
y: safePosition.y,
};
}
// Se a distância máxima for fornecida, verifica se estamos dentro dela
if (maxDistance !== null) {
const distanceToTarget = dw.distance(characterPos.x, characterPos.y, adjustedTargetPos.x, adjustedTargetPos.y);
// Se já estamos dentro da distância permitida, retorna o caminho direto
if (distanceToTarget <= maxDistance) {
return [characterPos, characterPos];
}
}
const openList = [];
const closedList = [];
const path = [];
const directions = [
{ x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
{ x: 1, y: 1 }, { x: -1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: -1 }
];
let iterations = 0;
// Cria o nó inicial como um objeto simples
const startNode = {
pos: characterPos,
g: 0,
h: dw.distance(characterPos.x, characterPos.y, adjustedTargetPos.x, adjustedTargetPos.y),
f: dw.distance(characterPos.x, characterPos.y, adjustedTargetPos.x, adjustedTargetPos.y),
parent: null
};
openList.push(startNode);
while (openList.length > 0) {
iterations++;
if (iterations > SETTINGS.maxPathfindingIterations) {
console.log("Iteration limit reached. Aborting!");
return path.reverse(); // Retorna o caminho gerado até agora
}
// Seleciona o nó com o menor custo total (f)
let currentNode = openList.reduce((prev, node) => node.f < prev.f ? node : prev);
// Se houver uma distância máxima, verifica se o nó atual está dentro dela
if (maxDistance !== null) {
const currentDistanceToTarget = dw.distance(currentNode.pos.x, currentNode.pos.y, adjustedTargetPos.x, adjustedTargetPos.y);
// Verifica se o caminho até o alvo está bloqueado por itens
const hasClearSight = !Util.isPathBlockedByItems(currentNode.pos.x, currentNode.pos.y, adjustedTargetPos.x, adjustedTargetPos.y);
// Se o ponto está dentro da distância e o caminho está limpo, paramos a busca
if (currentDistanceToTarget <= maxDistance && hasClearSight) {
let node = currentNode;
while (node) {
path.push(node.pos);
node = node.parent;
}
path.reverse(); // Retorna o caminho do início até o ponto mais próximo
return path;
}
} else {
// Se não houver distância máxima, verifica se chegamos ao alvo diretamente
if (dw.distance(currentNode.pos.x, currentNode.pos.y, adjustedTargetPos.x, adjustedTargetPos.y) <= SETTINGS.pathProximity) {
let node = currentNode;
while (node) {
path.push(node.pos);
node = node.parent;
}
path.reverse(); // Retorna o caminho do início até o destino
// Certifica-se de que o último ponto é exatamente o destino ajustado
if (path.length === 0 || (path[path.length - 1].x !== adjustedTargetPos.x || path[path.length - 1].y !== adjustedTargetPos.y)) {
path.push(adjustedTargetPos); // Adiciona o destino ajustado se não estiver no caminho
}
return path;
}
}
// Remove o nó atual da lista aberta e o adiciona à lista fechada
openList.splice(openList.indexOf(currentNode), 1);
closedList.push(currentNode);
// Ordena as direções com base na proximidade ao alvo
const sortedDirections = directions.slice().sort((a, b) => {
const distA = dw.distance(
currentNode.pos.x + a.x * SETTINGS.pathStepSize,
currentNode.pos.y + a.y * SETTINGS.pathStepSize,
adjustedTargetPos.x,
adjustedTargetPos.y
);
const distB = dw.distance(
currentNode.pos.x + b.x * SETTINGS.pathStepSize,
currentNode.pos.y + b.y * SETTINGS.pathStepSize,
adjustedTargetPos.x,
adjustedTargetPos.y
);
return distA - distB; // Ordena do mais próximo para o mais distante
});
// Explora os nós vizinhos
for (const direction of sortedDirections) {
const newPos = {
x: currentNode.pos.x + direction.x * SETTINGS.pathStepSize,
y: currentNode.pos.y + direction.y * SETTINGS.pathStepSize
};
if (Util.isPathBlocked(newPos, currentNode.pos)) {
continue;
}
// Verifica se o novo nó é seguro ou já foi explorado
if (!Util.isSafe(newPos) || closedList.find(node => node.pos.x === newPos.x && node.pos.y === newPos.y)) {
continue;
}
const gScore = currentNode.g + SETTINGS.pathStepSize;
let neighborNode = openList.find(node => node.pos.x === newPos.x && node.pos.y === newPos.y);
// Se o vizinho não estiver na lista aberta ou o novo caminho for mais barato
if (!neighborNode) {
const hScore = dw.distance(newPos.x, newPos.y, adjustedTargetPos.x, adjustedTargetPos.y);
neighborNode = {
pos: newPos,
g: gScore,
h: hScore,
f: gScore + hScore,
parent: currentNode
};
openList.push(neighborNode);
} else if (gScore < neighborNode.g) {
neighborNode.g = gScore;
neighborNode.f = gScore + neighborNode.h;
neighborNode.parent = currentNode;
}
}
}
console.log("No path found.");
return path; // Retorna o caminho gerado até agora ou vazio se nenhum caminho foi encontrado
},
/**
* Optimizes a given path by skipping over safe segments, minimizing the number of points in the path.
* @param {Array<Object>} path - An array of points (x, y) representing the original path.
* @returns {Array<Object>} The optimized path.
*/
optimizePath(path) {
// Array to hold the new optimized path
const optimizedPath = [];
let i = 0; // Start index of the path