-1

Im creating a game which i use multiple files and the code below is the file which i have the sprites, 2 classes Player() which stands for a puddle, and a ball Ball()

so i want to somehow(i dont know maybe inherit from player class but couldnt do anything with that) have control of the edges of the puddle i created at Player() in class Ball()so as to make the ball bounce when it is between the edges of the puddle from Player() and when the ball is: >= 560 pixels

class Player(pg.sprite.Sprite):

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((130,20))
        self.image.fill(black)
        self.rect = self.image.get_rect()
        self.rect.centerx = width/2
        self.rect.y = 560

    def update(self):
        self.vx = 0
        keys = pg.key.get_pressed()

        if keys[pg.K_LEFT]:
            self.vx = -15
        if keys[pg.K_RIGHT]:
            self.vx = 15
        if self.rect.left <= 0:
            self.rect.left = 0
        if self.rect.right >= width:
            self.rect.right = width

        self.rect.x += self.vx


class Ball(pg.sprite.Sprite):

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((10,10))
        self.image.fill(black)
        self.rect = self.image.get_rect()
        self.rect.centerx = width / 2
        self.rect.centery = height / 2
        self.vx = -4
        self.vy = 10

    def update(self):
        if self.rect.y >= 560:# and... how do i declare the puddle here???
            self.vy = -self.vy
        if self.rect.top <= 0:
            self.vy = -self.vy
        if self.rect.right <= 0:
            self.vx = -self.vx
        if self.rect.left >= width:
            self.vx = -self.vx

        self.rect.x += self.vx
        self.rect.y += self.vy
Aris
  • 75
  • 6

1 Answers1

1

You can use paddle.rect.colliderect(ball.rect) to test for a collision between ball and paddle. You will need to move the ball out of the collision area afterwards though.

marienbad
  • 1,461
  • 1
  • 9
  • 19