How can I create multiple rect objects?

Viewed 42

I am trying to make a block spawner like thingy in pygame. I've used lists to store x and y variables, but I can't make rects with these without using variables like rect1, rect2 ... How can I use lists or something else to have infinite amounts of rects?

My code is looking like that:

import pygame
from pygame.locals import *

screen = pygame.display.set_mode((800,600))

kares = []
karx = [0]
kary = [0]

karposx = 0
karposy = 0

k = 0

running = True
while running:

    # screen.fill((0,0,0))
    if k == 1:
        karx[0] = pygame.mouse.get_pos()[0]
        
        for i in range(len(karx)):
            a = [karx[i], kary[i]]
            kares.append(a)
        
        for i in kares:
            karposx = i[0]
            karposy = i[1]
            
        print(kares)
        k+=1
        
    rect1 = pygame.Rect(karposx,200,64,64)

        
    # for i in kares:
    #     kares[i][1] -= 1
        
        
        
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                k += 1
            
    if k >= 2:
        k = 0        
    
    if k == 1:
        pygame.draw.rect(screen, (255,0,0), rect1)
    pygame.display.update()
    

Output

1 Answers

You have to create a list of rectangles. Create rectangles and add them to the list:

rect = pygame.Rect(x, 200, 64, 64)
rects.append(rect)

Draw the rectangles in a loop:

for rect in rects:
    pygame.draw.rect(screen, (255,0,0), rect)

Minimal example based on your code:

import pygame
from pygame.locals import *

screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()

rects = []

running = True
while running:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == MOUSEBUTTONDOWN:
            if event.button == 3:
                x, _ = event.pos
                x = (x // 64) * 64
                if not any(r for r in rects if r.x == x):
                    rect = pygame.Rect(x, 200, 64, 64)
                    rects.append(rect)
                    print(len(rects))

    screen.fill((0,0,0))
    for rect in rects:
        pygame.draw.rect(screen, (255,0,0), rect)
    pygame.display.update()

pygame.quit()
Related