# Skelly - Project Structure Map

## Overview
Skelly is a Godot 4.4 game project featuring multiple gameplay modes. The project supports match-3 puzzle gameplay with planned clickomania gameplay through a modular gameplay architecture. It follows a modular structure with clear separation between scenes, autoloads, assets, and data.

## Project Root Structure

```
skelly/
├── .claude/                    # Claude Code configuration
├── .godot/                     # Godot engine generated files (ignored)
├── assets/                     # Game assets (sprites, audio, textures)
├── data/                       # Game data and configuration files
├── docs/                       # Documentation
├── localization/               # Internationalization files
├── scenes/                     # Godot scenes (.tscn) and scripts (.gd)
├── src/                        # Source code organization
├── tests/                      # Test scripts and validation utilities
├── project.godot               # Main Godot project configuration
└── icon.svg                    # Project icon
```

## Core Architecture

### Autoloads (Global Singletons)
Located in `src/autoloads/`, these scripts are automatically loaded when the game starts:

1. **SaveManager** (`src/autoloads/SaveManager.gd`)
   - Persistent game data management with validation
   - High score tracking and current score management
   - Game statistics (games played, total score)
   - Grid state persistence for match-3 gameplay continuity
   - Progress reset functionality with complete data cleanup
   - Security features: backup system, checksum validation, file size limits
   - Robust error handling with backup restoration capabilities
   - Uses: `user://savegame.save` for persistent storage

2. **SettingsManager** (`src/autoloads/SettingsManager.gd`)
   - Manages game settings and user preferences
   - Configuration file I/O
   - input validation
   - JSON parsing
   - Provides language selection functionality
   - Dependencies: `localization/languages.json`

3. **AudioManager** (`src/autoloads/AudioManager.gd`)
   - Controls music and sound effects
   - Manages audio bus configuration
   - Uses: `data/default_bus_layout.tres`

4. **GameManager** (`src/autoloads/GameManager.gd`)
   - Game state management and gameplay mode coordination with race condition protection
   - Scene transitions with concurrent change prevention and validation
   - Gameplay mode selection and launching with input validation (match3, clickomania)
   - Error handling for scene loading failures and fallback mechanisms
   - Navigation flow control with state protection
   - References: main.tscn, game.tscn and individual gameplay scenes

5. **LocalizationManager** (`src/autoloads/LocalizationManager.gd`)
   - Language switching functionality
   - Works with Godot's built-in internationalization system
   - Uses translation files in `localization/`

6. **DebugManager** (`src/autoloads/DebugManager.gd`)
   - Global debug state management and centralized logging system
   - Debug UI visibility control
   - F12 toggle functionality
   - Signal-based debug system
   - Structured logging with configurable log levels (TRACE, DEBUG, INFO, WARN, ERROR, FATAL)
   - Timestamp-based log formatting with category support
   - Runtime log level filtering


## Scene Hierarchy & Flow

### Main Scenes
```
main.tscn (Entry Point)
├── SplashScreen.tscn
├── MainMenu.tscn
└── SettingsMenu.tscn

game.tscn (Gameplay Container)
├── GameplayContainer (Dynamic content)
├── UI/ScoreDisplay
├── BackButton
└── DebugToggle
```

### Game Flow
1. **Main Scene** (`scenes/main/main.tscn` + `Main.gd`)
   - Application entry point
   - Manages splash screen
   - Transitions to main menu
   - Dynamic menu loading system

2. **Splash Screen** (`scenes/main/SplashScreen.tscn` + `SplashScreen.gd`)
   - Initial splash screen
   - Input detection for any key/button
   - Signals to main scene for transition

3. **Main Menu** (`scenes/ui/MainMenu.tscn` + `MainMenu.gd`)
   - Primary navigation hub
   - Start game, settings, quit options
   - Connected to GameManager for scene transitions

4. **Settings Menu** (`scenes/ui/SettingsMenu.tscn` + `SettingsMenu.gd`)
   - User preferences interface
   - Language selection
   - Audio volume controls
   - Connected to SettingsManager and AudioManager

