【发布时间】:2021-03-08 19:24:48
【问题描述】:
我想编写一个能够玩游戏的机器人,它被称为“piano Tiles”。基本上有四个垂直车道,每个车道都有黑色瓷砖掉落。玩家需要在到达屏幕末端之前点击它们。玩的时候越来越快。
我的目标是尽可能获得最高分。世界纪录目前为 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 次。
【问题讨论】:
标签: python multiprocessing click pyautogui pypy