3.2 Types of Events
Now that we’ve talked about how to access events, we should talk about the types of events. Mainly, there are
KEYUP
, KEYDOWN
, MOUSEBUTTONDOWN
, and MOUSEBUTTONUP
events.KEYDOWN
and KEYUP
If the event is a
KEYDOWN
or KEYUP
event, then the event will also have a key
attribute. The key
attribute refers to the key that was pressed or released. IMPORTANT:
KEYDOWN
event doesn't refer to the down arrow key being pressed, and KEYUP
event doesn't refer to the up arrow key being pressed. Instead, KEYDOWN
event refers to any key being pressed down, and KEYUP
event refers to any key being let go of. Their attribute key
is the actual key that was pressed or let go of. All keys follow the same format:
pygame.K_(key)
. If you do pygame.locals import *
, however, then these keys will be accessed as just K_(key)
. The following example shows these event types in use (if
from pygame.locals import *
isn't used):for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() break if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: # if the ‘w’ key is pressed print("you pressed the w key") if event.type == pygame.KEYUP: if event.key == pygame.K_w: # if the ‘w’ key is let go of print("you let go of the w key")
The key for the space key is
K_SPACE
(or pygame.K_SPACE
)
The key for the enter key is K_RETURN
(or pygame.K_RETURN
)MOUSEBUTTONDOWN
and MOUSEBUTTONUP
These types of events are pretty simple since you don’t need to worry about any key. If the
MOUSEBUTTONDOWN
event comes up, then that means that the user has clicked their mouse. If the MOUSEBUTTONUP
event comes up, then that means that the user has let go of the mouse button. For example:for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() break if event.type == pygame.MOUSEBUTTONDOWN: print(“you clicked the mouse”) if event.type == pygame.MOUSEBUTTONUP: print(“you let go of the mouse”)
In a real game, you should do more than just print to the console. For example, you could have it display to the screen some text, as outlined in 2.4 - Text and Fonts
Practice
Space Counter
Create a program that increments a counter every time the space bar is pressed. This counter should be displayed as text on the pygame window.
Previous Section
3.1 - Detecting EventsNext Section
3.3 - Blocking & Allowing EventsCopyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.