从另一个应用程序捕获和操作数据

2024-05-20 17:09:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用C写的游戏(Windows版)。我正在努力寻找一种方法来编写一个Python应用程序来读取数据并控制这个游戏。
例如:当我的角色生命值达到50%或更少时,捕获数据的Python程序会不断发送一个命令,使用一个项目还原生命值。
Python脚本我可以做得很好,但是我不知道用什么来捕获这个游戏的数据。你知道吗

附言:我不想要鼠标/键盘/图形自动化。我知道有一个程序正是我所描述的。用Python编写的,控制这个用C语言编写的游戏。游戏窗口甚至不需要在Python程序的焦点控制它。你知道吗

有没有Python模块可以访问另一个应用程序、读取和发送命令?你知道吗

编辑:

我现在可以读取内存(通过引擎获取)。 使用while循环,我每秒打印正确数量的生命值(十六进制):

from ctypes import *
from ctypes.wintypes import *
import time

OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle

PROCESS_ALL_ACCESS = 0x1F0FFF

pid = 3488   # I assume you have this from somewhere.
address = 0x0019F438  # Likewise; for illustration I'll get the .exe header.

buffer = c_char_p("The data goes here")
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
while True:
    if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
        print "Success:", buffer
    else:
        print "Failed."
    time.sleep(1)

CloseHandle(processHandle)

但很快它就开始印刷奇怪的价值观:

Success: c_char_p('\x8e') -> 142 |------------------
Success: c_char_p('\x8e') -> 142 |
Success: c_char_p('\x8e') -> 142 |
Success: c_char_p('\x90') -> 144 |
Success: c_char_p('\x90') -> 144 |
Success: c_char_p('\x90') -> 144 |
Success: c_char_p('\x90') -> 144 | This entire block is correct
Success: c_char_p('\x92') -> 146 | The hitpoints are increasing
Success: c_char_p('\x92') -> 146 |
Success: c_char_p('\x92') -> 146 |
Success: c_char_p('\x92') -> 146 |
Success: c_char_p('\x94') -> 148 |
Success: c_char_p('\x94') -> 148 |
Success: c_char_p('\x94') -> 148 |___________________
Success: c_char_p('\x0e') -> 14      |
Success: c_char_p('\x0e') -> 14      | Here it becomes 
Success: c_char_p('\x0e') -> 14      | print weird stuff
Success: c_char_p('\x06\xfa\x82p0')  |
Success: c_char_p('\x06\xfa\x82p0')  |___________________

Tags: fromimport程序游戏buffersuccesscharopenprocess