Ejemplo n.º 1
0
    def __init__(self, threadID, name, counter, gui_signals):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.gui_signals = gui_signals
        self.name = name
        self.counter = counter
        self.loger = logging.getLogger('main')

        self.game_logger = GameLogger()
Ejemplo n.º 2
0
 def drawfigure(self):
     LogFilename = 'log'
     L = GameLogger(LogFilename)
     p_name = str(self.ui_analyser.combobox_strategy.currentText())
     data = L.get_fundschange_chart(p_name)
     self.fig.clf()
     self.axes = self.fig.add_subplot(111)  # create an axis
     self.axes.clear()   # discards the old graph
     self.axes.set_title('My Funds')
     self.axes.set_xlabel('Time')
     self.axes.set_ylabel('$')
     self.axes.plot(data, '-')  # plot data
     self.draw()
Ejemplo n.º 3
0
 def drawfigure(self):
     LogFilename = 'log'
     L = GameLogger(LogFilename)
     p_name = str(self.ui_analyser.combobox_strategy.currentText())
     data = L.get_fundschange_chart(p_name)
     self.fig.clf()
     self.axes = self.fig.add_subplot(111)  # create an axis
     self.axes.clear()  # discards the old graph
     self.axes.set_title('My Funds')
     self.axes.set_xlabel('Time')
     self.axes.set_ylabel('$')
     self.axes.plot(data, '-')  # plot data
     self.draw()
Ejemplo n.º 4
0
def test_find_backup_image():
    p = StrategyHandler()
    p.read_strategy()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = GameLogger()
    version = 4.21
    t = TableScreenBased(p, table_dict, gui_signals, game_logger, version)
    image_backup = 10
    t.current_round_pot = 1

    while t.current_round_pot > 0:
        try:
            file_name = get_dir(os.path.join("log", "pics", 'table_' + str(image_backup) + '.png'))
            t.screenshot = Image.open(file_name)
            t.get_pots()
            if t.current_round_pot < 0:
                log.info(f"current_round_pot :{t.current_round_pot}.")
                break
            # log.info(f"Use backup image {image_backup}.")
        except:
            pass
        image_backup -= 1
    log.info(f"Use backup image {image_backup}.")
    return image_backup
Ejemplo n.º 5
0
def get_table_delta():
    p = StrategyHandler()
    p.read_strategy()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = GameLogger()
    version = 4.21

    t = TableScreenBased(p, table_dict, gui_signals, game_logger, version)
    ready = False
    while (not ready):
        ready = t.take_screenshot(True, p) and \
                t.get_top_left_corner(p, gui_signals) and \
                t.get_gg_poker()
    log.debug(f"Top left corner: {t.tlc}")
    log.debug(f"GG Poker : {t.gg_poker}")

    delta_x = 308 + (t.tlc[0] - t.gg_poker[0])
    delta_y = 287 + (t.tlc[1] - t.gg_poker[1])

    log.debug(f"delta_x, delta_y : {delta_x}, {delta_y} ")
    return delta_x, delta_y
Ejemplo n.º 6
0
def test_get_raise_and_callers():
    table_scraper_name = 'GG_6TABLE'
    table_dict = mongo.get_table(table_scraper_name)
    # Mock signal
    gui_signals = MagicMock()
    h = History()
    # Game logger
    game_logger = GameLogger()
    p = StrategyHandler()
    strategy = p.read_strategy(
        strategy_override='test')  # Read default strategy.
    # p.update_strategy1(strategy, 'bigBlind', 2)
    # p.update_strategy1(strategy, 'smallBlind', 1)
    t = TableScreenBased(p, table_dict, gui_signals, game_logger, 0.0)

    t.init_get_other_players_info()
    '''
    dealer pos = 4. sb vs bb (me) 
    in positions.
    
    '''
    t.dealer_position = 4  # abs pos
    h.round_number = 0
    # t.position_utg_plus = t.get_utg_from_abs_pos(0, t.dealer_position)  # 5
    t.position_utg_plus = (t.total_players + 3 -
                           t.dealer_position) % t.total_players
    t.other_players[0]['pot'] = 2  # abs 1
    t.other_players[0]['utg_position'] = t.get_utg_from_abs_pos(
        1, t.dealer_position)  # 0
    t.other_players[0]['status'] = 1
    t.other_players[1]['pot'] = 0  # abs 2
    t.other_players[1]['utg_position'] = t.get_utg_from_abs_pos(
        2, t.dealer_position)  # 1
    t.other_players[1]['status'] = 0
    t.other_players[2]['pot'] = 0  # abs 3
    t.other_players[2]['utg_position'] = t.get_utg_from_abs_pos(
        3, t.dealer_position)  # 2
    t.other_players[2]['status'] = 0
    t.other_players[3]['pot'] = 0  # abs 4
    t.other_players[3]['utg_position'] = t.get_utg_from_abs_pos(
        4, t.dealer_position)  # 3
    t.other_players[3]['status'] = 0
    t.other_players[4]['pot'] = 3  # abs 5
    t.other_players[4]['utg_position'] = t.get_utg_from_abs_pos(
        5, t.dealer_position)  # 4
    t.other_players[4]['status'] = 1
    t.big_blind_position_abs_all = (
        t.dealer_position + 2) % 6  # 0 is myself, 1 is player to my left
    t.big_blind_position_abs_op = t.big_blind_position_abs_all - 1
    if h.round_number == 0:  # get by get_round_number
        reference_pot = float(p.selected_strategy['bigBlind'])  # 2.0
    else:
        reference_pot = 5
    logging.info(f'reference_pot:{reference_pot}')
    first_raiser, second_raiser, first_caller, \
    first_raiser_utg, second_raiser_utg, first_caller_utg\
        = t.get_raisers_and_callers(p, reference_pot, is_debug=True)
