# Airplane Crash Game - Frontend Implementation Guide

## Overview
The frontend provides a real-time game interface for the airplane crash game with smooth animations, live multiplier updates, and responsive betting controls.

## Architecture

### Components

#### 1. CrashGameService (`lib/data/services/crash_game_service.dart`)
Core game logic service with:
- Game state management
- Multiplier calculations
- Crash point determination
- Event streaming
- Timer management

**Key Features:**
- 50ms update intervals for smooth animation
- Smooth multiplier progression using power curve
- Automatic round duration (7 seconds max)
- Crash point randomization (0.5s - 6.8s)

**Public API:**
```dart
class CrashGameService {
  // Start a new game round
  void startRound()
  
  // Stop the game immediately
  void stopGame()
  
  // Get current game state
  double get currentMultiplier
  bool get hasCrashed
  bool get isRunning
  double get elapsedSeconds
  double get remainingSeconds
  
  // Event streams
  Stream<GameEvent> get eventStream
  Stream<double> get multiplierStream
  Stream<double> get crashStream
}
```

**Events:**
```dart
enum GameEvent {
  roundStart,      // Game started
  multiplierUpdate, // Multiplier changed
  crash,           // Airplane crashed
  roundEnd,        // Game ended naturally
}
```

#### 2. CrashGameProvider (`lib/data/providers/crash_game_provider.dart`)
Riverpod state provider for:
- Game state management
- Player interaction handling
- Event listening and translation

**State:**
```dart
class CrashGameState {
  double currentMultiplier;      // Current multiplier (1.0 to 7.0)
  double elapsedSeconds;         // How long game has run
  double remainingSeconds;       // Time until game ends
  bool isRunning;                // Is game active
  bool hasCrashed;               // Did airplane crash
  double crashMultiplier;        // Multiplier at crash
  String gameStatus; // 'waiting', 'running', 'crashed', 'finished'
}
```

**Methods:**
```dart
class CrashGameNotifier extends StateNotifier<CrashGameState> {
  void startRound()  // Start new game round
  void stopRound()   // Stop game manually
}
```

#### 3. CrashGameWidget (`lib/presentation/widgets/crash_game_widget.dart`)
Main UI component displaying:
- Live airplane animation
- Real-time multiplier
- Game status
- Statistics display

**Props:**
```dart
class CrashGameWidget extends StatefulWidget {
  final double currentMultiplier;
  final bool isRunning;
  final bool hasCrashed;
  final VoidCallback? onGameStart;
}
```

**Visual Elements:**
- Animated airplane (✈️) flying across screen
- Flight path with altitude markers
- Current multiplier display (styled badge)
- Status message (Flying/Crashed/etc)
- Statistics panel (Max, Current, Status)
- Crash explosion animation

#### 4. AviatorGameScreen (`lib/presentation/screens/game/aviator_game_screen.dart`)
Main game screen with:
- Game widget integration
- Betting controls
- Balance display
- Game instructions

## Multiplier Calculation

### Formula
```
multiplier = 1.0 + 6.0 * (elapsed_time / 7.0)^1.2

Where:
- elapsed_time = seconds elapsed (0 to 7)
- Exponent 1.2 creates accelerating curve
- Result is clamped to [1.0, 7.0]
```

### Examples
```
Time    → Multiplier
0.0s    → 1.00x
0.5s    → 1.04x
1.0s    → 1.10x
2.0s    → 1.25x
3.0s    → 1.55x
4.0s    → 2.02x
5.0s    → 2.73x
6.0s    → 3.76x
7.0s    → 7.00x (max)
```

## Game Flow

### 1. Initialization
```dart
// Called on screen init
void initState() {
  ref.read(crashGameProvider.notifier).startRound();
}
```

### 2. User Interaction Flow

#### Placing a Bet
```
1. User enters bet amount
2. Validates amount (min/max)
3. Waits for game to start
4. Places bet via API
5. Bet confirmed, can now cashout
```

#### Cashing Out
```
1. User taps "Cash Out" button while game running
2. Current multiplier is captured
3. Stop game immediately
4. Calculate winnings = bet_amount * multiplier
5. Send cashout to API
6. Update balance
7. Show result
8. Start new round
```

#### Game Crash
```
1. Crash time reached
2. Airplane crashes (animation)
3. Game stops
4. Show final crash multiplier
5. Process all active bets as losses
6. Wait 2 seconds
7. Auto-start new round
```

## Animation Details

### Airplane Flight Path
- Starts at x = -50 (off-screen left)
- Ends at x = 400 (off-screen right)
- Duration: 7 seconds
- Curve: easeInQuad (accelerates)

### Crash Explosion
```dart
// Appears at crash point
// Scales from 0.5 to 2.0
// Opacity fades to 0
// Duration: 800ms
```

### Multiplier Update
- Updates every 50ms
- Smooth transition
- Color changes: Blue (normal) → Red (crash)

## Error Handling

