Now that we’ve talked about how to access events, we should talk about the types of events. Mainly, there are
If the event is a
KEYUPevent, then the event will also have a
keyattribute refers to the key that was pressed or released.
KEYDOWNevent doesn't refer to the down arrow key being pressed, and
KEYUPevent doesn't refer to the up arrow key being pressed. Instead,
KEYDOWNevent refers to any key being pressed down, and
KEYUPevent refers to any key being let go of. Their attribute
keyis 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
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
pygame.K_SPACE) The key for the enter key is
These types of events are pretty simple since you don’t need to worry about any key. If the
MOUSEBUTTONDOWNevent comes up, then that means that the user has clicked their mouse. If the
MOUSEBUTTONUPevent 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
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.