Give me the python script to simulate my chances of winning in a hold em poker game (using monte carlo) given a hand (always 2 cards) and a board (can be empty)
Assistant
Certainly! Below is a Python script that simulates your chances of winning in a Texas Hold'em poker game using the Monte Carlo method. This script takes your hand (2 cards) and the current board (which can be empty) as input, simulates numerous random outcomes, and estimates your probability of winning.
python
import random
from collections import Counter
from itertools import combinations
# Define card ranks and suits
RANKS = '23456789TJQKA'
SUITS = 'cdhs' # clubs, diamonds, hearts, spades
# Assign numerical values to ranks for comparison
RANK_VALUES = {rank: index for index, rank in enumerate(RANKS, start=2)}
# Generate a standard 52-card deck
def generate_deck():
return [rank + suit for rank in RANKS for suit in SUITS]
# Remove known cards from the deck
def remove_known_cards(deck, known_cards):
return [card for card in deck if card not in known_cards]
# Evaluate the strength of a hand
def evaluate_hand(cards):
"""
Returns a tuple where higher tuples represent better hands.
"""
counts = Counter(card[0] for card in cards)
suits = [card[1] for card in cards]
ranks = sorted((RANK_VALUES[card[0]] for card in cards), reverse=True)
is_flush = len(set(suits)) == 1
is_straight = False
high_card = ranks[0]
# Check for straight (including wheel straight)
unique_ranks = sorted(set(ranks), reverse=True)
if len(unique_ranks) >= 5:
for i in range(len(unique_ranks) - 4):
window = unique_ranks[i:i+5]
if window[0] - window[4] == 4:
is_straight = True
high_card = window[0]
break
# Special case: Ace to Five straight (A-2-3-4-5)
if set([14, 2, 3, 4, 5]).issubset(set(ranks)):
is_straight = True
high_card = 5
# Check for other hands
if is_flush and is_straight:
return (8, high_card) # Straight flush
elif 4 in counts.values():
four = [k for k, v in counts.items() if v == 4]
kicker = [k for k in ranks if RANK_VALUES[k] != RANK_VALUES[four[0]]]
return (7, RANK_VALUES[four[0]], kicker[0]) # Four of a kind
elif sorted(counts.values()) == [2, 3]:
three = [k for k, v in counts.items() if v == 3]
pair = [k for k, v in counts.items() if v == 2]
return (6, RANK_VALUES[three[0]], RANK_VALUES[pair[0]]) # Full house
elif is_flush:
return (5, ranks) # Flush
elif is_straight:
return (4, high_card) # Straight
elif 3 in counts.values():
three = [k for k, v in counts.items() if v == 3]
kickers = [k for k in ranks if RANK_VALUES[k] != RANK_VALUES[three[0]]]
return (3, RANK_VALUES[three[0]], kickers) # Three of a kind
elif list(counts.values()).count(2) == 2:
pairs = [k for k, v in counts.items() if v == 2]
kicker = [k for k in ranks if RANK_VALUES[k] not in [RANK_VALUES[p] for p in pairs]]
return (2, sorted([RANK_VALUES[p] for p in pairs], reverse=True), kicker[0]) # Two pair
elif 2 in counts.values():
pair = [k for k, v in counts.items() if v == 2]
kickers = [k for k in ranks if RANK_VALUES[k] != RANK_VALUES[pair[0]]]
return (1, RANK_VALUES[pair[0]], kickers) # One pair
else:
return (0, ranks) # High card
# Simulate a single game
def simulate_game(your_hand, board, deck, num_opponents):
# Complete the board
needed_board_cards = 5 - len(board)
board_cards = board + random.sample(deck, needed_board_cards)
remaining_deck = [card for card in deck if card not in board_cards]
# Deal opponent hands
opponent_hands = []
for _ in range(num_opponents):
opponent_hand = random.sample(remaining_deck, 2)
remaining_deck = [card for card in remaining_deck if card not in opponent_hand]
opponent_hands.append(opponent_hand)
# Evaluate your hand
your_best_hand = best_hand(your_hand + board_cards)
your_hand_value = evaluate_hand(your_best_hand)
# Evaluate opponents' hands
for opponent_hand in opponent_hands:
opponent_best_hand = best_hand(opponent_hand + board_cards)
opponent_hand_value = evaluate_hand(opponent_best_hand)
if opponent_hand_value > your_hand_value:
return False # You lose
elif opponent_hand_value == your_hand_value:
continue # Tie, but for Monte Carlo we'll treat ties as non-wins
return True # You win
# Get the best 5-card hand from 7 cards
def best_hand(cards):
best = None
best_value = (-1,)
for combo in combinations(cards, 5):
hand_value = evaluate_hand(combo)
if hand_value > best_value:
best_value = hand_value
best = combo
return best
# Main simulation function
def estimate_win_probability(your_hand, board=[], num_opponents=1, simulations=1000):
your_hand = your_hand.upper().split()
board = board.upper().split()
known_cards = your_hand + board
deck = generate_deck()
deck = remove_known_cards(deck, known_cards)
wins = 0
for _ in range(simulations):
if simulate_game(your_hand, board, deck.copy(), num_opponents):
wins += 1
win_probability = wins / simulations
print(f"Estimated probability of winning: {win_probability:.2%}")
return win_probability
# Example usage
if __name__ == "__main__":
your_hand = input("Enter your hand (e.g., 'Ah Kd'): ")
board = input("Enter the board cards (e.g., 'Qs Jc 10h') or press enter if none: ")
num_opponents = int(input("Enter the number of opponents: "))
simulations = int(input("Enter the number of simulations to run: "))
estimate_win_probability(your_hand, board, num_opponents, simulations)
How to Use the Script
Input Your Hand: When prompted, enter your two hole cards. Use the format 'Ah Kd' for Ace of hearts and King of diamonds. The ranks are:
'2' to '9' for numbered cards
'T' for Ten
'J' for Jack
'Q' for Queen
'K' for King
'A' for Ace
The suits are:
'c' for clubs
'd' for diamonds
'h' for hearts
's' for spades
Input the Board Cards: If there are community cards on the board, enter them in the same format (e.g., 'Qs Jc 10h'). If the board is empty, just press enter.
Number of Opponents: Enter the number of opponents you're facing.
Number of Simulations: Enter the number of Monte Carlo simulations to run. A higher number yields more accurate results but takes longer to compute. For testing, you may start with 1000 simulations.
Receive the Estimated Probability: The script will output the estimated probability of winning based on the simulations.
Notes:
Monte Carlo Simulation: The script simulates random possible outcomes by dealing random cards to complete the board and the opponents' hands, then evaluates the results.
Hand Evaluation: The script evaluates hands based on standard poker hand rankings, from high card up to straight flush.
Limitations:
Simplifications: Ties are treated as non-wins (you neither win nor lose in the simulation).
Performance: For a large number of simulations or opponents, the script may take time to run.
Example:
code
Enter your hand (e.g., 'Ah Kd'): As Ks
Enter the board cards (e.g., 'Qs Jc 10h') or press enter if none: Qs Js 9s
Enter the number of opponents: 2
Enter the number of simulations to run: 10000
Estimated probability of winning: 59.34%
Understanding the Code
Deck Generation: Creates a list of 52 unique cards.
Hand Evaluation: The evaluate_hand function assesses the strength of a 5-card poker hand and assigns it a numerical value for comparison.
Best Hand Selection: The best_hand function finds the best possible 5-card hand out of 7 cards (your hand plus the board).
Simulation Loop: Runs the specified number of simulations, each time randomly dealing unseen cards and evaluating the outcome.
Probability Calculation: Counts the number of wins over the total simulations to estimate the probability.
Customization
You can modify the script to suit different needs:
Multiple Opponents: Adjust the num_opponents parameter to simulate games with more players.
Simulation Accuracy: Increase the simulations parameter for a more precise estimate at the cost of computation time.
Hand Inputs: Modify the input method if you want to hard-code certain hands or integrate the script into another program.
Feel free to ask if you need further clarification or assistance with modifying the script!