6 Commits

Author SHA1 Message Date
538459f323 codemap generation
Some checks failed
Continuous Integration / Code Formatting (push) Successful in 31s
Continuous Integration / Code Quality Check (push) Successful in 28s
Continuous Integration / Test Execution (push) Failing after 17s
Continuous Integration / CI Summary (push) Failing after 4s
2025-10-01 14:36:21 +04:00
550b2ac220 Fix more PascalCase inconsistencies 2025-10-01 12:07:54 +04:00
f6475f83f6 Add credits 2025-10-01 11:55:55 +04:00
35151cecf1 android sdk (2nd try) 2025-10-01 08:48:48 +04:00
dde7b98ed2 android sdk prepare 2025-09-30 23:44:06 +04:00
d1761a2464 Merge pull request 'building-adventures' (#12) from building-adventures into main
Some checks failed
Continuous Integration / Code Formatting (push) Successful in 27s
Continuous Integration / Code Quality Check (push) Successful in 29s
Continuous Integration / Test Execution (push) Failing after 17s
Continuous Integration / CI Summary (push) Failing after 4s
Build Game / Prepare Build (push) Successful in 6s
Build Game / Build Windows (push) Successful in 1m17s
Build Game / Build Linux (push) Successful in 1m14s
Build Game / Build Android (push) Failing after 3m2s
Build Game / Build Summary (push) Failing after 3s
Build Game / Setup Export Templates (push) Successful in 2m55s
Build Game / Build macOS (push) Failing after 1m1s
Reviewed-on: #12
2025-09-29 22:34:53 +02:00
31 changed files with 4285 additions and 557 deletions

View File

@@ -6,7 +6,8 @@
"Bash(godot:*)", "Bash(godot:*)",
"Bash(python:*)", "Bash(python:*)",
"Bash(git mv:*)", "Bash(git mv:*)",
"Bash(dir:*)" "Bash(dir:*)",
"Bash(yamllint:*)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []

View File

@@ -4,10 +4,13 @@ name: Build Game
# #
# Features: # Features:
# - Manual trigger with individual platform checkboxes # - Manual trigger with individual platform checkboxes
# - Configurable version override (defaults to auto-generated)
# - Configurable tool versions (Godot, Java, Android API, etc.)
# - Flexible runner OS selection
# - Tag-based automatic builds for releases # - Tag-based automatic builds for releases
# - Multi-platform builds (Windows, Linux, macOS, Android) # - Multi-platform builds (Windows, Linux, macOS, Android)
# - Artifact storage for one week # - Artifact storage for one week
# - Configurable build options # - Comprehensive build configuration options
on: on:
# Manual trigger with platform selection # Manual trigger with platform selection
@@ -33,6 +36,11 @@ on:
required: false required: false
default: false default: false
type: boolean type: boolean
version:
description: 'Version (leave empty for auto-generated)'
required: false
default: ''
type: string
build_type: build_type:
description: 'Build type' description: 'Build type'
required: true required: true
@@ -41,9 +49,25 @@ on:
options: options:
- release - release
- debug - debug
version_override: godot_version:
description: 'Override version (optional)' description: 'Godot version (leave empty for default)'
required: false required: false
default: ''
type: string
runner_os:
description: 'Runner OS (leave empty for default ubuntu-latest)'
required: false
default: ''
type: string
java_version:
description: 'Java version (leave empty for default)'
required: false
default: ''
type: string
android_api_level:
description: 'Android API level (leave empty for default)'
required: false
default: ''
type: string type: string
# Automatic trigger on git tags (for releases) # Automatic trigger on git tags (for releases)
@@ -53,15 +77,39 @@ on:
- 'release-*' # Release tags - 'release-*' # Release tags
env: env:
# Core Configuration
GODOT_VERSION: "4.4.1" GODOT_VERSION: "4.4.1"
PROJECT_NAME: "Skelly" PROJECT_NAME: "Skelly"
BUILD_DIR: "builds" BUILD_DIR: "builds"
DEFAULT_VERSION: "1.0.0-dev"
# GitHub Actions Versions
ACTIONS_CHECKOUT_VERSION: "v4"
ACTIONS_CACHE_VERSION: "v4"
ACTIONS_UPLOAD_ARTIFACT_VERSION: "v3"
ACTIONS_SETUP_JAVA_VERSION: "v4"
# Third-party Actions Versions
CHICKENSOFT_SETUP_GODOT_VERSION: "v1"
ANDROID_ACTIONS_SETUP_ANDROID_VERSION: "v3"
# Runner Configuration
RUNNER_OS: "ubuntu-latest"
# Java Configuration
JAVA_DISTRIBUTION: "temurin"
JAVA_VERSION: "17"
# Android Configuration
ANDROID_API_LEVEL: "33"
ANDROID_BUILD_TOOLS_VERSION: "33.0.0"
ANDROID_CMDLINE_TOOLS_VERSION: "latest"
jobs: jobs:
# Preparation job - determines build configuration # Preparation job - determines build configuration
prepare: prepare:
name: Prepare Build name: Prepare Build
runs-on: ubuntu-latest runs-on: ${{ env.RUNNER_OS }}
outputs: outputs:
platforms: ${{ steps.config.outputs.platforms }} platforms: ${{ steps.config.outputs.platforms }}
build_type: ${{ steps.config.outputs.build_type }} build_type: ${{ steps.config.outputs.build_type }}
@@ -70,13 +118,35 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Configure build parameters - name: Configure build parameters
id: config id: config
run: | run: |
# Override environment variables with user inputs if provided
if [[ -n "${{ github.event.inputs.godot_version }}" ]]; then
echo "GODOT_VERSION=${{ github.event.inputs.godot_version }}" >> $GITHUB_ENV
echo "🔧 Using custom Godot version: ${{ github.event.inputs.godot_version }}"
fi
if [[ -n "${{ github.event.inputs.runner_os }}" ]]; then
echo "RUNNER_OS=${{ github.event.inputs.runner_os }}" >> $GITHUB_ENV
echo "🔧 Using custom runner OS: ${{ github.event.inputs.runner_os }}"
fi
if [[ -n "${{ github.event.inputs.java_version }}" ]]; then
echo "JAVA_VERSION=${{ github.event.inputs.java_version }}" >> $GITHUB_ENV
echo "🔧 Using custom Java version: ${{ github.event.inputs.java_version }}"
fi
if [[ -n "${{ github.event.inputs.android_api_level }}" ]]; then
echo "ANDROID_API_LEVEL=${{ github.event.inputs.android_api_level }}" >> $GITHUB_ENV
echo "ANDROID_BUILD_TOOLS_VERSION=${{ github.event.inputs.android_api_level }}.0.0" >> $GITHUB_ENV
echo "🔧 Using custom Android API level: ${{ github.event.inputs.android_api_level }}"
fi
# Determine platforms to build # Determine platforms to build
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
# Build platforms array from individual checkboxes # Build platforms array from individual checkboxes
@@ -97,25 +167,37 @@ jobs:
platforms="${platforms%,}" platforms="${platforms%,}"
build_type="${{ github.event.inputs.build_type }}" build_type="${{ github.event.inputs.build_type }}"
version_override="${{ github.event.inputs.version_override }}" user_version="${{ github.event.inputs.version }}"
else else
# Tag-triggered build - build all platforms # Tag-triggered build - build all platforms
platforms="windows,linux,macos,android" platforms="windows,linux,macos,android"
build_type="release" build_type="release"
version_override="" user_version=""
fi fi
# Determine version # Determine version with improved logic
if [[ -n "$version_override" ]]; then if [[ -n "$user_version" ]]; then
version="$version_override" # User provided explicit version
version="$user_version"
echo "🏷️ Using user-specified version: $version"
elif [[ "${{ github.ref_type }}" == "tag" ]]; then elif [[ "${{ github.ref_type }}" == "tag" ]]; then
# Tag-triggered build - use tag name
version="${{ github.ref_name }}" version="${{ github.ref_name }}"
else echo "🏷️ Using git tag version: $version"
# Generate version from git info elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
# Manual dispatch without version - use default + git info
commit_short=$(git rev-parse --short HEAD) commit_short=$(git rev-parse --short HEAD)
branch_name="${{ github.ref_name }}" branch_name="${{ github.ref_name }}"
timestamp=$(date +%Y%m%d-%H%M) timestamp=$(date +%Y%m%d-%H%M)
version="${branch_name}-${commit_short}-${timestamp}" version="${{ env.DEFAULT_VERSION }}-${branch_name}-${commit_short}-${timestamp}"
echo "🏷️ Using auto-generated version: $version"
else
# Fallback for other triggers
commit_short=$(git rev-parse --short HEAD)
branch_name="${{ github.ref_name }}"
timestamp=$(date +%Y%m%d-%H%M)
version="${{ env.DEFAULT_VERSION }}-${branch_name}-${commit_short}-${timestamp}"
echo "🏷️ Using fallback version: $version"
fi fi
# Create artifact name # Create artifact name
@@ -131,17 +213,24 @@ jobs:
echo " Build Type: ${build_type}" echo " Build Type: ${build_type}"
echo " Version: ${version}" echo " Version: ${version}"
echo " Artifact: ${artifact_name}" echo " Artifact: ${artifact_name}"
echo ""
echo "🔧 Tool Versions:"
echo " Godot: ${GODOT_VERSION}"
echo " Runner OS: ${RUNNER_OS}"
echo " Java: ${JAVA_VERSION}"
echo " Android API: ${ANDROID_API_LEVEL}"
echo " Android Build Tools: ${ANDROID_BUILD_TOOLS_VERSION}"
# Setup export templates (shared across all platform builds) # Setup export templates (shared across all platform builds)
setup-templates: setup-templates:
name: Setup Export Templates name: Setup Export Templates
runs-on: ubuntu-latest runs-on: ${{ env.RUNNER_OS }}
needs: prepare needs: prepare
steps: steps:
- name: Cache export templates - name: Cache export templates
id: cache-templates id: cache-templates
uses: actions/cache@v4 uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with: with:
path: ~/.local/share/godot/export_templates path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }} key: godot-templates-${{ env.GODOT_VERSION }}
@@ -150,7 +239,7 @@ jobs:
- name: Setup Godot - name: Setup Godot
if: steps.cache-templates.outputs.cache-hit != 'true' if: steps.cache-templates.outputs.cache-hit != 'true'
uses: chickensoft-games/setup-godot@v1 uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with: with:
version: ${{ env.GODOT_VERSION }} version: ${{ env.GODOT_VERSION }}
use-dotnet: false use-dotnet: false
@@ -174,22 +263,22 @@ jobs:
# Windows build job # Windows build job
build-windows: build-windows:
name: Build Windows name: Build Windows
runs-on: ubuntu-latest runs-on: ${{ env.RUNNER_OS }}
needs: [prepare, setup-templates] needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'windows') if: contains(needs.prepare.outputs.platforms, 'windows')
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Godot - name: Setup Godot
uses: chickensoft-games/setup-godot@v1 uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with: with:
version: ${{ env.GODOT_VERSION }} version: ${{ env.GODOT_VERSION }}
use-dotnet: false use-dotnet: false
- name: Restore export templates cache - name: Restore export templates cache
uses: actions/cache@v4 uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with: with:
path: ~/.local/share/godot/export_templates path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }} key: godot-templates-${{ env.GODOT_VERSION }}
@@ -221,7 +310,7 @@ jobs:
fi fi
- name: Upload Windows build - name: Upload Windows build
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with: with:
name: ${{ needs.prepare.outputs.artifact_name }}-windows name: ${{ needs.prepare.outputs.artifact_name }}-windows
path: ${{ env.BUILD_DIR }}/skelly-windows-${{ needs.prepare.outputs.version }}.exe path: ${{ env.BUILD_DIR }}/skelly-windows-${{ needs.prepare.outputs.version }}.exe
@@ -231,22 +320,22 @@ jobs:
# Linux build job # Linux build job
build-linux: build-linux:
name: Build Linux name: Build Linux
runs-on: ubuntu-latest runs-on: ${{ env.RUNNER_OS }}
needs: [prepare, setup-templates] needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'linux') if: contains(needs.prepare.outputs.platforms, 'linux')
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Godot - name: Setup Godot
uses: chickensoft-games/setup-godot@v1 uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with: with:
version: ${{ env.GODOT_VERSION }} version: ${{ env.GODOT_VERSION }}
use-dotnet: false use-dotnet: false
- name: Restore export templates cache - name: Restore export templates cache
uses: actions/cache@v4 uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with: with:
path: ~/.local/share/godot/export_templates path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }} key: godot-templates-${{ env.GODOT_VERSION }}
@@ -281,7 +370,7 @@ jobs:
fi fi
- name: Upload Linux build - name: Upload Linux build
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with: with:
name: ${{ needs.prepare.outputs.artifact_name }}-linux name: ${{ needs.prepare.outputs.artifact_name }}-linux
path: ${{ env.BUILD_DIR }}/skelly-linux-${{ needs.prepare.outputs.version }}.x86_64 path: ${{ env.BUILD_DIR }}/skelly-linux-${{ needs.prepare.outputs.version }}.x86_64
@@ -291,22 +380,22 @@ jobs:
# macOS build job # macOS build job
build-macos: build-macos:
name: Build macOS name: Build macOS
runs-on: ubuntu-latest runs-on: ${{ env.RUNNER_OS }}
needs: [prepare, setup-templates] needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'macos') if: contains(needs.prepare.outputs.platforms, 'macos')
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Godot - name: Setup Godot
uses: chickensoft-games/setup-godot@v1 uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with: with:
version: ${{ env.GODOT_VERSION }} version: ${{ env.GODOT_VERSION }}
use-dotnet: false use-dotnet: false
- name: Restore export templates cache - name: Restore export templates cache
uses: actions/cache@v4 uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with: with:
path: ~/.local/share/godot/export_templates path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }} key: godot-templates-${{ env.GODOT_VERSION }}
@@ -338,7 +427,7 @@ jobs:
fi fi
- name: Upload macOS build - name: Upload macOS build
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with: with:
name: ${{ needs.prepare.outputs.artifact_name }}-macos name: ${{ needs.prepare.outputs.artifact_name }}-macos
path: ${{ env.BUILD_DIR }}/skelly-macos-${{ needs.prepare.outputs.version }}.zip path: ${{ env.BUILD_DIR }}/skelly-macos-${{ needs.prepare.outputs.version }}.zip
@@ -348,34 +437,93 @@ jobs:
# Android build job # Android build job
build-android: build-android:
name: Build Android name: Build Android
runs-on: ubuntu-latest runs-on: ${{ env.RUNNER_OS }}
needs: [prepare, setup-templates] needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'android') if: contains(needs.prepare.outputs.platforms, 'android')
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v4 uses: actions/setup-java@${{ env.ACTIONS_SETUP_JAVA_VERSION }}
with: with:
distribution: 'temurin' distribution: ${{ env.JAVA_DISTRIBUTION }}
java-version: '17' java-version: ${{ env.JAVA_VERSION }}
- name: Setup Android SDK - name: Setup Android SDK
uses: android-actions/setup-android@v3 uses: android-actions/setup-android@${{ env.ANDROID_ACTIONS_SETUP_ANDROID_VERSION }}
with: with:
api-level: 33 api-level: ${{ env.ANDROID_API_LEVEL }}
build-tools: 33.0.0 build-tools: ${{ env.ANDROID_BUILD_TOOLS_VERSION }}
- name: Install Android Build Tools
run: |
echo "🔧 Installing Android Build Tools..."
# Set Android environment variables
export ANDROID_HOME=${ANDROID_SDK_ROOT}
echo "ANDROID_HOME=${ANDROID_SDK_ROOT}" >> $GITHUB_ENV
echo "ANDROID_SDK_ROOT=${ANDROID_SDK_ROOT}" >> $GITHUB_ENV
# Install build-tools using sdkmanager
yes | ${ANDROID_SDK_ROOT}/cmdline-tools/${{ env.ANDROID_CMDLINE_TOOLS_VERSION }}/bin/sdkmanager --licenses || true
${ANDROID_SDK_ROOT}/cmdline-tools/${{ env.ANDROID_CMDLINE_TOOLS_VERSION }}/bin/sdkmanager "build-tools;${{ env.ANDROID_BUILD_TOOLS_VERSION }}"
${ANDROID_SDK_ROOT}/cmdline-tools/${{ env.ANDROID_CMDLINE_TOOLS_VERSION }}/bin/sdkmanager "platforms;android-${{ env.ANDROID_API_LEVEL }}"
- name: Verify Android SDK Configuration
run: |
echo "📱 Verifying Android SDK setup..."
echo "📱 Using API Level: ${{ env.ANDROID_API_LEVEL }}"
echo "📱 Using Build Tools: ${{ env.ANDROID_BUILD_TOOLS_VERSION }}"
# Verify SDK installation
echo "📱 Android SDK Location: ${ANDROID_SDK_ROOT}"
ls -la ${ANDROID_SDK_ROOT}/
echo "📱 Build Tools:"
ls -la ${ANDROID_SDK_ROOT}/build-tools/
echo "📱 Platforms:"
ls -la ${ANDROID_SDK_ROOT}/platforms/ || echo "No platforms directory"
# Verify apksigner exists
if [ -f "${ANDROID_SDK_ROOT}/build-tools/${{ env.ANDROID_BUILD_TOOLS_VERSION }}/apksigner" ]; then
echo "✅ apksigner found at ${ANDROID_SDK_ROOT}/build-tools/${{ env.ANDROID_BUILD_TOOLS_VERSION }}/apksigner"
else
echo "❌ apksigner not found!"
exit 1
fi
- name: Setup Godot - name: Setup Godot
uses: chickensoft-games/setup-godot@v1 uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with: with:
version: ${{ env.GODOT_VERSION }} version: ${{ env.GODOT_VERSION }}
use-dotnet: false use-dotnet: false
- name: Configure Godot for Android
run: |
echo "🎮 Configuring Godot for Android builds..."
# Create Godot config directory
mkdir -p ~/.config/godot
# Configure Android SDK path in Godot settings
cat > ~/.config/godot/editor_settings-4.4.tres << EOF
[gd_resource type="EditorSettings" format=3]
[resource]
export/android/android_sdk_path = "${ANDROID_SDK_ROOT}"
export/android/debug_keystore = ""
export/android/debug_keystore_user = "androiddebugkey"
export/android/debug_keystore_pass = "android"
export/android/force_system_user = false
export/android/timestamping_authority_url = ""
export/android/shutdown_adb_on_exit = true
EOF
echo "✅ Godot Android configuration complete"
- name: Restore export templates cache - name: Restore export templates cache
uses: actions/cache@v4 uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with: with:
path: ~/.local/share/godot/export_templates path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }} key: godot-templates-${{ env.GODOT_VERSION }}
@@ -395,8 +543,11 @@ jobs:
run: | run: |
echo "🏗️ Building Android APK..." echo "🏗️ Building Android APK..."
# Set ANDROID_HOME if not already set # Verify Android environment
export ANDROID_HOME=${ANDROID_HOME:-$ANDROID_SDK_ROOT} echo "📱 Android SDK: ${ANDROID_SDK_ROOT}"
echo "📱 API Level: ${{ env.ANDROID_API_LEVEL }}"
echo "📱 Build Tools Version: ${{ env.ANDROID_BUILD_TOOLS_VERSION }}"
echo "📱 Available Build Tools: $(ls ${ANDROID_SDK_ROOT}/build-tools/)"
godot --headless --verbose --export-${{ needs.prepare.outputs.build_type }} "Android" \ godot --headless --verbose --export-${{ needs.prepare.outputs.build_type }} "Android" \
${{ env.BUILD_DIR }}/skelly-android-${{ needs.prepare.outputs.version }}.apk ${{ env.BUILD_DIR }}/skelly-android-${{ needs.prepare.outputs.version }}.apk
@@ -415,7 +566,7 @@ jobs:
fi fi
- name: Upload Android build - name: Upload Android build
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with: with:
name: ${{ needs.prepare.outputs.artifact_name }}-android name: ${{ needs.prepare.outputs.artifact_name }}-android
path: ${{ env.BUILD_DIR }}/skelly-android-${{ needs.prepare.outputs.version }}.apk path: ${{ env.BUILD_DIR }}/skelly-android-${{ needs.prepare.outputs.version }}.apk
@@ -425,7 +576,7 @@ jobs:
# Summary job - creates release summary # Summary job - creates release summary
summary: summary:
name: Build Summary name: Build Summary
runs-on: ubuntu-latest runs-on: ${{ env.RUNNER_OS }}
needs: [prepare, setup-templates, build-windows, build-linux, build-macos, build-android] needs: [prepare, setup-templates, build-windows, build-linux, build-macos, build-android]
if: always() if: always()

