Gayashan
Gayashan

Reputation: 21

How to prevent a function from being called more than one time in a while loop - PYTHON

What I'm trying to do is? automate a game using coordinates and pywin32.

Expected result: 

getting R of RGB colors value of using pyautogui.pixel(489, 209)[0] and check the R value is corresponded to what I am looking for, if it meets requirement perform a mouse click.

Drawback result: 

Once the code is run while loop start to work and click event performs until the if statement run into else statement. that resulted unwanted and unnecessary time consuming. is there anyway I can perform the click() method only once inside of this while loop.

import keyboard
import pyautogui
import time
import win32api, win32con


def click(x, y):

    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
    time.sleep(0.1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)

while not keyboard.is_pressed('q'):

        if  pyautogui.pixel(686, 172)[0] != 255:
        print("he is not looking at you, click the mouse")
        click(680, 694)
        else:
        print("he is looking at you, click again")
        click(680, 694)

Upvotes: 1

Views: 120

Answers (2)

Amisha Kirti
Amisha Kirti

Reputation: 152

I suggest modifying the code like this by making use of a flag variable:

while not keyboard.is_pressed('q'):

    flag=True

    if  (pyautogui.pixel(686, 172)[0] != 255 and flag==True):

    print("he is not looking at you, click the mouse")

    click(680, 694)

    flag=False

    else:

    print("he is looking at you, click again")

    click(680, 694)

Upvotes: 0

Bartosz Różycki
Bartosz Różycki

Reputation: 164

You can add a bool variable before the loop set as True and put click() into if, where condition is that bool variable. After one usage of click() set variable to False so the condition is False and click() will not be performed

Upvotes: 1

Related Questions