python部署压枪宏方式(含核心代码)

内容分享1天前发布
1 0 0

注:谨慎使用,后果自行承担,仅供分享
注:谨慎使用,后果自行承担,仅供分享
注:谨慎使用,后果自行承担,仅供分享
重要的事情说三遍
废话不多说 直接上教学
以PUBG为例,脚本针对鼠标,不对游戏数据进行任何更改

本地电脑设备就可以
1下载安装 PyCharm ,关于如何安装,这里不多说,直接百度搜索就行

目录架构

PUBG_Recoil_Macro/

├── src/ # 源代码目录
│ ├── init.py
│ ├── main.py # 主程序入口
│ ├── config_manager.py # 配置管理
│ ├── weapon_profiles.py # 武器配置文件管理
│ ├── pid_controller.py # PID控制器
│ ├── kalman_filter.py # 卡尔曼滤波器
│ ├── recoil_control.py # 压枪控制系统
│ ├── admin_manager.py # 管理员权限管理
│ ├── log_system.py # 日志系统
│ └── utils.py # 工具函数

├── profiles/ # 武器配置文件目录
│ ├── m416.json
│ ├── scar-l.json
│ ├── beryl.json
│ ├── akm.json
│ ├── ump45.json
│ └── sniper.json

├── data/ # 资源文件目录
│ ├── icon.ico # 程序图标
│ └── readme.txt # 使用说明

├── dist/ # 输出目录(打包后生成)
├── build/ # 构建目录(打包后生成)

├── requirements.txt # Python依赖
├── config.ini # 主配置文件
├── setup.py # 安装脚本
├── build_exe.py # 打包脚本
└── README.md # 项目说明文档

1 main.py 主程序


import os
import sys
import ctypes
import traceback
from src.recoil_control import RecoilControlSystem

def is_admin():
    """检查管理员权限"""
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def request_admin():
    """请求管理员权限"""
    try:
        script_path = os.path.abspath(sys.argv[0])
        params = ctypes.c_wchar_p(f'"{script_path}"')
        result = ctypes.windll.shell32.ShellExecuteW(
            None, "runas", sys.executable, params, None, 1
        )
        return result > 32
    except:
        return False

def main():
    """主函数"""
    try:
        # 检查管理员权限
        if not is_admin():
            print("请求管理员权限...")
            if request_admin():
                sys.exit(0)
            else:
                ctypes.windll.user32.MessageBoxW(
                    0, "程序需要管理员权限运行!", "权限错误", 0x10
                )
                sys.exit(1)
                
        # 创建互斥体确保单实例运行
        mutex_name = "PUBGRecoilMacroMutex"
        mutex = ctypes.windll.kernel32.CreateMutexW(None, False, mutex_name)
        last_error = ctypes.windll.kernel32.GetLastError()
        
        if last_error == 183:
            ctypes.windll.user32.MessageBoxW(0, "程序已在运行中!", "提示", 0x40)
            sys.exit(0)
            
        # 启动压枪系统
        macro = RecoilControlSystem()
        macro.start()
        
    except KeyboardInterrupt:
        print("
程序被用户中断")
    except Exception as e:
        print(f"程序运行出错: {str(e)}")
        traceback.print_exc()
        input("按回车键退出...")

if __name__ == "__main__":
    main()

2 创建资源路径处理函数 utils.py


import os
import sys

def resource_path(relative_path):
    """获取资源的绝对路径"""
    try:
        # PyInstaller创建临时文件夹,将路径存储在_MEIPASS中
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    
    return os.path.join(base_path, relative_path)

def get_app_data_path():
    """获取应用程序数据路径"""
    if getattr(sys, 'frozen', False):
        # 如果是打包后的程序
        return os.path.dirname(sys.executable)
    else:
        # 如果是开发环境
        return os.path.dirname(os.path.abspath(__file__))

3修改配置文件处理 config_manager.py


import configparser
import os
import logging
from .utils import get_app_data_path

class ConfigManager:
    def __init__(self):
        self.app_data_path = get_app_data_path()
        self.config_path = os.path.join(self.app_data_path, 'config.ini')
        self.profiles_path = os.path.join(self.app_data_path, 'profiles')
        
    def load(self):
        config = configparser.ConfigParser()
        default_config = {
            'Settings': {
                'Weapon': 'M416',
                'Sensitivity': '1.0',
                'LogLevel': 'INFO'
            }
        }

        # 确保配置目录存在
        os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
        os.makedirs(self.profiles_path, exist_ok=True)
        
        if not os.path.exists(self.config_path):
            config.read_dict(default_config)
            with open(self.config_path, 'w', encoding='utf-8') as f:
                config.write(f)
                
        config.read(self.config_path, encoding='utf-8')
        
        return {
            'weapon': config.get('Settings', 'Weapon', fallback='M416'),
            'sensitivity': config.getfloat('Settings', 'Sensitivity', fallback=1.0),
            'log_level': config.get('Settings', 'LogLevel', fallback='INFO')
        }
        
    def save(self, weapon, sensitivity, log_level='INFO'):
        config = configparser.ConfigParser()
        config['Settings'] = {
            'Weapon': weapon,
            'Sensitivity': str(sensitivity),
            'LogLevel': log_level
        }
        
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                config.write(f)
            return True
        except Exception as e:
            logging.error(f"保存配置失败: {str(e)}")
            return False

4创建打包脚本 build_exe.py


import os
import sys
import shutil
from cx_Freeze import setup, Executable

# 应用程序基本信息
app_name = "PUBG压枪宏"
version = "1.0.0"
description = "PUBG游戏压枪辅助工具"
author = "您的名称"

# 包含的文件
include_files = [
    ('profiles', 'profiles'),
    ('config.ini', 'config.ini'),
    ('data/readme.txt', 'readme.txt')
]

# 排除的模块
excludes = [
    "tkinter", "test", "unittest", "pydoc", "pyreadline", 
    "sqlite3", "email", "xml", "http", "html", "ssl"
]

# 构建选项
build_options = {
    "packages": ["os", "sys", "time", "random", "ctypes", "win32gui", "win32api", "win32con", 
                 "logging", "math", "datetime", "configparser", "threading", "collections", 
                 "pynput.keyboard", "pynput.mouse", "json"],
    "excludes": excludes,
    "include_files": include_files,
    "include_msvcr": True,
    "optimize": 2
}

# 设置执行文件
executables = [
    Executable(
        "src/main.py",
        base="console",
        target_name=f"{app_name}.exe",
        icon="data/icon.ico",
        copyright=f"Copyright (C) 2023 {author}",
        trademarks=description,
        shortcut_name=app_name,
        shortcut_dir="ProgramMenuFolder"
    )
]

# 设置
setup(
    name=app_name,
    version=version,
    description=description,
    options={"build_exe": build_options},
    executables=executables,
    author=author
)

print("构建完成!")
print("可执行文件位于 build 目录中")

5创建安装脚本 setup.py


from setuptools import setup, find_packages

setup(
    name="pubg_recoil_macro",
    version="1.0.0",
    description="PUBG压枪宏 - 基于PID控制和卡尔曼滤波",
    author="您的名称",
    packages=find_packages(),
    install_requires=[
        "pynput==1.7.6",
        "pywin32==305",
        "cx_Freeze==6.15.0"
    ],
    include_package_data=True,
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: Microsoft :: Windows",
    ],
)

