Skip to content

Tic-tac-toe in 20 minutes

What you'll build

  • A two-player game with turns, input validation and win detection
  • Tests that play the game without a server
  • A React board that two browsers can play on

Time: 20 minutesFinished code: examples/tic-tac-toe

You need Node.js 22 or newer. If you only want to see the game run, the quick start takes five minutes. Here you read the project from the rules outward: the game, its tests, the server, then the UI.

Terminal window
npm create shoehive@latest my-game

The scaffolder copies the tic-tac-toe template into my-game/ and installs it. Everything below is that code, so you can read along or delete src/game.ts and type it back in.

A game is one defineGame call. It says who plays, what the starting state is, whose turn it is, and what players can do. Start with the shape and one action:

import { defineGame, reject } from 'shoehive';
import { z } from 'zod';
type Mark = 'X' | 'O';
export const ticTacToe = defineGame({
id: 'tic-tac-toe',
name: 'Tic Tac Toe',
seats: { min: 2, max: 2 },
setup: () => ({
board: Array<Mark | null>(9).fill(null),
winner: null as Mark | 'draw' | null,
}),
turns: { order: 'round-robin' },
actions: {
place: {
input: z.object({ cell: z.number().int().min(0).max(8) }),
run({ state, seat, input, ctx }) {
if (ctx.turn.seat !== seat) reject('NOT_YOUR_TURN');
if (state.board[input.cell]) reject('CELL_TAKEN');
state.board[input.cell] = seat === 0 ? 'X' : 'O';
ctx.turn.next();
},
},
},
});
  • Seats. The table holds two seats, and the game starts when both are taken.
  • State. setup returns the starting state: nine cells and a winner. State must be plain JSON, so there are no classes, Maps or Dates.
  • Turns. With turns, the engine tracks whose turn it is in ctx.turn. round-robin goes through the seats in order, starting with seat 0.
  • Input. input is a zod schema. Anything that does not match, such as { cell: 9 }, is refused with INVALID_INPUT before your code runs.
  • Reject. run changes state directly. reject('CELL_TAKEN') stops the action and throws away every change it made, and the player gets that error code. Game codes are SCREAMING_SNAKE_CASE and may not reuse a built-in code.

The engine does not decide for you that only the seat on turn may act. You check it, which is why the first line of run rejects NOT_YOUR_TURN.

Add a plain function that looks at the board. It is ordinary TypeScript, so you can test it on its own:

src/game.ts
const LINES = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
] as const;
export function winnerOf(board: readonly (Mark | null)[]): Mark | 'draw' | null {
for (const [a, b, c] of LINES) {
const mark = board[a];
if (mark && mark === board[b] && mark === board[c]) return mark;
}
return board.every((cell) => cell !== null) ? 'draw' : null;
}

Now finish place. After the mark is set, compute the winner. If there is one, ctx.end closes the table with a result. Otherwise the turn moves on:

src/game.ts
place: {
input: z.object({ cell: z.number().int().min(0).max(8) }),
run({ state, seat, input, ctx }) {
if (ctx.turn.seat !== seat) reject('NOT_YOUR_TURN');
if (state.board[input.cell]) reject('CELL_TAKEN');
state.board[input.cell] = seat === 0 ? 'X' : 'O';
state.winner = winnerOf(state.board);
if (state.winner) ctx.end({ winner: state.winner });
else ctx.turn.next();
},
},

After ctx.end, the table is ended and later actions fail with TABLE_ENDED. The result reaches clients as meta.result. See the six concepts for how state, actions and turns fit together.

shoehive/testing runs a table in memory, with no server or sockets. createTestTable seats the players, t.act(seat, name, input) plays as one of them, and t.state and t.meta are what the server would hold.

test/game.test.ts
it('rejects a move out of turn', async () => {
const t = await createTestTable(ticTacToe, { players: 2 });
await expect(t.act(1, 'place', { cell: 0 })).rejects.toMatchObject({
code: 'NOT_YOUR_TURN',
source: 'game',
});
expect(t.state.board[0]).toBeNull();
});

A rejected action is a promise that rejects with the error, so toMatchObject can check its code. source: 'game' tells it apart from errors Shoehive raises itself.

test/game.test.ts
it('X wins on the diagonal and the table ends', async () => {
const t = await createTestTable(ticTacToe, { players: 2 });
for (const [seat, cell] of [
[0, 0],
[1, 1],
[0, 4],
[1, 2],
[0, 8],
] as const) {
await t.act(seat, 'place', { cell });
}
expect(t.state.winner).toBe('X');
expect(t.meta.status).toBe('ended');
expect(t.meta.result).toEqual({ winner: 'X' });
await expect(t.act(1, 'place', { cell: 3 })).rejects.toMatchObject({ code: 'TABLE_ENDED' });
await t.verifyReplay();
});

