BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

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