> ## Documentation Index
> Fetch the complete documentation index at: https://docs-ts.playservices.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Hop-On/Off Tournaments

> Player-count based tournaments created on-demand for continuous availability

# Hop-On/Off Tournament Format

Hop-on/off tournaments are created by the Game Platform on-demand when players join a lobby. Tournaments start when a minimum player threshold is reached, providing continuous availability and instant gratification for players.

## Key Characteristics

<Warning>
  This format requires **minimal new API development** - only tournament creation and refund logic are format-specific. All gameplay functionality is shared with scheduled tournaments.
</Warning>

* **On-demand Creation**: Game Platform creates tournaments when first player joins lobby
* **Player-count Start**: Tournament starts when minimum players reached
* **Lobby-based Registration**: Players join lobby first, then buy-in through Casino System
* **Continuous Cycle**: Late joiners automatically create new tournaments
* **Refund Logic**: Players can leave and get refunds before tournament starts

## Architecture Overview

**Key Principle**: Game Platform creates tournament upfront via internal API. Tournament starts when MIN\_PLAYERS reached instead of specific time.

### Format-Specific Features

* **On-demand Creation**: Game Platform creates tournaments when first player joins
* **Player-count Start**: Tournament starts when minimum players reached
* **Lobby-based Registration**: Players join via lobby, then buy-in through Casino System
* **Continuous Cycle**: Late joiners create new tournaments automatically

## Tournament Flow

```mermaid theme={null}
sequenceDiagram
    participant CS as Casino System
    participant TS as Tournament System
    participant GP as Game Platform
    participant UI as Casino UI
    participant SQS as AWS SQS

    Note over CS,SQS: 1. Tournament Creation on First Player Join (Format-Specific)
    CS->>UI: Player clicks join game link
    UI->>GP: Connect to lobby
    GP->>GP: Check: any tournament waiting for players?
    
    alt No Tournament Exists
        GP->>TS: POST /internal/tournaments<br/>Header: Authorization: Bearer internal_key<br/>Body: {name: 'Crash #{timestamp}', type: 'hop_on_off', gameSlug, minPlayers: 5, startCondition: 'min_players_reached'}
        TS->>TS: Validate internal API key
        TS->>TS: Create tournament (status: 'scheduled')
        TS->>TS: Set auto-start condition: minPlayers instead of startTime
        TS->>GP: 201 Created {tournamentId, status: 'scheduled', minPlayers: 5}
        GP->>GP: Store tournament ID for lobby
    else Tournament Already Waiting
        GP->>GP: Use existing tournament waiting for players
    end
    
    GP->>UI: postMessage {type: 'tournament.available', tournamentId}
    UI->>CS: Show tournament buy-in interface<br/>Tournament: {tournamentId}

    Note over CS,SQS: 2. Player Count-Based Tournament Start (Format-Specific)
    Note over CS,SQS: [Player registration via Common Flow]
    
    TS->>TS: Check: playerCount >= minPlayers?
    alt MIN_PLAYERS Reached
        TS->>TS: Auto-start tournament<br/>Set status: 'active'
        TS->>GP: POST /api/rooms/create<br/>Body: {tournamentId, gameConfig}
        GP->>GP: Create game room for tournament
        GP->>TS: 201 Created {roomId, roomUrl}
        TS->>TS: Store roomId & update status: 'active'
        TS->>SQS: Send event: tournament.started<br/>{tournamentId, status: 'active'}
        SQS->>CS: Tournament started notification
    end

    Note over CS,SQS: 3. Player Refund Logic (Format-Specific)
    alt Player Leaves Before Tournament Starts
        UI->>GP: Player disconnects/leaves lobby
        GP->>TS: DELETE /internal/tournaments/{tournament}/players/{player}<br/>Header: Authorization: Bearer internal_key<br/>Body: {reason: 'left_before_start'}
        TS->>TS: Validate tournament status: 'scheduled'
        TS->>CS: POST /api/operators/{operatorId}/players/{userId}/refund<br/>Body: {transactionId, amount, reason: 'left_before_start'}
        CS->>TS: 200 OK {refunded: true}
        TS->>TS: Remove player from tournament
        TS->>GP: 200 OK {refunded: true, remainingPlayers}
        
        alt Last Player Left - Cancel Tournament
            TS->>TS: Check: tournament has 0 players?
            TS->>TS: Cancel tournament<br/>Set status: 'cancelled'
            TS->>GP: Tournament cancelled notification
            GP->>GP: Clear tournament from lobby
        end
        
        GP->>UI: postMessage {type: 'player.left', refunded: true}
    end

    Note over CS,SQS: 4. Continuous Tournament Cycle (Format-Specific)
    alt Tournament Active - Late Joiner
        CS->>UI: Late player wants to join
        UI->>GP: Connect to lobby  
        GP->>GP: Current tournament active, create next tournament
        GP->>TS: POST /internal/tournaments<br/>Body: {name: 'Crash #{new_timestamp}', type: 'hop_on_off', minPlayers: 5}
        TS->>GP: 201 Created {nextTournamentId}
        GP->>UI: postMessage {type: 'tournament.available', tournamentId: nextTournamentId}
        
        Note over CS,TS: Player registers to next tournament via Common Flow
    end

    Note over CS,SQS: [COMMON FLOWS - Shared with Scheduled]
    Note over CS,SQS: Player Registration & Authentication → Common Flow
    Note over CS,SQS: Game Platform Configuration Exchange → Common Flow
    Note over CS,SQS: Game Launch & Room Connection → Common Flow
    Note over CS,SQS: Tournament Gameplay & Event Reporting → Common Flow
    Note over CS,SQS: Player Management (Rebuy/Leave) → Common Flow
    Note over CS,SQS: Tournament Completion & Cleanup → Common Flow
    Note over CS,SQS: Results & Leaderboard Access → Common Flow
```

