Game Development Reference
In-Depth Information
86. if event.type == KEYDOWN:
87. if event.key == ord('z'):
88. reverseCheat = True
89. if event.key == ord('x'):
90. slowCheat = True
If the event's type is KEYDOWN , then we know that the player has pressed down a key.
The Event object for keyboard events will also have a key attribute that is set to the
numeric ASCII value of the key pressed. The ord() function will return the ASCII value
of the letter passed to it.
For example, on line 87, we can check if the event describes the "z" key being pressed
down by checking if event.key == ord('z') . If this condition is True , then we
want to set the reverseCheat variable to True to indicate that the reverse cheat has
been activated. We will also check if the "x" key has been pressed to activate the slow cheat
in a similar way.
Pygame's keyboard events always use the ASCII values of lowercase letters, not
uppercase. What this means for your code is that you should always use event.key ==
ord('z') instead of event.key == ord('Z') . Otherwise, your program may act
as though the key hasn't been pressed at all.
91. if event.key == K_LEFT or event.key ==
ord('a'):
92. moveRight = False
93. moveLeft = True
94. if event.key == K_RIGHT or event.key ==
ord('d'):
95. moveLeft = False
96. moveRight = True
97. if event.key == K_UP or event.key == ord
('w'):
98. moveDown = False
99. moveUp = True
100. if event.key == K_DOWN or event.key ==
ord('s'):
101. moveUp = False
102. moveDown = True
We also want to check if the event was generated by the player pressing one of the arrow
keys. There is not an ASCII value for every key on the keyboard, such as the arrow keys or
the Esc key. Instead, Pygame provides some constant variables to use instead.
We can check if the player has pressed the left arrow key with the condition:
event.key == K_LEFT . Again, the reason we can use K_LEFT instead of
pygame.locals.K_LEFT is because we imported pygame.locals with the line
Search WWH ::




Custom Search