How Do I Randomize Where My Ball Collides With The Paddle? Pong Pygame

Viewed 60

so I was wondering how I could randomize where my ball collides with the paddle instead of just going on the same direction video the ball is just looping throw the same direction

    if ball1.rect.colliderect(playerman) or ball1.rect.colliderect(playerman2):
        ball1.velx *= -1

this is my balls movement


    ball1.x += ball1.velx
    ball1.y += ball1.yvel
    if ball1.x <= 0 or ball1.x >= height:
        ball1.velx *= -1
    if ball1.y <= 0 or ball1.y >= width:
        ball1.yvel *= -1
    ball1.rect.x = ball1.x
    ball1.rect.y = ball1.y


and its class:


class ball:
    def __init__(self,x,y,height,width,color):
        self.x =x
        self.y = y
        self.height = height
        self.width  = width
        self.color = color
        self.velx = 5
        self.yvel = 5
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.circle(window, self.color, self.rect.center,10)


ball1 = ball(290,200,20,20,white)



1 Answers

One possibility to get some randomness, is to slightly change yvel when the ball hits a paddle. Compute a random value in a certain range (e.g. random.randint(-3, 3)) and add it to yvel. Ensure that the amount of yvel is always less than the amount of velx:

if ball1.rect.colliderect(playerman) or ball1.rect.colliderect(playerman2):
    ball1.velx *= -1

    vel_change = random.randint(-3, 3)

    ball1.velx += vel_change
    ball1.velx = max(-abs(ball1.yvel), min(abs(ball1.yvel), ball1.velx))

If you use floating point values then use random.uniform() rather than random.randint():

vel_change = random.randint(-3, 3)

vel_change = random.uniform(-3, 3)
Related