Reputation: 51
So I have this problem of the code within the function not recognizing the keystrokes of my UP, DOWN, LEFT and DOWN keys and I wonder why. Can't seem to fix this. I need this to work somehow so i can use the same code in another part of the program I'm coding.
def movementVariables():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
#testkey
#if event.key == K_SPACE:
if event.key == K_LEFT:
moveRight = False
moveLeft = True
if event.key == K_RIGHT:
moveRight = True
moveLeft = False
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == K_DOWN:
moveDown = True
moveUp = False
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT:
moveLeft = False
if event.key == K_RIGHT:
moveRight = False
if event.key == K_UP:
moveUp = False
if event.key == K_DOWN:
moveDown = False
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 400
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVE_SPEED = 0
levelOne = True
while levelOne == True:
if moveDown and player.bottom < WINDOW_HEIGHT:
player.top += MOVE_SPEED
if moveUp and player.top > 0:
player.top -= MOVE_SPEED
if moveLeft and player.left > 0:
player.left -= MOVE_SPEED
if moveRight and player.right < WINDOW_WIDTH:
player.right += MOVE_SPEED
I tried to post as little code as possible so I don't overflow with useless code. Just type if you need the whole code.
Upvotes: 0
Views: 78
Reputation: 122032
moveUp
, moveDown
etc are local variables in your function movementVariables
, and they are assigned during the function then abandoned when it finishes. You need to use the outer scope variables explicitly:
def movementVariables():
global moveUp
global moveDown
global moveLeft
global moveRight
Or, better, actually return
and use something from the function:
def movementVariables():
...
return movement
Upvotes: 3