Build a multiplayer browser game without a server
This walkthrough builds Scribble Night, a four-player drawing and guessing game deployed as two static files. One player receives a secret prompt and draws it, the others submit guesses, and the host's browser manages round state, scores, and moderation.
Architecture
The entire game lives in index.html and game.js
on any static host. Peers discover one another over public relays, connect
directly via WebRTC, and exchange strokes, guesses, and state without an
application backend.
Without a server, the player who creates the room acts as referee. Passing
roles({selfAsAdmin: true}) gives the creator a
cryptographically verified 'admin' role that owns the round
state, scoreboard, and prompt selection. Other players can read shared
state and send actions on permitted channels, while unauthorized state
writes are rejected.
| Requirement | Trystero API |
|---|---|
| Private four-seat room with verified host | joinRoom with roles, selfAsAdmin, password, and maxUsers |
| Per-player name and brush color | makeUserState |
| Host-controlled round phase and timer | makeState (admin-only when roles() is loaded) |
| Live pointer strokes from the active drawer | makeAction gated to ['admin', 'drawer'] |
| Guess evaluation against the secret word | makeAction with kind: 'request' |
| Authoritative scoreboard | makeState |
| Removing disruptive players | room.ban |
Minimal HTML markup:
<!doctype html>
<meta charset="utf-8" />
<title>Scribble Night</title>
<canvas id="canvas" width="800" height="600"></canvas>
<ul id="roster"></ul>
<form id="guess-form"><input id="guess-input" placeholder="Guess the drawing" /></form>
<button id="start">Start round</button>
<script type="module" src="./game.js"></script>
All code below goes into game.js. DOM rendering helpers such
as renderRoster, drawPoint, and
showPrompt are left to your UI layer.
Step 1: Create or join the room
Both host and guests run the same script. Guests open an invite link
containing ?room=...; opening the bare URL starts a new room
as host.
import {joinRoom, roles} from 'https://esm.run/trystero'
const url = new URL(location.href)
const invitedRoomId = url.searchParams.get('room')
const isHost = !invitedRoomId
// Store the password in the URL hash so it is never sent in HTTP requests
const password = isHost ? crypto.randomUUID() : url.hash.slice(1)
const room = joinRoom(
{
appId: 'oedipa/scribble-night',
password,
maxUsers: 4,
use: [isHost ? roles({selfAsAdmin: true}) : roles()]
},
isHost ? `party-${crypto.randomUUID().slice(0, 4)}` : invitedRoomId
)
const {userId: myId, roomId} = await room.getSelf()
// selfAsAdmin formats roomId as "party-3f9a~<22-char host userId>"
const hostId = roomId.slice(roomId.lastIndexOf('~') + 1)
if (isHost) {
url.searchParams.set('room', roomId)
url.hash = password
showInviteLink(url.href)
}
room.onError(err => {
const alone = Object.keys(room.getPeers()).length === 0
if (err.code === 'room-full' && alone) {
showBanner('All four seats are taken.')
} else if (err.code === 'decrypt-failed' && alone) {
showBanner('Invite link is missing or has an invalid key.')
}
})- Self-certifying host ID.
roles({selfAsAdmin: true})appends~<userId>to the room name. Guests joining thatroomIdwithroles()verify admin signatures against the public key encoded in the room name itself. Joining a~room withoutroles()throws immediately. - User-level seat cap.
maxUsers: 4counts uniqueuserIds rather than tabs, so refreshing preserves a player's seat. Because every peer evaluates capacity from its own view, checkingObject.keys(room.getPeers()).length === 0ensures only a client that failed to enter sees the full-room banner. - Encrypted signaling.
passwordderives the signaling key via PBKDF2-SHA256 (600,000 iterations). Storing it inlocation.hashkeeps it out of HTTP requests and server logs.
Step 2: Player roster
Each player publishes their display name and color to
makeUserState('profile'). Entries are signed by their owner,
keyed by userId, and evicted automatically when that player's
last tab disconnects.
const profile = room.makeUserState('profile', {name: 'Anon', color: '#888'})
// Flushed during the admission handshake before remote onUserJoin handlers run
profile.set({name: pickName(), color: pickColor()})
profile.onChange(() => renderRoster(profile.getAll()), {replay: true})
room.onUserJoin(({userId}) => toast(`${profile.get(userId).name} joined`))
room.onUserLeave(({userId}) => toast(`${profile.get(userId).name} left`))
Calling profile.set() right after joinRoom()
flushes the initial record during the handshake before
onUserJoin fires on remote peers, so
profile.get(userId).name is already populated in join
notifications.
Local testing: browser tabs in the same profile share a
persistent 'local' userId in IndexedDB. Open a
private window or pass identity: 'none' to simulate
multiple players on one machine.
Step 3: Host-owned round state
The active round metadata belongs in makeState('round'). With
roles() loaded, makeState defaults to
roles: ['admin']: all peers read updates, only the host can
write them, and peers drop records without a valid admin signature.
const ROUND_MS = 60_000
// With roles() loaded, makeState defaults to admin-only writes
const round = room.makeState(
'round',
{number: 0, phase: 'lobby', drawerId: null, endsAt: 0, answer: null},
{
validate: next =>
['lobby', 'drawing', 'reveal'].includes(next.phase) &&
Number.isInteger(next.number) &&
next.number >= 0
}
)
round.onChange(
state => renderRound(state, {amDrawer: state.drawerId === myId}),
{replay: true}
) replay: true invokes the listener immediately if a round is
already underway when a late joiner connects.
Because shared state is readable by every client, the secret word stays
out of round during the drawing phase. The host keeps
secret in memory, sends it privately to the current drawer
over a targeted admin-only action, and publishes it to
round.answer only when the round ends:
const PROMPTS = ['lighthouse', 'accordion', 'cactus', 'submarine', 'post horn']
// Send the secret prompt only to the active drawer rather than shared state
const whisper = room.makeAction('whisper', {roles: ['admin']})
whisper.onMessage(({text}) => showPrompt(text))
let secret = null
let timer = null
const startRound = async () => {
clearTimeout(timer)
const players = [myId, ...Object.keys(room.getUsers())]
const {number} = round.get()
const drawerId = players[number % players.length]
secret = PROMPTS[Math.floor(Math.random() * PROMPTS.length)]
// Grant 'drawer' before updating round so the certificate is ready immediately
if (drawerId !== myId) await room.grantRole(drawerId, 'drawer')
await round.set({
number: number + 1,
phase: 'drawing',
drawerId,
endsAt: Date.now() + ROUND_MS,
answer: null
})
if (drawerId === myId) showPrompt(secret)
else await whisper.send({text: secret}, {target: drawerId})
timer = setTimeout(endRound, ROUND_MS)
}
const endRound = async () => {
clearTimeout(timer)
const {drawerId} = round.get()
await round.set(prev => ({...prev, phase: 'reveal', answer: secret}))
if (drawerId !== myId) await room.revokeRole(drawerId, 'drawer')
timer = setTimeout(startRound, 5_000)
}
if (isHost) startButton.onclick = startRound
Granting 'drawer' before updating round ensures
the chosen player already holds their signed role certificate as soon as
drawerId === myId becomes true.
Step 4: Streaming canvas strokes
Pointer coordinates are high-frequency transient events, which fit
makeAction. Restricting stroke to
roles: ['admin', 'drawer'] prevents other guessers from
injecting strokes on the wire:
const stroke = room.makeAction('stroke', {roles: ['admin', 'drawer']})
const amDrawing = () => {
const {phase, drawerId} = round.get()
return phase === 'drawing' && drawerId === myId
}
const sendPoint = (e, start) => {
if (!amDrawing()) return
const point = {
x: e.offsetX / canvas.clientWidth,
y: e.offsetY / canvas.clientHeight,
start
}
drawPoint(point)
stroke.send(point)
}
canvas.onpointerdown = e => sendPoint(e, true)
canvas.onpointermove = e => {
if (e.buttons) sendPoint(e, false)
}
stroke.onMessage((point, {userId}) => {
if (userId === round.get().drawerId) drawPoint(point)
})
Checking userId === round.get().drawerId on receive also
ignores accidental pointer events from the host when another player is
drawing. Payloads under 16 KiB transmit in a single data-channel frame,
and normalizing coordinates to 0..1 keeps drawings aligned
across different viewport sizes.
Step 5: Evaluating guesses and updating scores
Guesses use a kind: 'request' action targeted at
hostId so only the host sees unrevealed guesses and returns
whether each attempt matched.
Scores are stored in admin-only makeState('scores') rather
than makeUserState so players cannot modify their own totals.
Because the host is the sole writer, storing a
{[userId]: points} map in makeState
avoids concurrent write conflicts while preserving a player's score if
they refresh mid-game.
const guess = room.makeAction('guess', {kind: 'request'})
const scores = room.makeState('scores', {})
scores.onChange(all => renderScores(all), {replay: true})
const normalize = s => s.trim().toLowerCase()
const judge = (text, userId) => {
const {phase, drawerId} = round.get()
if (phase !== 'drawing' || userId === drawerId) return {correct: false}
const correct = normalize(text) === normalize(secret)
if (correct) {
scores.set(prev => ({
...prev,
[userId]: (prev[userId] ?? 0) + 10,
[drawerId]: (prev[drawerId] ?? 0) + 5
}))
endRound()
}
return {correct}
}
if (isHost) guess.onRequest(({text}, {userId}) => judge(text, userId))
guessForm.onsubmit = async e => {
e.preventDefault()
const text = guessInput.value
guessInput.value = ''
try {
const {correct} = isHost
? judge(text, myId)
: await guess.request({text}, {target: hostId, timeoutMs: 3000})
showGuessResult(text, correct)
} catch {
showBanner('Could not reach the host.')
}
} scores.set() and endRound() update the host's
local state synchronously, so a second guess arriving milliseconds later
sees phase: 'reveal' and is ignored. If the host disconnects,
guess.request() rejects with 'timeout' or
'disconnected'.
Step 6: Moderation
Calling room.ban(userId) disconnects all of that user's tabs,
revokes their granted roles, purges any state records they authored, and
blocks reconnection under that userId across connected peers:
const kick = async userId => {
await room.ban(userId, {reason: 'writing the answer on the canvas'})
// Remove the banned user's entry from host-authored scores
scores.set(prev => {
const {[userId]: removed, ...rest} = prev
return rest
})
}
room.onError(err => {
if (err.code === 'banned') {
showBanner(`Removed by host${err.reason ? `: ${err.reason}` : ''}`)
}
})
Because entries inside scores were signed by the host rather
than the banned player, kick also removes their key from
scores. Banned clients receive code: 'banned' on
room.onError, and their seat under maxUsers
reopens immediately.
Step 7: Production considerations
- Signaling relays. Public Nostr relays require zero
setup. For dedicated uptime guarantees, switch the import to
@trystero-p2p/ws-relay, Supabase, or Firebase without changing room logic; see Signaling & relays. - NAT traversal. Around 10โ15% of networks block direct
WebRTC and emit
'peer-connect-failed'unlessturnConfigis provided; see TURN & troubleshooting. - Larger player counts. Full-mesh connections work best
up to roughly ten peers. For larger rooms, add the experimental
scale()plugin. - Host disconnects. If the host leaves, guests retain the
last signed
roundandscoressnapshots, though no new rounds can start unless co-admins were configured viaroles({admins}); see Admins, roles & moderation.