저는 파이썬에 대해 매우 새로운 지식을 가지고 있습니다. 분명히 분명한 질문이 될 것입니다. Computer_paddle
클래스는 Ball
함수를 호출하여 y_position()
을 호출하고 반환 값을 얻을 수 있기를 바랍니다. 하지만 그 말을하지 않는 것 같습니다 :파이썬에서 다른 클래스의 함수에 접근하기
"global name 'ball' is not defined".
다른 함수 내에서 함수를 호출하기 위해 필요한 특별한 것이 있습니까?
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
StackOverflow에 오신 것을 환영합니다. 나는 당신의 질문을 형식화했다. (코드를 선택하고 툴바에있는'{}'버튼을 사용하여 다음 질문을 할 수있다.) 또한 문제와 관련없는 많은 코드가 있습니다. 문제가 있음을 입증하는 데 필요한 최소한의 코드로 줄여보십시오. 행운을 빕니다! – Johnsyweb