Example #1
0
def test_table_preflop_zenith():
    # tlc = get_table_tlc()
    # Init table function
    p = StrategyHandler()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = MagicMock()
    version = 4.21
    SB = 0.5
    prefix = 'e'

    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_dealer_position()
    t.get_miss_player()
    p_Zenith = CurrentHandPreflopStateZenith()
    p_Zenith.reset()
    # Specify miss player or calculate through t.get_miss_player().
    p_Zenith.miss_player = t.miss_player
    p_Zenith.dealer_position = t.dealer_position
    p_Zenith.small_blind = SB
    p_Zenith.abs_to_rel()

    table_preflop_zenith(t, p_Zenith, prefix, -2, 20)

    print(p_Zenith.actions)
Example #2
0
def test_preflop_nodelist2():
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    t = TableScraper(table_dict)
    t.screenshot = Image.open(os.path.join(os.environ['test_src'], '14.png'))
    t.crop_from_top_left_corner2(select_table=3)
    if is_debug:
        t.screenshot.save('log/pics/active_player2.png')
    preflop_state_Zenith = CurrentHandPreflopStateZenith()
    h = History()
    preflop_state_Zenith.get_players_status(t)
Example #3
0
def test_table_find_abs_pos():
    p_Zenith = CurrentHandPreflopStateZenith()
    p_Zenith.reset()
    p_Zenith.dealer_position = 1
    p_Zenith.abs_to_rel()
    p_Zenith.small_blind = 0.4

    abs_pos = p_Zenith.find_abs_pos(0)
    print(abs_pos)
Example #4
0
def test_active_player():
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    t = TableScraper(table_dict)
    t.screenshot = Image.open(os.path.join(os.environ['test_src'], '27.png'))
    t.crop_from_top_left_corner2(select_table=1)
    if is_debug:
        t.screenshot.save('log/pics/active_player.png')
    preflop_state_Zenith = CurrentHandPreflopStateZenith()
    h = History()
    preflop_state_Zenith.get_players_status(t)

    pytest.assume(preflop_state_Zenith.action == 'LJ_1.0')
    pytest.assume(preflop_state_Zenith.now_player_order == 1)
Example #5
0
def test_table_video():
    # Prepare table
    tlc = [1557, 289]
    someone_stop = False

    # Init table function
    p = StrategyHandler()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = MagicMock()
    version = 4.21
    t = TableScreenBased(p, table_dict, gui_signals, game_logger, version)
    t.screenshot = get_screenshot('cropped', tlc)
    preflop_state_Zenith = CurrentHandPreflopStateZenith()

    if someone_stop:
        sys.exit()
    ready = False
    image_backup = 10
    t.get_players_in_game()
    exclude = set(range(6)) - set(t.players_in_game)
    t.get_player_pots(skip=list(exclude))
    log.info(f"{t.players_in_game}")
    log.info(f"{t.player_pots}")
Example #6
0
def test_run():
    """
    Zenith test methodlogy:

    1. test by test_run() for multiple games.
    2. Locate each err game and
    3. test by test_table_preflop_zenith()

    parameter: SB= , table name=

    """
    log_file = get_dir(os.path.join("log", 'jobs.txt'))
    f = open(log_file, "a")
    f.write("New Project\n")
    f.close()
    table_name = "NLH Gold 12 - $1 / $2"
    tlc = get_table_tlc1(table_name)
    # x, y = get_table_delta()
    # update_delta(x, y)
    # Init table function
    p = StrategyHandler()
    p.read_strategy()
    mongo = MongoManager()
    table_dict = mongo.get_table('GG_6TABLE')
    gui_signals = MagicMock()
    gui_signals.select_table = 0  # select table
    game_logger = MagicMock()
    version = 4.21
    SB = 0.5
    # miss_player = [1]
    prefix = ''
    p_Zenith = CurrentHandPreflopStateZenith()
    jobs = []
    thread_ready = True
    count = 0
    while True:

        t = TableScreenBased(p, table_dict, gui_signals, game_logger, version)
        while thread_ready:
            if p_Zenith.dealer_position is not None:
                # Get new dealer pos.
                t.screenshot = get_screenshot('cropped', 'temp', tlc)
                t.get_dealer_position()
                t.get_miss_player()
                # Compare with previous handled dealer.
                if p_Zenith.dealer_position != t.dealer_position:
                    p_Zenith.reset()
                    p_Zenith.miss_player = t.miss_player
                    p_Zenith.dealer_position = t.dealer_position
                    p_Zenith.small_blind = SB
                    p_Zenith.abs_to_rel()
                    break
                time.sleep(0.5)
            else:
                # Initialize 1st table information.
                t.screenshot = get_screenshot('cropped', 'temp', tlc)
                t.get_dealer_position()
                p_Zenith.dealer_position = -1

        # d = threading.Thread(name='t_take_screenshots', target=get_screenshot1,
        #                      args=[20, prefix, tlc])  # 12 for test, 18 for backup
        # d.daemon = True
        # t1 = threading.Thread(name='t_run_preflopZenith1', target=table_preflop_zenith,
        #                       args=[t, p_Zenith, prefix, 0, 20])  # if preflop finished, break.
        if thread_ready:
            if count == 0:
                prefix = 'a'
            elif count == 1:
                prefix = 'b'
            elif count == 2:
                prefix = 'c'
            elif count == 3:
                prefix = 'd'
            elif count == 4:
                prefix = 'e'
            log.debug(f"count:{count} and prefix: {prefix}")
            for file_name in glob.glob(
                    get_dir(
                        os.path.join("log", "pics",
                                     'table_' + prefix + '*.png'))):
                # file_name = get_dir(os.path.join("log", "pics", 'table_' + str(i) + '.png'))
                if os.path.isfile(file_name):
                    try:
                        log.info(f"Remove {prefix} files")
                        os.remove(file_name)
                    except PermissionError:
                        time.sleep(0.5)
                        try:
                            os.remove(file_name)
                        except:
                            pass
            d = threading.Thread(name='t_take_screenshots',
                                 target=get_screenshot1,
                                 args=[20, prefix,
                                       tlc])  # 12 for test, 18 for backup
            d.daemon = True
            t1 = threading.Thread(name='t_run_preflopZenith1',
                                  target=table_preflop_zenith,
                                  args=[t, p_Zenith, prefix, 0,
                                        20])  # if preflop finished, break.

            thread_ready = False
            d.start()
            t1.start()
            d.join(
                0.1)  # after the non-daemon stops, daemon wait for 2 sec only.
            t1.join()
        if not (t1.is_alive() or d.is_alive()):
            thread_ready = True
            count += 1
            jobs.append({
                'dealer': p_Zenith.dealer_position,
                # 'miss_player': p_Zenith.miss_player,
                'last file_name': p_Zenith.file_name,
                'actions': p_Zenith.actions
            })
            f = open(log_file, "a")
            f.write(str({'dealer': p_Zenith.dealer_position}))
            f.write("\n")
            f.write(str({'last file_name': p_Zenith.file_name}))
            f.write("\n")

            f.write(str({'actions': p_Zenith.actions}))
            f.write("\n")
            f.write("---------------------------------------------------")
            f.write("\n")
            f.close()
            p_Zenith.reset()
            if len(jobs) == 5: break
    # Plot out job result.
    # reset_delta()
    for i in range(5):
        print(jobs[i])
    f.close()
