Learn Before
Executing Code Based on Keyboard Events in Pygame
Code may be routed depending on a keyboard press. For example, say you want to call a method which exists elsewhere known as moveUp(), which moves your character upwards. You only want to do this if the 'w' key is pressed on the keyboard. You must check that it is a keyboard event, which you can do by checking if type of the EventType object is equal to the constant KEYDOWN, which stores the integer value for keydown type events. Then, you could check the 'key' attribute on the keyboard event's EventType object, which stores which key was pressed in the form of an integer. Thankfully, there are also built in constants for this. The constant is always 'K_' followed by the key itself. For 'w', it is 'K_w'.
for event in pygame.event.get() #this block iterates through the queue if event.EventType.type == pygame.KEYDOWN: #if the event has type keydown if event.EventType.type == pygame.K_w: #if event key attribute is equal to w moveUp() #call moveUp()!
0
1
Tags
Python Programming Language
Data Science