BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

combat.test.js 50.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 { 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("players do not auto-retaliate while walking from a click order", () =>
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 ratId = harness.simulation.spawnEntity(mobComponents({
692 tileX: 9,
693 tileY: 8,
694 mobTypeId: MobId.rat,
695 spawnerId: null
696 }));
697
698 harness.simulation.enqueue(1, {
699 type: "move-to",
700 characterId: character.character_id,
701 tileX: 8,
702 tileY: 14
703 });
704 harness.simulation.step();
705 const path = componentsOf(harness.simulation, playerId).path;
706 assert.ok((path?.tiles?.length ?? 0) > 0, "player should be pathing");
707
708 let swung = false;
709 for (let i = 0; i < 80; i++)
710 {
711 harness.advance(50);
712 const events = harness.simulation.step().events;
713 if (events.some((event) =>
714 event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
715 ))
716 {
717 swung = true;
718 break;
719 }
720 }
721 assert.ok(swung, "expected the rat to swing at the walking player");
722 assert.equal(
723 componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
724 null,
725 "walking player should not auto-retaliate"
726 );
727 assert.ok(
728 (componentsOf(harness.simulation, playerId).path?.tiles?.length ?? 0) > 0
729 || componentsOf(harness.simulation, playerId).position.tileY !== 8,
730 "walk order should continue after the hit"
731 );
732 }
733 finally
734 { harness.close(); }
735});
736
737test("players do not auto-retaliate while gathering", () =>
738{
739 const harness = makeSimulation({ workerCount: 1 });
740 const restore = installDamagingCombatRng();
741 try
742 {
743 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
744 const playerId = harness.simulation.spawnCharacter(1, character);
745 const ratId = harness.simulation.spawnEntity(mobComponents({
746 tileX: 9,
747 tileY: 8,
748 mobTypeId: MobId.rat,
749 spawnerId: null
750 }));
751 const worker = workerOf(harness.simulation, playerId);
752 const handle = worker.world.ecs.handleOf(playerId);
753 worker.world.ecs.add(handle, Component.gather, {
754 kind: "mining",
755 tileX: 7,
756 tileY: 8,
757 materialId: "copper",
758 durationMs: 60_000,
759 startedAt: Date.now(),
760 finishesAt: Date.now() + 60_000,
761 nextSwingAt: Date.now() + 60_000
762 });
763 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
764 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
765 assert.ok(events.some((event) => event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block"));
766 assert.equal(
767 componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
768 null,
769 "gathering player should not auto-retaliate"
770 );
771 assert.ok(
772 worker.world.ecs.has(handle, Component.gather),
773 "gather session should survive the hit"
774 );
775 }
776 finally
777 {
778 restore();
779 harness.close();
780 }
781});
782
783test("aggressive rats do not aggro through walls or beyond range", () =>
784{
785 const harness = makeSimulation({ workerCount: 1 });
786 try
787 {
788 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
789 const playerId = harness.simulation.spawnCharacter(1, character);
790 const blockedRat = harness.simulation.spawnEntity(mobComponents({
791 tileX: 12,
792 tileY: 8,
793 mobTypeId: MobId.rat,
794 spawnerId: null
795 }));
796 const worker = workerOf(harness.simulation, playerId);
797 const world = worker.world;
798 const data = world.chunkData(0, 0);
799 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
800 for (let y = 6; y <= 10; y++)
801 { data.blocks[y * 16 + 10] = wall; }
802
803 harness.simulation.step();
804 assert.equal(
805 componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null,
806 null,
807 "wall blocks LOS aggro"
808 );
809
810 const farRat = harness.simulation.spawnEntity(mobComponents({
811 tileX: 20,
812 tileY: 8,
813 mobTypeId: MobId.rat,
814 spawnerId: null
815 }));
816 harness.simulation.step();
817 assert.equal(
818 componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null,
819 null,
820 "out of range does not aggro"
821 );
822 }
823 finally
824 { harness.close(); }
825});
826
827test("crafting stations and tables do not block ranged or spell line of sight", () =>
828{
829 assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
830 assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
831 assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
832 assert.equal(blockBlocksRangedAttacks(null), false);
833
834 const harness = makeSimulation({ workerCount: 1 });
835 try
836 {
837 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
838 const playerId = harness.simulation.spawnCharacter(1, character);
839 const worker = workerOf(harness.simulation, playerId);
840 const data = worker.world.chunkData(0, 0);
841 const blockIndex = (localY, localX) => localY * 16 + localX;
842
843 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
844 assert.equal(
845 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
846 true,
847 "furnace between caster and target should not block"
848 );
849
850 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
851 assert.equal(
852 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
853 true,
854 "table between caster and target should not block"
855 );
856
857 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
858 assert.equal(
859 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
860 false,
861 "stone wall should still block"
862 );
863 }
864 finally
865 { harness.close(); }
866});
867
868test("attacker keeps pursuing and can swing after the target moves", () =>
869{
870 const harness = makeSimulation({ workerCount: 1 });
871 try
872 {
873 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
874 const playerId = harness.simulation.spawnCharacter(1, character);
875 const ratId = harness.simulation.spawnEntity(mobComponents({
876 tileX: 12,
877 tileY: 8,
878 mobTypeId: MobId.rat,
879 spawnerId: null
880 }));
881
882 harness.simulation.enqueue(1, {
883 type: "attack",
884 characterId: character.character_id,
885 targetEntityId: ratId
886 });
887 harness.simulation.step();
888
889 const worker = workerOf(harness.simulation, playerId);
890 stepTimes(harness.simulation, 4);
891 teleportEntity(worker, ratId, 12, 10);
892
893 let swings = 0;
894 for (let i = 0; i < 120; i++)
895 {
896 const events = harness.simulation.step().events;
897 swings += events.filter((event) => event.type === "combat-swing").length;
898 if (swings > 0)
899 { break; }
900 }
901
902 assert.ok(swings >= 1);
903 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, ratId);
904 }
905 finally
906 { harness.close(); }
907});
908
909test("combatants keep auto-attacking while adjacent", () =>
910{
911 const harness = makeSimulation({ workerCount: 1 });
912 try
913 {
914 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
915 const playerId = harness.simulation.spawnCharacter(1, character);
916 const deerId = harness.simulation.spawnEntity(mobComponents({
917 tileX: 9,
918 tileY: 8,
919 mobTypeId: MobId.deer,
920 spawnerId: null
921 }));
922
923 harness.simulation.enqueue(1, {
924 type: "attack",
925 characterId: character.character_id,
926 targetEntityId: deerId
927 });
928 harness.simulation.step();
929
930 let swings = 0;
931 for (let i = 0; i < 50; i++)
932 {
933 harness.advance(50);
934 const events = harness.simulation.step().events;
935 swings += events.filter((event) => event.type === "combat-swing").length;
936 const player = componentsOf(harness.simulation, playerId);
937 const deer = componentsOf(harness.simulation, deerId);
938 if (swings >= 4
939 && player.combat?.targetEntityId === deerId
940 && deer.combat?.targetEntityId === playerId
941 && (player.health?.current ?? 0) > 0)
942 { break; }
943 }
944
945 assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
946 const player = componentsOf(harness.simulation, playerId);
947 const deer = componentsOf(harness.simulation, deerId);
948 assert.ok((player.health?.current ?? 0) > 0, "player should still be alive during sustained combat");
949 assert.equal(player.combat?.targetEntityId, deerId);
950 assert.equal(deer.combat?.targetEntityId, playerId);
951 }
952 finally
953 { harness.close(); }
954});
955
956test("cross-worker adjacent combat keeps engaging and swinging", () =>
957{
958 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
959 try
960 {
961 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
962 const playerId = harness.simulation.spawnCharacter(1, character);
963 const deerId = harness.simulation.spawnEntity(mobComponents({
964 tileX: 63,
965 tileY: 8,
966 mobTypeId: MobId.deer,
967 spawnerId: null
968 }));
969 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
970 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
971
972 harness.simulation.enqueue(1, {
973 type: "attack",
974 characterId: character.character_id,
975 targetEntityId: deerId
976 });
977 const first = harness.simulation.step();
978 assert.equal(first.events.some((event) => event.type === "command-error"), false);
979
980 const random = Math.random;
981 Math.random = () => 0;
982 try
983 {
984 let swings = 0;
985 for (let i = 0; i < 40; i++)
986 {
987 harness.advance(50);
988 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
989 if (swings >= 4)
990 { break; }
991 }
992
993 assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
994 const deerWorker = harness.simulation.workers[0];
995 const playerWorker = harness.simulation.workers[1];
996 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
997 const playerHandle = playerWorker.world.ecs.handleOf(playerId);
998 const deerCombat = deerWorker.world.ecs.get(deerHandle, Component.combat);
999 const playerCombat = playerWorker.world.ecs.get(playerHandle, Component.combat);
1000 const playerHealth = playerWorker.world.ecs.get(playerHandle, Component.health);
1001 assert.ok((playerHealth?.current ?? 0) > 0, "player should survive sustained cross-worker combat");
1002 assert.equal(deerCombat?.targetEntityId, playerId);
1003 assert.equal(playerCombat?.targetEntityId, deerId);
1004 }
1005 finally
1006 { Math.random = random; }
1007 }
1008 finally
1009 { harness.close(); }
1010});
1011
1012test("cancel attack stops the player but the mob keeps pursuing", () =>
1013{
1014 const harness = makeSimulation({ workerCount: 1 });
1015 try
1016 {
1017 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1018 const playerId = harness.simulation.spawnCharacter(1, character);
1019 const ratId = harness.simulation.spawnEntity(mobComponents({
1020 tileX: 9,
1021 tileY: 8,
1022 mobTypeId: MobId.rat,
1023 spawnerId: null
1024 }));
1025
1026 harness.simulation.enqueue(1, {
1027 type: "attack",
1028 characterId: character.character_id,
1029 targetEntityId: ratId
1030 });
1031 harness.simulation.step();
1032
1033 harness.simulation.enqueue(1, {
1034 type: "cancel-attack",
1035 characterId: character.character_id
1036 });
1037 harness.simulation.step();
1038
1039 const player = componentsOf(harness.simulation, playerId);
1040 const rat = componentsOf(harness.simulation, ratId);
1041 assert.equal(player.combat?.targetEntityId, null);
1042 assert.equal(rat.combat?.targetEntityId, playerId);
1043 }
1044 finally
1045 { harness.close(); }
1046});
1047
1048test("player combat and skills components are present on spawn", () =>
1049{
1050 const harness = makeSimulation({ workerCount: 1 });
1051 try
1052 {
1053 const character = makeCharacter(harness.stateDb);
1054 const playerId = harness.simulation.spawnCharacter(1, character);
1055 const comps = componentsOf(harness.simulation, playerId);
1056 assert.ok(comps.combat);
1057 assert.equal(comps.skills?.xp?.clubfighting, 0);
1058 assert.ok(comps.health);
1059 }
1060 finally
1061 { harness.close(); }
1062});
1063
1064test("mobs heal to full when their region unloads", () =>
1065{
1066 const harness = makeSimulation({ workerCount: 1 });
1067 try
1068 {
1069 const ratId = harness.simulation.spawnEntity(mobComponents({
1070 tileX: 8,
1071 tileY: 8,
1072 mobTypeId: MobId.rat
1073 }));
1074 const worker = workerOf(harness.simulation, ratId);
1075 const handle = worker.world.ecs.handleOf(ratId);
1076 worker.world.ecs.get(handle, Component.health).current = 2;
1077 const result = worker.call({
1078 type: WorkerMessage.dropRegion,
1079 regionX: tileToRegion(8),
1080 regionY: tileToRegion(8)
1081 });
1082 const record = result.dropped.find((entry) => entry.entityId === ratId);
1083 assert.ok(record);
1084 assert.equal(
1085 record.payload.components.health.current,
1086 record.payload.components.health.max
1087 );
1088 }
1089 finally
1090 { harness.close(); }
1091});
1092
1093test("taking damage awards Health XP equal to damage dealt", () =>
1094{
1095 const harness = makeSimulation({ workerCount: 1 });
1096 const restore = installDamagingCombatRng();
1097 try
1098 {
1099 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1100 const playerId = harness.simulation.spawnCharacter(1, character);
1101 const ratId = harness.simulation.spawnEntity(mobComponents({
1102 mobTypeId: MobId.rat,
1103 tileX: 9,
1104 tileY: 8
1105 }));
1106 const worker = harness.simulation.workers[0];
1107 const playerHandle = worker.world.ecs.handleOf(playerId);
1108 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
1109 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1110 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1111 const hit = events.find((event) => event.type === "combat-hit");
1112 assert.ok(hit);
1113 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1114 assert.ok(updated);
1115 assert.equal(updated.stored[SkillId.health] - before, hit.damage);
1116 }
1117 finally
1118 {
1119 restore();
1120 harness.close();
1121 }
1122});
1123
1124test("lethal damage awards no Health XP", () =>
1125{
1126 const harness = makeSimulation({ workerCount: 1 });
1127 const restore = installDamagingCombatRng();
1128 try
1129 {
1130 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1131 const playerId = harness.simulation.spawnCharacter(1, character);
1132 const ratId = harness.simulation.spawnEntity(mobComponents({
1133 mobTypeId: MobId.rat,
1134 tileX: 9,
1135 tileY: 8
1136 }));
1137 const worker = harness.simulation.workers[0];
1138 const playerHandle = worker.world.ecs.handleOf(playerId);
1139 const health = worker.world.ecs.get(playerHandle, Component.health);
1140 health.current = 1;
1141 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
1142 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1143 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1144 const hit = events.find((event) => event.type === "combat-hit");
1145 assert.ok(hit);
1146 assert.ok(hit.damage >= 1);
1147 assert.equal(hit.health, 0);
1148 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1149 assert.equal(updated, undefined);
1150 assert.equal(worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health], before);
1151 }
1152 finally
1153 {
1154 restore();
1155 harness.close();
1156 }
1157});
1158
1159test("dodging a hit awards Agility XP equal to avoided damage", () =>
1160{
1161 const harness = makeSimulation({ workerCount: 1 });
1162 const restore = installMissDodgeRng(1);
1163 try
1164 {
1165 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1166 const playerId = harness.simulation.spawnCharacter(1, character);
1167 const ratId = harness.simulation.spawnEntity(mobComponents({
1168 mobTypeId: MobId.rat,
1169 tileX: 9,
1170 tileY: 8
1171 }));
1172 const worker = harness.simulation.workers[0];
1173 const playerHandle = worker.world.ecs.handleOf(playerId);
1174 const skills = worker.world.ecs.get(playerHandle, Component.skills);
1175 skills.xp[SkillId.agility] = totalXpForLevel(10);
1176 const before = skills.xp[SkillId.agility] | 0;
1177 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1178 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1179 assert.ok(events.find((event) => event.type === "combat-miss"));
1180 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1181 assert.ok(updated);
1182 assert.equal(updated.stored[SkillId.agility] - before, 1);
1183 }
1184 finally
1185 {
1186 restore();
1187 harness.close();
1188 }
1189});
1190
1191test("blocking a hit awards Defence XP equal to avoided damage", () =>
1192{
1193 const harness = makeSimulation({ workerCount: 1 });
1194 const restore = installBlockRng(1);
1195 try
1196 {
1197 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1198 const playerId = harness.simulation.spawnCharacter(1, character);
1199 const ratId = harness.simulation.spawnEntity(mobComponents({
1200 mobTypeId: MobId.rat,
1201 tileX: 9,
1202 tileY: 8
1203 }));
1204 const worker = harness.simulation.workers[0];
1205 const playerHandle = worker.world.ecs.handleOf(playerId);
1206 const skills = worker.world.ecs.get(playerHandle, Component.skills);
1207 skills.xp[SkillId.defence] = totalXpForLevel(10);
1208 const before = skills.xp[SkillId.defence] | 0;
1209 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1210 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1211 assert.ok(events.find((event) => event.type === "combat-block"));
1212 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1213 assert.ok(updated);
1214 assert.equal(updated.stored[SkillId.defence] - before, 1);
1215 }
1216 finally
1217 {
1218 restore();
1219 harness.close();
1220 }
1221});
1222
1223test("stacked combatants against the same target spread to different tiles", () =>
1224{
1225 const harness = makeSimulation({ workerCount: 1 });
1226 try
1227 {
1228 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1229 const playerId = harness.simulation.spawnCharacter(1, character);
1230 const rat1 = harness.simulation.spawnEntity(mobComponents({
1231 tileX: 9,
1232 tileY: 8,
1233 mobTypeId: MobId.rat,
1234 spawnerId: null
1235 }));
1236 const rat2 = harness.simulation.spawnEntity(mobComponents({
1237 tileX: 9,
1238 tileY: 7,
1239 mobTypeId: MobId.rat,
1240 spawnerId: null
1241 }));
1242 const worker = workerOf(harness.simulation, playerId);
1243 const handle = worker.world.ecs.handleOf(playerId);
1244 const playerHealth = worker.world.ecs.get(handle, Component.health);
1245 playerHealth.max = 500;
1246 playerHealth.current = 500;
1247 engageTarget(worker.world.ecs, rat1, playerId);
1248 engageTarget(worker.world.ecs, rat2, playerId);
1249 assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
1250 assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
1251 teleportEntity(worker, rat2, 9, 8);
1252
1253 for (let i = 0; i < 200; i++)
1254 {
1255 harness.advance(50);
1256 harness.simulation.step();
1257 }
1258
1259 const pos1 = componentsOf(harness.simulation, rat1).position;
1260 const pos2 = componentsOf(harness.simulation, rat2).position;
1261 assert.notEqual(
1262 `${pos1.tileX},${pos1.tileY}`,
1263 `${pos2.tileX},${pos2.tileY}`,
1264 "expected stacked rats to spread apart"
1265 );
1266 }
1267 finally
1268 { harness.close(); }
1269});
1270
1271test("approaching combatants pick different adjacent goals", () =>
1272{
1273 const harness = makeSimulation({ workerCount: 1 });
1274 try
1275 {
1276 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1277 const playerId = harness.simulation.spawnCharacter(1, character);
1278 const rat1 = harness.simulation.spawnEntity(mobComponents({
1279 tileX: 6,
1280 tileY: 8,
1281 mobTypeId: MobId.rat,
1282 spawnerId: null
1283 }));
1284 const rat2 = harness.simulation.spawnEntity(mobComponents({
1285 tileX: 6,
1286 tileY: 7,
1287 mobTypeId: MobId.rat,
1288 spawnerId: null
1289 }));
1290 const worker = workerOf(harness.simulation, playerId);
1291 teleportEntity(worker, rat2, 6, 8);
1292
1293 for (let i = 0; i < 120; i++)
1294 {
1295 harness.advance(50);
1296 harness.simulation.step();
1297 }
1298
1299 const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
1300 const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
1301 const goal1 = path1[path1.length - 1];
1302 const goal2 = path2[path2.length - 1];
1303 if (goal1 && goal2)
1304 {
1305 assert.notEqual(
1306 `${goal1.x},${goal1.y}`,
1307 `${goal2.x},${goal2.y}`,
1308 "expected different approach goals"
1309 );
1310 }
1311
1312 const pos1 = componentsOf(harness.simulation, rat1).position;
1313 const pos2 = componentsOf(harness.simulation, rat2).position;
1314 assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
1315 }
1316 finally
1317 { harness.close(); }
1318});
1319
1320test("humanoid attackers add equipment bonuses on top of spawner level", () =>
1321{
1322 const harness = makeSimulation({ workerCount: 1 });
1323 const random = Math.random;
1324 /** Max every skill roll so damage equals effective damage skill. */
1325 Math.random = () => 0.999999;
1326 try
1327 {
1328 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1329 const playerId = harness.simulation.spawnCharacter(1, character);
1330 const player = componentsOf(harness.simulation, playerId);
1331 player.skills.xp[SkillId.agility] = 0;
1332 player.skills.xp[SkillId.defence] = 0;
1333
1334 const level = 5;
1335 const npcId = harness.simulation.spawnEntity(mobComponents({
1336 tileX: 9,
1337 tileY: 8,
1338 mobTypeId: MobId.humanoid,
1339 level,
1340 displayName: "Guard",
1341 sex: "male",
1342 equipment: {
1343 weapon: WoodItemId.oakQuarterstaff
1344 }
1345 }));
1346 const worker = workerOf(harness.simulation, npcId);
1347 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(npcId));
1348 assert.equal(profile.mobAttackSkill, level);
1349 assert.equal(profile.damageSkillId, SkillId.strength);
1350
1351 const events = resolveMeleeSwing(worker.world, npcId, playerId, profile, Date.now());
1352 const hit = events.find((event) => event.type === "combat-hit");
1353 assert.ok(hit, "expected a hit");
1354 assert.equal(hit.damage, combatDamageRollLevel(level + tierStatBonus(WoodTier.oak)));
1355 }
1356 finally
1357 {
1358 Math.random = random;
1359 harness.close();
1360 }
1361});
1362
1363test("staff melees like a quarterstaff and awards clubs XP", () =>
1364{
1365 const harness = makeSimulation({ workerCount: 1 });
1366 const random = Math.random;
1367 Math.random = () => 0.999999;
1368 try
1369 {
1370 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1371 const playerId = harness.simulation.spawnCharacter(1, character);
1372 const deerId = harness.simulation.spawnEntity(mobComponents({
1373 tileX: 9,
1374 tileY: 8,
1375 mobTypeId: MobId.deer
1376 }));
1377 const worker = workerOf(harness.simulation, playerId);
1378 const handle = worker.world.ecs.handleOf(playerId);
1379 const equipment = worker.world.ecs.get(handle, Component.equipment);
1380 equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
1381 const skills = worker.world.ecs.get(handle, Component.skills);
1382 skills.xp[SkillId.clubfighting] = totalXpForLevel(10);
1383 skills.xp[SkillId.magic] = totalXpForLevel(10);
1384 const clubsBefore = skills.xp[SkillId.clubfighting];
1385 const magicBefore = skills.xp[SkillId.magic];
1386
1387 const profile = attackProfileOf(worker.world.ecs, handle);
1388 assert.equal(profile.mode, "melee");
1389 assert.equal(profile.hitSkillId, SkillId.clubfighting);
1390 assert.equal(profile.damageSkillId, SkillId.strength);
1391
1392 const events = resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
1393 const hit = events.find((event) => event.type === "combat-hit");
1394 assert.ok(hit, "staff should land a melee hit");
1395 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1396 assert.ok(updated);
1397 assert.ok(updated.stored[SkillId.clubfighting] > clubsBefore, "melee staff awards clubs XP");
1398 assert.equal(updated.stored[SkillId.magic], magicBefore, "melee staff does not award magic XP");
1399 }
1400 finally
1401 {
1402 Math.random = random;
1403 harness.close();
1404 }
1405});
1406
1407test("spell damage marks seekCover on a melee mob", () =>
1408{
1409 const harness = makeSimulation({ workerCount: 1 });
1410 try
1411 {
1412 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1413 const playerId = harness.simulation.spawnCharacter(1, character);
1414 const deerId = harness.simulation.spawnEntity(mobComponents({
1415 tileX: 12,
1416 tileY: 8,
1417 mobTypeId: MobId.deer,
1418 spawnerId: null
1419 }));
1420 const worker = workerOf(harness.simulation, playerId);
1421 applyDamageAndKill(worker.world, playerId, deerId, 1, Date.now());
1422 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1423 assert.equal(componentsOf(harness.simulation, deerId).combat?.seekCover, true);
1424 }
1425 finally
1426 { harness.close(); }
1427});
1428
1429test("melee hit does not mark seekCover on a retaliating mob", () =>
1430{
1431 const random = Math.random;
1432 Math.random = () => 0;
1433 const harness = makeSimulation({ workerCount: 1 });
1434 try
1435 {
1436 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1437 const playerId = harness.simulation.spawnCharacter(1, character);
1438 const deerId = harness.simulation.spawnEntity(mobComponents({
1439 tileX: 9,
1440 tileY: 8,
1441 mobTypeId: MobId.deer,
1442 spawnerId: null
1443 }));
1444 const worker = workerOf(harness.simulation, playerId);
1445 const handle = worker.world.ecs.handleOf(playerId);
1446 const bag = harness.simulation.bagOf(playerId);
1447 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
1448 if (stickSlot >= 0)
1449 {
1450 harness.simulation.enqueue(1, {
1451 type: "equip-item",
1452 characterId: character.character_id,
1453 slotIndex: stickSlot
1454 });
1455 harness.simulation.step();
1456 }
1457 const profile = attackProfileOf(worker.world.ecs, handle);
1458 assert.equal(profile.mode, "melee");
1459 resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
1460 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1461 assert.equal(!!componentsOf(harness.simulation, deerId).combat?.seekCover, false);
1462 }
1463 finally
1464 {
1465 Math.random = random;
1466 harness.close();
1467 }
1468});
1469
1470test("seekCover mob flees to a no-LOS tile when melee approach is impossible", () =>
1471{
1472 const harness = makeSimulation({ workerCount: 1 });
1473 try
1474 {
1475 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1476 const playerId = harness.simulation.spawnCharacter(1, character);
1477 const deerId = harness.simulation.spawnEntity(mobComponents({
1478 tileX: 14,
1479 tileY: 8,
1480 mobTypeId: MobId.deer,
1481 spawnerId: null
1482 }));
1483 const worker = workerOf(harness.simulation, playerId);
1484 const world = worker.world;
1485 const data = world.chunkData(0, 0);
1486 const wall = { typeId: BlockType.stoneWall, state: null, config: null };
1487 const furnace = { typeId: BlockType.furnace, state: null, config: null };
1488 // Impassable stations around the player (do not block LOS) so no melee stand tile exists.
1489 for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]])
1490 { data.blocks[(8 + dy) * 16 + (8 + dx)] = furnace; }
1491 // Cover wall east of the approach.
1492 for (let y = 6; y <= 10; y++)
1493 { data.blocks[y * 16 + 12] = wall; }
1494
1495 assert.equal(hasCombatLineOfSight(world, 8, 8, 14, 8), false, "wall should block LOS east of the wall");
1496
1497 const deerHandle = world.ecs.handleOf(deerId);
1498 engageTarget(world.ecs, deerId, playerId);
1499 markSeekCover(world.ecs, deerId);
1500 const playerPos = world.ecs.get(world.ecs.handleOf(playerId), Component.position);
1501 teleportEntity(worker, deerId, 11, 8);
1502 assert.equal(hasCombatLineOfSight(world, 8, 8, 11, 8), true);
1503 queueMeleeApproach(world, deerId, deerHandle, world.ecs.get(deerHandle, Component.position), playerPos);
1504 const path = world.ecs.get(deerHandle, Component.path)?.tiles ?? [];
1505 assert.ok(path.length > 0, "expected a flee path into cover");
1506 const dest = path[path.length - 1];
1507 assert.equal(
1508 hasCombatLineOfSight(world, playerPos.tileX, playerPos.tileY, dest.x, dest.y),
1509 false,
1510 "flee destination must be out of player LOS"
1511 );
1512 }
1513 finally
1514 { harness.close(); }
1515});
1516
1517test("fairy flees to 2 tiles from hit source, then stops until hit again", () =>
1518{
1519 const harness = makeSimulation({ workerCount: 1 });
1520 try
1521 {
1522 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1523 const playerId = harness.simulation.spawnCharacter(1, character);
1524 const fairyId = harness.simulation.spawnEntity(mobComponents({
1525 tileX: 9,
1526 tileY: 8,
1527 mobTypeId: MobId.fairy,
1528 spawnerId: null
1529 }));
1530 const worker = workerOf(harness.simulation, fairyId);
1531 const world = worker.world;
1532 const fairyHandle = world.ecs.handleOf(fairyId);
1533
1534 applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
1535 const combat = world.ecs.get(fairyHandle, Component.combat);
1536 assert.equal(combat?.fleeFrom?.tileX, 8);
1537 assert.equal(combat?.fleeFrom?.tileY, 8);
1538 assert.equal(combat?.fleeFrom?.minDist, 2);
1539 assert.equal(combat?.targetEntityId, playerId);
1540
1541 stepCombat(world, Date.now());
1542 const path = world.ecs.get(fairyHandle, Component.path)?.tiles ?? [];
1543 assert.ok(path.length > 0, "fairy should path away while fleeing");
1544 const dest = path[path.length - 1];
1545 assert.ok(
1546 chebyshev(dest.x, dest.y, 8, 8) >= 2,
1547 `flee dest should be ≥2 from hit source, got ${dest.x},${dest.y}`
1548 );
1549
1550 teleportEntity(worker, fairyId, dest.x, dest.y);
1551 world.ecs.get(fairyHandle, Component.path).tiles = [];
1552 stepCombat(world, Date.now());
1553 assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom, null);
1554
1555 stepCombat(world, Date.now() + 5000);
1556 assert.equal(
1557 world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
1558 null,
1559 "no flee until hit again"
1560 );
1561
1562 teleportEntity(worker, fairyId, 9, 8);
1563 applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
1564 assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom?.minDist, 2);
1565
1566 teleportEntity(worker, fairyId, 12, 8);
1567 markFleeOnHit(world, fairyId, playerId);
1568 assert.equal(
1569 world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
1570 null,
1571 "already ≥2 tiles away does not start a flee"
1572 );
1573 }
1574 finally
1575 { harness.close(); }
1576});