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