template/packages-user/data-base/src/hero/location.ts

85 lines
1.9 KiB
TypeScript

import {
Hookable,
HookController,
IHookController,
IFaceHandler
} from '@motajs/common';
import {
FaceDirection,
IDataCommon,
IFacedTileLocator
} from '@user/data-common';
import { HeroMover } from './mover';
import {
IHeroLocation,
IHeroLocationHooks,
IHeroLocationSave,
IHeroMover
} from './types';
import { IGameMap } from '../map';
export class HeroLocation
extends Hookable<IHeroLocationHooks>
implements IHeroLocation
{
x: number;
y: number;
floorId: string | undefined = undefined;
map: IGameMap | null = null;
readonly state: IDataCommon;
readonly mover: IHeroMover<this>;
constructor(
state: IDataCommon,
loc: IFacedTileLocator,
faceHandler: IFaceHandler<FaceDirection>
) {
super();
this.state = state;
this.x = loc.x;
this.y = loc.y;
const mover = new HeroMover(this, faceHandler);
mover.faceDirection = loc.direction;
this.mover = mover;
}
protected createController(
hook: Partial<IHeroLocationHooks>
): IHookController<IHeroLocationHooks> {
return new HookController(this, hook);
}
setFloor(map: IGameMap): void {
this.floorId = map.floorId;
this.map = map;
this.forEachHook(hook => hook.onSetFloor?.(map));
}
setPos(x: number, y: number): void {
this.x = x;
this.y = y;
this.forEachHook(hook => hook.onSetPos?.(x, y));
}
getCurrentFaceDirection(): FaceDirection {
return this.mover.faceDirection;
}
saveState(): IHeroLocationSave {
return {
x: this.x,
y: this.y,
direction: this.mover.faceDirection,
floorId: this.floorId
};
}
loadState(state: IHeroLocationSave): void {
this.x = state.x;
this.y = state.y;
this.floorId = state.floorId;
this.mover.setFaceDir(state.direction);
}
}