Compare commits

..

4 Commits

Author SHA1 Message Date
j 00f0765ef8 added documentation to oxen quality 2024-04-02 22:58:17 -04:00
j 72b3c4537d added reset game state, updated documentation around active column 2024-04-02 22:57:31 -04:00
j 22f1b560f6 added addtl column active flag 2024-04-02 22:56:34 -04:00
j 46abc5ba68 cleanup 2024-04-02 22:56:16 -04:00
4 changed files with 52 additions and 102 deletions

View File

@ -1,4 +1,5 @@
CREATE TABLE IF NOT EXISTS gameState (
authorId INTEGER PRIMARY KEY,
data TEXT NOT NULL
data TEXT NOT NULL,
active BOOLEAN NOT NULL DEFAULT TRUE
);

View File

@ -27,56 +27,66 @@ export class DatabaseService {
}
/**
* Loads an existing game state for a given author from the database.
* If an existing game state is found, it returns a new GameState instance initialized with the stored values.
* If no game state exists for the given author, it returns null, indicating that a new game state needs to be initialized.
* Loads the active game state for a given author from the database.
* If no active game state exists, it returns null.
*
* @param {number} authorId - The unique identifier for the author whose game state is to be loaded.
* @returns {Promise<GameState | null>} The loaded game state if it exists and is active, otherwise null.
* @throws {Error} Throws an error if the database operation fails.
* @example
* const gameState = await DatabaseService.loadGameState(authorId);
* const gameState = await DatabaseService.loadGameState(1);
* if (gameState) {
* console.log('Game state loaded successfully.');
* // Game state exists and is active
* } else {
* console.log('No existing game state found. Initializing a new game.');
* // No active game state found
* }
*
* @param {number} authorId - The unique identifier for the author of the game.
* @returns {Promise<GameState | null>} A promise that resolves to a GameState instance if found, or null if no existing game state is present.
* @throws {Error} Will throw an error if the database operation fails.
*/
public static async loadGameState(authorId: number): Promise<GameState | null> {
const db = await DatabaseService.getDatabase();
const sql = `SELECT data FROM game_state WHERE authorId = ?`;
const sql = `SELECT data FROM game_state WHERE authorId = ? AND active = TRUE`;
const row = await db.get(sql, [authorId]);
if (row) {
return JSON.parse(row.data) as GameState; // Assuming GameState constructor can take authorId and a partial state object
return JSON.parse(row.data) as GameState;
} else {
return null; // Or return a new GameState with defaults
return null;
}
}
/**
* Saves the current game state for a given author to the database.
* If an existing game state for the author exists, it updates the stored values. If no game state exists, it inserts a new record.
* This method ensures the game state is persisted between sessions, allowing players to resume their game at any time.
*
* @example
* await DatabaseService.saveGameState(authorId, gameState);
* console.log('Game state saved successfully.');
*
* @param {number} authorId - The unique identifier for the author of the game.
* @param {GameState} gameState - The current game state to be saved.
* @returns {Promise<void>} A promise that resolves when the game state is successfully saved.
* @throws {Error} Will throw an error if the save operation fails.
*/
* Saves the current game state to the database. If an active game state already exists for the author,
* it updates that state. Otherwise, it creates a new active game state.
*
* @param {number} authorId - The unique identifier for the author of the game state.
* @param {GameState} gameState - The current state of the game to be saved.
* @throws {Error} Throws an error if the database operation fails.
* @example
* await DatabaseService.saveGameState(1, currentGameState);
*/
public static async saveGameState(authorId: number, gameState: GameState): Promise<void> {
const db = await DatabaseService.getDatabase();
const data = JSON.stringify(gameState);
const sql = `
INSERT INTO game_state (authorId, data) VALUES (?, ?)
INSERT INTO game_state (authorId, data, active) VALUES (?, ?, TRUE)
ON CONFLICT(authorId) DO UPDATE SET
data = excluded.data;
data = excluded.data
WHERE active = TRUE;
`;
await db.run(sql, [authorId, data]);
}
/**
* Resets the game state for a given author by setting the active state to false.
* This method should be called after a death event or when the player decides to start over.
*
* @param {number} authorId - The unique identifier for the author of the game state to be reset.
* @throws {Error} Throws an error if the database operation fails.
* @example
* await DatabaseService.resetGameState(1);
*/
public static async resetGameState(authorId: number): Promise<void> {
const db = await DatabaseService.getDatabase();
const sql = `UPDATE game_state SET active = FALSE WHERE authorId = ? AND active = TRUE`;
await db.run(sql, [authorId]);
}
}

View File

@ -82,6 +82,17 @@ class GameFlow {
}
/**
* Describes the quality of oxen based on the amount spent on animals within the game state.
* This method assesses the oxen quality by comparing the total amount spent on animals against predefined quality levels.
*
* @returns {string} A string describing the quality of the oxen, ranging from 'Basic Quality' to 'Exceptional Quality'. Returns 'Unknown Quality' if the amount spent does not fit the expected range.
* @example
* // If the gameState.amountSpentOnAnimals is 250
* describeOxenQuality(); // returns 'Good Quality'
*/
describeOxenQuality(): string {
const spent = this.gameState.amountSpentOnAnimals;
const qualityLevels = [

View File

@ -1,72 +0,0 @@
import GameState from './gameState';
import GameFlow from './gameFlow';
import { Comment } from '../rdrama/models/Comment';
import { CommentParser } from '../rdrama/services/CommentParser';
class GameSession {
private gameState: GameState;
private gameFlow: GameFlow;
private authorId: number;
private constructor(authorId: number, gameState: GameState) {
this.authorId = authorId;
this.gameState = gameState;
this.gameFlow = new GameFlow(gameState);
}
/**
* Loads an existing game session for the given author or creates a new one if none exists.
* @param authorId The ID of the author for whom to load or create the game session.
* @returns A GameSession instance for the given author.
*/
public static async loadSession(authorId: number): Promise<GameSession> {
const gameState = await GameState.load(authorId);
return new GameSession(authorId, gameState);
}
/**
* Handles user input by parsing the command and executing the corresponding action.
* @param comment The comment containing the user input.
*/
public async handleUserInput(comment: Comment): Promise<void> {
const { command, args } = CommentParser.parseCommand(comment);
// Process the command
switch (command) {
case 'startover':
// Example of resetting the game
this.gameState.reset();
break;
case 'buysupplies':
// Example of handling a purchase command
// Logic to handle buying supplies
break;
// Add additional cases for other commands
default:
console.error('Unrecognized command:', command);
break;
}
// After processing the command, save any changes to the game state
await this.gameState.save();
}
/**
* Generates a status update message based on the current state of the game.
* @returns A string representing the current game status, formatted for display.
*/
public getStatusUpdate(): string {
// Use the GameFlow instance to generate a status message
return this.gameFlow.generateStatusMessage();
}
/**
* Resets the game to its initial state and saves the updated state.
*/
private async reset(): Promise<void> {
this.gameState.reset();
await this.gameState.save();
}
}
export { GameSession };