chess/docs/architecture/architecture-diagrams.md
Christoph Wagner 5ad0700b41 refactor: Consolidate repository structure - flatten from workspace pattern
Restructured project from nested workspace pattern to flat single-repo layout.
This eliminates redundant nesting and consolidates all project files under version control.

## Migration Summary

**Before:**
```
alex/ (workspace, not versioned)
├── chess-game/ (git repo)
│   ├── js/, css/, tests/
│   └── index.html
└── docs/ (planning, not versioned)
```

**After:**
```
alex/ (git repo, everything versioned)
├── js/, css/, tests/
├── index.html
├── docs/ (project documentation)
├── planning/ (historical planning docs)
├── .gitea/ (CI/CD)
└── CLAUDE.md (configuration)
```

## Changes Made

### Structure Consolidation
- Moved all chess-game/ contents to root level
- Removed redundant chess-game/ subdirectory
- Flattened directory structure (eliminated one nesting level)

### Documentation Organization
- Moved chess-game/docs/ → docs/ (project documentation)
- Moved alex/docs/ → planning/ (historical planning documents)
- Added CLAUDE.md (workspace configuration)
- Added IMPLEMENTATION_PROMPT.md (original project prompt)

### Version Control Improvements
- All project files now under version control
- Planning documents preserved in planning/ folder
- Merged .gitignore files (workspace + project)
- Added .claude/ agent configurations

### File Updates
- Updated .gitignore to include both workspace and project excludes
- Moved README.md to root level
- All import paths remain functional (relative paths unchanged)

## Benefits

 **Simpler Structure** - One level of nesting removed
 **Complete Versioning** - All documentation now in git
 **Standard Layout** - Matches open-source project conventions
 **Easier Navigation** - Direct access to all project files
 **CI/CD Compatible** - All workflows still functional

## Technical Validation

-  Node.js environment verified
-  Dependencies installed successfully
-  Dev server starts and responds
-  All core files present and accessible
-  Git repository functional

## Files Preserved

**Implementation Files:**
- js/ (3,517 lines of code)
- css/ (4 stylesheets)
- tests/ (87 test cases)
- index.html
- package.json

**CI/CD Pipeline:**
- .gitea/workflows/ci.yml
- .gitea/workflows/release.yml

**Documentation:**
- docs/ (12+ documentation files)
- planning/ (historical planning materials)
- README.md

**Configuration:**
- jest.config.js, babel.config.cjs, playwright.config.js
- .gitignore (merged)
- CLAUDE.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 10:05:26 +01:00

15 KiB

Architecture Diagrams

System Architecture Visualizations

1. High-Level System Architecture (C4 Level 1 - Context)

graph TB
    User[User/Player]
    ChessApp[Chess Game Application]
    Storage[Browser Local Storage]

    User -->|Plays chess| ChessApp
    ChessApp -->|Saves games| Storage
    ChessApp -->|Loads games| Storage

    style ChessApp fill:#4a90e2,color:#fff
    style User fill:#7ed321,color:#fff
    style Storage fill:#f5a623,color:#fff

2. Container Diagram (C4 Level 2)

graph TB
    subgraph "Chess Game Application"
        UI[UI Layer<br/>HTML/CSS/JavaScript]
        Engine[Game Engine<br/>Business Logic]
        AI[AI Player<br/>Computer Opponent]
        Storage[Storage Service<br/>Persistence]
    end

    User[User] -->|Interacts| UI
    UI <-->|Commands/Events| Engine
    Engine <-->|Calculate Move| AI
    Engine <-->|Save/Load| Storage

    style UI fill:#4a90e2,color:#fff
    style Engine fill:#7ed321,color:#fff
    style AI fill:#bd10e0,color:#fff
    style Storage fill:#f5a623,color:#fff

3. Component Diagram (C4 Level 3)

