Untitled

 avatar
unknown
python
a year ago
8.2 kB
11
Indexable
import cv2
import numpy as np
import pyautogui
import keyboard
import pygetwindow
from PIL import Image
from time import sleep
from datetime import datetime
import os
import random  # Importing the random module

# Function Definitions

def set_active():
    global is_active
    if is_active:
        is_active = False
        print("Inactive")
    else:
        is_active = True
        print("Active")

def set_exit():
    global exit_script
    exit_script = True

def get_window_name():
    window_name = input("Enter the name of the window (e.g., TelegramDesktop): ")
    return window_name

def screenshot(window):
    path = './screenshots/blum.png'
    left, top, right, bottom = window.left, window.top, window.right, window.bottom
    # Adjust the region as needed
    region = (left + 10, top + 10, right - left - 20, bottom - top - 20)
    pyautogui.screenshot(path, region=region)
    return region

def detect_image(screenshot_gray, target_img_gray, threshold):
    result = cv2.matchTemplate(screenshot_gray, target_img_gray, cv2.TM_CCOEFF_NORMED)
    _, max_val, _, max_loc = cv2.minMaxLoc(result)
    if max_val >= threshold:
        return True, max_loc, max_val
    else:
        return False, None, max_val

# Initialize Variables
is_active = False
exit_script = False  # Renamed to avoid conflict with built-in 'exit'
consistent_matches = 0
required_consistent_matches = 3

# Set Hotkeys
keyboard.add_hotkey("q", set_active)
keyboard.add_hotkey("w", set_exit)

# Load Target Images
threshold = 0.7  # Increased threshold to reduce false positives

# Load target image
target_img_path = './images/target2.png'
target_img = cv2.imread(target_img_path, cv2.IMREAD_COLOR)
if target_img is None:
    print(f"Error: Target image '{target_img_path}' not found.")
    exit()

target_img_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY)
target_w, target_h = target_img_gray.shape[1], target_img_gray.shape[0]

# Load crash image
crash_img_path = './images/crash.png'
crash_img = cv2.imread(crash_img_path, cv2.IMREAD_COLOR)
if crash_img is None:
    print(f"Error: Crash image '{crash_img_path}' not found.")
    exit()

crash_img_gray = cv2.cvtColor(crash_img, cv2.COLOR_BGR2GRAY)
crash_w, crash_h = crash_img_gray.shape[1], crash_img_gray.shape[0]

# Load settings image
settings_img_path = './images/settings.png'
settings_img = cv2.imread(settings_img_path, cv2.IMREAD_COLOR)
if settings_img is None:
    print(f"Error: Settings image '{settings_img_path}' not found.")
    exit()

settings_img_gray = cv2.cvtColor(settings_img, cv2.COLOR_BGR2GRAY)
settings_w, settings_h = settings_img_gray.shape[1], settings_img_gray.shape[0]

# Load reset image
reset_img_path = './images/reset.png'
reset_img = cv2.imread(reset_img_path, cv2.IMREAD_COLOR)
if reset_img is None:
    print(f"Error: Reset image '{reset_img_path}' not found.")
    exit()

reset_img_gray = cv2.cvtColor(reset_img, cv2.COLOR_BGR2GRAY)
reset_w, reset_h = reset_img_gray.shape[1], reset_img_gray.shape[0]

# Ensure directories exist
os.makedirs('./screenshots', exist_ok=True)
os.makedirs('./result_image', exist_ok=True)

# Get Window
window = ''
while True:
    window_name = get_window_name()
    try:
        window = pygetwindow.getWindowsWithTitle(window_name)[0]
        print(f"Window '{window_name}' found")
        break
    except IndexError:
        print(f"Window '{window_name}' not found. Please try again.")

print('\nPress "q" to toggle the script.\nPress "w" to exit.\n')

# Main Loop
while True:
    if exit_script:
        break

    if is_active:
        screenshot_region = screenshot(window)
        blum_ss = cv2.imread('./screenshots/blum.png', cv2.IMREAD_COLOR)
        if blum_ss is None:
            print("Error: Screenshot not found.")
            continue

        blum_ss_gray = cv2.cvtColor(blum_ss, cv2.COLOR_BGR2GRAY)

        # First, check for crash.png
        found_crash, max_loc_crash, max_val_crash = detect_image(blum_ss_gray, crash_img_gray, threshold)
        if found_crash:
            print("Crash detected.")
            # Now, detect settings.png and click on it
            settings_clicked = False
            while not settings_clicked:
                screenshot_region = screenshot(window)
                blum_ss = cv2.imread('./screenshots/blum.png', cv2.IMREAD_COLOR)
                if blum_ss is None:
                    print("Error: Screenshot not found.")
                    continue
                blum_ss_gray = cv2.cvtColor(blum_ss, cv2.COLOR_BGR2GRAY)
                found_settings, max_loc_settings, max_val_settings = detect_image(blum_ss_gray, settings_img_gray, threshold)
                if found_settings:
                    x, y = max_loc_settings
                    center_x = int(x + settings_w / 2) + screenshot_region[0]
                    center_y = int(y + settings_h / 2) + screenshot_region[1]
                    pyautogui.leftClick(center_x, center_y)
                    settings_clicked = True
                    print("Clicked on settings.")
                else:
                    print("Settings not found, retrying.")
                    sleep(0.5)

            # Now, detect reset.png and click on it
            reset_clicked = False
            while not reset_clicked:
                screenshot_region = screenshot(window)
                blum_ss = cv2.imread('./screenshots/blum.png', cv2.IMREAD_COLOR)
                if blum_ss is None:
                    print("Error: Screenshot not found.")
                    continue
                blum_ss_gray = cv2.cvtColor(blum_ss, cv2.COLOR_BGR2GRAY)
                found_reset, max_loc_reset, max_val_reset = detect_image(blum_ss_gray, reset_img_gray, threshold)
                if found_reset:
                    x, y = max_loc_reset
                    center_x = int(x + reset_w / 2) + screenshot_region[0]
                    center_y = int(y + reset_h / 2) + screenshot_region[1]
                    pyautogui.leftClick(center_x, center_y)
                    reset_clicked = True
                    print("Clicked on reset.")
                else:
                    print("Reset not found, retrying.")
                    sleep(0.5)

            # Wait for 1 second
            sleep(1)

            # Click in the middle of the window
            center_x = window.left + window.width // 2
            center_y = window.top + window.height // 2
            pyautogui.leftClick(center_x, center_y)
            print("Clicked in the middle of the window.")

            # Now get back to detecting "target2.png"
            continue  # Start over from the beginning of the loop

        # Now check for "target2.png" as before
        found_target, max_loc_target, max_val_target = detect_image(blum_ss_gray, target_img_gray, threshold)
        if found_target:
            x, y = max_loc_target
            center_x = int(x + target_w / 2) + screenshot_region[0]
            center_y = int(y + target_h / 2) + screenshot_region[1]

            # Generate a random wait time between 1 and 25 seconds
            wait_time = random.uniform(1, 25)
            print(f"Image detected with confidence {max_val_target:.2f}. Waiting for {wait_time:.2f} seconds before clicking.")
            sleep(wait_time)  # Wait for the random duration

            # Perform the click
            pyautogui.leftClick(center_x, center_y + 10)
            print(f"Clicked at ({center_x}, {center_y + 10}) after waiting {wait_time:.2f} seconds.")

            # Draw rectangle for verification
            cv2.rectangle(blum_ss, (x, y), (x + target_w, y + target_h), (0, 255, 0), 2)

            # Save the result image with timestamp
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            result_path = f'./result_image/result_with_rectangles_{timestamp}.png'
            cv2.imwrite(result_path, blum_ss)
        else:
            # Optionally, print that target not found
            pass

    sleep(0.5)  # Adjust sleep time as needed

print('Script stopped.')
Editor is loading...
Leave a Comment