[SOLVED] Why does this code stop working when I put it in a function?

Issue

I’m only starting to grasp this idea of abstracting complex stuff via functions, so I decided to practice it a bit in Pygame.

So, this code right here works just fine, the pygame window is present, and you can close it by pressing X button:

#pygame initialization code and etc.

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    #code for drawing stuff out

But let’s say I want to make a function to just handle closing the window just for the sake of it:

#pygame initialization code and etc.

running = True

def handle_quit_event():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return False
        else:
            return True


while running:
    running = handle_quit_event()

    #code for drawing stuff out

Now it doesn’t work the same way anymore, the pygame window appears for a blink moment, and then program finishes, leaving me with this unease feeling that my idea of abstracting stuff using functions is all wrong.

[EDIT]: So in my code the function checks for only the first event in the list, but it still doesn’t explain why the program finishes right after running it, because even if it checks for the first event, it still should return true by running else clause. So what am I missing?

Solution

Abstracting functionality into functions is a great idea! Unfortunately your re-write has introduced a bug that might be causing your broken game. Without a stacktrace or error messages, it’s hard to say exactly why the game is broken.

Onto the bug:

The function handle_quit_event doesn’t iterate through all the events in pygame.event.get(). It returns True or False after checking the first event.

You probably wanted to write it more like:

def handle_quit_event():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return False
    return True

A more pythonic approach that uses list-comprehension and any():

def handle_quit_event():
    return not any([event.type == pygame.QUIT for event in pygame.event.get()])

Note the flipped logic with not is required because your function is currently returning True if there is not a QUIT event.

Answered By – Thomas Anderson

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.