@rpgjs/action-battle 5.0.0-beta.5 → 5.0.0-beta.6

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