codemap generation
Some checks failed
Some checks failed
This commit is contained in:
424
docs/ARCHITECTURE.md
Normal file
424
docs/ARCHITECTURE.md
Normal file
@@ -0,0 +1,424 @@
|
||||
# System Architecture
|
||||
|
||||
High-level architecture guide for the Skelly project, explaining system design, architectural patterns, and design decisions.
|
||||
|
||||
**Quick Links**:
|
||||
- **Coding Standards**: See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)
|
||||
- **Testing Protocols**: See [TESTING.md](TESTING.md)
|
||||
- **Component APIs**: See [UI_COMPONENTS.md](UI_COMPONENTS.md)
|
||||
|
||||
## Overview
|
||||
|
||||
Skelly uses a service-oriented architecture with **autoload managers** providing global services, **scene-based components** implementing gameplay, and **signal-based communication** for loose coupling.
|
||||
|
||||
**Key Architectural Principles**:
|
||||
- **Instance-based design**: No global static state for testability
|
||||
- **Signal-driven communication**: Loose coupling between systems
|
||||
- **Service layer pattern**: Autoloads as singleton services
|
||||
- **State machines**: Explicit state management for complex flows
|
||||
- **Defensive programming**: Input validation, error recovery, fallback mechanisms
|
||||
|
||||
## Autoload System
|
||||
|
||||
Autoloads provide singleton services accessible globally. Each has a specific responsibility.
|
||||
|
||||
### GameManager
|
||||
**Responsibility**: Scene transitions and game state coordination
|
||||
|
||||
**Key Features**:
|
||||
- Centralized scene loading with error handling
|
||||
- Race condition protection via `is_changing_scene` flag
|
||||
- Scene path constants for maintainability
|
||||
- Gameplay mode validation with whitelist
|
||||
- Never use `get_tree().change_scene_to_file()` directly
|
||||
|
||||
**Usage**:
|
||||
```gdscript
|
||||
# ✅ Correct
|
||||
GameManager.start_game_with_mode("match3")
|
||||
|
||||
# ❌ Wrong
|
||||
get_tree().change_scene_to_file("res://scenes/game/Game.tscn")
|
||||
```
|
||||
|
||||
**Files**: `src/autoloads/GameManager.gd`
|
||||
|
||||
### SaveManager
|
||||
**Responsibility**: Save/load game state with security and data integrity
|
||||
|
||||
**Key Features**:
|
||||
- **Tamper Detection**: Deterministic checksums detect save file modification
|
||||
- **Race Condition Protection**: Save operation locking prevents concurrent conflicts
|
||||
- **Permissive Validation**: Auto-repair system fixes corrupted data
|
||||
- **Type Safety**: NaN/Infinity/bounds checking for numeric values
|
||||
- **Memory Protection**: File size limits prevent memory exhaustion
|
||||
- **Version Migration**: Backward-compatible save format upgrades
|
||||
- **Error Recovery**: Multi-layered backup and fallback systems
|
||||
|
||||
**Security Model**:
|
||||
```gdscript
|
||||
# Checksum validates data integrity
|
||||
save_data["_checksum"] = _calculate_checksum(save_data)
|
||||
|
||||
# Auto-repair fixes corrupted fields
|
||||
if not _validate_save_data(data):
|
||||
data = _repair_save_data(data)
|
||||
|
||||
# Race condition protection
|
||||
if _is_saving:
|
||||
return # Prevent concurrent saves
|
||||
```
|
||||
|
||||
**Testing**: See [TESTING.md](TESTING.md#save-system-testing-protocols) for comprehensive test suites validating checksums, migration, and integration.
|
||||
|
||||
**Files**: `src/autoloads/SaveManager.gd`
|
||||
|
||||
### SettingsManager
|
||||
**Responsibility**: User settings persistence and validation
|
||||
|
||||
**Key Features**:
|
||||
- Input validation with NaN/Infinity checks
|
||||
- Bounds checking for numeric values
|
||||
- Security hardening against invalid inputs
|
||||
- Default fallback values
|
||||
- Type coercion with validation
|
||||
|
||||
**Files**: `src/autoloads/SettingsManager.gd`
|
||||
|
||||
### DebugManager
|
||||
**Responsibility**: Unified logging and debug UI coordination
|
||||
|
||||
**Key Features**:
|
||||
- Structured logging with log levels (TRACE, DEBUG, INFO, WARN, ERROR, FATAL)
|
||||
- Category-based log organization
|
||||
- Global debug UI toggle (F12 key)
|
||||
- Log level filtering for development/production
|
||||
- Replaces all `print()` and `push_error()` calls
|
||||
|
||||
**Usage**: See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md#logging-standards) for logging best practices.
|
||||
|
||||
**Files**: `src/autoloads/DebugManager.gd`
|
||||
|
||||
### AudioManager
|
||||
**Responsibility**: Music and sound effect playback
|
||||
|
||||
**Key Features**:
|
||||
- Audio bus system (Music, SFX)
|
||||
- Volume control per bus
|
||||
- Loop configuration for music
|
||||
- UI click sounds
|
||||
|
||||
**Files**: `src/autoloads/AudioManager.gd`
|
||||
|
||||
### LocalizationManager
|
||||
**Responsibility**: Language switching and translation management
|
||||
|
||||
**Key Features**:
|
||||
- Multi-language support (English, Russian)
|
||||
- Runtime language switching
|
||||
- Translation file management
|
||||
|
||||
**Files**: `src/autoloads/LocalizationManager.gd`
|
||||
|
||||
## Scene Management Pattern
|
||||
|
||||
All scene transitions flow through **GameManager** to ensure consistent error handling and state management.
|
||||
|
||||
### Scene Loading Flow
|
||||
|
||||
```
|
||||
User Action
|
||||
↓
|
||||
GameManager.start_game_with_mode(mode)
|
||||
↓
|
||||
Validate mode (whitelist check)
|
||||
↓
|
||||
Check is_changing_scene flag
|
||||
↓
|
||||
Load PackedScene with validation
|
||||
↓
|
||||
change_scene_to_packed()
|
||||
↓
|
||||
Reset is_changing_scene flag
|
||||
```
|
||||
|
||||
### Race Condition Prevention
|
||||
|
||||
```gdscript
|
||||
var is_changing_scene: bool = false
|
||||
|
||||
func start_game_with_mode(gameplay_mode: String) -> void:
|
||||
# Prevent concurrent scene changes
|
||||
if is_changing_scene:
|
||||
DebugManager.log_warn("Scene change already in progress", "GameManager")
|
||||
return
|
||||
|
||||
is_changing_scene = true
|
||||
# ... scene loading logic ...
|
||||
is_changing_scene = false
|
||||
```
|
||||
|
||||
**Why This Matters**: Multiple rapid button clicks or input events could trigger concurrent scene loads, causing crashes or undefined state.
|
||||
|
||||
## Modular Gameplay System
|
||||
|
||||
Game modes are implemented as separate gameplay modules in `scenes/game/gameplays/`.
|
||||
|
||||
### Gameplay Architecture
|
||||
|
||||
```
|
||||
Game.tscn (Main scene)
|
||||
↓
|
||||
├─> Match3Gameplay.tscn (Match-3 mode)
|
||||
├─> ClickomaniaGameplay.tscn (Clickomania mode)
|
||||
└─> [Future gameplay modes]
|
||||
```
|
||||
|
||||
**Pattern**: Each gameplay mode:
|
||||
- Extends Control or Node2D
|
||||
- Emits `score_changed` signal
|
||||
- Implements `_ready()` for initialization
|
||||
- Handles input independently
|
||||
- Includes optional debug menu
|
||||
|
||||
**Files**: `scenes/game/gameplays/`
|
||||
|
||||
## Design Patterns Used
|
||||
|
||||
### Instance-Based Architecture
|
||||
|
||||
**Problem**: Static variables prevent testing and create hidden dependencies.
|
||||
|
||||
**Solution**: Instance-based architecture with explicit dependencies.
|
||||
|
||||
```gdscript
|
||||
# ❌ Bad: Static global state
|
||||
static var current_gem_pool = [0, 1, 2, 3, 4]
|
||||
|
||||
# ✅ Good: Instance-based
|
||||
var active_gem_types: Array = []
|
||||
|
||||
func set_active_gem_types(gem_indices: Array) -> void:
|
||||
active_gem_types = gem_indices.duplicate()
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- Each instance isolated for testing
|
||||
- No hidden global state
|
||||
- Explicit dependencies
|
||||
- Thread-safe by default
|
||||
|
||||
### Signal-Based Communication
|
||||
|
||||
**Pattern**: Use signals for loose coupling between systems.
|
||||
|
||||
```gdscript
|
||||
# Component emits signal
|
||||
signal score_changed(new_score: int)
|
||||
|
||||
# Parent connects to signal
|
||||
gameplay.score_changed.connect(_on_score_changed)
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- Loose coupling
|
||||
- Easy to test components in isolation
|
||||
- Clear event flow
|
||||
- Flexible subscription model
|
||||
|
||||
### Service Layer Pattern
|
||||
|
||||
Autoloads act as singleton services providing global functionality.
|
||||
|
||||
**Pattern**:
|
||||
- Autoloads expose public API methods
|
||||
- Components call autoload methods
|
||||
- Autoloads emit signals for state changes
|
||||
- Never nest autoload calls deeply
|
||||
|
||||
### State Machine Pattern
|
||||
|
||||
Complex workflows use explicit state machines.
|
||||
|
||||
**Example**: Match-3 tile swapping
|
||||
```
|
||||
WAITING → SELECTING → SWAPPING → PROCESSING → WAITING
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- Clear state transitions
|
||||
- Easy to debug
|
||||
- Prevents invalid state combinations
|
||||
- Self-documenting code
|
||||
|
||||
## Critical Architecture Decisions
|
||||
|
||||
### Memory Management: queue_free() Over free()
|
||||
|
||||
**Decision**: Always use `queue_free()` instead of `free()` for node cleanup.
|
||||
|
||||
**Rationale**:
|
||||
- `free()` causes immediate deletion (crashes if referenced)
|
||||
- `queue_free()` waits until safe deletion point
|
||||
- Prevents use-after-free bugs
|
||||
|
||||
**Implementation**:
|
||||
```gdscript
|
||||
# ✅ Correct
|
||||
for child in children_to_remove:
|
||||
child.queue_free()
|
||||
await get_tree().process_frame # Wait for cleanup
|
||||
|
||||
# ❌ Dangerous
|
||||
for child in children_to_remove:
|
||||
child.free() # Can crash
|
||||
```
|
||||
|
||||
**Impact**: Eliminated multiple potential crash points. See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md#memory-management-standards) for standards.
|
||||
|
||||
### Race Condition Prevention: State Flags
|
||||
|
||||
**Decision**: Use state flags to prevent concurrent operations.
|
||||
|
||||
**Rationale**:
|
||||
- Async operations can overlap without protection
|
||||
- Multiple rapid inputs can trigger race conditions
|
||||
- State flags provide simple, effective protection
|
||||
|
||||
**Implementation**: Used in GameManager (scene loading), SaveManager (save operations), and gameplay systems (tile swapping).
|
||||
|
||||
### Error Recovery: Fallback Mechanisms
|
||||
|
||||
**Decision**: Provide fallback behavior for all critical failures.
|
||||
|
||||
**Rationale**:
|
||||
- Games should degrade gracefully, not crash
|
||||
- User experience > strict validation
|
||||
- Log errors but continue operation
|
||||
|
||||
**Examples**:
|
||||
- Settings file corrupted? Load defaults
|
||||
- Scene load failed? Return to main menu
|
||||
- Audio file missing? Continue without sound
|
||||
|
||||
### Input Validation: Whitelist Approach
|
||||
|
||||
**Decision**: Validate all user inputs against known-good values.
|
||||
|
||||
**Rationale**:
|
||||
- Security hardening
|
||||
- Prevent invalid state
|
||||
- Clear error messages
|
||||
- Self-documenting code
|
||||
|
||||
**Implementation**: Used in SettingsManager (volume, language), GameManager (gameplay modes), Match3Gameplay (grid movements).
|
||||
|
||||
## System Interactions
|
||||
|
||||
### Typical Game Flow
|
||||
|
||||
```
|
||||
Main Menu
|
||||
↓
|
||||
[GameManager.start_game_with_mode("match3")]
|
||||
↓
|
||||
Game Scene Loads
|
||||
↓
|
||||
Match3Gameplay initializes
|
||||
↓
|
||||
├─> SettingsManager (load difficulty)
|
||||
├─> AudioManager (play background music)
|
||||
└─> DebugManager (setup debug UI)
|
||||
↓
|
||||
Gameplay Loop
|
||||
↓
|
||||
├─> Input handling
|
||||
├─> Score updates (emit score_changed signal)
|
||||
├─> SaveManager (autosave high score)
|
||||
└─> DebugManager (log important events)
|
||||
```
|
||||
|
||||
### Signal Flow Example: Score Change
|
||||
|
||||
```
|
||||
Match3Gameplay detects match
|
||||
↓
|
||||
[emit score_changed(new_score)]
|
||||
↓
|
||||
Game.gd receives signal
|
||||
↓
|
||||
Updates score display UI
|
||||
↓
|
||||
SaveManager.save_high_score(score)
|
||||
```
|
||||
|
||||
### Debug System Integration
|
||||
|
||||
```
|
||||
User presses F12
|
||||
↓
|
||||
DebugManager.toggle_debug_ui()
|
||||
↓
|
||||
[emit debug_ui_toggled(visible)]
|
||||
↓
|
||||
All debug menus receive signal
|
||||
↓
|
||||
Show/hide debug panels
|
||||
```
|
||||
|
||||
## Quality Improvements
|
||||
|
||||
The project implements high-quality code standards from the start:
|
||||
|
||||
**Key Quality Features**:
|
||||
- **Memory Safety**: Uses `queue_free()` pattern for safe node cleanup
|
||||
- **Error Handling**: Comprehensive error handling with fallbacks
|
||||
- **Race Condition Protection**: State flag protection for async operations
|
||||
- **Instance-Based Architecture**: No global static state for testability
|
||||
- **Code Reuse**: Base class architecture (DebugMenuBase) for common functionality
|
||||
- **Input Validation**: Complete validation coverage for all user inputs
|
||||
|
||||
These standards are enforced through the [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md#code-quality-checklist) quality checklist.
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Extending the Architecture
|
||||
|
||||
When adding new features:
|
||||
|
||||
1. **New autoload?**
|
||||
- Only if truly global and used by many systems
|
||||
- Consider dependency injection instead
|
||||
- Keep autoloads focused on single responsibility
|
||||
|
||||
2. **New gameplay mode?**
|
||||
- Create in `scenes/game/gameplays/`
|
||||
- Extend appropriate base class
|
||||
- Emit `score_changed` signal
|
||||
- Add to GameManager mode whitelist
|
||||
|
||||
3. **New UI component?**
|
||||
- Create in `scenes/ui/components/`
|
||||
- Follow [UI_COMPONENTS.md](UI_COMPONENTS.md) patterns
|
||||
- Support keyboard/gamepad navigation
|
||||
- Emit signals for state changes
|
||||
|
||||
### Architecture Review Checklist
|
||||
|
||||
Before committing architectural changes:
|
||||
|
||||
- [ ] No new global static state introduced
|
||||
- [ ] All autoload access justified and documented
|
||||
- [ ] Signal-based communication used appropriately
|
||||
- [ ] Error handling with fallbacks implemented
|
||||
- [ ] Input validation in place
|
||||
- [ ] Memory management uses `queue_free()`
|
||||
- [ ] Race condition protection if async operations
|
||||
- [ ] Testing strategy defined
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- **[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)**: Coding standards and best practices
|
||||
- **[TESTING.md](TESTING.md)**: Testing protocols and procedures
|
||||
- **[UI_COMPONENTS.md](UI_COMPONENTS.md)**: Component API reference
|
||||
- **[CLAUDE.md](CLAUDE.md)**: LLM assistant quick start guide
|
||||
185
docs/CLAUDE.md
185
docs/CLAUDE.md
@@ -1,185 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for Claude Code (claude.ai/code) when working with this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
"Skelly" is a Godot 4.4 mobile game project with multiple gameplay modes. Supports match-3 puzzle gameplay with planned clickomania gameplay. Includes modular gameplay system, menu system, settings management, audio handling, localization support, and debug system.
|
||||
|
||||
**For detailed project architecture, see `docs/MAP.md`**
|
||||
|
||||
## Development Commands
|
||||
|
||||
### Running the Project
|
||||
- Open project in Godot Editor: Import `project.godot`
|
||||
- Run project: Press F5 in Godot Editor or use "Play" button
|
||||
- Debug: Use Godot's built-in debugger and remote inspector
|
||||
- Debug UI: Press F12 in-game or use debug button to toggle debug panels
|
||||
|
||||
### Testing & Development
|
||||
- Debug mode can be toggled with F12 key or debug button UI (available on all major scenes)
|
||||
- Match-3 debug controls include gem count adjustment and board reroll
|
||||
- Difficulty presets: Easy (3 gems), Normal (5 gems), Hard (8 gems)
|
||||
- Gameplay mode switching: Space+Enter in game scene switches between match-3 and clickomania modes
|
||||
- **Match-3 Gem Movement Testing**:
|
||||
- Keyboard: Arrow keys or WASD to navigate, Enter to select/confirm
|
||||
- Gamepad: D-pad to navigate, A button to select/confirm
|
||||
- Visual feedback: Selected tiles glow brighter with scale and color effects
|
||||
- Invalid swaps automatically revert after animation
|
||||
- State machine: WAITING → SELECTING → SWAPPING → PROCESSING
|
||||
- Test scripts located in `tests/` directory for system validation
|
||||
- Use `TestLogging.gd` to validate the logging system functionality
|
||||
|
||||
### Audio Configuration
|
||||
- Music: Located in `assets/audio/music/` directory with loop configuration in AudioManager
|
||||
- Sound effects: UI clicks and game audio managed through audio bus system
|
||||
- Audio buses: "Music" and "SFX" buses configured in `data/default_bus_layout.tres`
|
||||
|
||||
### Localization
|
||||
- Translations stored in `localization/` as `.translation` files
|
||||
- Currently supports English and Russian
|
||||
- New translations: Add to `project.godot` internationalization section
|
||||
|
||||
### Asset Management
|
||||
- **Document every asset** in `assets/sources.yaml` before committing
|
||||
- Include source, license, attribution, modifications, and usage information
|
||||
- Verify license compatibility
|
||||
- Commit asset files and sources.yaml together
|
||||
|
||||
## Key Development Guidelines
|
||||
|
||||
### Code Quality & Safety Standards
|
||||
- **Memory Management**: Use `queue_free()` instead of `free()`
|
||||
- **Input Validation**: Validate user inputs with bounds checking and type validation
|
||||
- **Error Handling**: Implement error handling with fallback mechanisms
|
||||
- **Race Condition Prevention**: Use state flags to prevent concurrent operations
|
||||
- **No Global State**: Avoid static variables; use instance-based architecture for testability
|
||||
|
||||
### Scene Management
|
||||
- **Use `GameManager` for all scene transitions** - never call `get_tree().change_scene_to_file()` directly
|
||||
- Scene paths defined as constants in GameManager
|
||||
- Error handling built into GameManager for failed scene loads
|
||||
- Use `GameManager.start_game_with_mode(mode)` to launch specific gameplay modes
|
||||
- Supported modes: "match3", "clickomania" (validated with whitelist)
|
||||
- GameManager prevents concurrent scene changes with `is_changing_scene` protection
|
||||
|
||||
### Autoload Usage
|
||||
- Use autoloads for global state management only
|
||||
- Prefer signals over direct access for loose coupling
|
||||
- Don't access autoloads from deeply nested components
|
||||
- **SaveManager**: Save system with tamper detection, race condition protection, and permissive validation
|
||||
- **SettingsManager**: Features input validation, NaN/Infinity checks, and security hardening
|
||||
- **GameManager**: Protected against race conditions with state management
|
||||
|
||||
### Save System Security & Data Integrity
|
||||
- **SaveManager implements security standards** for data protection
|
||||
- **Tamper Detection**: Deterministic checksums detect save file modification or corruption
|
||||
- **Race Condition Protection**: Save operation locking prevents concurrent conflicts
|
||||
- **Permissive Validation**: Auto-repair system fixes corrupted data instead of rejecting saves
|
||||
- **Type Safety**: NaN/Infinity/bounds checking for numeric values
|
||||
- **Memory Protection**: File size limits prevent memory exhaustion attacks
|
||||
- **Version Migration**: Backward-compatible system handles save format upgrades
|
||||
- **Error Recovery**: Multi-layered backup and fallback systems ensure no data loss
|
||||
- **Security Logging**: All save operations logged for monitoring and debugging
|
||||
|
||||
### Debug System Integration
|
||||
- Connect to `DebugManager.debug_ui_toggled` signal for debug UI visibility
|
||||
- Use F12 key for global debug toggle
|
||||
- Remove debug prints before committing unless permanently useful
|
||||
|
||||
### Logging System Usage
|
||||
- **All print() and push_error() statements migrated to DebugManager**
|
||||
- Use `DebugManager` logging functions instead of `print()`, `push_error()`, etc.
|
||||
- Use log levels: INFO for general messages, WARN for issues, ERROR for failures
|
||||
- Include categories to organize log output: `"GameManager"`, `"Match3"`, `"Settings"`, `"DebugMenu"`
|
||||
- Use structured logging for better debugging and production monitoring
|
||||
- Use `DebugManager.set_log_level()` to control verbosity during development and testing
|
||||
- Logging system provides unified output across all game systems
|
||||
|
||||
## Important File References
|
||||
|
||||
### Documentation Structure
|
||||
- **`docs/MAP.md`** - Complete project architecture and structure
|
||||
- **`docs/UI_COMPONENTS.md`** - Custom UI components
|
||||
- **`docs/CODE_OF_CONDUCT.md`** - Coding standards and best practices
|
||||
- **`docs/TESTING.md`** - Testing guidelines and conventions
|
||||
- **This file** - Claude Code specific development guidelines
|
||||
|
||||
### Key Scripts to Understand
|
||||
- `src/autoloads/GameManager.gd` - Scene transition patterns with race condition protection
|
||||
- `src/autoloads/SaveManager.gd` - **Save system with security features**
|
||||
- `src/autoloads/SettingsManager.gd` - Settings management with input validation and security
|
||||
- `src/autoloads/DebugManager.gd` - Debug system integration
|
||||
- `scenes/game/Game.gd` - Main game scene with modular gameplay system
|
||||
- `scenes/game/gameplays/Match3Gameplay.gd` - Match-3 implementation with input validation
|
||||
- `scenes/game/gameplays/Tile.gd` - Instance-based tile behavior without global state
|
||||
- `scenes/ui/DebugMenuBase.gd` - Unified debug menu base class
|
||||
- `scenes/ui/SettingsMenu.gd` - Settings UI with input validation
|
||||
- `scenes/game/gameplays/` - Individual gameplay mode implementations
|
||||
- `project.godot` - Input actions and autoload definitions
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Before Making Changes
|
||||
1. Check `docs/MAP.md` for architecture
|
||||
2. Review `docs/CODE_OF_CONDUCT.md` for coding standards
|
||||
3. **Review naming conventions**: See [Naming Convention Quick Reference](CODE_OF_CONDUCT.md#naming-convention-quick-reference) for all file and code naming standards
|
||||
4. Understand existing patterns before implementing features
|
||||
5. If adding assets, prepare `assets/sources.yaml` documentation following [asset naming conventions](CODE_OF_CONDUCT.md#5-asset-file-naming)
|
||||
|
||||
### Testing Changes
|
||||
- Run project with F5 in Godot Editor
|
||||
- Test debug UI with F12 toggle
|
||||
- Verify scene transitions work
|
||||
- Check mobile compatibility if UI changes made
|
||||
- Use test scripts from `tests/` directory to validate functionality
|
||||
- Run `TestLogging.gd` after logging system changes
|
||||
- **Save system testing**: Run save/load test suites after SaveManager changes
|
||||
- **Checksum validation**: Test `test_checksum_issue.gd` to verify deterministic checksums
|
||||
- **Migration compatibility**: Run `TestMigrationCompatibility.gd` for version upgrades
|
||||
|
||||
### Common Implementation Patterns
|
||||
- **Scene transitions**: Use `GameManager.start_game_with_mode()` with built-in validation
|
||||
- **Debug integration**: Connect to `DebugManager` signals and initialize debug state
|
||||
- **Logging**: Use `DebugManager.log_*()` functions with appropriate levels and categories
|
||||
- **Gameplay modes**: Implement in `scenes/game/gameplays/` directory following modular pattern
|
||||
- **Scoring system**: Connect `score_changed` signal from gameplay to main game scene
|
||||
- **Save/Load operations**: Use `SaveManager` with security and validation
|
||||
- **Settings**: Use `SettingsManager` with input validation, NaN/Infinity checks, and security hardening
|
||||
- **Audio**: Use `AudioManager` for music and sound effects
|
||||
- **Localization**: Use `LocalizationManager` for language switching
|
||||
- **UI Components**: Extend `DebugMenuBase` for debug menus to avoid code duplication
|
||||
- **Value Selection**: Use `ValueStepper` component for discrete option selection (language, resolution, difficulty)
|
||||
- **Memory Management**: Use `queue_free()` and await frame completion for safe cleanup
|
||||
- **Input Validation**: Validate user inputs with type checking and bounds validation
|
||||
|
||||
### Logging Best Practices
|
||||
```gdscript
|
||||
# Good logging
|
||||
DebugManager.log_info("Scene transition completed", "GameManager")
|
||||
DebugManager.log_warn("Settings file not found, using defaults", "Settings")
|
||||
DebugManager.log_error("Failed to load audio resource: " + audio_path, "AudioManager")
|
||||
|
||||
# Avoid
|
||||
print("debug") # Use structured logging instead
|
||||
push_error("error") # Use DebugManager.log_error() with category
|
||||
```
|
||||
|
||||
### Asset Management Workflow
|
||||
```yaml
|
||||
# ✅ Required assets/sources.yaml entry format
|
||||
audio:
|
||||
music:
|
||||
"background_music.ogg":
|
||||
source: "https://freesound.org/people/artist/sounds/123456/"
|
||||
license: "CC BY 4.0"
|
||||
attribution: "Background Music by Artist Name"
|
||||
modifications: "Converted to OGG, adjusted volume"
|
||||
usage: "Main menu and gameplay background music"
|
||||
|
||||
# ✅ Proper commit workflow
|
||||
# 1. Add asset to appropriate assets/ subdirectory
|
||||
# 2. Update assets/sources.yaml with complete metadata
|
||||
# 3. git add both files together
|
||||
# 4. Commit with descriptive message including attribution
|
||||
```
|
||||
@@ -208,6 +208,89 @@ func load_scene(path: String) -> void:
|
||||
get_tree().change_scene_to_packed(packed_scene)
|
||||
```
|
||||
|
||||
### Memory Management Standards
|
||||
|
||||
**Critical Rules**:
|
||||
1. **Always use `queue_free()`** instead of `free()` for node cleanup
|
||||
2. **Wait for frame completion** after queueing nodes for removal
|
||||
3. **Clear references before cleanup** to prevent access to freed memory
|
||||
4. **Connect signals properly** for dynamically created nodes
|
||||
|
||||
```gdscript
|
||||
# ✅ Correct memory management
|
||||
for child in children_to_remove:
|
||||
child.queue_free()
|
||||
await get_tree().process_frame # Wait for cleanup
|
||||
|
||||
# ❌ Dangerous pattern (causes crashes)
|
||||
for child in children_to_remove:
|
||||
child.free() # Immediate deletion can crash
|
||||
```
|
||||
|
||||
**Why This Matters**: Using `free()` causes immediate deletion which can crash if the node is still referenced elsewhere. `queue_free()` waits until it's safe to delete.
|
||||
|
||||
**See Also**: [ARCHITECTURE.md](ARCHITECTURE.md#memory-management-queue_free-over-free) for architectural rationale.
|
||||
|
||||
### Input Validation Standards
|
||||
|
||||
All user inputs must be validated before processing.
|
||||
|
||||
**Validation Requirements**:
|
||||
1. **Type checking**: Verify input types before processing
|
||||
2. **Bounds checking**: Validate numeric ranges and array indices
|
||||
3. **Null checking**: Handle null and empty inputs gracefully
|
||||
4. **Whitelist validation**: Validate against known good values
|
||||
|
||||
```gdscript
|
||||
# ✅ Proper input validation
|
||||
func set_volume(value: float, setting_key: String) -> bool:
|
||||
# Whitelist validation
|
||||
if not setting_key in ["master_volume", "music_volume", "sfx_volume"]:
|
||||
DebugManager.log_error("Invalid volume setting key: " + str(setting_key), "Settings")
|
||||
return false
|
||||
|
||||
# Bounds checking
|
||||
var clamped_value = clamp(value, 0.0, 1.0)
|
||||
if clamped_value != value:
|
||||
DebugManager.log_warn("Volume value clamped from %f to %f" % [value, clamped_value], "Settings")
|
||||
|
||||
SettingsManager.set_setting(setting_key, clamped_value)
|
||||
return true
|
||||
|
||||
# ✅ Grid movement validation
|
||||
func _move_cursor(direction: Vector2i) -> void:
|
||||
# Bounds checking
|
||||
if abs(direction.x) > 1 or abs(direction.y) > 1:
|
||||
DebugManager.log_error("Invalid cursor direction: " + str(direction), "Match3")
|
||||
return
|
||||
|
||||
# Null/empty checking
|
||||
if not grid or grid.is_empty():
|
||||
DebugManager.log_error("Grid not initialized", "Match3")
|
||||
return
|
||||
|
||||
# Process validated input
|
||||
var new_pos = cursor_pos + direction
|
||||
# ... continue with validated data
|
||||
```
|
||||
|
||||
**See Also**: [ARCHITECTURE.md](ARCHITECTURE.md#input-validation-whitelist-approach) for architectural decision rationale.
|
||||
|
||||
## Code Quality Checklist
|
||||
|
||||
Before committing code, verify:
|
||||
|
||||
- [ ] All user inputs validated (type, bounds, null checks)
|
||||
- [ ] Error handling with fallback mechanisms implemented
|
||||
- [ ] Memory cleanup uses `queue_free()` not `free()`
|
||||
- [ ] No global static state introduced
|
||||
- [ ] Proper logging with categories and appropriate levels
|
||||
- [ ] Race condition protection for async operations
|
||||
- [ ] Input actions defined in project input map
|
||||
- [ ] Resources loaded with null/type checking
|
||||
- [ ] Documentation updated for new public APIs
|
||||
- [ ] Test coverage for new functionality
|
||||
|
||||
## Git Workflow
|
||||
|
||||
### Commit Guidelines
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
# Code Quality Standards & Improvements
|
||||
|
||||
This document outlines the code quality standards implemented in the Skelly project and provides guidelines for maintaining high-quality, reliable code.
|
||||
|
||||
> 📋 **Naming Standards**: All code follows the [Naming Convention Quick Reference](CODE_OF_CONDUCT.md#naming-convention-quick-reference) for consistent file, class, and variable naming.
|
||||
|
||||
## Overview of Improvements
|
||||
|
||||
A comprehensive code quality improvement was conducted to eliminate critical flaws, improve maintainability, and ensure production-ready reliability. The improvements focus on memory safety, error handling, architecture quality, and input validation.
|
||||
|
||||
## 🔴 Critical Issues Resolved
|
||||
|
||||
### 1. Memory Management & Safety
|
||||
|
||||
**Issues Fixed:**
|
||||
- **Memory Leaks**: Eliminated dangerous `child.free()` calls that could cause crashes
|
||||
- **Resource Cleanup**: Implemented proper node cleanup sequencing with frame waiting
|
||||
- **Signal Management**: Added proper signal connections for dynamically created nodes
|
||||
|
||||
**Best Practices:**
|
||||
```gdscript
|
||||
# ✅ Correct memory management
|
||||
for child in children_to_remove:
|
||||
child.queue_free()
|
||||
await get_tree().process_frame # Wait for cleanup
|
||||
|
||||
# ❌ Dangerous pattern (now fixed)
|
||||
for child in children_to_remove:
|
||||
child.free() # Can cause immediate crashes
|
||||
```
|
||||
|
||||
**Files Improved:**
|
||||
- `scenes/game/gameplays/Match3Gameplay.gd`
|
||||
- `scenes/game/gameplays/Tile.gd`
|
||||
|
||||
### 2. Error Handling & Recovery
|
||||
|
||||
**Issues Fixed:**
|
||||
- **JSON Parsing Failures**: Added comprehensive error handling with detailed reporting
|
||||
- **File Operations**: Implemented fallback mechanisms for missing or corrupted files
|
||||
- **Resource Loading**: Added validation and recovery for failed resource loads
|
||||
|
||||
**Best Practices:**
|
||||
```gdscript
|
||||
# ✅ Comprehensive error handling
|
||||
var json = JSON.new()
|
||||
var parse_result = json.parse(json_string)
|
||||
if parse_result != OK:
|
||||
DebugManager.log_error("JSON parsing failed at line %d: %s" % [json.error_line, json.error_string], "SettingsManager")
|
||||
_load_default_settings() # Fallback mechanism
|
||||
return
|
||||
|
||||
# ❌ Minimal error handling (now improved)
|
||||
if json.parse(json_string) != OK:
|
||||
DebugManager.log_error("Error parsing JSON", "SettingsManager")
|
||||
return # No fallback, system left in undefined state
|
||||
```
|
||||
|
||||
**Files Improved:**
|
||||
- `src/autoloads/SettingsManager.gd`
|
||||
|
||||
### 3. Race Conditions & Concurrency
|
||||
|
||||
**Issues Fixed:**
|
||||
- **Scene Loading**: Protected against concurrent scene changes with state flags
|
||||
- **Resource Loading**: Added proper validation and timeout protection
|
||||
- **State Corruption**: Prevented state corruption during async operations
|
||||
|
||||
**Best Practices:**
|
||||
```gdscript
|
||||
# ✅ Race condition prevention
|
||||
var is_changing_scene: bool = false
|
||||
|
||||
func start_game_with_mode(gameplay_mode: String) -> void:
|
||||
if is_changing_scene:
|
||||
DebugManager.log_warn("Scene change already in progress", "GameManager")
|
||||
return
|
||||
|
||||
is_changing_scene = true
|
||||
# ... scene loading logic ...
|
||||
is_changing_scene = false
|
||||
|
||||
# ❌ Unprotected concurrent access (now fixed)
|
||||
func start_game_with_mode(gameplay_mode: String) -> void:
|
||||
# Multiple calls could interfere with each other
|
||||
get_tree().change_scene_to_packed(packed_scene)
|
||||
```
|
||||
|
||||
**Files Improved:**
|
||||
- `src/autoloads/GameManager.gd`
|
||||
|
||||
### 4. Architecture Issues
|
||||
|
||||
**Issues Fixed:**
|
||||
- **Global Static State**: Eliminated problematic static variables that prevented testing
|
||||
- **Instance Isolation**: Replaced with instance-based architecture
|
||||
- **Testability**: Enabled proper unit testing with isolated instances
|
||||
|
||||
**Best Practices:**
|
||||
```gdscript
|
||||
# ✅ Instance-based architecture
|
||||
func set_active_gem_types(gem_indices: Array) -> void:
|
||||
if not gem_indices or gem_indices.is_empty():
|
||||
DebugManager.log_error("Empty gem indices array", "Tile")
|
||||
return
|
||||
active_gem_types = gem_indices.duplicate()
|
||||
|
||||
# ❌ Static global state (now eliminated)
|
||||
static var current_gem_pool = [0, 1, 2, 3, 4]
|
||||
static func set_active_gem_pool(gem_indices: Array) -> void:
|
||||
current_gem_pool = gem_indices.duplicate()
|
||||
```
|
||||
|
||||
**Files Improved:**
|
||||
- `scenes/game/gameplays/Tile.gd`
|
||||
- `scenes/game/gameplays/Match3Gameplay.gd`
|
||||
|
||||
## 🟡 Code Quality Improvements
|
||||
|
||||
### 1. Code Duplication Elimination
|
||||
|
||||
**Achievement:** 90% reduction in duplicate code between debug menu classes
|
||||
|
||||
**Implementation:**
|
||||
- Created `DebugMenuBase.gd` with shared functionality
|
||||
- Refactored existing classes to extend base class
|
||||
- Added input validation and error handling
|
||||
|
||||
```gdscript
|
||||
# ✅ Unified base class
|
||||
class_name DebugMenuBase
|
||||
extends Control
|
||||
|
||||
# Shared functionality for all debug menus
|
||||
func _initialize_spinboxes():
|
||||
# Common spinbox setup code
|
||||
|
||||
func _validate_input(value, min_val, max_val):
|
||||
# Input validation logic
|
||||
|
||||
# ✅ Derived classes
|
||||
extends DebugMenuBase
|
||||
|
||||
func _find_target_scene():
|
||||
# Specific implementation for finding target scene
|
||||
```
|
||||
|
||||
**Files Created/Improved:**
|
||||
- `scenes/ui/DebugMenuBase.gd` (new)
|
||||
- `scenes/ui/DebugMenu.gd` (refactored)
|
||||
- `scenes/game/gameplays/Match3DebugMenu.gd` (refactored)
|
||||
|
||||
### 2. Input Validation & Security
|
||||
|
||||
**Implementation:** Comprehensive input validation across all user input paths
|
||||
|
||||
**Best Practices:**
|
||||
```gdscript
|
||||
# ✅ Volume setting validation
|
||||
func _on_volume_slider_changed(value, setting_key):
|
||||
if not setting_key in ["master_volume", "music_volume", "sfx_volume"]:
|
||||
DebugManager.log_error("Invalid volume setting key: " + str(setting_key), "Settings")
|
||||
return
|
||||
|
||||
var clamped_value = clamp(float(value), 0.0, 1.0)
|
||||
if clamped_value != value:
|
||||
DebugManager.log_warn("Volume value clamped", "Settings")
|
||||
|
||||
# ✅ Grid movement validation
|
||||
func _move_cursor(direction: Vector2i) -> void:
|
||||
if abs(direction.x) > 1 or abs(direction.y) > 1:
|
||||
DebugManager.log_error("Invalid cursor direction", "Match3")
|
||||
return
|
||||
```
|
||||
|
||||
**Files Improved:**
|
||||
- `scenes/ui/SettingsMenu.gd`
|
||||
- `scenes/game/gameplays/Match3Gameplay.gd`
|
||||
- `src/autoloads/GameManager.gd`
|
||||
|
||||
## Development Standards
|
||||
|
||||
### Memory Management Rules
|
||||
|
||||
1. **Always use `queue_free()`** instead of `free()` for node cleanup
|
||||
2. **Wait for frame completion** after queueing nodes for removal
|
||||
3. **Clear references before cleanup** to prevent access to freed memory
|
||||
4. **Connect signals properly** for dynamically created nodes
|
||||
|
||||
### Error Handling Requirements
|
||||
|
||||
1. **Provide fallback mechanisms** for all critical failures
|
||||
2. **Log detailed error information** with context and recovery actions
|
||||
3. **Validate all inputs** before processing
|
||||
4. **Handle edge cases** gracefully without crashing
|
||||
|
||||
### Architecture Guidelines
|
||||
|
||||
1. **Avoid global static state** - use instance-based architecture
|
||||
2. **Implement proper encapsulation** with private/protected members
|
||||
3. **Use composition over inheritance** where appropriate
|
||||
4. **Design for testability** with dependency injection
|
||||
|
||||
### Input Validation Standards
|
||||
|
||||
1. **Type checking** - verify input types before processing
|
||||
2. **Bounds checking** - validate numeric ranges and array indices
|
||||
3. **Null checking** - handle null and empty inputs gracefully
|
||||
4. **Whitelist validation** - validate against known good values
|
||||
|
||||
## Code Quality Metrics
|
||||
|
||||
### Before Improvements
|
||||
- **Memory Safety**: Multiple potential crash points from improper cleanup
|
||||
- **Error Recovery**: Limited error handling with undefined states
|
||||
- **Code Duplication**: 90% duplicate code in debug menus
|
||||
- **Input Validation**: Minimal validation, potential security issues
|
||||
- **Architecture**: Global state preventing proper testing
|
||||
|
||||
### After Improvements
|
||||
- **Memory Safety**: 100% of identified memory issues resolved
|
||||
- **Error Recovery**: Comprehensive error handling with fallbacks
|
||||
- **Code Duplication**: 90% reduction through base class architecture
|
||||
- **Input Validation**: Complete validation coverage for all user inputs
|
||||
- **Architecture**: Instance-based design enabling proper testing
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
### Memory Safety Testing
|
||||
```gdscript
|
||||
# Test node cleanup
|
||||
func test_node_cleanup():
|
||||
var initial_count = get_child_count()
|
||||
create_and_destroy_nodes()
|
||||
await get_tree().process_frame
|
||||
assert(get_child_count() == initial_count)
|
||||
```
|
||||
|
||||
### Error Handling Testing
|
||||
```gdscript
|
||||
# Test fallback mechanisms
|
||||
func test_settings_fallback():
|
||||
delete_settings_file()
|
||||
var settings = SettingsManager.new()
|
||||
assert(settings.get_setting("master_volume") == 0.5) # Default value
|
||||
```
|
||||
|
||||
### Input Validation Testing
|
||||
```gdscript
|
||||
# Test bounds checking
|
||||
func test_volume_validation():
|
||||
var result = settings.set_setting("master_volume", 2.0) # Invalid range
|
||||
assert(result == false)
|
||||
assert(settings.get_setting("master_volume") != 2.0)
|
||||
```
|
||||
|
||||
## Monitoring & Maintenance
|
||||
|
||||
### Code Quality Checklist
|
||||
- [ ] All user inputs validated
|
||||
- [ ] Error handling with fallbacks
|
||||
- [ ] Memory cleanup uses `queue_free()`
|
||||
- [ ] No global static state
|
||||
- [ ] Proper logging with categories
|
||||
- [ ] Race condition protection
|
||||
|
||||
### Regular Reviews
|
||||
- **Weekly**: Review new code for compliance with standards
|
||||
- **Monthly**: Run full codebase analysis for potential issues
|
||||
- **Release**: Comprehensive quality assurance testing
|
||||
|
||||
### Automated Checks
|
||||
- Memory leak detection during testing
|
||||
- Input validation coverage analysis
|
||||
- Error handling path verification
|
||||
- Code duplication detection
|
||||
|
||||
## Future Improvements
|
||||
|
||||
### Planned Enhancements
|
||||
1. **Unit Test Framework**: Implement comprehensive unit testing
|
||||
2. **Performance Monitoring**: Add performance metrics and profiling
|
||||
3. **Static Analysis**: Integrate automated code quality tools
|
||||
4. **Documentation**: Generate automated API documentation
|
||||
|
||||
### Scalability Considerations
|
||||
1. **Service Architecture**: Implement service-oriented patterns
|
||||
2. **Resource Pooling**: Add object pooling for frequently created nodes
|
||||
3. **Event System**: Expand event-driven architecture
|
||||
4. **Configuration Management**: Centralized configuration system
|
||||
|
||||
This document serves as the foundation for maintaining and improving code quality in the Skelly project. All new code should adhere to these standards, and existing code should be gradually updated to meet these requirements.
|
||||
383
docs/DEVELOPMENT.md
Normal file
383
docs/DEVELOPMENT.md
Normal file
@@ -0,0 +1,383 @@
|
||||
# Development Guide
|
||||
|
||||
Development workflows, commands, and procedures for the Skelly project.
|
||||
|
||||
**Quick Links**:
|
||||
- **Architecture**: [ARCHITECTURE.md](ARCHITECTURE.md) - Understand system design before developing
|
||||
- **Coding Standards**: [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - Follow coding conventions
|
||||
- **Testing**: [TESTING.md](TESTING.md) - Testing procedures and protocols
|
||||
|
||||
## Development Commands
|
||||
|
||||
### Running the Project
|
||||
|
||||
```bash
|
||||
# Open project in Godot Editor
|
||||
# Import project.godot
|
||||
|
||||
# Run project
|
||||
# Press F5 in Godot Editor or use "Play" button
|
||||
|
||||
# Toggle debug UI in-game
|
||||
# Press F12 key or use debug button
|
||||
```
|
||||
|
||||
### Code Maps Generation
|
||||
|
||||
Generate machine-readable code intelligence and visual documentation for development:
|
||||
|
||||
```bash
|
||||
# Generate everything (default behavior - maps + diagrams + docs + metrics)
|
||||
python tools/generate_code_map.py
|
||||
|
||||
# Generate specific outputs
|
||||
python tools/generate_code_map.py --diagrams # Visual diagrams only
|
||||
python tools/generate_code_map.py --docs # Markdown documentation only
|
||||
python tools/generate_code_map.py --metrics # Metrics dashboard only
|
||||
|
||||
# Generate all explicitly (same as no arguments)
|
||||
python tools/generate_code_map.py --all
|
||||
|
||||
# Via development workflow tool
|
||||
python tools/run_development.py --codemap
|
||||
|
||||
# Custom output (single JSON file)
|
||||
python tools/generate_code_map.py --output custom_map.json
|
||||
|
||||
# Skip PNG rendering (Mermaid source only)
|
||||
python tools/generate_code_map.py --diagrams --no-render
|
||||
```
|
||||
|
||||
**Generated Files** (Git-ignored):
|
||||
|
||||
**JSON Maps** (`.llm/` directory):
|
||||
- `code_map_api.json` - Function signatures, parameters, return types
|
||||
- `code_map_architecture.json` - Autoloads, design patterns, structure
|
||||
- `code_map_flows.json` - Signal chains, scene transitions
|
||||
- `code_map_security.json` - Input validation, error handling
|
||||
- `code_map_assets.json` - Asset dependencies, licensing
|
||||
- `code_map_metadata.json` - Statistics, quality metrics
|
||||
|
||||
**Diagrams** (`.llm/diagrams/` directory):
|
||||
- `architecture.png` - Autoload system dependencies
|
||||
- `signal_flows.png` - Signal connections between components
|
||||
- `scene_hierarchy.png` - Scene tree structure
|
||||
- `dependency_graph.png` - Module dependencies
|
||||
- `*.mmd` - Mermaid source files
|
||||
|
||||
**Documentation** (`docs/generated/` directory):
|
||||
- `AUTOLOADS_API.md` - Complete autoload API reference with diagrams
|
||||
- `SIGNALS_CATALOG.md` - Signal catalog with flow diagrams
|
||||
- `FUNCTION_INDEX.md` - Searchable function reference
|
||||
- `SCENE_REFERENCE.md` - Scene hierarchy with diagrams
|
||||
- `TODO_LIST.md` - Extracted TODO/FIXME comments
|
||||
- `METRICS.md` - Project metrics dashboard with charts
|
||||
|
||||
**When to Regenerate**:
|
||||
- Before LLM-assisted development sessions (fresh context)
|
||||
- After adding new files or major refactoring (update structure)
|
||||
- After changing autoloads or core architecture (capture changes)
|
||||
- When onboarding new developers (comprehensive docs)
|
||||
- To track project metrics and code complexity
|
||||
|
||||
### Testing Commands
|
||||
|
||||
```bash
|
||||
# Run specific test
|
||||
godot --headless --script tests/TestLogging.gd
|
||||
|
||||
# Run all save system tests
|
||||
godot --headless --script tests/test_checksum_issue.gd
|
||||
godot --headless --script tests/TestMigrationCompatibility.gd
|
||||
godot --headless --script tests/test_save_system_integration.gd
|
||||
|
||||
# Development workflow tool
|
||||
python tools/run_development.py --test
|
||||
```
|
||||
|
||||
See [TESTING.md](TESTING.md) for complete testing procedures.
|
||||
|
||||
## Development Workflows
|
||||
|
||||
### Adding a New Feature
|
||||
|
||||
1. **Generate code maps** for LLM context:
|
||||
```bash
|
||||
python tools/generate_code_map.py
|
||||
```
|
||||
|
||||
2. **Review architecture** to understand system design:
|
||||
- Read [ARCHITECTURE.md](ARCHITECTURE.md) for relevant system
|
||||
- Understand autoload responsibilities
|
||||
- Review existing patterns
|
||||
|
||||
3. **Follow coding standards**:
|
||||
- Use [naming conventions](CODE_OF_CONDUCT.md#naming-convention-quick-reference)
|
||||
- Follow [core patterns](CODE_OF_CONDUCT.md#project-specific-guidelines)
|
||||
- Implement [input validation](CODE_OF_CONDUCT.md#input-validation-standards)
|
||||
- Use [proper memory management](CODE_OF_CONDUCT.md#memory-management-standards)
|
||||
|
||||
4. **Write tests** for new functionality:
|
||||
- Create test file in `tests/` directory
|
||||
- Follow [test structure guidelines](TESTING.md#adding-new-tests)
|
||||
- Run tests to verify functionality
|
||||
|
||||
5. **Check quality checklist** before committing:
|
||||
- Review [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md#code-quality-checklist)
|
||||
- Verify all checkboxes are satisfied
|
||||
- Run tests one more time
|
||||
|
||||
### Debugging Issues
|
||||
|
||||
1. **Toggle debug UI** with F12 in-game:
|
||||
- View system state in debug panels
|
||||
- Check current values and configurations
|
||||
- Use debug controls for testing
|
||||
|
||||
2. **Check logs** using structured logging:
|
||||
```gdscript
|
||||
DebugManager.log_debug("Detailed debug info", "MyComponent")
|
||||
DebugManager.log_info("Important event occurred", "MyComponent")
|
||||
DebugManager.log_warn("Unexpected situation", "MyComponent")
|
||||
DebugManager.log_error("Something failed", "MyComponent")
|
||||
```
|
||||
|
||||
3. **Verify state** in debug panels:
|
||||
- Match-3: Check gem pool, grid state, match detection
|
||||
- Settings: Verify volume, language, difficulty values
|
||||
- Save: Check save data integrity
|
||||
|
||||
4. **Run relevant test scripts**:
|
||||
```bash
|
||||
# Test specific system
|
||||
godot --headless --script tests/TestMatch3Gameplay.gd
|
||||
godot --headless --script tests/TestSettingsManager.gd
|
||||
```
|
||||
|
||||
5. **Use Godot debugger**:
|
||||
- Set breakpoints in code
|
||||
- Inspect variables during execution
|
||||
- Step through code execution
|
||||
- Use remote inspector for live debugging
|
||||
|
||||
### Modifying Core Systems
|
||||
|
||||
1. **Understand current design**:
|
||||
- Read [ARCHITECTURE.md](ARCHITECTURE.md) for system architecture
|
||||
- Review autoload responsibilities
|
||||
- Understand signal flows and dependencies
|
||||
|
||||
2. **Run existing tests first**:
|
||||
```bash
|
||||
# Save system testing
|
||||
godot --headless --script tests/test_checksum_issue.gd
|
||||
godot --headless --script tests/TestMigrationCompatibility.gd
|
||||
|
||||
# Settings testing
|
||||
godot --headless --script tests/TestSettingsManager.gd
|
||||
|
||||
# Game manager testing
|
||||
godot --headless --script tests/TestGameManager.gd
|
||||
```
|
||||
|
||||
3. **Make changes following standards**:
|
||||
- Follow [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) patterns
|
||||
- Maintain backward compatibility where possible
|
||||
- Add input validation and error handling
|
||||
- Use proper memory management
|
||||
|
||||
4. **Run tests again** to verify no regressions:
|
||||
```bash
|
||||
# Run all relevant test suites
|
||||
python tools/run_development.py --test
|
||||
```
|
||||
|
||||
5. **Update documentation** if architecture changes:
|
||||
- Update [ARCHITECTURE.md](ARCHITECTURE.md) if design patterns change
|
||||
- Update [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) if new patterns emerge
|
||||
- Update [TESTING.md](TESTING.md) if new test protocols needed
|
||||
|
||||
## Testing Changes
|
||||
|
||||
### Manual Testing
|
||||
|
||||
```bash
|
||||
# Run project with F5 in Godot Editor
|
||||
# Test the following:
|
||||
|
||||
# Basic functionality
|
||||
# - F12 toggle for debug UI
|
||||
# - Scene transitions work correctly
|
||||
# - Settings persist across restarts
|
||||
# - Audio plays correctly
|
||||
|
||||
# Gameplay testing
|
||||
# - Match-3: Gem swapping, match detection, scoring
|
||||
# - Input: Keyboard (WASD/Arrows + Enter) and gamepad (D-pad + A)
|
||||
# - Visual feedback: Selection highlights, animations
|
||||
|
||||
# Mobile compatibility (if UI changes made)
|
||||
# - Touch input works
|
||||
# - UI scales correctly on different resolutions
|
||||
# - Performance is acceptable
|
||||
```
|
||||
|
||||
### Automated Testing
|
||||
|
||||
```bash
|
||||
# Logging system
|
||||
godot --headless --script tests/TestLogging.gd
|
||||
|
||||
# Save system (after SaveManager changes)
|
||||
godot --headless --script tests/test_checksum_issue.gd
|
||||
godot --headless --script tests/TestMigrationCompatibility.gd
|
||||
godot --headless --script tests/test_save_system_integration.gd
|
||||
|
||||
# Settings system
|
||||
godot --headless --script tests/TestSettingsManager.gd
|
||||
|
||||
# Game manager
|
||||
godot --headless --script tests/TestGameManager.gd
|
||||
|
||||
# Gameplay
|
||||
godot --headless --script tests/TestMatch3Gameplay.gd
|
||||
```
|
||||
|
||||
See [TESTING.md](TESTING.md) for complete testing protocols.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### When Stuck
|
||||
|
||||
1. **Check system design**: Read [ARCHITECTURE.md](ARCHITECTURE.md) for understanding
|
||||
2. **Review coding patterns**: Check [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for examples
|
||||
3. **Use debug system**: Press F12 to inspect current state
|
||||
4. **Search existing code**: Look for similar patterns in the codebase
|
||||
5. **Test understanding**: Create small experiments to verify assumptions
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Scene Loading Fails
|
||||
**Problem**: Scene transitions not working or crashes during scene change
|
||||
|
||||
**Solution**:
|
||||
- Check if using `GameManager.start_game_with_mode()` (correct)
|
||||
- Never use `get_tree().change_scene_to_file()` directly
|
||||
- Verify scene paths are correct constants in GameManager
|
||||
- Check for race conditions (multiple rapid scene changes)
|
||||
|
||||
**Example**:
|
||||
```gdscript
|
||||
# ✅ Correct
|
||||
GameManager.start_game_with_mode("match3")
|
||||
|
||||
# ❌ Wrong
|
||||
get_tree().change_scene_to_file("res://scenes/game/Game.tscn")
|
||||
```
|
||||
|
||||
#### Logs Not Appearing
|
||||
**Problem**: Debug messages not showing in console
|
||||
|
||||
**Solution**:
|
||||
- Use `DebugManager.log_*()` functions instead of `print()`
|
||||
- Include category for log organization
|
||||
- Check log level filtering (TRACE/DEBUG require debug mode)
|
||||
- Verify DebugManager is configured as autoload
|
||||
|
||||
**Example**:
|
||||
```gdscript
|
||||
# ✅ Correct
|
||||
DebugManager.log_info("Scene loaded", "GameManager")
|
||||
DebugManager.log_error("Failed to load resource", "AssetLoader")
|
||||
|
||||
# ❌ Wrong
|
||||
print("Scene loaded") # Use structured logging
|
||||
push_error("Failed") # Missing context and category
|
||||
```
|
||||
|
||||
#### Memory Crashes
|
||||
**Problem**: Crashes related to freed nodes or memory access
|
||||
|
||||
**Solution**:
|
||||
- Always use `queue_free()` instead of `free()`
|
||||
- Wait for frame completion after queueing nodes
|
||||
- Clear references before cleanup
|
||||
- Check for access to freed objects
|
||||
|
||||
**Example**:
|
||||
```gdscript
|
||||
# ✅ Correct
|
||||
for child in children_to_remove:
|
||||
child.queue_free()
|
||||
await get_tree().process_frame # Wait for cleanup
|
||||
|
||||
# ❌ Wrong
|
||||
for child in children_to_remove:
|
||||
child.free() # Immediate deletion causes crashes
|
||||
```
|
||||
|
||||
#### Tests Failing
|
||||
**Problem**: Test scripts fail or hang
|
||||
|
||||
**Solution**:
|
||||
- Run tests in sequence (avoid parallel execution)
|
||||
- Check autoload configuration in project.godot
|
||||
- Remove existing save files before testing SaveManager
|
||||
- Verify test file permissions
|
||||
- Check test timeout (should complete within seconds)
|
||||
|
||||
#### Input Not Working
|
||||
**Problem**: Keyboard/gamepad input not responding
|
||||
|
||||
**Solution**:
|
||||
- Verify input actions defined in project.godot
|
||||
- Check input map configuration
|
||||
- Ensure scene has input focus
|
||||
- Test with both keyboard and gamepad
|
||||
- Check for input event consumption by UI elements
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Before Committing
|
||||
|
||||
1. **Run all relevant tests**:
|
||||
```bash
|
||||
python tools/run_development.py --test
|
||||
```
|
||||
|
||||
2. **Check quality checklist**: [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md#code-quality-checklist)
|
||||
|
||||
3. **Verify no regressions**: Test existing functionality
|
||||
|
||||
4. **Update documentation**: If patterns or architecture changed
|
||||
|
||||
5. **Review changes**: Use `git diff` to review all modifications
|
||||
|
||||
### Code Review
|
||||
|
||||
- Focus on code clarity and maintainability
|
||||
- Check adherence to project patterns
|
||||
- Verify input validation and error handling
|
||||
- Ensure memory management is safe
|
||||
- Test the changes yourself before approving
|
||||
|
||||
### Performance Considerations
|
||||
|
||||
- Profile critical code paths
|
||||
- Use object pooling for frequently created nodes
|
||||
- Optimize expensive calculations
|
||||
- Cache node references with `@onready`
|
||||
- Avoid searching nodes repeatedly in `_process()`
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Godot GDScript Style Guide](https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/gdscript_styleguide.html)
|
||||
- [Godot Best Practices](https://docs.godotengine.org/en/stable/tutorials/best_practices/index.html)
|
||||
- [Godot Debugger](https://docs.godotengine.org/en/stable/tutorials/scripting/debug/overview_of_debugging_tools.html)
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) - System design and patterns
|
||||
- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - Coding standards
|
||||
- [TESTING.md](TESTING.md) - Testing procedures
|
||||
- [UI_COMPONENTS.md](UI_COMPONENTS.md) - Component API reference
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
Test scripts and utilities for validating Skelly project systems.
|
||||
|
||||
**Related Documentation**:
|
||||
- **Coding Standards**: [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - Follow coding standards when writing tests
|
||||
- **Architecture**: [ARCHITECTURE.md](ARCHITECTURE.md) - Understand system design before testing
|
||||
|
||||
## Overview
|
||||
|
||||
The `tests/` directory contains:
|
||||
@@ -11,7 +15,7 @@ The `tests/` directory contains:
|
||||
- Performance benchmarks
|
||||
- Debugging tools
|
||||
|
||||
> 📋 **File Naming**: All test files follow the [naming conventions](CODE_OF_CONDUCT.md#2-file-naming-standards) with PascalCase and "Test" prefix (e.g., `TestAudioManager.gd`).
|
||||
> 📋 **File Naming**: All test files follow the [naming conventions](CODE_OF_CONDUCT.md#naming-convention-quick-reference) with PascalCase and "Test" prefix (e.g., `TestAudioManager.gd`).
|
||||
|
||||
## Current Test Files
|
||||
|
||||
@@ -259,9 +263,15 @@ If tests take longer, investigate file I/O issues, memory leaks, infinite loops,
|
||||
## Contributing
|
||||
|
||||
When adding test files:
|
||||
1. Follow naming and structure conventions
|
||||
2. Update this README with test descriptions
|
||||
3. Ensure tests are self-contained and documented
|
||||
4. Test success and failure scenarios
|
||||
1. Follow [naming conventions](CODE_OF_CONDUCT.md#naming-convention-quick-reference)
|
||||
2. Follow [coding standards](CODE_OF_CONDUCT.md) for test code quality
|
||||
3. Understand [system architecture](ARCHITECTURE.md) before writing integration tests
|
||||
4. Update this file with test descriptions
|
||||
5. Ensure tests are self-contained and documented
|
||||
6. Test success and failure scenarios
|
||||
|
||||
This testing approach maintains code quality and provides validation tools for system changes.
|
||||
|
||||
**See Also**:
|
||||
- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md#code-quality-checklist) - Quality checklist before committing
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) - System design and architectural patterns
|
||||
|
||||
Reference in New Issue
Block a user