FPS_AI编程

声明

本文仅仅用于学习交流,请勿进行真人游戏或者商用。 目前也在根据代码进行AI打FPS的反击程序的测试,有兴趣的可以一起讨论。我们以APEX为列子进行说明。

技术层面需要掌握的东西

win32gui.FindWindow

win32gui.Findwindow(param1,param2):
param1需要传入窗口的类名,param2需要传入窗口的标题
一般情况下,参数一填写none即可,参数二是游戏名字

PyQt截图

这个依赖组件很多大家可以依次输入以下命令安装,也可以自己写个记事本批量安装

pip install pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install PyQt5 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install pypiwin32 -i https://pypi.tuna.tsinghua.edu.cn/simple/

使用pyautogui方法实现截屏

import pyautogui
import cv2
import numpy as np

img = pyautogui.screenshot(region=[300,50, 200, 100])  
# 分别代表:左上角坐标,宽高
#imshow,默认是BGR,pyautogui默认是RGB,因此要手动转换
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
cv2.imshow("截屏",img)
cv2.waitKey(0)

不使用的理由:不能指定获取程序的窗口,因此窗口也不能遮挡

使用win32gui方法实现截屏

from PyQt5.QtWidgets import QApplication
import win32gui
import sys
#这个是截取全屏的
hwnd = win32gui.FindWindow(None, 'C:/Windows/system32/cmd.exe')
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
img = screen.grabWindow(hwnd).toImage()
img.save("screenshot.bmp")

win32api.mouse_event

win32api.mouse_event(param1,param2,param3)
第一个参数,设定鼠标的行为:相对移动或者绝对移动
第二个参数,x轴相对移动的距离
第三个参数,y轴相对移动的距离

完整代码

import math
import sys
import torch
import win32api
import win32con
import win32gui
from PyQt5.QtWidgets import QApplication
from pynput.mouse import Controller


class Point:
    """
    定义点,便于后面计算距离
    """

    def __init__(self, x1, y1, x2, y2):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2


class Line(Point):
    """
    定义线,便于后面计算距离
    """

    def __init__(self, x1, y1, x2, y2):
        super().__init__(x1, y1, x2, y2)

    def get_len(self):
        """
        获取笛卡尔距离
        :return: 笛卡尔距离
        """
        length = math.sqrt(math.pow((self.x1 - self.x2), 2) +
                           math.pow((self.y1 - self.y2), 2))
        return length


def main():
    # GPU处理
    device = torch.device("cuda")
    model = torch.hub.load('E:\Project\Python_Project\yolov5-master', 'custom',
                           "E:\Project\Python_Project\yolov5--weights\yolov5x.pt",
                           source='local', force_reload=False)  # 加载本地模型

    def screen_record():
        """
        截图
        """
        hwnd = win32gui.FindWindow(None, "Apex Legends")
        app = QApplication(sys.argv)
        screen = QApplication.primaryScreen()
        img = screen.grabWindow(hwnd).toImage()
        img.save("ApexLegendsbg.bmp")

    while True:
        # 截取屏幕
        screen_record()
        # 使用模型
        model = model.to(device)
        img = 'ApexLegendsbg.bmp'
        # 开始推理
        results = model(img)
        # 过滤模型
        xmins = results.pandas().xyxy[0]['xmin']
        ymins = results.pandas().xyxy[0]['ymin']
        xmaxs = results.pandas().xyxy[0]['xmax']
        ymaxs = results.pandas().xyxy[0]['ymax']
        class_list = results.pandas().xyxy[0]['class']
        confidences = results.pandas().xyxy[0]['confidence']
        new_list = []
        for xmin, ymin, xmax, ymax, classitem, conf in zip(xmins, ymins, xmaxs, ymaxs, class_list, confidences):
            if classitem == 0 and conf > 0.5:
                new_list.append([int(xmin), int(ymin), int(xmax), int(ymax), conf])
        # 循环遍历每个敌人的坐标信息传入距离计算方法获取每个敌人距离鼠标的距离
        if len(new_list) > 0:
            # 存放距离数据
            cdList = []
            xyList = []
            for listItem in new_list:
                # 当前遍历的人物中心坐标
                x_index = int(listItem[2] - (listItem[2] - listItem[0]) / 2)
                y_index = int(listItem[3] - (listItem[3] - listItem[1]) / 2)
                mouseModal = Controller()
                x, y = mouseModal.position
                L1 = Line(x, y, x_index, y_index)
                # 获取到距离并且存放在cdList集合中
                cdList.append(int(L1.get_len()))
                xyList.append([x_index, y_index, listItem[0], listItem[1], listItem[2], listItem[3]])
            # 这里就得到了距离最近的敌人位置了
            minCD = min(cdList)
            # 分辨率
            game_width = 1920
            game_height = 1080
            # 如果敌人距离鼠标坐标小于150则自动进行瞄准,这里可以改大改小,小的话跟枪会显得自然些
            if minCD < 100:
                for cdItem, xyItem in zip(cdList, xyList):
                    if cdItem == minCD:
                        # 锁头算法:使用win32api获取左键按下状态,如果按下则开始自动跟枪
                        if win32api.GetAsyncKeyState(0x01):
                            win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, int(xyItem[0] - game_width // 4),
                                                 int(xyItem[1] - (game_height - (xyItem[3] - xyItem[5])) // 4), 0, 0)
                        break


if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值