简体   繁体   中英

How to handle if statement inside a while loop - Python

I am creating a game bot for my own game, here in this(attached image is down bellow) game this stick man turns and turns away itself randomly.in the meantime I can use the click button to steal his money if he turns while you are clicking on the button, game will be over.

what I am trying to perform is, taking x,y value of its forehead and and the pixel R value of RGB using library and if it matches R value of its forehead I would perform a mouse click.库获取其前额的 x,y 值和 RGB 的像素 R 值,如果它与前额的 R 值匹配,我将执行鼠标单击。 and same if it doesn't.

The problem I get is, when I tried to run the following script it runs perfectly but the mouse click event is fired more than one time.


    import keyboard
    import pyautogui
    
    while not keyboard.is_pressed('q'):
        if pyautogui.pixel(687, 144)[0] != 255:
            print("Looking at you")
            pyautogui.click(681, 662)
        else:
            print("Not looking at you")
            pyautogui.click(681,662)

I tried the upon script with bool variables in the following way, but it will only work onetime for both & once these variables become false the program doesn't work after.都有效。


    import keyboard
    import pyautogui
    
    
    boolval1=True
    boolval2=True
    
    while not keyboard.is_pressed('q'):
        if pyautogui.pixel(687, 144)[0] != 255:
            if boolval1:
                print("Looking at you")
                pyautogui.click(681, 662)
                boolval1 = False
        else:
            if boolval2:
                print("Not looking at you")
                pyautogui.click(681,662)
                boolval2 = False

is there anyway I can perform only a single click every time this stick man turns and turns away??

here I have attached a sketch of the game to get a brief idea

在此处输入图像描述

Have you tried wrapping your code in an infinite loop

while True:
    # do stuff with is pressed and clicks

Just a piece of advice but i think you should look up the MVC design pattern, this will be a mess to understand after:

        if pyautogui.pixel(687, 144)[0] != 255:

    a = True
    while not keyboard.is_pressed('q'):
    b = False
    if pyautogui.pixel(687, 144)[0] == 255:
        b = True
    if b != a:
        print("Click")
    a = b

I was able to find an answer this might save ones time

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