How to set the condition execution step

Viewed 43

How to set the condition execution step so that the execution of the action when SPACE is pressed is not continuous?

keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
    print("spacebar is pressed")
    new_bullet = Bullet(screen, gun)
    bullets.add(new_bullet)
1 Answers

See How to get keyboard input in pygame? and How do I stop more than 1 bullet firing at once?. You have to use the keyboard events instead of pygame.key.get_pressed().

pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.

# application loop
while run:

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame. K_SPACE:
                # [...]

    # [...]

An alternative method is to lock the key with a Boolean variable:

space_pressed = False

# application loop
while run:

    keys = pygame.key.get_pressed()
    
    if keys[pygame.K_SPACE]:
        if not space_pressed:
            space_pressed = True
            new_bullet = Bullet(screen, gun)
            bullets.add(new_bullet) 
    else:
        space_pressed = False
Related