7
.gitignore vendored
View File

@@ -7,7 +7,12 @@
*.import~ *.import~
test_results.txt test_results.txt
# Auto-generated code maps (regenerate with: python tools/generate_code_map.py)
.llm/
docs/generated/
# python # python
.venv .venv/
*.pyc *.pyc
.ruff/

32
.llm/README.md Normal file
View File

@@ -0,0 +1,32 @@
# Machine-Readable Code Maps
Auto-generated JSON files for LLM development assistance.
**⚠️ Git-ignored** - Regenerate with: `python tools/generate_code_map.py`
## Files
- `code_map_api.json` - Function signatures, parameters, return types, docstrings
- `code_map_architecture.json` - Autoloads, design patterns, system structure
- `code_map_flows.json` - Signal chains, scene transitions, call graphs
- `code_map_security.json` - Input validation, error handling patterns
- `code_map_assets.json` - Asset dependencies, licensing information
- `code_map_metadata.json` - Code quality metrics, test coverage, TODOs
## Diagrams
**Location**: `diagrams/` subdirectory (also copied to `docs/generated/diagrams/` for standalone viewing)
**Contents**:
- `*.mmd` - Mermaid source files (architecture, signal flows, scene hierarchy, dependencies)
- `*.png` - Rendered PNG diagrams
**Note**: Diagrams are automatically copied to `docs/generated/diagrams/` when generating documentation.
## Format
All JSON files are **minified** (no whitespace) for optimal LLM token efficiency.
## Usage
See root `CLAUDE.md` for integration with LLM development workflows.

