#Weird python error

7 messages · Page 1 of 1 (latest)

lucid stratus
#
import pygame

pygame.init()
screen = pygame.display.set_mode((1024, 512))
clock = pygame.time.Clock()
running = True
px = 0
py = 0

def drawPlayer():
    pygame.draw.circle(screen, (60,60,230), (px,py), 5)

def handleKeys():
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        py -= 20
    if keys[pygame.K_s]:
        py += 20
    if keys[pygame.K_a]:
        px -= 20
    if keys[pygame.K_d]:
        py += 0

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0,0,0))

    handleKeys()
    drawPlayer()

    pygame.display.flip()

    clock.tick(60)

pygame.quit()
Traceback (most recent call last):
  File "/home/xtagz/PycharmProjects/TagEngine/main.py", line 31, in <module>
    handleKeys()
  File "/home/xtagz/PycharmProjects/TagEngine/main.py", line 18, in handleKeys
    py += 20
UnboundLocalError: local variable 'py' referenced before assignment

How is it fine in drawPlayer but not in handleKeys ?

muted lotus
#

@lucid stratus

#

It is saying that you are using the variable without it being register

#
import pygame

pygame.init()
screen = pygame.display.set_mode((1024, 512))
clock = pygame.time.Clock()
running = True
px = 0
py = 0

def drawPlayer():
    pygame.draw.circle(screen, (60,60,230), (px,py), 5)

def handleKeys():
    global py, px
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        py -= 20
    if keys[pygame.K_s]:
        py += 20
    if keys[pygame.K_a]:
        px -= 20
    if keys[pygame.K_d]:
        py += 0

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0,0,0))

    handleKeys()
    drawPlayer()

    pygame.display.flip()

    clock.tick(60)

pygame.quit()
#

It should fix the errors

modern dune
#

oh god no, global variables are the gateway to spaghetti code, either include them as arguments to the function instead or make a class

grand grail
#

You should do not write 'px' and 'py'