Designing a System Command Handler for a Game
The system command handler module processes player input for in-game meta-actions. It must interpret commands, execute corresponding logic, and return text-based responses for the main game loop to display.
Module Structure and Dependencies
- File Path:
src/game_logic/commands.py - Key Dependencies:
morality: Requires theget_morality_ratiosfunction.llm_hint: Requires theget_llm_hintfunction.- Standard libraries:
logging,os,json.
- Input Parameters: The primary function receives the current
game_statedictionary and an optionalboss_fightobject for context-sensitive commands.
Game State Schema
The game_state dictionary is expected to have the following structure:
game_state = {
'current_layer': int, # Current layer number
'layer_round': int, # Round within the current layer
'virtue': int, # Virtue points
'balance': int, # Neutral points
'corruption': int, # Corruption points
'layer_cards': list, # Cards obtained in the current layer (resets per layer)
'wild_cards': list, # Accumulated wild cards (persists across layers)
'in_boss_fight': bool, # Flag for boss fight status (optional)
}
Each card in layer_cards and wild_cards is a dictionary with keys: 'type', 'name', 'description'.
Supported Commands
| Command | Available Context | Purpose |
|---|---|---|
HELP |
Anywhere | Displays game instructions. |
PACK |
Anywhere | Shows the player's current hand of cards. |
STATUS |
Any where | Displays current morality ratios and dominant alignment. |
HINT |
Boss Fight Only | Requests a hint from an AI companion. |
QUIT |
Anywhere | Exits the game. |
Core Handler Function
def process_command(
command_input: str,
game_state: dict,
boss_encounter = None
) -> dict:
"""
Executes a system command.
Args:
command_input: The player's command string.
game_state: The current game state dictionary.
boss_encounter: An instance of the boss fight class, if applicable.
Returns:
A dictionary with keys:
- 'message': The text output for the player.
- 'terminate_game': Boolean indicating if the game should exit.
"""
cmd = command_input.strip().upper()
if cmd == 'HELP':
return show_help()
elif cmd == 'PACK':
return show_cards(game_state)
elif cmd == 'STATUS':
return show_alignment(game_state)
elif cmd == 'HINT':
return get_assistance(game_state, boss_encounter)
elif cmd == 'QUIT':
return exit_game()
else:
return {
'message': f"Unrecognized command: {cmd}. Type HELP for a list of commands.",
'terminate_game': False
}
Command Implementation Details
HELP Command
- Function:
show_help() - Action: Reads content from a predefined help text file.
- File Path Resolution:
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) HELP_PATH = os.path.join(BASE_DIR, "resources", "game_help.txt") - Error Handling: If the file is missing, log a error and return a user-friendly message.
- Returns:
{'message': help_text, 'terminate_game': False}
PACK Command
- Function:
show_cards(state) - Action: Formats and displays the player's
layer_cardsandwild_cards. - Output Example:
【Current Hand】 Layer Cards (X total): - Virtue (N): • Heart Seal - A token earned from aiding others. - Corruption (M): • Domination Sigil - A mark gained from oppressive acts. - Neutral (K): • Cloud Gaze - Earned from passive observation. Wild Cards (Y total): • Phantom Echo - A residual shadow from the realm, usable as any card type. - Edge Case: If no cards are present, output "Your hand is empty."
STATUS Command
- Function:
show_alignment(state) - Action: Calculates and displays the ratios of virtue, neutral, and corruption points.
- Logic:
from morality import get_morality_ratios ratios = get_morality_ratios(state['virtue'], state['balance'], state['corruption']) primary = ratios.get('primary_alignment', 'None') - Output Format:
Alignment Status: Virtue: 45.5% (Points: 45) Neutral: 33.3% (Points: 33) Corruption: 21.2% (Points: 21) Primary Alignment: Virtue
HINT Command
- Function:
get_assistance(state, boss_obj) - Precondition Check: Returns an error message if
boss_objisNoneorstate.get('in_boss_fight')is notTrue. - Process:
- Call
boss_obj.get_context_for_hint()to retrieve relevant battle data. - Pass this context to
llm_hint.get_llm_hint().
- Call
- Error Handling: If the hint function returns
None, provide a fallback message.
QUIT Command
- Functon:
exit_game() - Action: Signals the main loop to terminate.
- Returns:
{'message': 'Game session ended.', 'terminate_game': True}
Help File Content
The help file, e.g., resources/game_help.txt, should contain instructional text for players, explaining core mechanics and command usage.
Error Logging
Implement structured logging for operational failures (e.g., file I/O, external API calls). Provide generic, non-technical error messages to the end-user.
Testing Guidelines
Create unit tests in tests/test_commands.py to verify:
- Correct file loading for the
HELPcommand. - Accurate formatting of card lists for the
PACKcommand under various data states. - Proper calculation and display of alignment ratios for the
STATUScommand. - Context validation and hint retrieval for the
HINTcommand, using mocking for external dependencies. - Correct termination flag for the
QUITcommand. - Appropriate handling of invalid command inputs.