High Five Studio

December 2026

How a Poker Algorithm Works in Python, From Shuffle to Showdown

A Python poker engine stays deterministic until it requests OS entropy; see how seeding, bounded draws, shuffling, and a state machine shape fair play

8 min read

How a Poker Algorithm Works in Python, From Shuffle to Showdown

A Python poker engine is deterministic right up to the point where it asks the operating system for entropy, and everything that looks random afterwards is bookkeeping: a seeded stream, a bounded integer draw, a permutation, and a state machine that refuses illegal actions. Get those four pieces right and a 52-card deck reproduces the same distribution as a regulated operator's shuffle; get them wrong and you ship a game where the same seat wins the button every third hand. The interesting part is not the code, it is where the randomness enters, how many bits you actually need, and which decisions belong to the algorithm rather than the player.

The shuffle is the whole security model

Start with the number that governs everything else. A 52-card deck has 52! arrangements, roughly 2^225. Any shuffle that can reach only a fraction of those arrangements is not a shuffle, it is a rotation with extra steps.

Regulated operators publish how they handle this. PokerStars, in documentation reproduced by the Parliament of Australia, describes two independent entropy sources: user input (mouse movements, event timing) and a Quantis quantum hardware RNG from ID Quantique. If the user input lacks sufficient entropy, the next hand is delayed until the Quantis device supplies enough. The company draws 249 random bits from both sources combined, mixes them with SHA-1, and runs a SHA-1-based pseudo-random generator over the result.

Two details in that description are worth copying. First, the deck is built by drawing one card at random from the original 52, then one from the remaining 51, and so on, each placed on top of a new deck until all cards have moved. That is Fisher–Yates, described in prose. Second, when mapping random bits onto a range, the operator takes 5 bits for 0–31 and discards anything above 25, repeating until the value is in range. That rejection step is the difference between a fair draw and a measurable bias toward low indices.

What Python gives you for free, and what it doesn't

random.shuffle() is Fisher–Yates under the hood and is fine for a home game, a solver harness, or a training environment. It is not fine for anything where money changes hands, because the Mersenne Twister is predictable: observe 624 consecutive 32-bit outputs and you can reconstruct the internal state and predict every future card. For a study group that is irrelevant. For a rake-taking product it is disqualifying.

The practical replacement is the secrets module, which pulls from os.urandom:

import secrets

def shuffled_deck():
    deck = list(range(52))
    for i in range(51, 0, -1):
        j = secrets.randbelow(i + 1)
        deck[i], deck[j] = deck[j], deck[i]
    return deck

secrets.randbelow handles the rejection sampling internally, so you get an unbiased index without writing the discard loop yourself. If you want the operator-grade version, secrets.randbits(249) plus a SHA-1 derivation mirrors the published approach, though for most purposes a CSPRNG-backed randbelow is sufficient and much easier to audit.

One Croatian-specific note: if you are building anything that accepts stakes, the shuffle is the least of your compliance problems. Under the Croatian gambling framework administered by the Ministry of Finance, licensed remote operators must have their random number generators tested and certified, and the testing is done against the source, not against your Python wrapper. A certified RNG sitting behind an uncertified state machine still fails.

From deck to showdown: modelling the hand

The shuffle gets the cards into an order. The engine then has to answer three questions per street: who acts, what are the legal actions, and what does the pot look like afterwards.

A state machine, not a script

The common beginner mistake is to write the hand as a sequence of function calls — deal, bet, deal, bet, showdown. That works until someone raises, or someone is all-in for less than the minimum, or a player times out mid-action. A hand of no-limit hold'em is a state machine with a small number of states and a large number of transitions.

from dataclasses import dataclass, field
from enum import Enum, auto

class Street(Enum):
    PREFLOP = auto()
    FLOP = auto()
    TURN = auto()
    RIVER = auto()
    SHOWDOWN = auto()

@dataclass
class HandState:
    deck: list
    stacks: list
    hole: list
    board: list = field(default_factory=list)
    pot: int = 0
    street: Street = Street.PREFLOP
    to_act: int = 0
    current_bet: int = 0
    min_raise: int = 0
    acted: set = field(default_factory=set)

The acted set is what closes a betting round. A round ends when every player who has not folded has either matched the current bet or is all-in, and has had at least one opportunity to act since the last aggression. Without that set you get the classic bug where the big blind is skipped because they were "already in" when the action returns to them.

Legal actions follow from state, not from the interface:

  • Fold is always available.
  • Check only when current_bet == 0 or the player has already matched.
  • Call for min(current_bet - committed, stack).
  • Raise to at least current_bet + min_raise, capped by stack.