Ejemplo n.º 7
0
    def __init__(self, p):
        self.dealer_position = -1
        self.big_blind_position_abs_op = -1
        self.position_utg_plus = -1
        game_logger = GameLogger()
        gui_signals = MagicMock()

        super(TableScreenBased, self).__init__(p, gui_signals, game_logger,
                                               '3.05')
Ejemplo n.º 8
0
    def __init__(self, threadID, name, counter, gui_signals):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.gui_signals = gui_signals
        self.logger = logging.getLogger('main')
        self.logger.setLevel(logging.DEBUG)

        self.game_logger = GameLogger()
Ejemplo n.º 9
0
def test_get_table_delta1():
    p = StrategyHandler()
    p.read_strategy()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = GameLogger()
    version = 4.21

    log_file = get_dir(os.path.join("log", 'delta.txt'))
    f = open(log_file, "a")
    f.write("New Project\n")
    f.close()
    count = 0
    while True:
        t = TableScreenBased(p, table_dict, gui_signals, game_logger, version)
        ready = False
        while (not ready):
            ready = t.take_screenshot(True, p) and \
                    t.get_top_left_corner(p, gui_signals) and \
                    t.get_gg_poker()
        log.debug(f"Top left corner: {t.tlc}")
        log.debug(f"GG Poker : {t.gg_poker}")
        x, y = get_table_delta()
        update_delta(x, y)

        delta_x = 308 + (t.tlc[0] - t.gg_poker[0])
        delta_y = 287 + (t.tlc[1] - t.gg_poker[1])
        f = open(log_file, "a")
        f.write(f"delta_x, delta_y : {delta_x}, {delta_y} ")
        f.write("\n")
        f.write("---------------------------------------------------")
        f.write("\n")
        f.close()
        log.debug(f"delta_x, delta_y : {delta_x}, {delta_y} ")
        file_name = get_dir(os.path.join('log', 'pics', 'table_update_delta.png'))
        file_name1 = get_dir(os.path.join('log', 'pics', 'table_default_delta.png'))
        file_name2 = get_dir(os.path.join('log', 'pics', 'table_default_origin.png'))
        """
        Move table by delta_x = -8 , delta_y = -5 from config.ini
        """
        save_table_rectangle_cv2(t.screenshot, table_dict, file_name)
        reset_delta()
        save_table_rectangle_cv2(t.screenshot, table_dict, file_name1)
        t.screenshot.save(file_name2)
        count += 1
        if count >=1:
            reset_delta()
            break

    return True
Ejemplo n.º 10
0
def test_get_table_delta_rel2():
    p = StrategyHandler()
    p.read_strategy()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = GameLogger()
    version = 4.21
    log_file = get_dir(os.path.join("log", 'delta.txt'))
    f = open(log_file, "a")
    f.write("New Project\n")
    f.close()
    count = 0
    prefix = 'e'

    while True:
        t = TableScreenBased(p, table_dict, gui_signals, game_logger, version)

        t.screenshot = Image.open(get_dir(os.path.join('log', 'pics', 'table_' + prefix + '0.png')))
        t.get_gg_poker_rel()

        x = 308 - t.gg_poker_rel[0]
        y = 287 - t.gg_poker_rel[1]
        update_delta(x, y)  # update delta in config.ini
        f = open(log_file, "a")
        f.write(f"delta_x, delta_y : {x}, {y} ")
        f.write("\n")
        f.write("---------------------------------------------------")
        f.write("\n")
        f.close()
        log.debug(f"delta_x, delta_y : {x}, {y} ")
        file_name = get_dir(os.path.join('log', 'pics', 'table_update_delta.png'))
        file_name1 = get_dir(os.path.join('log', 'pics', 'table_default_delta.png'))
        """
        Move table by delta_x = -8 , delta_y = -5 from config.ini
        """
        save_table_rectangle_cv2(t.screenshot, table_dict, file_name)
        # reset delta to default in config.ini
        reset_delta()
        save_table_rectangle_cv2(t.screenshot, table_dict, file_name1)
        count += 1
        if count >=1:
            break

    return True
Ejemplo n.º 11
0
def test_table_tlc():
    p = StrategyHandler()
    p.read_strategy()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = GameLogger()
    version = 4.21
    t = TableScreenBased(p, table_dict, gui_signals, game_logger, version)
    ready = False
    while (not ready):
        ready = t.take_screenshot(True, p) and \
                t.get_top_left_corner(p, gui_signals)

    log.info(f"Top left corner: {t.tlc}")
