[英]I'm making a brick breaker game and was wondering if there is a way I can put these bricks under one variable
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.
Stack Overflow不允许我放所有积木,所以它们是其中的1/3。 The total amount is 60 (3 rows of 20).
总数为60(3行,共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. 只需使用嵌套的
for
循环即可创建所有砖块的列表。
I will use pygame.Rect() to keep position and size because I will use it to check collision. 我将使用pygame.Rect()来保持位置和大小,因为我将使用它来检查碰撞。
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
循环绘制它们
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": ...}
) {"color": blue, "rect": pygame.Rect(x, y, 40, 20), "other": ...}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.