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>
This commit is contained in:
Christoph Wagner
2025-11-23 10:05:26 +01:00
co-authored by Claude
parent 1fd28d10b4
commit 5ad0700b41
326 changed files with 107368 additions and 281 deletions
+626
View File
@@ -0,0 +1,626 @@
# API Interfaces and Component Contracts
## Public API Interfaces
### 1. IChessBoard Interface
```javascript
interface IChessBoard {
// Properties
readonly squares: Square[];
readonly activePiece: ChessPiece | null;
// Square operations
getSquare(file: number, rank: number): Square;
getSquareByNotation(notation: string): Square;
setPiece(square: Square, piece: ChessPiece): void;
removePiece(square: Square): ChessPiece | null;
getPiece(square: Square): ChessPiece | null;
// Board queries
isSquareOccupied(square: Square): boolean;
isSquareEmpty(square: Square): boolean;
getSquareColor(square: Square): 'light' | 'dark';
findKing(color: 'white' | 'black'): Square | null;
getAllPieces(color?: 'white' | 'black'): ChessPiece[];
// Visual operations
highlightSquares(squares: Square[]): void;
clearHighlights(): void;
// State management
clone(): IChessBoard;
reset(): void;
toFEN(): string;
fromFEN(fen: string): void;
}
```
---
### 2. IChessPiece Interface
```javascript
interface IChessPiece {
// Properties
readonly type: PieceType;
readonly color: 'white' | 'black';
position: Square | null;
hasMoved: boolean;
// Move generation
getPossibleMoves(board: IChessBoard): Square[];
getLegalMoves(board: IChessBoard, gameState: IGameState): Square[];
canMoveTo(square: Square, board: IChessBoard): boolean;
getAttackingSquares(board: IChessBoard): Square[];
// Piece information
getValue(): number;
getNotation(): string;
getImagePath(theme?: string): string;
// Utilities
clone(): IChessPiece;
equals(other: IChessPiece): boolean;
}
```
---
### 3. IGameEngine Interface
```javascript
interface IGameEngine {
// Properties
readonly gameState: IGameState;
readonly currentPlayer: 'white' | 'black';
readonly moveHistory: IMove[];
readonly status: GameStatus;
// Game lifecycle
initializeGame(config?: GameConfig): void;
reset(): void;
// Move execution
executeMove(from: Square, to: Square, promotion?: PieceType): IMove | null;
undoMove(): IMove | null;
redoMove(): IMove | null;
// Game state queries
isCheck(color: 'white' | 'black'): boolean;
isCheckmate(color: 'white' | 'black'): boolean;
isStalemate(): boolean;
isDraw(): boolean;
isGameOver(): boolean;
getWinner(): 'white' | 'black' | 'draw' | null;
// Turn management
switchTurn(): void;
getCurrentPlayer(): 'white' | 'black';
// State management
getGameState(): IGameState;
loadGameState(state: IGameState): void;
saveGame(): string;
loadGame(saveData: string): void;
// Events
on(event: string, handler: Function): void;
off(event: string, handler: Function): void;
emit(event: string, data?: any): void;
}
```
---
### 4. IMoveValidator Interface
```javascript
interface IMoveValidator {
// Primary validation
isMoveLegal(from: Square, to: Square, gameState: IGameState): boolean;
validateMove(move: IMove, gameState: IGameState): ValidationResult;
// Specific validations
isPseudoLegal(from: Square, to: Square, board: IChessBoard): boolean;
wouldExposeKing(move: IMove, gameState: IGameState): boolean;
validateCastling(king: Square, rook: Square, gameState: IGameState): boolean;
validateEnPassant(from: Square, to: Square, gameState: IGameState): boolean;
validatePromotion(move: IMove): boolean;
// Threat detection
isSquareAttacked(square: Square, byColor: 'white' | 'black', gameState: IGameState): boolean;
getAttackingPieces(square: Square, byColor: 'white' | 'black', gameState: IGameState): IChessPiece[];
isKingInCheck(color: 'white' | 'black', gameState: IGameState): boolean;
// Cache management
clearCache(): void;
}
interface ValidationResult {
valid: boolean;
reason?: string;
code?: string;
}
```
---
### 5. IGameController Interface
```javascript
interface IGameController {
// Initialization
initialize(config: GameConfig): void;
startNewGame(config?: GameConfig): void;
// User interaction
handleSquareClick(square: Square): void;
handlePieceDrag(piece: IChessPiece, fromSquare: Square): void;
handlePieceDrop(toSquare: Square): void;
selectSquare(square: Square): void;
deselectSquare(): void;
// Game actions
makeMove(from: Square, to: Square, promotion?: PieceType): boolean;
offerDraw(): void;
acceptDraw(): void;
resign(color: 'white' | 'black'): void;
requestUndo(): void;
// Game management
pauseGame(): void;
resumeGame(): void;
saveGame(): string;
loadGame(saveData: string): void;
exportPGN(): string;
// Configuration
setGameMode(mode: 'pvp' | 'pva' | 'ava'): void;
setAIDifficulty(level: number): void;
updateSettings(settings: Partial<GameConfig>): void;
// Queries
getGameState(): IGameState;
getCurrentPlayer(): 'white' | 'black';
getGameStatus(): GameStatus;
getLegalMovesFor(square: Square): Square[];
}
```
---
### 6. IMoveGenerator Interface
```javascript
interface IMoveGenerator {
// Move generation
generateAllMoves(gameState: IGameState, color: 'white' | 'black'): IMove[];
generatePieceMoves(piece: IChessPiece, gameState: IGameState): IMove[];
generateCaptures(gameState: IGameState, color: 'white' | 'black'): IMove[];
generateQuietMoves(gameState: IGameState, color: 'white' | 'black'): IMove[];
// Special moves
generateCastlingMoves(color: 'white' | 'black', gameState: IGameState): IMove[];
generateEnPassantMoves(color: 'white' | 'black', gameState: IGameState): IMove[];
generatePromotionMoves(pawn: IChessPiece, gameState: IGameState): IMove[];
// Move ordering
orderMoves(moves: IMove[], gameState: IGameState): IMove[];
// Performance testing
perft(depth: number, gameState: IGameState): number;
// Cache
clearCache(): void;
}
```
---
### 7. IGameHistory Interface
```javascript
interface IGameHistory {
// Properties
readonly moves: IMove[];
readonly currentIndex: number;
readonly canUndo: boolean;
readonly canRedo: boolean;
// History operations
addMove(move: IMove, position: string): void;
getMove(index: number): IMove | null;
getAllMoves(): IMove[];
clear(): void;
// Navigation
undo(): IMove | null;
redo(): IMove | null;
goToMove(index: number): IMove | null;
// Queries
getMoveCount(): number;
getLastMove(): IMove | null;
isThreefoldRepetition(): boolean;
getFiftyMoveCount(): number;
// Export
toPGN(metadata?: PGNMetadata): string;
toJSON(): string;
exportMoves(): string[];
// Import
fromPGN(pgn: string): void;
fromJSON(json: string): void;
importMoves(moves: string[]): void;
}
```
---
### 8. IUIController Interface
```javascript
interface IUIController {
// Rendering
renderBoard(board: IChessBoard): void;
renderPiece(piece: IChessPiece, square: Square): void;
renderGameStatus(status: GameStatus): void;
updateCapturedPieces(pieces: { white: PieceType[], black: PieceType[] }): void;
// Animations
animateMove(from: Square, to: Square, duration?: number): Promise<void>;
animateCapture(square: Square): Promise<void>;
animatePromotion(square: Square, newPiece: PieceType): Promise<void>;
// Visual feedback
highlightSquare(square: Square, type: HighlightType): void;
clearHighlights(): void;
showLegalMoves(moves: Square[]): void;
hideLegalMoves(): void;
showCheck(color: 'white' | 'black'): void;
// Dialogs
showPromotionDialog(color: 'white' | 'black'): Promise<PieceType>;
showGameOverDialog(result: GameResult): void;
showSettingsDialog(): void;
// Interactions
enableDragAndDrop(): void;
disableDragAndDrop(): void;
enableClickToMove(): void;
disableClickToMove(): void;
// Sound
playSound(soundType: SoundType): void;
// Theme
setTheme(theme: string): void;
}
enum HighlightType {
SELECTED = 'selected',
LEGAL_MOVE = 'legal-move',
LAST_MOVE = 'last-move',
CHECK = 'check',
ATTACKED = 'attacked'
}
enum SoundType {
MOVE = 'move',
CAPTURE = 'capture',
CASTLE = 'castle',
CHECK = 'check',
CHECKMATE = 'checkmate',
DRAW = 'draw',
ILLEGAL = 'illegal'
}
```
---
### 9. IAIPlayer Interface
```javascript
interface IAIPlayer {
// Configuration
setDifficulty(level: number): void;
setThinkingTime(ms: number): void;
setSearchDepth(depth: number): void;
// Move calculation
calculateMove(gameState: IGameState): Promise<IMove>;
evaluatePosition(gameState: IGameState): number;
// Search
search(gameState: IGameState, depth: number): SearchResult;
minimax(depth: number, alpha: number, beta: number, gameState: IGameState): number;
// Opening book
hasOpeningMove(gameState: IGameState): boolean;
getOpeningMove(gameState: IGameState): IMove | null;
// Status
isThinking(): boolean;
cancelCalculation(): void;
// Events
on(event: 'move-ready' | 'thinking' | 'evaluation-update', handler: Function): void;
off(event: string, handler: Function): void;
}
interface SearchResult {
bestMove: IMove;
score: number;
depth: number;
nodesSearched: number;
timeElapsed: number;
principalVariation: IMove[];
}
```
---
### 10. IThemeManager Interface
```javascript
interface IThemeManager {
// Theme management
setTheme(themeName: string): void;
getTheme(): Theme;
getAvailableThemes(): string[];
// Custom themes
registerTheme(theme: Theme): void;
unregisterTheme(themeName: string): void;
// Import/Export
loadTheme(themeData: string): void;
exportTheme(themeName: string): string;
// Apply styles
applyColors(): void;
applyPieceSet(): void;
}
interface Theme {
name: string;
lightSquares: string;
darkSquares: string;
highlightColor: string;
legalMoveColor: string;
selectedColor: string;
checkColor: string;
pieceSet: string;
borderStyle?: string;
coordinatesColor?: string;
}
```
---
## Event System API
### Event Emitter Base
```javascript
interface IEventEmitter {
on(event: string, handler: Function): void;
off(event: string, handler: Function): void;
once(event: string, handler: Function): void;
emit(event: string, data?: any): void;
removeAllListeners(event?: string): void;
}
```
### Game Events
```javascript
// Event payloads
interface MoveExecutedEvent {
move: IMove;
gameState: IGameState;
isCheck: boolean;
isCheckmate: boolean;
}
interface PieceSelectedEvent {
piece: IChessPiece;
square: Square;
legalMoves: Square[];
}
interface GameOverEvent {
status: GameStatus;
winner: 'white' | 'black' | 'draw' | null;
reason: string;
}
interface TurnChangedEvent {
player: 'white' | 'black';
moveNumber: number;
}
interface CheckDetectedEvent {
color: 'white' | 'black';
attackingPieces: IChessPiece[];
}
```
---
## Factory Interfaces
### Piece Factory
```javascript
interface IPieceFactory {
createPiece(type: PieceType, color: 'white' | 'black', position?: Square): IChessPiece;
createPawn(color: 'white' | 'black', position?: Square): IChessPiece;
createKnight(color: 'white' | 'black', position?: Square): IChessPiece;
createBishop(color: 'white' | 'black', position?: Square): IChessPiece;
createRook(color: 'white' | 'black', position?: Square): IChessPiece;
createQueen(color: 'white' | 'black', position?: Square): IChessPiece;
createKing(color: 'white' | 'black', position?: Square): IChessPiece;
}
```
### Game Factory
```javascript
interface IGameFactory {
createGame(config?: GameConfig): IGameEngine;
createGameFromFEN(fen: string, config?: GameConfig): IGameEngine;
createGameFromPGN(pgn: string, config?: GameConfig): IGameEngine;
}
```
---
## Utility Interfaces
### Notation Converter
```javascript
interface INotationConverter {
moveToSAN(move: IMove, gameState: IGameState): string;
moveToLAN(move: IMove): string;
moveToUCI(move: IMove): string;
sanToMove(san: string, gameState: IGameState): IMove | null;
uciToMove(uci: string, gameState: IGameState): IMove | null;
}
```
### FEN Parser
```javascript
interface IFENParser {
parse(fen: string): IGameState;
generate(gameState: IGameState): string;
validate(fen: string): boolean;
}
```
### PGN Parser
```javascript
interface IPGNParser {
parse(pgn: string): PGNGame;
generate(game: IGameEngine): string;
validate(pgn: string): boolean;
}
interface PGNGame {
metadata: PGNMetadata;
moves: string[];
result: string;
}
interface PGNMetadata {
event?: string;
site?: string;
date?: string;
round?: string;
white?: string;
black?: string;
result?: string;
[key: string]: string | undefined;
}
```
---
## Plugin Interface
```javascript
interface IChessPlugin {
name: string;
version: string;
// Lifecycle hooks
initialize(game: IGameEngine): void;
destroy(): void;
// Optional hooks
onMoveExecuted?(move: IMove, gameState: IGameState): void;
onGameStart?(config: GameConfig): void;
onGameEnd?(result: GameResult): void;
onTurnChange?(player: 'white' | 'black'): void;
// Custom functionality
getAPI?(): any;
}
```
---
## Service Interfaces
### Storage Service
```javascript
interface IStorageService {
saveGame(key: string, game: IGameEngine): void;
loadGame(key: string): IGameEngine | null;
deleteGame(key: string): void;
listSavedGames(): string[];
saveSetting(key: string, value: any): void;
loadSetting(key: string): any;
clearAll(): void;
}
```
### Network Service (Future)
```javascript
interface INetworkService {
connect(gameId: string): Promise<void>;
disconnect(): void;
sendMove(move: IMove): void;
onMoveReceived(handler: (move: IMove) => void): void;
syncGameState(gameState: IGameState): void;
requestSync(): void;
chat(message: string): void;
onChatMessage(handler: (message: ChatMessage) => void): void;
}
```
---
## Usage Example
```javascript
// Initialize game
const gameFactory = new GameFactory();
const game = gameFactory.createGame({
mode: 'pvp',
theme: 'classic',
soundEnabled: true
});
// Set up UI
const uiController = new UIController('#board-container');
uiController.renderBoard(game.getBoard());
// Handle moves
game.on('move-executed', (event: MoveExecutedEvent) => {
uiController.animateMove(event.move.from, event.move.to);
uiController.renderGameStatus(event.gameState.status);
});
// User interaction
uiController.on('square-clicked', (square: Square) => {
const legalMoves = game.getLegalMovesFor(square);
uiController.showLegalMoves(legalMoves);
});
// Execute move
game.executeMove(fromSquare, toSquare);
```
This API design ensures loose coupling, clear contracts, and easy testing while providing flexibility for future extensions.
+613
View File
@@ -0,0 +1,613 @@
# Architecture Diagrams
## System Architecture Visualizations
### 1. High-Level System Architecture (C4 Level 1 - Context)
```mermaid
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)
```mermaid
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)
```mermaid
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
```mermaid
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
```mermaid
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
```mermaid
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
```mermaid
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
```mermaid
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
```mermaid
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
```mermaid
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
```mermaid
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
```mermaid
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.
@@ -0,0 +1,427 @@
# 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
+527
View File
@@ -0,0 +1,527 @@
# Data Models and Structures
## Core Data Structures
### 1. Square
Represents a single square on the chess board.
```javascript
class Square {
file: number; // 0-7 (a-h)
rank: number; // 0-7 (1-8)
color: 'light' | 'dark';
piece: ChessPiece | null;
// Helper methods
toAlgebraic(): string; // "e4"
fromAlgebraic(notation: string): Square;
equals(other: Square): boolean;
clone(): Square;
}
// Examples
{ file: 4, rank: 3, color: 'light', piece: null } // e4
{ file: 0, rank: 0, color: 'dark', piece: WhiteRook } // a1
```
**Algebraic Notation Mapping**:
- Files: a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7
- Ranks: 1=0, 2=1, 3=2, 4=3, 5=4, 6=5, 7=6, 8=7
---
### 2. BoardState
Represents the complete chess board configuration.
```javascript
class BoardState {
// Array representation (primary)
squares: Square[64];
// Alternative: 2D array
// grid: Square[8][8];
// Bitboard representation (optional, for performance)
bitboards: {
white: {
pawns: BigInt,
knights: BigInt,
bishops: BigInt,
rooks: BigInt,
queens: BigInt,
king: BigInt,
all: BigInt
},
black: { /* same structure */ },
occupied: BigInt,
empty: BigInt
};
// Helper methods
getSquare(file: number, rank: number): Square;
getSquareByIndex(index: number): Square;
getPieceAt(square: Square): ChessPiece | null;
setPieceAt(square: Square, piece: ChessPiece): void;
removePieceAt(square: Square): void;
clone(): BoardState;
toFEN(): string;
fromFEN(fen: string): BoardState;
}
```
**Index Calculation**:
```javascript
// Square to index: rank * 8 + file
// Index to square: { file: index % 8, rank: Math.floor(index / 8) }
```
**Starting Position FEN**:
```
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
```
---
### 3. PieceType Enumeration
```javascript
const PieceType = {
PAWN: 'pawn',
KNIGHT: 'knight',
BISHOP: 'bishop',
ROOK: 'rook',
QUEEN: 'queen',
KING: 'king'
};
const PieceValue = {
pawn: 1,
knight: 3,
bishop: 3,
rook: 5,
queen: 9,
king: Infinity
};
const PieceNotation = {
pawn: '', // No letter for pawns
knight: 'N',
bishop: 'B',
rook: 'R',
queen: 'Q',
king: 'K'
};
```
---
### 4. Move
Represents a single chess move with all metadata.
```javascript
class Move {
from: Square;
to: Square;
piece: PieceType;
color: 'white' | 'black';
captured: PieceType | null;
promotion: PieceType | null;
// Special move flags
isCastling: boolean;
isEnPassant: boolean;
isCheck: boolean;
isCheckmate: boolean;
// Metadata
notation: string; // "Nf3", "exd5", "O-O"
algebraicNotation: string; // "e2e4"
timestamp: number;
moveNumber: number;
// Methods
toSAN(): string; // Standard Algebraic Notation
toLAN(): string; // Long Algebraic Notation
toUCI(): string; // Universal Chess Interface
equals(other: Move): boolean;
clone(): Move;
}
```
**Notation Examples**:
- **SAN**: "Nf3", "e4", "O-O", "Qxe5+", "e8=Q#"
- **LAN**: "Ng1-f3", "e2-e4", "Qd1xe5+"
- **UCI**: "e2e4", "e7e5", "e1g1" (castling), "e7e8q" (promotion)
---
### 5. GameState
Complete game state snapshot for state management.
```javascript
class GameState {
board: BoardState;
currentPlayer: 'white' | 'black';
moveNumber: number;
halfMoveClock: number; // For 50-move rule
// Special move tracking
enPassantSquare: Square | null;
castlingRights: {
whiteKingSide: boolean,
whiteQueenSide: boolean,
blackKingSide: boolean,
blackQueenSide: boolean
};
// Game status
status: GameStatus;
lastMove: Move | null;
// Captured pieces
capturedPieces: {
white: PieceType[],
black: PieceType[]
};
// Methods
toFEN(): string;
fromFEN(fen: string): GameState;
clone(): GameState;
hash(): string; // For position repetition
equals(other: GameState): boolean;
}
```
**FEN Format**:
```
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
│ │ │ │ │ │
│ │ │ │ │ └─ Full move number
│ │ │ │ └─── Halfmove clock
│ │ │ └───── En passant square
│ │ └────────── Castling rights
│ └──────────── Active player
└──────────────────────────────────────────────────────── Board position
```
---
### 6. GameStatus Enumeration
```javascript
const GameStatus = {
ACTIVE: 'active',
CHECK: 'check',
CHECKMATE: 'checkmate',
STALEMATE: 'stalemate',
DRAW_50_MOVE: 'draw-50-move',
DRAW_REPETITION: 'draw-repetition',
DRAW_INSUFFICIENT: 'draw-insufficient-material',
DRAW_AGREEMENT: 'draw-agreement',
RESIGNATION: 'resignation'
};
```
---
### 7. GameConfiguration
Settings and options for game initialization.
```javascript
class GameConfig {
mode: 'pvp' | 'pva' | 'ava';
timeControl: TimeControl | null;
playerWhite: Player;
playerBlack: Player;
aiDifficulty: number; // 1-10 for AI opponent
theme: string;
soundEnabled: boolean;
animationSpeed: number; // ms for animations
autoSave: boolean;
legalMovesHighlight: boolean;
dragAndDrop: boolean;
}
class TimeControl {
type: 'none' | 'classical' | 'rapid' | 'blitz' | 'bullet';
initialTime: number; // seconds
increment: number; // seconds per move
whiteTime: number;
blackTime: number;
}
class Player {
name: string;
type: 'human' | 'ai';
color: 'white' | 'black';
elo: number | null;
}
```
---
### 8. MoveHistory
Structure for tracking complete game history.
```javascript
class MoveHistory {
moves: Move[];
positions: string[]; // FEN strings for repetition detection
currentIndex: number;
startingPosition: string; // Initial FEN
// PGN metadata
metadata: {
event: string,
site: string,
date: string,
round: string,
white: string,
black: string,
result: string
};
// Methods
addMove(move: Move, position: string): void;
getMove(index: number): Move;
getAllMoves(): Move[];
undo(): Move | null;
redo(): Move | null;
canUndo(): boolean;
canRedo(): boolean;
clear(): void;
toPGN(): string;
fromPGN(pgn: string): MoveHistory;
toJSON(): string;
fromJSON(json: string): MoveHistory;
}
```
**PGN Format Example**:
```
[Event "Casual Game"]
[Site "Chess App"]
[Date "2025.11.22"]
[Round "1"]
[White "Player 1"]
[Black "Player 2"]
[Result "1-0"]
1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 1-0
```
---
### 9. Event System
Event definitions for component communication.
```javascript
class GameEvent {
type: EventType;
payload: any;
timestamp: number;
source: string;
}
const EventType = {
// Board events
SQUARE_CLICKED: 'square-clicked',
PIECE_SELECTED: 'piece-selected',
PIECE_MOVED: 'piece-moved',
PIECE_CAPTURED: 'piece-captured',
PIECE_PROMOTED: 'piece-promoted',
// Game events
GAME_STARTED: 'game-started',
GAME_OVER: 'game-over',
TURN_CHANGED: 'turn-changed',
CHECK_DETECTED: 'check-detected',
MOVE_EXECUTED: 'move-executed',
MOVE_UNDONE: 'move-undone',
MOVE_REDONE: 'move-redone',
// UI events
THEME_CHANGED: 'theme-changed',
SETTINGS_UPDATED: 'settings-updated',
// AI events
AI_THINKING: 'ai-thinking',
AI_MOVE_READY: 'ai-move-ready',
// Error events
INVALID_MOVE: 'invalid-move',
VALIDATION_FAILED: 'validation-failed'
};
```
---
### 10. Bitboard Representation (Advanced)
For performance-critical operations and AI.
```javascript
class Bitboard {
value: BigInt; // 64-bit integer representing board
// Bitwise operations
setBit(square: Square): void;
clearBit(square: Square): void;
toggleBit(square: Square): void;
testBit(square: Square): boolean;
popCount(): number; // Count set bits
// Board operations
and(other: Bitboard): Bitboard;
or(other: Bitboard): Bitboard;
xor(other: Bitboard): Bitboard;
not(): Bitboard;
shift(direction: number): Bitboard;
// Move generation helpers
northOne(): Bitboard;
southOne(): Bitboard;
eastOne(): Bitboard;
westOne(): Bitboard;
getSetSquares(): Square[];
}
```
**Bitboard Example**:
```
Bit 0 = a1, Bit 1 = b1, ..., Bit 7 = h1
Bit 8 = a2, Bit 9 = b2, ..., Bit 63 = h8
White pawns starting position:
0x000000000000FF00 (bits 8-15 set)
Black pawns starting position:
0x00FF000000000000 (bits 48-55 set)
```
---
## Data Flow Diagrams
### Move Execution Flow
```
User Input
UI captures click/drag
GameController validates selection
MoveValidator checks legality
GameEngine executes move
BoardState updated
GameHistory records move
UI renders new state
Turn switches
```
### State Update Flow
```
Move → GameState (immutable) → New GameState
↓ ↓
└─────── History records both ──────┘
```
---
## Serialization Formats
### JSON Save Format
```json
{
"version": "1.0.0",
"timestamp": 1700000000000,
"gameState": {
"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"moveHistory": [
{"from": "e2", "to": "e4", "notation": "e4"},
{"from": "e7", "to": "e5", "notation": "e5"}
],
"capturedPieces": {"white": [], "black": []},
"timeControl": {
"whiteTime": 600,
"blackTime": 595
}
},
"config": {
"mode": "pvp",
"theme": "classic"
}
}
```
### Local Storage Keys
```javascript
const StorageKeys = {
CURRENT_GAME: 'chess-current-game',
SAVED_GAMES: 'chess-saved-games',
SETTINGS: 'chess-settings',
THEME: 'chess-theme',
GAME_HISTORY: 'chess-game-history'
};
```
---
## Performance Considerations
### Memory Optimization
- **Board Representation**: Array[64] uses ~2KB per position
- **Move History**: Average game ~80 moves = ~40KB
- **Bitboards**: Enable compact representation (8 bytes per piece type)
### Caching Strategy
```javascript
class CacheManager {
moveValidationCache: Map<string, boolean>;
moveGenerationCache: Map<string, Move[]>;
evaluationCache: Map<string, number>;
maxSize: number = 10000;
set(key: string, value: any): void;
get(key: string): any | null;
clear(): void;
prune(): void; // Remove old entries
}
```
### Position Hashing
```javascript
// Zobrist hashing for position identification
class ZobristHash {
pieceKeys: BigInt[64][12]; // Square × PieceType
castlingKeys: BigInt[4];
enPassantKeys: BigInt[8];
sideToMoveKey: BigInt;
hash(gameState: GameState): BigInt;
updateHash(hash: BigInt, move: Move): BigInt;
}
```
This data model design ensures efficient state management, easy serialization, and optimal performance for both UI rendering and AI computation.
@@ -0,0 +1,329 @@
# Implementation Architecture - Chess Game
## Overview
This document captures the final architectural decisions and implementation structure for the HTML chess game, integrating all architectural documentation into a coherent implementation plan.
## Architecture Pattern: MVC + Event System
### Model-View-Controller Pattern
The application follows a strict MVC pattern with additional event-driven communication:
- **Model**: Pure data structures and business logic (Board, GameState, Pieces)
- **View**: Presentation and rendering logic (BoardView, UIManager)
- **Controller**: Orchestration and user interaction (GameController, MoveController)
- **Event Bus**: Decoupled component communication
## System Layers
### 1. Data Layer (Models)
**Location**: `/chess-game/js/models/`
**Components**:
- `Board.js`: 8x8 grid representation using array[64] for performance
- `Piece.js`: Abstract base class for all chess pieces
- `pieces/`: Individual piece implementations with movement logic
- `Pawn.js`: Forward movement, en passant, promotion
- `Rook.js`: Straight-line movement, castling support
- `Knight.js`: L-shaped jumps
- `Bishop.js`: Diagonal movement
- `Queen.js`: Combined rook + bishop movement
- `King.js`: One-square movement, castling
- `GameState.js`: Immutable state management with FEN support
**Data Flow**: Models are pure and stateless, all state changes create new objects.
### 2. Business Logic Layer (Engine)
**Location**: `/chess-game/js/engine/`
**Components**:
- `MoveValidator.js`: Legal move validation, check detection
- `RuleEngine.js`: Special moves (castling, en passant, promotion)
- `CheckDetector.js`: Check, checkmate, stalemate detection
- `MoveGenerator.js`: Generate all legal moves for position analysis
- `AIEngine.js`: Minimax with alpha-beta pruning for computer opponent
**Performance Optimizations**:
- Move validation caching
- Bitboard operations for attack detection
- Lazy evaluation of legal moves
- Alpha-beta pruning for AI search
### 3. Presentation Layer (Views)
**Location**: `/chess-game/js/views/`
**Components**:
- `BoardView.js`: Renders board with coordinates, highlights legal moves
- `PieceView.js`: Piece rendering with drag-and-drop support
- `UIManager.js`: Game controls, move history, status display
**Rendering Strategy**:
- Virtual DOM diffing for efficient updates
- CSS-based animations for smooth movement
- Event delegation for square interactions
### 4. Control Layer (Controllers)
**Location**: `/chess-game/js/controllers/`
**Components**:
- `GameController.js`: Game lifecycle, turn management, game modes
- `MoveController.js`: Move execution orchestration
- `AIController.js`: Computer opponent decision-making
**Responsibilities**:
- Validate user input
- Coordinate between models and views
- Manage game state transitions
- Handle AI move calculation
### 5. Utility Layer
**Location**: `/chess-game/js/utils/`
**Components**:
- `Constants.js`: Game constants (piece types, colors, board size)
- `Helpers.js`: Utility functions (coordinate conversion, FEN parsing)
- `EventBus.js`: Pub/sub event system for component communication
## File Structure Implementation
```
chess-game/
├── index.html # Entry point, board layout
├── css/
│ ├── main.css # Global layout, responsive grid
│ ├── board.css # Board styling, square colors
│ ├── pieces.css # Piece rendering, animations
│ └── game-controls.css # UI controls, buttons, dialogs
├── js/
│ ├── main.js # Application initialization
│ ├── models/ # Data structures (immutable)
│ │ ├── Board.js
│ │ ├── Piece.js
│ │ ├── GameState.js
│ │ └── pieces/ # Individual piece logic
│ ├── controllers/ # Business logic orchestration
│ │ ├── GameController.js
│ │ ├── MoveController.js
│ │ └── AIController.js
│ ├── views/ # UI rendering
│ │ ├── BoardView.js
│ │ ├── PieceView.js
│ │ └── UIManager.js
│ ├── engine/ # Chess rules and AI
│ │ ├── MoveValidator.js
│ │ ├── RuleEngine.js
│ │ ├── CheckDetector.js
│ │ ├── MoveGenerator.js
│ │ └── AIEngine.js
│ └── utils/ # Shared utilities
│ ├── Constants.js
│ ├── Helpers.js
│ └── EventBus.js
├── assets/
│ ├── pieces/ # SVG piece images (Unicode fallback)
│ └── sounds/ # Sound effects (optional)
└── tests/
├── unit/ # Model and engine tests
├── integration/ # Game flow tests
└── e2e/ # Full game scenarios
```
## Component Communication
### Event-Driven Architecture
Components communicate through the EventBus to maintain loose coupling:
```
User Action → View → Event Bus → Controller → Model → Event Bus → View
```
**Key Events**:
- `square-clicked`: User selects square
- `piece-moved`: Move executed successfully
- `piece-captured`: Piece captured
- `game-state-changed`: Turn switched, check detected
- `game-over`: Checkmate, stalemate, or draw
### Data Flow for Move Execution
```
1. User clicks square → BoardView emits 'square-clicked'
2. GameController validates selection
3. MoveController checks legality via MoveValidator
4. GameState updates (immutable)
5. BoardView re-renders with new state
6. UIManager updates move history and status
```
## State Management
### Immutable State Pattern
All state changes create new objects rather than mutating existing ones:
```javascript
// ❌ Mutable (bad)
gameState.currentPlayer = 'black';
// ✅ Immutable (good)
const newState = gameState.withPlayer('black');
```
### State Structure
```javascript
{
board: BoardState, // 64-element array
currentPlayer: 'white'|'black',
moveNumber: number,
halfMoveClock: number, // 50-move rule
enPassantSquare: Square|null,
castlingRights: {
whiteKingSide: boolean,
whiteQueenSide: boolean,
blackKingSide: boolean,
blackQueenSide: boolean
},
status: GameStatus, // active, check, checkmate, etc.
lastMove: Move|null
}
```
## Performance Considerations
### Optimization Strategies
1. **Move Validation Caching**: Cache computed legal moves
2. **Bitboard Representation**: Use BigInt for attack detection
3. **Lazy Evaluation**: Only compute legal moves when needed
4. **Document Fragment**: Batch DOM updates
5. **Event Delegation**: Single listener per board
6. **Web Workers**: Offload AI computation (future enhancement)
### Performance Targets
- Board render: < 16ms (60 FPS)
- Move validation: < 5ms
- AI move (depth 4): < 2000ms
- UI response: < 100ms
## Testing Strategy
### Unit Tests
- Piece movement validation
- Check detection algorithms
- FEN parsing and generation
- Move notation conversion
### Integration Tests
- Full game scenarios
- Special move execution (castling, en passant, promotion)
- Game state transitions
- Undo/redo functionality
### End-to-End Tests
- User interaction flows
- AI vs Human gameplay
- Game save/load
- Performance benchmarks
## Deployment Architecture
### Single-Page Application
- No build process required
- ES6 modules with native browser support
- Progressive enhancement for older browsers
- Service Worker for offline play (future)
### Browser Compatibility
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
### File Size Budget
- HTML: ~5KB
- CSS: ~15KB
- JavaScript: ~50KB (unminified)
- Total: ~70KB (excluding assets)
## Scalability and Extensibility
### Extension Points
1. **AI Difficulty**: Pluggable evaluation functions
2. **Themes**: CSS custom properties for easy theming
3. **Variants**: Rule engine supports chess variants
4. **Network Play**: WebSocket integration point
5. **Time Controls**: Timer system architecture
### Future Enhancements (Phase 2)
- TypeScript migration for type safety
- WebAssembly for AI performance
- Multiplayer via WebRTC/WebSocket
- Opening book and endgame tablebases
- Analysis mode with move suggestions
- PGN import/export
- Game database integration
## Security Considerations
### Client-Side Security
- Input validation on all user actions
- XSS prevention in move notation display
- LocalStorage encryption for saved games
- No eval() or dangerous string operations
### Future Network Security
- WebSocket authentication
- Move verification on server
- Rate limiting for API calls
- Anti-cheat measures
## Accessibility
### WCAG 2.1 Level AA Compliance
- Keyboard navigation for all actions
- ARIA labels for screen readers
- Focus management for modals
- High contrast mode support
- Scalable UI for vision impairment
## Implementation Phases
### Phase 1: Foundation (Week 1)
- Constants and helpers
- EventBus implementation
- Board and piece models
### Phase 2: Core Logic (Week 2)
- Move validation
- Check detection
- Game state management
### Phase 3: UI (Week 3)
- Board rendering
- Drag-and-drop
- UI controls and feedback
### Phase 4: AI (Week 4)
- Move generation
- Minimax algorithm
- Position evaluation
### Phase 5: Polish (Week 5)
- Animations and sound
- Move history and notation
- Save/load functionality
- Testing and bug fixes
## Conclusion
This architecture provides:
- **Modularity**: Clear separation of concerns
- **Testability**: Pure functions and dependency injection
- **Maintainability**: Single-responsibility components
- **Performance**: Optimized for 60 FPS rendering
- **Extensibility**: Plugin points for new features
The implementation follows industry best practices while remaining simple enough for a single-page HTML application.
---
**Generated by**: Architect Agent
**Date**: 2025-11-22
**Status**: Ready for Implementation
+150
View File
@@ -0,0 +1,150 @@
# Chess Game - System Design
## Architecture Overview
The chess game follows a **modular, layered architecture** with clear separation of concerns. The system is designed for extensibility, testability, and maintainability.
### Architectural Style
- **Pattern**: MVC (Model-View-Controller) with Event-Driven Architecture
- **Modularity**: ES6 Modules for component isolation
- **State Management**: Centralized game state with immutable updates
- **Communication**: Event-based pub/sub for component decoupling
## System Layers
### 1. Presentation Layer
- **ChessBoardView**: Visual board rendering
- **ChessPieceView**: Piece rendering and animations
- **UIController**: User input handling and feedback
- **ThemeManager**: Visual styling and customization
### 2. Business Logic Layer
- **GameEngine**: Core game rules and state management
- **MoveValidator**: Legal move validation and check detection
- **MoveGenerator**: All possible moves calculation
- **GameController**: Game flow orchestration
- **TurnManager**: Player turn handling
### 3. Data Layer
- **BoardState**: Current board configuration
- **GameHistory**: Move history and undo/redo
- **GameConfig**: Configuration and settings
- **PersistenceManager**: Save/load game state
### 4. AI Layer (Optional)
- **AIPlayer**: Computer opponent interface
- **MoveEvaluator**: Position evaluation
- **SearchAlgorithm**: Minimax with alpha-beta pruning
## Core Principles
### Single Responsibility
Each component has one clear purpose and reason to change.
### Open/Closed Principle
Components are open for extension but closed for modification through interfaces and hooks.
### Dependency Inversion
High-level modules depend on abstractions, not concrete implementations.
### Event-Driven Communication
Components communicate through events to minimize coupling.
## System Constraints
### Performance
- Board updates: < 16ms (60 FPS)
- Move validation: < 5ms
- AI move calculation: < 2000ms (configurable)
### Browser Compatibility
- Modern browsers (ES6+ support)
- Chrome 90+, Firefox 88+, Safari 14+, Edge 90+
### Accessibility
- Keyboard navigation support
- Screen reader compatibility
- ARIA labels for all interactive elements
## Security Considerations
### Client-Side Only (Phase 1)
- No network communication
- Local storage only for persistence
- Input validation for all user actions
### Future Network Play (Phase 2)
- WebSocket communication
- Move verification on server
- Anti-cheat measures
- Rate limiting
## Scalability Strategy
### Modular Extension Points
- Plugin system for new features
- Theme customization hooks
- AI difficulty levels
- Alternative rule sets (variants)
### Performance Optimization
- Virtual DOM for efficient rendering
- Move generation caching
- Position evaluation memoization
- Web Workers for AI computation
## Deployment Architecture
### File Structure
```
chess-game/
├── index.html # Main entry point
├── styles/
│ ├── main.css # Core styles
│ ├── themes/ # Visual themes
│ └── responsive.css # Mobile support
├── src/
│ ├── core/ # Business logic
│ ├── ui/ # Presentation
│ ├── ai/ # AI components
│ └── utils/ # Shared utilities
├── assets/
│ ├── pieces/ # Piece images
│ └── sounds/ # Sound effects
└── tests/ # Test suite
```
## Technology Stack
### Core Technologies
- **HTML5**: Semantic structure
- **CSS3**: Styling and animations
- **Vanilla JavaScript**: ES6+ for logic
### Optional Enhancements
- **TypeScript**: Type safety (future)
- **Web Workers**: Background AI computation
- **Service Workers**: Offline play
- **IndexedDB**: Persistent storage
## Quality Attributes
### Maintainability
- Clear code organization
- Comprehensive documentation
- Automated testing (unit + integration)
### Testability
- Pure functions for core logic
- Dependency injection
- Mock-friendly interfaces
### Usability
- Intuitive drag-and-drop
- Visual feedback for all actions
- Responsive design for all devices
### Extensibility
- Plugin architecture
- Configuration-driven behavior
- Event hooks for customization