2011-08-21 7 views
2

저는 파이썬에 대해 매우 새로운 지식을 가지고 있습니다. 분명히 분명한 질문이 될 것입니다. 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 
+3

StackOverflow에 오신 것을 환영합니다. 나는 당신의 질문을 형식화했다. (코드를 선택하고 툴바에있는'{}'버튼을 사용하여 다음 질문을 할 수있다.) 또한 문제와 관련없는 많은 코드가 있습니다. 문제가 있음을 입증하는 데 필요한 최소한의 코드로 줄여보십시오. 행운을 빕니다! – Johnsyweb

답변

3

아니요,하지만 메소드에 액세스하려면 객체에 대한 참조가 필요합니다. ball을 결코 바인딩하지 않기 때문에 메소드를 호출 할 객체가 없습니다. 글로벌 레벨에서 을 Ball의 인스턴스로 생성 하시겠습니까?

2

Ball 클래스를 인스턴스화하고이 인스턴스를 Computer_paddle 인스턴스에 사용할 수 있도록해야합니다.

게임을 구성하고 패들에서 액세스 할 수있는 특성을 가진 처리기 클래스를 제안합니다. (또는 당신은 또한 games 모듈의 게임 클래스를 서브 클래스 수 있습니다.)

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() 

     # ... 
3

을 지금 모든 속성과 당신이 "볼"클래스에 정의 된 메소드는 인스턴스가 특정 : 그들을 당신이 할에 액세스 할 수 있도록 패들에을의 지식이 필요 인스턴스를 그 볼 예를을 통과 공 인스턴스 다음

  • 을 만들

    • 필요3210

    그래서 이런 식으로 뭔가 :

    ball_1=Ball(game, 0,0) 
    

    그런 다음 매개 변수로 볼 인스턴스를 허용하도록 패들의 업데이트 방법을 변경 : 코드에 어딘가에 볼 인스턴스 생성

    def update(self,ball): 
    

    을 그리고 공에 대해 알 필요가있는 패들의 업데이트 메서드를 호출 할 때 :

    my_paddle.update(ball_1) 
    

    이렇게하면 패들 오브젝트가 어떤 공의 y 위치에 액세스하려고하는지 알 수 있습니다. 그것은 그것의 y 위치를 조회 할 필요가 무엇 공을 알 수 있도록 어떻게 든 패들에 공 인스턴스를 통과

    물론 당신이 한,이 서로 다른 여러 가지 방법으로 할 수 있습니다.

    희망이 도움이됩니다.

  • +0

    불명확 한 것으로 여겨지면 죄송합니다. 나는 update 메소드를 직접 호출하지 않고 games.screen.mainloop()을 사용한다.따라서 TypeError는 "update()가 정확히 2 개의 위치 인수 (주어진 1 개)"를 취하고 update()에 두 개의 인수를 전달하는 방법을 알지 못한다고 말합니다. – Matt

    +0

    그러면 games.screen.mainloop() 코드를 게시 할 수 있습니까? 또는 ar 같은 라이브러리를 사용하고 있습니까? –

    관련 문제