230 lines
13 KiB
Python
Executable File
230 lines
13 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
import time
|
||
import pyautogui
|
||
import cv2
|
||
import numpy as np
|
||
import mss
|
||
import os
|
||
from datetime import datetime
|
||
from PIL import Image
|
||
|
||
|
||
def find_bober_on_screen():
|
||
"""
|
||
Ждет 3 секунды, нажимает левую кнопку мыши на 1 секунду,
|
||
затем ищет 'bober.png' на экране и выводит "bober find)" при обнаружении.
|
||
"""
|
||
print("Ожидание 3 секунд перед началом...")
|
||
time.sleep(3)
|
||
|
||
print("Нажатие левой кнопки мыши на 1 секунду...")
|
||
pyautogui.mouseDown(button='left')
|
||
time.sleep(1)
|
||
pyautogui.mouseUp(button='left')
|
||
print("Кнопка мыши отпущена.")
|
||
time.sleep(1)
|
||
|
||
template_image_path = "bober.png"
|
||
|
||
# Проверяем существование файла шаблона
|
||
if not os.path.exists(template_image_path):
|
||
print(f"Ошибка: Файл шаблона '{template_image_path}' не найден!")
|
||
print("Пожалуйста, убедитесь, что 'bober.png' находится в той же директории, что и скрипт.")
|
||
return
|
||
|
||
# Загрузка шаблонного изображения
|
||
template = cv2.imread(template_image_path, cv2.IMREAD_GRAYSCALE)
|
||
if template is None:
|
||
print(f"Ошибка: Не удалось загрузить шаблонное изображение по пути: {template_image_path}")
|
||
return
|
||
|
||
w, h = template.shape[::-1] # Ширина и высота шаблона
|
||
|
||
print(f"Поиск '{template_image_path}' в левой верхней четверти экрана...")
|
||
|
||
# Получаем размеры экрана
|
||
screen_width, screen_height = pyautogui.size()
|
||
|
||
# Определяем левую верхнюю четверть экрана
|
||
quarter_width = screen_width // 2
|
||
quarter_height = screen_height // 2
|
||
|
||
print(f"Размер экрана: {screen_width}x{screen_height}")
|
||
print(f"Область поиска (левая верхняя четверть): 0,0 - {quarter_width}x{quarter_height}")
|
||
|
||
with mss.mss() as sct:
|
||
# Определяем область для захвата (левая верхняя четверть)
|
||
monitor = {
|
||
"top": 0,
|
||
"left": 0,
|
||
"width": quarter_width,
|
||
"height": quarter_height
|
||
}
|
||
|
||
# Делаем скриншот левой верхней четверти экрана
|
||
sct_img = sct.grab(monitor)
|
||
|
||
# Конвертируем скриншот в массив numpy и затем в оттенки серого
|
||
img_np = np.array(sct_img)
|
||
img_gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
|
||
|
||
# Выполняем поиск шаблона
|
||
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
|
||
|
||
# Определяем порог для совпадения
|
||
# Можно настроить это значение (например, 0.8 или 0.9)
|
||
# в зависимости от того, насколько точным должно быть совпадение.
|
||
threshold = 0.5
|
||
loc = np.where(res >= threshold)
|
||
|
||
# Подсчет найденных совпадений
|
||
matches = list(zip(*loc[::-1]))
|
||
|
||
# Получаем максимальное значение совпадения для проверки
|
||
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
|
||
|
||
# Флаг для определения, нужно ли сохранять скриншот
|
||
should_save_screenshot = False
|
||
found_location = None
|
||
|
||
if len(matches) > 0:
|
||
print("bober find)")
|
||
should_save_screenshot = True
|
||
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
|
||
|
||
# Сохраняем скриншот области, где найден 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 Image
|
||
img_pil = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")
|
||
|
||
# Определяем область для обрезки вокруг найденного 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__":
|
||
find_bober_on_screen()
|