Ejemplo n.º 12
0
def test_reverse_sheetname():
    log = logging.getLogger(__name__)
    # Get table_dict
    table_scraper_name = 'GG_6TABLE'
    table_dict = mongo.get_table(table_scraper_name)
    # Mock signal
    gui_signals = MagicMock()
    # Game logger
    game_logger = GameLogger()

    preflop_state = CurrentHandPreflopState()
    h = History()

    preflop_url = get_dir(os.path.join('tools', 'preflop.xlsx'))
    # mongoclient = MongoClient(f'mongodb://*****:*****@dickreuter.com/neuron_poker')
    # mongodb = mongoclient.neuron_poker
    # cursor = mongodb.internal.find()
    # c = cursor.next()
    # preflop_url = c['preflop_url']
    # log.info(f'preflop_url: {preflop_url}')
    h.preflop_sheet = pd.read_excel(preflop_url, sheet_name=None)
    p = StrategyHandler()
    p.read_strategy()  # Read default strategy.
    t = TableScreenBased(p, table_dict, gui_signals, game_logger, 0.0)
    t.dealer_position = 4
    t.position_utg_plus = t.get_utg_from_abs_pos(0, t.dealer_position)  # 5

    preflop_state.reset()
    # preflop_state.other_players = deepcopy(t.other_players)
    preflop_state.bot_preflop_position_utg = t.position_utg_plus  # 5
    preflop_state.bot_preflop_decision = 'Bet'
    preflop_state.preflop_raiser_positions.append(5)
    # preflop_state.preflop_raiser_positions.append(4)
    # preflop_state.preflop_caller_positions.append(5)
    preflop_state.rounds = 0

    for abs_pos in [5]:
        sheet_name = preflop_state.get_reverse_sheetname(abs_pos, t, h)
        log.info(f'abs_pos:{abs_pos}, sheet_name: {sheet_name}')
        ranges = preflop_state.get_rangecards_from_sheetname(
            abs_pos, sheet_name, t, h, p)
        log.info(f'{ranges}')
