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

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 (66) hide show
  1. package/README.md +161 -22
  2. package/dist/ai.server.d.ts +55 -4
  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 +1343 -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 +7 -2
  29. package/dist/server/index.js +12 -7
  30. package/dist/server/index10.js +1340 -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/index2.js +1 -1
  37. package/dist/server/index3.js +25 -87
  38. package/dist/server/index4.js +45 -141
  39. package/dist/server/index5.js +104 -21
  40. package/dist/server/index6.js +137 -1215
  41. package/dist/server/index7.js +22 -34
  42. package/dist/server/index8.js +70 -44
  43. package/dist/server/index9.js +44 -437
  44. package/dist/server.d.ts +8 -2
  45. package/dist/ui/state.d.ts +5 -5
  46. package/package.json +5 -5
  47. package/src/ai.server.spec.ts +120 -0
  48. package/src/ai.server.ts +362 -56
  49. package/src/client.ts +21 -12
  50. package/src/config.ts +17 -2
  51. package/src/core/attack-profile.spec.ts +118 -0
  52. package/src/core/attack-profile.ts +100 -0
  53. package/src/core/attack-runtime.spec.ts +103 -0
  54. package/src/core/attack-runtime.ts +83 -0
  55. package/src/core/contracts.ts +3 -0
  56. package/src/core/enemy-attack-profiles.spec.ts +35 -0
  57. package/src/core/enemy-attack-profiles.ts +103 -0
  58. package/src/core/equipment.spec.ts +37 -0
  59. package/src/core/equipment.ts +17 -0
  60. package/src/core/hit-reaction.spec.ts +43 -0
  61. package/src/core/hit-reaction.ts +70 -0
  62. package/src/core/hit.spec.ts +54 -1
  63. package/src/core/hit.ts +26 -0
  64. package/src/index.ts +48 -1
  65. package/src/server.ts +192 -34
  66. package/src/types.ts +62 -6
