Add spawner bounty, town guards, levels, and mob spell combat.
Spawners can set bounty (awarded on kill), level (skills/HP/hover Lv.N name), and known spells with cast chances. Town Guard spawners send guards when bounty is earned nearby and escalate when a guard dies. Humanoids fight back; mobs use melee, ranged (infinite ammo), or spells depending on gear.
@@ -9,6 +9,7 @@ import {
9
9
isCentralExchangeSpawner,
10
10
spawnerEquipmentSlot
11
11
} from "/shared/definitions/mobs.js";
12
import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";
12
13
import { centralExchangeStaffCount } from "/shared/market/exchange.js";
13
14
import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js";
14
15
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
@@ -91,9 +92,11 @@ export function initTileConfigModal ({ onSave, onRemove })
91
92
let context = null;
92
93
/** @type {{ itemId: number, quantity: number }[]} */
93
94
let sellsDraft = [];
95
/** @type {{ spellId: string, chance: number }[]} */
96
let spellsDraft = [];
94
97
/** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
95
98
let equipmentDraft = {};
96
/** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */
99
/** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
97
100
let itemSearchMode = null;
98
101
/** @type {string|null} */
99
102
let dyeEditSlot = null;
@@ -496,6 +499,128 @@ export function initTileConfigModal ({ onSave, onRemove })
496
499
{ maxAlive.disabled = false; }
497
500
}
498
501
502
function syncSpellsSection (config)
503
{
504
form.querySelector("[data-spells]")?.remove();
505
form.append(renderSpellsFields(config));
506
}
507
508
function renderSpellsFields (config)
509
{
510
const wrap = document.createElement("div");
511
wrap.className = "spawner-spells-fields";
512
wrap.dataset.spells = "1";
513
514
const header = document.createElement("div");
515
header.className = "spawner-sells-header";
516
const titleEl = document.createElement("strong");
517
titleEl.textContent = "Spells";
518
const addBtn = document.createElement("button");
519
addBtn.type = "button";
520
addBtn.textContent = "+";
521
addBtn.title = "Add spell";
522
addBtn.addEventListener("click", () =>
523
{
524
const available = Object.values(SPELL_DEFINITIONS).find((def) =>
525
!spellsDraft.some((line) => line.spellId === def.spellId));
526
if (!available)
527
{ return; }
528
spellsDraft.push({ spellId: available.spellId, chance: 100 });
529
renderSpellsList();
530
});
531
header.append(titleEl, addBtn);
532
wrap.append(header);
533
534
const list = document.createElement("div");
535
list.className = "spawner-sells-list";
536
list.dataset.spellsList = "1";
537
wrap.append(list);
538
539
const hint = document.createElement("p");
540
hint.className = "hint";
541
hint.textContent = "Chance is the % roll when the mob picks that spell to cast. Only Attack (entity) spells are used in combat. Mobs only learn spells their Level can cast.";
542
wrap.append(hint);
543
544
if (!Array.isArray(spellsDraft) || !spellsDraft.length)
545
{
546
spellsDraft = (config?.spells ?? []).map((line) => ({
547
spellId: String(line.spellId ?? ""),
548
chance: Math.max(0, Math.min(100, Number(line.chance) || 0)) | 0
549
})).filter((line) => line.spellId);
550
}
551
queueMicrotask(() => renderSpellsList());
552
return wrap;
553
}
554
555
function renderSpellsList ()
556
{
557
const list = form.querySelector("[data-spells-list]");
558
if (!list)
559
{ return; }
560
list.replaceChildren();
561
if (!spellsDraft.length)
562
{
563
const empty = document.createElement("p");
564
empty.className = "hint";
565
empty.textContent = "No spells.";
566
list.append(empty);
567
return;
568
}
569
const level = Math.max(1, Number(form.querySelector('[name="level"]')?.value) || 1) | 0;
570
for (let index = 0; index < spellsDraft.length; index++)
571
{
572
const line = spellsDraft[index];
573
const def = SPELL_DEFINITIONS[line.spellId];
574
const row = document.createElement("div");
575
row.className = "spawner-sell-row";
576
577
const select = document.createElement("select");
578
for (const spell of Object.values(SPELL_DEFINITIONS))
579
{
580
const opt = document.createElement("option");
581
opt.value = spell.spellId;
582
const minLv = spell.minMagicLevel | 0 || 1;
583
opt.textContent = `${spell.displayName} (Magic ${minLv}+)`;
584
if (spell.spellId === line.spellId)
585
{ opt.selected = true; }
586
select.append(opt);
587
}
588
select.addEventListener("change", () =>
589
{
590
spellsDraft[index].spellId = select.value;
591
renderSpellsList();
592
});
593
594
const chance = document.createElement("input");
595
chance.type = "number";
596
chance.min = "0";
597
chance.max = "100";
598
chance.value = String(line.chance);
599
chance.title = "Cast chance %";
600
chance.addEventListener("change", () =>
601
{
602
spellsDraft[index].chance = Math.max(0, Math.min(100, Number(chance.value) || 0)) | 0;
603
});
604
605
const minLv = def?.minMagicLevel | 0 || 1;
606
const status = document.createElement("span");
607
status.className = "hint";
608
status.textContent = level < minLv ? `needs Lv.${minLv}` : `${line.chance}%`;
609
610
const remove = document.createElement("button");
611
remove.type = "button";
612
remove.textContent = "×";
613
remove.addEventListener("click", () =>
614
{
615
spellsDraft.splice(index, 1);
616
renderSpellsList();
617
});
618
619
row.append(select, chance, status, remove);
620
list.append(row);
621
}
622
}
623
499
624
function openSpawner (ctx)
500
625
{
501
626
context = { kind: "spawner", ...ctx };
@@ -505,6 +630,8 @@ export function initTileConfigModal ({ onSave, onRemove })
505
630
const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
506
631
form.append(
507
632
mobField,
633
field("Level", numberInput("level", config.level ?? 1, 1, 99)),
634
field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),
508
635
field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
509
636
field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
510
637
field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
@@ -521,6 +648,7 @@ export function initTileConfigModal ({ onSave, onRemove })
521
648
};
522
649
spawnInput.addEventListener("input", syncWanderMin);
523
650
syncWanderMin();
651
form.querySelector('[name="level"]')?.addEventListener("input", () => renderSpellsList());
524
652
form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>
525
653
{
526
654
const nextType = form.querySelector('[name="mobTypeId"]').value;
@@ -528,10 +656,18 @@ export function initTileConfigModal ({ onSave, onRemove })
528
656
form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);
529
657
form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);
530
658
form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);
659
form.querySelector('[name="level"]').value = String(defaults.level ?? 1);
660
form.querySelector('[name="bounty"]').value = String(defaults.bounty ?? 0);
531
661
syncWanderMin();
532
662
syncHumanoidSection(defaults);
663
syncSpellsSection(defaults);
533
664
});
665
spellsDraft = (config.spells ?? []).map((line) => ({
666
spellId: String(line.spellId ?? ""),
667
chance: Math.max(0, Math.min(100, Number(line.chance) || 0)) | 0
668
})).filter((line) => line.spellId);
534
669
syncHumanoidSection(config);
670
syncSpellsSection(config);
535
671
show(true);
536
672
}
537
673
@@ -573,11 +709,14 @@ export function initTileConfigModal ({ onSave, onRemove })
573
709
maxAlive: Number(data.get("maxAlive") || 3),
574
710
spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
575
711
maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
712
level: Number(data.get("level") || 1),
713
bounty: Number(data.get("bounty") || 0),
576
714
spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
577
715
sex: String(data.get("sex") || "male"),
578
716
displayName: String(data.get("displayName") || ""),
579
717
equipment,
580
718
sells: sellsDraft,
719
spells: spellsDraft,
581
720
buysItems: data.get("buysItems") === "on",
582
721
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
583
722
centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
@@ -9,6 +9,7 @@ import {9
isCentralExchangeSpawner,9
isCentralExchangeSpawner,10
spawnerEquipmentSlot10
spawnerEquipmentSlot11
} from "/shared/definitions/mobs.js";11
} from "/shared/definitions/mobs.js";12
import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";12
import { centralExchangeStaffCount } from "/shared/market/exchange.js";13
import { centralExchangeStaffCount } from "/shared/market/exchange.js";13
import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js";14
import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js";14
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";15
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";@@ -91,9 +92,11 @@ export function initTileConfigModal ({ onSave, onRemove })91
let context = null;92
let context = null;92
/** @type {{ itemId: number, quantity: number }[]} */93
/** @type {{ itemId: number, quantity: number }[]} */93
let sellsDraft = [];94
let sellsDraft = [];95
/** @type {{ spellId: string, chance: number }[]} */96
let spellsDraft = [];94
/** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */97
/** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */95
let equipmentDraft = {};98
let equipmentDraft = {};96
/** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */99
/** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */97
let itemSearchMode = null;100
let itemSearchMode = null;98
/** @type {string|null} */101
/** @type {string|null} */99
let dyeEditSlot = null;102
let dyeEditSlot = null;@@ -496,6 +499,128 @@ export function initTileConfigModal ({ onSave, onRemove })496
{ maxAlive.disabled = false; }499
{ maxAlive.disabled = false; }497
}500
}498
501
502
function syncSpellsSection (config)503
{504
form.querySelector("[data-spells]")?.remove();505
form.append(renderSpellsFields(config));506
}507
508
function renderSpellsFields (config)509
{510
const wrap = document.createElement("div");511
wrap.className = "spawner-spells-fields";512
wrap.dataset.spells = "1";513
514
const header = document.createElement("div");515
header.className = "spawner-sells-header";516
const titleEl = document.createElement("strong");517
titleEl.textContent = "Spells";518
const addBtn = document.createElement("button");519
addBtn.type = "button";520
addBtn.textContent = "+";521
addBtn.title = "Add spell";522
addBtn.addEventListener("click", () =>523
{524
const available = Object.values(SPELL_DEFINITIONS).find((def) =>525
!spellsDraft.some((line) => line.spellId === def.spellId));526
if (!available)527
{ return; }528
spellsDraft.push({ spellId: available.spellId, chance: 100 });529
renderSpellsList();530
});531
header.append(titleEl, addBtn);532
wrap.append(header);533
534
const list = document.createElement("div");535
list.className = "spawner-sells-list";536
list.dataset.spellsList = "1";537
wrap.append(list);538
539
const hint = document.createElement("p");540
hint.className = "hint";541
hint.textContent = "Chance is the % roll when the mob picks that spell to cast. Only Attack (entity) spells are used in combat. Mobs only learn spells their Level can cast.";542
wrap.append(hint);543
544
if (!Array.isArray(spellsDraft) || !spellsDraft.length)545
{546
spellsDraft = (config?.spells ?? []).map((line) => ({547
spellId: String(line.spellId ?? ""),548
chance: Math.max(0, Math.min(100, Number(line.chance) || 0)) | 0549
})).filter((line) => line.spellId);550
}551
queueMicrotask(() => renderSpellsList());552
return wrap;553
}554
555
function renderSpellsList ()556
{557
const list = form.querySelector("[data-spells-list]");558
if (!list)559
{ return; }560
list.replaceChildren();561
if (!spellsDraft.length)562
{563
const empty = document.createElement("p");564
empty.className = "hint";565
empty.textContent = "No spells.";566
list.append(empty);567
return;568
}569
const level = Math.max(1, Number(form.querySelector('[name="level"]')?.value) || 1) | 0;570
for (let index = 0; index < spellsDraft.length; index++)571
{572
const line = spellsDraft[index];573
const def = SPELL_DEFINITIONS[line.spellId];574
const row = document.createElement("div");575
row.className = "spawner-sell-row";576
577
const select = document.createElement("select");578
for (const spell of Object.values(SPELL_DEFINITIONS))579
{580
const opt = document.createElement("option");581
opt.value = spell.spellId;582
const minLv = spell.minMagicLevel | 0 || 1;583
opt.textContent = `${spell.displayName} (Magic ${minLv}+)`;584
if (spell.spellId === line.spellId)585
{ opt.selected = true; }586
select.append(opt);587
}588
select.addEventListener("change", () =>589
{590
spellsDraft[index].spellId = select.value;591
renderSpellsList();592
});593
594
const chance = document.createElement("input");595
chance.type = "number";596
chance.min = "0";597
chance.max = "100";598
chance.value = String(line.chance);599
chance.title = "Cast chance %";600
chance.addEventListener("change", () =>601
{602
spellsDraft[index].chance = Math.max(0, Math.min(100, Number(chance.value) || 0)) | 0;603
});604
605
const minLv = def?.minMagicLevel | 0 || 1;606
const status = document.createElement("span");607
status.className = "hint";608
status.textContent = level < minLv ? `needs Lv.${minLv}` : `${line.chance}%`;609
610
const remove = document.createElement("button");611
remove.type = "button";612
remove.textContent = "×";613
remove.addEventListener("click", () =>614
{615
spellsDraft.splice(index, 1);616
renderSpellsList();617
});618
619
row.append(select, chance, status, remove);620
list.append(row);621
}622
}623
499
function openSpawner (ctx)624
function openSpawner (ctx)500
{625
{501
context = { kind: "spawner", ...ctx };626
context = { kind: "spawner", ...ctx };@@ -505,6 +630,8 @@ export function initTileConfigModal ({ onSave, onRemove })505
const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));630
const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));506
form.append(631
form.append(507
mobField,632
mobField,633
field("Level", numberInput("level", config.level ?? 1, 1, 99)),634
field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)),508
field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),635
field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),509
field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),636
field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),510
field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),637
field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),@@ -521,6 +648,7 @@ export function initTileConfigModal ({ onSave, onRemove })521
};648
};522
spawnInput.addEventListener("input", syncWanderMin);649
spawnInput.addEventListener("input", syncWanderMin);523
syncWanderMin();650
syncWanderMin();651
form.querySelector('[name="level"]')?.addEventListener("input", () => renderSpellsList());524
form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>652
form.querySelector('[name="mobTypeId"]').addEventListener("change", () =>525
{653
{526
const nextType = form.querySelector('[name="mobTypeId"]').value;654
const nextType = form.querySelector('[name="mobTypeId"]').value;@@ -528,10 +656,18 @@ export function initTileConfigModal ({ onSave, onRemove })528
form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);656
form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive);529
form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);657
form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles);530
form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);658
form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles);659
form.querySelector('[name="level"]').value = String(defaults.level ?? 1);660
form.querySelector('[name="bounty"]').value = String(defaults.bounty ?? 0);531
syncWanderMin();661
syncWanderMin();532
syncHumanoidSection(defaults);662
syncHumanoidSection(defaults);663
syncSpellsSection(defaults);533
});664
});665
spellsDraft = (config.spells ?? []).map((line) => ({666
spellId: String(line.spellId ?? ""),667
chance: Math.max(0, Math.min(100, Number(line.chance) || 0)) | 0668
})).filter((line) => line.spellId);534
syncHumanoidSection(config);669
syncHumanoidSection(config);670
syncSpellsSection(config);535
show(true);671
show(true);536
}672
}537
673
@@ -573,11 +709,14 @@ export function initTileConfigModal ({ onSave, onRemove })573
maxAlive: Number(data.get("maxAlive") || 3),709
maxAlive: Number(data.get("maxAlive") || 3),574
spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),710
spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),575
maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),711
maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),712
level: Number(data.get("level") || 1),713
bounty: Number(data.get("bounty") || 0),576
spawnerId: String(data.get("spawnerId") || context.config.spawnerId),714
spawnerId: String(data.get("spawnerId") || context.config.spawnerId),577
sex: String(data.get("sex") || "male"),715
sex: String(data.get("sex") || "male"),578
displayName: String(data.get("displayName") || ""),716
displayName: String(data.get("displayName") || ""),579
equipment,717
equipment,580
sells: sellsDraft,718
sells: sellsDraft,719
spells: spellsDraft,581
buysItems: data.get("buysItems") === "on",720
buysItems: data.get("buysItems") === "on",582
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),721
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),583
centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))722
centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))@@ -792,9 +792,11 @@ function entityLabel (entity)
792
792
{
793
793
const first = (entity?.firstName ?? "").trim();
794
794
const last = (entity?.lastName ?? "").trim();
795
if (first && last)
796
{ return `${first} ${last}`; }
797
return first || "target";
795
const name = first && last ? `${first} ${last}` : (first || "target");
796
const level = entity?.level | 0;
797
if (entity?.mobTypeId && level > 0)
798
{ return `Lv.${level} ${name}`; }
799
return name;
798
800
}
799
801
800
802
function groundLabel (ground)
@@ -1573,7 +1575,11 @@ function updateWorldTooltip ()
1573
1575
const entity = view.entityAtScreen(mouseX, mouseY);
1574
1576
if (entity && entity.entityId !== view.localEntityId)
1575
1577
{
1576
hideWorldTooltip();
1578
const label = entityLabel(entity);
1579
worldTooltip.hidden = false;
1580
worldTooltip.textContent = label;
1581
worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1582
worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1577
1583
return;
1578
1584
}
1579
1585
const tile = view.screenToTile(mouseX, mouseY);
@@ -792,9 +792,11 @@ function entityLabel (entity)792
{792
{793
const first = (entity?.firstName ?? "").trim();793
const first = (entity?.firstName ?? "").trim();794
const last = (entity?.lastName ?? "").trim();794
const last = (entity?.lastName ?? "").trim();795
if (first && last)795
const name = first && last ? `${first} ${last}` : (first || "target");796
{ return `${first} ${last}`; }796
const level = entity?.level | 0;797
return first || "target";797
if (entity?.mobTypeId && level > 0)798
{ return `Lv.${level} ${name}`; }799
return name;798
}800
}799
801
800
function groundLabel (ground)802
function groundLabel (ground)@@ -1573,7 +1575,11 @@ function updateWorldTooltip ()1573
const entity = view.entityAtScreen(mouseX, mouseY);1575
const entity = view.entityAtScreen(mouseX, mouseY);1574
if (entity && entity.entityId !== view.localEntityId)1576
if (entity && entity.entityId !== view.localEntityId)1575
{1577
{1576
hideWorldTooltip();1578
const label = entityLabel(entity);1579
worldTooltip.hidden = false;1580
worldTooltip.textContent = label;1581
worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;1582
worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;1577
return;1583
return;1578
}1584
}1579
const tile = view.screenToTile(mouseX, mouseY);1585
const tile = view.screenToTile(mouseX, mouseY);@@ -1461,6 +1461,8 @@ export class WorldView
1461
1461
entity.sex = payload.sex ?? entity.sex;
1462
1462
entity.characterId = payload.characterId ?? entity.characterId ?? null;
1463
1463
entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1464
if (payload.level != null)
1465
{ entity.level = payload.level | 0; }
1464
1466
entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
1465
1467
entity.canFight = payload.canFight != null
1466
1468
? !!payload.canFight
@@ -1461,6 +1461,8 @@ export class WorldView1461
entity.sex = payload.sex ?? entity.sex;1461
entity.sex = payload.sex ?? entity.sex;1462
entity.characterId = payload.characterId ?? entity.characterId ?? null;1462
entity.characterId = payload.characterId ?? entity.characterId ?? null;1463
entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;1463
entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;1464
if (payload.level != null)1465
{ entity.level = payload.level | 0; }1464
entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;1466
entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;1465
entity.canFight = payload.canFight != null1467
entity.canFight = payload.canFight != null1466
? !!payload.canFight1468
? !!payload.canFight@@ -1,5 +1,6 @@
1
1
import { Component } from "../ecs/components.js";
2
2
import { itemDefinition } from "../../../shared/definitions/items.js";
3
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
3
4
import { mobDefinition } from "../../../shared/definitions/mobs.js";
4
5
import {
5
6
mobCanFightType,
@@ -8,6 +9,7 @@ import {
8
9
mobIsAggressive,
9
10
mobAggroRangeTiles
10
11
} from "../../../shared/definitions/mobCombat.js";
12
import { spellDefinition } from "../../../shared/definitions/spells.js";
11
13
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
12
14
import {
13
15
effectiveHitSkillInDarkness,
@@ -25,7 +27,7 @@ import {
25
27
equipmentBonusesFromSlots
26
28
} from "../../../shared/equipment/stats.js";
27
29
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
28
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS } from "../../../shared/spells/constants.js";
30
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";
29
31
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
30
32
import { chunkBoundsAround, findPath } from "../navigation/astar.js";
31
33
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -34,6 +36,7 @@ import { tileToChunk } from "../world/coordinates.js";
34
36
import { stackQuantity } from "../../../shared/items/inventory.js";
35
37
import { addGroundItem, publicGroundItem } from "../items/bags.js";
36
38
import { resolveItemDualTint } from "../../../shared/render/tint.js";
39
import { castMobAttackSpell } from "../spells/mobCast.js";
37
40
38
41
export function chebyshev (ax, ay, bx, by)
39
42
{
@@ -42,24 +45,53 @@ export function chebyshev (ax, ay, bx, by)
42
45
43
46
export function attackProfileOf (ecs, handle)
44
47
{
48
const creature = ecs.get(handle, Component.creature);
49
const level = creatureLevel(ecs, handle);
45
50
const equipment = ecs.get(handle, Component.equipment);
46
51
const weapon = equipment?.slots?.weapon;
47
52
if (weapon?.itemId != null)
48
53
{
49
54
const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
50
55
if (attack)
51
{ return { ...attack }; }
56
{
57
const profile = { ...attack };
58
if (creature)
59
{ profile.mobAttackSkill = level; }
60
return profile;
61
}
52
62
}
53
const creature = ecs.get(handle, Component.creature);
54
63
if (creature)
55
64
{
56
65
const def = mobDefinition(creature.mobTypeId);
57
66
if (mobCanFightType(creature.mobTypeId))
58
{ return mobMeleeAttackProfile(def); }
67
{ return mobMeleeAttackProfile(def, level); }
59
68
}
60
69
return { ...UNARMED_ATTACK };
61
70
}
62
71
72
function creatureLevel (ecs, handle)
73
{
74
const creature = ecs.get(handle, Component.creature);
75
if (!creature)
76
{ return 1; }
77
if (creature.level != null)
78
{ return Math.max(1, creature.level | 0 || 1); }
79
const origin = ecs.get(handle, Component.spawnOrigin);
80
if (origin?.level != null)
81
{ return Math.max(1, origin.level | 0 || 1); }
82
const def = mobDefinition(creature.mobTypeId);
83
return Math.max(1, def?.attackSkill | 0 || 1);
84
}
85
86
export function weaponEquipmentKind (ecs, handle)
87
{
88
const equipment = ecs.get(handle, Component.equipment);
89
const weapon = equipment?.slots?.weapon;
90
if (!weapon?.itemId)
91
{ return null; }
92
return itemDefinition(weapon.itemId)?.equipment?.kind ?? null;
93
}
94
63
95
export function ensureMobCombat (ecs, entityId)
64
96
{
65
97
const handle = ecs.handleOf(entityId);
@@ -69,10 +101,11 @@ export function ensureMobCombat (ecs, entityId)
69
101
if (!creature || !mobCanFightType(creature.mobTypeId))
70
102
{ return false; }
71
103
const def = mobDefinition(creature.mobTypeId);
104
const level = creatureLevel(ecs, handle);
72
105
if (!ecs.get(handle, Component.combat))
73
106
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
74
107
if (!ecs.get(handle, Component.skills))
75
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
108
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }
76
109
return true;
77
110
}
78
111
@@ -395,13 +428,18 @@ export function stepCombat (world, now = Date.now())
395
428
396
429
const profile = attackProfileOf(world.ecs, entity.handle);
397
430
const targetPos = target.pos;
431
const isCreature = !!world.ecs.get(entity.handle, Component.creature)
432
&& !world.ecs.get(entity.handle, Component.character);
433
const weaponKind = weaponEquipmentKind(world.ecs, entity.handle);
434
const isStaff = weaponKind === EquipmentKind.staff;
398
435
399
436
if (profile.mode === "ranged")
400
437
{
401
438
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
402
439
const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
403
440
const equipment = world.ecs.get(entity.handle, Component.equipment);
404
const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
441
const hasArrows = isCreature
442
|| (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0);
405
443
const inRange = dist >= 1 && dist <= maxRange
406
444
&& hasCombatLineOfSight(
407
445
world,
@@ -433,15 +471,71 @@ export function stepCombat (world, now = Date.now())
433
471
continue;
434
472
}
435
473
436
if (profile.mode !== "melee")
474
if (profile.mode !== "melee" && !isStaff)
437
475
{ continue; }
438
476
439
477
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
440
const canSwing = dist === 1
478
const canSwing = !isStaff
479
&& dist === 1
441
480
&& world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
481
const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : [];
482
const shouldCast = isCreature && attackSpells.length > 0 && (isStaff || !canSwing);
483
484
if (shouldCast)
485
{
486
const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES
487
&& hasCombatLineOfSight(
488
world,
489
entity.position.tileX,
490
entity.position.tileY,
491
targetPos.tileX,
492
targetPos.tileY
493
);
494
if (!inSpellRange)
495
{
496
queueStandInRangeApproach(
497
world,
498
entity.entityId,
499
entity.handle,
500
entity.position,
501
targetPos.tileX,
502
targetPos.tileY,
503
COMBAT_RANGE_TILES,
504
1
505
);
506
continue;
507
}
508
clearCombatApproachPath(world.ecs, entity.handle);
509
if (now < (combat.nextSwingAt || 0))
510
{ continue; }
511
const picked = pickMobAttackSpell(attackSpells);
512
if (!picked)
513
{
514
combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
515
continue;
516
}
517
combat.nextSwingAt = now + SPELL_COOLDOWN_MS;
518
events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now));
519
continue;
520
}
521
442
522
if (!canSwing)
443
523
{
444
queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
524
if (isStaff)
525
{
526
queueStandInRangeApproach(
527
world,
528
entity.entityId,
529
entity.handle,
530
entity.position,
531
targetPos.tileX,
532
targetPos.tileY,
533
COMBAT_RANGE_TILES,
534
1
535
);
536
}
537
else
538
{ queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); }
445
539
continue;
446
540
}
447
541
clearCombatApproachPath(world.ecs, entity.handle);
@@ -457,6 +551,40 @@ export function stepCombat (world, now = Date.now())
457
551
return events;
458
552
}
459
553
554
function eligibleMobAttackSpells (ecs, handle)
555
{
556
const spells = ecs.get(handle, Component.spells);
557
if (!spells?.known?.length)
558
{ return []; }
559
const level = creatureLevel(ecs, handle);
560
const chances = spells.castChances ?? {};
561
const out = [];
562
for (const spellId of spells.known)
563
{
564
const def = spellDefinition(spellId);
565
if (!def || def.target !== "entity")
566
{ continue; }
567
const minLevel = Math.max(1, def.minMagicLevel | 0 || 1);
568
if (level < minLevel)
569
{ continue; }
570
const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0;
571
if (chance <= 0)
572
{ continue; }
573
out.push({ spellId, chance });
574
}
575
return out;
576
}
577
578
function pickMobAttackSpell (spells)
579
{
580
if (!spells.length)
581
{ return null; }
582
const pick = spells[Math.floor(Math.random() * spells.length)];
583
if ((Math.random() * 100) >= pick.chance)
584
{ return null; }
585
return pick;
586
}
587
460
588
function clearCombatApproachPath (ecs, handle)
461
589
{
462
590
const path = ecs.get(handle, Component.path);
@@ -664,7 +792,9 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
664
792
const from = world.ecs.get(attackerHandle, Component.position);
665
793
if (!from || !targetPos)
666
794
{ return events; }
667
if (!consumeArrow(world.ecs, attackerHandle))
795
const isCreature = !!world.ecs.get(attackerHandle, Component.creature)
796
&& !world.ecs.get(attackerHandle, Component.character);
797
if (!isCreature && !consumeArrow(world.ecs, attackerHandle))
668
798
{ return events; }
669
799
670
800
const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };
@@ -1169,18 +1299,140 @@ function applyLocalMeleeHit (
1169
1299
const creature = world.ecs.get(targetHandle, Component.creature);
1170
1300
if (creature && !world.ecs.get(targetHandle, Component.character))
1171
1301
{
1172
events.push(...spawnMobDrops(world, targetHandle, to.tileX, to.tileY, now));
1173
const view = world.destroyEntity?.(targetId) ?? null;
1174
if (view)
1175
{
1176
events.push({
1177
type: "entity-despawn",
1178
entityId: targetId,
1179
tileX: view.tileX,
1180
tileY: view.tileY
1181
});
1182
}
1302
events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now));
1303
}
1304
}
1305
return events;
1306
}
1307
1308
/**
1309
* Drops, despawn, and `mob-killed` for bounty / town-guard reaction.
1310
* Shared by melee and spell kill paths.
1311
*/
1312
export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now)
1313
{
1314
const events = [];
1315
const handle = targetHandle ?? world.ecs.handleOf(targetId);
1316
if (handle == null)
1317
{ return events; }
1318
const creature = world.ecs.get(handle, Component.creature);
1319
const origin = world.ecs.get(handle, Component.spawnOrigin);
1320
const appearance = world.ecs.get(handle, Component.appearance);
1321
events.push(...spawnMobDrops(world, handle, tileX, tileY, now));
1322
events.push({
1323
type: "mob-killed",
1324
entityId: targetId,
1325
attackerId,
1326
mobTypeId: creature?.mobTypeId ?? null,
1327
level: creature?.level ?? origin?.level ?? 1,
1328
bounty: Math.max(0, origin?.bounty | 0 || 0),
1329
spawnerId: origin?.spawnerId ?? null,
1330
originTileX: origin?.originTileX ?? tileX,
1331
originTileY: origin?.originTileY ?? tileY,
1332
wanderRangeTiles: origin?.wanderRangeTiles ?? 0,
1333
townGuard: !!origin?.townGuard,
1334
displayName: appearance?.firstName ?? null,
1335
tileX,
1336
tileY
1337
});
1338
const view = world.destroyEntity?.(targetId) ?? null;
1339
if (view)
1340
{
1341
events.push({
1342
type: "entity-despawn",
1343
entityId: targetId,
1344
tileX: view.tileX,
1345
tileY: view.tileY
1346
});
1347
}
1348
return events;
1349
}
1350
1351
/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */
1352
export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now())
1353
{
1354
const events = [];
1355
const targetHandle = world.ecs.handleOf(targetId);
1356
if (targetHandle == null)
1357
{ return events; }
1358
const to = world.ecs.get(targetHandle, Component.position);
1359
if (!to)
1360
{ return events; }
1361
const health = world.ecs.get(targetHandle, Component.health);
1362
if (health)
1363
{ health.current = Math.max(0, (health.current | 0) - damage); }
1364
events.push({
1365
type: "combat-hit",
1366
attackerId,
1367
targetId,
1368
damage,
1369
tileX: to.tileX,
1370
tileY: to.tileY,
1371
health: health?.current ?? 0,
1372
maxHealth: health?.max ?? 0
1373
});
1374
1375
const attackerHandle = world.ecs.handleOf(attackerId);
1376
if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
1377
{
1378
const targetCombat = world.ecs.get(targetHandle, Component.combat);
1379
if (targetCombat && targetCombat.targetEntityId == null)
1380
{ engageTarget(world.ecs, targetId, attackerId, now); }
1381
}
1382
if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
1383
{
1384
const attackerCreature = world.ecs.get(attackerHandle, Component.creature);
1385
if (attackerCreature)
1386
{
1387
engageTarget(world.ecs, targetId, attackerId, now);
1388
}
1389
}
1390
1391
const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
1392
if (healthXp)
1393
{
1394
events.push({
1395
type: "skills-updated",
1396
entityId: targetId,
1397
characterId: healthXp.characterId,
1398
skills: healthXp.view,
1399
stored: healthXp.stored,
1400
levelUps: healthXp.levelUps ?? []
1401
});
1402
}
1403
1404
if (health && health.current <= 0)
1405
{
1406
clearEngage(world.ecs, attackerId);
1407
clearEngage(world.ecs, targetId);
1408
for (const entity of world.ecs.query(Component.combat))
1409
{
1410
if (entity.combat.targetEntityId === targetId)
1411
{ entity.combat.targetEntityId = null; }
1183
1412
}
1413
const targetCharacter = world.ecs.get(targetHandle, Component.character);
1414
if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
1415
{
1416
const path = world.ecs.get(targetHandle, Component.path);
1417
if (path)
1418
{ path.tiles = []; }
1419
world.ecs.add(targetHandle, Component.dead, {});
1420
const identity = world.ecs.get(targetHandle, Component.networkIdentity);
1421
events.push({
1422
type: "player-died",
1423
entityId: targetId,
1424
attackerId,
1425
characterId: targetCharacter.characterId,
1426
sessionId: identity?.sessionId ?? null,
1427
tileX: to.tileX,
1428
tileY: to.tileY,
1429
health: 0,
1430
maxHealth: health.max
1431
});
1432
}
1433
const creature = world.ecs.get(targetHandle, Component.creature);
1434
if (creature && !targetCharacter)
1435
{ events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }
1184
1436
}
1185
1437
return events;
1186
1438
}
@@ -1,5 +1,6 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { itemDefinition } from "../../../shared/definitions/items.js";2
import { itemDefinition } from "../../../shared/definitions/items.js";3
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";3
import { mobDefinition } from "../../../shared/definitions/mobs.js";4
import { mobDefinition } from "../../../shared/definitions/mobs.js";4
import {5
import {5
mobCanFightType,6
mobCanFightType,@@ -8,6 +9,7 @@ import {8
mobIsAggressive,9
mobIsAggressive,9
mobAggroRangeTiles10
mobAggroRangeTiles10
} from "../../../shared/definitions/mobCombat.js";11
} from "../../../shared/definitions/mobCombat.js";12
import { spellDefinition } from "../../../shared/definitions/spells.js";11
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";13
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";12
import {14
import {13
effectiveHitSkillInDarkness,15
effectiveHitSkillInDarkness,@@ -25,7 +27,7 @@ import {25
equipmentBonusesFromSlots27
equipmentBonusesFromSlots26
} from "../../../shared/equipment/stats.js";28
} from "../../../shared/equipment/stats.js";27
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";29
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";28
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS } from "../../../shared/spells/constants.js";30
import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS, SPELL_COOLDOWN_MS } from "../../../shared/spells/constants.js";29
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";31
import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";30
import { chunkBoundsAround, findPath } from "../navigation/astar.js";32
import { chunkBoundsAround, findPath } from "../navigation/astar.js";31
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";33
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";@@ -34,6 +36,7 @@ import { tileToChunk } from "../world/coordinates.js";34
import { stackQuantity } from "../../../shared/items/inventory.js";36
import { stackQuantity } from "../../../shared/items/inventory.js";35
import { addGroundItem, publicGroundItem } from "../items/bags.js";37
import { addGroundItem, publicGroundItem } from "../items/bags.js";36
import { resolveItemDualTint } from "../../../shared/render/tint.js";38
import { resolveItemDualTint } from "../../../shared/render/tint.js";39
import { castMobAttackSpell } from "../spells/mobCast.js";37
40
38
export function chebyshev (ax, ay, bx, by)41
export function chebyshev (ax, ay, bx, by)39
{42
{@@ -42,24 +45,53 @@ export function chebyshev (ax, ay, bx, by)42
45
43
export function attackProfileOf (ecs, handle)46
export function attackProfileOf (ecs, handle)44
{47
{48
const creature = ecs.get(handle, Component.creature);49
const level = creatureLevel(ecs, handle);45
const equipment = ecs.get(handle, Component.equipment);50
const equipment = ecs.get(handle, Component.equipment);46
const weapon = equipment?.slots?.weapon;51
const weapon = equipment?.slots?.weapon;47
if (weapon?.itemId != null)52
if (weapon?.itemId != null)48
{53
{49
const attack = itemDefinition(weapon.itemId)?.equipment?.attack;54
const attack = itemDefinition(weapon.itemId)?.equipment?.attack;50
if (attack)55
if (attack)51
{ return { ...attack }; }56
{57
const profile = { ...attack };58
if (creature)59
{ profile.mobAttackSkill = level; }60
return profile;61
}52
}62
}53
const creature = ecs.get(handle, Component.creature);54
if (creature)63
if (creature)55
{64
{56
const def = mobDefinition(creature.mobTypeId);65
const def = mobDefinition(creature.mobTypeId);57
if (mobCanFightType(creature.mobTypeId))66
if (mobCanFightType(creature.mobTypeId))58
{ return mobMeleeAttackProfile(def); }67
{ return mobMeleeAttackProfile(def, level); }59
}68
}60
return { ...UNARMED_ATTACK };69
return { ...UNARMED_ATTACK };61
}70
}62
71
72
function creatureLevel (ecs, handle)73
{74
const creature = ecs.get(handle, Component.creature);75
if (!creature)76
{ return 1; }77
if (creature.level != null)78
{ return Math.max(1, creature.level | 0 || 1); }79
const origin = ecs.get(handle, Component.spawnOrigin);80
if (origin?.level != null)81
{ return Math.max(1, origin.level | 0 || 1); }82
const def = mobDefinition(creature.mobTypeId);83
return Math.max(1, def?.attackSkill | 0 || 1);84
}85
86
export function weaponEquipmentKind (ecs, handle)87
{88
const equipment = ecs.get(handle, Component.equipment);89
const weapon = equipment?.slots?.weapon;90
if (!weapon?.itemId)91
{ return null; }92
return itemDefinition(weapon.itemId)?.equipment?.kind ?? null;93
}94
63
export function ensureMobCombat (ecs, entityId)95
export function ensureMobCombat (ecs, entityId)64
{96
{65
const handle = ecs.handleOf(entityId);97
const handle = ecs.handleOf(entityId);@@ -69,10 +101,11 @@ export function ensureMobCombat (ecs, entityId)69
if (!creature || !mobCanFightType(creature.mobTypeId))101
if (!creature || !mobCanFightType(creature.mobTypeId))70
{ return false; }102
{ return false; }71
const def = mobDefinition(creature.mobTypeId);103
const def = mobDefinition(creature.mobTypeId);104
const level = creatureLevel(ecs, handle);72
if (!ecs.get(handle, Component.combat))105
if (!ecs.get(handle, Component.combat))73
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }106
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }74
if (!ecs.get(handle, Component.skills))107
if (!ecs.get(handle, Component.skills))75
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }108
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }76
return true;109
return true;77
}110
}78
111
@@ -395,13 +428,18 @@ export function stepCombat (world, now = Date.now())395
428
396
const profile = attackProfileOf(world.ecs, entity.handle);429
const profile = attackProfileOf(world.ecs, entity.handle);397
const targetPos = target.pos;430
const targetPos = target.pos;431
const isCreature = !!world.ecs.get(entity.handle, Component.creature)432
&& !world.ecs.get(entity.handle, Component.character);433
const weaponKind = weaponEquipmentKind(world.ecs, entity.handle);434
const isStaff = weaponKind === EquipmentKind.staff;398
435
399
if (profile.mode === "ranged")436
if (profile.mode === "ranged")400
{437
{401
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);438
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);402
const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;439
const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;403
const equipment = world.ecs.get(entity.handle, Component.equipment);440
const equipment = world.ecs.get(entity.handle, Component.equipment);404
const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;441
const hasArrows = isCreature442
|| (arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0);405
const inRange = dist >= 1 && dist <= maxRange443
const inRange = dist >= 1 && dist <= maxRange406
&& hasCombatLineOfSight(444
&& hasCombatLineOfSight(407
world,445
world,@@ -433,15 +471,71 @@ export function stepCombat (world, now = Date.now())433
continue;471
continue;434
}472
}435
473
436
if (profile.mode !== "melee")474
if (profile.mode !== "melee" && !isStaff)437
{ continue; }475
{ continue; }438
476
439
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);477
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);440
const canSwing = dist === 1478
const canSwing = !isStaff479
&& dist === 1441
&& world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);480
&& world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);481
const attackSpells = isCreature ? eligibleMobAttackSpells(world.ecs, entity.handle) : [];482
const shouldCast = isCreature && attackSpells.length > 0 && (isStaff || !canSwing);483
484
if (shouldCast)485
{486
const inSpellRange = dist >= 1 && dist <= COMBAT_RANGE_TILES487
&& hasCombatLineOfSight(488
world,489
entity.position.tileX,490
entity.position.tileY,491
targetPos.tileX,492
targetPos.tileY493
);494
if (!inSpellRange)495
{496
queueStandInRangeApproach(497
world,498
entity.entityId,499
entity.handle,500
entity.position,501
targetPos.tileX,502
targetPos.tileY,503
COMBAT_RANGE_TILES,504
1505
);506
continue;507
}508
clearCombatApproachPath(world.ecs, entity.handle);509
if (now < (combat.nextSwingAt || 0))510
{ continue; }511
const picked = pickMobAttackSpell(attackSpells);512
if (!picked)513
{514
combat.nextSwingAt = now + SPELL_COOLDOWN_MS;515
continue;516
}517
combat.nextSwingAt = now + SPELL_COOLDOWN_MS;518
events.push(...castMobAttackSpell(world, entity.entityId, targetId, picked.spellId, now));519
continue;520
}521
442
if (!canSwing)522
if (!canSwing)443
{523
{444
queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);524
if (isStaff)525
{526
queueStandInRangeApproach(527
world,528
entity.entityId,529
entity.handle,530
entity.position,531
targetPos.tileX,532
targetPos.tileY,533
COMBAT_RANGE_TILES,534
1535
);536
}537
else538
{ queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos); }445
continue;539
continue;446
}540
}447
clearCombatApproachPath(world.ecs, entity.handle);541
clearCombatApproachPath(world.ecs, entity.handle);@@ -457,6 +551,40 @@ export function stepCombat (world, now = Date.now())457
return events;551
return events;458
}552
}459
553
554
function eligibleMobAttackSpells (ecs, handle)555
{556
const spells = ecs.get(handle, Component.spells);557
if (!spells?.known?.length)558
{ return []; }559
const level = creatureLevel(ecs, handle);560
const chances = spells.castChances ?? {};561
const out = [];562
for (const spellId of spells.known)563
{564
const def = spellDefinition(spellId);565
if (!def || def.target !== "entity")566
{ continue; }567
const minLevel = Math.max(1, def.minMagicLevel | 0 || 1);568
if (level < minLevel)569
{ continue; }570
const chance = Math.max(0, Math.min(100, Number(chances[spellId]) || 0)) | 0;571
if (chance <= 0)572
{ continue; }573
out.push({ spellId, chance });574
}575
return out;576
}577
578
function pickMobAttackSpell (spells)579
{580
if (!spells.length)581
{ return null; }582
const pick = spells[Math.floor(Math.random() * spells.length)];583
if ((Math.random() * 100) >= pick.chance)584
{ return null; }585
return pick;586
}587
460
function clearCombatApproachPath (ecs, handle)588
function clearCombatApproachPath (ecs, handle)461
{589
{462
const path = ecs.get(handle, Component.path);590
const path = ecs.get(handle, Component.path);@@ -664,7 +792,9 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D664
const from = world.ecs.get(attackerHandle, Component.position);792
const from = world.ecs.get(attackerHandle, Component.position);665
if (!from || !targetPos)793
if (!from || !targetPos)666
{ return events; }794
{ return events; }667
if (!consumeArrow(world.ecs, attackerHandle))795
const isCreature = !!world.ecs.get(attackerHandle, Component.creature)796
&& !world.ecs.get(attackerHandle, Component.character);797
if (!isCreature && !consumeArrow(world.ecs, attackerHandle))668
{ return events; }798
{ return events; }669
799
670
const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };800
const snapshot = { tileX: targetPos.tileX, tileY: targetPos.tileY };@@ -1169,18 +1299,140 @@ function applyLocalMeleeHit (1169
const creature = world.ecs.get(targetHandle, Component.creature);1299
const creature = world.ecs.get(targetHandle, Component.creature);1170
if (creature && !world.ecs.get(targetHandle, Component.character))1300
if (creature && !world.ecs.get(targetHandle, Component.character))1171
{1301
{1172
events.push(...spawnMobDrops(world, targetHandle, to.tileX, to.tileY, now));1302
events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now));1173
const view = world.destroyEntity?.(targetId) ?? null;1303
}1174
if (view)1304
}1175
{1305
return events;1176
events.push({1306
}1177
type: "entity-despawn",1307
1178
entityId: targetId,1308
/**1179
tileX: view.tileX,1309
* Drops, despawn, and `mob-killed` for bounty / town-guard reaction.1180
tileY: view.tileY1310
* Shared by melee and spell kill paths.1181
});1311
*/1182
}1312
export function finalizeMobKill (world, attackerId, targetId, targetHandle, tileX, tileY, now)1313
{1314
const events = [];1315
const handle = targetHandle ?? world.ecs.handleOf(targetId);1316
if (handle == null)1317
{ return events; }1318
const creature = world.ecs.get(handle, Component.creature);1319
const origin = world.ecs.get(handle, Component.spawnOrigin);1320
const appearance = world.ecs.get(handle, Component.appearance);1321
events.push(...spawnMobDrops(world, handle, tileX, tileY, now));1322
events.push({1323
type: "mob-killed",1324
entityId: targetId,1325
attackerId,1326
mobTypeId: creature?.mobTypeId ?? null,1327
level: creature?.level ?? origin?.level ?? 1,1328
bounty: Math.max(0, origin?.bounty | 0 || 0),1329
spawnerId: origin?.spawnerId ?? null,1330
originTileX: origin?.originTileX ?? tileX,1331
originTileY: origin?.originTileY ?? tileY,1332
wanderRangeTiles: origin?.wanderRangeTiles ?? 0,1333
townGuard: !!origin?.townGuard,1334
displayName: appearance?.firstName ?? null,1335
tileX,1336
tileY1337
});1338
const view = world.destroyEntity?.(targetId) ?? null;1339
if (view)1340
{1341
events.push({1342
type: "entity-despawn",1343
entityId: targetId,1344
tileX: view.tileX,1345
tileY: view.tileY1346
});1347
}1348
return events;1349
}1350
1351
/** Apply HP loss and shared death/loot side-effects (used by spell impacts). */1352
export function applyDamageAndKill (world, attackerId, targetId, damage, now = Date.now())1353
{1354
const events = [];1355
const targetHandle = world.ecs.handleOf(targetId);1356
if (targetHandle == null)1357
{ return events; }1358
const to = world.ecs.get(targetHandle, Component.position);1359
if (!to)1360
{ return events; }1361
const health = world.ecs.get(targetHandle, Component.health);1362
if (health)1363
{ health.current = Math.max(0, (health.current | 0) - damage); }1364
events.push({1365
type: "combat-hit",1366
attackerId,1367
targetId,1368
damage,1369
tileX: to.tileX,1370
tileY: to.tileY,1371
health: health?.current ?? 0,1372
maxHealth: health?.max ?? 01373
});1374
1375
const attackerHandle = world.ecs.handleOf(attackerId);1376
if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))1377
{1378
const targetCombat = world.ecs.get(targetHandle, Component.combat);1379
if (targetCombat && targetCombat.targetEntityId == null)1380
{ engageTarget(world.ecs, targetId, attackerId, now); }1381
}1382
if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))1383
{1384
const attackerCreature = world.ecs.get(attackerHandle, Component.creature);1385
if (attackerCreature)1386
{1387
engageTarget(world.ecs, targetId, attackerId, now);1388
}1389
}1390
1391
const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);1392
if (healthXp)1393
{1394
events.push({1395
type: "skills-updated",1396
entityId: targetId,1397
characterId: healthXp.characterId,1398
skills: healthXp.view,1399
stored: healthXp.stored,1400
levelUps: healthXp.levelUps ?? []1401
});1402
}1403
1404
if (health && health.current <= 0)1405
{1406
clearEngage(world.ecs, attackerId);1407
clearEngage(world.ecs, targetId);1408
for (const entity of world.ecs.query(Component.combat))1409
{1410
if (entity.combat.targetEntityId === targetId)1411
{ entity.combat.targetEntityId = null; }1183
}1412
}1413
const targetCharacter = world.ecs.get(targetHandle, Component.character);1414
if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))1415
{1416
const path = world.ecs.get(targetHandle, Component.path);1417
if (path)1418
{ path.tiles = []; }1419
world.ecs.add(targetHandle, Component.dead, {});1420
const identity = world.ecs.get(targetHandle, Component.networkIdentity);1421
events.push({1422
type: "player-died",1423
entityId: targetId,1424
attackerId,1425
characterId: targetCharacter.characterId,1426
sessionId: identity?.sessionId ?? null,1427
tileX: to.tileX,1428
tileY: to.tileY,1429
health: 0,1430
maxHealth: health.max1431
});1432
}1433
const creature = world.ecs.get(targetHandle, Component.creature);1434
if (creature && !targetCharacter)1435
{ events.push(...finalizeMobKill(world, attackerId, targetId, targetHandle, to.tileX, to.tileY, now)); }1184
}1436
}1185
return events;1437
return events;1186
}1438
}@@ -91,6 +91,7 @@ export function publicEntityView (ecs, entityId)
91
91
hasShop: shopHasInterface(ecs.get(handle, Component.shop)),
92
92
untargetable: !!mob?.untargetable,
93
93
freeFlight: !!mob?.freeFlight,
94
level: creature?.level ?? null,
94
95
health: health ? health.current : undefined,
95
96
maxHealth: health ? health.max : undefined,
96
97
sprite: layers[0]?.sprite ?? null,
@@ -132,6 +133,7 @@ export function replicationSpawn (view)
132
133
hasShop: !!view.hasShop,
133
134
untargetable: !!view.untargetable,
134
135
freeFlight: !!view.freeFlight,
136
level: view.level ?? null,
135
137
health: view.health,
136
138
maxHealth: view.maxHealth,
137
139
lightRadiusTiles: view.lightRadiusTiles ?? 0,
@@ -91,6 +91,7 @@ export function publicEntityView (ecs, entityId)91
hasShop: shopHasInterface(ecs.get(handle, Component.shop)),91
hasShop: shopHasInterface(ecs.get(handle, Component.shop)),92
untargetable: !!mob?.untargetable,92
untargetable: !!mob?.untargetable,93
freeFlight: !!mob?.freeFlight,93
freeFlight: !!mob?.freeFlight,94
level: creature?.level ?? null,94
health: health ? health.current : undefined,95
health: health ? health.current : undefined,95
maxHealth: health ? health.max : undefined,96
maxHealth: health ? health.max : undefined,96
sprite: layers[0]?.sprite ?? null,97
sprite: layers[0]?.sprite ?? null,@@ -132,6 +133,7 @@ export function replicationSpawn (view)132
hasShop: !!view.hasShop,133
hasShop: !!view.hasShop,133
untargetable: !!view.untargetable,134
untargetable: !!view.untargetable,134
freeFlight: !!view.freeFlight,135
freeFlight: !!view.freeFlight,136
level: view.level ?? null,135
health: view.health,137
health: view.health,136
maxHealth: view.maxHealth,138
maxHealth: view.maxHealth,137
lightRadiusTiles: view.lightRadiusTiles ?? 0,139
lightRadiusTiles: view.lightRadiusTiles ?? 0,@@ -39,5 +39,7 @@ export const WorkerMessage = Object.freeze({
39
39
setItemLastSales: "setItemLastSales",
40
40
stationExchangeClerk: "stationExchangeClerk",
41
41
releaseExchangeClerk: "releaseExchangeClerk",
42
applyAppearance: "applyAppearance"
42
applyAppearance: "applyAppearance",
43
engageTarget: "engageTarget",
44
listTownGuardsNear: "listTownGuardsNear"
43
45
});
@@ -39,5 +39,7 @@ export const WorkerMessage = Object.freeze({39
setItemLastSales: "setItemLastSales",39
setItemLastSales: "setItemLastSales",40
stationExchangeClerk: "stationExchangeClerk",40
stationExchangeClerk: "stationExchangeClerk",41
releaseExchangeClerk: "releaseExchangeClerk",41
releaseExchangeClerk: "releaseExchangeClerk",42
applyAppearance: "applyAppearance"42
applyAppearance: "applyAppearance",43
engageTarget: "engageTarget",44
listTownGuardsNear: "listTownGuardsNear"43
});45
});@@ -244,6 +244,11 @@ export class Simulation
244
244
events.push(...this.#applyPlayerDeath(event));
245
245
continue;
246
246
}
247
if (event.type === "mob-killed")
248
{
249
events.push(...this.#applyMobKilled(event));
250
continue;
251
}
247
252
this.#persistGroundEvent(event);
248
253
if (event.type !== "skills-updated")
249
254
{ events.push(event); }
@@ -1106,6 +1111,11 @@ export class Simulation
1106
1111
events.push(...this.#applyPlayerDeath(event));
1107
1112
continue;
1108
1113
}
1114
if (event.type === "mob-killed")
1115
{
1116
events.push(...this.#applyMobKilled(event));
1117
continue;
1118
}
1109
1119
this.#persistGroundEvent(event);
1110
1120
if (event.type !== "skills-updated")
1111
1121
{ events.push(event); }
@@ -1167,6 +1177,11 @@ export class Simulation
1167
1177
events.push(...this.#applyPlayerDeath(event));
1168
1178
continue;
1169
1179
}
1180
if (event.type === "mob-killed")
1181
{
1182
events.push(...this.#applyMobKilled(event));
1183
continue;
1184
}
1170
1185
this.#persistGroundEvent(event);
1171
1186
if (event.type !== "skills-updated")
1172
1187
{ events.push(event); }
@@ -1198,6 +1213,79 @@ export class Simulation
1198
1213
return events;
1199
1214
}
1200
1215
1216
#applyMobKilled (event)
1217
{
1218
const out = [event];
1219
const attackerRecord = this.directory.get(event.attackerId);
1220
const killerCharacterId = attackerRecord?.characterId ?? null;
1221
const killerPos = attackerRecord
1222
? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1223
: null;
1224
let bountyAwarded = 0;
1225
if (killerCharacterId && (event.bounty | 0) > 0)
1226
{
1227
bountyAwarded = event.bounty | 0;
1228
const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);
1229
out.push({
1230
type: "toast",
1231
characterId: killerCharacterId,
1232
message: `Bounty +${bountyAwarded} (total ${total})`
1233
});
1234
}
1235
1236
if (killerCharacterId && killerPos)
1237
{
1238
if (bountyAwarded > 0)
1239
{ this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); }
1240
if (event.townGuard)
1241
{ this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); }
1242
}
1243
return out;
1244
}
1245
1246
/**
1247
* Send up to `count` town guards at the killer. Prefer idle guards.
1248
* When `spawnerId` is set, only that spawner's guards are used.
1249
*/
1250
#dispatchTownGuards (targetEntityId, killerPos, spawnerId, count)
1251
{
1252
const want = Math.max(0, count | 0);
1253
if (want <= 0 || targetEntityId == null || !killerPos)
1254
{ return; }
1255
const candidates = [];
1256
for (const worker of this.workers)
1257
{
1258
const result = worker.call({
1259
type: WorkerMessage.listTownGuardsNear,
1260
tileX: killerPos.tileX,
1261
tileY: killerPos.tileY,
1262
spawnerId,
1263
limit: 32
1264
});
1265
for (const guard of result?.guards ?? [])
1266
{ candidates.push(guard); }
1267
}
1268
candidates.sort((a, b) => Number(a.busy) - Number(b.busy));
1269
let sent = 0;
1270
for (const guard of candidates)
1271
{
1272
if (sent >= want)
1273
{ break; }
1274
if (guard.entityId === targetEntityId)
1275
{ continue; }
1276
const record = this.directory.get(guard.entityId);
1277
if (!record)
1278
{ continue; }
1279
this.workers[record.workerId].call({
1280
type: WorkerMessage.engageTarget,
1281
attackerEntityId: guard.entityId,
1282
targetEntityId,
1283
now: this.now
1284
});
1285
sent += 1;
1286
}
1287
}
1288
1201
1289
#applyPlayerDeath (event)
1202
1290
{
1203
1291
const record = this.directory.get(event.entityId);
@@ -244,6 +244,11 @@ export class Simulation244
events.push(...this.#applyPlayerDeath(event));244
events.push(...this.#applyPlayerDeath(event));245
continue;245
continue;246
}246
}247
if (event.type === "mob-killed")248
{249
events.push(...this.#applyMobKilled(event));250
continue;251
}247
this.#persistGroundEvent(event);252
this.#persistGroundEvent(event);248
if (event.type !== "skills-updated")253
if (event.type !== "skills-updated")249
{ events.push(event); }254
{ events.push(event); }@@ -1106,6 +1111,11 @@ export class Simulation1106
events.push(...this.#applyPlayerDeath(event));1111
events.push(...this.#applyPlayerDeath(event));1107
continue;1112
continue;1108
}1113
}1114
if (event.type === "mob-killed")1115
{1116
events.push(...this.#applyMobKilled(event));1117
continue;1118
}1109
this.#persistGroundEvent(event);1119
this.#persistGroundEvent(event);1110
if (event.type !== "skills-updated")1120
if (event.type !== "skills-updated")1111
{ events.push(event); }1121
{ events.push(event); }@@ -1167,6 +1177,11 @@ export class Simulation1167
events.push(...this.#applyPlayerDeath(event));1177
events.push(...this.#applyPlayerDeath(event));1168
continue;1178
continue;1169
}1179
}1180
if (event.type === "mob-killed")1181
{1182
events.push(...this.#applyMobKilled(event));1183
continue;1184
}1170
this.#persistGroundEvent(event);1185
this.#persistGroundEvent(event);1171
if (event.type !== "skills-updated")1186
if (event.type !== "skills-updated")1172
{ events.push(event); }1187
{ events.push(event); }@@ -1198,6 +1213,79 @@ export class Simulation1198
return events;1213
return events;1199
}1214
}1200
1215
1216
#applyMobKilled (event)1217
{1218
const out = [event];1219
const attackerRecord = this.directory.get(event.attackerId);1220
const killerCharacterId = attackerRecord?.characterId ?? null;1221
const killerPos = attackerRecord1222
? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }1223
: null;1224
let bountyAwarded = 0;1225
if (killerCharacterId && (event.bounty | 0) > 0)1226
{1227
bountyAwarded = event.bounty | 0;1228
const total = this.stateDb.addCharacterBounty(killerCharacterId, bountyAwarded);1229
out.push({1230
type: "toast",1231
characterId: killerCharacterId,1232
message: `Bounty +${bountyAwarded} (total ${total})`1233
});1234
}1235
1236
if (killerCharacterId && killerPos)1237
{1238
if (bountyAwarded > 0)1239
{ this.#dispatchTownGuards(event.attackerId, killerPos, null, 1); }1240
if (event.townGuard)1241
{ this.#dispatchTownGuards(event.attackerId, killerPos, event.spawnerId, 2); }1242
}1243
return out;1244
}1245
1246
/**1247
* Send up to `count` town guards at the killer. Prefer idle guards.1248
* When `spawnerId` is set, only that spawner's guards are used.1249
*/1250
#dispatchTownGuards (targetEntityId, killerPos, spawnerId, count)1251
{1252
const want = Math.max(0, count | 0);1253
if (want <= 0 || targetEntityId == null || !killerPos)1254
{ return; }1255
const candidates = [];1256
for (const worker of this.workers)1257
{1258
const result = worker.call({1259
type: WorkerMessage.listTownGuardsNear,1260
tileX: killerPos.tileX,1261
tileY: killerPos.tileY,1262
spawnerId,1263
limit: 321264
});1265
for (const guard of result?.guards ?? [])1266
{ candidates.push(guard); }1267
}1268
candidates.sort((a, b) => Number(a.busy) - Number(b.busy));1269
let sent = 0;1270
for (const guard of candidates)1271
{1272
if (sent >= want)1273
{ break; }1274
if (guard.entityId === targetEntityId)1275
{ continue; }1276
const record = this.directory.get(guard.entityId);1277
if (!record)1278
{ continue; }1279
this.workers[record.workerId].call({1280
type: WorkerMessage.engageTarget,1281
attackerEntityId: guard.entityId,1282
targetEntityId,1283
now: this.now1284
});1285
sent += 1;1286
}1287
}1288
1201
#applyPlayerDeath (event)1289
#applyPlayerDeath (event)1202
{1290
{1203
const record = this.directory.get(event.entityId);1291
const record = this.directory.get(event.entityId);@@ -1,13 +1,15 @@
1
1
import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2
import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
2
import { mobCanFight, mobSkillLevels, mobHealthForLevel } from "../../../shared/definitions/mobCombat.js";
3
3
import {
4
4
normalizeSpawnerConfig,
5
5
listAmbientMobTypes,
6
6
mobDefinition,
7
7
mobSpriteName,
8
8
MobId,
9
spawnerEquipmentSlot
9
spawnerEquipmentSlot,
10
isTownGuardMob
10
11
} from "../../../shared/definitions/mobs.js";
12
import { spellDefinition } from "../../../shared/definitions/spells.js";
11
13
import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";
12
14
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
13
15
import { emptyEquipment } from "../../../shared/items/inventory.js";
@@ -64,6 +66,9 @@ export function collectSpawnRequests (world)
64
66
originTileX: originX,
65
67
originTileY: originY,
66
68
wanderRangeTiles: config.maxWanderRangeTiles,
69
level: config.level,
70
bounty: config.bounty,
71
spells: config.spells,
67
72
persistent,
68
73
sex: staff.sex,
69
74
displayName: staff.name,
@@ -71,7 +76,8 @@ export function collectSpawnRequests (world)
71
76
sells: [],
72
77
buysItems: false,
73
78
hiddenDiscount: config.hiddenDiscount,
74
centralExchange: true
79
centralExchange: true,
80
townGuard: false
75
81
});
76
82
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
77
83
}
@@ -91,6 +97,9 @@ export function collectSpawnRequests (world)
91
97
originTileX: originX,
92
98
originTileY: originY,
93
99
wanderRangeTiles: config.maxWanderRangeTiles,
100
level: config.level,
101
bounty: config.bounty,
102
spells: config.spells,
94
103
persistent,
95
104
sex: config.sex,
96
105
displayName: config.displayName,
@@ -98,7 +107,8 @@ export function collectSpawnRequests (world)
98
107
sells: config.sells,
99
108
buysItems: config.buysItems,
100
109
hiddenDiscount: config.hiddenDiscount,
101
centralExchange: false
110
centralExchange: false,
111
townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId)
102
112
});
103
113
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
104
114
}
@@ -115,6 +125,7 @@ export function mobComponents (request)
115
125
? request.sex
116
126
: (def.sex ?? "male");
117
127
const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
128
const level = Math.max(1, Math.min(99, Number(request.level) || 1)) | 0;
118
129
const appearance = {
119
130
sex,
120
131
firstName: displayName,
@@ -131,13 +142,14 @@ export function mobComponents (request)
131
142
{ appearance.sprite = sprite; }
132
143
}
133
144
145
const maxHp = mobHealthForLevel(def, level);
134
146
const components = {
135
147
position: { tileX: request.tileX, tileY: request.tileY },
136
148
movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
137
149
path: { tiles: [] },
138
150
appearance,
139
creature: { mobTypeId: def.mobTypeId },
140
health: { current: def.health ?? 8, max: def.health ?? 8 }
151
creature: { mobTypeId: def.mobTypeId, level },
152
health: { current: maxHp, max: maxHp }
141
153
};
142
154
if (request.spawnerId)
143
155
{
@@ -146,7 +158,10 @@ export function mobComponents (request)
146
158
originTileX: request.originTileX ?? request.tileX,
147
159
originTileY: request.originTileY ?? request.tileY,
148
160
wanderRangeTiles: request.wanderRangeTiles ?? 4,
161
bounty: Math.max(0, Number(request.bounty) || 0) | 0,
162
level,
149
163
centralExchange: !!request.centralExchange,
164
townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
150
165
stationTileX: null,
151
166
stationTileY: null
152
167
};
@@ -168,7 +183,25 @@ export function mobComponents (request)
168
183
if (mobCanFight(def))
169
184
{
170
185
components.combat = { targetEntityId: null, nextSwingAt: 0 };
171
components.skills = { levels: mobSkillLevels(def) };
186
components.skills = { levels: mobSkillLevels(def, level) };
187
}
188
189
const knownSpells = normalizeMobSpells(request.spells, level);
190
if (knownSpells.length)
191
{
192
components.spells = {
193
known: knownSpells.map((entry) => entry.spellId),
194
favorites: [],
195
autoCast: false,
196
castChances: Object.fromEntries(knownSpells.map((entry) => [entry.spellId, entry.chance]))
197
};
198
components.spellcasting = {
199
armedSpellId: null,
200
repeatSpellId: null,
201
repeatTargetEntityId: null,
202
nextCastAt: 0,
203
pendingCast: null
204
};
172
205
}
173
206
174
207
const equipmentSlots = emptyEquipment().slots;
@@ -226,6 +259,35 @@ export function mobComponents (request)
226
259
return components;
227
260
}
228
261
262
function normalizeMobSpells (raw, level)
263
{
264
if (!Array.isArray(raw))
265
{ return []; }
266
const out = [];
267
const seen = new Set();
268
const lv = Math.max(1, level | 0 || 1);
269
for (const entry of raw)
270
{
271
if (!entry || typeof entry !== "object")
272
{ continue; }
273
const spellId = String(entry.spellId ?? "").trim();
274
if (!spellId || seen.has(spellId))
275
{ continue; }
276
const def = spellDefinition(spellId);
277
if (!def)
278
{ continue; }
279
const minLevel = Math.max(1, def.minMagicLevel | 0 || 1);
280
if (lv < minLevel)
281
{ continue; }
282
seen.add(spellId);
283
out.push({
284
spellId,
285
chance: Math.max(0, Math.min(100, Number(entry.chance) || 0)) | 0
286
});
287
}
288
return out;
289
}
290
229
291
function collectAmbientRequests (world, reserved = new Set())
230
292
{
231
293
const requests = [];
@@ -264,6 +326,9 @@ function collectAmbientRequests (world, reserved = new Set())
264
326
...tile,
265
327
mobTypeId: def.mobTypeId,
266
328
spawnerId: null,
329
level: 1,
330
bounty: 0,
331
spells: [],
267
332
persistent: false
268
333
});
269
334
}
@@ -1,13 +1,15 @@1
import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";1
import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";2
import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";2
import { mobCanFight, mobSkillLevels, mobHealthForLevel } from "../../../shared/definitions/mobCombat.js";3
import {3
import {4
normalizeSpawnerConfig,4
normalizeSpawnerConfig,5
listAmbientMobTypes,5
listAmbientMobTypes,6
mobDefinition,6
mobDefinition,7
mobSpriteName,7
mobSpriteName,8
MobId,8
MobId,9
spawnerEquipmentSlot9
spawnerEquipmentSlot,10
isTownGuardMob10
} from "../../../shared/definitions/mobs.js";11
} from "../../../shared/definitions/mobs.js";12
import { spellDefinition } from "../../../shared/definitions/spells.js";11
import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";13
import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";12
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";14
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";13
import { emptyEquipment } from "../../../shared/items/inventory.js";15
import { emptyEquipment } from "../../../shared/items/inventory.js";@@ -64,6 +66,9 @@ export function collectSpawnRequests (world)64
originTileX: originX,66
originTileX: originX,65
originTileY: originY,67
originTileY: originY,66
wanderRangeTiles: config.maxWanderRangeTiles,68
wanderRangeTiles: config.maxWanderRangeTiles,69
level: config.level,70
bounty: config.bounty,71
spells: config.spells,67
persistent,72
persistent,68
sex: staff.sex,73
sex: staff.sex,69
displayName: staff.name,74
displayName: staff.name,@@ -71,7 +76,8 @@ export function collectSpawnRequests (world)71
sells: [],76
sells: [],72
buysItems: false,77
buysItems: false,73
hiddenDiscount: config.hiddenDiscount,78
hiddenDiscount: config.hiddenDiscount,74
centralExchange: true79
centralExchange: true,80
townGuard: false75
});81
});76
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);82
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);77
}83
}@@ -91,6 +97,9 @@ export function collectSpawnRequests (world)91
originTileX: originX,97
originTileX: originX,92
originTileY: originY,98
originTileY: originY,93
wanderRangeTiles: config.maxWanderRangeTiles,99
wanderRangeTiles: config.maxWanderRangeTiles,100
level: config.level,101
bounty: config.bounty,102
spells: config.spells,94
persistent,103
persistent,95
sex: config.sex,104
sex: config.sex,96
displayName: config.displayName,105
displayName: config.displayName,@@ -98,7 +107,8 @@ export function collectSpawnRequests (world)98
sells: config.sells,107
sells: config.sells,99
buysItems: config.buysItems,108
buysItems: config.buysItems,100
hiddenDiscount: config.hiddenDiscount,109
hiddenDiscount: config.hiddenDiscount,101
centralExchange: false110
centralExchange: false,111
townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId)102
});112
});103
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);113
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);104
}114
}@@ -115,6 +125,7 @@ export function mobComponents (request)115
? request.sex125
? request.sex116
: (def.sex ?? "male");126
: (def.sex ?? "male");117
const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;127
const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;128
const level = Math.max(1, Math.min(99, Number(request.level) || 1)) | 0;118
const appearance = {129
const appearance = {119
sex,130
sex,120
firstName: displayName,131
firstName: displayName,@@ -131,13 +142,14 @@ export function mobComponents (request)131
{ appearance.sprite = sprite; }142
{ appearance.sprite = sprite; }132
}143
}133
144
145
const maxHp = mobHealthForLevel(def, level);134
const components = {146
const components = {135
position: { tileX: request.tileX, tileY: request.tileY },147
position: { tileX: request.tileX, tileY: request.tileY },136
movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },148
movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },137
path: { tiles: [] },149
path: { tiles: [] },138
appearance,150
appearance,139
creature: { mobTypeId: def.mobTypeId },151
creature: { mobTypeId: def.mobTypeId, level },140
health: { current: def.health ?? 8, max: def.health ?? 8 }152
health: { current: maxHp, max: maxHp }141
};153
};142
if (request.spawnerId)154
if (request.spawnerId)143
{155
{@@ -146,7 +158,10 @@ export function mobComponents (request)146
originTileX: request.originTileX ?? request.tileX,158
originTileX: request.originTileX ?? request.tileX,147
originTileY: request.originTileY ?? request.tileY,159
originTileY: request.originTileY ?? request.tileY,148
wanderRangeTiles: request.wanderRangeTiles ?? 4,160
wanderRangeTiles: request.wanderRangeTiles ?? 4,161
bounty: Math.max(0, Number(request.bounty) || 0) | 0,162
level,149
centralExchange: !!request.centralExchange,163
centralExchange: !!request.centralExchange,164
townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),150
stationTileX: null,165
stationTileX: null,151
stationTileY: null166
stationTileY: null152
};167
};@@ -168,7 +183,25 @@ export function mobComponents (request)168
if (mobCanFight(def))183
if (mobCanFight(def))169
{184
{170
components.combat = { targetEntityId: null, nextSwingAt: 0 };185
components.combat = { targetEntityId: null, nextSwingAt: 0 };171
components.skills = { levels: mobSkillLevels(def) };186
components.skills = { levels: mobSkillLevels(def, level) };187
}188
189
const knownSpells = normalizeMobSpells(request.spells, level);190
if (knownSpells.length)191
{192
components.spells = {193
known: knownSpells.map((entry) => entry.spellId),194
favorites: [],195
autoCast: false,196
castChances: Object.fromEntries(knownSpells.map((entry) => [entry.spellId, entry.chance]))197
};198
components.spellcasting = {199
armedSpellId: null,200
repeatSpellId: null,201
repeatTargetEntityId: null,202
nextCastAt: 0,203
pendingCast: null204
};172
}205
}173
206
174
const equipmentSlots = emptyEquipment().slots;207
const equipmentSlots = emptyEquipment().slots;@@ -226,6 +259,35 @@ export function mobComponents (request)226
return components;259
return components;227
}260
}228
261
262
function normalizeMobSpells (raw, level)263
{264
if (!Array.isArray(raw))265
{ return []; }266
const out = [];267
const seen = new Set();268
const lv = Math.max(1, level | 0 || 1);269
for (const entry of raw)270
{271
if (!entry || typeof entry !== "object")272
{ continue; }273
const spellId = String(entry.spellId ?? "").trim();274
if (!spellId || seen.has(spellId))275
{ continue; }276
const def = spellDefinition(spellId);277
if (!def)278
{ continue; }279
const minLevel = Math.max(1, def.minMagicLevel | 0 || 1);280
if (lv < minLevel)281
{ continue; }282
seen.add(spellId);283
out.push({284
spellId,285
chance: Math.max(0, Math.min(100, Number(entry.chance) || 0)) | 0286
});287
}288
return out;289
}290
229
function collectAmbientRequests (world, reserved = new Set())291
function collectAmbientRequests (world, reserved = new Set())230
{292
{231
const requests = [];293
const requests = [];@@ -264,6 +326,9 @@ function collectAmbientRequests (world, reserved = new Set())264
...tile,326
...tile,265
mobTypeId: def.mobTypeId,327
mobTypeId: def.mobTypeId,266
spawnerId: null,328
spawnerId: null,329
level: 1,330
bounty: 0,331
spells: [],267
persistent: false332
persistent: false268
});333
});269
}334
}@@ -139,6 +139,10 @@ export class WorkerWorld
139
139
return this.#applyBag(message.entityId, message.bag);
140
140
case WorkerMessage.applyAppearance:
141
141
return this.#applyAppearance(message.entityId, message.appearance);
142
case WorkerMessage.engageTarget:
143
return this.#engageTargetMessage(message);
144
case WorkerMessage.listTownGuardsNear:
145
return this.#listTownGuardsNear(message);
142
146
case WorkerMessage.updateFlight:
143
147
return this.#updateFlight(message.entityId, message.flight, message.now);
144
148
case WorkerMessage.chunkIsSimulating:
@@ -771,6 +775,50 @@ export class WorkerWorld
771
775
return { events: [] };
772
776
}
773
777
778
#engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() })
779
{
780
if (this.ecs.handleOf(attackerEntityId) == null)
781
{ return { ok: false }; }
782
engageTarget(this.ecs, attackerEntityId, targetEntityId, now);
783
return { ok: true };
784
}
785
786
/**
787
* Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY).
788
* Optionally restrict to one spawnerId.
789
*/
790
#listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 })
791
{
792
const guards = [];
793
for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position))
794
{
795
if (!entity.spawnOrigin?.townGuard)
796
{ continue; }
797
if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId)
798
{ continue; }
799
const originX = entity.spawnOrigin.originTileX;
800
const originY = entity.spawnOrigin.originTileY;
801
const range = entity.spawnOrigin.wanderRangeTiles | 0;
802
const dx = Math.abs(tileX - originX);
803
const dy = Math.abs(tileY - originY);
804
if (Math.max(dx, dy) > range)
805
{ continue; }
806
const health = this.ecs.get(entity.handle, Component.health);
807
if (health && health.current <= 0)
808
{ continue; }
809
if (this.ecs.has(entity.handle, Component.dead))
810
{ continue; }
811
guards.push({
812
entityId: entity.entityId,
813
spawnerId: entity.spawnOrigin.spawnerId,
814
busy: entity.combat?.targetEntityId != null
815
});
816
if (guards.length >= limit)
817
{ break; }
818
}
819
return { guards };
820
}
821
774
822
#applyRemoteMelee (payload)
775
823
{
776
824
return applyRemoteMeleeSwing(this, payload);
@@ -139,6 +139,10 @@ export class WorkerWorld139
return this.#applyBag(message.entityId, message.bag);139
return this.#applyBag(message.entityId, message.bag);140
case WorkerMessage.applyAppearance:140
case WorkerMessage.applyAppearance:141
return this.#applyAppearance(message.entityId, message.appearance);141
return this.#applyAppearance(message.entityId, message.appearance);142
case WorkerMessage.engageTarget:143
return this.#engageTargetMessage(message);144
case WorkerMessage.listTownGuardsNear:145
return this.#listTownGuardsNear(message);142
case WorkerMessage.updateFlight:146
case WorkerMessage.updateFlight:143
return this.#updateFlight(message.entityId, message.flight, message.now);147
return this.#updateFlight(message.entityId, message.flight, message.now);144
case WorkerMessage.chunkIsSimulating:148
case WorkerMessage.chunkIsSimulating:@@ -771,6 +775,50 @@ export class WorkerWorld771
return { events: [] };775
return { events: [] };772
}776
}773
777
778
#engageTargetMessage ({ attackerEntityId, targetEntityId, now = Date.now() })779
{780
if (this.ecs.handleOf(attackerEntityId) == null)781
{ return { ok: false }; }782
engageTarget(this.ecs, attackerEntityId, targetEntityId, now);783
return { ok: true };784
}785
786
/**787
* Idle town-guard entity ids from spawners whose wander range covers (tileX, tileY).788
* Optionally restrict to one spawnerId.789
*/790
#listTownGuardsNear ({ tileX, tileY, spawnerId = null, limit = 8 })791
{792
const guards = [];793
for (const entity of this.ecs.query(Component.spawnOrigin, Component.creature, Component.combat, Component.position))794
{795
if (!entity.spawnOrigin?.townGuard)796
{ continue; }797
if (spawnerId != null && entity.spawnOrigin.spawnerId !== spawnerId)798
{ continue; }799
const originX = entity.spawnOrigin.originTileX;800
const originY = entity.spawnOrigin.originTileY;801
const range = entity.spawnOrigin.wanderRangeTiles | 0;802
const dx = Math.abs(tileX - originX);803
const dy = Math.abs(tileY - originY);804
if (Math.max(dx, dy) > range)805
{ continue; }806
const health = this.ecs.get(entity.handle, Component.health);807
if (health && health.current <= 0)808
{ continue; }809
if (this.ecs.has(entity.handle, Component.dead))810
{ continue; }811
guards.push({812
entityId: entity.entityId,813
spawnerId: entity.spawnOrigin.spawnerId,814
busy: entity.combat?.targetEntityId != null815
});816
if (guards.length >= limit)817
{ break; }818
}819
return { guards };820
}821
774
#applyRemoteMelee (payload)822
#applyRemoteMelee (payload)775
{823
{776
return applyRemoteMeleeSwing(this, payload);824
return applyRemoteMeleeSwing(this, payload);@@ -0,0 +1,110 @@
1
import { Component } from "../ecs/components.js";
2
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
3
import { spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";
4
import {
5
CAST_FLASH_MS,
6
SPELL_COOLDOWN_MS,
7
SPELL_PROJECTILE_MS,
8
castFlashRadiusTiles
9
} from "../../../shared/spells/constants.js";
10
import { resolveSpellCast } from "../../../shared/combat/magic.js";
11
import { hasCombatLineOfSight, chebyshev } from "../combat/service.js";
12
import { COMBAT_RANGE_TILES } from "../../../shared/spells/constants.js";
13
14
/**
15
* Server-side attack-spell cast for mobs (no player session / inventory).
16
* Queues the same projectile + impact pipeline as player casts.
17
*/
18
export function castMobAttackSpell (world, casterId, targetId, spellId, now = Date.now())
19
{
20
const events = [];
21
const handle = world.ecs.handleOf(casterId);
22
if (handle == null)
23
{ return events; }
24
const def = spellDefinition(spellId);
25
if (!def || def.target !== "entity")
26
{ return events; }
27
const from = world.ecs.get(handle, Component.position);
28
const targetHandle = world.ecs.handleOf(targetId);
29
const targetPos = targetHandle != null ? world.ecs.get(targetHandle, Component.position) : null;
30
if (!from || !targetPos)
31
{ return events; }
32
const dist = chebyshev(from.tileX, from.tileY, targetPos.tileX, targetPos.tileY);
33
if (dist < 1 || dist > COMBAT_RANGE_TILES)
34
{ return events; }
35
if (!hasCombatLineOfSight(world, from.tileX, from.tileY, targetPos.tileX, targetPos.tileY))
36
{ return events; }
37
38
const skills = world.ecs.get(handle, Component.skills);
39
const levels = {
40
magic: skillLevel(skills, SkillId.magic),
41
mind: skillLevel(skills, SkillId.mind)
42
};
43
const difficulty = spellDifficulty(def);
44
const cast = resolveSpellCast({
45
magicSkillLevel: levels.magic,
46
spellDifficulty: difficulty
47
});
48
49
let casting = world.ecs.get(handle, Component.spellcasting);
50
if (!casting)
51
{
52
casting = world.ecs.add(handle, Component.spellcasting, {
53
armedSpellId: null,
54
repeatSpellId: null,
55
repeatTargetEntityId: null,
56
nextCastAt: 0,
57
pendingCast: null
58
});
59
}
60
casting.nextCastAt = now + SPELL_COOLDOWN_MS;
61
62
if (!cast.success)
63
{
64
events.push({
65
type: "spell-fizzle",
66
casterId,
67
spellId,
68
fromTileX: from.tileX,
69
fromTileY: from.tileY,
70
tileX: targetPos.tileX,
71
tileY: targetPos.tileY
72
});
73
return events;
74
}
75
76
events.push({
77
type: "spell-cast-flash",
78
casterId,
79
tileX: from.tileX,
80
tileY: from.tileY,
81
radiusTiles: castFlashRadiusTiles(def.tier),
82
durationMs: CAST_FLASH_MS,
83
tier: def.tier
84
});
85
86
world.pendingSpellImpacts = world.pendingSpellImpacts ?? [];
87
world.pendingSpellImpacts.push({
88
executeAt: now + SPELL_PROJECTILE_MS,
89
casterEntityId: casterId,
90
casterCharacterId: null,
91
spellId,
92
targetTileX: targetPos.tileX,
93
targetTileY: targetPos.tileY,
94
targetEntityId: targetId,
95
levels
96
});
97
98
events.push({
99
type: "spell-projectile",
100
casterId,
101
spellId,
102
fromTileX: from.tileX,
103
fromTileY: from.tileY,
104
tileX: targetPos.tileX,
105
tileY: targetPos.tileY,
106
durationMs: SPELL_PROJECTILE_MS,
107
sprite: def.projectileSprite
108
});
109
return events;
110
}
@@ -0,0 +1,110 @@1
import { Component } from "../ecs/components.js";2
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";3
import { spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";4
import {5
CAST_FLASH_MS,6
SPELL_COOLDOWN_MS,7
SPELL_PROJECTILE_MS,8
castFlashRadiusTiles9
} from "../../../shared/spells/constants.js";10
import { resolveSpellCast } from "../../../shared/combat/magic.js";11
import { hasCombatLineOfSight, chebyshev } from "../combat/service.js";12
import { COMBAT_RANGE_TILES } from "../../../shared/spells/constants.js";13
14
/**15
* Server-side attack-spell cast for mobs (no player session / inventory).16
* Queues the same projectile + impact pipeline as player casts.17
*/18
export function castMobAttackSpell (world, casterId, targetId, spellId, now = Date.now())19
{20
const events = [];21
const handle = world.ecs.handleOf(casterId);22
if (handle == null)23
{ return events; }24
const def = spellDefinition(spellId);25
if (!def || def.target !== "entity")26
{ return events; }27
const from = world.ecs.get(handle, Component.position);28
const targetHandle = world.ecs.handleOf(targetId);29
const targetPos = targetHandle != null ? world.ecs.get(targetHandle, Component.position) : null;30
if (!from || !targetPos)31
{ return events; }32
const dist = chebyshev(from.tileX, from.tileY, targetPos.tileX, targetPos.tileY);33
if (dist < 1 || dist > COMBAT_RANGE_TILES)34
{ return events; }35
if (!hasCombatLineOfSight(world, from.tileX, from.tileY, targetPos.tileX, targetPos.tileY))36
{ return events; }37
38
const skills = world.ecs.get(handle, Component.skills);39
const levels = {40
magic: skillLevel(skills, SkillId.magic),41
mind: skillLevel(skills, SkillId.mind)42
};43
const difficulty = spellDifficulty(def);44
const cast = resolveSpellCast({45
magicSkillLevel: levels.magic,46
spellDifficulty: difficulty47
});48
49
let casting = world.ecs.get(handle, Component.spellcasting);50
if (!casting)51
{52
casting = world.ecs.add(handle, Component.spellcasting, {53
armedSpellId: null,54
repeatSpellId: null,55
repeatTargetEntityId: null,56
nextCastAt: 0,57
pendingCast: null58
});59
}60
casting.nextCastAt = now + SPELL_COOLDOWN_MS;61
62
if (!cast.success)63
{64
events.push({65
type: "spell-fizzle",66
casterId,67
spellId,68
fromTileX: from.tileX,69
fromTileY: from.tileY,70
tileX: targetPos.tileX,71
tileY: targetPos.tileY72
});73
return events;74
}75
76
events.push({77
type: "spell-cast-flash",78
casterId,79
tileX: from.tileX,80
tileY: from.tileY,81
radiusTiles: castFlashRadiusTiles(def.tier),82
durationMs: CAST_FLASH_MS,83
tier: def.tier84
});85
86
world.pendingSpellImpacts = world.pendingSpellImpacts ?? [];87
world.pendingSpellImpacts.push({88
executeAt: now + SPELL_PROJECTILE_MS,89
casterEntityId: casterId,90
casterCharacterId: null,91
spellId,92
targetTileX: targetPos.tileX,93
targetTileY: targetPos.tileY,94
targetEntityId: targetId,95
levels96
});97
98
events.push({99
type: "spell-projectile",100
casterId,101
spellId,102
fromTileX: from.tileX,103
fromTileY: from.tileY,104
tileX: targetPos.tileX,105
tileY: targetPos.tileY,106
durationMs: SPELL_PROJECTILE_MS,107
sprite: def.projectileSprite108
});109
return events;110
}@@ -31,7 +31,8 @@ import {
31
31
chebyshev,
32
32
hasCombatLineOfSight,
33
33
queueStandInRangeApproach,
34
resolveCombatTarget
34
resolveCombatTarget,
35
applyDamageAndKill
35
36
} from "../combat/service.js";
36
37
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
37
38
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
@@ -513,9 +514,6 @@ function applySpellImpact (world, impact, now)
513
514
514
515
if (impact.spellId === SpellId.spark && impact.targetEntityId != null)
515
516
{
516
const targetHandle = world.ecs.handleOf(impact.targetEntityId);
517
if (targetHandle == null)
518
{ return events; }
519
517
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
520
518
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
521
519
let multiplier = ElementMultiplier.neutral;
@@ -525,23 +523,15 @@ function applySpellImpact (world, impact, now)
525
523
else if (affinity === "resistant")
526
524
{ multiplier = ElementMultiplier.resistant; }
527
525
const damage = Math.max(1, Math.floor(mindRoll * multiplier));
528
const health = world.ecs.get(targetHandle, Component.health);
529
if (health)
530
{
531
health.current = Math.max(0, (health.current | 0) - damage);
532
}
533
events.push({
534
type: "combat-hit",
535
attackerId: impact.casterEntityId,
536
targetId: impact.targetEntityId,
526
events.push(...applyDamageAndKill(
527
world,
528
impact.casterEntityId,
529
impact.targetEntityId,
537
530
damage,
538
tileX: impact.targetTileX,
539
tileY: impact.targetTileY,
540
health: health?.current ?? 0,
541
maxHealth: health?.max ?? 0
542
});
531
now
532
));
543
533
const casterHandle = world.ecs.handleOf(impact.casterEntityId);
544
if (casterHandle != null)
534
if (casterHandle != null && impact.casterCharacterId)
545
535
{
546
536
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
547
537
if (xp)
@@ -556,18 +546,6 @@ function applySpellImpact (world, impact, now)
556
546
});
557
547
}
558
548
}
559
const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
560
if (healthXp)
561
{
562
events.push({
563
type: "skills-updated",
564
entityId: impact.targetEntityId,
565
characterId: healthXp.characterId,
566
skills: healthXp.view,
567
stored: healthXp.stored,
568
levelUps: healthXp.levelUps ?? []
569
});
570
}
571
549
}
572
550
return events;
573
551
}
@@ -31,7 +31,8 @@ import {31
chebyshev,31
chebyshev,32
hasCombatLineOfSight,32
hasCombatLineOfSight,33
queueStandInRangeApproach,33
queueStandInRangeApproach,34
resolveCombatTarget34
resolveCombatTarget,35
applyDamageAndKill35
} from "../combat/service.js";36
} from "../combat/service.js";36
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";37
import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";37
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";38
import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";@@ -513,9 +514,6 @@ function applySpellImpact (world, impact, now)513
514
514
if (impact.spellId === SpellId.spark && impact.targetEntityId != null)515
if (impact.spellId === SpellId.spark && impact.targetEntityId != null)515
{516
{516
const targetHandle = world.ecs.handleOf(impact.targetEntityId);517
if (targetHandle == null)518
{ return events; }519
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);517
const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);520
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;518
const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;521
let multiplier = ElementMultiplier.neutral;519
let multiplier = ElementMultiplier.neutral;@@ -525,23 +523,15 @@ function applySpellImpact (world, impact, now)525
else if (affinity === "resistant")523
else if (affinity === "resistant")526
{ multiplier = ElementMultiplier.resistant; }524
{ multiplier = ElementMultiplier.resistant; }527
const damage = Math.max(1, Math.floor(mindRoll * multiplier));525
const damage = Math.max(1, Math.floor(mindRoll * multiplier));528
const health = world.ecs.get(targetHandle, Component.health);526
events.push(...applyDamageAndKill(529
if (health)527
world,530
{528
impact.casterEntityId,531
health.current = Math.max(0, (health.current | 0) - damage);529
impact.targetEntityId,532
}533
events.push({534
type: "combat-hit",535
attackerId: impact.casterEntityId,536
targetId: impact.targetEntityId,537
damage,530
damage,538
tileX: impact.targetTileX,531
now539
tileY: impact.targetTileY,532
));540
health: health?.current ?? 0,541
maxHealth: health?.max ?? 0542
});543
const casterHandle = world.ecs.handleOf(impact.casterEntityId);533
const casterHandle = world.ecs.handleOf(impact.casterEntityId);544
if (casterHandle != null)534
if (casterHandle != null && impact.casterCharacterId)545
{535
{546
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);536
const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);547
if (xp)537
if (xp)@@ -556,18 +546,6 @@ function applySpellImpact (world, impact, now)556
});546
});557
}547
}558
}548
}559
const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);560
if (healthXp)561
{562
events.push({563
type: "skills-updated",564
entityId: impact.targetEntityId,565
characterId: healthXp.characterId,566
skills: healthXp.view,567
stored: healthXp.stored,568
levelUps: healthXp.levelUps ?? []569
});570
}571
}549
}572
return events;550
return events;573
}551
}@@ -0,0 +1,210 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import {
4
MobId,
5
normalizeSpawnerConfig,
6
mobMaxHealthForLevel,
7
mobLevelDisplayName,
8
mobDefinition
9
} from "../../shared/definitions/mobs.js";
10
import { mobCanFight } from "../../shared/definitions/mobCombat.js";
11
import { SpellId } from "../../shared/definitions/spells.js";
12
import { SkillId } from "../../shared/definitions/skills.js";
13
import { mobComponents } from "../src/simulation/spawners.js";
14
import { Component } from "../src/ecs/components.js";
15
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
16
import { ItemId } from "../../shared/definitions/items.js";
17
18
test("spawner config defaults bounty 0 and level 1", () =>
19
{
20
const config = normalizeSpawnerConfig({ mobTypeId: MobId.deer }, "0:0:1");
21
assert.equal(config.bounty, 0);
22
assert.equal(config.level, 1);
23
assert.deepEqual(config.spells, []);
24
});
25
26
test("spawner config keeps bounty, level, and spells", () =>
27
{
28
const config = normalizeSpawnerConfig({
29
mobTypeId: MobId.rat,
30
level: 5,
31
bounty: 25,
32
spells: [
33
{ spellId: SpellId.spark, chance: 75 },
34
{ spellId: SpellId.light, chance: 0 },
35
{ spellId: SpellId.spark, chance: 10 }
36
]
37
}, "s1");
38
assert.equal(config.level, 5);
39
assert.equal(config.bounty, 25);
40
assert.equal(config.spells.length, 2);
41
assert.equal(config.spells[0].spellId, SpellId.spark);
42
assert.equal(config.spells[0].chance, 75);
43
assert.equal(config.spells[1].chance, 0);
44
});
45
46
test("town guard is a fightable humanoid body mob", () =>
47
{
48
const def = mobDefinition(MobId.townGuard);
49
assert.ok(def.usePlayerBody);
50
assert.ok(def.townGuard);
51
assert.equal(mobCanFight(def), true);
52
assert.equal(mobCanFight(mobDefinition(MobId.humanoid)), true);
53
assert.equal(mobMaxHealthForLevel(def, 1), 11);
54
assert.equal(mobMaxHealthForLevel(def, 10), 20);
55
assert.equal(mobLevelDisplayName(7, "Town Guard"), "Lv.7 Town Guard");
56
});
57
58
test("mob components use spawner level for skills, HP, bounty origin, and spells", () =>
59
{
60
const components = mobComponents({
61
tileX: 8,
62
tileY: 8,
63
mobTypeId: MobId.townGuard,
64
spawnerId: "0:0:3",
65
originTileX: 8,
66
originTileY: 8,
67
wanderRangeTiles: 6,
68
level: 4,
69
bounty: 12,
70
displayName: "Captain",
71
sex: "male",
72
spells: [
73
{ spellId: SpellId.spark, chance: 50 },
74
{ spellId: SpellId.light, chance: 100 }
75
]
76
});
77
assert.equal(components.creature.level, 4);
78
assert.equal(components.health.max, 14);
79
assert.equal(components.health.current, 14);
80
assert.equal(components.skills.levels[SkillId.magic], 4);
81
assert.equal(components.skills.levels[SkillId.unarmed], 4);
82
assert.equal(components.spawnOrigin.bounty, 12);
83
assert.equal(components.spawnOrigin.townGuard, true);
84
assert.ok(components.spells.known.includes(SpellId.spark));
85
assert.ok(components.spells.known.includes(SpellId.light));
86
assert.equal(components.spells.castChances[SpellId.spark], 50);
87
});
88
89
test("mobs below spell minMagicLevel do not learn the spell", () =>
90
{
91
const components = mobComponents({
92
tileX: 8,
93
tileY: 8,
94
mobTypeId: MobId.rat,
95
spawnerId: "0:0:4",
96
level: 1,
97
spells: [{ spellId: SpellId.spark, chance: 100 }]
98
});
99
assert.equal(components.spells, undefined);
100
});
101
102
test("killing a bounty mob awards player bounty and can wake town guards", () =>
103
{
104
const harness = makeSimulation({ workerCount: 1 });
105
const random = Math.random;
106
Math.random = () => 0;
107
try
108
{
109
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
110
const playerId = harness.simulation.spawnCharacter(1, character);
111
const ratId = harness.simulation.spawnEntity(mobComponents({
112
tileX: 9,
113
tileY: 8,
114
mobTypeId: MobId.rat,
115
spawnerId: "bounty-rat",
116
originTileX: 9,
117
originTileY: 8,
118
wanderRangeTiles: 4,
119
level: 1,
120
bounty: 40
121
}));
122
const worker = harness.simulation.workers[0];
123
const ratHealth = worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health);
124
ratHealth.current = 1;
125
ratHealth.max = 1;
126
127
const guardId = harness.simulation.spawnEntity(mobComponents({
128
tileX: 10,
129
tileY: 8,
130
mobTypeId: MobId.townGuard,
131
spawnerId: "guard-1",
132
originTileX: 8,
133
originTileY: 8,
134
wanderRangeTiles: 8,
135
level: 3,
136
displayName: "Guard",
137
sex: "male",
138
townGuard: true
139
}));
140
141
harness.simulation.enqueue(1, {
142
type: "attack",
143
characterId: character.character_id,
144
targetEntityId: ratId
145
});
146
let killed = false;
147
for (let i = 0; i < 80; i++)
148
{
149
harness.advance(50);
150
const step = harness.simulation.step();
151
if (step.events.some((event) => event.type === "mob-killed" && event.entityId === ratId))
152
{
153
killed = true;
154
break;
155
}
156
}
157
assert.ok(killed, "expected rat kill");
158
assert.equal(harness.stateDb.getCharacterBounty(character.character_id), 40);
159
160
const guardHandle = worker.world.ecs.handleOf(guardId);
161
const guardCombat = worker.world.ecs.get(guardHandle, Component.combat);
162
assert.equal(guardCombat?.targetEntityId, playerId);
163
}
164
finally
165
{
166
Math.random = random;
167
harness.close();
168
}
169
});
170
171
test("humanoids retaliate when attacked", () =>
172
{
173
const harness = makeSimulation({ workerCount: 1 });
174
try
175
{
176
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
177
const playerId = harness.simulation.spawnCharacter(1, character);
178
const npcId = harness.simulation.spawnEntity(mobComponents({
179
tileX: 9,
180
tileY: 8,
181
mobTypeId: MobId.humanoid,
182
spawnerId: "shop-1",
183
level: 2,
184
displayName: "Shopkeep",
185
sex: "male",
186
equipment: { weapon: ItemId.stick }
187
}));
188
harness.simulation.enqueue(1, {
189
type: "attack",
190
characterId: character.character_id,
191
targetEntityId: npcId
192
});
193
let retaliated = false;
194
for (let i = 0; i < 40; i++)
195
{
196
harness.advance(50);
197
harness.simulation.step();
198
const worker = harness.simulation.workers[0];
199
const combat = worker.world.ecs.get(worker.world.ecs.handleOf(npcId), Component.combat);
200
if (combat?.targetEntityId === playerId)
201
{
202
retaliated = true;
203
break;
204
}
205
}
206
assert.ok(retaliated, "humanoid should engage the attacker");
207
}
208
finally
209
{ harness.close(); }
210
});
@@ -0,0 +1,210 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import {4
MobId,5
normalizeSpawnerConfig,6
mobMaxHealthForLevel,7
mobLevelDisplayName,8
mobDefinition9
} from "../../shared/definitions/mobs.js";10
import { mobCanFight } from "../../shared/definitions/mobCombat.js";11
import { SpellId } from "../../shared/definitions/spells.js";12
import { SkillId } from "../../shared/definitions/skills.js";13
import { mobComponents } from "../src/simulation/spawners.js";14
import { Component } from "../src/ecs/components.js";15
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";16
import { ItemId } from "../../shared/definitions/items.js";17
18
test("spawner config defaults bounty 0 and level 1", () =>19
{20
const config = normalizeSpawnerConfig({ mobTypeId: MobId.deer }, "0:0:1");21
assert.equal(config.bounty, 0);22
assert.equal(config.level, 1);23
assert.deepEqual(config.spells, []);24
});25
26
test("spawner config keeps bounty, level, and spells", () =>27
{28
const config = normalizeSpawnerConfig({29
mobTypeId: MobId.rat,30
level: 5,31
bounty: 25,32
spells: [33
{ spellId: SpellId.spark, chance: 75 },34
{ spellId: SpellId.light, chance: 0 },35
{ spellId: SpellId.spark, chance: 10 }36
]37
}, "s1");38
assert.equal(config.level, 5);39
assert.equal(config.bounty, 25);40
assert.equal(config.spells.length, 2);41
assert.equal(config.spells[0].spellId, SpellId.spark);42
assert.equal(config.spells[0].chance, 75);43
assert.equal(config.spells[1].chance, 0);44
});45
46
test("town guard is a fightable humanoid body mob", () =>47
{48
const def = mobDefinition(MobId.townGuard);49
assert.ok(def.usePlayerBody);50
assert.ok(def.townGuard);51
assert.equal(mobCanFight(def), true);52
assert.equal(mobCanFight(mobDefinition(MobId.humanoid)), true);53
assert.equal(mobMaxHealthForLevel(def, 1), 11);54
assert.equal(mobMaxHealthForLevel(def, 10), 20);55
assert.equal(mobLevelDisplayName(7, "Town Guard"), "Lv.7 Town Guard");56
});57
58
test("mob components use spawner level for skills, HP, bounty origin, and spells", () =>59
{60
const components = mobComponents({61
tileX: 8,62
tileY: 8,63
mobTypeId: MobId.townGuard,64
spawnerId: "0:0:3",65
originTileX: 8,66
originTileY: 8,67
wanderRangeTiles: 6,68
level: 4,69
bounty: 12,70
displayName: "Captain",71
sex: "male",72
spells: [73
{ spellId: SpellId.spark, chance: 50 },74
{ spellId: SpellId.light, chance: 100 }75
]76
});77
assert.equal(components.creature.level, 4);78
assert.equal(components.health.max, 14);79
assert.equal(components.health.current, 14);80
assert.equal(components.skills.levels[SkillId.magic], 4);81
assert.equal(components.skills.levels[SkillId.unarmed], 4);82
assert.equal(components.spawnOrigin.bounty, 12);83
assert.equal(components.spawnOrigin.townGuard, true);84
assert.ok(components.spells.known.includes(SpellId.spark));85
assert.ok(components.spells.known.includes(SpellId.light));86
assert.equal(components.spells.castChances[SpellId.spark], 50);87
});88
89
test("mobs below spell minMagicLevel do not learn the spell", () =>90
{91
const components = mobComponents({92
tileX: 8,93
tileY: 8,94
mobTypeId: MobId.rat,95
spawnerId: "0:0:4",96
level: 1,97
spells: [{ spellId: SpellId.spark, chance: 100 }]98
});99
assert.equal(components.spells, undefined);100
});101
102
test("killing a bounty mob awards player bounty and can wake town guards", () =>103
{104
const harness = makeSimulation({ workerCount: 1 });105
const random = Math.random;106
Math.random = () => 0;107
try108
{109
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });110
const playerId = harness.simulation.spawnCharacter(1, character);111
const ratId = harness.simulation.spawnEntity(mobComponents({112
tileX: 9,113
tileY: 8,114
mobTypeId: MobId.rat,115
spawnerId: "bounty-rat",116
originTileX: 9,117
originTileY: 8,118
wanderRangeTiles: 4,119
level: 1,120
bounty: 40121
}));122
const worker = harness.simulation.workers[0];123
const ratHealth = worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health);124
ratHealth.current = 1;125
ratHealth.max = 1;126
127
const guardId = harness.simulation.spawnEntity(mobComponents({128
tileX: 10,129
tileY: 8,130
mobTypeId: MobId.townGuard,131
spawnerId: "guard-1",132
originTileX: 8,133
originTileY: 8,134
wanderRangeTiles: 8,135
level: 3,136
displayName: "Guard",137
sex: "male",138
townGuard: true139
}));140
141
harness.simulation.enqueue(1, {142
type: "attack",143
characterId: character.character_id,144
targetEntityId: ratId145
});146
let killed = false;147
for (let i = 0; i < 80; i++)148
{149
harness.advance(50);150
const step = harness.simulation.step();151
if (step.events.some((event) => event.type === "mob-killed" && event.entityId === ratId))152
{153
killed = true;154
break;155
}156
}157
assert.ok(killed, "expected rat kill");158
assert.equal(harness.stateDb.getCharacterBounty(character.character_id), 40);159
160
const guardHandle = worker.world.ecs.handleOf(guardId);161
const guardCombat = worker.world.ecs.get(guardHandle, Component.combat);162
assert.equal(guardCombat?.targetEntityId, playerId);163
}164
finally165
{166
Math.random = random;167
harness.close();168
}169
});170
171
test("humanoids retaliate when attacked", () =>172
{173
const harness = makeSimulation({ workerCount: 1 });174
try175
{176
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });177
const playerId = harness.simulation.spawnCharacter(1, character);178
const npcId = harness.simulation.spawnEntity(mobComponents({179
tileX: 9,180
tileY: 8,181
mobTypeId: MobId.humanoid,182
spawnerId: "shop-1",183
level: 2,184
displayName: "Shopkeep",185
sex: "male",186
equipment: { weapon: ItemId.stick }187
}));188
harness.simulation.enqueue(1, {189
type: "attack",190
characterId: character.character_id,191
targetEntityId: npcId192
});193
let retaliated = false;194
for (let i = 0; i < 40; i++)195
{196
harness.advance(50);197
harness.simulation.step();198
const worker = harness.simulation.workers[0];199
const combat = worker.world.ecs.get(worker.world.ecs.handleOf(npcId), Component.combat);200
if (combat?.targetEntityId === playerId)201
{202
retaliated = true;203
break;204
}205
}206
assert.ok(retaliated, "humanoid should engage the attacker");207
}208
finally209
{ harness.close(); }210
});