5. **Game Scene** (`scenes/game/game.tscn` + `game.gd`)
   - Main gameplay container with modular gameplay system
   - Dynamic loading of gameplay modes into GameplayContainer
   - Global score management and display
   - Back button for navigation to main menu
   - Gameplay mode switching support (Space+Enter debug key)
   - Bridge between UI and individual gameplay implementations

### UI Components
```
scenes/ui/
├── components/
│   └── ValueStepper.tscn + ValueStepper.gd     # Reusable arrow-based value selector
├── DebugToggle.tscn + DebugToggle.gd           # Available on all major scenes
├── DebugMenuBase.gd                            # Unified base class for debug menus
├── DebugMenu.tscn + DebugMenu.gd               # Global debug controls (extends DebugMenuBase)
├── Match3DebugMenu.gd                          # Match-3 specific debug controls (extends DebugMenuBase)
├── MainMenu.tscn + MainMenu.gd                 # With gamepad/keyboard navigation
└── SettingsMenu.tscn + SettingsMenu.gd         # With comprehensive input validation
```

**Quality Improvements:**
- **ValueStepper Component**: Reusable arrow-based selector for discrete values (language, resolution, difficulty)
- **DebugMenuBase.gd**: Eliminates 90% code duplication between debug menu classes
- **Input Validation**: User inputs are validated and sanitized before processing
- **Error Recovery**: Error handling with fallback mechanisms throughout UI
- **Navigation Support**: Gamepad/keyboard navigation across menus

## Modular Gameplay System

The game now uses a modular gameplay architecture where different game modes can be dynamically loaded into the main game scene.

### Gameplay Architecture
- **Main Game Scene** (`scenes/game/game.gd`) - Container and coordinator
- **Gameplay Directory** (`scenes/game/gameplays/`) - Individual gameplay implementations
- **Dynamic Loading** - Gameplay scenes loaded at runtime based on mode selection
- **Signal-based Communication** - Gameplays communicate with main scene via signals

### Current Gameplay Modes

#### Match-3 Mode (`scenes/game/gameplays/match3_gameplay.tscn`)
1. **Match3 Controller** (`scenes/game/gameplays/match3_gameplay.gd`)
   - Grid management (8x8 default) with memory-safe node cleanup
   - Match detection algorithms with bounds checking and validation
   - Tile dropping and refilling with signal connections
   - Gem pool management (3-8 gem types) with instance-based architecture
   - Debug UI integration with validation
   - Score reporting via `score_changed` signal
   - **Memory Safety**: Uses `queue_free()` with frame waiting to prevent crashes
   - **Gem Movement System**: Keyboard and gamepad input for tile selection and swapping
     - State machine: WAITING → SELECTING → SWAPPING → PROCESSING
     - Adjacent tile validation (horizontal/vertical neighbors only)
     - Match validation (swaps must create matches or revert)
     - Smooth tile position animations with Tween
     - Cursor-based navigation with visual highlighting and bounds checking

2. **Tile System** (`scenes/game/gameplays/tile.gd` + `Tile.tscn`)
   - Tile behavior with instance-based architecture (no global state)
   - Gem type management with validation and bounds checking
   - Visual representation with scaling and color
   - Group membership for coordination
   - **Visual Feedback System**: Multi-state display for game interaction
     - Selection visual feedback (scale and color modulation)
     - State management (normal, highlighted, selected)
     - Signal-based communication with gameplay controller
     - Smooth animations with Tween system
   - **Memory Safety**: Resource management and cleanup

#### Clickomania Mode (`scenes/game/gameplays/clickomania_gameplay.tscn`)
- Planned implementation for clickomania-style gameplay
- Will integrate with same scoring and UI systems as match-3

### Debug System
- Global debug state via DebugManager with initialization
- Debug toggle available on all major scenes (MainMenu, SettingsMenu, SplashScreen, Game)
- Match-3 specific debug UI panel with gem count controls and difficulty presets
- Gem count controls (+/- buttons) with difficulty presets (Easy: 3, Normal: 5, Hard: 8)
- Board reroll functionality for testing
- F12 toggle support across all scenes
- Fewer debug prints in production code

