Python getpixel then click on described color in RGB

564 Views Asked by At

I've found this code at stackoverflow

color = (0, 137, 241)
s = pyautogui.screenshot()
for x in range(s.width):
    for y in range(s.height):
        if s.getpixel((x, y)) == color:
            pyautogui.click(x, y)  # do something here
            break

I'm creating some bot for a game that waits for its turn, picks up a spell and then clicks on monsters tile. The problem is that I want to click only once on the tile of the color = (0, 137, 241). Right now it searches for all of them in for loop. How to specify x and y (width and height) to make it pyautogui.click(x, y) only once at described colors RGB?

Thanks a lot for help!

1

There are 1 best solutions below

0
Farid Ibrahim On

The key here is to break both for loops once it met your condition. The problem with your code is it only stops on the current column of pixels that met your condition then continue to search on other columns of pixels because that initial loop hasn't been broken.

color = (0, 137, 241)
s = pyautogui.screenshot()
for x in range(s.width):
    for y in range(s.height):
        if s.getpixel((x, y)) == color:
            pyautogui.click(x, y)  # do something here
            break
    else # <---this is the key. 
        continue
    break