server/src/services/characterMoveService.ts

211 lines
6.9 KiB
TypeScript

import { BaseService } from '@/application/base/baseService'
import config from '@/application/config'
import { Character } from '@/entities/character'
import MapManager from '@/managers/mapManager'
type Position = { positionX: number; positionY: number }
export type Node = Position & { parent?: Node; g: number; h: number; f: number }
class PriorityQueue<T> {
private items: T[] = []
constructor(private compare: (a: T, b: T) => number) {}
enqueue(item: T): void {
this.items.push(item)
this.items.sort(this.compare)
}
dequeue(): T | undefined {
return this.items.shift()
}
get length(): number {
return this.items.length
}
}
class CharacterMoveService extends BaseService {
// Rotation lookup table for better performance
private readonly ROTATION_MAP = {
diagonal: {
'up-left': 7,
'down-right': 3,
'up-right': 5,
'down-left': 1
},
straight: {
left: 6,
right: 2,
down: 4,
up: 0
}
}
private readonly DIRECTIONS = [
{ x: 0, y: -1 }, // Up
{ x: 0, y: 1 }, // Down
{ x: -1, y: 0 }, // Left
{ x: 1, y: 0 }, // Right
{ x: -1, y: -1 }, // Up left
{ x: -1, y: 1 }, // Up right
{ x: 1, y: -1 }, // Down left
{ x: 1, y: 1 } // Down right
]
public async calculatePath(character: Character, targetX: number, targetY: number): Promise<Position[] | null> {
if (!this.validateInput(character, targetX, targetY)) {
return null
}
const map = MapManager.getMapById(character.map.id)
const grid = await map?.getGrid()
if (!grid?.length) {
this.logger.error('map:character:move error: Grid not found or empty')
return null
}
// Ensure we're working with valid coordinates
const start: Position = {
positionX: Math.floor(character.positionX),
positionY: Math.floor(character.positionY)
}
const end: Position = {
positionX: Math.floor(targetX),
positionY: Math.floor(targetY)
}
// Don't calculate path if start and end are the same
if (start.positionX === end.positionX && start.positionY === end.positionY) {
return null
}
return this.findPath(start, end, grid)
}
private validateInput(character: Character, targetX: number, targetY: number): boolean {
if (!character || !character.map) {
this.logger.error('Invalid character or map data')
return false
}
if (!Number.isFinite(targetX) || !Number.isFinite(targetY)) {
this.logger.error('Invalid target coordinates')
return false
}
return true
}
public calculateRotation(X1: number, Y1: number, X2: number, Y2: number): number {
if (config.ALLOW_DIAGONAL_MOVEMENT) {
// Check diagonal movements using lookup table
if (X1 > X2 && Y1 > Y2) return this.ROTATION_MAP.diagonal['up-left']
if (X1 < X2 && Y1 < Y2) return this.ROTATION_MAP.diagonal['down-right']
if (X1 > X2 && Y1 < Y2) return this.ROTATION_MAP.diagonal['up-right']
if (X1 < X2 && Y1 > Y2) return this.ROTATION_MAP.diagonal['down-left']
}
// Non-diagonal movements using lookup table
if (X1 > X2) return this.ROTATION_MAP.straight.left
if (X1 < X2) return this.ROTATION_MAP.straight.right
if (Y1 < Y2) return this.ROTATION_MAP.straight.down
if (Y1 > Y2) return this.ROTATION_MAP.straight.up
return this.ROTATION_MAP.straight.up // Default case
}
private findPath(start: Position, end: Position, grid: number[][]): Node[] {
const openList = new PriorityQueue<Node>((a, b) => a.f - b.f)
openList.enqueue({ ...start, g: 0, h: 0, f: 0 })
const closedSet = new Set<string>()
const getKey = (p: Position) => `${p.positionX},${p.positionY}`
while (openList.length > 0) {
const current = openList.dequeue()
if (!current) break
if (current.positionX === end.positionX && current.positionY === end.positionY) {
return this.reconstructPath(current)
}
closedSet.add(getKey(current))
const neighbors = this.getValidNeighbors(current, grid, end)
for (const neighbor of neighbors) {
if (closedSet.has(getKey(neighbor))) continue
const g = current.g + this.getDistance(current, neighbor)
const h = this.getDistance(neighbor, end)
const f = g + h
const node: Node = { ...neighbor, g, h, f, parent: current }
openList.enqueue(node)
}
}
return [] // No path found
}
private getValidNeighbors(current: Position, grid: number[][], end: Position): Position[] {
return this.DIRECTIONS.slice(0, config.ALLOW_DIAGONAL_MOVEMENT ? 8 : 4)
.map((dir) => ({
positionX: current.positionX + dir.x,
positionY: current.positionY + dir.y
}))
.filter((pos) => this.isValidPosition(pos, grid, end))
}
private isValidPosition(pos: Position, grid: number[][], end: Position): boolean {
return pos.positionX >= 0 && pos.positionY >= 0 && pos.positionX < grid[0]!.length && pos.positionY < grid.length && (grid[pos.positionY]![pos.positionX] === 0 || (pos.positionX === end.positionX && pos.positionY === end.positionY))
}
private getDistance(a: Position, b: Position): number {
const dx = Math.abs(a.positionX - b.positionX)
const dy = Math.abs(a.positionY - b.positionY)
// Manhattan distance for straight paths, then Euclidean for diagonals
return dx + dy + (Math.sqrt(2) - 2) * Math.min(dx, dy)
}
private reconstructPath(endNode: Node): Node[] {
const path: Node[] = []
let current: Node | undefined = endNode
while (current) {
path.unshift(current)
current = current.parent
}
return path
}
public validateMovementDistance(currentX: number, currentY: number, lastKnownPosition: { x: number; y: number } | null, stepDelay: number, isMoving: boolean): { isValid: boolean; maxAllowedDistance: number; actualDistance: number } {
if (!lastKnownPosition || !isMoving) {
return { isValid: true, maxAllowedDistance: 0, actualDistance: 0 }
}
const maxAllowedDistance = Math.ceil((stepDelay / 1000) * 2)
const actualDistance = Math.sqrt(Math.pow(currentX - lastKnownPosition.x, 2) + Math.pow(currentY - lastKnownPosition.y, 2))
return {
isValid: actualDistance <= maxAllowedDistance,
maxAllowedDistance,
actualDistance
}
}
public validateRequestDistance(currentX: number, currentY: number, targetX: number, targetY: number, maxRequestDistance: number): { isValid: boolean; distance: number } {
const requestDistance = Math.sqrt(Math.pow(targetX - currentX, 2) + Math.pow(targetY - currentY, 2))
return {
isValid: requestDistance <= maxRequestDistance,
distance: requestDistance
}
}
public isValidStep(current: { positionX: number; positionY: number }, next: { positionX: number; positionY: number }): boolean {
return Math.abs(next.positionX - current.positionX) <= 1 && Math.abs(next.positionY - current.positionY) <= 1
}
}
export default new CharacterMoveService()