chess/docs/diagrams/ARCHITECTURE.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

14 KiB

Architecture Diagrams - HTML Chess Game

System Architecture

High-Level Component Overview

graph TB
    UI[User Interface Layer]
    GAME[Game Logic Layer]
    DATA[Data Layer]

    UI --> GAME
    GAME --> DATA

    subgraph "UI Layer"
        RENDERER[BoardRenderer]
        DRAGDROP[DragDropHandler]
        UICTRL[UIController]
    end

    subgraph "Game Layer"
        CHESS[ChessGame]
        VALIDATOR[MoveValidator]
        SPECIAL[SpecialMoves]
    end

    subgraph "Data Layer"
        BOARD[Board]
        STATE[GameState]
        PIECES[Pieces]
    end

    RENDERER --> CHESS
    DRAGDROP --> CHESS
    UICTRL --> CHESS

    CHESS --> BOARD
    CHESS --> STATE
    CHESS --> VALIDATOR

    VALIDATOR --> PIECES
    SPECIAL --> BOARD

Detailed Component Diagram

classDiagram
    class ChessGame {
        +Board board
        +GameState gameState
        +string currentTurn
        +string status
        +makeMove(from, to)
        +newGame()
        +undo()
        +redo()
        +getLegalMoves(piece)
        +isInCheck(color)
        +resign()
    }

    class Board {
        +Piece[][] grid
        +getPiece(row, col)
        +setPiece(row, col, piece)
        +movePiece(from, to)
        +clone()
        +toFEN()
        +fromFEN(fen)
        +setupInitialPosition()
    }

    class GameState {
        +Move[] moveHistory
        +int currentMove
        +CapturedPieces captured
        +string status
        +Position enPassantTarget
        +int halfMoveClock
        +int fullMoveNumber
        +recordMove(move)
        +undo()
        +redo()
        +toFEN()
        +toPGN()
    }

    class Piece {
        <<abstract>>
        +string color
        +Position position
        +string type
        +bool hasMoved
        +getValidMoves(board)*
        +isValidMove(board, to)*
        +clone()
    }

    class Pawn {
        +getValidMoves(board)
    }

    class Knight {
        +getValidMoves(board)
    }

    class Bishop {
        +getValidMoves(board)
    }

    class Rook {
        +getValidMoves(board)
    }

    class Queen {
        +getValidMoves(board)
    }

    class King {
        +getValidMoves(board)
        +canCastle(board, side)
    }

    class MoveValidator {
        <<static>>
        +isMoveLegal(board, piece, to, state)
        +isKingInCheck(board, color)
        +isCheckmate(board, color)
        +isStalemate(board, color)
        +hasAnyLegalMove(board, color)
    }

    class SpecialMoves {
        <<static>>
        +canCastle(board, king, rook)
        +executeCastle(board, king, rook)
        +canEnPassant(board, pawn, target, state)
        +executeEnPassant(board, pawn, target)
        +canPromote(pawn)
        +promote(board, pawn, pieceType)
    }

    class BoardRenderer {
        +HTMLElement boardElement
        +renderBoard(board, state)
        +highlightMoves(moves)
        +clearHighlights()
        +selectSquare(row, col)
        +updateSquare(row, col, piece)
    }

    class DragDropHandler {
        +ChessGame game
        +BoardRenderer renderer
        +setupEventListeners()
        +onDragStart(event)
        +onDrop(event)
        +enable()
        +disable()
    }

    class UIController {
        +ChessGame game
        +BoardRenderer renderer
        +DragDropHandler dragDrop
        +init()
        +updateGameStatus(status)
        +showPromotionDialog(callback)
        +updateMoveHistory(moves)
    }

    ChessGame --> Board
    ChessGame --> GameState
    ChessGame --> MoveValidator

    Board --> Piece

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

    MoveValidator --> Piece
    SpecialMoves --> Board

    UIController --> ChessGame
    UIController --> BoardRenderer
    UIController --> DragDropHandler

    BoardRenderer --> Board
    DragDropHandler --> ChessGame

Move Validation Flow

