Why doesn't this code work? Mouse button release detection [SOLVED]

Hello,

I am trying to create a function which returns True if and only if the mouse button is released from being pressed. My idea to do this was to create a while loop which runs as long as the first mouse button is being held, but once it is released the while condition breaks and the function returns True.

These were a few of my attempts but neither one works, locking the user in the while loop indefinitely:

def check_release() -> bool:
    c = pygame.mouse.get_pressed()
    i = None

    while c[0]:
        i = 1
        c = pygame.mouse.get_pressed()

    if i is not None:
        return True
    return False

and

def check_release() -> bool:
    i = None

    while pygame.mouse.get_pressed()[0]:
        i = 1

    if i is not None:
        return True
    return False

I know about the pygame constant MOUSEBUTTONUP, but I am trying to find an alternative to using an event loop. Any suggestions would be appreciated!

Is the idea that this function returns False if the mouse button isn’t already down, otherwise it spins as fast as possible, burning CPU cycles as fast as it can, until the button is released? If so, try this:

# Untested.

def first_mouse_button_is_down():
    # Returns True for down and False for up.
    # See documentation here.
    # https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pressed
    pygame.event.get()
    return pygame.mouse.get_pressed()[0]

def check_release():
    if not first_mouse_button_is_down():
        return False
    while first_mouse_button_is_down():
        pass
    return True

You can make it a little less CPU hostile by replacing the pass in the while loop with time.sleep(0.01).

Thank you so much, this works exactly as I wanted it to!

At first I tried implementing it with my own version of first_mouse_button_is_down() which went as follows:

def check_down() -> bool:
    c = pygame.mouse.get_pressed()
    return c[0]

but it did not work. I am very new to pygame and python in general and am curious about the difference using pygame.event.get() makes. What exactly does calling that function do?

You would have to read the documentation and possibly source code to Pygame to understand why you need to call event.get(), but my guess is that it does something with the event loop to infer the current mouse state from whatever the last mouse event was.

1 Like