@rpgjs/action-battle 5.0.0-beta.2 → 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,30 +1,37 @@
1
- const normalizeMaskRows = (mask) => {
2
- if (!mask) return ["#"];
3
- if (Array.isArray(mask)) return mask;
4
- return mask.trim().split("\n").map((row) => row.replace(/\r/g, ""));
1
+ //#region src/targeting.ts
2
+ var normalizeMaskRows = (mask) => {
3
+ if (!mask) return ["#"];
4
+ if (Array.isArray(mask)) return mask;
5
+ return mask.trim().split("\n").map((row) => row.replace(/\r/g, ""));
5
6
  };
6
- const parseAoeMask = (mask) => {
7
- const rows = normalizeMaskRows(mask);
8
- const height = rows.length;
9
- const width = rows.reduce((max, row) => Math.max(max, row.length), 0);
10
- const centerX = Math.floor(width / 2);
11
- const centerY = Math.floor(height / 2);
12
- const cells = [];
13
- rows.forEach((row, y) => {
14
- for (let x = 0; x < row.length; x++) {
15
- const char = row[x];
16
- if (char && char !== "." && char !== " ") {
17
- cells.push({ dx: x - centerX, dy: y - centerY });
18
- }
19
- }
20
- });
21
- if (cells.length === 0) {
22
- cells.push({ dx: 0, dy: 0 });
23
- }
24
- return { width, height, centerX, centerY, cells };
25
- };
26
- const manhattanDistance = (a, b) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
27
- export {
28
- manhattanDistance,
29
- parseAoeMask
7
+ var parseAoeMask = (mask) => {
8
+ const rows = normalizeMaskRows(mask);
9
+ const height = rows.length;
10
+ const width = rows.reduce((max, row) => Math.max(max, row.length), 0);
11
+ const centerX = Math.floor(width / 2);
12
+ const centerY = Math.floor(height / 2);
13
+ const cells = [];
14
+ rows.forEach((row, y) => {
15
+ for (let x = 0; x < row.length; x++) {
16
+ const char = row[x];
17
+ if (char && char !== "." && char !== " ") cells.push({
18
+ dx: x - centerX,
19
+ dy: y - centerY
20
+ });
21
+ }
22
+ });
23
+ if (cells.length === 0) cells.push({
24
+ dx: 0,
25
+ dy: 0
26
+ });
27
+ return {
28
+ width,
29
+ height,
30
+ centerX,
31
+ centerY,
32
+ cells
33
+ };
30
34
  };
35
+ var manhattanDistance = (a, b) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
36
+ //#endregion
37
+ export { manhattanDistance, parseAoeMask };
@@ -1,64 +1,376 @@
1
- const DEFAULT_DIE_ANIMATION_DELAY_MS = 500;
2
- const DEFAULT_ANIMATION_BY_KEY = {
3
- attack: "attack",
4
- hurt: "hurt",
5
- die: "die",
6
- castSkill: "skill"
1
+ import { playActionBattleAnimation } from "./index2.js";
2
+ import { normalizeActionBattleOptions, setActionBattleOptions } from "./index3.js";
3
+ import { DEFAULT_KNOCKBACK } from "./index4.js";
4
+ import { manhattanDistance, parseAoeMask } from "./index5.js";
5
+ import { RpgEvent } from "@rpgjs/server";
6
+ import { Control, defineModule } from "@rpgjs/common";
7
+ //#region src/server.ts
8
+ var ACTION_BATTLE_ACTION_BAR_GUI_ID = "action-battle-action-bar";
9
+ /**
10
+ * Default player attack hitboxes offsets for each direction
11
+ *
12
+ * These hitboxes define the attack areas relative to the player's position
13
+ * for each cardinal direction. They are converted to absolute coordinates
14
+ * when creating the moving hitbox.
15
+ */
16
+ var DEFAULT_PLAYER_ATTACK_HITBOXES = {
17
+ up: {
18
+ offsetX: -16,
19
+ offsetY: -48,
20
+ width: 32,
21
+ height: 32
22
+ },
23
+ down: {
24
+ offsetX: -16,
25
+ offsetY: 16,
26
+ width: 32,
27
+ height: 32
28
+ },
29
+ left: {
30
+ offsetX: -48,
31
+ offsetY: -16,
32
+ width: 32,
33
+ height: 32
34
+ },
35
+ right: {
36
+ offsetX: 16,
37
+ offsetY: -16,
38
+ width: 32,
39
+ height: 32
40
+ },
41
+ default: {
42
+ offsetX: 0,
43
+ offsetY: -32,
44
+ width: 32,
45
+ height: 32
46
+ }
7
47
  };
8
- function resolveActionBattleAnimation(key, entity, animations, context, defaults = {}) {
9
- const defaultAnimationName = defaults.animationName ?? DEFAULT_ANIMATION_BY_KEY[key];
10
- const defaultRepeat = defaults.repeat ?? 1;
11
- const hasConfiguredAnimation = animations ? Object.prototype.hasOwnProperty.call(animations, key) : false;
12
- if (!hasConfiguredAnimation && key !== "attack") {
13
- return null;
14
- }
15
- const configured = hasConfiguredAnimation ? animations?.[key] : defaultAnimationName;
16
- const result = typeof configured === "function" ? configured(entity, context) : configured;
17
- if (result == null) return null;
18
- if (typeof result === "string") {
19
- return {
20
- animationName: result,
21
- repeat: defaultRepeat,
22
- waitEnd: false
23
- };
24
- }
25
- const animationName = result.animationName ?? defaultAnimationName;
26
- return {
27
- animationName,
28
- graphic: result.graphic,
29
- repeat: result.repeat ?? defaultRepeat,
30
- waitEnd: result.waitEnd ?? false,
31
- delayMs: result.delayMs
32
- };
48
+ /**
49
+ * Get knockback force from player's equipped weapon
50
+ *
51
+ * Retrieves the knockbackForce property from the player's equipped weapon.
52
+ * Falls back to DEFAULT_KNOCKBACK.force if no weapon or property is set.
53
+ *
54
+ * @param player - The player to get weapon knockback from
55
+ * @returns Knockback force value
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * // Player with weapon having knockbackForce: 80
60
+ * const force = getPlayerWeaponKnockbackForce(player); // 80
61
+ *
62
+ * // No weapon equipped
63
+ * const force = getPlayerWeaponKnockbackForce(player); // 50 (default)
64
+ * ```
65
+ */
66
+ function getPlayerWeaponKnockbackForce(player) {
67
+ try {
68
+ const equipments = player.equipments?.() || [];
69
+ for (const item of equipments) {
70
+ const itemData = player.databaseById?.(item.id());
71
+ if (itemData?._type === "weapon" && itemData.knockbackForce !== void 0) return itemData.knockbackForce;
72
+ }
73
+ } catch {}
74
+ return DEFAULT_KNOCKBACK.force;
33
75
  }
34
- function playActionBattleAnimation(key, entity, animations, context, defaults = {}) {
35
- const animation = resolveActionBattleAnimation(
36
- key,
37
- entity,
38
- animations,
39
- context,
40
- defaults
41
- );
42
- if (!animation) return null;
43
- if (animation.graphic !== void 0) {
44
- entity.setGraphicAnimation(
45
- animation.animationName,
46
- animation.graphic,
47
- animation.repeat
48
- );
49
- } else {
50
- entity.setGraphicAnimation(animation.animationName, animation.repeat);
51
- }
52
- return animation;
76
+ /**
77
+ * Apply hit from player to target (event with AI)
78
+ *
79
+ * Handles damage calculation, knockback based on weapon, and visual effects.
80
+ * Can be customized using hooks.
81
+ *
82
+ * @param player - The attacking player
83
+ * @param target - The event being hit
84
+ * @param hooks - Optional hooks for customizing hit behavior
85
+ * @returns Hit result if AI exists, undefined otherwise
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * // Basic hit
90
+ * const result = applyPlayerHitToEvent(player, event);
91
+ *
92
+ * // With custom hooks
93
+ * const result = applyPlayerHitToEvent(player, event, {
94
+ * onBeforeHit(result) {
95
+ * result.knockbackForce *= 2; // Double knockback
96
+ * return result;
97
+ * },
98
+ * onAfterHit(result) {
99
+ * if (result.defeated) {
100
+ * player.gold += 10;
101
+ * }
102
+ * }
103
+ * });
104
+ * ```
105
+ */
106
+ function applyPlayerHitToEvent(player, target, hooks) {
107
+ const ai = target.battleAi;
108
+ if (!ai) return void 0;
109
+ const knockbackForce = getPlayerWeaponKnockbackForce(player);
110
+ const defeated = ai.takeDamage(player);
111
+ const dx = target.x() - player.x();
112
+ const dy = target.y() - player.y();
113
+ const distance = Math.sqrt(dx * dx + dy * dy);
114
+ let hitResult = {
115
+ damage: 0,
116
+ knockbackForce,
117
+ knockbackDuration: DEFAULT_KNOCKBACK.duration,
118
+ defeated,
119
+ attacker: player,
120
+ target
121
+ };
122
+ if (hooks?.onBeforeHit) {
123
+ const modified = hooks.onBeforeHit(hitResult);
124
+ if (modified) hitResult = modified;
125
+ }
126
+ if (!hitResult.defeated && hitResult.knockbackForce > 0 && distance > 0) {
127
+ const knockbackDirection = {
128
+ x: dx / distance,
129
+ y: dy / distance
130
+ };
131
+ target.knockback(knockbackDirection, hitResult.knockbackForce, hitResult.knockbackDuration);
132
+ }
133
+ if (hooks?.onAfterHit) hooks.onAfterHit(hitResult);
134
+ return hitResult;
53
135
  }
54
- function getActionBattleAnimationRemovalDelay(animation) {
55
- if (!animation) return 0;
56
- if (animation.delayMs !== void 0) return animation.delayMs;
57
- return animation.waitEnd ? DEFAULT_DIE_ANIMATION_DELAY_MS : 0;
58
- }
59
- export {
60
- DEFAULT_DIE_ANIMATION_DELAY_MS,
61
- getActionBattleAnimationRemovalDelay,
62
- playActionBattleAnimation,
63
- resolveActionBattleAnimation
136
+ var resolveSignal = (value) => typeof value === "function" ? value() : value;
137
+ var resolveItemData = (player, itemId) => {
138
+ try {
139
+ return player.databaseById?.(itemId);
140
+ } catch {
141
+ return null;
142
+ }
143
+ };
144
+ var resolveSkillData = (player, skillId) => {
145
+ try {
146
+ return player.databaseById?.(skillId);
147
+ } catch {
148
+ return null;
149
+ }
150
+ };
151
+ var resolveSkillTargeting = (player, skillId, options) => {
152
+ const skillsOptions = options.skills;
153
+ const skillData = resolveSkillData(player, skillId);
154
+ if (skillsOptions?.getTargeting) return skillsOptions.getTargeting(skillData);
155
+ const range = skillData?.range ?? skillData?.targeting?.range ?? skillData?.targeting?.distance;
156
+ const aoeMask = skillData?.aoeMask ?? skillData?.targeting?.aoeMask ?? skillData?.targeting?.mask;
157
+ if (range === void 0 && aoeMask === void 0) return null;
158
+ return {
159
+ range: range ?? 0,
160
+ aoeMask
161
+ };
162
+ };
163
+ var normalizeMaskRows = (mask) => {
164
+ if (!mask) return [];
165
+ if (Array.isArray(mask)) return mask;
166
+ return mask.trim().split("\n").map((row) => row.replace(/\r/g, ""));
167
+ };
168
+ var buildActionBarData = (player, options) => {
169
+ return {
170
+ items: (player.items?.() || []).map((item) => {
171
+ const id = item.id?.() ?? item.id;
172
+ const data = resolveItemData(player, id);
173
+ const name = resolveSignal(data?.name) ?? resolveSignal(item.name) ?? id;
174
+ const description = resolveSignal(data?.description) ?? resolveSignal(item.description) ?? "";
175
+ const icon = resolveSignal(data?.icon) ?? resolveSignal(item.icon);
176
+ const quantity = resolveSignal(item.quantity) ?? 1;
177
+ const consumable = resolveSignal(data?.consumable);
178
+ const itemType = resolveSignal(data?._type);
179
+ return {
180
+ id,
181
+ name,
182
+ description,
183
+ icon,
184
+ quantity,
185
+ usable: quantity > 0 && consumable !== false && (itemType ? itemType === "item" : true)
186
+ };
187
+ }),
188
+ skills: (player.skills?.() || []).map((skill) => {
189
+ const id = skill.id?.() ?? skill.id;
190
+ const data = resolveSkillData(player, id) || skill;
191
+ const name = resolveSignal(data?.name) ?? resolveSignal(skill.name) ?? id;
192
+ const description = resolveSignal(data?.description) ?? resolveSignal(skill.description) ?? "";
193
+ const icon = resolveSignal(data?.icon) ?? resolveSignal(skill.icon);
194
+ const spCost = resolveSignal(data?.spCost) ?? resolveSignal(skill.spCost) ?? 0;
195
+ const usable = spCost <= player.sp;
196
+ const targeting = resolveSkillTargeting(player, id, options);
197
+ const skillEntry = {
198
+ id,
199
+ name,
200
+ description,
201
+ icon,
202
+ spCost,
203
+ usable,
204
+ range: targeting?.range ?? 0
205
+ };
206
+ if (targeting) {
207
+ const mask = targeting.aoeMask ?? options.skills?.defaultAoeMask;
208
+ if (mask) skillEntry.aoeMask = normalizeMaskRows(mask);
209
+ }
210
+ return skillEntry;
211
+ })
212
+ };
213
+ };
214
+ var ensureActionBarGui = (player, options) => {
215
+ const gui = player.getGui?.("action-battle-action-bar") || player.gui("action-battle-action-bar");
216
+ if (!gui.__actionBattleReady) {
217
+ gui.__actionBattleReady = true;
218
+ gui.on("useItem", ({ id }) => {
219
+ try {
220
+ player.useItem(id);
221
+ } catch {}
222
+ gui.update(buildActionBarData(player, options));
223
+ });
224
+ gui.on("useSkill", ({ id, target }) => {
225
+ handleActionBattleSkillUse(player, id, target, options);
226
+ gui.update(buildActionBarData(player, options));
227
+ });
228
+ gui.on("refresh", () => {
229
+ gui.update(buildActionBarData(player, options));
230
+ });
231
+ }
232
+ return gui;
233
+ };
234
+ var openActionBattleActionBar = (player, rawOptions = {}) => {
235
+ const options = normalizeActionBattleOptions(rawOptions);
236
+ ensureActionBarGui(player, options).open(buildActionBarData(player, options));
237
+ };
238
+ var updateActionBattleActionBar = (player, rawOptions = {}) => {
239
+ const options = normalizeActionBattleOptions(rawOptions);
240
+ const gui = player.getGui?.(ACTION_BATTLE_ACTION_BAR_GUI_ID);
241
+ if (gui) gui.update(buildActionBarData(player, options));
242
+ };
243
+ var getTileSize = (map) => ({
244
+ width: map?.tileWidth ?? 32,
245
+ height: map?.tileHeight ?? 32
246
+ });
247
+ var getEntityTile = (entity, tileSize) => {
248
+ const hitbox = entity.hitbox?.() || {
249
+ w: tileSize.width,
250
+ h: tileSize.height
251
+ };
252
+ return {
253
+ x: Math.floor((entity.x() + hitbox.w / 2) / tileSize.width),
254
+ y: Math.floor((entity.y() + hitbox.h / 2) / tileSize.height)
255
+ };
256
+ };
257
+ var handleActionBattleSkillUse = (player, skillId, target, options) => {
258
+ const skillData = resolveSkillData(player, skillId);
259
+ const map = player.getCurrentMap();
260
+ if (!map) {
261
+ playActionBattleAnimation("castSkill", player, options.animations, { skill: skillData });
262
+ player.useSkill(skillId);
263
+ return;
264
+ }
265
+ const targeting = resolveSkillTargeting(player, skillId, options);
266
+ if (!targeting || !target) {
267
+ playActionBattleAnimation("castSkill", player, options.animations, { skill: skillData });
268
+ player.useSkill(skillId);
269
+ return;
270
+ }
271
+ const tileSize = getTileSize(map);
272
+ const origin = getEntityTile(player, tileSize);
273
+ const targetTile = {
274
+ x: target.x,
275
+ y: target.y
276
+ };
277
+ if (manhattanDistance(origin, targetTile) > targeting.range) return;
278
+ const mask = parseAoeMask(targeting.aoeMask || options.skills?.defaultAoeMask);
279
+ const affected = /* @__PURE__ */ new Set();
280
+ mask.cells.forEach((cell) => {
281
+ const x = targetTile.x + cell.dx;
282
+ const y = targetTile.y + cell.dy;
283
+ affected.add(`${x},${y}`);
284
+ });
285
+ const targets = [];
286
+ const affects = options.targeting?.affects || "events";
287
+ if (affects === "events" || affects === "both") map.getEvents().forEach((event) => {
288
+ const tile = getEntityTile(event, tileSize);
289
+ if (affected.has(`${tile.x},${tile.y}`)) targets.push(event);
290
+ });
291
+ if (affects === "players" || affects === "both") map.getPlayers().forEach((other) => {
292
+ if (other.id === player.id) return;
293
+ const tile = getEntityTile(other, tileSize);
294
+ if (affected.has(`${tile.x},${tile.y}`)) targets.push(other);
295
+ });
296
+ if (!options.targeting?.allowEmptyTarget && targets.length === 0) return;
297
+ playActionBattleAnimation("castSkill", player, options.animations, {
298
+ skill: skillData,
299
+ target: targets[0]
300
+ });
301
+ player.useSkill(skillId, targets);
302
+ };
303
+ var createActionBattleServer = (rawOptions = {}) => {
304
+ const options = normalizeActionBattleOptions(rawOptions);
305
+ setActionBattleOptions(options);
306
+ return defineModule({
307
+ player: {
308
+ /**
309
+ * Handle player input for combat actions
310
+ *
311
+ * When a player presses the action key, create an attack hitbox
312
+ * that can damage AI enemies within range and knockback the event.
313
+ * Knockback force is based on the player's equipped weapon.
314
+ * Triggers attack animation and visual effects.
315
+ *
316
+ * @param player - The player performing the action
317
+ * @param input - Input data containing pressed keys
318
+ */
319
+ onInput(player, input) {
320
+ if (input.action == Control.Action) {
321
+ playActionBattleAnimation("attack", player, options.animations);
322
+ const playerX = player.x();
323
+ const playerY = player.y();
324
+ const hitboxConfig = DEFAULT_PLAYER_ATTACK_HITBOXES[player.getDirection()] || DEFAULT_PLAYER_ATTACK_HITBOXES.default;
325
+ const hitboxes = [{
326
+ x: playerX + hitboxConfig.offsetX,
327
+ y: playerY + hitboxConfig.offsetY,
328
+ width: hitboxConfig.width,
329
+ height: hitboxConfig.height
330
+ }];
331
+ player.getCurrentMap()?.createMovingHitbox(hitboxes, { speed: 3 }).subscribe({ next(hits) {
332
+ hits.forEach((hit) => {
333
+ if (hit instanceof RpgEvent) {
334
+ if (applyPlayerHitToEvent(player, hit)?.defeated) console.log(`Player ${player.id} defeated AI ${hit.id}`);
335
+ }
336
+ });
337
+ } });
338
+ }
339
+ },
340
+ onConnected(player) {
341
+ if (options.ui?.actionBar?.enabled && options.ui?.actionBar?.autoOpen) openActionBattleActionBar(player, options);
342
+ }
343
+ },
344
+ event: {
345
+ /**
346
+ * Handle player detection when entering AI vision
347
+ *
348
+ * Called when a player enters an AI event's vision range.
349
+ * The AI will start pursuing and attacking the player.
350
+ *
351
+ * @param event - The AI event
352
+ * @param player - The player entering vision
353
+ * @param shape - The vision shape
354
+ */
355
+ onDetectInShape(event, player, shape) {
356
+ event.battleAi?.onDetectInShape(player, shape);
357
+ },
358
+ /**
359
+ * Handle player leaving AI vision
360
+ *
361
+ * Called when a player leaves an AI event's vision range.
362
+ * The AI will stop pursuing the player.
363
+ *
364
+ * @param event - The AI event
365
+ * @param player - The player leaving vision
366
+ * @param shape - The vision shape
367
+ */
368
+ onDetectOutShape(event, player, shape) {
369
+ event.battleAi?.onDetectOutShape(player, shape);
370
+ }
371
+ }
372
+ });
64
373
  };
374
+ var server_default = createActionBattleServer();
375
+ //#endregion
376
+ export { ACTION_BATTLE_ACTION_BAR_GUI_ID, DEFAULT_PLAYER_ATTACK_HITBOXES, applyPlayerHitToEvent, createActionBattleServer, server_default as default, getPlayerWeaponKnockbackForce, openActionBattleActionBar, updateActionBattleActionBar };
package/dist/server.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { RpgEvent, RpgPlayer } from '@rpgjs/server';
1
+ import { RpgEvent, RpgPlayer, RpgServer } from '@rpgjs/server';
2
2
  import { HitResult, ApplyHitHooks } from './ai.server';
3
3
  import { ActionBattleOptions } from './types';
4
4
  export declare const ACTION_BATTLE_ACTION_BAR_GUI_ID = "action-battle-action-bar";
@@ -93,6 +93,6 @@ export declare function getPlayerWeaponKnockbackForce(player: RpgPlayer): number
93
93
  export declare function applyPlayerHitToEvent(player: RpgPlayer, target: RpgEvent, hooks?: ApplyHitHooks): HitResult | undefined;
94
94
  export declare const openActionBattleActionBar: (player: RpgPlayer, rawOptions?: ActionBattleOptions) => void;
95
95
  export declare const updateActionBattleActionBar: (player: RpgPlayer, rawOptions?: ActionBattleOptions) => void;
96
- export declare const createActionBattleServer: (rawOptions?: ActionBattleOptions) => any;
97
- declare const _default: any;
96
+ export declare const createActionBattleServer: (rawOptions?: ActionBattleOptions) => RpgServer;
97
+ declare const _default: RpgServer;
98
98
  export default _default;
@@ -9,9 +9,9 @@ export interface ActionBattleTargetingState {
9
9
  };
10
10
  aoeMask: string[] | string;
11
11
  }
12
- export declare const actionBattleUiOptions: any;
13
- export declare const actionBattleSkillOptions: any;
14
- export declare const actionBattleTargetingState: any;
12
+ export declare const actionBattleUiOptions: import('canvasengine').WritableObjectSignal<import('..').ActionBattleUiOptions>;
13
+ export declare const actionBattleSkillOptions: import('canvasengine').WritableObjectSignal<import('../types').ActionBattleSkillOptions>;
14
+ export declare const actionBattleTargetingState: import('canvasengine').WritableObjectSignal<ActionBattleTargetingState>;
15
15
  export declare const setActionBattleOptions: (options?: ActionBattleOptions) => void;
16
16
  export declare const startTargeting: (skill: ActionBattleActionBarSkill) => void;
17
17
  export declare const stopTargeting: () => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rpgjs/action-battle",
3
- "version": "5.0.0-beta.2",
3
+ "version": "5.0.0-beta.3",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "exports": {
@@ -23,10 +23,10 @@
23
23
  "description": "RPGJS is a framework for creating RPG/MMORPG games",
24
24
  "peerDependencies": {
25
25
  "@canvasengine/presets": "*",
26
- "@rpgjs/client": "5.0.0-beta.2",
27
- "@rpgjs/common": "5.0.0-beta.2",
28
- "@rpgjs/server": "5.0.0-beta.2",
29
- "@rpgjs/vite": "5.0.0-beta.2",
26
+ "@rpgjs/client": "5.0.0-beta.3",
27
+ "@rpgjs/common": "5.0.0-beta.3",
28
+ "@rpgjs/server": "5.0.0-beta.3",
29
+ "@rpgjs/vite": "5.0.0-beta.3",
30
30
  "canvasengine": "*"
31
31
  },
32
32
  "publishConfig": {