我无法在Python中重新开始第一次循环

-2 投票
1 回答
40 浏览
提问于 2025-04-12 15:38

首先,我对Python非常陌生,可能我的代码看起来会让你觉得很难受,真抱歉。 我写这段代码的目的是想用pyautogui做一个过滤系统。我的第一个循环运行得很好,但因为有太多嵌套的代码块,我需要创建第二个循环。我结束第一个循环的方法是把它改成False,但当我想重新开始时,它就失败了,直接结束了任务。我不知道该怎么解决这个问题,也不知道有没有人能帮我,因为我的代码实在是太乱了。

import pyautogui
import time
import keyboard

should_restart = True

time.sleep(1)
while should_restart:
  try:
    loop2 = False
    yellow = pyautogui.locateCenterOnScreen('Yellow_FL.png', confidence=0.7)
    pyautogui.moveTo(yellow)
    time.sleep(0.1)
    pyautogui.mouseDown()
    time.sleep(0.5)
    pyautogui.mouseUp()
    pyautogui.moveTo(1200, 600)
    print("Found1")
    continue
  except:
    try:
      green = pyautogui.locateCenterOnScreen('Green_FL.png', confidence=0.7, grayscale=True)
      pyautogui.moveTo(green)
      time.sleep(0.1)
      pyautogui.mouseDown()
      time.sleep(0.5)
      pyautogui.mouseUp()
      pyautogui.moveTo(1200, 600)
      print("Found2")
      continue
    except:
      try:
        purple = pyautogui.locateCenterOnScreen('Purple_FL.png', confidence=0.7, grayscale=True)
        pyautogui.moveTo(purple)
        time.sleep(0.1)
        pyautogui.mouseDown()
        time.sleep(0.5)
        pyautogui.mouseUp()
        pyautogui.moveTo(1200, 600)
        print("Found3")
        continue
      except:
        try:
          b_battery = pyautogui.locateCenterOnScreen('Brown_Battery.png', confidence=0.7, grayscale=True)
          pyautogui.moveTo(b_battery)
          time.sleep(0.1)
          pyautogui.mouseDown()
          time.sleep(0.5)
          pyautogui.mouseUp()
          pyautogui.moveTo(1200, 600)
          print("Found4")
          continue
        except:
          try:
            g_battery = pyautogui.locateCenterOnScreen('green_battery.png', confidence=0.7)
            pyautogui.moveTo(g_battery)
            time.sleep(0.1)
            pyautogui.mouseDown()
            time.sleep(0.5)
            pyautogui.mouseUp()
            pyautogui.moveTo(1200, 600)
            print("Found5")
            continue
          except:
           try:
             P_Lens = pyautogui.locateCenterOnScreen('Purple_Lens.png', confidence=0.7, grayscale=True)
             pyautogui.moveTo(P_Lens)
             time.sleep(0.1)
             pyautogui.mouseDown()
             time.sleep(0.5)
             pyautogui.mouseUp()
             pyautogui.moveTo(1200, 600)
             time.sleep(0.5)
             print("Found7")
             continue
           except:
             try:
               amp = pyautogui.locateCenterOnScreen('yellow_amp.png', confidence=0.7)
               pyautogui.moveTo(amp)
               time.sleep(0.1)
               pyautogui.mouseDown()
               time.sleep(0.5)
               pyautogui.mouseUp()
               pyautogui.moveTo(1200, 600)
               time.sleep(0.5)
               print("Found8")
               continue
             except:
               try:
                 styptic = pyautogui.locateCenterOnScreen('Styptic.png', confidence=0.7)
                 pyautogui.moveTo(styptic)
                 time.sleep(0.1)
                 pyautogui.mouseDown()
                 time.sleep(0.5)
                 pyautogui.mouseUp()
                 pyautogui.moveTo(1200, 600)
                 time.sleep(0.5)
                 print("Found9")
                 continue
               except:
                 should_restart = False

loop2 = True
while loop2:
  try:
    lens_y = pyautogui.locateCenterOnScreen('yellow_lens.png', confidence=0.7)
    pyautogui.moveTo(lens_y)
    time.sleep(0.1)
    pyautogui.mouseDown()
    time.sleep(0.5)
    pyautogui.mouseUp()
    pyautogui.moveTo(1200, 600)
    print("Found10")
    continue
  except:
    try:
      Syringe = pyautogui.locateCenterOnScreen('Syringe.png', confidence=0.7, grayscale=True)
      pyautogui.moveTo(Syringe)
      time.sleep(0.1)
      pyautogui.mouseDown()
      time.sleep(0.5)
      pyautogui.mouseUp()
      pyautogui.moveTo(1200, 600)
      print("Found11")
      continue
    except:
      try:
        Auto = pyautogui.locateCenterOnScreen('AutoBloodweb.png', confidence=0.7, grayscale=True)
        pyautogui.moveTo(Auto)
        time.sleep(0.1)
        pyautogui.mouseDown()
        time.sleep(0.5)
        pyautogui.mouseUp()
        pyautogui.moveTo(1200, 600)
        print("Found12")
        time.sleep(4)
        should_restart = True
        time.sleep(1)
        loop2 = False
      except:
        try:
          Empty = pyautogui.locateCenterOnScreen('EmptyBloo2aaadweb.png', confidence=0.7)
          break
        except:
          pass

