BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

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