All files / patterns/ecs/src engine.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 593x       3x                   3x       7x       6x       4x   4x   4x       4x       2x 1x         1x 1x           4x 4x     4x      
import { uuid } from "jga-generators-uuid";
 
import { SystemInterface } from "./system";
 
import { Entity, EntityInterface } from "./entity";
 
export interface EngineInterface {
    getEntities(): Map<string, EntityInterface>;
    addEntity(entity: EntityInterface): void;
    createEntity(): EntityInterface;
    removeEntity(id: string): void;
    process(systems: SystemInterface[]): void;
}
 
export class Engine implements EngineInterface {
    protected entities: Map<string, EntityInterface>;
 
    public constructor() {
        this.entities = new Map<string, EntityInterface>();
    }
 
    public getEntities(): Map<string, EntityInterface> {
        return this.entities;
    }
 
    public createEntity(): EntityInterface {
        const entity = new Entity(this.generateId());
 
        this.addEntity(entity);
 
        return entity;
    }
 
    public addEntity(entity: EntityInterface): void {
        this.entities.set(entity.getId(), entity);
    }
 
    public removeEntity(id: string): void {
        if (this.entities.has(id)) {
            this.entities.delete(id);
        }
    }
 
    public process(systems: SystemInterface[]): void {
        systems.forEach((system): void => {
            system.run();
        });
    }
 
    protected generateId(): string {
        let id: string;
        do {
            id = uuid();
        } while (this.entities.has(id));
 
        return id;
    }
}