diff --git a/.gitignore b/.gitignore index 5d381cc..a199f52 100644 --- a/.gitignore +++ b/.gitignore @@ -160,3 +160,4 @@ cython_debug/ # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ +.vscode diff --git a/bober.png b/bober.png index c79d653..0c66dc3 100644 Binary files a/bober.png and b/bober.png differ diff --git a/bober1.png b/bober1.png new file mode 100644 index 0000000..c79d653 Binary files /dev/null and b/bober1.png differ diff --git a/bober_found_20251107_200724.png b/bober_found_20251107_200724.png deleted file mode 100644 index f9fa5d0..0000000 Binary files a/bober_found_20251107_200724.png and /dev/null differ diff --git a/bober_found_20251107_200755.png b/bober_found_20251107_200755.png deleted file mode 100644 index 6e8dc08..0000000 Binary files a/bober_found_20251107_200755.png and /dev/null differ diff --git a/bober_found_20251107_200913.png b/bober_found_20251107_200913.png deleted file mode 100644 index 7a0775d..0000000 Binary files a/bober_found_20251107_200913.png and /dev/null differ diff --git a/bober_found_20251107_200922.png b/bober_found_20251107_200922.png deleted file mode 100644 index 4fd866f..0000000 Binary files a/bober_found_20251107_200922.png and /dev/null differ diff --git a/bober_found_20251107_200936.png b/bober_found_20251107_200936.png deleted file mode 100644 index 3b0121e..0000000 Binary files a/bober_found_20251107_200936.png and /dev/null differ diff --git a/bober_underwater.png b/bober_underwater.png new file mode 100644 index 0000000..220e96b Binary files /dev/null and b/bober_underwater.png differ diff --git a/main.py b/main.py index f00c594..0963310 100755 --- a/main.py +++ b/main.py @@ -74,7 +74,7 @@ def find_bober_on_screen(): # Определяем порог для совпадения # Можно настроить это значение (например, 0.8 или 0.9) # в зависимости от того, насколько точным должно быть совпадение. - threshold = 0.7 + threshold = 0.5 loc = np.where(res >= threshold) # Подсчет найденных совпадений @@ -85,30 +85,144 @@ def find_bober_on_screen(): # Флаг для определения, нужно ли сохранять скриншот should_save_screenshot = False + found_location = None if len(matches) > 0: print("bober find)") should_save_screenshot = True - # Опционально: можно вывести координаты найденных совпадений - # for pt in matches: - # print(f" Найдено в точке: ({pt[0]}, {pt[1]})") + found_location = max_loc # Используем место с максимальным совпадением + print(f" Найдено в точке: ({max_loc[0]}, {max_loc[1]})") else: print("bober не найден.") print(f"Максимальная уверенность совпадения: {max_val:.2f} (порог: {threshold})") if max_val >= 0.3: # Если есть хоть какое-то заметное совпадение print(f"Лучшее (но не достаточное) совпадение найдено в точке: ({max_loc[0]}, {max_loc[1]})") should_save_screenshot = True + found_location = max_loc - # Сохраняем скриншот левой верхней четверти экрана, если найдено совпадение (даже с низкой уверенностью) - if should_save_screenshot: + # Сохраняем скриншот области, где найден bober + if should_save_screenshot and found_location: # Создаем имя файла с временной меткой timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") screenshot_filename = f"bober_found_{timestamp}.png" - # Сохраняем скриншот левой верхней четверти экрана используя PIL + # Конвертируем скриншот в PIL Image img_pil = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX") - img_pil.save(screenshot_filename) - print(f"Скриншот левой верхней четверти экрана сохранен: {screenshot_filename}") + + # Определяем область для обрезки вокруг найденного bober + # Добавляем отступ (padding) вокруг найденного объекта + padding = 50 # пикселей вокруг найденного объекта + + x = found_location[0] + y = found_location[1] + + # Вычисляем координаты области для обрезки + left = max(0, x - padding) + top = max(0, y - padding) + right = min(img_pil.width, x + w + padding) + bottom = min(img_pil.height, y + h + padding) + + # Обрезаем изображение до области вокруг найденного bober + cropped_img = img_pil.crop((left, top, right, bottom)) + + # Сохраняем обрезанный скриншот + cropped_img.save(screenshot_filename) + print(f"Скриншот области с bober сохранен: {screenshot_filename}") + print(f" Область: ({left}, {top}) - ({right}, {bottom}), размер: {right-left}x{bottom-top}") + + # Теперь ждем появления bober_underwater.png в этой области + underwater_template_path = "bober_underwater.png" + if os.path.exists(underwater_template_path): + print(f"\nОжидание появления '{underwater_template_path}' в области с bober...") + print(" Мониторинг области каждые 0.5 секунды...") + + # Загружаем шаблон bober_underwater.png + underwater_template = cv2.imread(underwater_template_path, cv2.IMREAD_GRAYSCALE) + + if underwater_template is not None: + underwater_w, underwater_h = underwater_template.shape[::-1] + underwater_threshold = 0.5 + check_interval = 0.5 # секунд между проверками + check_count = 0 + found_underwater = False + + # Определяем область мониторинга на экране (абсолютные координаты) + # left, top уже в координатах левой верхней четверти, но нужно учесть, что это относительно monitor + monitor_left = left + monitor_top = top + monitor_right = right + monitor_bottom = bottom + + # Создаем область для захвата (абсолютные координаты экрана) + monitor_area = { + "top": monitor_top, + "left": monitor_left, + "width": monitor_right - monitor_left, + "height": monitor_bottom - monitor_top + } + + # Цикл ожидания появления bober_underwater + while not found_underwater: + check_count += 1 + + # Захватываем текущую область + area_screenshot = sct.grab(monitor_area) + + # Конвертируем в numpy array и оттенки серого + area_np = np.array(area_screenshot) + area_gray = cv2.cvtColor(area_np, cv2.COLOR_BGR2GRAY) + + # Выполняем поиск шаблона bober_underwater + underwater_res = cv2.matchTemplate(area_gray, underwater_template, cv2.TM_CCOEFF_NORMED) + + # Получаем максимальное значение совпадения + underwater_min_val, underwater_max_val, underwater_min_loc, underwater_max_loc = cv2.minMaxLoc(underwater_res) + + # Проверяем, найден ли bober_underwater + underwater_loc = np.where(underwater_res >= underwater_threshold) + underwater_matches = list(zip(*underwater_loc[::-1])) + + if len(underwater_matches) > 0: + found_underwater = True + print(f"\n✓ bober_underwater.png НАЙДЕН в области с bober!") + print(f" Проверок выполнено: {check_count}") + print(f" Уверенность совпадения: {underwater_max_val:.2f}") + print(f" Позиция в области: ({underwater_max_loc[0]}, {underwater_max_loc[1]})") + + # Сохраняем скриншот с найденным bober_underwater + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + underwater_screenshot_filename = f"bober_underwater_found_{timestamp}.png" + area_img_pil = Image.frombytes("RGB", area_screenshot.size, area_screenshot.bgra, "raw", "BGRX") + area_img_pil.save(underwater_screenshot_filename) + print(f" Скриншот сохранен: {underwater_screenshot_filename}") + + # Вычисляем координаты центра найденного bober_underwater для клика + # Позиция относительно области мониторинга + center_x = underwater_max_loc[0] + underwater_w // 2 + center_y = underwater_max_loc[1] + underwater_h // 2 + + # Абсолютные координаты на экране (учитываем смещение области мониторинга) + click_x = monitor_area["left"] + center_x + click_y = monitor_area["top"] + center_y + + print(f" Удержание левой кнопки мыши по координатам: ({click_x}, {click_y})") + # Перемещаем мышь к позиции и удерживаем кнопку 0.5 секунды + pyautogui.moveTo(click_x, click_y) + pyautogui.mouseDown(button='left') + time.sleep(0.5) + pyautogui.mouseUp(button='left') + print(" ✓ Левой кнопкой мыши удержано 0.5 секунды!") + else: + # Показываем прогресс каждые 10 проверок + if check_count % 10 == 0: + print(f" Проверка #{check_count}... (макс. уверенность: {underwater_max_val:.2f})") + + # Небольшая задержка перед следующей проверкой + time.sleep(check_interval) + else: + print(f"Ошибка: Не удалось загрузить '{underwater_template_path}'") + else: + print(f"\nПредупреждение: Файл '{underwater_template_path}' не найден, пропускаем мониторинг.") if __name__ == "__main__": diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b0bb038 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +mss==10.1.0 +numpy==2.2.6 +opencv-python==4.12.0.88 +Pillow==12.0.0 +PyAutoGUI==0.9.54 diff --git a/v-env/bin/f2py b/v-env/bin/f2py index 2e1b48c..bf3d0a0 100755 --- a/v-env/bin/f2py +++ b/v-env/bin/f2py @@ -1,4 +1,4 @@ -#!/home/feodosiy/project/albionbot/v-env/bin/python3 +#!/home/daniil/Repositories/albionbot/v-env/bin/python # -*- coding: utf-8 -*- import re import sys diff --git a/v-env/bin/mss b/v-env/bin/mss index a81f1b4..300cd3d 100755 --- a/v-env/bin/mss +++ b/v-env/bin/mss @@ -1,4 +1,4 @@ -#!/home/feodosiy/project/albionbot/v-env/bin/python3 +#!/home/daniil/Repositories/albionbot/v-env/bin/python # -*- coding: utf-8 -*- import re import sys diff --git a/v-env/bin/numpy-config b/v-env/bin/numpy-config index 6a78071..d0c572d 100755 --- a/v-env/bin/numpy-config +++ b/v-env/bin/numpy-config @@ -1,4 +1,4 @@ -#!/home/feodosiy/project/albionbot/v-env/bin/python3 +#!/home/daniil/Repositories/albionbot/v-env/bin/python # -*- coding: utf-8 -*- import re import sys diff --git a/v-env/bin/pip3 b/v-env/bin/pip3 index 17563c9..314152a 100755 --- a/v-env/bin/pip3 +++ b/v-env/bin/pip3 @@ -1,4 +1,4 @@ -#!/home/feodosiy/project/albionbot/v-env/bin/python3 +#!/home/daniil/Repositories/albionbot/v-env/bin/python # -*- coding: utf-8 -*- import re import sys diff --git a/v-env/bin/pip3.12 b/v-env/bin/pip3.12 index 17563c9..314152a 100755 --- a/v-env/bin/pip3.12 +++ b/v-env/bin/pip3.12 @@ -1,4 +1,4 @@ -#!/home/feodosiy/project/albionbot/v-env/bin/python3 +#!/home/daniil/Repositories/albionbot/v-env/bin/python # -*- coding: utf-8 -*- import re import sys