import xml.etree.ElementTree as ET
import pyautogui
import numpy as np
import time
import math
import random

class SmoothAimBot:
    def __init__(self, xml_file_path):
        """
        初始化平滑自瞄，从 XML 文件加载配置
        :param xml_file_path: XML 配置文件路径
        """
        self.load_config_from_xml(xml_file_path)
        self.center_x = self.screen_width // 2
        self.center_y = self.screen_height // 2

    def load_config_from_xml(self, xml_file_path):
        """从 XML 文件加载配置"""
        try:
            tree = ET.parse(xml_file_path)
            root = tree.getroot()

            # 解析屏幕设置
            screen = root.find('screen')
            self.screen_width = int(screen.find('width').text)
            self.screen_height = int(screen.find('height').text)

            # 解析自瞄设置
            aim_settings = root.find('aim_settings')
            self.aim_speed = float(aim_settings.find('aim_speed').text)
            self.fov = float(aim_settings.find('fov').text)
            self.steps = int(aim_settings.find('steps').text)

            print("成功加载 XML 配置:")
            print(f"屏幕分辨率: {self.screen_width}x{self.screen_height}")
            print(f"自瞄速度: {self.aim_speed}")
            print(f"视野范围 (FOV): {self.fov} 像素")
            print(f"平滑步数: {self.steps}")

        except FileNotFoundError:
            print(f"错误: 找不到 XML 文件 {xml_file_path}")
        except ET.ParseError:
            print("错误: XML 文件格式不正确")
        except Exception as e:
            print(f"解析 XML 文件时出错: {e}")

    def get_distance(self, x1, y1, x2, y2):
        """计算两点之间的距离"""
        return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

    def smooth_move(self, target_x, target_y):
        """
        平滑移动鼠标到目标位置
        :param target_x: 目标 x 坐标
        :param target_y: 目标 y 坐标
        """
        current_x, current_y = pyautogui.position()
        print(f"当前鼠标位置: ({current_x}, {current_y})")
        print(f"目标位置: ({target_x}, {target_y})")

        # 计算每一步的增量
        delta_x = (target_x - current_x) / self.steps
        delta_y = (target_y - current_y) / self.steps

        for step in range(self.steps):
            new_x = current_x + delta_x * (step + 1)
            new_y = current_y + delta_y * (step + 1)
            pyautogui.moveTo(new_x, new_y, duration=self.aim_speed / self.steps)
            time.sleep(self.aim_speed / self.steps)

    def simulate_aim(self, target_x, target_y):
        """
        模拟自瞄逻辑
        :param target_x: 目标 x 坐标
        :param target_y: 目标 y 坐标
        """
        distance = self.get_distance(self.center_x, self.center_y, target_x, target_y)
        if distance <= self.fov:
            print(f"目标在视野范围内，距离: {distance:.2f} 像素，开始平滑自瞄...")
            self.smooth_move(target_x, target_y)
        else:
            print(f"目标超出视野范围，距离: {distance:.2f} 像素，忽略...")

    def run_test(self):
        """运行测试，模拟自瞄"""
        print("平滑自瞄测试开始，按 Ctrl+C 退出...")
        try:
            while True:
                # 模拟随机生成目标位置（在实际游戏中需要通过图像识别获取目标位置）
                target_x = random.randint(0, self.screen_width)
                target_y = random.randint(0, self.screen_height)
                self.simulate_aim(target_x, target_y)
                time.sleep(1)  # 每秒模拟一次
        except KeyboardInterrupt:
            print("测试已结束。")

if __name__ == "__main__":
    # 假设 XML 文件路径为 "aimbot_config.xml"
    xml_file_path = "aimbot_config.xml"
    aim_bot = SmoothAimBot(xml_file_path)

    # 运行测试
    aim_bot.run_test()