JSFiddle - React, Tailwind, and code Playground
by ajinkyax
JavaScript
var plan =
[
'##o#',
'#oo#',
'ooo#',
'oooo'
];
function Grid(width, height){
this.space = new Array(width * height);
this.width = width;
this.height = height;
}
Grid.prototype.set = function(vector, char){
this.space[vector.x + vector.y * this.width] = char;
//=> this.space[22] = "#"
};
Grid.prototype.get = function(vector){
return this.space[vector.x + vector.y * this.width];
};
function elementFromChar(legend, char){
if(char === " ") {
return null;
}
var element = new legend[char]();
element.originChar = char;
return element;
}
function charFromElement(element){
if(element.originChar === null) {
return " ";
}
return element.originChar;
}
function Vector(x, y) {
this.x = x;
this.y = y;
}
//the world object
function World(map, legend){
var grid = new Grid(map[0].length, map.length);
this.grid = grid;
this.legend = legend;
map.forEach(function(line, y){
for(var x = 0; x < line.length; x++){
grid.set(new Vector(x, y), elementFromChar(legend, line[x]));
}
});
}
World.prototype.toString = function(){
var output = "", elem;
for(var y = 0; y < this.grid.height; y++) {
for(var x = 0; x < this.grid.width; x++) {
elem = this.grid.space[x + y * this.grid.width];
output += elem.originChar;
}
output += "\n";
}
return output;
};
function Wall(){}
function Circle(){}
var world = new World(plan, {"#": Wall, "o": Circle});
console.log(world.toString());