1
0
forked from noxious/server

Improved pathfinding

This commit is contained in:
Dennis Postma 2024-07-28 02:47:46 +02:00
parent f2fcc67cb6
commit 6c30e8d277
3 changed files with 304 additions and 191 deletions

View File

@ -1,79 +1,101 @@
import { Server } from 'socket.io' import { Server } from 'socket.io';
import { TSocket } from '../../utilities/Types' import { TSocket } from '../../utilities/Types';
import ZoneManager from '../../managers/ZoneManager' import ZoneManager from '../../managers/ZoneManager';
import prisma from '../../utilities/Prisma' import prisma from '../../utilities/Prisma';
import AStar from '../../utilities/Player/AStar' import AStar, { type Node } from '../../utilities/Player/AStar';
import Rotation from '../../utilities/Player/Rotation' import Rotation from '../../utilities/Player/Rotation';
type SocketResponseT = { interface SocketResponse {
position_x: number position_x: number;
position_y: number position_y: number;
} }
export default function (socket: TSocket, io: Server) { interface Character {
socket.on('character:move', async (data: SocketResponseT) => { id: number;
position_x: number;
position_y: number;
rotation: number;
zoneId: number;
}
export default function setupCharacterMove(socket: TSocket, io: Server) {
socket.on('character:move', async (data: SocketResponse) => {
try { try {
console.log('character:move requested', data) console.log('character:move requested', data);
if (!socket.character) { if (!socket.character) {
console.log('character:move error', 'Character not found') console.error('character:move error', 'Character not found');
return return;
} }
const start = { const grid = await ZoneManager.getGrid(socket.character.zoneId);
x: socket.character.position_x,
y: socket.character.position_y,
g: 0,
h: 0,
f: 0
}
const end = {
x: data.position_x,
y: data.position_y,
g: 0,
h: 0,
f: 0
}
const grid = await ZoneManager.getGrid(socket.character.zoneId)
if (grid.length === 0) { if (grid.length === 0) {
console.log('character:move error', 'Grid not found') console.error('character:move error', 'Grid not found');
return return;
} }
const path = AStar.findPath(start, end, grid) const start = { x: socket.character.position_x, y: socket.character.position_y };
const end = { x: data.position_x, y: data.position_y };
console.log('Starting position:', start);
console.log('Target position:', end);
console.log('Grid:', grid);
const path = AStar.findPath(start, end, grid);
console.log('Calculated path:', path);
if (path.length > 0) { if (path.length > 0) {
const finalPosition = path[path.length - 1] await moveAlongPath(socket, io, path, grid);
// Calculate the rotation
const rotation = Rotation.calculate(socket.character.position_x, socket.character.position_y, finalPosition.x, finalPosition.y)
socket.character.position_x = finalPosition.x
socket.character.position_y = finalPosition.y
socket.character.rotation = rotation // Assuming character has a rotation property
await prisma.character.update({
where: {
id: socket.character.id
},
data: {
position_x: finalPosition.x,
position_y: finalPosition.y,
rotation: rotation // Update the rotation in the database
}
})
ZoneManager.updateCharacterInZone(socket.character.zoneId, socket.character)
io.in(socket.character.zoneId.toString()).emit('character:moved', socket.character)
console.log(socket.character)
} else { } else {
console.log('character:move error', 'No valid path found') console.log('character:move error', 'No valid path found');
} }
} catch (error) { } catch (error) {
console.log('character:move error', error) console.error('character:move error', error);
} }
}) });
}
async function moveAlongPath(socket: TSocket, io: Server, path: Node[], grid: number[][]) {
if (!socket.character) return;
for (const position of path) {
if (isObstacle(position, grid)) {
console.log('Obstacle encountered at', position);
break;
}
const rotation = Rotation.calculate(
socket.character.position_x,
socket.character.position_y,
position.x,
position.y
);
await updateCharacterPosition(socket.character, position.x, position.y, rotation);
ZoneManager.updateCharacterInZone(socket.character.zoneId, socket.character);
io.in(socket.character.zoneId.toString()).emit('character:moved', socket.character);
console.log('Character moved to', position);
// Add a small delay between moves to avoid overwhelming the server
await new Promise(resolve => setTimeout(resolve, 100));
}
}
function isObstacle(position: Node, grid: number[][]): boolean {
return grid[position.y][position.x] === 1;
}
async function updateCharacterPosition(character: Character, x: number, y: number, rotation: number) {
character.position_x = x;
character.position_y = y;
character.rotation = rotation;
await prisma.character.update({
where: { id: character.id },
data: { position_x: x, position_y: y, rotation }
});
} }

View File