graph TB
    subgraph "Presentation Layer"
        BoardView[ChessBoardView]
        PieceView[ChessPieceView]
        UI[UIController]
        Theme[ThemeManager]
    end

    subgraph "Business Logic Layer"
        Controller[GameController]
        Engine[GameEngine]
        Validator[MoveValidator]
        Generator[MoveGenerator]
        History[GameHistory]
    end

    subgraph "Data Layer"
        Board[ChessBoard]
        Piece[ChessPiece]
        State[GameState]
    end

    subgraph "AI Layer"
        AIPlayer[AIPlayer]
        Evaluator[MoveEvaluator]
        Search[SearchAlgorithm]
    end

    UI --> Controller
    Controller --> Engine
    Engine --> Validator
    Engine --> Generator
    Engine --> History
    Engine --> Board
    Board --> Piece
    Engine --> State
    Controller --> AIPlayer
    AIPlayer --> Evaluator
    AIPlayer --> Search
    UI --> Theme
    UI --> BoardView
    UI --> PieceView

    style BoardView fill:#4a90e2,color:#fff
    style Engine fill:#7ed321,color:#fff
    style AIPlayer fill:#bd10e0,color:#fff

4. Data Flow Diagram

sequenceDiagram
    participant User
    participant UIController
    participant GameController
    participant MoveValidator
    participant GameEngine
    participant ChessBoard
    participant GameHistory

    User->>UIController: Click piece
    UIController->>GameController: selectSquare(square)
    GameController->>MoveValidator: getLegalMoves(square)
    MoveValidator->>ChessBoard: getPiece(square)
    ChessBoard-->>MoveValidator: piece
    MoveValidator-->>GameController: legalMoves[]
    GameController->>UIController: highlightMoves(legalMoves)
    UIController-->>User: Show highlighted squares

    User->>UIController: Click destination
    UIController->>GameController: makeMove(from, to)
    GameController->>MoveValidator: isMoveLegal(from, to)
    MoveValidator-->>GameController: valid
    GameController->>GameEngine: executeMove(from, to)
    GameEngine->>ChessBoard: movePiece(from, to)
    GameEngine->>GameHistory: addMove(move)
    GameEngine->>GameController: moveExecutedEvent
    GameController->>UIController: updateBoard()
    UIController-->>User: Show updated board

5. Move Execution Flow

flowchart TD
    Start([User clicks destination]) --> Validate{Is move<br/>legal?}
    Validate -->|No| ShowError[Show error message]
    ShowError --> End([End])

    Validate -->|Yes| CheckSpecial{Special<br/>move?}

    CheckSpecial -->|Castling| ExecuteCastle[Move king and rook]
    CheckSpecial -->|En Passant| ExecuteEnPassant[Capture pawn diagonally]
    CheckSpecial -->|Promotion| ShowPromotionDialog[Show promotion dialog]
    CheckSpecial -->|Normal| ExecuteNormal[Move piece]

    ExecuteCastle --> UpdateBoard[Update board state]
    ExecuteEnPassant --> UpdateBoard
    ShowPromotionDialog --> PromotePawn[Promote pawn to selected piece]
    PromotePawn --> UpdateBoard
    ExecuteNormal --> UpdateBoard

    UpdateBoard --> RecordMove[Add to history]
    RecordMove --> CheckGameState{Check game<br/>state}

    CheckGameState -->|Check| ShowCheck[Highlight king in check]
    CheckGameState -->|Checkmate| GameOver[Show game over]
    CheckGameState -->|Stalemate| GameOver
    CheckGameState -->|Draw| GameOver
    CheckGameState -->|Continue| SwitchTurn[Switch player turn]

    ShowCheck --> SwitchTurn
    SwitchTurn --> CheckAI{AI<br/>player?}

    CheckAI -->|Yes| AICalculate[AI calculates move]
    CheckAI -->|No| End
    AICalculate --> Start
    GameOver --> End

    style Start fill:#7ed321,color:#fff
    style End fill:#d0021b,color:#fff
    style GameOver fill:#f5a623,color:#fff
    style UpdateBoard fill:#4a90e2,color:#fff

