Reputation: 23
I can't figure out how to correctly track key-down events in PyGame. Whenever I try to increase the player's coordinates plx
or ply
, it doesn't work and it prints the same over and over!
import pygame, sys
from pygame.locals import *
global plx
global ply
plx = 0
ply = 0
DISPLAYSURF = pygame.display.set_mode((1, 1))
pygame.display.set_caption('Text Only Jam')
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if pygame.K_LEFT:
plx -= 1
print(plx)
if pygame.K_RIGHT:
plx += 1
print(plx)
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
And, here is the output:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
-1
0
-1
0
-1
0
I have also tried setting the variables in other ways, and I still can't get it to work. I have used some basic match like this before, so I don't know what to do. Any help is appreciated!
Upvotes: 2
Views: 101
Reputation: 823
After inspecting the output: -1, then 0, -1, then 0; it seems that plx -= 1
is first executed then plx += 1
gets executed right away. That means, both statements get executed every time, indicating that the conditions are wrong. That said, replace part of your code with this code:
if event.key == pygame.K_LEFT:
plx -= 1
print(plx)
if event.key == pygame.K_RIGHT:
plx += 1
print(plx)
Why? pygame.K_LEFT
and pygame.K_RIGHT
are values, so they evaluate to True
every time. The correct condition for checking the pressed key should be event.key == <KEY>
.
Upvotes: 4