BlueGit

timfa questward

Files

questward / server / tests / combat.test.js

combat.test.js

combat.test.js 36.3 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 { tierStatBonus, WoodTier } from "../../shared/definitions/materialTiers.js";
8import { BlockType, blockBlocksRangedAttacks } from "../../shared/definitions/tiles.js";
9import { Component } from "../src/ecs/components.js";
10import { tileKey } from "../src/world/coordinates.js";
11import { WorkerMessage } from "../src/simulation/protocol.js";
12import { tileToRegion } from "../src/world/coordinates.js";
13import { SkillId } from "../../shared/definitions/skills.js";
14import { totalXpForLevel } from "../../shared/skills/progression.js";
15import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight } from "../src/combat/service.js";
16import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
17
18function workerOf (simulation, entityId)
19{
20 const record = simulation.entityRecord(entityId);
21 assert.ok(record, "entity must be remembered");
22 return simulation.workers[record.workerId];
23}
24
25function componentsOf (simulation, entityId)
26{
27 const worker = workerOf(simulation, entityId);
28 const handle = worker.world.ecs.handleOf(entityId);
29 assert.ok(handle != null);
30 return worker.world.ecs.componentsOf(handle);
31}
32
33function teleportEntity (worker, entityId, tileX, tileY)
34{
35 const world = worker.world;
36 const handle = world.ecs.handleOf(entityId);
37 const pos = world.ecs.get(handle, Component.position);
38 const fromKey = tileKey(pos.tileX, pos.tileY);
39 const fromSet = world.occupancy.get(fromKey);
40 if (fromSet)
41 {
42 fromSet.delete(entityId);
43 if (fromSet.size === 0)
44 { world.occupancy.delete(fromKey); }
45 }
46 pos.tileX = tileX;
47 pos.tileY = tileY;
48 const toKey = tileKey(tileX, tileY);
49 let toSet = world.occupancy.get(toKey);
50 if (!toSet)
51 {
52 toSet = new Set();
53 world.occupancy.set(toKey, toSet);
54 }
55 toSet.add(entityId);
56}
57
58function entityIsAlive (simulation, entityId)
59{
60 const record = simulation.entityRecord(entityId);
61 if (!record)
62 { return false; }
63 const worker = simulation.workers[record.workerId];
64 const handle = worker.world.ecs.handleOf(entityId);
65 if (handle == null)
66 { return false; }
67 const health = worker.world.ecs.get(handle, Component.health);
68 return (health?.current ?? 0) > 0;
69}
70
71function simulateAttackClick (harness, character, targetEntityId)
72{
73 harness.simulation.enqueue(1, {
74 type: "attack",
75 characterId: character.character_id,
76 targetEntityId
77 });
78}
79
80/** Run ticks until one combatant dies or the step budget is exhausted. */
81function runCombatUntilOutcome (harness, playerId, deerId, maxSteps = 600)
82{
83 let swings = 0;
84 for (let i = 0; i < maxSteps; i++)
85 {
86 harness.advance(50);
87 const events = harness.simulation.step().events;
88 swings += events.filter((event) => event.type === "combat-swing").length;
89 const playerAlive = entityIsAlive(harness.simulation, playerId);
90 const deerAlive = entityIsAlive(harness.simulation, deerId);
91 if (!playerAlive || !deerAlive)
92 { return { playerAlive, deerAlive, swings, steps: i + 1 }; }
93 }
94 return {
95 playerAlive: entityIsAlive(harness.simulation, playerId),
96 deerAlive: entityIsAlive(harness.simulation, deerId),
97 swings,
98 steps: maxSteps
99 };
100}
101
102function withDeterministicCombat (fn)
103{
104 const random = Math.random;
105 Math.random = () => 0;
106 try
107 { fn(); }
108 finally
109 { Math.random = random; }
110}
111
112test("immortal deer auto-attacks until the player dies", () =>
113{
114 withDeterministicCombat(() =>
115 {
116 const harness = makeSimulation({ workerCount: 1 });
117 try
118 {
119 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
120 const playerId = harness.simulation.spawnCharacter(1, character);
121 const deerId = harness.simulation.spawnEntity(mobComponents({
122 tileX: 9,
123 tileY: 8,
124 mobTypeId: MobId.deer,
125 spawnerId: null
126 }));
127 const deer = componentsOf(harness.simulation, deerId);
128 deer.health.current = 1_000_000;
129 deer.health.max = 1_000_000;
130
131 simulateAttackClick(harness, character, deerId);
132 harness.simulation.step();
133
134 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
135 assert.ok(outcome.swings >= 2, `expected sustained auto-attack swings, got ${outcome.swings}`);
136 assert.equal(outcome.deerAlive, true, "immortal deer should survive");
137 assert.equal(outcome.playerAlive, false, "deer should kill the player via auto-attack");
138 assert.equal(
139 componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null,
140 null,
141 "deer should clear engage after the player dies"
142 );
143 }
144 finally
145 { harness.close(); }
146 });
147});
148
149test("immortal deer keeps auto-attacking after the player walks away", () =>
150{
151 withDeterministicCombat(() =>
152 {
153 const harness = makeSimulation({ workerCount: 1 });
154 try
155 {
156 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
157 const playerId = harness.simulation.spawnCharacter(1, character);
158 const deerId = harness.simulation.spawnEntity(mobComponents({
159 tileX: 9,
160 tileY: 8,
161 mobTypeId: MobId.deer,
162 spawnerId: null
163 }));
164 const deer = componentsOf(harness.simulation, deerId);
165 deer.health.current = 1_000_000;
166 deer.health.max = 1_000_000;
167
168 simulateAttackClick(harness, character, deerId);
169 harness.simulation.step();
170
171 // Let one exchange land, then cancel player engage by walking away (client moveTo).
172 for (let i = 0; i < 30; i++)
173 {
174 harness.advance(50);
175 const swings = harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
176 if (swings > 0)
177 { break; }
178 }
179 harness.simulation.enqueue(1, {
180 type: "move-to",
181 characterId: character.character_id,
182 tileX: 8,
183 tileY: 14
184 });
185 harness.simulation.step();
186 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
187 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
188
189 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
190 assert.ok(outcome.swings >= 1, `expected deer pursuit swings, got ${outcome.swings}`);
191 assert.equal(outcome.deerAlive, true);
192 assert.equal(outcome.playerAlive, false, "deer should chase and kill the player after walk-away");
193 }
194 finally
195 { harness.close(); }
196 });
197});
198
199test("cross-worker immortal deer auto-attacks until the player dies", () =>
200{
201 withDeterministicCombat(() =>
202 {
203 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
204 try
205 {
206 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
207 const playerId = harness.simulation.spawnCharacter(1, character);
208 const deerId = harness.simulation.spawnEntity(mobComponents({
209 tileX: 63,
210 tileY: 8,
211 mobTypeId: MobId.deer,
212 spawnerId: null
213 }));
214 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
215 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
216
217 const deerWorker = workerOf(harness.simulation, deerId);
218 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
219 const deerHealth = deerWorker.world.ecs.get(deerHandle, Component.health);
220 deerHealth.current = 1_000_000;
221 deerHealth.max = 1_000_000;
222
223 simulateAttackClick(harness, character, deerId);
224 const first = harness.simulation.step();
225 assert.equal(first.events.some((event) => event.type === "command-error"), false);
226
227 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
228 assert.ok(outcome.swings >= 2, `expected sustained cross-worker swings, got ${outcome.swings}`);
229 assert.equal(outcome.deerAlive, true);
230 assert.equal(outcome.playerAlive, false, "cross-worker deer should kill the player via auto-attack");
231 }
232 finally
233 { harness.close(); }
234 });
235});
236
237test("click attack from 5 tiles away ends with player or deer dead", () =>
238{
239 withDeterministicCombat(() =>
240 {
241 const harness = makeSimulation({ workerCount: 1 });
242 try
243 {
244 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
245 const playerId = harness.simulation.spawnCharacter(1, character);
246 const deerId = harness.simulation.spawnEntity(mobComponents({
247 tileX: 13,
248 tileY: 8,
249 mobTypeId: MobId.deer,
250 spawnerId: null
251 }));
252
253 simulateAttackClick(harness, character, deerId);
254 harness.simulation.step();
255
256 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
257 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
258 assert.ok(
259 !outcome.playerAlive || !outcome.deerAlive,
260 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
261 );
262 }
263 finally
264 { harness.close(); }
265 });
266});
267
268test("click attack while adjacent ends with player or deer dead", () =>
269{
270 withDeterministicCombat(() =>
271 {
272 const harness = makeSimulation({ workerCount: 1 });
273 try
274 {
275 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
276 const playerId = harness.simulation.spawnCharacter(1, character);
277 const deerId = harness.simulation.spawnEntity(mobComponents({
278 tileX: 9,
279 tileY: 8,
280 mobTypeId: MobId.deer,
281 spawnerId: null
282 }));
283
284 simulateAttackClick(harness, character, deerId);
285 harness.simulation.step();
286
287 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
288 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
289 assert.ok(
290 !outcome.playerAlive || !outcome.deerAlive,
291 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
292 );
293 }
294 finally
295 { harness.close(); }
296 });
297});
298
299test("cross-worker click attack from 5 tiles away ends with player or deer dead", () =>
300{
301 withDeterministicCombat(() =>
302 {
303 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
304 try
305 {
306 const character = makeCharacter(harness.stateDb, { tileX: 59, tileY: 8 });
307 const playerId = harness.simulation.spawnCharacter(1, character);
308 const deerId = harness.simulation.spawnEntity(mobComponents({
309 tileX: 64,
310 tileY: 8,
311 mobTypeId: MobId.deer,
312 spawnerId: null
313 }));
314 assert.equal(harness.simulation.entityRecord(playerId).workerId, 0);
315 assert.equal(harness.simulation.entityRecord(deerId).workerId, 1);
316
317 simulateAttackClick(harness, character, deerId);
318 const first = harness.simulation.step();
319 assert.equal(first.events.some((event) => event.type === "command-error"), false);
320
321 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
322 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
323 assert.ok(
324 !outcome.playerAlive || !outcome.deerAlive,
325 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
326 );
327 }
328 finally
329 { harness.close(); }
330 });
331});
332
333test("cross-worker adjacent click attack ends with player or deer dead", () =>
334{
335 withDeterministicCombat(() =>
336 {
337 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
338 try
339 {
340 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
341 const playerId = harness.simulation.spawnCharacter(1, character);
342 const deerId = harness.simulation.spawnEntity(mobComponents({
343 tileX: 63,
344 tileY: 8,
345 mobTypeId: MobId.deer,
346 spawnerId: null
347 }));
348 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
349 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
350
351 simulateAttackClick(harness, character, deerId);
352 const first = harness.simulation.step();
353 assert.equal(first.events.some((event) => event.type === "command-error"), false);
354
355 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
356 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
357 assert.ok(
358 !outcome.playerAlive || !outcome.deerAlive,
359 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
360 );
361 }
362 finally
363 { harness.close(); }
364 });
365});
366
367test("attack engages the attacker; target retaliates on first swing", () =>
368{
369 const harness = makeSimulation({ workerCount: 1 });
370 try
371 {
372 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
373 const playerId = harness.simulation.spawnCharacter(1, character);
374 // Deer are not aggressive — only retaliate after a real swing.
375 const deerId = harness.simulation.spawnEntity(mobComponents({
376 tileX: 12,
377 tileY: 8,
378 mobTypeId: MobId.deer,
379 spawnerId: null
380 }));
381
382 harness.simulation.enqueue(1, {
383 type: "attack",
384 characterId: character.character_id,
385 targetEntityId: deerId
386 });
387 harness.simulation.step();
388
389 assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, deerId);
390 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null, null);
391
392 let swung = false;
393 for (let i = 0; i < 80; i++)
394 {
395 harness.advance(50);
396 const events = harness.simulation.step().events;
397 if (events.some((event) => event.type === "combat-swing"))
398 {
399 swung = true;
400 break;
401 }
402 }
403 assert.ok(swung, "expected a melee swing once adjacent");
404 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
405 }
406 finally
407 { harness.close(); }
408});
409
410test("melee swing only resolves at Chebyshev distance 1", () =>
411{
412 const harness = makeSimulation({ workerCount: 1 });
413 try
414 {
415 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
416 const playerId = harness.simulation.spawnCharacter(1, character);
417 const bag = harness.simulation.bagOf(playerId);
418 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
419 assert.ok(stickSlot >= 0);
420 harness.simulation.enqueue(1, {
421 type: "equip-item",
422 characterId: character.character_id,
423 slotIndex: stickSlot
424 });
425 harness.simulation.step();
426 assert.equal(
427 harness.simulation.bagOf(playerId).equipment.slots[EQUIPMENT_SLOT.weapon]?.itemId,
428 ItemId.stick
429 );
430
431 const farRat = harness.simulation.spawnEntity(mobComponents({
432 tileX: 12,
433 tileY: 8,
434 mobTypeId: MobId.rat
435 }));
436 harness.simulation.enqueue(1, {
437 type: "attack",
438 characterId: character.character_id,
439 targetEntityId: farRat
440 });
441 const farEvents = harness.simulation.step().events;
442 assert.equal(farEvents.some((event) => event.type === "combat-swing"), false);
443
444 const nearRat = harness.simulation.spawnEntity(mobComponents({
445 tileX: 9,
446 tileY: 8,
447 mobTypeId: MobId.rat
448 }));
449 harness.simulation.enqueue(1, {
450 type: "attack",
451 characterId: character.character_id,
452 targetEntityId: nearRat
453 });
454 const nearEvents = harness.simulation.step().events;
455 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
456 assert.ok(nearEvents.some((event) =>
457 event.type === "combat-hit"
458 || event.type === "combat-miss"
459 || event.type === "combat-block"));
460 }
461 finally
462 { harness.close(); }
463});
464
465test("pigeons are untargetable free-flight and never get path tiles", () =>
466{
467 const harness = makeSimulation({ workerCount: 1 });
468 try
469 {
470 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
471 harness.simulation.spawnCharacter(1, character);
472 const pigeonId = harness.simulation.spawnEntity(mobComponents({
473 tileX: 10,
474 tileY: 8,
475 mobTypeId: MobId.pigeon
476 }));
477
478 const before = componentsOf(harness.simulation, pigeonId);
479 assert.equal(before.flight != null, true);
480 assert.equal(before.combat == null, true);
481 assert.deepEqual(before.path?.tiles ?? [], []);
482
483 harness.setNow(harness.now() + 500);
484 stepTimes(harness.simulation, 10);
485 const after = componentsOf(harness.simulation, pigeonId);
486 assert.deepEqual(after.path?.tiles ?? [], []);
487 assert.equal(after.flight != null, true);
488
489 harness.simulation.enqueue(1, {
490 type: "attack",
491 characterId: character.character_id,
492 targetEntityId: pigeonId
493 });
494 const result = harness.simulation.step();
495 assert.ok(result.events.some((event) => event.type === "command-error"));
496 assert.equal(componentsOf(harness.simulation, pigeonId).path?.tiles?.length ?? 0, 0);
497 }
498 finally
499 { harness.close(); }
500});
501
502test("deer retaliate when attacked", () =>
503{
504 const harness = makeSimulation({ workerCount: 1 });
505 try
506 {
507 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
508 const playerId = harness.simulation.spawnCharacter(1, character);
509 const deerId = harness.simulation.spawnEntity(mobComponents({
510 tileX: 9,
511 tileY: 8,
512 mobTypeId: MobId.deer,
513 spawnerId: null
514 }));
515
516 harness.simulation.enqueue(1, {
517 type: "attack",
518 characterId: character.character_id,
519 targetEntityId: deerId
520 });
521 const events = harness.simulation.step().events;
522 assert.ok(events.some((event) => event.type === "combat-swing"));
523
524 const deer = componentsOf(harness.simulation, deerId);
525 assert.equal(deer.combat?.targetEntityId, playerId);
526 assert.ok(deer.skills?.levels?.unarmed >= 1);
527 }
528 finally
529 { harness.close(); }
530});
531
532test("aggressive rats engage players within aggro range and LOS", () =>
533{
534 const harness = makeSimulation({ workerCount: 1 });
535 try
536 {
537 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
538 const playerId = harness.simulation.spawnCharacter(1, character);
539 const ratId = harness.simulation.spawnEntity(mobComponents({
540 tileX: 12,
541 tileY: 8,
542 mobTypeId: MobId.rat,
543 spawnerId: null
544 }));
545
546 harness.simulation.step();
547 assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);
548 }
549 finally
550 { harness.close(); }
551});
552
553test("players retaliate when a mob swings at them", () =>
554{
555 const harness = makeSimulation({ workerCount: 1 });
556 try
557 {
558 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
559 const playerId = harness.simulation.spawnCharacter(1, character);
560 const ratId = harness.simulation.spawnEntity(mobComponents({
561 tileX: 9,
562 tileY: 8,
563 mobTypeId: MobId.rat,
564 spawnerId: null
565 }));
566
567 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
568
569 let swung = false;
570 for (let i = 0; i < 80; i++)
571 {
572 harness.advance(50);
573 const events = harness.simulation.step().events;
574 if (events.some((event) =>
575 event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
576 ))
577 {
578 swung = true;
579 break;
580 }
581 }
582 assert.ok(swung, "expected the rat to swing at the player");
583 assert.equal(
584 componentsOf(harness.simulation, playerId).combat?.targetEntityId,
585 ratId,
586 "player should auto-retaliate after the mob swing"
587 );
588 }
589 finally
590 { harness.close(); }
591});
592
593test("aggressive rats do not aggro through walls or beyond range", () =>
594{
595 const harness = makeSimulation({ workerCount: 1 });
596 try
597 {
598 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
599 const playerId = harness.simulation.spawnCharacter(1, character);
600 const record = harness.simulation.entityRecord(playerId);
601 const worker = harness.simulation.workers[record.workerId];
602
603 const blockedRat = harness.simulation.spawnEntity(mobComponents({
604 tileX: 12,
605 tileY: 8,
606 mobTypeId: MobId.rat,
607 spawnerId: null
608 }));
609 const data = worker.world.chunkData(0, 0);
610 data.blocks[8 * 16 + 10] = { typeId: BlockType.stoneWall, state: null, config: null };
611
612 const farRat = harness.simulation.spawnEntity(mobComponents({
613 tileX: 14,
614 tileY: 8,
615 mobTypeId: MobId.rat,
616 spawnerId: null
617 }));
618
619 harness.simulation.step();
620 assert.equal(componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null, null);
621 assert.equal(componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null, null);
622 }
623 finally
624 { harness.close(); }
625});
626
627test("crafting stations and tables do not block ranged or spell line of sight", () =>
628{
629 assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
630 assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
631 assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
632 assert.equal(blockBlocksRangedAttacks(null), false);
633
634 const harness = makeSimulation({ workerCount: 1 });
635 try
636 {
637 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
638 const playerId = harness.simulation.spawnCharacter(1, character);
639 const worker = workerOf(harness.simulation, playerId);
640 const data = worker.world.chunkData(0, 0);
641 const blockIndex = (localY, localX) => localY * 16 + localX;
642
643 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
644 assert.equal(
645 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
646 true,
647 "furnace between caster and target should not block"
648 );
649
650 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
651 assert.equal(
652 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
653 true,
654 "table between caster and target should not block"
655 );
656
657 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
658 assert.equal(
659 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
660 false,
661 "stone wall should still block"
662 );
663 }
664 finally
665 { harness.close(); }
666});
667
668test("attacker keeps pursuing and can swing after the target moves", () =>
669{
670 const harness = makeSimulation({ workerCount: 1 });
671 try
672 {
673 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
674 const playerId = harness.simulation.spawnCharacter(1, character);
675 const ratId = harness.simulation.spawnEntity(mobComponents({
676 tileX: 12,
677 tileY: 8,
678 mobTypeId: MobId.rat,
679 spawnerId: null
680 }));
681
682 harness.simulation.enqueue(1, {
683 type: "attack",
684 characterId: character.character_id,
685 targetEntityId: ratId
686 });
687 harness.simulation.step();
688
689 const worker = workerOf(harness.simulation, playerId);
690 stepTimes(harness.simulation, 4);
691 teleportEntity(worker, ratId, 12, 10);
692
693 let swings = 0;
694 for (let i = 0; i < 120; i++)
695 {
696 const events = harness.simulation.step().events;
697 swings += events.filter((event) => event.type === "combat-swing").length;
698 if (swings > 0)
699 { break; }
700 }
701
702 assert.ok(swings >= 1);
703 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, ratId);
704 }
705 finally
706 { harness.close(); }
707});
708
709test("combatants keep auto-attacking while adjacent", () =>
710{
711 const harness = makeSimulation({ workerCount: 1 });
712 try
713 {
714 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
715 const playerId = harness.simulation.spawnCharacter(1, character);
716 const deerId = harness.simulation.spawnEntity(mobComponents({
717 tileX: 9,
718 tileY: 8,
719 mobTypeId: MobId.deer,
720 spawnerId: null
721 }));
722
723 harness.simulation.enqueue(1, {
724 type: "attack",
725 characterId: character.character_id,
726 targetEntityId: deerId
727 });
728 harness.simulation.step();
729
730 let swings = 0;
731 for (let i = 0; i < 50; i++)
732 {
733 harness.advance(50);
734 const events = harness.simulation.step().events;
735 swings += events.filter((event) => event.type === "combat-swing").length;
736 const player = componentsOf(harness.simulation, playerId);
737 const deer = componentsOf(harness.simulation, deerId);
738 if (swings >= 4
739 && player.combat?.targetEntityId === deerId
740 && deer.combat?.targetEntityId === playerId
741 && (player.health?.current ?? 0) > 0)
742 { break; }
743 }
744
745 assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
746 const player = componentsOf(harness.simulation, playerId);
747 const deer = componentsOf(harness.simulation, deerId);
748 assert.ok((player.health?.current ?? 0) > 0, "player should still be alive during sustained combat");
749 assert.equal(player.combat?.targetEntityId, deerId);
750 assert.equal(deer.combat?.targetEntityId, playerId);
751 }
752 finally
753 { harness.close(); }
754});
755
756test("cross-worker adjacent combat keeps engaging and swinging", () =>
757{
758 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
759 try
760 {
761 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
762 const playerId = harness.simulation.spawnCharacter(1, character);
763 const deerId = harness.simulation.spawnEntity(mobComponents({
764 tileX: 63,
765 tileY: 8,
766 mobTypeId: MobId.deer,
767 spawnerId: null
768 }));
769 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
770 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
771
772 harness.simulation.enqueue(1, {
773 type: "attack",
774 characterId: character.character_id,
775 targetEntityId: deerId
776 });
777 const first = harness.simulation.step();
778 assert.equal(first.events.some((event) => event.type === "command-error"), false);
779
780 const random = Math.random;
781 Math.random = () => 0;
782 try
783 {
784 let swings = 0;
785 for (let i = 0; i < 40; i++)
786 {
787 harness.advance(50);
788 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
789 if (swings >= 4)
790 { break; }
791 }
792
793 assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
794 const deerWorker = harness.simulation.workers[0];
795 const playerWorker = harness.simulation.workers[1];
796 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
797 const playerHandle = playerWorker.world.ecs.handleOf(playerId);
798 const deerCombat = deerWorker.world.ecs.get(deerHandle, Component.combat);
799 const playerCombat = playerWorker.world.ecs.get(playerHandle, Component.combat);
800 const playerHealth = playerWorker.world.ecs.get(playerHandle, Component.health);
801 assert.ok((playerHealth?.current ?? 0) > 0, "player should survive sustained cross-worker combat");
802 assert.equal(deerCombat?.targetEntityId, playerId);
803 assert.equal(playerCombat?.targetEntityId, deerId);
804 }
805 finally
806 { Math.random = random; }
807 }
808 finally
809 { harness.close(); }
810});
811
812test("cancel attack stops the player but the mob keeps pursuing", () =>
813{
814 const harness = makeSimulation({ workerCount: 1 });
815 try
816 {
817 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
818 const playerId = harness.simulation.spawnCharacter(1, character);
819 const ratId = harness.simulation.spawnEntity(mobComponents({
820 tileX: 9,
821 tileY: 8,
822 mobTypeId: MobId.rat,
823 spawnerId: null
824 }));
825
826 harness.simulation.enqueue(1, {
827 type: "attack",
828 characterId: character.character_id,
829 targetEntityId: ratId
830 });
831 harness.simulation.step();
832
833 harness.simulation.enqueue(1, {
834 type: "cancel-attack",
835 characterId: character.character_id
836 });
837 harness.simulation.step();
838
839 const player = componentsOf(harness.simulation, playerId);
840 const rat = componentsOf(harness.simulation, ratId);
841 assert.equal(player.combat?.targetEntityId, null);
842 assert.equal(rat.combat?.targetEntityId, playerId);
843 }
844 finally
845 { harness.close(); }
846});
847
848test("player combat and skills components are present on spawn", () =>
849{
850 const harness = makeSimulation({ workerCount: 1 });
851 try
852 {
853 const character = makeCharacter(harness.stateDb);
854 const playerId = harness.simulation.spawnCharacter(1, character);
855 const comps = componentsOf(harness.simulation, playerId);
856 assert.ok(comps.combat);
857 assert.equal(comps.skills?.xp?.clubfighting, 0);
858 assert.ok(comps.health);
859 }
860 finally
861 { harness.close(); }
862});
863
864test("mobs heal to full when their region unloads", () =>
865{
866 const harness = makeSimulation({ workerCount: 1 });
867 try
868 {
869 const ratId = harness.simulation.spawnEntity(mobComponents({
870 tileX: 8,
871 tileY: 8,
872 mobTypeId: MobId.rat
873 }));
874 const worker = workerOf(harness.simulation, ratId);
875 const handle = worker.world.ecs.handleOf(ratId);
876 worker.world.ecs.get(handle, Component.health).current = 2;
877 const result = worker.call({
878 type: WorkerMessage.dropRegion,
879 regionX: tileToRegion(8),
880 regionY: tileToRegion(8)
881 });
882 const record = result.dropped.find((entry) => entry.entityId === ratId);
883 assert.ok(record);
884 assert.equal(
885 record.payload.components.health.current,
886 record.payload.components.health.max
887 );
888 }
889 finally
890 { harness.close(); }
891});
892
893test("taking damage awards Health XP equal to damage dealt", () =>
894{
895 const harness = makeSimulation({ workerCount: 1 });
896 const random = Math.random;
897 Math.random = () => 0;
898 try
899 {
900 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
901 const playerId = harness.simulation.spawnCharacter(1, character);
902 const ratId = harness.simulation.spawnEntity(mobComponents({
903 mobTypeId: MobId.rat,
904 tileX: 9,
905 tileY: 8
906 }));
907 const worker = harness.simulation.workers[0];
908 const playerHandle = worker.world.ecs.handleOf(playerId);
909 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
910 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
911 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
912 const hit = events.find((event) => event.type === "combat-hit");
913 assert.ok(hit);
914 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
915 assert.ok(updated);
916 assert.equal(updated.stored[SkillId.health] - before, hit.damage);
917 }
918 finally
919 {
920 Math.random = random;
921 harness.close();
922 }
923});
924
925test("lethal damage awards no Health XP", () =>
926{
927 const harness = makeSimulation({ workerCount: 1 });
928 const random = Math.random;
929 Math.random = () => 0;
930 try
931 {
932 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
933 const playerId = harness.simulation.spawnCharacter(1, character);
934 const ratId = harness.simulation.spawnEntity(mobComponents({
935 mobTypeId: MobId.rat,
936 tileX: 9,
937 tileY: 8
938 }));
939 const worker = harness.simulation.workers[0];
940 const playerHandle = worker.world.ecs.handleOf(playerId);
941 const health = worker.world.ecs.get(playerHandle, Component.health);
942 health.current = 1;
943 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
944 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
945 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
946 const hit = events.find((event) => event.type === "combat-hit");
947 assert.ok(hit);
948 assert.ok(hit.damage >= 1);
949 assert.equal(hit.health, 0);
950 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
951 assert.equal(updated, undefined);
952 assert.equal(worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health], before);
953 }
954 finally
955 {
956 Math.random = random;
957 harness.close();
958 }
959});
960
961test("dodging a hit awards Agility XP equal to avoided damage", () =>
962{
963 const harness = makeSimulation({ workerCount: 1 });
964 let roll = 0;
965 const seq = [0, 0.5, 0];
966 const random = Math.random;
967 Math.random = () => seq[roll++ % seq.length];
968 try
969 {
970 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
971 const playerId = harness.simulation.spawnCharacter(1, character);
972 const ratId = harness.simulation.spawnEntity(mobComponents({
973 mobTypeId: MobId.rat,
974 tileX: 9,
975 tileY: 8
976 }));
977 const worker = harness.simulation.workers[0];
978 const playerHandle = worker.world.ecs.handleOf(playerId);
979 const skills = worker.world.ecs.get(playerHandle, Component.skills);
980 skills.xp[SkillId.agility] = totalXpForLevel(10);
981 const before = skills.xp[SkillId.agility] | 0;
982 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
983 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
984 assert.ok(events.find((event) => event.type === "combat-miss"));
985 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
986 assert.ok(updated);
987 assert.equal(updated.stored[SkillId.agility] - before, 1);
988 }
989 finally
990 {
991 Math.random = random;
992 harness.close();
993 }
994});
995
996test("blocking a hit awards Defence XP equal to avoided damage", () =>
997{
998 const harness = makeSimulation({ workerCount: 1 });
999 let roll = 0;
1000 const seq = [0.9, 0, 0, 0.9];
1001 const random = Math.random;
1002 Math.random = () => seq[roll++ % seq.length];
1003 try
1004 {
1005 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1006 const playerId = harness.simulation.spawnCharacter(1, character);
1007 const ratId = harness.simulation.spawnEntity(mobComponents({
1008 mobTypeId: MobId.rat,
1009 tileX: 9,
1010 tileY: 8
1011 }));
1012 const worker = harness.simulation.workers[0];
1013 const playerHandle = worker.world.ecs.handleOf(playerId);
1014 const skills = worker.world.ecs.get(playerHandle, Component.skills);
1015 skills.xp[SkillId.defence] = totalXpForLevel(10);
1016 const before = skills.xp[SkillId.defence] | 0;
1017 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
1018 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
1019 assert.ok(events.find((event) => event.type === "combat-block"));
1020 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
1021 assert.ok(updated);
1022 assert.equal(updated.stored[SkillId.defence] - before, 1);
1023 }
1024 finally
1025 {
1026 Math.random = random;
1027 harness.close();
1028 }
1029});
1030
1031test("stacked combatants against the same target spread to different tiles", () =>
1032{
1033 const harness = makeSimulation({ workerCount: 1 });
1034 try
1035 {
1036 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1037 const playerId = harness.simulation.spawnCharacter(1, character);
1038 const rat1 = harness.simulation.spawnEntity(mobComponents({
1039 tileX: 9,
1040 tileY: 8,
1041 mobTypeId: MobId.rat,
1042 spawnerId: null
1043 }));
1044 const rat2 = harness.simulation.spawnEntity(mobComponents({
1045 tileX: 9,
1046 tileY: 7,
1047 mobTypeId: MobId.rat,
1048 spawnerId: null
1049 }));
1050 const worker = workerOf(harness.simulation, playerId);
1051 teleportEntity(worker, rat2, 9, 8);
1052
1053 for (let i = 0; i < 200; i++)
1054 {
1055 harness.advance(50);
1056 harness.simulation.step();
1057 }
1058
1059 const pos1 = componentsOf(harness.simulation, rat1).position;
1060 const pos2 = componentsOf(harness.simulation, rat2).position;
1061 assert.notEqual(
1062 `${pos1.tileX},${pos1.tileY}`,
1063 `${pos2.tileX},${pos2.tileY}`,
1064 "expected stacked rats to spread apart"
1065 );
1066 assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
1067 assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
1068 }
1069 finally
1070 { harness.close(); }
1071});
1072
1073test("approaching combatants pick different adjacent goals", () =>
1074{
1075 const harness = makeSimulation({ workerCount: 1 });
1076 try
1077 {
1078 const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
1079 const playerId = harness.simulation.spawnCharacter(1, character);
1080 const rat1 = harness.simulation.spawnEntity(mobComponents({
1081 tileX: 6,
1082 tileY: 8,
1083 mobTypeId: MobId.rat,
1084 spawnerId: null
1085 }));
1086 const rat2 = harness.simulation.spawnEntity(mobComponents({
1087 tileX: 6,
1088 tileY: 7,
1089 mobTypeId: MobId.rat,
1090 spawnerId: null
1091 }));
1092 const worker = workerOf(harness.simulation, playerId);
1093 teleportEntity(worker, rat2, 6, 8);
1094
1095 for (let i = 0; i < 120; i++)
1096 {
1097 harness.advance(50);
1098 harness.simulation.step();
1099 }
1100
1101 const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
1102 const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
1103 const goal1 = path1[path1.length - 1];
1104 const goal2 = path2[path2.length - 1];
1105 if (goal1 && goal2)
1106 {
1107 assert.notEqual(
1108 `${goal1.x},${goal1.y}`,
1109 `${goal2.x},${goal2.y}`,
1110 "expected different approach goals"
1111 );
1112 }
1113
1114 const pos1 = componentsOf(harness.simulation, rat1).position;
1115 const pos2 = componentsOf(harness.simulation, rat2).position;
1116 assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
1117 }
1118 finally
1119 { harness.close(); }
1120});
1121
1122test("humanoid attackers add equipment bonuses on top of spawner level", () =>
1123{
1124 const harness = makeSimulation({ workerCount: 1 });
1125 const random = Math.random;
1126 /** Max every skill roll so damage equals effective damage skill. */
1127 Math.random = () => 0.999999;
1128 try
1129 {
1130 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1131 const playerId = harness.simulation.spawnCharacter(1, character);
1132 const player = componentsOf(harness.simulation, playerId);
1133 player.skills.xp[SkillId.agility] = 0;
1134 player.skills.xp[SkillId.defence] = 0;
1135
1136 const level = 5;
1137 const npcId = harness.simulation.spawnEntity(mobComponents({
1138 tileX: 9,
1139 tileY: 8,
1140 mobTypeId: MobId.humanoid,
1141 level,
1142 displayName: "Guard",
1143 sex: "male",
1144 equipment: {
1145 weapon: WoodItemId.oakQuarterstaff
1146 }
1147 }));
1148 const worker = workerOf(harness.simulation, npcId);
1149 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(npcId));
1150 assert.equal(profile.mobAttackSkill, level);
1151 assert.equal(profile.damageSkillId, SkillId.strength);
1152
1153 const events = resolveMeleeSwing(worker.world, npcId, playerId, profile, Date.now());
1154 const hit = events.find((event) => event.type === "combat-hit");
1155 assert.ok(hit, "expected a hit");
1156 assert.equal(hit.damage, level + tierStatBonus(WoodTier.oak));
1157 }
1158 finally
1159 {
1160 Math.random = random;
1161 harness.close();
1162 }
1163});