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