From b7fec57c0463e58f1ad8db126ff4879f59b057d0 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Wed, 6 Jan 2016 21:39:15 +0100 Subject: Start implementing input handling --- src/control/MapContext.ts | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) (limited to 'src/control') diff --git a/src/control/MapContext.ts b/src/control/MapContext.ts index 4bc75c7..df7eff6 100644 --- a/src/control/MapContext.ts +++ b/src/control/MapContext.ts @@ -7,6 +7,7 @@ import EntityPosition from '../model/EntityPosition'; import MapData from '../model/MapData'; import Position from '../model/Position'; +import InputHandler from '../view/InputHandler'; import MapView from '../view/MapView'; @@ -16,7 +17,7 @@ export default class MapContext { entities: {[key: string]: EntityPosition} = {}; playerEntity: EntityPosition; - constructor(public map: MapData) { + constructor(private map: MapData, private inputHandler: InputHandler) { this.playerEntity = new EntityPosition( new Entity('square'), new Position(8, 8), @@ -25,10 +26,36 @@ export default class MapContext { this.addEntity(this.playerEntity); - this.view = new MapView(map, this.entities); + this.view = new MapView(map, this.entities, (time: number) => this.updateState(time)); + + inputHandler.addListener(() => { + if (this.updateState(performance.now())) + this.view.redraw(); + }); } - addEntity(entity: EntityPosition) { + private addEntity(entity: EntityPosition) { this.entities[entity.position.asString()] = entity; } + + private updateState(time: number): boolean { + var ret = false; + var dir = this.playerEntity.direction; + + if (this.inputHandler.keys[InputHandler.Up]) + dir = Direction.North; + else if (this.inputHandler.keys[InputHandler.Right]) + dir = Direction.East; + else if (this.inputHandler.keys[InputHandler.Down]) + dir = Direction.South; + else if (this.inputHandler.keys[InputHandler.Left]) + dir = Direction.West; + + if (this.playerEntity.direction !== dir) { + this.playerEntity.direction = dir; + ret = true; + } + + return ret; + } } -- cgit v1.2.3