Add code for saving and loading game
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed

This commit is contained in:
Manuel Thalmann 2022-12-14 20:13:01 +01:00
parent 63a56e5b11
commit fd172a48ed
No known key found for this signature in database
GPG key ID: 5FD9AD3CCDDBD27B
3 changed files with 139 additions and 3 deletions

View file

@ -9,8 +9,16 @@
<body>
<div id="game">
</div>
<form class="menu-bar">
<button class="button new-game">
New Game
</button>
<button class="button save">
Save Game
</button>
<button class="button load">
Load Game
</button>
</form>
</body>
</html>

View file

@ -98,7 +98,10 @@ export class Game
load(data)
{
this.state.turnCount = data.turnCount;
this.state.board.splice(0);
this.#state = new State(Game.#width, Game.#height);
Object.assign(this.state.board, data.board);
this.draw();
}
/**

View file

@ -7,6 +7,56 @@ 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 = "";
/**
* Gets the save button.
*
* @returns {HTMLButtonElement}
* The save button.
*/
function getSaveButton()
{
return document.querySelector(".save");
}
/**
* Gets the load button.
*
* @returns {HTMLButtonElement}
* The load button.
*/
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.
*/
@ -19,6 +69,81 @@ function initialize()
{
game.reset();
};
getSaveButton().onclick = async () =>
{
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");
}
};
getLoadButton().onclick = async () =>
{
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");
}
};
}
initialize();