A solution to break / continue a loop in Python?

0

The question is this, I can not find a solution that will override console usage for my small application.

What happens is: My application runs in the eternal loop, but after it executes the loop, it should stop to ask if I want to stop the loop or continue. So far nothing impossible. However, I want it to continue the loop if I do nothing. For example:

  • I open the program.
  • The program executes the first loop.
  • A message appears: "Press any key to stop or wait 4 seconds."
  • From this moment on, there are two possibilities.

  • I press any key and the program closes.
  • I do not press anything and the program continues.
  • I've already thought of some things, such as using two threads one to read the keys (if any) and another to count the 4 seconds, but I could not. So I come to ask if anyone knows a solution to this problem.

    import pyautogui
    import sys, time, msvcrt, random, time, os
    
    # obs: Minha resolução de tela é 1366 x 768. Talvez será necessário adaptar as coordenadas
    #      dos cliques automatizados para sua tela. 
    
    def jogar():
        time.sleep(0.5)
        pyautogui.click(670, 330)
        time.sleep(0.5)
        cartaEscolhida = random.randint(1,5) # Escolhe uma carta aleatória.
        if cartaEscolhida == 1: 
            pyautogui.click(670, 330)
        elif cartaEscolhida == 2:
            pyautogui.click(717, 350)
        elif cartaEscolhida == 3:
            pyautogui.click(771, 351)
        elif cartaEscolhida == 4:
            pyautogui.click(815, 357)
        else:
            pyautogui.click(863, 350) 
        time.sleep(7.5)
        pyautogui.click(760, 410)
    
    def abrirJogo():                # Dá os cliques para abrir a extensão e o jogo de cartas.
        pyautogui.click(891, 537)
        time.sleep(1)
        pyautogui.click(694, 386)
    
    def fecharJogo():               # Dá os cliques para fechar a extensão.
        time.sleep(0.5)
        pyautogui.click(880, 531)
    
    def mudarAba():                 # Para mudar da aba do console para a aba do navegador.
        pyautogui.keyDown('alt',)
        pyautogui.press('tab')
        pyautogui.keyUp('alt')
    
    def pararPrograma():
        timeout = 4
        startTime = time.time()
        inp = None
        print("Aperte qualquer tecla para continuar ou aguarde 4 segundos.")
        while True:
            if msvcrt.kbhit():
                inp = msvcrt.getch()
                break
            elif time.time() - startTime > timeout:
                break
        if inp:
            sys.exit()
        else: 
           parar = False
    
    clear = lambda: os.system('cls')  # Para limpar o console. 
    
    # Daqui pra frente é o programa funcionando. 
    
    print("Abra o canal na twitch e deixe em modo teatro. O programa iniciará em 10 segundos.")
    time.sleep(10)
    parar = False
    while parar == False:
         abrirJogo()
         jogar()
         fecharJogo()
         mudarAba()
         clear()
         pararPrograma()     
         mudarAba()
    

    I also put the source code on the site pastebin.com and saved a video running it .

    Note: The current source code works, but I want to solve this problem because I want to use a graphical interface.

    To simplify the problem a little more I did this:

    from threading import Thread
    import time, sys
    
    def pergunta():
        print("Aperte qualquer tecla para parar ou aguarde 4 segundos.")
        input()
    
    def contar():
        timeout = 4
        startTime = time.time()
        while True:
            if time.time() - startTime > timeout:
                print("Continuando")
                break
    
    ThreadA = Thread(target=pergunta)
    ThreadB = Thread(target=contar)
    
    ThreadA.start()
    ThreadB.start()
    

    Now the problem changes. The input does not end after the 4 seconds has elapsed. And I can not call those threads again.

        
    asked by anonymous 27.04.2018 / 06:53

    1 answer

    2

    Good people. It's 4:31 matina and I solved it. = D I'm going to post to the Google drive since they are almost identical codes.

    The solution was I put the thread (deletes one) inside a while with a for. This way every time the thread finishes it will return pro while it will repeat the thread.

    And the input I left as normal. But now, as soon as 4 seconds pass and nothing is pressed, the program will type "continue" and continue the loop.

    obs: v3 is where the solution is.

    The link

        
    27.04.2018 / 09:37