### Game Not Ready
```
User Action: Place Bet
Game State: Not 'waiting' or 'running'
Response: Show error "Game not ready. Please wait for the round to start."
Recovery: User must wait for next round
```

### Invalid Inputs
```
User enters: Bet amount = -100
Validation: Amount must be > 0
Response: Show error "Bet amount must be greater than 0"
Recovery: User modifies input
```

## State Management Flow

```
┌─────────────────────────────────────┐
│  CrashGameWidget                    │
│  (UI Component)                     │
└──────────────┬──────────────────────┘
               │ watches
               ▼
┌─────────────────────────────────────┐
│  CrashGameProvider                  │
│  (Riverpod State)                   │
└──────────────┬──────────────────────┘
               │ listens to
               ▼
┌─────────────────────────────────────┐
│  CrashGameService                   │
│  (Game Logic)                       │
└──────────────┬──────────────────────┘
               │ streams
               ▼
     GameEvent / Multiplier values
```

## Integration with Existing Systems

### Betting System
```dart
// When user places bet
await ref.read(betProvider.notifier).placeBet(
  roundId: roundId,
  amount: betAmount,
  autoCashout: autoCashoutValue,
);

// When user cashes out
await ref.read(betProvider.notifier).cashout(
  betId: betId,
  currentMultiplier: crashGameState.currentMultiplier,
);
```

### Wallet System
```dart
// After bet placed - deduct from user wallet
final newBalance = wallet.balance - betAmount;

// After cashout - add winnings
final winnings = betAmount * multiplier;
final newBalance = wallet.balance + winnings;
```

## Performance Optimizations

### 1. Efficient Animations
- Uses AnimationController with custom curves
- Only rebuilds affected widgets
- AnimatedBuilder for airplane position
- Opacity transitions are GPU-accelerated

### 2. Event Streaming
- Broadcast streams for multiple listeners
- Selective widget rebuilds
- Riverpod state management (lazy evaluation)

### 3. Calculations
- Multiplier computed efficiently
- Math.pow() called only when needed
- No unnecessary re-renders

## Testing

### Unit Tests
```dart
test('Multiplier calculation', () {
  final service = CrashGameService();
  
  // Test at key points
  expect(calculateMultiplierAtTime(0), 1.0);
  expect(calculateMultiplierAtTime(7000), 7.0);
  expect(calculateMultiplierAtTime(3500), greaterThan(1.0));
  expect(calculateMultiplierAtTime(3500), lessThan(7.0));
});

test('Crash point is random', () {
  final service1 = CrashGameService();
  final service2 = CrashGameService();
  
  // Crash points should be different (with high probability)
  expect(service1.crashMultiplier, isNot(service2.crashMultiplier));
});
```

### Widget Tests
```dart
testWidgets('CrashGameWidget displays multiplier', (tester) async {
  await tester.pumpWidget(
    CrashGameWidget(
      currentMultiplier: 2.5,
      isRunning: true,
      hasCrashed: false,
    ),
  );
  
  expect(find.text('2.50x'), findsWidgets);
});
```

### Integration Tests
```dart
testWidgets('Full game flow', (tester) async {
  // 1. Start game
  // 2. Place bet
  // 3. Wait for updates
  // 4. Cashout or crash
  // 5. Verify state updates
});
```

## Customization

### Change Game Duration
```dart
// In CrashGameService
static const int gameDurationMs = 7000; // Change to desired duration
```

### Change Multiplier Formula
```dart
// In CrashGameService._calculateMultiplierAtTime()
// Modify the exponent (currently 1.2)
final multiplier = 1.0 + (maxMultiplier - 1.0) * pow(normalizedTime, 1.5);
```

### Change Crash Window
```dart
// In CrashGameService
static const int minCrashMs = 500;   // 0.5 seconds
static const int maxCrashMs = 6800;  // 6.8 seconds
// Adjust to desired range
```

### Customize Colors
```dart
// In CrashGameWidget
// Change AppColors.primaryBlue, AppColors.accentRed, etc.
```

## Debugging

### Enable Logging
```dart
// CrashGameService logs automatically
[CrashGameService] Round started
[CrashGameService]   Crash will occur at: 2000ms
[CrashGameService]   Crash multiplier: 2.80x
```

### Watch State Changes
```dart
// Use Riverpod devtools or add listeners
ref.listen(crashGameProvider, (previous, next) {
  print('Game state changed: ${next.gameStatus}');
  print('Current multiplier: ${next.currentMultiplier}');
});
```

## Future Enhancements

1. **Advanced Animations**
   - Smoke trail behind airplane
   - Cloud parallax effect
   - Sound effects

2. **Statistics**
   - Player win rate
   - Average multiplier
   - Bankroll graph

3. **Social Features**
   - Live leaderboard
   - Player achievements
   - Watch other players

4. **Mobile Optimization**
   - Simplified UI for small screens
   - Touch-optimized buttons
   - Portrait/landscape support

5. **Customization**
   - Theme selection
   - Animation speed settings
   - Sound toggle
