BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 10.5 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import {
5 mobCanFightType,
6 mobMeleeAttackProfile,
7 mobSkillLevels
8} from "../../../shared/definitions/mobCombat.js";
9import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
10import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
11import {
12 effectiveSkillLevel,
13 equipmentBonusesFromSlots
14} from "../../../shared/equipment/stats.js";
15import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
16import { chunkBoundsAround, findPath } from "../navigation/astar.js";
17import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
18
19export function chebyshev (ax, ay, bx, by)
20{
21 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
22}
23
24export function attackProfileOf (ecs, handle)
25{
26 const equipment = ecs.get(handle, Component.equipment);
27 const weapon = equipment?.slots?.weapon;
28 if (weapon?.itemId != null)
29 {
30 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
31 if (attack)
32 { return { ...attack }; }
33 }
34 const creature = ecs.get(handle, Component.creature);
35 if (creature)
36 {
37 const def = mobDefinition(creature.mobTypeId);
38 if (mobCanFightType(creature.mobTypeId))
39 { return mobMeleeAttackProfile(def); }
40 }
41 return { ...UNARMED_ATTACK };
42}
43
44export function ensureMobCombat (ecs, entityId)
45{
46 const handle = ecs.handleOf(entityId);
47 if (handle == null)
48 { return false; }
49 const creature = ecs.get(handle, Component.creature);
50 if (!creature || !mobCanFightType(creature.mobTypeId))
51 { return false; }
52 const def = mobDefinition(creature.mobTypeId);
53 if (!ecs.get(handle, Component.combat))
54 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
55 if (!ecs.get(handle, Component.skills))
56 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
57 return true;
58}
59
60function attackerSkillLevel (skills, profile, skillId)
61{
62 if (profile.mobAttackSkill != null)
63 { return profile.mobAttackSkill; }
64 return skillLevel(skills, skillId);
65}
66
67function defenderSkillLevel (skills, skillId, equipment = null)
68{
69 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
70 return effectiveSkillLevel(skills, skillId, bonuses);
71}
72
73function playerCombatLevels (ecs, handle, profile)
74{
75 const skills = ecs.get(handle, Component.skills);
76 const equipment = ecs.get(handle, Component.equipment);
77 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
78 return {
79 hitLevel: skillLevel(skills, profile.hitSkillId),
80 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
81 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
82 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
83 };
84}
85
86export function isUntargetable (ecs, handle)
87{
88 const creature = ecs.get(handle, Component.creature);
89 if (!creature)
90 { return false; }
91 return !!mobDefinition(creature.mobTypeId)?.untargetable;
92}
93
94export function engageTarget (ecs, attackerId, targetId, now = Date.now())
95{
96 const handle = ecs.handleOf(attackerId);
97 if (handle == null)
98 { return false; }
99 let combat = ecs.get(handle, Component.combat);
100 if (!combat)
101 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
102 const targetChanged = combat.targetEntityId !== targetId;
103 combat.targetEntityId = targetId;
104 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
105 if (targetChanged)
106 {
107 const path = ecs.get(handle, Component.path);
108 if (path)
109 { path.tiles = []; }
110 }
111 return true;
112}
113
114export function clearEngage (ecs, entityId)
115{
116 const handle = ecs.handleOf(entityId);
117 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
118 if (combat)
119 { combat.targetEntityId = null; }
120}
121
122export function stepCombat (world, now = Date.now())
123{
124 const events = [];
125 for (const entity of world.ecs.query(Component.combat, Component.position))
126 {
127 if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
128 { continue; }
129 const combat = entity.combat;
130 const targetId = combat.targetEntityId;
131 if (targetId == null)
132 { continue; }
133 const targetHandle = world.ecs.handleOf(targetId);
134 if (targetHandle == null)
135 {
136 combat.targetEntityId = null;
137 continue;
138 }
139 if (isUntargetable(world.ecs, targetHandle))
140 {
141 combat.targetEntityId = null;
142 continue;
143 }
144 const targetPos = world.ecs.get(targetHandle, Component.position);
145 const targetHealth = world.ecs.get(targetHandle, Component.health);
146 if (!targetPos || !targetHealth || targetHealth.current <= 0)
147 {
148 combat.targetEntityId = null;
149 continue;
150 }
151
152 const profile = attackProfileOf(world.ecs, entity.handle);
153 if (profile.mode !== "melee")
154 { continue; }
155
156 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
157 if (dist > 1)
158 {
159 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
160 continue;
161 }
162 if (dist !== 1)
163 { continue; }
164 if ((combat.nextSwingAt || 0) > now)
165 { continue; }
166
167 combat.nextSwingAt = now + (profile.cooldownMs || 800);
168 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
169 }
170 return events;
171}
172
173function queueMeleeApproach (world, entityId, handle, position, targetPos)
174{
175 if (world.frozen?.has?.(entityId))
176 { return; }
177 let path = world.ecs.get(handle, Component.path);
178 if (!path)
179 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
180 if (path.tiles?.length)
181 { return; }
182 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
183 if (!goal)
184 { return; }
185 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
186 path.tiles = findPath(
187 position.tileX,
188 position.tileY,
189 goal.x,
190 goal.y,
191 (x, y) => world.walkableFor(entityId, x, y),
192 bounds.minX,
193 bounds.minY,
194 bounds.maxX,
195 bounds.maxY
196 );
197 const movement = world.ecs.get(handle, Component.movement);
198 if (movement)
199 { movement.walkCarry = 0; }
200}
201
202function bestAdjacentGoal (world, entityId, position, targetPos)
203{
204 const dirs = [
205 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
206 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
207 ];
208 let best = null;
209 let bestDist = Infinity;
210 for (const dir of dirs)
211 {
212 const x = targetPos.tileX + dir.x;
213 const y = targetPos.tileY + dir.y;
214 if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))
215 { continue; }
216 const dist = chebyshev(position.tileX, position.tileY, x, y);
217 if (dist < bestDist)
218 {
219 bestDist = dist;
220 best = { x, y };
221 }
222 }
223 return best;
224}
225
226export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
227{
228 const events = [];
229 const attackerHandle = world.ecs.handleOf(attackerId);
230 const targetHandle = world.ecs.handleOf(targetId);
231 if (attackerHandle == null || targetHandle == null)
232 { return events; }
233 const from = world.ecs.get(attackerHandle, Component.position);
234 const to = world.ecs.get(targetHandle, Component.position);
235 if (!from || !to)
236 { return events; }
237
238 events.push({
239 type: "combat-swing",
240 attackerId,
241 targetId,
242 tileX: to.tileX,
243 tileY: to.tileY,
244 fromTileX: from.tileX,
245 fromTileY: from.tileY
246 });
247
248 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
249 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
250 { engageTarget(world.ecs, targetId, attackerId, now); }
251
252 const skills = world.ecs.get(attackerHandle, Component.skills);
253 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
254 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
255 const attackerLevels = attackerCharacter
256 ? playerCombatLevels(world.ecs, attackerHandle, profile)
257 : {
258 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
259 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
260 agilityLevel: skillLevel(skills, SkillId.dexterity),
261 defenceLevel: skillLevel(skills, SkillId.defence)
262 };
263 const hitLevel = attackerLevels.hitLevel;
264 const damageLevel = attackerLevels.damageLevel;
265 const agilityLevel = defenderSkillLevel(
266 defenderSkills,
267 SkillId.dexterity,
268 defenderEquipment
269 );
270 const defenceLevel = defenderSkillLevel(
271 defenderSkills,
272 SkillId.defence,
273 defenderEquipment
274 );
275
276 const resolved = resolvePhysicalAttack({
277 hitSkillLevel: hitLevel,
278 agilitySkillLevel: agilityLevel,
279 damageSkillLevel: damageLevel,
280 defenceSkillLevel: defenceLevel,
281 baseDamage: profile.baseDamage ?? 1
282 });
283
284 if (resolved.outcome === "miss")
285 {
286 events.push({
287 type: "combat-miss",
288 attackerId,
289 targetId,
290 tileX: to.tileX,
291 tileY: to.tileY
292 });
293 return events;
294 }
295
296 if (resolved.outcome === "block")
297 {
298 events.push({
299 type: "combat-block",
300 attackerId,
301 targetId,
302 tileX: to.tileX,
303 tileY: to.tileY
304 });
305 return events;
306 }
307
308 const damage = resolved.damage;
309 const targetCharacter = world.ecs.get(targetHandle, Component.character);
310 if (targetCharacter)
311 { syncPlayerHealth(world.ecs, targetHandle); }
312 const health = world.ecs.get(targetHandle, Component.health);
313 if (health)
314 {
315 health.current = Math.max(0, (health.current | 0) - damage);
316 }
317 events.push({
318 type: "combat-hit",
319 attackerId,
320 targetId,
321 damage,
322 tileX: to.tileX,
323 tileY: to.tileY,
324 health: health?.current ?? 0,
325 maxHealth: health?.max ?? 0
326 });
327
328 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
329 if (healthXp)
330 {
331 events.push({
332 type: "skills-updated",
333 entityId: targetId,
334 characterId: healthXp.characterId,
335 skills: healthXp.view,
336 stored: healthXp.stored
337 });
338 if (health)
339 {
340 const hitEvent = events[events.length - 2];
341 if (hitEvent?.type === "combat-hit")
342 {
343 hitEvent.health = health.current;
344 hitEvent.maxHealth = health.max;
345 }
346 }
347 }
348
349 if (attackerCharacter)
350 {
351 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
352 if (xpAward)
353 {
354 events.push({
355 type: "skills-updated",
356 entityId: attackerId,
357 characterId: attackerCharacter.characterId,
358 skills: xpAward.view,
359 stored: xpAward.stored
360 });
361 }
362 }
363
364 if (health && health.current <= 0)
365 {
366 clearEngage(world.ecs, attackerId);
367 clearEngage(world.ecs, targetId);
368 const creature = world.ecs.get(targetHandle, Component.creature);
369 if (creature && !world.ecs.get(targetHandle, Component.character))
370 {
371 const view = world.destroyEntity?.(targetId) ?? null;
372 if (view)
373 {
374 events.push({
375 type: "entity-despawn",
376 entityId: targetId,
377 tileX: view.tileX,
378 tileY: view.tileY
379 });
380 }
381 }
382 }
383 return events;
384}