What is the idiomatic way of saying to pygame to run something as long as a key is being pressed? With pygame.key.get_pressed()[pygame.K_p]==True or pygame.mouse.get_pressed()==(1,0,0) it seems to react only as the key or the button get strocken. Should one use a while loop for example?
I run the code below and i get print in the shell only upon strocking the key/button:
def main():
done = True
while done:
for i in pygame.event.get():
if pygame.key.get_pressed()[pygame.K_a] == 1:
print "Key a is being pressed..."
elif i.type == KEYDOWN and i.key == pygame.K_q:
done = 0
pygame.display.update()
pygame.quit()
main()
Event KEYDOWN means "key changed state from UP to DOWN" - it doesn't means "key is held pressed all time"

When you start pressing key - it generate event KEYDOWN and pygame.event.get() returns not empty list - and for loop can execute if pygame.event.get()
When you hold key pressed - it doesn't generate event KEYDOWN - and pygame.event.get() returns empty list - and for loop doesn't execute if pygame.event.get()
Your code should looks like
running = True
while running:
# check events
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == pygame.K_q:
running = False
# do it outside of `for event` loop
# it is executed many times
if pygame.key.get_pressed()[pygame.K_a]:
print "Key is hold pressed..."
pygame.display.update()
or - when you need to execute something only once
key_A_pressed = False
running = True
while running:
# check events
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == pygame.K_q:
running = False
elif event.key == pygame.K_a:
key_A_pressed = True
# it is executed only once
print "Key A - start pressing"
if event.type == KEYUP:
if event.key == pygame.K_a:
key_A_pressed = False
# it is executed only once
print "Key A - stop pressing"
# do it only once - outside of `for event` loop
# it is executed many times
#if pygame.key.get_pressed()[pygame.K_a]:
# or
if key_A_pressed:
print "Key A is held pressed..."
pygame.display.update()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With