-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.ts
131 lines (106 loc) · 2.74 KB
/
node.ts
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import { Box, OutOfBoundsError, XY, XYSet, combine } from "./deps.ts";
import { Sprite } from "./sprite.ts";
export abstract class Node {
abstract sprites: Sprite[];
protected abstract box: Box;
drawnPoints: XYSet = XYSet.empty();
shape: XYSet = XYSet.empty();
invalidatePreviouslyDrawnPoints() {
this.drawnPoints = XYSet.empty();
}
abstract currentLocation: XY;
clear() {
this.drawnPoints.coordinates.map((point) => {
this.box.clear(point);
});
this.invalidatePreviouslyDrawnPoints();
}
drawCurrentSprites() {
const previouslyDrawnPoints = this.drawnPoints.copy();
try {
this.drawnPoints = XYSet.empty();
this.shape = XYSet.empty();
this.sprites.forEach((sprite) => {
sprite.offsetPoints.forEach((point) => {
const relativeCoordinate = point.coordinate;
const actualCoordinate = combine([
this.currentLocation,
relativeCoordinate,
]);
this.box.bufferedWriteCharacter(point, actualCoordinate);
this.drawnPoints.add(actualCoordinate);
this.shape.add(relativeCoordinate);
});
});
previouslyDrawnPoints.exclude(this.drawnPoints).forEach((point) => {
this.box.clear(point);
});
} catch (error) {
if (!(error instanceof OutOfBoundsError)) {
throw error;
}
this.clear();
previouslyDrawnPoints.coordinates.map((point) => {
this.box.clear(point);
});
throw error;
}
}
switchSprites(sprites: Sprite[]) {
this.sprites = sprites;
this.drawCurrentSprites();
}
/**
* Move to a location
*/
moveTo({ x, y }: XY) {
const prev = { ...this.currentLocation };
try {
this.currentLocation.x = x;
this.currentLocation.y = y;
this.drawCurrentSprites();
} catch (error) {
this.currentLocation = prev;
this.drawCurrentSprites();
throw error;
}
}
/**
* Move by amount
*/
moveBy({ x, y }: XY) {
this.moveTo({
x: x + this.currentLocation.x,
y: y + this.currentLocation.y,
});
}
moveUp() {
this.moveBy({ x: 0, y: -1 });
}
moveDown() {
this.moveBy({ x: 0, y: 1 });
}
moveRight() {
this.moveBy({ x: 1, y: 0 });
}
moveLeft() {
this.moveBy({ x: -1, y: 0 });
}
get isAtBottomOfBox() {
const currentLowest = this.drawnPoints.bottommost?.y;
return (
this.box.height - 1 ===
(currentLowest ? currentLowest : this.currentLocation.y)
);
}
get distanceToBottomOfBox() {
const currentLowest = this.shape.bottommost;
return (
this.box.height -
((currentLowest
? combine([currentLowest, this.currentLocation]).y
: this.currentLocation.y) +
1)
);
}
}