Perfect Pair Blackjack: building a casino game in one HTML file
Perfect Pair Blackjack is a free-to-play blackjack table with two side bets, Perfect Pairs and 21+3. It started as a university project in Unity and C#, became a native SwiftUI app, and is now a web game.
The web version has some deliberate constraints:
- One file. The whole game is
index.html: markup, styles and about 1,100 lines of JavaScript. - No framework and no build step. The file in the repo is the file the browser runs.
- No server. GitHub Pages serves static files, and the player’s chip balance lives in
localStorageon their own device.
This article walks through how it fits together.
Architecture: one state object, one render function
Most of the structure comes from the SwiftUI version, where a view model holds the state and the view redraws from it. Without SwiftUI, the same idea becomes a loop: input calls an action, the action changes a single state object, and render() brings the DOM back in line with that state.
S. Actions never touch the DOM directly; they change state and call render(). The rules are pure functions over cards, so they're easy to reason about and test in isolation.The state is a plain object. Every field the UI depends on lives here, from the current phase to which toast is showing:
const S = {
phase: 'betting', hands: [newHand()], dealer: newHand(), balance: savedBal > 0 ? savedBal : 500,
idx: 0, message: 'Place your bets', results: {}, showInsurance: false,
luckyRank: 14, ppStreak: 0, history: [], round: 1, lastBets: [], chipHistory: [],
selectedChip: 5, /* …toasts, sheets, animation flags… */
};
Input is handled by a single delegated listener. Every interactive element carries a data-act attribute, and one switch maps it to an action, so there are no per-element event handlers to wire up or clean up when the DOM changes:
document.addEventListener('click', e => {
const t = e.target.closest('[data-act]'); if (!t) return;
switch (t.dataset.act) {
case 'hit': return requestHit();
case 'stand': return stand();
case 'double': return doubleDown();
case 'split': return requestSplit();
case 'deal': return deal();
// …
}
});
Cards and the shoe
A card is { id, suit, rank, faceUp }, with ranks stored as 2–14 (Ace high) to match the Rank enum’s raw values in the Swift version. The shoe builds six decks and shuffles them with Fisher–Yates, which gives every ordering equal probability:
reset() {
this.cards = [];
for (let d = 0; d < this.deckCount; d++)
for (let s = 0; s < 4; s++)
for (const r of RANKS) this.cards.push(mkCard(s, r));
for (let i = this.cards.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this.cards[i], this.cards[j]] = [this.cards[j], this.cards[i]];
}
}
When fewer than 52 cards remain, the shoe reshuffles before the next deal. The shoe also has a forced queue: push specific cards onto it and deal() returns those first. That’s what makes it possible to test rare situations, like a Perfect Pair on the lucky rank, without waiting thousands of hands for one to come up.
Soft hands and the Ace problem
An Ace counts as 1 or 11, so a hand doesn’t have one value; it has a set of possible values. Rather than special-casing “how many Aces are there?”, allValues branches on every Ace and lets the totals fan out:
function allValues(h) {
let vals = [0];
for (const c of h.cards) {
const next = [];
for (const v of vals) {
if (c.rank === 14) next.push(v + 1, v + 11);
else next.push(v + rankValue(c.rank));
}
vals = next;
}
return vals;
}
function bestValue(h) {
const a = allValues(h), ok = a.filter(v => v <= 21);
return ok.length ? Math.max(...ok) : Math.min(...a);
}
The set grows as 2ⁿ for n Aces, which sounds alarming until you remember a hand rarely holds more than three or four Aces. Being soft then falls out naturally: a hand is soft if its best total is higher than its total with every Ace counted as 1. That one check drives both the dealer’s soft-17 rule and the strategy hints.
A round is a state machine
Every round moves through a fixed set of phases, and each action starts by checking the phase it’s allowed in. That one guard stops a whole class of bugs, such as hitting during the dealer’s turn or placing a bet mid-hand.
hit() returns early unless the phase is playerTurn, addBet() only works in betting, and so on. Insurance is the only optional phase.The flow itself is written as async functions. Dealing is a loop that pushes a card, re-renders, and awaits a short pause, so the pacing reads top to bottom instead of being spread across timers and callbacks:
async function deal() {
if (!canDeal() || S.phase !== 'betting') return;
S.phase = 'dealing';
const step = async (target, up) => {
target.cards.push(shoe.deal(up)); play('card'); render();
await sleep(settings.anim ? speed(700) : speed(350));
};
for (const h of S.hands) await step(h, true); // first card to each hand
await step(S.dealer, true); // dealer up card
for (const h of S.hands) await step(h, true); // second card to each hand
await step(S.dealer, false); // dealer hole card, face down
await waitForReveal();
await postDealChecks();
}
Two small guards keep it robust. A busy flag blocks the buttons while a card is still landing, so a fast double-tap can’t hit twice. And waitForReveal() resolves only when every card-flip animation has finished, so totals and outcomes never get ahead of what the player can see.
The dealer
The dealer plays a fixed rule: draw below 17, and also draw on soft 17 (the “H17” rule). With bestValue and isSoft in place, that’s a one-line loop condition:
while (bestValue(S.dealer) < 17 || (bestValue(S.dealer) === 17 && isSoft(S.dealer))) {
await sleep(speed(450));
S.dealer.cards.push(shoe.deal(true)); play('card'); render();
await waitForReveal();
}
The dealer skips drawing altogether if every player hand has busted, surrendered or hit blackjack, since there’s nothing left to beat. Settlement then compares each hand in order: bust, blackjack (paid 3:2), dealer blackjack, dealer bust, higher total, tie. Insurance pays 2:1, which also makes “even money” on a blackjack work without special-casing it.
Side bets: Perfect Pairs and 21+3
Both side bets depend only on the first cards dealt, so they’re evaluated straight after the deal rather than at the end of the round. Winning side bets pay out immediately, and the result is locked onto the hand so a later split can’t change it.
Both evaluators are small, pure functions, which makes the payout tables easy to check against the rules pages:
function ppResult(h) {
if (h.cards.length < 2) return 'none';
const [a, b] = h.cards; if (a.rank !== b.rank) return 'none';
if (a.suit === b.suit) return 'perfect';
if (SUITS[a.suit].red === SUITS[b.suit].red) return 'coloured';
return 'mixed';
}
function evaluate21Plus3(c1, c2, d) {
const cs = [c1, c2, d];
const same = cs.every(c => c.suit === cs[0].suit);
if (c1.rank === c2.rank && c2.rank === d.rank && same) return 'suitedTrips';
if (c1.rank === c2.rank && c2.rank === d.rank) return 'threeOfAKind';
const consec = v => { const s = [...v].sort((a, b) => a - b); return s[2] - s[1] === 1 && s[1] - s[0] === 1; };
const straight = consec(cs.map(c => c.rank)) || consec(cs.map(c => c.rank === 14 ? 1 : c.rank));
if (same && straight) return 'straightFlush';
if (straight) return 'straight';
if (same) return 'flush';
return 'none';
}
The straight check runs twice, once with the Ace high (Q-K-A) and once with it low (A-2-3), so both ends of the deck count.
Two extras sit on top of Perfect Pairs. Each round picks a lucky rank, and a Perfect Pair of that rank pays an extra 500:1. Back-to-back Perfect Pairs also build a streak bonus that grows by 50 chips for each consecutive hit.
Drag-to-bet without a framework
In the SwiftUI app, chips are dragged onto betting spots using DragGesture, with each drop zone reporting its frame through a PreferenceKey. The web version gets the same result from two things the browser already provides: pointer events and document.elementFromPoint.
Every betting spot is marked with a data-drop attribute naming the bet type (bet, pp or t21). While dragging, a “ghost” chip follows the pointer, and the code asks the browser what’s under it:
const targetAt = (x, y) => {
const el = document.elementFromPoint(x, y);
return el && el.closest('[data-drop]');
};
There’s no layout bookkeeping: the browser already knows where everything is. Pointer capture keeps the drag tracking even when the finger leaves the chip, and a 6-pixel threshold separates a tap (select this chip) from a drag (place this chip). Pointer events also mean the same code handles mouse, touch and pen.
Rendering without a virtual DOM
Re-creating the whole table on every render() would restart every card animation. Instead, cards are reconciled by id: existing card elements are kept and repositioned, new ones are created and flipped in, and removed ones are deleted. It’s the same idea as React’s key prop, in about twenty lines.
For everything else, a tiny setHTML helper caches the last HTML string written to each element and skips the write if nothing changed. That keeps render() cheap enough to call after every state change without thinking about it.
Hosting and persistence
The deployment story is deliberately boring. The repo’s main branch is served by GitHub Pages, and a custom domain points at it. Pushing a commit is the entire release process, and a fix is live in about a minute.
Persistence is a small wrapper around localStorage that never throws. Private browsing, full storage and blocked cookies all fall back to defaults instead of crashing the game:
const store = {
get(k, d) { try { const v = localStorage.getItem(k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } },
set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} }
};
The balance is written back inside render() whenever it changes, so there’s no “save” moment to forget.
What I’d change next
- Split the file into ES modules. One file was the right call to get it shipped, but the pure rules (
allValues,ppResult,evaluate21Plus3, the strategy table) deserve their own module. - Unit-test the rules. Because they’re pure functions, a table-driven test of every side-bet outcome and payout would be cheap and would lock down the maths.
- A seeded random generator. Replacing
Math.random()with a seeded RNG would make whole rounds reproducible, which is useful for bug reports and for replaying a hand.
You can play the game or browse the source on GitHub.