## Asset Organization

### Audio (`assets/audio/`)
```
audio/
├── music/          # Background music files
└── sfx/           # Sound effects
```

### Visual Assets (`assets/`)
```
assets/
├── audio/
│   ├── music/                  # Background music files
│   └── sfx/                    # Sound effects
├── sprites/
│   ├── characters/skeleton/    # Character artwork
│   ├── gems/                   # Match-3 gem sprites
│   └── ui/                     # User interface elements
├── textures/
│   └── backgrounds/            # Background images
├── fonts/                      # Custom fonts
└── sources.yaml               # Asset metadata and attribution
```

### Asset Management (`assets/sources.yaml`)
**REQUIRED**: Every asset added to the project must be documented in `assets/sources.yaml` with:
- **Source information** - Where the asset came from (URL, artist, store, etc.)
- **License details** - Usage rights, attribution requirements, commercial permissions
- **Attribution text** - Exact text to use for credits if required
- **Modification notes** - Any changes made to the original asset
- **Usage context** - Where and how the asset is used in the project

**Example format:**
```yaml
audio:
  music:
    "Space Horror InGame Music (Exploration) _Clement Panchout.wav":
      source: "https://freesound.org/people/ClementPanchout/"
      license: "CC BY 4.0"
      attribution: "Space Horror InGame Music by Clement Panchout"
      modifications: "Converted to WAV, loop points adjusted"
      usage: "Background music for all gameplay scenes"

sprites:
  gems:
    "gem_blue.png":
      source: "Created in-house"
      license: "Project proprietary"
      attribution: "Skelly development team"
      modifications: "None"
      usage: "Match-3 blue gem sprite"
```

## Data & Configuration

### Game Data (`data/`)
- `default_bus_layout.tres` - Audio bus configuration for Godot

### Documentation (`docs/`)
- `MAP.md` - Project architecture and structure overview
- `CLAUDE.md` - Claude Code development guidelines
- `CODE_OF_CONDUCT.md` - Coding standards and best practices
- `TESTING.md` - Testing guidelines and conventions

### Localization (`localization/`)
- `languages.json` - Available language definitions
- `MainStrings.en.translation` - English translations
- `MainStrings.ru.translation` - Russian translations

### Testing & Validation (`tests/`)
- `test_logging.gd` - DebugManager logging system validation
- **`test_checksum_issue.gd`** - SaveManager checksum validation and deterministic hashing
- **`test_migration_compatibility.gd`** - SaveManager version migration and backward compatibility
- **`test_save_system_integration.gd`** - Complete save/load workflow integration testing
- **`test_checksum_fix_verification.gd`** - JSON serialization checksum fix verification
- `README.md` - Brief directory overview (see docs/TESTING.md for full guidelines)
- Comprehensive test scripts for save system security and data integrity validation
- Temporary test utilities for development and debugging

### Project Configuration
- `project.godot` - Main Godot project settings
  - Autoload definitions
  - Input map configurations
  - Rendering settings
  - Audio bus references

## Key Dependencies & Connections

### Signal Connections
```
SplashScreen --[confirm_pressed]--> Main
MainMenu --[open_settings]--> Main
SettingsMenu --[back_to_main_menu]--> Main
DebugManager --[debug_toggled]--> All scenes with DebugToggle
GameplayModes --[score_changed]--> Game Scene
Game Scene --[score updates]--> UI/ScoreDisplay
```

### Scene References
```
GameManager --> main.tscn, game.tscn
GameManager --> scenes/game/gameplays/*.tscn (via GAMEPLAY_SCENES constant)
Main --> MainMenu.tscn, SettingsMenu.tscn
Game --> GameplayContainer (dynamic loading of gameplay scenes)
Game --> scenes/game/gameplays/match3_gameplay.tscn, clickomania_gameplay.tscn
```

