These are the bricks I have made for my game. Stack Overflow is not letting me put all of my bricks so these are 1/3 of them. The total amount is 60 (3 rows of 20).
#Bricks
pygame.draw.rect(screen, (blue), (0,65,40,20), 0)
pygame.draw.rect(screen, (blue), (40,65,40,20), 0)
pygame.draw.rect(screen, (blue), (80,65,40,20), 0)
pygame.draw.rect(screen, (blue), (120,65,40,20), 0)
pygame.draw.rect(screen, (blue), (160,65,40,20), 0)
pygame.draw.rect(screen, (blue), (200,65,40,20), 0)
pygame.draw.rect(screen, (blue), (240,65,40,20), 0)
pygame.draw.rect(screen, (blue), (280,65,40,20), 0)
pygame.draw.rect(screen, (blue), (320,65,40,20), 0)
pygame.draw.rect(screen, (blue), (360,65,40,20), 0)
pygame.draw.rect(screen, (blue), (400,65,40,20), 0)
pygame.draw.rect(screen, (blue), (440,65,40,20), 0)
pygame.draw.rect(screen, (blue), (480,65,40,20), 0)
pygame.draw.rect(screen, (blue), (520,65,40,20), 0)
pygame.draw.rect(screen, (blue), (560,65,40,20), 0)
pygame.draw.rect(screen, (blue), (600,65,40,20), 0)
pygame.draw.rect(screen, (blue), (640,65,40,20), 0)
pygame.draw.rect(screen, (blue), (680,65,40,20), 0)
pygame.draw.rect(screen, (blue), (720,65,40,20), 0)
pygame.draw.rect(screen, (blue), (760,65,40,20), 0)
Is it possible I can put these bricks under one variable and also shorten this code? You're help is much appreciated. Thank you.
Simply use nested for
loops to create list with all bricks.
I will use pygame.Rect() to keep position and size because I will use it to check collision.
all_bricks = []
for y in range(65, 106, 20):
for x in range(0, 761, 40):
brick_rect = pygame.Rect(x, y, 40, 20)
all_bricks.append(brick_rect)
and then you can draw them using one for
loop
for brick_rect in all_bricks:
pygame.draw.rect(screen, blue, brick_rect, 0)
or check collisions
untouched_bricks = []
for brick_rect in all_bricks:
if not ball_rect.colliderect(brick_rect):
untouched_bricks.append(brick_rect)
#else:
# print("Brick touched")
# keep only untouched bricks
all_bricks = unbreaked_bricks
To keep position and different color for every brick separately you will need more complex structure:
[blue, pygame.Rect(x, y, 40, 20), ...]
{"color": blue, "rect": pygame.Rect(x, y, 40, 20), "other": ...}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.