Examples Game lobby with ready check

Game lobby with a ready check

A four-seat co-op lobby where each player controls their own profile and ready status, and clicking Start runs a live RPC confirmation across the connected players before launching the match.

Roster, ready state, and match start

makeUserState('player') gives each participant a signed slot and exposes the full roster via player.getAll(). A kind: 'request' action verifies everyone is still responsive and ready at launch time, and maxUsers: 4 caps the room at four distinct users.

import {joinRoom} from 'trystero'

// Invite link: https://example.com/lobby#MANGO-49
const lobbyCode = location.hash.slice(1) || newLobbyCode()

// maxUsers counts unique userIds rather than browser tabs
const room = joinRoom(
  {appId: 'example.com/lobby', maxUsers: 4},
  lobbyCode
)

const player = room.makeUserState('player', {
  name: 'Player',
  avatar: '๐ŸฆŠ',
  ready: false
})
const readyCheck = room.makeAction('ready-check', {kind: 'request'})
const start = room.makeAction('start')

player.onChange(() => renderRoster(player.getAll()))
player.set({name: nameInput.value, avatar: avatarPicker.value, ready: false})

readyToggle.onclick = () => player.set(prev => ({...prev, ready: !prev.ready}))

readyCheck.onRequest(() => player.get().ready)

startButton.onclick = async () => {
  const targets = Object.keys(room.getUsers())

  if (targets.length === 0 || !player.get().ready) {
    return showToast('Mark yourself ready and wait for at least one other player')
  }

  const results = await readyCheck.requestMany(null, {
    targets,
    timeoutMs: 5000,
    onResult: res =>
      markCheck(res.userId, res.status === 'fulfilled' && res.value === true)
  })

  const everyoneReady = results.every(
    res => res.status === 'fulfilled' && res.value === true
  )

  if (!everyoneReady) return showToast('Waiting on all players to confirm')

  const seed = crypto.getRandomValues(new Uint32Array(1))[0]
  await start.send({seed})
  startGame(seed)
}

start.onMessage(({seed}) => startGame(seed))

room.onError(err => {
  if (err.code === 'room-full' && Object.keys(room.getPeers()).length === 0) {
    showFullLobby(lobbyCode)
  }
})

renderRoster, markCheck, showToast, showFullLobby, and startGame are application UI callbacks. Using a globally unique appId (a domain you own or 'username/app-name') namespaces your rooms so short human-readable lobby codes do not collide with other Trystero apps.

Confirming readiness with requestMany

player.getAll() is eventually consistent: if a player closes their laptop or toggles ready off at the moment someone clicks Start, presence state may take a moment to reflect the disconnect.

requestMany acts as an explicit confirmation round. It sends one request per userId in targets (routed to one tab per user), waits up to timeoutMs, and resolves with a status entry per target: 'fulfilled' (with the returned boolean), 'timeout', 'disconnected', or 'rejected'. onResult fires as each peer replies so the UI can update checkmarks progressively, and the match only starts when every player responds true.

room.getUsers() returns remote users only, so targets.length === 0 prevents starting solo. Once confirmed, start.send({seed}) broadcasts a shared PRNG seed so all clients initialize the same level.

Counting users rather than tabs

maxUsers counts unique userIds (including the local user). Refreshing the page or opening a second tab reuses the same seat, while a fifth user is declined during admission before onUserJoin fires on seated players.

Because each peer evaluates capacity locally, an already-seated player can also receive 'room-full' if a peer they encounter saw a full room. Checking Object.keys(room.getPeers()).length === 0 isolates the case where the local client itself was turned away.

Local testing: tabs in the same browser profile share one userId. Use separate private windows or pass identity: 'none' when testing multi-seat lobbies on a single machine.