Пример #1
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
Пример #2
0
    def test_preflop_state1(self):
        strategy = 'snowie1'

        # preflop
        t, p, gui_signals, h, logger = init_table('tests/screenshots/76s.png',
                                                  strategy=strategy)
        p = StrategyHandler()
        p.read_strategy(strategy)
        l = MagicMock()
        t.totalPotValue = 0.5
        t.equity = 0.5
        t.checkButton = False
        d = Decision(t, h, p, l)
        t.isHeadsUp = True
        t.gameStage = "PreFlop"
        d.__init__(t, h, p, l)
        d.preflop_table_analyser(t, logger, h, p)
        preflop_state = CurrentHandPreflopState()
        bot_preflop_decision = 'Call'
        d = MagicMock()
        preflop_state.update_values(t, bot_preflop_decision, h, d)

        self.assertEqual(t.preflop_sheet_name, '6R4')

        # flop
        t, p, gui_signals, h, logger = init_table('tests/screenshots/76ss.png',
                                                  strategy=strategy)
        for abs_pos in range(5):
            if t.other_players[abs_pos]['status'] == 1:
                sheet_name = preflop_state.get_reverse_sheetname(abs_pos, t, h)

        self.assertEqual('4', sheet_name)
Пример #3
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}")
Пример #4
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)
Пример #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
Пример #6
0
    def __init__(self, table):
        cm = CoordinatesMerger('../coordinates.json', 'templates/')

        os.chdir('..')

        h = main.History()
        u = UpdateChecker()
        cursor = u.mongodb.internal.find()
        c = cursor.next()
        preflop_url = c['preflop_url']
        h.preflop_sheet = pd.read_excel(preflop_url, sheet_name=None)

        p = StrategyHandler()
        p.read_strategy('pokerstars')

        t = MyTableScreenBased(p)
        t.setCoordinates(cm.getCoordinates()['screen_scraping'])
        t.set_screenshot(table)

        testFunctions = [
            {'func':t.get_top_left_corner, 'params':{'p':p}},
            {'func':t.get_lost_everything, 'params':{'p':p}},
            {'func':t.check_for_imback, 'params':{}},
            {'func':t.get_my_cards, 'params':{}},
            {'func':t.get_my_funds, 'params':{'p':p}},
            {'func':t.get_table_cards, 'params':{}},
            # {'func':t.check_fast_fold, 'params':{'p':p, 'h':h}},
            {'func':t.check_for_button, 'params':{}},
            {'func':t.get_round_number, 'params':{}},
            {'func':t.init_get_other_players_info, 'params':{}},
            {'func':t.get_other_player_names, 'params':{'p':p}},
            {'func':t.get_other_player_funds, 'params':{'p':p}},
            {'func':t.get_other_player_pots, 'params':{}},
            {'func':t.get_total_pot_value, 'params':{}},
            {'func':t.get_round_pot_value, 'params':{}},
            {'func':t.get_other_player_status, 'params':{'p':p}},
            {'func':t.check_for_checkbutton, 'params':{}},
            {'func':t.check_for_call, 'params':{}},
            {'func':t.check_for_betbutton, 'params':{}},
            {'func':t.check_for_allincall, 'params':{}},
            {'func':t.get_current_call_value, 'params':{'p':p}},
            {'func':t.get_current_bet_value, 'params':{'p':p}},
            {'func':t.get_dealer_position, 'params':{}},
        ]


        for f in testFunctions:
            print()
            print('|============> '+f['func'].__name__+' <============ : ')
            result = f['func'](**f['params'])
            print('result ==> '+str(result))
            cv2.waitKey()
            cv2.destroyAllWindows()


        os.chdir(os.path.dirname(os.path.realpath(__file__)))
Пример #7
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
Пример #8
0
    def test_preflop_round2_3(self):
        t, p, gui_signals, h, logger = init_table('tests/screenshots/897376414_PreFlop_1.png', round_number=1)
        p = StrategyHandler()
        p.read_strategy('Pokemon4')
        l = MagicMock()
        t.checkButton = False
        d = Decision(t, h, p, l)
        t.isHeadsUp = True
        t.gameStage = "PreFlop"

        d.__init__(t, h, p, l)
        d.preflop_table_analyser(t, logger, h, p)
        self.assertEqual(t.first_raiser_utg, 2)
Пример #9
0
 def __init__(self, write_update, L):
     self.logger = logging.getLogger('genetic_algo')
     self.logger.setLevel(logging.DEBUG)
     self.output = ''
     p = StrategyHandler()
     p.read_strategy()
     p_name = p.current_strategy
     self.logger.debug("Strategy to analyse: "+p_name)
     self.load_log(p_name, L)
     self.improve_strategy(L, p)
     if (self.modified and write_update==True) or write_update=="Force":
         p.save_strategy_genetic_algorithm()
         config = ConfigObj("config.ini")
         config['last_strategy'] = p.current_strategy
         config.write()
         self.logger.info("Genetic algorithm: New strategy saved")
Пример #10
0
 def __init__(self, write_update, L):
     self.logger = logging.getLogger('genetic_algo')
     self.logger.setLevel(logging.DEBUG)
     self.output = ''
     p = StrategyHandler()
     p.read_strategy()
     p_name = p.current_strategy
     self.logger.debug("Strategy to analyse: " + p_name)
     self.load_log(p_name, L)
     self.improve_strategy(L, p)
     if (self.modified and write_update == True) or write_update == "Force":
         p.save_strategy_genetic_algorithm()
         config = ConfigObj("config.ini")
         config['last_strategy'] = p.current_strategy
         config.write()
         self.logger.info("Genetic algorithm: New strategy saved")
Пример #11
0
    def test_position_adjustment(self):
        t, p, gui_signals, h, logger = init_table('tests/screenshots/467381034_PreFlop_0.png', strategy='Pokemon4')
        t.gameStage = "PreFlop"
        p = StrategyHandler()
        p.read_strategy('Nickpick12')
        l = MagicMock()
        t.checkButton = True
        d = Decision(t, h, p, l)
        t.isHeadsUp = True
        t.gameStage = "Flop"
        p.selected_strategy['FlopBluffMinEquity'] = 0.3
        p.selected_strategy['FlopBluff'] = "1"
        p.selected_strategy['pre_flop_equity_reduction_by_position'] = 0.02

        d.__init__(t, h, p, l)
        self.assertAlmostEqual(d.preflop_adjustment, 0.1, delta=0.01)
