Designing a Deterministic Solitaire Rules Engine in TypeScript
A reliable solitaire implementation starts with a precise answer to how to play solitaire, then turns that answer into data structures, legal transitions, and repeatable tests. The visual table is only a projection of the game state. If the rules live inside button handlers or drag-and-drop callbacks, edge cases become difficult to reproduce and even harder to test.
This guide focuses on a deterministic rules engine for a Klondike-style solitaire variant. The same architecture can support other patience card games, but the rules should remain explicit rather than hidden behind generic UI code.
Define the State as Data, Not UI
The first design decision is to represent every meaningful part of the game as plain data. The engine should not know whether a card is rendered in HTML, drawn on a canvas, or displayed in a native application.
A useful card model contains immutable identity and rule-relevant properties:
type Suit = "clubs" | "diamonds" | "hearts" | "spades";
type Rank = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13;
type Card = Readonly<{
id: string;
suit: Suit;
rank: Rank;
faceUp: boolean;
}>;
The id should be stable for the lifetime of a game. A card can change from face down to face up, but its identity must not change. Stable identities make replay logs, debugging, and serialisation more dependable.
The board can then be modelled without any UI references:
type GameState = Readonly<{
tableau: readonly (readonly Card[])[];
stock: readonly Card[];
waste: readonly Card[];
foundations: Readonly<Record<Suit, readonly Card[]>>;
moveNumber: number;
}>;
There are several advantages to this approach:
- A state can be compared in tests without rendering a screen.
- A move can be applied on a server or in a browser.
- Replays can store actions instead of screenshots.
- Solvers can inspect possible moves using the same rules as the player.
- Bugs can be reduced to a state and one action.
The state should describe facts, not possibilities. For example, it should record that a card is face up, but not store canMoveCard: true. That value is derived from the current state and can become stale.
A reducer-style API keeps transitions centralised:
type Move =
| Readonly<{ type: "draw-stock" }>
| Readonly<{ type: "recycle-waste" }>
| Readonly<{ type: "move-waste-to-tableau"; target: number }>
| Readonly<{
type: "move-tableau-to-tableau";
source: number;
cardIndex: number;
target: number;
}>
| Readonly<{
type: "move-tableau-to-foundation";
source: number;
}>
| Readonly<{
type: "move-waste-to-foundation";
}>;
type MoveResult =
| Readonly<{ ok: true; state: GameState }>
| Readonly<{ ok: false; reason: string }>;
The UI can dispatch a Move, but it cannot mutate the tableau directly. This boundary prevents a common class of bugs where a card appears to move visually even though the underlying state rejects the action.
A helpful rule is that every public engine operation should be deterministic:
function applyMove(state: GameState, move: Move): MoveResult {
// Validate the action, create a new state, or return a reason.
return { ok: false, reason: "Not implemented" };
}
Returning a new state rather than mutating the old one is particularly useful for undo, replay, and debugging. Structural sharing can later reduce allocation costs if profiling shows that it is necessary.
A Move Algebra for Tableau, Stock, and Foundation
The rules become easier to maintain when moves are treated as a small algebra of state transitions. Each move type should answer three questions:
- Is this action structurally well formed?
- Is it legal in the current state?
- What exact state does it produce?
For a basic tableau move, the moving sequence must begin at a face-up card. Each following card must alternate colour and descend by one rank. A King may begin an empty tableau column in the common rule set.
These rules should be expressed as functions rather than scattered conditions:
function isRed(card: Card): boolean {
return card.suit === "diamonds" || card.suit === "hearts";
}
function canPlaceOnTableau(moving: Card, target: Card | undefined): boolean {
if (!target) {
return moving.rank === 13;
}
return (
isRed(moving) !== isRed(target) &&
moving.rank + 1 === target.rank
);
}
function isValidTableauRun(cards: readonly Card[]): boolean {
if (cards.length === 0 || cards.some(card => !card.faceUp)) {
return false;
}
for (let index = 1; index < cards.length; index += 1) {
const previous = cards[index - 1];
const current = cards[index];
if (!canPlaceOnTableau(current, previous)) {
return false;
}
}
return true;
}
Notice that canPlaceOnTableau is used in both directions. A card can be placed on a target when the moving card is one rank lower and has the opposite colour. The same predicate also checks adjacent cards inside a moving run.
Foundation rules are different. Each suit has its own ascending pile, beginning with an Ace:
function canPlaceOnFoundation(
card: Card,
foundation: readonly Card[]
): boolean {
const top = foundation.at(-1);
if (!top) {
return card.rank === 1;
}
return top.suit === card.suit && card.rank === top.rank + 1;
}
Stock and waste moves should also be explicit. Drawing from the stock removes a card from one collection and appends it to the waste. Recycling the waste should only be legal when the stock is empty, and its exact behaviour depends on whether the variant allows unlimited passes or imposes a pass limit.
This is where an implementation can diverge from a written solitaire rules guide. A content page such as solitaire setup instructions may describe the initial layout, but the engine still needs a formal policy for stock recycling, draw count, and redeals.
Avoid a generic moveCard(source, destination) method. It hides important differences between moving a tableau run, moving a waste card, and adding a card to a foundation. A discriminated union gives each action a clear contract and allows TypeScript to narrow the relevant fields.
TypeScript Validation at the Rules Boundary
TypeScript can make invalid move representations difficult to construct, but types alone cannot prove that a move is legal for a particular state. Runtime validation remains necessary at the engine boundary.
A useful pattern is to separate structural validation from rule validation:
function isTableauIndex(value: number, state: GameState): boolean {
return Number.isInteger(value) &&
value >= 0 &&
value < state.tableau.length;
}
function validateTableauMove(
state: GameState,
move: Extract<Move, { type: "move-tableau-to-tableau" }>
): string | null {
if (!isTableauIndex(move.source, state)) {
return "Invalid source column";
}
if (!isTableauIndex(move.target, state)) {
return "Invalid target column";
}
if (move.source === move.target) {
return "Source and target must differ";
}
const sourceColumn = state.tableau[move.source];
if (
!Number.isInteger(move.cardIndex) ||
move.cardIndex < 0 ||
move.cardIndex >= sourceColumn.length
) {
return "Invalid card index";
}
const movingCards = sourceColumn.slice(move.cardIndex);
if (!isValidTableauRun(movingCards)) {
return "Cards do not form a legal run";
}
const targetColumn = state.tableau[move.target];
const targetCard = targetColumn.at(-1);
if (!canPlaceOnTableau(movingCards[0], targetCard)) {
return "Run cannot be placed on target";
}
return null;
}
The function returns a reason rather than throwing for an expected illegal action. Exceptions are better reserved for programmer errors, such as a corrupted state that violates an internal invariant.
The TypeScript narrowing model is valuable here because each move variant exposes only the fields relevant to that action. The official TypeScript narrowing handbook documents the control-flow techniques behind this approach.
State invariants should be checked at development boundaries:
- Every card identifier appears exactly once across tableau, stock, waste, and foundations.
- Foundation cards are ordered by suit and rank.
- Face-down cards do not appear inside a face-up run.
- The number of tableau columns remains constant.
-
moveNumbernever decreases during normal play. - No collection contains the same card object identity twice.
A assertValidState function can run after every move in tests and development builds. It may be too expensive for a production release, but it is one of the fastest ways to identify the first operation that corrupts state.
The reducer should validate before constructing a new state:
function reduce(state: GameState, move: Move): MoveResult {
switch (move.type) {
case "move-tableau-to-tableau": {
const error = validateTableauMove(state, move);
if (error) {
return { ok: false, reason: error };
}
return {
ok: true,
state: moveTableauRun(state, move),
};
}
default:
return { ok: false, reason: "Move type not implemented" };
}
}
This creates one authoritative rules boundary. Drag-and-drop, keyboard controls, automated solvers, and replay playback all use the same validation path.
Property-Based Tests for Legal and Illegal Deals
Example-based tests are useful for named scenarios, but card engines benefit greatly from property-based testing. Instead of checking one manually written board, generate many valid states and assert that important rules always hold.
A basic property is card conservation. Starting from a complete deck, every legal operation should preserve the set of card IDs:
function collectCardIds(state: GameState): string[] {
return [
...state.tableau.flat().map(card => card.id),
...state.stock.map(card => card.id),
...state.waste.map(card => card.id),
...Object.values(state.foundations).flat().map(card => card.id),
];
}
The sorted result before and after a move should be identical. This catches accidental duplication, dropped cards, and incorrect slice boundaries.
Other useful properties include:
- An illegal tableau run is never accepted.
- A face-down card cannot be moved directly.
- A foundation never contains two suits.
- Foundation ranks increase by exactly one.
- An empty tableau accepts only the configured starting rank.
- Applying a rejected move leaves the state unchanged.
- Serialising and restoring a state produces an equivalent state.
- Replaying the same action sequence from the same seed produces the same final state.
Generated deals should distinguish between valid random input and intentionally corrupted input. If a test generator creates impossible states, the failure may only prove that the generator is invalid.
One practical strategy is to generate a shuffled deck, split it into zones, then apply controlled transformations. For example, a generator can construct legal tableau columns by placing face-down prefixes below face-up runs, while a separate generator can introduce one violation such as a same-colour adjacency.
Tests should also cover the boundary between legal and illegal actions:
it("rejects a same-colour tableau placement", () => {
const moving = card("hearts", 8);
const target = card("diamonds", 9);
expect(canPlaceOnTableau(moving, target)).toBe(false);
});
For a full property-based test suite, a library such as fast-check can generate ranks, suits, moves, and state fragments. The important design choice is not the testing library. It is writing properties that describe the engine’s guarantees rather than repeating implementation details.
A rules engine should also test the starting position. The initial deal is not just a visual arrangement. It is a contract about how many cards each tableau column receives, which cards are exposed, and where the undealt cards go. A card-game explanation such as how solitaire is played with cards can provide player-facing terminology, while tests should encode the machine-readable version of those rules.
Deterministic Seeds, Replay Logs, and Debugging
Randomness should enter the system at one controlled point. Do not call Math.random() while constructing individual moves or deciding whether a UI action succeeds. Instead, create a seeded shuffle and store the seed with the initial configuration.
A simple pseudo-random generator is enough for deterministic development tests:
function mulberry32(seed: number): () => number {
return () => {
let value = (seed += 0x6d2b79f5);
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
function shuffle<T>(items: readonly T[], seed: number): T[] {
const random = mulberry32(seed);
const result = [...items];
for (let index = result.length - 1; index > 0; index -= 1) {
const target = Math.floor(random() * (index + 1));
[result[index], result[target]] = [result[target], result[index]];
}
return result;
}
The exact generator is less important than keeping it stable. Changing the algorithm changes every deal associated with a seed, which can make old bug reports impossible to reproduce.
A replay should contain enough information to rebuild the session:
type Replay = Readonly<{
version: 1;
seed: number;
moves: readonly Move[];
}>;
The engine can then rebuild a game by creating the initial state from seed and applying each move in order. If a move is rejected during replay, the log is invalid or the rules version has changed.
For debugging, record the first failing move number, the action, and a serialised state before that action. This is more useful than logging every DOM event. A compact replay also makes regression tests easy to keep in the repository.
Versioning matters when rules evolve. If a later release changes stock recycling, a replay created under the old rules should not silently run under the new rules. Add a ruleset identifier or replay version before storing logs outside the current process.
Complexity Limits and Serialization Contracts
Solitaire is small enough that a straightforward implementation performs well, but careless copying can still make automated analysis expensive. A move validator should inspect only the relevant columns and piles. Moving a tableau run should not require scanning every card in the game unless an invariant check is enabled.
For normal interaction, the cost of validating a tableau move is proportional to the length of the proposed run. Foundation and stock checks are constant-time apart from copying the affected arrays. Full state validation is more expensive, so it is best treated as a development and testing tool.
A useful measurement should be part of the engine’s test or benchmark suite rather than a guess about how fast every browser will run it. For a seven-card face-up run, isValidTableauRun performs exactly six adjacent-card checks per call. Running the validator 10,000 times therefore exercises 60,000 adjacency checks, in addition to the initial face-up check and loop overhead.
The following browser-compatible harness records the actual elapsed time on the machine where it runs:
type BenchmarkResult = Readonly<{
name: string;
iterations: number;
elapsedMs: number;
microsecondsPerOperation: number;
}>;
function benchmark(
name: string,
operation: () => void,
iterations = 10_000,
): BenchmarkResult {
for (let index = 0; index < 1_000; index += 1) {
operation();
}
const start = performance.now();
for (let index = 0; index < iterations; index += 1) {
operation();
}
const elapsedMs = performance.now() - start;
return {
name,
iterations,
elapsedMs,
microsecondsPerOperation: (elapsedMs * 1_000) / iterations,
};
}
const sampleRun: readonly Card[] = [
{ id: "c-13", suit: "clubs", rank: 13, faceUp: true },
{ id: "h-12", suit: "hearts", rank: 12, faceUp: true },
{ id: "c-11", suit: "clubs", rank: 11, faceUp: true },
{ id: "h-10", suit: "hearts", rank: 10, faceUp: true },
{ id: "c-9", suit: "clubs", rank: 9, faceUp: true },
{ id: "h-8", suit: "hearts", rank: 8, faceUp: true },
{ id: "c-7", suit: "clubs", rank: 7, faceUp: true },
];
console.table([
benchmark("seven-card tableau validation", () => {
isValidTableauRun(sampleRun);
}),
]);
The result reports total milliseconds and microseconds per validation for the fixed workload. Record the output with the runtime, browser, and device when comparing implementations; a timing without that context is not a portable performance claim. The same harness can compare a copying reducer with a structurally shared version, or measure invariant checks separately from normal move validation.
Serialisation should be explicit and versioned:
type SerializedState = Readonly<{
version: 1;
tableau: readonly (readonly Card[])[];
stock: readonly Card[];
waste: readonly Card[];
foundations: Readonly<Record<Suit, readonly Card[]>>;
moveNumber: number;
}>;
Do not serialise class instances, closures, DOM references, or derived caches. Plain JSON-compatible data is easier to persist, inspect, migrate, and send between a browser worker and the main thread.
Card ordering must also be part of the contract. The first item in a tableau array should have one defined meaning, and the top of a pile should always be retrieved using the same convention. Ambiguous ordering creates subtle errors when restoring a saved session.
If a solver is added later, keep it as a consumer of the same immutable state and move algebra. The solver should not receive private mutation methods or bypass validation. This prevents the automated path from exploring positions that a player could never reach.
A deterministic rules engine is successful when the UI becomes replaceable. A browser build, a command-line simulator, a replay viewer, and a test runner should all produce the same result from the same seed and move sequence. That consistency is more valuable than any individual rendering technique because it gives the project a dependable foundation for new variants, accessibility controls, automated analysis, and future rule changes.
This article was created with the help of AI and reviewed by the author.

Top comments (0)