# Tetris Game Architecture

## Overview
A professional-level Tetris clone built with HTML5 Canvas, JavaScript, and CSS. The game features smooth animations, modern UI design, and complete Tetris mechanics following official guidelines.

## Core Components

### 1. Game Engine (`game.js`)
**Responsibilities:**
- Game loop management (60 FPS)
- State management (menu, playing, paused, game over)
- Timing and frame interpolation
- Event coordination

**Key Properties:**
- `state`: 'menu' | 'playing' | 'paused' | 'gameover'
- `score`: Current score
- `level`: Current level (1-15+)
- `lines`: Total lines cleared
- `gameTime`: Elapsed game time

### 2. Board Manager (`board.js`)
**Responsibilities:**
- 10x20 grid management (standard Tetris dimensions)
- Cell state tracking (empty, occupied, color)
- Line clearing detection and animation
- Collision detection

**Data Structure:**
```javascript
board = [
  [0,0,0,0,0,0,0,0,0,0], // Row 0 (top)
  [0,0,0,0,0,0,0,0,0,0], // Row 1
  // ... 20 rows total
]
// 0 = empty, 1-7 = color index
```

### 3. Piece System (`pieces.js`)
**Tetromino Definitions:**
| Piece | Shape | Color | Rotation States |
|-------|-------|-------|-----------------|
| I | ████ | Cyan | 2 states (horizontal/vertical) |
| O | ██ ██ | Yellow | 1 state (no rotation) |
| T | ▀█▀ | Purple | 4 states |
| S | ▄██ | Green | 2 states |
| Z | ██▄ | Red | 2 states |
| J | █▀▀ | Blue | 4 states |
| L | ▀▀█ | Orange | 4 states |

**Piece Properties:**
- `type`: Piece identifier
- `matrix`: 4x4 rotation matrix
- `x`, `y`: Board position
- `rotation`: Current rotation state (0-3)

### 4. Input Handler (`input.js`)
**Controls:**
| Action | Primary Key | Alternative |
|--------|-------------|-------------|
| Move Left | ← Arrow | A |
| Move Right | → Arrow | D |
| Soft Drop | ↓ Arrow | S |
| Hard Drop | Space | - |
| Rotate CW | ↑ Arrow | W |
| Rotate CCW | Z | - |
| Hold Piece | C | Shift |
| Pause | P | Escape |

**Input Features:**
- DAS (Delayed Auto Shift) for held keys
- ARR (Auto Repeat Rate) configuration
- Input buffering for responsive controls

### 5. Renderer (`renderer.js`)
**Rendering Layers:**
1. **Background** - Gradient/pattern background
2. **Board Grid** - Visible grid lines
3. **Ghost Piece** - Semi-transparent landing preview
4. **Active Piece** - Current falling piece
5. **Locked Cells** - Placed blocks
6. **UI Overlay** - Score, level, next piece

**Visual Features:**
- Smooth piece movement animations
- Line clear flash effect
- Particle effects for line clears
- Ghost piece (landing preview)
- Grid cell highlighting

### 6. Score System (`scoring.js`)
**Scoring Table (Official Nintendo Scoring):**
| Action | Points |
|--------|--------|
| Single Line | 100 × level |
| Double | 300 × level |
| Triple | 500 × level |
| Tetris (4 lines) | 800 × level |
| Soft Drop | 1 point per cell |
| Hard Drop | 2 points per cell |

**Level Progression:**
- Level up every 10 lines cleared
- Speed increases with level
- Maximum speed at level 15+

### 7. Audio Manager (`audio.js`)
**Sound Effects:**
- Piece move
- Piece rotate
- Piece land
- Line clear (1-4 lines, different sounds)
- Level up
- Game over
- Tetris (4 lines) - special sound

**Background Music:**
- Looping Tetris theme (optional)
- Volume controls

### 8. UI Manager (`ui.js`)
**UI Components:**
- **Main Menu**: Start game, high scores, controls
- **Game HUD**: Score, level, lines, next piece, hold piece
- **Pause Menu**: Resume, restart, quit
- **Game Over Screen**: Final score, high score entry, restart

## Data Flow

