Skip to content Skip to sidebar Skip to footer

Creating A Group To Add My Class To In Pygame

I am currently making a game in Pygame, and would like to generate several platforms randomly throughout my screen. However, I can't seem to figure out how to create a group so tha

Solution 1:

Your classes should inherit from pygame.sprite.Sprite, so that they can be put into sprite groups, e.g. class Platform(pg.sprite.Sprite):. Don't forget to call the __init__ method of the parent class super().__init__(). Then create the sprite groups (all_sprites = pg.sprite.Group()) and the sprite instances and call the add method of the groups to add the sprite.

Then you just have to call all_sprites.update() and all_sprites.draw(screen) in the main loop.

from random import randrange

import pygame as pg


class Platform(pg.sprite.Sprite):

    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pg.Surface((width, height))
        self.image.fill(pg.Color('dodgerblue1'))
        self.rect = self.image.get_rect(topleft=(x, y))


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()  # This group that will contain all sprites.
    # You probably want to add the platforms to a separate
    # group as well, so that you can use it for collision detection.
    platforms = pg.sprite.Group()

    for _ in range(6):  # Create six platforms at random coords.
        platform = Platform(randrange(600), randrange(440), 170, 20)
        platforms.add(platform)
        all_sprites.add(platform)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update()

        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

Post a Comment for "Creating A Group To Add My Class To In Pygame"