diff --git a/js/save_load.mjs b/js/save_load.mjs index 753b40f..fb7eab0 100644 --- a/js/save_load.mjs +++ b/js/save_load.mjs @@ -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); } diff --git a/js/world.mjs b/js/world.mjs index fdec33d..3532557 100644 --- a/js/world.mjs +++ b/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; +}