If your raise slider lets a player raise to 40 when the minimum is 60, the engine is lying to the player, and in a real-money context that is a dispute waiting to happen. The interface should derive its bounds from the same function the engine uses to validate, so there is one source of truth.

Hand evaluation

Evaluating seven cards is the part everyone writes badly first. The naive approach — generate all 21 five-card combinations, score each, take the max — is correct and slow enough to matter when you are running a million-hand simulation. The standard fix is a lookup table indexed by a 13-bit rank mask plus a flush flag, or a precomputed evaluator.

This is also where an existing library saves weeks. PokerKit, an open-source Python library described in a 2024 arXiv paper, supports Texas hold'em, Omaha, seven-card stud, razz and deuce-to-seven triple draw, with both game simulation and hand evaluation, and reports 99% code coverage via static type checking, doctests and unit tests. If your goal is to study strategy rather than to ship a room, using a tested evaluator and writing only the parts you care about is the rational choice. If your goal is to ship, you still need to test the evaluator against known hand rankings, because a single misranked wheel straight will be found by a player within a day.

Side pots

Side pots are the least glamorous and most bug-prone part of the engine. The rule is mechanical: at showdown, sort the distinct contribution levels, and for each level create a pot from all players who contributed at least that much, then award it among the eligible winners at that level. A player who folded contributes chips but is never eligible. A player who is all-in for less is eligible only for the pots they fully covered.

Test this with the ugly cases. Three players, stacks 100, 40 and 200, all-in preflop. If your engine returns a single pot of 340 to the best hand, you have just given the short stack money they were never entitled to. Run that scenario as a unit test before you run anything else.

Where the algorithm stops being a shuffle and starts being a player

Everything above is arithmetic. The moment you add an opponent who is not a human, you are in a different discipline, and the published benchmarks are worth knowing because they set expectations.

Pluribus, developed by Noam Brown and Tuomas Sandholm at Carnegie Mellon with Facebook, beat 15 top human players over 12 days and more than 10,000 hands in six-player no-limit Texas hold'em, with training cloud computing costing under $150. That last number is the one to sit with. The reason Pluribus was cheap is that six-player no-limit is a game of imperfect information where a relatively shallow search with a good abstraction outperforms brute force. It did not need a supercomputer to beat professionals; it needed the right algorithm and a lot of self-play.

If you are building a bot in Python for study, the practical route is counterfactual regret minimisation on an abstracted game tree, or a simpler opponent-modelling approach if you only need something that does not embarrass itself. Neither is a weekend project, and neither is what most "poker AI" repositories actually contain.

The human side of the table is easier to model and, for a product, more useful. Behavioural patterns show up in the data long before they show up in the strategy: avatars tilt noticeably less when the muck reveals opponent hands, and rebuy rates fall when avatars visibly show tilt. If your engine logs every action with a timestamp, you can measure these effects yourself rather than taking them on faith.

Testing a poker algorithm

A shuffle you cannot test is a shuffle you do not understand. Three tests cover most of the risk.

Distribution. Deal a million hands and check that each of the 1,326 distinct two-card starting combinations appears at roughly the expected frequency. The expected count for a specific combination is about 754 per million, and a chi-square test will tell you whether your deviations are noise or structure.

Determinism under seed. Your test suite should be able to replay a hand exactly. Inject the RNG rather than calling secrets directly, so tests can pass a seeded generator and production can pass the CSPRNG. This one design decision saves more debugging time than any other.

Invariants. After every action, assert that the sum of stacks plus the pot equals the starting total. Assert that no player's stack is negative. Assert that the number of cards in the deck plus the board plus all hole cards equals 52. These three assertions catch the overwhelming majority of state-machine bugs, and they cost nothing to run.

Timing matters too, and not only for fairness. Poker time banks that expire 2.4 seconds before the river bet are a clock problem, not a card problem, but they live in the same engine: the action timer is a state transition, and if it fires while a raise is being validated you get a race condition. Decide early whether the timer is authoritative on the server or advisory on the client. It must be the server.

The question the code cannot answer

A correct Python poker engine is achievable in a few hundred lines plus a tested evaluator, and the randomness problem has a published, auditable answer: 249 bits, a cryptographic hash, and a rejection loop that discards out-of-range values rather than folding them back in. What the code cannot tell you is where the line sits between simulating a game and operating one. The same Fisher–Yates loop that trains a solver in a notebook becomes, behind a deposit button, a regulated component subject to certification, and the certification tests the source, not the wrapper. Croatia's framework is explicit about that; most jurisdictions are. So the open question for anyone building in Python is not whether the shuffle is fair — it is whether the thing you are building is a study tool that happens to deal cards, or a product that needs a licence before the first hand is dealt. The code looks identical either way.