Near perfect movement

This commit is contained in:
2025-02-16 17:12:01 +01:00
parent 9f84247839
commit 161a9795bc
2 changed files with 99 additions and 115 deletions

View File

@ -12,70 +12,6 @@ import type { Server } from 'socket.io'
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.siftUp(this.items.length - 1)
}
dequeue(): T | undefined {
if (this.items.length === 0) return undefined
const result = this.items[0]
const last = this.items.pop()
if (this.items.length > 0 && last !== undefined) {
this.items[0] = last
this.siftDown(0)
}
return result
}
get length(): number {
return this.items.length
}
private siftUp(index: number): void {
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2)
if (this.compare(this.items[index]!, this.items[parentIndex]!) < 0) {
;[this.items[index], this.items[parentIndex]] = [this.items[parentIndex]!, this.items[index]!]
index = parentIndex
} else {
break
}
}
}
private siftDown(index: number): void {
const length = this.items.length
while (true) {
let minIndex = index
const leftChild = 2 * index + 1
const rightChild = 2 * index + 2
if (leftChild < length && this.compare(this.items[leftChild]!, this.items[minIndex]!) < 0) {
minIndex = leftChild
}
if (rightChild < length && this.compare(this.items[rightChild]!, this.items[minIndex]!) < 0) {
minIndex = rightChild
}
if (minIndex === index) break
;[this.items[index], this.items[minIndex]] = [this.items[minIndex]!, this.items[index]!]
index = minIndex
}
}
clear(): void {
this.items = []
}
}
class CharacterMoveService extends BaseService {
private io: Server = SocketManager.getIO()
@ -182,12 +118,14 @@ class CharacterMoveService extends BaseService {
private findPath(start: Position, end: Position, grid: number[][]): Node[] {
const openList = new PriorityQueue<Node>((a, b) => a.f - b.f)
const closedSet = new Set<string>()
const MAX_ITERATIONS = 1000 // Prevent infinite loops for impossible paths
const MAX_ITERATIONS = 1000
let iterations = 0
const getKey = (p: Position) => `${p.positionX},${p.positionY}`
const gScoreMap = new Map<string, number>()
openList.enqueue({ ...start, g: 0, h: 0, f: 0 })
openList.enqueue({ ...start, g: 0, h: this.getDistance(start, end), f: this.getDistance(start, end) })
gScoreMap.set(getKey(start), 0)
try {
while (openList.length > 0 && iterations < MAX_ITERATIONS) {
@ -199,28 +137,34 @@ class CharacterMoveService extends BaseService {
return this.reconstructPath(current)
}
closedSet.add(getKey(current))
const currentKey = getKey(current)
closedSet.add(currentKey)
const neighbors = this.getValidNeighbors(current, grid, end)
for (const neighbor of neighbors) {
if (closedSet.has(getKey(neighbor))) continue
const neighborKey = getKey(neighbor)
if (closedSet.has(neighborKey)) continue
const g = current.g + this.getDistance(current, neighbor)
const h = this.getDistance(neighbor, end)
const f = g + h
const tentativeGScore = current.g + this.getDistance(current, neighbor)
const node: Node = { ...neighbor, g, h, f, parent: current }
openList.enqueue(node)
if (!gScoreMap.has(neighborKey) || tentativeGScore < gScoreMap.get(neighborKey)!) {
gScoreMap.set(neighborKey, tentativeGScore)
const h = this.getDistance(neighbor, end)
const f = tentativeGScore + h
const node: Node = { ...neighbor, g: tentativeGScore, h, f, parent: current }
openList.enqueue(node)
}
}
}
this.logger.warn(`Path not found after ${iterations} iterations`)
return [] // No path found
return []
} finally {
// Clean up resources
while (openList.length > 0) openList.dequeue()
openList.clear()
closedSet.clear()
gScoreMap.clear()
}
}
@ -233,6 +177,14 @@ class CharacterMoveService extends BaseService {
.filter((pos) => this.isValidPosition(pos, grid, end))
}
private isValidPosition(pos: Position, grid: number[][], end: Position): boolean {
if (pos.positionX < 0 || pos.positionY < 0 || pos.positionX >= grid[0]!.length || pos.positionY >= grid.length) {
return false
}
return grid[pos.positionY]![pos.positionX] === 0 || (pos.positionX === end.positionX && pos.positionY === end.positionY)
}
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
}
@ -254,16 +206,6 @@ class CharacterMoveService extends BaseService {
}
}
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)
@ -302,7 +244,7 @@ class CharacterMoveService extends BaseService {
return { isValid: true, maxAllowedDistance: 0, actualDistance: 0 }
}
const maxAllowedDistance = Math.ceil((stepDelay / 1000) * 2)
const maxAllowedDistance = Math.ceil((stepDelay / 1000) * (config.ALLOW_DIAGONAL_MOVEMENT ? 2.5 : 2))
const actualDistance = Math.sqrt(Math.pow(currentX - lastKnownPosition.x, 2) + Math.pow(currentY - lastKnownPosition.y, 2))
return {
@ -311,14 +253,70 @@ class CharacterMoveService extends BaseService {
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
}
}
}
export default new CharacterMoveService()
class PriorityQueue<T> {
private items: T[] = []
constructor(private compare: (a: T, b: T) => number) {}
enqueue(item: T): void {
this.items.push(item)
this.siftUp(this.items.length - 1)
}
dequeue(): T | undefined {
if (this.items.length === 0) return undefined
const result = this.items[0]
const last = this.items.pop()
if (this.items.length > 0 && last !== undefined) {
this.items[0] = last
this.siftDown(0)
}
return result
}
get length(): number {
return this.items.length
}
private siftUp(index: number): void {
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2)
if (this.compare(this.items[index]!, this.items[parentIndex]!) < 0) {
;[this.items[index], this.items[parentIndex]] = [this.items[parentIndex]!, this.items[index]!]
index = parentIndex
} else {
break
}
}
}
private siftDown(index: number): void {
const length = this.items.length
while (true) {
let minIndex = index
const leftChild = 2 * index + 1
const rightChild = 2 * index + 2
if (leftChild < length && this.compare(this.items[leftChild]!, this.items[minIndex]!) < 0) {
minIndex = leftChild
}
if (rightChild < length && this.compare(this.items[rightChild]!, this.items[minIndex]!) < 0) {
minIndex = rightChild
}
if (minIndex === index) break
;[this.items[index], this.items[minIndex]] = [this.items[minIndex]!, this.items[index]!]
index = minIndex
}
}
clear(): void {
this.items = []
}
}