Flappy Bird is a popular mobile game where the player controls a bird that must navigate through obstacles. The game ends when the bird collides with an obstacle or the ground.
Game Code
python
import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up some constants
WIDTH, HEIGHT = 640, 480
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
OBSTACLE_WIDTH = 50
OBSTACLE_HEIGHT = 200
OBSTACLE_GAP = 150
BIRD_SIZE = 20
# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Set up the font
font = pygame.font.Font(None, 36)
# Set up the clock
clock = pygame.time.Clock()
class Bird:
def __init__(self):
self.x = WIDTH // 2
self.y = HEIGHT // 2
self.velocity = 0
self.gravity = 0.5
def move(self):
self.velocity += self.gravity
self.y += self.velocity
def jump(self):
self.velocity = -10
class Obstacle:
def __init__(self):
self.x = WIDTH
self.gap_y = HEIGHT // 2 - OBSTACLE_GAP // 2
def move(self):
self.x -= 5
def main():
bird = Bird()
obstacle = Obstacle()
score = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird.jump()
bird.move()
obstacle.move()
# Collision with obstacle
if (bird.x + BIRD_SIZE > obstacle.x and
bird.x < obstacle.x + OBSTACLE_WIDTH and
(bird.y < obstacle.gap_y or bird.y + BIRD_SIZE > obstacle.gap_y + OBSTACLE_GAP)):
print("Game Over")
pygame.quit()
sys.exit()
# Collision with ground
if bird.y + BIRD_SIZE > HEIGHT:
print("Game Over")
pygame.quit()
sys.exit()
# Check if obstacle is off the screen
if obstacle.x < -OBSTACLE_WIDTH:
obstacle = Obstacle()
score += 1
# Draw everything
screen.fill(WHITE)
pygame.draw.rect(screen, RED, (bird.x, bird.y, BIRD_SIZE, BIRD_SIZE))
pygame.draw.rect(screen, BLACK, (obstacle.x, 0, OBSTACLE_WIDTH, obstacle.gap_y))
pygame.draw.rect(screen, BLACK, (obstacle.x, obstacle.gap_y + OBSTACLE_GAP, OBSTACLE_WIDTH, HEIGHT - obstacle.gap_y - OBSTACLE_GAP))
text = font.render(str(score), True, BLACK)
screen.blit(text, (WIDTH // 2, 20))
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()
How to Run the Game
Install Pygame by running pip install pygame in your terminal/command prompt.
Save the game code in a file named flappy_bird.py.
Run the game by running python flappy_bird.py in your terminal/command prompt.
Use the space bar to jump.
Gameplay
The game will start with a bird in the middle of the screen. The bird will fall down due to gravity. You can make the bird jump by pressing the space bar. The goal is to navigate the bird through the obstacles without colliding with them. The game ends when the bird collides with an obstacle or the ground. The score will increase by one each time the bird passes an obstacle.