## Format-Specific APIs

### Tournament Creation (New API)

**Internal API - Game Platform creates tournaments:**

```http theme={null}
POST /internal/tournaments
Header: Authorization: Bearer {internal_api_key}  
Content-Type: application/json

{
  "name": "Crash #1642089600",
  "type": "hop_on_off",
  "gameSlug": "crash-classic",
  "minPlayers": 5,
  "maxPlayers": 50, 
  "startCondition": "min_players_reached",
  "entryFee": 5.00,
  "prizePool": {
    "type": "percentage", 
    "distribution": [60, 25, 15]
  },
  "rebuyEnabled": true,
  "rebuyFee": 5.00,
  "maxEntriesPerPlayer": 2
}
```

**Response:**

```json theme={null}
{
  "tournamentId": 12346,
  "status": "scheduled",
  "minPlayers": 5,
  "currentPlayers": 0,
  "startCondition": "min_players_reached"
}
```

### Player Refund Logic (New API)

**Internal API - Remove players with refund:**

```http theme={null}
DELETE /internal/tournaments/12346/players/tp_player_456
Header: Authorization: Bearer {internal_api_key}
Content-Type: application/json

{
  "reason": "left_before_start"
}
```

**External API - Process refund via Casino System:**

```http theme={null}
POST /api/operators/{operatorId}/players/{userId}/refund
Header: X-API-Key: {operator_key}
Content-Type: application/json

{
  "transactionId": "tx_12345",
  "amount": 5.00,
  "reason": "left_before_start"
}
```

## Player Experience Flow

### 1. Joining the Lobby

<Steps>
  <Step title="Player Clicks Join Game">
    Player clicks game link or join button in Casino UI
  </Step>

  <Step title="Connect to Game Lobby">
    Casino UI connects to Game Platform lobby via WebSocket/postMessage
  </Step>

  <Step title="Tournament Availability Check">
    Game Platform checks if tournament exists waiting for players
  </Step>

  <Step title="Create New Tournament (if needed)">
    If no tournament waiting, Game Platform creates new tournament via internal API
  </Step>

  <Step title="Show Buy-in Interface">
    Casino UI displays tournament details and buy-in option
  </Step>
</Steps>

### 2. Player Registration & Tournament Start

<Steps>
  <Step title="Player Buys In">
    Player confirms buy-in through Casino System standard registration flow
  </Step>

  <Step title="JWT Token Generated">
    Tournament System generates JWT token and returns game URL
  </Step>

  <Step title="Waiting for Players">
    Player waits in lobby for minimum player count to be reached
  </Step>

  <Step title="Auto-start When Ready">
    Tournament starts automatically when `playerCount >= minPlayers`
  </Step>

  <Step title="Game Room Connection">
    Players connected to game room using shared common flow
  </Step>
</Steps>

### 3. Late Joiner Handling

<Steps>
  <Step title="Tournament Already Active">
    New player tries to join but current tournament is already running
  </Step>

  <Step title="Create Next Tournament">
    Game Platform automatically creates new tournament for next round
  </Step>

  <Step title="Seamless Registration">
    Player registers for next tournament using same flow
  </Step>

  <Step title="Continuous Availability">
    Always a tournament available for immediate play
  </Step>
</Steps>

## Format-Specific Features

### Tournament Creation Logic

