Search code examples
pythonmultiprocessingpyautogui

Multiprocessing pause 1 code while the other is active?


I'm making a bot for a clicker game, the game has ads that pop up at random times. With the code below these pop-ups get dismissed whenever they're detected. However, the code that plays the clicker game is timed and whenever an ad is found, it messes with the code, making the program fail. Does anyone know something to pause what happens in play() whenever ad() finds something?

My code:

from pyautogui import * 
import pyautogui 
import time 
import keyboard 
import random
import win32api, win32con
from multiprocessing import Process
import sys

def ad():
    adloop = True
    while adloop:
        cross = pyautogui.locateOnScreen('image.png', confidence = 0.95)        
        if cross != None:
            print("Popup!")
        else:
            print("Checking for popups...")

def count():
    amount = 0
    count = True
    while count:
        amount += 1
        print(amount)
        time.sleep(1)


if __name__=='__main__':
        p1 = Process(target = ad)
        p1.start()
        p2 = Process(target = count)
        p2.start()

Solution

  • You could use a Process.Event as a flag.

    Note that pip install pyautogui pillow opencv-python is needed for operation.

    import pyautogui
    import time
    from multiprocessing import Process,Event
    
    def ad(e):
        adloop = True
        while adloop:
            cross = pyautogui.locateOnScreen('image.png', confidence = 0.95)
            if cross != None:
                print("Popup!")
                e.clear()
            else:
                print("Checking for popups...")
                e.set()
    
    def count(e):
        amount = 0
        while True:
            e.wait()  # sleep process when event is clear.
            amount += 1
            print(amount)
            time.sleep(1)
    
    if __name__=='__main__':
        # Create an event to share between the processes.
        # When set, the counting process will count.
        e = Event()
        e.set()
    
        # Make processes daemons, so exiting main process will kill them.
        p1 = Process(target = ad, args=(e,), daemon=True)
        p1.start()
        p2 = Process(target = count, args=(e,), daemon=True)
        p2.start()
        input('hit ENTER to exit...')
    

    Output:

    hit ENTER to exit...1
    Checking for popups...
    2
    Checking for popups...
    Checking for popups...
    3
    Checking for popups...
    4
    Checking for popups...
    Popup!
    Popup!
    Popup!
    Popup!
    Popup!
    Popup!
    Popup!
    Popup!
    Checking for popups...
    5
    Checking for popups...
    6
    Checking for popups...
    Checking for popups...
    7