我原本以为第一个循环结束后,第二个循环会开始,结果确实是这样,然后第二个循环会停止,接着第一个循环会再次开始,直到检测到'EmptyBloodweb.png'为止。 没想到的是,第一个循环停止后,第二个循环开始,然后第二个循环又停止了,就这样结束了。

1 个回答

1

很难判断你想要实现的具体逻辑是什么,但如果我的直觉没错的话,你可能是想按顺序点击这些东西,如果某次点击失败了,就从第一个开始重新点击,对吗?

如果是这样的话,我会把这个代码改成下面这样的。

这个想法是,find_and_click 函数会尝试找到并点击目标,如果找不到就返回 False(如果在移动鼠标或点击时出错,它会抛出异常)。

然后,在 main() 函数里的两个循环,如果有一次点击失败(也就是辅助函数返回 False),就会用 continue 重新开始这两个循环。

如果这两个循环是相互依赖的,你可以把它们提取成两个相似的函数:如果任何一步失败,就重试另一个循环,依此类推。

import time

import pyautogui


def find_and_click(png, grayscale=False):
    print(f"Looking for {png}...")
    try:
        obj = pyautogui.locateCenterOnScreen(png, confidence=0.7, grayscale=grayscale)
    except Exception as e:
        print(f"Could not find {png}: {e}")
        return False
    pyautogui.moveTo(obj)
    time.sleep(0.1)
    pyautogui.mouseDown()
    time.sleep(0.5)
    pyautogui.mouseUp()
    pyautogui.moveTo(1200, 600)
    return True


def main():
    while True:
        print("Starting loop 1...")
        if not find_and_click("Yellow_FL.png"):
            continue
        if not find_and_click("Green_FL.png", grayscale=True):
            continue
        if not find_and_click("Purple_FL.png", grayscale=True):
            continue
        if not find_and_click("Brown_Battery.png", grayscale=True):
            continue
        if not find_and_click("green_battery.png"):
            continue
        if not find_and_click("Purple_Lens.png", grayscale=True):
            continue
        if not find_and_click("yellow_amp.png"):
            continue
        if not find_and_click("Styptic.png"):
            continue
        break

    while True:
        print("Starting loop 2...")
        if not find_and_click("yellow_lens.png"):
            continue
        if not find_and_click("Syringe.png", grayscale=True):
            continue
        if not find_and_click("AutoBloodweb.png", grayscale=True):
            continue
        break

if __name__ == "__main__":
    main()

如果你的想法只是按顺序点击这些东西,等待它们出现,那么这个过程就可以简化成:

import time
from itertools import count

import pyautogui


def find_and_click(png, grayscale=False):
    print(f"Looking for {png}...")
    try:
        obj = pyautogui.locateCenterOnScreen(png, confidence=0.7, grayscale=grayscale)
    except Exception as e:
        print(f"Could not find {png}: {e}")
        return False
    pyautogui.moveTo(obj)
    time.sleep(0.1)
    pyautogui.mouseDown()
    time.sleep(0.5)
    pyautogui.mouseUp()
    pyautogui.moveTo(1200, 600)
    return True


def wait_for_find_and_click(png, grayscale=False):
    for attempt in count(1):
        print(f"Attempt {attempt} to find {png}...")
        if find_and_click(png, grayscale):
            break
        time.sleep(1)


def main():
    while True:
        wait_for_find_and_click("Yellow_FL.png")
        wait_for_find_and_click("Green_FL.png", grayscale=True)
        wait_for_find_and_click("Purple_FL.png", grayscale=True)
        wait_for_find_and_click("Brown_Battery.png", grayscale=True)
        wait_for_find_and_click("green_battery.png")
        wait_for_find_and_click("Purple_Lens.png", grayscale=True)
        wait_for_find_and_click("yellow_amp.png")
        wait_for_find_and_click("Styptic.png")
        wait_for_find_and_click("yellow_lens.png")
        wait_for_find_and_click("Syringe.png", grayscale=True)
        wait_for_find_and_click("AutoBloodweb.png", grayscale=True)


if __name__ == "__main__":
    main()

撰写回答