Game Development Reference
In-Depth Information
18 - Collision Detection and Input
44. if event.type == KEYDOWN:
Pygame has another event type called KEYDOWN . On line 41, we check if the
event.type attribute is equal to the QUIT value to check if we should exit the program.
But there are other events that Pygame can generate. A brief list of the events that could be
returned by pygame.event.get() is in Table 18-1.
Setting the Four Keyboard Variables
45. # change the keyboard variables
46. if event.key == K_LEFT or event.key == ord
('a'):
47. moveRight = False
48. moveLeft = True
49. if event.key == K_RIGHT or event.key == ord
('d'):
50. moveLeft = False
51. moveRight = True
52. if event.key == K_UP or event.key == ord
('w'):
53. moveDown = False
54. moveUp = True
55. if event.key == K_DOWN or event.key == ord
('s'):
56. moveUp = False
57. moveDown = True
If the event type is KEYDOWN , then the event object will have a key attribute that will
tell us which key was pressed down. On line 46, we can compare this value to K_LEFT ,
which represents the left arrow key on the keyboard. We will do this for each of the arrow
keys: K_LEFT , K_RIGHT , K_UP , K_DOWN .
When one of these keys is pressed down, we will set the corresponding movement
variable to True . We will also set the movement variable of the opposite direction to
False . For example, the program executes lines 47 and 48 when the left arrow key has
been pressed. In this case, we will set moveLeft to True and moveRight to False
(even though moveRight might already be False , we set it to False just to be sure).
You may notice that on line 46, in event.key can either be equal to K_LEFT or ord
('a') . The value in event.key is set to the integer ASCII value of the key that was
pressed on the keyboard. (There is no ASCII value for the arrow keys, which is why we use
the constant variable K_LEFT .) You can use the ord() function to get the ASCII value of
any single character to compare it with event.key .
By executing the code on lines 47 and 48 if the keystroke was either K_LEFT or ord 353
Search WWH ::




Custom Search