flowchart TD
    START([User Makes Move])
    GET_PIECE{Piece at source?}
    CHECK_TURN{Correct turn?}
    VALID_MOVE{Valid for piece?}
    SIMULATE[Simulate Move]
    CHECK_CHECK{Leaves king in check?}
    EXECUTE[Execute Move]
    UPDATE_STATE[Update Game State]
    SWITCH_TURN[Switch Turn]
    CHECK_STATUS[Check Game Status]
    END([Move Complete])
    ERROR([Return Error])

    START --> GET_PIECE
    GET_PIECE -->|No| ERROR
    GET_PIECE -->|Yes| CHECK_TURN
    CHECK_TURN -->|No| ERROR
    CHECK_TURN -->|Yes| VALID_MOVE
    VALID_MOVE -->|No| ERROR
    VALID_MOVE -->|Yes| SIMULATE
    SIMULATE --> CHECK_CHECK
    CHECK_CHECK -->|Yes| ERROR
    CHECK_CHECK -->|No| EXECUTE
    EXECUTE --> UPDATE_STATE
    UPDATE_STATE --> SWITCH_TURN
    SWITCH_TURN --> CHECK_STATUS
    CHECK_STATUS --> END

    style START fill:#90EE90
    style END fill:#90EE90
    style ERROR fill:#FFB6C1
    style EXECUTE fill:#87CEEB

Check Detection Algorithm

flowchart TD
    START([Is King In Check?])
    FIND_KING[Find King Position]
    LOOP_START{For each square}
    GET_PIECE[Get Piece]
    IS_OPPONENT{Opponent piece?}
    GET_MOVES[Get Valid Moves]
    CAN_ATTACK{Can attack king?}
    RETURN_TRUE([Return TRUE])
    RETURN_FALSE([Return FALSE])
    NEXT[Next Square]

    START --> FIND_KING
    FIND_KING --> LOOP_START
    LOOP_START -->|Yes| GET_PIECE
    LOOP_START -->|No| RETURN_FALSE
    GET_PIECE --> IS_OPPONENT
    IS_OPPONENT -->|No| NEXT
    IS_OPPONENT -->|Yes| GET_MOVES
    GET_MOVES --> CAN_ATTACK
    CAN_ATTACK -->|Yes| RETURN_TRUE
    CAN_ATTACK -->|No| NEXT
    NEXT --> LOOP_START

    style RETURN_TRUE fill:#FFB6C1
    style RETURN_FALSE fill:#90EE90

Castling Validation Flow

flowchart TD
    START([Can Castle?])
    MOVED{King or Rook moved?}
    CLEAR{Path clear?}
    IN_CHECK{King in check?}
    THROUGH_CHECK{Passes through check?}
    CAN_CASTLE([Can Castle])
    CANNOT([Cannot Castle])

    START --> MOVED
    MOVED -->|Yes| CANNOT
    MOVED -->|No| CLEAR
    CLEAR -->|No| CANNOT
    CLEAR -->|Yes| IN_CHECK
    IN_CHECK -->|Yes| CANNOT
    IN_CHECK -->|No| THROUGH_CHECK
    THROUGH_CHECK -->|Yes| CANNOT
    THROUGH_CHECK -->|No| CAN_CASTLE

    style CAN_CASTLE fill:#90EE90
    style CANNOT fill:#FFB6C1

UI Event Flow

sequenceDiagram
    participant User
    participant DOM
    participant DragDrop
    participant ChessGame
    participant Board
    participant Renderer

    User->>DOM: Drag piece
    DOM->>DragDrop: dragstart event
    DragDrop->>ChessGame: getLegalMoves(piece)
    ChessGame->>Board: getPiece(row, col)
    Board-->>ChessGame: piece
    ChessGame-->>DragDrop: legal moves
    DragDrop->>Renderer: highlightMoves(moves)
    Renderer->>DOM: Add CSS classes

    User->>DOM: Drop piece
    DOM->>DragDrop: drop event
    DragDrop->>ChessGame: makeMove(from, to)
    ChessGame->>Board: movePiece(from, to)
    Board-->>ChessGame: result
    ChessGame->>Renderer: renderBoard(board)
    Renderer->>DOM: Update squares

    ChessGame->>DragDrop: move result
    DragDrop->>Renderer: clearHighlights()

Data Flow Diagram

flowchart LR
    USER[User Input]
    UI[UI Layer]
    GAME[Game Logic]
    DATA[Data Layer]
    STORAGE[LocalStorage]

    USER -->|Click/Drag| UI
    UI -->|makeMove| GAME
    GAME -->|Update| DATA
    DATA -->|Notify| GAME
    GAME -->|Render| UI
    UI -->|Display| USER

    GAME <-->|Save/Load| STORAGE

    style USER fill:#87CEEB
    style UI fill:#90EE90
    style GAME fill:#FFD700
    style DATA fill:#FFA07A
    style STORAGE fill:#DDA0DD

