I am making a game in which you move a character with the arrow keys on the keyboard. Since my laptop sometimes think that I pressed a key twice i wanted to make sure that the program waited until I released the pressed key. I use the key.get_pressed() method. The problem is that when I press a key, the action is executed, but the loop waiting for the keys to be released keeps running because the get_pressed() event thinks that i still pressed the button. Here is the code:
while ChangeRun == False: # main game loop
for Event in pygame.event.get():
if Event == QUIT:
pygame.quit()
sys.exit()
BUTTON = -1
if pygame.key.get_pressed()[K_UP]:
BUTTON = 0
elif pygame.key.get_pressed()[K_DOWN]:
BUTTON = 1
elif pygame.key.get_pressed()[K_RIGHT]:
BUTTON = 2
elif pygame.key.get_pressed()[K_LEFT]:
BUTTON = 3
elif pygame.key.get_pressed()[K_p]:
BUTTON = 4
elif pygame.key.get_pressed()[K_RETURN]:
BUTTON = 5
if BUTTON == 4 or BUTTON == 5:
Execute()
elif BUTTON != -1:
SetDirection()
DisplaySurface() # Displays all data on screen
# it works until these rows:
while pygame.key.get_pressed()[K_UP] or pygame.key.get_pressed()[K_DOWN] or pygame.key.get_pressed()[K_LEFT] or pygame.key.get_pressed()[K_RIGHT] or pygame.key.get_pressed()[K_p] or pygame.key.get_pressed()[K_RETURN]:
pass # Keeps running because the get_pressed() method thinks one of the buttons is still pressed...
I checked what was wrong by printing all get_pressed() values.
It showed that the button I pressed keeps returning true, even when i released it.
I hope it's clear and that someone could help.
for Event in pygame.event.geta lot easier to me, but i agree with Dominic, you set the Button to-1each time through, so should work. - KodyVanRy