Rooms

Rooms are where players connect. Create one, share the code, and you're multiplayer.

Creating a Room

import { connect } from '@watchtower-sdk/core'

// Create with auto-generated code
const room = await connect()
console.log('Room code:', room.code)  // e.g., "X7K2M9"

// Share this code with friends
alert('Join with code: ' + room.code)

Joining a Room

// Join by code
const room = await connect('X7K2M9')

// Room code is case-insensitive
const room = await connect('x7k2m9')  // Same room

URL-Based Rooms

A common pattern is putting the room code in the URL:

// On page load
const code = window.location.hash.slice(1)  // "#X7K2M9" → "X7K2M9"
const room = await connect(code || undefined)

// Update URL with room code
window.location.hash = room.code

// Now sharing the URL shares the room!
// https://yourgame.com/#X7K2M9

Room Properties

room.code        // Room code for sharing
room.playerId    // Your player ID
room.players     // Array of players in room
room.playerCount // Number of players
room.hostId      // Host player's ID
room.isHost      // Are you the host?
room.connected   // WebSocket connected?

Players

// List all players
for (const player of room.players) {
  console.log(player.id)       // Unique ID
  console.log(player.name)     // Display name (if provided)
  console.log(player.meta)     // Custom metadata
  console.log(player.joinedAt) // Timestamp
}

Host

The first player to join becomes the host. If they leave, the next player becomes host.

if (room.isHost) {
  // You have authority over game state
  // Common pattern: only host can modify shared state
}

// Check who's host
console.log('Host:', room.hostId)

Player Events

room.on('join', (player) => {
  console.log(`${player.name || player.id} joined!`)
  console.log('Players now:', room.playerCount)
})

room.on('leave', (player) => {
  console.log(`${player.id} left`)
})

Leaving a Room

// Leave and disconnect
room.leave()

// After leaving, you can connect to a different room
const newRoom = await connect('OTHER-ROOM')

Connection Events

room.on('connected', () => {
  console.log('Connected to room')
})

room.on('disconnected', () => {
  console.log('Disconnected (will auto-reconnect)')
})

room.on('error', (error) => {
  console.error('Connection error:', error)
})

Auto-Reconnect

The SDK automatically reconnects if the connection drops. It uses exponential backoff (1s, 2s, 4s, ...) up to 30 seconds between attempts.

Connect Options

const room = await connect('my-room', {
  name: 'Alice',              // Display name
  meta: {                     // Custom metadata
    avatar: 'knight',
    color: '#ff0000',
    team: 'blue'
  },
  gameId: 'my-game',          // Game ID (defaults to hostname)
  playerId: 'custom-id'       // Custom player ID (auto-generated if omitted)
})

Next Steps