1
0
forked from noxious/server

code update

This commit is contained in:
2024-05-09 22:03:21 +02:00
parent 8356a83431
commit a2f21229d8
14 changed files with 216 additions and 45 deletions

53
src/app/ZoneManager.ts Normal file
View File

@ -0,0 +1,53 @@
import { Zone } from "@prisma/client";
import { LoadedZoneEntity } from "./entities/LoadedZoneEntity";
import ZoneRepository from "./repositories/zone";
class ZoneManager {
private static _instance: ZoneManager;
private _loadedZones: LoadedZoneEntity[] = [];
private constructor() {}
// Singleton instance getter
public static getInstance(): ZoneManager {
if (!ZoneManager._instance) {
ZoneManager._instance = new ZoneManager();
}
return ZoneManager._instance;
}
// Method to initialize zone loading
public async boot() {
const zoneRepository = new ZoneRepository();
const zones = await zoneRepository.getAll();
for (const zone of zones) {
this.loadZone(zone);
}
console.log('[✅] ZoneManager loaded');
}
// Method to handle individual zone loading
public loadZone(zone: Zone) {
const loadedZone = new LoadedZoneEntity(zone);
this._loadedZones.push(loadedZone);
console.log(`[✅] Zone ID ${zone.id} loaded`);
}
// Method to handle individual zone unloading
public unloadZone(zoneId: number) {
const index = this._loadedZones.findIndex(loadedZone => loadedZone.getZone().id === zoneId);
if (index > -1) {
this._loadedZones.splice(index, 1);
console.log(`[❌] Zone ID ${zoneId} unloaded`);
}
}
// Getter for loaded zones
public getLoadedZones(): LoadedZoneEntity[] {
return this._loadedZones;
}
}
export default ZoneManager;

View File

@ -0,0 +1,37 @@
import { PlayerEntity } from "./PlayerEntity";
import {Zone} from "@prisma/client";
export class LoadedZoneEntity
{
zone: Zone;
players: Map<string, PlayerEntity>;
constructor(zone: Zone) {
this.zone = zone;
this.players = new Map();
}
getZone() {
return this.zone;
}
addPlayer(player: PlayerEntity) {
this.players.set(player.id, player);
}
removePlayer(player: PlayerEntity) {
this.players.delete(player.id);
}
getPlayer(playerId: string) {
return this.players.get(playerId);
}
getPlayers() {
return Array.from(this.players.values());
}
getPlayersCount() {
return this.players.size;
}
}

View File

@ -0,0 +1,17 @@
export class PlayerEntity
{
id: string;
name: string;
position: { x: number, y: number };
constructor(id: string, name: string, position: { x: number, y: number }) {
this.id = id;
this.name = name;
this.position = position;
}
move(x: number, y: number) {
this.position.x = x;
this.position.y = y;
}
}

View File

@ -1,6 +1,6 @@
import { Socket, Server } from "socket.io";
export default function player_map_load(socket: Socket, io: Server) {
export default function player_zone_load(socket: Socket, io: Server) {
socket.on('player:map:load', (data) => {
console.log(`---User ${socket.id} has requested map.`);
});

View File

@ -1,15 +0,0 @@
import { Map } from '@prisma/client';
import prisma from '../utilities/prisma'; // Import the global Prisma instance
class MapRepository {
async getFirst(): Promise<Map | null> {
try {
return await prisma.map.findFirst();
} catch (error: any) {
// Handle error
throw new Error(`Failed to get first map: ${error.message}`);
}
}
}
export default MapRepository;

View File

@ -0,0 +1,24 @@
import { Zone } from '@prisma/client';
import prisma from '../utilities/prisma'; // Import the global Prisma instance
class ZoneRepository {
async getFirst(): Promise<Zone | null> {
try {
return await prisma.zone.findFirst();
} catch (error: any) {
// Handle error
throw new Error(`Failed to get first zone: ${error.message}`);
}
}
async getAll(): Promise<Zone[]> {
try {
return await prisma.zone.findMany();
} catch (error: any) {
// Handle error
throw new Error(`Failed to get all zone: ${error.message}`);
}
}
}
export default ZoneRepository;

View File

@ -1,81 +0,0 @@
import fs from "fs";
import path from "path";
import express from 'express';
import http from 'http';
import cors from 'cors';
import {Server as HttpServer, Socket} from 'socket.io';
import config from './utilities/config';
import prisma from './utilities/prisma';
import api from "./utilities/api";
export class Server
{
private readonly app: express.Application;
private readonly server: any;
private readonly io: HttpServer;
/**
* Creates an instance of GameServer.
*/
constructor() {
this.app = express();
this.app.use(cors());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.server = http.createServer(this.app)
this.io = new HttpServer(this.server);
}
/**
* Start the server
*/
public async start() {
// Print logo
const art = fs.readFileSync(path.join(__dirname, 'logo.txt'), 'utf8');
console.log('\x1b[31m%s\x1b[0m', art + '\n');
// Check prisma connection
try {
await prisma.$connect();
console.log('[✅] Database connected');
} catch (error: any) {
throw new Error(`[❌] Database connection failed: ${error.message}`);
}
// Start the server
try {
await this.server.listen(config.PORT);
console.log('[✅] Socket.IO running on port', config.PORT);
} catch (error: any) {
throw new Error(`[❌] Socket.IO failed to start: ${error.message}`);
}
// Add API routes
await api.addAuthRoutes(this.app);
// Add socket events
this.io.on('connection', this.handleConnection.bind(this));
}
/**
* Handle socket connection
* @param socket
* @private
*/
private async handleConnection(socket: Socket) {
const eventsPath = path.join(__dirname, 'events');
try {
const files = await fs.promises.readdir(eventsPath);
for (const file of files) {
if (!file.endsWith('.ts')) {
continue;
}
const module = await import(path.join(eventsPath, file));
module.default(socket, this.io);
}
} catch (error: any) {
throw new Error('[❌] Failed to load event handlers: ' + error.message);
}
}
}

13
src/app/services/zone.ts Normal file
View File

@ -0,0 +1,13 @@
import {LoadedZoneEntity} from "../entities/LoadedZoneEntity";
import {Zone} from "@prisma/client";
class ZoneService
{
public loaded: LoadedZoneEntity[] = [];
public boot() {
// Load all zones
// const zones = await new ZoneRepository().getAll();
// this.loadedZones = zones;
}
}

View File

@ -26,7 +26,7 @@ async function addAuthRoutes(app: any) {
return res.status(400).json({ message: 'Failed to register user' });
});
console.log('[🌎] Auth routes added');
console.log('[🕸️] Auth routes added');
}
export default { addAuthRoutes };