简体   繁体   中英

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 and check the R value is corresponded to what I am looking for, if it meets requirement perform a mouse click.获取 R 的 RGB colors 值并检查 R 值是否符合我正在寻找的鼠标的要求。

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM