Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Designing a System Command Handler for a Game

Tech May 15 1

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 the get_morality_ratios function.
    • llm_hint: Requires the get_llm_hint function.
    • Standard libraries: logging, os, json.
  • Input Parameters: The primary function receives the current game_state dictionary and an optional boss_fight object 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_cards and wild_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_obj is None or state.get('in_boss_fight') is not True.
  • Process:
    1. Call boss_obj.get_context_for_hint() to retrieve relevant battle data.
    2. Pass this context to llm_hint.get_llm_hint().
  • 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:

  1. Correct file loading for the HELP command.
  2. Accurate formatting of card lists for the PACK command under various data states.
  3. Proper calculation and display of alignment ratios for the STATUS command.
  4. Context validation and hint retrieval for the HINT command, using mocking for external dependencies.
  5. Correct termination flag for the QUIT command.
  6. Appropriate handling of invalid command inputs.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.