Ejemplo n.º 13
0
class ThreadManager(threading.Thread):
    def __init__(self, threadID, name, counter, gui_signals):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.gui_signals = gui_signals
        self.logger = logging.getLogger('main')
        self.logger.setLevel(logging.DEBUG)

        self.game_logger = GameLogger()

    def update_most_gui_items(self, preflop_state, p, m, t, d, h, gui_signals):
        try:
            sheet_name = t.preflop_sheet_name
        except:
            sheet_name = ''
        gui_signals.signal_decision.emit(str(d.decision + " " + sheet_name))
        gui_signals.signal_status.emit(d.decision)
        range2 = ''
        if hasattr(t, 'reverse_sheet_name'):
            range = t.reverse_sheet_name
            if hasattr(preflop_state, 'range_column_name'):
                range2 = " " + preflop_state.range_column_name + ""

        else:
            range = str(m.opponent_range)
        if range == '1': range = 'All cards'

        if t.gameStage != 'PreFlop' and p.selected_strategy['preflop_override']:
            sheet_name=preflop_state.preflop_sheet_name

        gui_signals.signal_label_number_update.emit('equity', str(np.round(t.abs_equity * 100, 2)) + "%")
        gui_signals.signal_label_number_update.emit('required_minbet', str(np.round(t.minBet,2)))
        gui_signals.signal_label_number_update.emit('required_mincall', str(np.round(t.minCall,2)))
        # gui_signals.signal_lcd_number_update.emit('potsize', t.totalPotValue)
        gui_signals.signal_label_number_update.emit('gamenumber',
                                                    str(int(self.game_logger.get_game_count(p.current_strategy))))
        gui_signals.signal_label_number_update.emit('assumed_players', str(int(t.assumedPlayers)))
        gui_signals.signal_label_number_update.emit('calllimit', str(np.round(d.finalCallLimit,2)))
        gui_signals.signal_label_number_update.emit('betlimit', str(np.round(d.finalBetLimit,2)))
        gui_signals.signal_label_number_update.emit('runs', str(int(m.runs)))
        gui_signals.signal_label_number_update.emit('sheetname', sheet_name)
        gui_signals.signal_label_number_update.emit('collusion_cards', str(m.collusion_cards))
        gui_signals.signal_label_number_update.emit('mycards', str(t.mycards))
        gui_signals.signal_label_number_update.emit('tablecards', str(t.cardsOnTable))
        gui_signals.signal_label_number_update.emit('opponent_range', str(range) + str(range2))
        gui_signals.signal_label_number_update.emit('mincallequity', str(np.round(t.minEquityCall, 2) * 100) + "%")
        gui_signals.signal_label_number_update.emit('minbetequity', str(np.round(t.minEquityBet, 2) * 100) + "%")
        gui_signals.signal_label_number_update.emit('outs', str(d.outs))
        gui_signals.signal_label_number_update.emit('initiative', str(t.other_player_has_initiative))
        gui_signals.signal_label_number_update.emit('round_pot', str(np.round(t.round_pot_value,2)))
        gui_signals.signal_label_number_update.emit('pot_multiple', str(np.round(d.pot_multiple,2)))

        if t.gameStage != 'PreFlop' and p.selected_strategy['use_relative_equity']:
            gui_signals.signal_label_number_update.emit('relative_equity', str(np.round(t.relative_equity,2) * 100) + "%")
            gui_signals.signal_label_number_update.emit('range_equity', str(np.round(t.range_equity,2) * 100) + "%")
        else:
            gui_signals.signal_label_number_update.emit('relative_equity', "")
            gui_signals.signal_label_number_update.emit('range_equity', "")



        # gui_signals.signal_lcd_number_update.emit('zero_ev', round(d.maxCallEV, 2))

        gui_signals.signal_pie_chart_update.emit(t.winnerCardTypeList)
        gui_signals.signal_curve_chart_update1.emit(h.histEquity, h.histMinCall, h.histMinBet, t.equity,
                                                    t.minCall, t.minBet,
                                                    'bo',
                                                    'ro')

        gui_signals.signal_curve_chart_update2.emit(t.power1, t.power2, t.minEquityCall, t.minEquityBet,
                                                    t.smallBlind, t.bigBlind,
                                                    t.maxValue_call,t.maxValue_bet,
                                                    t.maxEquityCall, t.max_X, t.maxEquityBet)

    def run(self):
        h = History()
        preflop_url, preflop_url_backup = u.get_preflop_sheet_url()
        try:
            h.preflop_sheet = pd.read_excel(preflop_url, sheetname=None)
        except:
            h.preflop_sheet = pd.read_excel(preflop_url_backup, sheetname=None)

        self.game_logger.clean_database()

        p = StrategyHandler()
        p.read_strategy()

        preflop_state = CurrentHandPreflopState()

        while True:
            if self.gui_signals.pause_thread:
                while self.gui_signals.pause_thread == True:
                    time.sleep(1)
                    if self.gui_signals.exit_thread == True: sys.exit()

            ready = False
            while (not ready):
                p.read_strategy()
                t = TableScreenBased(p, gui_signals, self.game_logger, version)
                mouse = MouseMoverTableBased(p.selected_strategy['pokerSite'])
                mouse.move_mouse_away_from_buttons_jump

                ready = t.take_screenshot(True, p) and \
                        t.get_top_left_corner(p) and \
                        t.check_for_captcha(mouse) and \
                        t.get_lost_everything(h, t, p, gui_signals) and \
                        t.check_for_imback(mouse) and \
                        t.get_my_cards(h) and \
                        t.get_new_hand(mouse, h, p) and \
                        t.get_table_cards(h) and \
                        t.upload_collusion_wrapper(p, h) and \
                        t.get_dealer_position() and \
                        t.get_snowie_advice(p, h) and \
                        t.check_fast_fold(h, p, mouse) and \
                        t.check_for_button() and \
                        t.get_round_number(h) and \
                        t.init_get_other_players_info() and \
                        t.get_other_player_names(p) and \
                        t.get_other_player_funds(p) and \
                        t.get_other_player_pots() and \
                        t.get_total_pot_value(h) and \
                        t.get_round_pot_value(h) and \
                        t.check_for_checkbutton() and \
                        t.get_other_player_status(p, h) and \
                        t.check_for_call() and \
                        t.check_for_betbutton() and \
                        t.check_for_allincall() and \
                        t.get_current_call_value(p) and \
                        t.get_current_bet_value(p)

            if not self.gui_signals.pause_thread:
                config = ConfigObj("config.ini")
                m = run_montecarlo_wrapper(p, self.gui_signals, config, ui, t, self.game_logger, preflop_state, h)
                d = Decision(t, h, p, self.game_logger)
                d.make_decision(t, h, p, self.logger, self.game_logger)
                if self.gui_signals.exit_thread: sys.exit()

                self.update_most_gui_items(preflop_state, p, m, t, d, h, self.gui_signals)

                self.logger.info(
                    "Equity: " + str(t.equity * 100) + "% -> " + str(int(t.assumedPlayers)) + " (" + str(
                        int(t.other_active_players)) + "-" + str(int(t.playersAhead)) + "+1) Plr")
                self.logger.info("Final Call Limit: " + str(d.finalCallLimit) + " --> " + str(t.minCall))
                self.logger.info("Final Bet Limit: " + str(d.finalBetLimit) + " --> " + str(t.minBet))
                self.logger.info(
                    "Pot size: " + str((t.totalPotValue)) + " -> Zero EV Call: " + str(round(d.maxCallEV, 2)))
                self.logger.info("+++++++++++++++++++++++ Decision: " + str(d.decision) + "+++++++++++++++++++++++")

                mouse_target = d.decision
                if mouse_target == 'Call' and t.allInCallButton:
                    mouse_target = 'Call2'
                mouse.mouse_action(mouse_target, t.tlc)

                t.time_action_completed = datetime.datetime.utcnow()

                filename = str(h.GameID) + "_" + str(t.gameStage) + "_" + str(h.round_number) + ".png"
                self.logger.debug("Saving screenshot: " + filename)
                pil_image = t.crop_image(t.entireScreenPIL, t.tlc[0], t.tlc[1], t.tlc[0] + 950, t.tlc[1] + 650)
                pil_image.save("log/screenshots/" + filename)

                self.gui_signals.signal_status.emit("Logging data")

                t_log_db = threading.Thread(name='t_log_db', target=self.game_logger.write_log_file, args=[p, h, t, d])
                t_log_db.daemon = True
                t_log_db.start()
                # self.game_logger.write_log_file(p, h, t, d)

                h.previousPot = t.totalPotValue
                h.histGameStage = t.gameStage
                h.histDecision = d.decision
                h.histEquity = t.equity
                h.histMinCall = t.minCall
                h.histMinBet = t.minBet
                h.hist_other_players = t.other_players
                h.first_raiser = t.first_raiser
                h.first_caller = t.first_caller
                h.previous_decision = d.decision
                h.lastRoundGameID = h.GameID
                h.previous_round_pot_value=t.round_pot_value
                h.last_round_bluff = False if t.currentBluff == 0 else True
                if t.gameStage == 'PreFlop':
                    preflop_state.update_values(t, d.decision, h, d)
                self.logger.info("=========== round end ===========")
