为了账号安全,请及时绑定邮箱和手机立即绑定

为什么下面的代码不起作用?

为什么下面的代码不起作用?

侃侃无极 2023-06-13 11:05:55
x=0while 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 键被按下?奇怪的是,当检测到 target 或 target2.png 时,它会按 W,否则不会?
查看完整描述

1 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

这里的问题是 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声明


查看完整回答
反对 回复 2023-06-13
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信