6.9: Checking for Keyboard Presses
- Page ID
- 14539
elif event.type == KEYDOWN: if event.key == K_q: clickedButton = YELLOW elif event.key == K_w: clickedButton = BLUE elif event.key == K_a: clickedButton = RED elif event.key == K_s: clickedButton = GREEN
Lines 1 [85] to 9 [93] check for any KEYDOWN
events (created when the user presses a key on the keyboard). The Q, W, A, and S keys correspond to the buttons because they are arranged in a square shape on the keyboard.
The Q key is in the upper left of the four keyboard keys, just like the yellow button on the screen is in the upper left, so we will make pressing the Q key the same as clicking on the yellow button.
We can do this by setting the clickedButton
variable to the value in the constant variable YELLOW
. We can do the same for the three other keys. This way, the user can play Simulate with either the mouse or keyboard.