import pygame
import random
# Initialize pygame
pygame.init()
# Create game window
window_width = 400
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Flappy Bird")
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
# Bird
bird_radius = 20
bird_x = 100
bird_y = 200
bird_y_change = 0
def draw_bird(x, y):
pygame.draw.circle(window, black, (x, y), bird_radius)
# Pipes
pipe_width = 70
pipe_height = random.randint(100, 300)
pipe_x = window_width
pipe_y = window_height - pipe_height
pipe_speed = 3
def draw_pipe(x, y, height):
pygame.draw.rect(window, black, (x, y, pipe_width, height))
pygame.draw.rect(window, black, (x, 0, pipe_width, window_height - height - 150))
# Game Loop
running = True
while running:
window.fill(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_y_change = -5
bird_y += bird_y_change
bird_y_change += 0.2
if bird_y <= 0 or bird_y >= window_height:
running = False
pipe_x -= pipe_speed
if pipe_x <= -pipe_width:
pipe_x = window_width
pipe_height = random.randint(100, 300)
pipe_y = window_height - pipe_height
draw_pipe(pipe_x, pipe_y, pipe_height)
draw_bird(bird_x, int(bird_y))
pygame.display.update()
# Quit the game
pygame.quit()
This code provides a basic structure for the Flappy Bird game with a bird flying and pipes appearing at a random height. You can further enhance the game by adding scoring, collision detection, sounds, and more.