State Machine Diagram

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

    Active --> Check: King Attacked
    Check --> Active: King Safe
    Check --> Checkmate: No Legal Moves

    Active --> Stalemate: No Legal Moves (Not in Check)
    Active --> Draw: Draw Condition Met
    Active --> Resigned: Player Resigns

    Checkmate --> [*]
    Stalemate --> [*]
    Draw --> [*]
    Resigned --> [*]

    Active --> Active: Valid Move
    Check --> Check: Valid Move

Piece Inheritance Hierarchy

graph TD
    PIECE[Piece Abstract Class]
    PAWN[Pawn]
    KNIGHT[Knight]
    BISHOP[Bishop]
    ROOK[Rook]
    QUEEN[Queen]
    KING[King]

    PIECE --> PAWN
    PIECE --> KNIGHT
    PIECE --> BISHOP
    PIECE --> ROOK
    PIECE --> QUEEN
    PIECE --> KING

    style PIECE fill:#FFD700
    style PAWN fill:#90EE90
    style KNIGHT fill:#90EE90
    style BISHOP fill:#90EE90
    style ROOK fill:#90EE90
    style QUEEN fill:#90EE90
    style KING fill:#87CEEB

Module Dependency Graph

graph TD
    MAIN[main.js]
    GAME[ChessGame]
    BOARD[Board]
    STATE[GameState]
    PIECES[Pieces/*]
    VALIDATOR[MoveValidator]
    SPECIAL[SpecialMoves]
    RENDERER[BoardRenderer]
    DRAGDROP[DragDropHandler]
    UICTRL[UIController]
    NOTATION[notation.js]
    STORAGE[storage.js]
    HELPERS[helpers.js]

    MAIN --> GAME
    MAIN --> UICTRL

    GAME --> BOARD
    GAME --> STATE
    GAME --> VALIDATOR

    BOARD --> PIECES

    VALIDATOR --> PIECES
    VALIDATOR --> SPECIAL

    SPECIAL --> BOARD

    UICTRL --> GAME
    UICTRL --> RENDERER
    UICTRL --> DRAGDROP

    RENDERER --> BOARD
    DRAGDROP --> GAME

    STATE --> NOTATION
    UICTRL --> STORAGE

    GAME --> HELPERS
    BOARD --> HELPERS

    style MAIN fill:#FFD700
    style GAME fill:#87CEEB
    style UICTRL fill:#90EE90

FEN Parsing Flow

flowchart TD
    START([FEN String])
    SPLIT[Split by Space]
    POSITION[Parse Position]
    TURN[Parse Turn]
    CASTLE[Parse Castling Rights]
    ENPASSANT[Parse En Passant]
    CLOCKS[Parse Clocks]

    CLEAR_BOARD[Clear Board]
    PARSE_RANKS[Parse Ranks]
    PLACE_PIECES[Place Pieces]
    SET_STATE[Set Game State]

    END([Board Configured])

    START --> SPLIT
    SPLIT --> POSITION
    SPLIT --> TURN
    SPLIT --> CASTLE
    SPLIT --> ENPASSANT
    SPLIT --> CLOCKS

    POSITION --> CLEAR_BOARD
    CLEAR_BOARD --> PARSE_RANKS
    PARSE_RANKS --> PLACE_PIECES

    PLACE_PIECES --> SET_STATE
    TURN --> SET_STATE
    CASTLE --> SET_STATE
    ENPASSANT --> SET_STATE
    CLOCKS --> SET_STATE

    SET_STATE --> END

    style START fill:#90EE90
    style END fill:#90EE90

Render Cycle

flowchart TD
    TRIGGER[Trigger Render]
    CLEAR[Clear Previous Highlights]
    LOOP[For Each Square]
    CREATE_SQUARE[Create Square Element]
    STYLE_SQUARE[Apply Light/Dark Style]
    GET_PIECE{Has Piece?}
    CREATE_PIECE[Create Piece Element]
    APPEND_PIECE[Append to Square]
    APPEND_SQUARE[Append to Board]
    DONE{All Squares?}
    ATTACH[Attach to DOM]
    END([Render Complete])

    TRIGGER --> CLEAR
    CLEAR --> LOOP
    LOOP --> CREATE_SQUARE
    CREATE_SQUARE --> STYLE_SQUARE
    STYLE_SQUARE --> GET_PIECE
    GET_PIECE -->|Yes| CREATE_PIECE
    CREATE_PIECE --> APPEND_PIECE
    APPEND_PIECE --> APPEND_SQUARE
    GET_PIECE -->|No| APPEND_SQUARE
    APPEND_SQUARE --> DONE
    DONE -->|No| LOOP
    DONE -->|Yes| ATTACH
    ATTACH --> END

    style END fill:#90EE90

Performance Optimization Points

graph LR
    INPUT[User Input]
    CACHE1{Move Cache Valid?}
    CALC1[Calculate Moves]
    STORE1[Store in Cache]
    VALIDATE[Validate Move]

    RENDER[Render Board]
    CACHE2{DOM Unchanged?}
    UPDATE[Update DOM]
    BATCH[Batch Updates]
    FRAGMENT[Document Fragment]
    ATTACH[Single Attach]

    INPUT --> CACHE1
    CACHE1 -->|No| CALC1
    CALC1 --> STORE1
    STORE1 --> VALIDATE
    CACHE1 -->|Yes| VALIDATE

    VALIDATE --> RENDER
    RENDER --> CACHE2
    CACHE2 -->|No| UPDATE
    UPDATE --> BATCH
    BATCH --> FRAGMENT
    FRAGMENT --> ATTACH

    style CACHE1 fill:#FFD700
    style CACHE2 fill:#FFD700
    style FRAGMENT fill:#90EE90

Error Handling Flow

flowchart TD
    ACTION[User Action]
    TRY[Try Execute]
    ERROR{Error?}
    TYPE{Error Type}

    INVALID_MOVE[Invalid Move]
    WRONG_TURN[Wrong Turn]
    NO_PIECE[No Piece]
    IN_CHECK[Leaves Check]

    LOG[Log Error]
    NOTIFY[Notify User]
    HIGHLIGHT[Highlight Issue]
    ROLLBACK[Rollback State]

    SUCCESS[Execute Success]
    UPDATE[Update UI]
    END([Complete])

    ACTION --> TRY
    TRY --> ERROR
    ERROR -->|Yes| TYPE
    ERROR -->|No| SUCCESS

    TYPE -->|Invalid| INVALID_MOVE
    TYPE -->|Turn| WRONG_TURN
    TYPE -->|Missing| NO_PIECE
    TYPE -->|Check| IN_CHECK

    INVALID_MOVE --> LOG
    WRONG_TURN --> LOG
    NO_PIECE --> LOG
    IN_CHECK --> LOG

    LOG --> NOTIFY
    NOTIFY --> HIGHLIGHT
    HIGHLIGHT --> ROLLBACK
    ROLLBACK --> END

    SUCCESS --> UPDATE
    UPDATE --> END

    style ERROR fill:#FFB6C1
    style SUCCESS fill:#90EE90

Testing Strategy Diagram

graph TB
    CODE[Application Code]

    UNIT[Unit Tests]
    INTEGRATION[Integration Tests]
    E2E[Manual Testing]

    PIECES[Piece Movement]
    VALIDATION[Move Validation]
    SPECIAL[Special Moves]

    SCENARIOS[Game Scenarios]
    STATE[State Management]

    BROWSER[Browser Testing]
    PERF[Performance]
    ACCESS[Accessibility]

    CODE --> UNIT
    CODE --> INTEGRATION
    CODE --> E2E

    UNIT --> PIECES
    UNIT --> VALIDATION
    UNIT --> SPECIAL

    INTEGRATION --> SCENARIOS
    INTEGRATION --> STATE

    E2E --> BROWSER
    E2E --> PERF
    E2E --> ACCESS

    style CODE fill:#FFD700
    style UNIT fill:#90EE90
    style INTEGRATION fill:#87CEEB
    style E2E fill:#FFA07A

Deployment Pipeline

flowchart LR
    DEV[Development]
    TEST[Run Tests]
    LINT[Lint Code]
    BUILD[Build]
    OPTIMIZE[Optimize]
    DEPLOY[Deploy]
    VERIFY[Verify]

    DEV --> TEST
    TEST --> LINT
    LINT --> BUILD
    BUILD --> OPTIMIZE
    OPTIMIZE --> DEPLOY
    DEPLOY --> VERIFY

    style DEV fill:#87CEEB
    style TEST fill:#FFD700
    style DEPLOY fill:#90EE90
    style VERIFY fill:#90EE90

These diagrams provide visual representations of:

  1. System Architecture - Overall structure
  2. Component Relationships - Class diagram
  3. Move Validation - Flow logic
  4. Check Detection - Algorithm flow
  5. Castling - Special move validation
  6. UI Events - Sequence diagram
  7. Data Flow - Information movement
  8. State Machine - Game states
  9. Inheritance - Piece hierarchy
  10. Dependencies - Module imports
  11. FEN Parsing - Data import
  12. Rendering - UI update cycle
  13. Performance - Optimization points
  14. Error Handling - Error flow
  15. Testing - Test strategy
  16. Deployment - Release pipeline

Use these diagrams as reference during implementation to understand component relationships and data flow.