import pygame as pg
pg.init()
SCREEN_WIDTH = 288
SCREEN_HEIGHT = 620
clock = pg.time.Clock()
FPS = 60
ground_scroll = 0
scroll_speed = 4
is_active = True
game_running = False
game_over = False
pipe_gap = 100
screen = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pg.display.set_caption('Flappy Bird', 'Assets/yellowbird-downflap.png')
bg = pg.image.load('Assets/background-day.png')
ground_img = pg.image.load('Assets/base.png')
class Bird(pg.sprite.Sprite):
def __init__(self, x, y):
pg.sprite.Sprite.__init__(self)
self.images = []
self.index = 0
self.counter = 0
for i in range(1, 4):
img = pg.image.load(f'Assets/red_bird_{i}.png')
self.images.append(img)
self.image = self.images[self.index]
self.rect = self.image.get_rect()
self.rect.center = [x, y]
self.velocity = 0
self.clicked = False
def update(self):
if game_running:
self.velocity += 0.3
if self.velocity > 8:
self.velocity = 8
if self.rect.bottom < 512:
self.rect.y += int(self.velocity)
if not game_over:
if pg.mouse.get_pressed()[0] == 1 and not self.clicked:
self.velocity -= 10
self.clicked = True
if pg.mouse.get_pressed()[0] == 0:
self.clicked = False
self.counter += 1
flap_cooldown = 7
if self.counter > flap_cooldown:
self.counter = 0
self.index += 1
if self.index >= len(self.images):
self.index = 0
self.image = self.images[self.index]
self.image = pg.transform.rotate(self.images[self.index], self.velocity * -2)
else:
self.image = pg.transform.rotate(self.images[self.index], -90)
class Pipe(pg.sprite.Sprite):
def __init__(self, x, y, pos):
pg.sprite.Sprite.__init__(self)
self.image = pg.image.load('Assets/pipe-green.png')
self.rect = self.image.get_rect()
if pos == 1:
self.image = pg.transform.flip(self.image, False, True)
self.rect.bottomleft = [x, y - int(pipe_gap / 2)]
else:
self.rect.topleft = [x, y + int(pipe_gap / 2)]
def update(self):
self.rect.x -= scroll_speed
bird_group = pg.sprite.Group()
pipe_group = pg.sprite.Group()
player = Bird(50, SCREEN_HEIGHT / 2)
bottom_pipe = Pipe(150, SCREEN_HEIGHT / 2, 1)
up_pipe = Pipe(150, SCREEN_HEIGHT / 2, -1)
pipe_group.add(bottom_pipe)
pipe_group.add(up_pipe)
bird_group.add(player)
while is_active:
clock.tick(FPS)
screen.blit(bg, (0, 0))
bird_group.draw(screen)
bird_group.update()
pipe_group.draw(screen)
pipe_group.update()
screen.blit(ground_img, (ground_scroll, 512))
if player.rect.bottom > 512:
game_over = True
game_running = False
if game_over == False:
ground_scroll -= scroll_speed
if abs(ground_scroll) > 35:
ground_scroll = 0
for event in pg.event.get():
if event.type == pg.QUIT:
is_active = False
if event.type == pg.MOUSEBUTTONDOWN and not game_running and not game_over:
game_running = True
pg.display.update()
pg.quit()