Search code examples
pythonpython-2.7pygameonmouseclick

How to pause a loop with a mouse click using pygame?


I m a beginner in python and I m doing a project using pygame. I initiated a loop on a mouse click and it runs good. But i couldn't stop that loop. I want it to stop on a mouse click and the loop should run until that mouse click. I have provided the outline of the code, below. Can anyone help me with a proper code? Thanks in advance.

for event in pygame.event.get():
    if (event.type == pygame.MOUSEBUTTONDOWN):
         (mx,my)= pygame.mouse.get_pos()
         if((mx>=375)&(mx<=425)&(my>=500)&(my<=550)): #to begin loop on mouse click#
           while True:
              ---statements-----
              if((mx>=300)&(mx<=350)&(my>=500)&(my<=550)): #to end loop on mouse click#
                 exit
              else:
                 continue

Solution

  • The problem is that once you enter the while True loop, you are no longer waiting for mouse events coming from pygame. Try checking for new events right before looping:

    for event in pygame.event.get(pygame.MOUSEBUTTONDOWN):
        mx, my = pygame.mouse.get_pos()
        if 375 <= mx <= 425 and 500 <= my <= 550:
            run = True
            while run:
                # statements
                # ...
                for event in pygame.event.get(pygame.MOUSEBUTTONDOWN):
                    mx, my = pygame.mouse.get_pos()
                    if 300 <= mx <= 350 and 500 <= my <= 550:
                        run = False
    

    You can filter directly the events in the event.get call.

    Note that I rewrote the boundary checks, as the logic and in Python is actualy and, while & is a bitwise operation. Python allows for a cool syntax when checking ranges too!