Skip to content

Instantly share code, notes, and snippets.

@knowlet
Last active May 7, 2025 15:26
Show Gist options
  • Save knowlet/555de4847f8eca2bea410fc8b7433278 to your computer and use it in GitHub Desktop.
Save knowlet/555de4847f8eca2bea410fc8b7433278 to your computer and use it in GitHub Desktop.
Auto dice maplestory on Mac, test with MapleStory Worlds Artale.
import pyautogui
import time
# import os # Removed as it's unused
from ocrmac import ocrmac
import random # Added import for random offset
# --- Configuration ---
SCREENSHOT_REGION = (1220, 690, 60, 30) # x, y, width, height
CLICK_COORDINATES = (1355, 690) # x, y
THRESHOLD_NUMBER = 12
MAX_RETRIES = 200 # Max number of attempts before stopping
RETRY_DELAY_SECONDS = 1 # Delay between retries in seconds
TEMP_SCREENSHOT_PATH = "temp_screenshot.png" # Temporary screenshot
# --- Helper Functions ---
def capture_and_ocr(region, filepath):
"""
Captures a screenshot of the specified region, saves it,
performs OCR using the ocrmac Python library, and attempts to extract
a number. Returns the extracted number (int) or None if unsuccessful.
"""
try:
return _extracted_from_capture_and_ocr_9(region, filepath)
except Exception as e: # Catch a broader range of ocrmac or other errors
print(f"An error occurred during screen capture or OCR: {e}")
print("Ensure 'ocrmac' and its dependencies (like pyobjc) are "
"correctly installed.")
return None
# finally:
# # Clean up the temporary screenshot file
# if os.path.exists(filepath):
# try:
# os.remove(filepath)
# # print(f"Cleaned up temporary file: {filepath}")
# except Exception as e:
# print(f"Error deleting temporary file {filepath}: {e}")
# TODO Rename this here and in `capture_and_ocr`
def _extracted_from_capture_and_ocr_9(region, filepath):
# Capture the screenshot
screenshot = pyautogui.screenshot(region=region)
screenshot.save(filepath)
# print(f"Screenshot saved to {filepath}")
# Perform OCR using ocrmac library
# The recognize() method returns a list of (text, confidence,
# bounding_box) tuples. For example:
# [('123', 0.95, (x, y, w, h)), ('text', 0.8, (x,y,w,h))]
# We are interested in the text part.
annotations = ocrmac.OCR(
filepath, recognition_level='accurate'
).recognize()
if not annotations:
# print(f"ocrmac returned no annotations for {filepath}")
return None
# Concatenate all recognized text parts
ocr_text = " ".join([ann[0] for ann in annotations if ann[0]])
# print(f"OCR raw text: '{ocr_text}'")
# Attempt to extract a number from the OCR text
# This basic cleaning removes non-digit characters.
# For complex OCR, robust parsing (e.g., regex) might be needed.
cleaned_text = "".join(filter(str.isdigit, ocr_text))
return int(cleaned_text) if cleaned_text else None
def randomize_click_coordinates(click_coordinates):
# Calculate randomized click coordinates
random_offset_x = random.randint(-3, 3)
random_offset_y = random.randint(-3, 3)
click_x = click_coordinates[0] + random_offset_x
click_y = click_coordinates[1] + random_offset_y
return click_x, click_y
if __name__ == "__main__":
# macOS: Check for minimal screen size to avoid issues with coordinates.
# PyAutoGUI raises FailSafeException if mouse moves to (0,0) by default.
pyautogui.FAILSAFE = True
# You might need to adjust your mouse sensitivity or disable
# shake-to-locate cursor if you experience issues with
# pyautogui's mouse control.
print("Starting automation script...")
print(f" Screen capture region (x,y,w,h): {SCREENSHOT_REGION}")
print(f" Click coordinates (x, y): {CLICK_COORDINATES}")
print(f" Click if number is less than: {THRESHOLD_NUMBER}")
print(f" Maximum retries: {MAX_RETRIES}")
print(f" Delay between retries: {RETRY_DELAY_SECONDS} second(s)")
print("-" * 40)
print("IMPORTANT: Ensure terminal/Python has Accessibility and Screen "
"Recording permissions")
print("in System Settings > Privacy & Security on macOS.")
print("Script pauses for 5s to switch to target window/app.")
time.sleep(5)
retries_count = 0
while retries_count < MAX_RETRIES:
print(f"\nAttempt {retries_count + 1} of {MAX_RETRIES}...")
extracted_number = capture_and_ocr(SCREENSHOT_REGION,
TEMP_SCREENSHOT_PATH)
if extracted_number is None:
print("Failed to recognize a number in this attempt.")
else:
print(f"Recognized number: {extracted_number}")
if extracted_number >= THRESHOLD_NUMBER:
print(f"Num {extracted_number} >= {THRESHOLD_NUMBER}. Stop.")
break
click_x, click_y = randomize_click_coordinates(CLICK_COORDINATES)
# Log randomized coords
print(f"Num {extracted_number} < {THRESHOLD_NUMBER}. "
f"Clicking at ({click_x}, {click_y}).")
try:
pyautogui.click(click_x, click_y) # Use randomized coords
print("Click performed.")
except Exception as e:
print(f"Error during click: {e}")
# Optional: add a small delay after clicking
# if the application needs it
# time.sleep(0.2)
retries_count += 1
if retries_count < MAX_RETRIES:
print(f"Waiting {RETRY_DELAY_SECONDS}s before next attempt...")
time.sleep(RETRY_DELAY_SECONDS)
else:
print("\nMax retries reached.")
print("-" * 40)
print("Automation script finished.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment