Store game in localStorage
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
Manuel Thalmann 2022-12-15 01:02:20 +01:00
parent e34ae6d1c3
commit 9107c557af
No known key found for this signature in database
GPG key ID: 5FD9AD3CCDDBD27B

View file

@ -7,15 +7,7 @@ import { Game } from "./Game.js";
*/ */
let game; let game;
/** const saveGameKey = "connect-force-save";
* A value indicating whether a transfer is pending.
*/
let transferPending = false;
/**
* The id of the save game.
*/
let id = "";
/** /**
* Gets the save button. * Gets the save button.
@ -39,24 +31,6 @@ function getLoadButton()
return document.querySelector(".load"); return document.querySelector(".load");
} }
/**
* Gets an url for storing and loading the save game.
*
* @returns {URL}
* The url for storing and loading the save game.
*/
function getUrl()
{
let result = new URL(
id,
new URL(
"/api/data/",
window.location.origin));
result.searchParams.append("token", "c4game");
return result;
}
/** /**
* Initializes the board. * Initializes the board.
*/ */
@ -71,79 +45,16 @@ function initialize()
game.reset(); game.reset();
}; };
getSaveButton().onclick = async () => getSaveButton().onclick = async (event) =>
{ {
if (!transferPending) event.preventDefault();
{ localStorage.setItem(saveGameKey, JSON.stringify(game.dump()));
transferPending = true;
getSaveButton().disabled = true;
getLoadButton().disabled = true;
try
{
if (id === "")
{
let result = await (await fetch(
getUrl(),
{
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(game.dump())
})).json();
({ id } = result);
}
else
{
await fetch(
getUrl(),
{
method: "PUT",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(game.dump())
});
}
}
catch { }
getSaveButton().disabled = false;
getLoadButton().disabled = false;
transferPending = false;
}
else
{
console.log("Already busy");
}
}; };
getLoadButton().onclick = async () => getLoadButton().onclick = async (event) =>
{ {
if (!transferPending) event.preventDefault();
{ game.load(JSON.parse(localStorage.getItem(saveGameKey)));
transferPending = true;
getSaveButton().disabled = true;
getLoadButton().disabled = true;
try
{
game.load(
await (
await fetch(getUrl())).json());
}
catch { }
getSaveButton().disabled = false;
getLoadButton().disabled = false;
transferPending = false;
}
else
{
console.log("Already busy");
}
}; };
} }