Marc0_H
Marc0_H

Reputation: 29

Python - How to get information/use functions from other classes before I defined them?

I'm a beginner in python and I enjoy coding in the pygame module. I've been trying to create pong to learn OOP better but I've been running into some problems. For example a basic pong game I tried to make:

import pygame
...
Class Ball:
      def __init__(self,x,y,width,height):
         ...
      def check_collide(self):
          self.ball_rect.collide(paddle_left.get_rect())

Class Player:
      def __init__(self,x,y,w,h):
          ...
      def get_rect():
          return self.player_rect
 
def main():
    ball = Ball(400,400,20,20)
    paddle_left = Player(20,300, 10, 100)
    
    while True:
         draw()
         ...
main()

In the first class I tried to get the current position of the left_paddle, but obviously that gives me an error. How do you get information or use functions from other classes when they haven't been defined yet? What would be a better way to approach this?

Upvotes: 1

Views: 54

Answers (1)

Rabbid76
Rabbid76

Reputation: 210998

You have to pass an object instance to the method:

class Ball:
      def __init__(self,x,y,width,height):
         # [...]

      def check_collide_paddle(self, paddle):
          return self.ball_rect.collide(paddle.get_rect())
def main():
    ball = Ball(400,400,20,20)
    paddle_left = Player(20,300, 10, 100)
    paddle_right = Player(...)
    
    while True:
         # [...]

         if ball.check_collide_paddle(paddle_left):
             # [...]

         if ball.check_collide_paddle(paddle_right):
             # [...]

Upvotes: 1

Related Questions