如何使用 python 让光标在游戏中移动(例如:第一射手射击游戏)

Sul*_*.aj 2 python automation

I\xe2\x80\x99m 尝试使用 python 构建一个自动化程序,使用 Opencv 来检测给定的颜色和 pyautogui 进行自动化。我尝试使用 pyautogui 在游戏中移动光标,但 \xe2\x80\x99 不起作用。使用另一个库 pynput 有一些优点然后停止。我\xe2\x80\x99d需要你的帮助!

\n\n

这是我的代码:

\n\n
import pyautogui as pg\nimport time\nfrom PIL import ImageGrab\nimport numpy as np\nimport cv2\nimport keyboard\nfrom pynput.mouse import Controller, Button\n\ndef clickAt(Mouse, x, y):\n    Mouse.position = (x, y)\n    Mouse.press(Button.right)\n    Mouse.click(Button.left)\n    time.sleep(2)\n    Mouse.release(Button.right)\n\n\n#screen \nx1, y1 = (200, 290)\nx2, y2 = (1525, 800)\n\nfor i in range(50):\n\n   img = ImageGrab.grab(bbox=(x1, y1, x2, y2)) #bbox specifies specific region (bbox= x,y,width,height)\n   img_np = np.array(img)\n   frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2HSV)\n\n   #lower and higher of the color\n   lower = np.array([86, 179, 7])\n   upper = np.array([255, 255, 255])\n\n   mask = cv2.inRange(frame, lower, upper)\n\n   croped = cv2.bitwise_and(frame, frame, mask=mask)\n\n   res = cv2.bitwise_and(frame,frame, mask= mask)\n\n   #cv2.imshow("res",res)\n   cv2.imshow("mask", mask)\n   #cv2.imshow("frame", frame)\n\n   van = np.where(mask > 0)\n   #print(van)\n   x_van = van[1]\n   y_van = van[0]\n   time.sleep(5)\n\n   Mouse = Controller()\n   #clickAt(Mouse,100,100)\n\n   x_axis = van[1] + x1\n   y_axis = van[0] + y1\n\n   print(x_axis[5])\n   print(y_axis[5])\n\n   hit_pos = (x_van[0] + x1, y_van[1] + y1)\n\n   pg.moveTo(hit_pos)\n   clickAt(Mouse,100,100)\n   clickAt(Mouse,x_axis[5], y_axis[5])\n\n   #click the mouse\n   pg.click(hit_pos)\n   print(\'BIRD HIT at\', hit_pos)\n\n   time.sleep(1)\n\n  cv2.waitKey(25) \n  time.sleep(3)\n  #cv2.destroyAllWindows()\n
Run Code Online (Sandbox Code Playgroud)\n

Lem*_*Tea 8

我正在做与你完全相同的项目,我发现下面的方法有效,但是,移动是坐标点,而不是 x,y 参数相对于你当前的鼠标位置移动

import win32api, win32con

win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, x, y, 0, 0)
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚想出来了。您需要使用“win32con.MOUSEEVENTF_ABSOLUTE”来使用坐标点,但是Windows基于65535 x 65535像素,因此您必须做一些数学运算并将其除以显示器屏幕宽度/高度。'win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, x,y,0,0)' (3认同)