Пример #12
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
Пример #13
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}")
Пример #14
0
    def test_preflop_call_before_raise(self):
        t, p, gui_signals, h, logger = init_table('tests/screenshots/1791526_PreFlop_0.png', round_number=0)
        p = StrategyHandler()
        p.read_strategy('Pokemon4')
        l = MagicMock()
        t.checkButton = False
        d = Decision(t, h, p, l)
        t.isHeadsUp = True
        t.gameStage = "PreFlop"

        d.__init__(t, h, p, l)
        d.preflop_table_analyser(t, logger, h, p)

        self.assertEqual(t.first_raiser, 2)
        self.assertEqual(t.second_raiser, 4)

        self.assertEqual(t.preflop_sheet_name, '6R5C3')
Пример #15
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)
Пример #16
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}')
Пример #17
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()
    cursor = u.mongodb.internal.find()
    c = cursor.next()
    preflop_url = c['preflop_url']
    h.preflop_sheet = pd.read_excel(preflop_url, sheetname=None)
    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
Пример #18
0
    def test_bluff(self):
        t, p, gui_signals, h, logger = init_table('tests/screenshots/751235173_PreFlop_0.png')
        p = StrategyHandler()
        p.read_strategy('Pokemon')
        l = MagicMock()
        t.totalPotValue = 0.5
        t.equity = 0.7
        t.checkButton = True
        d = Decision(t, h, p, l)
        t.isHeadsUp = True
        t.gameStage = "Flop"
        p.selected_strategy['FlopBluffMinEquity'] = 0.3
        p.selected_strategy['FlopBluff'] = "1"

        d.decision = DecisionTypes.check
        t.playersAhead = 0
        d.bluff(t, p, h)
        self.assertEqual(d.decision, DecisionTypes.bet_bluff)

        d.decision = DecisionTypes.check
        t.playersAhead = 1
        d.bluff(t, p, h)
        self.assertEqual(d.decision, DecisionTypes.check)
Пример #19
0
def upload_pio_strategy(file_name, label):
    """update table strategy"""
    # buf = get_piosolver_stategy(file_name)
    with open(file_name, encoding='utf-8') as f:
        buf = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    buf = [x.strip() for x in buf]

    p = StrategyHandler()
    # strategy = p.read_strategy(strategy_override='piosolver')
    strategy = p.read_strategy(strategy_override='test')
    try:
        del strategy['_id']
    except:
        pass
    result = p.mongodb.strategies.update_one(
        {"Strategy": strategy['Strategy']}, {'$set': {
            label: buf
        }},
        upsert=True)
Пример #20
0
def test_strategy_download():    # !! ok
    p = StrategyHandler()      # connect to server
    l = p.get_playable_strategy_list()
    for ele in l:
        selected_strategy = p.read_strategy(strategy_override=ele)
        create_new_strategy(selected_strategy)
