Quiz: round-based play
What you'll build
- A quiz for 2 to 12 players with timed questions
- Simultaneous answers that stay hidden until the reveal
- Scores that reward fast correct answers
In tic-tac-toe players took turns. Here everyone acts at the same
time, inside a window that closes on a timer. Project setup, serving and the React basics are
the same as there, so this page only covers what is new. The finished code is in
examples/quiz/.
Options
Section titled “Options”A game can take options when a table is created. They are a schema, so a bad value is
rejected before setup runs, and setup receives the parsed result.
options: z.object({ questions: z.number().int().min(1).max(QUESTIONS.length).default(3) }),The lobby passes { questions: 5 } to client.createTable. setup uses random.shuffle
to pick that many questions, so the order is seeded and replayable.
Phases and rounds
Section titled “Phases and rounds”The quiz alternates between two phases: question and reveal. The question phase uses
rounds, the model for simultaneous play. A round opens on entering the phase, collects
one submission from each seated player, and closes.
question: { rounds: { durationMs: QUESTION_MS, closeWhen: 'all-submitted', onOpen: ({ state, ctx }) => { state.answers = {}; state.openedAt = ctx.now(); }, onClose: ({ state, ctx }) => { const question = QUESTIONS[state.order[state.current]!]!; for (const [seat, answer] of Object.entries(state.answers)) { if (answer.choice !== question.answer) continue; // Faster correct answers score more: from 1000 down to 500 at the deadline. const points = Math.round(MAX_POINTS - (MAX_POINTS / 2) * (answer.after / QUESTION_MS)); state.scores[Number(seat)] = (state.scores[Number(seat)] ?? 0) + points; } ctx.phase.go('reveal'); }, }, actions: { answer: { once: true, input: z.object({ choice: z.number().int().min(0).max(3) }), run({ state, seat, input, ctx }) { state.answers[String(seat)] = { choice: input.choice, after: ctx.now() - state.openedAt, }; }, }, },},durationMsgives the round a deadline.closeWhen: 'all-submitted'closes it early as soon as every participant has submitted, or at the deadline, whichever comes first.participantsare the seats occupied when the round opened. Someone who sits down mid-question waits for the next one.- An action with
once: trueis a submission. A second call from the same seat is rejected withALREADY_SUBMITTEDbeforerunexecutes. A call from a non-participant getsNOT_PARTICIPANT, and one after the close getsROUND_CLOSED. onOpenresets the answers and records the open time.onCloseruns exactly once per round: it scores the answers and moves toreveal.
ctx.now() is the recorded clock, constant for the whole action, so the scoring is
deterministic and replays exactly. Answers arrive in any order, but never at the same
instant: the table runs them one at a time.
Rounds do not reopen by themselves. Here onClose changes phase, which opens a fresh round
when the next question starts. See Turns and rounds for the
full model.
Timers
Section titled “Timers”The reveal phase shows the answer for five seconds, then asks the next question.
reveal: { onEnter: ({ ctx }) => { ctx.timers.after('next', REVEAL_MS, 'nextQuestion'); }, actions: { nextQuestion: { internal: true, run({ state, ctx }) { if (state.current + 1 >= state.order.length) { const best = Math.max(...state.scores); ctx.end({ scores: state.scores, winners: ctx.occupied.filter((s) => state.scores[s] === best), }); return; } state.current += 1; ctx.phase.go('question'); }, }, },},ctx.timers.after(name, ms, action) schedules an action to run later. The action here is
internal: true, so the timer and the engine can run it but a client calling it gets
ACTION_NOT_ALLOWED. Timers live in the table's state, so they survive a server restart.
Pass { visible: true } as the last argument and the deadline appears in meta.timers, so
a client can show a countdown. The quiz does not need it, because the question round already
publishes its deadline in meta.round.deadline. More in
Timers and turn clocks.
The last nextQuestion calls ctx.end with the scores and the winning seats, which ends
the table.
Hiding answers until the reveal
Section titled “Hiding answers until the reveal”Every client gets its own view of the state, built by view. State stays on the server, so
hiding something is a matter of not putting it in the view.
// Until the reveal, a player sees only their own answer, and nobody sees the correct one.view: ({ state, viewer, ctx }) => { const question = QUESTIONS[state.order[state.current]!]!; const revealing = ctx.phase === 'reveal' || ctx.status === 'ended'; const mine = viewer.seat === null ? undefined : state.answers[String(viewer.seat)]; return { number: state.current + 1, of: state.order.length, question: { text: question.text, choices: question.choices }, correct: revealing ? question.answer : null, answers: revealing ? Object.fromEntries(Object.entries(state.answers).map(([seat, a]) => [seat, a.choice])) : mine ? { [String(viewer.seat)]: mine.choice } : {}, scores: state.scores, };},During a question each player sees only their own choice, and correct is null for
everyone, spectators included. In the reveal phase, and once the game has ended, the view
includes every answer and the correct choice. The question's answer field never leaves the
server before then. See Views and sync and
Hidden information.
Test with a fake clock
Section titled “Test with a fake clock”createTestTable runs the game without a server, with a clock you control. t.advance(ms)
moves it forward and fires any timer that falls due, in order.
it('scores faster correct answers higher, using the recorded clock', async () => { const { t, correct } = await table(); await t.act(0, 'answer', { choice: correct() }); await t.advance(QUESTION_MS / 2); await t.act(1, 'answer', { choice: correct() }); await t.advance(QUESTION_MS / 2); // seat 2 never answers; the round times out expect(t.state.scores.slice(0, 3)).toEqual([1000, 750, 0]);});Seat 0 answers at time zero, seat 1 half way through, and seat 2 never answers, so the round closes at the deadline. The scores 1000 and 750 follow from the recorded times. Two more tests cover the rest.
it('hides answers until the reveal, then shows everything', async () => { const { t, correct } = await table(); await t.act(0, 'answer', { choice: correct() }); expect(t.viewOf(0).answers).toEqual({ '0': correct() }); expect(t.viewOf(1).answers).toEqual({}); expect(t.viewOf('spectator').correct).toBeNull(); expect(t.meta.round?.submitted).toEqual([0]);
await t.act(1, 'answer', { choice: (correct() + 1) % 4 }); await t.act(2, 'answer', { choice: correct() }); expect(t.meta.phase).toBe('reveal'); expect(t.viewOf(1).correct).toBe(correct()); expect(Object.keys(t.viewOf(1).answers)).toHaveLength(3);});it('one answer per player per question', async () => { const { t } = await table(); await t.act(0, 'answer', { choice: 0 }); await expect(t.act(0, 'answer', { choice: 1 })).rejects.toMatchObject({ code: 'ALREADY_SUBMITTED', });});t.viewOf(seat) returns what that player would see, and t.meta.round is the same round
data a client receives. The last test in the file ends with t.verifyReplay(), which
replays the whole recorded game and checks it ends in the same state. More in
Testing games.
The countdown
Section titled “The countdown”The server sends a deadline, not a number of seconds left, so every client counts down
against the same moment. useServerTime returns the current time as the server sees it, and
re-renders on an interval.
const now = useServerTime(250);const secondsLeft = asking && meta.round?.deadline ? Math.max(0, Math.ceil((meta.round.deadline - now) / 1000)) : null;meta.round.submitted lists the seats that have answered, which is how the UI shows
"answered" or "thinking" next to each player without revealing what they chose. The answer
buttons call act('answer', { choice }), and ALREADY_SUBMITTED and ROUND_CLOSED errors
arrive in actionError, where the example maps them to friendly messages.
Run it
Section titled “Run it”pnpm --filter @shoehive-examples/quiz build:webpnpm --filter @shoehive-examples/quiz startOpen http://localhost:3102 in two browser windows, one of them private, as in the quick start.
- Turns vs rounds: choosing the model for each phase.
- Phases: more on
onEnter,onExitand moving between phases. - Blackjack: a game that mixes both models and handles money.
