using colliderect in an array of random coordinates

Use collidelist() to test test if one rectangle in a list intersects:

for i in self.imagenes1_array:
    s = pygame.image.load(i)
    self.images.append(s)
    r = s.get_rect()
    
    position_set = False 
    while not position_set:
        r.x = random.randint(300,1000)
        r.y = random.randint(200,700)    
        
        margin = 10
        rl = [rect.inflate(margin*2, margin*2) for rect in self.rects]
        if len(self.rects) == 0 or r.collidelist(rl) < 0:
            self.rects.append(r)
            position_set = True

See the minimal example, that uses the algorithm to generate random not overlapping rectangles:

import pygame
import random

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

def new_recs(rects):
    rects.clear()
    for _ in range(10):
        r = pygame.Rect(0, 0, random.randint(30, 40), random.randint(30, 50))
        
        position_set = False 
        while not position_set:
            r.x = random.randint(10, 340)
            r.y = random.randint(10, 340)    
            
            margin = 10
            rl = [rect.inflate(margin*2, margin*2) for rect in rects]
            if len(rects) == 0 or r.collidelist(rl) < 0:
                rects.append(r)
                position_set = True
rects = []
new_recs(rects)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
            new_recs(rects)          

    window.fill(0)
    for r in rects:
        pygame.draw.rect(window, (255, 0, 0), r)
    pygame.display.flip()

pygame.quit()
exit()

Leave a Comment