Ejemplo n.º 14
0
    def __init__(self, ui_main_window):
        self.logger = logging.getLogger('gui')

        l = GameLogger()
        l.clean_database()

        self.p = StrategyHandler()
        self.p.read_strategy()
        p = self.p

        self.pause_thread = True
        self.exit_thread = False

        QObject.__init__(self)
        self.strategy_items_with_multipliers = {
            "always_call_low_stack_multiplier": 1,
            "out_multiplier": 1,
            "FlopBluffMaxEquity": 100,
            "TurnBluffMaxEquity": 100,
            "RiverBluffMaxEquity": 100,
            "max_abs_fundchange": 100,
            "RiverCheckDeceptionMinEquity": 100,
            "TurnCheckDeceptionMinEquity": 100,
            "pre_flop_equity_reduction_by_position": 100,
            "pre_flop_equity_increase_if_bet": 100,
            "pre_flop_equity_increase_if_call": 100,
            "minimum_bet_size": 1,
            "range_multiple_players": 100,
            "range_utg0": 100,
            "range_utg1": 100,
            "range_utg2": 100,
            "range_utg3": 100,
            "range_utg4": 100,
            "range_utg5": 100,
            "PreFlopCallPower": 1,
            "secondRiverBetPotMinEquity": 100,
            "FlopBetPower": 1,
            "betPotRiverEquityMaxBBM": 1,
            "TurnMinBetEquity": 100,
            "PreFlopBetPower": 1,
            "potAdjustmentPreFlop": 1,
            "RiverCallPower": 1,
            "minBullyEquity": 100,
            "PreFlopMinBetEquity": 100,
            "PreFlopMinCallEquity": 100,
            "BetPlusInc": 1,
            "FlopMinCallEquity": 100,
            "secondRoundAdjustmentPreFlop": 100,
            "FlopBluffMinEquity": 100,
            "TurnBluffMinEquity": 100,
            "FlopCallPower": 1,
            "TurnCallPower": 1,
            "RiverMinCallEquity": 100,
            "CoveredPlayersCallLikelihoodFlop": 100,
            "TurnMinCallEquity": 100,
            "secondRoundAdjustment": 100,
            "maxPotAdjustmentPreFlop": 100,
            "bullyDivider": 1,
            "maxBullyEquity": 100,
            "alwaysCallEquity": 100,
            "PreFlopMaxBetEquity": 100,
            "RiverBetPower": 1,
            "minimumLossForIteration": -1,
            "initialFunds": 100,
            "initialFunds2": 100,
            "potAdjustment": 1,
            "FlopCheckDeceptionMinEquity": 100,
            "bigBlind": 100,
            "secondRoundAdjustmentPowerIncrease": 1,
            "considerLastGames": 1,
            "betPotRiverEquity": 100,
            "RiverBluffMinEquity": 100,
            "smallBlind": 100,
            "TurnBetPower": 1,
            "FlopMinBetEquity": 100,
            "strategyIterationGames": 1,
            "RiverMinBetEquity": 100,
            "maxPotAdjustment": 100
        }
        self.pokersite_types = ['PP', 'PS2', 'SN', 'PP_old']

        self.ui = ui_main_window
        self.progressbar_value = 0

        # Main Window matplotlip widgets
        self.gui_funds = FundsPlotter(ui_main_window, p)
        self.gui_bar = BarPlotter(ui_main_window, p)
        self.gui_curve = CurvePlot(ui_main_window, p)
        self.gui_pie = PiePlotter(ui_main_window,
                                  winnerCardTypeList={'Highcard': 22})

        # main window status update signal connections
        self.signal_progressbar_increase.connect(self.increase_progressbar)
        self.signal_progressbar_reset.connect(self.reset_progressbar)
        self.signal_status.connect(self.update_mainwindow_status)
        self.signal_decision.connect(self.update_mainwindow_decision)

        self.signal_lcd_number_update.connect(self.update_lcd_number)
        self.signal_label_number_update.connect(self.update_label_number)

        self.signal_bar_chart_update.connect(
            lambda: self.gui_bar.drawfigure(l, p.current_strategy))

        self.signal_funds_chart_update.connect(
            lambda: self.gui_funds.drawfigure(l))
        self.signal_curve_chart_update1.connect(self.gui_curve.update_plots)
        self.signal_curve_chart_update2.connect(self.gui_curve.update_lines)
        self.signal_pie_chart_update.connect(self.gui_pie.drawfigure)
        self.signal_open_setup.connect(lambda: self.open_setup(p, l))

        ui_main_window.button_genetic_algorithm.clicked.connect(
            lambda: self.open_genetic_algorithm(p, l))
        ui_main_window.button_log_analyser.clicked.connect(
            lambda: self.open_strategy_analyser(p, l))
        ui_main_window.button_strategy_editor.clicked.connect(
            lambda: self.open_strategy_editor())
        ui_main_window.button_pause.clicked.connect(
            lambda: self.pause(ui_main_window, p))
        ui_main_window.button_resume.clicked.connect(
            lambda: self.resume(ui_main_window, p))

        ui_main_window.pushButton_setup.clicked.connect(
            lambda: self.open_setup(p, l))
        ui_main_window.pushButton_help.clicked.connect(
            lambda: self.open_help(p, l))

        self.signal_update_strategy_sliders.connect(
            lambda: self.update_strategy_editor_sliders(p.current_strategy))

        playable_list = p.get_playable_strategy_list()
        ui_main_window.comboBox_current_strategy.addItems(playable_list)
        ui_main_window.comboBox_current_strategy.currentIndexChanged[
            str].connect(lambda: self.signal_update_selected_strategy(l, p))
        config = ConfigObj("config.ini")
        initial_selection = config['last_strategy']
        for i in [
                i for i, x in enumerate(playable_list)
                if x == initial_selection
        ]:
            idx = i
        ui_main_window.comboBox_current_strategy.setCurrentIndex(idx)
