PYGAME two actions with one key press?

Viewed 34

I'm trying to make the player shoot when I press the K_SPACE key and run when I hold it down.

Pseudo code:
   speed = 5
    if key_pressed(pygame.K_SPACE):
         speed += 3
    if key_pressed(pygame.K_SPACE) and speed <=5:
         player shot
2 Answers

You can access the keyboard events in the pygame event loop (pygame.event.get()) or with pygame.key.get_pressed(). You can write a condition, which checks if the space bar got pressed and write as many lines of code after the condition as you want:

if space bar pressed:
    speed += 3
    ...
    if speed <=5:
        player shot
        ...

Using the event loop (active when a key gets pressed):

speed = 5

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.button == pygame.K_SPACE:
            speed += 3
            if speed <= 5:
                player shot
    #if event.type == pygame.KEYUP: # (if needed)

Using pygame.key.get_pressed() (active while you hold a key):

speed = 5
keys_pressed = pygame.key.get_pressed()

if keys_pressed[pygame.K_SPACE]:
    speed += 3
if keys_pressed[pygame.K_SPACE] and speed <= 5:
    player shot

The pygame.eventpygame module for interacting with events and queues queue gets pygame.KEYDOWN and pygame.KEYUP events when the keyboard buttons are pressed and released. Both events have key and mod attributes.

Based on that knowledge I suggest you make it so you cannot shoot again and you keep running until the pygame.KEYUP occurs.

Related