gpt4 book ai didi

python - 我正在制作一款打砖 block 游戏,想知道是否有一种方法可以将这些砖 block 放在一个变量下

转载 作者:行者123 更新时间:2023-12-01 02:17:38 25 4
gpt4 key购买 nike

这些是我为我的游戏制作的积木。 Stack Overflow 不允许我放置所有积木,因此这些是其中的 1/3。总数为 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)

我是否可以将这些砖 block 放在一个变量下并缩短这段代码?非常感谢您的帮助。谢谢。

最佳答案

只需使用嵌套的for循环即可创建包含所有砖 block 的列表。

我将使用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)

然后您可以使用一个 for 循环绘制它们

for brick_rect in all_bricks:    
pygame.draw.rect(screen, blue, brick_rect, 0)

或检查碰撞

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
<小时/>

要分别保持每 block 砖的位置和不同颜色,您将需要更复杂的结构:

  • 列表 - 即。 [blue, pygame.Rect(x, y, 40, 20), ...]
  • 字典 - 即。 {"color": 蓝色, "rect": pygame.Rect(x, y, 40, 20), "other": ...})

关于python - 我正在制作一款打砖 block 游戏,想知道是否有一种方法可以将这些砖 block 放在一个变量下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48244479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com