(python)cf fire line aims at the red name and automatically fires

I. Introduction

This should be the fourth article in the cf series. I have already written about AI aiming and Logitech mouse macros. The functions of this article are simpler than the first two. Because there is not much code, I will not write classes and functions. I will go straight to Huanglong. , I also wrote some auxiliary scripts that can be used to obtain the current coordinates and color of the mouse. It can be used when changing the resolution.

Required preparations : Logitech driver .dll file and corresponding Logitech driver version, I’ve put the link below

Link: https://pan.baidu.com/s/1pd2RjNW6QoOSDRs_3gm1Tw?pwd=6666 
Extraction code: 6666

Note : The in-game resolution here must be 1280*720. My position coordinate parameters are adjusted based on this resolution.

2. Code

2.1 Driver code

This part of the code mainly calls the .dll file and uses the methods encapsulated in it, such as moving the mouse, clicking the mouse, keyboard, etc. The main function is to perform shooting operations, that is, to automatically click the left button of the mouse.

import ctypes
import os


try:
    # 获取当前绝对路径
    root = os.path.abspath(os.path.dirname(__file__))
    driver = ctypes.CDLL(f'{root}/logitech.driver.dll')
    ok = driver.device_open() == 1  # 该驱动每个进程可打开一个实例
    if not ok:
        print('错误, GHUB驱动没有找到')
except FileNotFoundError:
    print(f'错误, DLL 文件没有找到')



class Logitech:

    class mouse:

        """
        code: 1:左键, 2:中键, 3:右键
        """

        @staticmethod
        def press(code):
            if not ok:
                return
            driver.mouse_down(code)

        @staticmethod
        def release(code):
            if not ok:
                return
            driver.mouse_up(code)

        @staticmethod
        def click(code):
            if not ok:
                return
            driver.mouse_down(code)
            driver.mouse_up(code)

        @staticmethod
        def scroll(a):
            """
            鼠标滚轮
            """
            if not ok:
                return
            driver.scroll(a)

        @staticmethod
        def move(x, y):
            """
            相对移动, 绝对移动需配合 pywin32 的 win32gui 中的 GetCursorPos 计算位置
            pip install pywin32 -i https://pypi.tuna.tsinghua.edu.cn/simple
            x: 水平移动的方向和距离, 正数向右, 负数向左
            y: 垂直移动的方向和距离
            """
            if not ok:
                return
            if x == 0 and y == 0:
                return
            driver.moveR(x, y, True)

    class keyboard:

        """
        键盘按键函数中,传入的参数采用的是键盘按键对应的键码
        code: 'a'-'z':A键-Z键, '0'-'9':0-9
        """

        @staticmethod
        def press(code):

            if not ok:
                return
            driver.key_down(code)

        @staticmethod
        def release(code):
            if not ok:
                return
            driver.key_up(code)

        @staticmethod
        def click(code):
            if not ok:
                return
            driver.key_down(code)
            driver.key_up(code)



class RunLogitechTwo:
    def __init__(self):
        self.log_mouse = Logitech.mouse
        pass

    def quick_move(self):
        # time.sleep(random.randint(1, 3))
        self.log_mouse.click(1)
        # print('hahaha')


2.2 Red name identification code

Code idea: Use the mss() function of the mss library to take a screenshot of the current screen during the process, and set the dictionary monitor parameter, which contains the coordinates of the upper left corner, width and height, to control the scope of the screenshot. Here, I will show the red name of the enemy. 16 pixels are intercepted in the center of the 16 pixels. There must be a red pixel grid among these 16 pixels. Once one of them meets the rgb range requirements, it will jump out of the loop and not execute the judgment of the remaining pixels. This saves resources and prevents continuous shooting.

Explanation of the for loop part: The two-layer for loop is to traverse the RGB values ​​​​of the 16 intercepted pixels for judgment. The bgr attribute of the second for loop (each decomposed pixel) contains 4 values, namely R, B, G, transparency, we only take the first three. Don’t worry about the transparency. np.array() will divide the 16 pixel values ​​into a two-dimensional array (4*4) similar to the shape of a matrix, so Two levels of for loops are enough

Shooting delay : This shooting delay must be added, otherwise it will definitely be too fast. Check it and you can modify the speed and try it yourself. Mine is the delay of the troll. The cannon can be adjusted longer, and the firing line is also One problem is that the red name may start to appear when you aim near that person, so you also need to set the shooting delay to balance the automatic shooting timing.

