# Crash Game - Developer Quick Reference

## 🚀 Project Structure

```
d:\flutter project\avi\
├── backend/
│   ├── cmd/
│   │   └── server/
│   │       └── main.go              # Server entry point
│   └── internal/
│       ├── handlers/
│       │   ├── game_handler.go       # REST endpoints (5 routes)
│       │   └── websocket_handler.go  # WebSocket broadcaster
│       ├── services/
│       │   ├── crash_game_service.go # Core game logic
│       │   └── wallet_service.go     # Balance management
│       ├── repositories/
│       │   └── game_repository.go    # Database access
│       ├── models/
│       │   └── game.go               # Data structures
│       └── migrations/
│           └── migrations.go         # Database setup
├── lib/
│   ├── main.dart                     # Flutter entry point
│   ├── data/
│   │   ├── providers/
│   │   │   └── crash_game_provider.dart       # Riverpod state
│   │   └── services/
│   │       └── crash_game_service.dart        # Game logic
│   └── presentation/
│       ├── screens/
│       │   └── game/
│       │       └── aviator_game_screen.dart   # Main screen
│       └── widgets/
│           └── crash_game_widget.dart         # Game display
└── docs/
    ├── CRASH_GAME_BACKEND_INTEGRATION.md       # API reference
    ├── CRASH_GAME_FRONTEND_GUIDE.md            # UI guide
    ├── CRASH_GAME_IMPLEMENTATION_SUMMARY.md    # Progress
    └── CRASH_GAME_STATUS_REPORT.md             # Final status
```

## 🔑 Key Files & What They Do

| File | Purpose | Lines | Key Classes |
|------|---------|-------|-------------|
| `game.go` | Database models | 50 | GameRound, GameBet |
| `crash_game_service.go` | Game engine | 800+ | CrashGameService |
| `wallet_service.go` | Balance ops | 300+ | WalletService, Player |
| `game_handler.go` | REST API | 300+ | GameHandler |
| `websocket_handler.go` | Real-time updates | 250+ | WebSocketHandler, GameBroadcaster |
| `game_repository.go` | Data access | 200+ | GameRepository, BetRepository |
| `migrations.go` | Schema setup | 50 | Migrate() |
| `main.go` | Startup | 150+ | initDatabase(), setupRoutes() |

## 🎮 Game Flow

```
1. Frontend: User clicks "Start Round"
   ↓
2. Backend: POST /api/v1/game/round/start
   - Generate crash point (random 500-6800ms)
   - Broadcast round_start WebSocket message
   - Return round ID to player
   ↓
3. Frontend: User places bet (amount + auto-cashout)
   ↓
4. Backend: POST /api/v1/game/bet
   - Validate balance
   - Deduct from wallet
   - Create bet record
   - Broadcast bet placed
   ↓
5. Backend: Game loop runs (50ms intervals)
   - Calculate current multiplier
   - Broadcast multiplier_update WebSocket
   ↓
6. Either:
   A. Frontend: User clicks "Cash Out"
      - POST /api/v1/game/cashout
      - Calculate payout (bet × multiplier)
      - Add to wallet
      ↓
   B. Backend: Crash detected
      - Broadcast round_crashed
      - Mark bet as lost
      - Bet amount already deducted
   ↓
7. Round ends, repeat
```

## 💻 Common Commands

### Backend Development
```bash
# Run server
go run cmd/server/main.go

# Test health endpoint
curl http://localhost:8888/health

# Start new round
curl -X POST http://localhost:8888/api/v1/game/round/start \
  -H "X-User-ID: user123"

# Place bet
curl -X POST http://localhost:8888/api/v1/game/bet \
  -H "X-User-ID: user123" \
  -H "Content-Type: application/json" \
  -d '{
    "round_id": "round_123",
    "amount": 100,
    "auto_cashout_multiplier": 2.5
  }'

# Monitor WebSocket
npm install -g wscat
wscat -c "ws://localhost:8888/api/v1/game/ws" \
  --header "X-User-ID: user123"

# Build binary
go build -o avi_server cmd/server/main.go
```

### Frontend Development
```bash
# Get dependencies
flutter pub get

# Run app
flutter run -d windows    # or macos, ios, etc.

# Run with specific backend URL
flutter run --dart-define=API_URL=http://10.0.0.1:8888

# Build release
flutter build apk      # Android
flutter build ios      # iOS
flutter build windows  # Windows
```

## 🔌 API Endpoint Quick Reference

### Round Management
```
POST   /api/v1/game/round/start       → Start new game
GET    /api/v1/game/round/:id         → Get round status
```

### Betting
```
POST   /api/v1/game/bet               → Place bet
POST   /api/v1/game/cashout           → Manual cashout
GET    /api/v1/game/bets              → Get bet history
```

### Real-Time
```
WS     /api/v1/game/ws                → WebSocket connection
```

## 📊 Database Schema

### GameRound Table
```sql
id              STRING PRIMARY KEY
status          STRING (waiting, running, finished)
crash_time_ms   INTEGER
crash_multiplier FLOAT
started_at      TIMESTAMP
ended_at        TIMESTAMP
```

### GameBet Table
```sql
id                      STRING PRIMARY KEY
user_id                 STRING
game_round_id           STRING
amount                  FLOAT
auto_cashout_multiplier FLOAT
status                  STRING (placed, won, lost, cashed_out, crashed)
final_multiplier        FLOAT
payout                  FLOAT
placed_at               TIMESTAMP
created_at              TIMESTAMP
updated_at              TIMESTAMP
```