6 创建启动批处理文件 start.bat


@echo off
chcp 65001 >nul
echo ========================================
echo        PUBG压枪宏启动程序
echo ========================================
echo.
echo 正在检查管理员权限...

net session >nul 2>&1
if %errorLevel% neq 0 (
    echo 请求管理员权限...
    powershell -Command "Start-Process cmd -ArgumentList '/c %~dp0start.bat' -Verb RunAs"
    exit /b
)

echo 管理员权限确认!
echo.
echo 正在启动压枪宏...

cd /d %~dp0
if exist "distPUBG压枪宏.exe" (
    distPUBG压枪宏.exe
) else if exist "buildexe.win-amd64-3.*PUBG压枪宏.exe" (
    buildexe.win-amd64-3.*PUBG压枪宏.exe
) else (
    echo 错误: 未找到可执行文件!
    echo 请先运行 build_exe.py 构建程序
)

pause

7创建配置文件 config.ini


[Settings]
Weapon = M416
Sensitivity = 1.0
LogLevel = INFO

8创建武器配置文件 profiles/m416.json


{
    "display_name": "M416",
    "vertical_pattern": [0.25, 0.27, 0.28, 0.27, 0.26, 0.25, 0.24, 0.25, 0.26, 0.27],
    "horizontal_variance": 0.02,
    "fire_interval": 0.085,
    "pid_params": {"kp": 0.35, "ki": 0.01, "kd": 0.05},
    "sensitivity_scaling": 0.9,
    "recoil_decay": 0.96,
    "max_deviation": 8,
    "stability_factor": 0.99
}

创建其他武器的类似配置文件。

9 创建使用说明文档 data/readme.txt


PUBG压枪宏使用说明

1. 程序功能
   - 自动压枪:根据武器后坐力模式自动控制鼠标移动
   - 多武器支持:M416, SCAR-L, Beryl M762, AKM, UMP45, 狙击模式
   - 灵敏度调整:实时调整压枪强度
   - 状态显示:实时显示程序状态和参数

2. 热键说明
   - F1: 暂停/恢复宏
   - F2: M416    F3: SCAR-L
   - F4: Beryl   F5: AKM
   - F6: UMP45   F7: Sniper
   - PageUp/PageDown: 调整灵敏度
   - Alt+R: 重置后坐力积累
   - Alt+X: 退出程序

3. 注意事项
   - 必须以管理员权限运行
   - 在游戏训练场中测试效果
   - 根据个人鼠标灵敏度调整配置
   - 仅用于教育目的,请遵守游戏规则

4. 自定义配置
   - 编辑profiles目录下的JSON文件可以自定义武器参数
   - 编辑config.ini可以修改全局设置

如有问题,请联系开发者。

打包为可执行文件
1 安装依赖
pip install -r requirements.txt
2. 使用cx_Freeze打包 python build_exe.py build


使用步骤

解压到任意目录

运行PUBG压枪宏.exe(可能需要右键选择"以管理员身份运行")

程序会自动创建必要的配置文件和目录

按照屏幕提示和使用说明操作
© 版权声明

相关文章

暂无评论

none
暂无评论...