Compare commits

17 Commits

Author SHA1 Message Date
02ea7c04ec foobar 2025-10-01 20:39:01 +04:00
a53ac0944d runs-on: ["ubuntu-latest"] 2025-10-01 20:29:06 +04:00
9ce5c2ef02 Merge pull request 'Delete format_results.yaml' (#13) from nett00n-patch-1 into main
Reviewed-on: #13
2025-10-01 14:25:15 +02:00
db2cad10d8 Delete format_results.yaml 2025-10-01 14:25:09 +02:00
35ee2f9a5e format
Some checks failed
Continuous Integration / Code Formatting (push) Successful in 33s
Continuous Integration / Code Quality Check (push) Successful in 28s
Continuous Integration / Test Execution (push) Failing after 16s
Continuous Integration / CI Summary (push) Failing after 3s
2025-10-01 15:35:34 +04:00
Gitea Actions
1f1c394587 🎨 Auto-format GDScript code
Automated formatting applied by tools/run_development.py

🤖 Generated by Gitea Actions
Workflow: Continuous Integration
Run: http://server:3000/nett00n/skelly/actions/runs/90
2025-10-01 11:05:19 +00:00
3b8da89ad5 more lint and formatting
Some checks failed
Continuous Integration / Code Formatting (push) Successful in 33s
Continuous Integration / Code Quality Check (push) Successful in 29s
Continuous Integration / Test Execution (push) Failing after 16s
Continuous Integration / CI Summary (push) Failing after 4s
2025-10-01 15:04:40 +04:00
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
ffd88c02e1 claude
Some checks failed
Continuous Integration / Code Formatting (pull_request) Successful in 30s
Continuous Integration / Code Quality Check (pull_request) Successful in 28s
Continuous Integration / Test Execution (pull_request) Failing after 17s
Continuous Integration / CI Summary (pull_request) Failing after 5s
2025-09-30 00:29:06 +04:00
bd9b7c009a change platforms defaults 2025-09-30 00:28:52 +04:00
e61ab94935 typo 2025-09-30 00:28:29 +04:00
9150622e74 add build cache
use checkboxes
2025-09-30 00:28:17 +04:00
53 changed files with 6476 additions and 1257 deletions

View File

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

View File

@@ -1,13 +1,19 @@
# GDFormat configuration file
# GDFormat configuration file (YAML format)
# This file configures the gdformat tool for consistent GDScript formatting
# Maximum line length (default is 100)
# Godot's style guide recommends keeping lines under 100 characters
line_length = 80
line_length: 80
# Whether to use tabs or spaces for indentation
# Use spaces instead of tabs (null = use tabs)
# Set to integer for space count, or null for tabs
# Godot uses tabs by default
use_tabs = true
use_spaces: null
# Number of spaces per tab (when displaying)
tab_width = 4
# Safety checks (null = enabled by default)
safety_checks: null
# Directories to exclude from formatting
excluded_directories: !!set
.git: null
.godot: null

View File

@@ -3,32 +3,71 @@ name: Build Game
# Build pipeline for creating game executables across multiple platforms
#
# Features:
# - Manual trigger with platform selection
# - 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
# - Multi-platform builds (Windows, Linux, macOS, Android)
# - Artifact storage for one week
# - Configurable build options
# - Comprehensive build configuration options
on:
# Manual trigger with platform selection
workflow_dispatch:
inputs:
platforms:
description: 'Platforms to build (comma-separated: windows,linux,macos,android)'
required: true
default: 'windows,linux'
build_windows:
description: 'Build for Windows'
required: false
default: true
type: boolean
build_linux:
description: 'Build for Linux'
required: false
default: false
type: boolean
build_macos:
description: 'Build for macOS'
required: false
default: false
type: boolean
build_android:
description: 'Build for Android'
required: false
default: false
type: boolean
version:
description: 'Version (leave empty for auto-generated)'
required: false
default: ''
type: string
build_type:
description: 'Build type'
description: 'Build type release/debug'
required: true
default: 'release'
type: choice
default: 'debug'
type: debug
options:
- release
- debug
version_override:
description: 'Override version (optional)'
godot_version:
description: 'Godot version (leave empty for default)'
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
# Automatic trigger on git tags (for releases)
@@ -38,9 +77,33 @@ on:
- 'release-*' # Release tags
env:
# Core Configuration
GODOT_VERSION: "4.4.1"
PROJECT_NAME: "Skelly"
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:
# Preparation job - determines build configuration
@@ -55,36 +118,92 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
with:
fetch-depth: 0
- name: Configure build parameters
id: config
run: |
# Determine platforms to build
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
platforms="${{ github.event.inputs.platforms }}"
build_type="${{ github.event.inputs.build_type }}"
version_override="${{ github.event.inputs.version_override }}"
else
# Tag-triggered build - build all platforms
platforms="windows,linux,macos,android"
build_type="release"
version_override=""
# 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
# Determine version
if [[ -n "$version_override" ]]; then
version="$version_override"
elif [[ "${{ github.ref_type }}" == "tag" ]]; then
version="${{ github.ref_name }}"
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 build type first - tags always use release
if [[ "${{ github.ref_type }}" == "tag" ]]; then
# Tag build - always release mode
build_type="release"
platforms="windows,linux,macos,android"
user_version=""
elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
# Manual dispatch - use user inputs
build_type="${{ github.event.inputs.build_type }}"
user_version="${{ github.event.inputs.version }}"
# Build platforms array from individual checkboxes
platforms=""
if [[ "${{ github.event.inputs.build_windows }}" == "true" ]]; then
platforms="${platforms}windows,"
fi
if [[ "${{ github.event.inputs.build_linux }}" == "true" ]]; then
platforms="${platforms}linux,"
fi
if [[ "${{ github.event.inputs.build_macos }}" == "true" ]]; then
platforms="${platforms}macos,"
fi
if [[ "${{ github.event.inputs.build_android }}" == "true" ]]; then
platforms="${platforms}android,"
fi
# Remove trailing comma
platforms="${platforms%,}"
else
# Generate version from git info
# Other triggers - build all platforms in release mode
platforms="windows,linux,macos,android"
build_type="release"
user_version=""
fi
# Determine version with improved logic
if [[ -n "$user_version" ]]; then
# User provided explicit version
version="$user_version"
echo "🏷️ Using user-specified version: $version"
elif [[ "${{ github.ref_type }}" == "tag" ]]; then
# Tag-triggered build - use tag name
version="${{ github.ref_name }}"
echo "🏷️ Using git tag version: $version"
elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
# Manual dispatch without version - use default + git info
commit_short=$(git rev-parse --short HEAD)
branch_name="${{ github.ref_name }}"
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
# Create artifact name
@@ -100,25 +219,39 @@ jobs:
echo " Build Type: ${build_type}"
echo " Version: ${version}"
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}"
# Windows build job
build-windows:
name: Build Windows
# Setup export templates (shared across all platform builds)
setup-templates:
name: Setup Export Templates
runs-on: ubuntu-latest
needs: prepare
if: contains(needs.prepare.outputs.platforms, 'windows')
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Cache export templates
id: cache-templates
uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with:
path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }}
restore-keys: |
godot-templates-
- name: Setup Godot
uses: chickensoft-games/setup-godot@v1
if: steps.cache-templates.outputs.cache-hit != 'true'
uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with:
version: ${{ env.GODOT_VERSION }}
use-dotnet: false
- name: Install export templates
if: steps.cache-templates.outputs.cache-hit != 'true'
run: |
echo "📦 Installing Godot export templates..."
mkdir -p ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable
@@ -128,6 +261,36 @@ jobs:
echo "✅ Export templates installed successfully"
ls -la ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable/
- name: Verify templates cache
run: |
echo "🔍 Verifying export templates are available:"
ls -la ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable/
# Windows build job
build-windows:
name: Build Windows
runs-on: ubuntu-latest
needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'windows')
steps:
- name: Checkout repository
uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Godot
uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with:
version: ${{ env.GODOT_VERSION }}
use-dotnet: false
- name: Restore export templates cache
uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with:
path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }}
restore-keys: |
godot-templates-
- name: Create build directory
run: mkdir -p ${{ env.BUILD_DIR }}
@@ -153,7 +316,7 @@ jobs:
fi
- name: Upload Windows build
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with:
name: ${{ needs.prepare.outputs.artifact_name }}-windows
path: ${{ env.BUILD_DIR }}/skelly-windows-${{ needs.prepare.outputs.version }}.exe
@@ -164,28 +327,26 @@ jobs:
build-linux:
name: Build Linux
runs-on: ubuntu-latest
needs: prepare
needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'linux')
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Godot
uses: chickensoft-games/setup-godot@v1
uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with:
version: ${{ env.GODOT_VERSION }}
use-dotnet: false
- name: Install export templates
run: |
echo "📦 Installing Godot export templates..."
mkdir -p ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable
wget -q https://github.com/godotengine/godot/releases/download/${{ env.GODOT_VERSION }}-stable/Godot_v${{ env.GODOT_VERSION }}-stable_export_templates.tpz
unzip -q Godot_v${{ env.GODOT_VERSION }}-stable_export_templates.tpz
mv templates/* ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable/
echo "✅ Export templates installed successfully"
ls -la ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable/
- name: Restore export templates cache
uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with:
path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }}
restore-keys: |
godot-templates-
- name: Create build directory
run: mkdir -p ${{ env.BUILD_DIR }}
@@ -215,7 +376,7 @@ jobs:
fi
- name: Upload Linux build
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with:
name: ${{ needs.prepare.outputs.artifact_name }}-linux
path: ${{ env.BUILD_DIR }}/skelly-linux-${{ needs.prepare.outputs.version }}.x86_64
@@ -226,28 +387,26 @@ jobs:
build-macos:
name: Build macOS
runs-on: ubuntu-latest
needs: prepare
needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'macos')
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Godot
uses: chickensoft-games/setup-godot@v1
uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with:
version: ${{ env.GODOT_VERSION }}
use-dotnet: false
- name: Install export templates
run: |
echo "📦 Installing Godot export templates..."
mkdir -p ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable
wget -q https://github.com/godotengine/godot/releases/download/${{ env.GODOT_VERSION }}-stable/Godot_v${{ env.GODOT_VERSION }}-stable_export_templates.tpz
unzip -q Godot_v${{ env.GODOT_VERSION }}-stable_export_templates.tpz
mv templates/* ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable/
echo "✅ Export templates installed successfully"
ls -la ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable/
- name: Restore export templates cache
uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with:
path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }}
restore-keys: |
godot-templates-
- name: Create build directory
run: mkdir -p ${{ env.BUILD_DIR }}
@@ -274,7 +433,7 @@ jobs:
fi
- name: Upload macOS build
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with:
name: ${{ needs.prepare.outputs.artifact_name }}-macos
path: ${{ env.BUILD_DIR }}/skelly-macos-${{ needs.prepare.outputs.version }}.zip
@@ -285,39 +444,97 @@ jobs:
build-android:
name: Build Android
runs-on: ubuntu-latest
needs: prepare
needs: [prepare, setup-templates]
if: contains(needs.prepare.outputs.platforms, 'android')
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@${{ env.ACTIONS_CHECKOUT_VERSION }}
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@${{ env.ACTIONS_SETUP_JAVA_VERSION }}
with:
distribution: 'temurin'
java-version: '17'
distribution: ${{ env.JAVA_DISTRIBUTION }}
java-version: ${{ env.JAVA_VERSION }}
- name: Setup Android SDK
uses: android-actions/setup-android@v3
uses: android-actions/setup-android@${{ env.ANDROID_ACTIONS_SETUP_ANDROID_VERSION }}
with:
api-level: 33
build-tools: 33.0.0
api-level: ${{ env.ANDROID_API_LEVEL }}
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
uses: chickensoft-games/setup-godot@v1
uses: chickensoft-games/setup-godot@${{ env.CHICKENSOFT_SETUP_GODOT_VERSION }}
with:
version: ${{ env.GODOT_VERSION }}
use-dotnet: false
- name: Install export templates
- name: Configure Godot for Android
run: |
echo "📦 Installing Godot export templates..."
mkdir -p ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable
wget -q https://github.com/godotengine/godot/releases/download/${{ env.GODOT_VERSION }}-stable/Godot_v${{ env.GODOT_VERSION }}-stable_export_templates.tpz
unzip -q Godot_v${{ env.GODOT_VERSION }}-stable_export_templates.tpz
mv templates/* ~/.local/share/godot/export_templates/${{ env.GODOT_VERSION }}.stable/
echo "✅ Export templates installed successfully"
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
uses: actions/cache@${{ env.ACTIONS_CACHE_VERSION }}
with:
path: ~/.local/share/godot/export_templates
key: godot-templates-${{ env.GODOT_VERSION }}
restore-keys: |
godot-templates-
- name: Create build directory
run: mkdir -p ${{ env.BUILD_DIR }}
@@ -332,8 +549,11 @@ jobs:
run: |
echo "🏗️ Building Android APK..."
# Set ANDROID_HOME if not already set
export ANDROID_HOME=${ANDROID_HOME:-$ANDROID_SDK_ROOT}
# Verify Android environment
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" \
${{ env.BUILD_DIR }}/skelly-android-${{ needs.prepare.outputs.version }}.apk
@@ -352,7 +572,7 @@ jobs:
fi
- name: Upload Android build
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@${{ env.ACTIONS_UPLOAD_ARTIFACT_VERSION }}
with:
name: ${{ needs.prepare.outputs.artifact_name }}-android
path: ${{ env.BUILD_DIR }}/skelly-android-${{ needs.prepare.outputs.version }}.apk
@@ -363,7 +583,7 @@ jobs:
summary:
name: Build Summary
runs-on: ubuntu-latest
needs: [prepare, build-windows, build-linux, build-macos, build-android]
needs: [prepare, setup-templates, build-windows, build-linux, build-macos, build-android]
if: always()
steps:

View File

@@ -112,31 +112,31 @@ jobs:
git diff --stat
fi
- name: Commit and push formatting changes
if: steps.check-changes.outputs.has_changes == 'true'
run: |
echo "💾 Committing formatting changes..."
# - name: Commit and push formatting changes
# if: steps.check-changes.outputs.has_changes == 'true'
# run: |
# echo "💾 Committing formatting changes..."
git config user.name "Gitea Actions"
git config user.email "actions@gitea.local"
# git config user.name "Gitea Actions"
# git config user.email "actions@gitea.local"
git add -A
# git add -A
commit_message="🎨 Auto-format GDScript code
# commit_message="🎨 Auto-format GDScript code
Automated formatting applied by tools/run_development.py
# Automated formatting applied by tools/run_development.py
🤖 Generated by Gitea Actions
Workflow: ${{ github.workflow }}
Run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
# 🤖 Generated by Gitea Actions
# Workflow: ${{ github.workflow }}
# Run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
git commit -m "$commit_message"
# git commit -m "$commit_message"
target_branch="${{ github.event.pull_request.head.ref || github.ref_name }}"
echo "📤 Pushing changes to branch: $target_branch"
git push origin HEAD:"$target_branch"
# target_branch="${{ github.event.pull_request.head.ref || github.ref_name }}"
# echo "📤 Pushing changes to branch: $target_branch"
# git push origin HEAD:"$target_branch"
echo "✅ Formatting changes pushed successfully!"
# echo "✅ Formatting changes pushed successfully!"
lint:
name: Code Quality Check
@@ -210,9 +210,19 @@ jobs:
- name: Run tests
id: test
continue-on-error: true
run: |
echo "🧪 Running GDScript tests..."
python tools/run_development.py --test --silent --yaml > test_results.yaml
python tools/run_development.py --test --yaml > test_results.yaml 2>&1
TEST_EXIT_CODE=$?
# Display test results regardless of success/failure
echo ""
echo "📊 Test Results:"
cat test_results.yaml
# Exit with the original test exit code
exit $TEST_EXIT_CODE
- name: Upload test results
if: always()
@@ -224,6 +234,49 @@ jobs:
retention-days: 7
compression-level: 0
- name: Check test results and display errors
if: always()
run: |
echo ""
echo "================================================"
echo "📊 TEST RESULTS SUMMARY"
echo "================================================"
# Parse YAML to check if tests failed
if grep -q "success: false" test_results.yaml; then
echo "❌ Status: FAILED"
echo ""
echo "💥 Failed Test Details:"
echo "================================================"
# Extract and display failed test information
grep -A 2 "failed_test_details:" test_results.yaml || echo "No detailed error information available"
# Show statistics
echo ""
echo "📈 Statistics:"
grep "tests_passed:" test_results.yaml || true
grep "tests_failed:" test_results.yaml || true
grep "total_tests_run:" test_results.yaml || true
echo ""
echo "================================================"
echo "⚠️ Please review the test errors above and fix them before merging."
echo "================================================"
exit 1
elif grep -q "success: true" test_results.yaml; then
echo "✅ Status: PASSED"
echo ""
grep "total_tests_run:" test_results.yaml || true
echo "================================================"
exit 0
else
echo "⚠️ Status: UNKNOWN"
echo "Could not determine test status from YAML output"
echo "================================================"
exit 1
fi
summary:
name: CI Summary
runs-on: ubuntu-latest

7
.gitignore vendored
View File

@@ -7,7 +7,12 @@
*.import~
test_results.txt
# Auto-generated code maps (regenerate with: python tools/generate_code_map.py)
.llm/
docs/generated/
# python
.venv
.venv/
*.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;
- Get following files in context before doing anything else:
- docs\CLAUDE.md
- docs\CODE_OF_CONDUCT.md
- project.godot
- Use TDD methodology for development;
- Use static data types;
- Keep documentation up to date;
- Always run tests `tools\run_development.py --yaml --silent`;
# CLAUDE.md
Guidance for Claude Code (claude.ai/code) when working with this repository.
## Required Context Files
Before doing anything else, get the following files in context:
- **docs/ARCHITECTURE.md** - System design, autoloads, architectural patterns
- **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)
```
### Memory Management Standards
**Critical Rules**:
1. **Always use `queue_free()`** instead of `free()` for node cleanup
2. **Wait for frame completion** after queueing nodes for removal
3. **Clear references before cleanup** to prevent access to freed memory
4. **Connect signals properly** for dynamically created nodes
```gdscript
# ✅ Correct memory management
for child in children_to_remove:
child.queue_free()
await get_tree().process_frame # Wait for cleanup
# ❌ Dangerous pattern (causes crashes)
for child in children_to_remove:
child.free() # Immediate deletion can crash
```
**Why This Matters**: Using `free()` causes immediate deletion which can crash if the node is still referenced elsewhere. `queue_free()` waits until it's safe to delete.
**See Also**: [ARCHITECTURE.md](ARCHITECTURE.md#memory-management-queue_free-over-free) for architectural rationale.
### Input Validation Standards
All user inputs must be validated before processing.
**Validation Requirements**:
1. **Type checking**: Verify input types before processing
2. **Bounds checking**: Validate numeric ranges and array indices
3. **Null checking**: Handle null and empty inputs gracefully
4. **Whitelist validation**: Validate against known good values
```gdscript
# ✅ Proper input validation
func set_volume(value: float, setting_key: String) -> bool:
# Whitelist validation
if not setting_key in ["master_volume", "music_volume", "sfx_volume"]:
DebugManager.log_error("Invalid volume setting key: " + str(setting_key), "Settings")
return false
# Bounds checking
var clamped_value = clamp(value, 0.0, 1.0)
if clamped_value != value:
DebugManager.log_warn("Volume value clamped from %f to %f" % [value, clamped_value], "Settings")
SettingsManager.set_setting(setting_key, clamped_value)
return true
# ✅ Grid movement validation
func _move_cursor(direction: Vector2i) -> void:
# Bounds checking
if abs(direction.x) > 1 or abs(direction.y) > 1:
DebugManager.log_error("Invalid cursor direction: " + str(direction), "Match3")
return
# Null/empty checking
if not grid or grid.is_empty():
DebugManager.log_error("Grid not initialized", "Match3")
return
# Process validated input
var new_pos = cursor_pos + direction
# ... continue with validated data
```
**See Also**: [ARCHITECTURE.md](ARCHITECTURE.md#input-validation-whitelist-approach) for architectural decision rationale.
## Code Quality Checklist
Before committing code, verify:
- [ ] All user inputs validated (type, bounds, null checks)
- [ ] Error handling with fallback mechanisms implemented
- [ ] Memory cleanup uses `queue_free()` not `free()`
- [ ] No global static state introduced
- [ ] Proper logging with categories and appropriate levels
- [ ] Race condition protection for async operations
- [ ] Input actions defined in project input map
- [ ] Resources loaded with null/type checking
- [ ] Documentation updated for new public APIs
- [ ] Test coverage for new functionality
## Git Workflow
### Commit Guidelines

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
1. **Main Scene** (`scenes/main/main.tscn` + `Main.gd`)
1. **Main Scene** (`scenes/main/Main.tscn` + `Main.gd`)
- Application entry point
- Manages splash screen
- Transitions to main menu
@@ -112,7 +112,7 @@ game.tscn (Gameplay Container)
- Audio volume controls
- 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
- Dynamic loading of gameplay modes into GameplayContainer
- 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.
### 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
- **Dynamic Loading** - Gameplay scenes loaded at runtime based on mode selection
- **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
- 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)
- Gem type management with validation and bounds checking
- Visual representation with scaling and color

View File

@@ -2,6 +2,10 @@
Test scripts and utilities for validating Skelly project systems.
**Related Documentation**:
- **Coding Standards**: [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - Follow coding standards when writing tests
- **Architecture**: [ARCHITECTURE.md](ARCHITECTURE.md) - Understand system design before testing
## Overview
The `tests/` directory contains:
@@ -11,7 +15,7 @@ The `tests/` directory contains:
- Performance benchmarks
- Debugging tools
> 📋 **File Naming**: All test files follow the [naming conventions](CODE_OF_CONDUCT.md#2-file-naming-standards) with PascalCase and "Test" prefix (e.g., `TestAudioManager.gd`).
> 📋 **File Naming**: All test files follow the [naming conventions](CODE_OF_CONDUCT.md#naming-convention-quick-reference) with PascalCase and "Test" prefix (e.g., `TestAudioManager.gd`).
## Current Test Files
@@ -259,9 +263,15 @@ If tests take longer, investigate file I/O issues, memory leaks, infinite loops,
## Contributing
When adding test files:
1. Follow naming and structure conventions
2. Update this README with test descriptions
3. Ensure tests are self-contained and documented
4. Test success and failure scenarios
1. Follow [naming conventions](CODE_OF_CONDUCT.md#naming-convention-quick-reference)
2. Follow [coding standards](CODE_OF_CONDUCT.md) for test code quality
3. Understand [system architecture](ARCHITECTURE.md) before writing integration tests
4. Update this file with test descriptions
5. Ensure tests are self-contained and documented
6. Test success and failure scenarios
This testing approach maintains code quality and provides validation tools for system changes.
**See Also**:
- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md#code-quality-checklist) - Quality checklist before committing
- [ARCHITECTURE.md](ARCHITECTURE.md) - System design and architectural patterns

View File

@@ -11,14 +11,17 @@ var language_stepper: ValueStepper = $VBoxContainer/Examples/LanguageContainer/L
var difficulty_stepper: ValueStepper = $VBoxContainer/Examples/DifficultyContainer/DifficultyStepper
@onready
var resolution_stepper: ValueStepper = $VBoxContainer/Examples/ResolutionContainer/ResolutionStepper
@onready var custom_stepper: ValueStepper = $VBoxContainer/Examples/CustomContainer/CustomStepper
@onready
var custom_stepper: ValueStepper = $VBoxContainer/Examples/CustomContainer/CustomStepper
func _ready():
DebugManager.log_info("ValueStepper example ready", "Example")
# Setup navigation array
navigable_steppers = [language_stepper, difficulty_stepper, resolution_stepper, custom_stepper]
navigable_steppers = [
language_stepper, difficulty_stepper, resolution_stepper, custom_stepper
]
# Connect to value change events
for stepper in navigable_steppers:
@@ -52,15 +55,22 @@ func _input(event: InputEvent):
func _navigate_steppers(direction: int):
current_stepper_index = (current_stepper_index + direction) % navigable_steppers.size()
current_stepper_index = (
(current_stepper_index + direction) % navigable_steppers.size()
)
if current_stepper_index < 0:
current_stepper_index = navigable_steppers.size() - 1
_update_stepper_highlighting()
DebugManager.log_info("Stepper navigation: index " + str(current_stepper_index), "Example")
DebugManager.log_info(
"Stepper navigation: index " + str(current_stepper_index), "Example"
)
func _handle_stepper_input(action: String):
if current_stepper_index >= 0 and current_stepper_index < navigable_steppers.size():
if (
current_stepper_index >= 0
and current_stepper_index < navigable_steppers.size()
):
var stepper = navigable_steppers[current_stepper_index]
if stepper.handle_input_action(action):
AudioManager.play_ui_click()
@@ -73,7 +83,14 @@ func _update_stepper_highlighting():
func _on_stepper_value_changed(new_value: String, new_index: int):
DebugManager.log_info(
"Stepper value changed to: " + new_value + " (index: " + str(new_index) + ")", "Example"
(
"Stepper value changed to: "
+ new_value
+ " (index: "
+ str(new_index)
+ ")"
),
"Example"
)
# Handle value change in your scene
# For example: apply settings, save preferences, update UI, etc.

View File

@@ -11,7 +11,7 @@ config_version=5
[application]
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/icon="res://icon.svg"
boot_splash/handheld/orientation=0
@@ -224,3 +224,4 @@ locale/translations=PackedStringArray("res://localization/MainStrings.en.transla
textures/canvas_textures/default_texture_filter=0
renderer/rendering_method="gl_compatibility"
renderer/rendering_method.mobile="gl_compatibility"
textures/vram_compression/import_etc2_astc=true

View File

@@ -1,4 +1,10 @@
setuptools<81
gdtoolkit==4
aiofiles>=23.0.0
aiofiles>=23
gdtoolkit>=4
PyYAML>=6.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

@@ -20,15 +20,20 @@ func _ready() -> void:
# GameManager will set the gameplay mode, don't set default here
DebugManager.log_debug(
"Game _ready() completed, waiting for GameManager to set gameplay mode", "Game"
"Game _ready() completed, waiting for GameManager to set gameplay mode",
"Game"
)
func set_gameplay_mode(mode: String) -> void:
DebugManager.log_info("set_gameplay_mode called with mode: %s" % mode, "Game")
DebugManager.log_info(
"set_gameplay_mode called with mode: %s" % mode, "Game"
)
current_gameplay_mode = mode
await load_gameplay(mode)
DebugManager.log_info("set_gameplay_mode completed for mode: %s" % mode, "Game")
DebugManager.log_info(
"set_gameplay_mode completed for mode: %s" % mode, "Game"
)
func load_gameplay(mode: String) -> void:
@@ -37,24 +42,35 @@ func load_gameplay(mode: String) -> void:
# Clear existing gameplay and wait for removal
var existing_children = gameplay_container.get_children()
if existing_children.size() > 0:
DebugManager.log_debug("Removing %d existing children" % existing_children.size(), "Game")
DebugManager.log_debug(
"Removing %d existing children" % existing_children.size(), "Game"
)
for child in existing_children:
DebugManager.log_debug("Removing existing child: %s" % child.name, "Game")
DebugManager.log_debug(
"Removing existing child: %s" % child.name, "Game"
)
child.queue_free()
# Wait for children to be properly removed from scene tree
await get_tree().process_frame
DebugManager.log_debug(
"Children removal complete, container count: %d" % gameplay_container.get_child_count(),
(
"Children removal complete, container count: %d"
% gameplay_container.get_child_count()
),
"Game"
)
# Load new gameplay
if GAMEPLAY_SCENES.has(mode):
DebugManager.log_debug("Found scene path: %s" % GAMEPLAY_SCENES[mode], "Game")
DebugManager.log_debug(
"Found scene path: %s" % GAMEPLAY_SCENES[mode], "Game"
)
var gameplay_scene = load(GAMEPLAY_SCENES[mode])
var gameplay_instance = gameplay_scene.instantiate()
DebugManager.log_debug("Instantiated gameplay: %s" % gameplay_instance.name, "Game")
DebugManager.log_debug(
"Instantiated gameplay: %s" % gameplay_instance.name, "Game"
)
gameplay_container.add_child(gameplay_instance)
DebugManager.log_debug(
(
@@ -69,7 +85,9 @@ func load_gameplay(mode: String) -> void:
gameplay_instance.score_changed.connect(_on_score_changed)
DebugManager.log_debug("Connected score_changed signal", "Game")
else:
DebugManager.log_error("Gameplay mode '%s' not found in GAMEPLAY_SCENES" % mode, "Game")
DebugManager.log_error(
"Gameplay mode '%s' not found in GAMEPLAY_SCENES" % mode, "Game"
)
func set_global_score(value: int) -> void:
@@ -102,10 +120,15 @@ func _on_back_button_pressed() -> void:
if gameplay_instance and gameplay_instance.has_method("save_current_state"):
DebugManager.log_info("Saving grid state before exit", "Game")
# Make sure the gameplay instance is still valid and not being destroyed
if is_instance_valid(gameplay_instance) and gameplay_instance.is_inside_tree():
if (
is_instance_valid(gameplay_instance)
and gameplay_instance.is_inside_tree()
):
gameplay_instance.save_current_state()
else:
DebugManager.log_warn("Gameplay instance invalid, skipping grid save on exit", "Game")
DebugManager.log_warn(
"Gameplay instance invalid, skipping grid save on exit", "Game"
)
# Save the current score immediately before exiting
SaveManager.finish_game(global_score)
@@ -116,7 +139,10 @@ func _input(event: InputEvent) -> void:
if event.is_action_pressed("ui_back"):
# Handle gamepad/keyboard back action - same as back button
_on_back_button_pressed()
elif event.is_action_pressed("action_south") and Input.is_action_pressed("action_north"):
elif (
event.is_action_pressed("action_south")
and Input.is_action_pressed("action_north")
):
# Debug: Switch to clickomania when primary+secondary actions pressed together
if current_gameplay_mode == "match3":
set_gameplay_mode("clickomania")

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="PackedScene" path="res://scenes/ui/DebugToggle.tscn" id="3_debug"]

View File

@@ -49,13 +49,21 @@ func _ready() -> void:
instance_id = "Match3_%d" % get_instance_id()
if grid_initialized:
DebugManager.log_warn(
"[%s] Match3 _ready() called multiple times, skipping initialization" % instance_id,
"Match3"
(
DebugManager
. log_warn(
(
"[%s] Match3 _ready() called multiple times, skipping initialization"
% instance_id
),
"Match3"
)
)
return
DebugManager.log_debug("[%s] Match3 _ready() started" % instance_id, "Match3")
DebugManager.log_debug(
"[%s] Match3 _ready() started" % instance_id, "Match3"
)
grid_initialized = true
# Calculate grid layout
@@ -64,12 +72,16 @@ func _ready() -> void:
# Try to load saved state, otherwise use default
var loaded_saved_state = await load_saved_state()
if not loaded_saved_state:
DebugManager.log_info("No saved state found, using default grid initialization", "Match3")
DebugManager.log_info(
"No saved state found, using default grid initialization", "Match3"
)
_initialize_grid()
else:
DebugManager.log_info("Successfully loaded saved grid state", "Match3")
DebugManager.log_debug("Match3 _ready() completed, calling debug structure check", "Match3")
DebugManager.log_debug(
"Match3 _ready() completed, calling debug structure check", "Match3"
)
# Notify UI that grid state is loaded
grid_state_loaded.emit(grid_size, tile_types)
@@ -91,7 +103,8 @@ func _calculate_grid_layout():
# Align grid to left side with margins
var total_grid_height = tile_size * grid_size.y
grid_offset = Vector2(
GRID_LEFT_MARGIN, (viewport_size.y - total_grid_height) / 2 + GRID_TOP_MARGIN
GRID_LEFT_MARGIN,
(viewport_size.y - total_grid_height) / 2 + GRID_TOP_MARGIN
)
@@ -136,7 +149,9 @@ func _has_match_at(pos: Vector2i) -> bool:
return false
if pos.y >= grid.size() or pos.x >= grid[pos.y].size():
DebugManager.log_error("Grid array bounds exceeded at (%d,%d)" % [pos.x, pos.y], "Match3")
DebugManager.log_error(
"Grid array bounds exceeded at (%d,%d)" % [pos.x, pos.y], "Match3"
)
return false
var tile = grid[pos.y][pos.x]
@@ -146,7 +161,8 @@ func _has_match_at(pos: Vector2i) -> bool:
# Check if tile has required properties
if not "tile_type" in tile:
DebugManager.log_warn(
"Tile at (%d,%d) missing tile_type property" % [pos.x, pos.y], "Match3"
"Tile at (%d,%d) missing tile_type property" % [pos.x, pos.y],
"Match3"
)
return false
@@ -177,13 +193,18 @@ func _get_match_line(start: Vector2i, dir: Vector2i) -> Array:
# Validate input parameters
if not _is_valid_grid_position(start):
DebugManager.log_error(
"Invalid start position for match line: (%d,%d)" % [start.x, start.y], "Match3"
(
"Invalid start position for match line: (%d,%d)"
% [start.x, start.y]
),
"Match3"
)
return []
if abs(dir.x) + abs(dir.y) != 1 or (dir.x != 0 and dir.y != 0):
DebugManager.log_error(
"Invalid direction vector for match line: (%d,%d)" % [dir.x, dir.y], "Match3"
"Invalid direction vector for match line: (%d,%d)" % [dir.x, dir.y],
"Match3"
)
return []
@@ -206,7 +227,10 @@ func _get_match_line(start: Vector2i, dir: Vector2i) -> Array:
var current = start + dir * offset
var steps = 0
# Safety limit prevents infinite loops in case of logic errors
while steps < grid_size.x + grid_size.y and _is_valid_grid_position(current):
while (
steps < grid_size.x + grid_size.y
and _is_valid_grid_position(current)
):
if current.y >= grid.size() or current.x >= grid[current.y].size():
break
@@ -233,7 +257,9 @@ func _clear_matches() -> void:
"""
# Check grid integrity
if not _validate_grid_integrity():
DebugManager.log_error("Grid integrity check failed in _clear_matches", "Match3")
DebugManager.log_error(
"Grid integrity check failed in _clear_matches", "Match3"
)
return
var match_groups := []
@@ -282,7 +308,9 @@ func _clear_matches() -> void:
else:
match_score = match_size + max(0, match_size - 2) # n + (n-2) for n >= 4
total_score += match_score
print("Debug: Match of ", match_size, " gems = ", match_score, " points")
print(
"Debug: Match of ", match_size, " gems = ", match_score, " points"
)
# Remove duplicates from all matches combined
var to_clear := []
@@ -308,7 +336,9 @@ func _clear_matches() -> void:
# Validate tile has grid_position property
if not "grid_position" in tile:
DebugManager.log_warn("Tile missing grid_position during removal", "Match3")
DebugManager.log_warn(
"Tile missing grid_position during removal", "Match3"
)
tile.queue_free()
continue
@@ -322,7 +352,10 @@ func _clear_matches() -> void:
grid[tile_pos.y][tile_pos.x] = null
else:
DebugManager.log_warn(
"Invalid grid position during tile removal: (%d,%d)" % [tile_pos.x, tile_pos.y],
(
"Invalid grid position during tile removal: (%d,%d)"
% [tile_pos.x, tile_pos.y]
),
"Match3"
)
@@ -358,7 +391,9 @@ func _drop_tiles():
func _fill_empty_cells():
# Safety check for grid integrity
if not _validate_grid_integrity():
DebugManager.log_error("Grid integrity check failed in _fill_empty_cells", "Match3")
DebugManager.log_error(
"Grid integrity check failed in _fill_empty_cells", "Match3"
)
return
# Create gem pool for current tile types
@@ -374,14 +409,17 @@ func _fill_empty_cells():
for x in range(grid_size.x):
if x >= grid[y].size():
DebugManager.log_error("Grid column %d does not exist in row %d" % [x, y], "Match3")
DebugManager.log_error(
"Grid column %d does not exist in row %d" % [x, y], "Match3"
)
continue
if not grid[y][x]:
var tile = TILE_SCENE.instantiate()
if not tile:
DebugManager.log_error(
"Failed to instantiate tile at (%d,%d)" % [x, y], "Match3"
"Failed to instantiate tile at (%d,%d)" % [x, y],
"Match3"
)
continue
@@ -393,13 +431,17 @@ func _fill_empty_cells():
if tile.has_method("set_active_gem_types"):
tile.set_active_gem_types(gem_indices)
else:
DebugManager.log_warn("Tile missing set_active_gem_types method", "Match3")
DebugManager.log_warn(
"Tile missing set_active_gem_types method", "Match3"
)
# Set random tile type with bounds checking
if tile_types > 0:
tile.tile_type = randi() % tile_types
else:
DebugManager.log_error("tile_types is 0, cannot set tile type", "Match3")
DebugManager.log_error(
"tile_types is 0, cannot set tile type", "Match3"
)
tile.queue_free()
continue
@@ -408,7 +450,9 @@ func _fill_empty_cells():
if tile.has_signal("tile_selected"):
tile.tile_selected.connect(_on_tile_selected)
else:
DebugManager.log_warn("Tile missing tile_selected signal", "Match3")
DebugManager.log_warn(
"Tile missing tile_selected signal", "Match3"
)
tiles_created += 1
@@ -423,12 +467,15 @@ func _fill_empty_cells():
iteration += 1
if iteration >= MAX_CASCADE_ITERATIONS:
DebugManager.log_warn(
(
"Maximum cascade iterations reached (%d), stopping to prevent infinite loop"
% MAX_CASCADE_ITERATIONS
),
"Match3"
(
DebugManager
. log_warn(
(
"Maximum cascade iterations reached (%d), stopping to prevent infinite loop"
% MAX_CASCADE_ITERATIONS
),
"Match3"
)
)
# Save grid state after cascades complete
@@ -444,20 +491,27 @@ func regenerate_grid():
or grid_size.y > MAX_GRID_SIZE
):
DebugManager.log_error(
"Invalid grid size for regeneration: %dx%d" % [grid_size.x, grid_size.y], "Match3"
(
"Invalid grid size for regeneration: %dx%d"
% [grid_size.x, grid_size.y]
),
"Match3"
)
return
if tile_types < 3 or tile_types > MAX_TILE_TYPES:
DebugManager.log_error(
"Invalid tile types count for regeneration: %d" % tile_types, "Match3"
"Invalid tile types count for regeneration: %d" % tile_types,
"Match3"
)
return
# Use time-based seed to ensure different patterns each time
var new_seed = Time.get_ticks_msec()
seed(new_seed)
DebugManager.log_debug("Regenerating grid with seed: " + str(new_seed), "Match3")
DebugManager.log_debug(
"Regenerating grid with seed: " + str(new_seed), "Match3"
)
# Safe tile cleanup with improved error handling
var children_to_remove = []
@@ -470,14 +524,16 @@ func regenerate_grid():
# More robust tile detection
if child.has_method("get_script") and child.get_script():
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)
removed_count += 1
elif "grid_position" in child: # Fallback detection
children_to_remove.append(child)
removed_count += 1
DebugManager.log_debug("Found %d tile children to remove" % removed_count, "Match3")
DebugManager.log_debug(
"Found %d tile children to remove" % removed_count, "Match3"
)
# First clear grid array references to prevent access to nodes being freed
for y in range(grid.size()):
@@ -508,20 +564,30 @@ func regenerate_grid():
func set_tile_types(new_count: int):
# Input validation
if new_count < 3:
DebugManager.log_error("Tile types count too low: %d (minimum 3)" % new_count, "Match3")
DebugManager.log_error(
"Tile types count too low: %d (minimum 3)" % new_count, "Match3"
)
return
if new_count > MAX_TILE_TYPES:
DebugManager.log_error(
"Tile types count too high: %d (maximum %d)" % [new_count, MAX_TILE_TYPES], "Match3"
(
"Tile types count too high: %d (maximum %d)"
% [new_count, MAX_TILE_TYPES]
),
"Match3"
)
return
if new_count == tile_types:
DebugManager.log_debug("Tile types count unchanged, skipping regeneration", "Match3")
DebugManager.log_debug(
"Tile types count unchanged, skipping regeneration", "Match3"
)
return
DebugManager.log_debug("Changing tile types from %d to %d" % [tile_types, new_count], "Match3")
DebugManager.log_debug(
"Changing tile types from %d to %d" % [tile_types, new_count], "Match3"
)
tile_types = new_count
# Regenerate grid with new tile types (gem pool is updated in regenerate_grid)
@@ -551,10 +617,14 @@ func set_grid_size(new_size: Vector2i):
return
if new_size == grid_size:
DebugManager.log_debug("Grid size unchanged, skipping regeneration", "Match3")
DebugManager.log_debug(
"Grid size unchanged, skipping regeneration", "Match3"
)
return
DebugManager.log_debug("Changing grid size from %s to %s" % [grid_size, new_size], "Match3")
DebugManager.log_debug(
"Changing grid size from %s to %s" % [grid_size, new_size], "Match3"
)
grid_size = new_size
# Regenerate grid with new size
@@ -577,13 +647,19 @@ func reset_all_visual_states() -> void:
func _debug_scene_structure() -> void:
DebugManager.log_debug("=== Scene Structure Debug ===", "Match3")
DebugManager.log_debug("Match3 node children count: %d" % get_child_count(), "Match3")
DebugManager.log_debug("Match3 global position: %s" % global_position, "Match3")
DebugManager.log_debug(
"Match3 node children count: %d" % get_child_count(), "Match3"
)
DebugManager.log_debug(
"Match3 global position: %s" % global_position, "Match3"
)
DebugManager.log_debug("Match3 scale: %s" % scale, "Match3")
# Check if grid is properly initialized
if not grid or grid.size() == 0:
DebugManager.log_error("Grid not initialized when debug structure called", "Match3")
DebugManager.log_error(
"Grid not initialized when debug structure called", "Match3"
)
return
# Check tiles
@@ -593,23 +669,33 @@ func _debug_scene_structure() -> void:
if y < grid.size() and x < grid[y].size() and grid[y][x]:
tile_count += 1
DebugManager.log_debug(
"Created %d tiles out of %d expected" % [tile_count, grid_size.x * grid_size.y], "Match3"
(
"Created %d tiles out of %d expected"
% [tile_count, grid_size.x * grid_size.y]
),
"Match3"
)
# Check first tile in detail
if grid.size() > 0 and grid[0].size() > 0 and grid[0][0]:
var first_tile = grid[0][0]
DebugManager.log_debug(
"First tile global position: %s" % first_tile.global_position, "Match3"
"First tile global position: %s" % first_tile.global_position,
"Match3"
)
DebugManager.log_debug(
"First tile local position: %s" % first_tile.position, "Match3"
)
DebugManager.log_debug("First tile local position: %s" % first_tile.position, "Match3")
# Check parent chain
var current_node = self
var depth = 0
while current_node and depth < 10:
DebugManager.log_debug(
"Parent level %d: %s (type: %s)" % [depth, current_node.name, current_node.get_class()],
(
"Parent level %d: %s (type: %s)"
% [depth, current_node.name, current_node.get_class()]
),
"Match3"
)
current_node = current_node.get_parent()
@@ -618,16 +704,27 @@ func _debug_scene_structure() -> void:
func _input(event: InputEvent) -> void:
# Debug key to reset all visual states
if event.is_action_pressed("action_east") and DebugManager.is_debug_enabled():
if (
event.is_action_pressed("action_east")
and DebugManager.is_debug_enabled()
):
reset_all_visual_states()
return
if current_state == GameState.SWAPPING or current_state == GameState.PROCESSING:
if (
current_state == GameState.SWAPPING
or current_state == GameState.PROCESSING
):
return
# Handle action_east (B button/ESC) to deselect selected tile
if event.is_action_pressed("action_east") and current_state == GameState.SELECTING:
DebugManager.log_debug("action_east pressed - deselecting current tile", "Match3")
if (
event.is_action_pressed("action_east")
and current_state == GameState.SELECTING
):
DebugManager.log_debug(
"action_east pressed - deselecting current tile", "Match3"
)
_deselect_tile()
return
@@ -652,18 +749,23 @@ func _input(event: InputEvent) -> void:
func _move_cursor(direction: Vector2i) -> void:
# Input validation for direction vector
if abs(direction.x) > 1 or abs(direction.y) > 1:
DebugManager.log_error("Invalid cursor direction vector: " + str(direction), "Match3")
DebugManager.log_error(
"Invalid cursor direction vector: " + str(direction), "Match3"
)
return
if direction.x != 0 and direction.y != 0:
DebugManager.log_error(
"Diagonal cursor movement not supported: " + str(direction), "Match3"
"Diagonal cursor movement not supported: " + str(direction),
"Match3"
)
return
# Validate grid integrity before cursor operations
if not _validate_grid_integrity():
DebugManager.log_error("Grid integrity check failed in cursor movement", "Match3")
DebugManager.log_error(
"Grid integrity check failed in cursor movement", "Match3"
)
return
var old_pos = cursor_position
@@ -676,19 +778,30 @@ func _move_cursor(direction: Vector2i) -> void:
if new_pos != cursor_position:
# Safe access to old tile
var old_tile = _safe_grid_access(old_pos)
if old_tile and "is_selected" in old_tile and "is_highlighted" in old_tile:
if (
old_tile
and "is_selected" in old_tile
and "is_highlighted" in old_tile
):
if not old_tile.is_selected:
old_tile.is_highlighted = false
DebugManager.log_debug(
"Cursor moved from (%d,%d) to (%d,%d)" % [old_pos.x, old_pos.y, new_pos.x, new_pos.y],
(
"Cursor moved from (%d,%d) to (%d,%d)"
% [old_pos.x, old_pos.y, new_pos.x, new_pos.y]
),
"Match3"
)
cursor_position = new_pos
# Safe access to new tile
var new_tile = _safe_grid_access(cursor_position)
if new_tile and "is_selected" in new_tile and "is_highlighted" in new_tile:
if (
new_tile
and "is_selected" in new_tile
and "is_highlighted" in new_tile
):
if not new_tile.is_selected:
new_tile.is_highlighted = true
@@ -708,13 +821,19 @@ func _select_tile_at_cursor() -> void:
var tile = _safe_grid_access(cursor_position)
if tile:
DebugManager.log_debug(
"Keyboard selection at cursor (%d,%d)" % [cursor_position.x, cursor_position.y],
(
"Keyboard selection at cursor (%d,%d)"
% [cursor_position.x, cursor_position.y]
),
"Match3"
)
_on_tile_selected(tile)
else:
DebugManager.log_warn(
"No valid tile at cursor position (%d,%d)" % [cursor_position.x, cursor_position.y],
(
"No valid tile at cursor position (%d,%d)"
% [cursor_position.x, cursor_position.y]
),
"Match3"
)
@@ -728,9 +847,15 @@ func _on_tile_selected(tile: Node2D) -> void:
SELECTING -> SWAPPING: Different tile clicked (attempt swap)
"""
# Block tile selection during busy states
if current_state == GameState.SWAPPING or current_state == GameState.PROCESSING:
if (
current_state == GameState.SWAPPING
or current_state == GameState.PROCESSING
):
DebugManager.log_debug(
"Tile selection ignored - game busy (state: %s)" % [GameState.keys()[current_state]],
(
"Tile selection ignored - game busy (state: %s)"
% [GameState.keys()[current_state]]
),
"Match3"
)
return
@@ -773,7 +898,11 @@ func _select_tile(tile: Node2D) -> void:
tile.is_selected = true
current_state = GameState.SELECTING # State transition: WAITING -> SELECTING
DebugManager.log_debug(
"Selected tile at (%d, %d)" % [tile.grid_position.x, tile.grid_position.y], "Match3"
(
"Selected tile at (%d, %d)"
% [tile.grid_position.x, tile.grid_position.y]
),
"Match3"
)
@@ -784,12 +913,17 @@ func _deselect_tile() -> void:
DebugManager.log_debug(
(
"Deselecting tile at (%d,%d)"
% [selected_tile.grid_position.x, selected_tile.grid_position.y]
% [
selected_tile.grid_position.x,
selected_tile.grid_position.y
]
),
"Match3"
)
else:
DebugManager.log_debug("Deselecting tile (no grid position available)", "Match3")
DebugManager.log_debug(
"Deselecting tile (no grid position available)", "Match3"
)
# Safe property access for selection state
if "is_selected" in selected_tile:
@@ -833,7 +967,9 @@ func _are_adjacent(tile1: Node2D, tile2: Node2D) -> bool:
func _attempt_swap(tile1: Node2D, tile2: Node2D) -> void:
if not _are_adjacent(tile1, tile2):
DebugManager.log_debug("Tiles are not adjacent, selecting new tile instead", "Match3")
DebugManager.log_debug(
"Tiles are not adjacent, selecting new tile instead", "Match3"
)
_deselect_tile()
_select_tile(tile2)
return
@@ -886,7 +1022,9 @@ func _attempt_swap(tile1: Node2D, tile2: Node2D) -> void:
func _swap_tiles(tile1: Node2D, tile2: Node2D) -> void:
if not tile1 or not tile2:
DebugManager.log_error("Cannot swap tiles - one or both tiles are null", "Match3")
DebugManager.log_error(
"Cannot swap tiles - one or both tiles are null", "Match3"
)
return
# Update grid positions
@@ -934,7 +1072,9 @@ func serialize_grid_state() -> Array:
)
if grid.size() == 0:
DebugManager.log_error("Grid array is empty during serialization!", "Match3")
DebugManager.log_error(
"Grid array is empty during serialization!", "Match3"
)
return []
var serialized_grid = []
@@ -950,7 +1090,11 @@ func serialize_grid_state() -> Array:
# Only log first few for brevity
if valid_tiles <= 5:
DebugManager.log_debug(
"Serializing tile (%d,%d): type %d" % [x, y, grid[y][x].tile_type], "Match3"
(
"Serializing tile (%d,%d): type %d"
% [x, y, grid[y][x].tile_type]
),
"Match3"
)
else:
row.append(-1) # Invalid/empty tile
@@ -958,7 +1102,8 @@ func serialize_grid_state() -> Array:
# Only log first few nulls for brevity
if null_tiles <= 5:
DebugManager.log_debug(
"Serializing tile (%d,%d): NULL/empty (-1)" % [x, y], "Match3"
"Serializing tile (%d,%d): NULL/empty (-1)" % [x, y],
"Match3"
)
serialized_grid.append(row)
@@ -1002,7 +1147,9 @@ func save_current_state():
func load_saved_state() -> bool:
# Check if there's a saved grid state
if not SaveManager.has_saved_grid():
DebugManager.log_info("No saved grid state found, using default generation", "Match3")
DebugManager.log_info(
"No saved grid state found, using default generation", "Match3"
)
return false
var saved_state = SaveManager.get_saved_grid_state()
@@ -1015,12 +1162,21 @@ func load_saved_state() -> bool:
saved_gems.append(int(gem))
var saved_layout = saved_state.grid_layout
DebugManager.log_info(
(
"[%s] Loading saved grid state: size(%d,%d), %d tile types, layout_size=%d"
% [instance_id, saved_size.x, saved_size.y, tile_types, saved_layout.size()]
),
"Match3"
(
DebugManager
. log_info(
(
"[%s] Loading saved grid state: size(%d,%d), %d tile types, layout_size=%d"
% [
instance_id,
saved_size.x,
saved_size.y,
tile_types,
saved_layout.size()
]
),
"Match3"
)
)
# Debug: Print first few rows of loaded layout
@@ -1058,7 +1214,10 @@ func load_saved_state() -> bool:
# Recalculate layout if size changed
if old_size != saved_size:
DebugManager.log_info(
"Grid size changed from %s to %s, recalculating layout" % [old_size, saved_size],
(
"Grid size changed from %s to %s, recalculating layout"
% [old_size, saved_size]
),
"Match3"
)
_calculate_grid_layout()
@@ -1069,7 +1228,9 @@ func load_saved_state() -> bool:
return true
func _restore_grid_from_layout(grid_layout: Array, active_gems: Array[int]) -> void:
func _restore_grid_from_layout(
grid_layout: Array, active_gems: Array[int]
) -> void:
DebugManager.log_info(
(
"[%s] Starting grid restoration: layout_size=%d, active_gems=%s"
@@ -1084,11 +1245,12 @@ func _restore_grid_from_layout(grid_layout: Array, active_gems: Array[int]) -> v
for child in get_children():
if child.has_method("get_script") and child.get_script():
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)
DebugManager.log_debug(
"Found %d existing tile children to remove" % all_tile_children.size(), "Match3"
"Found %d existing tile children to remove" % all_tile_children.size(),
"Match3"
)
# Remove all found tile children
@@ -1133,17 +1295,24 @@ func _restore_grid_from_layout(grid_layout: Array, active_gems: Array[int]) -> v
if saved_tile_type >= 0 and saved_tile_type < tile_types:
tile.tile_type = saved_tile_type
DebugManager.log_debug(
"✓ Restored tile (%d,%d) with saved type %d" % [x, y, saved_tile_type], "Match3"
(
"✓ Restored tile (%d,%d) with saved type %d"
% [x, y, saved_tile_type]
),
"Match3"
)
else:
# Fallback for invalid tile types
tile.tile_type = randi() % tile_types
DebugManager.log_error(
(
"✗ Invalid saved tile type %d at (%d,%d), using random %d"
% [saved_tile_type, x, y, tile.tile_type]
),
"Match3"
(
DebugManager
. log_error(
(
"✗ Invalid saved tile type %d at (%d,%d), using random %d"
% [saved_tile_type, x, y, tile.tile_type]
),
"Match3"
)
)
# Connect tile signals
@@ -1151,13 +1320,22 @@ func _restore_grid_from_layout(grid_layout: Array, active_gems: Array[int]) -> v
grid[y].append(tile)
DebugManager.log_info(
"Completed grid restoration: %d tiles restored" % [grid_size.x * grid_size.y], "Match3"
(
"Completed grid restoration: %d tiles restored"
% [grid_size.x * grid_size.y]
),
"Match3"
)
# Safety and validation helper functions
func _is_valid_grid_position(pos: Vector2i) -> bool:
return pos.x >= 0 and pos.y >= 0 and pos.x < grid_size.x and pos.y < grid_size.y
return (
pos.x >= 0
and pos.y >= 0
and pos.x < grid_size.x
and pos.y < grid_size.y
)
func _validate_grid_integrity() -> bool:
@@ -1168,7 +1346,8 @@ func _validate_grid_integrity() -> bool:
if grid.size() != grid_size.y:
DebugManager.log_error(
"Grid height mismatch: %d vs %d" % [grid.size(), grid_size.y], "Match3"
"Grid height mismatch: %d vs %d" % [grid.size(), grid_size.y],
"Match3"
)
return false
@@ -1179,7 +1358,11 @@ func _validate_grid_integrity() -> bool:
if grid[y].size() != grid_size.x:
DebugManager.log_error(
"Grid row %d width mismatch: %d vs %d" % [y, grid[y].size(), grid_size.x], "Match3"
(
"Grid row %d width mismatch: %d vs %d"
% [y, grid[y].size(), grid_size.x]
),
"Match3"
)
return false
@@ -1192,7 +1375,9 @@ func _safe_grid_access(pos: Vector2i) -> Node2D:
return null
if pos.y >= grid.size() or pos.x >= grid[pos.y].size():
DebugManager.log_warn("Grid bounds exceeded: (%d,%d)" % [pos.x, pos.y], "Match3")
DebugManager.log_warn(
"Grid bounds exceeded: (%d,%d)" % [pos.x, pos.y], "Match3"
)
return null
var tile = grid[pos.y][pos.x]

View File

@@ -11,7 +11,9 @@ extends RefCounted
## var grid_pos = Match3InputHandler.get_grid_position_from_world(node, world_pos, offset, size)
static func find_tile_at_position(grid: Array, grid_size: Vector2i, world_pos: Vector2) -> Node2D:
static func find_tile_at_position(
grid: Array, grid_size: Vector2i, world_pos: Vector2
) -> Node2D:
## Find the tile that contains the world position.
##
## Iterates through all tiles and checks if the world position falls within
@@ -31,7 +33,9 @@ static func find_tile_at_position(grid: Array, grid_size: Vector2i, world_pos: V
if tile and tile.has_node("Sprite2D"):
var sprite = tile.get_node("Sprite2D")
if sprite and sprite.texture:
var sprite_bounds = get_sprite_world_bounds(tile, sprite)
var sprite_bounds = get_sprite_world_bounds(
tile, sprite
)
if is_point_inside_rect(world_pos, sprite_bounds):
return tile
return null

View File

@@ -51,7 +51,9 @@ static func serialize_grid_state(grid: Array, grid_size: Vector2i) -> Array:
return serialized_grid
static func get_active_gem_types_from_grid(grid: Array, tile_types: int) -> Array:
static func get_active_gem_types_from_grid(
grid: Array, tile_types: int
) -> Array:
# Get active gem types from the first available tile
if grid.size() > 0 and grid[0].size() > 0 and grid[0][0]:
return grid[0][0].active_gem_types.duplicate()
@@ -94,7 +96,7 @@ static func restore_grid_from_layout(
for child in match3_node.get_children():
if child.has_method("get_script") and child.get_script():
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)
# Remove all found tile children
@@ -132,9 +134,15 @@ static func restore_grid_from_layout(
tile.tile_type = randi() % tile_types
# Connect tile signals
if tile.has_signal("tile_selected") and match3_node.has_method("_on_tile_selected"):
if (
tile.has_signal("tile_selected")
and match3_node.has_method("_on_tile_selected")
):
tile.tile_selected.connect(match3_node._on_tile_selected)
if tile.has_signal("tile_hovered") and match3_node.has_method("_on_tile_hovered"):
if (
tile.has_signal("tile_hovered")
and match3_node.has_method("_on_tile_hovered")
):
tile.tile_hovered.connect(match3_node._on_tile_hovered)
tile.tile_unhovered.connect(match3_node._on_tile_unhovered)

View File

@@ -25,7 +25,12 @@ static func is_valid_grid_position(pos: Vector2i, grid_size: Vector2i) -> bool:
##
## Returns:
## bool: True if position is valid, False if out of bounds
return pos.x >= 0 and pos.y >= 0 and pos.x < grid_size.x and pos.y < grid_size.y
return (
pos.x >= 0
and pos.y >= 0
and pos.x < grid_size.x
and pos.y < grid_size.y
)
static func validate_grid_integrity(grid: Array, grid_size: Vector2i) -> bool:
@@ -46,7 +51,8 @@ static func validate_grid_integrity(grid: Array, grid_size: Vector2i) -> bool:
if grid.size() != grid_size.y:
DebugManager.log_error(
"Grid height mismatch: %d vs %d" % [grid.size(), grid_size.y], "Match3"
"Grid height mismatch: %d vs %d" % [grid.size(), grid_size.y],
"Match3"
)
return false
@@ -57,20 +63,28 @@ static func validate_grid_integrity(grid: Array, grid_size: Vector2i) -> bool:
if grid[y].size() != grid_size.x:
DebugManager.log_error(
"Grid row %d width mismatch: %d vs %d" % [y, grid[y].size(), grid_size.x], "Match3"
(
"Grid row %d width mismatch: %d vs %d"
% [y, grid[y].size(), grid_size.x]
),
"Match3"
)
return false
return true
static func safe_grid_access(grid: Array, pos: Vector2i, grid_size: Vector2i) -> Node2D:
static func safe_grid_access(
grid: Array, pos: Vector2i, grid_size: Vector2i
) -> Node2D:
# Safe grid access with comprehensive bounds checking
if not is_valid_grid_position(pos, grid_size):
return null
if pos.y >= grid.size() or pos.x >= grid[pos.y].size():
DebugManager.log_warn("Grid bounds exceeded: (%d,%d)" % [pos.x, pos.y], "Match3")
DebugManager.log_warn(
"Grid bounds exceeded: (%d,%d)" % [pos.x, pos.y], "Match3"
)
return null
var tile = grid[pos.y][pos.x]

View File

@@ -123,7 +123,9 @@ func remove_gem_type(gem_index: int) -> bool:
return false
if active_gem_types.size() <= 2: # Keep at least 2 gem types
DebugManager.log_warn("Cannot remove gem type - minimum 2 types required", "Tile")
DebugManager.log_warn(
"Cannot remove gem type - minimum 2 types required", "Tile"
)
return false
active_gem_types.erase(gem_index)
@@ -178,7 +180,12 @@ func _update_visual_feedback() -> void:
DebugManager.log_debug(
(
"SELECTING tile (%d,%d): target scale %.2fx, current scale %s"
% [grid_position.x, grid_position.y, scale_multiplier, sprite.scale]
% [
grid_position.x,
grid_position.y,
scale_multiplier,
sprite.scale
]
),
"Match3"
)
@@ -186,12 +193,20 @@ func _update_visual_feedback() -> void:
# Highlighted: subtle glow and larger than original board size
target_modulate = Color(1.1, 1.1, 1.1, 1.0)
scale_multiplier = UIConstants.TILE_HIGHLIGHTED_SCALE
DebugManager.log_debug(
(
"HIGHLIGHTING tile (%d,%d): target scale %.2fx, current scale %s"
% [grid_position.x, grid_position.y, scale_multiplier, sprite.scale]
),
"Match3"
(
DebugManager
. log_debug(
(
"HIGHLIGHTING tile (%d,%d): target scale %.2fx, current scale %s"
% [
grid_position.x,
grid_position.y,
scale_multiplier,
sprite.scale
]
),
"Match3"
)
)
else:
# Normal state: white and original board size
@@ -200,7 +215,12 @@ func _update_visual_feedback() -> void:
DebugManager.log_debug(
(
"NORMALIZING tile (%d,%d): target scale %.2fx, current scale %s"
% [grid_position.x, grid_position.y, scale_multiplier, sprite.scale]
% [
grid_position.x,
grid_position.y,
scale_multiplier,
sprite.scale
]
),
"Match3"
)
@@ -228,7 +248,11 @@ func _update_visual_feedback() -> void:
tween.tween_callback(_on_scale_animation_completed.bind(target_scale))
else:
DebugManager.log_debug(
"No scale change needed for tile (%d,%d)" % [grid_position.x, grid_position.y], "Match3"
(
"No scale change needed for tile (%d,%d)"
% [grid_position.x, grid_position.y]
),
"Match3"
)
@@ -264,7 +288,9 @@ func _input(event: InputEvent) -> void:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
# Check if the mouse click is within the tile's bounds
var local_position = to_local(get_global_mouse_position())
var sprite_rect = Rect2(-TILE_SIZE / 2.0, -TILE_SIZE / 2.0, TILE_SIZE, TILE_SIZE)
var sprite_rect = Rect2(
-TILE_SIZE / 2.0, -TILE_SIZE / 2.0, TILE_SIZE, TILE_SIZE
)
if sprite_rect.has_point(local_position):
tile_selected.emit(self)

View File

@@ -1,6 +1,6 @@
[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"]
script = ExtResource("1_tile_script")

View File

@@ -22,7 +22,9 @@ func _setup_splash_screen_connection() -> void:
# Try to find SplashScreen node
splash_screen = get_node_or_null("SplashScreen")
if not splash_screen:
DebugManager.log_warn("SplashScreen node not found, trying alternative methods", "Main")
DebugManager.log_warn(
"SplashScreen node not found, trying alternative methods", "Main"
)
# Try to find by class or group
var splash_nodes = get_tree().get_nodes_in_group("localizable")
for node in splash_nodes:
@@ -31,11 +33,15 @@ func _setup_splash_screen_connection() -> void:
break
if splash_screen:
DebugManager.log_debug("SplashScreen node found: %s" % splash_screen.name, "Main")
DebugManager.log_debug(
"SplashScreen node found: %s" % splash_screen.name, "Main"
)
# Try connecting to the signal if it exists
if splash_screen.has_signal("confirm_pressed"):
splash_screen.confirm_pressed.connect(_on_confirm_pressed)
DebugManager.log_debug("Connected to confirm_pressed signal", "Main")
DebugManager.log_debug(
"Connected to confirm_pressed signal", "Main"
)
else:
# Fallback: use input handling directly on the main scene
DebugManager.log_warn("Using fallback input handling", "Main")

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="PackedScene" uid="uid://gbe1jarrwqsi" path="res://scenes/main/SplashScreen.tscn" id="1_o5qli"]

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

@@ -0,0 +1,289 @@
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

@@ -17,12 +17,16 @@ func _find_target_scene():
# Fallback: search by common node names
if not match3_scene:
for possible_name in ["Match3", "match3", "Match3Game"]:
match3_scene = current_scene.find_child(possible_name, true, false)
match3_scene = current_scene.find_child(
possible_name, true, false
)
if match3_scene:
break
if match3_scene:
DebugManager.log_debug("Found match3 scene: " + match3_scene.name, log_category)
DebugManager.log_debug(
"Found match3 scene: " + match3_scene.name, log_category
)
_update_ui_from_scene()
_stop_search_timer()
else:

View File

@@ -8,7 +8,8 @@ const MIN_GRID_SIZE := 3
const MIN_TILE_TYPES := 3
const SCENE_SEARCH_COOLDOWN := 0.5
@export var target_script_path: String = "res://scenes/game/gameplays/Match3Gameplay.gd"
@export
var target_script_path: String = "res://scenes/game/gameplays/Match3Gameplay.gd"
@export var log_category: String = "DebugMenu"
var match3_scene: Node2D
@@ -16,8 +17,10 @@ var search_timer: Timer
var last_scene_search_time: float = 0.0
@onready var regenerate_button: Button = $VBoxContainer/RegenerateButton
@onready var gem_types_spinbox: SpinBox = $VBoxContainer/GemTypesContainer/GemTypesSpinBox
@onready var gem_types_label: Label = $VBoxContainer/GemTypesContainer/GemTypesLabel
@onready
var gem_types_spinbox: SpinBox = $VBoxContainer/GemTypesContainer/GemTypesSpinBox
@onready
var gem_types_label: Label = $VBoxContainer/GemTypesContainer/GemTypesLabel
@onready
var grid_width_spinbox: SpinBox = $VBoxContainer/GridSizeContainer/GridWidthContainer/GridWidthSpinBox
@onready
@@ -86,7 +89,9 @@ func _setup_scene_finding() -> void:
# Virtual method - override in derived classes for specific finding logic
func _find_target_scene() -> void:
DebugManager.log_error("_find_target_scene() not implemented in derived class", log_category)
DebugManager.log_error(
"_find_target_scene() not implemented in derived class", log_category
)
func _find_node_by_script(node: Node, script_path: String) -> Node:
@@ -114,10 +119,14 @@ func _update_ui_from_scene() -> void:
# Connect to grid state loaded signal if not already connected
if (
match3_scene.has_signal("grid_state_loaded")
and not match3_scene.grid_state_loaded.is_connected(_on_grid_state_loaded)
and not match3_scene.grid_state_loaded.is_connected(
_on_grid_state_loaded
)
):
match3_scene.grid_state_loaded.connect(_on_grid_state_loaded)
DebugManager.log_debug("Connected to grid_state_loaded signal", log_category)
DebugManager.log_debug(
"Connected to grid_state_loaded signal", log_category
)
# Update gem types display
if match3_scene.has_method("get") and "TILE_TYPES" in match3_scene:
@@ -135,7 +144,10 @@ func _update_ui_from_scene() -> void:
func _on_grid_state_loaded(grid_size: Vector2i, tile_types: int) -> void:
DebugManager.log_debug(
"Grid state loaded signal received: size=%s, types=%d" % [grid_size, tile_types],
(
"Grid state loaded signal received: size=%s, types=%d"
% [grid_size, tile_types]
),
log_category
)
@@ -155,7 +167,10 @@ func _stop_search_timer() -> void:
func _start_search_timer() -> void:
if search_timer and not search_timer.timeout.is_connected(_find_target_scene):
if (
search_timer
and not search_timer.timeout.is_connected(_find_target_scene)
):
search_timer.timeout.connect(_find_target_scene)
search_timer.start()
@@ -176,7 +191,8 @@ func _refresh_current_values() -> void:
# Refresh UI with current values from the scene
if match3_scene:
DebugManager.log_debug(
"Refreshing debug menu values from current scene state", log_category
"Refreshing debug menu values from current scene state",
log_category
)
_update_ui_from_scene()
@@ -186,14 +202,18 @@ func _on_regenerate_pressed() -> void:
_find_target_scene()
if not match3_scene:
DebugManager.log_error("Could not find target scene for regeneration", log_category)
DebugManager.log_error(
"Could not find target scene for regeneration", log_category
)
return
if match3_scene.has_method("regenerate_grid"):
DebugManager.log_debug("Calling regenerate_grid()", log_category)
await match3_scene.regenerate_grid()
else:
DebugManager.log_error("Target scene does not have regenerate_grid method", log_category)
DebugManager.log_error(
"Target scene does not have regenerate_grid method", log_category
)
func _on_gem_types_changed(value: float) -> void:
@@ -207,7 +227,9 @@ func _on_gem_types_changed(value: float) -> void:
last_scene_search_time = current_time
if not match3_scene:
DebugManager.log_error("Could not find target scene for gem types change", log_category)
DebugManager.log_error(
"Could not find target scene for gem types change", log_category
)
return
var new_value: int = int(value)
@@ -221,15 +243,21 @@ func _on_gem_types_changed(value: float) -> void:
log_category
)
# Reset to valid value
gem_types_spinbox.value = clamp(new_value, MIN_TILE_TYPES, MAX_TILE_TYPES)
gem_types_spinbox.value = clamp(
new_value, MIN_TILE_TYPES, MAX_TILE_TYPES
)
return
if match3_scene.has_method("set_tile_types"):
DebugManager.log_debug("Setting tile types to " + str(new_value), log_category)
DebugManager.log_debug(
"Setting tile types to " + str(new_value), log_category
)
await match3_scene.set_tile_types(new_value)
gem_types_label.text = "Gem Types: " + str(new_value)
else:
DebugManager.log_error("Target scene does not have set_tile_types method", log_category)
DebugManager.log_error(
"Target scene does not have set_tile_types method", log_category
)
# Fallback: try to set TILE_TYPES directly
if "TILE_TYPES" in match3_scene:
match3_scene.TILE_TYPES = new_value
@@ -247,7 +275,9 @@ func _on_grid_width_changed(value: float) -> void:
last_scene_search_time = current_time
if not match3_scene:
DebugManager.log_error("Could not find target scene for grid width change", log_category)
DebugManager.log_error(
"Could not find target scene for grid width change", log_category
)
return
var new_width: int = int(value)
@@ -261,7 +291,9 @@ func _on_grid_width_changed(value: float) -> void:
log_category
)
# Reset to valid value
grid_width_spinbox.value = clamp(new_width, MIN_GRID_SIZE, MAX_GRID_SIZE)
grid_width_spinbox.value = clamp(
new_width, MIN_GRID_SIZE, MAX_GRID_SIZE
)
return
grid_width_label.text = "Width: " + str(new_width)
@@ -271,11 +303,19 @@ func _on_grid_width_changed(value: float) -> void:
if match3_scene.has_method("set_grid_size"):
DebugManager.log_debug(
"Setting grid size to " + str(new_width) + "x" + str(current_height), log_category
(
"Setting grid size to "
+ str(new_width)
+ "x"
+ str(current_height)
),
log_category
)
await match3_scene.set_grid_size(Vector2i(new_width, current_height))
else:
DebugManager.log_error("Target scene does not have set_grid_size method", log_category)
DebugManager.log_error(
"Target scene does not have set_grid_size method", log_category
)
func _on_grid_height_changed(value: float) -> void:
@@ -289,7 +329,9 @@ func _on_grid_height_changed(value: float) -> void:
last_scene_search_time = current_time
if not match3_scene:
DebugManager.log_error("Could not find target scene for grid height change", log_category)
DebugManager.log_error(
"Could not find target scene for grid height change", log_category
)
return
var new_height: int = int(value)
@@ -303,7 +345,9 @@ func _on_grid_height_changed(value: float) -> void:
log_category
)
# Reset to valid value
grid_height_spinbox.value = clamp(new_height, MIN_GRID_SIZE, MAX_GRID_SIZE)
grid_height_spinbox.value = clamp(
new_height, MIN_GRID_SIZE, MAX_GRID_SIZE
)
return
grid_height_label.text = "Height: " + str(new_height)
@@ -313,8 +357,16 @@ func _on_grid_height_changed(value: float) -> void:
if match3_scene.has_method("set_grid_size"):
DebugManager.log_debug(
"Setting grid size to " + str(current_width) + "x" + str(new_height), log_category
(
"Setting grid size to "
+ str(current_width)
+ "x"
+ str(new_height)
),
log_category
)
await match3_scene.set_grid_size(Vector2i(current_width, new_height))
else:
DebugManager.log_error("Target scene does not have set_grid_size method", log_category)
DebugManager.log_error(
"Target scene does not have set_grid_size method", log_category
)

View File

@@ -31,6 +31,12 @@ func _on_settings_button_pressed() -> void:
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:
AudioManager.play_ui_click()
DebugManager.log_info("Exit pressed", "MainMenu")
@@ -43,6 +49,7 @@ func _setup_menu_navigation() -> void:
menu_buttons.append($MenuContainer/NewGameButton)
menu_buttons.append($MenuContainer/SettingsButton)
menu_buttons.append($MenuContainer/CreditsButton)
menu_buttons.append($MenuContainer/ExitButton)
for button in menu_buttons:
@@ -74,13 +81,17 @@ func _navigate_menu(direction: int) -> void:
if current_menu_index < 0:
current_menu_index = menu_buttons.size() - 1
_update_visual_selection()
DebugManager.log_info("Menu navigation: index " + str(current_menu_index), "MainMenu")
DebugManager.log_info(
"Menu navigation: index " + str(current_menu_index), "MainMenu"
)
func _activate_current_button() -> void:
if current_menu_index >= 0 and current_menu_index < menu_buttons.size():
var button: Button = menu_buttons[current_menu_index]
DebugManager.log_info("Activating button via keyboard/gamepad: " + button.text, "MainMenu")
DebugManager.log_info(
"Activating button via keyboard/gamepad: " + button.text, "MainMenu"
)
button.pressed.emit()
@@ -88,7 +99,9 @@ func _update_visual_selection() -> void:
for i in range(menu_buttons.size()):
var button: Button = menu_buttons[i]
if i == current_menu_index:
button.scale = original_button_scales[i] * UIConstants.BUTTON_HOVER_SCALE
button.scale = (
original_button_scales[i] * UIConstants.BUTTON_HOVER_SCALE
)
button.modulate = Color(1.2, 1.2, 1.0)
else:
button.scale = original_button_scales[i]

View File

@@ -111,6 +111,10 @@ text = "New Game"
layout_mode = 2
text = "Settings"
[node name="CreditsButton" type="Button" parent="MenuContainer"]
layout_mode = 2
text = "Credits"
[node name="ExitButton" type="Button" parent="MenuContainer"]
layout_mode = 2
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/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"]

View File

@@ -14,10 +14,13 @@ var current_control_index: int = 0
var original_control_scales: Array[Vector2] = []
var original_control_modulates: Array[Color] = []
@onready var master_slider = $SettingsContainer/MasterVolumeContainer/MasterVolumeSlider
@onready var music_slider = $SettingsContainer/MusicVolumeContainer/MusicVolumeSlider
@onready
var master_slider = $SettingsContainer/MasterVolumeContainer/MasterVolumeSlider
@onready
var music_slider = $SettingsContainer/MusicVolumeContainer/MusicVolumeSlider
@onready var sfx_slider = $SettingsContainer/SFXVolumeContainer/SFXVolumeSlider
@onready var language_stepper = $SettingsContainer/LanguageContainer/LanguageStepper
@onready
var language_stepper = $SettingsContainer/LanguageContainer/LanguageStepper
@onready var reset_progress_button = $ResetSettingsContainer/ResetProgressButton
@@ -26,11 +29,15 @@ func _ready() -> void:
DebugManager.log_info("SettingsMenu ready", "Settings")
# Language selector is initialized automatically
var master_callback: Callable = _on_volume_slider_changed.bind("master_volume")
var master_callback: Callable = _on_volume_slider_changed.bind(
"master_volume"
)
if not master_slider.value_changed.is_connected(master_callback):
master_slider.value_changed.connect(master_callback)
var music_callback: Callable = _on_volume_slider_changed.bind("music_volume")
var music_callback: Callable = _on_volume_slider_changed.bind(
"music_volume"
)
if not music_slider.value_changed.is_connected(music_callback):
music_slider.value_changed.connect(music_callback)
@@ -57,20 +64,28 @@ func _update_controls_from_settings() -> void:
func _on_volume_slider_changed(value: float, setting_key: String) -> void:
# Input validation for volume settings
if not setting_key in ["master_volume", "music_volume", "sfx_volume"]:
DebugManager.log_error("Invalid volume setting key: " + str(setting_key), "Settings")
DebugManager.log_error(
"Invalid volume setting key: " + str(setting_key), "Settings"
)
return
if typeof(value) != TYPE_FLOAT and typeof(value) != TYPE_INT:
DebugManager.log_error("Invalid volume value type: " + str(typeof(value)), "Settings")
DebugManager.log_error(
"Invalid volume value type: " + str(typeof(value)), "Settings"
)
return
# Clamp value to valid range
var clamped_value: float = clamp(float(value), 0.0, 1.0)
if clamped_value != value:
DebugManager.log_warn("Volume value %f clamped to %f" % [value, clamped_value], "Settings")
DebugManager.log_warn(
"Volume value %f clamped to %f" % [value, clamped_value], "Settings"
)
if not settings_manager.set_setting(setting_key, clamped_value):
DebugManager.log_error("Failed to set volume setting: " + setting_key, "Settings")
DebugManager.log_error(
"Failed to set volume setting: " + setting_key, "Settings"
)
func _exit_settings() -> void:
@@ -80,8 +95,13 @@ func _exit_settings() -> void:
func _input(event: InputEvent) -> void:
if event.is_action_pressed("action_east") or event.is_action_pressed("pause_menu"):
DebugManager.log_debug("Cancel/back action pressed in settings", "Settings")
if (
event.is_action_pressed("action_east")
or event.is_action_pressed("pause_menu")
):
DebugManager.log_debug(
"Cancel/back action pressed in settings", "Settings"
)
_exit_settings()
get_viewport().set_input_as_handled()
return
@@ -116,8 +136,12 @@ func _on_back_button_pressed() -> void:
func update_text() -> void:
$SettingsContainer/SettingsTitle.text = tr("settings_title")
$SettingsContainer/MasterVolumeContainer/MasterVolume.text = tr("master_volume")
$SettingsContainer/MusicVolumeContainer/MusicVolume.text = tr("music_volume")
$SettingsContainer/MasterVolumeContainer/MasterVolume.text = tr(
"master_volume"
)
$SettingsContainer/MusicVolumeContainer/MusicVolume.text = tr(
"music_volume"
)
$SettingsContainer/SFXVolumeContainer/SFXVolume.text = tr("sfx_volume")
$SettingsContainer/LanguageContainer/LanguageLabel.text = tr("language")
$BackButtonContainer/BackButton.text = tr("back")
@@ -129,7 +153,9 @@ func _on_reset_setting_button_pressed() -> void:
DebugManager.log_info("Resetting settings", "Settings")
settings_manager.reset_settings_to_defaults()
_update_controls_from_settings()
localization_manager.change_language(settings_manager.get_setting("language"))
localization_manager.change_language(
settings_manager.get_setting("language")
)
func _setup_navigation_system() -> void:
@@ -156,15 +182,22 @@ func _setup_navigation_system() -> void:
func _navigate_controls(direction: int) -> void:
AudioManager.play_ui_click()
current_control_index = (current_control_index + direction) % navigable_controls.size()
current_control_index = (
(current_control_index + direction) % navigable_controls.size()
)
if current_control_index < 0:
current_control_index = navigable_controls.size() - 1
_update_visual_selection()
DebugManager.log_info("Settings navigation: index " + str(current_control_index), "Settings")
DebugManager.log_info(
"Settings navigation: index " + str(current_control_index), "Settings"
)
func _adjust_current_control(direction: int) -> void:
if current_control_index < 0 or current_control_index >= navigable_controls.size():
if (
current_control_index < 0
or current_control_index >= navigable_controls.size()
):
return
var control: Control = navigable_controls[current_control_index]
@@ -178,17 +211,26 @@ func _adjust_current_control(direction: int) -> void:
slider.value = new_value
AudioManager.play_ui_click()
DebugManager.log_info(
"Slider adjusted: %s = %f" % [_get_control_name(control), new_value], "Settings"
(
"Slider adjusted: %s = %f"
% [_get_control_name(control), new_value]
),
"Settings"
)
# Handle language stepper with left/right
elif control == language_stepper:
if language_stepper.handle_input_action("move_left" if direction == -1 else "move_right"):
if language_stepper.handle_input_action(
"move_left" if direction == -1 else "move_right"
):
AudioManager.play_ui_click()
func _activate_current_control() -> void:
if current_control_index < 0 or current_control_index >= navigable_controls.size():
if (
current_control_index < 0
or current_control_index >= navigable_controls.size()
):
return
var control: Control = navigable_controls[current_control_index]
@@ -196,12 +238,17 @@ func _activate_current_control() -> void:
# Handle buttons
if control is Button:
AudioManager.play_ui_click()
DebugManager.log_info("Activating button via keyboard/gamepad: " + control.text, "Settings")
DebugManager.log_info(
"Activating button via keyboard/gamepad: " + control.text,
"Settings"
)
control.pressed.emit()
# Handle language stepper (no action needed on activation, left/right handles it)
elif control == language_stepper:
DebugManager.log_info("Language stepper selected - use left/right to change", "Settings")
DebugManager.log_info(
"Language stepper selected - use left/right to change", "Settings"
)
func _update_visual_selection() -> void:
@@ -212,7 +259,10 @@ func _update_visual_selection() -> void:
if control == language_stepper:
language_stepper.set_highlighted(true)
else:
control.scale = original_control_scales[i] * UIConstants.UI_CONTROL_HIGHLIGHT_SCALE
control.scale = (
original_control_scales[i]
* UIConstants.UI_CONTROL_HIGHLIGHT_SCALE
)
control.modulate = Color(1.1, 1.1, 0.9)
else:
# Reset highlighting
@@ -235,9 +285,17 @@ func _get_control_name(control: Control) -> String:
return "button"
func _on_language_stepper_value_changed(new_value: String, new_index: float) -> void:
func _on_language_stepper_value_changed(
new_value: String, new_index: float
) -> void:
DebugManager.log_info(
"Language changed via ValueStepper: " + new_value + " (index: " + str(int(new_index)) + ")",
(
"Language changed via ValueStepper: "
+ new_value
+ " (index: "
+ str(int(new_index))
+ ")"
),
"Settings"
)

View File

@@ -30,17 +30,25 @@ var is_highlighted: bool = false
func _ready() -> void:
DebugManager.log_info("ValueStepper ready for: " + data_source, "ValueStepper")
DebugManager.log_info(
"ValueStepper ready for: " + data_source, "ValueStepper"
)
# Store original visual properties
original_scale = scale
original_modulate = modulate
# Connect button signals
if left_button and not left_button.pressed.is_connected(_on_left_button_pressed):
if (
left_button
and not left_button.pressed.is_connected(_on_left_button_pressed)
):
left_button.pressed.connect(_on_left_button_pressed)
if right_button and not right_button.pressed.is_connected(_on_right_button_pressed):
if (
right_button
and not right_button.pressed.is_connected(_on_right_button_pressed)
):
right_button.pressed.connect(_on_right_button_pressed)
# Initialize data
@@ -58,7 +66,9 @@ func _load_data() -> void:
"difficulty":
_load_difficulty_data()
_:
DebugManager.log_warn("Unknown data_source: " + data_source, "ValueStepper")
DebugManager.log_warn(
"Unknown data_source: " + data_source, "ValueStepper"
)
func _load_language_data() -> void:
@@ -68,22 +78,30 @@ func _load_language_data() -> void:
display_names.clear()
for lang_code in languages_data.languages.keys():
values.append(lang_code)
display_names.append(languages_data.languages[lang_code]["display_name"])
display_names.append(
languages_data.languages[lang_code]["display_name"]
)
# Set current index based on current language
var current_lang: String = SettingsManager.get_setting("language")
var index: int = values.find(current_lang)
current_index = max(0, index)
DebugManager.log_info("Loaded %d languages" % values.size(), "ValueStepper")
DebugManager.log_info(
"Loaded %d languages" % values.size(), "ValueStepper"
)
func _load_resolution_data() -> void:
# Example resolution data - customize as needed
values = ["1920x1080", "1366x768", "1280x720", "1024x768"]
display_names = ["1920×1080 (Full HD)", "1366×768", "1280×720 (HD)", "1024×768"]
display_names = [
"1920×1080 (Full HD)", "1366×768", "1280×720 (HD)", "1024×768"
]
current_index = 0
DebugManager.log_info("Loaded %d resolutions" % values.size(), "ValueStepper")
DebugManager.log_info(
"Loaded %d resolutions" % values.size(), "ValueStepper"
)
func _load_difficulty_data() -> void:
@@ -91,12 +109,18 @@ func _load_difficulty_data() -> void:
values = ["easy", "normal", "hard", "nightmare"]
display_names = ["Easy", "Normal", "Hard", "Nightmare"]
current_index = 1 # Default to "normal"
DebugManager.log_info("Loaded %d difficulty levels" % values.size(), "ValueStepper")
DebugManager.log_info(
"Loaded %d difficulty levels" % values.size(), "ValueStepper"
)
## Updates the display text based on current selection
func _update_display() -> void:
if values.size() == 0 or current_index < 0 or current_index >= values.size():
if (
values.size() == 0
or current_index < 0
or current_index >= values.size()
):
value_display.text = "N/A"
return
@@ -109,7 +133,9 @@ func _update_display() -> void:
## Changes the current value by the specified direction (-1 for previous, +1 for next)
func change_value(direction: int) -> void:
if values.size() == 0:
DebugManager.log_warn("No values available for: " + data_source, "ValueStepper")
DebugManager.log_warn(
"No values available for: " + data_source, "ValueStepper"
)
return
var new_index: int = (current_index + direction) % values.size()
@@ -123,7 +149,14 @@ func change_value(direction: int) -> void:
_apply_value_change(new_value, current_index)
value_changed.emit(new_value, current_index)
DebugManager.log_info(
"Value changed to: " + new_value + " (index: " + str(current_index) + ")", "ValueStepper"
(
"Value changed to: "
+ new_value
+ " (index: "
+ str(current_index)
+ ")"
),
"ValueStepper"
)
@@ -136,10 +169,14 @@ func _apply_value_change(new_value: String, _index: int) -> void:
LocalizationManager.change_language(new_value)
"resolution":
# Apply resolution change logic here
DebugManager.log_info("Resolution would change to: " + new_value, "ValueStepper")
DebugManager.log_info(
"Resolution would change to: " + new_value, "ValueStepper"
)
"difficulty":
# Apply difficulty change logic here
DebugManager.log_info("Difficulty would change to: " + new_value, "ValueStepper")
DebugManager.log_info(
"Difficulty would change to: " + new_value, "ValueStepper"
)
## Sets up custom values for the stepper
@@ -148,16 +185,24 @@ func setup_custom_values(
) -> void:
values = custom_values.duplicate()
display_names = (
custom_display_names.duplicate() if custom_display_names.size() > 0 else values.duplicate()
custom_display_names.duplicate()
if custom_display_names.size() > 0
else values.duplicate()
)
current_index = 0
_update_display()
DebugManager.log_info("Setup custom values: " + str(values.size()) + " items", "ValueStepper")
DebugManager.log_info(
"Setup custom values: " + str(values.size()) + " items", "ValueStepper"
)
## Gets the current value
func get_current_value() -> String:
if values.size() > 0 and current_index >= 0 and current_index < values.size():
if (
values.size() > 0
and current_index >= 0
and current_index < values.size()
):
return values[current_index]
return ""

View File

@@ -22,7 +22,9 @@ func _ready():
var orig_stream = _load_stream()
if not orig_stream:
DebugManager.log_error("Failed to load music stream: %s" % MUSIC_PATH, "AudioManager")
DebugManager.log_error(
"Failed to load music stream: %s" % MUSIC_PATH, "AudioManager"
)
return
var stream = orig_stream.duplicate(true) as AudioStream
@@ -52,7 +54,9 @@ func _configure_stream_loop(stream: AudioStream) -> void:
func _configure_audio_bus() -> void:
music_player.bus = "Music"
music_player.volume_db = linear_to_db(SettingsManager.get_setting("music_volume"))
music_player.volume_db = linear_to_db(
SettingsManager.get_setting("music_volume")
)
func update_music_volume(volume: float) -> void:

View File

@@ -83,7 +83,9 @@ func _log_level_to_string(level: LogLevel) -> String:
return level_strings.get(level, "UNKNOWN")
func _format_log_message(level: LogLevel, message: String, category: String = "") -> String:
func _format_log_message(
level: LogLevel, message: String, category: String = ""
) -> String:
"""Format log message with timestamp, level, category, and content"""
var timestamp = Time.get_datetime_string_from_system()
var level_str = _log_level_to_string(level)

View File

@@ -6,8 +6,9 @@
extends Node
const GAME_SCENE_PATH := "res://scenes/game/game.tscn"
const MAIN_SCENE_PATH := "res://scenes/main/main.tscn"
const GAME_SCENE_PATH := "res://scenes/game/Game.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 is_changing_scene: bool = false
@@ -48,14 +49,17 @@ func start_game_with_mode(gameplay_mode: String) -> void:
var packed_scene := load(GAME_SCENE_PATH)
if not packed_scene or not packed_scene is PackedScene:
DebugManager.log_error("Failed to load Game scene at: %s" % GAME_SCENE_PATH, "GameManager")
DebugManager.log_error(
"Failed to load Game scene at: %s" % GAME_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 game scene (Error code: %d)" % result, "GameManager"
"Failed to change to game scene (Error code: %d)" % result,
"GameManager"
)
is_changing_scene = false
return
@@ -66,22 +70,31 @@ func start_game_with_mode(gameplay_mode: String) -> void:
# Validate scene was loaded successfully
if not get_tree().current_scene:
DebugManager.log_error("Current scene is null after scene change", "GameManager")
DebugManager.log_error(
"Current scene is null after scene change", "GameManager"
)
is_changing_scene = false
return
# Configure game scene with requested gameplay mode
if get_tree().current_scene.has_method("set_gameplay_mode"):
DebugManager.log_info("Setting gameplay mode to: %s" % pending_gameplay_mode, "GameManager")
DebugManager.log_info(
"Setting gameplay mode to: %s" % pending_gameplay_mode,
"GameManager"
)
get_tree().current_scene.set_gameplay_mode(pending_gameplay_mode)
# Load saved score
if get_tree().current_scene.has_method("set_global_score"):
var saved_score = SaveManager.get_current_score()
DebugManager.log_info("Loading saved score: %d" % saved_score, "GameManager")
DebugManager.log_info(
"Loading saved score: %d" % saved_score, "GameManager"
)
get_tree().current_scene.set_global_score(saved_score)
else:
DebugManager.log_error("Game scene does not have set_gameplay_mode method", "GameManager")
DebugManager.log_error(
"Game scene does not have set_gameplay_mode method", "GameManager"
)
is_changing_scene = false
@@ -90,19 +103,66 @@ func save_game() -> void:
"""Save current game state and score via SaveManager"""
# Get current score from the active game scene
var current_score = 0
if get_tree().current_scene and get_tree().current_scene.has_method("get_global_score"):
if (
get_tree().current_scene
and get_tree().current_scene.has_method("get_global_score")
):
current_score = get_tree().current_scene.get_global_score()
SaveManager.finish_game(current_score)
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:
"""Exit to main menu with race condition protection"""
# Prevent concurrent scene changes
if is_changing_scene:
DebugManager.log_warn(
"Scene change already in progress, ignoring exit to main menu request", "GameManager"
(
DebugManager
. log_warn(
"Scene change already in progress, ignoring exit to main menu request",
"GameManager"
)
)
return
@@ -111,14 +171,17 @@ func exit_to_main_menu() -> void:
var packed_scene := load(MAIN_SCENE_PATH)
if not packed_scene or not packed_scene is PackedScene:
DebugManager.log_error("Failed to load Main scene at: %s" % MAIN_SCENE_PATH, "GameManager")
DebugManager.log_error(
"Failed to load Main scene at: %s" % MAIN_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 main scene (Error code: %d)" % result, "GameManager"
"Failed to change to main scene (Error code: %d)" % result,
"GameManager"
)
is_changing_scene = false
return
@@ -134,25 +197,33 @@ func _validate_game_mode_request(gameplay_mode: String) -> bool:
"""Validate gameplay mode request with combined checks"""
# Input validation
if not gameplay_mode or gameplay_mode.is_empty():
DebugManager.log_error("Empty or null gameplay mode provided", "GameManager")
DebugManager.log_error(
"Empty or null gameplay mode provided", "GameManager"
)
return false
if not gameplay_mode is String:
DebugManager.log_error(
"Invalid gameplay mode type: " + str(typeof(gameplay_mode)), "GameManager"
"Invalid gameplay mode type: " + str(typeof(gameplay_mode)),
"GameManager"
)
return false
# Prevent concurrent scene changes (race condition protection)
if is_changing_scene:
DebugManager.log_warn("Scene change already in progress, ignoring request", "GameManager")
DebugManager.log_warn(
"Scene change already in progress, ignoring request", "GameManager"
)
return false
# Validate gameplay mode
var valid_modes = ["match3", "clickomania"]
if not gameplay_mode in valid_modes:
DebugManager.log_error(
"Invalid gameplay mode: '%s'. Valid modes: %s" % [gameplay_mode, str(valid_modes)],
(
"Invalid gameplay mode: '%s'. Valid modes: %s"
% [gameplay_mode, str(valid_modes)]
),
"GameManager"
)
return false

View File

@@ -42,7 +42,9 @@ func save_game() -> bool:
"""Save current game data with race condition protection and error handling"""
# Prevent concurrent saves
if _save_in_progress:
DebugManager.log_warn("Save already in progress, skipping", "SaveManager")
DebugManager.log_warn(
"Save already in progress, skipping", "SaveManager"
)
return false
_save_in_progress = true
@@ -61,10 +63,13 @@ func _perform_save() -> bool:
# Calculate checksum excluding _checksum field
save_data["_checksum"] = _calculate_checksum(save_data)
var save_file: FileAccess = FileAccess.open(SAVE_FILE_PATH, FileAccess.WRITE)
var save_file: FileAccess = FileAccess.open(
SAVE_FILE_PATH, FileAccess.WRITE
)
if save_file == null:
DebugManager.log_error(
"Failed to open save file for writing: %s" % SAVE_FILE_PATH, "SaveManager"
"Failed to open save file for writing: %s" % SAVE_FILE_PATH,
"SaveManager"
)
return false
@@ -72,7 +77,9 @@ func _perform_save() -> bool:
# Validate JSON creation
if json_string.is_empty():
DebugManager.log_error("Failed to serialize save data to JSON", "SaveManager")
DebugManager.log_error(
"Failed to serialize save data to JSON", "SaveManager"
)
save_file.close()
return false
@@ -92,7 +99,9 @@ func _perform_save() -> bool:
func load_game() -> void:
"""Load game data from disk with comprehensive validation and error recovery"""
if not FileAccess.file_exists(SAVE_FILE_PATH):
DebugManager.log_info("No save file found, using defaults", "SaveManager")
DebugManager.log_info(
"No save file found, using defaults", "SaveManager"
)
return
# Reset restore flag
@@ -111,7 +120,8 @@ func _load_and_parse_save_file() -> Variant:
var save_file: FileAccess = FileAccess.open(SAVE_FILE_PATH, FileAccess.READ)
if save_file == null:
DebugManager.log_error(
"Failed to open save file for reading: %s" % SAVE_FILE_PATH, "SaveManager"
"Failed to open save file for reading: %s" % SAVE_FILE_PATH,
"SaveManager"
)
return null
@@ -119,7 +129,11 @@ func _load_and_parse_save_file() -> Variant:
var file_size: int = save_file.get_length()
if file_size > MAX_FILE_SIZE:
DebugManager.log_error(
"Save file too large: %d bytes (max %d)" % [file_size, MAX_FILE_SIZE], "SaveManager"
(
"Save file too large: %d bytes (max %d)"
% [file_size, MAX_FILE_SIZE]
),
"SaveManager"
)
save_file.close()
return null
@@ -128,21 +142,26 @@ func _load_and_parse_save_file() -> Variant:
save_file.close()
if not json_string is String:
DebugManager.log_error("Save file contains invalid data type", "SaveManager")
DebugManager.log_error(
"Save file contains invalid data type", "SaveManager"
)
return null
var json: JSON = JSON.new()
var parse_result: Error = json.parse(json_string)
if parse_result != OK:
DebugManager.log_error(
"Failed to parse save file JSON: %s" % json.error_string, "SaveManager"
"Failed to parse save file JSON: %s" % json.error_string,
"SaveManager"
)
_handle_load_failure("JSON parse failed")
return null
var loaded_data: Variant = json.data
if not loaded_data is Dictionary:
DebugManager.log_error("Save file root is not a dictionary", "SaveManager")
DebugManager.log_error(
"Save file root is not a dictionary", "SaveManager"
)
_handle_load_failure("Invalid data format")
return null
@@ -154,7 +173,8 @@ func _process_loaded_data(loaded_data: Variant) -> void:
# Validate checksum first
if not _validate_checksum(loaded_data):
DebugManager.log_error(
"Save file checksum validation failed - possible tampering", "SaveManager"
"Save file checksum validation failed - possible tampering",
"SaveManager"
)
_handle_load_failure("Checksum validation failed")
return
@@ -162,14 +182,17 @@ func _process_loaded_data(loaded_data: Variant) -> void:
# Handle version migration
var migrated_data: Variant = _handle_version_migration(loaded_data)
if migrated_data == null:
DebugManager.log_error("Save file version migration failed", "SaveManager")
DebugManager.log_error(
"Save file version migration failed", "SaveManager"
)
_handle_load_failure("Migration failed")
return
# Validate and fix loaded data
if not _validate_and_fix_save_data(migrated_data):
DebugManager.log_error(
"Save file failed validation after migration, using defaults", "SaveManager"
"Save file failed validation after migration, using defaults",
"SaveManager"
)
_handle_load_failure("Validation failed")
return
@@ -184,7 +207,8 @@ func _handle_load_failure(reason: String) -> void:
var backup_restored = _restore_backup_if_exists()
if not backup_restored:
DebugManager.log_warn(
"%s and backup restore failed, using defaults" % reason, "SaveManager"
"%s and backup restore failed, using defaults" % reason,
"SaveManager"
)
DebugManager.log_info(
@@ -199,11 +223,14 @@ func _handle_load_failure(reason: String) -> void:
func update_current_score(score: int) -> void:
# Input validation
if score < 0:
DebugManager.log_warn("Negative score rejected: %d" % score, "SaveManager")
DebugManager.log_warn(
"Negative score rejected: %d" % score, "SaveManager"
)
return
if score > MAX_SCORE:
DebugManager.log_warn(
"Score too high, capping at maximum: %d -> %d" % [score, MAX_SCORE], "SaveManager"
"Score too high, capping at maximum: %d -> %d" % [score, MAX_SCORE],
"SaveManager"
)
score = MAX_SCORE
@@ -219,23 +246,33 @@ func start_new_game() -> void:
# Clear saved grid state
game_data.grid_state.grid_layout = []
DebugManager.log_info(
"Started new game #%d (cleared grid state)" % game_data.games_played, "SaveManager"
"Started new game #%d (cleared grid state)" % game_data.games_played,
"SaveManager"
)
func finish_game(final_score: int) -> void:
# Input validation
if final_score < 0:
DebugManager.log_warn("Negative final score rejected: %d" % final_score, "SaveManager")
DebugManager.log_warn(
"Negative final score rejected: %d" % final_score, "SaveManager"
)
return
if final_score > MAX_SCORE:
DebugManager.log_warn(
"Final score too high, capping: %d -> %d" % [final_score, MAX_SCORE], "SaveManager"
(
"Final score too high, capping: %d -> %d"
% [final_score, MAX_SCORE]
),
"SaveManager"
)
final_score = MAX_SCORE
DebugManager.log_info(
"Finishing game with score: %d (previous: %d)" % [final_score, game_data.current_score],
(
"Finishing game with score: %d (previous: %d)"
% [final_score, game_data.current_score]
),
"SaveManager"
)
game_data.current_score = final_score
@@ -250,7 +287,9 @@ func finish_game(final_score: int) -> void:
if final_score > game_data.high_score:
game_data.high_score = final_score
DebugManager.log_info("New high score achieved: %d" % final_score, "SaveManager")
DebugManager.log_info(
"New high score achieved: %d" % final_score, "SaveManager"
)
save_game()
@@ -271,11 +310,18 @@ func get_total_score() -> int:
func save_grid_state(
grid_size: Vector2i, tile_types_count: int, active_gem_types: Array, grid_layout: Array
grid_size: Vector2i,
tile_types_count: int,
active_gem_types: Array,
grid_layout: Array
) -> void:
# Input validation
if not _validate_grid_parameters(grid_size, tile_types_count, active_gem_types, grid_layout):
DebugManager.log_error("Grid state validation failed, not saving", "SaveManager")
if not _validate_grid_parameters(
grid_size, tile_types_count, active_gem_types, grid_layout
):
DebugManager.log_error(
"Grid state validation failed, not saving", "SaveManager"
)
return
DebugManager.log_info(
@@ -338,10 +384,13 @@ func reset_all_progress() -> bool:
if FileAccess.file_exists(SAVE_FILE_PATH):
var error: Error = DirAccess.remove_absolute(SAVE_FILE_PATH)
if error == OK:
DebugManager.log_info("Main save file deleted successfully", "SaveManager")
DebugManager.log_info(
"Main save file deleted successfully", "SaveManager"
)
else:
DebugManager.log_error(
"Failed to delete main save file: error %d" % error, "SaveManager"
"Failed to delete main save file: error %d" % error,
"SaveManager"
)
# Delete backup file
@@ -349,21 +398,27 @@ func reset_all_progress() -> bool:
if FileAccess.file_exists(backup_path):
var error: Error = DirAccess.remove_absolute(backup_path)
if error == OK:
DebugManager.log_info("Backup save file deleted successfully", "SaveManager")
DebugManager.log_info(
"Backup save file deleted successfully", "SaveManager"
)
else:
DebugManager.log_error(
"Failed to delete backup save file: error %d" % error, "SaveManager"
"Failed to delete backup save file: error %d" % error,
"SaveManager"
)
DebugManager.log_info(
"Progress reset completed - all scores and save data cleared", "SaveManager"
"Progress reset completed - all scores and save data cleared",
"SaveManager"
)
# Clear restore flag
_restore_in_progress = false
# Create fresh save file with default data
DebugManager.log_info("Creating fresh save file with default data", "SaveManager")
DebugManager.log_info(
"Creating fresh save file with default data", "SaveManager"
)
save_game()
return true
@@ -395,11 +450,17 @@ func _validate_save_data(data: Dictionary) -> bool:
func _validate_required_fields(data: Dictionary) -> bool:
"""Validate that all required fields exist"""
var required_fields: Array[String] = [
"high_score", "current_score", "games_played", "total_score", "grid_state"
"high_score",
"current_score",
"games_played",
"total_score",
"grid_state"
]
for field in required_fields:
if not data.has(field):
DebugManager.log_error("Missing required field: %s" % field, "SaveManager")
DebugManager.log_error(
"Missing required field: %s" % field, "SaveManager"
)
return false
return true
@@ -409,7 +470,9 @@ func _validate_score_fields(data: Dictionary) -> bool:
var score_fields = ["high_score", "current_score", "total_score"]
for field in score_fields:
if not _is_valid_score(data.get(field, 0)):
DebugManager.log_error("Invalid %s validation failed" % field, "SaveManager")
DebugManager.log_error(
"Invalid %s validation failed" % field, "SaveManager"
)
return false
return true
@@ -419,7 +482,10 @@ func _validate_games_played_field(data: Dictionary) -> bool:
var games_played: Variant = data.get("games_played", 0)
if not (games_played is int or games_played is float):
DebugManager.log_error(
"Invalid games_played type: %s (type: %s)" % [str(games_played), typeof(games_played)],
(
"Invalid games_played type: %s (type: %s)"
% [str(games_played), typeof(games_played)]
),
"SaveManager"
)
return false
@@ -427,14 +493,18 @@ func _validate_games_played_field(data: Dictionary) -> bool:
# Check for NaN/Infinity in games_played if it's a float
if games_played is float and (is_nan(games_played) or is_inf(games_played)):
DebugManager.log_error(
"Invalid games_played float value: %s" % str(games_played), "SaveManager"
"Invalid games_played float value: %s" % str(games_played),
"SaveManager"
)
return false
var games_played_int: int = int(games_played)
if games_played_int < 0 or games_played_int > MAX_GAMES_PLAYED:
DebugManager.log_error(
"Invalid games_played value: %d (range: 0-%d)" % [games_played_int, MAX_GAMES_PLAYED],
(
"Invalid games_played value: %d (range: 0-%d)"
% [games_played_int, MAX_GAMES_PLAYED]
),
"SaveManager"
)
return false
@@ -447,16 +517,23 @@ func _validate_and_fix_save_data(data: Dictionary) -> bool:
Permissive validation that fixes issues instead of rejecting data entirely.
Used during migration to preserve as much user data as possible.
"""
DebugManager.log_info("Running permissive validation with auto-fix", "SaveManager")
DebugManager.log_info(
"Running permissive validation with auto-fix", "SaveManager"
)
# Ensure all required fields exist, create defaults if missing
var required_fields: Array[String] = [
"high_score", "current_score", "games_played", "total_score", "grid_state"
"high_score",
"current_score",
"games_played",
"total_score",
"grid_state"
]
for field in required_fields:
if not data.has(field):
DebugManager.log_warn(
"Missing required field '%s', adding default value" % field, "SaveManager"
"Missing required field '%s', adding default value" % field,
"SaveManager"
)
match field:
"high_score", "current_score", "total_score":
@@ -475,15 +552,21 @@ func _validate_and_fix_save_data(data: Dictionary) -> bool:
for field in ["high_score", "current_score", "total_score"]:
var value: Variant = data.get(field, 0)
if not (value is int or value is float):
DebugManager.log_warn("Invalid type for %s, converting to 0" % field, "SaveManager")
DebugManager.log_warn(
"Invalid type for %s, converting to 0" % field, "SaveManager"
)
data[field] = 0
else:
var numeric_value: int = int(value)
if numeric_value < 0:
DebugManager.log_warn("Negative %s fixed to 0" % field, "SaveManager")
DebugManager.log_warn(
"Negative %s fixed to 0" % field, "SaveManager"
)
data[field] = 0
elif numeric_value > MAX_SCORE:
DebugManager.log_warn("%s too high, clamped to maximum" % field, "SaveManager")
DebugManager.log_warn(
"%s too high, clamped to maximum" % field, "SaveManager"
)
data[field] = MAX_SCORE
else:
data[field] = numeric_value
@@ -491,7 +574,9 @@ func _validate_and_fix_save_data(data: Dictionary) -> bool:
# Fix games_played
var games_played: Variant = data.get("games_played", 0)
if not (games_played is int or games_played is float):
DebugManager.log_warn("Invalid games_played type, converting to 0", "SaveManager")
DebugManager.log_warn(
"Invalid games_played type, converting to 0", "SaveManager"
)
data["games_played"] = 0
else:
var games_played_int: int = int(games_played)
@@ -505,7 +590,9 @@ func _validate_and_fix_save_data(data: Dictionary) -> bool:
# Fix grid_state - ensure it exists and has basic structure
var grid_state: Variant = data.get("grid_state", {})
if not grid_state is Dictionary:
DebugManager.log_warn("Invalid grid_state, creating default", "SaveManager")
DebugManager.log_warn(
"Invalid grid_state, creating default", "SaveManager"
)
data["grid_state"] = {
"grid_size": {"x": 8, "y": 8},
"tile_types_count": 5,
@@ -514,24 +601,48 @@ func _validate_and_fix_save_data(data: Dictionary) -> bool:
}
else:
# Fix grid_state fields if they're missing or invalid
if not grid_state.has("grid_size") or not grid_state.grid_size is Dictionary:
DebugManager.log_warn("Invalid grid_size, using default", "SaveManager")
if (
not grid_state.has("grid_size")
or not grid_state.grid_size is Dictionary
):
DebugManager.log_warn(
"Invalid grid_size, using default", "SaveManager"
)
grid_state["grid_size"] = {"x": 8, "y": 8}
if not grid_state.has("tile_types_count") or not grid_state.tile_types_count is int:
DebugManager.log_warn("Invalid tile_types_count, using default", "SaveManager")
if (
not grid_state.has("tile_types_count")
or not grid_state.tile_types_count is int
):
DebugManager.log_warn(
"Invalid tile_types_count, using default", "SaveManager"
)
grid_state["tile_types_count"] = 5
if not grid_state.has("active_gem_types") or not grid_state.active_gem_types is Array:
DebugManager.log_warn("Invalid active_gem_types, using default", "SaveManager")
if (
not grid_state.has("active_gem_types")
or not grid_state.active_gem_types is Array
):
DebugManager.log_warn(
"Invalid active_gem_types, using default", "SaveManager"
)
grid_state["active_gem_types"] = [0, 1, 2, 3, 4]
if not grid_state.has("grid_layout") or not grid_state.grid_layout is Array:
DebugManager.log_warn("Invalid grid_layout, clearing saved grid", "SaveManager")
if (
not grid_state.has("grid_layout")
or not grid_state.grid_layout is Array
):
DebugManager.log_warn(
"Invalid grid_layout, clearing saved grid", "SaveManager"
)
grid_state["grid_layout"] = []
DebugManager.log_info(
"Permissive validation completed - data has been fixed and will be loaded", "SaveManager"
(
DebugManager
. log_info(
"Permissive validation completed - data has been fixed and will be loaded",
"SaveManager"
)
)
return true
@@ -569,7 +680,10 @@ func _validate_grid_size(grid_state: Dictionary) -> Dictionary:
"""Validate grid size and return validation result with dimensions"""
var result = {"valid": false, "width": 0, "height": 0}
if not grid_state.has("grid_size") or not grid_state.grid_size is Dictionary:
if (
not grid_state.has("grid_size")
or not grid_state.grid_size is Dictionary
):
DebugManager.log_error("Invalid grid_size in save data", "SaveManager")
return result
@@ -581,8 +695,15 @@ func _validate_grid_size(grid_state: Dictionary) -> Dictionary:
var height: Variant = size.y
if not width is int or not height is int:
return result
if width < 3 or height < 3 or width > MAX_GRID_SIZE or height > MAX_GRID_SIZE:
DebugManager.log_error("Grid size out of bounds: %dx%d" % [width, height], "SaveManager")
if (
width < 3
or height < 3
or width > MAX_GRID_SIZE
or height > MAX_GRID_SIZE
):
DebugManager.log_error(
"Grid size out of bounds: %dx%d" % [width, height], "SaveManager"
)
return result
result.valid = true
@@ -595,16 +716,22 @@ func _validate_tile_types(grid_state: Dictionary) -> int:
"""Validate tile types count and return it, or -1 if invalid"""
var tile_types: Variant = grid_state.get("tile_types_count", 0)
if not tile_types is int or tile_types < 3 or tile_types > MAX_TILE_TYPES:
DebugManager.log_error("Invalid tile_types_count: %s" % str(tile_types), "SaveManager")
DebugManager.log_error(
"Invalid tile_types_count: %s" % str(tile_types), "SaveManager"
)
return -1
return tile_types
func _validate_active_gem_types(grid_state: Dictionary, tile_types: int) -> bool:
func _validate_active_gem_types(
grid_state: Dictionary, tile_types: int
) -> bool:
"""Validate active gem types array"""
var active_gems: Variant = grid_state.get("active_gem_types", [])
if not active_gems is Array:
DebugManager.log_error("active_gem_types is not an array", "SaveManager")
DebugManager.log_error(
"active_gem_types is not an array", "SaveManager"
)
return false
# If active_gem_types exists, validate its contents
@@ -613,12 +740,17 @@ func _validate_active_gem_types(grid_state: Dictionary, tile_types: int) -> bool
var gem_type: Variant = active_gems[i]
if not gem_type is int:
DebugManager.log_error(
"active_gem_types[%d] is not an integer: %s" % [i, str(gem_type)], "SaveManager"
(
"active_gem_types[%d] is not an integer: %s"
% [i, str(gem_type)]
),
"SaveManager"
)
return false
if gem_type < 0 or gem_type >= tile_types:
DebugManager.log_error(
"active_gem_types[%d] out of range: %d" % [i, gem_type], "SaveManager"
"active_gem_types[%d] out of range: %d" % [i, gem_type],
"SaveManager"
)
return false
return true
@@ -629,7 +761,10 @@ func _validate_grid_layout(
) -> bool:
if layout.size() != expected_height:
DebugManager.log_error(
"Grid layout height mismatch: %d vs %d" % [layout.size(), expected_height],
(
"Grid layout height mismatch: %d vs %d"
% [layout.size(), expected_height]
),
"SaveManager"
)
return false
@@ -637,11 +772,16 @@ func _validate_grid_layout(
for y in range(layout.size()):
var row: Variant = layout[y]
if not row is Array:
DebugManager.log_error("Grid layout row %d is not an array" % y, "SaveManager")
DebugManager.log_error(
"Grid layout row %d is not an array" % y, "SaveManager"
)
return false
if row.size() != expected_width:
DebugManager.log_error(
"Grid layout row %d width mismatch: %d vs %d" % [y, row.size(), expected_width],
(
"Grid layout row %d width mismatch: %d vs %d"
% [y, row.size(), expected_width]
),
"SaveManager"
)
return false
@@ -650,13 +790,20 @@ func _validate_grid_layout(
var tile_type: Variant = row[x]
if not tile_type is int:
DebugManager.log_error(
"Grid tile [%d][%d] is not an integer: %s" % [y, x, str(tile_type)],
(
"Grid tile [%d][%d] is not an integer: %s"
% [y, x, str(tile_type)]
),
"SaveManager"
)
return false
if tile_type < -1 or tile_type >= max_tile_type:
DebugManager.log_error(
"Grid tile [%d][%d] type out of range: %d" % [y, x, tile_type], "SaveManager"
(
"Grid tile [%d][%d] type out of range: %d"
% [y, x, tile_type]
),
"SaveManager"
)
return false
@@ -664,7 +811,10 @@ func _validate_grid_layout(
func _validate_grid_parameters(
grid_size: Vector2i, tile_types_count: int, active_gem_types: Array, grid_layout: Array
grid_size: Vector2i,
tile_types_count: int,
active_gem_types: Array,
grid_layout: Array
) -> bool:
# Validate grid size
if (
@@ -685,7 +835,10 @@ func _validate_grid_parameters(
# Validate tile types count
if tile_types_count < 3 or tile_types_count > MAX_TILE_TYPES:
DebugManager.log_error(
"Invalid tile types count: %d (min 3, max %d)" % [tile_types_count, MAX_TILE_TYPES],
(
"Invalid tile types count: %d (min 3, max %d)"
% [tile_types_count, MAX_TILE_TYPES]
),
"SaveManager"
)
return false
@@ -702,14 +855,20 @@ func _validate_grid_parameters(
return false
# Validate grid layout
return _validate_grid_layout(grid_layout, grid_size.x, grid_size.y, tile_types_count)
return _validate_grid_layout(
grid_layout, grid_size.x, grid_size.y, tile_types_count
)
func _is_valid_score(score: Variant) -> bool:
# Accept both int and float, but convert to int for validation
if not (score is int or score is float):
DebugManager.log_error(
"Score is not a number: %s (type: %s)" % [str(score), typeof(score)], "SaveManager"
(
"Score is not a number: %s (type: %s)"
% [str(score), typeof(score)]
),
"SaveManager"
)
return false
@@ -717,13 +876,16 @@ func _is_valid_score(score: Variant) -> bool:
if score is float:
if is_nan(score) or is_inf(score):
DebugManager.log_error(
"Score contains invalid float value (NaN/Inf): %s" % str(score), "SaveManager"
"Score contains invalid float value (NaN/Inf): %s" % str(score),
"SaveManager"
)
return false
var score_int = int(score)
if score_int < 0 or score_int > MAX_SCORE:
DebugManager.log_error("Score out of bounds: %d" % score_int, "SaveManager")
DebugManager.log_error(
"Score out of bounds: %d" % score_int, "SaveManager"
)
return false
return true
@@ -737,12 +899,16 @@ func _merge_validated_data(loaded_data: Dictionary) -> void:
# Games played should always be an integer
if loaded_data.has("games_played"):
game_data["games_played"] = _safe_get_numeric_value(loaded_data, "games_played", 0)
game_data["games_played"] = _safe_get_numeric_value(
loaded_data, "games_played", 0
)
# Merge grid state carefully
var loaded_grid: Variant = loaded_data.get("grid_state", {})
if loaded_grid is Dictionary:
for grid_key in ["grid_size", "tile_types_count", "active_gem_types", "grid_layout"]:
for grid_key in [
"grid_size", "tile_types_count", "active_gem_types", "grid_layout"
]:
if loaded_grid.has(grid_key):
game_data.grid_state[grid_key] = loaded_grid[grid_key]
@@ -844,15 +1010,22 @@ func _validate_checksum(data: Dictionary) -> bool:
# Try to be more lenient with existing saves to prevent data loss
var data_version: Variant = data.get("_version", 0)
if data_version <= 1:
DebugManager.log_warn(
(
"Checksum mismatch in v%d save file - may be due to JSON serialization issue "
+ (
"(stored: %s, calculated: %s)"
% [data_version, stored_checksum, calculated_checksum]
)
),
"SaveManager"
(
DebugManager
. log_warn(
(
"Checksum mismatch in v%d save file - may be due to JSON serialization issue "
+ (
"(stored: %s, calculated: %s)"
% [
data_version,
stored_checksum,
calculated_checksum
]
)
),
"SaveManager"
)
)
(
DebugManager
@@ -876,7 +1049,9 @@ func _validate_checksum(data: Dictionary) -> bool:
return is_valid
func _safe_get_numeric_value(data: Dictionary, key: String, default_value: float) -> int:
func _safe_get_numeric_value(
data: Dictionary, key: String, default_value: float
) -> int:
"""Safely extract and convert numeric values with comprehensive validation"""
var value: Variant = data.get(key, default_value)
@@ -910,13 +1085,15 @@ func _safe_get_numeric_value(data: Dictionary, key: String, default_value: float
if key in ["high_score", "current_score", "total_score"]:
if int_value < 0 or int_value > MAX_SCORE:
DebugManager.log_warn(
"Score %s out of bounds: %d, using default" % [key, int_value], "SaveManager"
"Score %s out of bounds: %d, using default" % [key, int_value],
"SaveManager"
)
return int(default_value)
elif key == "games_played":
if int_value < 0 or int_value > MAX_GAMES_PLAYED:
DebugManager.log_warn(
"Games played out of bounds: %d, using default" % int_value, "SaveManager"
"Games played out of bounds: %d, using default" % int_value,
"SaveManager"
)
return int(default_value)
@@ -930,7 +1107,8 @@ func _handle_version_migration(data: Dictionary) -> Variant:
if data_version == SAVE_FORMAT_VERSION:
# Current version, no migration needed
DebugManager.log_info(
"Save file is current version (%d)" % SAVE_FORMAT_VERSION, "SaveManager"
"Save file is current version (%d)" % SAVE_FORMAT_VERSION,
"SaveManager"
)
return data
if data_version > SAVE_FORMAT_VERSION:
@@ -945,7 +1123,10 @@ func _handle_version_migration(data: Dictionary) -> Variant:
return null
# Older version - migrate
DebugManager.log_info(
"Migrating save data from version %d to %d" % [data_version, SAVE_FORMAT_VERSION],
(
"Migrating save data from version %d to %d"
% [data_version, SAVE_FORMAT_VERSION]
),
"SaveManager"
)
return _migrate_save_data(data, data_version)
@@ -960,7 +1141,9 @@ func _migrate_save_data(data: Dictionary, from_version: int) -> Dictionary:
# Add new fields that didn't exist in version 0
if not migrated_data.has("total_score"):
migrated_data["total_score"] = 0
DebugManager.log_info("Added total_score field during migration", "SaveManager")
DebugManager.log_info(
"Added total_score field during migration", "SaveManager"
)
if not migrated_data.has("grid_state"):
migrated_data["grid_state"] = {
@@ -969,7 +1152,9 @@ func _migrate_save_data(data: Dictionary, from_version: int) -> Dictionary:
"active_gem_types": [0, 1, 2, 3, 4],
"grid_layout": []
}
DebugManager.log_info("Added grid_state structure during migration", "SaveManager")
DebugManager.log_info(
"Added grid_state structure during migration", "SaveManager"
)
# Ensure all numeric values are within bounds after migration
for score_key in ["high_score", "current_score", "total_score"]:
@@ -981,11 +1166,17 @@ func _migrate_save_data(data: Dictionary, from_version: int) -> Dictionary:
DebugManager.log_warn(
(
"Clamping %s during migration: %d -> %d"
% [score_key, int_score, clamp(int_score, 0, MAX_SCORE)]
% [
score_key,
int_score,
clamp(int_score, 0, MAX_SCORE)
]
),
"SaveManager"
)
migrated_data[score_key] = clamp(int_score, 0, MAX_SCORE)
migrated_data[score_key] = clamp(
int_score, 0, MAX_SCORE
)
# Future migrations would go here
# if from_version < 2:
@@ -997,7 +1188,9 @@ func _migrate_save_data(data: Dictionary, from_version: int) -> Dictionary:
# Recalculate checksum after migration
migrated_data["_checksum"] = _calculate_checksum(migrated_data)
DebugManager.log_info("Save data migration completed successfully", "SaveManager")
DebugManager.log_info(
"Save data migration completed successfully", "SaveManager"
)
return migrated_data
@@ -1005,7 +1198,9 @@ func _create_backup() -> void:
# Create backup of current save file
if FileAccess.file_exists(SAVE_FILE_PATH):
var backup_path: String = SAVE_FILE_PATH + ".backup"
var original: FileAccess = FileAccess.open(SAVE_FILE_PATH, FileAccess.READ)
var original: FileAccess = FileAccess.open(
SAVE_FILE_PATH, FileAccess.READ
)
var backup: FileAccess = FileAccess.open(backup_path, FileAccess.WRITE)
if original and backup:
backup.store_var(original.get_var())
@@ -1017,7 +1212,9 @@ func _create_backup() -> void:
func _restore_backup_if_exists() -> bool:
var backup_path: String = SAVE_FILE_PATH + ".backup"
if not FileAccess.file_exists(backup_path):
DebugManager.log_warn("No backup file found for recovery", "SaveManager")
DebugManager.log_warn(
"No backup file found for recovery", "SaveManager"
)
return false
DebugManager.log_info("Attempting to restore from backup", "SaveManager")
@@ -1025,12 +1222,16 @@ func _restore_backup_if_exists() -> bool:
# Validate backup file size before attempting restore
var backup_file: FileAccess = FileAccess.open(backup_path, FileAccess.READ)
if backup_file == null:
DebugManager.log_error("Failed to open backup file for reading", "SaveManager")
DebugManager.log_error(
"Failed to open backup file for reading", "SaveManager"
)
return false
var backup_size: int = backup_file.get_length()
if backup_size > MAX_FILE_SIZE:
DebugManager.log_error("Backup file too large: %d bytes" % backup_size, "SaveManager")
DebugManager.log_error(
"Backup file too large: %d bytes" % backup_size, "SaveManager"
)
backup_file.close()
return false
@@ -1045,13 +1246,17 @@ func _restore_backup_if_exists() -> bool:
# Create new save file from backup
var original: FileAccess = FileAccess.open(SAVE_FILE_PATH, FileAccess.WRITE)
if original == null:
DebugManager.log_error("Failed to create new save file from backup", "SaveManager")
DebugManager.log_error(
"Failed to create new save file from backup", "SaveManager"
)
return false
original.store_var(backup_data)
original.close()
DebugManager.log_info("Backup restored successfully to main save file", "SaveManager")
DebugManager.log_info(
"Backup restored successfully to main save file", "SaveManager"
)
# Note: The restored file will be loaded on the next game restart
# We don't recursively load here to prevent infinite loops
return true

View File

@@ -10,7 +10,10 @@ const MAX_SETTING_STRING_LENGTH = 10 # Max length for string settings like lang
var settings: Dictionary = {}
var default_settings: Dictionary = {
"master_volume": 0.50, "music_volume": 0.40, "sfx_volume": 0.50, "language": "en"
"master_volume": 0.50,
"music_volume": 0.40,
"sfx_volume": 0.50,
"language": "en"
}
var languages_data: Dictionary = {}
@@ -32,7 +35,9 @@ func load_settings() -> void:
if load_result == OK:
for key in default_settings.keys():
var loaded_value = config.get_value("settings", key, default_settings[key])
var loaded_value = config.get_value(
"settings", key, default_settings[key]
)
# Validate loaded settings before applying
if _validate_setting_value(key, loaded_value):
settings[key] = loaded_value
@@ -45,10 +50,15 @@ func load_settings() -> void:
"SettingsManager"
)
settings[key] = default_settings[key]
DebugManager.log_info("Settings loaded: " + str(settings), "SettingsManager")
DebugManager.log_info(
"Settings loaded: " + str(settings), "SettingsManager"
)
else:
DebugManager.log_warn(
"No settings file found (Error code: %d), using defaults" % load_result,
(
"No settings file found (Error code: %d), using defaults"
% load_result
),
"SettingsManager"
)
settings = default_settings.duplicate()
@@ -58,7 +68,9 @@ func load_settings() -> void:
func _apply_all_settings():
DebugManager.log_info("Applying settings: " + str(settings), "SettingsManager")
DebugManager.log_info(
"Applying settings: " + str(settings), "SettingsManager"
)
# Apply language setting
if "language" in settings:
@@ -70,24 +82,33 @@ func _apply_all_settings():
var sfx_bus = AudioServer.get_bus_index("SFX")
if master_bus >= 0 and "master_volume" in settings:
AudioServer.set_bus_volume_db(master_bus, linear_to_db(settings["master_volume"]))
AudioServer.set_bus_volume_db(
master_bus, linear_to_db(settings["master_volume"])
)
else:
DebugManager.log_warn(
"Master audio bus not found or master_volume setting missing", "SettingsManager"
"Master audio bus not found or master_volume setting missing",
"SettingsManager"
)
if music_bus >= 0 and "music_volume" in settings:
AudioServer.set_bus_volume_db(music_bus, linear_to_db(settings["music_volume"]))
AudioServer.set_bus_volume_db(
music_bus, linear_to_db(settings["music_volume"])
)
else:
DebugManager.log_warn(
"Music audio bus not found or music_volume setting missing", "SettingsManager"
"Music audio bus not found or music_volume setting missing",
"SettingsManager"
)
if sfx_bus >= 0 and "sfx_volume" in settings:
AudioServer.set_bus_volume_db(sfx_bus, linear_to_db(settings["sfx_volume"]))
AudioServer.set_bus_volume_db(
sfx_bus, linear_to_db(settings["sfx_volume"])
)
else:
DebugManager.log_warn(
"SFX audio bus not found or sfx_volume setting missing", "SettingsManager"
"SFX audio bus not found or sfx_volume setting missing",
"SettingsManager"
)
@@ -99,7 +120,8 @@ func save_settings():
var save_result = config.save(SETTINGS_FILE)
if save_result != OK:
DebugManager.log_error(
"Failed to save settings (Error code: %d)" % save_result, "SettingsManager"
"Failed to save settings (Error code: %d)" % save_result,
"SettingsManager"
)
return false
@@ -119,7 +141,8 @@ func set_setting(key: String, value) -> bool:
# Validate value type and range based on key
if not _validate_setting_value(key, value):
DebugManager.log_error(
"Invalid value for setting '%s': %s" % [key, str(value)], "SettingsManager"
"Invalid value for setting '%s': %s" % [key, str(value)],
"SettingsManager"
)
return false
@@ -157,7 +180,8 @@ func _validate_volume_setting(key: String, value) -> bool:
# Check for NaN and infinity
if is_nan(float_value) or is_inf(float_value):
DebugManager.log_warn(
"Invalid float value for %s: %s" % [key, str(value)], "SettingsManager"
"Invalid float value for %s: %s" % [key, str(value)],
"SettingsManager"
)
return false
# Range validation
@@ -170,7 +194,8 @@ func _validate_language_setting(value) -> bool:
# Prevent extremely long strings
if value.length() > MAX_SETTING_STRING_LENGTH:
DebugManager.log_warn(
"Language code too long: %d characters" % value.length(), "SettingsManager"
"Language code too long: %d characters" % value.length(),
"SettingsManager"
)
return false
# Check for valid characters (alphanumeric and common separators only)
@@ -178,11 +203,15 @@ func _validate_language_setting(value) -> bool:
regex.compile("^[a-zA-Z0-9_-]+$")
if not regex.search(value):
DebugManager.log_warn(
"Language code contains invalid characters: %s" % value, "SettingsManager"
"Language code contains invalid characters: %s" % value,
"SettingsManager"
)
return false
# Check if language is supported
if languages_data.has("languages") and languages_data.languages is Dictionary:
if (
languages_data.has("languages")
and languages_data.languages is Dictionary
):
return value in languages_data.languages
# Fallback to basic validation if languages not loaded
return value in ["en", "ru"]
@@ -192,7 +221,9 @@ func _validate_default_setting(key: String, value) -> bool:
# Default validation: accept if type matches default setting type
var default_value = default_settings.get(key)
if default_value == null:
DebugManager.log_warn("Unknown setting key in validation: %s" % key, "SettingsManager")
DebugManager.log_warn(
"Unknown setting key in validation: %s" % key, "SettingsManager"
)
return false
return typeof(value) == typeof(default_value)
@@ -210,7 +241,9 @@ func _apply_setting_side_effect(key: String, value) -> void:
AudioManager.update_music_volume(value)
"sfx_volume":
if AudioServer.get_bus_index("SFX") >= 0:
AudioServer.set_bus_volume_db(AudioServer.get_bus_index("SFX"), linear_to_db(value))
AudioServer.set_bus_volume_db(
AudioServer.get_bus_index("SFX"), linear_to_db(value)
)
func load_languages():
@@ -230,7 +263,11 @@ func load_languages():
languages_data = parsed_data
DebugManager.log_info(
"Languages loaded successfully: " + str(languages_data.languages.keys()), "SettingsManager"
(
"Languages loaded successfully: "
+ str(languages_data.languages.keys())
),
"SettingsManager"
)
@@ -239,7 +276,8 @@ func _load_languages_file() -> String:
if not file:
var error_code = FileAccess.get_open_error()
DebugManager.log_error(
"Could not open languages.json (Error code: %d)" % error_code, "SettingsManager"
"Could not open languages.json (Error code: %d)" % error_code,
"SettingsManager"
)
return ""
@@ -247,14 +285,19 @@ func _load_languages_file() -> String:
var file_size = file.get_length()
if file_size > MAX_JSON_FILE_SIZE:
DebugManager.log_error(
"Languages.json file too large: %d bytes (max %d)" % [file_size, MAX_JSON_FILE_SIZE],
(
"Languages.json file too large: %d bytes (max %d)"
% [file_size, MAX_JSON_FILE_SIZE]
),
"SettingsManager"
)
file.close()
return ""
if file_size == 0:
DebugManager.log_error("Languages.json file is empty", "SettingsManager")
DebugManager.log_error(
"Languages.json file is empty", "SettingsManager"
)
file.close()
return ""
@@ -264,7 +307,8 @@ func _load_languages_file() -> String:
if file_error != OK:
DebugManager.log_error(
"Error reading languages.json (Error code: %d)" % file_error, "SettingsManager"
"Error reading languages.json (Error code: %d)" % file_error,
"SettingsManager"
)
return ""
@@ -274,27 +318,36 @@ func _load_languages_file() -> String:
func _parse_languages_json(json_string: String) -> Dictionary:
# Validate the JSON string is not empty
if json_string.is_empty():
DebugManager.log_error("Languages.json contains empty content", "SettingsManager")
DebugManager.log_error(
"Languages.json contains empty content", "SettingsManager"
)
return {}
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],
(
"JSON parsing failed at line %d: %s"
% [json.error_line, json.error_string]
),
"SettingsManager"
)
return {}
if not json.data or not json.data is Dictionary:
DebugManager.log_error("Invalid JSON data structure in languages.json", "SettingsManager")
DebugManager.log_error(
"Invalid JSON data structure in languages.json", "SettingsManager"
)
return {}
return json.data
func _load_default_languages_with_fallback(reason: String):
DebugManager.log_warn("Loading default languages due to: " + reason, "SettingsManager")
DebugManager.log_warn(
"Loading default languages due to: " + reason, "SettingsManager"
)
_load_default_languages()
@@ -302,9 +355,14 @@ func _load_default_languages():
# Fallback language data when JSON file fails to load
languages_data = {
"languages":
{"en": {"name": "English", "flag": "🇺🇸"}, "ru": {"name": "Русский", "flag": "🇷🇺"}}
{
"en": {"name": "English", "flag": "🇺🇸"},
"ru": {"name": "Русский", "flag": "🇷🇺"}
}
}
DebugManager.log_info("Default languages loaded as fallback", "SettingsManager")
DebugManager.log_info(
"Default languages loaded as fallback", "SettingsManager"
)
func get_languages_data():
@@ -312,15 +370,21 @@ func get_languages_data():
func reset_settings_to_defaults() -> void:
DebugManager.log_info("Resetting all settings to defaults", "SettingsManager")
DebugManager.log_info(
"Resetting all settings to defaults", "SettingsManager"
)
for key in default_settings.keys():
settings[key] = default_settings[key]
_apply_setting_side_effect(key, settings[key])
var save_success = save_settings()
if save_success:
DebugManager.log_info("Settings reset completed successfully", "SettingsManager")
DebugManager.log_info(
"Settings reset completed successfully", "SettingsManager"
)
else:
DebugManager.log_error("Failed to save reset settings", "SettingsManager")
DebugManager.log_error(
"Failed to save reset settings", "SettingsManager"
)
func _validate_languages_structure(data: Dictionary) -> bool:
@@ -344,16 +408,22 @@ func _validate_languages_structure(data: Dictionary) -> bool:
func _validate_languages_root_structure(data: Dictionary) -> bool:
"""Validate the root structure of languages data"""
if not data.has("languages"):
DebugManager.log_error("Languages.json missing 'languages' key", "SettingsManager")
DebugManager.log_error(
"Languages.json missing 'languages' key", "SettingsManager"
)
return false
var languages = data["languages"]
if not languages is Dictionary:
DebugManager.log_error("'languages' is not a dictionary", "SettingsManager")
DebugManager.log_error(
"'languages' is not a dictionary", "SettingsManager"
)
return false
if languages.is_empty():
DebugManager.log_error("Languages dictionary is empty", "SettingsManager")
DebugManager.log_error(
"Languages dictionary is empty", "SettingsManager"
)
return false
return true
@@ -367,28 +437,35 @@ func _validate_individual_languages(languages: Dictionary) -> bool:
return true
func _validate_single_language_entry(lang_code: Variant, lang_data: Variant) -> bool:
func _validate_single_language_entry(
lang_code: Variant, lang_data: Variant
) -> bool:
"""Validate a single language entry"""
if not lang_code is String:
DebugManager.log_error(
"Language code is not a string: %s" % str(lang_code), "SettingsManager"
"Language code is not a string: %s" % str(lang_code),
"SettingsManager"
)
return false
if lang_code.length() > MAX_SETTING_STRING_LENGTH:
DebugManager.log_error("Language code too long: %s" % lang_code, "SettingsManager")
DebugManager.log_error(
"Language code too long: %s" % lang_code, "SettingsManager"
)
return false
if not lang_data is Dictionary:
DebugManager.log_error(
"Language data for '%s' is not a dictionary" % lang_code, "SettingsManager"
"Language data for '%s' is not a dictionary" % lang_code,
"SettingsManager"
)
return false
# Validate required fields in language data
if not lang_data.has("name") or not lang_data["name"] is String:
DebugManager.log_error(
"Language '%s' missing valid 'name' field" % lang_code, "SettingsManager"
"Language '%s' missing valid 'name' field" % lang_code,
"SettingsManager"
)
return false

View File

@@ -69,12 +69,17 @@ func test_basic_functionality():
# Test that AudioManager has expected methods
var expected_methods = ["update_music_volume", "play_ui_click"]
TestHelperClass.assert_has_methods(audio_manager, expected_methods, "AudioManager methods")
TestHelperClass.assert_has_methods(
audio_manager, expected_methods, "AudioManager methods"
)
# Test that AudioManager has expected constants
TestHelperClass.assert_true("MUSIC_PATH" in audio_manager, "MUSIC_PATH constant exists")
TestHelperClass.assert_true(
"UI_CLICK_SOUND_PATH" in audio_manager, "UI_CLICK_SOUND_PATH constant exists"
"MUSIC_PATH" in audio_manager, "MUSIC_PATH constant exists"
)
TestHelperClass.assert_true(
"UI_CLICK_SOUND_PATH" in audio_manager,
"UI_CLICK_SOUND_PATH constant exists"
)
@@ -85,9 +90,12 @@ func test_audio_constants():
var music_path = audio_manager.MUSIC_PATH
var click_path = audio_manager.UI_CLICK_SOUND_PATH
TestHelperClass.assert_true(music_path.begins_with("res://"), "Music path uses res:// protocol")
TestHelperClass.assert_true(
click_path.begins_with("res://"), "Click sound path uses res:// protocol"
music_path.begins_with("res://"), "Music path uses res:// protocol"
)
TestHelperClass.assert_true(
click_path.begins_with("res://"),
"Click sound path uses res:// protocol"
)
# Test file extensions
@@ -101,11 +109,17 @@ func test_audio_constants():
if click_path.ends_with(ext):
click_has_valid_ext = true
TestHelperClass.assert_true(music_has_valid_ext, "Music file has valid audio extension")
TestHelperClass.assert_true(click_has_valid_ext, "Click sound has valid audio extension")
TestHelperClass.assert_true(
music_has_valid_ext, "Music file has valid audio extension"
)
TestHelperClass.assert_true(
click_has_valid_ext, "Click sound has valid audio extension"
)
# Test that audio files exist
TestHelperClass.assert_true(ResourceLoader.exists(music_path), "Music file exists at path")
TestHelperClass.assert_true(
ResourceLoader.exists(music_path), "Music file exists at path"
)
TestHelperClass.assert_true(
ResourceLoader.exists(click_path), "Click sound file exists at path"
)
@@ -115,9 +129,12 @@ func test_audio_player_initialization():
TestHelperClass.print_step("Audio Player Initialization")
# Test music player initialization
TestHelperClass.assert_not_null(audio_manager.music_player, "Music player is initialized")
TestHelperClass.assert_not_null(
audio_manager.music_player, "Music player is initialized"
)
TestHelperClass.assert_true(
audio_manager.music_player is AudioStreamPlayer, "Music player is AudioStreamPlayer type"
audio_manager.music_player is AudioStreamPlayer,
"Music player is AudioStreamPlayer type"
)
TestHelperClass.assert_true(
audio_manager.music_player.get_parent() == audio_manager,
@@ -125,7 +142,9 @@ func test_audio_player_initialization():
)
# Test UI click player initialization
TestHelperClass.assert_not_null(audio_manager.ui_click_player, "UI click player is initialized")
TestHelperClass.assert_not_null(
audio_manager.ui_click_player, "UI click player is initialized"
)
TestHelperClass.assert_true(
audio_manager.ui_click_player is AudioStreamPlayer,
"UI click player is AudioStreamPlayer type"
@@ -137,10 +156,14 @@ func test_audio_player_initialization():
# Test audio bus assignment
TestHelperClass.assert_equal(
"Music", audio_manager.music_player.bus, "Music player assigned to Music bus"
"Music",
audio_manager.music_player.bus,
"Music player assigned to Music bus"
)
TestHelperClass.assert_equal(
"SFX", audio_manager.ui_click_player.bus, "UI click player assigned to SFX bus"
"SFX",
audio_manager.ui_click_player.bus,
"UI click player assigned to SFX bus"
)
@@ -148,26 +171,38 @@ func test_stream_loading_and_validation():
TestHelperClass.print_step("Stream Loading and Validation")
# Test music stream loading
TestHelperClass.assert_not_null(audio_manager.music_player.stream, "Music stream is loaded")
TestHelperClass.assert_not_null(
audio_manager.music_player.stream, "Music stream is loaded"
)
if audio_manager.music_player.stream:
TestHelperClass.assert_true(
audio_manager.music_player.stream is AudioStream, "Music stream is AudioStream type"
audio_manager.music_player.stream is AudioStream,
"Music stream is AudioStream type"
)
# Test click stream loading
TestHelperClass.assert_not_null(audio_manager.click_stream, "Click stream is loaded")
TestHelperClass.assert_not_null(
audio_manager.click_stream, "Click stream is loaded"
)
if audio_manager.click_stream:
TestHelperClass.assert_true(
audio_manager.click_stream is AudioStream, "Click stream is AudioStream type"
audio_manager.click_stream is AudioStream,
"Click stream is AudioStream type"
)
# Test stream resource loading directly
var loaded_music = load(audio_manager.MUSIC_PATH)
TestHelperClass.assert_not_null(loaded_music, "Music resource loads successfully")
TestHelperClass.assert_true(loaded_music is AudioStream, "Loaded music is AudioStream type")
TestHelperClass.assert_not_null(
loaded_music, "Music resource loads successfully"
)
TestHelperClass.assert_true(
loaded_music is AudioStream, "Loaded music is AudioStream type"
)
var loaded_click = load(audio_manager.UI_CLICK_SOUND_PATH)
TestHelperClass.assert_not_null(loaded_click, "Click resource loads successfully")
TestHelperClass.assert_not_null(
loaded_click, "Click resource loads successfully"
)
TestHelperClass.assert_true(
loaded_click is AudioStream, "Loaded click sound is AudioStream type"
)
@@ -186,7 +221,9 @@ func test_audio_bus_configuration():
# Test player bus assignments match actual AudioServer buses
if music_bus_index >= 0:
TestHelperClass.assert_equal(
"Music", audio_manager.music_player.bus, "Music player correctly assigned to Music bus"
"Music",
audio_manager.music_player.bus,
"Music player correctly assigned to Music bus"
)
if sfx_bus_index >= 0:
@@ -208,20 +245,27 @@ func test_volume_management():
# Test volume update to valid range
audio_manager.update_music_volume(0.5)
TestHelperClass.assert_float_equal(
linear_to_db(0.5), audio_manager.music_player.volume_db, 0.001, "Music volume set correctly"
linear_to_db(0.5),
audio_manager.music_player.volume_db,
0.001,
"Music volume set correctly"
)
# Test volume update to zero (should stop music)
audio_manager.update_music_volume(0.0)
TestHelperClass.assert_equal(
linear_to_db(0.0), audio_manager.music_player.volume_db, "Zero volume set correctly"
linear_to_db(0.0),
audio_manager.music_player.volume_db,
"Zero volume set correctly"
)
# Note: We don't test playing state as it depends on initialization conditions
# Test volume update to maximum
audio_manager.update_music_volume(1.0)
TestHelperClass.assert_equal(
linear_to_db(1.0), audio_manager.music_player.volume_db, "Maximum volume set correctly"
linear_to_db(1.0),
audio_manager.music_player.volume_db,
"Maximum volume set correctly"
)
# Test volume range validation
@@ -248,7 +292,8 @@ func test_music_playback_control():
audio_manager.music_player, "Music player exists for playback testing"
)
TestHelperClass.assert_not_null(
audio_manager.music_player.stream, "Music player has stream for playback testing"
audio_manager.music_player.stream,
"Music player has stream for playback testing"
)
# Test playback state management
@@ -279,8 +324,12 @@ func test_ui_sound_effects():
TestHelperClass.print_step("UI Sound Effects")
# Test UI click functionality
TestHelperClass.assert_not_null(audio_manager.ui_click_player, "UI click player exists")
TestHelperClass.assert_not_null(audio_manager.click_stream, "Click stream is loaded")
TestHelperClass.assert_not_null(
audio_manager.ui_click_player, "UI click player exists"
)
TestHelperClass.assert_not_null(
audio_manager.click_stream, "Click stream is loaded"
)
# Test that play_ui_click can be called safely
var original_stream = audio_manager.ui_click_player.stream
@@ -296,7 +345,9 @@ func test_ui_sound_effects():
# Test multiple rapid clicks (should not cause errors)
for i in range(3):
audio_manager.play_ui_click()
TestHelperClass.assert_true(true, "Rapid click %d handled safely" % (i + 1))
TestHelperClass.assert_true(
true, "Rapid click %d handled safely" % (i + 1)
)
# Test click with null stream
var backup_stream = audio_manager.click_stream
@@ -315,7 +366,9 @@ func test_stream_loop_configuration():
if music_stream is AudioStreamWAV:
# For WAV files, check loop mode
var has_loop_mode = "loop_mode" in music_stream
TestHelperClass.assert_true(has_loop_mode, "WAV stream has loop_mode property")
TestHelperClass.assert_true(
has_loop_mode, "WAV stream has loop_mode property"
)
if has_loop_mode:
TestHelperClass.assert_equal(
AudioStreamWAV.LOOP_FORWARD,
@@ -325,12 +378,18 @@ func test_stream_loop_configuration():
elif music_stream is AudioStreamOggVorbis:
# For OGG files, check loop property
var has_loop = "loop" in music_stream
TestHelperClass.assert_true(has_loop, "OGG stream has loop property")
TestHelperClass.assert_true(
has_loop, "OGG stream has loop property"
)
if has_loop:
TestHelperClass.assert_true(music_stream.loop, "OGG stream loop enabled")
TestHelperClass.assert_true(
music_stream.loop, "OGG stream loop enabled"
)
# Test loop configuration for different stream types
TestHelperClass.assert_true(true, "Stream loop configuration tested based on type")
TestHelperClass.assert_true(
true, "Stream loop configuration tested based on type"
)
func test_error_handling():
@@ -341,15 +400,18 @@ func test_error_handling():
# Test that AudioManager initializes even with potential issues
TestHelperClass.assert_not_null(
audio_manager, "AudioManager initializes despite potential resource issues"
audio_manager,
"AudioManager initializes despite potential resource issues"
)
# Test that players are still created even if streams fail to load
TestHelperClass.assert_not_null(
audio_manager.music_player, "Music player created regardless of stream loading"
audio_manager.music_player,
"Music player created regardless of stream loading"
)
TestHelperClass.assert_not_null(
audio_manager.ui_click_player, "UI click player created regardless of stream loading"
audio_manager.ui_click_player,
"UI click player created regardless of stream loading"
)
# Test null stream handling in play_ui_click
@@ -358,7 +420,9 @@ func test_error_handling():
# This should not crash
audio_manager.play_ui_click()
TestHelperClass.assert_true(true, "play_ui_click handles null stream gracefully")
TestHelperClass.assert_true(
true, "play_ui_click handles null stream gracefully"
)
# Restore original stream
audio_manager.click_stream = original_click_stream

View File

@@ -57,7 +57,9 @@ func test_basic_functionality():
# Test that GameManager has expected properties
TestHelperClass.assert_has_properties(
game_manager, ["pending_gameplay_mode", "is_changing_scene"], "GameManager properties"
game_manager,
["pending_gameplay_mode", "is_changing_scene"],
"GameManager properties"
)
# Test that GameManager has expected methods
@@ -70,13 +72,19 @@ func test_basic_functionality():
"save_game",
"exit_to_main_menu"
]
TestHelperClass.assert_has_methods(game_manager, expected_methods, "GameManager methods")
TestHelperClass.assert_has_methods(
game_manager, expected_methods, "GameManager methods"
)
# Test initial state
TestHelperClass.assert_equal(
"match3", game_manager.pending_gameplay_mode, "Default pending gameplay mode"
"match3",
game_manager.pending_gameplay_mode,
"Default pending gameplay mode"
)
TestHelperClass.assert_false(
game_manager.is_changing_scene, "Initial scene change flag"
)
TestHelperClass.assert_false(game_manager.is_changing_scene, "Initial scene change flag")
func test_scene_constants():
@@ -97,15 +105,23 @@ func test_scene_constants():
TestHelperClass.assert_true(
game_path.begins_with("res://"), "Game scene path uses res:// protocol"
)
TestHelperClass.assert_true(game_path.ends_with(".tscn"), "Game scene path has .tscn extension")
TestHelperClass.assert_true(
game_path.ends_with(".tscn"), "Game scene path has .tscn extension"
)
TestHelperClass.assert_true(
main_path.begins_with("res://"), "Main scene path uses res:// protocol"
)
TestHelperClass.assert_true(main_path.ends_with(".tscn"), "Main scene path has .tscn extension")
TestHelperClass.assert_true(
main_path.ends_with(".tscn"), "Main scene path has .tscn extension"
)
# Test that scene files exist
TestHelperClass.assert_true(ResourceLoader.exists(game_path), "Game scene file exists at path")
TestHelperClass.assert_true(ResourceLoader.exists(main_path), "Main scene file exists at path")
TestHelperClass.assert_true(
ResourceLoader.exists(game_path), "Game scene file exists at path"
)
TestHelperClass.assert_true(
ResourceLoader.exists(main_path), "Main scene file exists at path"
)
func test_input_validation():
@@ -118,38 +134,50 @@ func test_input_validation():
# Test empty string validation
game_manager.start_game_with_mode("")
TestHelperClass.assert_equal(
original_mode, game_manager.pending_gameplay_mode, "Empty string mode rejected"
original_mode,
game_manager.pending_gameplay_mode,
"Empty string mode rejected"
)
TestHelperClass.assert_false(
game_manager.is_changing_scene, "Scene change flag unchanged after empty mode"
game_manager.is_changing_scene,
"Scene change flag unchanged after empty mode"
)
# Test null validation - GameManager expects String, so this tests the type safety
# Note: In Godot 4.4, passing null to String parameter causes script error as expected
# The function properly validates empty strings instead
TestHelperClass.assert_equal(
original_mode, game_manager.pending_gameplay_mode, "Mode preserved after empty string test"
original_mode,
game_manager.pending_gameplay_mode,
"Mode preserved after empty string test"
)
TestHelperClass.assert_false(
game_manager.is_changing_scene, "Scene change flag unchanged after validation tests"
game_manager.is_changing_scene,
"Scene change flag unchanged after validation tests"
)
# Test invalid mode validation
game_manager.start_game_with_mode("invalid_mode")
TestHelperClass.assert_equal(
original_mode, game_manager.pending_gameplay_mode, "Invalid mode rejected"
original_mode,
game_manager.pending_gameplay_mode,
"Invalid mode rejected"
)
TestHelperClass.assert_false(
game_manager.is_changing_scene, "Scene change flag unchanged after invalid mode"
game_manager.is_changing_scene,
"Scene change flag unchanged after invalid mode"
)
# Test case sensitivity
game_manager.start_game_with_mode("MATCH3")
TestHelperClass.assert_equal(
original_mode, game_manager.pending_gameplay_mode, "Case-sensitive mode validation"
original_mode,
game_manager.pending_gameplay_mode,
"Case-sensitive mode validation"
)
TestHelperClass.assert_false(
game_manager.is_changing_scene, "Scene change flag unchanged after wrong case"
game_manager.is_changing_scene,
"Scene change flag unchanged after wrong case"
)
@@ -165,14 +193,19 @@ func test_race_condition_protection():
# Verify second request was rejected
TestHelperClass.assert_equal(
original_mode, game_manager.pending_gameplay_mode, "Concurrent scene change blocked"
original_mode,
game_manager.pending_gameplay_mode,
"Concurrent scene change blocked"
)
TestHelperClass.assert_true(
game_manager.is_changing_scene, "Scene change flag preserved"
)
TestHelperClass.assert_true(game_manager.is_changing_scene, "Scene change flag preserved")
# Test exit to main menu during scene change
game_manager.exit_to_main_menu()
TestHelperClass.assert_true(
game_manager.is_changing_scene, "Exit request blocked during scene change"
game_manager.is_changing_scene,
"Exit request blocked during scene change"
)
# Reset state
@@ -191,13 +224,17 @@ func test_gameplay_mode_validation():
# Create a temporary mock to test validation
var test_mode_valid = mode in ["match3", "clickomania"]
TestHelperClass.assert_true(test_mode_valid, "Valid mode accepted: " + mode)
TestHelperClass.assert_true(
test_mode_valid, "Valid mode accepted: " + mode
)
# Test whitelist enforcement
var invalid_modes = ["puzzle", "arcade", "adventure", "rpg", "action"]
for mode in invalid_modes:
var test_mode_invalid = not (mode in ["match3", "clickomania"])
TestHelperClass.assert_true(test_mode_invalid, "Invalid mode rejected: " + mode)
TestHelperClass.assert_true(
test_mode_invalid, "Invalid mode rejected: " + mode
)
func test_scene_transition_safety():
@@ -209,12 +246,20 @@ func test_scene_transition_safety():
# Test scene resource loading
var game_scene = load(game_scene_path)
TestHelperClass.assert_not_null(game_scene, "Game scene resource loads successfully")
TestHelperClass.assert_true(game_scene is PackedScene, "Game scene is PackedScene type")
TestHelperClass.assert_not_null(
game_scene, "Game scene resource loads successfully"
)
TestHelperClass.assert_true(
game_scene is PackedScene, "Game scene is PackedScene type"
)
var main_scene = load(main_scene_path)
TestHelperClass.assert_not_null(main_scene, "Main scene resource loads successfully")
TestHelperClass.assert_true(main_scene is PackedScene, "Main scene is PackedScene type")
TestHelperClass.assert_not_null(
main_scene, "Main scene resource loads successfully"
)
TestHelperClass.assert_true(
main_scene is PackedScene, "Main scene is PackedScene type"
)
# Test that current scene exists
TestHelperClass.assert_not_null(current_scene, "Current scene exists")
@@ -234,10 +279,14 @@ func test_error_handling():
# Verify state preservation after invalid inputs
game_manager.start_game_with_mode("")
TestHelperClass.assert_equal(
original_changing, game_manager.is_changing_scene, "State preserved after empty mode error"
original_changing,
game_manager.is_changing_scene,
"State preserved after empty mode error"
)
TestHelperClass.assert_equal(
original_mode, game_manager.pending_gameplay_mode, "Mode preserved after empty mode error"
original_mode,
game_manager.pending_gameplay_mode,
"Mode preserved after empty mode error"
)
game_manager.start_game_with_mode("invalid")
@@ -247,7 +296,9 @@ func test_error_handling():
"State preserved after invalid mode error"
)
TestHelperClass.assert_equal(
original_mode, game_manager.pending_gameplay_mode, "Mode preserved after invalid mode error"
original_mode,
game_manager.pending_gameplay_mode,
"Mode preserved after invalid mode error"
)
@@ -263,9 +314,15 @@ func test_scene_method_validation():
var has_set_global_score = mock_scene.has_method("set_global_score")
var has_get_global_score = mock_scene.has_method("get_global_score")
TestHelperClass.assert_false(has_set_gameplay_mode, "Mock scene lacks set_gameplay_mode method")
TestHelperClass.assert_false(has_set_global_score, "Mock scene lacks set_global_score method")
TestHelperClass.assert_false(has_get_global_score, "Mock scene lacks get_global_score method")
TestHelperClass.assert_false(
has_set_gameplay_mode, "Mock scene lacks set_gameplay_mode method"
)
TestHelperClass.assert_false(
has_set_global_score, "Mock scene lacks set_global_score method"
)
TestHelperClass.assert_false(
has_get_global_score, "Mock scene lacks get_global_score method"
)
# Clean up mock scene
mock_scene.queue_free()
@@ -284,7 +341,9 @@ func test_pending_mode_management():
# This simulates what would happen in start_game_with_mode
game_manager.pending_gameplay_mode = test_mode
TestHelperClass.assert_equal(
test_mode, game_manager.pending_gameplay_mode, "Pending mode set correctly"
test_mode,
game_manager.pending_gameplay_mode,
"Pending mode set correctly"
)
# Test mode preservation during errors

View File

@@ -51,7 +51,9 @@ func setup_test_environment():
# Load Match3 scene
match3_scene = load("res://scenes/game/gameplays/Match3Gameplay.tscn")
TestHelperClass.assert_not_null(match3_scene, "Match3 scene loads successfully")
TestHelperClass.assert_not_null(
match3_scene, "Match3 scene loads successfully"
)
# Create test viewport for isolated testing
test_viewport = SubViewport.new()
@@ -62,7 +64,9 @@ func setup_test_environment():
if match3_scene:
match3_instance = match3_scene.instantiate()
test_viewport.add_child(match3_instance)
TestHelperClass.assert_not_null(match3_instance, "Match3 instance created successfully")
TestHelperClass.assert_not_null(
match3_instance, "Match3 instance created successfully"
)
# Wait for initialization
await process_frame
@@ -73,28 +77,44 @@ func test_basic_functionality():
TestHelperClass.print_step("Basic Functionality")
if not match3_instance:
TestHelperClass.assert_true(false, "Match3 instance not available for testing")
TestHelperClass.assert_true(
false, "Match3 instance not available for testing"
)
return
# Test that Match3 has expected properties
var expected_properties = [
"GRID_SIZE", "TILE_TYPES", "grid", "current_state", "selected_tile", "cursor_position"
"GRID_SIZE",
"TILE_TYPES",
"grid",
"current_state",
"selected_tile",
"cursor_position"
]
for prop in expected_properties:
TestHelperClass.assert_true(prop in match3_instance, "Match3 has property: " + prop)
TestHelperClass.assert_true(
prop in match3_instance, "Match3 has property: " + prop
)
# Test that Match3 has expected methods
var expected_methods = [
"_has_match_at", "_check_for_matches", "_get_match_line", "_clear_matches"
"_has_match_at",
"_check_for_matches",
"_get_match_line",
"_clear_matches"
]
TestHelperClass.assert_has_methods(match3_instance, expected_methods, "Match3 gameplay methods")
TestHelperClass.assert_has_methods(
match3_instance, expected_methods, "Match3 gameplay methods"
)
# Test signals
TestHelperClass.assert_true(
match3_instance.has_signal("score_changed"), "Match3 has score_changed signal"
match3_instance.has_signal("score_changed"),
"Match3 has score_changed signal"
)
TestHelperClass.assert_true(
match3_instance.has_signal("grid_state_loaded"), "Match3 has grid_state_loaded signal"
match3_instance.has_signal("grid_state_loaded"),
"Match3 has grid_state_loaded signal"
)
@@ -105,26 +125,41 @@ func test_constants_and_safety_limits():
return
# Test safety constants exist
TestHelperClass.assert_true("MAX_GRID_SIZE" in match3_instance, "MAX_GRID_SIZE constant exists")
TestHelperClass.assert_true(
"MAX_GRID_SIZE" in match3_instance, "MAX_GRID_SIZE constant exists"
)
TestHelperClass.assert_true(
"MAX_TILE_TYPES" in match3_instance, "MAX_TILE_TYPES constant exists"
)
TestHelperClass.assert_true(
"MAX_CASCADE_ITERATIONS" in match3_instance, "MAX_CASCADE_ITERATIONS constant exists"
"MAX_CASCADE_ITERATIONS" in match3_instance,
"MAX_CASCADE_ITERATIONS constant exists"
)
TestHelperClass.assert_true(
"MIN_GRID_SIZE" in match3_instance, "MIN_GRID_SIZE constant exists"
)
TestHelperClass.assert_true("MIN_GRID_SIZE" in match3_instance, "MIN_GRID_SIZE constant exists")
TestHelperClass.assert_true(
"MIN_TILE_TYPES" in match3_instance, "MIN_TILE_TYPES constant exists"
)
# Test safety limit values are reasonable
TestHelperClass.assert_equal(15, match3_instance.MAX_GRID_SIZE, "MAX_GRID_SIZE is reasonable")
TestHelperClass.assert_equal(10, match3_instance.MAX_TILE_TYPES, "MAX_TILE_TYPES is reasonable")
TestHelperClass.assert_equal(
20, match3_instance.MAX_CASCADE_ITERATIONS, "MAX_CASCADE_ITERATIONS prevents infinite loops"
15, match3_instance.MAX_GRID_SIZE, "MAX_GRID_SIZE is reasonable"
)
TestHelperClass.assert_equal(
10, match3_instance.MAX_TILE_TYPES, "MAX_TILE_TYPES is reasonable"
)
TestHelperClass.assert_equal(
20,
match3_instance.MAX_CASCADE_ITERATIONS,
"MAX_CASCADE_ITERATIONS prevents infinite loops"
)
TestHelperClass.assert_equal(
3, match3_instance.MIN_GRID_SIZE, "MIN_GRID_SIZE is reasonable"
)
TestHelperClass.assert_equal(
3, match3_instance.MIN_TILE_TYPES, "MIN_TILE_TYPES is reasonable"
)
TestHelperClass.assert_equal(3, match3_instance.MIN_GRID_SIZE, "MIN_GRID_SIZE is reasonable")
TestHelperClass.assert_equal(3, match3_instance.MIN_TILE_TYPES, "MIN_TILE_TYPES is reasonable")
# Test current values are within safety limits
TestHelperClass.assert_in_range(
@@ -148,13 +183,16 @@ func test_constants_and_safety_limits():
# Test timing constants
TestHelperClass.assert_true(
"CASCADE_WAIT_TIME" in match3_instance, "CASCADE_WAIT_TIME constant exists"
"CASCADE_WAIT_TIME" in match3_instance,
"CASCADE_WAIT_TIME constant exists"
)
TestHelperClass.assert_true(
"SWAP_ANIMATION_TIME" in match3_instance, "SWAP_ANIMATION_TIME constant exists"
"SWAP_ANIMATION_TIME" in match3_instance,
"SWAP_ANIMATION_TIME constant exists"
)
TestHelperClass.assert_true(
"TILE_DROP_WAIT_TIME" in match3_instance, "TILE_DROP_WAIT_TIME constant exists"
"TILE_DROP_WAIT_TIME" in match3_instance,
"TILE_DROP_WAIT_TIME constant exists"
)
@@ -165,8 +203,12 @@ func test_grid_initialization():
return
# Test grid structure
TestHelperClass.assert_not_null(match3_instance.grid, "Grid array is initialized")
TestHelperClass.assert_true(match3_instance.grid is Array, "Grid is Array type")
TestHelperClass.assert_not_null(
match3_instance.grid, "Grid array is initialized"
)
TestHelperClass.assert_true(
match3_instance.grid is Array, "Grid is Array type"
)
# Test grid dimensions
var expected_height = match3_instance.GRID_SIZE.y
@@ -180,7 +222,9 @@ func test_grid_initialization():
for y in range(match3_instance.grid.size()):
if y < expected_height:
TestHelperClass.assert_equal(
expected_width, match3_instance.grid[y].size(), "Grid row %d has correct width" % y
expected_width,
match3_instance.grid[y].size(),
"Grid row %d has correct width" % y
)
# Test tiles are properly instantiated
@@ -195,10 +239,12 @@ func test_grid_initialization():
if tile and is_instance_valid(tile):
valid_tile_count += 1
TestHelperClass.assert_true(
"tile_type" in tile, "Tile at (%d,%d) has tile_type property" % [x, y]
"tile_type" in tile,
"Tile at (%d,%d) has tile_type property" % [x, y]
)
TestHelperClass.assert_true(
"grid_position" in tile, "Tile at (%d,%d) has grid_position property" % [x, y]
"grid_position" in tile,
"Tile at (%d,%d) has grid_position property" % [x, y]
)
# Test tile type is within valid range
@@ -222,15 +268,24 @@ func test_grid_layout_calculation():
return
# Test tile size calculation
TestHelperClass.assert_true(match3_instance.tile_size > 0, "Tile size is positive")
TestHelperClass.assert_true(
match3_instance.tile_size <= 200, "Tile size is reasonable (not too large)"
match3_instance.tile_size > 0, "Tile size is positive"
)
TestHelperClass.assert_true(
match3_instance.tile_size <= 200,
"Tile size is reasonable (not too large)"
)
# Test grid offset
TestHelperClass.assert_not_null(match3_instance.grid_offset, "Grid offset is set")
TestHelperClass.assert_true(match3_instance.grid_offset.x >= 0, "Grid offset X is non-negative")
TestHelperClass.assert_true(match3_instance.grid_offset.y >= 0, "Grid offset Y is non-negative")
TestHelperClass.assert_not_null(
match3_instance.grid_offset, "Grid offset is set"
)
TestHelperClass.assert_true(
match3_instance.grid_offset.x >= 0, "Grid offset X is non-negative"
)
TestHelperClass.assert_true(
match3_instance.grid_offset.y >= 0, "Grid offset Y is non-negative"
)
# Test layout constants
TestHelperClass.assert_equal(
@@ -242,7 +297,9 @@ func test_grid_layout_calculation():
TestHelperClass.assert_equal(
50.0, match3_instance.GRID_LEFT_MARGIN, "Grid left margin constant"
)
TestHelperClass.assert_equal(50.0, match3_instance.GRID_TOP_MARGIN, "Grid top margin constant")
TestHelperClass.assert_equal(
50.0, match3_instance.GRID_TOP_MARGIN, "Grid top margin constant"
)
func test_state_management():
@@ -253,23 +310,30 @@ func test_state_management():
# Test GameState enum exists and has expected values
var game_state_class = match3_instance.get_script().get_global_class()
TestHelperClass.assert_true("GameState" in match3_instance, "GameState enum accessible")
TestHelperClass.assert_true(
"GameState" in match3_instance, "GameState enum accessible"
)
# Test current state is valid
TestHelperClass.assert_not_null(match3_instance.current_state, "Current state is set")
TestHelperClass.assert_not_null(
match3_instance.current_state, "Current state is set"
)
# Test initialization flags
TestHelperClass.assert_true(
"grid_initialized" in match3_instance, "Grid initialized flag exists"
)
TestHelperClass.assert_true(match3_instance.grid_initialized, "Grid is marked as initialized")
TestHelperClass.assert_true(
match3_instance.grid_initialized, "Grid is marked as initialized"
)
# Test instance ID for debugging
TestHelperClass.assert_true(
"instance_id" in match3_instance, "Instance ID exists for debugging"
)
TestHelperClass.assert_true(
match3_instance.instance_id.begins_with("Match3_"), "Instance ID has correct format"
match3_instance.instance_id.begins_with("Match3_"),
"Instance ID has correct format"
)
@@ -281,13 +345,16 @@ func test_match_detection():
# Test match detection methods exist and can be called safely
TestHelperClass.assert_true(
match3_instance.has_method("_has_match_at"), "_has_match_at method exists"
match3_instance.has_method("_has_match_at"),
"_has_match_at method exists"
)
TestHelperClass.assert_true(
match3_instance.has_method("_check_for_matches"), "_check_for_matches method exists"
match3_instance.has_method("_check_for_matches"),
"_check_for_matches method exists"
)
TestHelperClass.assert_true(
match3_instance.has_method("_get_match_line"), "_get_match_line method exists"
match3_instance.has_method("_get_match_line"),
"_get_match_line method exists"
)
# Test boundary checking with invalid positions
@@ -310,7 +377,10 @@ func test_match_detection():
)
TestHelperClass.assert_true(
is_invalid,
"Invalid position (%d,%d) is correctly identified as invalid" % [pos.x, pos.y]
(
"Invalid position (%d,%d) is correctly identified as invalid"
% [pos.x, pos.y]
)
)
# Test valid positions through public interface
@@ -324,7 +394,8 @@ func test_match_detection():
and pos.y < match3_instance.GRID_SIZE.y
)
TestHelperClass.assert_true(
is_valid, "Valid position (%d,%d) is within grid bounds" % [x, y]
is_valid,
"Valid position (%d,%d) is within grid bounds" % [x, y]
)
@@ -339,12 +410,14 @@ func test_scoring_system():
# Test that the match3 instance can handle scoring (indirectly through clearing matches)
TestHelperClass.assert_true(
match3_instance.has_method("_clear_matches"), "Scoring system method exists"
match3_instance.has_method("_clear_matches"),
"Scoring system method exists"
)
# Test that score_changed signal exists
TestHelperClass.assert_true(
match3_instance.has_signal("score_changed"), "Score changed signal exists"
match3_instance.has_signal("score_changed"),
"Score changed signal exists"
)
# Test scoring formula logic (based on the documented formula)
@@ -360,7 +433,9 @@ func test_scoring_system():
calculated_score = match_size + max(0, match_size - 2)
TestHelperClass.assert_equal(
expected_score, calculated_score, "Scoring formula correct for %d gems" % match_size
expected_score,
calculated_score,
"Scoring formula correct for %d gems" % match_size
)
@@ -375,22 +450,26 @@ func test_input_validation():
match3_instance.cursor_position, "Cursor position is initialized"
)
TestHelperClass.assert_true(
match3_instance.cursor_position is Vector2i, "Cursor position is Vector2i type"
match3_instance.cursor_position is Vector2i,
"Cursor position is Vector2i type"
)
# Test keyboard navigation flag
TestHelperClass.assert_true(
"keyboard_navigation_enabled" in match3_instance, "Keyboard navigation flag exists"
"keyboard_navigation_enabled" in match3_instance,
"Keyboard navigation flag exists"
)
TestHelperClass.assert_true(
match3_instance.keyboard_navigation_enabled is bool, "Keyboard navigation flag is boolean"
match3_instance.keyboard_navigation_enabled is bool,
"Keyboard navigation flag is boolean"
)
# Test selected tile safety
# selected_tile can be null initially, which is valid
if match3_instance.selected_tile:
TestHelperClass.assert_true(
is_instance_valid(match3_instance.selected_tile), "Selected tile is valid if not null"
is_instance_valid(match3_instance.selected_tile),
"Selected tile is valid if not null"
)
@@ -412,20 +491,25 @@ func test_memory_safety():
var tile = match3_instance.grid[y][x]
if tile:
TestHelperClass.assert_true(
is_instance_valid(tile), "Grid tile at (%d,%d) is valid instance" % [x, y]
is_instance_valid(tile),
"Grid tile at (%d,%d) is valid instance" % [x, y]
)
TestHelperClass.assert_true(
tile.get_parent() == match3_instance, "Tile properly parented to Match3"
tile.get_parent() == match3_instance,
"Tile properly parented to Match3"
)
# Test position validation
TestHelperClass.assert_true(
match3_instance.has_method("_is_valid_grid_position"), "Position validation method exists"
match3_instance.has_method("_is_valid_grid_position"),
"Position validation method exists"
)
# Test safe tile access patterns exist
# The Match3 code uses comprehensive bounds checking and null validation
TestHelperClass.assert_true(true, "Memory safety patterns implemented in Match3 code")
TestHelperClass.assert_true(
true, "Memory safety patterns implemented in Match3 code"
)
func test_performance_requirements():
@@ -449,13 +533,16 @@ func test_performance_requirements():
# Test timing constants are reasonable for 60fps gameplay
TestHelperClass.assert_true(
match3_instance.CASCADE_WAIT_TIME >= 0.05, "Cascade wait time allows for smooth animation"
match3_instance.CASCADE_WAIT_TIME >= 0.05,
"Cascade wait time allows for smooth animation"
)
TestHelperClass.assert_true(
match3_instance.SWAP_ANIMATION_TIME <= 0.5, "Swap animation time is responsive"
match3_instance.SWAP_ANIMATION_TIME <= 0.5,
"Swap animation time is responsive"
)
TestHelperClass.assert_true(
match3_instance.TILE_DROP_WAIT_TIME <= 0.3, "Tile drop wait time is responsive"
match3_instance.TILE_DROP_WAIT_TIME <= 0.3,
"Tile drop wait time is responsive"
)
# Test grid initialization performance

View File

@@ -58,7 +58,9 @@ func test_migration_compatibility():
# The checksums should be different (old system broken)
TestHelperClass.assert_not_equal(
old_checksum, new_checksum, "Old and new checksum formats should be different"
old_checksum,
new_checksum,
"Old and new checksum formats should be different"
)
print("Old checksum: %s" % old_checksum)
print("New checksum: %s" % new_checksum)
@@ -85,9 +87,13 @@ func test_migration_compatibility():
print("Consistent checksum: %s" % first_checksum)
TestHelperClass.print_step("Migration Strategy Verification")
TestHelperClass.assert_true(true, "Version-based checksum handling implemented")
TestHelperClass.assert_true(
true, "Version-based checksum handling implemented"
)
print("✓ Files without _checksum: Allow (backward compatibility)")
print("✓ Files with version < current: Recalculate checksum after migration")
print(
"✓ Files with version < current: Recalculate checksum after migration"
)
print("✓ Files with current version: Use new checksum validation")

View File

@@ -46,7 +46,9 @@ func test_scene_discovery():
for directory in scene_directories:
discover_scenes_in_directory(directory)
TestHelperClass.assert_true(discovered_scenes.size() > 0, "Found scenes in project")
TestHelperClass.assert_true(
discovered_scenes.size() > 0, "Found scenes in project"
)
print("Discovered %d scene files" % discovered_scenes.size())
# List discovered scenes for reference
@@ -89,23 +91,31 @@ func validate_scene_loading(scene_path: String):
# Check if resource exists
if not ResourceLoader.exists(scene_path):
validation_results[scene_path] = "Resource does not exist"
TestHelperClass.assert_false(true, "%s - Resource does not exist" % scene_name)
TestHelperClass.assert_false(
true, "%s - Resource does not exist" % scene_name
)
return
# Attempt to load the scene
var packed_scene = load(scene_path)
if not packed_scene:
validation_results[scene_path] = "Failed to load scene"
TestHelperClass.assert_false(true, "%s - Failed to load scene" % scene_name)
TestHelperClass.assert_false(
true, "%s - Failed to load scene" % scene_name
)
return
if not packed_scene is PackedScene:
validation_results[scene_path] = "Resource is not a PackedScene"
TestHelperClass.assert_false(true, "%s - Resource is not a PackedScene" % scene_name)
TestHelperClass.assert_false(
true, "%s - Resource is not a PackedScene" % scene_name
)
return
validation_results[scene_path] = "Loading successful"
TestHelperClass.assert_true(true, "%s - Scene loads successfully" % scene_name)
TestHelperClass.assert_true(
true, "%s - Scene loads successfully" % scene_name
)
func test_scene_instantiation():
@@ -127,12 +137,15 @@ func validate_scene_instantiation(scene_path: String):
var scene_instance = packed_scene.instantiate()
if not scene_instance:
validation_results[scene_path] = "Failed to instantiate scene"
TestHelperClass.assert_false(true, "%s - Failed to instantiate scene" % scene_name)
TestHelperClass.assert_false(
true, "%s - Failed to instantiate scene" % scene_name
)
return
# Validate the instance
TestHelperClass.assert_not_null(
scene_instance, "%s - Scene instantiation creates valid node" % scene_name
scene_instance,
"%s - Scene instantiation creates valid node" % scene_name
)
# Clean up the instance
@@ -148,8 +161,8 @@ func test_critical_scenes():
# Define critical scenes that must work
var critical_scenes = [
"res://scenes/main/main.tscn",
"res://scenes/game/game.tscn",
"res://scenes/main/Main.tscn",
"res://scenes/game/Game.tscn",
"res://scenes/ui/MainMenu.tscn",
"res://scenes/game/gameplays/Match3Gameplay.tscn"
]
@@ -160,10 +173,15 @@ func test_critical_scenes():
TestHelperClass.assert_equal(
"Full validation successful",
status,
"Critical scene %s must pass all validation" % scene_path.get_file()
(
"Critical scene %s must pass all validation"
% scene_path.get_file()
)
)
else:
TestHelperClass.assert_false(true, "Critical scene missing: %s" % scene_path)
TestHelperClass.assert_false(
true, "Critical scene missing: %s" % scene_path
)
func print_validation_summary():
@@ -175,7 +193,10 @@ func print_validation_summary():
for scene_path in discovered_scenes:
var status = validation_results.get(scene_path, "Not tested")
if status == "Full validation successful" or status == "Loading successful":
if (
status == "Full validation successful"
or status == "Loading successful"
):
successful_scenes += 1
else:
failed_scenes += 1

View File

@@ -64,23 +64,35 @@ func test_basic_functionality():
# Test that SettingsManager has expected methods
var expected_methods = [
"get_setting", "set_setting", "save_settings", "load_settings", "reset_settings_to_defaults"
"get_setting",
"set_setting",
"save_settings",
"load_settings",
"reset_settings_to_defaults"
]
TestHelperClass.assert_has_methods(
settings_manager, expected_methods, "SettingsManager methods"
)
# Test default settings structure
var expected_defaults = ["master_volume", "music_volume", "sfx_volume", "language"]
var expected_defaults = [
"master_volume", "music_volume", "sfx_volume", "language"
]
for key in expected_defaults:
TestHelperClass.assert_has_key(
settings_manager.default_settings, key, "Default setting key: " + key
settings_manager.default_settings,
key,
"Default setting key: " + key
)
# Test getting settings
var master_volume = settings_manager.get_setting("master_volume")
TestHelperClass.assert_not_null(master_volume, "Can get master_volume setting")
TestHelperClass.assert_true(master_volume is float, "master_volume is float type")
TestHelperClass.assert_not_null(
master_volume, "Can get master_volume setting"
)
TestHelperClass.assert_true(
master_volume is float, "master_volume is float type"
)
func test_input_validation_security():
@@ -88,38 +100,56 @@ func test_input_validation_security():
# Test NaN validation
var nan_result = settings_manager.set_setting("master_volume", NAN)
TestHelperClass.assert_false(nan_result, "NaN values rejected for volume settings")
TestHelperClass.assert_false(
nan_result, "NaN values rejected for volume settings"
)
# Test Infinity validation
var inf_result = settings_manager.set_setting("master_volume", INF)
TestHelperClass.assert_false(inf_result, "Infinity values rejected for volume settings")
TestHelperClass.assert_false(
inf_result, "Infinity values rejected for volume settings"
)
# Test negative infinity validation
var neg_inf_result = settings_manager.set_setting("master_volume", -INF)
TestHelperClass.assert_false(neg_inf_result, "Negative infinity values rejected")
TestHelperClass.assert_false(
neg_inf_result, "Negative infinity values rejected"
)
# Test range validation for volumes
var negative_volume = settings_manager.set_setting("master_volume", -0.5)
TestHelperClass.assert_false(negative_volume, "Negative volume values rejected")
TestHelperClass.assert_false(
negative_volume, "Negative volume values rejected"
)
var excessive_volume = settings_manager.set_setting("master_volume", 1.5)
TestHelperClass.assert_false(excessive_volume, "Volume values > 1.0 rejected")
TestHelperClass.assert_false(
excessive_volume, "Volume values > 1.0 rejected"
)
# Test valid volume range
var valid_volume = settings_manager.set_setting("master_volume", 0.5)
TestHelperClass.assert_true(valid_volume, "Valid volume values accepted")
TestHelperClass.assert_equal(
0.5, settings_manager.get_setting("master_volume"), "Volume value set correctly"
0.5,
settings_manager.get_setting("master_volume"),
"Volume value set correctly"
)
# Test string length validation for language
var long_language = "a".repeat(20) # Exceeds MAX_SETTING_STRING_LENGTH
var long_lang_result = settings_manager.set_setting("language", long_language)
TestHelperClass.assert_false(long_lang_result, "Excessively long language codes rejected")
var long_lang_result = settings_manager.set_setting(
"language", long_language
)
TestHelperClass.assert_false(
long_lang_result, "Excessively long language codes rejected"
)
# Test invalid characters in language code
var invalid_chars = settings_manager.set_setting("language", "en<script>")
TestHelperClass.assert_false(invalid_chars, "Language codes with invalid characters rejected")
TestHelperClass.assert_false(
invalid_chars, "Language codes with invalid characters rejected"
)
# Test valid language code
var valid_lang = settings_manager.set_setting("language", "en")
@@ -141,10 +171,14 @@ func test_file_io_security():
# Test loading with backup scenario
settings_manager.load_settings()
TestHelperClass.assert_not_null(settings_manager.settings, "Settings loaded successfully")
TestHelperClass.assert_not_null(
settings_manager.settings, "Settings loaded successfully"
)
# Test that settings file exists after save
TestHelperClass.assert_file_exists("user://settings.cfg", "Settings file created after save")
TestHelperClass.assert_file_exists(
"user://settings.cfg", "Settings file created after save"
)
func test_json_parsing_security():
@@ -157,7 +191,9 @@ func test_json_parsing_security():
temp_files.append(invalid_json_path)
# Create oversized JSON file
var large_json_content = '{"languages": {"' + "x".repeat(70000) + '": "test"}}'
var large_json_content = (
'{"languages": {"' + "x".repeat(70000) + '": "test"}}'
)
var oversized_json_path = TestHelper.create_temp_file(
"oversized_languages.json", large_json_content
)
@@ -178,11 +214,15 @@ func test_language_validation():
var supported_langs = ["en", "ru"]
for lang in supported_langs:
var result = settings_manager.set_setting("language", lang)
TestHelperClass.assert_true(result, "Supported language accepted: " + lang)
TestHelperClass.assert_true(
result, "Supported language accepted: " + lang
)
# Test unsupported language
var unsupported_result = settings_manager.set_setting("language", "xyz")
TestHelperClass.assert_false(unsupported_result, "Unsupported language rejected")
TestHelperClass.assert_false(
unsupported_result, "Unsupported language rejected"
)
# Test empty language
var empty_result = settings_manager.set_setting("language", "")
@@ -201,26 +241,32 @@ func test_volume_validation():
for setting in volume_settings:
# Test boundary values
TestHelperClass.assert_true(
settings_manager.set_setting(setting, 0.0), "Volume 0.0 accepted for " + setting
settings_manager.set_setting(setting, 0.0),
"Volume 0.0 accepted for " + setting
)
TestHelperClass.assert_true(
settings_manager.set_setting(setting, 1.0), "Volume 1.0 accepted for " + setting
settings_manager.set_setting(setting, 1.0),
"Volume 1.0 accepted for " + setting
)
# Test out of range values
TestHelperClass.assert_false(
settings_manager.set_setting(setting, -0.1), "Negative volume rejected for " + setting
settings_manager.set_setting(setting, -0.1),
"Negative volume rejected for " + setting
)
TestHelperClass.assert_false(
settings_manager.set_setting(setting, 1.1), "Volume > 1.0 rejected for " + setting
settings_manager.set_setting(setting, 1.1),
"Volume > 1.0 rejected for " + setting
)
# Test invalid types
TestHelperClass.assert_false(
settings_manager.set_setting(setting, "0.5"), "String volume rejected for " + setting
settings_manager.set_setting(setting, "0.5"),
"String volume rejected for " + setting
)
TestHelperClass.assert_false(
settings_manager.set_setting(setting, null), "Null volume rejected for " + setting
settings_manager.set_setting(setting, null),
"Null volume rejected for " + setting
)
@@ -228,8 +274,12 @@ func test_error_handling_and_recovery():
TestHelperClass.print_step("Error Handling and Recovery")
# Test unknown setting key
var unknown_result = settings_manager.set_setting("unknown_setting", "value")
TestHelperClass.assert_false(unknown_result, "Unknown setting keys rejected")
var unknown_result = settings_manager.set_setting(
"unknown_setting", "value"
)
TestHelperClass.assert_false(
unknown_result, "Unknown setting keys rejected"
)
# Test recovery from corrupted settings
# Save current state
@@ -248,13 +298,18 @@ func test_error_handling_and_recovery():
# Test fallback language loading
TestHelperClass.assert_true(
settings_manager.languages_data.has("languages"), "Fallback languages loaded"
settings_manager.languages_data.has("languages"),
"Fallback languages loaded"
)
TestHelperClass.assert_has_key(
settings_manager.languages_data["languages"], "en", "English fallback language available"
settings_manager.languages_data["languages"],
"en",
"English fallback language available"
)
TestHelperClass.assert_has_key(
settings_manager.languages_data["languages"], "ru", "Russian fallback language available"
settings_manager.languages_data["languages"],
"ru",
"Russian fallback language available"
)
@@ -281,7 +336,9 @@ func test_reset_functionality():
)
# Test that reset saves automatically
TestHelperClass.assert_file_exists("user://settings.cfg", "Settings file exists after reset")
TestHelperClass.assert_file_exists(
"user://settings.cfg", "Settings file exists after reset"
)
func test_performance_benchmarks():
@@ -290,18 +347,24 @@ func test_performance_benchmarks():
# Test settings load performance
TestHelperClass.start_performance_test("load_settings")
settings_manager.load_settings()
TestHelperClass.end_performance_test("load_settings", 100.0, "Settings load within 100ms")
TestHelperClass.end_performance_test(
"load_settings", 100.0, "Settings load within 100ms"
)
# Test settings save performance
TestHelperClass.start_performance_test("save_settings")
settings_manager.save_settings()
TestHelperClass.end_performance_test("save_settings", 50.0, "Settings save within 50ms")
TestHelperClass.end_performance_test(
"save_settings", 50.0, "Settings save within 50ms"
)
# Test validation performance
TestHelperClass.start_performance_test("validation")
for i in range(100):
settings_manager.set_setting("master_volume", 0.5)
TestHelperClass.end_performance_test("validation", 50.0, "100 validations within 50ms")
TestHelperClass.end_performance_test(
"validation", 50.0, "100 validations within 50ms"
)
func cleanup_tests():

View File

@@ -62,7 +62,9 @@ func setup_test_environment():
if tile_scene:
tile_instance = tile_scene.instantiate()
test_viewport.add_child(tile_instance)
TestHelperClass.assert_not_null(tile_instance, "Tile instance created successfully")
TestHelperClass.assert_not_null(
tile_instance, "Tile instance created successfully"
)
# Wait for initialization
await process_frame
@@ -73,7 +75,9 @@ func test_basic_functionality():
TestHelperClass.print_step("Basic Functionality")
if not tile_instance:
TestHelperClass.assert_true(false, "Tile instance not available for testing")
TestHelperClass.assert_true(
false, "Tile instance not available for testing"
)
return
# Test that Tile has expected properties
@@ -86,7 +90,9 @@ func test_basic_functionality():
"active_gem_types"
]
for prop in expected_properties:
TestHelperClass.assert_true(prop in tile_instance, "Tile has property: " + prop)
TestHelperClass.assert_true(
prop in tile_instance, "Tile has property: " + prop
)
# Test that Tile has expected methods
var expected_methods = [
@@ -96,19 +102,28 @@ func test_basic_functionality():
"remove_gem_type",
"force_reset_visual_state"
]
TestHelperClass.assert_has_methods(tile_instance, expected_methods, "Tile component methods")
TestHelperClass.assert_has_methods(
tile_instance, expected_methods, "Tile component methods"
)
# Test signals
TestHelperClass.assert_true(
tile_instance.has_signal("tile_selected"), "Tile has tile_selected signal"
tile_instance.has_signal("tile_selected"),
"Tile has tile_selected signal"
)
# Test sprite reference
TestHelperClass.assert_not_null(tile_instance.sprite, "Sprite node is available")
TestHelperClass.assert_true(tile_instance.sprite is Sprite2D, "Sprite is Sprite2D type")
TestHelperClass.assert_not_null(
tile_instance.sprite, "Sprite node is available"
)
TestHelperClass.assert_true(
tile_instance.sprite is Sprite2D, "Sprite is Sprite2D type"
)
# Test group membership
TestHelperClass.assert_true(tile_instance.is_in_group("tiles"), "Tile is in 'tiles' group")
TestHelperClass.assert_true(
tile_instance.is_in_group("tiles"), "Tile is in 'tiles' group"
)
func test_tile_constants():
@@ -118,22 +133,33 @@ func test_tile_constants():
return
# Test TILE_SIZE constant
TestHelperClass.assert_equal(48, tile_instance.TILE_SIZE, "TILE_SIZE constant is correct")
TestHelperClass.assert_equal(
48, tile_instance.TILE_SIZE, "TILE_SIZE constant is correct"
)
# Test all_gem_textures array
TestHelperClass.assert_not_null(tile_instance.all_gem_textures, "All gem textures array exists")
TestHelperClass.assert_not_null(
tile_instance.all_gem_textures, "All gem textures array exists"
)
TestHelperClass.assert_true(
tile_instance.all_gem_textures is Array, "All gem textures is Array type"
tile_instance.all_gem_textures is Array,
"All gem textures is Array type"
)
TestHelperClass.assert_equal(
8, tile_instance.all_gem_textures.size(), "All gem textures has expected count"
8,
tile_instance.all_gem_textures.size(),
"All gem textures has expected count"
)
# Test that all gem textures are valid
for i in range(tile_instance.all_gem_textures.size()):
var texture = tile_instance.all_gem_textures[i]
TestHelperClass.assert_not_null(texture, "Gem texture %d is not null" % i)
TestHelperClass.assert_true(texture is Texture2D, "Gem texture %d is Texture2D type" % i)
TestHelperClass.assert_not_null(
texture, "Gem texture %d is not null" % i
)
TestHelperClass.assert_true(
texture is Texture2D, "Gem texture %d is Texture2D type" % i
)
func test_texture_management():
@@ -147,10 +173,12 @@ func test_texture_management():
tile_instance.active_gem_types, "Active gem types is initialized"
)
TestHelperClass.assert_true(
tile_instance.active_gem_types is Array, "Active gem types is Array type"
tile_instance.active_gem_types is Array,
"Active gem types is Array type"
)
TestHelperClass.assert_true(
tile_instance.active_gem_types.size() > 0, "Active gem types has content"
tile_instance.active_gem_types.size() > 0,
"Active gem types has content"
)
# Test texture assignment for valid tile types
@@ -164,7 +192,8 @@ func test_texture_management():
if tile_instance.sprite:
TestHelperClass.assert_not_null(
tile_instance.sprite.texture, "Sprite texture assigned for type %d" % i
tile_instance.sprite.texture,
"Sprite texture assigned for type %d" % i
)
# Restore original type
@@ -184,42 +213,60 @@ func test_gem_type_management():
var test_gems = [0, 1, 2]
tile_instance.set_active_gem_types(test_gems)
TestHelperClass.assert_equal(
3, tile_instance.get_active_gem_count(), "Active gem count set correctly"
3,
tile_instance.get_active_gem_count(),
"Active gem count set correctly"
)
# Test add_gem_type
var add_result = tile_instance.add_gem_type(3)
TestHelperClass.assert_true(add_result, "Valid gem type added successfully")
TestHelperClass.assert_equal(
4, tile_instance.get_active_gem_count(), "Gem count increased after addition"
4,
tile_instance.get_active_gem_count(),
"Gem count increased after addition"
)
# Test adding duplicate gem type
var duplicate_result = tile_instance.add_gem_type(3)
TestHelperClass.assert_false(duplicate_result, "Duplicate gem type addition rejected")
TestHelperClass.assert_false(
duplicate_result, "Duplicate gem type addition rejected"
)
TestHelperClass.assert_equal(
4, tile_instance.get_active_gem_count(), "Gem count unchanged after duplicate"
4,
tile_instance.get_active_gem_count(),
"Gem count unchanged after duplicate"
)
# Test add_gem_type with invalid index
var invalid_add = tile_instance.add_gem_type(99)
TestHelperClass.assert_false(invalid_add, "Invalid gem index addition rejected")
TestHelperClass.assert_false(
invalid_add, "Invalid gem index addition rejected"
)
# Test remove_gem_type
var remove_result = tile_instance.remove_gem_type(3)
TestHelperClass.assert_true(remove_result, "Valid gem type removed successfully")
TestHelperClass.assert_true(
remove_result, "Valid gem type removed successfully"
)
TestHelperClass.assert_equal(
3, tile_instance.get_active_gem_count(), "Gem count decreased after removal"
3,
tile_instance.get_active_gem_count(),
"Gem count decreased after removal"
)
# Test removing non-existent gem type
var nonexistent_remove = tile_instance.remove_gem_type(99)
TestHelperClass.assert_false(nonexistent_remove, "Non-existent gem type removal rejected")
TestHelperClass.assert_false(
nonexistent_remove, "Non-existent gem type removal rejected"
)
# Test minimum gem types protection
tile_instance.set_active_gem_types([0, 1]) # Set to minimum
var protected_remove = tile_instance.remove_gem_type(0)
TestHelperClass.assert_false(protected_remove, "Minimum gem types protection active")
TestHelperClass.assert_false(
protected_remove, "Minimum gem types protection active"
)
TestHelperClass.assert_equal(
2, tile_instance.get_active_gem_count(), "Minimum gem count preserved"
)
@@ -240,7 +287,9 @@ func test_visual_feedback_system():
# Test selection visual feedback
tile_instance.is_selected = true
TestHelperClass.assert_true(tile_instance.is_selected, "Selection state set correctly")
TestHelperClass.assert_true(
tile_instance.is_selected, "Selection state set correctly"
)
# Wait for potential animation
await process_frame
@@ -256,21 +305,29 @@ func test_visual_feedback_system():
# Test highlight visual feedback
tile_instance.is_selected = false
tile_instance.is_highlighted = true
TestHelperClass.assert_true(tile_instance.is_highlighted, "Highlight state set correctly")
TestHelperClass.assert_true(
tile_instance.is_highlighted, "Highlight state set correctly"
)
# Wait for potential animation
await process_frame
# Test normal state
tile_instance.is_highlighted = false
TestHelperClass.assert_false(tile_instance.is_highlighted, "Normal state restored")
TestHelperClass.assert_false(
tile_instance.is_highlighted, "Normal state restored"
)
# Test force reset
tile_instance.is_selected = true
tile_instance.is_highlighted = true
tile_instance.force_reset_visual_state()
TestHelperClass.assert_false(tile_instance.is_selected, "Force reset clears selection")
TestHelperClass.assert_false(tile_instance.is_highlighted, "Force reset clears highlight")
TestHelperClass.assert_false(
tile_instance.is_selected, "Force reset clears selection"
)
TestHelperClass.assert_false(
tile_instance.is_highlighted, "Force reset clears highlight"
)
# Restore original state
tile_instance.is_selected = original_selected
@@ -284,12 +341,16 @@ func test_state_management():
return
# Test initial state
TestHelperClass.assert_true(tile_instance.tile_type >= 0, "Initial tile type is non-negative")
TestHelperClass.assert_true(
tile_instance.grid_position is Vector2i, "Grid position is Vector2i type"
tile_instance.tile_type >= 0, "Initial tile type is non-negative"
)
TestHelperClass.assert_true(
tile_instance.original_scale is Vector2, "Original scale is Vector2 type"
tile_instance.grid_position is Vector2i,
"Grid position is Vector2i type"
)
TestHelperClass.assert_true(
tile_instance.original_scale is Vector2,
"Original scale is Vector2 type"
)
# Test tile type bounds checking
@@ -324,20 +385,23 @@ func test_input_validation():
tile_instance.set_active_gem_types([])
# Should fall back to defaults or maintain previous state
TestHelperClass.assert_true(
tile_instance.get_active_gem_count() > 0, "Empty gem array handled gracefully"
tile_instance.get_active_gem_count() > 0,
"Empty gem array handled gracefully"
)
# Test null gem types array
tile_instance.set_active_gem_types(null)
TestHelperClass.assert_true(
tile_instance.get_active_gem_count() > 0, "Null gem array handled gracefully"
tile_instance.get_active_gem_count() > 0,
"Null gem array handled gracefully"
)
# Test invalid gem indices in array
tile_instance.set_active_gem_types([0, 1, 99, 2]) # 99 is invalid
# Should use fallback or filter invalid indices
TestHelperClass.assert_true(
tile_instance.get_active_gem_count() > 0, "Invalid gem indices handled gracefully"
tile_instance.get_active_gem_count() > 0,
"Invalid gem indices handled gracefully"
)
# Test negative gem indices
@@ -345,7 +409,9 @@ func test_input_validation():
TestHelperClass.assert_false(negative_add, "Negative gem index rejected")
# Test out-of-bounds gem indices
var oob_add = tile_instance.add_gem_type(tile_instance.all_gem_textures.size())
var oob_add = tile_instance.add_gem_type(
tile_instance.all_gem_textures.size()
)
TestHelperClass.assert_false(oob_add, "Out-of-bounds gem index rejected")
# Restore original state
@@ -359,9 +425,15 @@ func test_scaling_and_sizing():
return
# Test original scale calculation
TestHelperClass.assert_not_null(tile_instance.original_scale, "Original scale is calculated")
TestHelperClass.assert_true(tile_instance.original_scale.x > 0, "Original scale X is positive")
TestHelperClass.assert_true(tile_instance.original_scale.y > 0, "Original scale Y is positive")
TestHelperClass.assert_not_null(
tile_instance.original_scale, "Original scale is calculated"
)
TestHelperClass.assert_true(
tile_instance.original_scale.x > 0, "Original scale X is positive"
)
TestHelperClass.assert_true(
tile_instance.original_scale.y > 0, "Original scale Y is positive"
)
# Test that tile size is respected
if tile_instance.sprite and tile_instance.sprite.texture:
@@ -369,11 +441,14 @@ func test_scaling_and_sizing():
var scaled_size = texture_size * tile_instance.original_scale
var max_dimension = max(scaled_size.x, scaled_size.y)
TestHelperClass.assert_true(
max_dimension <= tile_instance.TILE_SIZE + 1, "Scaled tile fits within TILE_SIZE"
max_dimension <= tile_instance.TILE_SIZE + 1,
"Scaled tile fits within TILE_SIZE"
)
# Test scale animation for visual feedback
var original_scale = tile_instance.sprite.scale if tile_instance.sprite else Vector2.ONE
var original_scale = (
tile_instance.sprite.scale if tile_instance.sprite else Vector2.ONE
)
# Test selection scaling
tile_instance.is_selected = true
@@ -383,7 +458,8 @@ func test_scaling_and_sizing():
if tile_instance.sprite:
var selected_scale = tile_instance.sprite.scale
TestHelperClass.assert_true(
selected_scale.x >= original_scale.x, "Selected tile scale is larger or equal"
selected_scale.x >= original_scale.x,
"Selected tile scale is larger or equal"
)
# Reset to normal
@@ -420,7 +496,8 @@ func test_memory_safety():
# Test gem types array integrity
TestHelperClass.assert_true(
tile_instance.active_gem_types is Array, "Active gem types maintains Array type"
tile_instance.active_gem_types is Array,
"Active gem types maintains Array type"
)
# Test that gem indices are within bounds
@@ -444,12 +521,16 @@ func test_error_handling():
# Test that tile type setting handles null sprite gracefully
tile_instance.tile_type = 0 # Use public property instead
TestHelperClass.assert_true(true, "Tile type setting handles null sprite gracefully")
TestHelperClass.assert_true(
true, "Tile type setting handles null sprite gracefully"
)
# Test that scaling handles null sprite gracefully
# Force redraw to trigger scaling logic
tile_instance.queue_redraw()
TestHelperClass.assert_true(true, "Sprite scaling handles null sprite gracefully")
TestHelperClass.assert_true(
true, "Sprite scaling handles null sprite gracefully"
)
# Restore sprite
tile_instance.sprite = backup_sprite
@@ -473,7 +554,10 @@ func test_error_handling():
tile_instance.set_active_gem_types(large_gem_types)
# Should fall back to safe defaults
TestHelperClass.assert_true(
tile_instance.get_active_gem_count() <= tile_instance.all_gem_textures.size(),
(
tile_instance.get_active_gem_count()
<= tile_instance.all_gem_textures.size()
),
"Large gem array handled safely"
)

View File

@@ -55,7 +55,9 @@ func setup_test_environment():
# Load ValueStepper scene
stepper_scene = load("res://scenes/ui/components/ValueStepper.tscn")
TestHelperClass.assert_not_null(stepper_scene, "ValueStepper scene loads successfully")
TestHelperClass.assert_not_null(
stepper_scene, "ValueStepper scene loads successfully"
)
# Create test viewport for isolated testing
test_viewport = SubViewport.new()
@@ -79,15 +81,23 @@ func test_basic_functionality():
TestHelperClass.print_step("Basic Functionality")
if not stepper_instance:
TestHelperClass.assert_true(false, "ValueStepper instance not available for testing")
TestHelperClass.assert_true(
false, "ValueStepper instance not available for testing"
)
return
# Test that ValueStepper has expected properties
var expected_properties = [
"data_source", "custom_format_function", "values", "display_names", "current_index"
"data_source",
"custom_format_function",
"values",
"display_names",
"current_index"
]
for prop in expected_properties:
TestHelperClass.assert_true(prop in stepper_instance, "ValueStepper has property: " + prop)
TestHelperClass.assert_true(
prop in stepper_instance, "ValueStepper has property: " + prop
)
# Test that ValueStepper has expected methods
var expected_methods = [
@@ -105,12 +115,17 @@ func test_basic_functionality():
# Test signals
TestHelperClass.assert_true(
stepper_instance.has_signal("value_changed"), "ValueStepper has value_changed signal"
stepper_instance.has_signal("value_changed"),
"ValueStepper has value_changed signal"
)
# Test UI components
TestHelperClass.assert_not_null(stepper_instance.left_button, "Left button is available")
TestHelperClass.assert_not_null(stepper_instance.right_button, "Right button is available")
TestHelperClass.assert_not_null(
stepper_instance.left_button, "Left button is available"
)
TestHelperClass.assert_not_null(
stepper_instance.right_button, "Right button is available"
)
TestHelperClass.assert_not_null(
stepper_instance.value_display, "Value display label is available"
)
@@ -135,24 +150,33 @@ func test_data_source_loading():
# Test default language data source
TestHelperClass.assert_equal(
"language", stepper_instance.data_source, "Default data source is language"
"language",
stepper_instance.data_source,
"Default data source is language"
)
# Test that values are loaded
TestHelperClass.assert_not_null(stepper_instance.values, "Values array is initialized")
TestHelperClass.assert_not_null(
stepper_instance.values, "Values array is initialized"
)
TestHelperClass.assert_not_null(
stepper_instance.display_names, "Display names array is initialized"
)
TestHelperClass.assert_true(stepper_instance.values is Array, "Values is Array type")
TestHelperClass.assert_true(
stepper_instance.values is Array, "Values is Array type"
)
TestHelperClass.assert_true(
stepper_instance.display_names is Array, "Display names is Array type"
)
# Test that language data is loaded correctly
if stepper_instance.data_source == "language":
TestHelperClass.assert_true(stepper_instance.values.size() > 0, "Language values loaded")
TestHelperClass.assert_true(
stepper_instance.display_names.size() > 0, "Language display names loaded"
stepper_instance.values.size() > 0, "Language values loaded"
)
TestHelperClass.assert_true(
stepper_instance.display_names.size() > 0,
"Language display names loaded"
)
TestHelperClass.assert_equal(
stepper_instance.values.size(),
@@ -161,7 +185,9 @@ func test_data_source_loading():
)
# Test that current language is properly selected
var current_lang = root.get_node("SettingsManager").get_setting("language")
var current_lang = root.get_node("SettingsManager").get_setting(
"language"
)
var expected_index = stepper_instance.values.find(current_lang)
if expected_index >= 0:
TestHelperClass.assert_equal(
@@ -176,9 +202,13 @@ func test_data_source_loading():
test_viewport.add_child(resolution_stepper)
await process_frame
TestHelperClass.assert_true(resolution_stepper.values.size() > 0, "Resolution values loaded")
TestHelperClass.assert_true(
resolution_stepper.values.size() > 0, "Resolution values loaded"
)
TestHelperClass.assert_contains(
resolution_stepper.values, "1920x1080", "Resolution data contains expected value"
resolution_stepper.values,
"1920x1080",
"Resolution data contains expected value"
)
resolution_stepper.queue_free()
@@ -189,9 +219,13 @@ func test_data_source_loading():
test_viewport.add_child(difficulty_stepper)
await process_frame
TestHelperClass.assert_true(difficulty_stepper.values.size() > 0, "Difficulty values loaded")
TestHelperClass.assert_true(
difficulty_stepper.values.size() > 0, "Difficulty values loaded"
)
TestHelperClass.assert_contains(
difficulty_stepper.values, "normal", "Difficulty data contains expected value"
difficulty_stepper.values,
"normal",
"Difficulty data contains expected value"
)
TestHelperClass.assert_equal(
1, difficulty_stepper.current_index, "Difficulty defaults to normal"
@@ -214,13 +248,17 @@ func test_value_navigation():
var initial_value = stepper_instance.get_current_value()
stepper_instance.change_value(1)
var next_value = stepper_instance.get_current_value()
TestHelperClass.assert_not_equal(initial_value, next_value, "Forward navigation changes value")
TestHelperClass.assert_not_equal(
initial_value, next_value, "Forward navigation changes value"
)
# Test backward navigation
stepper_instance.change_value(-1)
var back_value = stepper_instance.get_current_value()
TestHelperClass.assert_equal(
initial_value, back_value, "Backward navigation returns to original value"
initial_value,
back_value,
"Backward navigation returns to original value"
)
# Test wrap-around forward
@@ -228,14 +266,18 @@ func test_value_navigation():
stepper_instance.current_index = max_index
stepper_instance.change_value(1)
TestHelperClass.assert_equal(
0, stepper_instance.current_index, "Forward navigation wraps to beginning"
0,
stepper_instance.current_index,
"Forward navigation wraps to beginning"
)
# Test wrap-around backward
stepper_instance.current_index = 0
stepper_instance.change_value(-1)
TestHelperClass.assert_equal(
max_index, stepper_instance.current_index, "Backward navigation wraps to end"
max_index,
stepper_instance.current_index,
"Backward navigation wraps to end"
)
# Restore original state
@@ -258,13 +300,19 @@ func test_custom_values():
var custom_values = ["apple", "banana", "cherry"]
stepper_instance.setup_custom_values(custom_values)
TestHelperClass.assert_equal(3, stepper_instance.values.size(), "Custom values set correctly")
TestHelperClass.assert_equal("apple", stepper_instance.values[0], "First custom value correct")
TestHelperClass.assert_equal(
3, stepper_instance.values.size(), "Custom values set correctly"
)
TestHelperClass.assert_equal(
"apple", stepper_instance.values[0], "First custom value correct"
)
TestHelperClass.assert_equal(
0, stepper_instance.current_index, "Index reset to 0 for custom values"
)
TestHelperClass.assert_equal(
"apple", stepper_instance.get_current_value(), "Current value matches first custom value"
"apple",
stepper_instance.get_current_value(),
"Current value matches first custom value"
)
# Test custom values with display names
@@ -272,31 +320,43 @@ func test_custom_values():
stepper_instance.setup_custom_values(custom_values, custom_display_names)
TestHelperClass.assert_equal(
3, stepper_instance.display_names.size(), "Custom display names set correctly"
3,
stepper_instance.display_names.size(),
"Custom display names set correctly"
)
TestHelperClass.assert_equal(
"Red Apple", stepper_instance.display_names[0], "First display name correct"
"Red Apple",
stepper_instance.display_names[0],
"First display name correct"
)
# Test navigation with custom values
stepper_instance.change_value(1)
TestHelperClass.assert_equal(
"banana", stepper_instance.get_current_value(), "Navigation works with custom values"
"banana",
stepper_instance.get_current_value(),
"Navigation works with custom values"
)
# Test set_current_value
stepper_instance.set_current_value("cherry")
TestHelperClass.assert_equal(
"cherry", stepper_instance.get_current_value(), "set_current_value works correctly"
"cherry",
stepper_instance.get_current_value(),
"set_current_value works correctly"
)
TestHelperClass.assert_equal(
2, stepper_instance.current_index, "Index updated correctly by set_current_value"
2,
stepper_instance.current_index,
"Index updated correctly by set_current_value"
)
# Test invalid value
stepper_instance.set_current_value("grape")
TestHelperClass.assert_equal(
"cherry", stepper_instance.get_current_value(), "Invalid value doesn't change current value"
"cherry",
stepper_instance.get_current_value(),
"Invalid value doesn't change current value"
)
# Restore original state
@@ -319,7 +379,9 @@ func test_input_handling():
var left_handled = stepper_instance.handle_input_action("move_left")
TestHelperClass.assert_true(left_handled, "Left input action handled")
TestHelperClass.assert_not_equal(
original_value, stepper_instance.get_current_value(), "Left action changes value"
original_value,
stepper_instance.get_current_value(),
"Left action changes value"
)
# Test right input action
@@ -333,14 +395,18 @@ func test_input_handling():
# Test invalid input action
var invalid_handled = stepper_instance.handle_input_action("invalid_action")
TestHelperClass.assert_false(invalid_handled, "Invalid input action not handled")
TestHelperClass.assert_false(
invalid_handled, "Invalid input action not handled"
)
# Test button press simulation
if stepper_instance.left_button:
var before_left = stepper_instance.get_current_value()
stepper_instance.handle_input_action("move_left")
TestHelperClass.assert_not_equal(
before_left, stepper_instance.get_current_value(), "Left button press changes value"
before_left,
stepper_instance.get_current_value(),
"Left button press changes value"
)
if stepper_instance.right_button:
@@ -365,9 +431,12 @@ func test_visual_feedback():
# Test highlighting
stepper_instance.set_highlighted(true)
TestHelperClass.assert_true(stepper_instance.is_highlighted, "Highlighted state set correctly")
TestHelperClass.assert_true(
stepper_instance.scale.x > original_scale.x, "Scale increased when highlighted"
stepper_instance.is_highlighted, "Highlighted state set correctly"
)
TestHelperClass.assert_true(
stepper_instance.scale.x > original_scale.x,
"Scale increased when highlighted"
)
# Test unhighlighting
@@ -376,17 +445,25 @@ func test_visual_feedback():
stepper_instance.is_highlighted, "Highlighted state cleared correctly"
)
TestHelperClass.assert_equal(
original_scale, stepper_instance.scale, "Scale restored when unhighlighted"
original_scale,
stepper_instance.scale,
"Scale restored when unhighlighted"
)
TestHelperClass.assert_equal(
original_modulate, stepper_instance.modulate, "Modulate restored when unhighlighted"
original_modulate,
stepper_instance.modulate,
"Modulate restored when unhighlighted"
)
# Test display update
if stepper_instance.value_display:
var current_text = stepper_instance.value_display.text
TestHelperClass.assert_true(current_text.length() > 0, "Value display has text content")
TestHelperClass.assert_not_equal("N/A", current_text, "Value display shows valid content")
TestHelperClass.assert_true(
current_text.length() > 0, "Value display has text content"
)
TestHelperClass.assert_not_equal(
"N/A", current_text, "Value display shows valid content"
)
func test_settings_integration():
@@ -413,13 +490,17 @@ func test_settings_integration():
# Value change is applied automatically through set_current_value
# Verify setting was updated
var updated_lang = root.get_node("SettingsManager").get_setting("language")
var updated_lang = root.get_node("SettingsManager").get_setting(
"language"
)
TestHelperClass.assert_equal(
target_lang, updated_lang, "Language setting updated correctly"
)
# Restore original language
root.get_node("SettingsManager").set_setting("language", original_lang)
root.get_node("SettingsManager").set_setting(
"language", original_lang
)
func test_boundary_conditions():
@@ -435,12 +516,16 @@ func test_boundary_conditions():
await process_frame
TestHelperClass.assert_equal(
"", empty_stepper.get_current_value(), "Empty values array returns empty string"
"",
empty_stepper.get_current_value(),
"Empty values array returns empty string"
)
# Test change_value with empty array
empty_stepper.change_value(1) # Should not crash
TestHelperClass.assert_true(true, "change_value handles empty array gracefully")
TestHelperClass.assert_true(
true, "change_value handles empty array gracefully"
)
empty_stepper.queue_free()
@@ -450,14 +535,18 @@ func test_boundary_conditions():
stepper_instance.current_index = -1
# Display updates automatically when value changes
TestHelperClass.assert_equal(
"N/A", stepper_instance.value_display.text, "Negative index shows N/A"
"N/A",
stepper_instance.value_display.text,
"Negative index shows N/A"
)
# Test out-of-bounds index handling
stepper_instance.current_index = stepper_instance.values.size()
# Display updates automatically when value changes
TestHelperClass.assert_equal(
"N/A", stepper_instance.value_display.text, "Out-of-bounds index shows N/A"
"N/A",
stepper_instance.value_display.text,
"Out-of-bounds index shows N/A"
)
# Restore valid index
@@ -487,7 +576,8 @@ func test_error_handling():
control_name.ends_with("_stepper"), "Control name has correct suffix"
)
TestHelperClass.assert_true(
control_name.begins_with(stepper_instance.data_source), "Control name includes data source"
control_name.begins_with(stepper_instance.data_source),
"Control name includes data source"
)
# Test custom values with mismatched arrays
@@ -496,16 +586,22 @@ func test_error_handling():
stepper_instance.setup_custom_values(values_3, names_2)
# Should handle gracefully - display_names should be duplicated from values
TestHelperClass.assert_equal(3, stepper_instance.values.size(), "Values array size preserved")
TestHelperClass.assert_equal(
2, stepper_instance.display_names.size(), "Display names size preserved as provided"
3, stepper_instance.values.size(), "Values array size preserved"
)
TestHelperClass.assert_equal(
2,
stepper_instance.display_names.size(),
"Display names size preserved as provided"
)
# Test navigation with mismatched arrays
stepper_instance.current_index = 2 # Index where display_names doesn't exist
# Display updates automatically when value changes
TestHelperClass.assert_equal(
"c", stepper_instance.value_display.text, "Falls back to value when display name missing"
"c",
stepper_instance.value_display.text,
"Falls back to value when display name missing"
)

1683
tools/generate_code_map.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -333,13 +333,31 @@ def print_result(success: bool, output: str = "", silent: bool = False) -> None:
def get_gd_files(project_root: Path) -> List[Path]:
"""Get all .gd files in the project."""
return list(project_root.rglob("*.gd"))
"""Get all .gd files in the project, respecting gitignore."""
gitignore_patterns = read_gitignore(project_root)
gd_files = []
for gd_file in project_root.rglob("*.gd"):
if gd_file.is_file() and not is_ignored_by_gitignore(
gd_file, project_root, gitignore_patterns
):
gd_files.append(gd_file)
return gd_files
def get_py_files(project_root: Path) -> List[Path]:
"""Get all .py files in the project."""
return list(project_root.rglob("*.py"))
"""Get all .py files in the project, respecting gitignore."""
gitignore_patterns = read_gitignore(project_root)
py_files = []
for py_file in project_root.rglob("*.py"):
if py_file.is_file() and not is_ignored_by_gitignore(
py_file, project_root, gitignore_patterns
):
py_files.append(py_file)
return py_files
def read_gitignore(project_root: Path) -> List[str]:
@@ -661,15 +679,21 @@ def check_naming_convention(file_path: Path) -> Tuple[bool, str]:
def get_naming_files(project_root: Path) -> List[Path]:
"""Get all .tscn and .gd files that should follow naming conventions."""
"""Get all .tscn and .gd files that should follow naming conventions, respecting gitignore."""
gitignore_patterns = read_gitignore(project_root)
files = []
for pattern in ["**/*.tscn", "**/*.gd"]:
files.extend(project_root.glob(pattern))
# Filter out files that should be ignored
for pattern in ["**/*.tscn", "**/*.gd"]:
for file_path in project_root.glob(pattern):
if file_path.is_file():
files.append(file_path)
# Filter out files that should be ignored (gitignore + TestHelper)
filtered_files = []
for file_path in files:
if not should_skip_file(file_path):
if not should_skip_file(file_path) and not is_ignored_by_gitignore(
file_path, project_root, gitignore_patterns
):
filtered_files.append(file_path)
return filtered_files
@@ -1302,6 +1326,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(
project_root: Path, silent: bool = False, yaml_output: bool = False
) -> Tuple[bool, Dict]:
@@ -1740,7 +1807,15 @@ def run_tests(
success = failed_tests == 0
if yaml_output:
output_yaml_results("test", {**stats, "results": test_results}, success)
yaml_results = {**stats, "results": test_results}
if failed_tests > 0:
yaml_results["failed_test_details"] = [
{"test": name, "error": error}
for name, passed, error in test_results
if not passed and error
]
output_yaml_results("test", yaml_results, success)
else:
print_summary("Test Execution Summary", stats, silent)
if not silent:
@@ -1847,7 +1922,15 @@ async def run_tests_async(
}
if yaml_output:
output_yaml_results("test", {**stats, "results": test_results}, failed == 0)
yaml_results = {**stats, "results": test_results}
if failed > 0:
yaml_results["failed_test_details"] = [
{"test": name, "error": error}
for name, passed, error in test_results
if not passed and error
]
output_yaml_results("test", yaml_results, failed == 0)
elif not silent:
print_summary("Test Summary", stats)
print()
@@ -1905,6 +1988,10 @@ def run_workflow(
"📝 Naming convention check (PascalCase)",
lambda root: run_naming(root, silent, yaml_output),
),
"codemap": (
"🗺️ Code map generation (yaml)",
lambda root: run_codemap(root, silent, yaml_output),
),
}
if not silent:
@@ -2060,6 +2147,12 @@ async def run_workflow_async(
root, silent, yaml_output
), # 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:
@@ -2174,7 +2267,7 @@ async def main_async():
parser.add_argument(
"--steps",
nargs="+",
choices=["lint", "format", "test", "validate", "ruff", "naming"],
choices=["lint", "format", "test", "validate", "ruff", "naming", "codemap"],
default=["format", "lint", "ruff", "test", "validate", "naming"],
help="Workflow steps to run",
)
@@ -2190,6 +2283,7 @@ async def main_async():
parser.add_argument(
"--naming", action="store_true", help="Check PascalCase naming conventions"
)
parser.add_argument("--codemap", action="store_true", help="Generate code map YAML")
parser.add_argument(
"--silent",
"-s",
@@ -2221,6 +2315,10 @@ async def main_async():
steps = ["validate"]
elif args.ruff:
steps = ["ruff"]
elif args.naming:
steps = ["naming"]
elif args.codemap:
steps = ["codemap"]
else:
steps = args.steps
@@ -2239,6 +2337,7 @@ async def main_async():
),
"ruff": lambda root: run_ruff_async(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)
else:
@@ -2249,6 +2348,7 @@ async def main_async():
"validate": lambda root: run_validate(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),
"codemap": lambda root: run_codemap(root, args.silent, args.yaml),
}
success, _ = step_funcs[steps[0]](project_root)
else:
@@ -2296,6 +2396,9 @@ def main():
parser.add_argument(
"--naming", action="store_true", help="Check PascalCase naming conventions"
)
parser.add_argument(
"--codemap", action="store_true", help="Generate code map YAML"
)
parser.add_argument(
"--silent",
"-s",
@@ -2327,6 +2430,10 @@ def main():
steps = ["validate"]
elif args.ruff:
steps = ["ruff"]
elif args.naming:
steps = ["naming"]
elif args.codemap:
steps = ["codemap"]
else:
steps = args.steps
@@ -2339,6 +2446,7 @@ def main():
"validate": lambda root: run_validate(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),
"codemap": lambda root: run_codemap(root, args.silent, args.yaml),
}
success, _ = step_funcs[steps[0]](project_root)
else: