Untitled

mail@pastecode.io avatar
unknown
python
2 months ago
2.5 kB
1
Indexable
Never
import time
import keyboard
import mss
from ultralytics import YOLO
import numpy as np
import pyautogui
import cv2
from ConfigReader import ConfigReader


def calculate_region(monitor_size, fov_x, fov_y):
    x_center = monitor_size.width // 2
    y_center = monitor_size.height // 2
    left = x_center - fov_x // 2
    top = y_center - fov_y // 2
    width = fov_x
    height = fov_y
    return {'left': left, 'top': top, 'width': width, 'height': height}


def get_screen(region):
    with mss.mss() as sct:
        screenshot = sct.grab(region)
        return np.array(screenshot)


def main():
    config_file_path = 'config.ini'
    config_reader = ConfigReader(config_file_path)
    aim_config = config_reader.get_aim_config()
    ai_config = config_reader.get_ai_config()
    FovX = aim_config['fovx']
    FovY = aim_config['fovy']
    model_path = ai_config['model_path']

    model = YOLO(model_path)
    monitor_size = pyautogui.size()
    region = calculate_region(monitor_size, FovX, FovY)

    while True:
        t = time.time()
        screen = get_screen(region)
        screen = cv2.cvtColor(screen, cv2.COLOR_RGBA2RGB)
        cv2.imshow('screen', screen)

        results = model(screen)
        print('fps: {}'.format(1 / (time.time() - t)))

        detected_objects = xyxy_boxes = []

        for result in results:
            xyxy_boxes.extend(result.boxes.xyxy)

        print(detected_objects)

        if xyxy_boxes:
            if len(xyxy_boxes) > 1:
                print("enemy_head")
                enemy_head = xyxy_boxes[1]
                center_x = (enemy_head[0] + enemy_head[2]) / 2
                center_y = (enemy_head[1] + enemy_head[3]) / 2
                print(center_x)
                print(center_y)
                print("moved to enemy_head: ", enemy_head)
            else:
                print("enemy")
                enemy = xyxy_boxes[0]
                target_height = 0.8 * (enemy[3] - enemy[1])
                center_x = (enemy[0] + enemy[2]) / 2
                center_y = ((enemy[1] + enemy[3]) / 2) - (target_height / 2)
                print("moved to enemy: ", enemy)

            pyautogui.moveTo(center_x, center_y)
            print(center_x, center_y)

        if keyboard.is_pressed("q"):
            break
        cv2.waitKey(1)

    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()
Leave a Comment