Search code examples
pythonpygamecollisionpong

adding points to player when pong reaches screen boundry


def pong_collision(paddles, pong, size):
    ''' paddles and pong out of bounds collison '''

    for paddle in paddles:
        ends = [0, size[0] - paddle.rect.width]

        # pong|paddle collision
        if paddle.rect.colliderect(pong.rect):
            pong.vel.x = -pong.vel.x
            pong.music.sound.play(loops=0, maxtime=0, fade_ms=0)


        if (ends[1] <= pong.rect.x or pong.rect.x <= ends[0]):
        # pong out of bounds collision

            if pong.rect.x <= ends[0]:
                # add point to right paddle if pong is < 0
                if paddle.side == 'right':
                    paddle.text.value += 1

            if pong.rect.x >= ends[1]:
                # add poitn to left paddle if pong is > screen size
                if paddle.side == 'left':
                    paddle.text.value += 1


            # freezes ball until user starts game
            pong.state = False

            # resets pong position to initial
            pong.rect.topleft = [
                (size[0]-pong.rect.width)/2,
                (size[1]-pong.rect.height)/2
            ]

So i have this pong collision detection above that detects when the ping pong ball reaches the screen's boundary. What's suppose to happen is the player than scores the point gets a point. Then, the ball is paused and reset to the middle of the screen. Everything works fine except for one thing, when the right player scores a point, the point is not added.

I'm confused as to why this happens, clearly the collision detection is the same for both paddles, so why is one not working?


Solution

  • Since you have the for paddle in paddles:, if the ball goes out of bounds it gets reset before it has iterated through both of the paddles, my guess would be that the left paddle is the first in the set of paddles.

    One method to fix this would be to iterate through the paddles when you have determined that the ball is out of bounds to ensure that both paddles are evaluated.