我是Python的新手,对于什么肯定是一个明显的问题感到遗憾。我希望课程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
答案 0 :(得分:3)
不,但您需要引用一个对象才能访问其方法。由于你永远不会将ball
绑定到任何东西,因此无法调用方法。您是否打算在全球范围内将ball
创建为Ball
的实例?
答案 1 :(得分:3)
现在,您为“Ball”类定义的所有属性和方法都是特定于实例的:为了能够访问它们,您需要
这样的事情: 代码中的某处创建了一个球实例:
ball_1=Ball(game, 0,0)
然后更改您的Paddle的更新方法以接受球实例作为参数:
def update(self,ball):
在任何需要了解球的球拍上调用更新方法时:
my_paddle.update(ball_1)
这样,球拍对象将知道你试图访问的球的y位置。
当然你可以通过多种方式做到这一点,只要你以某种方式将球实例传递给球拍,这样就知道需要什么球来查询它的y位置。
希望这有帮助!
答案 2 :(得分:2)
您需要在任何地方实例化类Ball
,并使此实例可用于Computer_paddle实例。
我建议使用一个处理程序类来组织游戏,并且可以从paddles访问属性。 (或者你也可以继承games
模块的Game-class。)
class GameHandle(object):
def __init__(self):
self.game = games.Game() # or however to create a game instance
self.ball = Ball(self.game, 0, 0)
self.player1 = Human_paddle(self.game, -100, 0, self)
self.player2 = Computer_paddle(self.game, 100, 0, self)
class Paddle(games.Sprite):
def __init__(self, game, x, y, handle):
# ...
self.handle = handle
class Computer_paddle(Paddle):
def update(self):
# ...
ball_y = self.handle.ball.y_position()
# ...