avocado-old/packages/topdown/tiles.js

65 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-03-25 19:03:34 -05:00
import {compose} from '@avocado/core';
import {Rectangle, Vector} from '@avocado/math';
const decorate = compose(
Vector.Mixin('size', 'width', 'height', {
default: [0, 0],
}),
);
class TilesBase {
fromJSON(json) {
if (json.size) {
this.size = json.size;
}
if (json.data) {
this.data = json.data;
}
return this;
}
get rectangle() {
return Rectangle.compose([0, 0], this.size);
}
2019-03-25 20:49:16 -05:00
setTileAt(x, y, tile) {
const index = y * this.width + x;
if (index < 0 || index >= this.data.length) {
return;
}
this.data[index] = tile;
}
2019-03-25 19:03:34 -05:00
slice(rectangle) {
const tilesRectangle = this.rectangle;
if (!Rectangle.intersects(rectangle, tilesRectangle)) {
return [];
}
let [x, y, width, height] = Rectangle.intersection(rectangle, tilesRectangle);
const rowWidth = tilesRectangle[2];
const slice = new Array(width * height);
for (let j = 0; j < height; ++j) {
for (let i = 0; i < width; ++i) {
slice[y * width + x] = this.data[y * rowWidth + x];
x++;
}
y++;
x -= width;
}
return slice;
}
tileAt(x, y) {
const [width, height] = this.size;
return this.data[y * width + x];
}
toJSON() {
}
}
export class Tiles extends decorate(TilesBase) {}