diff --git a/src/services/characterMoveService.ts b/src/services/characterMoveService.ts index 0510f57..92756f9 100644 --- a/src/services/characterMoveService.ts +++ b/src/services/characterMoveService.ts @@ -107,7 +107,16 @@ class CharacterMoveService extends BaseService { const grid = await map?.getGrid() if (!grid?.length) { - this.logger.error('map:character:move error: Grid not found or empty') + return null + } + + // Validate target position is within map boundaries + if (targetX < 0 || targetY < 0 || targetX >= grid[0]!.length || targetY >= grid.length) { + return null + } + + // Check if target position is walkable + if (grid[Math.floor(targetY)]![Math.floor(targetX)] !== 0) { return null } @@ -165,13 +174,16 @@ class CharacterMoveService extends BaseService { private findPath(start: Position, end: Position, grid: number[][]): Node[] { const openList = new PriorityQueue((a, b) => a.f - b.f) const closedSet = new Set() + const MAX_ITERATIONS = 1000 // Prevent infinite loops for impossible paths + let iterations = 0 const getKey = (p: Position) => `${p.positionX},${p.positionY}` openList.enqueue({ ...start, g: 0, h: 0, f: 0 }) try { - while (openList.length > 0) { + while (openList.length > 0 && iterations < MAX_ITERATIONS) { + iterations++ const current = openList.dequeue() if (!current) break @@ -195,8 +207,10 @@ class CharacterMoveService extends BaseService { } } + this.logger.warn(`Path not found after ${iterations} iterations`) return [] // No path found } finally { + // Clean up resources while (openList.length > 0) openList.dequeue() closedSet.clear() }