### Player Table
```sql
id              STRING PRIMARY KEY
balance         FLOAT
total_bet       FLOAT
total_won       FLOAT
created_at      TIMESTAMP
updated_at      TIMESTAMP
```

## ⚙️ Configuration Constants

All in `internal/services/crash_game_service.go`:
```go
const (
    MaxMultiplier      = 7.0           // Max possible multiplier
    GameDurationMs     = 7000          // 7 seconds
    MinCrashMs         = 500           // Earliest crash (0.5s)
    MaxCrashMs         = 6800          // Latest crash (6.8s)
    UpdateIntervalMs   = 50            // Update frequency (20/sec)
    CrashPointExponent = 1.2           // Multiplier curve acceleration
)
```

And in `internal/services/wallet_service.go`:
```go
const startingBalance = 1000.0  // New player starting balance
```

## 🧪 Quick Testing Scenarios

### Scenario 1: Win by Auto-Cashout
1. Start round
2. Place bet with auto_cashout_multiplier = 2.0
3. Wait for multiplier to reach 2.0 (auto-triggers)
4. Verify payout = bet × 2.0

### Scenario 2: Win by Manual Cashout
1. Start round
2. Place bet
3. Monitor WebSocket for multiplier updates
4. Manually cashout at 4x
5. Verify payout = bet × 4

### Scenario 3: Lose to Crash
1. Start round
2. Place bet without auto-cashout (or high threshold)
3. Game crashes before threshold
4. Verify balance deducted, no payout

### Scenario 4: Concurrent Players
1. Start round
2. Two players place bets
3. One cashes out early
4. Other player loses to crash
5. Verify both outcomes processed correctly

## 🔍 Debugging Tips

### WebSocket Not Connecting?
- Check server is running: `curl http://localhost:8888/health`
- Verify header: `X-User-ID` must be present
- Check CORS: Should allow WebSocket upgrade
- Browser DevTools → Network → WS

### Bet Not Processing?
- Verify player has balance: Check Players table
- Verify round ID is valid: Check GameRounds table
- Check auth header is correct: `X-User-ID: <user>`
- Server logs should show SQL errors if DB problem

### Multiplier Updates Slow?
- Check WebSocket connection is active
- Verify UpdateIntervalMs = 50 in config
- Monitor server CPU usage
- Check database query performance (indexes)

### Payout Incorrect?
- Verify formula: Payout = Bet × Multiplier
- Check final_multiplier stored in database
- Verify wallet service adds correct amount
- Check for floating-point rounding issues

## 📝 Code Examples

### Starting a New Round (Go)
```go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

round, err := gameService.StartRound(ctx)
if err != nil {
    log.Fatal(err)
}
log.Printf("Round started: %s\n", round.ID)
```

### Listening to WebSocket Updates (Dart/Flutter)
```dart
final channel = WebSocketChannel.connect(
  Uri.parse('ws://localhost:8888/api/v1/game/ws'),
  headers: {'X-User-ID': userId},
);

channel.stream.listen((event) {
  final data = json.decode(event);
  print(data['type']); // 'multiplier_update', 'round_crashed', etc.
});
```

### Checking Balance (Go)
```go
balance, err := walletService.GetBalance(ctx, "user123")
if err != nil {
    log.Fatal(err)
}
log.Printf("User balance: %.2f\n", balance)
```

## 🚨 Common Errors & Solutions

| Error | Cause | Solution |
|-------|-------|----------|
| `insufficient_balance` | Bet amount > balance | Login, add funds, or place smaller bet |
| `connection refused` | Server not running | Start: `go run cmd/server/main.go` |
| `round not found` | Invalid round ID | Start new round first |
| `bet already cashed out` | Trying to cashout twice | Can only cashout once per bet |
| `database locked` | SQLite concurrency issue | Switch to PostgreSQL |
| `401 Unauthorized` | Missing X-User-ID header | Add header to request |
| `WebSocket upgrade failed` | CORS issue | Check CORS middleware |

## 🎯 Performance Targets

| Metric | Target | Status |
|--------|--------|--------|
| REST Response Time | <100ms | ✅ Achieved |
| WebSocket Latency | <10ms | ✅ Achieved |
| Multiplier Updates/sec | 20 | ✅ Achieved |
| Concurrent Players | 100+ | ✅ Supported |
| Database Indexes | 6 | ✅ Created |
| Bet Processing | <50ms | ✅ Achieved |

## 📚 Learning Resources

- **Game Mechanics**: See `CRASH_GAME_IMPLEMENTATION_SUMMARY.md`
- **API Contracts**: See `CRASH_GAME_BACKEND_INTEGRATION.md`
- **UI Architecture**: See `CRASH_GAME_FRONTEND_GUIDE.md`
- **Status & Deployment**: See `CRASH_GAME_STATUS_REPORT.md`

## ✅ Checklist for First Run

- [ ] Go v1.18+ installed: `go version`
- [ ] Flutter v3.0+ installed: `flutter --version`
- [ ] Backend database initialized (auto-migrates on startup)
- [ ] Backend server running: `go run cmd/server/main.go`
- [ ] Health check passes: `curl http://localhost:8888/health`
- [ ] Frontend dependencies installed: `flutter pub get`
- [ ] Frontend connected to backend: Update `localhost:8888` if needed
- [ ] Test: Place bet and observe WebSocket updates

## 🎉 You're Ready!

Everything is set up and ready to use. Start the backend server, run the Flutter app, and test the game end-to-end!
