100 lines
2.1 KiB
JavaScript
100 lines
2.1 KiB
JavaScript
import { iter_2d, range } from "./utils/range.mjs";
|
|
|
|
const BOX_EXTENT_FROM_CENTER = 4;
|
|
export const BOX_SIZE = BOX_EXTENT_FROM_CENTER * 2 + 1;
|
|
export const CENTER = BOX_EXTENT_FROM_CENTER;
|
|
|
|
|
|
|
|
function create_world (size) {
|
|
return {
|
|
tiles: Array(size).fill(0).map(_ =>
|
|
Array(size).fill(0).map(_ => empty_tile())
|
|
),
|
|
depth: 0,
|
|
};
|
|
}
|
|
const world = create_world(BOX_SIZE);
|
|
|
|
export function empty_tile () {
|
|
return { type: "empty" };
|
|
}
|
|
|
|
export function create_new () {
|
|
return create_world(BOX_SIZE);
|
|
}
|
|
|
|
export function set_tile (world, x, y, tile) {
|
|
if (out_of_bounds(x, y)) return;
|
|
world.tiles[x][y] = tile;
|
|
}
|
|
|
|
export function get_tile (world, x, y) {
|
|
if (out_of_bounds(x, y)) return { type: "out_of_bounds" };
|
|
return world.tiles[x][y];
|
|
}
|
|
|
|
export function clear_tile (box, x, y) {
|
|
set_tile(box, x, y, empty_tile());
|
|
}
|
|
|
|
export function create_box (parent) {
|
|
return {
|
|
...create_world(BOX_SIZE),
|
|
depth: parent.depth + 1,
|
|
parent,
|
|
};
|
|
}
|
|
|
|
export function get_root () {
|
|
return world;
|
|
}
|
|
|
|
export function out_of_bounds (x, y) {
|
|
return x < 0 || x >= BOX_SIZE ||
|
|
y < 0 || y >= BOX_SIZE
|
|
}
|
|
|
|
export function for_each_tile (world, callback) {
|
|
iter_2d(range(0, BOX_SIZE - 1), (x, y) => {
|
|
callback(x, y, get_tile(world, x, y), world);
|
|
});
|
|
}
|
|
|
|
export function replace_root (new_world) {
|
|
// maybe unnecessary to go over each tile instead of just each column.
|
|
for_each_tile(new_world, (x, y, tile) => {
|
|
set_tile(world, x, y, tile);
|
|
});
|
|
}
|
|
|
|
export function to_json () {
|
|
return JSON.stringify(world, (key, value) => {
|
|
if (key === "parent") return undefined;
|
|
return value;
|
|
});
|
|
}
|
|
|
|
function reconstruct_parent (world, parent) {
|
|
world.parent = parent;
|
|
for_each_tile(world, (x, y, tile) => {
|
|
if (tile.type !== "box") return;
|
|
reconstruct_parent(tile.box, world);
|
|
});
|
|
}
|
|
|
|
export function from_json (json) {
|
|
const result = JSON.parse(json, (key, value) => {
|
|
if (value === undefined || value === 0 || value === null) return empty_tile();
|
|
return value;
|
|
});
|
|
|
|
for_each_tile(result, (x, y, tile) => {
|
|
if (tile.type === "box") {
|
|
reconstruct_parent(tile.box, result);
|
|
}
|
|
});
|
|
|
|
return result;
|
|
}
|