# Airplane Crash Game - Backend Implementation Guide

## Overview
The backend handles game logic, fairness, and state management for the airplane crash game. All game rounds are generated server-side to ensure fairness and prevent cheating.

## Architecture

### 1. Game Round Management
- Each round has a unique ID
- Crash point is determined when the round starts (server-side)
- Crash multiplier is calculated based on crash time
- Round duration: exactly 7 seconds
- Crash window: 0.5s to 6.8s (before 7s)

### 2. Database Schema

#### GameRound Table
```sql
CREATE TABLE game_round (
    id VARCHAR(36) PRIMARY KEY,
    status VARCHAR(50) NOT NULL, -- 'waiting', 'running', 'crashed', 'ended'
    crash_time_ms INT NOT NULL, -- When the airplane crashes (milliseconds)
    crash_multiplier DECIMAL(10, 2) NOT NULL, -- Multiplier at crash
    started_at TIMESTAMP,
    ended_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

#### PlayerBet Table
```sql
CREATE TABLE player_bet (
    id VARCHAR(36) PRIMARY KEY,
    user_id VARCHAR(36) NOT NULL,
    game_round_id VARCHAR(36) NOT NULL,
    amount DECIMAL(10, 2) NOT NULL,
    auto_cashout_multiplier DECIMAL(10, 2) NOT NULL,
    status VARCHAR(50) NOT NULL, -- 'placed', 'won', 'lost', 'cashed_out'
    final_multiplier DECIMAL(10, 2),
    payout DECIMAL(10, 2),
    placed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES user(id),
    FOREIGN KEY (game_round_id) REFERENCES game_round(id),
    INDEX (user_id),
    INDEX (game_round_id)
);
```

### 3. Game Calculation Logic

#### Multiplier Calculation Formula
```
multiplier = 1.0 + 6.0 * (t / 7)^1.2

