Skip to content

Commit

Permalink
persist game state
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxMuehlbauer committed Apr 29, 2024
1 parent 6adbdfe commit 5a6d122
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
15 changes: 14 additions & 1 deletion src/scripts/buildGameState.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { playAudio } from "./audio";
import { getStateId } from "./stateIdGenerator";
import Alpine from "alpinejs";
import type { DynamicAnswerState, DynamicFailState, DynamicGameState, DynamicQuestionState, DynamicTeamState, StorableAnswerState, StorableFailState, StorableGameState, StorableQuestionState, StorableTeamState } from "./types";

function buildAnswer(answer: StorableAnswerState): DynamicAnswerState {
Expand Down Expand Up @@ -101,6 +102,10 @@ function loadGameStateFromStorage(id: string): StorableGameState | null {
}
}

function saveGameStateToStorage(id: string, state: string) {
localStorage.setItem(id, state);
}

function buildGameStateFromJSON(inputState: StorableGameState): DynamicGameState {
return {
...inputState,
Expand Down Expand Up @@ -173,7 +178,7 @@ function buildDefaultGameState(): DynamicGameState {
});
}

export function getGameState(id: string = "currentGameState"): DynamicGameState {
function getGameState(id: string): DynamicGameState {
const savedState = loadGameStateFromStorage(id);
let dynamicState = buildDefaultGameState();

Expand All @@ -186,4 +191,12 @@ export function getGameState(id: string = "currentGameState"): DynamicGameState
}

return dynamicState;
}

export function initGameState(id: string = "gameState") {
const state = getGameState(id);
Alpine.store(id, state);
Alpine.effect(() => {
saveGameStateToStorage(id, JSON.stringify(Alpine.store(id)));
})
}
6 changes: 3 additions & 3 deletions src/scripts/main.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import Alpine from "alpinejs";
import { revealDirective } from "./reveal-directive";
import { getGameState } from "./buildGameState";
import { initGameState } from "./buildGameState";

// @ts-ignore
window["Alpine"] = Alpine;

Alpine.store("game", getGameState());

Alpine.directive("reveal", revealDirective);

initGameState("gameState");

Alpine.start();

0 comments on commit 5a6d122

Please sign in to comment.