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


x=0
while x==0:
target = pyautogui.locateOnScreen(os.path.expanduser(r'~Desktop botreferencestarget.png'),region=(0,0,1024,768),confidence=.7)
time.sleep(0.5)
target2 = pyautogui.locateOnScreen(os.path.expanduser(r'~Desktop botreferencestarget2.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键?奇怪的是,当检测到target或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/"",布尔转换返回True。这导致代码中出现意外行为。

同样的想法也适用于elif语句

最新更新