How do I make the image repeat - for example 10x in a row - in Pygame

Viewed 53

So, basically, I'm making the flappy bird game, and I would like to duplicate the pipes, so I don't have to make variable for each pipe for example like - 20x.. but simply just duplicating it..

1 Answers

Create a Pipe class and mange multiple instance of Pipe in a container (e.g. in a list).
In Pygame it is recommended to use pygame.sprite.Sprite and pygame.sprite.Group.


See the minimal example, that uses pygame.sprite.Sprite and pygame.sprite.Group and spawns Sprites with a time interval:

import pygame, random

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    
    def __init__(self, image):
        super().__init__() 
        self.image = image.copy()
        size = image.get_size()
        x = random.randrange(size[0]//2, window.get_width()-size[0]//2)
        y = random.randrange(size[1]//2, window.get_height()-size[1]//2)
        self.rect = self.image.get_rect(center = (x, y))
        self.alpha = 255
    
    def update(self):
        if self.alpha >= 0:
            self.image.set_alpha(self.alpha)
        else:
            self.kill()
        self.alpha -= 1
        
object_surf = pygame.image.load('Bird.png').convert_alpha()
all_sprites = pygame.sprite.Group()
time_interval = 200 # 200 milliseconds == 0.2 seconds
next_object_time = 0 

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    current_time = pygame.time.get_ticks()
    if current_time > next_object_time:
        next_object_time += time_interval
        all_sprites.add(Player(object_surf))

    all_sprites.update()

    window.fill(0)
    all_sprites.draw(window)
    pygame.display.flip()

pygame.quit()
exit()
Related