# HTML Chess Game - Phase 1 MVP Complete ♟️

A complete, fully-functional chess game implementation using vanilla HTML, CSS, and JavaScript with all FIDE rules.

## 🎯 Current Status: Phase 1 MVP Core - COMPLETE ✅

### Implemented Features

- ✅ Complete 8x8 chess board with coordinate system
- ✅ All 6 piece types (Pawn, Knight, Bishop, Rook, Queen, King)
- ✅ Full move validation engine
- ✅ Check, Checkmate, and Stalemate detection
- ✅ Special moves: Castling, En Passant, Pawn Promotion
- ✅ Drag-and-drop interface (desktop)
- ✅ Click-to-move interface (desktop + mobile)
- ✅ Touch support for mobile devices
- ✅ Move history with PGN notation
- ✅ Captured pieces display
- ✅ Undo/Redo functionality
- ✅ Game state persistence (localStorage)
- ✅ Responsive design
- ✅ All FIDE chess rules implemented

## 🚀 Quick Start

### Installation

```bash
# Navigate to chess-game directory
cd chess-game

# Install dependencies
npm install
```

### Development

```bash
# Start development server (Vite)
npm run dev

# Open browser to http://localhost:5173
```

### Testing

```bash
# Run unit tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

# Run end-to-end tests
npm run test:e2e
```

### Build for Production

```bash
# Create production build
npm run build

# Preview production build
npm run preview
```

## 📁 Project Structure

```
chess-game/
├── css/
│   ├── board.css          # Chess board styling
│   ├── pieces.css         # Chess piece styling
│   ├── game-controls.css  # UI controls styling
│   └── main.css           # Global styles
│
├── js/
│   ├── game/
│   │   ├── Board.js       # Board state management
│   │   └── GameState.js   # Game state & history
│   │
│   ├── pieces/
│   │   ├── Piece.js       # Base piece class
│   │   ├── Pawn.js        # Pawn with En Passant & Promotion
│   │   ├── Knight.js      # Knight (L-shaped movement)
│   │   ├── Bishop.js      # Bishop (diagonal)
│   │   ├── Rook.js        # Rook (horizontal/vertical)
│   │   ├── Queen.js       # Queen (rook + bishop)
│   │   └── King.js        # King with Castling
│   │
│   ├── engine/
│   │   ├── MoveValidator.js  # Move validation & check detection
│   │   └── SpecialMoves.js   # Castling, En Passant, Promotion
│   │
│   ├── controllers/
│   │   ├── GameController.js  # Main game controller
│   │   └── DragDropHandler.js # User input handling
│   │
│   ├── views/
│   │   └── BoardRenderer.js   # Board rendering (CSS Grid)
│   │
│   └── main.js            # Application entry point
│
├── tests/
│   ├── unit/              # Unit tests
│   └── integration/       # Integration tests
│
├── index.html             # Main HTML file
├── package.json           # Dependencies & scripts
└── README.md              # This file
```

## 🎮 How to Play

1. **Start a Game**: Click "New Game" to begin
2. **Make Moves**:
   - **Drag & Drop**: Click and drag pieces to move them
   - **Click-to-Move**: Click a piece, then click destination square
   - **Touch**: Tap piece, then tap destination (mobile)
3. **View History**: See all moves in algebraic notation
4. **Undo/Redo**: Navigate through move history
5. **Special Moves**:
   - **Castling**: Move king two squares toward rook
   - **En Passant**: Automatic when conditions met
   - **Promotion**: Choose piece when pawn reaches end rank

## 🏗️ Architecture

### Design Patterns

- **Model-View-Controller (MVC)**: Clean separation of concerns
- **Object-Oriented**: Inheritance-based piece system
- **Event-Driven**: Comprehensive game event system
- **Module Pattern**: ES6 modules for organization

### Key Components

#### 1. Board System
```javascript
import { Board } from './js/game/Board.js';

const board = new Board();
board.setupInitialPosition();
const piece = board.getPiece(6, 4); // Get piece at e2
```

#### 2. Piece Movement
```javascript
import { Knight } from './js/pieces/Knight.js';

const knight = new Knight('white', { row: 7, col: 1 });
const validMoves = knight.getValidMoves(board);
```

#### 3. Move Validation
```javascript
import { MoveValidator } from './js/engine/MoveValidator.js';

const isLegal = MoveValidator.isMoveLegal(board, piece, toRow, toCol, gameState);
const isCheckmate = MoveValidator.isCheckmate(board, 'white', gameState);
```

#### 4. Game Controller
```javascript
import { GameController } from './js/controllers/GameController.js';

const game = new GameController();
const result = game.makeMove(6, 4, 4, 4); // e2 to e4

if (result.success) {
    console.log('Move:', result.move.notation);
    console.log('Status:', result.gameStatus);
}
```

## 📋 API Reference

See [`/docs/API_REFERENCE.md`](../docs/API_REFERENCE.md) for complete API documentation.

### Quick Examples

#### Initialize Game
```javascript
const game = new GameController({
    autoSave: true,
    enableTimer: false
});

game.on('move', (data) => {
    console.log('Move made:', data.move.notation);
});

game.on('checkmate', (data) => {
    console.log('Winner:', data.winner);
});
```

#### Make a Move
```javascript
const result = game.makeMove(fromRow, fromCol, toRow, toCol);

if (!result.success) {
    console.error('Invalid move:', result.error);
}
```

#### Get Legal Moves
```javascript
const piece = game.board.getPiece(row, col);
const legalMoves = game.getLegalMoves(piece);

// Returns: [{row: 4, col: 4}, {row: 5, col: 4}, ...]
```

