在 Python 中检测多个像素并并行单击它们的更快方法?

如何解决在 Python 中检测多个像素并并行单击它们的更快方法?

我想编写一个能够玩游戏的机器人,它被称为“钢琴瓷砖”。基本上有四个垂直车道,每个车道都有黑色的瓷砖掉落。玩家需要在他们到达屏幕末尾之前点击它们。玩的时候越来越快。

我的目标是尽可能获得最高分。目前的世界纪录是 17 次点击/秒(瓷砖/秒)。我无法获得高于 15 次/秒的点击次数,但我无法确定我在哪里减慢了我的脚本速度。

我的第一种方法是使用 pyautogui.pixel(x,y) 检查单个像素/通道,如果其 rgb 值 == 瓷砖的颜色 - 单击该位置。使用该变体评分约 10 次点击/秒。

在那之后,我计算了一个偏移量以保持加速度,基本上我在该点击的 y 位置添加了一个递增的数字,这让我大约每秒点击 12 次。

我记录下来并逐帧观看它失败。发生的事情是,最终游戏变得如此之快,以至于示例脚本无法检测到“lane 1”中的像素,而点击发生在“lane 4”中

我想出的解决方案是多处理和 pypy。

    import pyautogui
    import multiprocessing
    import time


    time.sleep(2)
    print("READYprint")



    def Lane1():
        a = 0
        b = 0
        pyautogui.PAUSE = 0
        while True:

            if pyautogui.pixel(800,520) [0] == 0:
                pyautogui.click(x=800,y=520 + b)
                
                a = a + 1
                b = a // 15
            
            
                

    def Lane2():
        a = 0
        b = 0
        pyautogui.PAUSE = 0
        while True:

            if pyautogui.pixel(902,520) [0] == 0:
                pyautogui.click(x=902,y=520 + b)
                
                a = a + 1
                b = a // 15
            
                

    def Lane3():
        a = 0
        b = 0
        pyautogui.PAUSE = 0
        while True:

            if pyautogui.pixel(1033,520) [0] == 0:
                pyautogui.click(x=1033,y=520 + b)
                
                a = a + 1
                b = a // 15
            
                

    def Lane4():
        a = 0
        b = 0
        pyautogui.PAUSE = 0
        while True:

            if pyautogui.pixel(1134,520) [0] == 0:
                pyautogui.click(x=1134,y=520 + b)
                
                a = a + 1
                b = a // 15
            
                

    p1 = multiprocessing.Process(target=Lane1)
    p2 = multiprocessing.Process(target=Lane2)
    p3 = multiprocessing.Process(target=Lane3)
    p4 = multiprocessing.Process(target=Lane4)


    if __name__ == "__main__":
        p1.start()
        p2.start()
        p3.start()
        p4.start()


我还进行了测试,以对脚本的性能进行基准测试。

import time
import pyautogui

start_time = time.time()


def test():
    a = 0
    b = 0
    pyautogui.PAUSE = 0
    while a < 100:
     
        if pyautogui.pixel(970,208) [0] == 255:
        
            pyautogui.click(x=970,y=208 + b)
            a = a + 1
            b = a // 15


test()

    
print("--- %s seconds ---" % (time.time() - start_time))

输出:--- 1.7149109840393066 秒 ---,这是 100 次“获取 rgb 值 + 单击,如果它是白色的。”

我不知道为什么机器人那么“慢”。当它失败时,它离那个 0,017... 秒/checked_click 很远。这可能是多处理的原因吗?虽然它确实变快了一点,但它应该快得多。我也确实在没有 pypy 的情况下运行了它。如果没有 pypy JIT,它大约为每秒 13 次点击。

解决方法

不是对您问题的直接回答,但一次获取所有四个车道的屏幕截图可能会更快。 pyautogui.pixel() combines 截图和 getpixel 函数。因此,您的代码会为每个通道单独获取屏幕截图。更快的方法可能是这样做:

xlocations= [800,902,1033,1134]
yloc=520
while True:
    im = pyautogui.screenshot()
    for xloc in xlocations: 
       if im.getpixel((xloc,yloc)) [0] == 0:
          pyautogui.click(x=xloc,y=yloc+ b)
          a = a + 1
          b = a // 15
    
,

我想出的“最终”解决方案如下:

import time
import win32api,win32con,win32ui
import multiprocessing

time.sleep(1)
print("RDY")

def Lane1():

    
    window_name = "App Player" 
    wd = win32ui.FindWindow(None,window_name)
    

    while True:
        dc = wd.GetWindowDC()
        try:

             
            j = dc.GetPixel (35,230)  
            
            if j == 0:
                
                win32api.SetCursorPos((35,230))
                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0)
                time.sleep(0.01)
                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0)
            dc.DeleteDC()

        except win32ui.error:
            print("we got an error 1")
            continue

def Lane2():

    
    window_name = "App Player" 
    wd = win32ui.FindWindow(None,window_name)
     

    while True:
        dc = wd.GetWindowDC()

        try:

            
            j = dc.GetPixel (60,240)  
            
            if j == 0:
                
                win32api.SetCursorPos((60,240))
                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0)
            dc.DeleteDC()

        except win32ui.error:
            print("we got an error 2")
            continue

def Lane3():

    
    window_name = "App Player" 
    wd = win32ui.FindWindow(None,window_name)
    
    while True:
        dc = wd.GetWindowDC()

        try:

            
            j = dc.GetPixel (120,250)  
            
            if j == 0:
                
                win32api.SetCursorPos((120,250))
                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0)
            dc.DeleteDC()

        except win32ui.error:
            print("we got an error 3")
            continue

def Lane4():

    
    window_name = "App Player" 
    wd = win32ui.FindWindow(None,window_name)
    

    while True:
        dc = wd.GetWindowDC()
         

        try:

            
            j = dc.GetPixel (180,260)  
            
            if j == 0:
                
                win32api.SetCursorPos((180,260))
                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0)
            dc.DeleteDC()

        except win32ui.error:
            print("we got an error 4")
            continue
        

        




p1 = multiprocessing.Process(target=Lane1)
p2 = multiprocessing.Process(target=Lane2)
p3 = multiprocessing.Process(target=Lane3)
p4 = multiprocessing.Process(target=Lane4)


if __name__ == "__main__":
    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

我检查了不同 y 位置上的像素,以确保不同进程之间没有这种竞争条件,这确实导致了误操作。此外,保持游戏窗口尽可能小也有很大帮助,因为模拟器往往会滞后。

使用此版本的机器人,得分约为每秒 22 次点击。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-