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

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