I'm making a Breakout in Pygame, but, to add some challenge, I want the ball to be bouncing in a random but still logic way. For example : If the ball goes both up (y) and right (x), if it bounces on a brick, it will not simply revert its y direction nor go back the left side of the screen it came from (which wouldn't make sewnse), but it will have a new, random direction and speed, so it is not too predictable or repetitive and gets boring (I hope I made this clear enough :p).
class Ball(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([10, 10])
self.image.fill(white)
self.rect = self.image.get_rect()
self.speed_x = 1
self.speed_y = 1
self.direction = [random.randint(0, 1), random.randint(0, 1)]
self.lives = 5
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
# Wall and Paddle Bounces
if self.rect.y > 500:
self.lives -= 1
pong.rect.x = 375
pong.rect.y = 320
if self.rect.y < 1:
self.speed_y = 1
if self.rect.x > 740:
self.speed_x = -1
if self.rect.x < 1:
self.speed_x = 1
if self.rect.colliderect(paddle1.rect):
self.speed_y *= -1
for brick in brick_list :
if pong.rect.colliderect(brick.rect) :
self.speed_y *= -1
brick_list.remove(brick)
I tried various methods (like simply randoming self.speed_x and self.speed_y, but everytime, the ball gets stuck or has a really weird behavior. Any explanation / solution ?