All files / games/roguelike/src/game/engine/systems movement.ts

100% Statements 22/22
100% Branches 12/12
100% Functions 6/6
100% Lines 22/22

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74        19x       19x             19x                 15x   15x 15x       1x       1x       6x 6x   6x 5x       5x           10x         10x 8x   8x 7x 5x 2x 1x         10x      
import { PositionInterface } from "jga-games-map";
 
import { GameMap, TileInterface } from "../../map";
 
import { ComponentName, PositionComponent } from "../components";
 
import { Entity } from "../entity";
 
import { System } from "./system";
 
export interface MoveInterface {
    canMove: boolean;
    newPosition: PositionInterface | null;
}
 
export class MovementSystem extends System {
    protected position: PositionInterface;
    protected map: GameMap;
 
    public constructor(
        entities: Map<string, Entity>,
        position: PositionInterface,
        map: GameMap,
    ) {
        super(entities, [ComponentName.MOVEABLE, ComponentName.POSITION]);
 
        this.position = position;
        this.map = map;
    }
 
    public getPosition(): PositionInterface {
        return this.position;
    }
 
    public getMap(): GameMap {
        return this.map;
    }
 
    public run(): void {
        this.entities.forEach((entity, key): void => {
            const move = this.canMove();
 
            if (move.canMove) {
                const positionComponent = entity.getComponent(
                    ComponentName.POSITION,
                ) as PositionComponent;
 
                positionComponent.setPosition(this.position);
            }
        });
    }
 
    public canMove(): MoveInterface {
        const move: MoveInterface = {
            canMove: false,
            newPosition: this.position,
        };
 
        if (null != this.position && null != this.map) {
            const tile: TileInterface = this.map.getTile(this.position);
 
            if (null !== tile) {
                if (tile.isWalkable) {
                    move.canMove = true;
                } else if (tile.isDiggable) {
                    this.map.dig(this.position);
                }
            }
        }
 
        return move;
    }
}