implement saving and loading world data to file.
This commit is contained in:
parent
bfb207386c
commit
7299916fa7
|
@ -11,4 +11,7 @@
|
|||
|
||||
<body>
|
||||
<canvas id="canvas" width="729" height="729"></canvas>
|
||||
<br>
|
||||
<button id="save">save game to file</button>
|
||||
<button id="load">load game from file</button>
|
||||
</body>
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
import * as graphics from "./graphics.mjs";
|
||||
import { BOX_SIZE, get_tile } from "./world.mjs";
|
||||
import { get_player_box } from "./player.mjs";
|
||||
import "./save_load.mjs";
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
import { get_root, replace_root } from "./world.mjs";
|
||||
|
||||
|
||||
|
||||
const get_elem = id => document.getElementById(id);
|
||||
const create_elem = type => document.createElement(type);
|
||||
const save_button = get_elem("save");
|
||||
const load_button = get_elem("load");
|
||||
|
||||
save_button.onclick = _ => {
|
||||
const timestamp = new Date().getTime();
|
||||
const filename = `boxes_${timestamp}.boxes`;
|
||||
|
||||
const world = get_root();
|
||||
const data = btoa(JSON.stringify(world));
|
||||
|
||||
save_text(filename, data);
|
||||
};
|
||||
|
||||
function save_text (filename, text) {
|
||||
const link = create_elem("a");
|
||||
const file = new Blob([text], { type: "text/plain" });
|
||||
link.href = URL.createObjectURL(file);
|
||||
link.download = filename;
|
||||
link.click();
|
||||
}
|
||||
|
||||
load_button.onclick = _ => {
|
||||
const input = create_elem("input");
|
||||
input.type = "file";
|
||||
input.addEventListener("change", e => {
|
||||
const file = e.target.files[0];
|
||||
const reader = new FileReader();
|
||||
reader.onload = e => load_text(e.target.result);
|
||||
reader.onerror = error => alert("couldn't load the file.");
|
||||
reader.readAsText(file);
|
||||
});
|
||||
input.click();
|
||||
}
|
||||
|
||||
function load_text (text) {
|
||||
const data = JSON.parse(atob(text));
|
||||
replace_root(data);
|
||||
}
|
|
@ -1,3 +1,5 @@
|
|||
import { iter_2d, range } from "./utils/range.mjs";
|
||||
|
||||
export const BOX_SIZE = 9;
|
||||
export const CENTER = Math.floor(BOX_SIZE / 2);
|
||||
|
||||
|
@ -35,3 +37,10 @@ export function out_of_bounds (x, y) {
|
|||
return x < 0 || x >= BOX_SIZE ||
|
||||
y < 0 || y >= BOX_SIZE
|
||||
}
|
||||
|
||||
export function replace_root (new_world) {
|
||||
// maybe unnecessary to go over each tile instead of just each column.
|
||||
iter_2d(range(0, BOX_SIZE - 1), (x, y) => {
|
||||
set_tile(world, x, y, get_tile(new_world, x, y));
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue