mc-beta-server/server/World.ts

89 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-04-08 20:52:47 +01:00
import { FunkyArray } from "../funkyArray";
import { Chunk } from "./Chunk";
import { IEntity } from "./entities/IEntity";
2023-04-09 04:19:10 +01:00
import { Player } from "./entities/Player";
2023-04-09 04:47:23 +01:00
//import { FlatGenerator } from "./generators/Flat";
2023-04-09 04:19:10 +01:00
import { HillyGenerator } from "./generators/Hilly";
2023-04-08 20:52:47 +01:00
import { IGenerator } from "./generators/IGenerator";
export class World {
public chunks:FunkyArray<number, Chunk>;
public entites:FunkyArray<number, IEntity>;
public generator:IGenerator;
2023-04-09 04:19:10 +01:00
public constructor(seed:number) {
2023-04-08 20:52:47 +01:00
this.chunks = new FunkyArray<number, Chunk>();
this.entites = new FunkyArray<number, IEntity>();
2023-04-09 04:19:10 +01:00
this.generator = new HillyGenerator(seed);
2023-04-08 20:52:47 +01:00
}
public addEntity(entity:IEntity) {
this.entites.set(entity.entityId, entity);
}
2023-04-09 04:19:10 +01:00
// TODO: getChunkByCoordPair failed in here during removeEntity, figure out why.
public removeEntity(entity:IEntity) {
if (entity instanceof Player) {
2023-04-09 04:47:23 +01:00
for (const coordPair of entity.loadedChunks) {
2023-04-09 04:19:10 +01:00
const chunk = this.getChunkByCoordPair(coordPair);
chunk.playersInChunk.remove(entity.entityId);
if (chunk.playersInChunk.length === 0) {
this.unloadChunk(coordPair);
}
}
}
this.entites.remove(entity.entityId);
// TODO: Inform clients about entity removal
}
public getChunk(x:number, z:number, generate:boolean = true) {
const coordPair = Chunk.CreateCoordPair(x, z);
const existingChunk = this.chunks.get(coordPair);
if (!(existingChunk instanceof Chunk)) {
if (generate) {
return this.chunks.set(coordPair, new Chunk(this, x, z));
}
throw new Error(`BADLOOKUP: Chunk [${x}, ${z}] does not exist.`);
2023-04-08 20:52:47 +01:00
}
2023-04-09 04:19:10 +01:00
return existingChunk;
2023-04-08 20:52:47 +01:00
}
2023-04-09 04:19:10 +01:00
public getChunkByCoordPair(coordPair:number) {
const existingChunk = this.chunks.get(coordPair);
if (!(existingChunk instanceof Chunk)) {
throw new Error(`BADLOOKUP: Chunk ${coordPair} does not exist.`);
}
return existingChunk;
}
public unloadChunk(coordPair:number) {
// TODO: Save to disk
this.chunks.remove(coordPair);
2023-04-08 20:52:47 +01:00
}
2023-04-09 04:47:23 +01:00
public tick() {
2023-04-09 04:19:10 +01:00
this.entites.forEach(entity => {
if (entity instanceof Player) {
if (entity.justUnloaded.length > 0) {
2023-04-09 04:47:23 +01:00
for (const coordPair of entity.justUnloaded) {
2023-04-09 04:19:10 +01:00
const chunkToUnload = this.getChunkByCoordPair(coordPair);
chunkToUnload.playersInChunk.remove(entity.entityId);
if (chunkToUnload.playersInChunk.length === 0) {
this.unloadChunk(coordPair);
}
}
entity.justUnloaded = new Array<number>();
}
}
entity.onTick();
})
2023-04-08 20:52:47 +01:00
}
}