Search code examples
pythonpygamepython-3.2flappy-bird-clone

How to create recurring, different rectangles in Pygame?


As a beginner at Pygame, and a relative beginner at Python (around 4 months of knowledge), I thought it would be good practice to try and recreate the popular phone app 'Flappy Bird.' I have been fine with doing this, up to the point I am at now. How do I keep one rectangle scrolling, while drawing another that will scroll using the same function? Is this possible? There is probably a method for just this, but I've only been learning the module for less than 7 hours :D Here's my code so far in Python 3.2. (Not including imports)

def drawPipe():
    randh = random.randint(40,270)
    scrollx -=0.2
    pygame.draw.rect(screen, (0,150,30), Rect((scrollx,0),(30,340)))


bif = "BG.jpg"
mif = "bird.png"

pygame.init()
screen = pygame.display.set_mode((640,900),0,32)

background = pygame.image.load(bif).convert()
bird = pygame.image.load(mif).convert_alpha()

pygame.display.set_caption("Flappy Bird")
pygame.display.set_icon(bird)

x,y = 320,0
movex, movey = 0,0

scrollx = 640

while True:
    for event in pygame.event.get():
        movey = +0.8
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_SPACE:
                movey = -2


    x += movex
    y += movey


    screen.blit(background,(0,0))
    screen.blit(bird,(x,y))

    drawPipe()


    pygame.display.update()

Thank you for any help you can give!


Solution

  • You should first create object that you want to have in the game, with one operation being to draw them.

    So instead of having a function that draws a pipe and scrolls, you want to have something along these lines:

    class Pipe:
    
    def __init__(self,x,height):
        self.rect = Rect((x,0),(30,height))
    
    def update():
        self.rect.move_ip(-2,0)
    
    def draw(screen):
        pygame.draw.rect(screen,color,self.rect)
    

    And then later in game you can have:

    pipes = [Pipe(x*20,random.randint(40,270)) for x in range(5)]
    
    for pipe in pipes:
        pipe.draw(screen)
        pipe.update()
    

    Later on you could just remove the pipes that are not on the screen, and append new ones when a pipe is removed.