-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathboard.js
65 lines (52 loc) · 1.8 KB
/
board.js
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
var Constants = require('../utility/constants');
class Board {
constructor(width=Constants.width, height=Constants.height) {
this.width = width;
this.height = height;
this.score = 0;
this.objects = [];
}
add(character) {
if (character.x >= 0 && character.x < this.width && character.y >= 0 && character.y < this.height) {
// Character is in bounds, safe to insert.
this.objects.push(character);
}
else {
throw 'Invalid character position: ' + character.toString(true) + '. Board size is width=' + this.width + ', height=' + this.height +'.';
}
}
findByType(type) {
return this.objects.filter(obj => { return obj.type === type });
}
player() {
var player = this.findByType(Constants.type.PLAYER);
return player.length ? player[0] : null;
}
treasure() {
var treasure = this.findByType(Constants.type.TREASURE);
return treasure.length ? treasure[0] : null;
}
update() {
// Find the player.
var player = this.player();
if (player) {
// Find any objects in the same cell as the player and notify the player object of the collision.
var objects = this.objects.filter(obj => { return obj.isAlive && obj !== player && obj.x === player.x && obj.y === player.y });
objects.forEach(obj => player.collide(obj));
}
}
toString() {
var result = '';
// Draw the board.
for (var y=0; y<this.height; y++) {
for (var x=0; x<this.width; x++) {
var objectsInPosition = this.objects.filter(obj => { return obj.x === x && obj.y === y });
// Display the first character on this spot.
result += objectsInPosition.length ? (objectsInPosition[0].toString() || '.') : '.';
}
result += y < this.height - 1 ? '\n' : '';
}
return result;
}
}
module.exports = Board;