From 9107c557afa3fbf98d2be164b801b3653456a2b3 Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Thu, 15 Dec 2022 01:02:20 +0100 Subject: [PATCH] Store game in localStorage --- src/js/main.js | 103 ++++--------------------------------------------- 1 file changed, 7 insertions(+), 96 deletions(-) diff --git a/src/js/main.js b/src/js/main.js index fd9ef4e..3168a6f 100644 --- a/src/js/main.js +++ b/src/js/main.js @@ -7,15 +7,7 @@ import { Game } from "./Game.js"; */ let game; -/** - * A value indicating whether a transfer is pending. - */ -let transferPending = false; - -/** - * The id of the save game. - */ -let id = ""; +const saveGameKey = "connect-force-save"; /** * Gets the save button. @@ -39,24 +31,6 @@ function getLoadButton() 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. */ @@ -71,79 +45,16 @@ function initialize() game.reset(); }; - getSaveButton().onclick = async () => + getSaveButton().onclick = async (event) => { - if (!transferPending) - { - 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"); - } + event.preventDefault(); + localStorage.setItem(saveGameKey, JSON.stringify(game.dump())); }; - getLoadButton().onclick = async () => + getLoadButton().onclick = async (event) => { - if (!transferPending) - { - 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"); - } + event.preventDefault(); + game.load(JSON.parse(localStorage.getItem(saveGameKey))); }; }