霸王龙游戏:http://www.trex-game.skipser.com/
我是 Python 新手。现在我正在学习编写自动机脚本。
我曾多次尝试按照 YouTube 上的说明更改代码。 (“使用 Python 在任何游戏中作弊 | Python 和 PYAutoGUI 教程 2020 | 为初学者学习 Python”,作者:Davidd That's Me:https://www.youtube.com/watch?v=xYymkeNh2lE),但失败了。
YouTube 上的代码在 Windows 上,但我的是在 MacOS 上。
pyobjc 和 pyobjc-core 都安装了。 (MacOS)
使用“Shift-Command-4”(MacOS) 获取屏幕坐标(x 像素、y 像素)
pyautogui.moveTo(x, y) : 鼠标指针正确移动到“Shift-Command-4”(屏幕坐标)读取的指定位置。
但是……
pyautogui.screenshot(region = (left, top, width, height) : 我发现要插入“left”(以及其他参数)的整数必须乘以 2 才能正确获得所需区域的屏幕截图。
我想知道...
为什么输入到截图函数(pyautogui.screenshot())中的坐标与从屏幕坐标中获取的坐标不同。还有
pyautogui 库可能存在不稳定问题吗? 我尝试多次运行脚本,有时screenshot()函数运行不正常,例如,从函数获取的图像发生变化而屏幕保持不变,或者从getcolors()函数返回的值为零而图片是白色的。
下面是我的代码。
任何帮助将不胜感激。
'''
from PIL import ImageGrab # The ImageGrab module can be used to copy the contents of the screen
from PIL import ImageOps # Analyze it to find out whether it's gray or white
import pyautogui # Control mouse and keyboard
import time
from numpy import *
replaybtn = (640, 530)
dianosaur = (407, 540)
# i for debugging
i = 0
def restartGame():
pyautogui.moveTo(replaybtn, duration=0.5)
pyautogui.click(replaybtn)
print("I just clicked play buttom.")
def image_grab():
global i
# (left_x, top_y, width, high)
# box = (2*dianosaur[0]+10, 2*dinosaur[1], 2*dianosaur[0]+50, 2*dianosaur[1]+10)
# image = ImageGrab.grab(box)
# region = (left_x, top_y, width, high)
image = pyautogui.screenshot(region=(2*dianosaur[0]+10, 2*dianosaur[1],50, 10))
# For debugging
# image.save(str(i) + '.png')
grayImage = ImageOps.grayscale(image)
a = array(grayImage.getcolors())
# For debugging
# White screen a.sum = 1247
print(a)
print('a.sum = ', a.sum())
if (a.sum() != 1247):
image.save(str(i) + '.png')
i+=1
return a.sum()
def pressSpace():
time.sleep(0.1)
pyautogui.keyDown('space')
print("Space pressed.")
time.sleep(3)
restartGame()
try:
while True:
image_grab()
if (image_grab() != 1247):
pressSpace()
time.sleep(0.1)
except KeyboardInterrupt:
print("\nDone...")
'''