Ejemplo n.º 15
0
def test_round_details():
    log = logging.getLogger(__name__)
    l = GameLogger()
    df = l.get_round_detail(GameID='365943240')
    log.info(df)
Ejemplo n.º 16
0
def test_worst_games1():
    log = logging.getLogger(__name__)
    l = GameLogger()
    df = l.get_worst_games('Default')
    log.info(df)
Ejemplo n.º 17
0
def run_genetic_algorithm(write, logger):
    logger.info("===Running genetic algorithm===")
    L = GameLogger()
    GeneticAlgorithm(write, logger, L)
Ejemplo n.º 18
0
class ThreadManager(threading.Thread):
    def __init__(self, threadID, name, counter, gui_signals):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.gui_signals = gui_signals
        self.logger = logging.getLogger('main')
        self.logger.setLevel(logging.DEBUG)

        self.game_logger = GameLogger()

    def update_most_gui_items(self, preflop_state, p, m, t, d, h, gui_signals):
        try:
            sheet_name = t.preflop_sheet_name
        except:
            sheet_name = ''
        gui_signals.signal_decision.emit(str(d.decision + " " + sheet_name))
        gui_signals.signal_status.emit(d.decision)
        range2 = ''
        if hasattr(t, 'reverse_sheet_name'):
            range = t.reverse_sheet_name
            if hasattr(preflop_state, 'range_column_name'):
                range2 = " " + preflop_state.range_column_name + ""

        else:
            range = str(m.opponent_range)
        if range == '1': range = 'All cards'

        if t.gameStage != 'PreFlop' and p.selected_strategy['preflop_override']:
            sheet_name = preflop_state.preflop_sheet_name

        gui_signals.signal_label_number_update.emit(
            'equity',
            str(np.round(t.abs_equity * 100, 2)) + "%")
        gui_signals.signal_label_number_update.emit('required_minbet',
                                                    str(np.round(t.minBet, 2)))
        gui_signals.signal_label_number_update.emit(
            'required_mincall', str(np.round(t.minCall, 2)))
        # gui_signals.signal_lcd_number_update.emit('potsize', t.totalPotValue)
        gui_signals.signal_label_number_update.emit(
            'gamenumber',
            str(int(self.game_logger.get_game_count(p.current_strategy))))
        gui_signals.signal_label_number_update.emit('assumed_players',
                                                    str(int(t.assumedPlayers)))
        gui_signals.signal_label_number_update.emit(
            'calllimit', str(np.round(d.finalCallLimit, 2)))
        gui_signals.signal_label_number_update.emit(
            'betlimit', str(np.round(d.finalBetLimit, 2)))
        gui_signals.signal_label_number_update.emit('runs', str(int(m.runs)))
        gui_signals.signal_label_number_update.emit('sheetname', sheet_name)
        gui_signals.signal_label_number_update.emit('collusion_cards',
                                                    str(m.collusion_cards))
        gui_signals.signal_label_number_update.emit('mycards', str(t.mycards))
        gui_signals.signal_label_number_update.emit('tablecards',
                                                    str(t.cardsOnTable))
        gui_signals.signal_label_number_update.emit('opponent_range',
                                                    str(range) + str(range2))
        gui_signals.signal_label_number_update.emit(
            'mincallequity',
            str(np.round(t.minEquityCall, 2) * 100) + "%")
        gui_signals.signal_label_number_update.emit(
            'minbetequity',
            str(np.round(t.minEquityBet, 2) * 100) + "%")
        gui_signals.signal_label_number_update.emit('outs', str(d.outs))
        gui_signals.signal_label_number_update.emit(
            'initiative', str(t.other_player_has_initiative))
        gui_signals.signal_label_number_update.emit(
            'round_pot', str(np.round(t.round_pot_value, 2)))
        gui_signals.signal_label_number_update.emit(
            'pot_multiple', str(np.round(d.pot_multiple, 2)))

        if t.gameStage != 'PreFlop' and p.selected_strategy[
                'use_relative_equity']:
            gui_signals.signal_label_number_update.emit(
                'relative_equity',
                str(np.round(t.relative_equity, 2) * 100) + "%")
            gui_signals.signal_label_number_update.emit(
                'range_equity',
                str(np.round(t.range_equity, 2) * 100) + "%")
        else:
            gui_signals.signal_label_number_update.emit('relative_equity', "")
            gui_signals.signal_label_number_update.emit('range_equity', "")

        # gui_signals.signal_lcd_number_update.emit('zero_ev', round(d.maxCallEV, 2))

        gui_signals.signal_pie_chart_update.emit(t.winnerCardTypeList)
        gui_signals.signal_curve_chart_update1.emit(h.histEquity,
                                                    h.histMinCall,
                                                    h.histMinBet, t.equity,
                                                    t.minCall, t.minBet, 'bo',
                                                    'ro')

        gui_signals.signal_curve_chart_update2.emit(
            t.power1, t.power2, t.minEquityCall, t.minEquityBet, t.smallBlind,
            t.bigBlind, t.maxValue_call, t.maxValue_bet, t.maxEquityCall,
            t.max_X, t.maxEquityBet)

    def run(self):
        h = History()
        preflop_url, preflop_url_backup = u.get_preflop_sheet_url()
        try:
            h.preflop_sheet = pd.read_excel(preflop_url, sheetname=None)
        except:
            h.preflop_sheet = pd.read_excel(preflop_url_backup, sheetname=None)

        self.game_logger.clean_database()

        p = StrategyHandler()
        p.read_strategy()

        preflop_state = CurrentHandPreflopState()

        while True:
            if self.gui_signals.pause_thread:
                while self.gui_signals.pause_thread == True:
                    time.sleep(1)
                    if self.gui_signals.exit_thread == True: sys.exit()

            ready = False
            while (not ready):
                p.read_strategy()
                t = TableScreenBased(p, gui_signals, self.game_logger, version)
                mouse = MouseMoverTableBased(p.selected_strategy['pokerSite'])
                mouse.move_mouse_away_from_buttons_jump

                ready = t.take_screenshot(True, p) and \
                        t.get_top_left_corner(p) and \
                        t.check_for_captcha(mouse) and \
                        t.get_lost_everything(h, t, p, gui_signals) and \
                        t.check_for_imback(mouse) and \
                        t.get_my_cards(h) and \
                        t.get_new_hand(mouse, h, p) and \
                        t.get_table_cards(h) and \
                        t.upload_collusion_wrapper(p, h) and \
                        t.get_dealer_position() and \
                        t.get_snowie_advice(p, h) and \
                        t.check_fast_fold(h, p, mouse) and \
                        t.check_for_button() and \
                        t.get_round_number(h) and \
                        t.init_get_other_players_info() and \
                        t.get_other_player_names(p) and \
                        t.get_other_player_funds(p) and \
                        t.get_other_player_pots() and \
                        t.get_total_pot_value(h) and \
                        t.get_round_pot_value(h) and \
                        t.check_for_checkbutton() and \
                        t.get_other_player_status(p, h) and \
                        t.check_for_call() and \
                        t.check_for_betbutton() and \
                        t.check_for_allincall() and \
                        t.get_current_call_value(p) and \
                        t.get_current_bet_value(p)

            if not self.gui_signals.pause_thread:
                config = ConfigObj("config.ini")
                m = run_montecarlo_wrapper(p, self.gui_signals, config, ui, t,
                                           self.game_logger, preflop_state, h)
                d = Decision(t, h, p, self.game_logger)
                d.make_decision(t, h, p, self.logger, self.game_logger)
                if self.gui_signals.exit_thread: sys.exit()

                self.update_most_gui_items(preflop_state, p, m, t, d, h,
                                           self.gui_signals)

                self.logger.info("Equity: " + str(t.equity * 100) + "% -> " +
                                 str(int(t.assumedPlayers)) + " (" +
                                 str(int(t.other_active_players)) + "-" +
                                 str(int(t.playersAhead)) + "+1) Plr")
                self.logger.info("Final Call Limit: " + str(d.finalCallLimit) +
                                 " --> " + str(t.minCall))
                self.logger.info("Final Bet Limit: " + str(d.finalBetLimit) +
                                 " --> " + str(t.minBet))
                self.logger.info("Pot size: " + str((t.totalPotValue)) +
                                 " -> Zero EV Call: " +
                                 str(round(d.maxCallEV, 2)))
                self.logger.info("+++++++++++++++++++++++ Decision: " +
                                 str(d.decision) + "+++++++++++++++++++++++")

                mouse_target = d.decision
                if mouse_target == 'Call' and t.allInCallButton:
                    mouse_target = 'Call2'
                mouse.mouse_action(mouse_target, t.tlc)

                t.time_action_completed = datetime.datetime.utcnow()

                filename = str(h.GameID) + "_" + str(t.gameStage) + "_" + str(
                    h.round_number) + ".png"
                self.logger.debug("Saving screenshot: " + filename)
                pil_image = t.crop_image(t.entireScreenPIL, t.tlc[0], t.tlc[1],
                                         t.tlc[0] + 950, t.tlc[1] + 650)
                pil_image.save("log/screenshots/" + filename)

                self.gui_signals.signal_status.emit("Logging data")

                t_log_db = threading.Thread(
                    name='t_log_db',
                    target=self.game_logger.write_log_file,
                    args=[p, h, t, d])
                t_log_db.daemon = True
                t_log_db.start()
                # self.game_logger.write_log_file(p, h, t, d)

                h.previousPot = t.totalPotValue
                h.histGameStage = t.gameStage
                h.histDecision = d.decision
                h.histEquity = t.equity
                h.histMinCall = t.minCall
                h.histMinBet = t.minBet
                h.hist_other_players = t.other_players
                h.first_raiser = t.first_raiser
                h.first_caller = t.first_caller
                h.previous_decision = d.decision
                h.lastRoundGameID = h.GameID
                h.previous_round_pot_value = t.round_pot_value
                h.last_round_bluff = False if t.currentBluff == 0 else True
                if t.gameStage == 'PreFlop':
                    preflop_state.update_values(t, d.decision, h, d)
                self.logger.info("=========== round end ===========")
