def save_setup(self): config = get_config() config['DEFAULT']['control'] = self.ui_setup.comboBox_vm.currentText() config['DEFAULT'][ 'montecarlo_timeout'] = self.ui_setup.comboBox_2.currentText() config.write() self.setup_form.close()
def test_full_update_translate_abs(): """ 'player_funds_area' 'player_pot_area' 56x23 'current_round_pot' 'total_pot_area' 'call_value' 'raise_value' """ config = get_config() x = config['DEFAULT']['delta_x'] y = config['DEFAULT']['delta_y'] update_coordinate_rel('player_funds_area', player=0, delta_x=x, delta_y=y) update_coordinate_rel('player_funds_area', player=1, delta_x=x, delta_y=y) update_coordinate_rel('player_funds_area', player=2, delta_x=x, delta_y=y) update_coordinate_rel('player_funds_area', player=3, delta_x=x, delta_y=y) update_coordinate_rel('player_funds_area', player=4, delta_x=x, delta_y=y) update_coordinate_rel('player_funds_area', player=5, delta_x=x, delta_y=y) update_coordinate_rel('player_pot_area', player=0, delta_x=x, delta_y=y) update_coordinate_rel('player_pot_area', player=1, delta_x=x, delta_y=y) update_coordinate_rel('player_pot_area', player=2, delta_x=x, delta_y=y) update_coordinate_rel('player_pot_area', player=3, delta_x=x, delta_y=y) update_coordinate_rel('player_pot_area', player=4, delta_x=x, delta_y=y) update_coordinate_rel('player_pot_area', player=5, delta_x=x, delta_y=y) update_coordinate_rel('total_pot_area', player=None, delta_x=x, delta_y=y) update_coordinate_rel('current_round_pot', player=None, delta_x=x, delta_y=y) reset_delta()
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 = get_config() try: mouse_control = config['DEFAULT']['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['DEFAULT']['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 take_screenshot(self, initial, p): if initial: self.gui_signals.signal_status.emit("") self.gui_signals.signal_progressbar_reset.emit() if self.gui_signals.exit_thread == True: sys.exit() if self.gui_signals.pause_thread == True: while self.gui_signals.pause_thread: time.sleep(.2) if self.gui_signals.exit_thread == True: sys.exit() time.sleep(0.1) config = get_config() control = config.config.get('main', 'control') if control == 'Direct mouse control': self.take_screenshot2() self.entireScreenPIL = self.screenshot else: try: vb = VirtualBoxController() self.entireScreenPIL = vb.get_screenshot_vbox() self.logger.debug("Screenshot taken from virtual machine") except: self.logger.warning("No virtual machine found. Press SETUP to re initialize the VM controller") # gui_signals.signal_open_setup.emit(p,L) self.take_screenshot2() self.entireScreenPIL = self.screenshot self.gui_signals.signal_status.emit(str(p.current_strategy)) self.gui_signals.signal_progressbar_increase.emit(5) self.logger.info("Screenshot taken") return True
def get_playable_strategy_list(self): config = get_config() login = config.config.get('main', 'login') password = config.config.get('main', 'password') lst = requests.post(URL + "get_playable_strategy_list", params={"login": login, "password": password, "computer_name": COMPUTER_NAME}).json() return lst
def save_table_rectangle_cv2(screenshot, table_dict, filename, x=None, y=None): config = get_config() delta_x = config['DEFAULT']['delta_x'] delta_y = config['DEFAULT']['delta_y'] delta_x = int(delta_x) delta_y = int(delta_y) if x is not None: delta_x -= x if y is not None: delta_y -= y image = pil_to_cv2(screenshot) for i in range(6): x1 = table_dict['player_pot_area'][str(i)]['x1'] + int(delta_x) y1 = table_dict['player_pot_area'][str(i)]['y1'] + int(delta_y) x2 = table_dict['player_pot_area'][str(i)]['x2'] + int(delta_x) y2 = table_dict['player_pot_area'][str(i)]['y2'] + int(delta_y) image = cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2) # blue for pot for i in range(6): x1 = table_dict['player_funds_area'][str(i)]['x1'] + int(delta_x) y1 = table_dict['player_funds_area'][str(i)]['y1'] + int(delta_y) x2 = table_dict['player_funds_area'][str(i)]['x2'] + int(delta_x) y2 = table_dict['player_funds_area'][str(i)]['y2'] + int(delta_y) image = cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 2) # red for funds for i in range(6): x1 = table_dict['miss_player_area'][str(i)]['x1'] + int(delta_x) y1 = table_dict['miss_player_area'][str(i)]['y1'] + int(delta_y) x2 = table_dict['miss_player_area'][str(i)]['x2'] + int(delta_x) y2 = table_dict['miss_player_area'][str(i)]['y2'] + int(delta_y) image = cv2.rectangle(image, (x1, y1), (x2, y2), (0, 128, 0), 2) # Green for funds for i in range(6): x1 = table_dict['covered_card_area'][str(i)]['x1'] + int(delta_x) y1 = table_dict['covered_card_area'][str(i)]['y1'] + int(delta_y) x2 = table_dict['covered_card_area'][str(i)]['x2'] + int(delta_x) y2 = table_dict['covered_card_area'][str(i)]['y2'] + int(delta_y) image = cv2.rectangle(image, (x1, y1), (x2, y2), (147, 20, 255), 2) # Green for funds x1 = table_dict['total_pot_area']['x1'] + int(delta_x) y1 = table_dict['total_pot_area']['y1'] + int(delta_y) x2 = table_dict['total_pot_area']['x2'] + int(delta_x) y2 = table_dict['total_pot_area']['y2'] + int(delta_y) image = cv2.rectangle(image, (x1, y1), (x2, y2), (255, 255, 0), 2) # yellow for total pot x1 = table_dict['current_round_pot']['x1'] + int(delta_x) y1 = table_dict['current_round_pot']['y1'] + int(delta_y) x2 = table_dict['current_round_pot']['x2'] + int(delta_x) y2 = table_dict['current_round_pot']['y2'] + int(delta_y) image = cv2.rectangle(image, (x1, y1), (x2, y2), (255, 255, 0), 2) # yellow for current round pot cv2.imwrite(filename, image)
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.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 = get_config() initial_selection = config['DEFAULT']['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 save_strategy(self, strategy_dict): config = get_config() login = config.config.get('main', 'login') password = config.config.get('main', 'password') response = requests.post( URL + "save_strategy", json={'strategy': json.dumps(strategy_dict), 'login': login, 'password': password}).json() if response: log.info("Saved") return True else: log.error("Not allowed to write strategies") return False
def signal_update_selected_strategy(self, l, p): config = get_config() newly_selected_strategy = self.ui.comboBox_current_strategy.currentText( ) config['DEFAULT']['last_strategy'] = newly_selected_strategy table_selection = self.ui.table_selection.currentText() config['DEFAULT']['table_scraper_name'] = table_selection # config.write() p.read_strategy() self.logger.info("Active strategy changed to: " + p.current_strategy) self.logger.info("Active table changed to: " + table_selection)
def __init__(self, table_dict): config = get_config() try: mouse_control = config.config.get('main', 'control') if mouse_control != 'Direct mouse control': self.vbox_mode = True else: self.vbox_mode = False except: self.vbox_mode = False super().__init__(self.vbox_mode) self.table_dict = table_dict
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 is True) or write_update == "Force": p.save_strategy_genetic_algorithm() config = get_config() config.config.set('main', 'last_strategy', p.current_strategy) config.update_file() self.logger.info("Genetic algorithm: New strategy saved")
def __init__(self): super().__init__() self.vm = None self.session = None self.logger = logging.getLogger('vm_control') self.logger.setLevel(logging.DEBUG) try: self.vbox = virtualbox.VirtualBox() config = get_config() self.control_name = config.config.get('main','control') if self.control_name not in self.get_vbox_list(): self.control_name = 'Direct mouse control' config.config.set('main','control', 'Direct mouse control') config.update_file() self.start_vm() self.logger.debug("VM session established successfully") except Exception as e: self.logger.error(str(e))
def save_strategy_genetic_algorithm(self): config = get_config() login = config.config.get('main', 'login') password = config.config.get('main', 'password') m = re.search(r'([a-zA-Z?-_]+)([0-9]+)', self.current_strategy) stringPart = m.group(1) numberPart = int(m.group(2)) numberPart += 1 suffix = "_" + str(datetime.datetime.now()) self.new_strategy_name = stringPart + str(numberPart) + suffix self.selected_strategy['Strategy'] = self.new_strategy_name self.current_strategy = self.new_strategy_name del self.selected_strategy['_id'] response = requests.post( URL + "save_strategy", json={'strategy': json.dumps(self.selected_strategy), 'login': login, 'password': password}).json() if response: log.info("Saved") else: log.error("Not allowed to write strategies")
def read_strategy(self, strategy_override=''): config = get_config() login = config.config.get('main', 'login') password = config.config.get('main', 'password') last_strategy = config.config.get('main', 'last_strategy') self.current_strategy = last_strategy if strategy_override == '' else strategy_override try: output = requests.post( URL + "get_strategy", params={'name': self.current_strategy, "login": login, "password": password}).json()[0] except: log.error(f"This Strategy is not available for this user: {login}") time.sleep(1) output = requests.post(URL + "get_strategy", params={'name': 'Default', "login": '******', "password": '******'}).json()[0] self.selected_strategy = output self.check_defaults() return True
def take_screenshot(self): """Take a screenshot""" log.info("Clearing window") self.signal_update_screenshot_pic.emit(Image.new('RGB', (3, 3))) log.info("Taking screenshot") config = get_config() control = config.config.get('main', 'control') if control == 'Direct mouse control': self.original_screenshot = take_screenshot() else: try: vb = VirtualBoxController() self.original_screenshot = vb.get_screenshot_vbox() log.debug("Screenshot taken from virtual machine") except: log.warning("No virtual machine found. Press SETUP to re initialize the VM controller") self.original_screenshot = take_screenshot() log.info("Emitting update signal") self.signal_update_screenshot_pic.emit(self.original_screenshot) log.info("signal emission complete")
def __init__(self, ui_main_window): self.logger = logging.getLogger('gui') self.l = GameLogger() self.l.clean_database() l = self.l self.p = StrategyHandler() self.p.read_strategy() p = self.p # self.h = History() # h = self.h 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.ui = ui_main_window self.progressbar_value = 0 self.ui_handView = None self.select_table = 0 self.tableList = [] # 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)) self.signal_hand_history.connect(self.update_hand_history) 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)) ui_main_window.open_chat.clicked.connect(lambda: self.open_chat()) ui_main_window.button_table_setup.clicked.connect( lambda: self.open_table_setup()) ui_main_window.HandHistory1.clicked.connect( lambda: self.show_hand_history()) ui_main_window.radioButton.toggled.connect( lambda: self._select_inactive_table(ui_main_window)) ui_main_window.radioButton_2.toggled.connect( lambda: self._select_inactive_table(ui_main_window)) ui_main_window.radioButton_3.toggled.connect( lambda: self._select_inactive_table(ui_main_window)) ui_main_window.checkBox1.toggled.connect( lambda: self._select_mutiple_tables(ui_main_window)) ui_main_window.checkBox_2.toggled.connect( lambda: self._select_mutiple_tables(ui_main_window)) ui_main_window.checkBox_3.toggled.connect( lambda: self._select_mutiple_tables(ui_main_window)) ui_main_window.checkBox_4.toggled.connect( lambda: self._select_mutiple_tables(ui_main_window)) ui_main_window.checkBox_5.toggled.connect( lambda: self._select_mutiple_tables(ui_main_window)) self.signal_update_strategy_sliders.connect( lambda: self.update_strategy_editor_sliders(p.current_strategy)) mongo = MongoManager() available_tables = mongo.get_available_tables() ui_main_window.table_selection.addItems(available_tables) 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)) ui_main_window.table_selection.currentIndexChanged[str].connect( lambda: self.signal_update_selected_strategy(l, p)) config = get_config() initial_selection = config['DEFAULT']['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) table_scraper_name = config['DEFAULT']['table_scraper_name'] idx = available_tables.index(table_scraper_name) ui_main_window.table_selection.setCurrentIndex(idx)
def get_table_cards3(self): # self.table_cards = [] # img_values_dir = 'C:\\Users\\jinyi\\Desktop\\Poker\\poker\\cards\\values' # img_suits_dir = 'C:\\Users\\jinyi\\Desktop\\Poker\\poker\\cards\\suits' img_values_dir = get_dir(os.path.join('cards', 'values')) img_suits_dir = get_dir(os.path.join('cards', 'suits')) cardsFound = set() matchingThreshold = 0.90 allValueMatches = [] maxVal = 0 maxVal1 = 0 card = None rectangle = [None for _ in range(4)] config = get_config() table_size = config['DEFAULT']['table_size'] lower = float(config['DEFAULT']['table' + table_size + '_lower_boundary']) upper = float(config['DEFAULT']['table' + table_size + '_upper_boundary']) suitRecord = {} for template_value_path in glob.glob(img_values_dir + "\\*.png"): value = self.path_leaf(template_value_path) valueTemplate = cv2.imread(template_value_path) valueTemplate = cv2.cvtColor(valueTemplate, cv2.COLOR_BGR2GRAY) valueTemplate = valueTemplate[0:30, 0:20] (tH, tW) = valueTemplate.shape[:2] # loop over the scales of the image # for scale in np.linspace(1, 2.0, 20)[::-1]: for scale in np.linspace(lower, upper, 3)[::-1]: # resize the image according to the scale, and keep track # of the ratio of the resizing search_area = self.table_dict['table_cards_area'] # cropped_screenshot = self.screenshot.crop( # (search_area['x1'], search_area['y1'], search_area['x2'], search_area['y2'])) # scale_m = config['DEFAULT']['scale'] # table_size = config['DEFAULT']['table_size'] scale_m = scale_cal(table_size, 'table_cards_area') rectangle[0], rectangle[1], rectangle[2], rectangle[ 3] = scale_convertor2(search_area['x1'], search_area['y1'], search_area['x2'], search_area['y2'], scale_m) cropped_screenshot = self.screenshot.crop( (rectangle[0], rectangle[1], rectangle[2], rectangle[3])) original = cv2.cvtColor(np.array(cropped_screenshot), cv2.COLOR_BGR2GRAY) # cv2.imshow("Image", original) # cv2.waitKey(0) resized = imutils.resize(original, width=int(original.shape[1] * scale)) r = resized.shape[1] / float(original.shape[1]) # if the resized image is smaller than the template, then break # from the loop if resized.shape[0] < tH or resized.shape[1] < tW: break valueMatches, maxVal, maxLoc = templateMatching.getMatches( resized, valueTemplate, 0.92) valueMatches = map( lambda match: { 'topLeft': (match[0], match[1]), 'name': value }, valueMatches) for valueMatch in valueMatches: tcl = valueMatch['topLeft'] searchArea = resized[(tcl[1] + 0 - 30):(tcl[1] + 90 - 30 + 50), (tcl[0] - 5 - 20):(tcl[0] + 60 - 20 + 50)] # cv2.imshow("Image", searchArea) # cv2.waitKey(0) for template_suit_path in glob.glob(img_suits_dir + "\\*.png"): suit = self.path_leaf(template_suit_path) suitTemplate = cv2.imread(template_suit_path) suitTemplate = cv2.cvtColor(suitTemplate, cv2.COLOR_BGR2GRAY) (sH, sW) = suitTemplate.shape[:2] if searchArea.shape[0] < sH or searchArea.shape[1] < sW: break _, maxVal1, _ = templateMatching.getMatches( searchArea, suitTemplate, matchingThreshold) suitRecord[suit] = maxVal1 bestSuit = 'spade' if searchArea.shape[0] < sH or searchArea.shape[1] < sW: break for template_suit_path in glob.glob(img_suits_dir + "\\*.png"): suit = self.path_leaf(template_suit_path) if suitRecord[suit] >= suitRecord[bestSuit]: bestSuit = suit card = value[0] + bestSuit[0].upper() if suitRecord[bestSuit] > 0.90: cardsFound.add(card) if self.found[card] is None or maxVal > self.found[card][0] or suitRecord[bestSuit] > \ self.found[card][1]: self.found[card] = (maxVal, suitRecord[bestSuit], maxLoc, r) if self.found[card] is None or self.found[card][0] == 0: continue self.table_cards = list(cardsFound) print(self.found) return True
def get_my_cards3(self): """Get my cards""" for card in self.hand: self.hand[card] = 0 self.my_cards = [] img_values_dir = get_dir(os.path.join('cards', 'values')) img_suits_dir = get_dir(os.path.join('cards', 'suits_mycard')) cardsFound = set() matchingThreshold = 0.90 rectangle = [None for _ in range(4)] config = get_config() table_size = config['DEFAULT']['table_size'] lower = float(config['DEFAULT']['table' + table_size + '_lower_boundary']) upper = float(config['DEFAULT']['table' + table_size + '_upper_boundary']) suitRecord = {} angleList = [-5, 5] for angle in angleList: for template_value_path in glob.glob(img_values_dir + "\\*.png"): value = self.path_leaf(template_value_path) valueTemplate = cv2.imread(template_value_path) valueTemplate = cv2.cvtColor(valueTemplate, cv2.COLOR_BGR2GRAY) valueTemplate = valueTemplate[0:30, 0:20] (tH, tW) = valueTemplate.shape[:2] # loop over the scales of the image for scale in np.linspace(lower, upper, 3)[::-1]: search_area = self.table_dict['my_right_card_area'] scale_m = scale_cal(table_size, 'my_right_card_area') rectangle[0], rectangle[1], rectangle[2], rectangle[ 3] = scale_convertor2(search_area['x1'], search_area['y1'], search_area['x2'], search_area['y2'], scale_m) cropped_screenshot = self.screenshot.crop( (rectangle[0], rectangle[1], rectangle[2], rectangle[3])) original = cv2.cvtColor(np.array(cropped_screenshot), cv2.COLOR_BGR2GRAY) resized = imutils.resize(original, width=int(original.shape[1] * scale)) r = resized.shape[1] / float(original.shape[1]) if resized.shape[0] < tH or resized.shape[1] < tW: break valueTemplateRotP5 = self.getRotImage(angle, valueTemplate) valueMatches, maxVal, maxLoc = templateMatching.getMatches( resized, valueTemplateRotP5, 0.92) valueMatches = map( lambda match: { 'topLeft': (match[0], match[1]), 'name': value }, valueMatches) for valueMatch in valueMatches: tcl = valueMatch['topLeft'] # cv2.imshow("Image", resized) # cv2.waitKey(0) searchArea = resized[(tcl[1] + 0 - 30):(tcl[1] + 90 - 30 + 50), (tcl[0] - 5 - 20):(tcl[0] + 60 - 20)] # cv2.imshow("Image", searchArea) # cv2.waitKey(0) for template_suit_path in glob.glob(img_suits_dir + "\\*.png"): suit = self.path_leaf(template_suit_path) suitTemplate = cv2.imread(template_suit_path) suitTemplate = cv2.cvtColor( suitTemplate, cv2.COLOR_BGR2GRAY) (sH, sW) = suitTemplate.shape[:2] if searchArea.shape[0] < sH or searchArea.shape[ 1] < sW: break _, maxVal1, _ = templateMatching.getMatches( searchArea, suitTemplate, matchingThreshold) suitRecord[suit] = maxVal1 bestSuit = 'spadeR' if searchArea.shape[0] < sH or searchArea.shape[1] < sW: break for template_suit_path in glob.glob(img_suits_dir + "\\*.png"): suit = self.path_leaf(template_suit_path) if suitRecord[suit] >= suitRecord[bestSuit]: bestSuit = suit card = value[0] + bestSuit[0].upper() if suitRecord[bestSuit] > 0.90: cardsFound.add(card) self.hand[card] += 1 if self.found[card] is None or maxVal > self.found[card][0] or suitRecord[bestSuit] > \ self.found[card][1]: self.found[card] = (maxVal, suitRecord[bestSuit], maxLoc, r) if self.found[card] is None or self.found[card][0] == 0: continue while len(cardsFound) > 2: minValue = 10000 minCard = '' for card in cardsFound: if self.hand[card] <= minValue: minValue = self.hand[card] minCard = card # print("remove redundant card", minCard) cardsFound.remove(minCard) self.my_cards = list(cardsFound) print(self.found) return True
def __init__(self, table_dict): config = get_config() self.table_size = config['DEFAULT']['table_size'] self.delta_x = config['DEFAULT']['delta_x'] self.delta_y = config['DEFAULT']['delta_y'] self.scale_table_cards_area = scale_cal(self.table_size, 'table_cards_area') self.scale_defaults = scale_cal(self.table_size) self.table_dict = table_dict self.screenshot = None self.screenshots = [None for _ in range(6)] # Maximum = 6 self.total_players = 6 self.my_cards = None self.table_cards = None self.current_round_pot = None self.total_pot = None self.dealer_position = None self.miss_player = None self.players_in_game = None self.player_funds = None # self.player_pots = None self.call_value = 0 self.raise_value = 0 self.call_button = None self.raise_button = None self.tlc = None self.player_funds = [0 for _ in range(self.total_players)] self.player_pots = [0 for _ in range(self.total_players)] self.count = 0 self.test = 0 self.select_table = 0 self.tlcs = None self.scale_m = 1.0 self.gg_poker = None self.gg_poker_rel = None # self.found = {'2s': None, '2h': None, '2d': None, '2c': None, '3s': None, '3h': None, '3d': None, '3c': None, # '4s': None, # '4h': None, '4d': None, # '4c': None, '5s': None, '5h': None, '5d': None, '5c': None, '6s': None, '6h': None, '6d': None, # '6c': None, # '7s': None, '7h': None, # '7d': None, '7c': None, '8s': None, '8h': None, '8d': None, '8c': None, '9s': None, '9h': None, # '9d': None, # '9c': None, 'Ts': None, # 'Th': None, 'Td': None, 'Tc': None, 'Js': None, 'Jh': None, 'Jd': None, 'Jc': None, 'Qs': None, # 'Qh': None, # 'Qd': None, 'Qc': None, # 'Ks': None, 'Kh': None, 'Kd': None, 'Kc': None, 'As': None, 'Ah': None, 'Ad': None, 'Ac': None} self.found = { '2S': None, '2H': None, '2D': None, '2C': None, '3S': None, '3H': None, '3D': None, '3C': None, '4S': None, '4H': None, '4D': None, '4C': None, '5S': None, '5H': None, '5D': None, '5C': None, '6S': None, '6H': None, '6D': None, '6C': None, '7S': None, '7H': None, '7D': None, '7C': None, '8S': None, '8H': None, '8D': None, '8C': None, '9S': None, '9H': None, '9D': None, '9C': None, 'TS': None, 'TH': None, 'TD': None, 'TC': None, 'JS': None, 'JH': None, 'JD': None, 'JC': None, 'QS': None, 'QH': None, 'QD': None, 'QC': None, 'KS': None, 'KH': None, 'KD': None, 'KC': None, 'AS': None, 'AH': None, 'AD': None, 'AC': None } self.hand = { '2S': 0, '2H': 0, '2D': 0, '2C': 0, '3S': 0, '3H': 0, '3D': 0, '3C': 0, '4S': 0, '4H': 0, '4D': 0, '4C': 0, '5S': 0, '5H': 0, '5D': 0, '5C': 0, '6S': 0, '6H': 0, '6D': 0, '6C': 0, '7S': 0, '7H': 0, '7D': 0, '7C': 0, '8S': 0, '8H': 0, '8D': 0, '8C': 0, '9S': 0, '9H': 0, '9D': 0, '9C': 0, 'TS': 0, 'TH': 0, 'TD': 0, 'TC': 0, 'JS': 0, 'JH': 0, 'JD': 0, 'JC': 0, 'QS': 0, 'QH': 0, 'QD': 0, 'QC': 0, 'KS': 0, 'KH': 0, 'KD': 0, 'KC': 0, 'AS': 0, 'AH': 0, 'AD': 0, 'AC': 0 }
import io import json import logging import requests from PIL import Image from fastapi.encoders import jsonable_encoder from poker.tools.helper import COMPUTER_NAME, get_config, get_dir from poker.tools.singleton import Singleton TABLES_COLLECTION = 'tables' log = logging.getLogger(__name__) config = get_config() URL = config.config.get('main', 'db') class MongoManager(metaclass=Singleton): """Single class to manage interaction with mongodb""" def __init__(self): """Initialize connection as singleton""" self.login = config.config.get('main', 'login') self.password = config.config.get('main', 'password') def save_image(self, table_name, label, image): """ save market image in mongodb