I am attempting to make a ball bounce simulation using the Pygame module in Python 3.7.3. The class I have displays the balls but doesn't work with movement. The error is "local variable x referenced before assignment." I think this means that it is local but needs to be global, however to have the number of balls as a variable (so i can say how many to generate) i don't know how to fix this.
I've tried reading other questions but none have solved my issue. I am able to get a single ball bouncing around the screen with border collision working but not when i make it object oriented. I have also played around with self variables to refer to each individual ball but that didn't work.
class BallEntity():
def __init__(self, radius):
x = random.randint(radius, win_width - radius)
y = random.randint(radius, win_height - radius)
pos = x, y
pygame.draw.circle(win, (248, 24, 148), pos, radius)
dx = random.randint(-5, 5)
dy = random.randint(-5, 5)
BallEntity.movement(self)
def movement(self):
if x <= r1 or x >= win_width - r1:
dx = -dx
elif x > r1 and x < win_width -r1:
x += dx
if y <= r1 or y >= win_height - r1:
dy = -dy
elif self.y > r1 and self.y < win_height -r1:
y += dy
numbBalls = 8
r1 = 8
for i in range(numbBalls):
BallEntity.__init__(i, r1)
I expect the balls to print and move with collision working, but instead I get the error "local variable x referenced before assignment."