Key events
Syntax
for |
e |
in |
event. |
get() |
if e.type |
== |
KEYDOWN |
: |
|
if e.key |
== |
K_a |
: |
The event loop in pygame is a common feature of 99% of all pygame projects and as such, is one which you must master. It will always be found in the game loop and takes the form of a for loop. Regardless of the type of event you wish to manage, the loop will always have the same structure. When dealing with keys it is important to remember that this responds to events rather than waits for them.
Some sample code to try –
from pygame import *
init()
# we only need a screen to get access to the events!
screen = display.set_mode((640, 480))
display.set_caption('The amazing key presser!')
endProgram = False
while not endProgram:
# pygame event loop
for e in event.get():
if e.type == KEYDOWN:
if (e.key == K_a):
print "A was pressed"
elif (e.key == K_b):
print "B was pressed"
elif (e.key == K_RETURN):
print "return was pressed"
elif e.key == K_ESCAPE:
endProgram = True
else:
print "errorz - wrong key"
Helpful links
http://www.pygame.org/docs/ref/event.html – Types of events
http://www.pygame.org/docs/ref/key.html – Key codes used in pygame
http://openbookproject.net/thinkcs/python/english3e/pygame.html – Pygame game loop











