To move the mouse in a square pattern (down-right, down-left, up-left, up-right) and return it to its starting position, you can use the pyautogui library in Python. This library allows you to programmatically control the mouse and keyboard.
Below is the Python script that accomplishes this:
Script:
import pyautogui
import time
# Function to move the mouse in a square pattern
def move_mouse_square():
# Define the step size for each movement (in pixels)
step_size = 100
# Get the current mouse position (starting position)
start_x, start_y = pyautogui.position()
print(f"Starting position: ({start_x}, {start_y})")
try:
# Move down-right
pyautogui.move(step_size, step_size, duration=0.5)
print("Moved down-right")
# Move down-left
pyautogui.move(-step_size, step_size, duration=0.5)
print("Moved down-left")
# Move up-left
pyautogui.move(-step_size, -step_size, duration=0.5)
print("Moved up-left")
# Move up-right
pyautogui.move(step_size, -step_size, duration=0.5)
print("Moved up-right")
# Ensure the mouse is back to the starting position
pyautogui.moveTo(start_x, start_y, duration=0.5)
print(f"Returned to starting position: ({start_x}, {start_y})")
except Exception as e:
print(f"An error occurred: {e}")
# Add a delay before starting to give you time to focus the desired window
print("The script will start in 3 seconds. Move your mouse to the desired starting position.")
time.sleep(3)
# Call the function to execute the square movement
move_mouse_square()
Explanation of the Script:
-
Imports:
pyautogui: Used to control the mouse.
time: Used to add delays for better usability.
-
Step Size:
- The
step_size variable defines how far the mouse moves in each direction (in pixels). You can adjust this value to make the square larger or smaller.
-
Mouse Movement:
- The
pyautogui.move() function moves the mouse relative to its current position.
- Each movement corresponds to one side of the square:
- Down-right: Positive
x and y.
- Down-left: Negative
x, positive y.
- Up-left: Negative
x and y.
- Up-right: Positive
x, negative y.
-
Return to Start:
- After completing the square, the script uses
pyautogui.moveTo() to ensure the mouse returns to its original position.
-
Delay:
- A 3-second delay (
time.sleep(3)) is added at the beginning to give you time to position the mouse where you want the square to start.
-
Error Handling:
- A
try-except block is used to catch and report any errors during execution.
How to Run the Script:
-
Install the pyautogui library if you don't already have it:
pip install pyautogui
-
Save the script to a .py file (e.g., move_mouse_square.py).
-
Run the script:
python move_mouse_square.py
-
Move your mouse to the desired starting position within the 3-second delay.
Output:
The mouse will move in a square pattern and return to its starting position. The console will display messages indicating each movement.
Let me know if you need further customization!