1

I want to add multiple rectangles to this collision simulation, I am not familiarized with OOP which I know is the best solution for this problem in order not to have same code repeated. Here is my code so far:

import pygame, sys

def bouncing_rect():
    global x_speed, y_speed, other_speed
    
    moving_rect.x += x_speed
    moving_rect.y += y_speed
    #collision with border of screen:
    if moving_rect.right >= screen_width or moving_rect.left <= 0:
        x_speed = - x_speed
    if moving_rect.bottom >= screen_height or moving_rect.top <= 0:
        y_speed = - y_speed        

    # moving the other rect:
    other_rect.y += other_speed
    if other_rect.top <= 0 or other_rect.bottom >= screen_height:
        other_speed = - other_speed

    #collision with other rect:
    collision_tolerance = 10
    if moving_rect.colliderect(other_rect):
        if abs(other_rect.top - moving_rect.bottom) < collision_tolerance and y_speed > 0:
            y_speed = - y_speed
        if abs(other_rect.bottom - moving_rect.top) < collision_tolerance and y_speed < 0:
            y_speed = - y_speed
        if abs(other_rect.right - moving_rect.left) < collision_tolerance and x_speed < 0:
            x_speed = - x_speed
        if abs(other_rect.left - moving_rect.right) < collision_tolerance and x_speed > 0:
            x_speed = - x_speed
    
    pygame.draw.rect(screen, (255,255,255), moving_rect)
    pygame.draw.rect(screen, (255,0,0), other_rect)

pygame.init()
clock = pygame.time.Clock()
screen_width, screen_height = 800,800
screen = pygame.display.set_mode((screen_width, screen_height))

moving_rect = pygame.Rect(50,50,50,50) #(left, top, width, height)
x_speed, y_speed = 5,4

other_rect = pygame.Rect(300,600,200,100)
other_speed = 2

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()


    screen.fill((30,30,30))
    bouncing_rect()
    pygame.display.flip()
    clock.tick(60)

it's not using OOP yet.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
mac179
  • 1,540
  • 1
  • 14
  • 24

1 Answers1

1

Create a list of rectangles:

other_rect_list = [other_rect1, other_rect2, other_rect3] 

Use collidelist() o find the index of the 1st rectangle in the list that collides with a rectangle:

index = moving_rect.collidelist(other_rect_list)
if index >= 0:
    other_rect = other_rect_list[index]
    # [...]

Alternatively, you can use collidelistall() to get a list of the indexes of all colliding rectangles:

index_list = moving_rect.collidelistall(other_rect_list)
for index in index_list:
    other_rect = other_rect_list[index]
    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174