Advertisement
Toumo

constrain_mouse_pointer_to_rect.py

Apr 18th, 2023 (edited)
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. from time import sleep
  2. from pynput import mouse, keyboard
  3.  
  4. def constrain(val, min_val, max_val):
  5.     return min(max_val, max(min_val, val))
  6.  
  7. def on_press(key):
  8.     global end
  9.     global correct
  10.     if key == keyboard.Key.end: end = True
  11.     if key == keyboard.Key.tab: correct = not correct
  12.  
  13. CPS = 300 # Corrections Per Second
  14. rect = {"top_left":  {"x": 0,    "y": 0},
  15.         "bot_right": {"x": 1350, "y": 767}}
  16.  
  17. end = False
  18. correct = True
  19. mouse = mouse.Controller()
  20. kb_listener = keyboard.Listener(on_press = on_press)
  21. kb_listener.start()            
  22. while not end:
  23.     sleep(1/CPS)
  24.     if correct:
  25.         x, y = mouse.position
  26.         mouse.position = (constrain(x, rect["top_left"]["x"], rect["bot_right"]["x"]),
  27.                           constrain(y, rect["top_left"]["y"], rect["bot_right"]["y"]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement