-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrid.js
More file actions
51 lines (48 loc) · 1.17 KB
/
grid.js
File metadata and controls
51 lines (48 loc) · 1.17 KB
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
var fs = require('fs');
exports.makeGrid = function(width, height, components) {
var grid = [];
grid.width = width;
grid.height = height;
grid.get = function(x, y) {
return grid[y*width+x];
};
grid.set = function(x, y, d) {
grid[y*width+x] = d;
};
grid.toJSON = function() {
return {
width: this.width,
height: this.height,
data: this.slice(0)
};
};
var l = width * height;
for(var i = 0; i < l; ++i) {
if(components && components[i]) {
grid[i] = components[i];
} else {
grid[i] = 'XX';
}
}
return grid;
};
exports.loadGrid = function(filename) {
var contents = fs.readFileSync(filename, { encoding: 'utf8' });
var lines = contents.split('\n').filter(function(l) {
return l.length >= 2 && l[0] != '#';
}).map(function(l) {
return l.split(/[ ]+/).filter(function(c) {
return !!c.length;
});
});
var width = lines[0].length;
var height = lines.length;
var components = Array.prototype.concat.apply([], lines);
return exports.makeGrid(width, height, components);
};
exports.printGrid = function(grid) {
for(var i = 0; i < grid.height; i++) {
var row = grid.slice(i * grid.width, (i + 1) * grid.width);
console.log(row.join(' '));
}
};