Increase a variable just by one when a key is pressed

Viewed 580

I have a variable state counter which I want to decrease by one, when a key a is pressed and increase by one when a d key is pressed.

I took an inspiration in question: Increase just by one when a key is pressed, but my code did not work as expected, when I reset the was_pressed variable to false the state counter began to increase itself.

running = True
state_counter = 0
number_of_states = 0
was_pressed = False

import pygame

while running:
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
        # The user closed the window or pressed escape
        running = False

        if event.type == KEYDOWN and event.key==K_a:
            if not was_pressed:
                state_counter -= 1
                print("state_counter %d times"%state_counter)
                was_pressed = True
            else:
                was_pressed = False

        elif event.type == KEYDOWN and event.key == K_d:
            if not was_pressed:
                state_counter += 1
                print("state_counter %d times"%state_counter)
                was_pressed = True
            else:
                was_pressed = False
pygame.quit()
print('Done!, state counter is: ', state_counter)

The problem is that I need the variable both increment and decrement (thats the difference from the mentioned question) and of course I need the variable to change each and every time I press the key (which is probably the case of the previous question as well but I could not achieve that). I also cannot us time.sleep() because I don't want the program to sleep.

Any help appreciated, thank you very much in advance.

2 Answers

The KEYDOWN event occurs only once when the key is pressed. It doesn't appear continuously when the key is hold. So there is no need of a was_pressed state:

while running:
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
            # The user closed the window or pressed escape
            running = False

        if event.type == KEYDOWN and event.key==K_a:
            state_counter -= 1
            print("state_counter %d times"%state_counter)

        elif event.type == KEYDOWN and event.key == K_d:
            state_counter += 1
            print("state_counter %d times"%state_counter)
import pyautogui
import pygame
Number_of_Presses = 0
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
       if event.key == pygame.K_a:
            Number_of_Presses -= 1
            print (Number_of_Presses)
    if event.type == pygame.KEYDOWN:
       if event.key == pygame.K_d:
            Number_of_Presses += 1
            print (Number_of_Presses)
Related