|
const Cast = require('../../util/cast'); |
|
const Clone = require('../../util/clone'); |
|
|
|
const blankGridReturn = { |
|
grid: [ |
|
[0, 0, 0], |
|
[0, 0, 0], |
|
[0, 0, 0] |
|
], |
|
offset: { |
|
left: 0, |
|
top: 0 |
|
} |
|
}; |
|
|
|
class Map { |
|
constructor() { |
|
this.boxes = []; |
|
} |
|
static new(...args) { |
|
return new Map(...args); |
|
} |
|
|
|
add(x1, y1, x2, y2) { |
|
|
|
x1 = Math.round(Cast.toNumber(x1)); |
|
y1 = Math.round(Cast.toNumber(y1)); |
|
x2 = Math.round(Cast.toNumber(x2)); |
|
y2 = Math.round(Cast.toNumber(y2)); |
|
|
|
const position = { |
|
x1: x1, |
|
y1: y1, |
|
x2: x2, |
|
y2: y2, |
|
}; |
|
if (x2 < x1) { |
|
|
|
position.x1 = x2; |
|
position.x2 = x1; |
|
} |
|
if (y2 > y1) { |
|
|
|
position.y1 = y2; |
|
position.y2 = y1; |
|
} |
|
const box = { |
|
x: position.x1, |
|
y: position.x2, |
|
width: position.x2 - position.x1, |
|
height: position.y1 - position.y2 |
|
}; |
|
this.boxes.push(box); |
|
return box; |
|
} |
|
clear() { |
|
this.boxes = []; |
|
} |
|
|
|
toGrid() { |
|
|
|
if (!this.boxes) return blankGridReturn; |
|
if (this.boxes.length <= 0) return blankGridReturn; |
|
|
|
const grid = []; |
|
|
|
let highestY = -Infinity; |
|
for (const box of this.boxes) { |
|
if (box.y > highestY) highestY = box.y; |
|
} |
|
|
|
let lowestY = Infinity; |
|
let lowestHeight = 0; |
|
for (const box of this.boxes) { |
|
if (box.y < lowestY) { |
|
lowestY = box.y; |
|
lowestHeight = box.height; |
|
} |
|
} |
|
|
|
const baseRow = []; |
|
|
|
|
|
let lowestX = Infinity; |
|
for (const box of this.boxes) { |
|
if (box.x < lowestX) lowestX = box.x; |
|
} |
|
|
|
let highestX = -Infinity; |
|
let highestWidth = 0; |
|
for (const box of this.boxes) { |
|
if (box.x > highestX) { |
|
highestX = box.x; |
|
highestWidth = box.width; |
|
} |
|
} |
|
|
|
const xtoxwidth = (highestX - lowestX) + highestWidth; |
|
for (let i = 0; i < xtoxwidth; i++) { |
|
baseRow.push(0); |
|
} |
|
|
|
const ytoyheight = (highestY - lowestY) + lowestHeight; |
|
for (let i = 0; i < ytoyheight; i++) { |
|
|
|
const clone = Clone.simple(baseRow); |
|
grid.push(clone); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
const offset = Clone.simple({ |
|
top: highestY, |
|
left: lowestX |
|
}); |
|
for (const box of this.boxes) { |
|
|
|
|
|
|
|
const offsetX = box.x - offset.left; |
|
const offsetY = Math.abs(box.y - offset.top); |
|
let tileIdx = offsetX; |
|
let rowIdx = offsetY; |
|
|
|
|
|
for (let i = 0; i < box.height; i++) { |
|
for (let j = 0; j < box.width; j++) { |
|
|
|
const row = grid[rowIdx]; |
|
row[tileIdx] = 1; |
|
tileIdx++; |
|
} |
|
rowIdx++; |
|
tileIdx = offsetX; |
|
} |
|
} |
|
|
|
return { |
|
grid: grid, |
|
offset: offset |
|
} |
|
} |
|
} |
|
|
|
module.exports = Map; |