@ -1,132 +1,124 @@
import { Character, Zone } from '@prisma/client' import { Character, Zone } from '@prisma/client';
import ZoneRepository from '../repositories/ZoneRepository' import ZoneRepository from '../repositories/ZoneRepository';
import ZoneService from '../services/ZoneService' import ZoneService from '../services/ZoneService';
import zoneRepository from '../repositories/ZoneRepository' import zoneRepository from '../repositories/ZoneRepository';
type TLoadedZone = { type TLoadedZone = {
zone: Zone zone: Zone,
characters: Character[] characters: Character[],
} grid: number[][]
};
class ZoneManager { class ZoneManager {
private loadedZones: TLoadedZone[] = [] private loadedZones: TLoadedZone[] = [];
// Method to initialize zone manager // Method to initialize zone manager
public async boot() { public async boot() {
if (!(await ZoneRepository.getById(1))) { if (!(await ZoneRepository.getById(1))) {
const zoneService = new ZoneService() const zoneService = new ZoneService();
await zoneService.createDemoZone() await zoneService.createDemoZone();
} }
const zones = await ZoneRepository.getAll() const zones = await ZoneRepository.getAll();
for (const zone of zones) { for (const zone of zones) {
this.loadZone(zone) await this.loadZone(zone);
} }
console.log('[✅] Zone manager loaded') console.log('[✅] Zone manager loaded');
} }
// Method to handle individual zone loading // Method to handle individual zone loading
public loadZone(zone: Zone) { public async loadZone(zone: Zone) {
const grid = await this.getGrid(zone.id); // Create the grid for the zone
this.loadedZones.push({ this.loadedZones.push({
zone, zone,
characters: [] characters: [],
}) grid
console.log(`[✅] Zone ID ${zone.id} loaded`) });
console.log(`[✅] Zone ID ${zone.id} loaded`);
} }
// Method to handle individual zone unloading // Method to handle individual zone unloading
public unloadZone(zoneId: number) { public unloadZone(zoneId: number) {
this.loadedZones = this.loadedZones.filter((loadedZone) => { this.loadedZones = this.loadedZones.filter((loadedZone) => {
return loadedZone.zone.id !== zoneId return loadedZone.zone.id !== zoneId;
}) });
console.log(`[❌] Zone ID ${zoneId} unloaded`) console.log(`[❌] Zone ID ${zoneId} unloaded`);
} }
// Getter for loaded zones // Getter for loaded zones
public getLoadedZones(): TLoadedZone[] { public getLoadedZones(): TLoadedZone[] {
return this.loadedZones return this.loadedZones;
}
// Check if position is walkable
private isPositionWalkable(zoneId: number, x: number, y: number): boolean {
const loadedZone = this.loadedZones.find((lz) => lz.zone.id === zoneId);
return loadedZone ? loadedZone.grid[y][x] === 0 : false;
} }
public addCharacterToZone(zoneId: number, character: Character) { public addCharacterToZone(zoneId: number, character: Character) {
const loadedZone = this.loadedZones.find((loadedZone) => { const loadedZone = this.loadedZones.find((loadedZone) => {
return loadedZone.zone.id === zoneId return loadedZone.zone.id === zoneId;
}) });
if (loadedZone) { if (loadedZone && this.isPositionWalkable(zoneId, character.position_x, character.position_y)) {
loadedZone.characters.push(character) loadedZone.characters.push(character);
} }
} }
public removeCharacterFromZone(zoneId: number, character: Character) { public removeCharacterFromZone(zoneId: number, character: Character) {
const loadedZone = this.loadedZones.find((loadedZone) => { const loadedZone = this.loadedZones.find((loadedZone) => {
return loadedZone.zone.id === zoneId return loadedZone.zone.id === zoneId;
}) });
if (loadedZone) { if (loadedZone) {
loadedZone.characters = loadedZone.characters.filter((loadedCharacter) => { loadedZone.characters = loadedZone.characters.filter((loadedCharacter) => {
return loadedCharacter.id !== character.id return loadedCharacter.id !== character.id;
}) });
} }
} }
public updateCharacterInZone(zoneId: number, character: Character) { public updateCharacterInZone(zoneId: number, character: Character) {
const loadedZone = this.loadedZones.find((loadedZone) => { const loadedZone = this.loadedZones.find((loadedZone) => {
return loadedZone.zone.id === zoneId return loadedZone.zone.id === zoneId;
}) });
if (loadedZone) { if (loadedZone) {
const characterIndex = loadedZone.characters.findIndex((loadedCharacter) => { const characterIndex = loadedZone.characters.findIndex((loadedCharacter) => {
return loadedCharacter.id === character.id return loadedCharacter.id === character.id;
}) });
if (characterIndex !== -1) { if (characterIndex !== -1) {
loadedZone.characters[characterIndex] = character loadedZone.characters[characterIndex] = character;
} }
} }
} }
public getCharactersInZone(zoneId: number): Character[] { public getCharactersInZone(zoneId: number): Character[] {
const loadedZone = this.loadedZones.find((loadedZone) => { const loadedZone = this.loadedZones.find((loadedZone) => {
return loadedZone.zone.id === zoneId return loadedZone.zone.id === zoneId;
}) });
return loadedZone ? loadedZone.characters : [] return loadedZone ? loadedZone.characters : [];
} }
public async getGrid(zoneId: number): Promise<number[][]> { public async getGrid(zoneId: number): Promise<number[][]> {
const zone = this.loadedZones.find((z) => z.zone.id === zoneId) const zone = this.loadedZones.find((z) => z.zone.id === zoneId);
let grid: number[][] = [] if (zone) return zone.grid;
if (zone) {
const eventTiles = await zoneRepository.getEventTiles(zoneId)
const objects = await zoneRepository.getObjects(zoneId)
// Create a grid based on the event tiles const loadedZone = await ZoneRepository.getById(zoneId);
for (let i = 0; i < zone.zone.width; i++) { if (!loadedZone) return [];
grid.push(Array(zone.zone.height).fill(0))
} let grid: number[][] = Array.from({ length: loadedZone.height }, () => Array.from({ length: loadedZone.width }, () => 0));
const eventTiles = await zoneRepository.getEventTiles(zoneId);
// Set the grid values based on the event tiles, these are strings // Set the grid values based on the event tiles, these are strings
eventTiles.forEach((eventTile) => { eventTiles.forEach((eventTile) => {
if (eventTile.type === 'BLOCK') { if (eventTile.type === 'BLOCK') {
grid[eventTile.position_x][eventTile.position_y] = 0 grid[eventTile.position_y][eventTile.position_x] = 1;
} else if (eventTile.type === 'WARP') {
grid[eventTile.position_x][eventTile.position_y] = 1
} else if (eventTile.type === 'NPC') {
grid[eventTile.position_x][eventTile.position_y] = 2
} else if (eventTile.type === 'ITEM') {
grid[eventTile.position_x][eventTile.position_y] = 3
} }
}); });
objects.forEach((object) => { return grid;
if (object.objectId === 'blank_tile') {
grid[object.position_x][object.position_y] = 0
} else {
grid[object.position_x][object.position_y] = 1
}
});
return grid
}
return []
} }
} }
export default new ZoneManager() export default new ZoneManager();

