Is there an easier way to get keyboard input in Pygame than specifying each individual key? For instance,
if event.key == pygame.K_a:
command = command + "a"
elif event.key == pygame.K_b:
command = command + "b"
elif event.key == pygame.K_c:
command = command + "c"
Is there some way to use a function to do this for me?
If an entirely different action is necessary for each key, then there isn't really a better way. If multiple keys result in similar actions, where say a single function f
could take the key as an argument, you could use an in
expression like so:
if event.key in (pygame.K_a, pygame.K_b, pygame.K_c):
f(event.key)
An in
expression evaluates to True
if what's on the left side is contained within what's on the right side. So, with that code if the key pressed is 'a', 'b', or 'c,' the function f
will be called with the key as an argument.
As a practical example, say you want either the 'Esc' or 'q' key to quit the program. You could accomplish that this way:
if event.key in (pygame.K_ESCAPE, pygame.K_q):
pygame.quit()
The above code is effectively the same as:
if event.key == pygame.K_ESCAPE:
pygame.quit()
elif event.key == pygame.K_q:
pygame.quit()
From a comment, command
is a string that is concatenated to. If say you wanted to add any key a-z that was pressed to command
, you could do this:
if event.key in range(pygame.K_a, pygame.K_z + 1):
command += event.unicode