BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

combat.test.js 63.3 KiB Download Raw
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mobComponents } from "../src/simulation/spawners.js";
4import { MobId } from "../../shared/definitions/mobs.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6import { WoodItemId } from "../../shared/definitions/woodItems.js";
7import { GemItemId } from "../../shared/definitions/gemItems.js";
8import { tierStatBonus, WoodTier } from "../../shared/definitions/materialTiers.js";
9import { BlockType, blockBlocksRangedAttacks } from "../../shared/definitions/tiles.js";
10import { Component } from "../src/ecs/components.js";
11import { tileKey } from "../src/world/coordinates.js";
12import { WorkerMessage } from "../src/simulation/protocol.js";
13import { tileToRegion } from "../src/world/coordinates.js";
14import { SkillId } from "../../shared/definitions/skills.js";
15import { SpellId } from "../../shared/definitions/spells.js";
16import { totalXpForLevel } from "../../shared/skills/progression.js";
17import { GAIT } from "../../shared/protocol/constants.js";
18import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight, queueMeleeApproach, markSeekCover, engageTarget, applyDamageAndKill, markFleeOnHit, stepCombat, chebyshev, COMBAT_CHASE_RUN_TILES, combatLeashLimit, spawnOriginDistance } from "../src/combat/service.js";
19import { combatDamageRollLevel } from "../../shared/combat/rolls.js";
20import { SKULL_KILL_BONUS } from "../../shared/combat/skull.js";
21import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
22import { withDamagingCombatRng, installDamagingCombatRng, installMissDodgeRng, installBlockRng } from "./helpers/combatRng.js";
23
24function workerOf (simulation, entityId)
25{
26 const record = simulation.entityRecord(entityId);
27 assert.ok(record, "entity must be remembered");
28 return simulation.workers[record.workerId];
29}
30
31function componentsOf (simulation, entityId)
32{
33 const worker = workerOf(simulation, entityId);
34 const handle = worker.world.ecs.handleOf(entityId);
35 assert.ok(handle != null);
36 return worker.world.ecs.componentsOf(handle);
37}
38
39function teleportEntity (worker, entityId, tileX, tileY)
40{
41 const world = worker.world;
42 const handle = world.ecs.handleOf(entityId);
43 const pos = world.ecs.get(handle, Component.position);
44 const fromKey = tileKey(pos.tileX, pos.tileY);
45 const fromSet = world.occupancy.get(fromKey);
46 if (fromSet)
47 {
48 fromSet.delete(entityId);
49 if (fromSet.size === 0)
50 { world.occupancy.delete(fromKey); }
51 }
52 pos.tileX = tileX;
53 pos.tileY = tileY;
54 const toKey = tileKey(tileX, tileY);
55 let toSet = world.occupancy.get(toKey);
56 if (!toSet)
57 {
58 toSet = new Set();
59 world.occupancy.set(toKey, toSet);
60 }
61 toSet.add(entityId);
62}
63
64function entityIsAlive (simulation, entityId)
65{
66 const record = simulation.entityRecord(entityId);
67 if (!record)
68 { return false; }
69 const worker = simulation.workers[record.workerId];
70 const handle = worker.world.ecs.handleOf(entityId);
71 if (handle == null)
72 { return false; }
73 const health = worker.world.ecs.get(handle, Component.health);
74 return (health?.current ?? 0) > 0;
75}
76
77function simulateAttackClick (harness, character, targetEntityId)
78{
79 harness.simulation.enqueue(1, {
80 type: "attack",
81 characterId: character.character_id,
82 targetEntityId
83 });
84}
85
86/** Run ticks until one combatant dies or the step budget is exhausted. */
87function runCombatUntilOutcome (harness, playerId, deerId, maxSteps = 600)
88{
89 let swings = 0;
90 for (let i = 0; i < maxSteps; i++)
91 {
92 harness.advance(50);
93 const events = harness.simulation.step().events;
94 swings += events.filter((event) => event.type === "combat-swing").length;
95 const playerAlive = entityIsAlive(harness.simulation, playerId);
96 const deerAlive = entityIsAlive(harness.simulation, deerId);
97 if (!playerAlive || !deerAlive)
98 { return { playerAlive, deerAlive, swings, steps: i + 1 }; }
99 }
100 return {
101 playerAlive: entityIsAlive(harness.simulation, playerId),
102 deerAlive: entityIsAlive(harness.simulation, deerId),
103 swings,
104 steps: maxSteps
105 };
106}
107
108function withDeterministicCombat (fn)
109{
110 withDamagingCombatRng(fn);
111}
112
113test("immortal deer auto-attacks until the player dies", () =>
114{
115 withDeterministicCombat(() =>
116 {
117 const harness = makeSimulation({ workerCount: 1 });
118 try
119 {
120 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
121 const playerId = harness.simulation.spawnCharacter(1, character);
122 const deerId = harness.simulation.spawnEntity(mobComponents({
123 tileX: 9,
124 tileY: 8,
125 mobTypeId: MobId.deer,
126 spawnerId: null
127 }));
128 const deer = componentsOf(harness.simulation, deerId);
129 deer.health.current = 1_000_000;
130 deer.health.max = 1_000_000;
131
132 simulateAttackClick(harness, character, deerId);
133 harness.simulation.step();
134
135 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
136 assert.ok(outcome.swings >= 2, `expected sustained auto-attack swings, got ${outcome.swings}`);
137 assert.equal(outcome.deerAlive, true, "immortal deer should survive");
138 assert.equal(outcome.playerAlive, false, "deer should kill the player via auto-attack");
139 assert.equal(
140 componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null,
141 null,
142 "deer should clear engage after the player dies"
143 );
144 }
145 finally
146 { harness.close(); }
147 });
148});
149
150test("immortal deer keeps auto-attacking after the player walks away", () =>
151{
152 withDeterministicCombat(() =>
153 {
154 const harness = makeSimulation({ workerCount: 1 });
155 try
156 {
157 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
158 const playerId = harness.simulation.spawnCharacter(1, character);
159 const deerId = harness.simulation.spawnEntity(mobComponents({
160 tileX: 9,
161 tileY: 8,
162 mobTypeId: MobId.deer,
163 spawnerId: null
164 }));
165 const deer = componentsOf(harness.simulation, deerId);
166 deer.health.current = 1_000_000;
167 deer.health.max = 1_000_000;
168
169 simulateAttackClick(harness, character, deerId);
170 harness.simulation.step();
171
172 // Let one exchange land, then cancel player engage by walking away (client moveTo).
173 for (let i = 0; i < 30; i++)
174 {
175 harness.advance(50);
176 const swings = harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
177 if (swings > 0)
178 { break; }
179 }
180 harness.simulation.enqueue(1, {
181 type: "move-to",
182 characterId: character.character_id,
183 tileX: 8,
184 tileY: 14
185 });
186 harness.simulation.step();
187 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
188 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
189
190 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
191 assert.ok(outcome.swings >= 1, `expected deer pursuit swings, got ${outcome.swings}`);
192 assert.equal(outcome.deerAlive, true);
193 assert.equal(outcome.playerAlive, false, "deer should chase and kill the player after walk-away");
194 }
195 finally
196 { harness.close(); }
197 });
198});
199
200test("cross-worker immortal deer auto-attacks until the player dies", () =>
201{
202 withDeterministicCombat(() =>
203 {
204 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
205 try
206 {
207 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
208 const playerId = harness.simulation.spawnCharacter(1, character);
209 const deerId = harness.simulation.spawnEntity(mobComponents({
210 tileX: 63,
211 tileY: 8,
212 mobTypeId: MobId.deer,
213 spawnerId: null
214 }));
215 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
216 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
217
218 const deerWorker = workerOf(harness.simulation, deerId);
219 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
220 const deerHealth = deerWorker.world.ecs.get(deerHandle, Component.health);
221 deerHealth.current = 1_000_000;
222 deerHealth.max = 1_000_000;
223
224 simulateAttackClick(harness, character, deerId);
225 const first = harness.simulation.step();
226 assert.equal(first.events.some((event) => event.type === "command-error"), false);
227
228 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
229 assert.ok(outcome.swings >= 2, `expected sustained cross-worker swings, got ${outcome.swings}`);
230 assert.equal(outcome.deerAlive, true);
231 assert.equal(outcome.playerAlive, false, "cross-worker deer should kill the player via auto-attack");
232 }
233 finally
234 { harness.close(); }
235 });
236});
237
238test("click attack from 5 tiles away ends with player or deer dead", () =>
239{
240 withDeterministicCombat(() =>
241 {
242 const harness = makeSimulation({ workerCount: 1 });
243 try
244 {
245 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
246 const playerId = harness.simulation.spawnCharacter(1, character);
247 const deerId = harness.simulation.spawnEntity(mobComponents({
248 tileX: 13,
249 tileY: 8,
250 mobTypeId: MobId.deer,
251 spawnerId: null
252 }));
253
254 simulateAttackClick(harness, character, deerId);
255 harness.simulation.step();
256
257 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
258 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
259 assert.ok(
260 !outcome.playerAlive || !outcome.deerAlive,
261 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
262 );
263 }
264 finally
265 { harness.close(); }
266 });
267});
268
269test("click attack while adjacent ends with player or deer dead", () =>
270{
271 withDeterministicCombat(() =>
272 {
273 const harness = makeSimulation({ workerCount: 1 });
274 try
275 {
276 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
277 const playerId = harness.simulation.spawnCharacter(1, character);
278 const deerId = harness.simulation.spawnEntity(mobComponents({
279 tileX: 9,
280 tileY: 8,
281 mobTypeId: MobId.deer,
282 spawnerId: null
283 }));
284
285 simulateAttackClick(harness, character, deerId);
286 harness.simulation.step();
287
288 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
289 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
290 assert.ok(
291 !outcome.playerAlive || !outcome.deerAlive,
292 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
293 );
294 }
295 finally
296 { harness.close(); }
297 });
298});
299
300test("cross-worker click attack from 5 tiles away ends with player or deer dead", () =>
301{
302 withDeterministicCombat(() =>
303 {
304 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
305 try
306 {
307 const character = makeCharacter(harness.stateDb, { tileX: 59, tileY: 8 });
308 const playerId = harness.simulation.spawnCharacter(1, character);
309 const deerId = harness.simulation.spawnEntity(mobComponents({
310 tileX: 64,
311 tileY: 8,
312 mobTypeId: MobId.deer,
313 spawnerId: null
314 }));
315 assert.equal(harness.simulation.entityRecord(playerId).workerId, 0);
316 assert.equal(harness.simulation.entityRecord(deerId).workerId, 1);
317
318 simulateAttackClick(harness, character, deerId);
319 const first = harness.simulation.step();
320 assert.equal(first.events.some((event) => event.type === "command-error"), false);
321
322 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
323 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
324 assert.ok(
325 !outcome.playerAlive || !outcome.deerAlive,
326 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
327 );
328 }
329 finally
330 { harness.close(); }
331 });
332});
333
334test("cross-worker adjacent click attack ends with player or deer dead", () =>
335{
336 withDeterministicCombat(() =>
337 {
338 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
339 try
340 {
341 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
342 const playerId = harness.simulation.spawnCharacter(1, character);
343 const deerId = harness.simulation.spawnEntity(mobComponents({
344 tileX: 63,
345 tileY: 8,
346 mobTypeId: MobId.deer,
347 spawnerId: null
348 }));
349 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
350 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
351
352 simulateAttackClick(harness, character, deerId);
353 const first = harness.simulation.step();
354 assert.equal(first.events.some((event) => event.type === "command-error"), false);
355
356 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
357 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
358 assert.ok(
359 !outcome.playerAlive || !outcome.deerAlive,
360 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
361 );
362 }
363 finally
364 { harness.close(); }
365 });
366});
367
368test("attack engages the attacker; target retaliates on first swing", () =>
369{
370 const harness = makeSimulation({ workerCount: 1 });
371 try
372 {
373 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
374 const playerId = harness.simulation.spawnCharacter(1, character);
375 // Deer are not aggressive — only retaliate after a real swing.
376 const deerId = harness.simulation.spawnEntity(mobComponents({
377 tileX: 12,
378 tileY: 8,
379 mobTypeId: MobId.deer,
380 spawnerId: null
381 }));
382
383 harness.simulation.enqueue(1, {
384 type: "attack",
385 characterId: character.character_id,
386 targetEntityId: deerId
387 });
388 harness.simulation.step();
389
390 assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, deerId);
391 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null, null);
392
393 let swung = false;
394 for (let i = 0; i < 80; i++)
395 {
396 harness.advance(50);
397 const events = harness.simulation.step().events;
398 if (events.some((event) => event.type === "combat-swing"))
399 {
400 swung = true;
401 break;
402 }
403 }
404 assert.ok(swung, "expected a melee swing once adjacent");
405 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
406 }
407 finally
408 { harness.close(); }
409});
410
411test("passive spawner mob takes hits but does not retaliate", () =>
412{
413 const harness = makeSimulation({ workerCount: 1 });
414 try
415 {
416 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
417 const playerId = harness.simulation.spawnCharacter(1, character);
418 const npcId = harness.simulation.spawnEntity(mobComponents({
419 tileX: 9,
420 tileY: 8,
421 mobTypeId: MobId.humanoid,
422 spawnerId: "passive-npc",
423 originTileX: 9,
424 originTileY: 8,
425 wanderRangeTiles: 1,
426 level: 1,
427 aggressive: false,
428 passive: true,
429 displayName: "Pacifist",
430 sex: "male"
431 }));
432
433 harness.simulation.enqueue(1, {
434 type: "attack",
435 characterId: character.character_id,
436 targetEntityId: npcId
437 });
438 harness.simulation.step();
439 assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, npcId);
440
441 let swung = false;
442 for (let i = 0; i < 80; i++)
443 {
444 harness.advance(50);
445 const events = harness.simulation.step().events;
446 if (events.some((event) => event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss"))
447 {
448 swung = true;
449 break;
450 }
451 }
452 assert.ok(swung, "expected a melee swing against the passive npc");
453 assert.equal(
454 componentsOf(harness.simulation, npcId).combat?.targetEntityId ?? null,
455 null,
456 "passive npc must not retaliate"
457 );
458 }
459 finally
460 { harness.close(); }
461});
462
463test("melee swing only resolves at Chebyshev distance 1", () =>
464{
465 const harness = makeSimulation({ workerCount: 1 });
466 try
467 {
468 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
469 const playerId = harness.simulation.spawnCharacter(1, character);
470 const bag = harness.simulation.bagOf(playerId);
471 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
472 assert.ok(stickSlot >= 0);
473 harness.simulation.enqueue(1, {
474 type: "equip-item",
475 characterId: character.character_id,
476 slotIndex: stickSlot
477 });
478 harness.simulation.step();
479 assert.equal(
480 harness.simulation.bagOf(playerId).equipment.slots[EQUIPMENT_SLOT.weapon]?.itemId,
481 ItemId.stick
482 );
483
484 const farRat = harness.simulation.spawnEntity(mobComponents({
485 tileX: 12,
486 tileY: 8,
487 mobTypeId: MobId.rat
488 }));
489 harness.simulation.enqueue(1, {
490 type: "attack",
491 characterId: character.character_id,
492 targetEntityId: farRat
493 });
494 const farEvents = harness.simulation.step().events;
495 assert.equal(farEvents.some((event) => event.type === "combat-swing"), false);
496
497 const nearRat = harness.simulation.spawnEntity(mobComponents({
498 tileX: 9,
499 tileY: 8,
500 mobTypeId: MobId.rat
501 }));
502 harness.simulation.enqueue(1, {
503 type: "attack",
504 characterId: character.character_id,
505 targetEntityId: nearRat
506 });
507 const nearEvents = harness.simulation.step().events;
508 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
509 assert.ok(nearEvents.some((event) =>
510 event.type === "combat-hit"
511 || event.type === "combat-miss"
512 || event.type === "combat-block"));
513 }
514 finally
515 { harness.close(); }
516});
517
518test("pigeons are untargetable free-flight and never get path tiles", () =>
519{
520 const harness = makeSimulation({ workerCount: 1 });
521 try
522 {
523 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
524 harness.simulation.spawnCharacter(1, character);
525 const pigeonId = harness.simulation.spawnEntity(mobComponents({
526 tileX: 10,
527 tileY: 8,
528 mobTypeId: MobId.pigeon
529 }));
530
531 const before = componentsOf(harness.simulation, pigeonId);
532 assert.equal(before.flight != null, true);
533 assert.equal(before.combat == null, true);
534 assert.deepEqual(before.path?.tiles ?? [], []);
535
536 harness.setNow(harness.now() + 500);
537 stepTimes(harness.simulation, 10);
538 const after = componentsOf(harness.simulation, pigeonId);
539 assert.deepEqual(after.path?.tiles ?? [], []);
540 assert.equal(after.flight != null, true);
541
542 harness.simulation.enqueue(1, {
543 type: "attack",
544 characterId: character.character_id,
545 targetEntityId: pigeonId
546 });
547 const result = harness.simulation.step();
548 assert.ok(result.events.some((event) => event.type === "command-error"));
549 assert.equal(componentsOf(harness.simulation, pigeonId).path?.tiles?.length ?? 0, 0);
550 }
551 finally
552 { harness.close(); }
553});
554
555test("deer retaliate when attacked", () =>
556{
557 const harness = makeSimulation({ workerCount: 1 });
558 try
559 {
560 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
561 const playerId = harness.simulation.spawnCharacter(1, character);
562 const deerId = harness.simulation.spawnEntity(mobComponents({
563 tileX: 9,
564 tileY: 8,
565 mobTypeId: MobId.deer,
566 spawnerId: null
567 }));
568
569 harness.simulation.enqueue(1, {
570 type: "attack",
571 characterId: character.character_id,
572 targetEntityId: deerId
573 });
574 const events = harness.simulation.step().events;
575 assert.ok(events.some((event) => event.type === "combat-swing"));
576
577 const deer = componentsOf(harness.simulation, deerId);
578 assert.equal(deer.combat?.targetEntityId, playerId);
579 assert.ok(deer.skills?.levels?.unarmed >= 1);
580 }
581 finally
582 { harness.close(); }
583});
584
585test("aggressive rats engage players within aggro range and LOS", () =>
586{
587 const harness = makeSimulation({ workerCount: 1 });
588 try
589 {
590 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
591 const playerId = harness.simulation.spawnCharacter(1, character);
592 const ratId = harness.simulation.spawnEntity(mobComponents({
593 tileX: 12,
594 tileY: 8,
595 mobTypeId: MobId.rat,
596 spawnerId: null
597 }));
598
599 harness.simulation.step();
600 assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);
601 }
602 finally
603 { harness.close(); }
604});
605
606test("aggressive creatures run when chasing farther than two tiles", () =>
607{
608 const harness = makeSimulation({ workerCount: 1 });
609 try
610 {
611 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
612 const playerId = harness.simulation.spawnCharacter(1, character);
613 const ratId = harness.simulation.spawnEntity(mobComponents({
614 tileX: 12,
615 tileY: 8,
616 mobTypeId: MobId.rat,
617 spawnerId: null
618 }));
619
620 harness.simulation.step();
621 assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);
622 assert.equal(componentsOf(harness.simulation, ratId).movement.gait, GAIT.run);
623 assert.equal(chebyshev(12, 8, 8, 8) > COMBAT_CHASE_RUN_TILES, true);
624 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
625
626 const worker = workerOf(harness.simulation, ratId);
627 teleportEntity(worker, ratId, 10, 8);
628 harness.simulation.step();
629 assert.equal(chebyshev(10, 8, 8, 8), COMBAT_CHASE_RUN_TILES);
630 assert.equal(componentsOf(harness.simulation, ratId).movement.gait, GAIT.walk);
631 }
632 finally
633 { harness.close(); }
634});
635
636test("aggressive mobs and town guards aggro each other", () =>
637{
638 const harness = makeSimulation({ workerCount: 1 });
639 try
640 {
641 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
642 harness.simulation.spawnCharacter(1, character);
643 const guardId = harness.simulation.spawnEntity(mobComponents({
644 tileX: 10,
645 tileY: 8,
646 mobTypeId: MobId.townGuard,
647 spawnerId: "0:0:guard",
648 originTileX: 10,
649 originTileY: 8,
650 wanderRangeTiles: 4,
651 level: 10
652 }));
653 const ratId = harness.simulation.spawnEntity(mobComponents({
654 tileX: 12,
655 tileY: 8,
656 mobTypeId: MobId.rat,
657 spawnerId: "0:0:rat",
658 originTileX: 12,
659 originTileY: 8,
660 wanderRangeTiles: 4,
661 aggressive: true
662 }));
663
664 harness.simulation.step();
665 const ratCombat = componentsOf(harness.simulation, ratId).combat?.targetEntityId;
666 const guardCombat = componentsOf(harness.simulation, guardId).combat?.targetEntityId;
667 assert.ok(
668 ratCombat === guardId || guardCombat === ratId,
669 `expected mutual aggro; rat→${ratCombat} guard→${guardCombat}`
670 );
671 }
672 finally
673 { harness.close(); }
674});
675
676test("town guards aggro players whose skull tint lerps toward red", () =>
677{
678 const harness = makeSimulation({ workerCount: 1 });
679 try
680 {
681 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
682 harness.stateDb.addKillCounter(character.character_id, SKULL_KILL_BONUS + 1, harness.now());
683 const playerId = harness.simulation.spawnCharacter(1, character);
684 assert.equal(componentsOf(harness.simulation, playerId).character?.skullValue, SKULL_KILL_BONUS + 1);
685
686 const guardId = harness.simulation.spawnEntity(mobComponents({
687 tileX: 10,
688 tileY: 8,
689 mobTypeId: MobId.townGuard,
690 spawnerId: "0:0:guard",
691 originTileX: 10,
692 originTileY: 8,
693 wanderRangeTiles: 8,
694 level: 10
695 }));
696
697 harness.simulation.step();
698 assert.equal(
699 componentsOf(harness.simulation, guardId).combat?.targetEntityId,
700 playerId
701 );
702 }
703 finally
704 { harness.close(); }
705});
706
707test("town guards ignore players at black-max skull (not yet red)", () =>
708{
709 const harness = makeSimulation({ workerCount: 1 });
710 try
711 {
712 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
713 harness.stateDb.setKillCounter(character.character_id, SKULL_KILL_BONUS, harness.now());
714 const playerId = harness.simulation.spawnCharacter(1, character);
715 assert.equal(componentsOf(harness.simulation, playerId).character?.skullValue, SKULL_KILL_BONUS);
716
717 const guardId = harness.simulation.spawnEntity(mobComponents({
718 tileX: 10,
719 tileY: 8,
720 mobTypeId: MobId.townGuard,
721 spawnerId: "0:0:guard",
722 originTileX: 10,
723 originTileY: 8,
724 wanderRangeTiles: 8,
725 level: 10
726 }));
727
728 harness.simulation.step();
729 assert.equal(componentsOf(harness.simulation, guardId).combat?.targetEntityId, null);
730 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, null);
731 }
732 finally
733 { harness.close(); }
734});
735
736test("town guards ignore players with white-only skull", () =>
737{
738 const harness = makeSimulation({ workerCount: 1 });
739 try
740 {
741 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
742 harness.stateDb.setKillCounter(character.character_id, 1, harness.now());
743 const playerId = harness.simulation.spawnCharacter(1, character);
744 assert.equal(componentsOf(harness.simulation, playerId).character?.skullValue, 1);
745
746 const guardId = harness.simulation.spawnEntity(mobComponents({
747 tileX: 10,
748 tileY: 8,
749 mobTypeId: MobId.townGuard,
750 spawnerId: "0:0:guard",
751 originTileX: 10,
752 originTileY: 8,
753 wanderRangeTiles: 8,
754 level: 10
755 }));
756
757 harness.simulation.step();
758 assert.equal(componentsOf(harness.simulation, guardId).combat?.targetEntityId, null);
759 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, null);
760 }
761 finally
762 { harness.close(); }
763});
764
765test("spawner mobs far from home path chunk-step toward the origin", () =>
766{
767 const harness = makeSimulation({ workerCount: 1, maxChunkX: 5 });
768 try
769 {
770 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
771 const playerId = harness.simulation.spawnCharacter(1, character);
772 const deerId = harness.simulation.spawnEntity(mobComponents({
773 tileX: 10,
774 tileY: 8,
775 mobTypeId: MobId.deer,
776 spawnerId: "0:0:deer",
777 originTileX: 8,
778 originTileY: 8,
779 wanderRangeTiles: 2
780 }));
781 const worker = workerOf(harness.simulation, playerId);
782 teleportEntity(worker, deerId, 40, 8);
783 const handle = worker.world.ecs.handleOf(deerId);
784 worker.world.ecs.get(handle, Component.path).tiles = [];
785
786 let movedCloser = false;
787 for (let i = 0; i < 40; i++)
788 {
789 harness.advance(50);
790 harness.simulation.step();
791 const pos = worker.world.ecs.get(handle, Component.position);
792 const path = worker.world.ecs.get(handle, Component.path)?.tiles ?? [];
793 const fromX = pos.tileX;
794 const fromY = pos.tileY;
795 const fromDist = Math.max(Math.abs(fromX - 8), Math.abs(fromY - 8));
796 if (path.length)
797 {
798 const dest = path[path.length - 1];
799 const destDist = Math.max(Math.abs(dest.x - 8), Math.abs(dest.y - 8));
800 if (destDist < fromDist)
801 {
802 movedCloser = true;
803 break;
804 }
805 }
806 if (fromDist < 32)
807 {
808 movedCloser = true;
809 break;
810 }
811 }
812 assert.ok(movedCloser, "expected a return path closer to the spawner");
813 }
814 finally
815 { harness.close(); }
816});
817
818test("players retaliate when a mob swings at them", () =>
819{
820 const harness = makeSimulation({ workerCount: 1 });
821 try
822 {
823 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
824 const playerId = harness.simulation.spawnCharacter(1, character);
825 const ratId = harness.simulation.spawnEntity(mobComponents({
826 tileX: 9,
827 tileY: 8,
828 mobTypeId: MobId.rat,
829 spawnerId: null
830 }));
831
832 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
833
834 let swung = false;
835 for (let i = 0; i < 80; i++)
836 {
837 harness.advance(50);
838 const events = harness.simulation.step().events;
839 if (events.some((event) =>
840 event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
841 ))
842 {
843 swung = true;
844 break;
845 }
846 }
847 assert.ok(swung, "expected the rat to swing at the player");
848 assert.equal(
849 componentsOf(harness.simulation, playerId).combat?.targetEntityId,
850 ratId,
851 "player should auto-retaliate after the mob swing"
852 );
853 }
854 finally
855 { harness.close(); }
856});
857
858test("staff with favorite attack spell retaliates by auto-casting it", () =>
859{
860 const harness = makeSimulation({ workerCount: 1 });
861 try
862 {
863 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
864 const playerId = harness.simulation.spawnCharacter(1, character);
865 const ratId = harness.simulation.spawnEntity(mobComponents({
866 tileX: 9,
867 tileY: 8,
868 mobTypeId: MobId.rat,
869 spawnerId: null
870 }));
871 const worker = workerOf(harness.simulation, playerId);
872 const handle = worker.world.ecs.handleOf(playerId);
873 const equipment = worker.world.ecs.get(handle, Component.equipment);
874 equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
875 const spells = worker.world.ecs.get(handle, Component.spells);
876 spells.known.push(SpellId.manaBullet);
877 spells.favorites = [SpellId.light, SpellId.manaBullet];
878 spells.autoCast = false;
879
880 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
881 resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
882
883 const casting = worker.world.ecs.get(handle, Component.spellcasting);
884 assert.equal(casting.repeatSpellId, SpellId.manaBullet);
885 assert.equal(casting.repeatTargetEntityId, ratId);
886 assert.equal(
887 componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
888 null,
889 "staff spell retaliate should not melee-engage"
890 );
891 }
892 finally
893 { harness.close(); }
894});
895
896test("staff without favorite attack spell retaliates with melee", () =>
897{
898 const harness = makeSimulation({ workerCount: 1 });
899 try
900 {
901 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
902 const playerId = harness.simulation.spawnCharacter(1, character);
903 const ratId = harness.simulation.spawnEntity(mobComponents({
904 tileX: 9,
905 tileY: 8,
906 mobTypeId: MobId.rat,
907 spawnerId: null
908 }));
909 const worker = workerOf(harness.simulation, playerId);
910 const handle = worker.world.ecs.handleOf(playerId);
911 const equipment = worker.world.ecs.get(handle, Component.equipment);
912 equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
913 const spells = worker.world.ecs.get(handle, Component.spells);
914 spells.favorites = [SpellId.light];
915
916 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
917 resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
918
919 assert.equal(
920 componentsOf(harness.simulation, playerId).combat?.targetEntityId,
921 ratId,
922 "staff without attack favorites should melee-retaliate"
923 );
924 assert.equal(
925 worker.world.ecs.get(handle, Component.spellcasting)?.repeatSpellId ?? null,
926 null
927 );
928 }
929 finally
930 { harness.close(); }
931});
932
933test("staff click-attack arms favorite spell instead of melee approach", () =>
934{
935 const harness = makeSimulation({ workerCount: 1 });
936 try
937 {
938 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
939 const playerId = harness.simulation.spawnCharacter(1, character);
940 // Beyond spell range so auto-cast queues a stand-in-range path (not melee adjacency).
941 const ratId = harness.simulation.spawnEntity(mobComponents({
942 tileX: 28,
943 tileY: 8,
944 mobTypeId: MobId.rat,
945 spawnerId: null
946 }));
947 const worker = workerOf(harness.simulation, playerId);
948 const handle = worker.world.ecs.handleOf(playerId);
949 const equipment = worker.world.ecs.get(handle, Component.equipment);
950 equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
951 const spells = worker.world.ecs.get(handle, Component.spells);
952 spells.known.push(SpellId.manaBullet);
953 spells.favorites = [SpellId.manaBullet];
954 spells.autoCast = false;
955
956 harness.simulation.enqueue(1, {
957 type: "attack",
958 characterId: character.character_id,
959 targetEntityId: ratId
960 });
961 harness.simulation.step();
962
963 const casting = worker.world.ecs.get(handle, Component.spellcasting);
964 assert.equal(casting.repeatSpellId, SpellId.manaBullet);
965 assert.equal(casting.repeatTargetEntityId, ratId);
966 assert.equal(
967 componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
968 null,
969 "staff click-attack should not melee-engage"
970 );
971
972 const path = componentsOf(harness.simulation, playerId).path;
973 const tiles = path?.tiles ?? [];
974 assert.ok(tiles.length > 0, "should approach into spell range");
975 const last = tiles[tiles.length - 1];
976 const standDist = chebyshev(last.x, last.y, 28, 8);
977 assert.ok(
978 standDist > 1,
979 `spell approach should stop outside melee adjacency, got dist=${standDist}`
980 );
981 }
982 finally
983 { harness.close(); }
984});
985
986test("staff cast-spell-entity approaches spell range and keeps auto-repeat without autoCast", () =>
987{
988 const harness = makeSimulation({ workerCount: 1 });
989 try
990 {
991 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
992 const playerId = harness.simulation.spawnCharacter(1, character);
993 const ratId = harness.simulation.spawnEntity(mobComponents({
994 tileX: 28,
995 tileY: 8,
996 mobTypeId: MobId.rat,
997 spawnerId: null
998 }));
999 const worker = workerOf(harness.simulation, playerId);
1000 const handle = worker.world.ecs.handleOf(playerId);
1001 const equipment = worker.world.ecs.get(handle, Component.equipment);
1002 equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
1003 const spells = worker.world.ecs.get(handle, Component.spells);
1004 spells.known.push(SpellId.manaBullet);
1005 spells.favorites = [SpellId.manaBullet];
1006 spells.autoCast = false;
1007 const skills = worker.world.ecs.get(handle, Component.skills);
1008 skills.xp[SkillId.magic] = totalXpForLevel(20);
1009
1010 harness.simulation.enqueue(1, {
1011 type: "cast-spell-entity",
1012 characterId: character.character_id,
1013 spellId: SpellId.manaBullet,
1014 targetEntityId: ratId
1015 });
1016 harness.simulation.step();
1017
1018 const casting = worker.world.ecs.get(handle, Component.spellcasting);
1019 assert.equal(casting.repeatSpellId, SpellId.manaBullet);
1020 assert.equal(casting.repeatTargetEntityId, ratId);
1021 assert.equal(casting.pendingCast?.spellId, SpellId.manaBullet);
1022 assert.equal(
1023 componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
1024 null
1025 );
1026 const path = componentsOf(harness.simulation, playerId).path;
1027 const tiles = path?.tiles ?? [];
1028 assert.ok(tiles.length > 0, "should approach into spell range");
1029 const last = tiles[tiles.length - 1];
1030 assert.ok(chebyshev(last.x, last.y, 28, 8) > 1);
1031 }
1032 finally
1033 { harness.close(); }
1034});
1035
1036test("players do not auto-retaliate while walking from a click order", () =>
1037{
1038 const harness = makeSimulation({ workerCount: 1 });
1039 try
1040 {
1041 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1042 const playerId = harness.simulation.spawnCharacter(1, character);
1043 const ratId = harness.simulation.spawnEntity(mobComponents({
1044 tileX: 9,
1045 tileY: 8,
1046 mobTypeId: MobId.rat,
1047 spawnerId: null
1048 }));
1049
1050 harness.simulation.enqueue(1, {
1051 type: "move-to",
1052 characterId: character.character_id,
1053 tileX: 8,
1054 tileY: 14
1055 });
1056 harness.simulation.step();
1057 const path = componentsOf(harness.simulation, playerId).path;
1058 assert.ok((path?.tiles?.length ?? 0) > 0, "player should be pathing");
1059
1060 let swung = false;
1061 for (let i = 0; i < 80; i++)
1062 {
1063 harness.advance(50);
1064 const events = harness.simulation.step().events;
1065 if (events.some((event) =>
1066 event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
1067 ))
1068 {
1069 swung = true;
1070 break;
1071 }
1072 }
1073 assert.ok(swung, "expected the rat to swing at the walking player");
1074 assert.equal(
1075 componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
1076 null,
1077 "walking player should not auto-retaliate"
1078 );
1079 assert.ok(
1080 (componentsOf(harness.simulation, playerId).path?.tiles?.length ?? 0) > 0
1081 || componentsOf(harness.simulation, playerId).position.tileY !== 8,
1082 "walk order should continue after the hit"
1083 );
1084 }
1085 finally
1086 { harness.close(); }
1087});
1088
1089test("players do not auto-retaliate while gathering", () =>
1090{
1091 const harness = makeSimulation({ workerCount: 1 });
1092 const restore = installDamagingCombatRng();
1093 try
1094 {
1095 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1096 const playerId = harness.simulation.spawnCharacter(1, character);
1097 const ratId = harness.simulation.spawnEntity(mobComponents({
1098 tileX: 9,
1099 tileY: 8,
1100 mobTypeId: MobId.rat,
1101 spawnerId: null
1102 }));
1103 const worker = workerOf(harness.simulation, playerId);
1104 const handle = worker.world.ecs.handleOf(playerId);
1105 worker.world.ecs.add(handle, Component.gather, {
1106 kind: "mining",
1107 tileX: 7,
1108 tileY: 8,
1109 materialId: "copper",
1110 durationMs: 60_000,
1111 startedAt: Date.now(),
1112 finishesAt: Date.now() + 60_000,
1113 nextSwingAt: Date.now() + 60_000
1114 });
1115 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1116 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1117 assert.ok(events.some((event) => event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block"));
1118 assert.equal(
1119 componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
1120 null,
1121 "gathering player should not auto-retaliate"
1122 );
1123 assert.ok(
1124 worker.world.ecs.has(handle, Component.gather),
1125 "gather session should survive the hit"
1126 );
1127 }
1128 finally
1129 {
1130 restore();
1131 harness.close();
1132 }
1133});
1134
1135test("aggressive rats do not aggro through walls or beyond range", () =>
1136{
1137 const harness = makeSimulation({ workerCount: 1 });
1138 try
1139 {
1140 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1141 const playerId = harness.simulation.spawnCharacter(1, character);
1142 const blockedRat = harness.simulation.spawnEntity(mobComponents({
1143 tileX: 12,
1144 tileY: 8,
1145 mobTypeId: MobId.rat,
1146 spawnerId: null
1147 }));
1148 const worker = workerOf(harness.simulation, playerId);
1149 const world = worker.world;
1150 const data = world.chunkData(0, 0);
1151 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
1152 for (let y = 6; y <= 10; y++)
1153 { data.blocks[y * 16 + 10] = wall; }
1154
1155 harness.simulation.step();
1156 assert.equal(
1157 componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null,
1158 null,
1159 "wall blocks LOS aggro"
1160 );
1161
1162 const farRat = harness.simulation.spawnEntity(mobComponents({
1163 tileX: 20,
1164 tileY: 8,
1165 mobTypeId: MobId.rat,
1166 spawnerId: null
1167 }));
1168 harness.simulation.step();
1169 assert.equal(
1170 componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null,
1171 null,
1172 "out of range does not aggro"
1173 );
1174 }
1175 finally
1176 { harness.close(); }
1177});
1178
1179test("crafting stations and tables do not block ranged or spell line of sight", () =>
1180{
1181 assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
1182 assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
1183 assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
1184 assert.equal(blockBlocksRangedAttacks(null), false);
1185
1186 const harness = makeSimulation({ workerCount: 1 });
1187 try
1188 {
1189 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1190 const playerId = harness.simulation.spawnCharacter(1, character);
1191 const worker = workerOf(harness.simulation, playerId);
1192 const data = worker.world.chunkData(0, 0);
1193 const blockIndex = (localY, localX) => localY * 16 + localX;
1194
1195 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
1196 assert.equal(
1197 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
1198 true,
1199 "furnace between caster and target should not block"
1200 );
1201
1202 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
1203 assert.equal(
1204 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
1205 true,
1206 "table between caster and target should not block"
1207 );
1208
1209 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
1210 assert.equal(
1211 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
1212 false,
1213 "stone wall should still block"
1214 );
1215 }
1216 finally
1217 { harness.close(); }
1218});
1219
1220test("attacker keeps pursuing and can swing after the target moves", () =>
1221{
1222 const harness = makeSimulation({ workerCount: 1 });
1223 try
1224 {
1225 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1226 const playerId = harness.simulation.spawnCharacter(1, character);
1227 const ratId = harness.simulation.spawnEntity(mobComponents({
1228 tileX: 12,
1229 tileY: 8,
1230 mobTypeId: MobId.rat,
1231 spawnerId: null
1232 }));
1233
1234 harness.simulation.enqueue(1, {
1235 type: "attack",
1236 characterId: character.character_id,
1237 targetEntityId: ratId
1238 });
1239 harness.simulation.step();
1240
1241 const worker = workerOf(harness.simulation, playerId);
1242 stepTimes(harness.simulation, 4);
1243 teleportEntity(worker, ratId, 12, 10);
1244
1245 let swings = 0;
1246 for (let i = 0; i < 120; i++)
1247 {
1248 const events = harness.simulation.step().events;
1249 swings += events.filter((event) => event.type === "combat-swing").length;
1250 if (swings > 0)
1251 { break; }
1252 }
1253
1254 assert.ok(swings >= 1);
1255 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, ratId);
1256 }
1257 finally
1258 { harness.close(); }
1259});
1260
1261test("combatants keep auto-attacking while adjacent", () =>
1262{
1263 const harness = makeSimulation({ workerCount: 1 });
1264 try
1265 {
1266 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1267 const playerId = harness.simulation.spawnCharacter(1, character);
1268 const deerId = harness.simulation.spawnEntity(mobComponents({
1269 tileX: 9,
1270 tileY: 8,
1271 mobTypeId: MobId.deer,
1272 spawnerId: null
1273 }));
1274
1275 harness.simulation.enqueue(1, {
1276 type: "attack",
1277 characterId: character.character_id,
1278 targetEntityId: deerId
1279 });
1280 harness.simulation.step();
1281
1282 let swings = 0;
1283 for (let i = 0; i < 50; i++)
1284 {
1285 harness.advance(50);
1286 const events = harness.simulation.step().events;
1287 swings += events.filter((event) => event.type === "combat-swing").length;
1288 const player = componentsOf(harness.simulation, playerId);
1289 const deer = componentsOf(harness.simulation, deerId);
1290 if (swings >= 4
1291 && player.combat?.targetEntityId === deerId
1292 && deer.combat?.targetEntityId === playerId
1293 && (player.health?.current ?? 0) > 0)
1294 { break; }
1295 }
1296
1297 assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
1298 const player = componentsOf(harness.simulation, playerId);
1299 const deer = componentsOf(harness.simulation, deerId);
1300 assert.ok((player.health?.current ?? 0) > 0, "player should still be alive during sustained combat");
1301 assert.equal(player.combat?.targetEntityId, deerId);
1302 assert.equal(deer.combat?.targetEntityId, playerId);
1303 }
1304 finally
1305 { harness.close(); }
1306});
1307
1308test("cross-worker adjacent combat keeps engaging and swinging", () =>
1309{
1310 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
1311 try
1312 {
1313 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
1314 const playerId = harness.simulation.spawnCharacter(1, character);
1315 const deerId = harness.simulation.spawnEntity(mobComponents({
1316 tileX: 63,
1317 tileY: 8,
1318 mobTypeId: MobId.deer,
1319 spawnerId: null
1320 }));
1321 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
1322 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
1323
1324 harness.simulation.enqueue(1, {
1325 type: "attack",
1326 characterId: character.character_id,
1327 targetEntityId: deerId
1328 });
1329 const first = harness.simulation.step();
1330 assert.equal(first.events.some((event) => event.type === "command-error"), false);
1331
1332 const random = Math.random;
1333 Math.random = () => 0;
1334 try
1335 {
1336 let swings = 0;
1337 for (let i = 0; i < 40; i++)
1338 {
1339 harness.advance(50);
1340 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
1341 if (swings >= 4)
1342 { break; }
1343 }
1344
1345 assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
1346 const deerWorker = harness.simulation.workers[0];
1347 const playerWorker = harness.simulation.workers[1];
1348 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
1349 const playerHandle = playerWorker.world.ecs.handleOf(playerId);
1350 const deerCombat = deerWorker.world.ecs.get(deerHandle, Component.combat);
1351 const playerCombat = playerWorker.world.ecs.get(playerHandle, Component.combat);
1352 const playerHealth = playerWorker.world.ecs.get(playerHandle, Component.health);
1353 assert.ok((playerHealth?.current ?? 0) > 0, "player should survive sustained cross-worker combat");
1354 assert.equal(deerCombat?.targetEntityId, playerId);
1355 assert.equal(playerCombat?.targetEntityId, deerId);
1356 }
1357 finally
1358 { Math.random = random; }
1359 }
1360 finally
1361 { harness.close(); }
1362});
1363
1364test("cancel attack stops the player but the mob keeps pursuing", () =>
1365{
1366 const harness = makeSimulation({ workerCount: 1 });
1367 try
1368 {
1369 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1370 const playerId = harness.simulation.spawnCharacter(1, character);
1371 const ratId = harness.simulation.spawnEntity(mobComponents({
1372 tileX: 9,
1373 tileY: 8,
1374 mobTypeId: MobId.rat,
1375 spawnerId: null
1376 }));
1377
1378 harness.simulation.enqueue(1, {
1379 type: "attack",
1380 characterId: character.character_id,
1381 targetEntityId: ratId
1382 });
1383 harness.simulation.step();
1384
1385 harness.simulation.enqueue(1, {
1386 type: "cancel-attack",
1387 characterId: character.character_id
1388 });
1389 harness.simulation.step();
1390
1391 const player = componentsOf(harness.simulation, playerId);
1392 const rat = componentsOf(harness.simulation, ratId);
1393 assert.equal(player.combat?.targetEntityId, null);
1394 assert.equal(rat.combat?.targetEntityId, playerId);
1395 }
1396 finally
1397 { harness.close(); }
1398});
1399
1400test("player combat and skills components are present on spawn", () =>
1401{
1402 const harness = makeSimulation({ workerCount: 1 });
1403 try
1404 {
1405 const character = makeCharacter(harness.stateDb);
1406 const playerId = harness.simulation.spawnCharacter(1, character);
1407 const comps = componentsOf(harness.simulation, playerId);
1408 assert.ok(comps.combat);
1409 assert.equal(comps.skills?.xp?.clubfighting, 0);
1410 assert.ok(comps.health);
1411 }
1412 finally
1413 { harness.close(); }
1414});
1415
1416test("mobs heal to full when their region unloads", () =>
1417{
1418 const harness = makeSimulation({ workerCount: 1 });
1419 try
1420 {
1421 const ratId = harness.simulation.spawnEntity(mobComponents({
1422 tileX: 8,
1423 tileY: 8,
1424 mobTypeId: MobId.rat
1425 }));
1426 const worker = workerOf(harness.simulation, ratId);
1427 const handle = worker.world.ecs.handleOf(ratId);
1428 worker.world.ecs.get(handle, Component.health).current = 2;
1429 const result = worker.call({
1430 type: WorkerMessage.dropRegion,
1431 regionX: tileToRegion(8),
1432 regionY: tileToRegion(8)
1433 });
1434 const record = result.dropped.find((entry) => entry.entityId === ratId);
1435 assert.ok(record);
1436 assert.equal(
1437 record.payload.components.health.current,
1438 record.payload.components.health.max
1439 );
1440 }
1441 finally
1442 { harness.close(); }
1443});
1444
1445test("taking damage awards Health XP equal to damage dealt", () =>
1446{
1447 const harness = makeSimulation({ workerCount: 1 });
1448 const restore = installDamagingCombatRng();
1449 try
1450 {
1451 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1452 const playerId = harness.simulation.spawnCharacter(1, character);
1453 const ratId = harness.simulation.spawnEntity(mobComponents({
1454 mobTypeId: MobId.rat,
1455 tileX: 9,
1456 tileY: 8
1457 }));
1458 const worker = harness.simulation.workers[0];
1459 const playerHandle = worker.world.ecs.handleOf(playerId);
1460 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
1461 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1462 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1463 const hit = events.find((event) => event.type === "combat-hit");
1464 assert.ok(hit);
1465 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1466 assert.ok(updated);
1467 assert.equal(updated.stored[SkillId.health] - before, hit.damage);
1468 }
1469 finally
1470 {
1471 restore();
1472 harness.close();
1473 }
1474});
1475
1476test("lethal damage awards no Health XP", () =>
1477{
1478 const harness = makeSimulation({ workerCount: 1 });
1479 const restore = installDamagingCombatRng();
1480 try
1481 {
1482 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1483 const playerId = harness.simulation.spawnCharacter(1, character);
1484 const ratId = harness.simulation.spawnEntity(mobComponents({
1485 mobTypeId: MobId.rat,
1486 tileX: 9,
1487 tileY: 8
1488 }));
1489 const worker = harness.simulation.workers[0];
1490 const playerHandle = worker.world.ecs.handleOf(playerId);
1491 const health = worker.world.ecs.get(playerHandle, Component.health);
1492 health.current = 1;
1493 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
1494 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1495 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1496 const hit = events.find((event) => event.type === "combat-hit");
1497 assert.ok(hit);
1498 assert.ok(hit.damage >= 1);
1499 assert.equal(hit.health, 0);
1500 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1501 assert.equal(updated, undefined);
1502 assert.equal(worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health], before);
1503 }
1504 finally
1505 {
1506 restore();
1507 harness.close();
1508 }
1509});
1510
1511test("dodging a hit awards Agility XP equal to avoided damage", () =>
1512{
1513 const harness = makeSimulation({ workerCount: 1 });
1514 const restore = installMissDodgeRng(1);
1515 try
1516 {
1517 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1518 const playerId = harness.simulation.spawnCharacter(1, character);
1519 const ratId = harness.simulation.spawnEntity(mobComponents({
1520 mobTypeId: MobId.rat,
1521 tileX: 9,
1522 tileY: 8
1523 }));
1524 const worker = harness.simulation.workers[0];
1525 const playerHandle = worker.world.ecs.handleOf(playerId);
1526 const skills = worker.world.ecs.get(playerHandle, Component.skills);
1527 skills.xp[SkillId.agility] = totalXpForLevel(10);
1528 const before = skills.xp[SkillId.agility] | 0;
1529 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1530 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1531 assert.ok(events.find((event) => event.type === "combat-miss"));
1532 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1533 assert.ok(updated);
1534 assert.equal(updated.stored[SkillId.agility] - before, 1);
1535 }
1536 finally
1537 {
1538 restore();
1539 harness.close();
1540 }
1541});
1542
1543test("blocking a hit awards Defence XP equal to avoided damage", () =>
1544{
1545 const harness = makeSimulation({ workerCount: 1 });
1546 const restore = installBlockRng(1);
1547 try
1548 {
1549 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1550 const playerId = harness.simulation.spawnCharacter(1, character);
1551 const ratId = harness.simulation.spawnEntity(mobComponents({
1552 mobTypeId: MobId.rat,
1553 tileX: 9,
1554 tileY: 8
1555 }));
1556 const worker = harness.simulation.workers[0];
1557 const playerHandle = worker.world.ecs.handleOf(playerId);
1558 const skills = worker.world.ecs.get(playerHandle, Component.skills);
1559 skills.xp[SkillId.defence] = totalXpForLevel(10);
1560 const before = skills.xp[SkillId.defence] | 0;
1561 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1562 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1563 assert.ok(events.find((event) => event.type === "combat-block"));
1564 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1565 assert.ok(updated);
1566 assert.equal(updated.stored[SkillId.defence] - before, 1);
1567 }
1568 finally
1569 {
1570 restore();
1571 harness.close();
1572 }
1573});
1574
1575test("stacked combatants against the same target spread to different tiles", () =>
1576{
1577 const harness = makeSimulation({ workerCount: 1 });
1578 try
1579 {
1580 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1581 const playerId = harness.simulation.spawnCharacter(1, character);
1582 const rat1 = harness.simulation.spawnEntity(mobComponents({
1583 tileX: 9,
1584 tileY: 8,
1585 mobTypeId: MobId.rat,
1586 spawnerId: null
1587 }));
1588 const rat2 = harness.simulation.spawnEntity(mobComponents({
1589 tileX: 9,
1590 tileY: 7,
1591 mobTypeId: MobId.rat,
1592 spawnerId: null
1593 }));
1594 const worker = workerOf(harness.simulation, playerId);
1595 const handle = worker.world.ecs.handleOf(playerId);
1596 const playerHealth = worker.world.ecs.get(handle, Component.health);
1597 playerHealth.max = 500;
1598 playerHealth.current = 500;
1599 engageTarget(worker.world.ecs, rat1, playerId);
1600 engageTarget(worker.world.ecs, rat2, playerId);
1601 assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
1602 assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
1603 teleportEntity(worker, rat2, 9, 8);
1604
1605 for (let i = 0; i < 200; i++)
1606 {
1607 harness.advance(50);
1608 harness.simulation.step();
1609 }
1610
1611 const pos1 = componentsOf(harness.simulation, rat1).position;
1612 const pos2 = componentsOf(harness.simulation, rat2).position;
1613 assert.notEqual(
1614 `${pos1.tileX},${pos1.tileY}`,
1615 `${pos2.tileX},${pos2.tileY}`,
1616 "expected stacked rats to spread apart"
1617 );
1618 }
1619 finally
1620 { harness.close(); }
1621});
1622
1623test("approaching combatants pick different adjacent goals", () =>
1624{
1625 const harness = makeSimulation({ workerCount: 1 });
1626 try
1627 {
1628 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1629 const playerId = harness.simulation.spawnCharacter(1, character);
1630 const rat1 = harness.simulation.spawnEntity(mobComponents({
1631 tileX: 6,
1632 tileY: 8,
1633 mobTypeId: MobId.rat,
1634 spawnerId: null
1635 }));
1636 const rat2 = harness.simulation.spawnEntity(mobComponents({
1637 tileX: 6,
1638 tileY: 7,
1639 mobTypeId: MobId.rat,
1640 spawnerId: null
1641 }));
1642 const worker = workerOf(harness.simulation, playerId);
1643 teleportEntity(worker, rat2, 6, 8);
1644
1645 for (let i = 0; i < 120; i++)
1646 {
1647 harness.advance(50);
1648 harness.simulation.step();
1649 }
1650
1651 const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
1652 const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
1653 const goal1 = path1[path1.length - 1];
1654 const goal2 = path2[path2.length - 1];
1655 if (goal1 && goal2)
1656 {
1657 assert.notEqual(
1658 `${goal1.x},${goal1.y}`,
1659 `${goal2.x},${goal2.y}`,
1660 "expected different approach goals"
1661 );
1662 }
1663
1664 const pos1 = componentsOf(harness.simulation, rat1).position;
1665 const pos2 = componentsOf(harness.simulation, rat2).position;
1666 assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
1667 }
1668 finally
1669 { harness.close(); }
1670});
1671
1672test("humanoid attackers add equipment bonuses on top of spawner level", () =>
1673{
1674 const harness = makeSimulation({ workerCount: 1 });
1675 const random = Math.random;
1676 /** Max every skill roll so damage equals effective damage skill. */
1677 Math.random = () => 0.999999;
1678 try
1679 {
1680 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1681 const playerId = harness.simulation.spawnCharacter(1, character);
1682 const player = componentsOf(harness.simulation, playerId);
1683 player.skills.xp[SkillId.agility] = 0;
1684 player.skills.xp[SkillId.defence] = 0;
1685
1686 const level = 5;
1687 const npcId = harness.simulation.spawnEntity(mobComponents({
1688 tileX: 9,
1689 tileY: 8,
1690 mobTypeId: MobId.humanoid,
1691 level,
1692 displayName: "Guard",
1693 sex: "male",
1694 equipment: {
1695 weapon: WoodItemId.oakQuarterstaff
1696 }
1697 }));
1698 const worker = workerOf(harness.simulation, npcId);
1699 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(npcId));
1700 assert.equal(profile.mobAttackSkill, level);
1701 assert.equal(profile.damageSkillId, SkillId.strength);
1702
1703 const events = resolveMeleeSwing(worker.world, npcId, playerId, profile, Date.now());
1704 const hit = events.find((event) => event.type === "combat-hit");
1705 assert.ok(hit, "expected a hit");
1706 assert.equal(hit.damage, combatDamageRollLevel(level + tierStatBonus(WoodTier.oak)));
1707 }
1708 finally
1709 {
1710 Math.random = random;
1711 harness.close();
1712 }
1713});
1714
1715test("staff melees like a quarterstaff and awards clubs XP", () =>
1716{
1717 const harness = makeSimulation({ workerCount: 1 });
1718 const random = Math.random;
1719 Math.random = () => 0.999999;
1720 try
1721 {
1722 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1723 const playerId = harness.simulation.spawnCharacter(1, character);
1724 const deerId = harness.simulation.spawnEntity(mobComponents({
1725 tileX: 9,
1726 tileY: 8,
1727 mobTypeId: MobId.deer
1728 }));
1729 const worker = workerOf(harness.simulation, playerId);
1730 const handle = worker.world.ecs.handleOf(playerId);
1731 const equipment = worker.world.ecs.get(handle, Component.equipment);
1732 equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
1733 const skills = worker.world.ecs.get(handle, Component.skills);
1734 skills.xp[SkillId.clubfighting] = totalXpForLevel(10);
1735 skills.xp[SkillId.magic] = totalXpForLevel(10);
1736 const clubsBefore = skills.xp[SkillId.clubfighting];
1737 const magicBefore = skills.xp[SkillId.magic];
1738
1739 const profile = attackProfileOf(worker.world.ecs, handle);
1740 assert.equal(profile.mode, "melee");
1741 assert.equal(profile.hitSkillId, SkillId.clubfighting);
1742 assert.equal(profile.damageSkillId, SkillId.strength);
1743
1744 const events = resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
1745 const hit = events.find((event) => event.type === "combat-hit");
1746 assert.ok(hit, "staff should land a melee hit");
1747 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1748 assert.ok(updated);
1749 assert.ok(updated.stored[SkillId.clubfighting] > clubsBefore, "melee staff awards clubs XP");
1750 assert.equal(updated.stored[SkillId.magic], magicBefore, "melee staff does not award magic XP");
1751 }
1752 finally
1753 {
1754 Math.random = random;
1755 harness.close();
1756 }
1757});
1758
1759test("spell damage marks seekCover on a melee mob", () =>
1760{
1761 const harness = makeSimulation({ workerCount: 1 });
1762 try
1763 {
1764 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1765 const playerId = harness.simulation.spawnCharacter(1, character);
1766 const deerId = harness.simulation.spawnEntity(mobComponents({
1767 tileX: 12,
1768 tileY: 8,
1769 mobTypeId: MobId.deer,
1770 spawnerId: null
1771 }));
1772 const worker = workerOf(harness.simulation, playerId);
1773 applyDamageAndKill(worker.world, playerId, deerId, 1, Date.now());
1774 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1775 assert.equal(componentsOf(harness.simulation, deerId).combat?.seekCover, true);
1776 }
1777 finally
1778 { harness.close(); }
1779});
1780
1781test("melee hit does not mark seekCover on a retaliating mob", () =>
1782{
1783 const random = Math.random;
1784 Math.random = () => 0;
1785 const harness = makeSimulation({ workerCount: 1 });
1786 try
1787 {
1788 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1789 const playerId = harness.simulation.spawnCharacter(1, character);
1790 const deerId = harness.simulation.spawnEntity(mobComponents({
1791 tileX: 9,
1792 tileY: 8,
1793 mobTypeId: MobId.deer,
1794 spawnerId: null
1795 }));
1796 const worker = workerOf(harness.simulation, playerId);
1797 const handle = worker.world.ecs.handleOf(playerId);
1798 const bag = harness.simulation.bagOf(playerId);
1799 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
1800 if (stickSlot >= 0)
1801 {
1802 harness.simulation.enqueue(1, {
1803 type: "equip-item",
1804 characterId: character.character_id,
1805 slotIndex: stickSlot
1806 });
1807 harness.simulation.step();
1808 }
1809 const profile = attackProfileOf(worker.world.ecs, handle);
1810 assert.equal(profile.mode, "melee");
1811 resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
1812 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1813 assert.equal(!!componentsOf(harness.simulation, deerId).combat?.seekCover, false);
1814 }
1815 finally
1816 {
1817 Math.random = random;
1818 harness.close();
1819 }
1820});
1821
1822test("seekCover mob flees to a no-LOS tile when melee approach is impossible", () =>
1823{
1824 const harness = makeSimulation({ workerCount: 1 });
1825 try
1826 {
1827 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1828 const playerId = harness.simulation.spawnCharacter(1, character);
1829 const deerId = harness.simulation.spawnEntity(mobComponents({
1830 tileX: 14,
1831 tileY: 8,
1832 mobTypeId: MobId.deer,
1833 spawnerId: null
1834 }));
1835 const worker = workerOf(harness.simulation, playerId);
1836 const world = worker.world;
1837 const data = world.chunkData(0, 0);
1838 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
1839 const furnace = { typeId: BlockType.furnace, state: null, config: null };
1840 // Impassable stations around the player (do not block LOS) so no melee stand tile exists.
1841 for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]])
1842 { data.blocks[(8 + dy) * 16 + (8 + dx)] = furnace; }
1843 // Cover wall east of the approach.
1844 for (let y = 6; y <= 10; y++)
1845 { data.blocks[y * 16 + 12] = wall; }
1846
1847 assert.equal(hasCombatLineOfSight(world, 8, 8, 14, 8), false, "wall should block LOS east of the wall");
1848
1849 const deerHandle = world.ecs.handleOf(deerId);
1850 engageTarget(world.ecs, deerId, playerId);
1851 markSeekCover(world.ecs, deerId);
1852 const playerPos = world.ecs.get(world.ecs.handleOf(playerId), Component.position);
1853 teleportEntity(worker, deerId, 11, 8);
1854 assert.equal(hasCombatLineOfSight(world, 8, 8, 11, 8), true);
1855 queueMeleeApproach(world, deerId, deerHandle, world.ecs.get(deerHandle, Component.position), playerPos);
1856 const path = world.ecs.get(deerHandle, Component.path)?.tiles ?? [];
1857 assert.ok(path.length > 0, "expected a flee path into cover");
1858 const dest = path[path.length - 1];
1859 assert.equal(
1860 hasCombatLineOfSight(world, playerPos.tileX, playerPos.tileY, dest.x, dest.y),
1861 false,
1862 "flee destination must be out of player LOS"
1863 );
1864 }
1865 finally
1866 { harness.close(); }
1867});
1868
1869test("fairy flees to 2 tiles from hit source, then stops until hit again", () =>
1870{
1871 const harness = makeSimulation({ workerCount: 1 });
1872 try
1873 {
1874 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1875 const playerId = harness.simulation.spawnCharacter(1, character);
1876 const fairyId = harness.simulation.spawnEntity(mobComponents({
1877 tileX: 9,
1878 tileY: 8,
1879 mobTypeId: MobId.fairy,
1880 spawnerId: null
1881 }));
1882 const worker = workerOf(harness.simulation, fairyId);
1883 const world = worker.world;
1884 const fairyHandle = world.ecs.handleOf(fairyId);
1885
1886 applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
1887 const combat = world.ecs.get(fairyHandle, Component.combat);
1888 assert.equal(combat?.fleeFrom?.tileX, 8);
1889 assert.equal(combat?.fleeFrom?.tileY, 8);
1890 assert.equal(combat?.fleeFrom?.minDist, 2);
1891 assert.equal(combat?.targetEntityId, playerId);
1892
1893 stepCombat(world, Date.now());
1894 const path = world.ecs.get(fairyHandle, Component.path)?.tiles ?? [];
1895 assert.ok(path.length > 0, "fairy should path away while fleeing");
1896 const dest = path[path.length - 1];
1897 assert.ok(
1898 chebyshev(dest.x, dest.y, 8, 8) >= 2,
1899 `flee dest should be ≥2 from hit source, got ${dest.x},${dest.y}`
1900 );
1901
1902 teleportEntity(worker, fairyId, dest.x, dest.y);
1903 world.ecs.get(fairyHandle, Component.path).tiles = [];
1904 stepCombat(world, Date.now());
1905 assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom, null);
1906
1907 stepCombat(world, Date.now() + 5000);
1908 assert.equal(
1909 world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
1910 null,
1911 "no flee until hit again"
1912 );
1913
1914 teleportEntity(worker, fairyId, 9, 8);
1915 applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
1916 assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom?.minDist, 2);
1917
1918 teleportEntity(worker, fairyId, 12, 8);
1919 markFleeOnHit(world, fairyId, playerId);
1920 assert.equal(
1921 world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
1922 null,
1923 "already ≥2 tiles away does not start a flee"
1924 );
1925 }
1926 finally
1927 { harness.close(); }
1928});
1929
1930test("combat leash limit is max of 3× wander and wander + combat range", () =>
1931{
1932 assert.equal(combatLeashLimit(4), 16);
1933 assert.equal(combatLeashLimit(0), 12);
1934 assert.equal(combatLeashLimit(8), 24);
1935 assert.equal(spawnOriginDistance({ tileX: 8, tileY: 8 }, { originTileX: 8, originTileY: 12 }), 4);
1936});
1937
1938test("spawner mobs break combat beyond 3× wander range and leash home", () =>
1939{
1940 withDamagingCombatRng(() =>
1941 {
1942 const harness = makeSimulation({ workerCount: 1 });
1943 try
1944 {
1945 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1946 const playerId = harness.simulation.spawnCharacter(1, character);
1947 const ratId = harness.simulation.spawnEntity(mobComponents({
1948 tileX: 10,
1949 tileY: 8,
1950 mobTypeId: MobId.rat,
1951 spawnerId: "leash-rat",
1952 originTileX: 10,
1953 originTileY: 8,
1954 wanderRangeTiles: 2,
1955 aggressive: true
1956 }));
1957 harness.simulation.step();
1958
1959 const worker = workerOf(harness.simulation, ratId);
1960 const world = worker.world;
1961 const handle = world.ecs.handleOf(ratId);
1962 engageTarget(world.ecs, ratId, playerId, Date.now());
1963 assert.equal(world.ecs.get(handle, Component.combat)?.targetEntityId, playerId);
1964
1965 // Euclidean distance 15 > max(3×2, 2+12)=14 → break leash.
1966 teleportEntity(worker, ratId, 25, 8);
1967 stepCombat(world, Date.now());
1968 const combat = world.ecs.get(handle, Component.combat);
1969 assert.equal(combat?.targetEntityId, null);
1970 assert.equal(combat?.leashing, true);
1971
1972 stepTimes(harness.simulation, 5);
1973 const path = world.ecs.get(handle, Component.path);
1974 assert.ok(
1975 (path?.tiles?.length ?? 0) > 0 || (() =>
1976 {
1977 const pos = world.ecs.get(handle, Component.position);
1978 return Math.max(Math.abs(pos.tileX - 10), Math.abs(pos.tileY - 8)) <= 2;
1979 })(),
1980 "leashing mob should path toward wander home"
1981 );
1982 }
1983 finally
1984 { harness.close(); }
1985 });
1986});