From 08851d70fc4d190be1a4e0416aa5b65501c3156b Mon Sep 17 00:00:00 2001 From: j Date: Tue, 26 Mar 2024 22:55:04 -0400 Subject: [PATCH] implemented save and load of game state --- src/game/gameState.ts | 52 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/src/game/gameState.ts b/src/game/gameState.ts index 1d0fd5d..8909946 100644 --- a/src/game/gameState.ts +++ b/src/game/gameState.ts @@ -1,4 +1,12 @@ +import { DatabaseService } from "../db/services/Database"; + +/** + * Represents the state of a game session for an Oregon Trail-style game. + * This class stores all relevant game state information and provides methods + * to load from and save to a database. + */ class GameState { + authorId: number = 0; amountSpentOnAnimals: number = 0; amountSpentOnAmmunition: number = 0; actualResponseTimeForBang: number = 0; @@ -32,12 +40,48 @@ class GameState { actionChoiceForEachTurn: number = 0; fortOptionFlag: boolean = false; death: boolean = false; + phase: PHASE_ENUM = PHASE_ENUM.SETUP; + subPhase: number = 0; - constructor(authorId: string) { - // Load existing session for authorId or create default values + private constructor(authorId: number, state?: Partial) { + this.authorId = authorId; + Object.assign(this, state); // Initialize with loaded state or undefined } - // Methods to update game state variables and check game conditions + /** + * Saves the current game state to the database. + */ + public async save() { + await DatabaseService.saveGameState(this.authorId, this); + } + + /** + * Loads an existing game state from the database or creates a new one if it doesn't exist. + * @param {number} authorId - The ID of the author/player. + * @returns {Promise} - The loaded or newly created game state. + */ + public static async load(authorId: number): Promise { + const loadedState = await DatabaseService.loadGameState(authorId); + if (loadedState) { + return new GameState(authorId, loadedState); + } else { + // Create a new GameState with default values + const newState = new GameState(authorId); + await newState.save(); // Optionally save the new state to the database + return newState; + } + } } -export default GameState \ No newline at end of file +export default GameState + +// Enumeration for different phases of the game. +enum PHASE_ENUM { + SETUP = 'SETUP', + TRAVEL = 'TRAVEL', + FORT_HUNT = 'FORT_HUNT', + ENCOUNTER = 'ENCOUNTER', + EVENT = 'EVENT', + MOUNTAIN = 'MOUNTAIN', + DEATH_CHECK = 'DEATH_CHECK', +} \ No newline at end of file