BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

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