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 KEYUPIf 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.
<aside>
🚨 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.
</aside>
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")
<aside>
💡 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)
</aside>
MOUSEBUTTONDOWN and MOUSEBUTTONUPThese 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”)
<aside> 💡 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
</aside>
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.