Something went wrong. Try again.
A Social Deduction / Deception Game
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204// Browser side of the wire protocol: open the subscription socket for a game, keep a projected// state by folding #event frames onto the initial #snapshot (wire/apply.ts), and expose a small// API for sending upstream intent frames. Identity (DID) is carried by the session cookie sent on// the WebSocket upgrade — not a URL param; `handle`/`spriteRef` are cosmetic presentation hints.
import { decodeFrame, messageFrame, applyWireEvent } from '../../wire/index.js'import type { WireAction } from '../../wire/index.js'import type { ProjectedState } from '../../lexgen/types/town/deception/defs.js'import type { StationInteraction } from '../../engine/selectors.js'import type { Answer, AnswerLineKind, DeductionCaseView, InspectMood, PublicEvidence } from '../../engine/deduction/index.js'
export type { ProjectedState, StationInteraction }
export interface GameConnection { /** Send an upstream intent frame, e.g. sendIntent('#start') or sendIntent('#move', { vec }). */ sendIntent: (t: string, body?: unknown) => void close: () => void}
export interface ConnectOpts { code: string handle?: string spriteRef?: string | null onState: (state: ProjectedState) => void /** reply to a #interact intent: the per-viewer station menu, for THIS client only */ onInteraction?: (menu: StationInteraction) => void onError?: (error: string, message?: string) => void onClose?: () => void}
function wsUrl(opts: ConnectOpts): string { const proto = location.protocol === 'https:' ? 'wss' : 'ws' const q = new URLSearchParams({ code: opts.code }) if (opts.handle) q.set('handle', opts.handle) if (opts.spriteRef) q.set('spriteRef', opts.spriteRef) return `${proto}://${location.host}/ws?${q.toString()}`}
export function connectGame(opts: ConnectOpts): GameConnection { let state: ProjectedState | null = null let closedByUs = false const ws = new WebSocket(wsUrl(opts)) ws.binaryType = 'arraybuffer'
ws.onmessage = (ev) => { const { header, body } = decodeFrame(new Uint8Array(ev.data as ArrayBuffer)) if (header.op === -1) { const e = body as { error: string; message?: string } opts.onError?.(e.error, e.message) return } if (header.t === '#interaction') { const m = body as { stationId: string; menu: StationInteraction } if (m.menu) opts.onInteraction?.(m.menu) return } const msg = body as { seq: number; serverTime: number; state?: ProjectedState; action?: WireAction } if (header.t === '#snapshot' && msg.state) { state = msg.state opts.onState(state) } else if (header.t === '#event' && msg.action) { if (!state) return const next = applyWireEvent(state, msg.action) if (next) { next.seq = msg.seq state = next } else { // a round-phase event we can't fold incrementally yet; keep state, advance the cursor state = { ...state, seq: msg.seq, now: Math.max(state.now, msg.serverTime) } } opts.onState(state) } }
ws.onerror = () => opts.onError?.('socket-error') ws.onclose = () => { if (!closedByUs) opts.onClose?.() }
return { sendIntent: (t, payload = {}) => { if (ws.readyState === WebSocket.OPEN) ws.send(messageFrame(t, payload)) }, close: () => { closedByUs = true ws.close() }, }}
// --- single-player deduction --------------------------------------------------// The deduction room speaks the SAME #snapshot/#event world frames (so the world folds identically to// the deception client above), plus side-channel frames it never sends in deception: #case (suspects +// inspectable stations, once at connect) and the request/reply pairs #inspect→#revealed (walk a// station's clue stack), #question→#answer (own up / deny), #accuse→#verdict. Identity is the session// cookie; the room is private to its creator (the server rejects anyone else).
/** Reply to an #inspect: the surface `mood` at the station's current frontier, and the clue there * (null when the slot is clean / repaired). The client accumulates the clues it earns this way. */export interface DeductionRevealed { stationId: string depth: number mood: InspectMood /** the station's (public) job — lets the client render every mood, clue or not. */ verb: PublicEvidence['verb'] resource: string clue: PublicEvidence | null}export interface DeductionAnswer { suspectDid: string clueId: string answer: Answer /** which line the suspect gives (rendered with display names client-side). */ line: AnswerLineKind /** true when this owning-up just opened a deeper clue at `stationId` (re-investigate to find it). */ unlocked: boolean stationId: string}export interface DeductionVerdict { suspectDid: string correct: boolean culpritDid: string}
export interface DeductionConnectOpts { code: string onState: (state: ProjectedState) => void /** the public case, delivered once just after the opening snapshot */ onCase: (view: DeductionCaseView) => void /** reply to an #inspect intent: what's at the station's current frontier */ onRevealed: (msg: DeductionRevealed) => void /** reply to a #question intent: one suspect's answer about one clue */ onAnswer: (msg: DeductionAnswer) => void /** reply to an #accuse intent: whether the accused is the culprit (and who actually is) */ onVerdict: (msg: DeductionVerdict) => void onError?: (error: string, message?: string) => void onClose?: () => void}
export type { DeductionCaseView }
export function connectDeduction(opts: DeductionConnectOpts): GameConnection { let state: ProjectedState | null = null let closedByUs = false const proto = location.protocol === 'https:' ? 'wss' : 'ws' const ws = new WebSocket(`${proto}://${location.host}/ws/deduction?code=${encodeURIComponent(opts.code)}`) ws.binaryType = 'arraybuffer'
ws.onmessage = (ev) => { const { header, body } = decodeFrame(new Uint8Array(ev.data as ArrayBuffer)) if (header.op === -1) { const e = body as { error: string; message?: string } opts.onError?.(e.error, e.message) return } if (header.t === '#case') { opts.onCase(body as unknown as DeductionCaseView) return } if (header.t === '#revealed') { opts.onRevealed(body as unknown as DeductionRevealed) return } if (header.t === '#answer') { opts.onAnswer(body as unknown as DeductionAnswer) return } if (header.t === '#verdict') { opts.onVerdict(body as unknown as DeductionVerdict) return } const msg = body as { seq: number; serverTime: number; state?: ProjectedState; action?: WireAction } if (header.t === '#snapshot' && msg.state) { state = msg.state opts.onState(state) } else if (header.t === '#event' && msg.action) { if (!state) return const next = applyWireEvent(state, msg.action) if (next) { next.seq = msg.seq state = next } else { state = { ...state, seq: msg.seq, now: Math.max(state.now, msg.serverTime) } } opts.onState(state) } }
ws.onerror = () => opts.onError?.('socket-error') ws.onclose = () => { if (!closedByUs) opts.onClose?.() }
return { sendIntent: (t, payload = {}) => { if (ws.readyState === WebSocket.OPEN) ws.send(messageFrame(t, payload)) }, close: () => { closedByUs = true ws.close() }, }}