BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

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