@@ -0,0 +1,504 @@
1
+ import "./index2.js";
2
+ import { normalizeActionBattleAttackProfile } from "./index3.js";
3
+ import { normalizeActionBattleOptions, setActionBattleOptions } from "./index4.js";
4
+ import { manhattanDistance, parseAoeMask } from "./index7.js";
5
+ import { playActionBattleAnimation } from "./index10.js";
6
+ import { ActionBattleHitTracker, createActionBattleAttackId, getNormalizedActionBattleAttackProfile, resolveActionBattleHitboxSpeed, scheduleActionBattleStartup } from "./index11.js";
7
+ import { DEFAULT_ZELDA_PLAYER_HITBOXES } from "./index13.js";
8
+ import { getActionBattleSystems, setActionBattleSystems } from "./index14.js";
9
+ import "./index15.js";
10
+ import "./index16.js";
11
+ import { resolveActionBattleWeaponAttackProfile } from "./index17.js";
12
+ import { applyActionBattleHit } from "./index18.js";
13
+ import { Control, defineModule } from "@rpgjs/common";
14
+ //#region src/server.ts
15
+ var RpgEvent = null;
16
+ var DEFAULT_KNOCKBACK = null;
17
+ var ACTION_BATTLE_ACTION_BAR_GUI_ID = "action-battle-action-bar";
18
+ var DEFAULT_ATTACK_LOCK_DURATION_MS = 350;
19
+ /**
20
+ * Default player attack hitboxes offsets for each direction
21
+ *
22
+ * These hitboxes define the attack areas relative to the player's position
23
+ * for each cardinal direction. They are converted to absolute coordinates
24
+ * when creating the moving hitbox.
25
+ */
26
+ var DEFAULT_PLAYER_ATTACK_HITBOXES = { ...DEFAULT_ZELDA_PLAYER_HITBOXES };
27
+ var beginPlayerAttackLock = (player, map, durationMs, locks) => {
28
+ if (durationMs <= 0) return true;
29
+ const runtimePlayer = player;
30
+ const now = Date.now();
31
+ if (typeof runtimePlayer.__actionBattleAttackLockedUntil === "number" && runtimePlayer.__actionBattleAttackLockedUntil > now) return false;
32
+ const lockId = (runtimePlayer.__actionBattleAttackLockId ?? 0) + 1;
33
+ runtimePlayer.__actionBattleAttackLockId = lockId;
34
+ runtimePlayer.__actionBattleAttackLockedUntil = now + durationMs;
35
+ const previousCanMove = typeof player.canMove === "function" ? player.canMove() : true;
36
+ const previousDirectionFixed = player.directionFixed;
37
+ const previousAnimationFixed = player.animationFixed;
38
+ if (locks.movement) {
39
+ player.pendingInputs = [];
40
+ player.lastProcessedInputTs = 0;
41
+ map?.stopMovement?.(player);
42
+ player.canMove.set(false);
43
+ }
44
+ if (locks.direction) player.directionFixed = true;
45
+ setTimeout(() => {
46
+ if (runtimePlayer.__actionBattleAttackLockId !== lockId) return;
47
+ runtimePlayer.__actionBattleAttackLockedUntil = 0;
48
+ player.canMove.set(previousCanMove);
49
+ player.directionFixed = previousDirectionFixed;
50
+ player.animationFixed = previousAnimationFixed;
51
+ }, durationMs);
52
+ return true;
53
+ };
54
+ var isBattleEvent = (event) => !!event.battleAi;
55
+ var rectsOverlap = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
56
+ var eventRect = (event) => {
57
+ const hitbox = typeof event.hitbox === "function" ? event.hitbox() : event.hitbox;
58
+ return {
59
+ x: event.x(),
60
+ y: event.y(),
61
+ width: hitbox?.w ?? 32,
62
+ height: hitbox?.h ?? 32
63
+ };
64
+ };
65
+ var getVisibleActionEvents = (player, map, hitboxes) => {
66
+ if (!map) return [];
67
+ const eventsById = /* @__PURE__ */ new Map();
68
+ const addEvent = (event) => {
69
+ if (!event) return;
70
+ if (!(typeof map.isEventVisibleForPlayer === "function" ? map.isEventVisibleForPlayer(event, player) : true)) return;
71
+ eventsById.set(event.id, event);
72
+ };
73
+ const collisions = map.getCollisions?.(player.id);
74
+ if (Array.isArray(collisions)) collisions.forEach((id) => addEvent(map.getEvent(id)));
75
+ const direction = typeof player.getDirection === "function" ? player.getDirection() : void 0;
76
+ const interactionCollisions = map.getInteractionCollisions?.(player.id, direction);
77
+ if (Array.isArray(interactionCollisions)) interactionCollisions.forEach((id) => addEvent(map.getEvent(id)));
78
+ for (const event of map.getEvents()) {
79
+ const rect = eventRect(event);
80
+ if (hitboxes.some((hitbox) => rectsOverlap(hitbox, rect))) addEvent(event);
81
+ }
82
+ return Array.from(eventsById.values());
83
+ };
84
+ var isActionReservedForNormalEvent = (player, map, hitboxes) => {
85
+ const events = getVisibleActionEvents(player, map, hitboxes);
86
+ return events.length > 0 && !events.some(isBattleEvent);
87
+ };
88
+ /**
89
+ * Get knockback force from player's equipped weapon
90
+ *
91
+ * Retrieves the knockbackForce property from the player's equipped weapon.
92
+ * Falls back to DEFAULT_KNOCKBACK.force if no weapon or property is set.
93
+ *
94
+ * @param player - The player to get weapon knockback from
95
+ * @returns Knockback force value
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * // Player with weapon having knockbackForce: 80
100
+ * const force = getPlayerWeaponKnockbackForce(player); // 80
101
+ *
102
+ * // No weapon equipped
103
+ * const force = getPlayerWeaponKnockbackForce(player); // 50 (default)
104
+ * ```
105
+ */
106
+ function getPlayerWeaponKnockbackForce(player) {
107
+ try {
108
+ const equipments = player.equipments?.() || [];
109
+ for (const item of equipments) {
110
+ const itemData = player.databaseById?.(item.id());
111
+ if (itemData?._type === "weapon" && itemData.knockbackForce !== void 0) return itemData.knockbackForce;
112
+ }
113
+ } catch {}
114
+ return DEFAULT_KNOCKBACK.force;
115
+ }
116
+ /**
117
+ * Apply hit from player to target (event with AI)
118
+ *
119
+ * Handles damage calculation, knockback based on weapon, and visual effects.
120
+ * Can be customized using hooks.
121
+ *
122
+ * @param player - The attacking player
123
+ * @param target - The event being hit
124
+ * @param hooks - Optional hooks for customizing hit behavior
125
+ * @returns Hit result if AI exists, undefined otherwise
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * // Basic hit
130
+ * const result = applyPlayerHitToEvent(player, event);
131
+ *
132
+ * // With custom hooks
133
+ * const result = applyPlayerHitToEvent(player, event, {
134
+ * onBeforeHit(result) {
135
+ * result.knockbackForce *= 2; // Double knockback
136
+ * return result;
137
+ * },
138
+ * onAfterHit(result) {
139
+ * if (result.defeated) {
140
+ * player.gold += 10;
141
+ * }
142
+ * }
143
+ * });
144
+ * ```
145
+ */
146
+ function applyPlayerHitToEvent(player, target, hooks, metadata) {
147
+ const ai = target.battleAi;
148
+ if (!ai) return void 0;
149
+ const systems = getActionBattleSystems();
150
+ const result = applyActionBattleHit({
151
+ ...systems.combat,
152
+ hooks: hooks ? {
153
+ ...systems.combat.hooks,
154
+ beforeHit(context) {
155
+ const before = systems.combat.hooks?.beforeHit?.(context);
156
+ if (before === false) return false;
157
+ const nextContext = before || context;
158
+ const legacyResult = toLegacyHitResult(nextContext);
159
+ const modified = hooks.onBeforeHit?.(legacyResult);
160
+ if (!modified) return nextContext;
161
+ return {
162
+ ...nextContext,
163
+ damage: {
164
+ damage: modified.damage,
165
+ defeated: modified.defeated,
166
+ raw: nextContext.damage?.raw
167
+ },
168
+ knockback: {
169
+ force: modified.knockbackForce,
170
+ duration: modified.knockbackDuration,
171
+ direction: nextContext.knockback?.direction
172
+ }
173
+ };
174
+ },
175
+ afterHit(result) {
176
+ systems.combat.hooks?.afterHit?.(result);
177
+ hooks.onAfterHit?.(result);
178
+ }
179
+ } : systems.combat.hooks
180
+ }, {
181
+ attacker: player,
182
+ target,
183
+ metadata,
184
+ reaction: metadata?.reaction
185
+ });
186
+ if (!result.cancelled) ai.handleDamage(player, {
187
+ damage: result.damage,
188
+ defeated: result.defeated,
189
+ raw: result.rawDamage,
190
+ reaction: result.reaction
191
+ });
192
+ return result;
193
+ }
194
+ var toLegacyHitResult = (context) => ({
195
+ damage: context.damage?.damage ?? 0,
196
+ knockbackForce: context.knockback?.force ?? getPlayerWeaponKnockbackForce(context.attacker),
197
+ knockbackDuration: context.knockback?.duration ?? DEFAULT_KNOCKBACK.duration,
198
+ defeated: context.damage?.defeated ?? false,
199
+ attacker: context.attacker,
200
+ target: context.target
201
+ });
202
+ var resolvePlayerAttackHitboxes = (player, directionKey, options, profile) => {
203
+ const configuredHitboxes = {
204
+ ...DEFAULT_PLAYER_ATTACK_HITBOXES,
205
+ ...options.attack?.hitboxes,
206
+ ...profile.hitboxes
207
+ };
208
+ const hitboxConfig = configuredHitboxes[directionKey] || configuredHitboxes.default;
209
+ const defaultHitboxes = [{
210
+ x: player.x() + hitboxConfig.offsetX,
211
+ y: player.y() + hitboxConfig.offsetY,
212
+ width: hitboxConfig.width,
213
+ height: hitboxConfig.height
214
+ }];
215
+ return options.attack?.resolveHitboxes?.({
216
+ player,
217
+ direction: directionKey,
218
+ defaultHitboxes
219
+ }) ?? defaultHitboxes;
220
+ };
221
+ var mergeAttackProfileOverrides = (base, override) => ({
222
+ ...base,
223
+ ...override,
224
+ reaction: {
225
+ ...base.reaction,
226
+ ...override.reaction
227
+ },
228
+ hitboxes: {
229
+ ...base.hitboxes,
230
+ ...override.hitboxes
231
+ }
232
+ });
233
+ var resolvePlayerAttackProfile = (player, options) => {
234
+ const baseProfile = getNormalizedActionBattleAttackProfile(options);
235
+ const weaponProfile = resolveActionBattleWeaponAttackProfile(player);
236
+ if (!weaponProfile) return baseProfile;
237
+ return normalizeActionBattleAttackProfile(mergeAttackProfileOverrides(baseProfile, weaponProfile), {
238
+ lockMovement: options.attack?.lockMovement,
239
+ lockDurationMs: options.attack?.lockDurationMs,
240
+ hitboxes: options.attack?.hitboxes
241
+ });
242
+ };
243
+ var resolveSignal = (value) => typeof value === "function" ? value() : value;
244
+ var resolveItemData = (player, itemId) => {
245
+ try {
246
+ return player.databaseById?.(itemId);
247
+ } catch {
248
+ return null;
249
+ }
250
+ };
251
+ var resolveSkillData = (player, skillId) => {
252
+ try {
253
+ return player.databaseById?.(skillId);
254
+ } catch {
255
+ return null;
256
+ }
257
+ };
258
+ var resolveSkillTargeting = (player, skillId, options) => {
259
+ const skillsOptions = options.skills;
260
+ const skillData = resolveSkillData(player, skillId);
261
+ if (skillsOptions?.getTargeting) return skillsOptions.getTargeting(skillData);
262
+ const range = skillData?.range ?? skillData?.targeting?.range ?? skillData?.targeting?.distance;
263
+ const aoeMask = skillData?.aoeMask ?? skillData?.targeting?.aoeMask ?? skillData?.targeting?.mask;
264
+ if (range === void 0 && aoeMask === void 0) return null;
265
+ return {
266
+ range: range ?? 0,
267
+ aoeMask
268
+ };
269
+ };
270
+ var normalizeMaskRows = (mask) => {
271
+ if (!mask) return [];
272
+ if (Array.isArray(mask)) return mask;
273
+ return mask.trim().split("\n").map((row) => row.replace(/\r/g, ""));
274
+ };
275
+ var buildActionBarData = (player, options) => {
276
+ return {
277
+ items: (player.items?.() || []).map((item) => {
278
+ const id = item.id?.() ?? item.id;
279
+ const data = resolveItemData(player, id);
280
+ const name = resolveSignal(data?.name) ?? resolveSignal(item.name) ?? id;
281
+ const description = resolveSignal(data?.description) ?? resolveSignal(item.description) ?? "";
282
+ const icon = resolveSignal(data?.icon) ?? resolveSignal(item.icon);
283
+ const quantity = resolveSignal(item.quantity) ?? 1;
284
+ const consumable = resolveSignal(data?.consumable);
285
+ const itemType = resolveSignal(data?._type);
286
+ return {
287
+ id,
288
+ name,
289
+ description,
290
+ icon,
291
+ quantity,
292
+ usable: quantity > 0 && consumable !== false && (itemType ? itemType === "item" : true)
293
+ };
294
+ }),
295
+ skills: (player.skills?.() || []).map((skill) => {
296
+ const id = skill.id?.() ?? skill.id;
297
+ const data = resolveSkillData(player, id) || skill;
298
+ const name = resolveSignal(data?.name) ?? resolveSignal(skill.name) ?? id;
299
+ const description = resolveSignal(data?.description) ?? resolveSignal(skill.description) ?? "";
300
+ const icon = resolveSignal(data?.icon) ?? resolveSignal(skill.icon);
301
+ const spCost = resolveSignal(data?.spCost) ?? resolveSignal(skill.spCost) ?? 0;
302
+ const usable = spCost <= player.sp;
303
+ const targeting = resolveSkillTargeting(player, id, options);
304
+ const skillEntry = {
305
+ id,
306
+ name,
307
+ description,
308
+ icon,
309
+ spCost,
310
+ usable,
311
+ range: targeting?.range ?? 0
312
+ };
313
+ if (targeting) {
314
+ const mask = targeting.aoeMask ?? options.skills?.defaultAoeMask;
315
+ if (mask) skillEntry.aoeMask = normalizeMaskRows(mask);
316
+ }
317
+ return skillEntry;
318
+ })
319
+ };
320
+ };
321
+ var ensureActionBarGui = (player, options) => {
322
+ const gui = player.getGui?.("action-battle-action-bar") || player.gui("action-battle-action-bar");
323
+ if (!gui.__actionBattleReady) {
324
+ gui.__actionBattleReady = true;
325
+ gui.on("useItem", ({ id }) => {
326
+ try {
327
+ player.useItem(id);
328
+ } catch {}
329
+ gui.update(buildActionBarData(player, options));
330
+ });
331
+ gui.on("useSkill", ({ id, target }) => {
332
+ handleActionBattleSkillUse(player, id, target, options);
333
+ gui.update(buildActionBarData(player, options));
334
+ });
335
+ gui.on("refresh", () => {
336
+ gui.update(buildActionBarData(player, options));
337
+ });
338
+ }
339
+ return gui;
340
+ };
341
+ var openActionBattleActionBar = (player, rawOptions = {}) => {
342
+ const options = normalizeActionBattleOptions(rawOptions);
343
+ ensureActionBarGui(player, options).open(buildActionBarData(player, options));
344
+ };
345
+ var updateActionBattleActionBar = (player, rawOptions = {}) => {
346
+ const options = normalizeActionBattleOptions(rawOptions);
347
+ const gui = player.getGui?.(ACTION_BATTLE_ACTION_BAR_GUI_ID);
348
+ if (gui) gui.update(buildActionBarData(player, options));
349
+ };
350
+ var getTileSize = (map) => ({
351
+ width: map?.tileWidth ?? 32,
352
+ height: map?.tileHeight ?? 32
353
+ });
354
+ var getEntityTile = (entity, tileSize) => {
355
+ const hitbox = entity.hitbox?.() || {
356
+ w: tileSize.width,
357
+ h: tileSize.height
358
+ };
359
+ return {
360
+ x: Math.floor((entity.x() + hitbox.w / 2) / tileSize.width),
361
+ y: Math.floor((entity.y() + hitbox.h / 2) / tileSize.height)
362
+ };
363
+ };
364
+ var handleActionBattleSkillUse = (player, skillId, target, options) => {
365
+ const skillData = resolveSkillData(player, skillId);
366
+ const map = player.getCurrentMap();
367
+ if (!map) {
368
+ playActionBattleAnimation("castSkill", player, options.animations, { skill: skillData });
369
+ player.useSkill(skillId);
370
+ return;
371
+ }
372
+ const targeting = resolveSkillTargeting(player, skillId, options);
373
+ if (!targeting || !target) {
374
+ playActionBattleAnimation("castSkill", player, options.animations, { skill: skillData });
375
+ player.useSkill(skillId);
376
+ return;
377
+ }
378
+ const tileSize = getTileSize(map);
379
+ const origin = getEntityTile(player, tileSize);
380
+ const targetTile = {
381
+ x: target.x,
382
+ y: target.y
383
+ };
384
+ if (manhattanDistance(origin, targetTile) > targeting.range) return;
385
+ const mask = parseAoeMask(targeting.aoeMask || options.skills?.defaultAoeMask);
386
+ const affected = /* @__PURE__ */ new Set();
387
+ mask.cells.forEach((cell) => {
388
+ const x = targetTile.x + cell.dx;
389
+ const y = targetTile.y + cell.dy;
390
+ affected.add(`${x},${y}`);
391
+ });
392
+ const targets = [];
393
+ const affects = options.targeting?.affects || "events";
394
+ if (affects === "events" || affects === "both") map.getEvents().forEach((event) => {
395
+ const tile = getEntityTile(event, tileSize);
396
+ if (affected.has(`${tile.x},${tile.y}`)) targets.push(event);
397
+ });
398
+ if (affects === "players" || affects === "both") map.getPlayers().forEach((other) => {
399
+ if (other.id === player.id) return;
400
+ const tile = getEntityTile(other, tileSize);
401
+ if (affected.has(`${tile.x},${tile.y}`)) targets.push(other);
402
+ });
403
+ if (!options.targeting?.allowEmptyTarget && targets.length === 0) return;
404
+ playActionBattleAnimation("castSkill", player, options.animations, {
405
+ skill: skillData,
406
+ target: targets[0]
407
+ });
408
+ player.useSkill(skillId, targets);
409
+ };
410
+ var createActionBattleServer = (rawOptions = {}) => {
411
+ const options = normalizeActionBattleOptions(rawOptions);
412
+ setActionBattleOptions(options);
413
+ setActionBattleSystems(options);
414
+ return defineModule({
415
+ player: {
416
+ /**
417
+ * Handle player input for combat actions
418
+ *
419
+ * When a player presses the action key, create an attack hitbox
420
+ * that can damage AI enemies within range and knockback the event.
421
+ * Knockback force is based on the player's equipped weapon.
422
+ * Triggers attack animation and visual effects.
423
+ *
424
+ * @param player - The player performing the action
425
+ * @param input - Input data containing pressed keys
426
+ */
427
+ onInput(player, input) {
428
+ if (input.action == Control.Action) {
429
+ const map = player.getCurrentMap();
430
+ const direction = player.getDirection();
431
+ const attackProfile = resolvePlayerAttackProfile(player, options);
432
+ const hitboxes = resolvePlayerAttackHitboxes(player, direction, options, attackProfile);
433
+ if (isActionReservedForNormalEvent(player, map, hitboxes)) return;
434
+ const lockMovement = attackProfile.movementLock;
435
+ const lockDirection = attackProfile.directionLock;
436
+ const lockDurationMs = attackProfile.totalDurationMs ?? DEFAULT_ATTACK_LOCK_DURATION_MS;
437
+ const actionLocked = (lockMovement || lockDirection) && lockDurationMs > 0;
438
+ if (actionLocked && !beginPlayerAttackLock(player, map, Math.max(0, lockDurationMs), {
439
+ movement: lockMovement,
440
+ direction: lockDirection
441
+ })) return;
442
+ playActionBattleAnimation("attack", player, options.animations);
443
+ if (actionLocked) player.animationFixed = true;
444
+ const attackId = createActionBattleAttackId(player.id, attackProfile.id);
445
+ const hitTracker = new ActionBattleHitTracker(attackProfile.hitPolicy);
446
+ if (options.debug?.attacks) console.log("[ActionBattle] player attack", {
447
+ attackId,
448
+ playerId: player.id,
449
+ profile: attackProfile.id,
450
+ hitboxes
451
+ });
452
+ scheduleActionBattleStartup(attackProfile, () => {
453
+ map?.createMovingHitbox(hitboxes, { speed: resolveActionBattleHitboxSpeed(attackProfile, hitboxes.length) }).subscribe({ next(hits) {
454
+ hits.forEach((hit) => {
455
+ if (hit instanceof RpgEvent) {
456
+ if (!hitTracker.tryHit(hit)) return;
457
+ if (applyPlayerHitToEvent(player, hit, void 0, {
458
+ attackId,
459
+ attackProfileId: attackProfile.id,
460
+ reaction: attackProfile.reaction
461
+ })?.defeated) console.log(`Player ${player.id} defeated AI ${hit.id}`);
462
+ }
463
+ });
464
+ } });
465
+ });
466
+ }
467
+ },
468
+ onConnected(player) {
469
+ if (options.ui?.actionBar?.enabled && options.ui?.actionBar?.autoOpen) openActionBattleActionBar(player, options);
470
+ }
471
+ },
472
+ event: {
473
+ /**
474
+ * Handle player detection when entering AI vision
475
+ *
476
+ * Called when a player enters an AI event's vision range.
477
+ * The AI will start pursuing and attacking the player.
478
+ *
479
+ * @param event - The AI event
480
+ * @param player - The player entering vision
481
+ * @param shape - The vision shape
482
+ */
483
+ onDetectInShape(event, player, shape) {
484
+ event.battleAi?.onDetectInShape(player, shape);
485
+ },
486
+ /**
487
+ * Handle player leaving AI vision
488
+ *
489
+ * Called when a player leaves an AI event's vision range.
490
+ * The AI will stop pursuing the player.
491
+ *
492
+ * @param event - The AI event
493
+ * @param player - The player leaving vision
494
+ * @param shape - The vision shape
495
+ */
496
+ onDetectOutShape(event, player, shape) {
497
+ event.battleAi?.onDetectOutShape(player, shape);
498
+ }
499
+ }
500
+ });
501
+ };
502
+ createActionBattleServer();
503
+ //#endregion
504
+ export { ACTION_BATTLE_ACTION_BAR_GUI_ID, DEFAULT_PLAYER_ATTACK_HITBOXES, applyPlayerHitToEvent, createActionBattleServer, getPlayerWeaponKnockbackForce, openActionBattleActionBar, updateActionBattleActionBar };
@@ -1,85 +1,47 @@
1
- import { DEFAULT_ACTION_BATTLE_OPTIONS, normalizeActionBattleOptions } from "./index2.js";
2
- import { signal } from "canvasengine";
3
- //#region src/ui/state.ts
4
- var defaultTargetingState = {
5
- active: false,
6
- skill: null,
7
- range: 0,
8
- offset: {
9
- x: 0,
10
- y: 0
11
- },
12
- aoeMask: DEFAULT_ACTION_BATTLE_OPTIONS.skills?.defaultAoeMask || ["#"]
13
- };
14
- var defaultAttackPreviewState = {
15
- active: false,
16
- id: 0,
17
- direction: "down",
18
- startedAt: 0,
19
- durationMs: 180,
20
- color: 16774064,
21
- accentColor: 16777215
22
- };
23
- var actionBattleUiOptions = signal(normalizeActionBattleOptions({}).ui || {});
24
- var actionBattleSkillOptions = signal(normalizeActionBattleOptions({}).skills || {});
25
- var actionBattleTargetingState = signal({ ...defaultTargetingState });
26
- var actionBattleAttackPreviewState = signal({ ...defaultAttackPreviewState });
27
- var setActionBattleOptions = (options = {}) => {
28
- const normalized = normalizeActionBattleOptions(options);
29
- actionBattleUiOptions.set(normalized.ui || {});
30
- actionBattleSkillOptions.set(normalized.skills || {});
31
- };
32
- var startTargeting = (skill) => {
33
- const skillsOptions = actionBattleSkillOptions();
34
- const mask = skill.aoeMask || skillsOptions.defaultAoeMask || ["#"];
35
- actionBattleTargetingState.set({
36
- active: true,
37
- skill,
38
- range: skill.range ?? 0,
39
- offset: {
40
- x: 0,
41
- y: 0
42
- },
43
- aoeMask: mask
44
- });
45
- };
46
- var stopTargeting = () => {
47
- actionBattleTargetingState.set({ ...defaultTargetingState });
48
- };
49
- var moveTargetingOffset = (dx, dy) => {
50
- const state = actionBattleTargetingState();
51
- if (!state.active) return;
52
- const next = {
53
- x: state.offset.x + dx,
54
- y: state.offset.y + dy
1
+ import { DEFAULT_ACTION_BATTLE_HIT_REACTION, normalizeActionBattleHitReaction } from "./index2.js";
2
+ //#region src/core/attack-profile.ts
3
+ var DEFAULT_ACTION_BATTLE_ATTACK_PROFILE = {
4
+ id: "basic",
5
+ startupMs: 0,
6
+ activeMs: 120,
7
+ recoveryMs: 230,
8
+ cooldownMs: 350,
9
+ movementLock: true,
10
+ directionLock: true,
11
+ animationKey: "attack",
12
+ hitPolicy: "oncePerTarget",
13
+ reaction: DEFAULT_ACTION_BATTLE_HIT_REACTION,
14
+ totalDurationMs: 350
15
+ };
16
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
17
+ var nonNegativeMs = (value, fallback) => isFiniteNumber(value) ? Math.max(0, value) : fallback;
18
+ var positiveMs = (value, fallback) => isFiniteNumber(value) ? Math.max(1, value) : fallback;
19
+ var resolveHitPolicy = (value) => value === "allowRepeatHits" ? "allowRepeatHits" : "oncePerTarget";
20
+ var resolveAnimationKey = (value) => value ?? DEFAULT_ACTION_BATTLE_ATTACK_PROFILE.animationKey;
21
+ function normalizeActionBattleAttackProfile(profile = {}, fallbacks = {}) {
22
+ const startupMs = nonNegativeMs(profile.startupMs, DEFAULT_ACTION_BATTLE_ATTACK_PROFILE.startupMs);
23
+ const activeMs = positiveMs(profile.activeMs, DEFAULT_ACTION_BATTLE_ATTACK_PROFILE.activeMs);
24
+ const legacyDuration = nonNegativeMs(fallbacks.lockDurationMs, DEFAULT_ACTION_BATTLE_ATTACK_PROFILE.totalDurationMs);
25
+ const fallbackRecoveryMs = Math.max(0, legacyDuration - startupMs - activeMs);
26
+ const recoveryMs = nonNegativeMs(profile.recoveryMs, fallbackRecoveryMs);
27
+ const totalDurationMs = startupMs + activeMs + recoveryMs;
28
+ const cooldownMs = nonNegativeMs(profile.cooldownMs, totalDurationMs);
29
+ const hitboxes = profile.hitboxes ?? fallbacks.hitboxes;
30
+ const normalized = {
31
+ id: profile.id || fallbacks.id || DEFAULT_ACTION_BATTLE_ATTACK_PROFILE.id,
32
+ startupMs,
33
+ activeMs,
34
+ recoveryMs,
35
+ cooldownMs,
36
+ movementLock: profile.movementLock ?? fallbacks.lockMovement ?? DEFAULT_ACTION_BATTLE_ATTACK_PROFILE.movementLock,
37
+ directionLock: profile.directionLock ?? DEFAULT_ACTION_BATTLE_ATTACK_PROFILE.directionLock,
38
+ animationKey: resolveAnimationKey(profile.animationKey),
39
+ hitPolicy: resolveHitPolicy(profile.hitPolicy),
40
+ reaction: normalizeActionBattleHitReaction(profile.reaction),
41
+ totalDurationMs
55
42
  };
56
- if (Math.abs(next.x) + Math.abs(next.y) > state.range) return;
57
- actionBattleTargetingState.set({
58
- ...state,
59
- offset: next
60
- });
61
- };
62
- var startAttackPreview = (options) => {
63
- const id = actionBattleAttackPreviewState().id + 1;
64
- const durationMs = Math.max(1, options.durationMs ?? defaultAttackPreviewState.durationMs);
65
- actionBattleAttackPreviewState.set({
66
- active: true,
67
- id,
68
- direction: options.direction,
69
- startedAt: Date.now(),
70
- durationMs,
71
- color: options.color ?? defaultAttackPreviewState.color,
72
- accentColor: options.accentColor ?? defaultAttackPreviewState.accentColor
73
- });
74
- return id;
75
- };
76
- var stopAttackPreview = (id) => {
77
- const current = actionBattleAttackPreviewState();
78
- if (id !== void 0 && current.id !== id) return;
79
- actionBattleAttackPreviewState.set({
80
- ...current,
81
- active: false
82
- });
83
- };
43
+ if (hitboxes) normalized.hitboxes = hitboxes;
44
+ return normalized;
45
+ }
84
46
  //#endregion
85
- export { actionBattleAttackPreviewState, actionBattleTargetingState, actionBattleUiOptions, moveTargetingOffset, setActionBattleOptions, startAttackPreview, startTargeting, stopAttackPreview, stopTargeting };
47
+ export { DEFAULT_ACTION_BATTLE_ATTACK_PROFILE, normalizeActionBattleAttackProfile };