Melee mobs seek cover when retaliating to ranged or spells.
Approach paths weight LOS-exposed tiles higher so they close behind walls, and if no melee stand is reachable they flee to the nearest tile the player cannot shoot. Ranged/spell-capable mobs still path for line of sight.
@@ -117,7 +117,7 @@ export function ensureMobCombat (ecs, entityId)
117
117
const def = mobDefinition(creature.mobTypeId);
118
118
const level = creatureLevel(ecs, handle);
119
119
if (!ecs.get(handle, Component.combat))
120
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
120
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false }); }
121
121
if (!ecs.get(handle, Component.skills))
122
122
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }
123
123
return true;
@@ -171,7 +171,7 @@ export function engageTarget (ecs, attackerId, targetId, now = Date.now())
171
171
{ return false; }
172
172
let combat = ecs.get(handle, Component.combat);
173
173
if (!combat)
174
{ combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
174
{ combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false }); }
175
175
const targetChanged = combat.targetEntityId !== targetId;
176
176
combat.targetEntityId = targetId;
177
177
if (targetChanged)
@@ -185,6 +185,15 @@ export function engageTarget (ecs, attackerId, targetId, now = Date.now())
185
185
return true;
186
186
}
187
187
188
/** Melee mobs shot by player ranged/spells prefer cover while closing. */
189
export function markSeekCover (ecs, entityId)
190
{
191
const handle = ecs.handleOf(entityId);
192
const combat = handle != null ? ecs.get(handle, Component.combat) : null;
193
if (combat)
194
{ combat.seekCover = true; }
195
}
196
188
197
/** Pending cast or entity-spell auto-repeat — physical combat must not run. */
189
198
export function isSpellCombatBusy (ecs, handle)
190
199
{
@@ -217,7 +226,10 @@ export function clearEngage (ecs, entityId)
217
226
const handle = ecs.handleOf(entityId);
218
227
const combat = handle != null ? ecs.get(handle, Component.combat) : null;
219
228
if (combat)
220
{ combat.targetEntityId = null; }
229
{
230
combat.targetEntityId = null;
231
combat.seekCover = false;
232
}
221
233
}
222
234
223
235
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
@@ -772,6 +784,170 @@ function combatGoalPreference (entityId, tileX, tileY)
772
784
return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
773
785
}
774
786
787
/** Cost multiplier for tiles the threat can currently shoot. */
788
const COVER_EXPOSED_STEP_COST = 5;
789
790
function mobHasRangedRetaliation (world, handle)
791
{
792
const profile = attackProfileOf(world.ecs, handle);
793
if (profile?.mode === "ranged")
794
{ return true; }
795
return eligibleMobAttackSpells(world.ecs, handle).length > 0;
796
}
797
798
/** Melee-only creatures closing after a player ranged/spell hit. */
799
function shouldSeekCoverApproach (world, handle)
800
{
801
if (world.ecs.get(handle, Component.character))
802
{ return false; }
803
if (!world.ecs.get(handle, Component.creature))
804
{ return false; }
805
const combat = world.ecs.get(handle, Component.combat);
806
if (!combat?.seekCover)
807
{ return false; }
808
return !mobHasRangedRetaliation(world, handle);
809
}
810
811
function coverStepCost (world, threatPos, goalX, goalY, x, y)
812
{
813
// Final adjacent step is always in LOS — don't punish the last lunge.
814
if (x === goalX && y === goalY)
815
{ return 1; }
816
if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y))
817
{ return COVER_EXPOSED_STEP_COST; }
818
return 1;
819
}
820
821
function pathCoverScore (world, threatPos, tiles)
822
{
823
let score = 0;
824
for (const step of tiles)
825
{
826
score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y)
827
? COVER_EXPOSED_STEP_COST
828
: 1;
829
}
830
return score;
831
}
832
833
function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved)
834
{
835
const dirs = [
836
{ x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
837
{ x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
838
];
839
const goals = [];
840
for (const dir of dirs)
841
{
842
const x = targetPos.tileX + dir.x;
843
const y = targetPos.tileY + dir.y;
844
const isHere = x === position.tileX && y === position.tileY;
845
const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
846
const key = combatTileKey(x, y);
847
if (reserved?.has(key) && !(isHere && aloneHere))
848
{ continue; }
849
const clear = world.isClearStanding?.(entityId, x, y)
850
?? world.walkableFor(entityId, x, y);
851
if (!clear && !isHere)
852
{ continue; }
853
if (isHere && !aloneHere)
854
{ continue; }
855
goals.push({ x, y });
856
}
857
return goals;
858
}
859
860
function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved)
861
{
862
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
863
const preferVertical = !!world.ecs.get(handle, Component.character);
864
const isWalkable = (x, y, goal) =>
865
{
866
if (x === goal.x && y === goal.y)
867
{
868
return world.isClearStanding?.(entityId, x, y)
869
?? world.walkableFor(entityId, x, y);
870
}
871
return world.walkableFor(entityId, x, y);
872
};
873
let bestTiles = null;
874
let bestScore = Infinity;
875
let bestPref = Infinity;
876
for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved))
877
{
878
if (goal.x === position.tileX && goal.y === position.tileY)
879
{ return []; }
880
const tiles = findPath(
881
position.tileX,
882
position.tileY,
883
goal.x,
884
goal.y,
885
(x, y) => isWalkable(x, y, goal),
886
bounds.minX,
887
bounds.minY,
888
bounds.maxX,
889
bounds.maxY,
890
{
891
preferVertical,
892
stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
893
}
894
);
895
if (!tiles.length)
896
{ continue; }
897
const score = pathCoverScore(world, targetPos, tiles);
898
const pref = combatGoalPreference(entityId, goal.x, goal.y);
899
if (score < bestScore || (score === bestScore && pref < bestPref))
900
{
901
bestScore = score;
902
bestPref = pref;
903
bestTiles = tiles;
904
}
905
}
906
return bestTiles;
907
}
908
909
/** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */
910
function queueFleeToCover (world, entityId, handle, position, threatPos)
911
{
912
let path = world.ecs.get(handle, Component.path);
913
if (!path)
914
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }
915
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
916
const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
917
const isGoal = (x, y) =>
918
{
919
if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
920
{ return false; }
921
if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)
922
{ return false; }
923
return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y);
924
};
925
if (isGoal(position.tileX, position.tileY))
926
{
927
path.tiles = [];
928
return;
929
}
930
const tiles = findPathToNearestGoal(
931
position.tileX,
932
position.tileY,
933
isGoal,
934
isWalkable,
935
bounds.minX,
936
bounds.minY,
937
bounds.maxX,
938
bounds.maxY
939
);
940
if (!tiles.length)
941
{
942
path.tiles = [];
943
return;
944
}
945
path.tiles = tiles;
946
const movement = world.ecs.get(handle, Component.movement);
947
if (movement)
948
{ movement.walkCarry = 0; }
949
}
950
775
951
export function queueMeleeApproach (world, entityId, handle, position, targetPos)
776
952
{
777
953
if (world.frozen?.has?.(entityId))
@@ -790,6 +966,38 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
790
966
791
967
const combat = world.ecs.get(handle, Component.combat);
792
968
const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
969
const seekCover = shouldSeekCoverApproach(world, handle);
970
971
if (seekCover)
972
{
973
const coverTiles = findCoverMeleeApproachPath(
974
world,
975
entityId,
976
handle,
977
position,
978
targetPos,
979
reserved
980
);
981
if (coverTiles)
982
{
983
if (!coverTiles.length)
984
{
985
path.tiles = [];
986
return;
987
}
988
const goal = coverTiles[coverTiles.length - 1];
989
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
990
{ return; }
991
path.tiles = coverTiles;
992
const movement = world.ecs.get(handle, Component.movement);
993
if (movement)
994
{ movement.walkCarry = 0; }
995
return;
996
}
997
queueFleeToCover(world, entityId, handle, position, targetPos);
998
return;
999
}
1000
793
1001
const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
794
1002
if (!goal)
795
1003
{
@@ -1305,7 +1513,11 @@ function applyLocalMeleeHit (
1305
1513
1306
1514
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
1307
1515
if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
1308
{ engageTarget(world.ecs, targetId, attackerId, now); }
1516
{
1517
engageTarget(world.ecs, targetId, attackerId, now);
1518
if (profile?.mode === "ranged")
1519
{ markSeekCover(world.ecs, targetId); }
1520
}
1309
1521
if (attackerIsPlayer === false)
1310
1522
{
1311
1523
const targetCharacter = world.ecs.get(targetHandle, Component.character);
@@ -1604,9 +1816,12 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D
1604
1816
const attackerHandle = world.ecs.handleOf(attackerId);
1605
1817
if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
1606
1818
{
1819
const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
1607
1820
const targetCombat = world.ecs.get(targetHandle, Component.combat);
1608
1821
if (targetCombat && targetCombat.targetEntityId == null)
1609
1822
{ engageTarget(world.ecs, targetId, attackerId, now); }
1823
if (attackerIsPlayer)
1824
{ markSeekCover(world.ecs, targetId); }
1610
1825
}
1611
1826
if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))
1612
1827
{
@@ -117,7 +117,7 @@ export function ensureMobCombat (ecs, entityId)117
const def = mobDefinition(creature.mobTypeId);117
const def = mobDefinition(creature.mobTypeId);118
const level = creatureLevel(ecs, handle);118
const level = creatureLevel(ecs, handle);119
if (!ecs.get(handle, Component.combat))119
if (!ecs.get(handle, Component.combat))120
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }120
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false }); }121
if (!ecs.get(handle, Component.skills))121
if (!ecs.get(handle, Component.skills))122
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }122
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def, level) }); }123
return true;123
return true;@@ -171,7 +171,7 @@ export function engageTarget (ecs, attackerId, targetId, now = Date.now())171
{ return false; }171
{ return false; }172
let combat = ecs.get(handle, Component.combat);172
let combat = ecs.get(handle, Component.combat);173
if (!combat)173
if (!combat)174
{ combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }174
{ combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0, seekCover: false }); }175
const targetChanged = combat.targetEntityId !== targetId;175
const targetChanged = combat.targetEntityId !== targetId;176
combat.targetEntityId = targetId;176
combat.targetEntityId = targetId;177
if (targetChanged)177
if (targetChanged)@@ -185,6 +185,15 @@ export function engageTarget (ecs, attackerId, targetId, now = Date.now())185
return true;185
return true;186
}186
}187
187
188
/** Melee mobs shot by player ranged/spells prefer cover while closing. */189
export function markSeekCover (ecs, entityId)190
{191
const handle = ecs.handleOf(entityId);192
const combat = handle != null ? ecs.get(handle, Component.combat) : null;193
if (combat)194
{ combat.seekCover = true; }195
}196
188
/** Pending cast or entity-spell auto-repeat — physical combat must not run. */197
/** Pending cast or entity-spell auto-repeat — physical combat must not run. */189
export function isSpellCombatBusy (ecs, handle)198
export function isSpellCombatBusy (ecs, handle)190
{199
{@@ -217,7 +226,10 @@ export function clearEngage (ecs, entityId)217
const handle = ecs.handleOf(entityId);226
const handle = ecs.handleOf(entityId);218
const combat = handle != null ? ecs.get(handle, Component.combat) : null;227
const combat = handle != null ? ecs.get(handle, Component.combat) : null;219
if (combat)228
if (combat)220
{ combat.targetEntityId = null; }229
{230
combat.targetEntityId = null;231
combat.seekCover = false;232
}221
}233
}222
234
223
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)235
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)@@ -772,6 +784,170 @@ function combatGoalPreference (entityId, tileX, tileY)772
return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;784
return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;773
}785
}774
786
787
/** Cost multiplier for tiles the threat can currently shoot. */788
const COVER_EXPOSED_STEP_COST = 5;789
790
function mobHasRangedRetaliation (world, handle)791
{792
const profile = attackProfileOf(world.ecs, handle);793
if (profile?.mode === "ranged")794
{ return true; }795
return eligibleMobAttackSpells(world.ecs, handle).length > 0;796
}797
798
/** Melee-only creatures closing after a player ranged/spell hit. */799
function shouldSeekCoverApproach (world, handle)800
{801
if (world.ecs.get(handle, Component.character))802
{ return false; }803
if (!world.ecs.get(handle, Component.creature))804
{ return false; }805
const combat = world.ecs.get(handle, Component.combat);806
if (!combat?.seekCover)807
{ return false; }808
return !mobHasRangedRetaliation(world, handle);809
}810
811
function coverStepCost (world, threatPos, goalX, goalY, x, y)812
{813
// Final adjacent step is always in LOS — don't punish the last lunge.814
if (x === goalX && y === goalY)815
{ return 1; }816
if (hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y))817
{ return COVER_EXPOSED_STEP_COST; }818
return 1;819
}820
821
function pathCoverScore (world, threatPos, tiles)822
{823
let score = 0;824
for (const step of tiles)825
{826
score += hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, step.x, step.y)827
? COVER_EXPOSED_STEP_COST828
: 1;829
}830
return score;831
}832
833
function listAdjacentMeleeGoals (world, entityId, position, targetPos, reserved)834
{835
const dirs = [836
{ x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },837
{ x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }838
];839
const goals = [];840
for (const dir of dirs)841
{842
const x = targetPos.tileX + dir.x;843
const y = targetPos.tileY + dir.y;844
const isHere = x === position.tileX && y === position.tileY;845
const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;846
const key = combatTileKey(x, y);847
if (reserved?.has(key) && !(isHere && aloneHere))848
{ continue; }849
const clear = world.isClearStanding?.(entityId, x, y)850
?? world.walkableFor(entityId, x, y);851
if (!clear && !isHere)852
{ continue; }853
if (isHere && !aloneHere)854
{ continue; }855
goals.push({ x, y });856
}857
return goals;858
}859
860
function findCoverMeleeApproachPath (world, entityId, handle, position, targetPos, reserved)861
{862
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);863
const preferVertical = !!world.ecs.get(handle, Component.character);864
const isWalkable = (x, y, goal) =>865
{866
if (x === goal.x && y === goal.y)867
{868
return world.isClearStanding?.(entityId, x, y)869
?? world.walkableFor(entityId, x, y);870
}871
return world.walkableFor(entityId, x, y);872
};873
let bestTiles = null;874
let bestScore = Infinity;875
let bestPref = Infinity;876
for (const goal of listAdjacentMeleeGoals(world, entityId, position, targetPos, reserved))877
{878
if (goal.x === position.tileX && goal.y === position.tileY)879
{ return []; }880
const tiles = findPath(881
position.tileX,882
position.tileY,883
goal.x,884
goal.y,885
(x, y) => isWalkable(x, y, goal),886
bounds.minX,887
bounds.minY,888
bounds.maxX,889
bounds.maxY,890
{891
preferVertical,892
stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)893
}894
);895
if (!tiles.length)896
{ continue; }897
const score = pathCoverScore(world, targetPos, tiles);898
const pref = combatGoalPreference(entityId, goal.x, goal.y);899
if (score < bestScore || (score === bestScore && pref < bestPref))900
{901
bestScore = score;902
bestPref = pref;903
bestTiles = tiles;904
}905
}906
return bestTiles;907
}908
909
/** Duck behind the nearest tile the threat cannot shoot when melee approach is impossible. */910
function queueFleeToCover (world, entityId, handle, position, threatPos)911
{912
let path = world.ecs.get(handle, Component.path);913
if (!path)914
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }915
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);916
const isWalkable = (x, y) => world.walkableFor(entityId, x, y);917
const isGoal = (x, y) =>918
{919
if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))920
{ return false; }921
if (chebyshev(x, y, threatPos.tileX, threatPos.tileY) < 1)922
{ return false; }923
return !hasCombatLineOfSight(world, threatPos.tileX, threatPos.tileY, x, y);924
};925
if (isGoal(position.tileX, position.tileY))926
{927
path.tiles = [];928
return;929
}930
const tiles = findPathToNearestGoal(931
position.tileX,932
position.tileY,933
isGoal,934
isWalkable,935
bounds.minX,936
bounds.minY,937
bounds.maxX,938
bounds.maxY939
);940
if (!tiles.length)941
{942
path.tiles = [];943
return;944
}945
path.tiles = tiles;946
const movement = world.ecs.get(handle, Component.movement);947
if (movement)948
{ movement.walkCarry = 0; }949
}950
775
export function queueMeleeApproach (world, entityId, handle, position, targetPos)951
export function queueMeleeApproach (world, entityId, handle, position, targetPos)776
{952
{777
if (world.frozen?.has?.(entityId))953
if (world.frozen?.has?.(entityId))@@ -790,6 +966,38 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos790
966
791
const combat = world.ecs.get(handle, Component.combat);967
const combat = world.ecs.get(handle, Component.combat);792
const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);968
const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);969
const seekCover = shouldSeekCoverApproach(world, handle);970
971
if (seekCover)972
{973
const coverTiles = findCoverMeleeApproachPath(974
world,975
entityId,976
handle,977
position,978
targetPos,979
reserved980
);981
if (coverTiles)982
{983
if (!coverTiles.length)984
{985
path.tiles = [];986
return;987
}988
const goal = coverTiles[coverTiles.length - 1];989
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))990
{ return; }991
path.tiles = coverTiles;992
const movement = world.ecs.get(handle, Component.movement);993
if (movement)994
{ movement.walkCarry = 0; }995
return;996
}997
queueFleeToCover(world, entityId, handle, position, targetPos);998
return;999
}1000
793
const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);1001
const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);794
if (!goal)1002
if (!goal)795
{1003
{@@ -1305,7 +1513,11 @@ function applyLocalMeleeHit (1305
1513
1306
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.1514
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.1307
if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))1515
if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))1308
{ engageTarget(world.ecs, targetId, attackerId, now); }1516
{1517
engageTarget(world.ecs, targetId, attackerId, now);1518
if (profile?.mode === "ranged")1519
{ markSeekCover(world.ecs, targetId); }1520
}1309
if (attackerIsPlayer === false)1521
if (attackerIsPlayer === false)1310
{1522
{1311
const targetCharacter = world.ecs.get(targetHandle, Component.character);1523
const targetCharacter = world.ecs.get(targetHandle, Component.character);@@ -1604,9 +1816,12 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D1604
const attackerHandle = world.ecs.handleOf(attackerId);1816
const attackerHandle = world.ecs.handleOf(attackerId);1605
if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))1817
if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))1606
{1818
{1819
const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);1607
const targetCombat = world.ecs.get(targetHandle, Component.combat);1820
const targetCombat = world.ecs.get(targetHandle, Component.combat);1608
if (targetCombat && targetCombat.targetEntityId == null)1821
if (targetCombat && targetCombat.targetEntityId == null)1609
{ engageTarget(world.ecs, targetId, attackerId, now); }1822
{ engageTarget(world.ecs, targetId, attackerId, now); }1823
if (attackerIsPlayer)1824
{ markSeekCover(world.ecs, targetId); }1610
}1825
}1611
if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))1826
if (attackerHandle != null && world.ecs.get(targetHandle, Component.character))1612
{1827
{@@ -41,3 +41,26 @@ test("player and mob axis bias diverge on diagonal goals", () =>
41
41
assert.deepEqual(mobPath[0], { x: -1, y: 0 });
42
42
assert.deepEqual(playerPath[0], { x: 0, y: -1 });
43
43
});
44
45
test("A* stepCost prefers the cheaper route around an expensive corridor", () =>
46
{
47
// Two routes from (0,0) to (2,0): through (1,0) cost 10, or via (0,1)-(1,1)-(2,1) cost 1 each.
48
const expensive = new Set(["1,0"]);
49
const path = findPath(
50
0,
51
0,
52
2,
53
0,
54
() => true,
55
-2,
56
-2,
57
4,
58
4,
59
{
60
stepCost: (x, y) => (expensive.has(`${x},${y}`) ? 10 : 1)
61
}
62
);
63
assert.ok(path.length > 0);
64
assert.deepEqual(path.at(-1), { x: 2, y: 0 });
65
assert.ok(!path.some((step) => step.x === 1 && step.y === 0));
66
});
@@ -41,3 +41,26 @@ test("player and mob axis bias diverge on diagonal goals", () =>41
assert.deepEqual(mobPath[0], { x: -1, y: 0 });41
assert.deepEqual(mobPath[0], { x: -1, y: 0 });42
assert.deepEqual(playerPath[0], { x: 0, y: -1 });42
assert.deepEqual(playerPath[0], { x: 0, y: -1 });43
});43
});44
45
test("A* stepCost prefers the cheaper route around an expensive corridor", () =>46
{47
// Two routes from (0,0) to (2,0): through (1,0) cost 10, or via (0,1)-(1,1)-(2,1) cost 1 each.48
const expensive = new Set(["1,0"]);49
const path = findPath(50
0,51
0,52
2,53
0,54
() => true,55
-2,56
-2,57
4,58
4,59
{60
stepCost: (x, y) => (expensive.has(`${x},${y}`) ? 10 : 1)61
}62
);63
assert.ok(path.length > 0);64
assert.deepEqual(path.at(-1), { x: 2, y: 0 });65
assert.ok(!path.some((step) => step.x === 1 && step.y === 0));66
});@@ -13,7 +13,7 @@ import { WorkerMessage } from "../src/simulation/protocol.js";
13
13
import { tileToRegion } from "../src/world/coordinates.js";
14
14
import { SkillId } from "../../shared/definitions/skills.js";
15
15
import { totalXpForLevel } from "../../shared/skills/progression.js";
16
import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight } from "../src/combat/service.js";
16
import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight, queueMeleeApproach, markSeekCover, engageTarget, applyDamageAndKill } from "../src/combat/service.js";
17
17
import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
18
18
19
19
function workerOf (simulation, entityId)
@@ -1206,3 +1206,113 @@ test("staff melees like a quarterstaff and awards clubs XP", () =>
1206
1206
harness.close();
1207
1207
}
1208
1208
});
1209
1210
test("spell damage marks seekCover on a melee mob", () =>
1211
{
1212
const harness = makeSimulation({ workerCount: 1 });
1213
try
1214
{
1215
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1216
const playerId = harness.simulation.spawnCharacter(1, character);
1217
const deerId = harness.simulation.spawnEntity(mobComponents({
1218
tileX: 12,
1219
tileY: 8,
1220
mobTypeId: MobId.deer,
1221
spawnerId: null
1222
}));
1223
const worker = workerOf(harness.simulation, playerId);
1224
applyDamageAndKill(worker.world, playerId, deerId, 1, Date.now());
1225
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1226
assert.equal(componentsOf(harness.simulation, deerId).combat?.seekCover, true);
1227
}
1228
finally
1229
{ harness.close(); }
1230
});
1231
1232
test("melee hit does not mark seekCover on a retaliating mob", () =>
1233
{
1234
const random = Math.random;
1235
Math.random = () => 0;
1236
const harness = makeSimulation({ workerCount: 1 });
1237
try
1238
{
1239
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1240
const playerId = harness.simulation.spawnCharacter(1, character);
1241
const deerId = harness.simulation.spawnEntity(mobComponents({
1242
tileX: 9,
1243
tileY: 8,
1244
mobTypeId: MobId.deer,
1245
spawnerId: null
1246
}));
1247
const worker = workerOf(harness.simulation, playerId);
1248
const handle = worker.world.ecs.handleOf(playerId);
1249
const bag = harness.simulation.bagOf(playerId);
1250
const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
1251
if (stickSlot >= 0)
1252
{
1253
harness.simulation.enqueue(1, {
1254
type: "equip-item",
1255
characterId: character.character_id,
1256
slotIndex: stickSlot
1257
});
1258
harness.simulation.step();
1259
}
1260
const profile = attackProfileOf(worker.world.ecs, handle);
1261
assert.equal(profile.mode, "melee");
1262
resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
1263
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
1264
assert.equal(!!componentsOf(harness.simulation, deerId).combat?.seekCover, false);
1265
}
1266
finally
1267
{
1268
Math.random = random;
1269
harness.close();
1270
}
1271
});
1272
1273
test("seekCover mob flees to a no-LOS tile when melee approach is impossible", () =>
1274
{
1275
const harness = makeSimulation({ workerCount: 1 });
1276
try
1277
{
1278
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
1279
const playerId = harness.simulation.spawnCharacter(1, character);
1280
const deerId = harness.simulation.spawnEntity(mobComponents({
1281
tileX: 14,
1282
tileY: 8,
1283
mobTypeId: MobId.deer,
1284
spawnerId: null
1285
}));
1286
const worker = workerOf(harness.simulation, playerId);
1287
const world = worker.world;
1288
const data = world.chunkData(0, 0);
1289
const wall = { typeId: BlockType.stoneWall, state: null, config: null };
1290
const furnace = { typeId: BlockType.furnace, state: null, config: null };
1291
// Impassable stations around the player (do not block LOS) so no melee stand tile exists.
1292
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]])
1293
{ data.blocks[(8 + dy) * 16 + (8 + dx)] = furnace; }
1294
// Cover wall east of the approach.
1295
for (let y = 6; y <= 10; y++)
1296
{ data.blocks[y * 16 + 12] = wall; }
1297
1298
assert.equal(hasCombatLineOfSight(world, 8, 8, 14, 8), false, "wall should block LOS east of the wall");
1299
1300
const deerHandle = world.ecs.handleOf(deerId);
1301
engageTarget(world.ecs, deerId, playerId);
1302
markSeekCover(world.ecs, deerId);
1303
const playerPos = world.ecs.get(world.ecs.handleOf(playerId), Component.position);
1304
teleportEntity(worker, deerId, 11, 8);
1305
assert.equal(hasCombatLineOfSight(world, 8, 8, 11, 8), true);
1306
queueMeleeApproach(world, deerId, deerHandle, world.ecs.get(deerHandle, Component.position), playerPos);
1307
const path = world.ecs.get(deerHandle, Component.path)?.tiles ?? [];
1308
assert.ok(path.length > 0, "expected a flee path into cover");
1309
const dest = path[path.length - 1];
1310
assert.equal(
1311
hasCombatLineOfSight(world, playerPos.tileX, playerPos.tileY, dest.x, dest.y),
1312
false,
1313
"flee destination must be out of player LOS"
1314
);
1315
}
1316
finally
1317
{ harness.close(); }
1318
});
@@ -13,7 +13,7 @@ import { WorkerMessage } from "../src/simulation/protocol.js";13
import { tileToRegion } from "../src/world/coordinates.js";13
import { tileToRegion } from "../src/world/coordinates.js";14
import { SkillId } from "../../shared/definitions/skills.js";14
import { SkillId } from "../../shared/definitions/skills.js";15
import { totalXpForLevel } from "../../shared/skills/progression.js";15
import { totalXpForLevel } from "../../shared/skills/progression.js";16
import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight } from "../src/combat/service.js";16
import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight, queueMeleeApproach, markSeekCover, engageTarget, applyDamageAndKill } from "../src/combat/service.js";17
import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";17
import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";18
18
19
function workerOf (simulation, entityId)19
function workerOf (simulation, entityId)@@ -1206,3 +1206,113 @@ test("staff melees like a quarterstaff and awards clubs XP", () =>1206
harness.close();1206
harness.close();1207
}1207
}1208
});1208
});1209
1210
test("spell damage marks seekCover on a melee mob", () =>1211
{1212
const harness = makeSimulation({ workerCount: 1 });1213
try1214
{1215
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });1216
const playerId = harness.simulation.spawnCharacter(1, character);1217
const deerId = harness.simulation.spawnEntity(mobComponents({1218
tileX: 12,1219
tileY: 8,1220
mobTypeId: MobId.deer,1221
spawnerId: null1222
}));1223
const worker = workerOf(harness.simulation, playerId);1224
applyDamageAndKill(worker.world, playerId, deerId, 1, Date.now());1225
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);1226
assert.equal(componentsOf(harness.simulation, deerId).combat?.seekCover, true);1227
}1228
finally1229
{ harness.close(); }1230
});1231
1232
test("melee hit does not mark seekCover on a retaliating mob", () =>1233
{1234
const random = Math.random;1235
Math.random = () => 0;1236
const harness = makeSimulation({ workerCount: 1 });1237
try1238
{1239
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });1240
const playerId = harness.simulation.spawnCharacter(1, character);1241
const deerId = harness.simulation.spawnEntity(mobComponents({1242
tileX: 9,1243
tileY: 8,1244
mobTypeId: MobId.deer,1245
spawnerId: null1246
}));1247
const worker = workerOf(harness.simulation, playerId);1248
const handle = worker.world.ecs.handleOf(playerId);1249
const bag = harness.simulation.bagOf(playerId);1250
const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);1251
if (stickSlot >= 0)1252
{1253
harness.simulation.enqueue(1, {1254
type: "equip-item",1255
characterId: character.character_id,1256
slotIndex: stickSlot1257
});1258
harness.simulation.step();1259
}1260
const profile = attackProfileOf(worker.world.ecs, handle);1261
assert.equal(profile.mode, "melee");1262
resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());1263
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);1264
assert.equal(!!componentsOf(harness.simulation, deerId).combat?.seekCover, false);1265
}1266
finally1267
{1268
Math.random = random;1269
harness.close();1270
}1271
});1272
1273
test("seekCover mob flees to a no-LOS tile when melee approach is impossible", () =>1274
{1275
const harness = makeSimulation({ workerCount: 1 });1276
try1277
{1278
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });1279
const playerId = harness.simulation.spawnCharacter(1, character);1280
const deerId = harness.simulation.spawnEntity(mobComponents({1281
tileX: 14,1282
tileY: 8,1283
mobTypeId: MobId.deer,1284
spawnerId: null1285
}));1286
const worker = workerOf(harness.simulation, playerId);1287
const world = worker.world;1288
const data = world.chunkData(0, 0);1289
const wall = { typeId: BlockType.stoneWall, state: null, config: null };1290
const furnace = { typeId: BlockType.furnace, state: null, config: null };1291
// Impassable stations around the player (do not block LOS) so no melee stand tile exists.1292
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]])1293
{ data.blocks[(8 + dy) * 16 + (8 + dx)] = furnace; }1294
// Cover wall east of the approach.1295
for (let y = 6; y <= 10; y++)1296
{ data.blocks[y * 16 + 12] = wall; }1297
1298
assert.equal(hasCombatLineOfSight(world, 8, 8, 14, 8), false, "wall should block LOS east of the wall");1299
1300
const deerHandle = world.ecs.handleOf(deerId);1301
engageTarget(world.ecs, deerId, playerId);1302
markSeekCover(world.ecs, deerId);1303
const playerPos = world.ecs.get(world.ecs.handleOf(playerId), Component.position);1304
teleportEntity(worker, deerId, 11, 8);1305
assert.equal(hasCombatLineOfSight(world, 8, 8, 11, 8), true);1306
queueMeleeApproach(world, deerId, deerHandle, world.ecs.get(deerHandle, Component.position), playerPos);1307
const path = world.ecs.get(deerHandle, Component.path)?.tiles ?? [];1308
assert.ok(path.length > 0, "expected a flee path into cover");1309
const dest = path[path.length - 1];1310
assert.equal(1311
hasCombatLineOfSight(world, playerPos.tileX, playerPos.tileY, dest.x, dest.y),1312
false,1313
"flee destination must be out of player LOS"1314
);1315
}1316
finally1317
{ harness.close(); }1318
});