### Production Configuration Setup Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Example configuration for production, utilizing environment variables for sensitive credentials. ```ini [main] db = https://api.production.com/poker/ login = prod_user password = ${POKERBOT_PASSWORD} control = ProductionVM log_level = INFO log_dir = /var/log/pokerbot ``` -------------------------------- ### Development Configuration Setup Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Example configuration for a local development environment using a local API endpoint. ```ini [main] db = http://localhost:5000/api/ login = dev_user password = dev_password control = Direct mouse control log_level = DEBUG log_dir = log ``` -------------------------------- ### List Playable Strategies Example Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Usage example for fetching and printing the list of accessible strategies. ```python strategies = strategy_handler.get_playable_strategy_list() print(strategies) # ['MyStrategy1', 'MyStrategy2', 'DefaultStrategy'] ``` -------------------------------- ### Load Strategy Example Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Usage example for loading a specific strategy by name. ```python strategy_handler = StrategyHandler() strategy_handler.read_strategy('MyStrategy') # Now strategy_handler.selected_strategy contains all parameters ``` -------------------------------- ### Database Connection Examples Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Common URL configurations for local and remote database access. ```text http://localhost:5000/api/ # Local development http://192.168.1.100:8080/api/ # Local network https://api.example.com/poker/ # Cloud hosted ``` -------------------------------- ### Configuration File Structure Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Example of the poker/config.ini file containing database connection details. ```ini [main] db = http://example.com/api/ login = username password = password last_strategy = MyStrategy ``` -------------------------------- ### Example: Get Game Count Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/game-logger.md Demonstrates how to instantiate the logger and retrieve the game count for a specific strategy. ```python from poker.tools.game_logger import GameLogger logger = GameLogger() total_games = logger.get_game_count('MyStrategy') print(f"Games with MyStrategy: {total_games}") ``` -------------------------------- ### Install Dependencies for Local Execution Source: https://github.com/dickreuter/poker/blob/master/readme.rst Commands to set up the local Python environment and install required packages. ```bash pip install -r requirements.txt ``` ```bash pip install tesserocr ``` -------------------------------- ### VirtualBox Configuration Setup Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Configuration for running the bot with a VirtualBox machine as the control interface. ```ini [main] db = http://192.168.1.100:5000/api/ login = vbox_user password = vbox_pass control = PokerVM # VirtualBox machine name log_level = INFO log_dir = logs ``` -------------------------------- ### Calculate Outs Example Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/decision-maker.md Usage example for evaluating hand strength and calculating outs. ```python from poker.decisionmaker.outs_calculator import Outs_Calculator calc = Outs_Calculator() # Evaluate K-Q on board 9-8-7 outs = calc.evaluate_hands(['KS', 'QH'], ['9D', '8C', '7H'], calc) # Returns outs count for straight and other draws ``` -------------------------------- ### Example: Extracting player funds Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/table-scraper.md Demonstrates extracting funds for all players while skipping specific positions. ```python scraper.get_players_funds(my_funds_only=False, skip=[2, 5]) print(scraper.player_funds) # [1250.50, 800, 0, 1500, 0, 0] ``` -------------------------------- ### Install and Download Dataset Source: https://github.com/dickreuter/poker/blob/master/notebooks/yolotrainer.ipynb Installs the roboflow package and downloads a specific version of a project dataset formatted for YOLOv7. ```python !pip install roboflow from roboflow import Roboflow rf = Roboflow(api_key="") project = rf.workspace("poker-v9lfq").project("playingcards-ixvhp") dataset = project.version(1).download("yolov7") ``` -------------------------------- ### Clone and Run Poker Bot with Docker Source: https://github.com/dickreuter/poker/blob/master/readme.rst Commands to clone the repository and start the application using Docker Compose. ```bash $ git clone https://github.com/dickreuter/Poker.git ``` ```bash $ cd Poker ``` ```bash $ docker compose up -d ``` ```bash $ xhost local:root # This permits the root user on the local machine to connect to X windows display ``` ```bash $ docker-compose exec app python3 main.py # once the container is running you can launch the bot with this command ``` -------------------------------- ### Configure Mouse Control Mode Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Example configuration for the poker/config.ini file to set the mouse control mode. ```ini [main] control = Direct mouse control # or VirtualBox machine name ``` -------------------------------- ### Example: Extracting pot information Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/table-scraper.md Demonstrates retrieving and printing the current round and total pot values. ```python scraper.get_pots() print(f"Round pot: {scraper.current_round_pot}") print(f"Total pot: {scraper.total_pot}") ``` -------------------------------- ### Analyze Strategy Performance Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/game-logger.md Example of querying the GameLogger to retrieve performance data for a specific strategy. ```python # Analyze strategy performance logger = GameLogger() # Get total games games = logger.get_game_count('MyStrategy') # Could analyze: # - Win rate by position # - Equity realization by stage # - Decision accuracy # - P&L trends over time ``` -------------------------------- ### Example: Extracting individual player bets Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/table-scraper.md Demonstrates extracting player bets while skipping a specific position. ```python scraper.get_player_pots(skip=[2]) # Get each player's current bet amount ``` -------------------------------- ### Get Playable Strategy List Method Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Method signature for retrieving a list of available strategies. ```python def get_playable_strategy_list(self) -> list: ``` -------------------------------- ### Execute Mouse Click Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Defines the click method signature and provides a usage example. ```python def self, x: int, y: int) -> None: ``` ```python mover = MouseMover(vbox_mode=False) mover.click(500, 400) # Click at position ``` -------------------------------- ### OCR Usage Examples Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/screen-operations.md Demonstrates reading player funds, extracting pot values in fast mode, and iterating through multiple player positions. ```python from poker.tools.screen_operations import ocr # Get player funds funds = ocr(screenshot, 'player_funds_area', table_dict, position='0') print(f"Player stack: ${funds}") # Get pot (fast mode) pot = ocr(screenshot, 'total_pot_area', table_dict, fast=True) print(f"Pot: ${pot}") # Process multiple positions for pos in range(6): player_stack = ocr(screenshot, 'player_funds_area', table_dict, position=str(pos)) print(f"Position {pos}: ${player_stack}") ``` -------------------------------- ### Database API Request Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Example of a POST request to the database endpoint using the requests library. ```python requests.post( f"{db_url}/get_strategy", params={ "name": "StrategyName", "login": login, "password": password } ) ``` -------------------------------- ### Integrate GameLogger in Main Loop Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/game-logger.md Manage session lifecycle by starting, logging decisions, and ending sessions. ```python from poker.main import ThreadManager from poker.tools.game_logger import GameLogger game_logger = GameLogger() game_logger.start_session({ 'strategy': strategy.current_strategy, 'buy_in': buy_in_amount, 'table': table_name }) # In decision loop... game_logger.log_decision({ 'game_id': game_id, 'decision': decision_string, 'equity': equity_value, 'pot': current_pot }) # At session end game_logger.end_session({ 'cash_out': final_stack, 'duration': total_seconds }) ``` -------------------------------- ### Calculate Maximum Investment Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/decision-maker.md Method signature and usage example for calculating the maximum recommended investment based on equity and stack size. ```python def calc_max_invest(self, equity: float, pw: float, bigBlindMultiplier: float) -> float: ``` ```python # Max invest with 55% equity, power 2.0, 50bb stack max_invest = base.calc_max_invest(0.55, 2.0, 50) ``` -------------------------------- ### Preflop Equity JSON Format Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/monte-carlo.md Example of the JSON structure used for mapping hand combinations to win percentages. ```json { "AAS": 85.3, "AKS": 66.7, "AQS": 62.8, "AKO": 65.1, ... } ``` -------------------------------- ### Error Log Format Example Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/game-logger.md Displays the standard structure for error logs, including timestamp, severity, module, message, and game ID. ```text timestamp | severity | module | message | game_id 2024-01-15 14:30:45 | ERROR | scraper | Card recognition failed | 123456 2024-01-15 14:31:00 | WARNING | mouse | Click missed | 123457 ``` -------------------------------- ### Getting Equity Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Uses Monte Carlo simulations to calculate hand scores and determine opponent ranges. ```python from poker.decisionmaker.montecarlo_python import MonteCarlo mc = MonteCarlo() mc.use_range_of_range = False # Get opponent range allowed_hands = mc.get_opponent_allowed_cards_list(0.25) # Top 25% # Get hand score score, ranks, hand_type = mc.calc_score(['AS', 'KD', '9D', '8C', '7H', '6S', '5D']) print(f"Hand type: {hand_type}, Score: {score}") ``` -------------------------------- ### Retrieve opponent allowed range Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/monte-carlo.md Example usage for filtering hands based on a specific equity percentage. ```python # Get opponent allowed range for top 25% of hands allowed_range = mc.get_opponent_allowed_cards_list(0.25) print(len(allowed_range)) # Approximately 169 * 0.25 = ~42 hands ``` -------------------------------- ### Initialize Neural Network Environment Source: https://github.com/dickreuter/poker/blob/master/notebooks/train_card_nn.ipynb Set up the system path to include the project root and import the CardNeuralNetwork class. ```python import sys import os sys.path.insert(0, os.path.abspath('..')) from poker.scraper.table_scraper_nn import CardNeuralNetwork ``` -------------------------------- ### Setting Up Logging Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Configures the application logger with specific log levels and directory paths. ```python from poker.tools.helper import init_logger import logging logger = init_logger( screenlevel=logging.DEBUG, filename='pokerbot_{date}', logdir='log', modulename='poker' ) logger.info("Important message") logger.error("Error occurred") ``` -------------------------------- ### Configuration Templates Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Configuration settings for minimal, VirtualBox, and production environments. ```ini [main] db = http://localhost/api/ login = guest password = guest last_strategy = Default control = Direct mouse control log_level = DEBUG log_dir = log ``` ```ini [main] db = http://localhost/api/ login = guest password = guest control = MyPokerVM log_level = INFO ``` ```ini [main] db = https://api.example.com/poker/ login = username password = secure_password control = DirectMouseControl log_level = INFO ``` -------------------------------- ### Initialize and execute basic decision making Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/decision-maker.md Requires initialized table, history, strategy, and logger objects. Accesses recommended actions and limits after instantiation. ```python from poker.decisionmaker.decisionmaker import Decision from poker.decisionmaker.current_hand_memory import History # Assuming table (t), history (h), strategy (p), logger (l) are initialized decision = Decision(t, h, p, l) # Check the recommended action print(decision.decision) # e.g., 'Fold', 'Call', 'Bet' print(decision.finalCallLimit) # Maximum call amount print(decision.finalBetLimit) # Maximum bet amount ``` -------------------------------- ### Initialize Module Logging Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Sets up module-specific loggers and initializes the global logger in the main entry point. ```python # Each module should setup its own logger import logging from poker.tools.helper import init_logger logger = logging.getLogger(__name__) # In main.py: init_logger(logging.DEBUG, 'pokerbot_{date}', 'log', 'poker') # In other modules: logger.debug("Detailed info") logger.info("Important event") logger.warning("Unexpected condition") logger.error("Error occurred") ``` -------------------------------- ### Configure Training Directories Source: https://github.com/dickreuter/poker/blob/master/notebooks/train_card_nn.ipynb Define the base directory and specific folders for training, validation, and testing image datasets. ```python import logging log = logging.getLogger(__name__) SCRAPER_DIR = 'pics' TRAIN_FOLDER = 'pics/train_cards' VALIDATE_FOLDER = 'pics/validate_cards' TEST_FOLDER = 'pics/test_cards' ``` -------------------------------- ### Modify Strategy Usage Examples Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Demonstrates increasing or decreasing strategy parameters using the modify_strategy method. ```python # Increase call equity threshold by 0.05 strategy_handler.modify_strategy('PreFlopMinCallEquity', 0.05) # Decrease by multiplying (genetic algorithm style) strategy_handler.modify_strategy('FlopCallPower', -0.5) ``` -------------------------------- ### Calculate Bet Expected Value Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/decision-maker.md Method signature and usage example for determining the EV of a bet action. ```python def calc_bet_EV(self, E: float, P: float, S: float, c: float, t) -> float: ``` ```python # Bet $50 into $100 pot with 60% equity ev = base.calc_bet_EV(0.6, 100, 50, 1.0, table) ``` -------------------------------- ### Initialize and use PyMouse Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Basic usage of the PyMouse interface for retrieving coordinates and performing mouse actions. ```python mouse = PyMouse() # Get current position x, y = mouse.position() # Move to position mouse.move(x, y) # Click at position mouse.click(x, y) ``` -------------------------------- ### MouseMoverTableBased.__init__ Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Initializes the MouseMoverTableBased instance with table configuration. ```APIDOC ## Constructor ### Signature `MouseMoverTableBased(table_dict: dict)` ### Parameters - **table_dict** (dict) - Required - Table configuration containing button locations. ``` -------------------------------- ### Calculate Call Expected Value Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/decision-maker.md Method signature and usage example for determining the EV of a call action. ```python def calc_call_EV(self, E: float, P: float, S: float) -> float: ``` ```python from poker.decisionmaker.base import DecisionBase base = DecisionBase() # With 50% equity, $100 pot, and $20 call ev = base.calc_call_EV(0.5, 100, 20) # ev = 0.0 (break-even) ``` -------------------------------- ### Implement Basic Decision Loop Source: https://github.com/dickreuter/poker/blob/master/_autodocs/README.md Demonstrates the core bot loop, including table state capture, decision calculation, and mouse action execution. ```python from poker.scraper.table_scraper import TableScraper from poker.decisionmaker.decisionmaker import Decision from poker.decisionmaker.current_hand_memory import History from poker.tools.strategy_handler import StrategyHandler from poker.tools.mouse_mover import MouseMoverTableBased import logging # Initialize table_scraper = TableScraper(table_dict) strategy = StrategyHandler() strategy.read_strategy('MyStrategy') history = History() logger = logging.getLogger(__name__) # Main loop while True: # Capture table state table_scraper.take_screenshot2() if not table_scraper.is_my_turn(): continue # Extract game information table_scraper.get_my_cards2() table_scraper.get_table_cards2() table_scraper.get_pots() # Make decision decision = Decision( table_scraper.game_state, # t history, # h strategy, # p logger # l ) # Execute action mover = MouseMoverTableBased(table_dict) mover.mouse_action(decision.decision, topleftcorner) # Update history history.lastDecision = decision.decision history.histEquity = table_scraper.game_state.equity ``` -------------------------------- ### Configure table options Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/table-scraper.md Configuration settings for table size and neural network activation. ```python { 'max_players': {'value': 6}, # Table size 'use_neural_network': '2', # '1'=disabled, '2'=enabled '_class_mapping': {...}, # NN class indices } ``` -------------------------------- ### Loading a Strategy Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Initializes the strategy handler and reads a specific strategy configuration. ```python from poker.tools.strategy_handler import StrategyHandler handler = StrategyHandler() handler.read_strategy('MyStrategy') strategy_params = handler.selected_strategy ``` -------------------------------- ### Accessing Configuration Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Retrieves application settings from the configuration file. ```python from poker.tools.helper import get_config config = get_config() db_url = config.config.get('main', 'db') login = config.config.get('main', 'login') password = config.config.get('main', 'password') ``` -------------------------------- ### Initialize and Run TableScraper Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/table-scraper.md Demonstrates the basic loop for capturing screen data and extracting game state using a table configuration. ```python from poker.scraper.table_scraper import TableScraper # Load table template table_dict = load_table_config('pokerstars') # Create scraper scraper = TableScraper(table_dict) # Main loop while True: # Capture and crop scraper.take_screenshot2() scraper.crop_from_top_left_corner() # Check if my turn if not scraper.is_my_turn(): continue # Extract game state scraper.get_my_cards2() scraper.get_table_cards2() scraper.get_dealer_position2() scraper.get_players_in_game() scraper.get_pots() scraper.get_my_funds2() # Use extracted data for decisions print(f"My cards: {scraper.my_cards}") print(f"Pot: {scraper.total_pot}") ``` -------------------------------- ### Implement card detection error recovery Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/table-scraper.md Example of handling card detection failures with a retry mechanism and logging. ```python try: scraper.get_my_cards2() if len(scraper.my_cards) != 2: logger.warning("Retrying card detection") time.sleep(0.5) scraper.get_my_cards2() except Exception as e: logger.error(f"Card detection failed: {e}") ``` -------------------------------- ### Perform Basic Game Logging Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/game-logger.md Initialize the logger and retrieve game counts for a specific strategy. ```python from poker.tools.game_logger import GameLogger logger = GameLogger() # Check performance game_count = logger.get_game_count('MyStrategy') print(f"Total games: {game_count}") ``` -------------------------------- ### Execute Click with Tolerance Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Defines the mouse_clicker method signature and provides a usage example for clicking with randomized offsets. ```python def self, x2: int, y2: int, buttonToleranceX: int, buttonToleranceY: int) -> None: ``` ```python # Click call button with ±5 pixel tolerance mover.mouse_clicker(500, 600, 5, 5) ``` -------------------------------- ### Perform Human-like Mouse Movement Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Defines the mouse_mover method signature and provides a usage example for moving to a button. ```python def self, x1: int, y1: int, x2: int, y2: int) -> None: ``` ```python # Move from current position to button mover.mouse_mover(100, 200, 500, 400) ``` -------------------------------- ### Configure Strategy Parameters Source: https://github.com/dickreuter/poker/blob/master/_autodocs/README.md Shows how to load, modify, and save bot strategy parameters using the StrategyHandler. ```python from poker.tools.strategy_handler import StrategyHandler handler = StrategyHandler() # Load strategy handler.read_strategy('MyBot') # Modify parameters handler.modify_strategy('PreFlopMinCallEquity', 0.02) # More aggressive handler.modify_strategy('FlopCallPower', -0.5) # Less aggressive # Save handler.save_strategy(handler.selected_strategy) ``` -------------------------------- ### Load and Modify Strategy Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Demonstrates loading an existing strategy, updating a specific parameter, and saving the modified strategy. ```python from poker.tools.strategy_handler import StrategyHandler handler = StrategyHandler() # Load strategy handler.read_strategy('AggressiveBot') # Modify a parameter handler.modify_strategy('PreFlopMinCallEquity', 0.01) # More aggressive # Save changes handler.save_strategy(handler.selected_strategy) ``` -------------------------------- ### MouseMover.mouse_mover(x1, y1, x2, y2) Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Moves the mouse cursor smoothly from a starting coordinate to an ending coordinate. ```APIDOC ## mouse_mover(x1, y1, x2, y2) ### Description Moves the mouse cursor smoothly from (x1, y1) to (x2, y2) using randomized step sizes and delays to simulate human movement. ### Parameters - **x1** (int) - Starting X coordinate - **y1** (int) - Starting Y coordinate - **x2** (int) - Ending X coordinate - **y2** (int) - Ending Y coordinate ``` -------------------------------- ### Handling Configuration Missing Errors Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Implement a fallback mechanism when configuration retrieval fails. ```python try: config = get_config() db = config.config.get('main', 'db') except Exception as e: logger.error(f"Config error: {e}") # Use default db = 'http://localhost/api/' ``` -------------------------------- ### Perform Basic Direct Mouse Control Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Initializes MouseMover for direct system control and executes movement and click actions. ```python from poker.tools.mouse_mover import MouseMover # Direct system mouse control mover = MouseMover(vbox_mode=False) # Move smoothly mover.mouse_mover(100, 100, 500, 500) # Click with tolerance mover.mouse_clicker(500, 600, 5, 5) ``` -------------------------------- ### Configure Movement Parameters Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Sets speed, step sizes, tremolo, and timing delays to simulate human-like mouse movement. ```python speed = 0.5 # Relative speed (0.5 = half speed) # Step sizes (pixels per waypoint) stepMin = 7 stepMax = 20 # Tremolo (random shake) xTremble = 20 yTremble = 20 # Delays between waypoints time.sleep(np.random.uniform(0.01 * speed, 0.03 * speed)) ``` -------------------------------- ### List Available Strategies Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Retrieves and prints a list of all playable strategies currently available. ```python strategies = handler.get_playable_strategy_list() for strat in strategies: print(strat) ``` -------------------------------- ### Crop Screenshot with Reference Image Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/screen-operations.md Locates a reference image within a screenshot and crops the area starting from the top-left corner. Useful for isolating specific game components from a full-screen capture. ```python def crop_screenshot_with_topleft_corner(screenshot: PIL.Image, reference_image: PIL.Image or np.ndarray) -> tuple: ``` ```python from poker.tools.screen_operations import crop_screenshot_with_topleft_corner import cv2 screenshot = take_screenshot() reference = cv2.imread('table_corner.png') cropped, (tlx, tly) = crop_screenshot_with_topleft_corner(screenshot, reference) print(f"Table at: ({tlx}, {tly})") # Cropped image now contains just the table ``` -------------------------------- ### MouseMover.__init__ Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Initializes the MouseMover instance with specified control mode. ```APIDOC ## MouseMover.__init__(vbox_mode: bool) ### Description Initializes the mouse control interface. If vbox_mode is True, it enables VirtualBox-specific control; otherwise, it uses direct system mouse control. ### Parameters - **vbox_mode** (bool) - Required - If True, controls mouse in VirtualBox VM; if False, direct system mouse control. ``` -------------------------------- ### Access Configuration with get_config Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Retrieves the singleton configuration instance, optionally using an override file path. ```python def get_config(config_override_filename: str = None) -> CustomConfigParser: ``` ```python from poker.tools.helper import get_config config = get_config() db_url = config.config.get('main', 'db') login = config.config.get('main', 'login') ``` -------------------------------- ### Calculate Equity with Monte Carlo Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/monte-carlo.md Initializes the Monte Carlo engine and iterates through an opponent's range to simulate equity against specific hole cards. ```python from poker.decisionmaker.montecarlo_python import MonteCarlo mc = MonteCarlo() mc.use_range_of_range = False # Use full range # Player's hole cards my_cards = ['AH', 'KD'] # Community board cards board_cards = ['9D', '8C', '7H'] # Opponent range (top 30% of hands) opponent_range = 0.30 allowed_hands = mc.get_opponent_allowed_cards_list(opponent_range) # Simulate against each allowed hand wins = 0 for opp_hand in allowed_hands: # Run simulation logic... pass ``` -------------------------------- ### Initialize CustomConfigParser Constructor Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Defines the constructor for the singleton configuration parser. ```python def __init__(self, config_override_filename: str = None): ``` -------------------------------- ### Initialize Decision Class Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/decision-maker.md Constructor signature for the main decision-making class. ```python def __init__(self, t, h, p, l): ``` -------------------------------- ### Read Strategy Configuration Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Method signature for loading a strategy from the remote database. ```python def read_strategy(self, strategy_override: str = '') -> bool: ``` -------------------------------- ### Resolve Configuration File Paths Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Constructs an absolute path to configuration files using the codebase directory. ```python main_file = os.path.join(get_dir('codebase'), 'config.ini') # Result: /path/to/poker/config.ini (absolute path) ``` -------------------------------- ### get_opponent_allowed_cards_list(opponent_ranges) Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/monte-carlo.md Loads preflop equity data and returns a set of allowed card combinations for an opponent based on a specified range percentage. ```APIDOC ## get_opponent_allowed_cards_list(opponent_ranges) ### Description Loads preflop equity data and returns opponent allowed card combinations based on range percentage. It sorts hands by equity and returns the top N% of hands. ### Parameters - **opponent_ranges** (float) - Required - Opponent range as decimal 0.0-1.0 (e.g., 0.2 = top 20%) ### Returns - **set** - Set of card combination strings (e.g., {'AAS', 'AKO', 'AQO'}) ### Example ```python allowed_range = mc.get_opponent_allowed_cards_list(0.25) ``` ``` -------------------------------- ### Handle Cross-Platform File Paths Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Constructs file paths dynamically based on the operating system using helper utilities. ```python from poker.tools.helper import get_dir, IS_WINDOWS import os # Cross-platform path handling equity_file = os.path.join(get_dir('codebase'), 'decisionmaker', 'preflop_equity.json') if IS_WINDOWS: executable = os.path.join(get_dir('codebase'), 'dist', 'pokerbot.exe') else: executable = os.path.join(get_dir('codebase'), 'dist', 'pokerbot') ``` -------------------------------- ### init_logger(screenlevel, filename=None, logdir=None, modulename='') Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Initializes logging with file and console handlers, supporting rotating file logs and custom log directories. ```APIDOC ## init_logger(screenlevel, filename=None, logdir=None, modulename='') ### Description Initialize logging with file and console handlers. Sets up rotating file handlers for all logs, info-only logs, and error-only logs. ### Parameters - **screenlevel** (int) - Required - Console logging level (e.g., logging.DEBUG, logging.INFO). - **filename** (str) - Optional - Log filename without extension (supports {date} pattern). - **logdir** (str) - Optional - Directory for log files. - **modulename** (str) - Optional - Module/project name for logger. ### Returns - **logging.Logger** - Configured logger instance. ### Example ```python from poker.tools.helper import init_logger import logging logger = init_logger( screenlevel=logging.DEBUG, filename='pokerbot_{date}', logdir='log', modulename='poker' ) ``` ``` -------------------------------- ### Authentication Configuration Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Credentials format for the config.ini file. ```ini [main] login = username password = password_or_token ``` -------------------------------- ### Basic Strategy Parameters Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Defines core strategy identity and initial table stakes. ```python { 'Strategy': 'MyStrategy', # Strategy name 'bigBlind': 0.02, # Big blind amount 'smallBlind': 0.01, # Small blind amount 'initialFunds': 50.0, # Initial stack size } ``` -------------------------------- ### Complete Screen Reading Workflow Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/screen-operations.md Demonstrates the end-to-end process of capturing a screenshot, cropping it based on table configuration, and performing OCR to extract game state information. ```python from poker.tools.screen_operations import ( take_screenshot, crop_screenshot_with_topleft_corner, is_template_in_search_area, ocr ) from poker.scraper.table_scraper import TableScraper # Setup table_dict = load_table_config() scraper = TableScraper(table_dict) # Capture and process screenshot = take_screenshot() cropped, tlc = crop_screenshot_with_topleft_corner(screenshot, table_dict['topleft_corner']) # Extract game state my_turn = is_template_in_search_area(table_dict, screenshot, 'my_turn', 'my_turn_search_area') if my_turn: # Read game values pot = ocr(screenshot, 'total_pot_area', table_dict) call_amount = ocr(screenshot, 'call_amount_area', table_dict) print(f"Pot: ${pot}, Call: ${call_amount}") ``` -------------------------------- ### Importing Poker Modules Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Standard import paths for decision making, table scraping, mouse operations, strategy management, and utilities. ```python # Decision Making from poker.decisionmaker.decisionmaker import Decision, DecisionTypes, GameStages from poker.decisionmaker.base import DecisionBase from poker.decisionmaker.montecarlo_python import MonteCarlo from poker.decisionmaker.outs_calculator import Outs_Calculator # Table State Extraction from poker.scraper.table_scraper import TableScraper from poker.tools.screen_operations import ( take_screenshot, crop_screenshot_with_topleft_corner, is_template_in_search_area, ocr ) # Action Execution from poker.tools.mouse_mover import MouseMover, MouseMoverTableBased # Strategy Management from poker.tools.strategy_handler import StrategyHandler # Logging and Analytics from poker.tools.game_logger import GameLogger # Utilities from poker.tools.helper import get_config, init_logger, get_dir, IS_WINDOWS, IS_MAC from poker.decisionmaker.current_hand_memory import History, CurrentHandPreflopState ``` -------------------------------- ### Configure Strategy Equity Thresholds Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Sets minimum and maximum equity thresholds for call and bet actions across different game stages. ```python strategy = { 'PreFlopMinCallEquity': 0.15, # 15% minimum to call preflop 'PreFlopMinBetEquity': 0.25, # 25% minimum to bet preflop 'PreFlopMaxBetEquity': 0.80, # Max 80% for preflop bluff 'FlopMinCallEquity': 0.25, 'FlopMinBetEquity': 0.35, 'FlopBluffMaxEquity': 0.75, 'TurnMinCallEquity': 0.30, 'TurnMinBetEquity': 0.40, 'TurnBluffMaxEquity': 0.70, 'RiverMinCallEquity': 0.35, 'RiverMinBetEquity': 0.50, 'RiverBluffMaxEquity': 0.65 } ``` -------------------------------- ### VirtualBoxController Methods Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Methods for controlling the mouse within a VirtualBox VM environment. ```APIDOC ## mouse_move_vbox(x, y) ### Description Moves the mouse cursor within the VirtualBox VM environment. ### Parameters - **x** (int) - Target horizontal position. - **y** (int) - Target vertical position. ## mouse_click_vbox(x, y) ### Description Performs a mouse click within the VirtualBox VM environment. ### Parameters - **x** (int) - Target horizontal position. - **y** (int) - Target vertical position. ``` -------------------------------- ### Capture Screen with take_screenshot Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/screen-operations.md Captures the entire screen as a PIL Image object. Performance varies between 50-500ms based on display resolution. ```python def take_screenshot() -> PIL.Image: ``` ```python from poker.tools.screen_operations import take_screenshot screenshot = take_screenshot() print(screenshot.size) # (1920, 1080) or higher screenshot.save('screen.png') # Save for inspection ``` -------------------------------- ### Convert hands to short notation Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/monte-carlo.md Demonstrates conversion of suited, offsuit, and paired hands into short-hand notation. ```python # Different hand types print(mc.get_two_short_notation(['KS', 'QS'])) # ('KQS', 'QKS') - suited print(mc.get_two_short_notation(['KS', 'QH'])) # ('KQ', 'QK') - offsuit print(mc.get_two_short_notation(['KS', 'KH'])) # ('KK', 'KK') - pair ``` -------------------------------- ### Initialize Logging with init_logger Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Configures a logger with console and rotating file handlers. Supports date-based filename patterns and custom log directories. ```python def init_logger(screenlevel: int, filename: str = None, logdir: str = None, modulename: str = '') -> logging.Logger: ``` ```python from poker.tools.helper import init_logger import logging logger = init_logger( screenlevel=logging.DEBUG, filename='pokerbot_{date}', logdir='log', modulename='poker' ) logger.info("Bot started") logger.error("Error occurred") ``` -------------------------------- ### Define VirtualBox mouse methods Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Required method signatures when operating in VirtualBox mode. ```python def mouse_move_vbox(self, x: int, y: int) -> None: # Move mouse within VirtualBox VM def mouse_click_vbox(self, x: int, y: int) -> None: # Click within VirtualBox VM ``` -------------------------------- ### Define get_opponent_allowed_cards_list method Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/monte-carlo.md Method signature for retrieving opponent hand ranges based on equity percentage. ```python def get_opponent_allowed_cards_list(self, opponent_ranges: float) -> set: ``` -------------------------------- ### Initialize MouseMover Constructor Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Defines the constructor signature for the MouseMover class. ```python def __init__(self, vbox_mode: bool): ``` -------------------------------- ### Configure Main Settings in config.ini Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Defines the primary operational parameters for the poker bot, including database credentials and logging preferences. ```ini [main] db = http://192.168.1.100:5000/api/ login = myusername password = secure_password last_strategy = MyStrategy control = Direct mouse control log_level = DEBUG log_dir = log log_filename = pokerbot_{date} ``` -------------------------------- ### Initialize Monte Carlo Engine Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/monte-carlo.md Constructor for the MonteCarlo class. ```python def __init__(self): ``` -------------------------------- ### Configure Performance Timing Parameters Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Adjust mouse movement, click delays, and screenshot intervals by modifying these constants in the source code. ```python # Mouse movement MOUSE_STEP_MIN = 7 MOUSE_STEP_MAX = 20 MOUSE_TREMOLO_X = 20 MOUSE_TREMOLO_Y = 20 MOUSE_MOVE_DELAY = 0.01 - 0.03 # Seconds # Click timing CLICK_DELAY = 0.01 - 0.1 # Seconds POST_CLICK_DELAY = 0.1 - 0.5 # Seconds # Screenshot capture SCREENSHOT_INTERVAL = 0.5 # Seconds between screenshots OCR_TIMEOUT = 10 # Seconds max for OCR ``` -------------------------------- ### POST /get_playable_strategy_list Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Retrieves a list of all available strategies. ```APIDOC ## POST /get_playable_strategy_list ### Description List available strategies. ### Method POST ### Endpoint /get_playable_strategy_list ``` -------------------------------- ### Set Environment Modes Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Configure the application environment for testing or CI/CD pipelines using shell exports. ```bash export ENV=TEST ``` ```bash export ENV=CI ``` -------------------------------- ### Retrieve project directory paths Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Use get_dir to resolve absolute paths for standard project directories, supporting both standard and PyInstaller-frozen environments. ```python def get_dir(directory_type: str) -> str: ``` ```python from poker.tools.helper import get_dir codebase = get_dir('codebase') log_dir = get_dir('log') config_path = get_dir('config') # Create path to preflop equity file equity_file = os.path.join(get_dir('codebase'), 'decisionmaker/preflop_equity.json') ``` -------------------------------- ### Power Exponent Parameters Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Aggression settings for pre-flop calling behavior. ```python 'PreFlopCallPower': 2.0 # Aggressive 'PreFlopCallPower': 3.0 # Balanced 'PreFlopCallPower': 4.0 # Conservative ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/dickreuter/poker/blob/master/_autodocs/QUICK_REFERENCE.md Set the log level to DEBUG in the configuration file to increase output verbosity. ```ini # In config.ini [main] log_level = DEBUG ``` -------------------------------- ### Detect execution environment Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Use ON_CI to check for CI/CD environments and COMPUTER_NAME to retrieve the host machine's name. ```python from poker.tools.helper import ON_CI, COMPUTER_NAME if ON_CI: # Running in CI/CD environment pass print(f"Computer: {COMPUTER_NAME}") # Socket hostname ``` -------------------------------- ### Handle Authentication Failures Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/strategy-handler.md Implementation pattern for catching strategy loading exceptions and applying a fallback. ```python try: strategy_handler.read_strategy('MyStrategy') except Exception as e: logger.error(f"Failed to load strategy: {e}") # Falls back to 'Default' guest strategy ``` -------------------------------- ### Initialize MouseMoverTableBased Constructor Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Defines the constructor signature for the table-based mouse mover. ```python def __init__(self, table_dict: dict): ``` -------------------------------- ### Check for UI elements using is_template_in_search_area Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/screen-operations.md Demonstrates how to verify the presence of buttons or cards in specific screen regions using the template matching utility. ```python from poker.tools.screen_operations import is_template_in_search_area # Check for call button has_call = is_template_in_search_area( table_dict, screenshot, 'call_button', 'buttons_search_area' ) if has_call: # Call button visible, can act pass # Check for card in specific position has_card = is_template_in_search_area( table_dict, screenshot, 'covered_card', 'covered_card_area', position='1' # Position 1 player ) ``` -------------------------------- ### Configure Strategy Power Parameters Source: https://github.com/dickreuter/poker/blob/master/_autodocs/configuration.md Controls aggression levels using curve exponents ranging from 2 to 8. ```python strategy = { # Preflop 'PreFlopCallPower': 2.0, # Higher = more aggressive 'PreFlopBetPower': 2.5, # Flop 'FlopCallPower': 2.0, 'FlopBetPower': 2.5, # Turn 'TurnCallPower': 2.0, 'TurnBetPower': 2.5, # River 'RiverCallPower': 2.0, 'RiverBetPower': 2.5 } ``` -------------------------------- ### PyMouse Interface Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/mouse-mover.md Methods for interacting with the host system mouse. ```APIDOC ## PyMouse.position() ### Description Retrieves the current X and Y coordinates of the mouse cursor. ### Returns - **x** (int) - The horizontal coordinate. - **y** (int) - The vertical coordinate. ## PyMouse.move(x, y) ### Description Moves the mouse cursor to the specified coordinates. ### Parameters - **x** (int) - Target horizontal position. - **y** (int) - Target vertical position. ## PyMouse.click(x, y) ### Description Performs a mouse click at the specified coordinates. ### Parameters - **x** (int) - Target horizontal position. - **y** (int) - Target vertical position. ``` -------------------------------- ### get_config(config_override_filename: str = None) Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Public accessor for the configuration file using a singleton pattern. ```APIDOC ## get_config(config_override_filename: str = None) ### Description Public accessor for configuration file (singleton pattern). Loads config from poker/config.ini or an override path on the first call and returns a cached instance on subsequent calls. ### Parameters - **config_override_filename** (str) - Optional - Path to custom config file. ### Returns - **CustomConfigParser** - Singleton config instance. ### Example ```python from poker.tools.helper import get_config config = get_config() db_url = config.config.get('main', 'db') ``` ``` -------------------------------- ### Initialize Python Logger Source: https://github.com/dickreuter/poker/blob/master/_autodocs/types.md Standard implementation for logging messages at various severity levels using the built-in logging module. ```python import logging logger = logging.getLogger(__name__) logger.debug(message) # DEBUG level logger.info(message) # INFO level logger.warning(message) # WARNING level logger.error(message) # ERROR level ``` -------------------------------- ### Execute Neural Network Training Source: https://github.com/dickreuter/poker/blob/master/notebooks/train_card_nn.ipynb Run the training pipeline by creating augmented images and initiating the training process for a specific table. ```python table_name = "test" log.info(f"Start trainig for {table_name}") n = CardNeuralNetwork() log.info(f"Creating augmented images in {TRAIN_FOLDER}") n.create_augmented_images(table_name) n.train_neural_network() # n.save_model_to_disk() # n.save_model_to_db(stable_name) ``` -------------------------------- ### Update Configuration File Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/helper-utilities.md Persists runtime configuration changes to the disk. ```python def __init__(self, config_override_filename: str = None): ``` ```python def update_file(self) -> None: ``` ```python config = get_config() config.config.set('main', 'last_strategy', 'NewStrategy') config.update_file() # Write to disk ``` -------------------------------- ### take_screenshot() Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/screen-operations.md Captures the entire screen as a PIL Image object. ```APIDOC ## take_screenshot() ### Description Captures the entire screen as a PIL Image object. Returns the screenshot in RGB or RGBA format. ### Returns - **PIL.Image** - The captured screenshot. ``` -------------------------------- ### Configure GameLogger via INI Source: https://github.com/dickreuter/poker/blob/master/_autodocs/api-reference/game-logger.md The logger reads configuration settings from the poker/config.ini file. ```ini [logging] log_dir = log log_level = DEBUG database_url = mongodb://localhost/poker ```