### Asset Dependencies
```
AudioManager --> assets/audio/music/
SettingsManager --> localization/languages.json
AudioManager --> data/default_bus_layout.tres
Asset Management --> assets/sources.yaml (required for all assets)
```

## Logging System

The project uses a centralized logging system implemented in DebugManager for consistent, structured logging throughout the application.

### Log Levels
```
TRACE (0)  - Detailed execution tracing (debug mode only)
DEBUG (1)  - Development debugging information (debug mode only)
INFO (2)   - General application information (always visible)
WARN (3)   - Warning messages that don't break functionality
ERROR (4)  - Error conditions that may affect functionality
FATAL (5)  - Critical errors that may cause application failure
```

### Usage Examples
```gdscript
# Basic logging with automatic categorization
DebugManager.log_info("Game started successfully")
DebugManager.log_warn("Settings file not found, using defaults")
DebugManager.log_error("Failed to load audio resource")

# Logging with custom categories for better organization
DebugManager.log_debug("Grid regenerated with 64 tiles", "Match3")
DebugManager.log_info("Language changed to: en", "Settings")
DebugManager.log_error("Invalid scene path provided", "GameManager")

# Standard categories in use:
# - GameManager: Scene transitions, gameplay mode management
# - Match3: Match-3 gameplay, grid operations, tile interactions
# - Settings: Settings management, language changes
# - Game: Main game scene, mode switching
# - MainMenu: Main menu interactions
# - SplashScreen: Splash screen
# - Clickomania: Clickomania gameplay mode
# - DebugMenu: Debug menu operations
```

### Log Format
```
[timestamp] LEVEL [category]: message
Example: [2025-09-24T10:48:08] INFO [GameManager]: Loading main scene
```

### Runtime Configuration
```gdscript
# Set minimum log level (filters out lower priority messages)
DebugManager.set_log_level(DebugManager.LogLevel.WARN)

# Get current log level
var current_level = DebugManager.get_log_level()

# Check if a specific level would be logged
if DebugManager._should_log(DebugManager.LogLevel.DEBUG):
    # Expensive debug calculation here
```

### Integration with Godot Systems
- **WARN/ERROR/FATAL** levels automatically call `push_warning()` and `push_error()`
- **TRACE/DEBUG** levels only display when debug mode is enabled
- **INFO** and higher levels always display regardless of debug mode
- All levels respect the configured minimum log level threshold

## Development Notes

### Current Implementation Status
- Modular gameplay system with dynamic loading architecture
- Match-3 system with 8x8 grid and configurable gem pools
- **Interactive Match-3 Gameplay**: Keyboard and gamepad gem movement system
  - Keyboard: Arrow key navigation with Enter to select/confirm (WASD also supported)
  - Gamepad: D-pad navigation with A button to select/confirm
  - Visual feedback: Tile highlighting, selection indicators, smooth animations
  - Game logic: Adjacent-only swaps, match validation, automatic revert on invalid moves
  - State machine: WAITING → SELECTING → SWAPPING → PROCESSING states
- **Comprehensive Logging System**: All print()/push_error() statements migrated to DebugManager
  - Structured logging with categories: GameManager, Match3, Settings, Game, MainMenu, etc.
  - Multiple log levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL
  - Debug mode integration with level filtering
- Global scoring system integrated across gameplay modes
- Debug UI system with F12 toggle functionality across all major scenes
- Scene transition system via GameManager with gameplay mode support
- Internationalization support for English/Russian

### Architecture Patterns
1. **Autoload Pattern** - Global managers as singletons
2. **Signal-Based Communication** - Loose coupling between components
3. **Modular Gameplay Architecture** - Dynamic loading of gameplay modes
4. **Scene Composition** - Modular scene loading and management
5. **Data-Driven Configuration** - JSON for settings and translations
6. **Component Architecture** - Reusable UI and game components
7. **Centralized Scoring System** - Global score management across gameplay modes
8. **Structured Logging System** - Centralized logging with level-based filtering and formatted output

This structure provides a clean separation of concerns, making the codebase maintainable and extensible for future features.
