I'm very new to Python, so sorry about what will surely be an obvious question. I want the class Computer_paddle to be able to call Ball's function, y_position(), and get the return value. But it doesn't seem to be doing that, telling me:
"global name 'ball' is not defined".
Is there something special I need to do to call a function within another function?
class Ball(games.Sprite):
""" A ball that bounces off walls and paddles. """
image = games.load_image("ball.png")
def __init__(self, game, x, y):
""" Initialise ball sprite. """
super(Ball, self).__init__(image = Ball.image,
x = x, y = y,
dx = -3, dy = 0)
def update(self):
"""Check if ball has hit paddle or wall, and then bounce that ball. """
super(Ball, self).update()
# check if ball overlaps paddles
if self.overlapping_sprites:
self.dx = -self.dx
self.dy += random.randint(-1, 1)
# check if ball hits a wall
if self.top < 0 or self.bottom > games.screen.height:
self.dy = -self.dy
if self.left < 0 or self.right > games.screen.width:
self.dx = -self.dx
def y_position(self):
return self.y
class Paddle(games.Sprite):
""" A paddle that can only partly leave the screen. """
image = games.load_image("paddle.png")
def __init__(self, game, x, y):
""" Initialise paddle sprite."""
super(Paddle, self).__init__(image = Paddle.image, x = x, y = y)
def update(self):
""" Prevent sprite from completely leaving the screen. """
if self.top < -33:
self.top = -33
if self.bottom > games.screen.height + 33:
self.bottom = games.screen.height + 33
class Human_paddle(Paddle):
""" A paddle controlled by the player. """
def update(self):
""" Move paddle to mouse position. """
super(Human_paddle, self).update()
self.y = games.mouse.y
class Computer_paddle(Paddle):
""" A paddle controlled by the computer. """
MAX_SPEED = 1
def update(self):
""" Move paddle towards ball's position on Y-axis. """
super(Computer_paddle, self).update()
ball_y = ball.y_position()
if ball_y > self.y:
self.y += MAX_SPEED
if ball_y < self.y:
self.y -= MAX_SPEED
{}button in the toolbar). Also, there's a lot of code here that's not relevant to your problem, please try to reduce your code to the bare minimum required to demonstrate the issue you are having. Good luck!