<Tabs>
  <Tab title="First Player Join">
    **When no tournament exists:**

    * Game Platform creates new tournament via `POST /internal/tournaments`
    * Tournament status set to `scheduled` with `startCondition: 'min_players_reached'`
    * Lobby displays tournament info and buy-in interface
    * Players can register immediately via standard external APIs
  </Tab>

  <Tab title="Subsequent Players">
    **When tournament already waiting:**

    * Game Platform uses existing tournament ID
    * Players join existing tournament via standard registration
    * Tournament tracks player count toward minimum threshold
  </Tab>
</Tabs>

### Auto-start Logic

<Info>
  Unlike scheduled tournaments that start at a specific time, hop-on/off tournaments start when `playerCount >= minPlayers`.
</Info>

**Start Trigger Process:**

1. **Player Count Check**: After each registration, check if `playerCount >= minPlayers`
2. **Auto-start Tournament**: Change status from `scheduled` to `active`
3. **Create Game Room**: Request room creation from Game Platform
4. **Notify Players**: Send SQS events and postMessage notifications
5. **Begin Gameplay**: Use shared common flows for game management

### Refund System

Players can leave before tournament starts and receive full refunds:

<Warning>
  **Important**: Refunds are only available before tournament starts (`status: 'scheduled'`). Once tournament is active, standard leave policies apply.
</Warning>

**Refund Process:**

1. **Player Leaves Lobby**: Disconnects before tournament starts
2. **Internal API Call**: Game Platform notifies Tournament System
3. **Refund Request**: Tournament System requests refund from Casino System
4. **Player Removal**: Player removed from tournament registration
5. **Tournament Check**: If last player left, tournament is cancelled

### Continuous Tournament Cycle

**Late Joiner Flow:**

* Player tries to join when tournament is already `active`
* Game Platform creates next tournament immediately
* Player registers for next tournament while current one runs
* Ensures continuous availability without waiting

## Shared Common Flows

After format-specific creation and start logic, hop-on/off tournaments use identical flows as scheduled tournaments:

<CardGroup cols={2}>
  <Card title="Player Registration" icon="user-plus" href="/casino-integration/player-management#registration-flow">
    Standard JWT generation and player session management.
  </Card>

  <Card title="Game Configuration" icon="gear" href="/game-platform-integration/internal-apis#tournament-configuration">
    Tournament config delivery and real-time status sync.
  </Card>

  <Card title="Real-time Gameplay" icon="bolt" href="/game-platform-integration/real-time-communication">
    Room management, postMessage events, SQS reporting.
  </Card>

  <Card title="Results & Completion" icon="trophy" href="/casino-integration/results-leaderboards">
    Prize calculation, distribution, and tournament cleanup.
  </Card>
</CardGroup>

## Architecture Benefits

<Columns cols={2}>
  <div>
    ### Player-count Reliability

    * Tournaments only start when enough players ready
    * No empty or under-populated tournaments
    * Guaranteed competitive experience
  </div>

  <div>
    ### Continuous Availability

    * Always a tournament available for players to join
    * No waiting for scheduled times
    * Instant gratification for casual players
  </div>
</Columns>

### Minimal Development Requirements

* **Shared Functionality**: 90% of code reused from scheduled tournaments
* **New APIs**: Only tournament creation and refund logic
* **Proven Infrastructure**: All gameplay and event systems already exist

## Use Cases

**Ideal for:**

* 🎮 **Casual Gaming**: Players wanting immediate tournament action
* 🔄 **Continuous Play**: Games with steady player flow throughout the day
* 📱 **Mobile Games**: Quick tournament rounds for mobile users
* 🌐 **Global Audiences**: Different time zones, always someone ready to play

**Example Scenarios:**

* Crash game tournaments starting every 5-10 minutes
* Quick poker tournaments with 5-player minimum
* Arcade-style competitions with instant starts
* Practice tournaments for learning game mechanics

## Implementation Timeline

<Steps>
  <Step title="Phase 1: Internal Tournament Creation API">
    Implement `POST /internal/tournaments` for Game Platform tournament creation
  </Step>

  <Step title="Phase 2: Player-count Start Logic">
    Add auto-start logic when minimum players reached
  </Step>

  <Step title="Phase 3: Refund System">
    Implement player removal and Casino System refund integration
  </Step>

  <Step title="Phase 4: Continuous Cycle Logic">
    Add late joiner detection and automatic next tournament creation
  </Step>
</Steps>

## Next Steps

<Card title="Casino Integration APIs" icon="building" href="/casino-integration/introduction" horizontal>
  Learn about the external APIs used by both tournament formats for operator integration.
</Card>
