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

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