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.