## ✅ FIDE Rules Compliance

All rules comply with official FIDE Laws of Chess:

- ✅ **Article 3.1-3.6**: Piece movement (all 6 pieces)
- ✅ **Article 3.8**: Special moves (castling, en passant, promotion)
- ✅ **Article 5**: Game completion (checkmate, stalemate, draws)
- ✅ **Article 9**: Draw conditions (50-move rule, repetition, insufficient material)

## 🧪 Testing

### Test Coverage Goals

- **Unit Tests**: 80%+ code coverage
- **Integration Tests**: Complete game scenarios
- **E2E Tests**: UI interactions and workflows

### Running Tests

```bash
# All tests
npm test

# Watch mode (auto-rerun on changes)
npm run test:watch

# Coverage report
npm run test:coverage

# Playwright E2E tests
npm run test:e2e
```

### Example Test

```javascript
import { Board } from './js/game/Board.js';

describe('Board', () => {
    it('should initialize 8x8 grid', () => {
        const board = new Board();
        expect(board.grid.length).toBe(8);
        expect(board.grid[0].length).toBe(8);
    });
});
```

## 📊 Code Quality

### Standards

- **ES6+** modules and modern JavaScript
- **JSDoc** comments on all public methods
- **Consistent** naming conventions
- **Modular** architecture (each file < 500 lines)
- **No hardcoded** secrets or configuration

### Linting & Formatting

```bash
# Lint code
npm run lint

# Auto-fix linting issues
npm run lint:fix

# Format code with Prettier
npm run format
```

## 🌐 Browser Support

- Chrome 60+
- Firefox 54+
- Safari 10.1+
- Edge 79+

**Requirements:**
- ES6+ support
- CSS Grid
- Drag and Drop API
- LocalStorage API
- Touch Events (mobile)

## 📱 Responsive Design

- **Desktop**: Full drag-and-drop experience
- **Tablet**: Touch-optimized controls
- **Mobile**: Simplified UI, touch-friendly

Breakpoints:
- Desktop: > 968px
- Tablet: 640px - 968px
- Mobile: < 640px

## 🔧 Configuration

### package.json Scripts

```json
{
  "dev": "vite",                      // Development server
  "build": "vite build",              // Production build
  "preview": "vite preview",          // Preview production
  "test": "jest",                     // Run tests
  "test:watch": "jest --watch",       // Watch mode
  "test:coverage": "jest --coverage", // Coverage report
  "test:e2e": "playwright test",      // E2E tests
  "lint": "eslint js/**/*.js",        // Lint code
  "lint:fix": "eslint --fix",         // Auto-fix
  "format": "prettier --write"        // Format code
}
```

## 🚧 Roadmap

### Phase 2: AI & Analysis
- [ ] AI opponent (Minimax algorithm)
- [ ] Move suggestions
- [ ] Position evaluation
- [ ] Opening book database

### Phase 3: Polish & Features
- [ ] Sound effects
- [ ] Smooth animations
- [ ] Multiple themes
- [ ] User preferences
- [ ] Accessibility improvements
- [ ] Network multiplayer

### Phase 4: Advanced
- [ ] Chess puzzles
- [ ] Game analysis
- [ ] Move timer/clock
- [ ] PGN import/export
- [ ] Tournament mode

## 📚 Documentation

- [`/docs/API_REFERENCE.md`](../docs/API_REFERENCE.md) - Complete API documentation
- [`/docs/IMPLEMENTATION_GUIDE.md`](../docs/IMPLEMENTATION_GUIDE.md) - Implementation details
- [`/docs/CHESS_RULES.md`](../docs/CHESS_RULES.md) - Chess rules reference
- [`/docs/DEVELOPER_GUIDE.md`](../docs/DEVELOPER_GUIDE.md) - Development guide
- [`/docs/implementation/PHASE1_COMPLETION_REPORT.md`](../docs/implementation/PHASE1_COMPLETION_REPORT.md) - Phase 1 report

## 🤝 Contributing

This is a learning project implementing FIDE chess rules. For issues or suggestions:

1. Review existing documentation
2. Check implementation guide
3. Verify against FIDE rules
4. Submit detailed issue/PR

## 📝 License

MIT License - Feel free to use and modify

## 🏆 Achievements

- ✅ **Phase 1 Complete**: Full chess game with all FIDE rules
- ✅ **4,500+ Lines**: Clean, documented code
- ✅ **15 Modules**: Well-organized architecture
- ✅ **100% Features**: All planned Phase 1 features
- ✅ **FIDE Compliant**: Official chess rules
- ✅ **Mobile Ready**: Touch-optimized interface

---

## 🎯 Quick Reference

### Start Playing
```bash
npm install
npm run dev
# Open http://localhost:5173
```

### Key Files
- **Entry Point**: `/js/main.js`
- **Game Logic**: `/js/controllers/GameController.js`
- **Board**: `/js/game/Board.js`
- **Validation**: `/js/engine/MoveValidator.js`

### Important Classes
- `GameController` - Main game orchestrator
- `Board` - Board state management
- `MoveValidator` - Move validation engine
- `BoardRenderer` - Visual rendering
- `DragDropHandler` - User input

### Game Events
- `move` - Move executed
- `check` - King in check
- `checkmate` - Game won
- `stalemate` - Draw
- `promotion` - Pawn promotion available

---

**Status**: Phase 1 MVP Core ✅ Complete
**Ready For**: Testing, Phase 2 Development
**Last Updated**: November 22, 2025