```
┌─────────────┐
│   Input     │
│  Handler    │
└──────┬──────┘
       │ Player Actions
       ▼
┌─────────────┐     ┌──────────────┐
│    Game     │────▶│    Board     │
│   Engine    │     │   Manager    │
└──────┬──────┘     └──────┬───────┘
       │                   │
       │ Game State        │ Board State
       ▼                   ▼
┌─────────────┐     ┌──────────────┐
│  Renderer   │◀────│   Pieces     │
│             │     │   System     │
└─────────────┘     └──────────────┘
       │
       │ Visual Output
       ▼
┌─────────────┐
│   Canvas    │
│   Display   │
└─────────────┘
```

## Game Loop Sequence

```
1. Input Phase
   - Process keyboard events
   - Apply DAS/ARR for held keys
   - Execute player actions

2. Update Phase
   - Move piece down (gravity)
   - Check collisions
   - Lock piece if landed
   - Check line clears
   - Update score/level
   - Spawn new piece

3. Render Phase
   - Clear canvas
   - Draw background
   - Draw board grid
   - Draw ghost piece
   - Draw active piece
   - Draw locked cells
   - Draw UI overlay
```

## Key Technical Decisions

### 1. Canvas vs DOM Rendering
**Decision:** HTML5 Canvas
**Rationale:**
- Better performance for 60 FPS animation
- Easier pixel-perfect rendering
- Smooth animations without layout thrashing
- Standard for game development

### 2. Collision Detection
**Method:** Matrix-based collision
- Check each cell of piece matrix against board
- Boundary checking for walls and floor
- Overlap checking with locked cells

### 3. Rotation System
**Implementation:** Super Rotation System (SRS) - Simplified
- Wall kicks for edge cases
- 4 rotation states per piece
- Offset tables for I and O pieces

### 4. State Management
**Pattern:** Single game state object
- Centralized state for easy debugging
- Immutable updates where possible
- State change events for UI updates

### 5. Audio Strategy
**Implementation:** Web Audio API
- Low latency sound effects
- Audio sprite support
- Volume and mute controls

## File Structure

```
tetris/
├── index.html          # Main HTML file
├── css/
│   └── style.css       # Game styling and UI
├── js/
│   ├── main.js         # Entry point and initialization
│   ├── game.js         # Game engine and loop
│   ├── board.js        # Board management
│   ├── pieces.js       # Tetromino definitions and logic
│   ├── input.js        # Input handling
│   ├── renderer.js     # Canvas rendering
│   ├── scoring.js      # Score calculation
│   ├── audio.js        # Sound management
│   └── ui.js           # UI management
├── assets/
│   ├── sounds/         # Sound effect files
│   └── images/         # Any image assets
└── README.md           # Documentation
```

## Responsive Design

**Breakpoints:**
- Desktop: > 800px - Full layout with side panels
- Tablet: 500-800px - Compact layout
- Mobile: < 500px - Touch controls, vertical layout

**Touch Controls (Mobile):**
- Tap left/right side: Move
- Swipe down: Soft drop
- Double tap: Rotate
- Swipe up: Hard drop

## Performance Targets

- **Frame Rate:** Consistent 60 FPS
- **Input Latency:** < 16ms (one frame)
- **Load Time:** < 2 seconds
- **Memory:** < 50MB

## Quality Features (Professional Level)

1. **Ghost Piece** - Shows where piece will land
2. **Hold Piece** - Save a piece for later
3. **Next Piece Preview** - See upcoming pieces (1-3 ahead)
4. **Wall Kicks** - Rotation near walls works correctly
5. **Lock Delay** - Brief moment to adjust before piece locks
6. **Combo System** - Bonus for consecutive line clears
7. **High Scores** - Local storage persistence
8. **Statistics** - Pieces placed, efficiency rating

## Implementation Phases

### Phase 1: Core Mechanics
- Board rendering
- Piece movement and rotation
- Collision detection
- Line clearing

### Phase 2: Game Systems
- Scoring system
- Level progression
- Game states (menu, play, pause, game over)
- Basic UI

### Phase 3: Polish
- Ghost piece
- Hold piece
- Next piece preview
- Sound effects
- Animations and effects

### Phase 4: Professional Features
- High score system
- Statistics tracking
- Touch controls
- Settings menu
- Performance optimization

## Browser Support

- Chrome 80+
- Firefox 75+
- Safari 13+
- Edge 80+
- Mobile browsers (iOS Safari, Chrome Android)