Skip to content

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

Time: 30 minutesFinished code: examples/quiz

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/.

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.

src/game.ts
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.

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.

src/game.ts
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,
};
},
},
},
},
  • durationMs gives the round a deadline. closeWhen: 'all-submitted' closes it early as soon as every participant has submitted, or at the deadline, whichever comes first.
  • participants are the seats occupied when the round opened. Someone who sits down mid-question waits for the next one.
  • An action with once: true is a submission. A second call from the same seat is rejected with ALREADY_SUBMITTED before run executes. A call from a non-participant gets NOT_PARTICIPANT, and one after the close gets ROUND_CLOSED.
  • onOpen resets the answers and records the open time. onClose runs exactly once per round: it scores the answers and moves to reveal.

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.

The reveal phase shows the answer for five seconds, then asks the next question.

src/game.ts
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.

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.

src/game.ts
// 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.

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.

test/game.test.ts
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.

test/game.test.ts
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);
});
test/game.test.ts
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 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.

web/App.tsx
const now = useServerTime(250);
web/App.tsx
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.

Terminal window
pnpm --filter @shoehive-examples/quiz build:web
pnpm --filter @shoehive-examples/quiz start

Open 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, onExit and moving between phases.
  • Blackjack: a game that mixes both models and handles money.