如何让整个 pygame 精灵组移动(从屏幕顶部掉落)?

问题描述 投票:0回答:0

我学习了几周的 Python 编码,我被困在一个任务中,要让一组 pygame 精灵在屏幕上向下移动(同时)。到目前为止,我设法让它们一个接一个地倒下,但不能让整排倒下。 我在这里阅读了类似问题的示例和答案,但不知何故我无法在我的代码中实现它们。我想我在构建我的程序时使用了一个次优的结构或算法,加上不够了解,阻止了我这样做。如果有人告诉我如何完成这项任务,我将不胜感激,如果您有时间,我也会提出任何其他改进建议。

import pygame


class FallingBricks:
    """Bricks falling from the top of the screen"""

    def __init__(self):
        self.screen_colour = (50, 150, 100)
        screen_width = 1500
        screen_height = 1500
        self.brick_colour = (150, 0, 0)
        self.brick_width = 100
        self.brick_height = 50

        pygame.init()

        self.screen = pygame.display.set_mode((screen_width, screen_height))
        pygame.display.set_caption("Falling bricks")
        self.screen_rect = self.screen.get_rect()
        self.screen.fill(self.screen_colour)

        # A group to hold all the sprites (Bricks)
        self.all_sprites_list = pygame.sprite.Group()

    def run_prog(self):
        """"Starting the main program loop"""

        self.all_sprites_list.draw(self.screen)
        brick = Brick(self.brick_colour, self.brick_height, self.brick_width)
        brick_width, brick_height = brick.rect.size
        screen_width, screen_height = self.screen.get_size()
        available_x = (screen_width // brick_width) // 2 + 1

        running = True
        clock = pygame.time.Clock()

        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

            for n in range(available_x):
                Brick.create_brick(n)

            pygame.display.flip()
            clock.tick(60)


class Brick(pygame.sprite.Sprite):
    """A class to make a brick object"""

    def __init__(self, color, height, width):
        super().__init__()

        self.image = pygame.Surface([width, height])

        # Draw each new object  near the top left of the screen; correct position will be given later
        pygame.draw.rect(self.image, color, pygame.Rect(0, 0, width, height))

        self.rect = self.image.get_rect()

        # Store the brick's exact vertical position
        self.y = float(self.rect.y)

    def update(self):
        self.rect.y += 5

    @staticmethod
    def create_brick(number):
        brick = Brick(fb.brick_colour, 50, 100)
        brick_width, brick_height = brick.rect.size
        brick.x = 2 * brick_width * number
        brick.rect.x = brick.x

        while brick.rect.bottom <= fb.screen_rect.bottom:
            brick.update()
            fb.screen.fill(fb.screen_colour)
            fb.all_sprites_list.add(brick)
            fb.all_sprites_list.draw(fb.screen)
            fb.all_sprites_list.empty()
            pygame.display.flip()


if __name__ == '__main__':
    fb = FallingBricks()
    fb.run_prog()
python-3.x pygame sprite move group
© www.soinside.com 2019 - 2024. All rights reserved.