Complaint: When you aim at an enemy, his name is a gradient, from dark red-red-bright red-orange. This RGB range makes it easy for me to find.

import logitech_test
from mss import mss
import numpy as np
import time
import random




if __name__ == "__main__":
    # 设置检测区域,这里截取整个屏幕
    monitor = {"top": 405, "left": 635, "width": 4, "height": 4}
    # monitor = {"top": 490, "left": 910, "width": 200, "height": 200}  # 反人类的设计,正常左上,他上左
    obj = logitech_test.RunLogitechTwo()
    # 设置目标颜色(示例:红色)
    target_color = np.array([163, 57, 49])  # RGB颜色值
    # 创建截屏对象
    sct = mss()
    while True:
        flag=False
        # 获取屏幕截图
        screen_shot = sct.grab(monitor)
        # 展示
        scr_img = np.array(screen_shot)

        for each_pic in scr_img:
            for bgr in each_pic:
                b, g, r = bgr[:3]
                # rgb参数145,245,47,80,20,57
                if r >= 140 and r <= 245 and g >= 45 and g <= 80 and b >= 20 and b <= 60:
                    time.sleep(random.randint(2, 5) * 0.01)
                    obj.quick_move()
                    flag = True
                    break
            if flag:
                break

3. Auxiliary tools

The following script is used to obtain the coordinates x, y and rgb values ​​of the current mouse position at all times, and is used to calculate parameters when changing the resolution.

import pyautogui
from PIL import Image


def test_b():
    # obj = RunLogitechTwo()
    # 默认屏幕为1280 * 720,屏幕中心位置如下
    # x = 640   # 1.18
    # y = 360   # 32.66666
    # 屏幕检测区域
    # region_to_check = (590, 310, 690, 430)
    # x = 636
    # y = 410
    while True:
        x, y = pyautogui.position()  # 获取鼠标当前位置

        # region = (600, 400, 80, 20)
        im = pyautogui.screenshot()  # 返回屏幕的截图,是一个Pillow的image对象

        r,g,b = im.getpixel((x,y))
        print("x:", x, "y:", y, "r:", r,"-g:", g,"-b:", b)


        # img = Image.new('RGB', (300, 300), im.getpixel((x, y)))  # 用获取的颜色创建一张图片
        # img.show()  # 展示当前图片


if __name__ == '__main__':
    test_b()

4. Finished product display

Because someone suggested that it would be better to integrate this into an app. The code is not too much, so I took the time to integrate it. The picture is as follows

Here I have given several parameters that can be modified

Game resolution: Because some people may not be able to find the location after changing the resolution, I added this parameter and it will find the location adaptively. You can also click Calculate Area to get a red name area that is more suitable for the current resolution. 

Red name area: This is the scanning range. If your computer configuration is good, you can set it larger, but generally the adaptive area calculation is enough.

Fire reaction rate: This is used to control the interval between when you reach the red name and before shooting. If it is too fast, you may go into a small dark room for an hour to cool down. If you are playing JU, I recommend 7-10, because the mechanism of the line of fire is seconds. A red name will appear near the person's body, so when you are playing JU, someone may slowly come out, so the first thing you aim at is the air, so add some delay appropriately, and other rifles and sprayers will Just leave it as default, you don’t need to think about this

Finally, if you are interested or have questions about this, you can send me an email message and I will reply when I see it.

 

5. Summary

Let me say one more important thing. If you want to use my code, the in-game resolution must be adjusted to 1280*720, because I take the pixel position based on this resolution. If you want to use another resolution, re-create it yourself. Just calculate it, it’s not difficult. Re-find the coordinate position of the red name in the new resolution. If you can’t find the coordinate position of the red name in the new resolution, I suggest you adjust the computer resolution to be the same as the game. resolution, then take a screenshot in the game, set the screenshot photo to full screen, and then turn on the auxiliary tools to get the coordinates and rgb, so that you can know it accurately (this is what I did)

Finally, if there is anything you still don’t understand or have difficulty with or can improve, you can contact me by email and we can make progress together, [email protected]

おすすめ

転載: blog.csdn.net/calmdownn/article/details/132003851
おすすめ