From bbeac955125d260b135caee94a1353de08bc03e1 Mon Sep 17 00:00:00 2001 From: Dennis Postma Date: Mon, 29 Jul 2024 09:01:54 +0200 Subject: [PATCH] Worked on pathfinding, character animation & rotation, few enhancements --- src/events/character/Move.ts | 95 ++++++++++----------- src/managers/ZoneManager.ts | 94 ++++++++++----------- src/repositories/CharacterRepository.ts | 31 ++++++- src/utilities/Http.ts | 26 +++--- src/utilities/Player/AStar.ts | 106 +++++++++++------------- 5 files changed, 188 insertions(+), 164 deletions(-) diff --git a/src/events/character/Move.ts b/src/events/character/Move.ts index c17481c..d0f8f57 100644 --- a/src/events/character/Move.ts +++ b/src/events/character/Move.ts @@ -1,95 +1,96 @@ -import { Server } from 'socket.io'; -import { TSocket } from '../../utilities/Types'; -import ZoneManager from '../../managers/ZoneManager'; -import prisma from '../../utilities/Prisma'; -import AStar, { type Node } from '../../utilities/Player/AStar'; -import Rotation from '../../utilities/Player/Rotation'; +import { Server } from 'socket.io' +import { TSocket } from '../../utilities/Types' +import ZoneManager from '../../managers/ZoneManager' +import prisma from '../../utilities/Prisma' +import AStar, { type Node } from '../../utilities/Player/AStar' +import Rotation from '../../utilities/Player/Rotation' interface SocketResponse { - position_x: number; - position_y: number; + position_x: number + position_y: number } interface Character { - id: number; - position_x: number; - position_y: number; - rotation: number; - zoneId: number; + 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 { - console.log('character:move requested', data); + console.log('character:move requested', data) if (!socket.character) { - console.error('character:move error', 'Character not found'); - return; + console.error('character:move error', 'Character not found') + return } - const grid = await ZoneManager.getGrid(socket.character.zoneId); + const grid = await ZoneManager.getGrid(socket.character.zoneId) if (grid.length === 0) { - console.error('character:move error', 'Grid not found'); - return; + console.error('character:move error', 'Grid not found') + return } - const start = { x: socket.character.position_x, y: socket.character.position_y }; - const end = { x: data.position_x, y: data.position_y }; + const start = { x: socket.character.position_x, y: socket.character.position_y } + const end = { x: data.position_x, y: data.position_y } - const path = AStar.findPath(start, end, grid); + const path = AStar.findPath(start, end, grid) if (path.length > 0) { - await moveAlongPath(socket, io, path, grid); + await moveAlongPath(socket, io, path, grid) } else { - console.log('character:move error', 'No valid path found'); + console.log('character:move error', 'No valid path found') } } catch (error) { - console.error('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; + if (!socket.character) return - for (const position of path) { + for (let i = 0; i < path.length; i++) { + const position = path[i] if (isObstacle(position, grid)) { - console.log('Obstacle encountered at', position); - break; + console.log('Obstacle encountered at', position) + break } - const rotation = Rotation.calculate( - socket.character.position_x, - socket.character.position_y, - position.x, - position.y - ); + // Calculate rotation based on the next position in the path + let rotation = socket.character.rotation + if (i < path.length - 1) { + const nextPosition = path[i + 1] + rotation = Rotation.calculate(position.x, position.y, nextPosition.x, nextPosition.y) + } - await updateCharacterPosition(socket.character, position.x, position.y, rotation); + 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); + ZoneManager.updateCharacterInZone(socket.character.zoneId, socket.character) + io.in(socket.character.zoneId.toString()).emit('character:moved', socket.character) - console.log('Character moved to', position); + console.log('Character moved to', position) // Add a small delay between moves to avoid overwhelming the server - await new Promise(resolve => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)) } } function isObstacle(position: Node, grid: number[][]): boolean { - return grid[position.y][position.x] === 1; + 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; + 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 } - }); -} \ No newline at end of file + }) +} diff --git a/src/managers/ZoneManager.ts b/src/managers/ZoneManager.ts index bb44f31..7c549c1 100644 --- a/src/managers/ZoneManager.ts +++ b/src/managers/ZoneManager.ts @@ -1,124 +1,124 @@ -import { Character, Zone } from '@prisma/client'; -import ZoneRepository from '../repositories/ZoneRepository'; -import ZoneService from '../services/ZoneService'; -import zoneRepository from '../repositories/ZoneRepository'; +import { Character, Zone } from '@prisma/client' +import ZoneRepository from '../repositories/ZoneRepository' +import ZoneService from '../services/ZoneService' +import zoneRepository from '../repositories/ZoneRepository' type TLoadedZone = { - zone: Zone, - characters: Character[], + zone: Zone + characters: Character[] grid: number[][] -}; +} class ZoneManager { - private loadedZones: TLoadedZone[] = []; + private loadedZones: TLoadedZone[] = [] // Method to initialize zone manager public async boot() { if (!(await ZoneRepository.getById(1))) { - const zoneService = new ZoneService(); - await zoneService.createDemoZone(); + const zoneService = new ZoneService() + await zoneService.createDemoZone() } - const zones = await ZoneRepository.getAll(); + const zones = await ZoneRepository.getAll() for (const zone of zones) { - await this.loadZone(zone); + await this.loadZone(zone) } - console.log('[✅] Zone manager loaded'); + console.log('[✅] Zone manager loaded') } // Method to handle individual zone loading public async loadZone(zone: Zone) { - const grid = await this.getGrid(zone.id); // Create the grid for the zone + const grid = await this.getGrid(zone.id) // Create the grid for the zone this.loadedZones.push({ zone, characters: [], grid - }); - console.log(`[✅] Zone ID ${zone.id} loaded`); + }) + console.log(`[✅] Zone ID ${zone.id} loaded`) } // Method to handle individual zone unloading public unloadZone(zoneId: number) { this.loadedZones = this.loadedZones.filter((loadedZone) => { - return loadedZone.zone.id !== zoneId; - }); - console.log(`[❌] Zone ID ${zoneId} unloaded`); + return loadedZone.zone.id !== zoneId + }) + console.log(`[❌] Zone ID ${zoneId} unloaded`) } // Getter for loaded zones 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; + const loadedZone = this.loadedZones.find((lz) => lz.zone.id === zoneId) + return loadedZone ? loadedZone.grid[y][x] === 0 : false } public addCharacterToZone(zoneId: number, character: Character) { const loadedZone = this.loadedZones.find((loadedZone) => { - return loadedZone.zone.id === zoneId; - }); + return loadedZone.zone.id === zoneId + }) 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) { const loadedZone = this.loadedZones.find((loadedZone) => { - return loadedZone.zone.id === zoneId; - }); + return loadedZone.zone.id === zoneId + }) if (loadedZone) { loadedZone.characters = loadedZone.characters.filter((loadedCharacter) => { - return loadedCharacter.id !== character.id; - }); + return loadedCharacter.id !== character.id + }) } } public updateCharacterInZone(zoneId: number, character: Character) { const loadedZone = this.loadedZones.find((loadedZone) => { - return loadedZone.zone.id === zoneId; - }); + return loadedZone.zone.id === zoneId + }) if (loadedZone) { const characterIndex = loadedZone.characters.findIndex((loadedCharacter) => { - return loadedCharacter.id === character.id; - }); + return loadedCharacter.id === character.id + }) if (characterIndex !== -1) { - loadedZone.characters[characterIndex] = character; + loadedZone.characters[characterIndex] = character } } } public getCharactersInZone(zoneId: number): Character[] { const loadedZone = this.loadedZones.find((loadedZone) => { - return loadedZone.zone.id === zoneId; - }); - return loadedZone ? loadedZone.characters : []; + return loadedZone.zone.id === zoneId + }) + return loadedZone ? loadedZone.characters : [] } public async getGrid(zoneId: number): Promise { - const zone = this.loadedZones.find((z) => z.zone.id === zoneId); - if (zone) return zone.grid; + const zone = this.loadedZones.find((z) => z.zone.id === zoneId) + if (zone) return zone.grid - const loadedZone = await ZoneRepository.getById(zoneId); - if (!loadedZone) return []; + const loadedZone = await ZoneRepository.getById(zoneId) + if (!loadedZone) return [] - let grid: number[][] = Array.from({ length: loadedZone.height }, () => Array.from({ length: loadedZone.width }, () => 0)); + let grid: number[][] = Array.from({ length: loadedZone.height }, () => Array.from({ length: loadedZone.width }, () => 0)) - const eventTiles = await zoneRepository.getEventTiles(zoneId); + const eventTiles = await zoneRepository.getEventTiles(zoneId) // Set the grid values based on the event tiles, these are strings eventTiles.forEach((eventTile) => { if (eventTile.type === 'BLOCK') { - grid[eventTile.position_y][eventTile.position_x] = 1; + grid[eventTile.position_y][eventTile.position_x] = 1 } - }); + }) - return grid; + return grid } } -export default new ZoneManager(); +export default new ZoneManager() diff --git a/src/repositories/CharacterRepository.ts b/src/repositories/CharacterRepository.ts index 9234fa1..94f50cf 100644 --- a/src/repositories/CharacterRepository.ts +++ b/src/repositories/CharacterRepository.ts @@ -7,6 +7,14 @@ class CharacterRepository { return await prisma.character.findMany({ where: { userId + }, + include: { + zone: true, + characterType: { + include: { + sprite: true + } + } } }) } catch (error: any) { @@ -23,7 +31,12 @@ class CharacterRepository { id: characterId }, include: { - zone: true + zone: true, + characterType: { + include: { + sprite: true + } + } } }) } catch (error: any) { @@ -37,6 +50,14 @@ class CharacterRepository { return await prisma.character.findUnique({ where: { id + }, + include: { + zone: true, + characterType: { + include: { + sprite: true + } + } } }) } catch (error: any) { @@ -81,6 +102,14 @@ class CharacterRepository { return await prisma.character.findFirst({ where: { name + }, + include: { + zone: true, + characterType: { + include: { + sprite: true + } + } } }) } catch (error: any) { diff --git a/src/utilities/Http.ts b/src/utilities/Http.ts index aaaa9ad..0e064d5 100644 --- a/src/utilities/Http.ts +++ b/src/utilities/Http.ts @@ -49,31 +49,31 @@ async function addHttpRoutes(app: Application) { }) app.get('/assets/:type/:spriteId?/:file', (req: Request, res: Response) => { - const assetType = req.params.type; - const spriteId = req.params.spriteId; - const fileName = req.params.file; + const assetType = req.params.type + const spriteId = req.params.spriteId + const fileName = req.params.file - let assetPath; + let assetPath if (assetType === 'sprites' && spriteId) { - assetPath = path.join(process.cwd(), 'public', assetType, spriteId, fileName); + assetPath = path.join(process.cwd(), 'public', assetType, spriteId, fileName) } else { - assetPath = path.join(process.cwd(), 'public', assetType, fileName); + assetPath = path.join(process.cwd(), 'public', assetType, fileName) } - console.log(`Attempting to serve: ${assetPath}`); + console.log(`Attempting to serve: ${assetPath}`) if (!fs.existsSync(assetPath)) { - console.error(`File not found: ${assetPath}`); - return res.status(404).send('Asset not found'); + console.error(`File not found: ${assetPath}`) + return res.status(404).send('Asset not found') } res.sendFile(assetPath, (err) => { if (err) { - console.error('Error sending file:', err); - res.status(500).send('Error downloading the asset'); + console.error('Error sending file:', err) + res.status(500).send('Error downloading the asset') } - }); - }); + }) + }) app.post('/login', async (req: Request, res: Response) => { const { username, password } = req.body diff --git a/src/utilities/Player/AStar.ts b/src/utilities/Player/AStar.ts index 0cda4ae..dc33ec7 100644 --- a/src/utilities/Player/AStar.ts +++ b/src/utilities/Player/AStar.ts @@ -1,13 +1,13 @@ interface Position { - x: number; - y: number; + x: number + y: number } export interface Node extends Position { - parent?: Node; - g: number; - h: number; - f: number; + parent?: Node + g: number + h: number + f: number } /** @@ -16,17 +16,17 @@ export interface Node extends Position { class AStar { private static readonly ORTHOGONAL_DIRECTIONS: Position[] = [ { x: 0, y: -1 }, // up - { x: 0, y: 1 }, // down + { x: 0, y: 1 }, // down { x: -1, y: 0 }, // left - { x: 1, y: 0 } // right - ]; + { 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 - ]; + { 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. @@ -37,79 +37,77 @@ class AStar { * @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(); + const openList: Node[] = [] + const closedSet = new Set() - const startNode: Node = { ...start, g: 0, h: 0, f: 0 }; - openList.push(startNode); + const startNode: Node = { ...start, g: 0, h: 0, f: 0 } + openList.push(startNode) while (openList.length > 0) { - const currentNode = this.getLowestFScoreNode(openList); + const currentNode = this.getLowestFScoreNode(openList) if (this.isEndNode(currentNode, end)) { - return this.reconstructPath(currentNode); + return this.reconstructPath(currentNode) } - this.removeNodeFromOpenList(openList, currentNode); - closedSet.add(this.nodeToString(currentNode)); + this.removeNodeFromOpenList(openList, currentNode) + closedSet.add(this.nodeToString(currentNode)) for (const neighbor of this.getValidNeighbors(currentNode, grid, end, allowDiagonal)) { - if (closedSet.has(this.nodeToString(neighbor))) continue; + if (closedSet.has(this.nodeToString(neighbor))) continue - const tentativeGScore = currentNode.g + this.getDistance(currentNode, neighbor); + 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; + 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); + openList.push(neighbor) } } } } - return []; // No path found + return [] // No path found } /** * Gets the node with the lowest F score from a list. */ private static getLowestFScoreNode(nodes: Node[]): Node { - return nodes.reduce((min, node) => (node.f < min.f ? node : min)); + return nodes.reduce((min, node) => (node.f < min.f ? node : min)) } /** * Checks if the given node is the end node. */ private static isEndNode(node: Node, end: Position): boolean { - return node.x === end.x && node.y === end.y; + return node.x === end.x && node.y === end.y } /** * 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); + 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}`; + 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; + const directions = allowDiagonal ? [...this.ORTHOGONAL_DIRECTIONS, ...this.DIAGONAL_DIRECTIONS] : this.ORTHOGONAL_DIRECTIONS return directions .map((dir) => ({ @@ -119,41 +117,37 @@ class AStar { h: 0, f: 0 })) - .filter((pos) => this.isValidPosition(pos, grid, end)) as Node[]; + .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)) - ); + 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); + 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); + 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); + return Math.sqrt(dx * dx + dy * dy) } else { // Diagonal movement with cost sqrt(2) - return Math.sqrt(dx * dx + dy * dy); + return Math.sqrt(dx * dx + dy * dy) } } @@ -161,23 +155,23 @@ class AStar { * Heuristic function estimating the distance from a node to the goal. */ private static heuristic(node: Position, goal: Position): number { - return this.getDistance(node, goal); + 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; + const path: Node[] = [] + let currentNode: Node | undefined = endNode while (currentNode) { - path.unshift(currentNode); - currentNode = currentNode.parent; + path.unshift(currentNode) + currentNode = currentNode.parent } - return path; + return path } } -export default AStar; \ No newline at end of file +export default AStar