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

        self.game_logger = GameLogger()
Ejemplo n.º 2
0
 def drawfigure(self, my_computer_only):
     LogFilename = 'log'
     L = GameLogger(LogFilename)
     p_name = str(self.ui_analyser.combobox_strategy.currentText())
     data = L.get_fundschange_chart(p_name, my_computer_only)
     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 init_table(file, round_number=0, strategy='Default1'):
    # LOG_FILENAME = 'testing.log'
    logger = logging.getLogger('tester')
    gui_signals = MagicMock()
    p = StrategyHandler()
    p.read_strategy(strategy_override=strategy)
    h = main.History()
    u = UpdateChecker()
    c = requests.post(URL + "get_internal")[0]
    preflop_url = c['preflop_url']
    # preflop_url = 'decisionmaker/preflop.xlsx'
    h.preflop_sheet = pd.read_excel(preflop_url,
                                    sheet_name=None,
                                    engine='openpyxl')
    game_logger = GameLogger()
    t = main.TableScreenBased(p, {}, gui_signals, game_logger, 0.0)
    t.entireScreenPIL = Image.open(file)
    t.get_top_left_corner(p)
    t.get_dealer_position()
    t.get_my_funds(h, p)
    t.get_my_cards_nn(h)
    # t.get_table_cards_nn(h)
    t.get_round_number(h)
    h.round_number = round_number
    t.init_get_other_players_info()
    t.get_other_player_names(p)
    t.get_other_player_funds(p)
    t.get_other_player_pots()
    t.get_other_player_status(p, h)
    t.check_for_checkbutton()
    t.check_for_call()
    t.check_for_betbutton()
    t.check_for_allincall()
    t.get_current_call_value(p)
    t.get_current_bet_value(p)
    p = MagicMock()
    gui_signals = MagicMock()
    t.totalPotValue = 0.5
    t.equity = 0.5
    return t, p, gui_signals, h, logger
Ejemplo n.º 4
0
class ThreadManager(threading.Thread):
    def __init__(self, threadID, name, counter, gui_signals, updater):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.gui_signals = gui_signals
        self.updater = updater
        self.name = name
        self.counter = counter
        self.loger = logging.getLogger('main')

        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):
        log = logging.getLogger(__name__)
        history = History()
        preflop_url, preflop_url_backup = self.updater.get_preflop_sheet_url()
        try:
            history.preflop_sheet = pd.read_excel(preflop_url,
                                                  sheet_name=None,
                                                  engine='openpyxl')
        except:
            history.preflop_sheet = pd.read_excel(preflop_url_backup,
                                                  sheet_name=None,
                                                  engine='openpyxl')

        self.game_logger.clean_database()

        strategy = StrategyHandler()
        strategy.read_strategy()

        preflop_state = CurrentHandPreflopState()
        mongo = MongoManager()
        table_scraper_name = None

        while True:
            # reload table if changed
            config = ConfigObj(CONFIG_FILENAME)
            if table_scraper_name != config['table_scraper_name']:
                table_scraper_name = config['table_scraper_name']
                log.info(
                    f"Loading table scraper info for {table_scraper_name}")
                table_dict = mongo.get_table(table_scraper_name)

            if self.gui_signals.pause_thread:
                while self.gui_signals.pause_thread:
                    time.sleep(0.5)
                    if self.gui_signals.exit_thread:
                        sys.exit()

            ready = False
            while not ready:
                strategy.read_strategy()
                table = TableScreenBased(strategy, table_dict,
                                         self.gui_signals, self.game_logger,
                                         version)
                mouse = MouseMoverTableBased(table_dict)
                mouse.move_mouse_away_from_buttons_jump()

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

            if not self.gui_signals.pause_thread:
                config = ConfigObj(CONFIG_FILENAME)
                m = run_montecarlo_wrapper(strategy, self.gui_signals, config,
                                           ui, table, self.game_logger,
                                           preflop_state, history)
                self.gui_signals.signal_progressbar_increase.emit(20)
                d = Decision(table, history, strategy, self.game_logger)
                d.make_decision(table, history, strategy, self.game_logger)
                self.gui_signals.signal_progressbar_increase.emit(10)
                if self.gui_signals.exit_thread: sys.exit()

                self.update_most_gui_items(preflop_state, strategy, m, table,
                                           d, history, self.gui_signals)

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

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

                table.time_action_completed = datetime.datetime.utcnow()

                filename = str(history.GameID) + "_" + str(
                    table.gameStage) + "_" + str(history.round_number) + ".png"
                log.debug("Saving screenshot: " + filename)
                pil_image = table.crop_image(table.entireScreenPIL,
                                             table.tlc[0], table.tlc[1],
                                             table.tlc[0] + 950,
                                             table.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=[strategy, history, table, d])
                t_log_db.daemon = True
                t_log_db.start()
                # self.game_logger.write_log_file(strategy, history, table, d)

                history.previousPot = table.totalPotValue
                history.histGameStage = table.gameStage
                history.histDecision = d.decision
                history.histEquity = table.equity
                history.histMinCall = table.minCall
                history.histMinBet = table.minBet
                history.hist_other_players = table.other_players
                history.first_raiser = table.first_raiser
                history.first_caller = table.first_caller
                history.previous_decision = d.decision
                history.lastRoundGameID = history.GameID
                history.previous_round_pot_value = table.round_pot_value
                history.last_round_bluff = False if table.currentBluff == 0 else True
                if table.gameStage == 'PreFlop':
                    preflop_state.update_values(table, d.decision, history, d)
                mongo.increment_plays(table_scraper_name)
                log.info("=========== round end ===========")
Ejemplo n.º 5
0
def run_genetic_algorithm(write, logger):
    logger.info("===Running genetic algorithm===")
    L = GameLogger()
    GeneticAlgorithm(write, logger, L)