Sign InNuggetsCoursesCodePadCheatsheet

Event Handling with Pygame

Recall that an event is a user action, such as a key press or mouse click, that basically begs your program to "please pay attention."

In the unit Writing Games with Turtle Graphics you've learned how to interact with turtle applications.

Now let's see how to handle events in pygame.

It's OK to Quit -- Sometimes :)

In previous examples, we have used the following code snippet many times. What does it do?

while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()

Pulling Events

This is an example that illustrates how events are handled in pygame.

Whenever the user does something like pressing a mouse button, an event is triggered. In this case -- when the user clicks the close button of the game window -- the pygame.QUIT event will be generated.

Our program keeps checking for such signals inside the game loop -- in programming, this is called pulling.

During every iteration of the game loop, we repeatedly check if there exists any event we should pay attention to. We do this by examining all events from pygame.event.get().

Once pygame.QUIT is observed, we subsequently call sys.exit() to exit the application.

© CS Wonders·Home·About·Contact·Classes·Gallery·Glossary·Fun Facts