forked from kholland4/platformeng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
saveload.js
94 lines (83 loc) · 2.13 KB
/
saveload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
function loadf(url, callback, timeout = null, timeoutCallback = null) {
var xhttp = new XMLHttpRequest();
xhttp._callback = callback;
xhttp.onreadystatechange = function() {
if(this.readyState == 4) {
this._callback();
}
};
if(timeout != null) {
xhttp.timeout = timeout;
}
if(timeoutCallback != null) {
xhttp.ontimeout = timeoutCallback;
}
xhttp.open("GET", url);
xhttp.send();
}
function serializeGame() {
return {
"map": map.serialize(),
"player": player.serialize()
};
}
function deserializeGame(d) {
map = Map.deserialize(d.map);
player = Player.deserialize(d.player);
player.map = map;
if(typeof hud != "undefined") {
hud.map = map;
hud.player = player;
}
}
function exportGame() {
var data = JSON.stringify(serializeGame());
var a = document.createElement("a");
a.href = "data:application/x-octet-stream;base64," + btoa(data);
a.download = "game.json";
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
var _importGame_callback;
function importGame(callback=undefined) {
_importGame_callback = callback;
var fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.onchange = importGameFile;
fileInput.style.display = "none";
document.body.appendChild(fileInput);
fileInput.click();
document.body.removeChild(fileInput);
}
function importGameFile(e) {
var files = e.target.files;
if(files.length) {
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(e) {
if(e.target.readyState == FileReader.DONE) {
try {
var data = JSON.parse(e.target.result);
deserializeGame(data);
if(_importGame_callback != undefined) { _importGame_callback(); }
} catch(e) {
//TODO error message
}
}
};
reader.readAsText(file);
}
}
function importGameURL(url) {
loadf(url, function() {
deserializeGame(JSON.parse(this.responseText));
});
}
function resetTime() {
if(typeof timeline != "undefined") {
timeline = [];
timelineOffset = performance.now();
}
}