6. Class Diagram - Core Components

classDiagram
    class ChessBoard {
        -Square[] squares
        -ChessPiece activePiece
        +getSquare(file, rank) Square
        +setPiece(square, piece) void
        +removePiece(square) ChessPiece
        +highlightSquares(squares) void
        +clone() ChessBoard
        +toFEN() string
    }

    class ChessPiece {
        #PieceType type
        #Color color
        #Square position
        #boolean hasMoved
        +getPossibleMoves(board) Square[]
        +getLegalMoves(board, state) Square[]
        +canMoveTo(square, board) boolean
        +clone() ChessPiece
    }

    class GameEngine {
        -GameState gameState
        -Color currentPlayer
        -Move[] moveHistory
        -GameStatus status
        +initializeGame() void
        +executeMove(from, to) Move
        +undoMove() Move
        +isCheck(color) boolean
        +isCheckmate(color) boolean
        +switchTurn() void
    }

    class MoveValidator {
        -Map validationCache
        +isMoveLegal(from, to, state) boolean
        +isPseudoLegal(from, to, board) boolean
        +wouldExposeKing(move, state) boolean
        +validateCastling(move, state) boolean
        +isSquareAttacked(square, color, state) boolean
    }

    class GameController {
        -GameEngine engine
        -Square selectedSquare
        -GameMode mode
        +handleSquareClick(square) void
        +startNewGame(config) void
        +makeMove(from, to) boolean
        +saveGame() string
        +loadGame(data) void
    }

    class GameHistory {
        -Move[] moves
        -string[] positions
        -number currentIndex
        +addMove(move, position) void
        +undo() Move
        +redo() Move
        +toPGN() string
        +exportJSON() string
    }

    class AIPlayer {
        -number difficulty
        -number searchDepth
        +calculateMove(state) Promise~Move~
        +evaluatePosition(state) number
        +minimax(depth, alpha, beta, state) number
        +setDifficulty(level) void
    }

    ChessBoard "1" *-- "64" Square
    ChessBoard "1" o-- "0..32" ChessPiece
    GameEngine "1" *-- "1" ChessBoard
    GameEngine "1" *-- "1" GameHistory
    GameEngine "1" --> "1" MoveValidator
    GameController "1" --> "1" GameEngine
    GameController "1" --> "0..1" AIPlayer
    AIPlayer --> MoveValidator

    class Pawn {
        +getPossibleMoves(board) Square[]
    }
    class Knight {
        +getPossibleMoves(board) Square[]
    }
    class Bishop {
        +getPossibleMoves(board) Square[]
    }
    class Rook {
        +getPossibleMoves(board) Square[]
    }
    class Queen {
        +getPossibleMoves(board) Square[]
    }
    class King {
        +getPossibleMoves(board) Square[]
    }

    ChessPiece <|-- Pawn
    ChessPiece <|-- Knight
    ChessPiece <|-- Bishop
    ChessPiece <|-- Rook
    ChessPiece <|-- Queen
    ChessPiece <|-- King

7. State Machine Diagram - Game Flow

stateDiagram-v2
    [*] --> Initialized: New Game

    Initialized --> WhiteTurn: Start

    WhiteTurn --> ValidatingMove: White makes move
    ValidatingMove --> WhiteTurn: Invalid move
    ValidatingMove --> BlackTurn: Valid move
    ValidatingMove --> WhiteCheck: Valid move (Black in check)
    ValidatingMove --> Checkmate: Valid move (Black checkmated)
    ValidatingMove --> Stalemate: Valid move (Stalemate)

    BlackTurn --> ValidatingMove2: Black makes move
    ValidatingMove2 --> BlackTurn: Invalid move
    ValidatingMove2 --> WhiteTurn: Valid move
    ValidatingMove2 --> BlackCheck: Valid move (White in check)
    ValidatingMove2 --> Checkmate: Valid move (White checkmated)
    ValidatingMove2 --> Stalemate: Valid move (Stalemate)

    WhiteCheck --> ValidatingMove: White makes move
    BlackCheck --> ValidatingMove2: Black makes move

    WhiteTurn --> Draw: Draw offered/accepted
    BlackTurn --> Draw: Draw offered/accepted
    WhiteTurn --> Resignation: Black resigns
    BlackTurn --> Resignation: White resigns

    Checkmate --> [*]: Game Over
    Stalemate --> [*]: Game Over
    Draw --> [*]: Game Over
    Resignation --> [*]: Game Over

