# <!-- Powered by BMAD™ Core -->
template:
  id: game-architecture-template-v2
  name: Game Architecture Document
  version: 2.0
  output:
    format: markdown
    filename: "docs/{{game_name}}-game-architecture.md"
    title: "{{game_title}} Game Architecture Document"

workflow:
  mode: interactive

sections:
  - id: initial-setup
    instruction: |
      This template creates a comprehensive game architecture document specifically for Phaser 3 + TypeScript projects. This should provide the technical foundation for all game development stories and epics.

      If available, review any provided documents: Game Design Document (GDD), Technical Preferences. This architecture should support all game mechanics defined in the GDD.

  - id: introduction
    title: Introduction
    instruction: Establish the document's purpose and scope for game development
    content: |
      This document outlines the complete technical architecture for {{game_title}}, a 2D game built with Phaser 3 and TypeScript. It serves as the technical foundation for AI-driven game development, ensuring consistency and scalability across all game systems.

      This architecture is designed to support the gameplay mechanics defined in the Game Design Document while maintaining 60 FPS performance and cross-platform compatibility.
    sections:
      - id: change-log
        title: Change Log
        instruction: Track document versions and changes
        type: table
        template: |
          | Date | Version | Description | Author |
          | :--- | :------ | :---------- | :----- |

  - id: technical-overview
    title: Technical Overview
    instruction: Present all subsections together, then apply `tasks#advanced-elicitation` protocol to the complete section.
    sections:
      - id: architecture-summary
        title: Architecture Summary
        instruction: |
          Provide a comprehensive overview covering:

          - Game engine choice and configuration
          - Project structure and organization
          - Key systems and their interactions
          - Performance and optimization strategy
          - How this architecture achieves GDD requirements
      - id: platform-targets
        title: Platform Targets
        instruction: Based on GDD requirements, confirm platform support
        template: |
          **Primary Platform:** {{primary_platform}}
          **Secondary Platforms:** {{secondary_platforms}}
          **Minimum Requirements:** {{min_specs}}
          **Target Performance:** 60 FPS on {{target_device}}
      - id: technology-stack
        title: Technology Stack
        template: |
          **Core Engine:** Phaser 3.70+
          **Language:** TypeScript 5.0+ (Strict Mode)
          **Build Tool:** {{build_tool}} (Webpack/Vite/Parcel)
          **Package Manager:** {{package_manager}}
          **Testing:** {{test_framework}}
          **Deployment:** {{deployment_platform}}

  - id: project-structure
    title: Project Structure
    instruction: Define the complete project organization that developers will follow
    sections:
      - id: repository-organization
        title: Repository Organization
        instruction: Design a clear folder structure for game development
        type: code
        language: text
        template: |
          {{game_name}}/
          ├── src/
          │   ├── scenes/          # Game scenes
          │   ├── gameObjects/     # Custom game objects
          │   ├── systems/         # Core game systems
          │   ├── utils/           # Utility functions
          │   ├── types/           # TypeScript type definitions
          │   ├── config/          # Game configuration
          │   └── main.ts          # Entry point
          ├── assets/
          │   ├── images/          # Sprite assets
          │   ├── audio/           # Sound files
          │   ├── data/            # JSON data files
          │   └── fonts/           # Font files
          ├── public/              # Static web assets
          ├── tests/               # Test files
          ├── docs/                # Documentation
          │   ├── stories/         # Development stories
          │   └── architecture/    # Technical docs
          └── dist/                # Built game files
      - id: module-organization
        title: Module Organization
        instruction: Define how TypeScript modules should be organized
        sections:
          - id: scene-structure
            title: Scene Structure
            type: bullet-list
            template: |
              - Each scene in separate file
              - Scene-specific logic contained
              - Clear data passing between scenes
          - id: game-object-pattern
            title: Game Object Pattern
            type: bullet-list
            template: |
              - Component-based architecture
              - Reusable game object classes
              - Type-safe property definitions
          - id: system-architecture
            title: System Architecture
            type: bullet-list
            template: |
              - Singleton managers for global systems
              - Event-driven communication
              - Clear separation of concerns

  - id: core-game-systems
    title: Core Game Systems
    instruction: Detail each major system that needs to be implemented. Each system should be specific enough for developers to create implementation stories.
    sections:
      - id: scene-management
        title: Scene Management System
        template: |
          **Purpose:** Handle game flow and scene transitions

          **Key Components:**

          - Scene loading and unloading
          - Data passing between scenes
          - Transition effects
          - Memory management

          **Implementation Requirements:**

          - Preload scene for asset loading
          - Menu system with navigation
          - Gameplay scenes with state management
          - Pause/resume functionality

          **Files to Create:**

          - `src/scenes/BootScene.ts`
          - `src/scenes/PreloadScene.ts`
          - `src/scenes/MenuScene.ts`
          - `src/scenes/GameScene.ts`
          - `src/systems/SceneManager.ts`
      - id: game-state-management
        title: Game State Management
        template: |
          **Purpose:** Track player progress and game status

          **State Categories:**

          - Player progress (levels, unlocks)
          - Game settings (audio, controls)
          - Session data (current level, score)
          - Persistent data (achievements, statistics)

          **Implementation Requirements:**

          - Save/load system with localStorage
          - State validation and error recovery
          - Cross-session data persistence
          - Settings management

          **Files to Create:**

          - `src/systems/GameState.ts`
          - `src/systems/SaveManager.ts`
          - `src/types/GameData.ts`
      - id: asset-management
        title: Asset Management System
        template: |
          **Purpose:** Efficient loading and management of game assets

          **Asset Categories:**

          - Sprite sheets and animations
          - Audio files and music
          - Level data and configurations
          - UI assets and fonts

          **Implementation Requirements:**

          - Progressive loading strategy
          - Asset caching and optimization
          - Error handling for failed loads
          - Memory management for large assets

          **Files to Create:**

          - `src/systems/AssetManager.ts`
          - `src/config/AssetConfig.ts`
          - `src/utils/AssetLoader.ts`
      - id: input-management
        title: Input Management System
        template: |
          **Purpose:** Handle all player input across platforms

          **Input Types:**

          - Keyboard controls
          - Mouse/pointer interaction
          - Touch gestures (mobile)
          - Gamepad support (optional)

          **Implementation Requirements:**

          - Input mapping and configuration
          - Touch-friendly mobile controls
          - Input buffering for responsive gameplay
          - Customizable control schemes

          **Files to Create:**

          - `src/systems/InputManager.ts`
          - `src/utils/TouchControls.ts`
          - `src/types/InputTypes.ts`
      - id: game-mechanics-systems
        title: Game Mechanics Systems
        instruction: For each major mechanic defined in the GDD, create a system specification
        repeatable: true
        sections:
          - id: mechanic-system
            title: "{{mechanic_name}} System"
            template: |
              **Purpose:** {{system_purpose}}

              **Core Functionality:**

              - {{feature_1}}
              - {{feature_2}}
              - {{feature_3}}

              **Dependencies:** {{required_systems}}

              **Performance Considerations:** {{optimization_notes}}

              **Files to Create:**

              - `src/systems/{{system_name}}.ts`
              - `src/gameObjects/{{related_object}}.ts`
              - `src/types/{{system_types}}.ts`
      - id: physics-collision
        title: Physics & Collision System
        template: |
          **Physics Engine:** {{physics_choice}} (Arcade Physics/Matter.js)

          **Collision Categories:**

          - Player collision
          - Enemy interactions
          - Environmental objects
          - Collectibles and items

          **Implementation Requirements:**

          - Optimized collision detection
          - Physics body management
          - Collision callbacks and events
          - Performance monitoring

          **Files to Create:**

          - `src/systems/PhysicsManager.ts`
          - `src/utils/CollisionGroups.ts`
      - id: audio-system
        title: Audio System
        template: |
          **Audio Requirements:**

          - Background music with looping
          - Sound effects for actions
          - Audio settings and volume control
          - Mobile audio optimization

          **Implementation Features:**

          - Audio sprite management
          - Dynamic music system
          - Spatial audio (if applicable)
          - Audio pooling for performance

          **Files to Create:**

          - `src/systems/AudioManager.ts`
          - `src/config/AudioConfig.ts`
      - id: ui-system
        title: UI System
        template: |
          **UI Components:**

          - HUD elements (score, health, etc.)
          - Menu navigation
          - Modal dialogs
          - Settings screens

          **Implementation Requirements:**

          - Responsive layout system
          - Touch-friendly interface
          - Keyboard navigation support
          - Animation and transitions

          **Files to Create:**

          - `src/systems/UIManager.ts`
          - `src/gameObjects/UI/`
          - `src/types/UITypes.ts`

  - id: performance-architecture
    title: Performance Architecture
    instruction: Define performance requirements and optimization strategies
    sections:
      - id: performance-targets
        title: Performance Targets
        template: |
          **Frame Rate:** 60 FPS sustained, 30 FPS minimum
          **Memory Usage:** <{{memory_limit}}MB total
          **Load Times:** <{{initial_load}}s initial, <{{level_load}}s per level
          **Battery Optimization:** Reduced updates when not visible
      - id: optimization-strategies
        title: Optimization Strategies
        sections:
          - id: object-pooling
            title: Object Pooling
            type: bullet-list
            template: |
              - Bullets and projectiles
              - Particle effects
              - Enemy objects
              - UI elements
          - id: asset-optimization
            title: Asset Optimization
            type: bullet-list
            template: |
              - Texture atlases for sprites
              - Audio compression
              - Lazy loading for large assets
              - Progressive enhancement
          - id: rendering-optimization
            title: Rendering Optimization
            type: bullet-list
            template: |
              - Sprite batching
              - Culling off-screen objects
              - Reduced particle counts on mobile
              - Texture resolution scaling
          - id: optimization-files
            title: Files to Create
            type: bullet-list
            template: |
              - `src/utils/ObjectPool.ts`
              - `src/utils/PerformanceMonitor.ts`
              - `src/config/OptimizationConfig.ts`

  - id: game-configuration
    title: Game Configuration
    instruction: Define all configurable aspects of the game
    sections:
      - id: phaser-configuration
        title: Phaser Configuration
        type: code
        language: typescript
        template: |
          // src/config/GameConfig.ts
          const gameConfig: Phaser.Types.Core.GameConfig = {
              type: Phaser.AUTO,
              width: {{game_width}},
              height: {{game_height}},
              scale: {
                  mode: {{scale_mode}},
                  autoCenter: Phaser.Scale.CENTER_BOTH
              },
              physics: {
                  default: '{{physics_system}}',
                  {{physics_system}}: {
                      gravity: { y: {{gravity}} },
                      debug: false
                  }
              },
              // Additional configuration...
          };
      - id: game-balance-configuration
        title: Game Balance Configuration
        instruction: Based on GDD, define configurable game parameters
        type: code
        language: typescript
        template: |
          // src/config/GameBalance.ts
          export const GameBalance = {
              player: {
                  speed: {{player_speed}},
                  health: {{player_health}},
                  // Additional player parameters...
              },
              difficulty: {
                  easy: {{easy_params}},
                  normal: {{normal_params}},
                  hard: {{hard_params}}
              },
              // Additional balance parameters...
          };

  - id: development-guidelines
    title: Development Guidelines
    instruction: Provide coding standards specific to game development
    sections:
      - id: typescript-standards
        title: TypeScript Standards
        sections:
          - id: type-safety
            title: Type Safety
            type: bullet-list
            template: |
              - Use strict mode
              - Define interfaces for all data structures
              - Avoid `any` type usage
              - Use enums for game states
          - id: code-organization
            title: Code Organization
            type: bullet-list
            template: |
              - One class per file
              - Clear naming conventions
              - Proper error handling
              - Comprehensive documentation
      - id: phaser-best-practices
        title: Phaser 3 Best Practices
        sections:
          - id: scene-management-practices
            title: Scene Management
            type: bullet-list
            template: |
              - Clean up resources in shutdown()
              - Use scene data for communication
              - Implement proper event handling
              - Avoid memory leaks
          - id: game-object-design
            title: Game Object Design
            type: bullet-list
            template: |
              - Extend Phaser classes appropriately
              - Use component-based architecture
              - Implement object pooling where needed
              - Follow consistent update patterns
      - id: testing-strategy
        title: Testing Strategy
        sections:
          - id: unit-testing
            title: Unit Testing
            type: bullet-list
            template: |
              - Test game logic separately from Phaser
              - Mock Phaser dependencies
              - Test utility functions
              - Validate game balance calculations
          - id: integration-testing
            title: Integration Testing
            type: bullet-list
            template: |
              - Scene loading and transitions
              - Save/load functionality
              - Input handling
              - Performance benchmarks
          - id: test-files
            title: Files to Create
            type: bullet-list
            template: |
              - `tests/utils/GameLogic.test.ts`
              - `tests/systems/SaveManager.test.ts`
              - `tests/performance/FrameRate.test.ts`

  - id: deployment-architecture
    title: Deployment Architecture
    instruction: Define how the game will be built and deployed
    sections:
      - id: build-process
        title: Build Process
        sections:
          - id: development-build
            title: Development Build
            type: bullet-list
            template: |
              - Fast compilation
              - Source maps enabled
              - Debug logging active
              - Hot reload support
          - id: production-build
            title: Production Build
            type: bullet-list
            template: |
              - Minified and optimized
              - Asset compression
              - Performance monitoring
              - Error tracking
      - id: deployment-strategy
        title: Deployment Strategy
        sections:
          - id: web-deployment
            title: Web Deployment
            type: bullet-list
            template: |
              - Static hosting ({{hosting_platform}})
              - CDN for assets
              - Progressive loading
              - Browser compatibility
          - id: mobile-packaging
            title: Mobile Packaging
            type: bullet-list
            template: |
              - Cordova/Capacitor wrapper
              - Platform-specific optimization
              - App store requirements
              - Performance testing

  - id: implementation-roadmap
    title: Implementation Roadmap
    instruction: Break down the architecture implementation into phases that align with the GDD development phases
    sections:
      - id: phase-1-foundation
        title: "Phase 1: Foundation ({{duration}})"
        sections:
          - id: phase-1-core
            title: Core Systems
            type: bullet-list
            template: |
              - Project setup and configuration
              - Basic scene management
              - Asset loading pipeline
              - Input handling framework
          - id: phase-1-epics
            title: Story Epics
            type: bullet-list
            template: |
              - "Engine Setup and Configuration"
              - "Basic Scene Management System"
              - "Asset Loading Foundation"
      - id: phase-2-game-systems
        title: "Phase 2: Game Systems ({{duration}})"
        sections:
          - id: phase-2-gameplay
            title: Gameplay Systems
            type: bullet-list
            template: |
              - {{primary_mechanic}} implementation
              - Physics and collision system
              - Game state management
              - UI framework
          - id: phase-2-epics
            title: Story Epics
            type: bullet-list
            template: |
              - "{{primary_mechanic}} System Implementation"
              - "Physics and Collision Framework"
              - "Game State Management System"
      - id: phase-3-content-polish
        title: "Phase 3: Content & Polish ({{duration}})"
        sections:
          - id: phase-3-content
            title: Content Systems
            type: bullet-list
            template: |
              - Level loading and management
              - Audio system integration
              - Performance optimization
              - Final polish and testing
          - id: phase-3-epics
            title: Story Epics
            type: bullet-list
            template: |
              - "Level Management System"
              - "Audio Integration and Optimization"
              - "Performance Optimization and Testing"

  - id: risk-assessment
    title: Risk Assessment
    instruction: Identify potential technical risks and mitigation strategies
    type: table
    template: |
      | Risk                         | Probability | Impact     | Mitigation Strategy |
      | ---------------------------- | ----------- | ---------- | ------------------- |
      | Performance issues on mobile | {{prob}}    | {{impact}} | {{mitigation}}      |
      | Asset loading bottlenecks    | {{prob}}    | {{impact}} | {{mitigation}}      |
      | Cross-platform compatibility | {{prob}}    | {{impact}} | {{mitigation}}      |

  - id: success-criteria
    title: Success Criteria
    instruction: Define measurable technical success criteria
    sections:
      - id: technical-metrics
        title: Technical Metrics
        type: bullet-list
        template: |
          - All systems implemented per specification
          - Performance targets met consistently
          - Zero critical bugs in core systems
          - Successful deployment across target platforms
      - id: code-quality
        title: Code Quality
        type: bullet-list
        template: |
          - 90%+ test coverage on game logic
          - Zero TypeScript errors in strict mode
          - Consistent adherence to coding standards
          - Comprehensive documentation coverage
