How to get keyboard input in pygame?
You can get the events from pygame and then watch out for the KEYDOWN
event, instead of looking at the keys returned by get_pressed()
(which gives you keys that are currently pressed down, whereas the KEYDOWN
event shows you which keys were pressed down on that frame).
What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
location -= 1
if event.key == pygame.K_RIGHT:
location += 1
To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.
move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if move_ticker == 0:
move_ticker = 10
location -= 1
if location == -1:
location = 0
if keys[K_RIGHT]:
if move_ticker == 0:
move_ticker = 10
location+=1
if location == 5:
location = 4
Then somewhere during the game loop you would do something like this:
if move_ticker > 0:
move_ticker -= 1
This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)
How to detect a key-press with pygame?
pygame.K_w
is not an event type, but a key. You need to verify that the event type is pygame.KEYDOWN
and the key is pygame.K_w
:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key== pygame.K_w:
# [...]
The keyboard events KEYDOWN
and KEYUP
(see pygame.event module) create a pygame.event.Event
object with additional attributes. The key that was pressed can be obtained from the key
attribute (e.g. K_RETURN
, K_a
) and the mod
attribute contains a bitset with additional modifiers (e.g. KMOD_LSHIFT
). The unicode
attribute provides the Unicode representation of the keyboard input.
Getting Pygame keyboard input and check if it's a number
pygame.key.get_pressed()
returns a list with the state of all keyboard buttons. This is not intended to get the key of a keyboard event. The key that was pressed can be obtained from the key
attribute of the pygame.event.Event
object:
if event.type == pg.KEYDOWN:
if event.key == pg.K_a:
# [...]
unicode
contains a single character string that is the fully translated character:
if event.type == pg.KEYDOWN:
if event.unicode == 'a':
# [...]
See also pygame.key.
How do I check for two keyboard keys being pressed at the same time with pygame?
Use pygame.key.get_pressed()
to get the state of all keyboard buttons.
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and keys[pygame.K_ESCAPE]:
# [...]
Check the state of the keys when the KEYDOWN
event occurs on one of the keys (a or ESC):
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a or event.key == pygame.K_ESCAPE: # <--- or
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and keys[pygame.K_ESCAPE]:
print("a and ESC")
The same combined in a single condition:
event_list = pygame.event.get()
keys = pygame.key.get_pressed()
for event in event_list:
# [...]
if event.type == pygame.KEYDOWN and \
((event.key == pygame.K_a and keys[pygame.K_ESCAPE]) or \
(event.key == pygame.K_ESCAPE and keys[pygame.K_a])):
print("a and ESC")
Note: pygame.event.get()
must be called before pygame.key.get_pressed()
, since the states of the keys returned by pygame.event.get()
are set when the events are evaluated.
Related Topics
Importerror: Dll Load Failed: %1 Is Not a Valid Win32 Application. But the Dll's Are There
Pandas: Drop Consecutive Duplicates
Why Python 3.6.1 Throws Attributeerror: Module 'Enum' Has No Attribute 'Intflag'
Is It Pythonic: Naming Lambdas
Pandas Read_Csv: Low_Memory and Dtype Options
Python List VS. Array - When to Use
How to Manage Local VS Production Settings in Django
What Is the Purpose of the -M Switch
How to Check If a String Contains an Element from a List in Python
Adding Days to a Date in Python
String Concatenation of Two Pandas Columns
How to Get Monitor Resolution in Python
How to Convert Each Item in the List to String, for the Purpose of Joining Them
Non-Alphanumeric List Order from Os.Listdir()