BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

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