def test_4ocr_valu44(): # ok log = logging.getLogger(__name__) mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') table_scraper = TableScraper(table_dict) file_name = get_dir(os.path.join('log', 'pics', 'table_b_16.png')) table_scraper.screenshot = Image.open(file_name) # table_scraper.crop_from_top_left_corner2(select_table=0) if is_debug: # table_scraper.screenshot.save('log/pics/table1.png') file_name = get_dir(os.path.join('log', 'pics', 'table_label.png')) save_table_rectangle_cv2(table_scraper.screenshot, table_dict, file_name) table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_player_pots() log.info(f"{table_scraper.total_pot}") log.info(f"{table_scraper.current_round_pot}") log.info(f"{table_scraper.player_funds}") log.info(f"{table_scraper.player_pots}") # pytest.assume(table_scraper.total_pot == 4.0) # assert table_scraper.total_pot == 4.0 # pytest.assume(table_scraper.player_pots == [-1.0, -1.0, -1.0, 0.5, -1.0, 1.0]) pytest.assume(table_scraper.current_round_pot == 2.0)
def prepareImage(img_orig, image_area=None, binarize=True, mode=None): """Prepare image for OCR""" def binarize_array_opencv(image): """Binarize image from gray channel with 76 as threshold""" img = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, thresh2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) # _, thresh2 = cv2.threshold(img, 76, 255, cv2.THRESH_BINARY_INV) return Image.fromarray(thresh2) # def binarize_array_opencv1(image): # image = pil_to_cv2(image) # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # gray = cv2.threshold(gray, 0, 255, # cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] # return Image.fromarray(gray) basewidth = 300 wpercent = (basewidth / float(img_orig.size[0])) hsize = int((float(img_orig.size[1]) * float(wpercent))) img_resized = img_orig.convert('L').resize((basewidth, hsize), Image.LANCZOS) # if image_area[:15] == 'player_pot_area': # binarize = False # log.info(f'The image_area is:{image_area}') if binarize: img_resized = binarize_array_opencv(img_resized) # else: # img_resized = binarize_array_opencv1(img_resized) # if mode == 1: # img_resized = img_resized.filter(ImageFilter.MinFilter) # log.info(f'Min filter is applied') # elif mode == 2: # img_resized = img_resized.filter(ImageFilter.ModeFilter) # log.info(f'Mode filter is applied') # elif mode == 3: # img_resized = img_resized.filter(ImageFilter.MedianFilter) # log.info(f'Median filter is applied') # elif mode == 4: # img_resized = img_resized.filter(ImageFilter.SHARPEN) # log.info(f'Sharpen filter is applied') if mode==True: pics_path = "log/pics" try: if not os.path.exists(pics_path): os.makedirs(pics_path) except OSError: log.error("Creation of the directory %s failed" % pics_path) sys.exit(1) img_orig.save(get_dir(os.path.join('log', 'pics', image_area + '.png'))) img_resized.save(get_dir(os.path.join('log', 'pics', image_area + '_resized.png'))) log.debug("ocr images prepared") return img_resized
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
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
def test_ocr_valu36(): # ok log = logging.getLogger(__name__) mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(os.environ['test_test'], '5.png')) table_scraper.crop_from_top_left_corner2(select_table=2) if is_debug: # table_scraper.screenshot.save('log/pics/table1.png') file_name = get_dir(os.path.join('log', 'pics', 'table_label.png')) save_table_rectangle_cv2(table_scraper.screenshot, table_dict, file_name) table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_player_pots() log.info(f"{table_scraper.total_pot}") log.info(f"{table_scraper.player_funds}") log.info(f"{table_scraper.player_pots}") pytest.assume(table_scraper.total_pot == 12.0) pytest.assume( table_scraper.player_funds == [145.5, 100.0, 20.0, 18.0, 187.5, 94.5]) pytest.assume( table_scraper.player_pots == [-1.0, -1.0, -1.0, -1.0, -1.0, -1.0])
def test_ocr_valu22(): # ok # init_logger(screenlevel=logging.DEBUG, filename='test-ocr', logdir='log') mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(os.environ['test_test'], '2.png')) table_scraper.crop_from_top_left_corner2(select_table=3) if is_debug: # table_scraper.screenshot.save('log/pics/table1.png') file_name = get_dir(os.path.join('log', 'pics', 'table_label.png')) save_table_rectangle_cv2(table_scraper.screenshot, table_dict, file_name) table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_player_pots() log.info(f"{table_scraper.total_pot}") log.info(f"{table_scraper.player_funds}") log.info(f"{table_scraper.player_pots}") pytest.assume(table_scraper.total_pot == 12.5) pytest.assume( table_scraper.player_funds == [154.0, 104.5, 90.0, 95.0, 20.0, 190.0]) pytest.assume(table_scraper.player_pots == [ 2.0, 0.5, 10.0, -1.0, -1.0, -1.0 ]) # [2.0, 0.5, 10.0, -1.0, 4.0, -1.0]
def test_ocr_valu10(): # ok log = logging.getLogger(__name__) mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(os.environ['test_src'], '1.png')) table_scraper.crop_from_top_left_corner2(select_table=3) if is_debug: # table_scraper.screenshot.save('log/pics/table1.png') file_name = get_dir(os.path.join('log', 'pics', 'table_label.png')) save_table_rectangle_cv2(table_scraper.screenshot, table_dict, file_name) table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_player_pots() log.info(f"{table_scraper.total_pot}") log.info(f"{table_scraper.player_funds}") log.info(f"{table_scraper.player_pots}") pytest.assume(table_scraper.total_pot == 5.0) # 73.0 pytest.assume(table_scraper.player_funds == [ 25.0, 11.0, 98.0, 188.5, 50.5, 100.0 ]) # [29.0, 6.0, 98.0, 108.9, 30.5, 10.0] pytest.assume(table_scraper.player_pots == [ -1.0, -1.0, 2.0, 2.0, 1.0, -1.0 ]) # [-1.0, -1.0, 25.0, -1.0, 1.0, -1.0]
def test_ocr_valu8(): # ok log = logging.getLogger(__name__) mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(os.environ['test_src'], '1.png')) table_scraper.crop_from_top_left_corner2(select_table=0) if is_debug: # table_scraper.screenshot.save('log/pics/table1.png') file_name = get_dir(os.path.join('log', 'pics', 'table_label.png')) save_table_rectangle_cv2(table_scraper.screenshot, table_dict, file_name) table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_player_pots() pytest.assume(table_scraper.total_pot == 12.5) pytest.assume( table_scraper.player_funds == [23.0, 100.0, 42.0, 23.0, 97.5, 102.0]) # pass pytest.assume( table_scraper.player_pots == [-1.0, -1.0, 6.0, -1.0, -1.0, -1.0]) # Ghost number
def test_ocr_valu6(): # ok log = logging.getLogger(__name__) mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') table_scraper = TableScraper(table_dict) table_scraper.screenshot = Image.open( os.path.join(os.environ['test_src1'], '9.png')) table_scraper.crop_from_top_left_corner2(select_table=0) if is_debug: # table_scraper.screenshot.save('log/pics/table1.png') file_name = get_dir(os.path.join('log', 'pics', 'table_label.png')) save_table_rectangle_cv2(table_scraper.screenshot, table_dict, file_name) table_scraper.get_pots() table_scraper.get_players_funds() table_scraper.get_player_pots() log.info(f"{table_scraper.total_pot}") log.info(f"{table_scraper.player_funds}") log.info(f"{table_scraper.player_pots}") # assert table_scraper.total_pot == 4 pytest.assume(table_scraper.total_pot == 4.0) # 0.4 == 4.0 capture err pytest.assume( table_scraper.player_funds == [16.5, 23.5, 225.0, 65.5, 101.5, 100.0]) pytest.assume( table_scraper.player_pots == [-1.0, 0.5, 1.0, 2.5, -1.0, -1.0])
def test_table_preflop_zenith(): # tlc = get_table_tlc() # Init table function p = StrategyHandler() p.read_strategy() mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') gui_signals = MagicMock() gui_signals.select_table = 0 # select table game_logger = MagicMock() version = 4.21 SB = 0.5 prefix = 'e' t = TableScreenBased(p, table_dict, gui_signals, game_logger, version) t.screenshot = Image.open( get_dir(os.path.join('log', 'pics', 'table_' + prefix + '_0.png'))) t.get_dealer_position() t.get_miss_player() p_Zenith = CurrentHandPreflopStateZenith() p_Zenith.reset() # Specify miss player or calculate through t.get_miss_player(). p_Zenith.miss_player = t.miss_player p_Zenith.dealer_position = t.dealer_position p_Zenith.small_blind = SB p_Zenith.abs_to_rel() table_preflop_zenith(t, p_Zenith, prefix, -2, 20) print(p_Zenith.actions)
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
def test_label_pos0(): # ok log = logging.getLogger(__name__) mongo = MongoManager() table_dict = mongo.get_table('GG_6TABLE') table_scraper = TableScraper(table_dict) prefix = 'b_16' table_scraper.screenshot = Image.open(get_dir(os.path.join('log', 'pics', 'table_' + prefix + '.png'))) for i in [0]: for j in [0]: # table_scraper.crop_from_top_left_corner2(select_table=0) if is_debug: file_name = get_dir(os.path.join('log', 'pics', 'table_label_pos_' + str(i) + '_' + str(j) + '.png')) """ Move table by delta_x = -8 , delta_y = -5 from config.ini """ save_table_rectangle_cv2(table_scraper.screenshot, table_dict, file_name) return True
def get_screenshot(name, prefix, tlc): original_screenshot = take_screenshot() cropped_screenshot = original_screenshot.crop( scale_convertor1(tlc[0], tlc[1], tlc[0] + 900, tlc[1] + 700, 1.0)) file_name = get_dir(os.path.join("log", "pics", 'table_' + prefix + '_' + name + '.png')) if os.path.isfile(file_name): os.remove(file_name) cropped_screenshot.save(file_name) log.info(f"{file_name} is saved.") return cropped_screenshot
def test_pytesseract_value(): log_file = get_dir(os.path.join("log", "pics", 'pytesseract.txt')) f = open(log_file, "a") f.write("New pytesseract\n") f.close() name = [ 'total_pot_area.png', 'player_pot_area0.png', 'player_pot_area1.png', 'player_pot_area2.png', 'player_pot_area3.png', 'player_pot_area4.png', 'player_pot_area5.png', 'player_funds_area0.png', 'player_funds_area1.png', 'player_funds_area2.png', 'player_funds_area3.png', 'player_funds_area4.png', 'player_funds_area5.png', 'current_round_pot.png' ] for i in range(14): lst = [] file_name = get_dir(os.path.join('log', 'pics', name[i])) img_orig = Image.open(file_name) is_debug = False img_resized = prepareImage(img_orig, mode=False) config_ocr = "--psm 7 --oem 1 -c tessedit_char_whitelist='0123456789.,$£B ' --user-patterns eng.user_patterns" lst.append( pytesseract.image_to_string(img_resized, 'eng', config=config_ocr).strip()) lst.append( pytesseract.image_to_string(img_resized, 'ocrd', config=config_ocr).strip()) lst.append( pytesseract.image_to_string(img_resized, 'deu', config=config_ocr).strip()) f = open(log_file, "a") f.write(f'{name[i]} with eng:{lst[-3]}') f.write("\n") f.write(f'{name[i]} with ocrd:{lst[-2]}') f.write("\n") if is_bb_exist(lst[-1]): f.write(f'{name[i]} with deu:{lst[-1]}') else: f.write(f'{name[i]} with deu: None reporting {lst[-1]}') f.write("\n") f.write("---------------------------------------------------") f.write("\n") f.close()
def get_screenshot1(n, prefix, tlc): """ scheme30: 10*1 + 20*0.1 19:12:29 INFO Finished 'get_screenshot1' in 26.8203 secs 19:12:43 INFO Finished 'test_table_preflopZenith1' in 40.6602 secs 19:12:43 INFO Finished 'test_run' in 40.6652 secs scheme20: 10*1 + 10*0.1 19:16:16 INFO Finished 'get_screenshot1' in 20.9223 secs 19:16:25 INFO Finished 'test_run' in 30.0056 secs scheme20: 6*1 + 14*0.1 19:19:44 INFO Finished 'get_screenshot1' in 17.9457 secs 19:19:56 INFO Finished 'test_run' in 30.3717 secs scheme10: 3*2 + 4*0.1 + 3*2 19:32:30 INFO Finished 'get_screenshot1' in 18.1581 secs 19:32:33 INFO Finished 'test_run' in 21.4130 secs scheme12: 3*2 + 4*0.1 + 5*1.5 19:38:38 INFO Finished 'get_screenshot1' in 20.4316 secs 19:38:40 INFO Finished 'test_run' in 22.0900 secs """ log.debug(f"'{prefix}' daemon starting") 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: os.remove(file_name) except PermissionError: time.sleep(0.5) try: os.remove(file_name) except: pass # scheme: 12 for i in range(n): get_screenshot(str(i), prefix, tlc) # 8*0.5 + 7*2 = 18 sec if i % 5 == 0 and i % 5 == 2: time.sleep(0.1) else: time.sleep(1.5) # # scheme: 20 # for i in range(n): # get_screenshot(str(i), tlc) # if i < 6: # time.sleep(1) # elif i < 20: # time.sleep(0.1) log.debug(f"'{prefix}' Daemon Exiting") return True
def test_table_screenshot(): tlc = [1529, 377] """ 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 = GameLogger() t = TableScreenBased(p, table_dict, gui_signals, game_logger, version) """ original_screenshot = take_screenshot() cropped_screenshot = original_screenshot.crop( scale_convertor1(tlc[0], tlc[1], tlc[0] + 900, tlc[1] + 700, 1.0)) cropped_screenshot.save(get_dir(os.path.join('log', 'pics', 'table_cropped.png')))
def find_backup_image(t): image_backup = 10 t.current_round_pot = 1 while t.current_round_pot > 0: file_name = get_dir(os.path.join("log", "pics", 'table_' + str(image_backup) + '.png')) if os.path.isfile(file_name): t.screenshot = Image.open(file_name) t.get_pots() if t.current_round_pot < 0: log.debug(f"current_round_pot :{t.current_round_pot}.") break # log.info(f"Use backup image {image_backup}.") image_backup -= 1 if image_backup < 0: return False log.debug(f"Use backup image {image_backup}.") return True
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 is_new_action(self, t): """ if there is pot change for player in game, returns True. """ # t.get_pots() # update current_round_pot and total_pot # # Prepare to check Active player abs # t.get_players_in_game() # t.get_player_pots(skip=[]) # t.get_my_cards3() self.is_my_turn = t.is_my_turn() # self.players_in_game_abs = t.players_in_game is_zero_covered = is_template_in_search_area(t.table_dict, t.screenshot, 'covered_card', 'covered_card_area', t.scale_defaults, str(0)) # To use in Round test. is_bb_covered = is_template_in_search_area(t.table_dict, t.screenshot, 'covered_card', 'covered_card_area', t.scale_defaults, str(5)) self_logger.debug(f"player 0 is covered card {is_zero_covered}") self_logger.debug(f"player 5 is covered card {is_bb_covered}") if not self.is_my_turn and not is_zero_covered: try: index = self.players_in_game_abs.index(0) self.players_in_game_abs.pop(index) except: pass if not is_bb_covered: try: index = self.players_in_game_abs.index(5) self.players_in_game_abs.pop(index) except: pass # Update player in game with now_player_order. self.update_player_in_game(t) if len(self.players_in_game_abs1) == 0: self_logger.info(f"There is no Players in game for this Preflop.") return False self.player_pots = t.player_pots # test active player abs and rels if self.is_my_turn: self.active_player_abs = 0 self.active_player_rel = self.find_rel_pos(self.active_player_abs) self.current_active_player = self.player_round[ self.active_player_rel] else: self_logger.info( f"players in game rel: {self.players_in_game_rel}") self_logger.info( f"players in game abs1: {self.players_in_game_abs1}") if not self.get_active_player_abs(): self_logger.info(f'No active player') return False self.active_player_rel = self.find_rel_pos(self.active_player_abs) self.current_active_player = self.player_round[ self.active_player_rel] self_logger.info(f'active player abs: {self.active_player_abs}') self_logger.info(f'active player rels: {self.active_player_rel}') self_logger.info( f'current active player: {self.current_active_player}') # Get current Round if self.get_round_status(): self_logger.info(f'round: {self.round}') self_logger.info(f'Now Player Order: {self.now_player_order}') else: self_logger.info(f'Failed to check round status.') return False # Get player action: if self.round == 1: tmp = 0 else: tmp = self.max_player if self.now_player_order > self.active_player_rel + tmp: self_logger.info(f'It is up-to-date') self_logger.info(f" actions: {self.actions}") return False while self.now_player_order <= self.active_player_rel + tmp: t.get_pots2("total_pot_area") self.now_player_order_abs = self.find_abs_pos( self.now_player_order) self_logger.debug( f"-----------Debug log---------------------------------") self_logger.debug(f'round: {self.round}') self_logger.debug(f'dealer: {self.dealer_position}') self_logger.debug(f"total_pot: {t.total_pot} ") self_logger.debug(f"now_player_order: {self.now_player_order}") self_logger.debug( f"now_player_order_abs: {self.now_player_order_abs}") t.get_player_pots_nn(self.now_player_order_abs) self_logger.debug( f"current_pot: {t.player_pots[self.now_player_order_abs]}") self_logger.debug( f"players_in_game_abs1: {self.players_in_game_abs1}") self_logger.debug(f'current_round_pot: {t.current_round_pot}') self_logger.debug(f'self.last_image_pots: {self.last_image_pots}') self_logger.debug(f'self.player_pots: {self.player_pots}') self_logger.debug(f'SB: {self.small_blind}') self_logger.debug(f"--------------------------------------------") # handle players not in game if self.now_player_order_abs not in self.players_in_game_abs1: self_logger.debug( f"before go into next stage {self.now_player_order_abs} not in {self.players_in_game_abs1}" ) self.action = self.player_round[self.now_player_order % self.max_player] + '_' + 'fold' self.actions[self.now_player_order] = self.action self.now_player_order += 1 if is_debug: t.screenshot.save( get_dir( os.path.join( 'log', 'pics', str(self.dealer_position) + '_' + self.action + '.png'))) continue # handle players in game. if t.total_pot == 1.0 + self.small_blind: if t.player_pots[self.now_player_order_abs] <= 1: self_logger.debug( f"before go into nex stage {t.total_pot} == 1.5,{t.player_pots[self.now_player_order_abs]} <= 1" ) if t.current_round_pot > 0: self_logger.info(f"all actions are completed.") self_logger.debug( f"before go into nex stage t.current_round_pot > 0" ) call = self.get_max_bet_value(self.now_player_order) self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + str(call) self.actions[self.now_player_order] = self.action return False break # self.action = self.player_round[self.now_player_order % self.max_player] + '_' + 'fold' # # Remove from players in game. # index = t.players_in_game.index(self.now_player_order_abs) # self.players_in_game_abs.pop(index) # self.actions[self.now_player_order] = self.action # self.now_player_order += 1 # self_logger.info(f"action: {self.action}") elif t.total_pot > 1.0 + self.small_blind: t.get_player_pots_nn(self.now_player_order_abs) # 1st round if self.now_player_order < self.max_player: current_pot = t.player_pots[self.now_player_order_abs] if t.current_round_pot > 0: self_logger.debug( f"self.now_player_order < self.max_player and t.current_round_pot > 0" ) # if max value is -1 and number_of_player == n, call = total_pot // n. call = self.get_max_bet_value(self.now_player_order) if call < 0: sys.exit() #call = t.total_pot // len(self.players_in_game_abs1) self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + str(call) self.actions[self.now_player_order] = self.action self.now_player_order += 1 continue elif current_pot == 1: # self.action = self.player_round[self.now_player_order % self.max_player] + '_' + 'fold' # # Remove from players in game. # index = t.players_in_game.index(self.now_player_order_abs) # self.players_in_game_abs.pop(index) self_logger.debug( f"before go into nex stage current_pot == 1") if self.now_player_order != self.bb_rel: self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + str(1.0) self.actions[self.now_player_order] = self.action self.now_player_order += 1 continue else: break # if is_debug: # t.screenshot.save( # get_dir(os.path.join('log', 'pics', # str(self.dealer_position) + '_' + self.action + '.png'))) elif current_pot > 1 and t.current_round_pot < 0: self_logger.debug( f"before go into nex stage t.player_pots[self.now_player_order_abs] > 1" ) self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + str( t.player_pots[self.now_player_order_abs]) self.actions[self.now_player_order] = self.action self.now_player_order += 1 if is_debug: t.screenshot.save( get_dir( os.path.join( 'log', 'pics', str(self.dealer_position) + '_' + self.action + '.png'))) else: self_logger.debug( f" current_pot < 1 and t.current_round_pot < 0") break # 2nd round elif self.now_player_order >= self.max_player: pre_pot = float( self.actions[self.now_player_order % self.max_player].split('_')[1]) current_pot = t.player_pots[self.now_player_order_abs] if t.current_round_pot > 0: self_logger.info(f"all actions are completed.") self_logger.debug( f"before go into nex stage t.current_round_pot > 0" ) call = self.get_max_bet_value(self.now_player_order) if call < 0: return False self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + str(call) self.actions[self.now_player_order] = self.action return False if current_pot < 0 and t.current_round_pot < 0: self_logger.debug( f"before go into nex stage current_pot < 0 and t.current_round_pot < 0" ) break # Check in another image. if current_pot == pre_pot: self_logger.debug( f"before go into nex stage current_pot == pre_pot") break # pots are distributed and transfered to next game. if current_pot < pre_pot and current_pot > 0: self_logger.info(f"all actions are completed.") self_logger.debug( f"before go into nex stage current_pot < pre_pot and current_pot > 0" ) return False self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + str(current_pot) self.actions[self.now_player_order] = self.action self.now_player_order += 1 if is_debug: t.screenshot.save( get_dir( os.path.join( 'log', 'pics', str(self.dealer_position) + '_' + self.action + '.png'))) # self_logger.info(f"action: {self.action}") elif t.total_pot == 1.0: # sb fold and BB win the pot. if self.now_player_order == self.max_player - 2: # SB self_logger.debug( f"t.total_pot == 1.0: and self.now_player_order == self.max_player - 2" ) self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + 'fold' self.actions[self.now_player_order] = self.action self.now_player_order += 1 elif self.now_player_order == self.max_player - 1: # BB self_logger.debug( f"t.total_pot == 1.0: and self.now_player_order == self.max_player - 1" ) self.action = self.player_round[ self.now_player_order % self.max_player] + '_' + '1.0' self.actions[self.now_player_order] = self.action self.now_player_order += 1 return True else: return True else: self_logger.info(f'There is err, total_pot: {t.total_pot}') return False # all player have same pots. Transfer to next game stage. # if max(t.player_pots) != min([t.player_pots[i] for i in t.players_in_game]): # self_logger.info(f"use_backup_image") # self.use_backup_image = True 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 table_preflop_zenith(t, p_Zenith, prefix, start, end): log.debug("Non-daemon starting") # # Update basic information. # t.screenshot = get_screenshot('cropped', tlc) # 1st= 0.6, 2nd=2.0, 3rd=0.6 time.sleep(3.2) # Find image with players in game. for i in range(start + 2, end): # 1st= 0.6, 2nd=2.0, 3rd=0.6 # time.sleep(3.2) file_name = get_dir(os.path.join("log", "pics", 'table_' + prefix + '_' + str(i) + '.png')) while not os.path.isfile(file_name): time.sleep(0.5) t.screenshot = Image.open(file_name) # If it is flop stage, check next image. t.get_pots2("current_round_pot") if t.current_round_pot > 0: continue t.get_players_in_game() if len(t.players_in_game) > 1: log.info(f"Players in game: {t.players_in_game} and start from: {i} and {file_name}") p_Zenith.players_in_game_abs = t.players_in_game start = i break # Exit if consume all images. if len(t.players_in_game) < 2 and i == end - 1: log.debug(f"Non-daemon Exiting prefix: {prefix} by len(t.players_in_game) < 2 and i == end - 1") return True t.get_dealer_position() p_Zenith.dealer_position = t.dealer_position # p_Zenith.abs_to_rel() t.get_pots() # exclude = set(range(6)) - set(t.players_in_game) # t.get_player_pots(skip=list(exclude)) t.get_player_pots() p_Zenith.player_pots = t.player_pots # Update again for missed player. p_Zenith.update_miss_player() log.info(f"miss player:{p_Zenith.miss_player}") p_Zenith.abs_to_rel() for i in range(start, end): file_name = get_dir(os.path.join("log", "pics", 'table_' + prefix + '_' + str(i) + '.png')) log.debug(f"Start to analyze table :{file_name}") # Update players in game with low time cost. t.get_players_in_game() p_Zenith.players_in_game_abs = t.players_in_game # try: # t.screenshot = Image.open(file_name) # except FileNotFoundError: # try: # time.sleep(0.5) # t.screenshot = Image.open(file_name) # except FileNotFoundError: # try: # time.sleep(0.5) # t.screenshot = Image.open(file_name) # except FileNotFoundError: # pass while not os.path.isfile(file_name): time.sleep(0.5) t.screenshot = Image.open(file_name) p_Zenith.file_name = file_name # log.debug(f"now_player_order:{p_Zenith.now_player_order}") t.get_pots2("current_round_pot") # exclude = set(range(6)) - set([now_player_order_abs]) # t.get_player_pots(skip=list(exclude)) log.debug(f"prepared") log.debug(f"current_round_pot :{t.current_round_pot}") if not t.is_dealer_changed(p_Zenith.dealer_position): log.debug(f"Dealer position changed.") break if t.current_round_pot < 0: # gamestaget: preflop # Process preflop status. # ready = preflop_state_Zenith.get_players_status(t) ready = p_Zenith.get_players_status(t) log.debug(f"--------------------------------------") log.debug(f"p_Zenith.now_player_order : {p_Zenith.now_player_order}") log.debug(f"p_Zenith.actions : {p_Zenith.actions}") log.debug(f"--------------------------------------") # if file_name is None: # sys.exit() # p_Zenith.file_name = file_name elif t.current_round_pot > 0: ready = p_Zenith.get_players_status(t) if not ready: # if file_name is None: # sys.exit() # p_Zenith.file_name = file_name break continue if len(p_Zenith.players_in_game_abs1) == 0: break log.debug("Non-daemon Exiting") return True
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()