BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 10.3 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 combat.targetEntityId = targetId;
103 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
104 return true;
105}
106
107export function clearEngage (ecs, entityId)
108{
109 const handle = ecs.handleOf(entityId);
110 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
111 if (combat)
112 { combat.targetEntityId = null; }
113}
114
115export function stepCombat (world, now = Date.now())
116{
117 const events = [];
118 for (const entity of world.ecs.query(Component.combat, Component.position))
119 {
120 const combat = entity.combat;
121 const targetId = combat.targetEntityId;
122 if (targetId == null)
123 { continue; }
124 const targetHandle = world.ecs.handleOf(targetId);
125 if (targetHandle == null)
126 {
127 combat.targetEntityId = null;
128 continue;
129 }
130 if (isUntargetable(world.ecs, targetHandle))
131 {
132 combat.targetEntityId = null;
133 continue;
134 }
135 const targetPos = world.ecs.get(targetHandle, Component.position);
136 const targetHealth = world.ecs.get(targetHandle, Component.health);
137 if (!targetPos || !targetHealth || targetHealth.current <= 0)
138 {
139 combat.targetEntityId = null;
140 continue;
141 }
142
143 const profile = attackProfileOf(world.ecs, entity.handle);
144 if (profile.mode !== "melee")
145 { continue; }
146
147 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
148 if (dist > 1)
149 {
150 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
151 continue;
152 }
153 if (dist !== 1)
154 { continue; }
155 if ((combat.nextSwingAt || 0) > now)
156 { continue; }
157
158 combat.nextSwingAt = now + (profile.cooldownMs || 800);
159 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
160 }
161 return events;
162}
163
164function queueMeleeApproach (world, entityId, handle, position, targetPos)
165{
166 if (world.frozen?.has?.(entityId))
167 { return; }
168 let path = world.ecs.get(handle, Component.path);
169 if (!path)
170 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
171 if (path.tiles?.length)
172 { return; }
173 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
174 if (!goal)
175 { return; }
176 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
177 path.tiles = findPath(
178 position.tileX,
179 position.tileY,
180 goal.x,
181 goal.y,
182 (x, y) => world.walkableFor(entityId, x, y),
183 bounds.minX,
184 bounds.minY,
185 bounds.maxX,
186 bounds.maxY
187 );
188 const movement = world.ecs.get(handle, Component.movement);
189 if (movement)
190 { movement.walkCarry = 0; }
191}
192
193function bestAdjacentGoal (world, entityId, position, targetPos)
194{
195 const dirs = [
196 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
197 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
198 ];
199 let best = null;
200 let bestDist = Infinity;
201 for (const dir of dirs)
202 {
203 const x = targetPos.tileX + dir.x;
204 const y = targetPos.tileY + dir.y;
205 if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))
206 { continue; }
207 const dist = chebyshev(position.tileX, position.tileY, x, y);
208 if (dist < bestDist)
209 {
210 bestDist = dist;
211 best = { x, y };
212 }
213 }
214 return best;
215}
216
217export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
218{
219 const events = [];
220 const attackerHandle = world.ecs.handleOf(attackerId);
221 const targetHandle = world.ecs.handleOf(targetId);
222 if (attackerHandle == null || targetHandle == null)
223 { return events; }
224 const from = world.ecs.get(attackerHandle, Component.position);
225 const to = world.ecs.get(targetHandle, Component.position);
226 if (!from || !to)
227 { return events; }
228
229 events.push({
230 type: "combat-swing",
231 attackerId,
232 targetId,
233 tileX: to.tileX,
234 tileY: to.tileY,
235 fromTileX: from.tileX,
236 fromTileY: from.tileY
237 });
238
239 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
240 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
241 { engageTarget(world.ecs, targetId, attackerId, now); }
242
243 const skills = world.ecs.get(attackerHandle, Component.skills);
244 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
245 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
246 const attackerLevels = attackerCharacter
247 ? playerCombatLevels(world.ecs, attackerHandle, profile)
248 : {
249 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
250 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
251 agilityLevel: skillLevel(skills, SkillId.dexterity),
252 defenceLevel: skillLevel(skills, SkillId.defence)
253 };
254 const hitLevel = attackerLevels.hitLevel;
255 const damageLevel = attackerLevels.damageLevel;
256 const agilityLevel = defenderSkillLevel(
257 defenderSkills,
258 SkillId.dexterity,
259 defenderEquipment
260 );
261 const defenceLevel = defenderSkillLevel(
262 defenderSkills,
263 SkillId.defence,
264 defenderEquipment
265 );
266
267 const resolved = resolvePhysicalAttack({
268 hitSkillLevel: hitLevel,
269 agilitySkillLevel: agilityLevel,
270 damageSkillLevel: damageLevel,
271 defenceSkillLevel: defenceLevel,
272 baseDamage: profile.baseDamage ?? 1
273 });
274
275 if (resolved.outcome === "miss")
276 {
277 events.push({
278 type: "combat-miss",
279 attackerId,
280 targetId,
281 tileX: to.tileX,
282 tileY: to.tileY
283 });
284 return events;
285 }
286
287 if (resolved.outcome === "block")
288 {
289 events.push({
290 type: "combat-block",
291 attackerId,
292 targetId,
293 tileX: to.tileX,
294 tileY: to.tileY
295 });
296 return events;
297 }
298
299 const damage = resolved.damage;
300 const targetCharacter = world.ecs.get(targetHandle, Component.character);
301 if (targetCharacter)
302 { syncPlayerHealth(world.ecs, targetHandle); }
303 const health = world.ecs.get(targetHandle, Component.health);
304 if (health)
305 {
306 health.current = Math.max(0, (health.current | 0) - damage);
307 }
308 events.push({
309 type: "combat-hit",
310 attackerId,
311 targetId,
312 damage,
313 tileX: to.tileX,
314 tileY: to.tileY,
315 health: health?.current ?? 0,
316 maxHealth: health?.max ?? 0
317 });
318
319 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
320 if (healthXp)
321 {
322 events.push({
323 type: "skills-updated",
324 entityId: targetId,
325 characterId: healthXp.characterId,
326 skills: healthXp.view,
327 stored: healthXp.stored
328 });
329 if (health)
330 {
331 const hitEvent = events[events.length - 2];
332 if (hitEvent?.type === "combat-hit")
333 {
334 hitEvent.health = health.current;
335 hitEvent.maxHealth = health.max;
336 }
337 }
338 }
339
340 if (attackerCharacter)
341 {
342 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
343 if (xpAward)
344 {
345 events.push({
346 type: "skills-updated",
347 entityId: attackerId,
348 characterId: attackerCharacter.characterId,
349 skills: xpAward.view,
350 stored: xpAward.stored
351 });
352 }
353 }
354
355 if (health && health.current <= 0)
356 {
357 clearEngage(world.ecs, attackerId);
358 clearEngage(world.ecs, targetId);
359 const creature = world.ecs.get(targetHandle, Component.creature);
360 if (creature && !world.ecs.get(targetHandle, Component.character))
361 {
362 const view = world.destroyEntity?.(targetId) ?? null;
363 if (view)
364 {
365 events.push({
366 type: "entity-despawn",
367 entityId: targetId,
368 tileX: view.tileX,
369 tileY: view.tileY
370 });
371 }
372 }
373 }
374 return events;
375}