Pygame 'not responding' during animations

Question:

This is more of an open question to people who have experience with Pygame.
I made a game with Pygame. In this game I have character that can move using W,A,S,D. This is all working. But I also have little animations like this (pseudo code):

while player.x != target_x and player.y != target_y:
    if player.x < target_x:
        player.x += 1
    else:
        player.x -= 1

    if player.y < target_y:
        player.y += 1
    else:
        player.y -= 1
    
    draw() # updates / draws the screen
    clock.tick(30)

My problem is that the window with game on it keeps crashing. Like the ‘animation’ begins an the character moves. But sometimes the window just goes ‘not responding’ and the animation freezes. BUT the program continues. After the time that it would take to finish the animation the window becomes responsive again and the character stands where it should bee at the end of the animation. So only the updating of the screen is a problem.
Has anyone ever experienced something like this before?

I don’t understand where the difference is between me pressing a button and telling the character to go right and the animation doing it.

NOTE: The animations worked fine in the past. I had this ‘not responsive’ a few rare times. But recently it happens more and more. Like almost every time.

Asked By: Akut Luna

||

Answers:

You have to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.

while player.x != target_x and player.y != target_y:

    pygame.event.pump() # <--- this is missing

    if player.x < target_x:
        player.x += 1
    else:
        player.x -= 1

    if player.y < target_y:
        player.y += 1
    else:
        player.y -= 1
    
    draw() # updates / draws the screen
    clock.tick(30)
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.