implemented save and load of game state

master
j 2024-03-26 22:55:04 -04:00
parent 5e898fe8ce
commit 08851d70fc
1 changed files with 48 additions and 4 deletions

View File

@ -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<GameState>) {
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<GameState>} - The loaded or newly created game state.
*/
public static async load(authorId: number): Promise<GameState> {
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
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',
}