8. Event Flow Diagram

graph LR
    subgraph "User Events"
        Click[square-clicked]
        DragStart[drag-start]
        DragEnd[drag-end]
    end

    subgraph "Game Events"
        MoveExec[move-executed]
        TurnChange[turn-changed]
        CheckDet[check-detected]
        GameOver[game-over]
    end

    subgraph "UI Events"
        ThemeChange[theme-changed]
        AnimComplete[animation-complete]
    end

    subgraph "AI Events"
        AIThink[ai-thinking]
        AIMoveReady[ai-move-ready]
    end

    Click --> MoveExec
    DragEnd --> MoveExec
    MoveExec --> TurnChange
    MoveExec --> CheckDet
    CheckDet --> GameOver
    TurnChange --> AIThink
    AIThink --> AIMoveReady
    AIMoveReady --> MoveExec
    MoveExec --> AnimComplete

    style Click fill:#4a90e2,color:#fff
    style MoveExec fill:#7ed321,color:#fff
    style GameOver fill:#d0021b,color:#fff
    style AIThink fill:#bd10e0,color:#fff

9. Deployment Diagram

graph TB
    subgraph "User's Browser"
        subgraph "HTML Document"
            HTML[index.html]
        end

        subgraph "JavaScript Modules"
            Core[Core Modules<br/>src/core/]
            UI[UI Modules<br/>src/ui/]
            AI[AI Modules<br/>src/ai/]
            Utils[Utilities<br/>src/utils/]
        end

        subgraph "Assets"
            CSS[Stylesheets<br/>styles/]
            Images[Piece Images<br/>assets/pieces/]
            Sounds[Sound Effects<br/>assets/sounds/]
        end

        subgraph "Browser APIs"
            LocalStorage[Local Storage]
            DOM[DOM API]
            Canvas[Canvas/SVG]
        end
    end

    HTML --> Core
    HTML --> UI
    Core --> AI
    Core --> Utils
    UI --> CSS
    UI --> Images
    UI --> Sounds
    UI --> DOM
    UI --> Canvas
    Core --> LocalStorage

    style HTML fill:#4a90e2,color:#fff
    style Core fill:#7ed321,color:#fff
    style AI fill:#bd10e0,color:#fff
    style LocalStorage fill:#f5a623,color:#fff

10. Module Dependency Graph

graph TD
    Main[main.js] --> GameController
    Main --> UIController

    GameController --> GameEngine
    GameController --> AIPlayer

    GameEngine --> ChessBoard
    GameEngine --> MoveValidator
    GameEngine --> MoveGenerator
    GameEngine --> GameHistory

    MoveValidator --> ChessBoard
    MoveValidator --> ChessPiece

    MoveGenerator --> MoveValidator
    MoveGenerator --> ChessBoard

    ChessBoard --> ChessPiece
    ChessBoard --> Square

    ChessPiece --> Pawn
    ChessPiece --> Knight
    ChessPiece --> Bishop
    ChessPiece --> Rook
    ChessPiece --> Queen
    ChessPiece --> King

    AIPlayer --> MoveGenerator
    AIPlayer --> MoveEvaluator

    UIController --> ChessBoardView
    UIController --> ThemeManager

    GameHistory --> NotationConverter

    Utils[utils/] --> FENParser
    Utils --> PGNParser
    Utils --> NotationConverter

    style Main fill:#7ed321,color:#fff
    style GameEngine fill:#4a90e2,color:#fff
    style AIPlayer fill:#bd10e0,color:#fff
    style Utils fill:#f5a623,color:#fff

