Move all click handlers to the App

This commit is contained in:
Manuel Thalmann 2022-12-15 14:17:11 +01:00
parent 80b55732e7
commit 30cbc40d38
No known key found for this signature in database
GPG key ID: 5FD9AD3CCDDBD27B

View file

@ -1,6 +1,9 @@
import { Constants } from "./Constants.js";
const saveGameKey = "connect-force-save";
const newGameClass = "new-game";
const saveGameClass = "save-game";
const loadGameClass = "load-game";
/**
* Gets a component which represents the specified {@link game `game`}.
@ -20,20 +23,35 @@ export function App(game)
{
let target = /** @type {HTMLElement} */ (event.target);
for (let y = 0; y < game.board.length; y++)
if (target.classList.contains(newGameClass))
{
let rowLength = game.board[y].length;
for (let x = 0; x < rowLength; x++)
game.reset();
}
else if (target.classList.contains(saveGameClass))
{
localStorage.setItem(saveGameKey, JSON.stringify(game.dump()));
}
else if (target.classList.contains(loadGameClass))
{
game.load(JSON.parse(localStorage.getItem(saveGameKey)));
}
else
{
for (let y = 0; y < game.board.length; y++)
{
let node = document.querySelector(".board").children.item(y * rowLength + x);
let rowLength = game.board[y].length;
if (node === target || node.contains(target))
for (let x = 0; x < rowLength; x++)
{
if (game.addChip(x, y))
let node = document.querySelector(".board").children.item(y * rowLength + x);
if (node === target || node.contains(target))
{
game.state.turnCount++;
game.draw();
if (game.addChip(x, y))
{
game.state.turnCount++;
game.draw();
}
}
}
}
@ -123,41 +141,30 @@ export function MenuBar(game)
{ className: "menu-bar" },
[
Button,
{
text: "New Game",
attributes: {
onclick: () =>
{
game.reset();
}
[
"New Game",
{
className: newGameClass
}
}
]
],
[
Button,
{
text: "Save Game",
attributes: {
onclick: () =>
{
localStorage.setItem(
saveGameKey,
JSON.stringify(game.dump()));
}
[
"Save Game",
{
className: saveGameClass
}
}
]
],
[
Button,
{
text: "Load Game",
attributes: {
onclick: () =>
{
game.load(JSON.parse(localStorage.getItem(saveGameKey)));
}
[
"Load Game",
{
className: loadGameClass
}
}
]
]
];
}
@ -165,17 +172,16 @@ export function MenuBar(game)
/**
* Renders a button.
*
* @param {{text: string, attributes: (Partial<HTMLElement> & Record<string, any>)}} data
* @param {...ElementDescriptor[1][]} content
* The settings of the button.
*
* @returns {NodeDescriptor}
* The rendered element.
*/
export function Button(data)
export function Button(content)
{
return [
"button",
data.attributes,
data.text
...content
];
}