BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

combat.test.js 46.9 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 { totalXpForLevel } from "../../shared/skills/progression.js";
16import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight, queueMeleeApproach, markSeekCover, engageTarget, applyDamageAndKill, markFleeOnHit, stepCombat, chebyshev } from "../src/combat/service.js";
17import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
18
19function workerOf (simulation, entityId)
20{
21 const record = simulation.entityRecord(entityId);
22 assert.ok(record, "entity must be remembered");
23 return simulation.workers[record.workerId];
24}
25
26function componentsOf (simulation, entityId)
27{
28 const worker = workerOf(simulation, entityId);
29 const handle = worker.world.ecs.handleOf(entityId);
30 assert.ok(handle != null);
31 return worker.world.ecs.componentsOf(handle);
32}
33
34function teleportEntity (worker, entityId, tileX, tileY)
35{
36 const world = worker.world;
37 const handle = world.ecs.handleOf(entityId);
38 const pos = world.ecs.get(handle, Component.position);
39 const fromKey = tileKey(pos.tileX, pos.tileY);
40 const fromSet = world.occupancy.get(fromKey);
41 if (fromSet)
42 {
43 fromSet.delete(entityId);
44 if (fromSet.size === 0)
45 { world.occupancy.delete(fromKey); }
46 }
47 pos.tileX = tileX;
48 pos.tileY = tileY;
49 const toKey = tileKey(tileX, tileY);
50 let toSet = world.occupancy.get(toKey);
51 if (!toSet)
52 {
53 toSet = new Set();
54 world.occupancy.set(toKey, toSet);
55 }
56 toSet.add(entityId);
57}
58
59function entityIsAlive (simulation, entityId)
60{
61 const record = simulation.entityRecord(entityId);
62 if (!record)
63 { return false; }
64 const worker = simulation.workers[record.workerId];
65 const handle = worker.world.ecs.handleOf(entityId);
66 if (handle == null)
67 { return false; }
68 const health = worker.world.ecs.get(handle, Component.health);
69 return (health?.current ?? 0) > 0;
70}
71
72function simulateAttackClick (harness, character, targetEntityId)
73{
74 harness.simulation.enqueue(1, {
75 type: "attack",
76 characterId: character.character_id,
77 targetEntityId
78 });
79}
80
81/** Run ticks until one combatant dies or the step budget is exhausted. */
82function runCombatUntilOutcome (harness, playerId, deerId, maxSteps = 600)
83{
84 let swings = 0;
85 for (let i = 0; i < maxSteps; i++)
86 {
87 harness.advance(50);
88 const events = harness.simulation.step().events;
89 swings += events.filter((event) => event.type === "combat-swing").length;
90 const playerAlive = entityIsAlive(harness.simulation, playerId);
91 const deerAlive = entityIsAlive(harness.simulation, deerId);
92 if (!playerAlive || !deerAlive)
93 { return { playerAlive, deerAlive, swings, steps: i + 1 }; }
94 }
95 return {
96 playerAlive: entityIsAlive(harness.simulation, playerId),
97 deerAlive: entityIsAlive(harness.simulation, deerId),
98 swings,
99 steps: maxSteps
100 };
101}
102
103function withDeterministicCombat (fn)
104{
105 const random = Math.random;
106 Math.random = () => 0;
107 try
108 { fn(); }
109 finally
110 { Math.random = random; }
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("melee swing only resolves at Chebyshev distance 1", () =>
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 bag = harness.simulation.bagOf(playerId);
419 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
420 assert.ok(stickSlot >= 0);
421 harness.simulation.enqueue(1, {
422 type: "equip-item",
423 characterId: character.character_id,
424 slotIndex: stickSlot
425 });
426 harness.simulation.step();
427 assert.equal(
428 harness.simulation.bagOf(playerId).equipment.slots[EQUIPMENT_SLOT.weapon]?.itemId,
429 ItemId.stick
430 );
431
432 const farRat = harness.simulation.spawnEntity(mobComponents({
433 tileX: 12,
434 tileY: 8,
435 mobTypeId: MobId.rat
436 }));
437 harness.simulation.enqueue(1, {
438 type: "attack",
439 characterId: character.character_id,
440 targetEntityId: farRat
441 });
442 const farEvents = harness.simulation.step().events;
443 assert.equal(farEvents.some((event) => event.type === "combat-swing"), false);
444
445 const nearRat = harness.simulation.spawnEntity(mobComponents({
446 tileX: 9,
447 tileY: 8,
448 mobTypeId: MobId.rat
449 }));
450 harness.simulation.enqueue(1, {
451 type: "attack",
452 characterId: character.character_id,
453 targetEntityId: nearRat
454 });
455 const nearEvents = harness.simulation.step().events;
456 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
457 assert.ok(nearEvents.some((event) =>
458 event.type === "combat-hit"
459 || event.type === "combat-miss"
460 || event.type === "combat-block"));
461 }
462 finally
463 { harness.close(); }
464});
465
466test("pigeons are untargetable free-flight and never get path tiles", () =>
467{
468 const harness = makeSimulation({ workerCount: 1 });
469 try
470 {
471 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
472 harness.simulation.spawnCharacter(1, character);
473 const pigeonId = harness.simulation.spawnEntity(mobComponents({
474 tileX: 10,
475 tileY: 8,
476 mobTypeId: MobId.pigeon
477 }));
478
479 const before = componentsOf(harness.simulation, pigeonId);
480 assert.equal(before.flight != null, true);
481 assert.equal(before.combat == null, true);
482 assert.deepEqual(before.path?.tiles ?? [], []);
483
484 harness.setNow(harness.now() + 500);
485 stepTimes(harness.simulation, 10);
486 const after = componentsOf(harness.simulation, pigeonId);
487 assert.deepEqual(after.path?.tiles ?? [], []);
488 assert.equal(after.flight != null, true);
489
490 harness.simulation.enqueue(1, {
491 type: "attack",
492 characterId: character.character_id,
493 targetEntityId: pigeonId
494 });
495 const result = harness.simulation.step();
496 assert.ok(result.events.some((event) => event.type === "command-error"));
497 assert.equal(componentsOf(harness.simulation, pigeonId).path?.tiles?.length ?? 0, 0);
498 }
499 finally
500 { harness.close(); }
501});
502
503test("deer retaliate when attacked", () =>
504{
505 const harness = makeSimulation({ workerCount: 1 });
506 try
507 {
508 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
509 const playerId = harness.simulation.spawnCharacter(1, character);
510 const deerId = harness.simulation.spawnEntity(mobComponents({
511 tileX: 9,
512 tileY: 8,
513 mobTypeId: MobId.deer,
514 spawnerId: null
515 }));
516
517 harness.simulation.enqueue(1, {
518 type: "attack",
519 characterId: character.character_id,
520 targetEntityId: deerId
521 });
522 const events = harness.simulation.step().events;
523 assert.ok(events.some((event) => event.type === "combat-swing"));
524
525 const deer = componentsOf(harness.simulation, deerId);
526 assert.equal(deer.combat?.targetEntityId, playerId);
527 assert.ok(deer.skills?.levels?.unarmed >= 1);
528 }
529 finally
530 { harness.close(); }
531});
532
533test("aggressive rats engage players within aggro range and LOS", () =>
534{
535 const harness = makeSimulation({ workerCount: 1 });
536 try
537 {
538 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
539 const playerId = harness.simulation.spawnCharacter(1, character);
540 const ratId = harness.simulation.spawnEntity(mobComponents({
541 tileX: 12,
542 tileY: 8,
543 mobTypeId: MobId.rat,
544 spawnerId: null
545 }));
546
547 harness.simulation.step();
548 assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);
549 }
550 finally
551 { harness.close(); }
552});
553
554test("aggressive mobs and town guards aggro each other", () =>
555{
556 const harness = makeSimulation({ workerCount: 1 });
557 try
558 {
559 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
560 harness.simulation.spawnCharacter(1, character);
561 const guardId = harness.simulation.spawnEntity(mobComponents({
562 tileX: 10,
563 tileY: 8,
564 mobTypeId: MobId.townGuard,
565 spawnerId: "0:0:guard",
566 originTileX: 10,
567 originTileY: 8,
568 wanderRangeTiles: 4,
569 level: 10
570 }));
571 const ratId = harness.simulation.spawnEntity(mobComponents({
572 tileX: 12,
573 tileY: 8,
574 mobTypeId: MobId.rat,
575 spawnerId: "0:0:rat",
576 originTileX: 12,
577 originTileY: 8,
578 wanderRangeTiles: 4,
579 aggressive: true
580 }));
581
582 harness.simulation.step();
583 const ratCombat = componentsOf(harness.simulation, ratId).combat?.targetEntityId;
584 const guardCombat = componentsOf(harness.simulation, guardId).combat?.targetEntityId;
585 assert.ok(
586 ratCombat === guardId || guardCombat === ratId,
587 `expected mutual aggro; rat→${ratCombat} guard→${guardCombat}`
588 );
589 }
590 finally
591 { harness.close(); }
592});
593
594test("spawner mobs far from home path chunk-step toward the origin", () =>
595{
596 const harness = makeSimulation({ workerCount: 1, maxChunkX: 5 });
597 try
598 {
599 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
600 const playerId = harness.simulation.spawnCharacter(1, character);
601 const deerId = harness.simulation.spawnEntity(mobComponents({
602 tileX: 10,
603 tileY: 8,
604 mobTypeId: MobId.deer,
605 spawnerId: "0:0:deer",
606 originTileX: 8,
607 originTileY: 8,
608 wanderRangeTiles: 2
609 }));
610 const worker = workerOf(harness.simulation, playerId);
611 teleportEntity(worker, deerId, 40, 8);
612 const handle = worker.world.ecs.handleOf(deerId);
613 worker.world.ecs.get(handle, Component.path).tiles = [];
614
615 let movedCloser = false;
616 for (let i = 0; i < 40; i++)
617 {
618 harness.advance(50);
619 harness.simulation.step();
620 const pos = worker.world.ecs.get(handle, Component.position);
621 const path = worker.world.ecs.get(handle, Component.path)?.tiles ?? [];
622 const fromX = pos.tileX;
623 const fromY = pos.tileY;
624 const fromDist = Math.max(Math.abs(fromX - 8), Math.abs(fromY - 8));
625 if (path.length)
626 {
627 const dest = path[path.length - 1];
628 const destDist = Math.max(Math.abs(dest.x - 8), Math.abs(dest.y - 8));
629 if (destDist < fromDist)
630 {
631 movedCloser = true;
632 break;
633 }
634 }
635 if (fromDist < 32)
636 {
637 movedCloser = true;
638 break;
639 }
640 }
641 assert.ok(movedCloser, "expected a return path closer to the spawner");
642 }
643 finally
644 { harness.close(); }
645});
646
647test("players retaliate when a mob swings at them", () =>
648{
649 const harness = makeSimulation({ workerCount: 1 });
650 try
651 {
652 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
653 const playerId = harness.simulation.spawnCharacter(1, character);
654 const ratId = harness.simulation.spawnEntity(mobComponents({
655 tileX: 9,
656 tileY: 8,
657 mobTypeId: MobId.rat,
658 spawnerId: null
659 }));
660
661 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
662
663 let swung = false;
664 for (let i = 0; i < 80; i++)
665 {
666 harness.advance(50);
667 const events = harness.simulation.step().events;
668 if (events.some((event) =>
669 event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
670 ))
671 {
672 swung = true;
673 break;
674 }
675 }
676 assert.ok(swung, "expected the rat to swing at the player");
677 assert.equal(
678 componentsOf(harness.simulation, playerId).combat?.targetEntityId,
679 ratId,
680 "player should auto-retaliate after the mob swing"
681 );
682 }
683 finally
684 { harness.close(); }
685});
686
687test("aggressive rats do not aggro through walls or beyond range", () =>
688{
689 const harness = makeSimulation({ workerCount: 1 });
690 try
691 {
692 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
693 const playerId = harness.simulation.spawnCharacter(1, character);
694 const blockedRat = harness.simulation.spawnEntity(mobComponents({
695 tileX: 12,
696 tileY: 8,
697 mobTypeId: MobId.rat,
698 spawnerId: null
699 }));
700 const worker = workerOf(harness.simulation, playerId);
701 const world = worker.world;
702 const data = world.chunkData(0, 0);
703 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
704 for (let y = 6; y <= 10; y++)
705 { data.blocks[y * 16 + 10] = wall; }
706
707 harness.simulation.step();
708 assert.equal(
709 componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null,
710 null,
711 "wall blocks LOS aggro"
712 );
713
714 const farRat = harness.simulation.spawnEntity(mobComponents({
715 tileX: 20,
716 tileY: 8,
717 mobTypeId: MobId.rat,
718 spawnerId: null
719 }));
720 harness.simulation.step();
721 assert.equal(
722 componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null,
723 null,
724 "out of range does not aggro"
725 );
726 }
727 finally
728 { harness.close(); }
729});
730
731test("crafting stations and tables do not block ranged or spell line of sight", () =>
732{
733 assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
734 assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
735 assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
736 assert.equal(blockBlocksRangedAttacks(null), false);
737
738 const harness = makeSimulation({ workerCount: 1 });
739 try
740 {
741 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
742 const playerId = harness.simulation.spawnCharacter(1, character);
743 const worker = workerOf(harness.simulation, playerId);
744 const data = worker.world.chunkData(0, 0);
745 const blockIndex = (localY, localX) => localY * 16 + localX;
746
747 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
748 assert.equal(
749 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
750 true,
751 "furnace between caster and target should not block"
752 );
753
754 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
755 assert.equal(
756 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
757 true,
758 "table between caster and target should not block"
759 );
760
761 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
762 assert.equal(
763 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
764 false,
765 "stone wall should still block"
766 );
767 }
768 finally
769 { harness.close(); }
770});
771
772test("attacker keeps pursuing and can swing after the target moves", () =>
773{
774 const harness = makeSimulation({ workerCount: 1 });
775 try
776 {
777 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
778 const playerId = harness.simulation.spawnCharacter(1, character);
779 const ratId = harness.simulation.spawnEntity(mobComponents({
780 tileX: 12,
781 tileY: 8,
782 mobTypeId: MobId.rat,
783 spawnerId: null
784 }));
785
786 harness.simulation.enqueue(1, {
787 type: "attack",
788 characterId: character.character_id,
789 targetEntityId: ratId
790 });
791 harness.simulation.step();
792
793 const worker = workerOf(harness.simulation, playerId);
794 stepTimes(harness.simulation, 4);
795 teleportEntity(worker, ratId, 12, 10);
796
797 let swings = 0;
798 for (let i = 0; i < 120; i++)
799 {
800 const events = harness.simulation.step().events;
801 swings += events.filter((event) => event.type === "combat-swing").length;
802 if (swings > 0)
803 { break; }
804 }
805
806 assert.ok(swings >= 1);
807 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, ratId);
808 }
809 finally
810 { harness.close(); }
811});
812
813test("combatants keep auto-attacking while adjacent", () =>
814{
815 const harness = makeSimulation({ workerCount: 1 });
816 try
817 {
818 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
819 const playerId = harness.simulation.spawnCharacter(1, character);
820 const deerId = harness.simulation.spawnEntity(mobComponents({
821 tileX: 9,
822 tileY: 8,
823 mobTypeId: MobId.deer,
824 spawnerId: null
825 }));
826
827 harness.simulation.enqueue(1, {
828 type: "attack",
829 characterId: character.character_id,
830 targetEntityId: deerId
831 });
832 harness.simulation.step();
833
834 let swings = 0;
835 for (let i = 0; i < 50; i++)
836 {
837 harness.advance(50);
838 const events = harness.simulation.step().events;
839 swings += events.filter((event) => event.type === "combat-swing").length;
840 const player = componentsOf(harness.simulation, playerId);
841 const deer = componentsOf(harness.simulation, deerId);
842 if (swings >= 4
843 && player.combat?.targetEntityId === deerId
844 && deer.combat?.targetEntityId === playerId
845 && (player.health?.current ?? 0) > 0)
846 { break; }
847 }
848
849 assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
850 const player = componentsOf(harness.simulation, playerId);
851 const deer = componentsOf(harness.simulation, deerId);
852 assert.ok((player.health?.current ?? 0) > 0, "player should still be alive during sustained combat");
853 assert.equal(player.combat?.targetEntityId, deerId);
854 assert.equal(deer.combat?.targetEntityId, playerId);
855 }
856 finally
857 { harness.close(); }
858});
859
860test("cross-worker adjacent combat keeps engaging and swinging", () =>
861{
862 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
863 try
864 {
865 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
866 const playerId = harness.simulation.spawnCharacter(1, character);
867 const deerId = harness.simulation.spawnEntity(mobComponents({
868 tileX: 63,
869 tileY: 8,
870 mobTypeId: MobId.deer,
871 spawnerId: null
872 }));
873 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
874 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
875
876 harness.simulation.enqueue(1, {
877 type: "attack",
878 characterId: character.character_id,
879 targetEntityId: deerId
880 });
881 const first = harness.simulation.step();
882 assert.equal(first.events.some((event) => event.type === "command-error"), false);
883
884 const random = Math.random;
885 Math.random = () => 0;
886 try
887 {
888 let swings = 0;
889 for (let i = 0; i < 40; i++)
890 {
891 harness.advance(50);
892 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
893 if (swings >= 4)
894 { break; }
895 }
896
897 assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
898 const deerWorker = harness.simulation.workers[0];
899 const playerWorker = harness.simulation.workers[1];
900 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
901 const playerHandle = playerWorker.world.ecs.handleOf(playerId);
902 const deerCombat = deerWorker.world.ecs.get(deerHandle, Component.combat);
903 const playerCombat = playerWorker.world.ecs.get(playerHandle, Component.combat);
904 const playerHealth = playerWorker.world.ecs.get(playerHandle, Component.health);
905 assert.ok((playerHealth?.current ?? 0) > 0, "player should survive sustained cross-worker combat");
906 assert.equal(deerCombat?.targetEntityId, playerId);
907 assert.equal(playerCombat?.targetEntityId, deerId);
908 }
909 finally
910 { Math.random = random; }
911 }
912 finally
913 { harness.close(); }
914});
915
916test("cancel attack stops the player but the mob keeps pursuing", () =>
917{
918 const harness = makeSimulation({ workerCount: 1 });
919 try
920 {
921 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
922 const playerId = harness.simulation.spawnCharacter(1, character);
923 const ratId = harness.simulation.spawnEntity(mobComponents({
924 tileX: 9,
925 tileY: 8,
926 mobTypeId: MobId.rat,
927 spawnerId: null
928 }));
929
930 harness.simulation.enqueue(1, {
931 type: "attack",
932 characterId: character.character_id,
933 targetEntityId: ratId
934 });
935 harness.simulation.step();
936
937 harness.simulation.enqueue(1, {
938 type: "cancel-attack",
939 characterId: character.character_id
940 });
941 harness.simulation.step();
942
943 const player = componentsOf(harness.simulation, playerId);
944 const rat = componentsOf(harness.simulation, ratId);
945 assert.equal(player.combat?.targetEntityId, null);
946 assert.equal(rat.combat?.targetEntityId, playerId);
947 }
948 finally
949 { harness.close(); }
950});
951
952test("player combat and skills components are present on spawn", () =>
953{
954 const harness = makeSimulation({ workerCount: 1 });
955 try
956 {
957 const character = makeCharacter(harness.stateDb);
958 const playerId = harness.simulation.spawnCharacter(1, character);
959 const comps = componentsOf(harness.simulation, playerId);
960 assert.ok(comps.combat);
961 assert.equal(comps.skills?.xp?.clubfighting, 0);
962 assert.ok(comps.health);
963 }
964 finally
965 { harness.close(); }
966});
967
968test("mobs heal to full when their region unloads", () =>
969{
970 const harness = makeSimulation({ workerCount: 1 });
971 try
972 {
973 const ratId = harness.simulation.spawnEntity(mobComponents({
974 tileX: 8,
975 tileY: 8,
976 mobTypeId: MobId.rat
977 }));
978 const worker = workerOf(harness.simulation, ratId);
979 const handle = worker.world.ecs.handleOf(ratId);
980 worker.world.ecs.get(handle, Component.health).current = 2;
981 const result = worker.call({
982 type: WorkerMessage.dropRegion,
983 regionX: tileToRegion(8),
984 regionY: tileToRegion(8)
985 });
986 const record = result.dropped.find((entry) => entry.entityId === ratId);
987 assert.ok(record);
988 assert.equal(
989 record.payload.components.health.current,
990 record.payload.components.health.max
991 );
992 }
993 finally
994 { harness.close(); }
995});
996
997test("taking damage awards Health XP equal to damage dealt", () =>
998{
999 const harness = makeSimulation({ workerCount: 1 });
1000 const random = Math.random;
1001 Math.random = () => 0;
1002 try
1003 {
1004 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1005 const playerId = harness.simulation.spawnCharacter(1, character);
1006 const ratId = harness.simulation.spawnEntity(mobComponents({
1007 mobTypeId: MobId.rat,
1008 tileX: 9,
1009 tileY: 8
1010 }));
1011 const worker = harness.simulation.workers[0];
1012 const playerHandle = worker.world.ecs.handleOf(playerId);
1013 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
1014 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1015 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1016 const hit = events.find((event) => event.type === "combat-hit");
1017 assert.ok(hit);
1018 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1019 assert.ok(updated);
1020 assert.equal(updated.stored[SkillId.health] - before, hit.damage);
1021 }
1022 finally
1023 {
1024 Math.random = random;
1025 harness.close();
1026 }
1027});
1028
1029test("lethal damage awards no Health XP", () =>
1030{
1031 const harness = makeSimulation({ workerCount: 1 });
1032 const random = Math.random;
1033 Math.random = () => 0;
1034 try
1035 {
1036 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1037 const playerId = harness.simulation.spawnCharacter(1, character);
1038 const ratId = harness.simulation.spawnEntity(mobComponents({
1039 mobTypeId: MobId.rat,
1040 tileX: 9,
1041 tileY: 8
1042 }));
1043 const worker = harness.simulation.workers[0];
1044 const playerHandle = worker.world.ecs.handleOf(playerId);
1045 const health = worker.world.ecs.get(playerHandle, Component.health);
1046 health.current = 1;
1047 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
1048 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1049 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1050 const hit = events.find((event) => event.type === "combat-hit");
1051 assert.ok(hit);
1052 assert.ok(hit.damage >= 1);
1053 assert.equal(hit.health, 0);
1054 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1055 assert.equal(updated, undefined);
1056 assert.equal(worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health], before);
1057 }
1058 finally
1059 {
1060 Math.random = random;
1061 harness.close();
1062 }
1063});
1064
1065test("dodging a hit awards Agility XP equal to avoided damage", () =>
1066{
1067 const harness = makeSimulation({ workerCount: 1 });
1068 let roll = 0;
1069 const seq = [0, 0.5, 0];
1070 const random = Math.random;
1071 Math.random = () => seq[roll++ % seq.length];
1072 try
1073 {
1074 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1075 const playerId = harness.simulation.spawnCharacter(1, character);
1076 const ratId = harness.simulation.spawnEntity(mobComponents({
1077 mobTypeId: MobId.rat,
1078 tileX: 9,
1079 tileY: 8
1080 }));
1081 const worker = harness.simulation.workers[0];
1082 const playerHandle = worker.world.ecs.handleOf(playerId);
1083 const skills = worker.world.ecs.get(playerHandle, Component.skills);
1084 skills.xp[SkillId.agility] = totalXpForLevel(10);
1085 const before = skills.xp[SkillId.agility] | 0;
1086 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1087 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1088 assert.ok(events.find((event) => event.type === "combat-miss"));
1089 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1090 assert.ok(updated);
1091 assert.equal(updated.stored[SkillId.agility] - before, 1);
1092 }
1093 finally
1094 {
1095 Math.random = random;
1096 harness.close();
1097 }
1098});
1099
1100test("blocking a hit awards Defence XP equal to avoided damage", () =>
1101{
1102 const harness = makeSimulation({ workerCount: 1 });
1103 let roll = 0;
1104 const seq = [0.9, 0, 0, 0.9];
1105 const random = Math.random;
1106 Math.random = () => seq[roll++ % seq.length];
1107 try
1108 {
1109 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1110 const playerId = harness.simulation.spawnCharacter(1, character);
1111 const ratId = harness.simulation.spawnEntity(mobComponents({
1112 mobTypeId: MobId.rat,
1113 tileX: 9,
1114 tileY: 8
1115 }));
1116 const worker = harness.simulation.workers[0];
1117 const playerHandle = worker.world.ecs.handleOf(playerId);
1118 const skills = worker.world.ecs.get(playerHandle, Component.skills);
1119 skills.xp[SkillId.defence] = totalXpForLevel(10);
1120 const before = skills.xp[SkillId.defence] | 0;
1121 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1122 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1123 assert.ok(events.find((event) => event.type === "combat-block"));
1124 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1125 assert.ok(updated);
1126 assert.equal(updated.stored[SkillId.defence] - before, 1);
1127 }
1128 finally
1129 {
1130 Math.random = random;
1131 harness.close();
1132 }
1133});
1134
1135test("stacked combatants against the same target spread to different tiles", () =>
1136{
1137 const harness = makeSimulation({ workerCount: 1 });
1138 try
1139 {
1140 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1141 const playerId = harness.simulation.spawnCharacter(1, character);
1142 const rat1 = harness.simulation.spawnEntity(mobComponents({
1143 tileX: 9,
1144 tileY: 8,
1145 mobTypeId: MobId.rat,
1146 spawnerId: null
1147 }));
1148 const rat2 = harness.simulation.spawnEntity(mobComponents({
1149 tileX: 9,
1150 tileY: 7,
1151 mobTypeId: MobId.rat,
1152 spawnerId: null
1153 }));
1154 const worker = workerOf(harness.simulation, playerId);
1155 teleportEntity(worker, rat2, 9, 8);
1156
1157 for (let i = 0; i < 200; i++)
1158 {
1159 harness.advance(50);
1160 harness.simulation.step();
1161 }
1162
1163 const pos1 = componentsOf(harness.simulation, rat1).position;
1164 const pos2 = componentsOf(harness.simulation, rat2).position;
1165 assert.notEqual(
1166 `${pos1.tileX},${pos1.tileY}`,
1167 `${pos2.tileX},${pos2.tileY}`,
1168 "expected stacked rats to spread apart"
1169 );
1170 assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
1171 assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
1172 }
1173 finally
1174 { harness.close(); }
1175});
1176
1177test("approaching combatants pick different adjacent goals", () =>
1178{
1179 const harness = makeSimulation({ workerCount: 1 });
1180 try
1181 {
1182 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1183 const playerId = harness.simulation.spawnCharacter(1, character);
1184 const rat1 = harness.simulation.spawnEntity(mobComponents({
1185 tileX: 6,
1186 tileY: 8,
1187 mobTypeId: MobId.rat,
1188 spawnerId: null
1189 }));
1190 const rat2 = harness.simulation.spawnEntity(mobComponents({
1191 tileX: 6,
1192 tileY: 7,
1193 mobTypeId: MobId.rat,
1194 spawnerId: null
1195 }));
1196 const worker = workerOf(harness.simulation, playerId);
1197 teleportEntity(worker, rat2, 6, 8);
1198
1199 for (let i = 0; i < 120; i++)
1200 {
1201 harness.advance(50);
1202 harness.simulation.step();
1203 }
1204
1205 const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
1206 const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
1207 const goal1 = path1[path1.length - 1];
1208 const goal2 = path2[path2.length - 1];
1209 if (goal1 && goal2)
1210 {
1211 assert.notEqual(
1212 `${goal1.x},${goal1.y}`,
1213 `${goal2.x},${goal2.y}`,
1214 "expected different approach goals"
1215 );
1216 }
1217
1218 const pos1 = componentsOf(harness.simulation, rat1).position;
1219 const pos2 = componentsOf(harness.simulation, rat2).position;
1220 assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
1221 }
1222 finally
1223 { harness.close(); }
1224});
1225
1226test("humanoid attackers add equipment bonuses on top of spawner level", () =>
1227{
1228 const harness = makeSimulation({ workerCount: 1 });
1229 const random = Math.random;
1230 /** Max every skill roll so damage equals effective damage skill. */
1231 Math.random = () => 0.999999;
1232 try
1233 {
1234 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1235 const playerId = harness.simulation.spawnCharacter(1, character);
1236 const player = componentsOf(harness.simulation, playerId);
1237 player.skills.xp[SkillId.agility] = 0;
1238 player.skills.xp[SkillId.defence] = 0;
1239
1240 const level = 5;
1241 const npcId = harness.simulation.spawnEntity(mobComponents({
1242 tileX: 9,
1243 tileY: 8,
1244 mobTypeId: MobId.humanoid,
1245 level,
1246 displayName: "Guard",
1247 sex: "male",
1248 equipment: {
1249 weapon: WoodItemId.oakQuarterstaff
1250 }
1251 }));
1252 const worker = workerOf(harness.simulation, npcId);
1253 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(npcId));
1254 assert.equal(profile.mobAttackSkill, level);
1255 assert.equal(profile.damageSkillId, SkillId.strength);
1256
1257 const events = resolveMeleeSwing(worker.world, npcId, playerId, profile, Date.now());
1258 const hit = events.find((event) => event.type === "combat-hit");
1259 assert.ok(hit, "expected a hit");
1260 assert.equal(hit.damage, level + tierStatBonus(WoodTier.oak));
1261 }
1262 finally
1263 {
1264 Math.random = random;
1265 harness.close();
1266 }
1267});
1268
1269test("staff melees like a quarterstaff and awards clubs XP", () =>
1270{
1271 const harness = makeSimulation({ workerCount: 1 });
1272 const random = Math.random;
1273 Math.random = () => 0.999999;
1274 try
1275 {
1276 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1277 const playerId = harness.simulation.spawnCharacter(1, character);
1278 const deerId = harness.simulation.spawnEntity(mobComponents({
1279 tileX: 9,
1280 tileY: 8,
1281 mobTypeId: MobId.deer
1282 }));
1283 const worker = workerOf(harness.simulation, playerId);
1284 const handle = worker.world.ecs.handleOf(playerId);
1285 const equipment = worker.world.ecs.get(handle, Component.equipment);
1286 equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
1287 const skills = worker.world.ecs.get(handle, Component.skills);
1288 skills.xp[SkillId.clubfighting] = totalXpForLevel(10);
1289 skills.xp[SkillId.magic] = totalXpForLevel(10);
1290 const clubsBefore = skills.xp[SkillId.clubfighting];
1291 const magicBefore = skills.xp[SkillId.magic];
1292
1293 const profile = attackProfileOf(worker.world.ecs, handle);
1294 assert.equal(profile.mode, "melee");
1295 assert.equal(profile.hitSkillId, SkillId.clubfighting);
1296 assert.equal(profile.damageSkillId, SkillId.strength);
1297
1298 const events = resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
1299 const hit = events.find((event) => event.type === "combat-hit");
1300 assert.ok(hit, "staff should land a melee hit");
1301 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1302 assert.ok(updated);
1303 assert.ok(updated.stored[SkillId.clubfighting] > clubsBefore, "melee staff awards clubs XP");
1304 assert.equal(updated.stored[SkillId.magic], magicBefore, "melee staff does not award magic XP");
1305 }
1306 finally
1307 {
1308 Math.random = random;
1309 harness.close();
1310 }
1311});
1312
1313test("spell damage marks seekCover on a melee mob", () =>
1314{
1315 const harness = makeSimulation({ workerCount: 1 });
1316 try
1317 {
1318 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1319 const playerId = harness.simulation.spawnCharacter(1, character);
1320 const deerId = harness.simulation.spawnEntity(mobComponents({
1321 tileX: 12,
1322 tileY: 8,
1323 mobTypeId: MobId.deer,
1324 spawnerId: null
1325 }));
1326 const worker = workerOf(harness.simulation, playerId);
1327 applyDamageAndKill(worker.world, playerId, deerId, 1, Date.now());
1328 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1329 assert.equal(componentsOf(harness.simulation, deerId).combat?.seekCover, true);
1330 }
1331 finally
1332 { harness.close(); }
1333});
1334
1335test("melee hit does not mark seekCover on a retaliating mob", () =>
1336{
1337 const random = Math.random;
1338 Math.random = () => 0;
1339 const harness = makeSimulation({ workerCount: 1 });
1340 try
1341 {
1342 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1343 const playerId = harness.simulation.spawnCharacter(1, character);
1344 const deerId = harness.simulation.spawnEntity(mobComponents({
1345 tileX: 9,
1346 tileY: 8,
1347 mobTypeId: MobId.deer,
1348 spawnerId: null
1349 }));
1350 const worker = workerOf(harness.simulation, playerId);
1351 const handle = worker.world.ecs.handleOf(playerId);
1352 const bag = harness.simulation.bagOf(playerId);
1353 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
1354 if (stickSlot >= 0)
1355 {
1356 harness.simulation.enqueue(1, {
1357 type: "equip-item",
1358 characterId: character.character_id,
1359 slotIndex: stickSlot
1360 });
1361 harness.simulation.step();
1362 }
1363 const profile = attackProfileOf(worker.world.ecs, handle);
1364 assert.equal(profile.mode, "melee");
1365 resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
1366 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1367 assert.equal(!!componentsOf(harness.simulation, deerId).combat?.seekCover, false);
1368 }
1369 finally
1370 {
1371 Math.random = random;
1372 harness.close();
1373 }
1374});
1375
1376test("seekCover mob flees to a no-LOS tile when melee approach is impossible", () =>
1377{
1378 const harness = makeSimulation({ workerCount: 1 });
1379 try
1380 {
1381 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1382 const playerId = harness.simulation.spawnCharacter(1, character);
1383 const deerId = harness.simulation.spawnEntity(mobComponents({
1384 tileX: 14,
1385 tileY: 8,
1386 mobTypeId: MobId.deer,
1387 spawnerId: null
1388 }));
1389 const worker = workerOf(harness.simulation, playerId);
1390 const world = worker.world;
1391 const data = world.chunkData(0, 0);
1392 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
1393 const furnace = { typeId: BlockType.furnace, state: null, config: null };
1394 // Impassable stations around the player (do not block LOS) so no melee stand tile exists.
1395 for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]])
1396 { data.blocks[(8 + dy) * 16 + (8 + dx)] = furnace; }
1397 // Cover wall east of the approach.
1398 for (let y = 6; y <= 10; y++)
1399 { data.blocks[y * 16 + 12] = wall; }
1400
1401 assert.equal(hasCombatLineOfSight(world, 8, 8, 14, 8), false, "wall should block LOS east of the wall");
1402
1403 const deerHandle = world.ecs.handleOf(deerId);
1404 engageTarget(world.ecs, deerId, playerId);
1405 markSeekCover(world.ecs, deerId);
1406 const playerPos = world.ecs.get(world.ecs.handleOf(playerId), Component.position);
1407 teleportEntity(worker, deerId, 11, 8);
1408 assert.equal(hasCombatLineOfSight(world, 8, 8, 11, 8), true);
1409 queueMeleeApproach(world, deerId, deerHandle, world.ecs.get(deerHandle, Component.position), playerPos);
1410 const path = world.ecs.get(deerHandle, Component.path)?.tiles ?? [];
1411 assert.ok(path.length > 0, "expected a flee path into cover");
1412 const dest = path[path.length - 1];
1413 assert.equal(
1414 hasCombatLineOfSight(world, playerPos.tileX, playerPos.tileY, dest.x, dest.y),
1415 false,
1416 "flee destination must be out of player LOS"
1417 );
1418 }
1419 finally
1420 { harness.close(); }
1421});
1422
1423test("fairy flees to 2 tiles from hit source, then stops until hit again", () =>
1424{
1425 const harness = makeSimulation({ workerCount: 1 });
1426 try
1427 {
1428 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1429 const playerId = harness.simulation.spawnCharacter(1, character);
1430 const fairyId = harness.simulation.spawnEntity(mobComponents({
1431 tileX: 9,
1432 tileY: 8,
1433 mobTypeId: MobId.fairy,
1434 spawnerId: null
1435 }));
1436 const worker = workerOf(harness.simulation, fairyId);
1437 const world = worker.world;
1438 const fairyHandle = world.ecs.handleOf(fairyId);
1439
1440 applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
1441 const combat = world.ecs.get(fairyHandle, Component.combat);
1442 assert.equal(combat?.fleeFrom?.tileX, 8);
1443 assert.equal(combat?.fleeFrom?.tileY, 8);
1444 assert.equal(combat?.fleeFrom?.minDist, 2);
1445 assert.equal(combat?.targetEntityId, playerId);
1446
1447 stepCombat(world, Date.now());
1448 const path = world.ecs.get(fairyHandle, Component.path)?.tiles ?? [];
1449 assert.ok(path.length > 0, "fairy should path away while fleeing");
1450 const dest = path[path.length - 1];
1451 assert.ok(
1452 chebyshev(dest.x, dest.y, 8, 8) >= 2,
1453 `flee dest should be ≥2 from hit source, got ${dest.x},${dest.y}`
1454 );
1455
1456 teleportEntity(worker, fairyId, dest.x, dest.y);
1457 world.ecs.get(fairyHandle, Component.path).tiles = [];
1458 stepCombat(world, Date.now());
1459 assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom, null);
1460
1461 stepCombat(world, Date.now() + 5000);
1462 assert.equal(
1463 world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
1464 null,
1465 "no flee until hit again"
1466 );
1467
1468 teleportEntity(worker, fairyId, 9, 8);
1469 applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
1470 assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom?.minDist, 2);
1471
1472 teleportEntity(worker, fairyId, 12, 8);
1473 markFleeOnHit(world, fairyId, playerId);
1474 assert.equal(
1475 world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
1476 null,
1477 "already ≥2 tiles away does not start a flee"
1478 );
1479 }
1480 finally
1481 { harness.close(); }
1482});