PokerKit Documentation

repository·main·Indexed 19 days ago

https://github.com/uoftcprg/pokerkit

A pure Python library for poker game simulation, hand evaluation, and statistical analysis. It supports a wide range of poker variants including Texas Hold'em, Omaha, Badugi, and Short-deck Hold'em. Key features include Monte Carlo simulations for player equities and hand strength, range parsing with parse_range(), and a Statistics class for aggregating player performance data from hand histories.

Tokens
23.2K
Snippets
48
Records
69
Agent score
66%

What's inside PokerKit

  1. Overview of PokerKit features

    main

    PokerKit is a pure Python library designed for simulating poker games, evaluating hands, and performing statistical analysis. It is suitable for poker AI development, tool creation, and casino implementations.

    Key features include:

    • Support for an extensive array of major and minor poker variants.
    • High-speed hand evaluations.
    • Customizable game states and parameters.
    • A unified high-level programmatic API.
    • High reliability via static type checking and 99% code coverage through extensive unit tests and doctests.
  2. Overview of PokerKit game simulation

    main

    PokerKit is a highly customizable poker game simulation library designed to support almost any poker variant. It allows users to define unique games, adapt existing variants, or implement unsupported ones.

    The library is designed to cater to different levels of control depending on the use case:

    1. AI Agent Development: Focuses on action selection during betting rounds. In these scenarios, granular details like showdown order, posting blinds/antes, and bet collection can be abstracted away.
    2. Online Poker Casino Simulation: Requires granular control over every game aspect, including dealing hole cards individually, burning cards, managing mucking/showing during showdown, killing hands, and the precise movement of chips between stacks.

    PokerKit provides varying levels of automation to balance these needs, allowing developers to choose between high-level automation or low-level manual control.

  3. Understand the core functionalities of PokerKit

    main

    PokerKit provides three primary categories of functionality for developers:

    1. Game Simulations: Programmatically creating environments to play out poker games and simulate real-world scenarios with high fidelity.
    2. Hand Evaluations: Determining the strength and ranking of specific poker hands.
    3. Statistical Analysis: Reviewing hand histories or analyzing specific poker situations to derive data and insights.
  4. Explore the pokerkit API modules

    main

    The pokerkit library is organized into several specialized modules. Depending on your task, you should import from the following namespaces:

    • pokerkit.games: Core game logic and engine components.
    • pokerkit.state: Management of game state, including hands, boards, and player information.
    • pokerkit.hands: Hand evaluation, ranking, and hand-specific logic.
    • pokerkit.analysis: Tools for analyzing game outcomes, probabilities, or statistics.
    • pokerkit.notation: Parsing and generating poker notations (e.g., hand histories or action sequences).
    • pokerkit.lookups: Pre-computed tables and lookup data for efficient poker calculations.
    • pokerkit.utilities: General helper functions and internal tools.

    Refer to the specific module documentation for detailed class and function signatures.

  5. Configure poker variant parameters

    main

    When defining a poker variant, use the following 'raw' parameter formats which PokerKit will automatically clean and interpret:

    Antes

    • Uniform Antes: Provide a single value (e.g., 2.00) to apply to all players.
    • Non-uniform/Big-blind Antes: Use a list [0, 2] or a dictionary {1: 2}.
    • Button Antes: Use a dictionary with key -1 (e.g., {-1: 2}).
    • Ante Trimming Status: Set to True for uniform antes and False for non-uniform antes.

    Blinds and Straddles

    • Standard Blinds: Use a list like [0.5, 1] for SB and BB.
    • Multi-level Straddles: Use a list like [0.5, 1, 2] for UTG, SB, and BB.
    • Button Straddles: Use a dictionary with key -1 (e.g., {0: 0.5, 1: 1, -1: 2}).
    • No Blinds: Supply 0 or a list of zeros (e.g., [0, 0, 0, 0]).

    Other Configuration

    • Bring-In: A positive value (e.g., 1.5) if the game uses bring-ins; otherwise 0. Note: Blinds/Straddles and Bring-ins are mutually exclusive.
    • Starting Stacks: A numeric value or math.inf if unknown.
    • Player Count: Total number of players.
    • Mode: Use pokerkit.state.Mode to specify tournament or cash-game rulesets.
    • Starting Board Count: Number of boards to be dealt (usually 1, or 2 for double board games).
  6. Interact with State attributes and methods correctly

    main

    To maintain state integrity, follow these rules:

    1. Read-only attributes: Many fields are read-only and enforced via dataclasses.
    2. State modification: Never modify attributes of pokerkit.state.State directly. Instead, only read from them or use the provided public methods to trigger modifications.
    3. Avoid protected/private members: Do not call methods or access attributes denoted with a preceding underscore (_).
  7. Construct game trees for simulations

    main
    PokerKit is well-suited for Monte-Carlo simulations. When building a game tree, use Python's copy.deepcopy to branch states and verify the validity of operations to ensure the tree remains consistent. Be mindful of how Python's dataclasses interact with state copying.
  8. How game phase transitions work in PokerKit

    main

    PokerKit structures game flow into distinct, sequential phases. Each phase supports a specific set of operations (e.g., dealing, betting, collecting bets).

    Key behaviors:

    • Phase Skipping: Phases are automatically bypassed if they are not applicable to the current game state. For example, if no antes are configured, the Ante Posting phase is skipped. If no bets are placed, Bet Collection is skipped.
    • Internal Management: Transitions between phases are managed internally by the framework. Once a phase is completed, the game automatically moves to the next logical phase.
    • Phase-Specific Operations: You can only invoke specific methods (operations) when the game is in the corresponding active phase. Attempting to call a betting operation during a dealing phase will not work.
    • Repetition: Depending on the specific poker variant and the number of betting rounds, the Dealing, Betting, and Bet Collection phases may repeat multiple times during a single hand.
  9. How operation triplets (Verifier, Querier, Operator) work in PokerKit

    main

    Every operation in PokerKit is implemented as a triplet of associated methods:

    1. Verifier: Validates if a move is legal according to the rules and current state. It raises a ValueError if the move is illegal or issues a UserWarning for suspicious actions.
    2. Querier: A Boolean check (e.g., can_fold()) that wraps the Verifier. It returns True if the action is valid and False if the Verifier raises a ValueError.
    3. Operator: The actual execution method (e.g., fold()). It first runs the Verifier; if no error is raised, it executes the operation and returns a result object describing the action (players involved, amounts, cards, etc.).

    Error Handling Note: PokerKit uses ValueError for illegal moves and UserWarning for suspicious moves. By default, Queriers ignore warnings and only return False on ValueError. To treat warnings as errors, configure Python's warning filter:

    from warnings import filterwarnings
    
    filterwarnings('error')

    When warnings are treated as errors, PokerKit's action query methods will return False if a warning is issued.

  10. Understand Ante Trimming Status

    main

    The ante_trimming_status parameter resolves ambiguity when players pay different ante amounts (non-uniform antes).

    • When to use False: If non-uniform antes are used (e.g., BB ante, BTN ante in tournaments) or if a player's starting stack is lower than the ante amount, and you want the winner to be entitled to the full amount of all antes, even if some players couldn't post the full amount.
    • When to use True: If you want to ensure that a player who cannot post a full ante only wins a proportional portion of the other players' antes.

    Rule of thumb: If non-uniform antes are used, you must supply False.

  11. Define a custom poker variant from scratch

    main

    If a variant is not pre-defined, you must define a custom variant by specifying its core rules. A variant definition requires the following components:

    • Deck: The deck used (e.g., standard 52-card deck).
    • Hand Types: The number of hand types (typically 1, or 2 for split-pot games).
    • Streets: For each street, define:
      • Card Burning Status: Whether to burn a card (True or False).
      • Hole Dealings: How to deal hole cards (face-up/down); use an empty tuple () for none.
      • Board Dealings: Number of board cards to deal (0 for none).
      • Is Draw Stage: Whether it is a draw round (True or False).
      • Opening: Logic for who acts first (e.g., position-based or card-based).
      • Min Completion/Bet/Raise: The minimum size for actions.
      • Max # of Completion/Bet/Raise: Maximum number of actions allowed (None for unlimited).
    • Betting Structure: The limits applied (e.g., no-limit, pot-limit, or fixed-limit).
  12. Understand Player Positions in PokerKit

    main

    PokerKit uses positions rather than seat numbers to manage gameplay logic.

    • In non-heads-up button games:
      • Position 0: Small Blind
      • Position 1: Big Blind
      • Position 2: UTG (Under the Gun)
      • ...
      • Last Position: The Button (in position).
    • In Stud games: Position is relative to the dealer. The player to the immediate left of the dealer is in position 0, and the player to the immediate right is in the last position.

    Note: The player in the $n$-th position is the $n$-th person to be dealt hole cards at the start of the hand.