233
CLAUDE.md
View File

@@ -1,9 +1,224 @@
- The documentation of the project is located in docs/ directory; # CLAUDE.md
- Get following files in context before doing anything else:
- docs\CLAUDE.md Guidance for Claude Code (claude.ai/code) when working with this repository.
- docs\CODE_OF_CONDUCT.md
- project.godot ## Required Context Files
- Use TDD methodology for development;
- Use static data types; Before doing anything else, get the following files in context:
- Keep documentation up to date; - **docs/ARCHITECTURE.md** - System design, autoloads, architectural patterns
- Always run tests `./tools/run_development.py --yaml --silent`; - **docs/CODE_OF_CONDUCT.md** - Coding standards, naming conventions, best practices
- **project.godot** - Input actions and autoload definitions
## Auto-Generated Machine-Readable Documentation
**⚠️ IMPORTANT**: Before starting development, generate fresh code maps for current codebase context:
```bash
python tools/generate_code_map.py
```
This generates machine-readable JSON maps optimized for LLM consumption in `.llm/` directory (git-ignored).
**When to use**:
- At the start of every development session
- After major refactoring or adding new files
- When you need current codebase structure/API reference
## Core Development Rules
- **Use TDD methodology** for development
- **Use static data types** in all GDScript code
- **Keep documentation up to date** when making changes
- **Always run tests**: `./tools/run_development.py --yaml --silent`
## Code Maps (LLM Development Workflow)
Machine-readable code intelligence for LLM-assisted development.
### Quick Reference: Which Map to Load?
| Task | Load This Map | Size | Contains |
|------|---------------|------|----------|
| Adding/modifying functions | `code_map_api.json` | ~47KB | Function signatures, parameters, return types |
| System architecture work | `code_map_architecture.json` | ~32KB | Autoloads, design patterns, structure |
| Signal/scene connections | `code_map_flows.json` | ~7KB | Signal chains, scene transitions |
| Input validation/errors | `code_map_security.json` | ~12KB | Validation patterns, error handling |
| Asset/resource management | `code_map_assets.json` | ~12KB | Dependencies, preloads, licensing |
| Code metrics/statistics | `code_map_metadata.json` | ~300B | Stats, complexity metrics |
### Generated Files (Git-Ignored)
**Location**: `.llm/` directory (automatically excluded from git)
**Format**: All JSON files are minified (no whitespace) for optimal LLM token efficiency.
**Total size**: ~110KB if loading all maps (recommended: load only what you need)
### Generating Code Maps
```bash
# Generate everything (default behavior - maps + diagrams + docs + metrics)
python tools/generate_code_map.py
# Generate only specific outputs
python tools/generate_code_map.py --diagrams # Diagrams only
python tools/generate_code_map.py --docs # Documentation only
python tools/generate_code_map.py --metrics # Metrics dashboard only
# Explicitly generate all (same as no arguments)
python tools/generate_code_map.py --all
# Via development workflow tool
python tools/run_development.py --codemap
# Custom output location (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
```
**New Features**:
- **Diagrams**: Auto-generated diagrams (architecture, signal flows, scene hierarchy, dependencies) rendered to PNG using matplotlib
- **Documentation**: Human-readable markdown docs with embedded diagrams (AUTOLOADS_API.md, SIGNALS_CATALOG.md, FUNCTION_INDEX.md, etc.)
- **Metrics**: Markdown dashboard with statistics charts and complexity analysis
### When to Regenerate
Regenerate code maps when:
- **Starting an LLM-assisted development session** - Get fresh context
- **After adding new files** - Include new code in maps
- **After major refactoring** - Update structure information
- **After changing autoloads** - Capture architectural changes
- **When onboarding new developers** - Provide comprehensive context
### LLM Development Workflow
1. **Generate maps**: `python tools/generate_code_map.py`
2. **Load relevant maps**: Choose based on your task
**For API/Function development**:
```
Load: .llm/code_map_api.json (~47KB)
Contains: All function signatures, parameters, return types, docstrings
```
**For architecture/system design**:
```
Load: .llm/code_map_architecture.json (~32KB)
Contains: Autoloads, design patterns, system structure
```
**For signal/scene work**:
```
Load: .llm/code_map_flows.json (~7KB)
Contains: Signal chains, scene transitions, connections
```
**For security/validation**:
```
Load: .llm/code_map_security.json (~12KB)
Contains: Input validation patterns, error handling
```
**For assets/resources**:
```
Load: .llm/code_map_assets.json (~12KB)
Contains: Asset dependencies, preloads, licensing
```
**For metrics/stats**:
```
Load: .llm/code_map_metadata.json (~300B)
Contains: Code statistics, complexity metrics
```
3. **Use selectively**:
- Load only maps relevant to current task
- Reduces token usage and improves focus
- Can always add more context later
- Total size if loading all: ~110KB minified JSON
## Essential Coding Patterns
### Scene Management
```gdscript
# ✅ Correct - Use GameManager
GameManager.start_game_with_mode("match3")
# ❌ Wrong - Never call directly
get_tree().change_scene_to_file("res://scenes/game/Game.tscn")
```
### Logging
```gdscript
# ✅ Correct - Use DebugManager with categories
DebugManager.log_info("Scene loaded successfully", "GameManager")
DebugManager.log_error("Failed to load resource", "AssetLoader")
# ❌ Wrong - Never use plain print/push_error
print("Scene loaded") # No structure, no category
push_error("Failed") # Missing context
```
### Memory Management
```gdscript
# ✅ Correct - Use queue_free()
for child in children_to_remove:
child.queue_free()
await get_tree().process_frame # Wait for cleanup
# ❌ Wrong - Never use free()
child.free() # Immediate deletion causes crashes
```
### Input Validation
```gdscript
# ✅ Correct - Validate all inputs
func set_volume(value: float) -> bool:
if value < 0.0 or value > 1.0:
DebugManager.log_error("Invalid volume: " + str(value), "Settings")
return false
# Process validated input
# ❌ Wrong - No validation
func set_volume(value: float):
volume = value # Could be negative or > 1.0
```
See [docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md) for complete coding standards.
## Quick Reference
- **Development commands**: See [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)
- **Testing protocols**: See [docs/TESTING.md](docs/TESTING.md)
- **Architecture patterns**: See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
- **Naming conventions**: See [docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md#naming-convention-quick-reference)
- **Quality checklist**: See [docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md#code-quality-checklist)
## Project Structure
```
skelly/
├── src/autoloads/ # Global manager singletons
├── scenes/game/gameplays/ # Gameplay mode implementations
├── scenes/ui/ # Menu scenes and components
├── assets/ # Audio, sprites, fonts (kebab-case)
├── data/ # Godot resource files (.tres)
├── docs/ # Documentation
├── tests/ # Test scripts
└── tools/ # Development tools
```
See [docs/MAP.md](docs/MAP.md) for complete file organization.
## Key Files to Understand
- `src/autoloads/GameManager.gd` - Scene transitions with race condition protection
- `src/autoloads/SaveManager.gd` - Save system with security features
- `src/autoloads/SettingsManager.gd` - Settings with input validation
- `src/autoloads/DebugManager.gd` - Unified logging and debug UI
- `scenes/game/Game.gd` - Main game scene, modular gameplay system
- `scenes/game/gameplays/Match3Gameplay.gd` - Match-3 implementation
- `project.godot` - Input actions and autoload definitions

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2025 Vladimir @nett00n Budylnikov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) 2025 Vladimir @nett00n Budylnikov
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

147
README.md Normal file
View File

@@ -0,0 +1,147 @@
# Skelly
Godot 4.4 mobile game project with multiple gameplay modes. Features modular gameplay system with match-3 puzzle (implemented) and planned clickomania mode.
**Tech Stack**: Godot 4.4, GDScript
**Target Platform**: Mobile (Android/iOS)
**Architecture**: See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for detailed system design
## Quick Start
### Running the Project
1. **Open in Godot Editor**: Import `project.godot`
2. **Run**: Press `F5` or click the "Play" button
3. **Debug UI**: Press `F12` in-game to toggle debug panels
### Development Commands
```bash
# Generate code maps for LLM development
python tools/generate_code_map.py
# Run tests
godot --headless --script tests/TestLogging.gd
# Development workflow helper
python tools/run_development.py --codemap # Generate code maps
python tools/run_development.py --test # Run tests
```
See [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) for complete development workflows and commands.
## Project Structure
```
skelly/
├── src/autoloads/ # Global manager singletons (GameManager, SaveManager, etc.)
├── scenes/
│ ├── game/gameplays/ # Gameplay mode implementations (Match3, Clickomania)
│ ├── ui/components/ # Reusable UI components (ValueStepper, etc.)
│ └── ui/ # Menu scenes (MainMenu, SettingsMenu)
├── assets/ # Audio, sprites, fonts (kebab-case naming)
├── data/ # Godot resource files (.tres)
├── docs/ # Documentation (architecture, coding standards, testing)
├── tests/ # Test scripts for system validation
├── tools/ # Development tools (code map generator, etc.)
└── localization/ # Translation files (English, Russian)
```
See [docs/MAP.md](docs/MAP.md) for complete file organization details.
## Documentation
- **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** - System design, autoloads, architectural patterns
- **[docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md)** - Coding standards, naming conventions, best practices
- **[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)** - Development workflows and commands
- **[docs/TESTING.md](docs/TESTING.md)** - Testing procedures and protocols
- **[docs/UI_COMPONENTS.md](docs/UI_COMPONENTS.md)** - UI component API reference
- **[docs/MAP.md](docs/MAP.md)** - Complete project structure
## Features
- **Modular Gameplay System**: Easy to add new game modes
- **Match-3 Puzzle**: Fully implemented with keyboard/gamepad support
- **Settings Management**: Volume, language, difficulty with input validation
- **Save System**: Secure save/load with tamper detection and auto-repair
- **Debug System**: F12 toggle for debug panels on all major scenes
- **Localization**: Multi-language support (English, Russian)
- **Audio System**: Music and SFX with bus-based volume control
## Contributing
### Before Making Changes
1. Read [docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md) for coding standards
2. Review [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for system design
3. Check [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) for workflows
4. Follow the [quality checklist](docs/CODE_OF_CONDUCT.md#code-quality-checklist)
### Core Development Rules
- **Scene transitions**: Use `GameManager.start_game_with_mode()` - never call `get_tree().change_scene_to_file()` directly
- **Logging**: Use `DebugManager.log_*()` functions with categories - never use plain `print()` or `push_error()`
- **Memory management**: Always use `queue_free()` instead of `free()`
- **Input validation**: Validate all user inputs with type/bounds/null checking
- **TDD methodology**: Write tests for new functionality
See [docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md) for complete standards.
### Asset Management
- **Document every asset** in `assets/sources.yaml` before committing
- Include source URL, license, attribution, modifications, and usage
- Verify license compatibility (CC BY, CC0, Public Domain, etc.)
- Commit asset files and sources.yaml together
See [docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md#asset-management) for detailed workflow.
### Testing
```bash
# Manual testing
# F5 in Godot Editor - Run project
# F12 in-game - Toggle debug UI
# Automated testing
godot --headless --script tests/TestLogging.gd
godot --headless --script tests/test_checksum_issue.gd
```
See [docs/TESTING.md](docs/TESTING.md) for complete testing procedures.
## Development Highlights
### Autoload System
Global singleton services providing core functionality:
- **GameManager**: Scene transitions with race condition protection
- **SaveManager**: Secure save/load with tamper detection
- **SettingsManager**: Settings persistence with input validation
- **DebugManager**: Unified logging and debug UI
- **AudioManager**: Music and SFX playback
- **LocalizationManager**: Language switching
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#autoload-system) for details.
### Code Quality Standards
- **Memory Safety**: `queue_free()` pattern for safe node cleanup
- **Error Handling**: Comprehensive error handling with fallbacks
- **Race Condition Protection**: State flags for async operations
- **Instance-Based Architecture**: No global static state
- **Input Validation**: Complete validation coverage
See [docs/CODE_OF_CONDUCT.md](docs/CODE_OF_CONDUCT.md#code-quality-checklist) for complete quality standards.
## 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)
- Project documentation in `docs/` directory
## License
GPLv3.0
See [LICENSE](LICENSE) file for more information

424
docs/ARCHITECTURE.md Normal file
View 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

View File

@@ -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
```

View File

@@ -208,6 +208,89 @@ func load_scene(path: String) -> void:
get_tree().change_scene_to_packed(packed_scene) 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 ## Git Workflow
### Commit Guidelines ### Commit Guidelines

View File

@@ -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
View 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

View File

@@ -90,7 +90,7 @@ game.tscn (Gameplay Container)
``` ```
### Game Flow ### Game Flow
1. **Main Scene** (`scenes/main/main.tscn` + `Main.gd`) 1. **Main Scene** (`scenes/main/Main.tscn` + `Main.gd`)
- Application entry point - Application entry point
- Manages splash screen - Manages splash screen
- Transitions to main menu - Transitions to main menu
@@ -112,7 +112,7 @@ game.tscn (Gameplay Container)
- Audio volume controls - Audio volume controls
- Connected to SettingsManager and AudioManager - Connected to SettingsManager and AudioManager
5. **Game Scene** (`scenes/game/game.tscn` + `game.gd`) 5. **Game Scene** (`scenes/game/Game.tscn` + `Game.gd`)
- Main gameplay container with modular gameplay system - Main gameplay container with modular gameplay system
- Dynamic loading of gameplay modes into GameplayContainer - Dynamic loading of gameplay modes into GameplayContainer
- Global score management and display - Global score management and display
@@ -145,7 +145,7 @@ scenes/ui/
The game now uses a modular gameplay architecture where different game modes can be dynamically loaded into the main game scene. The game now uses a modular gameplay architecture where different game modes can be dynamically loaded into the main game scene.
### Gameplay Architecture ### Gameplay Architecture
- **Main Game Scene** (`scenes/game/game.gd`) - Container and coordinator - **Main Game Scene** (`scenes/game/Game.gd`) - Container and coordinator
- **Gameplay Directory** (`scenes/game/gameplays/`) - Individual gameplay implementations - **Gameplay Directory** (`scenes/game/gameplays/`) - Individual gameplay implementations
- **Dynamic Loading** - Gameplay scenes loaded at runtime based on mode selection - **Dynamic Loading** - Gameplay scenes loaded at runtime based on mode selection
- **Signal-based Communication** - Gameplays communicate with main scene via signals - **Signal-based Communication** - Gameplays communicate with main scene via signals
@@ -168,7 +168,7 @@ The game now uses a modular gameplay architecture where different game modes can
- Smooth tile position animations with Tween - Smooth tile position animations with Tween
- Cursor-based navigation with visual highlighting and bounds checking - Cursor-based navigation with visual highlighting and bounds checking
2. **Tile System** (`scenes/game/gameplays/tile.gd` + `Tile.tscn`) 2. **Tile System** (`scenes/game/gameplays/Tile.gd` + `Tile.tscn`)
- Tile behavior with instance-based architecture (no global state) - Tile behavior with instance-based architecture (no global state)
- Gem type management with validation and bounds checking - Gem type management with validation and bounds checking
- Visual representation with scaling and color - Visual representation with scaling and color

View File

@@ -2,6 +2,10 @@
Test scripts and utilities for validating Skelly project systems. 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 ## Overview
The `tests/` directory contains: The `tests/` directory contains:
@@ -11,7 +15,7 @@ The `tests/` directory contains:
- Performance benchmarks - Performance benchmarks
- Debugging tools - 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 ## Current Test Files
@@ -259,9 +263,15 @@ If tests take longer, investigate file I/O issues, memory leaks, infinite loops,
## Contributing ## Contributing
When adding test files: When adding test files:
1. Follow naming and structure conventions 1. Follow [naming conventions](CODE_OF_CONDUCT.md#naming-convention-quick-reference)
2. Update this README with test descriptions 2. Follow [coding standards](CODE_OF_CONDUCT.md) for test code quality
3. Ensure tests are self-contained and documented 3. Understand [system architecture](ARCHITECTURE.md) before writing integration tests
4. Test success and failure scenarios 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. 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

View File

@@ -11,7 +11,7 @@ config_version=5
[application] [application]
config/name="Skelly" config/name="Skelly"
run/main_scene="res://scenes/main/main.tscn" run/main_scene="res://scenes/main/Main.tscn"
config/features=PackedStringArray("4.4", "Mobile") config/features=PackedStringArray("4.4", "Mobile")
config/icon="res://icon.svg" config/icon="res://icon.svg"
boot_splash/handheld/orientation=0 boot_splash/handheld/orientation=0
@@ -224,3 +224,4 @@ locale/translations=PackedStringArray("res://localization/MainStrings.en.transla
textures/canvas_textures/default_texture_filter=0 textures/canvas_textures/default_texture_filter=0
renderer/rendering_method="gl_compatibility" renderer/rendering_method="gl_compatibility"
renderer/rendering_method.mobile="gl_compatibility" renderer/rendering_method.mobile="gl_compatibility"
textures/vram_compression/import_etc2_astc=true

View File

@@ -1,4 +1,10 @@
setuptools<81 aiofiles>=23
gdtoolkit==4 gdtoolkit>=4
aiofiles>=23.0.0 PyYAML>=6.0
ruff>=0.1.0 ruff>=0.1.0
setuptools<81
yamllint>=1
# Diagram generation and rendering
matplotlib>=3.8.0 # Chart and graph generation
pillow>=10.0.0 # Image processing and manipulation

View File

@@ -1,4 +1,4 @@
[gd_scene load_steps=4 format=3 uid="uid://8c2w55brpwmm"] [gd_scene load_steps=4 format=3 uid="uid://dmctbuggudsx2"]
[ext_resource type="Script" uid="uid://bs4veuda3h358" path="res://scenes/game/game.gd" id="1_uwrxv"] [ext_resource type="Script" uid="uid://bs4veuda3h358" path="res://scenes/game/game.gd" id="1_uwrxv"]
[ext_resource type="PackedScene" path="res://scenes/ui/DebugToggle.tscn" id="3_debug"] [ext_resource type="PackedScene" path="res://scenes/ui/DebugToggle.tscn" id="3_debug"]

View File

@@ -470,7 +470,7 @@ func regenerate_grid():
# More robust tile detection # More robust tile detection
if child.has_method("get_script") and child.get_script(): if child.has_method("get_script") and child.get_script():
var script_path = child.get_script().resource_path var script_path = child.get_script().resource_path
if script_path == "res://scenes/game/gameplays/tile.gd": if script_path == "res://scenes/game/gameplays/Tile.gd":
children_to_remove.append(child) children_to_remove.append(child)
removed_count += 1 removed_count += 1
elif "grid_position" in child: # Fallback detection elif "grid_position" in child: # Fallback detection
@@ -1084,7 +1084,7 @@ func _restore_grid_from_layout(grid_layout: Array, active_gems: Array[int]) -> v
for child in get_children(): for child in get_children():
if child.has_method("get_script") and child.get_script(): if child.has_method("get_script") and child.get_script():
var script_path = child.get_script().resource_path var script_path = child.get_script().resource_path
if script_path == "res://scenes/game/gameplays/tile.gd": if script_path == "res://scenes/game/gameplays/Tile.gd":
all_tile_children.append(child) all_tile_children.append(child)
DebugManager.log_debug( DebugManager.log_debug(

View File

@@ -94,7 +94,7 @@ static func restore_grid_from_layout(
for child in match3_node.get_children(): for child in match3_node.get_children():
if child.has_method("get_script") and child.get_script(): if child.has_method("get_script") and child.get_script():
var script_path = child.get_script().resource_path var script_path = child.get_script().resource_path
if script_path == "res://scenes/game/gameplays/tile.gd": if script_path == "res://scenes/game/gameplays/Tile.gd":
all_tile_children.append(child) all_tile_children.append(child)
# Remove all found tile children # Remove all found tile children

View File

@@ -1,6 +1,6 @@
[gd_scene load_steps=2 format=3 uid="uid://bnk1gqom3oi6q"] [gd_scene load_steps=2 format=3 uid="uid://bnk1gqom3oi6q"]
[ext_resource type="Script" path="res://scenes/game/gameplays/tile.gd" id="1_tile_script"] [ext_resource type="Script" path="res://scenes/game/gameplays/Tile.gd" id="1_tile_script"]
[node name="Tile" type="Node2D"] [node name="Tile" type="Node2D"]
script = ExtResource("1_tile_script") script = ExtResource("1_tile_script")

View File

@@ -1,4 +1,4 @@
[gd_scene load_steps=5 format=3 uid="uid://bwvq7u0mv5dku"] [gd_scene load_steps=5 format=3 uid="uid://podhr4b5aq2v"]
[ext_resource type="Script" uid="uid://rvuchiy0guv3" path="res://scenes/main/Main.gd" id="1_0wfyh"] [ext_resource type="Script" uid="uid://rvuchiy0guv3" path="res://scenes/main/Main.gd" id="1_0wfyh"]
[ext_resource type="PackedScene" uid="uid://gbe1jarrwqsi" path="res://scenes/main/SplashScreen.tscn" id="1_o5qli"] [ext_resource type="PackedScene" uid="uid://gbe1jarrwqsi" path="res://scenes/main/SplashScreen.tscn" id="1_o5qli"]

242
scenes/ui/Credits.gd Normal file
View File

@@ -0,0 +1,242 @@
extends Control
signal back_pressed
const YAML_SOURCES: Array[String] = [
"res://assets/sources.yaml",
# Future sources:
# "res://assets/audio/audio-sources.yaml",
# "res://assets/sprites/sprite-sources.yaml",
]
@onready var scroll_container: ScrollContainer = $MarginContainer/VBoxContainer/ScrollContainer
@onready var credits_text: RichTextLabel = $MarginContainer/VBoxContainer/ScrollContainer/CreditsText
@onready var back_button: Button = $MarginContainer/VBoxContainer/BackButton
func _ready() -> void:
DebugManager.log_info("Credits scene ready", "Credits")
_load_and_display_credits()
back_button.grab_focus()
DebugManager.log_info("Back button focused for gamepad support", "Credits")
func _load_and_display_credits() -> void:
"""Load credits from multiple YAML files and display formatted output"""
var all_credits_data: Dictionary = {}
# Load all YAML source files
for yaml_path in YAML_SOURCES:
var yaml_data: Dictionary = _load_yaml_file(yaml_path)
if not yaml_data.is_empty():
_merge_credits_data(all_credits_data, yaml_data)
# Generate and display formatted credits
_display_formatted_credits(all_credits_data)
func _load_yaml_file(yaml_path: String) -> Dictionary:
"""Load and parse a YAML file into a dictionary structure"""
var file := FileAccess.open(yaml_path, FileAccess.READ)
if not file:
DebugManager.log_warn("Could not open YAML file: %s" % yaml_path, "Credits")
return {}
var content: String = file.get_as_text()
file.close()
DebugManager.log_info("Loaded YAML file: %s" % yaml_path, "Credits")
return _parse_yaml_content(content)
func _parse_yaml_content(yaml_content: String) -> Dictionary:
"""Parse YAML content into structured dictionary"""
var result: Dictionary = {}
var lines: Array = yaml_content.split("\n")
var current_section: String = ""
var current_subsection: String = ""
var current_asset: String = ""
var current_asset_data: Dictionary = {}
for line in lines:
var trimmed: String = line.strip_edges()
# Skip comments and empty lines
if trimmed.is_empty() or trimmed.begins_with("#"):
continue
# Top-level section (audio, sprites, textures, etc.)
if not line.begins_with(" ") and not line.begins_with("\t") and trimmed.ends_with(":"):
if current_asset and not current_asset_data.is_empty():
_store_asset_data(
result, current_section, current_subsection, current_asset, current_asset_data
)
current_section = trimmed.trim_suffix(":")
current_subsection = ""
current_asset = ""
current_asset_data = {}
if not result.has(current_section):
result[current_section] = {}
# Subsection (music, sfx, characters, etc.)
elif line.begins_with(" ") and not line.begins_with(" ") and trimmed.ends_with(":"):
if current_asset and not current_asset_data.is_empty():
_store_asset_data(
result, current_section, current_subsection, current_asset, current_asset_data
)
current_subsection = trimmed.trim_suffix(":")
current_asset = ""
current_asset_data = {}
if current_section and not result[current_section].has(current_subsection):
result[current_section][current_subsection] = {}
# Asset name
elif trimmed.begins_with('"') and trimmed.contains('":'):
if current_asset and not current_asset_data.is_empty():
_store_asset_data(
result, current_section, current_subsection, current_asset, current_asset_data
)
var parts: Array = trimmed.split('"')
current_asset = parts[1] if parts.size() > 1 else ""
current_asset_data = {}
# Asset properties
elif ":" in trimmed:
var parts: Array = trimmed.split(":", false, 1)
if parts.size() == 2:
var key: String = parts[0].strip_edges()
var value: String = parts[1].strip_edges().trim_prefix('"').trim_suffix('"')
if value and value != '""':
current_asset_data[key] = value
# Store last asset
if current_asset and not current_asset_data.is_empty():
_store_asset_data(
result, current_section, current_subsection, current_asset, current_asset_data
)
return result
func _store_asset_data(
result: Dictionary, section: String, subsection: String, asset: String, data: Dictionary
) -> void:
"""Store parsed asset data into result dictionary"""
if not section or not asset:
return
if subsection:
if not result[section].has(subsection):
result[section][subsection] = {}
result[section][subsection][asset] = data
else:
result[section][asset] = data
func _merge_credits_data(target: Dictionary, source: Dictionary) -> void:
"""Merge source credits data into target dictionary"""
for section in source:
if not target.has(section):
target[section] = {}
for subsection in source[section]:
if source[section][subsection] is Dictionary:
if not target[section].has(subsection):
target[section][subsection] = {}
for asset in source[section][subsection]:
target[section][subsection][asset] = source[section][subsection][asset]
func _display_formatted_credits(credits_data: Dictionary) -> void:
"""Generate BBCode formatted credits from parsed data"""
if not credits_text:
DebugManager.log_error("Credits text node is null, cannot display credits", "Credits")
return
var credits_bbcode: String = "[center][b][font_size=32]CREDITS[/font_size][/b][/center]\n\n"
# Audio section
if credits_data.has("audio"):
credits_bbcode += "[b][font_size=24]AUDIO[/font_size][/b]\n\n"
credits_bbcode += _format_section(credits_data["audio"])
# Sprites section
if credits_data.has("sprites"):
credits_bbcode += "[b][font_size=24]GRAPHICS[/font_size][/b]\n\n"
credits_bbcode += _format_section(credits_data["sprites"])
# Textures section
if credits_data.has("textures"):
if not credits_data.has("sprites"):
credits_bbcode += "[b][font_size=24]GRAPHICS[/font_size][/b]\n\n"
credits_bbcode += _format_section(credits_data["textures"])
# Game development credits
credits_bbcode += "[b][font_size=24]GAME DEVELOPMENT[/font_size][/b]\n\n"
credits_bbcode += "[i]Developed with Godot Engine 4.4[/i]\n"
credits_bbcode += "[url=https://godotengine.org]https://godotengine.org[/url]\n\n"
credits_text.bbcode_enabled = true
credits_text.text = credits_bbcode
DebugManager.log_info("Credits displayed successfully", "Credits")
func _format_section(section_data: Dictionary) -> String:
"""Format a credits section with subsections and assets"""
var result: String = ""
for subsection in section_data:
if section_data[subsection] is Dictionary:
# Add subsection header
var subsection_title: String = subsection.capitalize()
result += "[i]" + subsection_title + "[/i]\n"
# Add assets in this subsection
for asset in section_data[subsection]:
var asset_data: Dictionary = section_data[subsection][asset]
result += _format_asset(asset_data)
result += "\n"
return result
func _format_asset(asset_data: Dictionary) -> String:
"""Format a single asset's credit information"""
var result: String = ""
if asset_data.has("attribution") and asset_data["attribution"]:
result += "[b]" + asset_data["attribution"] + "[/b]\n"
if asset_data.has("license") and asset_data["license"]:
result += "License: " + asset_data["license"] + "\n"
if asset_data.has("source") and asset_data["source"]:
result += "[url=" + asset_data["source"] + "]Source[/url]\n"
if result:
result += "\n"
return result
func _on_back_button_pressed() -> void:
AudioManager.play_ui_click()
DebugManager.log_info("Back button pressed", "Credits")
GameManager.exit_to_main_menu()
func _input(event: InputEvent) -> void:
if event.is_action_pressed("ui_back") or event.is_action_pressed("action_east"):
_on_back_button_pressed()
elif event.is_action_pressed("move_up") or event.is_action_pressed("ui_up"):
_scroll_credits(-50.0)
elif event.is_action_pressed("move_down") or event.is_action_pressed("ui_down"):
_scroll_credits(50.0)
func _scroll_credits(amount: float) -> void:
"""Scroll the credits by the specified amount"""
var current_scroll: float = scroll_container.scroll_vertical
scroll_container.scroll_vertical = int(current_scroll + amount)
DebugManager.log_debug("Scrolled credits to: %d" % scroll_container.scroll_vertical, "Credits")

1
scenes/ui/Credits.gd.uid Normal file
View File

@@ -0,0 +1 @@
uid://cwygtx0r6gdt1

52
scenes/ui/Credits.tscn Normal file
View File

@@ -0,0 +1,52 @@
[gd_scene load_steps=2 format=3 uid="uid://cspq2y7mvjxn5"]
[ext_resource type="Script" path="res://scenes/ui/Credits.gd" id="1_credits"]
[node name="Credits" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_credits")
[node name="MarginContainer" type="MarginContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 40
theme_override_constants/margin_top = 40
theme_override_constants/margin_right = 40
theme_override_constants/margin_bottom = 40
[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer"]
layout_mode = 2
[node name="ScrollContainer" type="ScrollContainer" parent="MarginContainer/VBoxContainer"]
layout_mode = 2
size_flags_vertical = 3
horizontal_scroll_mode = 0
follow_focus = true
[node name="CreditsText" type="RichTextLabel" parent="MarginContainer/VBoxContainer/ScrollContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
bbcode_enabled = true
text = "[center][b]CREDITS[/b][/center]
Loading credits..."
fit_content = true
scroll_active = false
[node name="BackButton" type="Button" parent="MarginContainer/VBoxContainer"]
custom_minimum_size = Vector2(150, 50)
layout_mode = 2
size_flags_horizontal = 4
text = "Back"
[connection signal="pressed" from="MarginContainer/VBoxContainer/BackButton" to="." method="_on_back_button_pressed"]

View File

@@ -31,6 +31,12 @@ func _on_settings_button_pressed() -> void:
open_settings.emit() open_settings.emit()
func _on_credits_button_pressed() -> void:
AudioManager.play_ui_click()
DebugManager.log_info("Credits pressed", "MainMenu")
GameManager.show_credits()
func _on_exit_button_pressed() -> void: func _on_exit_button_pressed() -> void:
AudioManager.play_ui_click() AudioManager.play_ui_click()
DebugManager.log_info("Exit pressed", "MainMenu") DebugManager.log_info("Exit pressed", "MainMenu")
@@ -43,6 +49,7 @@ func _setup_menu_navigation() -> void:
menu_buttons.append($MenuContainer/NewGameButton) menu_buttons.append($MenuContainer/NewGameButton)
menu_buttons.append($MenuContainer/SettingsButton) menu_buttons.append($MenuContainer/SettingsButton)
menu_buttons.append($MenuContainer/CreditsButton)
menu_buttons.append($MenuContainer/ExitButton) menu_buttons.append($MenuContainer/ExitButton)
for button in menu_buttons: for button in menu_buttons:

View File

@@ -111,6 +111,10 @@ text = "New Game"
layout_mode = 2 layout_mode = 2
text = "Settings" text = "Settings"
[node name="CreditsButton" type="Button" parent="MenuContainer"]
layout_mode = 2
text = "Credits"
[node name="ExitButton" type="Button" parent="MenuContainer"] [node name="ExitButton" type="Button" parent="MenuContainer"]
layout_mode = 2 layout_mode = 2
text = "Exit" text = "Exit"
@@ -120,4 +124,5 @@ layout_mode = 1
[connection signal="pressed" from="MenuContainer/NewGameButton" to="." method="_on_new_game_button_pressed"] [connection signal="pressed" from="MenuContainer/NewGameButton" to="." method="_on_new_game_button_pressed"]
[connection signal="pressed" from="MenuContainer/SettingsButton" to="." method="_on_settings_button_pressed"] [connection signal="pressed" from="MenuContainer/SettingsButton" to="." method="_on_settings_button_pressed"]
[connection signal="pressed" from="MenuContainer/CreditsButton" to="." method="_on_credits_button_pressed"]
[connection signal="pressed" from="MenuContainer/ExitButton" to="." method="_on_exit_button_pressed"] [connection signal="pressed" from="MenuContainer/ExitButton" to="." method="_on_exit_button_pressed"]

View File

@@ -6,8 +6,9 @@
extends Node extends Node
const GAME_SCENE_PATH := "res://scenes/game/game.tscn" const GAME_SCENE_PATH := "res://scenes/game/Game.tscn"
const MAIN_SCENE_PATH := "res://scenes/main/main.tscn" const MAIN_SCENE_PATH := "res://scenes/main/Main.tscn"
const CREDITS_SCENE_PATH := "res://scenes/ui/Credits.tscn"
var pending_gameplay_mode: String = "match3" var pending_gameplay_mode: String = "match3"
var is_changing_scene: bool = false var is_changing_scene: bool = false
@@ -97,6 +98,41 @@ func save_game() -> void:
DebugManager.log_info("Game saved with score: %d" % current_score, "GameManager") DebugManager.log_info("Game saved with score: %d" % current_score, "GameManager")
func show_credits() -> void:
"""Show credits scene with race condition protection"""
# Prevent concurrent scene changes
if is_changing_scene:
DebugManager.log_warn(
"Scene change already in progress, ignoring show credits request", "GameManager"
)
return
is_changing_scene = true
DebugManager.log_info("Attempting to show credits scene", "GameManager")
var packed_scene := load(CREDITS_SCENE_PATH)
if not packed_scene or not packed_scene is PackedScene:
DebugManager.log_error(
"Failed to load Credits scene at: %s" % CREDITS_SCENE_PATH, "GameManager"
)
is_changing_scene = false
return
var result = get_tree().change_scene_to_packed(packed_scene)
if result != OK:
DebugManager.log_error(
"Failed to change to credits scene (Error code: %d)" % result, "GameManager"
)
is_changing_scene = false
return
DebugManager.log_info("Successfully loaded credits scene", "GameManager")
# Wait for scene to be ready, then mark scene change as complete
await get_tree().process_frame
is_changing_scene = false
func exit_to_main_menu() -> void: func exit_to_main_menu() -> void:
"""Exit to main menu with race condition protection""" """Exit to main menu with race condition protection"""
# Prevent concurrent scene changes # Prevent concurrent scene changes

View File

@@ -148,8 +148,8 @@ func test_critical_scenes():
# Define critical scenes that must work # Define critical scenes that must work
var critical_scenes = [ var critical_scenes = [
"res://scenes/main/main.tscn", "res://scenes/main/Main.tscn",
"res://scenes/game/game.tscn", "res://scenes/game/Game.tscn",
"res://scenes/ui/MainMenu.tscn", "res://scenes/ui/MainMenu.tscn",
"res://scenes/game/gameplays/Match3Gameplay.tscn" "res://scenes/game/gameplays/Match3Gameplay.tscn"
] ]

1662
tools/generate_code_map.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1302,6 +1302,49 @@ async def run_validate_async(
) )
def run_codemap(
project_root: Path, silent: bool = False, yaml_output: bool = False
) -> Tuple[bool, Dict]:
"""Generate code map - JSON format only"""
if not silent and not yaml_output:
print_header("🗺️ Code Map Generator")
try:
result = run_command(
["python", "tools/generate_code_map.py"],
project_root,
timeout=120,
)
success = result.returncode == 0
if not yaml_output:
if success:
if not silent:
print(result.stdout)
msg = "✅ Code maps generated in .llm/ directory"
colored_msg = Colors.colorize(msg, Colors.GREEN + Colors.BOLD)
print(colored_msg)
else:
msg = "❌ Code map generation failed"
colored_msg = Colors.colorize(msg, Colors.RED + Colors.BOLD)
print(colored_msg)
if result.stderr:
print(Colors.colorize(result.stderr, Colors.RED))
stats = {"Success": success}
if yaml_output:
output_yaml_results("codemap", stats, success)
return success, stats
except Exception as e:
if not silent and not yaml_output:
print(f"❌ ERROR: {e}")
return False, {}
def run_naming( def run_naming(
project_root: Path, silent: bool = False, yaml_output: bool = False project_root: Path, silent: bool = False, yaml_output: bool = False
) -> Tuple[bool, Dict]: ) -> Tuple[bool, Dict]:
@@ -1905,6 +1948,10 @@ def run_workflow(
"📝 Naming convention check (PascalCase)", "📝 Naming convention check (PascalCase)",
lambda root: run_naming(root, silent, yaml_output), lambda root: run_naming(root, silent, yaml_output),
), ),
"codemap": (
"🗺️ Code map generation (yaml)",
lambda root: run_codemap(root, silent, yaml_output),
),
} }
if not silent: if not silent:
@@ -2060,6 +2107,12 @@ async def run_workflow_async(
root, silent, yaml_output root, silent, yaml_output
), # Using sync version - lightweight ), # Using sync version - lightweight
), ),
"codemap": (
"🗺️ Code map generation (yaml)",
lambda root: run_codemap(
root, silent, yaml_output
), # Using sync version - subprocess call
),
} }
if not silent: if not silent:
@@ -2174,7 +2227,7 @@ async def main_async():
parser.add_argument( parser.add_argument(
"--steps", "--steps",
nargs="+", nargs="+",
choices=["lint", "format", "test", "validate", "ruff", "naming"], choices=["lint", "format", "test", "validate", "ruff", "naming", "codemap"],
default=["format", "lint", "ruff", "test", "validate", "naming"], default=["format", "lint", "ruff", "test", "validate", "naming"],
help="Workflow steps to run", help="Workflow steps to run",
) )
@@ -2190,6 +2243,7 @@ async def main_async():
parser.add_argument( parser.add_argument(
"--naming", action="store_true", help="Check PascalCase naming conventions" "--naming", action="store_true", help="Check PascalCase naming conventions"
) )
parser.add_argument("--codemap", action="store_true", help="Generate code map YAML")
parser.add_argument( parser.add_argument(
"--silent", "--silent",
"-s", "-s",
@@ -2221,6 +2275,10 @@ async def main_async():
steps = ["validate"] steps = ["validate"]
elif args.ruff: elif args.ruff:
steps = ["ruff"] steps = ["ruff"]
elif args.naming:
steps = ["naming"]
elif args.codemap:
steps = ["codemap"]
else: else:
steps = args.steps steps = args.steps
@@ -2239,6 +2297,7 @@ async def main_async():
), ),
"ruff": lambda root: run_ruff_async(root, args.silent, args.yaml), "ruff": lambda root: run_ruff_async(root, args.silent, args.yaml),
"naming": lambda root: run_naming(root, args.silent, args.yaml), "naming": lambda root: run_naming(root, args.silent, args.yaml),
"codemap": lambda root: run_codemap(root, args.silent, args.yaml),
} }
success, _ = await step_funcs[steps[0]](project_root) success, _ = await step_funcs[steps[0]](project_root)
else: else:
@@ -2249,6 +2308,7 @@ async def main_async():
"validate": lambda root: run_validate(root, args.silent, args.yaml), "validate": lambda root: run_validate(root, args.silent, args.yaml),
"ruff": lambda root: run_ruff(root, args.silent, args.yaml), "ruff": lambda root: run_ruff(root, args.silent, args.yaml),
"naming": lambda root: run_naming(root, args.silent, args.yaml), "naming": lambda root: run_naming(root, args.silent, args.yaml),
"codemap": lambda root: run_codemap(root, args.silent, args.yaml),
} }
success, _ = step_funcs[steps[0]](project_root) success, _ = step_funcs[steps[0]](project_root)
else: else:
@@ -2296,6 +2356,9 @@ def main():
parser.add_argument( parser.add_argument(
"--naming", action="store_true", help="Check PascalCase naming conventions" "--naming", action="store_true", help="Check PascalCase naming conventions"
) )
parser.add_argument(
"--codemap", action="store_true", help="Generate code map YAML"
)
parser.add_argument( parser.add_argument(
"--silent", "--silent",
"-s", "-s",
@@ -2327,6 +2390,10 @@ def main():
steps = ["validate"] steps = ["validate"]
elif args.ruff: elif args.ruff:
steps = ["ruff"] steps = ["ruff"]
elif args.naming:
steps = ["naming"]
elif args.codemap:
steps = ["codemap"]
else: else:
steps = args.steps steps = args.steps
@@ -2339,6 +2406,7 @@ def main():
"validate": lambda root: run_validate(root, args.silent, args.yaml), "validate": lambda root: run_validate(root, args.silent, args.yaml),
"ruff": lambda root: run_ruff(root, args.silent, args.yaml), "ruff": lambda root: run_ruff(root, args.silent, args.yaml),
"naming": lambda root: run_naming(root, args.silent, args.yaml), "naming": lambda root: run_naming(root, args.silent, args.yaml),
"codemap": lambda root: run_codemap(root, args.silent, args.yaml),
} }
success, _ = step_funcs[steps[0]](project_root) success, _ = step_funcs[steps[0]](project_root)
else: else: