Skip to content

Texas Hold'em: private hands and side pots

What you'll build

  • A Hold'em table for 2 to 9 players
  • Private hands that only their owner can see
  • Betting rounds, side pots and a showdown

Time: 60 minutesFinished code: examples/holdem

This tutorial assumes you finished blackjack, so hidden cards, phases, turn timers and the wallet are not explained again. Hold'em adds three things: many hands that stay private until a showdown, betting rules that must be exact, and pots that split when players are all-in. The full code is in examples/holdem/src/game.ts.

The game is a no-limit cash game. The options are validated by a zod schema, so a table with bigBlind: 5 and smallBlind: 10 fails with INVALID_OPTIONS before it exists.

src/game.ts
const optionsSchema = z
.object({
smallBlind: z.number().int().positive().default(5),
bigBlind: z.number().int().positive().default(10),
buyIn: z.number().int().positive().default(200),
turnMs: z.number().int().positive().default(30_000),
})
.refine((o) => o.bigBlind >= o.smallBlind, {
message: 'bigBlind must be at least smallBlind',
path: ['bigBlind'],
})
.refine((o) => o.buyIn >= o.bigBlind, {
message: 'buyIn must be at least bigBlind',
path: ['buyIn'],
});
export type HoldemOptions = z.output<typeof optionsSchema>;

Each seat keeps its own cards and chips. The state holds the pieces of the hand that are never sent anywhere, such as deck.

src/game.ts
export interface SeatState {
stack: number;
hole: Card[];
/** Dealt into the current hand. */
inHand: boolean;
folded: boolean;
/** Chips put in on this street. */
bet: number;
/** Chips put in this hand (including `bet`); the pot is the sum over seats. */
total: number;
/** Acted since the last full raise on this street. */
acted: boolean;
/** Hole cards revealed at showdown. */
shown: boolean;
}

bet is what a seat has put in on this street and total is what it has put in this hand. Everything the pot needs is derived from total, so there is no separate pot counter to keep in step.

startHand moves the button, posts the blinds, shuffles with ctx.random and deals two cards to each seat, starting at the small blind. Heads-up, the button is the small blind. Then it calls ctx.phase.go('preflop').

state.deck = ctx.random.shuffle(standardDeck());
const from = dealt.indexOf(state.smallBlind);
for (let round = 0; round < 2; round++) {
for (let i = 0; i < dealt.length; i++) {
state.seats[dealt[(from + i) % dealt.length]!]!.hole.push(...draw(state.deck, 1));
}
}

Using ctx.random is what makes a hand replayable: the same seed and the same actions give the same cards. The deck is plain state, and the next section is why that is safe.

A viewer sees their own hole cards and nothing else, until a hand reaches showdown. Two helpers from shoehive/cards do the work. seatView shows the real value for the seats the viewer holds and calls your function for every other seat. revealTo(cards, visible) returns the cards, or one null per card when visible is false, so everyone can still count them.

src/game.ts
view: ({ state, viewer }) => {
// Own cards always; other hands only once shown at showdown (spectators hold no seat).
const holes: VisibleCard[][] = seatView(
state.seats.map((p) => p.hole),
viewer,
(hole, seat) => revealTo(hole, state.seats[seat]!.shown),
);
return {
hand: state.hand,
button: state.button,
smallBlind: state.smallBlind,
bigBlind: state.bigBlind,
board: state.board,
pot: state.seats.reduce((sum, p) => sum + p.total, 0),
currentBet: state.currentBet,
minRaiseTo: state.currentBet + state.lastRaise,
seats: state.seats.map((p, seat) => ({
stack: p.stack,
bet: p.bet,
inHand: p.inHand,
folded: p.folded,
allIn: live(p) && p.stack === 0,
hole: holes[seat]!,
})),
last: state.last,
};
},

Three details matter:

  • Spectators hold no seat, so they only ever get the revealTo branch.
  • shown is set at showdown for every hand that was still live. A folded hand stays hidden from everyone but its owner, even after the hand ends.
  • deck is not in the view at all, and neither is anything else you did not list. The view is an allow-list. See hidden information and the security model.

The four betting streets share one set of actions and one turn config. The turn order is computed from state, not stored: turns.first returns the first seat that still has to act, and skip passes over folded and all-in seats.

src/game.ts
/**
* Turns for a betting street: the first seat after `from` that has to act starts. When
* nobody has to act, `onEnter` ends the street at once, so the start does not matter.
*/
function streetTurns(
from: (state: HoldemState) => number,
): TurnsConfig<HoldemState, HoldemOptions> {
return {
order: 'round-robin',
first: ({ state }) => nextToAct(state, from(state)) ?? from(state),
skip: ({ seat, state }) => !canAct(state.seats[seat]!),
timeoutMs: ({ options }) => options.turnMs,
onTimeout: 'timeout',
};
}

timeoutMs reads the turnMs option, so each table can pick its own clock. When it fires, the engine runs the internal timeout action: check if that is legal, otherwise fold. The deadline is in meta.turn.deadline, which clients use to draw a countdown. See timers and turn clocks.

Each street names who starts. Preflop it is the seat after the big blind, later streets the seat after the button. onEnter deals the street's cards and ends the street at once if nobody can bet, which runs the board out when everyone is all-in.

src/game.ts
preflop: {
turns: streetTurns((state) => state.bigBlind),
onEnter: ({ state, ctx }) => {
enterStreet(state, ctx, 0); // blinds may already have put everyone all-in
},
actions: bettingActions,
},
flop: {
turns: streetTurns((state) => state.button),
onEnter: ({ state, ctx }) => {
enterStreet(state, ctx, 3);
},
actions: bettingActions,
},

bet and raise are the same action, and amount is the total the seat's bet becomes for the street ("raise to"), not the increment. That is how players say it and how a UI slider works. It also makes the checks short.

src/game.ts
function raiseTo(state: HoldemState, seat: number, amount: number, ctx: Ctx): void {
const p = myTurn(state, seat, ctx);
const max = p.bet + p.stack;
const min = state.currentBet + state.lastRaise;
if (!mayRaise(state, seat)) reject('RAISE_NOT_ALLOWED');
if (amount > max) reject('NOT_ENOUGH_CHIPS', { max });
if (amount <= state.currentBet || (amount < min && amount < max)) {
reject('RAISE_TOO_SMALL', { min: Math.min(min, max) });
}
const increment = amount - state.currentBet;
put(p, amount - p.bet);
if (increment >= state.lastRaise) {
// A full raise reopens the betting for everyone else.
state.lastRaise = increment;
for (const o of state.seats) o.acted = false;
}
state.currentBet = amount;
p.acted = true;
ctx.emit('action', { seat, action: p.stack === 0 ? 'allIn' : 'raise', to: amount });
advance(state, ctx, seat);
}

A raise must add at least the last full raise (lastRaise), or be exactly all-in. A full raise reopens the betting by clearing acted on every seat. A short all-in does not, so a seat that already acted may only call or fold and gets RAISE_NOT_ALLOWED. reject carries details such as min and max, so the UI can say why. The view's minRaiseTo is the same number, ready for a slider.

When one player is all-in for less, the others keep betting into a side pot the short stack cannot win. splitPots(contributions, folded) turns what each seat put in into pots, main pot first, each with its eligible seats.

import { splitPots } from 'shoehive/cards';
// Seat 0 is all-in for 50, seats 1 and 2 put in 200, seat 3 folded after 20.
const pots = splitPots([50, 200, 200, 20], [false, false, false, true]);
// [{ amount: 170, eligible: [0, 1, 2] }, { amount: 300, eligible: [1, 2] }]

awardPots(pots, scores, { firstSeat }) pays them. scores[seat] is the seat's hand strength, higher wins, null for a seat with no hand. Ties split evenly, and odd chips go one at a time to the tied winners starting at firstSeat. Passing the seat left of the button gives the standard rule. Hands are scored with evaluateHand(cards).rank on the two hole cards plus the board. It finds the best five of 5 to 7 cards, and .description gives text such as "Two pair, Aces and Sevens".

src/game.ts
function settle(state: HoldemState, ctx: Ctx): void {
const contenders = state.seats.flatMap((p, seat) => (live(p) ? [seat] : []));
const uncontested = contenders.length === 1;
const scores = state.seats.map((p) => {
if (!live(p)) return null;
return uncontested ? 0 : evaluateHand([...p.hole, ...state.board]).rank;
});
if (!uncontested) for (const seat of contenders) state.seats[seat]!.shown = true;
const pots = splitPots(
state.seats.map((p) => p.total),
state.seats.map((p) => !live(p)),
);
const firstSeat = (state.button + 1) % state.seats.length;
const won = state.seats.map(() => 0);
const results = pots.map((pot): PotResult => {
const share = awardPots([pot], scores, { firstSeat });
share.forEach((chips, seat) => (won[seat]! += chips));
const winners = share.flatMap((chips, seat) => (chips > 0 ? [seat] : []));
return { amount: pot.amount, eligible: pot.eligible, winners };
});
state.seats.forEach((p, seat) => {
p.stack += won[seat]!;
p.bet = 0;
p.total = 0;
});
state.last = {
hand: state.hand,
uncontested,
pots: results,
won,
hands: state.seats.map((p) =>
p.shown ? evaluateHand([...p.hole, ...state.board]).description : null,
),
};
ctx.emit('handEnd', state.last as unknown as Json);
ctx.timers.after('nextHand', NEXT_HAND_MS, 'nextHand', null, { visible: true });
}

Notes on settle:

  • Chips never leave the table here: each pot is awarded separately so the result can list the pots, winners and descriptions for the UI.
  • When everyone else folded, the last seat gets any score and nobody is marked shown, so no cards are revealed.
  • Uncalled chips (the part of the top bet nobody matched) are returned in endStreet, before this runs.
  • The nextHand timer is visible, so clients can show a countdown to the next deal.

At the table chips are numbers in state. The wallet sees only two moments: a player buys in, and a player cashes out. When a player sits, the game reserves buyIn and commits it in the same entry. If the reserve is refused, the seat stays at 0 chips and sits out until a rebuy action succeeds.

src/game.ts
async function buyIn(state: HoldemState, seat: number, ctx: Ctx): Promise<boolean> {
const { buyIn: amount } = ctx.options;
state.ledger += 1;
const key = `buyin:s${seat}:${state.ledger}`;
const ok = await ctx.wallet.reserve(seat, amount, key);
if (ok) {
ctx.wallet.commit(key);
state.seats[seat]!.stack += amount;
}
return ok;
}

Leaving is the other half. onStand credits the whole remaining stack, then folds the seat if it was in the hand. Chips already in the pot stay there.

src/game.ts
onStand: ({ state, seat, ctx }) => {
const p = state.seats[seat!]!;
const wasLive = isBetting(ctx) && live(p);
// Cash out what is left behind; chips already in the pot stay there.
if (p.stack > 0) {
state.ledger += 1;
ctx.wallet.credit(seat!, p.stack, `cashout:s${seat!}:${state.ledger}`);
p.stack = 0;
}
p.folded = true;
p.hole = [];
if (!wasLive) return;
ctx.emit('action', { seat: seat!, action: 'fold', left: true });
if (bettingDone(state)) {
endStreet(state, ctx);
return;
}
// The engine passed a turn held by the leaving seat to the next seat with chips,
// which may not be the next one that has to act.
const current = ctx.turn.seat;
if (current === null || !needsAction(state, state.seats[current]!)) {
ctx.turn.set(nextToAct(state, seat!)!);
}
},

Every wallet key includes state.ledger, a counter that only goes up, so a seat that stands and sits again never reuses a key. Credit keys must be unique for good, because a repeated key is treated as a duplicate and the second payout is lost. Read wallets and real-money safety before you use a real wallet.

Hand-written tests cover the rules (blinds, minimum raises, side pots with the odd chip, a player who stands mid-hand). The test that finds the bugs you did not think of plays random legal moves and checks two invariants after every step:

  • Chip conservation. Wallet balances plus chips at the table always equal what the players started with.
  • No leaks. No view, spectators included, contains a card that is in the deck or in a hand the viewer may not see. The check searches the whole serialized view for the card text, so a card hidden in the wrong field is caught too.
test/game.test.ts
/** Asserts chips are conserved and no view leaks a hidden card. */
async function checkInvariants(t: Table, players: Set<string>): Promise<void> {
const state = t.state;
expect(t.walletErrors).toEqual([]);
expect((await walletTotal(t, players)) + tableChips(state)).toBe(players.size * STARTING_BALANCE);
for (const p of state.seats) expect(p.stack).toBeGreaterThanOrEqual(0);
const deck = new Set<string>(state.deck);
const viewers: (number | 'spectator')[] = ['spectator'];
t.seats.forEach((s, seat) => {
if (s.status !== 'empty') viewers.push(seat);
});
for (const viewer of viewers) {
const view = t.viewOf(viewer);
const json = JSON.stringify(view);
for (const card of deck) expect(json).not.toContain(`"${card}"`);
view.seats.forEach((seen, seat) => {
const own = viewer === seat;
const revealed = state.seats[seat]!.shown;
if (own || revealed) expect(seen.hole).toEqual(state.seats[seat]!.hole);
else expect(seen.hole.every((c) => c === null)).toBe(true);
// Hidden cards must not show up anywhere else in the view either.
if (!own && !revealed) {
for (const card of state.seats[seat]!.hole) expect(json).not.toContain(`"${card}"`);
}
});
}
}

The session also times out turns, makes players stand and sit mid-hand, rebuys busted seats and calls verifyReplay at the end. Over 200 hands it exercises side pots and showdowns that no one would script by hand. See testing games for the tools.

  • Run the example with pnpm --filter @shoehive-examples/holdem build:web and then pnpm --filter @shoehive-examples/holdem start, and open two browsers to see the private hands in the UI.
  • Read turns and rounds for how turns.first, skip and order fit together.
  • Try adding a feature: a straddle, a rake taken in settle, or a table that deals the board twice when everyone is all-in.