01Back to the board
Some of my clearest memories from those summers in Khartoum are of a chessboard. Lessons in the morning, sport in the afternoon, and somewhere in between, games that felt like the only quiet thing all day. I was not good. I just loved the shape of it, a problem with clear rules and no luck to hide behind.
Years later I wanted to come back to it from the other side, as the person building the thing. A chess platform looks small and turns out not to be. You need the board and the rules, an opponent smart enough to be worth playing, and the wiring for two strangers to play each other in real time. I picked it as the kind of project that forces you to learn the things you have been avoiding.
02Choosing the pieces
Most of my work lives in React and Next.js, so for this one I went somewhere else on purpose. SvelteKit is lean, the compiler does a lot of the work, and its stores map cleanly onto something as stateful as a chess game. On top of that I pulled in chess.js for move generation and validation, and the lite single-threaded WebAssembly build of Stockfish 18 for the computer opponent. The board is chessground, the one Lichess uses, in a small Svelte wrapper I keep in the repo. It replaced svelte-chessground when I moved the project to Svelte 5. The multiplayer side runs on a small Node server using Express and the ws library.
Late in the project it also got a real logo, the Split King. It is one king cut down the middle and held together only by its crown, so both players share one piece and neither of them wins.

03One board, two modes
The same board has to work whether you are playing the computer or another person, so both modes extend one shared GameModel that owns the game view the UI reads. The rules themselves sit one level lower, in a small ChessCore class that wraps chess.js and nothing else. The AI subclass bolts on the engine. The multiplayer subclass bolts on the socket, the reconnection handling, and a display of the clock the server keeps. The board component never has to know which one it is driving, even now that the two modes need quite different things. And because ChessCore is a plain class with no Svelte in it, the rules layer gets ordinary unit tests instead of hoping the UI exercises every edge case.
04The engine, kept off the main thread
Stockfish is a serious chess engine. The build I ship is a WebAssembly file of about 7 MB, and at the top levels it will spend up to two seconds on a single move. Run that on the main thread and the whole UI freezes while the computer makes up its mind. So the engine lives in a Web Worker, and the app talks to it over the standard UCI protocol with postMessage. You cannot just start asking it for moves either. First it has to come up through the UCI handshake: send uci, wait for uciok, send isready, wait for readyok, and only then is it ready to play. Anything the game asks for before then waits in a queue.
05Making difficulty feel human
Even on its weakest setting, raw Stockfish plays with a precision that flattens a casual player. Making the computer strong is the easy part. The hard part is making it fun to lose to when you crank it up and fun to beat when you dial it down, and one strength slider cannot carry that.
My first answer spread each level across six engine settings, with sigmoid curves, Contempt, and MultiPV. Stockfish 18 made me throw that tuning out. Even its built-in Elo floor of 1320 beats most beginners, and it has no Contempt option at all. So a difficulty level from 1 to 20 now fans out into four settings. Skill Level climbs in a straight line from 0 to 20. A depth cap grows slowly at first, so level 1 looks only one half-move ahead and misses simple tactics. Move time grows on a curve from 50 ms to two seconds. The low levels also get a deliberate delay, because nothing sells a human opponent quite like pretending to think.
setDifficulty(level: number): void {
this.difficulty = level;
const skillLevel = this.mapLevelToSkill(level);
const moveTime = this.mapLevelToMoveTime(level);
const depth = this.mapLevelToDepth(level);
const moveDelay = this.mapLevelToMoveDelay(level);
this.log(
`Setting difficulty: Skill Level ${skillLevel}, Move Time ${moveTime}, Depth ${depth}, Move Delay ${moveDelay}`,
'info'
);
this.searchParams = { moveTime, depth, moveDelay };
// Queued until readyok if the handshake hasn't finished yet.
this.applyDifficultyOptions((cmd) => this.send(cmd));
}
private applyDifficultyOptions(post: (command: string) => void): void {
post(`setoption name Skill Level value ${this.mapLevelToSkill(this.difficulty)}`);
}
// ...
/** Level 1-20 → Stockfish Skill Level 0-20 (linear). */
private mapLevelToSkill(level: number): number {
return Math.round(((clampLevel(level) - 1) * 20) / 19);
}
/** Level 1-20 → search depth cap 1-20, slow at first: ((level-1)/19)^1.5. */
private mapLevelToDepth(level: number): number {
return Math.round(1 + Math.pow((clampLevel(level) - 1) / 19, 1.5) * 19);
}
/** Level 1-20 → move time 50-2000 ms, quadratic. */
private mapLevelToMoveTime(level: number): number {
return Math.round(50 + Math.pow((clampLevel(level) - 1) / 19, 2) * 1950);
}
/** Level 1-20 → cosmetic delay before searching, 400-0 ms (linear). */
private mapLevelToMoveDelay(level: number): number {
return Math.round(400 - ((clampLevel(level) - 1) / 19) * 400);
}
06One rulebook, two sides
Once single-player was playable, the harder half of the brief was still sitting there: two strangers on two machines, agreeing on one game. The browser and multiplayer server both use chess.js at the same declared version, which removes one source of rule drift. The client uses it to preview legal moves and validate local input. The server still owns the result. It replays every submitted move on its own board and resynchronizes the client when the states differ. The library throws on an illegal move instead of returning false. On the beta I started with, one bad message could take the whole server down. The server now validates and rate-limits every frame, and the move handler catches whatever still gets through.
private handleMove(player: Player, move: WireMove) {
if (!this.gameStarted || player.color !== this.currentTurn) {
this.resyncPlayer(player);
return;
}
// ...
if (!move || typeof move.from !== 'string' || typeof move.to !== 'string') {
this.resyncPlayer(player);
return;
}
let success;
try {
// chess.js (beta) throws on illegal moves
success = this.chess.move(move);
} catch {
this.resyncPlayer(player);
return;
}
if (!success) {
this.resyncPlayer(player);
return;
}
this.updateGameStateAfterMove(player, {
from: success.from,
to: success.to,
promotion: success.promotion
});
}07Keeping time
Each multiplayer game is a GameRoom on the server, holding the board, both players, and their clocks. The project carries an AUDIT.md, which started as one full pass over my own shipped code and now records five more rounds of review. Its first headline finding was embarrassing: the first version of the clock trusted the client. When you ran out of time, your opponent's browser was the one that said so, which means anyone who could type a WebSocket message could have said so whenever they liked. Nobody ever cheated me with it, as far as I know. It still went to the top of the audit as the thing to kill first.
The fix inverted the design. All the clock arithmetic moved into a pure module that never calls Date.now() or setTimeout itself. The current time comes in as an argument, so flag-fall is deterministic and every case sits in an ordinary unit test. When a move lands, the server charges the mover for exactly the time they spent and awards the increment only if they had not already flagged. Timeouts are the server's call alone. It arms a watchdog for the side to move and ends the game itself when the clock it keeps runs out. The result is a loss on time, or a draw if the side with time left has nothing that could ever mate. A later review caught me skipping that FIDE rule. The message handler no longer even has a timeout case, just a comment saying clients cannot declare outcomes.
The server owns the clock
/**
* Pure, authoritative clock math for the multiplayer server.
*
* No `Date.now()` or `setTimeout` lives in here — the current time is always
* injected as `now` (ms). This keeps flag-fall deterministic and unit-testable
* (see clock.test.ts). Clocks are stored in MILLISECONDS to avoid the
* seconds/ms rounding drift the old per-move logic suffered from.
*/
// ...
/**
* The mover's new remaining ms after completing a move: deduct the time spent
* on the move, then add the increment (awarded only if they did not flag).
*/
export function clockAfterMove(
currentMs: number,
turnStartedAt: number | null,
incrementMs: number,
now: number
): number {
const elapsed = turnStartedAt !== null ? now - turnStartedAt : 0;
const remaining = currentMs - elapsed;
if (remaining <= 0) return 0;
return remaining + incrementMs;
}08No clock before the first move
Another round of review found that White's clock started the moment Black joined. If you were still finding the board, you were already losing time. Timed games now follow the Lichess rule. No clock runs until both sides have made their first move, and those moves cost no time and earn no increment. Each side gets 30 seconds for its first move, or the server aborts the game with no result. Resigning or offering a draw before both sides have moved aborts it too.
private updateGameStateAfterMove(player: Player, move: WireMove) {
const now = this.now();
// This was the mover's first move (the move is already on the board).
const firstMoves = this.chess.history().length <= 2;
// Apply the clock to the mover (the side whose turn just ended), then flip.
// A side's first move costs no time and earns no increment: its clock
// wasn't running (CR3-4).
if (!this.timeControl.isUnlimited && !firstMoves) {
this.clocksMs[player.color] = clockAfterMove(
this.clocksMs[player.color],
this.turnStartedAt,
this.timeControl.increment * 1000,
now
);
}
this.currentTurn = opposite(player.color);
if (this.timeControl.isUnlimited) {
this.turnStartedAt = null;
} else if (firstMoves && player.color === 'white') {
// White's first move: Black's clock stays stopped until Black's first move,
// and Black's window starts now if Black is here (else when it returns).
this.turnStartedAt = null;
this.firstMoveDeadlineAt = null;
this.startFirstMoveWindow();
} else {
// Both sides have moved (or this is a later move): White's clock runs now.
this.turnStartedAt = now;
this.firstMoveDeadlineAt = null;
}
// ...
}09A seat, not a cookie
Real games happen on flaky phone networks, so losing the socket does not remove a player. It marks them disconnected and keeps the seat in the room. The first version remembered you by a player ID, and the audit found that ID leaking into the WebSocket URL, the server logs, and a cookie any script on the page could read. Anyone with the room ID could join, too.
Now each seat has a secret token, created with the room. Your browser keeps it in localStorage and sends it in the first message on every new socket, never in the socket's URL. The server compares it in constant time and sends back one full snapshot of the game. The invite link carries your friend's token in the URL fragment, the part browsers never send to a server. That token works once.
If you stay away for more than a minute, your opponent can claim the game, and the server checks that claim itself. Disconnects never delete a room. A sweep clears it out after half an hour with no activity, because the first version deleted it the moment the creator refreshed the waiting page.

Taking a seat
/**
* Bind `ws` to the seat whose token it presented (first join or reconnect).
* Returns the seated player, or null for an unknown/stale token. The colour
* comes from the seat, never from the client (audit F2/C3).
*/
claimSeat(token: string, ws: WebSocket): Player | null {
const color = (['white', 'black'] as const).find((c) => sameToken(this.seats[c].token, token));
if (!color) return null;
const existing = this.players.find((p) => p.color === color);
if (existing) {
this.sendTo(ws, { type: 'seat', color, token: this.seats[color].token });
this.reconnect(existing, ws);
return existing;
}
// First claim: rotate the single-use token and seat the player.
this.seats[color].token = newToken();
const player: Player = {
id: nanoid(),
color,
ws,
connected: true,
disconnectedAt: null
};
this.players.push(player);
this.touch();
this.sendToPlayer(player, { type: 'seat', color, token: this.seats[color].token });
// ...
return player;
}10Where the server lives
I did not start with Express. My first sketch ran on Cloudflare Workers with Hono, which is a lovely setup right up until you need two clients to share one live game room. Coordinating that much stateful, in-memory back-and-forth across a distributed edge runtime fought me harder than the feature was worth, so I backed off to something I could hold in my head: a plain Express server with the ws library, owning the rooms directly.
The multiplayer backend is small on purpose. One Express process handles the WebSocket connections too, and the live games sit in memory as a map of rooms. There is no database and no message broker, which does mean a game will not survive a server restart. For something like this I think that is a fair trade, and I would rather say so than pretend the limit is not there. It is a single process, it does not scale sideways, and the day I genuinely needed it to, I would reach for a shared store and pub/sub. For now it runs in a container on the same ordinary VPS as a few other services, so it adds little to infrastructure I already keep online. WebSocket connections have to come from an allowed origin, and one IP address can hold at most 20 at a time.
11Offline, and surviving my own deploys
A service worker now precaches the app shell and keeps the engine in its own cache, so after one visit you can play the computer offline. Getting there broke three things. The engine's URL depended on a fragment that the service worker dropped, so the engine moved to a versioned folder. The service worker also cached every room link as its own page until I switched it to cache pages by path. The third bug showed up on every deploy. The new service worker deleted the previous build's cache while open tabs were still running that build.
/**
* How many previous builds' app caches survive an update (CR2-8). The new
* service worker takes over open tabs at once (`skipWaiting` + `claim`), and a
* tab still running an older build lazily loads that build's content-hashed
* chunks — which the server stops serving after a deploy. Keeping the last
* couple of builds' caches (and looking chunks up in every cache) lets those
* tabs keep working until they're reloaded.
*/
export const PREVIOUS_BUILDS_KEPT = 2;
// ...
/**
* Caches to delete on activate: everything but the current app cache, the
* engine cache and the `keep` most recent previous app caches. `keys` is in
* `caches.keys()` order, which is creation order (oldest first).
*/
export function staleCaches(
keys: string[],
current: string,
keep: number = PREVIOUS_BUILDS_KEPT
): string[] {
const others = keys.filter((key) => key !== current && key !== ENGINE_CACHE);
const previousBuilds = others.filter((key) => key.startsWith(APP_CACHE_PREFIX));
const kept = new Set(keep > 0 ? previousBuilds.slice(-keep) : []);
return others.filter((key) => !kept.has(key));
}12The small things that make it feel finished
A lot of the work went into details you notice only when they fail. Against the computer, undo takes back one move if the engine is still thinking and two if it already replied, so it always lands on your turn. The old version always took back two. Undoing mid-search could hand the engine your side, or apply its answer to a position that no longer existed. The game also has a hint arrow, PGN export, keyboard move entry, draw offers, rematches that swap colors, and audio cues for moves, captures, castling, and check. None is difficult alone. Together they move the project past a board that merely works.
/**
* Take back the player's last move: one ply if the AI is still thinking about
* its reply, two plies (AI reply + player move) otherwise. Always lands on the
* player's turn — or, if the history runs out before that, restarts the AI's
* search so the game can't stall (audit SM-2.1).
*/
undoMove() {
if (!this.canUndo()) return;
this.engine.stop();
this.hintToken++;
let history = this.snapshot().moveHistory;
while (history.length > 0) {
this.core.undo();
history = history.slice(0, -1);
if (this.core.turn() === this.player) break;
}
this.patch({ moveHistory: history, hint: null, hintPending: false, thinking: false });
this.updateGameState();
this.syncEnginePosition();
this.triggerAiMove();
}13The code I trusted
Stalemates dragged me through a stack I do not touch day to day and a problem I had mostly only read about, real-time game state. The authoritative server, the reconnection handling, and the difficulty curves are the parts I am proudest of, because they are the parts that only matter once you treat the game as something real people will sit down and play.
Object-oriented structure turned out not to be gospel. Here it was a frame, one small base model that lets two different modes share a board, with the rules pushed into a plain class that has its own tests. The Cloudflare detour taught me to distrust the fancier option by default, because the boring server I understood shipped the feature faster than the clever one I kept fighting. But the audit is the one I think about. One pass has turned into six, and the later rounds still found real bugs. The cleanup that cleared expired seats out of localStorage was also deleting your saved AI game, your sound setting, and your board theme every time you joined a room. The worst bugs were not in the code I found hard. They were in the code I had trusted without looking.
The board is still on. Accounts, a game history that lives somewhere other than your browser, and post-game analysis are the obvious next moves, and they are on the list. For now it is live, so go play a game, and if something breaks, I want to hear about it.