View File

@ -1,84 +1,183 @@
// utilities/AStar.ts interface Position {
x: number;
type Node = { y: number;
x: number
y: number
parent?: Node
g: number
h: number
f: number
} }
class AStar { export interface Node extends Position {
static findPath(start: Node, end: Node, grid: number[][]): Node[] { parent?: Node;
// Initialize the open and closed lists g: number;
let openList: Node[] = [] h: number;
let closedList: Node[] = [] f: number;
}
// Push the start node onto the open list /**
openList.push(start) * A* pathfinding algorithm.
*/
class AStar {
private static readonly ORTHOGONAL_DIRECTIONS: Position[] = [
{ x: 0, y: -1 }, // up
{ x: 0, y: 1 }, // down
{ x: -1, y: 0 }, // left
{ x: 1, y: 0 } // right
];
private static readonly DIAGONAL_DIRECTIONS: Position[] = [
{ x: -1, y: -1 }, // up-left
{ x: -1, y: 1 }, // down-left
{ x: 1, y: -1 }, // up-right
{ x: 1, y: 1 } // down-right
];
/**
* Finds the shortest path from start to end on the given grid.
* @param start - Start position.
* @param end - End position.
* @param grid - The grid representing the map (0 = open space, 1 = obstacle).
* @param allowDiagonal - Whether diagonal movements are allowed.
* @returns Array of `Node` representing the path from start to end.
*/
static findPath(start: Position, end: Position, grid: number[][], allowDiagonal: boolean = false): Node[] {
const openList: Node[] = [];
const closedSet = new Set<string>();
const startNode: Node = { ...start, g: 0, h: 0, f: 0 };
openList.push(startNode);
while (openList.length > 0) { while (openList.length > 0) {
// Get the node with the lowest f value const currentNode = this.getLowestFScoreNode(openList);
let currentNode = openList.reduce((prev, curr) => (prev.f < curr.f ? prev : curr))
// Move the current node to the closed list if (this.isEndNode(currentNode, end)) {
openList = openList.filter((node) => node !== currentNode) return this.reconstructPath(currentNode);
closedList.push(currentNode)
// Check if we've reached the end
if (currentNode.x === end.x && currentNode.y === end.y) {
let path: Node[] = []
let curr = currentNode
while (curr) {
path.push(curr)
curr = curr.parent as Node
}
return path.reverse()
} }
// Get the neighboring nodes this.removeNodeFromOpenList(openList, currentNode);
let neighbors = this.getNeighbors(currentNode, grid) closedSet.add(this.nodeToString(currentNode));
for (let neighbor of neighbors) {
if (closedList.some((node) => node.x === neighbor.x && node.y === neighbor.y)) { for (const neighbor of this.getValidNeighbors(currentNode, grid, end, allowDiagonal)) {
continue if (closedSet.has(this.nodeToString(neighbor))) continue;
const tentativeGScore = currentNode.g + this.getDistance(currentNode, neighbor);
if (!this.isInOpenList(openList, neighbor) || tentativeGScore < neighbor.g) {
neighbor.parent = currentNode;
neighbor.g = tentativeGScore;
neighbor.h = this.heuristic(neighbor, end);
neighbor.f = neighbor.g + neighbor.h;
if (!this.isInOpenList(openList, neighbor)) {
openList.push(neighbor);
} }
neighbor.g = currentNode.g + 1
neighbor.h = Math.abs(neighbor.x - end.x) + Math.abs(neighbor.y - end.y)
neighbor.f = neighbor.g + neighbor.h
neighbor.parent = currentNode
if (!openList.some((node) => node.x === neighbor.x && node.y === neighbor.y)) {
openList.push(neighbor)
} }
} }
} }
// No path found return []; // No path found
return []
} }
private static getNeighbors(node: Node, grid: number[][]): Node[] { /**
let neighbors: Node[] = [] * Gets the node with the lowest F score from a list.
let directions = [ */
{ x: 0, y: -1 }, private static getLowestFScoreNode(nodes: Node[]): Node {
{ x: 0, y: 1 }, return nodes.reduce((min, node) => (node.f < min.f ? node : min));
{ x: -1, y: 0 }, }
{ x: 1, y: 0 }
]
for (let direction of directions) { /**
let x = node.x + direction.x * Checks if the given node is the end node.
let y = node.y + direction.y */
private static isEndNode(node: Node, end: Position): boolean {
return node.x === end.x && node.y === end.y;
}
if (x >= 0 && y >= 0 && x < grid.length && y < grid[0].length && grid[x][y] === 0) { /**
neighbors.push({ x, y, g: 0, h: 0, f: 0 }) * Removes a node from the open list.
*/
private static removeNodeFromOpenList(openList: Node[], node: Node): void {
const index = openList.findIndex(n => n.x === node.x && n.y === node.y);
if (index !== -1) openList.splice(index, 1);
}
/**
* Converts a node to a string representation.
*/
private static nodeToString(node: Position): string {
return `${node.x},${node.y}`;
}
/**
* Gets valid neighbors of the given node.
*/
private static getValidNeighbors(node: Node, grid: number[][], end: Position, allowDiagonal: boolean): Node[] {
const directions = allowDiagonal
? [...this.ORTHOGONAL_DIRECTIONS, ...this.DIAGONAL_DIRECTIONS]
: this.ORTHOGONAL_DIRECTIONS;
return directions
.map((dir) => ({
x: node.x + dir.x,
y: node.y + dir.y,
g: 0,
h: 0,
f: 0
}))
.filter((pos) => this.isValidPosition(pos, grid, end)) as Node[];
}
/**
* Checks if the given position is valid.
*/
private static isValidPosition(pos: Position, grid: number[][], end: Position): boolean {
const { x, y } = pos;
return (
x >= 0 && y >= 0 &&
x < grid.length && y < grid[0].length &&
(grid[y][x] === 0 || (x === end.x && y === end.y))
);
}
/**
* Checks if the given node is in the open list.
*/
private static isInOpenList(openList: Node[], node: Position): boolean {
return openList.some((n) => n.x === node.x && n.y === node.y);
}
/**
* Gets the distance between two positions.
*/
private static getDistance(a: Position, b: Position): number {
const dx = Math.abs(a.x - b.x);
const dy = Math.abs(a.y - b.y);
if (a.x === b.x || a.y === b.y) {
// Orthogonal movement (horizontal/vertical)
return Math.sqrt(dx * dx + dy * dy);
} else {
// Diagonal movement with cost sqrt(2)
return Math.sqrt(dx * dx + dy * dy);
} }
} }
return neighbors /**
* Heuristic function estimating the distance from a node to the goal.
*/
private static heuristic(node: Position, goal: Position): number {
return this.getDistance(node, goal);
}
/**
* Reconstructs the path from the end node.
*/
private static reconstructPath(endNode: Node): Node[] {
const path: Node[] = [];
let currentNode: Node | undefined = endNode;
while (currentNode) {
path.unshift(currentNode);
currentNode = currentNode.parent;
}
return path;
} }
} }
export default AStar export default AStar;