verifyReplay() is worth ending every test with. It replays the table's action log from scratch and fails if the result differs from the live state. That catches a game that reads the clock or Math.random() instead of ctx.now() and ctx.random, which would break reconnects and history. The template's file has three more tests, for input validation, a taken cell and the game not starting with one player.

Terminal window
npm test
src/server.ts
const shoehive = createServer({
games: [ticTacToe],
// Signs guest resume tokens, so players keep their seats across reloads and restarts.
// `npm run dev` sets a random SHOEHIVE_SECRET for the session (see vite.config.ts). In
// production, set your own (32 characters or more): createServer() refuses to start
// without it. Never put one in code: whoever knows it can sign in as any guest.
secret: process.env.SHOEHIVE_SECRET,
// The devtools inspector, in development only. Its URL (with a token) is logged at startup.
// Under `npm run dev` the token stays the same when this server restarts.
devtools: dev && { enabled: true, token: process.env.SHOEHIVE_DEVTOOLS_TOKEN },
});

createServer takes the list of games it can host. The secret signs the resume tokens that let a guest keep their seat after a reload. npm run dev sets a random one for the session, and in production the server refuses to start without SHOEHIVE_SECRET. Never write one into the code: whoever knows it can sign in as any guest. The devtools option turns on the inspector, in development only.

The rest of src/server.ts is a small static file server for the built web app. The one line that matters is this one, which adds the Shoehive WebSocket endpoint (at /shoehive) and the inspector to that HTTP server:

src/server.ts
await shoehive.attach(http);

By default tables live in memory. See stores when you need them to survive a restart.

The browser never gets the game's rules, only its types. Everything it knows about a table comes from the server as a view, which for this game is the whole state.

web/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { ShoehiveProvider } from 'shoehive/react';
import { App } from './App';
// The socket is on the page's own origin: src/server.ts serves both after a build, and in
// development the Vite dev server proxies /shoehive to it (see vite.config.ts).
const url = `${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/shoehive`;
createRoot(document.getElementById('root')!).render(
<StrictMode>
<ShoehiveProvider url={url}>
<App />
</ShoehiveProvider>
</StrictMode>,
);

ShoehiveProvider creates one client for the page and connects it. Each browser becomes a guest player, remembered across reloads. In the app, useConnection() gives the connection status and who you are:

web/App.tsx
const { status, player } = useConnection();
web/App.tsx
const lobby = useLobby();
const client = useClient<[TicTacToe]>();
const [creating, setCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
const tables = (lobby?.tables ?? []).filter((t) => t.game === GAME_ID && t.status !== 'ended');
const create = async (): Promise<void> => {
setCreating(true);
setError(null);
try {
const id = await client.createTable(GAME_ID);
window.location.hash = tableHref(id);
} catch (err) {
setError(describeError(err));
setCreating(false);
}
};

useLobby() is a live list of open tables, null until it loads. createTable makes a new one and returns its id, and the app routes to it with the URL hash. Passing useClient<[TicTacToe]>() the game type (typeof ticTacToe, imported as a type only) is what makes createTable and act check their arguments against your game.

web/App.tsx
const { status, error, view, meta, seats, mySeat, pending, actionError, act, sit } =
useTable<TicTacToe>(tableId);

useTable joins the table and keeps it current. view is the game state, typed from your game. meta has the status and whose turn it is, seats and mySeat say who sits where, and act and sit send actions. They never throw: a failure lands in actionError, and pending counts actions still waiting for the server. From those the component works out what to show:

web/App.tsx
const turn = meta.turn?.seat ?? null;
const over = meta.status === 'ended';
const myTurn = !over && turn !== null && turn === mySeat;
const canSit = mySeat === null && !over && seats.some((s) => s.status === 'empty');

The board is a button per cell. It is disabled unless it is your turn, the cell is empty and nothing is in flight, and clicking sends the place action:

web/App.tsx
<div className="board">
{view.board.map((cell, i) => (
<button
key={i}
type="button"
className="cell"
aria-label={`cell ${String(i)}`}
disabled={!myTurn || cell !== null || pending > 0}
onClick={() => {
// Errors show up in actionError; the hook's act() never rejects.
void act('place', { cell: i });
}}
>
{cell ?? ''}
</button>
))}
</div>

The disabled button is a convenience, not the rule. A modified client can still send a move out of turn, and the server rejects it, which the app shows from actionError using the error codes you wrote in the game.

Terminal window
npm run dev

This starts the Vite dev server and the game server together. Open http://localhost:5173 in two windows, one of them private, so that each is a different guest. Create a game in one, take a seat, then open the same address in the other and take the second seat. Play to a win. Try clicking out of turn, and reload a window mid-game: you keep your seat.

The game server printed an inspector link when it started (Devtools inspector: ...). Open it while a game is running. You can see the table's state, each seat's view next to the spectator's, and the action log, including the moves the game rejected. See devtools for what else it does.

  • The six concepts: the ideas behind what you just built.
  • The blank template: npm create shoehive@latest my-game -- --template blank.
  • Devtools and stores, from the reference.