我想在指定的矩形區域(限制座標x1,y1,x2,y2,x3,y3,x4,y4)隨機鼠標移動。 運動應該是平滑的,隨機的,不只是直線,隨機上/下/左/右/等在指定的時間。蟒蛇隨機鼠標移動
你可以給我一個手或工作的例子,我可以從中學習嗎? 非常感謝
我想在指定的矩形區域(限制座標x1,y1,x2,y2,x3,y3,x4,y4)隨機鼠標移動。 運動應該是平滑的,隨機的,不只是直線,隨機上/下/左/右/等在指定的時間。蟒蛇隨機鼠標移動
你可以給我一個手或工作的例子,我可以從中學習嗎? 非常感謝
此代碼僅適用於Windows。您可以嘗試random_movement函數中的參數以獲得更好的結果。祝你好運!
import ctypes
import random
import time
import math
def move_mouse(pos):
x_pos, y_pos = pos
screen_size = ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1)
x = 65536L * x_pos/screen_size[0] + 1
y = 65536L * y_pos/screen_size[1] + 1
return ctypes.windll.user32.mouse_event(32769, x, y, 0, 0)
def random_movement(top_left_corner, bottom_right_corner, min_speed=100, max_speed=200):
'''speed is in pixels per second'''
x_bound = top_left_corner[0], bottom_right_corner[0]
y_bound = top_left_corner[1], bottom_right_corner[1]
pos = (random.randrange(*x_bound),
random.randrange(*y_bound))
speed = min_speed + random.random()*(max_speed-min_speed)
direction = 2*math.pi*random.random()
def get_new_val(min_val, max_val, val, delta=0.01):
new_val = val + random.randrange(-1,2)*(max_val-min_val)*delta
if new_val<min_val or new_val>max_val:
return get_new_val(min_val, max_val, val, delta)
return new_val
steps_per_second = 35.0
while True:
move_mouse(pos)
time.sleep(1.0/steps_per_second)
speed = get_new_val(min_speed, max_speed, speed)
direction+=random.randrange(-1,2)*math.pi/5.0*random.random()
new_pos = (int(round(pos[0]+speed*math.cos(direction)/steps_per_second)),
int(round(pos[1]+speed*math.sin(direction)/steps_per_second)))
while new_pos[0] not in xrange(*x_bound) or new_pos[1] not in xrange(*y_bound):
direction = 2*math.pi*random.random()
new_pos = (int(round(pos[0]+speed*math.cos(direction)/steps_per_second)),
int(round(pos[1]+speed*math.sin(direction)/steps_per_second)))
pos=new_pos
實施例:
random_movement((300,300),(600,600))
酷! :) 非常感謝你。我將從這個例子中學習一些東西。 – peter
對於受限於矩形的隨機平滑運動,我會嘗試使用隨機更改係數的Lissajous curves。
感謝它看起來不錯。但是我想隨機做鼠標移動(例如當你在屏幕上移動你的鼠標時,你永遠不會得到相同的動作,所以我不需要「好的」曲線,它應該只是模擬用戶的鼠標)。不幸的是,我不是蟒蛇英雄,所以任何例子都非常感謝。謝謝 – peter
對於執行這些動作,可以使用第三方軟件包PyUserInput,它允許您控制鼠標或鍵盤,並且它是跨平臺的。使用點安裝它:
$ pip install PyUserInput
爲了做平滑的動作,你可以嘗試9000在他的回答中提出的。
Above program does throws error in Win7 64 bit machine with embeded python and the trace being:
Traceback (most recent call last):
File "mouse.py", line 52, in <module>
random_movement((300,300),(600,600))
File "mouse.py", line 35, in random_movement
move_mouse(pos)
File "mouse.py", line 11, in move_mouse
return ctypes.windll.user32.mouse_event(32769, x, y, 0, 0)
ctypes.ArgumentError: argument 2: <class 'TypeError'>: Don't know how to convert
parameter 2
Any idea what is wrong ?
控制鼠標指針是高度特異性的平臺。你在使用什麼平臺? – 9000