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
75
76
77
78
79
80
81
82
83
84
85
|
'use strict';
import Direction from '../model/Direction';
import Entity from '../model/Entity';
import EntityPosition from '../model/EntityPosition';
import MapData from '../model/MapData';
import Position from '../model/Position';
import Transition from '../model/Transition';
import InputHandler from '../view/InputHandler';
import MapView from '../view/MapView';
export default class MapContext {
view: MapView;
entities: {[key: string]: EntityPosition} = {};
playerEntity: EntityPosition;
constructor(private map: MapData, private inputHandler: InputHandler) {
this.playerEntity = new EntityPosition(
new Entity('square'),
new Position(8, 8),
Direction.East
);
this.addEntity(this.playerEntity);
this.view = new MapView(map, this.entities, (time: number) => this.updateState(time));
inputHandler.addListener(() => {
if (this.updateState(performance.now()))
this.view.redraw();
});
}
private addEntity(entity: EntityPosition) {
this.entities[entity.position.asString()] = entity;
}
private addTransition(entity: EntityPosition, dest: Position, start: number, dur: number) {
entity.transition = new Transition(start, start+dur, entity.position, dest);
}
private finishTransition(entity: EntityPosition) {
entity.position = entity.transition.dest;
entity.transition = null;
}
private updateState(time: number): boolean {
var ret = false;
while (true) {
var origTime = time;
if (this.playerEntity.transition && this.playerEntity.transition.end <= time) {
origTime = this.playerEntity.transition.end;
this.finishTransition(this.playerEntity);
ret = true;
}
if (this.playerEntity.transition)
return true;
var dir: Direction = null;
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 (dir === null)
return ret;
this.playerEntity.direction = dir;
this.addTransition(this.playerEntity, this.playerEntity.position.translate(dir, 1),
origTime, 250);
}
}
}
|