Example #7
0
    def run(self):
        log = logging.getLogger(__name__)
        h = History()
        # preflop_url, preflop_url_backup = self.updater.get_preflop_sheet_url()
        preflop_url = os.path.join('tools', 'preflop.xlsx')
        try:
            h.preflop_sheet = pd.read_excel(preflop_url, sheet_name=None)
        except:
            h.preflop_sheet = pd.read_excel(preflop_url_backup,
                                            sheet_name=None)

        self.game_logger.clean_database()

        p = StrategyHandler()
        p.read_strategy()

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

        while True:
            # reload table if changed
            config = ConfigObj("config.ini")
            if table_scraper_name != config['DEFAULT']['table_scraper_name']:
                table_scraper_name = config['DEFAULT']['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 == True:
                    time.sleep(0.5)
                    if self.gui_signals.exit_thread == True: sys.exit()

            ready = False
            while (not ready):
                p.read_strategy()
                t = TableScreenBased(p, table_dict, self.gui_signals,
                                     self.game_logger, version)
                try:
                    time_start = datetime.datetime.utcnow()
                    # mouse = MouseMoverTableBased(table_dict)
                    # mouse.move_mouse_away_from_buttons_jump()
                    log.info(
                        "___________________________________________________")
                    ready = t.take_screenshot(True, p) and \
                            t.get_top_left_corner(p, self.gui_signals) and \
                            t.get_my_cards(h, is_debug) and \
                            t.get_table_cards(h) and \
                            t.upload_collusion_wrapper(p, h) and \
                            t.get_dealer_position() and \
                            t.check_for_button(is_debug) and \
                            t.get_round_number(h) and \
                            t.check_for_checkbutton() and \
                            t.init_get_other_players_info() and \
                            t.get_other_player_status(p, h) and \
                            t.get_my_funds(h, 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_call() and \
                            t.check_for_betbutton() and \
                            t.get_current_call_value(p) and \
                            t.get_current_bet_value(p) and \
                            t.get_new_hand2(h, p) and \
                            t.check_for_allincall()
                    # t.get_other_player_names(p) and \
                    # t.get_lost_everything(h, t, p, self.gui_signals) and \
                    # t.check_for_captcha(mouse) and \
                    # t.check_for_imback(mouse) and \
                    # t.get_new_hand(mouse, h, p) and \
                    # t.check_fast_fold(h, p, mouse) and \
                    # t.check_for_allincall() and \
                finally:
                    time_end = datetime.datetime.utcnow()
                    log.info(
                        "___________________________________________________")
                    log.info(f"time to total record: {time_end - time_start}")

            if not self.gui_signals.pause_thread:
                config = ConfigObj("config.ini")
                if not is_debug:
                    m = run_montecarlo_wrapper(p, self.gui_signals, config, ui,
                                               t, self.game_logger,
                                               preflop_state, h)
                    self.gui_signals.signal_progressbar_increase.emit(20)
                    d = Decision(t, h, p, self.game_logger)
                    d.make_decision(t, h, p, 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, p, m, t, d, h,
                                               self.gui_signals)

                    log.info("Equity: " + str(t.equity * 100) + "% -> " +
                             str(int(t.assumedPlayers)) + " (" +
                             str(int(t.other_active_players)) + "-" +
                             str(int(t.playersAhead)) + "+1) Plr")
                    log.info("Final Call Limit: " + str(d.finalCallLimit) +
                             " --> " + str(t.minCall))
                    log.info("Final Bet Limit: " + str(d.finalBetLimit) +
                             " --> " + str(t.minBet))
                    log.info("Pot size: " + str((t.totalPotValue)) +
                             " -> Zero EV Call: " + str(round(d.maxCallEV, 2)))
                    # log.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"
                    log.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':
                    if not is_debug:
                        preflop_state.update_values(t, d.decision, h, d)
                    preflop_state_Zenith.get_players_status(t)
                log.info("=========== round end ===========")
                log.info(f"{h.GameID}")
                self.gui_signals.signal_hand_history.emit(h)