Ejemplo n.º 19
0
    def __init__(self, ui_main_window):
        self.logger = logging.getLogger('gui')

        l = GameLogger()
        l.clean_database()

        self.p = StrategyHandler()
        self.p.read_strategy()
        p = self.p

        self.pause_thread = True
        self.exit_thread = False

        QObject.__init__(self)
        self.strategy_items_with_multipliers = {
            "always_call_low_stack_multiplier": 1,
            "out_multiplier": 1,
            "FlopBluffMaxEquity": 100,
            "TurnBluffMaxEquity": 100,
            "RiverBluffMaxEquity": 100,
            "max_abs_fundchange": 100,
            "RiverCheckDeceptionMinEquity": 100,
            "TurnCheckDeceptionMinEquity": 100,
            "pre_flop_equity_reduction_by_position": 100,
            "pre_flop_equity_increase_if_bet": 100,
            "pre_flop_equity_increase_if_call": 100,
            "minimum_bet_size": 1,
            "range_multiple_players": 100,
            "range_utg0": 100,
            "range_utg1": 100,
            "range_utg2": 100,
            "range_utg3": 100,
            "range_utg4": 100,
            "range_utg5": 100,
            "PreFlopCallPower": 1,
            "secondRiverBetPotMinEquity": 100,
            "FlopBetPower": 1,
            "betPotRiverEquityMaxBBM": 1,
            "TurnMinBetEquity": 100,
            "PreFlopBetPower": 1,
            "potAdjustmentPreFlop": 1,
            "RiverCallPower": 1,
            "minBullyEquity": 100,
            "PreFlopMinBetEquity": 100,
            "PreFlopMinCallEquity": 100,
            "BetPlusInc": 1,
            "FlopMinCallEquity": 100,
            "secondRoundAdjustmentPreFlop": 100,
            "FlopBluffMinEquity": 100,
            "TurnBluffMinEquity": 100,
            "FlopCallPower": 1,
            "TurnCallPower": 1,
            "RiverMinCallEquity": 100,
            "CoveredPlayersCallLikelihoodFlop": 100,
            "TurnMinCallEquity": 100,
            "secondRoundAdjustment": 100,
            "maxPotAdjustmentPreFlop": 100,
            "bullyDivider": 1,
            "maxBullyEquity": 100,
            "alwaysCallEquity": 100,
            "PreFlopMaxBetEquity": 100,
            "RiverBetPower": 1,
            "minimumLossForIteration": -1,
            "initialFunds": 100,
            "initialFunds2": 100,
            "potAdjustment": 1,
            "FlopCheckDeceptionMinEquity": 100,
            "bigBlind": 100,
            "secondRoundAdjustmentPowerIncrease": 1,
            "considerLastGames": 1,
            "betPotRiverEquity": 100,
            "RiverBluffMinEquity": 100,
            "smallBlind": 100,
            "TurnBetPower": 1,
            "FlopMinBetEquity": 100,
            "strategyIterationGames": 1,
            "RiverMinBetEquity": 100,
            "maxPotAdjustment": 100
        }
        self.pokersite_types = ['PP', 'PS2', 'SN', 'PP_old']

        self.ui = ui_main_window
        self.progressbar_value = 0

        # Main Window matplotlip widgets
        self.gui_funds = FundsPlotter(ui_main_window, p)
        self.gui_bar = BarPlotter(ui_main_window, p)
        self.gui_curve = CurvePlot(ui_main_window, p)
        self.gui_pie = PiePlotter(ui_main_window, winnerCardTypeList={'Highcard': 22})

        # main window status update signal connections
        self.signal_progressbar_increase.connect(self.increase_progressbar)
        self.signal_progressbar_reset.connect(self.reset_progressbar)
        self.signal_status.connect(self.update_mainwindow_status)
        self.signal_decision.connect(self.update_mainwindow_decision)

        self.signal_lcd_number_update.connect(self.update_lcd_number)
        self.signal_label_number_update.connect(self.update_label_number)

        self.signal_bar_chart_update.connect(lambda: self.gui_bar.drawfigure(l, p.current_strategy))

        self.signal_funds_chart_update.connect(lambda: self.gui_funds.drawfigure(l))
        self.signal_curve_chart_update1.connect(self.gui_curve.update_plots)
        self.signal_curve_chart_update2.connect(self.gui_curve.update_lines)
        self.signal_pie_chart_update.connect(self.gui_pie.drawfigure)
        self.signal_open_setup.connect(lambda: self.open_setup(p, l))

        ui_main_window.button_genetic_algorithm.clicked.connect(lambda: self.open_genetic_algorithm(p, l))
        ui_main_window.button_log_analyser.clicked.connect(lambda: self.open_strategy_analyser(p, l))
        ui_main_window.button_strategy_editor.clicked.connect(lambda: self.open_strategy_editor())
        ui_main_window.button_pause.clicked.connect(lambda: self.pause(ui_main_window, p))
        ui_main_window.button_resume.clicked.connect(lambda: self.resume(ui_main_window, p))

        ui_main_window.pushButton_setup.clicked.connect(lambda: self.open_setup(p, l))
        ui_main_window.pushButton_help.clicked.connect(lambda: self.open_help(p, l))

        self.signal_update_strategy_sliders.connect(lambda: self.update_strategy_editor_sliders(p.current_strategy))

        playable_list = p.get_playable_strategy_list()
        ui_main_window.comboBox_current_strategy.addItems(playable_list)
        ui_main_window.comboBox_current_strategy.currentIndexChanged[str].connect(
            lambda: self.signal_update_selected_strategy(l, p))
        config = ConfigObj("config.ini")
        initial_selection = config['last_strategy']
        for i in [i for i, x in enumerate(playable_list) if x == initial_selection]:
            idx = i
        ui_main_window.comboBox_current_strategy.setCurrentIndex(idx)