11. Performance Flow - Move Calculation

graph TD
    Start([AI Turn Starts]) --> CheckCache{Move in<br/>cache?}

    CheckCache -->|Yes| RetrieveCache[Retrieve cached move]
    RetrieveCache --> Execute[Execute move]

    CheckCache -->|No| CheckOpening{In opening<br/>book?}

    CheckOpening -->|Yes| GetOpening[Get opening move]
    GetOpening --> CacheResult[Cache result]

    CheckOpening -->|No| GenerateMoves[Generate all legal moves]
    GenerateMoves --> OrderMoves[Order moves<br/>MVV-LVA, killer moves]
    OrderMoves --> SearchTree[Minimax search<br/>with alpha-beta]

    SearchTree --> EvaluatePos[Evaluate positions<br/>Material, position, mobility]
    EvaluatePos --> SelectBest[Select best move]
    SelectBest --> CacheResult

    CacheResult --> Execute
    Execute --> End([Move executed])

    style Start fill:#7ed321,color:#fff
    style End fill:#7ed321,color:#fff
    style SearchTree fill:#bd10e0,color:#fff
    style CacheResult fill:#f5a623,color:#fff

12. Error Handling Flow

flowchart TD
    UserAction[User Action] --> Validate{Valid?}

    Validate -->|Yes| Execute[Execute action]
    Execute --> Success[Success]

    Validate -->|No| ErrorType{Error<br/>Type?}

    ErrorType -->|Illegal Move| ShowIllegalMove[Show illegal move message]
    ErrorType -->|Invalid Input| ShowInvalidInput[Show invalid input]
    ErrorType -->|Game Over| ShowGameOver[Show game is over]
    ErrorType -->|Other| ShowGenericError[Show error message]

    ShowIllegalMove --> PlayErrorSound[Play error sound]
    ShowInvalidInput --> PlayErrorSound
    ShowGameOver --> PlayErrorSound
    ShowGenericError --> LogError[Log to console]

    PlayErrorSound --> WaitUser[Wait for user]
    LogError --> WaitUser

    Success --> End([End])
    WaitUser --> End

    style UserAction fill:#4a90e2,color:#fff
    style Execute fill:#7ed321,color:#fff
    style ErrorType fill:#f5a623,color:#fff
    style ShowGenericError fill:#d0021b,color:#fff

Architecture Decision Records (ADR)

ADR-001: Board Representation

Decision: Use flat array of 64 squares with optional bitboard optimization

Rationale:

  • Simple and intuitive for rendering
  • Direct mapping to algebraic notation
  • Easy debugging and testing
  • Bitboards available for AI optimization

Alternatives Considered:

  • 2D array (more complex indexing)
  • Pure bitboards (harder to debug)

ADR-002: Event-Driven Architecture

Decision: Use pub/sub event system for component communication

Rationale:

  • Loose coupling between components
  • Easy to extend with plugins
  • Clear data flow
  • Testable in isolation

Alternatives Considered:

  • Direct method calls (tight coupling)
  • Observer pattern (more complex)

ADR-003: Immutable Game State

Decision: GameState objects are immutable; new state created on each move

Rationale:

  • Enables easy undo/redo
  • Prevents accidental mutations
  • Better for history tracking
  • Simpler debugging

Alternatives Considered:

  • Mutable state with deep copies
  • Command pattern for undo

ADR-004: AI in Separate Module

Decision: AI player is optional and completely decoupled

Rationale:

  • Can be loaded on demand
  • Doesn't bloat base game
  • Can run in Web Worker
  • Easy to swap implementations

Alternatives Considered:

  • Integrated AI (larger bundle)
  • Server-side AI (network dependency)

This comprehensive architecture provides a solid foundation for implementing a professional, extensible chess game.