fix worlds with boxes not saving & loading due to cyclic references.
This commit is contained in:
parent
17ad391731
commit
41b9ab7a2e
|
@ -20,7 +20,7 @@ save_button.onclick = _ => {
|
|||
|
||||
function generate_save_data () {
|
||||
const root = world.get_root();
|
||||
return btoa(JSON.stringify(root));
|
||||
return btoa(world.to_json(root));
|
||||
}
|
||||
|
||||
function save_text (filename, text) {
|
||||
|
@ -45,7 +45,7 @@ load_button.onclick = _ => {
|
|||
}
|
||||
|
||||
function load_from_text (text) {
|
||||
const data = JSON.parse(atob(text));
|
||||
const data = world.from_json(atob(text));
|
||||
world.replace_root(data);
|
||||
}
|
||||
|
||||
|
|
36
js/world.mjs
36
js/world.mjs
|
@ -42,9 +42,39 @@ export function out_of_bounds (x, y) {
|
|||
y < 0 || y >= BOX_SIZE
|
||||
}
|
||||
|
||||
export function replace_root (new_world) {
|
||||
// maybe unnecessary to go over each tile instead of just each column.
|
||||
export function for_each_tile (world, callback) {
|
||||
iter_2d(range(0, BOX_SIZE - 1), (x, y) => {
|
||||
set_tile(world, x, y, get_tile(new_world, 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) {
|
||||
for_each_tile(world, (x, y, tile) => {
|
||||
if (tile.type !== "box") return;
|
||||
tile.parent = parent;
|
||||
reconstruct_parent(tile.box, world);
|
||||
});
|
||||
}
|
||||
|
||||
export function from_json (json) {
|
||||
const result = JSON.parse(json);
|
||||
for_each_tile(result, (x, y, tile) => {
|
||||
if (tile.type !== "box") return;
|
||||
reconstruct_parent(tile.box, result);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue