How this Spider Solitaire is built in TypeScript
By Spider Solitaire Online Editorial Team · Published
The game is a pure TypeScript engine with no DOM, clock or Math.random, so every deal is a seed and every move is replayable. Moves return a reversible delta, which makes undo an exact inverse that tests check.
This page describes how the game on this site is built, for people who want to write their own Spider Solitaire or just see how a small, carefully tested game engine fits together. It is a description of our own code, not a tutorial for a particular framework, and the snippets are quoted from the project. The aim is a design in which the rules can be tested without a browser, every game can be replayed exactly, and mistakes in the interface cannot corrupt the game.
The central decision: a pure engine
All of the rules live in a set of TypeScript modules that know nothing about the page. They do not touch the DOM, read the clock or call a random-number function. The header of the types file states the contract:
/**
* Core types for the pure Spider engine. No DOM, no Date.now(), no Math.random().
* Cards and states are treated as immutable values: every engine function returns
* new objects (columns are copied on write, unchanged columns are shared).
*/
That contract pays for itself many times. Because nothing in the engine depends on the environment, the same code runs in the browser, in the Node test runner, and in the offline scripts that certify deals and run our experiments. A bug in the rules can be reproduced by a test that needs no browser. And a game state is a plain value you can serialise, hash and compare.
Modelling the game
A card is a small immutable record:
export interface Card {
readonly id: number; // unique within a deal, stable across moves
readonly suit: Suit;
readonly rank: Rank;
readonly up: boolean;
}
A game state holds the columns (arrays of cards, bottom to top), the stock, the completed runs, the move count, the score and the number of hints used, plus the rules it was started with. Every variant on the site, from one-suit to Spiderette to expert mode, is a configuration object with fields such as the number of decks, the number of columns, the size of each stock deal, whether undo is allowed and how scoring works. The engine reads the configuration and has no special cases by name. Adding a variant is therefore mostly a matter of writing a new configuration, which is how we built two extra variants that the site does not yet route.
Moves are a two-case union: a tableau move with a source column, a destination column and a card count, or a deal. Nothing else can change a game.
Determinism: seeds, not randomness
A game begins from a seed. The engine builds the unshuffled deck for the rules, then reorders it with a Fisher–Yates shuffle driven by a small seeded generator. Here is the whole generator:
export function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
It uses only 32-bit integer arithmetic, so it produces the same sequence in every JavaScript engine. The seed is the only source of randomness in a game; where an actual random seed is needed, the interface layer asks the browser's cryptographic source for one and hands it to the engine. Two consequences follow. A deal is identified by a short code (the suit count and the seed), which lets players share and replay games. And a saved game is just a seed plus a list of moves, which matters for the next section.
The rules in a few lines
The central rule is what can be picked up. Starting at the top of a column, count the face-up cards that form a descending run of one suit:
export function runLength(col: readonly Card[], anySuit = false): number {
let n = 0;
for (let i = col.length - 1; i >= 0; i--) {
const c = col[i] as Card;
if (!c.up) break;
if (n > 0) {
const above = col[i + 1] as Card;
if ((!anySuit && c.suit !== above.suit) || c.rank !== above.rank + 1) break;
}
n++;
}
return n;
}
A move is legal when the requested number of cards is no more than that run length and the destination is empty or its top card is exactly one rank higher. The function that checks this returns a reason string instead of throwing, so the interface can explain a refusal and the tests can assert on the reason. The optional anySuit argument is how a variant in which any descending run may move is expressed, with no change to the rest of the engine.
Applying a move and undoing it
Applying a move copies the columns it touches, makes the change, flips the newly exposed card if it was face down, and checks whether a complete King-to-Ace run has formed. It returns the new state and a record of what happened:
export interface Delta {
readonly move: Move;
readonly flippedSource: boolean;
readonly removals: readonly Removal[];
readonly movesBefore: number;
readonly scoreBefore: number;
}
The delta is everything undo needs. It is smaller than a copy of the whole state, and undo is its exact inverse: it puts back removed runs, un-flips cards that were flipped, and moves the cards back. The undo function takes the state produced by the move and the delta and returns the earlier state. An automated test checks the identity on many positions: apply a move, undo it, and compare a compact string describing the position. Treating undo as a pure inverse, and testing it as one, is what makes unlimited undo safe.
Saving and resuming
A saved game is stored in the browser as a small JSON object: the variant, suit count, seed, every card with its face-up flag, the stock, the completed runs, and an optional compact list of the moves played so far. Loading a save does not trust it. The loader checks that every field has the right type and range, that the cards form a valid deck, and that the numbers add up. If anything is off, it returns nothing and the game starts fresh instead of crashing on corrupt data.
The move list lets undo history survive a reload. On resume, the game replays the saved moves from the seed and compares the result with the saved position. If they match, the undo history is rebuilt from the replay. If they do not, the game resumes without history. In neither case can a wrong undo occur. Moves are encoded compactly, three characters each, with a deal written as a fixed marker.
Layers around the engine
The engine is the middle of three layers.
- The controller holds the undo and redo stacks, the timer, the hint count and persistence. It has no DOM either, and is tested directly.
- The renderer turns a state into DOM elements. It keeps one element per card and animates changes using the technique called FLIP: record where each card is, apply the new state, measure where it has moved to, and animate the difference. Cards are placed with transforms so animation does not trigger layout.
- The input layer handles pointer dragging, tap-to-select and the keyboard map. It asks the controller to make a move and reacts to the refusal reason. Every action available by dragging is also available by tapping and by keyboard.
Keeping these separate means an interface bug cannot break the rules, and a rules bug cannot hide behind an animation.
The hint and the solver reuse the engine
Both the in-game hint and the offline solver are built from the same legal-move generator and move function as the interface. The hint scores the legal moves using only face-up cards and looks a few moves ahead (see how the hint works). The solver, which sees every card, searches for a complete win, and every solution it finds is replayed through the engine before it is stored (see how deals are certified). Because the engine is the single authority on the rules, neither component can disagree with the game about what is legal.
Testing
The project has about 175 automated tests that run in seconds without a browser, using Node's built-in test runner. The engine tests fall into a few kinds, and each kind catches a different sort of mistake.
- Hand-checked fixtures. Small positions built by hand check individual rules: that a same-suit run moves onto a card one rank higher, that a mixed-suit sequence moves only as far as its same-suit run, that face-down cards never move, that a completed King-to-Ace run is removed and scores 100, and that a mixed-suit sequence is not removed.
- Composition checks. For each suit count, a test confirms the deal has 104 cards, columns of six and five, and a stock of 50.
- Golden fixtures. A file of known deals, generated by our own script, locks the shuffle so that a change across Node versions or platforms would be noticed. It guards against drift. It cannot prove the original shuffle was correct, which is why the distribution is also checked statistically (see card probabilities).
- An environment-free guard. One test reads the source of the core and fails if it contains a call to the random-number function, the clock or the performance timer. The promise that the engine is pure is enforced, not just stated.
- Inverse tests. Undo composed with a move must equal the starting position, for a plain move, a reveal, a run removal and a stock deal, including a deal that completes several runs at once.
- Property tests. Random legal walks, 25 seeds of 400 steps for each suit count, check that every position stays valid and that the whole walk can be undone back to the start.
- Hint tests. The hint must prefer completing a run, then revealing, then same-suit builds; must not split a run to make a mixed move; and must never return an illegal move or change the state it is given.
- Persistence tests. A mid-game position round-trips through a save, and corrupt, old-version or tampered saves return nothing instead of throwing.
Separate tests replay every stored certified solution against the current engine. A browser-driven suite then drives the real page with a headless browser, covering dragging, tapping, keyboard play, undo, saving and the dialogs. We keep the browser tests few and the engine tests many, because the engine is where mistakes are cheapest to find.
Size and cost
The game's JavaScript is 58.2 KB before compression and 20.2 KB compressed, covering the engine, hint, renderer, input and interface. It loads only on game pages; the guides and trust pages ship no JavaScript at all. The pure core is small: the rules, dealing, serialisation, move encoding and run-finishing together are a few hundred lines. Those figures are from our own production build.
Things that surprised us
- The hint's weights became experiment inputs. They started as constants. When we wanted to ask what each one was worth, we added an optional argument that overrides them for a single call, leaving normal play unchanged. If we were starting again we would have treated them as data from the beginning.
- Equal-looking positions are not equal. The compact position string we use for undo tests and for the solver's table covers the columns, face-up flags, stock size and completed runs. Choosing what belongs in that identity took more care than we expected, and the solver's table uses an even lossier hash, which is safe only because every solution is replayed before it is trusted.
- Pure logic does not make the interface easy. Most of the bugs we hit were in the interface layers: stale cached card elements when the suit count changed, clicks landing on the wrong card because of overlap, and keyboard focus escaping a dialog. The engine tests did their job by ruling the rules out quickly.
- Rules from other games need named sources. The Spiderette rules were provisional until we checked them against published descriptions and recorded them, and the configuration said so in its header comment while they were. A comment that marks an assumption is cheap, and it keeps the assumption from hardening into a fact.
Where to look
The rules are described in plain language on the rules page, and the numbers that come out of the engine are in the win rates and probabilities guides. The accessibility guide covers the interface layer in more detail.