为什么下面的代码不起作用? (使用 pyautogui 在游戏中创建机器人)

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

(代码应该用导入的模块重新创建)大家好!我试图为游戏创建一个简单的机器人,它在未检测到目标时向前移动,但在检测到目标时停止移动。为什么这不能让 W 键被按下?奇怪的是,当检测到目标或 target2.png 时,它会按 W 否则它不会?

这里的问题是 python 将某些值视为 True,而将其他值视为 False。

在Python中,None0""(空串)都被认为是False。任何其他值都被视为 True。

在您的代码中,有这一行:

if target and target2 is None:

虽然这句话听起来不错(如果两者都是 None),但真正发生的是 target 在计算中被转换为布尔值:

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

由于 target 不是 None/0/"",布尔转换 returns 为真。这会导致代码出现意外行为。

同样的想法适用于 elif 语句