sanguine
sanguine

Reputation: 107

Why does the code below not work? (using pyautogui to create a bot in a game)

x=0
while x==0:
    target = pyautogui.locateOnScreen(os.path.expanduser(r'~\Desktop\ bot\references\target.png'),region=(0,0,1024,768),confidence=.7)
    time.sleep(0.5)
    target2 = pyautogui.locateOnScreen(os.path.expanduser(r'~\Desktop\ bot\references\target2.png'),region=(0,0,1024,768),confidence=.7)
    print(target,target2)
    if target and target2 is None:
        pyautogui.keyDown('W')
    elif target or target2 != None:
        pyautogui.keyUp("W")
        print(target or target2)
        target_point = pyautogui.center(target or target2)
        targetx, targety = target_point
        pyautogui.click(targetx, targety)
        x=1

(the code should be recreated with the modules imported)Hey everyone! I was trying to create a simple bot for a game that moves forward when it doesnt detect a target, but stops moving when the target is detected. Why does this not get the W key to be pressed down? Whats weird is that when target or target2.png is detected, it presses W otherwise it doesnt?

Upvotes: 0

Views: 72

Answers (1)

Mike67
Mike67

Reputation: 11342

The issue here is that python treats some values as True, and others as False.

In Python, None, 0, and "" (empty string) are all considered False. Any other value is considered True.

In your code, there is this line:

if target and target2 is None:

While the phrase sounds right (if both are None), what's really happening is target is converted to a boolean in the evaluation:

if bool(target) == True and target2 is None:

Since target is not None/0/"", the bool conversion returns True. This is causing the unexpected behavior in the code.

The same idea applies to the elif statement

Upvotes: 1

Related Questions