Ожидание клёва
1
.gitignore
vendored
@ -160,3 +160,4 @@ cython_debug/
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
.vscode
|
||||
|
||||
BIN
bober.png
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 5.6 KiB |
BIN
bober1.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 2.1 MiB |
|
Before Width: | Height: | Size: 2.1 MiB |
|
Before Width: | Height: | Size: 240 KiB |
|
Before Width: | Height: | Size: 2.1 MiB |
|
Before Width: | Height: | Size: 2.1 MiB |
BIN
bober_underwater.png
Normal file
|
After Width: | Height: | Size: 4.6 KiB |
132
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__":
|
||||
|
||||
5
requirements.txt
Normal file
@ -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
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||