initial commit
This commit is contained in:
87
MapLoader.js
Normal file
87
MapLoader.js
Normal file
@@ -0,0 +1,87 @@
|
||||
class MapLoader {
|
||||
constructor(fileName) {
|
||||
this.fileName = fileName;
|
||||
this.fileContent = null;
|
||||
}
|
||||
|
||||
start() {
|
||||
this.readFile();
|
||||
}
|
||||
|
||||
readFile() {
|
||||
const rawFile = new XMLHttpRequest();
|
||||
rawFile.open("GET", this.fileName, false);
|
||||
rawFile.addEventListener('readystatechange', () => {
|
||||
if(rawFile.readyState === 4) {
|
||||
if(rawFile.status === 200 || rawFile.status === 0) {
|
||||
const content = rawFile.responseText;
|
||||
console.log(content);
|
||||
this.fileContent = content;
|
||||
|
||||
this.loadMap();
|
||||
}
|
||||
}
|
||||
});
|
||||
rawFile.send(null);
|
||||
}
|
||||
|
||||
loadMap() {
|
||||
const tiles = [];
|
||||
const mapRaw = this.fileContent;
|
||||
|
||||
const rows = mapRaw.split(/\r?\n/g);
|
||||
|
||||
if(rows.length === 0) {
|
||||
throw LoadingException;
|
||||
}
|
||||
|
||||
const width = rows[0].length,
|
||||
height = rows.length;
|
||||
let spawn;
|
||||
|
||||
for(let x = 0; x < width; x++) {
|
||||
tiles.push([]);
|
||||
}
|
||||
|
||||
rows.forEach((row, y) => {
|
||||
if(row.length !== width) {
|
||||
throw `Row length not consistent. Expected ${width}, got ${row.length} at row ${y}`;
|
||||
}
|
||||
|
||||
for(let x = 0; x < row.length; x++) {
|
||||
const tileRaw = row[x];
|
||||
let tile;
|
||||
|
||||
switch (tileRaw) {
|
||||
case 'X':
|
||||
tile = new MapTile(x, y, true);
|
||||
break;
|
||||
case '.':
|
||||
tile = new MapTile(x, y, false, true);
|
||||
break;
|
||||
case '-':
|
||||
tile = new MapTile(x, y, false);
|
||||
break;
|
||||
case 'S':
|
||||
tile = new MapTile(x, y, false);
|
||||
spawn = {x, y};
|
||||
break;
|
||||
case 'O':
|
||||
tile = new MapTile(x, y, false);
|
||||
break;
|
||||
}
|
||||
|
||||
tiles[x][y] = tile;
|
||||
}
|
||||
});
|
||||
|
||||
this.map = new GameMap(tiles, spawn);
|
||||
}
|
||||
|
||||
getMap() {
|
||||
while(!this.map) {
|
||||
|
||||
}
|
||||
return this.map;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user