aboutsummaryrefslogtreecommitdiff
path: root/src/lib/stores/games.svelte.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/stores/games.svelte.js')
-rw-r--r--src/lib/stores/games.svelte.js91
1 files changed, 91 insertions, 0 deletions
diff --git a/src/lib/stores/games.svelte.js b/src/lib/stores/games.svelte.js
new file mode 100644
index 0000000..ae76ce3
--- /dev/null
+++ b/src/lib/stores/games.svelte.js
@@ -0,0 +1,91 @@
+import { createGame, createTeam } from "../logic/players.js";
+import {
+ proposeGames,
+ createDefaultGames,
+ collectConfirmedPlayerNames,
+} from "../logic/matchmaking.js";
+import {
+ getCourts,
+} from "./courts.svelte.js";
+import {
+ getRegulars,
+ incrementRegularGames,
+ resetRegulars,
+} from "./regulars.svelte.js";
+import { getGuests, incrementGuestGames } from "./guests.svelte.js";
+import { getSkillFactor } from "./skillFactor.svelte.js";
+import { start as startTimer, stopTimer } from "./timer.svelte.js";
+
+const GAMES_STORAGE_KEY = "Game";
+const ROUND_STORAGE_KEY = "round";
+const GAME_COUNT = 12;
+
+function loadInitialGames() {
+ const stored = JSON.parse(localStorage.getItem(GAMES_STORAGE_KEY));
+ if (stored && stored.length > 0) {
+ return stored.map((g) =>
+ createGame(
+ Number(g.id),
+ Boolean(g.status),
+ createTeam(g.teamOne.playerOne, g.teamOne.playerTwo),
+ createTeam(g.teamTwo.playerOne, g.teamTwo.playerTwo)
+ )
+ );
+ }
+ return createDefaultGames(GAME_COUNT);
+}
+
+let games = $state(loadInitialGames());
+let round = $state(Number(localStorage.getItem(ROUND_STORAGE_KEY)) || 0);
+
+function persistGames() {
+ localStorage.setItem(GAMES_STORAGE_KEY, JSON.stringify(games));
+}
+
+export function getGames() {
+ return games;
+}
+
+export function getRound() {
+ return round;
+}
+
+export function getGameDescription() {
+ const confirmed = games[0]?.status;
+ return confirmed ? `Round ${round}` : "Proposal";
+}
+
+export function propose() {
+ games = proposeGames({
+ courts: getCourts(),
+ regulars: getRegulars(),
+ guests: getGuests(),
+ skillFactor: getSkillFactor(),
+ });
+}
+
+export function confirm() {
+ const alreadyConfirmed = games[0]?.status;
+ if (alreadyConfirmed) return;
+
+ round += 1;
+ localStorage.setItem(ROUND_STORAGE_KEY, round);
+ for (const game of games) game.status = true;
+
+ const selectedNames = collectConfirmedPlayerNames(games);
+ incrementRegularGames(selectedNames);
+ incrementGuestGames(selectedNames);
+
+ persistGames();
+ startTimer(true);
+}
+
+export function resetSession() {
+ localStorage.removeItem(ROUND_STORAGE_KEY);
+ localStorage.removeItem(GAMES_STORAGE_KEY);
+ localStorage.removeItem("Court");
+ localStorage.removeItem("Guest");
+ resetRegulars();
+ stopTimer();
+ window.location.reload();
+}