Пример #21
0
        
        a = 0b11110000000111111000000000
        c = a | mask_bet_size35_105_250
        # remove the bit 
        c = c^mask_bet_size35_105_250
        a == c  # True
        # check if the bit is on
        c & mask_bet_size35_105_250 == mask_bet_size35_105_250
    '''
    # label = mask_pos_IP | mask_stack_100bb | mask_bet_size25_95_220 | mask_mode_IPvsBB | mask_vpip30 | mask_rake3_5
    label1 = mask_pos_OOP | mask_mode_SBvsBB | mask_stack_100bb | \
             mask_rake4_5 | mask_bet_size35_105_250 | mask_bet_size40_120_290
    label1 = label1 << 9
    label1 = label1 | OOP_SBVSBB_LIMP_BET_0
    p = StrategyHandler()
    strategy = p.read_strategy(strategy_override='test')

    changeLabel = False
    try:
        buf = strategy[str(label1)]
    except:
        changeLabel = True
        pass
    if changeLabel:
        # label1 = label1 >> 9
        # label1 = label1 ^ mask_bet_size40_120_290
        # label1 = label1 << 9
        # label1 = label1 | OOP_SBVSBB_LIMP_BET_0
        label1 = remove_betsize_mask(label1,
                                     bitmask=mask_bet_size40_120_290,
                                     node=OOP_SBVSBB_LIMP_BET_0)
Пример #22
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)
Пример #23
0
class UIActionAndSignals(QObject):
    signal_progressbar_increase = QtCore.pyqtSignal(int)
    signal_progressbar_reset = QtCore.pyqtSignal()

    signal_status = QtCore.pyqtSignal(str)
    signal_decision = QtCore.pyqtSignal(str)

    signal_bar_chart_update = QtCore.pyqtSignal(object, str)
    signal_funds_chart_update = QtCore.pyqtSignal(object)
    signal_pie_chart_update = QtCore.pyqtSignal(dict)
    signal_curve_chart_update1 = QtCore.pyqtSignal(float, float, float, float,
                                                   float, float, str, str)
    signal_curve_chart_update2 = QtCore.pyqtSignal(float, float, float, float,
                                                   float, float, float, float,
                                                   float, float, float)
    signal_lcd_number_update = QtCore.pyqtSignal(str, float)
    signal_label_number_update = QtCore.pyqtSignal(str, str)
    signal_update_selected_strategy = QtCore.pyqtSignal(str)

    signal_update_strategy_sliders = QtCore.pyqtSignal(str)
    signal_open_setup = QtCore.pyqtSignal(object, object)

    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)

    def signal_update_selected_strategy(self, l, p):
        newly_selected_strategy = self.ui.comboBox_current_strategy.currentText(
        )
        config = ConfigObj("config.ini")
        config['last_strategy'] = newly_selected_strategy
        config.write()
        p.read_strategy()
        self.logger.info("Active strategy changed to: " + p.current_strategy)

    def pause(self, ui, p):
        ui.button_resume.setEnabled(True)
        ui.button_pause.setEnabled(False)
        self.pause_thread = True

    def resume(self, ui, p):
        ui.button_resume.setEnabled(False)
        ui.button_pause.setEnabled(True)
        self.pause_thread = False

    def increase_progressbar(self, value):
        self.progressbar_value += value
        if self.progressbar_value > 100: self.progressbar_value = 100
        self.ui.progress_bar.setValue(self.progressbar_value)

    def reset_progressbar(self):
        self.progressbar_value = 0
        self.ui.progress_bar.setValue(0)

    def update_mainwindow_status(self, text):
        self.ui.status.setText(text)

    def update_mainwindow_decision(self, text):
        self.ui.last_decision.setText(text)

    def update_lcd_number(self, item, value):
        func = getattr(self.ui, item)
        func.display(value)

    def update_label_number(self, item, value):
        func = getattr(self.ui, item)
        func.setText(str(value))

    def open_strategy_analyser(self, p, l):
        self.signal_progressbar_reset.emit()
        self.stragegy_analyser_form = QtWidgets.QWidget()
        self.ui_analyser = Ui_Form()
        self.ui_analyser.setupUi(self.stragegy_analyser_form)
        self.stragegy_analyser_form.show()

        self.gui_fundschange = FundsChangePlot(self.ui_analyser)
        self.gui_fundschange.drawfigure()

        self.ui_analyser.combobox_actiontype.addItems([
            'Fold', 'Check', 'Call', 'Bet', 'BetPlus', 'Bet half pot',
            'Bet pot', 'Bet Bluff'
        ])
        self.ui_analyser.combobox_gamestage.addItems(
            ['PreFlop', 'Flop', 'Turn', 'River'])
        self.ui_analyser.combobox_strategy.addItems(
            l.get_played_strategy_list())

        index = self.ui_analyser.combobox_strategy.findText(
            p.current_strategy, QtCore.Qt.MatchFixedString)
        if index >= 0:
            self.ui_analyser.combobox_strategy.setCurrentIndex(index)

        self.gui_histogram = HistogramEquityWinLoss(self.ui_analyser)
        self.gui_scatterplot = ScatterPlot(self.ui_analyser)

        self.ui_analyser.combobox_gamestage.currentIndexChanged[str].connect(
            lambda: self.strategy_analyser_update_plots(l, p))
        self.ui_analyser.combobox_actiontype.currentIndexChanged[str].connect(
            lambda: self.strategy_analyser_update_plots(l, p))
        self.ui_analyser.combobox_strategy.currentIndexChanged[str].connect(
            lambda: self.update_strategy_analyser(l, p))

        self.gui_bar2 = BarPlotter2(self.ui_analyser, l)
        self.gui_bar2.drawfigure(
            l, self.ui_analyser.combobox_strategy.currentText())
        self.update_strategy_analyser(l, p)

    def open_strategy_editor(self):
        self.p_edited = StrategyHandler()
        self.p_edited.read_strategy()
        self.signal_progressbar_reset.emit()
        self.stragegy_editor_form = QtWidgets.QWidget()
        self.ui_editor = Ui_editor_form()
        self.ui_editor.setupUi(self.stragegy_editor_form)
        self.stragegy_editor_form.show()

        self.curveplot_preflop = CurvePlot(self.ui_editor,
                                           self.p_edited,
                                           layout='verticalLayout_preflop')
        self.curveplot_flop = CurvePlot(self.ui_editor,
                                        self.p_edited,
                                        layout='verticalLayout_flop')
        self.curveplot_turn = CurvePlot(self.ui_editor,
                                        self.p_edited,
                                        layout='verticalLayout_turn')
        self.curveplot_river = CurvePlot(self.ui_editor,
                                         self.p_edited,
                                         layout='verticalLayout_river')

        self.ui_editor.pushButton_update1.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.
                                                       current_strategy))
        self.ui_editor.pushButton_update2.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.
                                                       current_strategy))
        self.ui_editor.pushButton_update3.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.
                                                       current_strategy))
        self.ui_editor.pushButton_update4.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.
                                                       current_strategy))

        self.ui_editor.pokerSite.addItems(self.pokersite_types)

        self.signal_update_strategy_sliders.emit(
            self.p_edited.current_strategy)
        self.ui_editor.Strategy.currentIndexChanged.connect(
            lambda: self.update_strategy_editor_sliders(self.ui_editor.Strategy
                                                        .currentText()))
        self.ui_editor.pushButton_save_new_strategy.clicked.connect(
            lambda: self.save_strategy(self.ui_editor.lineEdit_new_name.text(),
                                       False))
        self.ui_editor.pushButton_save_current_strategy.clicked.connect(
            lambda: self.save_strategy(self.ui_editor.Strategy.currentText(),
                                       True))

        self.playable_list = self.p_edited.get_playable_strategy_list()
        self.ui_editor.Strategy.addItems(self.playable_list)
        config = ConfigObj("config.ini")
        initial_selection = config['last_strategy']
        for i in [
                i for i, x in enumerate(self.playable_list)
                if x == initial_selection
        ]:
            idx = i
        self.ui_editor.Strategy.setCurrentIndex(idx)

    def open_genetic_algorithm(self, p, l):
        self.ui.button_genetic_algorithm.setEnabled(False)
        g = GeneticAlgorithm(False, l)
        r = g.get_results()

        self.genetic_algorithm_dialog = QtWidgets.QDialog()
        self.genetic_algorithm_form = Ui_Dialog()
        self.genetic_algorithm_form.setupUi(self.genetic_algorithm_dialog)
        self.genetic_algorithm_dialog.show()

        self.genetic_algorithm_form.textBrowser.setText(str(r))
        self.genetic_algorithm_dialog.show()

        self.genetic_algorithm_form.buttonBox.accepted.connect(
            lambda: GeneticAlgorithm(True, self.logger, l))

    def open_help(self, p, l):
        url = "https://github.com/dickreuter/Poker/wiki/Frequently-asked-questions"
        webbrowser.open(url, new=2)
        # self.help_form = QtWidgets.QWidget()
        # self.ui_help = Ui_help_form()
        # self.ui_help.setupUi(self.help_form)
        # self.help_form.show()

    def open_setup(self, p, l):
        self.setup_form = QtWidgets.QWidget()
        self.ui_setup = Ui_setup_form()
        self.ui_setup.setupUi(self.setup_form)
        self.setup_form.show()

        self.ui_setup.pushButton_save.clicked.connect(
            lambda: self.save_setup())
        vm_list = ['Direct mouse control']
        try:
            vm = VirtualBoxController()
            vm_list += vm.get_vbox_list()
        except:
            pass  # no virtual machine

        self.ui_setup.comboBox_vm.addItems(vm_list)
        timeouts = ['8', '9', '10', '11', '12']
        self.ui_setup.comboBox_2.addItems(timeouts)

        config = ConfigObj("config.ini")
        try:
            mouse_control = config['control']
        except:
            mouse_control = 'Direct mouse control'
        for i in [i for i, x in enumerate(vm_list) if x == mouse_control]:
            idx = i
            self.ui_setup.comboBox_vm.setCurrentIndex(idx)

        try:
            timeout = config['montecarlo_timeout']
        except:
            timeout = 10
        for i in [i for i, x in enumerate(timeouts) if x == timeout]:
            idx = i
            self.ui_setup.comboBox_2.setCurrentIndex(idx)

    def save_setup(self):
        config = ConfigObj("config.ini")
        config['control'] = self.ui_setup.comboBox_vm.currentText()
        config['montecarlo_timeout'] = self.ui_setup.comboBox_2.currentText()
        config.write()
        self.setup_form.close()

    def update_strategy_analyser(self, l, p):
        number_of_games = int(
            l.get_game_count(self.ui_analyser.combobox_strategy.currentText()))
        total_return = l.get_strategy_return(
            self.ui_analyser.combobox_strategy.currentText(), 999999)

        winnings_per_bb_100 = total_return / p.selected_strategy[
            'bigBlind'] / number_of_games * 100

        self.ui_analyser.lcdNumber_2.display(number_of_games)
        self.ui_analyser.lcdNumber.display(winnings_per_bb_100)
        self.gui_bar2.drawfigure(
            l, self.ui_analyser.combobox_strategy.currentText())
        self.gui_fundschange.drawfigure()
        self.strategy_analyser_update_plots(l, p)
        self.strategy_analyser_update_table(l)

    def strategy_analyser_update_plots(self, l, p):
        p_name = str(self.ui_analyser.combobox_strategy.currentText())
        game_stage = str(self.ui_analyser.combobox_gamestage.currentText())
        decision = str(self.ui_analyser.combobox_actiontype.currentText())

        self.gui_histogram.drawfigure(p_name, game_stage, decision, l)

        if p_name == '.*':
            p.read_strategy()
        else:
            p.read_strategy(p_name)

        call_or_bet = 'Bet' if decision[0] == 'B' else 'Call'

        max_value = float(p.selected_strategy['initialFunds'])
        min_equity = float(p.selected_strategy[game_stage + 'Min' +
                                               call_or_bet + 'Equity'])
        max_equity = float(
            p.selected_strategy['PreFlopMaxBetEquity']
        ) if game_stage == 'PreFlop' and call_or_bet == 'Bet' else 1
        power = float(p.selected_strategy[game_stage + call_or_bet + 'Power'])
        max_X = .86 if game_stage == "Preflop" else 1

        self.gui_scatterplot.drawfigure(
            p_name, game_stage, decision, l,
            float(p.selected_strategy['smallBlind']),
            float(p.selected_strategy['bigBlind']), max_value, min_equity,
            max_X, max_equity, power)

    def strategy_analyser_update_table(self, l):
        p_name = str(self.ui_analyser.combobox_strategy.currentText())
        df = l.get_worst_games(p_name)
        model = PandasModel(df)
        self.ui_analyser.tableView.setModel(model)

    def update_strategy_editor_sliders(self, strategy_name):
        self.p.read_strategy(strategy_name)
        for key, value in self.strategy_items_with_multipliers.items():
            func = getattr(self.ui_editor, key)
            func.setValue(100)
            v = float(self.p.selected_strategy[key]) * value
            func.setValue(v)
            # print (key)

        self.ui_editor.pushButton_save_current_strategy.setEnabled(False)
        try:
            if self.p.selected_strategy['computername'] == os.environ['COMPUTERNAME'] or \
                            os.environ['COMPUTERNAME'] == 'NICOLAS-ASUS' or os.environ['COMPUTERNAME'] == 'Home-PC-ND':
                self.ui_editor.pushButton_save_current_strategy.setEnabled(
                    True)
        except Exception as e:
            pass

        selection = self.p.selected_strategy['pokerSite']
        for i in [
                i for i, x in enumerate(self.pokersite_types) if x == selection
        ]:
            idx = i
        self.ui_editor.pokerSite.setCurrentIndex(idx)

        self.ui_editor.use_relative_equity.setChecked(
            self.p.selected_strategy['use_relative_equity'])
        self.ui_editor.use_pot_multiples.setChecked(
            self.p.selected_strategy['use_pot_multiples'])
        self.ui_editor.opponent_raised_without_initiative_flop.setChecked(
            self.p.selected_strategy['opponent_raised_without_initiative_flop']
        )
        self.ui_editor.opponent_raised_without_initiative_turn.setChecked(
            self.p.selected_strategy['opponent_raised_without_initiative_turn']
        )
        self.ui_editor.opponent_raised_without_initiative_river.setChecked(
            self.p.
            selected_strategy['opponent_raised_without_initiative_river'])
        self.ui_editor.differentiate_reverse_sheet.setChecked(
            self.p.selected_strategy['differentiate_reverse_sheet'])
        self.ui_editor.preflop_override.setChecked(
            self.p.selected_strategy['preflop_override'])
        self.ui_editor.gather_player_names.setChecked(
            self.p.selected_strategy['gather_player_names'])

        self.ui_editor.collusion.setChecked(
            self.p.selected_strategy['collusion'])
        self.ui_editor.flop_betting_condidion_1.setChecked(
            self.p.selected_strategy['flop_betting_condidion_1'])
        self.ui_editor.turn_betting_condidion_1.setChecked(
            self.p.selected_strategy['turn_betting_condidion_1'])
        self.ui_editor.river_betting_condidion_1.setChecked(
            self.p.selected_strategy['river_betting_condidion_1'])
        self.ui_editor.flop_bluffing_condidion_1.setChecked(
            self.p.selected_strategy['flop_bluffing_condidion_1'])
        self.ui_editor.turn_bluffing_condidion_1.setChecked(
            self.p.selected_strategy['turn_bluffing_condidion_1'])
        self.ui_editor.turn_bluffing_condidion_2.setChecked(
            self.p.selected_strategy['turn_bluffing_condidion_2'])
        self.ui_editor.river_bluffing_condidion_1.setChecked(
            self.p.selected_strategy['river_bluffing_condidion_1'])
        self.ui_editor.river_bluffing_condidion_2.setChecked(
            self.p.selected_strategy['river_bluffing_condidion_2'])

        self.update_strategy_editor_graphs(strategy_name)

    def update_strategy_editor_graphs(self, strategy_name):
        strategy_dict = self.update_dictionary(strategy_name)

        try:
            self.curveplot_preflop.update_lines(
                float(strategy_dict['PreFlopCallPower']),
                float(strategy_dict['PreFlopBetPower']),
                float(strategy_dict['PreFlopMinCallEquity']),
                float(strategy_dict['PreFlopMinBetEquity']),
                float(strategy_dict['smallBlind']),
                float(strategy_dict['bigBlind']),
                float(strategy_dict['initialFunds']),
                float(strategy_dict['initialFunds2']), 1, 0.85,
                float(strategy_dict['PreFlopMaxBetEquity']))

            self.curveplot_flop.update_lines(
                float(strategy_dict['FlopCallPower']),
                float(strategy_dict['FlopBetPower']),
                float(strategy_dict['FlopMinCallEquity']),
                float(strategy_dict['FlopMinBetEquity']),
                float(strategy_dict['smallBlind']),
                float(strategy_dict['bigBlind']),
                float(strategy_dict['initialFunds']),
                float(strategy_dict['initialFunds2']), 1, 1, 1)

            self.curveplot_turn.update_lines(
                float(strategy_dict['TurnCallPower']),
                float(strategy_dict['TurnBetPower']),
                float(strategy_dict['TurnMinCallEquity']),
                float(strategy_dict['TurnMinBetEquity']),
                float(strategy_dict['smallBlind']),
                float(strategy_dict['bigBlind']),
                float(strategy_dict['initialFunds']),
                float(strategy_dict['initialFunds2']), 1, 1, 1)

            self.curveplot_river.update_lines(
                float(strategy_dict['RiverCallPower']),
                float(strategy_dict['RiverBetPower']),
                float(strategy_dict['RiverMinCallEquity']),
                float(strategy_dict['RiverMinBetEquity']),
                float(strategy_dict['smallBlind']),
                float(strategy_dict['bigBlind']),
                float(strategy_dict['initialFunds']),
                float(strategy_dict['initialFunds2']), 1, 1, 1)
        except:
            print("retry")

    def update_dictionary(self, name):
        self.strategy_dict = self.p_edited.selected_strategy
        for key, value in self.strategy_items_with_multipliers.items():
            func = getattr(self.ui_editor, key)
            self.strategy_dict[key] = func.value() / value
        self.strategy_dict['Strategy'] = name
        self.strategy_dict['pokerSite'] = self.ui_editor.pokerSite.currentText(
        )
        self.strategy_dict['computername'] = os.environ['COMPUTERNAME']

        self.strategy_dict['use_relative_equity'] = int(
            self.ui_editor.use_relative_equity.isChecked())
        self.strategy_dict['use_pot_multiples'] = int(
            self.ui_editor.use_pot_multiples.isChecked())

        self.strategy_dict['opponent_raised_without_initiative_flop'] = int(
            self.ui_editor.opponent_raised_without_initiative_flop.isChecked())
        self.strategy_dict['opponent_raised_without_initiative_turn'] = int(
            self.ui_editor.opponent_raised_without_initiative_turn.isChecked())
        self.strategy_dict['opponent_raised_without_initiative_river'] = int(
            self.ui_editor.opponent_raised_without_initiative_river.isChecked(
            ))

        self.strategy_dict['differentiate_reverse_sheet'] = int(
            self.ui_editor.differentiate_reverse_sheet.isChecked())
        self.strategy_dict['preflop_override'] = int(
            self.ui_editor.preflop_override.isChecked())
        self.strategy_dict['gather_player_names'] = int(
            self.ui_editor.gather_player_names.isChecked())

        self.strategy_dict['collusion'] = int(
            self.ui_editor.collusion.isChecked())

        self.strategy_dict['flop_betting_condidion_1'] = int(
            self.ui_editor.flop_betting_condidion_1.isChecked())
        self.strategy_dict['turn_betting_condidion_1'] = int(
            self.ui_editor.turn_betting_condidion_1.isChecked())
        self.strategy_dict['river_betting_condidion_1'] = int(
            self.ui_editor.river_betting_condidion_1.isChecked())
        self.strategy_dict['flop_bluffing_condidion_1'] = int(
            self.ui_editor.flop_bluffing_condidion_1.isChecked())
        self.strategy_dict['turn_bluffing_condidion_1'] = int(
            self.ui_editor.turn_bluffing_condidion_1.isChecked())
        self.strategy_dict['turn_bluffing_condidion_2'] = int(
            self.ui_editor.turn_bluffing_condidion_2.isChecked())
        self.strategy_dict['river_bluffing_condidion_1'] = int(
            self.ui_editor.river_bluffing_condidion_1.isChecked())
        self.strategy_dict['river_bluffing_condidion_2'] = int(
            self.ui_editor.river_bluffing_condidion_2.isChecked())

        return self.strategy_dict

    def save_strategy(self, name, update):
        if (name != "" and name not in self.playable_list) or update:
            strategy_dict = self.update_dictionary(name)
            if update:
                self.p_edited.update_strategy(strategy_dict)
            else:
                self.p_edited.save_strategy(strategy_dict)
                self.ui_editor.Strategy.insertItem(0, name)
                idx = len(self.p_edited.get_playable_strategy_list())
                self.ui_editor.Strategy.setCurrentIndex(0)
                self.ui.comboBox_current_strategy.insertItem(0, name)
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setText("Saved")
            msg.setWindowTitle("Strategy editor")
            msg.setStandardButtons(QMessageBox.Ok)
            retval = msg.exec()
            self.logger.info("Strategy saved successfully")

        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setText(
                "There has been a problem and the strategy is not saved. Check if the name is already taken."
            )
            msg.setWindowTitle("Strategy editor")
            msg.setStandardButtons(QMessageBox.Ok)
            retval = msg.exec()
            self.logger.warning("Strategy not saved")
Пример #24
0
    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 ===========")
Пример #25
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()
Пример #26
0
    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 ===========")
Пример #27
0
class UIActionAndSignals(QObject):
    signal_progressbar_increase = QtCore.pyqtSignal(int)
    signal_progressbar_reset = QtCore.pyqtSignal()

    signal_status = QtCore.pyqtSignal(str)
    signal_decision = QtCore.pyqtSignal(str)

    signal_bar_chart_update = QtCore.pyqtSignal(object, str)
    signal_funds_chart_update = QtCore.pyqtSignal(object)
    signal_pie_chart_update = QtCore.pyqtSignal(dict)
    signal_curve_chart_update1 = QtCore.pyqtSignal(float, float, float, float, float, float, str, str)
    signal_curve_chart_update2 = QtCore.pyqtSignal(float, float, float, float, float, float, float, float, float, float, float)
    signal_lcd_number_update = QtCore.pyqtSignal(str, float)
    signal_label_number_update = QtCore.pyqtSignal(str, str)
    signal_update_selected_strategy = QtCore.pyqtSignal(str)

    signal_update_strategy_sliders = QtCore.pyqtSignal(str)
    signal_open_setup = QtCore.pyqtSignal(object, object)

    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)

    def signal_update_selected_strategy(self, l, p):
        newly_selected_strategy = self.ui.comboBox_current_strategy.currentText()
        config = ConfigObj("config.ini")
        config['last_strategy'] = newly_selected_strategy
        config.write()
        p.read_strategy()
        self.logger.info("Active strategy changed to: " + p.current_strategy)

    def pause(self, ui, p):
        ui.button_resume.setEnabled(True)
        ui.button_pause.setEnabled(False)
        self.pause_thread = True

    def resume(self, ui, p):
        ui.button_resume.setEnabled(False)
        ui.button_pause.setEnabled(True)
        self.pause_thread = False

    def increase_progressbar(self, value):
        self.progressbar_value += value
        if self.progressbar_value > 100: self.progressbar_value = 100
        self.ui.progress_bar.setValue(self.progressbar_value)

    def reset_progressbar(self):
        self.progressbar_value = 0
        self.ui.progress_bar.setValue(0)

    def update_mainwindow_status(self, text):
        self.ui.status.setText(text)

    def update_mainwindow_decision(self, text):
        self.ui.last_decision.setText(text)

    def update_lcd_number(self, item, value):
        func = getattr(self.ui, item)
        func.display(value)

    def update_label_number(self, item, value):
        func = getattr(self.ui, item)
        func.setText(str(value))

    def open_strategy_analyser(self, p, l):
        self.signal_progressbar_reset.emit()
        self.stragegy_analyser_form = QtWidgets.QWidget()
        self.ui_analyser = Ui_Form()
        self.ui_analyser.setupUi(self.stragegy_analyser_form)
        self.stragegy_analyser_form.show()

        self.gui_fundschange = FundsChangePlot(self.ui_analyser)
        self.gui_fundschange.drawfigure()

        self.ui_analyser.combobox_actiontype.addItems(
            ['Fold', 'Check', 'Call', 'Bet', 'BetPlus', 'Bet half pot', 'Bet pot', 'Bet Bluff'])
        self.ui_analyser.combobox_gamestage.addItems(['PreFlop', 'Flop', 'Turn', 'River'])
        self.ui_analyser.combobox_strategy.addItems(l.get_played_strategy_list())

        index = self.ui_analyser.combobox_strategy.findText(p.current_strategy, QtCore.Qt.MatchFixedString)
        if index >= 0:
            self.ui_analyser.combobox_strategy.setCurrentIndex(index)

        self.gui_histogram = HistogramEquityWinLoss(self.ui_analyser)
        self.gui_scatterplot = ScatterPlot(self.ui_analyser)

        self.ui_analyser.combobox_gamestage.currentIndexChanged[str].connect(
            lambda: self.strategy_analyser_update_plots(l, p))
        self.ui_analyser.combobox_actiontype.currentIndexChanged[str].connect(
            lambda: self.strategy_analyser_update_plots(l, p))
        self.ui_analyser.combobox_strategy.currentIndexChanged[str].connect(lambda: self.update_strategy_analyser(l, p))

        self.gui_bar2 = BarPlotter2(self.ui_analyser, l)
        self.gui_bar2.drawfigure(l, self.ui_analyser.combobox_strategy.currentText())
        self.update_strategy_analyser(l, p)

    def open_strategy_editor(self):
        self.p_edited = StrategyHandler()
        self.p_edited.read_strategy()
        self.signal_progressbar_reset.emit()
        self.stragegy_editor_form = QtWidgets.QWidget()
        self.ui_editor = Ui_editor_form()
        self.ui_editor.setupUi(self.stragegy_editor_form)
        self.stragegy_editor_form.show()

        self.curveplot_preflop = CurvePlot(self.ui_editor, self.p_edited, layout='verticalLayout_preflop')
        self.curveplot_flop = CurvePlot(self.ui_editor, self.p_edited, layout='verticalLayout_flop')
        self.curveplot_turn = CurvePlot(self.ui_editor, self.p_edited, layout='verticalLayout_turn')
        self.curveplot_river = CurvePlot(self.ui_editor, self.p_edited, layout='verticalLayout_river')

        self.ui_editor.pushButton_update1.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.current_strategy))
        self.ui_editor.pushButton_update2.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.current_strategy))
        self.ui_editor.pushButton_update3.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.current_strategy))
        self.ui_editor.pushButton_update4.clicked.connect(
            lambda: self.update_strategy_editor_graphs(self.p_edited.current_strategy))

        self.ui_editor.pokerSite.addItems(self.pokersite_types)

        self.signal_update_strategy_sliders.emit(self.p_edited.current_strategy)
        self.ui_editor.Strategy.currentIndexChanged.connect(
            lambda: self.update_strategy_editor_sliders(self.ui_editor.Strategy.currentText()))
        self.ui_editor.pushButton_save_new_strategy.clicked.connect(
            lambda: self.save_strategy(self.ui_editor.lineEdit_new_name.text(), False))
        self.ui_editor.pushButton_save_current_strategy.clicked.connect(
            lambda: self.save_strategy(self.ui_editor.Strategy.currentText(), True))

        self.playable_list = self.p_edited.get_playable_strategy_list()
        self.ui_editor.Strategy.addItems(self.playable_list)
        config = ConfigObj("config.ini")
        initial_selection = config['last_strategy']
        for i in [i for i, x in enumerate(self.playable_list) if x == initial_selection]:
            idx = i
        self.ui_editor.Strategy.setCurrentIndex(idx)

    def open_genetic_algorithm(self, p, l):
        self.ui.button_genetic_algorithm.setEnabled(False)
        g = GeneticAlgorithm(False, l)
        r = g.get_results()

        self.genetic_algorithm_dialog = QtWidgets.QDialog()
        self.genetic_algorithm_form = Ui_Dialog()
        self.genetic_algorithm_form.setupUi(self.genetic_algorithm_dialog)
        self.genetic_algorithm_dialog.show()

        self.genetic_algorithm_form.textBrowser.setText(str(r))
        self.genetic_algorithm_dialog.show()

        self.genetic_algorithm_form.buttonBox.accepted.connect(lambda: GeneticAlgorithm(True, self.logger, l))

    def open_help(self, p, l):
        url = "https://github.com/dickreuter/Poker/wiki/Frequently-asked-questions"
        webbrowser.open(url,new=2)
        # self.help_form = QtWidgets.QWidget()
        # self.ui_help = Ui_help_form()
        # self.ui_help.setupUi(self.help_form)
        # self.help_form.show()

    def open_setup(self, p, l):
        self.setup_form = QtWidgets.QWidget()
        self.ui_setup = Ui_setup_form()
        self.ui_setup.setupUi(self.setup_form)
        self.setup_form.show()

        self.ui_setup.pushButton_save.clicked.connect(lambda: self.save_setup())
        vm_list = ['Direct mouse control']
        try:
            vm = VirtualBoxController()
            vm_list += vm.get_vbox_list()
        except:
            pass  # no virtual machine

        self.ui_setup.comboBox_vm.addItems(vm_list)
        timeouts = ['8','9','10', '11','12']
        self.ui_setup.comboBox_2.addItems(timeouts)

        config = ConfigObj("config.ini")
        try:
            mouse_control = config['control']
        except:
            mouse_control = 'Direct mouse control'
        for i in [i for i, x in enumerate(vm_list) if x == mouse_control]:
            idx = i
            self.ui_setup.comboBox_vm.setCurrentIndex(idx)

        try:
            timeout = config['montecarlo_timeout']
        except:
            timeout = 10
        for i in [i for i, x in enumerate(timeouts) if x == timeout]:
            idx = i
            self.ui_setup.comboBox_2.setCurrentIndex(idx)

    def save_setup(self):
        config = ConfigObj("config.ini")
        config['control'] = self.ui_setup.comboBox_vm.currentText()
        config['montecarlo_timeout'] = self.ui_setup.comboBox_2.currentText()
        config.write()
        self.setup_form.close()

    def update_strategy_analyser(self, l, p):
        number_of_games = int(l.get_game_count(self.ui_analyser.combobox_strategy.currentText()))
        total_return = l.get_strategy_return(self.ui_analyser.combobox_strategy.currentText(), 999999)

        winnings_per_bb_100 = total_return / p.selected_strategy['bigBlind'] / number_of_games * 100

        self.ui_analyser.lcdNumber_2.display(number_of_games)
        self.ui_analyser.lcdNumber.display(winnings_per_bb_100)
        self.gui_bar2.drawfigure(l, self.ui_analyser.combobox_strategy.currentText())
        self.gui_fundschange.drawfigure()
        self.strategy_analyser_update_plots(l, p)
        self.strategy_analyser_update_table(l)

    def strategy_analyser_update_plots(self, l, p):
        p_name = str(self.ui_analyser.combobox_strategy.currentText())
        game_stage = str(self.ui_analyser.combobox_gamestage.currentText())
        decision = str(self.ui_analyser.combobox_actiontype.currentText())

        self.gui_histogram.drawfigure(p_name, game_stage, decision, l)

        if p_name == '.*':
            p.read_strategy()
        else:
            p.read_strategy(p_name)

        call_or_bet = 'Bet' if decision[0] == 'B' else 'Call'

        max_value = float(p.selected_strategy['initialFunds'])
        min_equity = float(p.selected_strategy[game_stage + 'Min' + call_or_bet + 'Equity'])
        max_equity = float(
            p.selected_strategy['PreFlopMaxBetEquity']) if game_stage == 'PreFlop' and call_or_bet == 'Bet' else 1
        power = float(p.selected_strategy[game_stage + call_or_bet + 'Power'])
        max_X = .86 if game_stage == "Preflop" else 1

        self.gui_scatterplot.drawfigure(p_name, game_stage, decision, l,
                                        float(p.selected_strategy['smallBlind']),
                                        float(p.selected_strategy['bigBlind']),
                                        max_value,
                                        min_equity,
                                        max_X,
                                        max_equity,
                                        power)

    def strategy_analyser_update_table(self, l):
        p_name = str(self.ui_analyser.combobox_strategy.currentText())
        df = l.get_worst_games(p_name)
        model = PandasModel(df)
        self.ui_analyser.tableView.setModel(model)

    def update_strategy_editor_sliders(self, strategy_name):
        self.p.read_strategy(strategy_name)
        for key, value in self.strategy_items_with_multipliers.items():
            func = getattr(self.ui_editor, key)
            func.setValue(100)
            v = float(self.p.selected_strategy[key]) * value
            func.setValue(v)
            # print (key)

        self.ui_editor.pushButton_save_current_strategy.setEnabled(False)
        try:
            if self.p.selected_strategy['computername'] == os.environ['COMPUTERNAME'] or \
                            os.environ['COMPUTERNAME'] == 'NICOLAS-ASUS' or os.environ['COMPUTERNAME'] == 'Home-PC-ND':
                self.ui_editor.pushButton_save_current_strategy.setEnabled(True)
        except Exception as e:
            pass

        selection = self.p.selected_strategy['pokerSite']
        for i in [i for i, x in enumerate(self.pokersite_types) if x == selection]:
            idx = i
        self.ui_editor.pokerSite.setCurrentIndex(idx)

        self.ui_editor.use_relative_equity.setChecked(self.p.selected_strategy['use_relative_equity'])
        self.ui_editor.use_pot_multiples.setChecked(self.p.selected_strategy['use_pot_multiples'])
        self.ui_editor.opponent_raised_without_initiative_flop.setChecked(self.p.selected_strategy['opponent_raised_without_initiative_flop'])
        self.ui_editor.opponent_raised_without_initiative_turn.setChecked(self.p.selected_strategy['opponent_raised_without_initiative_turn'])
        self.ui_editor.opponent_raised_without_initiative_river.setChecked(self.p.selected_strategy['opponent_raised_without_initiative_river'])
        self.ui_editor.differentiate_reverse_sheet.setChecked(self.p.selected_strategy['differentiate_reverse_sheet'])
        self.ui_editor.preflop_override.setChecked(self.p.selected_strategy['preflop_override'])
        self.ui_editor.gather_player_names.setChecked(self.p.selected_strategy['gather_player_names'])

        self.ui_editor.collusion.setChecked(self.p.selected_strategy['collusion'])
        self.ui_editor.flop_betting_condidion_1.setChecked(self.p.selected_strategy['flop_betting_condidion_1'])
        self.ui_editor.turn_betting_condidion_1.setChecked(self.p.selected_strategy['turn_betting_condidion_1'])
        self.ui_editor.river_betting_condidion_1.setChecked(self.p.selected_strategy['river_betting_condidion_1'])
        self.ui_editor.flop_bluffing_condidion_1.setChecked(self.p.selected_strategy['flop_bluffing_condidion_1'])
        self.ui_editor.turn_bluffing_condidion_1.setChecked(self.p.selected_strategy['turn_bluffing_condidion_1'])
        self.ui_editor.turn_bluffing_condidion_2.setChecked(self.p.selected_strategy['turn_bluffing_condidion_2'])
        self.ui_editor.river_bluffing_condidion_1.setChecked(self.p.selected_strategy['river_bluffing_condidion_1'])
        self.ui_editor.river_bluffing_condidion_2.setChecked(self.p.selected_strategy['river_bluffing_condidion_2'])

        self.update_strategy_editor_graphs(strategy_name)

    def update_strategy_editor_graphs(self, strategy_name):
        strategy_dict = self.update_dictionary(strategy_name)

        try:
            self.curveplot_preflop.update_lines(float(strategy_dict['PreFlopCallPower']),
                                                float(strategy_dict['PreFlopBetPower']),
                                                float(strategy_dict['PreFlopMinCallEquity']),
                                                float(strategy_dict['PreFlopMinBetEquity']),
                                                float(strategy_dict['smallBlind']),
                                                float(strategy_dict['bigBlind']),
                                                float(strategy_dict['initialFunds']),
                                                float(strategy_dict['initialFunds2']),
                                                1,
                                                0.85,
                                                float(strategy_dict['PreFlopMaxBetEquity']))

            self.curveplot_flop.update_lines(float(strategy_dict['FlopCallPower']),
                                             float(strategy_dict['FlopBetPower']),
                                             float(strategy_dict['FlopMinCallEquity']),
                                             float(strategy_dict['FlopMinBetEquity']),
                                             float(strategy_dict['smallBlind']),
                                             float(strategy_dict['bigBlind']),
                                             float(strategy_dict['initialFunds']),
                                             float(strategy_dict['initialFunds2']),
                                             1,
                                             1,
                                             1)

            self.curveplot_turn.update_lines(float(strategy_dict['TurnCallPower']),
                                             float(strategy_dict['TurnBetPower']),
                                             float(strategy_dict['TurnMinCallEquity']),
                                             float(strategy_dict['TurnMinBetEquity']),
                                             float(strategy_dict['smallBlind']),
                                             float(strategy_dict['bigBlind']),
                                             float(strategy_dict['initialFunds']),
                                             float(strategy_dict['initialFunds2']),
                                             1,
                                             1,
                                             1)

            self.curveplot_river.update_lines(float(strategy_dict['RiverCallPower']),
                                              float(strategy_dict['RiverBetPower']),
                                              float(strategy_dict['RiverMinCallEquity']),
                                              float(strategy_dict['RiverMinBetEquity']),
                                              float(strategy_dict['smallBlind']),
                                              float(strategy_dict['bigBlind']),
                                              float(strategy_dict['initialFunds']),
                                              float(strategy_dict['initialFunds2']),
                                              1,
                                              1,
                                              1)
        except:
            print("retry")

    def update_dictionary(self, name):
        self.strategy_dict = self.p_edited.selected_strategy
        for key, value in self.strategy_items_with_multipliers.items():
            func = getattr(self.ui_editor, key)
            self.strategy_dict[key] = func.value() / value
        self.strategy_dict['Strategy'] = name
        self.strategy_dict['pokerSite'] = self.ui_editor.pokerSite.currentText()
        self.strategy_dict['computername'] = os.environ['COMPUTERNAME']

        self.strategy_dict['use_relative_equity'] = int(self.ui_editor.use_relative_equity.isChecked())
        self.strategy_dict['use_pot_multiples'] = int(self.ui_editor.use_pot_multiples.isChecked())

        self.strategy_dict['opponent_raised_without_initiative_flop'] = int(self.ui_editor.opponent_raised_without_initiative_flop.isChecked())
        self.strategy_dict['opponent_raised_without_initiative_turn'] = int(self.ui_editor.opponent_raised_without_initiative_turn.isChecked())
        self.strategy_dict['opponent_raised_without_initiative_river'] = int(self.ui_editor.opponent_raised_without_initiative_river.isChecked())


        self.strategy_dict['differentiate_reverse_sheet'] = int(self.ui_editor.differentiate_reverse_sheet.isChecked())
        self.strategy_dict['preflop_override'] = int(self.ui_editor.preflop_override.isChecked())
        self.strategy_dict['gather_player_names'] = int(self.ui_editor.gather_player_names.isChecked())

        self.strategy_dict['collusion'] = int(self.ui_editor.collusion.isChecked())

        self.strategy_dict['flop_betting_condidion_1'] = int(self.ui_editor.flop_betting_condidion_1.isChecked())
        self.strategy_dict['turn_betting_condidion_1'] = int(self.ui_editor.turn_betting_condidion_1.isChecked())
        self.strategy_dict['river_betting_condidion_1'] = int(self.ui_editor.river_betting_condidion_1.isChecked())
        self.strategy_dict['flop_bluffing_condidion_1'] = int(self.ui_editor.flop_bluffing_condidion_1.isChecked())
        self.strategy_dict['turn_bluffing_condidion_1'] = int(self.ui_editor.turn_bluffing_condidion_1.isChecked())
        self.strategy_dict['turn_bluffing_condidion_2'] = int(self.ui_editor.turn_bluffing_condidion_2.isChecked())
        self.strategy_dict['river_bluffing_condidion_1'] = int(self.ui_editor.river_bluffing_condidion_1.isChecked())
        self.strategy_dict['river_bluffing_condidion_2'] = int(self.ui_editor.river_bluffing_condidion_2.isChecked())

        return self.strategy_dict

    def save_strategy(self, name, update):
        if (name != "" and name not in self.playable_list) or update:
            strategy_dict = self.update_dictionary(name)
            if update:
                self.p_edited.update_strategy(strategy_dict)
            else:
                self.p_edited.save_strategy(strategy_dict)
                self.ui_editor.Strategy.insertItem(0, name)
                idx = len(self.p_edited.get_playable_strategy_list())
                self.ui_editor.Strategy.setCurrentIndex(0)
                self.ui.comboBox_current_strategy.insertItem(0, name)
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setText("Saved")
            msg.setWindowTitle("Strategy editor")
            msg.setStandardButtons(QMessageBox.Ok)
            retval = msg.exec()
            self.logger.info("Strategy saved successfully")

        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setText("There has been a problem and the strategy is not saved. Check if the name is already taken.")
            msg.setWindowTitle("Strategy editor")
            msg.setStandardButtons(QMessageBox.Ok)
            retval = msg.exec()
            self.logger.warning("Strategy not saved")