-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathparse_map.js
More file actions
78 lines (70 loc) · 1.68 KB
/
parse_map.js
File metadata and controls
78 lines (70 loc) · 1.68 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
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
#!/usr/bin/env node
/**
* Convert the `map` files into json
*
* All maps begin with the lines:
*
* type octile
* height x
* width y
* map
*
* where x and y are the repsective height and width of the map.
*
* The map data is store as an ASCII grid. The following characters are possible:
*
* . - passable terrain
* G - passable terrain
* @ - out of bounds
* O - out of bounds
* T - trees (unpassable)
* S - swamp (passable from regular terrain)
* W - water (traversable, but not passable from terrain)
*
*/
/**
* Implementation note:
* For convenience, only '.' and 'G' are interpreted as walkable.
*/
var fs = require('fs');
function parse(filename) {
var content = fs.readFileSync(filename, { encoding: 'utf8' });
var lines = content.split(/\r?\n/);
return {
height : parseInt(lines[1].split(' ')[1]),
width : parseInt(lines[2].split(' ')[1]),
grid : parseGrid(lines.slice(4)),
};
}
exports.parse = parse;
function parseGrid(lines) {
var grid = [];
lines.forEach(function(line) {
if (!line.length) {
return;
}
var row = [];
line.split('').forEach(function(char) {
row.push(char in { '.': 1, 'G': 1 } ? 0 : 1);
});
grid.push(row);
});
return grid;
}
function splitext(filename) {
var index = filename.lastIndexOf('.');
if (index < 0) {
return [filename, ''];
} else {
return [filename.substr(0, index), filename.substr(index)];
}
}
function main(argv) {
var filename = argv[2];
var obj = parse(filename);
var root = splitext(filename)[0];
fs.writeFileSync(root + '.json', JSON.stringify(obj));
}
if (!module.parent) {
main(process.argv);
}