Salem
Salem

Reputation: 255

How can i draw rectangles in multiple rows and columns in pygame?

I'm trying to make the Brick Breakout game. However, I'm having a problem drawing the bricks. I actually can draw them all, but I'm looking for a professional way to do it in order to use less code lines. Here is some of my code, but it's useless:

pygame.draw.rect(screen1, brick_colors[b], (x1, y1, 60, 12))
pygame.draw.rect(screen1, brick_colors[b], (x2, y1, 60, 12))
pygame.draw.rect(screen1, brick_colors[b], (x3, y1, 60, 12))
pygame.draw.rect(screen1, brick_colors[b], (x4, y1, 60, 12))
pygame.draw.rect(screen1, brick_colors[b], (x5, y1, 60, 12))
pygame.draw.rect(screen1, brick_colors[b], (x6, y1, 60, 12))
pygame.draw.rect(screen1, brick_colors[b], (x7, y1, 60, 12))
pygame.draw.rect(screen1, brick_colors[b], (x8, y1, 60, 12))

So, is there a method using the for loop for example to do the work? Note: the bricks should be 8 lines and 8 per line.

Upvotes: 1

Views: 1181

Answers (1)

Rabbid76
Rabbid76

Reputation: 210997

Use nested loops:

no_of_rows = 8
no_of_cols = 8

x0, y0 = 20, 20    # just for example
dx, dy = 70, 16    # just for example

for row in range(no_of_rows):
    for col in range(no_of_cols):
        pygame.draw.rect(screen1, brick_colors[b], (x0 + col*dx, y0 + row*dy, 60, 12))

I recommend making a list of the block locations and drawing the block rectangles from the locations in the list. If a block is destroyed, all you have to do is remove the location from the list:

blocks = []
for row in range(no_of_rows):
    for col in range(no_of_cols):
        blocks.append((x0 + col*dx, y0 + row*dy))
for pos in blocks:
    pygame.draw.rect(screen1, brick_colors[b], (pos[0], pos[1], 60, 12))

This can be further improved by using pygame.Rect objects:

blocks = []
for row in range(no_of_rows):
    for col in range(no_of_cols):
        rect = pygame.Rect(x0 + col*dx, y0 + row*dy, 60, 12)
        blocks.append(rect )
for rect in blocks:
    pygame.draw.rect(screen1, brick_colors[b], rect )

If you want to draw checkered tiles overall the screen, the draw the tiles on a background surface before the application loop and blit the background surface on the screen in the application loop for best performance.

import pygame

screen = pygame.display.set_mode([500, 500]) 
clock = pygame.time.Clock() 

background = pygame.Surface(screen.get_size())
color1 = (64, 64, 128)
color2 = (196, 128, 64)
sx, sy = 50, 50
for i in range((screen.get_width() + sx -1) // sx):
    for j in range((screen.get_height() +sy - 1) // sy):
        c = color1 if (i+j) % 2 == 0 else color2
        pygame.draw.rect(background, c, (i*sx, j*sy, sx, sy))   

run = True 
while run:  
    clock.tick(100)
    for event in pygame.event.get():         
        if event.type == pygame.QUIT:             
            run = False      

    screen.blit(background, (0, 0))     

    pygame.display.update()

pygame.quit()

Upvotes: 2

Related Questions