Where:
- t = elapsed time in seconds (0 to 7)
- The exponent 1.2 creates an accelerating curve
- Result ranges from 1.0x to 7.0x
```

#### Crash Time Determination
```
Crash time is randomly selected between 500ms and 6800ms
This ensures the airplane never completes a full round
Distribution: Uniform random (fair for all clients)
```

## API Endpoints

### 1. Get Current Round Status
**Endpoint:** `GET /api/v1/game/round`

**Response:**
```json
{
    "id": "round_12345",
    "status": "running",
    "started_at": "2024-01-01T12:00:00Z",
    "remaining_seconds": 3.5,
    "created_round_countdown": 0
}
```

### 2. Start New Round
**Endpoint:** `POST /api/v1/game/round/start`

**Response:**
```json
{
    "id": "round_12345",
    "status": "waiting",
    "started_at": "2024-01-01T12:00:00Z"
}
```

### 3. Place Bet
**Endpoint:** `POST /api/v1/game/bet`

**Request:**
```json
{
    "game_round_id": "round_12345",
    "amount": 100.00,
    "auto_cashout_multiplier": 2.5
}
```

**Response:**
```json
{
    "id": "bet_67890",
    "user_id": "user_123",
    "game_round_id": "round_12345",
    "amount": 100.00,
    "auto_cashout_multiplier": 2.5,
    "status": "placed",
    "placed_at": "2024-01-01T12:00:01Z"
}
```

**Validation:**
- Amount must be between min and max limits
- Auto cashout must be > 1.0
- Only one active bet per user per round
- Round must be in 'waiting' status

### 4. Cashout (Manual Stop)
**Endpoint:** `POST /api/v1/game/cashout`

**Request:**
```json
{
    "bet_id": "bet_67890",
    "current_multiplier": 2.3
}
```

**Response:**
```json
{
    "id": "bet_67890",
    "status": "cashed_out",
    "final_multiplier": 2.3,
    "payout": 230.00,
    "updated_at": "2024-01-01T12:00:05Z"
}
```

**Process:**
1. Validate bet exists and is active
2. Verify current_multiplier hasn't exceeded crash point
3. Calculate payout = bet_amount * current_multiplier
4. Deduct from player balance
5. Update bet status to 'cashed_out'

### 5. Get Game History
**Endpoint:** `GET /api/v1/game/bets?page=1&limit=20`

**Response:**
```json
{
    "data": [
        {
            "id": "bet_67890",
            "game_round_id": "round_12345",
            "amount": 100.00,
            "auto_cashout_multiplier": 2.5,
            "final_multiplier": 1.8,
            "status": "lost",
            "payout": 0.00,
            "placed_at": "2024-01-01T12:00:01Z"
        }
    ],
    "total": 100,
    "page": 1,
    "limit": 20
}
```

## WebSocket Messages

### Client → Server

#### Connect
```json
{
    "type": "gameConnect",
    "token": "bearer_token"
}
```

#### Place Bet
```json
{
    "type": "placebet",
    "game_round_id": "round_12345",
    "amount": 100.00,
    "auto_cashout_multiplier": 2.5
}
```

#### Cashout
```json
{
    "type": "cashout",
    "bet_id": "bet_67890",
    "current_multiplier": 2.3
}
```

### Server → Client

#### Round Start
```json
{
    "type": "round_start",
    "data": {
        "round_id": "round_12345",
        "started_at": "2024-01-01T12:00:00Z"
    }
}
```

#### Multiplier Update (Every 50ms)
```json
{
    "type": "multiplier_update",
    "data": {
        "round_id": "round_12345",
        "current_multiplier": 1.5,
        "elapsed_ms": 500
    }
}
```

#### Crash
```json
{
    "type": "crash",
    "data": {
        "round_id": "round_12345",
        "crash_multiplier": 2.8,
        "crash_time_ms": 2000
    }
}
```

#### Bet Placed Confirmation
```json
{
    "type": "bet_placed",
    "data": {
        "bet_id": "bet_67890",
        "amount": 100.00,
        "status": "placed"
    }
}
```

#### Cashout Confirmation
```json
{
    "type": "cashout_confirmed",
    "data": {
        "bet_id": "bet_67890",
        "final_multiplier": 2.3,
        "payout": 230.00
    }
}
```

## Game Logic Implementation (Go Example)

### Calculate Multiplier
```go
func CalculateMultiplier(elapsedMs int) float64 {
    seconds := float64(elapsedMs) / 1000.0
    maxSeconds := 7.0
    
    if seconds >= maxSeconds {
        return 7.0
    }
    
    // Formula: 1 + 6 * (t/7)^1.2
    normalized := seconds / maxSeconds
    exponent := 1.2
    multiplier := 1.0 + 6.0*math.Pow(normalized, exponent)
    
    if multiplier > 7.0 {
        return 7.0
    }
    return multiplier
}
```

### Generate Crash Point
```go
func GenerateCrashPoint() int {
    minCrash := 500   // 0.5 seconds
    maxCrash := 6800  // 6.8 seconds
    
    crashMs := rand.Intn(maxCrash-minCrash+1) + minCrash
    return crashMs
}
```

### Process Round
```go
func (s *GameService) ProcessRound(ctx context.Context) {
    round := &GameRound{
        ID: uuid.New().String(),
        CrashTimeMs: GenerateCrashPoint(),
        Status: "running",
        StartedAt: time.Now(),
    }
    
    round.CrashMultiplier = CalculateMultiplier(round.CrashTimeMs)
    
    // Save to database
    err := s.db.CreateRound(ctx, round)
    if err != nil {
        return
    }
    
    // Broadcast round start
    s.broadcaster.SendMessage(map[string]interface{}{
        "type": "round_start",
        "data": round,
    })
    
    // Simulate game tick (50ms intervals)
    ticker := time.NewTicker(50 * time.Millisecond)
    defer ticker.Stop()
    
    startTime := time.Now()
    for {
        select {
        case <-ctx.Done():
            return
        case <-ticker.C:
            elapsed := time.Since(startTime).Milliseconds()
            
            // Check if crashed
            if elapsed >= int64(round.CrashTimeMs) {
                s.broadcaster.SendMessage(map[string]interface{}{
                    "type": "crash",
                    "data": round,
                })
                s.processCrashedBets(ctx, round)
                return
            }
            
            // Check if game ended naturally
            if elapsed >= 7000 {
                s.broadcaster.SendMessage(map[string]interface{}{
                    "type": "round_end",
                    "data": round,
                })
                return
            }
            
            // Send multiplier update
            multiplier := CalculateMultiplier(int(elapsed))
            s.broadcaster.SendMessage(map[string]interface{}{
                "type": "multiplier_update",
                "data": map[string]interface{}{
                    "round_id": round.ID,
                    "current_multiplier": multiplier,
                    "elapsed_ms": elapsed,
                },
            })
        }
    }
}
```

## Security Considerations

1. **Crash Point Randomness**: Use cryptographically secure random number generation
2. **Server Authority**: Never trust client multiplier claims - calculate server-side
3. **Rate Limiting**: Limit bet placement and cashout requests per user
4. **Balance Validation**: Always verify sufficient balance before accepting bets
5. **Transaction Integrity**: Use database transactions for bet/payout operations
6. **Logging**: Log all bets, crashes, and payouts for audit trail
7. **Time Sync**: Ensure server time is accurate (NTP)

## Error Handling

### Common Errors

| Code | Message | Cause |
|------|---------|-------|
| 400 | Round not ready | Round status not 'waiting' |
| 400 | Insufficient balance | Player balance < bet amount |
| 400 | Invalid multiplier | Auto cashout not > 1.0 |
| 404 | Round not found | Invalid round ID |
| 404 | Bet not found | Invalid bet ID |
| 409 | Bet already exists | User already has active bet |
| 422 | Game ended | Cashout attempt after crash |

## Performance Optimization

1. **WebSocket Broadcasting**: Use Redis pub/sub for multi-server deployments
2. **Database**: Index on user_id, game_round_id, round status
3. **Caching**: Cache current round status in Redis with 1s TTL
4. **Connection Pooling**: Use connection pool for database
5. **Message Queue**: For high-volume scenarios, queue bet processing

## Testing

### Unit Tests
- Multiplier calculation accuracy
- Crash point randomness
- Payout calculations
- Validation logic

### Integration Tests
- Full game flow (bet → game → cashout/crash)
- Concurrent bets and cashouts
- WebSocket message delivery
- Error scenarios

### Load Tests
- 1000+ concurrent players
- ~14,000 multiplier updates per round (50ms × 7s)
- Message broadcasting performance
