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 do I use keyboard inputs in pygame?
pygame.draw.circle
returns the bounding rectangle (pygame.Rect
object) of the circle. However the center of the circle is always (x
, y
). Therefore you need to change x
instead of character.x
:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_LEFT]:
x -= 1
if keyPressed[pygame.K_RIGHT]:
x += 1
This code can even be simplified:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
x += (keyPressed[pygame.K_RIGHT] - keyPressed[pygame.K_LEFT])
How to get a variable keyboard input in pygame?
Get the KEYDOWN
event and evaluate the .unicode
attribute of the event (see event). Note, since your characters are capital letters, you have to get the lower case character form random_letter
:
def mainLoop():
# [...]
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
y_moved = 7
if event.type == pygame.KEYDOWN:
if event.unicode == random_letter.lower():
print("correct")
# [...]
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.
Easier way of getting keyboard input in Pygame?
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()
Edit
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
Related Topics
How to Print Without a Newline or Space
Are Dictionaries Ordered in Python 3.6+
How to Remove Duplicates from a List, While Preserving Order
Is There a Difference Between "==" and "Is"
How to Count the Occurrences of a List Item
Is There a Built in Function For String Natural Sort
How to Make Function Decorators and Chain Them Together
What Do Lambda Function Closures Capture
Iterating Over Dictionaries Using 'For' Loops
Convert Columns into Rows With Pandas
Input() Error - Nameerror: Name '...' Is Not Defined
How to Generate All Permutations of a List
Why Does Append() Always Return None in Python
Difference Between Re.Search and Re.Match