# Component Specifications ## Core Components ### 1. ChessBoard **Responsibility**: Manages the 8x8 chess board representation and coordinates. **Properties**: - `squares`: Array[64] of Square objects - `activePiece`: Reference to currently selected piece - `legalMoves`: Array of legal destination squares **Methods**: - `getSquare(file, rank)`: Get square at position - `setPiece(square, piece)`: Place piece on square - `removePiece(square)`: Remove piece from square - `getPiece(square)`: Get piece at square - `highlightSquares(squares)`: Visual highlight - `clearHighlights()`: Remove highlights - `isSquareOccupied(square)`: Check occupancy - `getSquareColor(square)`: Get square color (light/dark) **Events Emitted**: - `square-clicked`: User clicks a square - `piece-selected`: Piece is selected - `piece-deselected`: Piece is deselected **Dependencies**: - Square - ChessPiece (for rendering) --- ### 2. ChessPiece **Responsibility**: Represents individual chess pieces with movement rules. **Properties**: - `type`: PieceType (pawn, knight, bishop, rook, queen, king) - `color`: Color (white, black) - `position`: Current square - `hasMoved`: Boolean (for castling, en passant) - `moveCount`: Number of moves made **Methods**: - `getPossibleMoves(board)`: Get all pseudo-legal moves - `getLegalMoves(board, gameState)`: Get truly legal moves - `canMoveTo(square, board)`: Check if move is valid - `clone()`: Deep copy of piece - `getNotation()`: Get piece notation (K, Q, R, B, N, P) - `getImagePath()`: Get piece image asset path **Piece-Specific Logic**: - **Pawn**: Forward movement, diagonal capture, en passant, promotion - **Knight**: L-shaped movement, jump over pieces - **Bishop**: Diagonal movement - **Rook**: Straight movement, castling - **Queen**: Combination of bishop and rook - **King**: One square in any direction, castling **Events Emitted**: - `piece-moved`: Piece completes movement - `piece-captured`: Piece is captured - `piece-promoted`: Pawn promotion **Dependencies**: - Board (for move validation) - MoveValidator --- ### 3. GameEngine **Responsibility**: Enforces chess rules and manages game state. **Properties**: - `gameState`: Current game state object - `currentPlayer`: Current player's turn - `moveHistory`: Array of all moves - `capturedPieces`: Object with arrays per color - `gameStatus`: Status (active, check, checkmate, stalemate, draw) **Methods**: - `initializeGame()`: Set up new game - `executeMove(from, to)`: Perform a move - `undoMove()`: Undo last move - `redoMove()`: Redo undone move - `isCheck(color)`: Check if king is in check - `isCheckmate(color)`: Check for checkmate - `isStalemate()`: Check for stalemate - `isDraw()`: Check for draw conditions - `switchTurn()`: Change active player - `getGameState()`: Get current state snapshot - `loadGameState(state)`: Restore game state **Game State Object**: ```javascript { board: BoardState, currentPlayer: 'white' | 'black', moveNumber: number, halfMoveClock: number, enPassantSquare: Square | null, castlingRights: { whiteKingSide: boolean, whiteQueenSide: boolean, blackKingSide: boolean, blackQueenSide: boolean }, lastMove: Move | null, status: GameStatus } ``` **Events Emitted**: - `game-started`: New game begins - `move-executed`: Move completed - `turn-changed`: Player turn switches - `check-detected`: King in check - `game-over`: Game ends (checkmate/stalemate/draw) **Dependencies**: - ChessBoard - MoveValidator - GameHistory --- ### 4. MoveValidator **Responsibility**: Validates move legality according to chess rules. **Properties**: - `validationCache`: Map for caching validation results **Methods**: - `isMoveLegal(from, to, gameState)`: Full legality check - `isPseudoLegal(from, to, board)`: Basic movement check - `wouldExposeKing(move, gameState)`: Check detection - `validateCastling(move, gameState)`: Castling validation - `validateEnPassant(move, gameState)`: En passant validation - `validatePromotion(move)`: Pawn promotion validation - `getCheckingPieces(color, gameState)`: Find pieces giving check - `isSquareAttacked(square, byColor, gameState)`: Attack detection - `clearCache()`: Clear validation cache **Validation Rules**: 1. Piece movement follows type-specific rules 2. Move doesn't leave own king in check 3. Special moves (castling, en passant) meet conditions 4. Target square is valid (on board, not occupied by own piece) **Events Emitted**: - `validation-failed`: Move rejected with reason **Dependencies**: - ChessPiece - ChessBoard - GameState --- ### 5. GameController **Responsibility**: Orchestrates game flow and user interaction. **Properties**: - `gameEngine`: Reference to GameEngine - `boardView`: Reference to visual board - `selectedSquare`: Currently selected square - `gameMode`: Mode (pvp, pva, ava) - `playerColors`: Map of player to color **Methods**: - `handleSquareClick(square)`: Process square selection - `handlePieceDrag(piece, square)`: Process drag-and-drop - `startNewGame(config)`: Initialize new game - `resignGame()`: End game with resignation - `offerDraw()`: Propose draw - `requestUndo()`: Request move undo - `saveGame()`: Persist current game - `loadGame(saveData)`: Restore saved game - `configureGame(options)`: Update settings **User Interaction Flow**: 1. User clicks piece → Highlight legal moves 2. User clicks destination → Validate and execute move 3. Update UI → Switch turn → Check game status **Events Emitted**: - `user-action`: User performs action - `game-saved`: Game state persisted - `game-loaded`: Game state restored **Dependencies**: - GameEngine - ChessBoardView - UIController - AIPlayer (optional) --- ### 6. MoveGenerator **Responsibility**: Generates all possible moves for position analysis. **Properties**: - `generationCache`: Map for move generation results **Methods**: - `generateAllMoves(gameState, color)`: All legal moves for color - `generatePieceMoves(piece, gameState)`: Moves for specific piece - `generateCaptures(gameState, color)`: Only capturing moves - `generateQuietMoves(gameState, color)`: Non-capturing moves - `perft(depth, gameState)`: Performance test (move counting) - `clearCache()`: Clear generation cache **Optimization**: - Lazy evaluation for move generation - Bitboard operations for efficiency - Move ordering for search algorithms **Events Emitted**: - None (pure computation) **Dependencies**: - MoveValidator - ChessBoard - GameState --- ### 7. GameHistory **Responsibility**: Tracks move history and enables undo/redo. **Properties**: - `moves`: Array of Move objects - `positions`: Array of board positions (for repetition detection) - `currentIndex`: Current position in history **Methods**: - `addMove(move)`: Record a move - `getMove(index)`: Retrieve specific move - `getAllMoves()`: Get complete history - `undo()`: Move back one position - `redo()`: Move forward one position - `canUndo()`: Check if undo available - `canRedo()`: Check if redo available - `clear()`: Reset history - `exportPGN()`: Export as PGN notation - `exportJSON()`: Export as JSON - `isThreefoldRepetition()`: Detect draw by repetition **Move Object**: ```javascript { from: Square, to: Square, piece: PieceType, captured: PieceType | null, promotion: PieceType | null, isCheck: boolean, isCheckmate: boolean, isCastling: boolean, isEnPassant: boolean, notation: string, timestamp: number } ``` **Events Emitted**: - `history-updated`: Move added to history - `history-cleared`: History reset **Dependencies**: - Move notation system --- ### 8. UIController **Responsibility**: Manages user interface and visual feedback. **Properties**: - `selectedPiece`: Currently selected piece element - `draggedPiece`: Piece being dragged - `theme`: Current visual theme **Methods**: - `renderBoard()`: Draw complete board - `renderPiece(piece, square)`: Draw piece on square - `animateMove(from, to)`: Animate piece movement - `showLegalMoves(moves)`: Highlight valid destinations - `hideLegalMoves()`: Remove highlights - `updateGameStatus(status)`: Display game state - `showPromotion(square)`: Display promotion dialog - `playSound(event)`: Play sound effect - `updateCapturedPieces(pieces)`: Display captured pieces - `enableDragAndDrop()`: Enable drag-and-drop - `disableDragAndDrop()`: Disable interactions **Visual Feedback**: - Highlight selected piece - Highlight legal move squares - Animate piece movement - Show check/checkmate indicators - Display current player turn - Show captured pieces **Events Emitted**: - `ui-click`: User clicks element - `ui-drag-start`: Drag begins - `ui-drag-end`: Drag ends - `promotion-selected`: User selects promotion piece **Dependencies**: - ChessBoardView - ThemeManager --- ### 9. AIPlayer (Optional) **Responsibility**: Provides computer opponent with configurable difficulty. **Properties**: - `difficulty`: Difficulty level (1-10) - `thinkingTime`: Max time per move (ms) - `searchDepth`: Minimax search depth - `evaluator`: Position evaluation function **Methods**: - `calculateMove(gameState)`: Determine best move - `evaluatePosition(gameState)`: Score position - `minimax(depth, alpha, beta, gameState)`: Search algorithm - `orderMoves(moves)`: Move ordering for pruning - `getOpeningMove(gameState)`: Opening book lookup - `setDifficulty(level)`: Adjust AI strength **AI Levels**: 1. **Random**: Random legal moves 2. **Beginner**: Material-only evaluation, depth 2 3. **Intermediate**: Positional evaluation, depth 3-4 4. **Advanced**: Full evaluation, depth 5-6 5. **Expert**: Advanced pruning, depth 7+ **Evaluation Factors**: - Material count (piece values) - Piece positioning (piece-square tables) - King safety - Pawn structure - Mobility - Center control **Events Emitted**: - `ai-thinking`: AI calculation started - `ai-move-ready`: AI move calculated **Dependencies**: - MoveGenerator - MoveEvaluator - GameState --- ### 10. ThemeManager **Responsibility**: Manages visual themes and customization. **Properties**: - `currentTheme`: Active theme object - `availableThemes`: Map of registered themes **Methods**: - `setTheme(themeName)`: Apply theme - `getTheme()`: Get current theme - `registerTheme(theme)`: Add custom theme - `loadTheme(themeData)`: Load theme from data - `exportTheme()`: Export current theme **Theme Object**: ```javascript { name: string, lightSquares: color, darkSquares: color, highlightColor: color, legalMoveColor: color, selectedPieceColor: color, checkColor: color, pieceSet: string, boardBorder: style } ``` **Events Emitted**: - `theme-changed`: Theme switched **Dependencies**: - CSS custom properties --- ## Component Interaction Map ``` User Input → UIController → GameController → GameEngine ↓ ↓ MoveValidator ← ChessBoard ↓ ↓ GameHistory ← ChessPiece AIPlayer → MoveGenerator → MoveValidator → GameEngine ``` ## Initialization Sequence 1. Create ChessBoard instance 2. Initialize GameEngine with board 3. Create MoveValidator with engine 4. Initialize GameController with engine 5. Set up UIController with board view 6. Create GameHistory tracker 7. Initialize AIPlayer (if enabled) 8. Start new game