@rpgjs/action-battle 5.0.0-alpha.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1128 @@
1
+ import { MAXHP, RpgPlayer } from "@rpgjs/server";
2
+ const AiDebug = {
3
+ /** Enable/disable all AI debug logs */
4
+ enabled: typeof process !== "undefined" && process.env?.RPGJS_DEBUG_AI === "1" || false,
5
+ /** Filter logs to a specific event ID (null = all events) */
6
+ filterEventId: null,
7
+ /** Log categories to enable (empty = all) */
8
+ categories: [],
9
+ /**
10
+ * Log an AI debug message
11
+ *
12
+ * @param category - Log category (e.g., 'state', 'attack', 'movement', 'damage')
13
+ * @param eventId - Event ID for filtering
14
+ * @param message - Log message
15
+ * @param data - Optional additional data
16
+ */
17
+ log(category, eventId, message, data) {
18
+ if (!this.enabled) return;
19
+ if (this.filterEventId && eventId !== this.filterEventId) return;
20
+ if (this.categories.length > 0 && !this.categories.includes(category)) return;
21
+ const prefix = `[AI:${category}]${eventId ? ` [${eventId.substring(0, 8)}]` : ""}`;
22
+ if (data !== void 0) {
23
+ console.log(prefix, message, data);
24
+ } else {
25
+ console.log(prefix, message);
26
+ }
27
+ }
28
+ };
29
+ var AiState = /* @__PURE__ */ ((AiState2) => {
30
+ AiState2["Idle"] = "idle";
31
+ AiState2["Alert"] = "alert";
32
+ AiState2["Combat"] = "combat";
33
+ AiState2["Flee"] = "flee";
34
+ AiState2["Stunned"] = "stunned";
35
+ return AiState2;
36
+ })(AiState || {});
37
+ var EnemyType = /* @__PURE__ */ ((EnemyType2) => {
38
+ EnemyType2["Aggressive"] = "aggressive";
39
+ EnemyType2["Defensive"] = "defensive";
40
+ EnemyType2["Ranged"] = "ranged";
41
+ EnemyType2["Tank"] = "tank";
42
+ EnemyType2["Berserker"] = "berserker";
43
+ return EnemyType2;
44
+ })(EnemyType || {});
45
+ var AttackPattern = /* @__PURE__ */ ((AttackPattern2) => {
46
+ AttackPattern2["Melee"] = "melee";
47
+ AttackPattern2["Combo"] = "combo";
48
+ AttackPattern2["Charged"] = "charged";
49
+ AttackPattern2["Zone"] = "zone";
50
+ AttackPattern2["DashAttack"] = "dashAttack";
51
+ return AttackPattern2;
52
+ })(AttackPattern || {});
53
+ const DEFAULT_KNOCKBACK = {
54
+ /** Default knockback force */
55
+ force: 50,
56
+ /** Default knockback duration in milliseconds */
57
+ duration: 300
58
+ };
59
+ class BattleAi {
60
+ /**
61
+ * Create a new Battle AI Controller
62
+ *
63
+ * The AI controls behavior only. Stats should be set on the event
64
+ * using standard RPGJS methods (hp, param, learnSkill, etc.)
65
+ *
66
+ * @param event - The event to control
67
+ * @param options - AI behavior configuration
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * // In your event's onInit
72
+ * this.hp = 100;
73
+ * this.param[ATK] = 20;
74
+ * this.learnSkill(FireBall);
75
+ *
76
+ * new BattleAi(this, {
77
+ * enemyType: EnemyType.Ranged,
78
+ * attackSkill: FireBall,
79
+ * visionRange: 200,
80
+ * fleeThreshold: 0.2
81
+ * });
82
+ * ```
83
+ */
84
+ constructor(event, options = {}) {
85
+ this.target = null;
86
+ this.lastAttackTime = 0;
87
+ this.state = "idle";
88
+ this.stateStartTime = 0;
89
+ this.stunnedUntil = 0;
90
+ this.lastDodgeTime = 0;
91
+ this.comboCount = 0;
92
+ this.comboMax = 3;
93
+ this.chargingAttack = false;
94
+ this.nearbyEnemies = [];
95
+ this.groupUpdateInterval = 0;
96
+ this.patrolWaypoints = [];
97
+ this.currentPatrolIndex = 0;
98
+ this.lastHpCheck = 0;
99
+ this.recentDamageTaken = 0;
100
+ this.damageCheckInterval = 2e3;
101
+ this.isMovingToTarget = false;
102
+ this.lastFacingDirection = null;
103
+ event.battleAi = this;
104
+ this.event = event;
105
+ this.enemyType = options.enemyType || "aggressive";
106
+ this.applyEnemyTypeBehavior(options);
107
+ this.attackSkill = options.attackSkill || null;
108
+ this.attackPatterns = options.attackPatterns || [
109
+ "melee",
110
+ "combo",
111
+ "dashAttack"
112
+ /* DashAttack */
113
+ ];
114
+ this.groupBehavior = options.groupBehavior || false;
115
+ this.patrolWaypoints = options.patrolWaypoints || [];
116
+ this.currentPatrolIndex = 0;
117
+ this.onDefeatedCallback = options.onDefeated;
118
+ this.setupVision();
119
+ this.startAiBehaviorLoop();
120
+ this.changeState(
121
+ "idle"
122
+ /* Idle */
123
+ );
124
+ this.debugLog("init", `AI created (type=${this.enemyType}, visionRange=${this.visionRange}, attackRange=${this.attackRange})`);
125
+ }
126
+ /**
127
+ * Log AI debug message for this event
128
+ */
129
+ debugLog(category, message, data) {
130
+ AiDebug.log(category, this.event.id, message, data);
131
+ }
132
+ /**
133
+ * Apply enemy type-specific behavior modifiers
134
+ *
135
+ * This only affects AI behavior (cooldowns, ranges, dodge).
136
+ * Stats should be set on the event itself.
137
+ */
138
+ applyEnemyTypeBehavior(options) {
139
+ switch (this.enemyType) {
140
+ case "aggressive":
141
+ this.attackCooldown = options.attackCooldown ?? 600;
142
+ this.visionRange = options.visionRange ?? 150;
143
+ this.attackRange = options.attackRange ?? 50;
144
+ this.dodgeChance = options.dodgeChance ?? 0.1;
145
+ this.dodgeCooldown = options.dodgeCooldown ?? 3e3;
146
+ this.fleeThreshold = options.fleeThreshold ?? 0.15;
147
+ break;
148
+ case "defensive":
149
+ this.attackCooldown = options.attackCooldown ?? 1500;
150
+ this.visionRange = options.visionRange ?? 120;
151
+ this.attackRange = options.attackRange ?? 60;
152
+ this.dodgeChance = options.dodgeChance ?? 0.5;
153
+ this.dodgeCooldown = options.dodgeCooldown ?? 1500;
154
+ this.fleeThreshold = options.fleeThreshold ?? 0.3;
155
+ break;
156
+ case "ranged":
157
+ this.attackCooldown = options.attackCooldown ?? 1200;
158
+ this.visionRange = options.visionRange ?? 200;
159
+ this.attackRange = options.attackRange ?? 120;
160
+ this.dodgeChance = options.dodgeChance ?? 0.4;
161
+ this.dodgeCooldown = options.dodgeCooldown ?? 2e3;
162
+ this.fleeThreshold = options.fleeThreshold ?? 0.25;
163
+ break;
164
+ case "tank":
165
+ this.attackCooldown = options.attackCooldown ?? 2e3;
166
+ this.visionRange = options.visionRange ?? 100;
167
+ this.attackRange = options.attackRange ?? 50;
168
+ this.dodgeChance = 0;
169
+ this.dodgeCooldown = options.dodgeCooldown ?? 5e3;
170
+ this.fleeThreshold = options.fleeThreshold ?? 0.1;
171
+ break;
172
+ case "berserker":
173
+ this.attackCooldown = options.attackCooldown ?? 800;
174
+ this.visionRange = options.visionRange ?? 180;
175
+ this.attackRange = options.attackRange ?? 55;
176
+ this.dodgeChance = options.dodgeChance ?? 0.15;
177
+ this.dodgeCooldown = options.dodgeCooldown ?? 2500;
178
+ this.fleeThreshold = options.fleeThreshold ?? 0.05;
179
+ break;
180
+ default:
181
+ this.attackCooldown = options.attackCooldown ?? 1e3;
182
+ this.visionRange = options.visionRange ?? 150;
183
+ this.attackRange = options.attackRange ?? 60;
184
+ this.dodgeChance = options.dodgeChance ?? 0.2;
185
+ this.dodgeCooldown = options.dodgeCooldown ?? 2e3;
186
+ this.fleeThreshold = options.fleeThreshold ?? 0.2;
187
+ }
188
+ }
189
+ /**
190
+ * Setup vision detection
191
+ */
192
+ setupVision() {
193
+ const diameter = this.visionRange * 2;
194
+ this.event.attachShape(`vision_${this.event.id}`, {
195
+ radius: this.visionRange,
196
+ width: diameter,
197
+ height: diameter,
198
+ angle: 360
199
+ });
200
+ }
201
+ /**
202
+ * Start the AI behavior loop
203
+ */
204
+ startAiBehaviorLoop() {
205
+ const updateInterval = setInterval(() => {
206
+ if (!this.event.getCurrentMap()) {
207
+ this.destroy();
208
+ return;
209
+ }
210
+ this.updateAiBehavior();
211
+ }, 100);
212
+ this.updateInterval = updateInterval;
213
+ }
214
+ /**
215
+ * Change AI state with validated transitions
216
+ */
217
+ changeState(newState) {
218
+ const validTransitions = {
219
+ [
220
+ "idle"
221
+ /* Idle */
222
+ ]: [
223
+ "alert",
224
+ "combat"
225
+ /* Combat */
226
+ ],
227
+ [
228
+ "alert"
229
+ /* Alert */
230
+ ]: [
231
+ "idle",
232
+ "combat"
233
+ /* Combat */
234
+ ],
235
+ [
236
+ "combat"
237
+ /* Combat */
238
+ ]: [
239
+ "idle",
240
+ "flee",
241
+ "stunned"
242
+ /* Stunned */
243
+ ],
244
+ [
245
+ "flee"
246
+ /* Flee */
247
+ ]: [
248
+ "idle",
249
+ "combat"
250
+ /* Combat */
251
+ ],
252
+ [
253
+ "stunned"
254
+ /* Stunned */
255
+ ]: [
256
+ "combat",
257
+ "idle"
258
+ /* Idle */
259
+ ]
260
+ };
261
+ if (!validTransitions[this.state].includes(newState)) {
262
+ this.debugLog("state", `INVALID transition ${this.state} -> ${newState}`);
263
+ return;
264
+ }
265
+ this.debugLog("state", `STATE change: ${this.state} -> ${newState}`);
266
+ this.state = newState;
267
+ this.stateStartTime = Date.now();
268
+ switch (newState) {
269
+ case "idle":
270
+ if (this.patrolWaypoints.length > 0) {
271
+ this.startPatrol();
272
+ }
273
+ break;
274
+ case "alert":
275
+ this.event.stopMoveTo();
276
+ break;
277
+ case "combat":
278
+ this.comboCount = 0;
279
+ break;
280
+ case "flee":
281
+ if (this.target) {
282
+ this.fleeFromTarget();
283
+ }
284
+ break;
285
+ case "stunned":
286
+ this.event.stopMoveTo();
287
+ break;
288
+ }
289
+ }
290
+ /**
291
+ * Main AI behavior update loop
292
+ */
293
+ updateAiBehavior() {
294
+ const currentTime = Date.now();
295
+ if (this.groupBehavior) {
296
+ this.updateGroupBehavior();
297
+ }
298
+ if (this.state === "stunned") {
299
+ if (currentTime >= this.stunnedUntil) {
300
+ this.changeState(
301
+ "combat"
302
+ /* Combat */
303
+ );
304
+ }
305
+ return;
306
+ }
307
+ if (this.enemyType === "berserker" && this.event.param[MAXHP]) {
308
+ const hpPercent = this.event.hp / this.event.param[MAXHP];
309
+ const berserkerModifier = Math.max(0.3, hpPercent);
310
+ this.attackCooldown = 800 * berserkerModifier;
311
+ }
312
+ switch (this.state) {
313
+ case "idle":
314
+ this.updateIdleBehavior();
315
+ break;
316
+ case "alert":
317
+ this.updateAlertBehavior();
318
+ break;
319
+ case "combat":
320
+ this.updateCombatBehavior(currentTime);
321
+ break;
322
+ case "flee":
323
+ this.updateFleeBehavior();
324
+ break;
325
+ }
326
+ this.checkDamageTaken();
327
+ }
328
+ /**
329
+ * Update idle behavior (patrolling)
330
+ */
331
+ updateIdleBehavior() {
332
+ if (this.patrolWaypoints.length > 0) {
333
+ const waypoint = this.patrolWaypoints[this.currentPatrolIndex];
334
+ const distance = this.getDistance(this.event, {
335
+ x: () => waypoint.x,
336
+ y: () => waypoint.y
337
+ });
338
+ if (distance < 10) {
339
+ this.currentPatrolIndex = (this.currentPatrolIndex + 1) % this.patrolWaypoints.length;
340
+ }
341
+ }
342
+ }
343
+ /**
344
+ * Update alert behavior
345
+ */
346
+ updateAlertBehavior() {
347
+ if (this.target) {
348
+ this.faceTarget();
349
+ const distance = this.getDistance(this.event, this.target);
350
+ if (distance <= this.attackRange * 1.5) {
351
+ this.changeState(
352
+ "combat"
353
+ /* Combat */
354
+ );
355
+ }
356
+ } else {
357
+ this.changeState(
358
+ "idle"
359
+ /* Idle */
360
+ );
361
+ }
362
+ }
363
+ /**
364
+ * Update combat behavior
365
+ */
366
+ updateCombatBehavior(currentTime) {
367
+ if (!this.target) {
368
+ this.debugLog("combat", "No target, returning to idle");
369
+ this.changeState(
370
+ "idle"
371
+ /* Idle */
372
+ );
373
+ return;
374
+ }
375
+ const distance = this.getDistance(this.event, this.target);
376
+ if (distance > this.visionRange * 1.5) {
377
+ this.debugLog("combat", `Target out of range (dist=${distance.toFixed(1)}, maxRange=${(this.visionRange * 1.5).toFixed(1)})`);
378
+ this.target = null;
379
+ this.isMovingToTarget = false;
380
+ this.event.stopMoveTo();
381
+ this.changeState(
382
+ "idle"
383
+ /* Idle */
384
+ );
385
+ return;
386
+ }
387
+ if (this.event.param[MAXHP]) {
388
+ const hpPercent = this.event.hp / this.event.param[MAXHP];
389
+ if (hpPercent <= this.fleeThreshold) {
390
+ this.debugLog("combat", `HP low (${(hpPercent * 100).toFixed(0)}%), fleeing`);
391
+ this.isMovingToTarget = false;
392
+ this.changeState(
393
+ "flee"
394
+ /* Flee */
395
+ );
396
+ return;
397
+ }
398
+ }
399
+ if (this.canDodge() && this.shouldDodge()) {
400
+ this.debugLog("combat", "Attempting dodge");
401
+ this.isMovingToTarget = false;
402
+ this.tryDodge();
403
+ return;
404
+ }
405
+ if (this.enemyType === "ranged") {
406
+ if (distance < this.attackRange * 0.6) {
407
+ this.debugLog("movement", `Retreating (dist=${distance.toFixed(1)}, minRange=${(this.attackRange * 0.6).toFixed(1)})`);
408
+ this.isMovingToTarget = false;
409
+ this.retreatFromTarget();
410
+ } else if (distance > this.attackRange) {
411
+ if (!this.isMovingToTarget) {
412
+ this.debugLog("movement", `Moving to target (dist=${distance.toFixed(1)}, attackRange=${this.attackRange})`);
413
+ this.isMovingToTarget = true;
414
+ this.event.moveTo(this.target);
415
+ }
416
+ } else {
417
+ if (this.isMovingToTarget) {
418
+ this.debugLog("movement", `In range, stopping (dist=${distance.toFixed(1)})`);
419
+ this.isMovingToTarget = false;
420
+ this.event.stopMoveTo();
421
+ }
422
+ }
423
+ } else {
424
+ if (distance > this.attackRange) {
425
+ if (!this.isMovingToTarget) {
426
+ this.debugLog("movement", `Moving to target (dist=${distance.toFixed(1)}, attackRange=${this.attackRange})`);
427
+ this.isMovingToTarget = true;
428
+ this.event.moveTo(this.target);
429
+ }
430
+ } else {
431
+ if (this.isMovingToTarget) {
432
+ this.debugLog("movement", `In range, stopping (dist=${distance.toFixed(1)})`);
433
+ this.isMovingToTarget = false;
434
+ this.event.stopMoveTo();
435
+ }
436
+ }
437
+ }
438
+ if (distance <= this.attackRange && currentTime - this.lastAttackTime >= this.attackCooldown) {
439
+ if (!this.chargingAttack) {
440
+ this.debugLog("attack", `Attacking (dist=${distance.toFixed(1)}, cooldown=${this.attackCooldown}ms)`);
441
+ this.selectAndPerformAttack();
442
+ this.lastAttackTime = currentTime;
443
+ }
444
+ }
445
+ }
446
+ /**
447
+ * Update flee behavior
448
+ */
449
+ updateFleeBehavior() {
450
+ if (!this.target) {
451
+ this.changeState(
452
+ "idle"
453
+ /* Idle */
454
+ );
455
+ return;
456
+ }
457
+ const distance = this.getDistance(this.event, this.target);
458
+ if (this.event.param[MAXHP]) {
459
+ const hpPercent = this.event.hp / this.event.param[MAXHP];
460
+ if (hpPercent > this.fleeThreshold * 1.5 || distance > this.visionRange * 2) {
461
+ this.changeState(
462
+ "combat"
463
+ /* Combat */
464
+ );
465
+ return;
466
+ }
467
+ }
468
+ this.fleeFromTarget();
469
+ }
470
+ /**
471
+ * Select and perform an attack pattern
472
+ */
473
+ selectAndPerformAttack() {
474
+ if (!this.target) return;
475
+ if (this.comboCount > 0 && this.comboCount < this.comboMax) {
476
+ this.debugLog("attack", `Continuing combo (${this.comboCount}/${this.comboMax})`);
477
+ this.performComboAttack();
478
+ return;
479
+ }
480
+ const pattern = this.selectAttackPattern();
481
+ this.debugLog("attack", `Selected pattern: ${pattern}`);
482
+ this.performAttackPattern(pattern);
483
+ }
484
+ /**
485
+ * Select attack pattern with weighted probability
486
+ */
487
+ selectAttackPattern() {
488
+ const weights = {
489
+ [
490
+ "melee"
491
+ /* Melee */
492
+ ]: 40,
493
+ [
494
+ "combo"
495
+ /* Combo */
496
+ ]: 25,
497
+ [
498
+ "charged"
499
+ /* Charged */
500
+ ]: 15,
501
+ [
502
+ "zone"
503
+ /* Zone */
504
+ ]: 10,
505
+ [
506
+ "dashAttack"
507
+ /* DashAttack */
508
+ ]: 10
509
+ };
510
+ switch (this.enemyType) {
511
+ case "aggressive":
512
+ weights[
513
+ "combo"
514
+ /* Combo */
515
+ ] += 20;
516
+ weights[
517
+ "dashAttack"
518
+ /* DashAttack */
519
+ ] += 15;
520
+ break;
521
+ case "defensive":
522
+ weights[
523
+ "charged"
524
+ /* Charged */
525
+ ] += 25;
526
+ break;
527
+ case "ranged":
528
+ weights[
529
+ "zone"
530
+ /* Zone */
531
+ ] += 20;
532
+ break;
533
+ case "tank":
534
+ weights[
535
+ "charged"
536
+ /* Charged */
537
+ ] += 30;
538
+ weights[
539
+ "zone"
540
+ /* Zone */
541
+ ] += 15;
542
+ break;
543
+ case "berserker":
544
+ weights[
545
+ "combo"
546
+ /* Combo */
547
+ ] += 35;
548
+ break;
549
+ }
550
+ let total = 0;
551
+ const available = [];
552
+ this.attackPatterns.forEach((p) => {
553
+ const weight = weights[p] || 10;
554
+ total += weight;
555
+ available.push({ pattern: p, weight });
556
+ });
557
+ let random = Math.random() * total;
558
+ for (const item of available) {
559
+ random -= item.weight;
560
+ if (random <= 0) return item.pattern;
561
+ }
562
+ return this.attackPatterns[0] || "melee";
563
+ }
564
+ /**
565
+ * Perform attack pattern
566
+ */
567
+ performAttackPattern(pattern) {
568
+ switch (pattern) {
569
+ case "melee":
570
+ this.performMeleeAttack();
571
+ break;
572
+ case "combo":
573
+ this.performComboAttack();
574
+ break;
575
+ case "charged":
576
+ this.performChargedAttack();
577
+ break;
578
+ case "zone":
579
+ this.performZoneAttack();
580
+ break;
581
+ case "dashAttack":
582
+ this.performDashAttack();
583
+ break;
584
+ }
585
+ }
586
+ /**
587
+ * Perform melee attack
588
+ * Uses skill if configured, otherwise creates hitbox
589
+ */
590
+ performMeleeAttack() {
591
+ if (!this.target) return;
592
+ this.faceTarget();
593
+ this.event.setAnimation("attack", 1);
594
+ if (this.attackSkill) {
595
+ try {
596
+ this.event.useSkill(this.attackSkill, this.target);
597
+ } catch (e) {
598
+ this.performBasicHitbox();
599
+ }
600
+ } else {
601
+ this.performBasicHitbox();
602
+ }
603
+ }
604
+ /**
605
+ * Perform basic hitbox attack when no skill is set
606
+ */
607
+ performBasicHitbox() {
608
+ if (!this.target) return;
609
+ const eventX = this.event.x();
610
+ const eventY = this.event.y();
611
+ const dx = this.target.x() - eventX;
612
+ const dy = this.target.y() - eventY;
613
+ const dist = Math.sqrt(dx * dx + dy * dy);
614
+ if (dist === 0) return;
615
+ const dirX = dx / dist;
616
+ const dirY = dy / dist;
617
+ const hitboxes = [{
618
+ x: eventX + dirX * 30,
619
+ y: eventY + dirY * 30,
620
+ width: 40,
621
+ height: 40
622
+ }];
623
+ const map = this.event.getCurrentMap();
624
+ map?.createMovingHitbox(hitboxes, { speed: 5 }).subscribe({
625
+ next: (hits) => {
626
+ hits.forEach((hit) => {
627
+ if (hit instanceof RpgPlayer && hit !== this.event) {
628
+ this.applyHit(hit);
629
+ }
630
+ });
631
+ }
632
+ });
633
+ }
634
+ /**
635
+ * Apply hit to target using RPGJS damage system with knockback
636
+ *
637
+ * Calculates damage using RPGJS formula, applies knockback based on
638
+ * equipped weapon's knockbackForce property, and triggers visual effects.
639
+ * Supports hooks for customizing behavior.
640
+ *
641
+ * @param target - The player or entity being hit
642
+ * @param hooks - Optional hooks for customizing hit behavior
643
+ * @returns The hit result containing damage and knockback info
644
+ *
645
+ * @example
646
+ * ```ts
647
+ * // Basic hit
648
+ * this.applyHit(player);
649
+ *
650
+ * // With custom hooks
651
+ * this.applyHit(player, {
652
+ * onBeforeHit(result) {
653
+ * result.knockbackForce *= 1.5; // Increase knockback
654
+ * return result;
655
+ * },
656
+ * onAfterHit(result) {
657
+ * console.log(`Dealt ${result.damage} damage!`);
658
+ * }
659
+ * });
660
+ * ```
661
+ */
662
+ applyHit(target, hooks) {
663
+ const { damage } = target.applyDamage(this.event);
664
+ const knockbackForce = this.getWeaponKnockbackForce();
665
+ const knockbackDuration = DEFAULT_KNOCKBACK.duration;
666
+ let hitResult = {
667
+ damage,
668
+ knockbackForce,
669
+ knockbackDuration,
670
+ defeated: target.hp <= 0,
671
+ attacker: this.event,
672
+ target
673
+ };
674
+ if (hooks?.onBeforeHit) {
675
+ const modified = hooks.onBeforeHit(hitResult);
676
+ if (modified) {
677
+ hitResult = modified;
678
+ }
679
+ }
680
+ target.flash({
681
+ type: "tint",
682
+ tint: "red",
683
+ duration: 200,
684
+ cycles: 1
685
+ });
686
+ target.showHit(`-${hitResult.damage}`);
687
+ if (hitResult.knockbackForce > 0) {
688
+ const dx = target.x() - this.event.x();
689
+ const dy = target.y() - this.event.y();
690
+ const distance = Math.sqrt(dx * dx + dy * dy);
691
+ if (distance > 0) {
692
+ const knockbackDirection = {
693
+ x: dx / distance,
694
+ y: dy / distance
695
+ };
696
+ target.knockback(knockbackDirection, hitResult.knockbackForce, hitResult.knockbackDuration);
697
+ }
698
+ }
699
+ if (hooks?.onAfterHit) {
700
+ hooks.onAfterHit(hitResult);
701
+ }
702
+ return hitResult;
703
+ }
704
+ /**
705
+ * Get knockback force from equipped weapon
706
+ *
707
+ * Retrieves the knockbackForce property from the event's equipped weapon.
708
+ * Falls back to DEFAULT_KNOCKBACK.force if no weapon or property is set.
709
+ *
710
+ * @returns Knockback force value
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * // Weapon with knockbackForce: 80
715
+ * const force = this.getWeaponKnockbackForce(); // 80
716
+ *
717
+ * // No weapon equipped
718
+ * const force = this.getWeaponKnockbackForce(); // 50 (default)
719
+ * ```
720
+ */
721
+ getWeaponKnockbackForce() {
722
+ try {
723
+ const equipments = this.event.equipments?.() || [];
724
+ for (const item of equipments) {
725
+ const itemData = this.event.databaseById?.(item.id());
726
+ if (itemData?._type === "weapon" && itemData.knockbackForce !== void 0) {
727
+ return itemData.knockbackForce;
728
+ }
729
+ }
730
+ } catch {
731
+ }
732
+ return DEFAULT_KNOCKBACK.force;
733
+ }
734
+ /**
735
+ * Perform combo attack
736
+ */
737
+ performComboAttack() {
738
+ if (!this.target) return;
739
+ this.comboCount++;
740
+ this.performMeleeAttack();
741
+ if (this.comboCount < this.comboMax) {
742
+ setTimeout(() => {
743
+ if (this.target && this.state === "combat") {
744
+ this.performComboAttack();
745
+ } else {
746
+ this.comboCount = 0;
747
+ }
748
+ }, 300);
749
+ } else {
750
+ this.comboCount = 0;
751
+ }
752
+ }
753
+ /**
754
+ * Perform charged attack
755
+ */
756
+ performChargedAttack() {
757
+ if (!this.target) return;
758
+ this.chargingAttack = true;
759
+ this.faceTarget();
760
+ this.event.setAnimation("attack", 2);
761
+ setTimeout(() => {
762
+ if (!this.target || this.state !== "combat") {
763
+ this.chargingAttack = false;
764
+ return;
765
+ }
766
+ if (this.attackSkill) {
767
+ try {
768
+ this.event.useSkill(this.attackSkill, this.target);
769
+ } catch (e) {
770
+ this.performBasicHitbox();
771
+ }
772
+ } else {
773
+ this.performBasicHitbox();
774
+ }
775
+ this.chargingAttack = false;
776
+ }, 800);
777
+ }
778
+ /**
779
+ * Perform zone attack (360 degrees)
780
+ */
781
+ performZoneAttack() {
782
+ this.event.setAnimation("attack", 1);
783
+ const eventX = this.event.x();
784
+ const eventY = this.event.y();
785
+ const radius = 50;
786
+ const hitboxes = [];
787
+ const angles = [0, 90, 180, 270];
788
+ angles.forEach((angle) => {
789
+ const rad = angle * Math.PI / 180;
790
+ hitboxes.push({
791
+ x: eventX + Math.cos(rad) * radius,
792
+ y: eventY + Math.sin(rad) * radius,
793
+ width: 40,
794
+ height: 40
795
+ });
796
+ });
797
+ const map = this.event.getCurrentMap();
798
+ map?.createMovingHitbox(hitboxes, { speed: 5 }).subscribe({
799
+ next: (hits) => {
800
+ hits.forEach((hit) => {
801
+ if (hit instanceof RpgPlayer && hit !== this.event) {
802
+ this.applyHit(hit);
803
+ }
804
+ });
805
+ }
806
+ });
807
+ }
808
+ /**
809
+ * Perform dash attack
810
+ */
811
+ performDashAttack() {
812
+ if (!this.target) return;
813
+ const dx = this.target.x() - this.event.x();
814
+ const dy = this.target.y() - this.event.y();
815
+ const dist = Math.sqrt(dx * dx + dy * dy);
816
+ if (dist === 0) return;
817
+ const dirX = dx / dist;
818
+ const dirY = dy / dist;
819
+ this.faceTarget();
820
+ this.event.dash({ x: dirX, y: dirY }, 10, 200);
821
+ setTimeout(() => {
822
+ if (!this.target || this.state !== "combat") return;
823
+ this.performMeleeAttack();
824
+ }, 200);
825
+ }
826
+ /**
827
+ * Face the current target with hysteresis to prevent animation flickering
828
+ *
829
+ * Uses multiple strategies to prevent flickering:
830
+ * 1. When very close to target (collision), keep current direction
831
+ * 2. When near diagonal, require significant difference to change
832
+ * 3. Only change if direction is clearly wrong (opposite)
833
+ */
834
+ faceTarget() {
835
+ if (!this.target) return;
836
+ const dx = this.target.x() - this.event.x();
837
+ const dy = this.target.y() - this.event.y();
838
+ const absX = Math.abs(dx);
839
+ const absY = Math.abs(dy);
840
+ const distance = Math.sqrt(dx * dx + dy * dy);
841
+ const minDistanceForDirectionChange = 40;
842
+ if (this.lastFacingDirection && distance < minDistanceForDirectionChange) {
843
+ return;
844
+ }
845
+ let newDirection;
846
+ if (absX >= absY) {
847
+ newDirection = dx >= 0 ? "right" : "left";
848
+ } else {
849
+ newDirection = dy >= 0 ? "down" : "up";
850
+ }
851
+ const hysteresisThreshold = 0.2;
852
+ const ratio = absX > 0 || absY > 0 ? Math.min(absX, absY) / Math.max(absX, absY) : 0;
853
+ if (this.lastFacingDirection && ratio > 1 - hysteresisThreshold) {
854
+ const isOpposite = this.lastFacingDirection === "left" && dx > 20 || this.lastFacingDirection === "right" && dx < -20 || this.lastFacingDirection === "up" && dy > 20 || this.lastFacingDirection === "down" && dy < -20;
855
+ if (!isOpposite) {
856
+ return;
857
+ }
858
+ }
859
+ this.lastFacingDirection = newDirection;
860
+ this.event.changeDirection(newDirection);
861
+ }
862
+ /**
863
+ * Try to dodge
864
+ */
865
+ tryDodge() {
866
+ const currentTime = Date.now();
867
+ if (currentTime - this.lastDodgeTime < this.dodgeCooldown) {
868
+ this.debugLog("dodge", `Dodge on cooldown (${this.dodgeCooldown - (currentTime - this.lastDodgeTime)}ms remaining)`);
869
+ return;
870
+ }
871
+ if (Math.random() > this.dodgeChance) {
872
+ this.debugLog("dodge", `Dodge roll failed (chance=${(this.dodgeChance * 100).toFixed(0)}%)`);
873
+ return;
874
+ }
875
+ if (!this.target) return;
876
+ const dx = this.target.x() - this.event.x();
877
+ const dy = this.target.y() - this.event.y();
878
+ const dist = Math.sqrt(dx * dx + dy * dy);
879
+ if (dist === 0) return;
880
+ const dodgeDirX = -dy / dist;
881
+ const dodgeDirY = dx / dist;
882
+ const side = Math.random() > 0.5 ? 1 : -1;
883
+ this.debugLog("dodge", `Dodging (dir=${side > 0 ? "right" : "left"})`);
884
+ this.event.dash({ x: dodgeDirX * side, y: dodgeDirY * side }, 12, 300);
885
+ this.lastDodgeTime = currentTime;
886
+ if (this.enemyType === "defensive" && Math.random() < 0.5) {
887
+ this.debugLog("dodge", "Counter-attack after dodge");
888
+ setTimeout(() => {
889
+ if (this.target && this.state === "combat") {
890
+ this.selectAndPerformAttack();
891
+ }
892
+ }, 400);
893
+ }
894
+ }
895
+ canDodge() {
896
+ if (this.dodgeChance === 0) return false;
897
+ return Date.now() - this.lastDodgeTime >= this.dodgeCooldown;
898
+ }
899
+ shouldDodge() {
900
+ if (!this.target) return false;
901
+ const distance = this.getDistance(this.event, this.target);
902
+ return distance < this.attackRange * 0.8;
903
+ }
904
+ /**
905
+ * Flee from target
906
+ */
907
+ fleeFromTarget() {
908
+ if (!this.target) return;
909
+ const dx = this.event.x() - this.target.x();
910
+ const dy = this.event.y() - this.target.y();
911
+ const dist = Math.sqrt(dx * dx + dy * dy);
912
+ if (dist === 0) return;
913
+ const fleeTarget = {
914
+ x: () => this.event.x() + dx / dist * 200,
915
+ y: () => this.event.y() + dy / dist * 200
916
+ };
917
+ this.event.moveTo(fleeTarget);
918
+ }
919
+ /**
920
+ * Retreat from target (temporary)
921
+ */
922
+ retreatFromTarget() {
923
+ if (!this.target) return;
924
+ const dx = this.event.x() - this.target.x();
925
+ const dy = this.event.y() - this.target.y();
926
+ const dist = Math.sqrt(dx * dx + dy * dy);
927
+ if (dist === 0) return;
928
+ this.event.dash({ x: dx / dist, y: dy / dist }, 8, 200);
929
+ }
930
+ /**
931
+ * Check damage taken for retreat decision
932
+ */
933
+ checkDamageTaken() {
934
+ const currentTime = Date.now();
935
+ if (currentTime - this.lastHpCheck >= this.damageCheckInterval) {
936
+ this.recentDamageTaken = 0;
937
+ this.lastHpCheck = currentTime;
938
+ }
939
+ }
940
+ /**
941
+ * Start patrol
942
+ */
943
+ startPatrol() {
944
+ if (this.patrolWaypoints.length === 0) return;
945
+ const waypoint = this.patrolWaypoints[this.currentPatrolIndex];
946
+ this.event.moveTo({ x: () => waypoint.x, y: () => waypoint.y });
947
+ }
948
+ /**
949
+ * Update group behavior
950
+ */
951
+ updateGroupBehavior() {
952
+ if (!this.groupBehavior) return;
953
+ this.groupUpdateInterval++;
954
+ if (this.groupUpdateInterval >= 20) {
955
+ this.groupUpdateInterval = 0;
956
+ this.findNearbyEnemies();
957
+ }
958
+ if (this.nearbyEnemies.length > 0 && this.target && this.state === "combat") {
959
+ this.applyFormation();
960
+ }
961
+ }
962
+ /**
963
+ * Find nearby enemies
964
+ */
965
+ findNearbyEnemies() {
966
+ this.nearbyEnemies = [];
967
+ const map = this.event.getCurrentMap();
968
+ if (!map) return;
969
+ const allEvents = Object.values(map.events());
970
+ const groupRadius = 150;
971
+ allEvents.forEach((event) => {
972
+ if (event === this.event) return;
973
+ const ai = event.battleAi;
974
+ if (ai && ai.groupBehavior) {
975
+ const distance = this.getDistance(this.event, event);
976
+ if (distance <= groupRadius) {
977
+ this.nearbyEnemies.push(ai);
978
+ }
979
+ }
980
+ });
981
+ }
982
+ /**
983
+ * Apply formation around target
984
+ */
985
+ applyFormation() {
986
+ if (!this.target || this.nearbyEnemies.length === 0) return;
987
+ const totalEnemies = this.nearbyEnemies.length + 1;
988
+ const angleStep = 2 * Math.PI / totalEnemies;
989
+ let ourIndex = 0;
990
+ for (let i = 0; i < this.nearbyEnemies.length; i++) {
991
+ if (this.nearbyEnemies[i].event.id < this.event.id) {
992
+ ourIndex++;
993
+ }
994
+ }
995
+ const angle = angleStep * ourIndex;
996
+ const formationRadius = this.attackRange * 1.2;
997
+ const formationX = this.target.x() + Math.cos(angle) * formationRadius;
998
+ const formationY = this.target.y() + Math.sin(angle) * formationRadius;
999
+ const distanceToFormation = Math.sqrt(
1000
+ Math.pow(this.event.x() - formationX, 2) + Math.pow(this.event.y() - formationY, 2)
1001
+ );
1002
+ if (distanceToFormation > 20) {
1003
+ this.event.moveTo({ x: () => formationX, y: () => formationY });
1004
+ }
1005
+ }
1006
+ /**
1007
+ * Handle player entering vision
1008
+ */
1009
+ onDetectInShape(player, shape) {
1010
+ this.debugLog("vision", `Player ${player.id} entered vision (state=${this.state})`);
1011
+ this.target = player;
1012
+ if (this.state === "idle") {
1013
+ this.changeState(
1014
+ "alert"
1015
+ /* Alert */
1016
+ );
1017
+ } else if (this.state === "alert") {
1018
+ this.changeState(
1019
+ "combat"
1020
+ /* Combat */
1021
+ );
1022
+ }
1023
+ }
1024
+ /**
1025
+ * Handle player leaving vision
1026
+ */
1027
+ onDetectOutShape(player, shape) {
1028
+ this.debugLog("vision", `Player ${player.id} left vision (wasTarget=${this.target === player})`);
1029
+ if (this.target === player) {
1030
+ this.target = null;
1031
+ this.isMovingToTarget = false;
1032
+ this.event.stopMoveTo();
1033
+ this.changeState(
1034
+ "idle"
1035
+ /* Idle */
1036
+ );
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Handle taking damage (called from server.ts)
1041
+ *
1042
+ * This triggers state changes like stun and flee check.
1043
+ * The actual damage is applied externally via RPGJS API.
1044
+ */
1045
+ takeDamage(attacker) {
1046
+ const { damage } = this.event.applyDamage(attacker);
1047
+ this.debugLog("damage", `Took ${damage} damage from ${attacker.id} (HP: ${this.event.hp}/${this.event.param[MAXHP] || "?"})`);
1048
+ this.event.flash({
1049
+ type: "tint",
1050
+ tint: "red",
1051
+ duration: 200,
1052
+ cycles: 1
1053
+ });
1054
+ this.event.showHit(`-${damage}`);
1055
+ this.recentDamageTaken += damage;
1056
+ if (this.state !== "stunned" && this.state !== "flee") {
1057
+ this.debugLog("damage", "Stunned from damage");
1058
+ this.isMovingToTarget = false;
1059
+ this.stunnedUntil = Date.now() + 150;
1060
+ this.changeState(
1061
+ "stunned"
1062
+ /* Stunned */
1063
+ );
1064
+ }
1065
+ if (this.event.hp <= 0) {
1066
+ this.debugLog("damage", "Defeated!");
1067
+ this.kill();
1068
+ return true;
1069
+ }
1070
+ return false;
1071
+ }
1072
+ /**
1073
+ * Kill this AI
1074
+ *
1075
+ * Stops all movements, cleans up resources, calls the onDefeated hook,
1076
+ * and removes the event from the map.
1077
+ */
1078
+ kill() {
1079
+ if (this.onDefeatedCallback) {
1080
+ this.onDefeatedCallback(this.event);
1081
+ }
1082
+ this.destroy();
1083
+ this.event.remove();
1084
+ }
1085
+ /**
1086
+ * Get distance between entities
1087
+ */
1088
+ getDistance(entity1, entity2) {
1089
+ const dx = entity1.x() - entity2.x();
1090
+ const dy = entity1.y() - entity2.y();
1091
+ return Math.sqrt(dx * dx + dy * dy);
1092
+ }
1093
+ // Public getters
1094
+ getHealth() {
1095
+ return this.event.hp;
1096
+ }
1097
+ getMaxHealth() {
1098
+ return this.event.param[MAXHP];
1099
+ }
1100
+ getTarget() {
1101
+ return this.target;
1102
+ }
1103
+ getState() {
1104
+ return this.state;
1105
+ }
1106
+ getEnemyType() {
1107
+ return this.enemyType;
1108
+ }
1109
+ /**
1110
+ * Clean up
1111
+ */
1112
+ destroy() {
1113
+ if (this.updateInterval) {
1114
+ clearInterval(this.updateInterval);
1115
+ this.updateInterval = void 0;
1116
+ }
1117
+ this.target = null;
1118
+ this.nearbyEnemies = [];
1119
+ }
1120
+ }
1121
+ export {
1122
+ AiDebug,
1123
+ AiState,
1124
+ AttackPattern,
1125
+ BattleAi,
1126
+ DEFAULT_KNOCKBACK,
1127
+ EnemyType
1128
+ };