BlueGit

timfa questward

Files

questward / server / src / combat / service.js

service.js

service.js 11.4 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
181 if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) <= 1)
182 {
183 path.tiles = [];
184 return;
185 }
186
187 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
188 if (!goal)
189 {
190 path.tiles = [];
191 clearEngage(world.ecs, entityId);
192 return;
193 }
194
195 if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
196 { return; }
197
198 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
199 const tiles = findPath(
200 position.tileX,
201 position.tileY,
202 goal.x,
203 goal.y,
204 (x, y) => world.walkableFor(entityId, x, y),
205 bounds.minX,
206 bounds.minY,
207 bounds.maxX,
208 bounds.maxY
209 );
210 if (!tiles.length)
211 {
212 path.tiles = [];
213 clearEngage(world.ecs, entityId);
214 return;
215 }
216 path.tiles = tiles;
217 const movement = world.ecs.get(handle, Component.movement);
218 if (movement)
219 { movement.walkCarry = 0; }
220}
221
222function meleePathStale (world, entityId, position, targetPos, path, goal)
223{
224 const dest = path.tiles[path.tiles.length - 1];
225 if (dest.x !== goal.x || dest.y !== goal.y)
226 { return true; }
227 if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
228 { return true; }
229 const next = path.tiles[0];
230 if (!next)
231 { return true; }
232 const blockedByOther = !world.walkableFor(entityId, next.x, next.y)
233 && !(next.x === targetPos.tileX && next.y === targetPos.tileY);
234 return blockedByOther;
235}
236
237function bestAdjacentGoal (world, entityId, position, targetPos)
238{
239 const dirs = [
240 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
241 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
242 ];
243 let best = null;
244 let bestDist = Infinity;
245 for (const dir of dirs)
246 {
247 const x = targetPos.tileX + dir.x;
248 const y = targetPos.tileY + dir.y;
249 if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))
250 { continue; }
251 const dist = chebyshev(position.tileX, position.tileY, x, y);
252 if (dist < bestDist)
253 {
254 bestDist = dist;
255 best = { x, y };
256 }
257 }
258 return best;
259}
260
261export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
262{
263 const events = [];
264 const attackerHandle = world.ecs.handleOf(attackerId);
265 const targetHandle = world.ecs.handleOf(targetId);
266 if (attackerHandle == null || targetHandle == null)
267 { return events; }
268 const from = world.ecs.get(attackerHandle, Component.position);
269 const to = world.ecs.get(targetHandle, Component.position);
270 if (!from || !to)
271 { return events; }
272
273 events.push({
274 type: "combat-swing",
275 attackerId,
276 targetId,
277 tileX: to.tileX,
278 tileY: to.tileY,
279 fromTileX: from.tileX,
280 fromTileY: from.tileY
281 });
282
283 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
284 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
285 { engageTarget(world.ecs, targetId, attackerId, now); }
286
287 const skills = world.ecs.get(attackerHandle, Component.skills);
288 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
289 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
290 const attackerLevels = attackerCharacter
291 ? playerCombatLevels(world.ecs, attackerHandle, profile)
292 : {
293 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
294 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
295 agilityLevel: skillLevel(skills, SkillId.dexterity),
296 defenceLevel: skillLevel(skills, SkillId.defence)
297 };
298 const hitLevel = attackerLevels.hitLevel;
299 const damageLevel = attackerLevels.damageLevel;
300 const agilityLevel = defenderSkillLevel(
301 defenderSkills,
302 SkillId.dexterity,
303 defenderEquipment
304 );
305 const defenceLevel = defenderSkillLevel(
306 defenderSkills,
307 SkillId.defence,
308 defenderEquipment
309 );
310
311 const resolved = resolvePhysicalAttack({
312 hitSkillLevel: hitLevel,
313 agilitySkillLevel: agilityLevel,
314 damageSkillLevel: damageLevel,
315 defenceSkillLevel: defenceLevel,
316 baseDamage: profile.baseDamage ?? 1
317 });
318
319 if (resolved.outcome === "miss")
320 {
321 events.push({
322 type: "combat-miss",
323 attackerId,
324 targetId,
325 tileX: to.tileX,
326 tileY: to.tileY
327 });
328 return events;
329 }
330
331 if (resolved.outcome === "block")
332 {
333 events.push({
334 type: "combat-block",
335 attackerId,
336 targetId,
337 tileX: to.tileX,
338 tileY: to.tileY
339 });
340 return events;
341 }
342
343 const damage = resolved.damage;
344 const targetCharacter = world.ecs.get(targetHandle, Component.character);
345 if (targetCharacter)
346 { syncPlayerHealth(world.ecs, targetHandle); }
347 const health = world.ecs.get(targetHandle, Component.health);
348 if (health)
349 {
350 health.current = Math.max(0, (health.current | 0) - damage);
351 }
352 events.push({
353 type: "combat-hit",
354 attackerId,
355 targetId,
356 damage,
357 tileX: to.tileX,
358 tileY: to.tileY,
359 health: health?.current ?? 0,
360 maxHealth: health?.max ?? 0
361 });
362
363 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
364 if (healthXp)
365 {
366 events.push({
367 type: "skills-updated",
368 entityId: targetId,
369 characterId: healthXp.characterId,
370 skills: healthXp.view,
371 stored: healthXp.stored
372 });
373 if (health)
374 {
375 const hitEvent = events[events.length - 2];
376 if (hitEvent?.type === "combat-hit")
377 {
378 hitEvent.health = health.current;
379 hitEvent.maxHealth = health.max;
380 }
381 }
382 }
383
384 if (attackerCharacter)
385 {
386 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
387 if (xpAward)
388 {
389 events.push({
390 type: "skills-updated",
391 entityId: attackerId,
392 characterId: attackerCharacter.characterId,
393 skills: xpAward.view,
394 stored: xpAward.stored
395 });
396 }
397 }
398
399 if (health && health.current <= 0)
400 {
401 clearEngage(world.ecs, attackerId);
402 clearEngage(world.ecs, targetId);
403 const creature = world.ecs.get(targetHandle, Component.creature);
404 if (creature && !world.ecs.get(targetHandle, Component.character))
405 {
406 const view = world.destroyEntity?.(targetId) ?? null;
407 if (view)
408 {
409 events.push({
410 type: "entity-despawn",
411 entityId: targetId,
412 tileX: view.tileX,
413 tileY: view.tileY
414 });
415 }
416 }
417 }
418 return events;
419}