import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 400, 600
GROUND_HEIGHT = 100
BIRD_WIDTH, BIRD_HEIGHT = 40, 40
PIPE_WIDTH = 80
PIPE_GAP = 200
PIPE_VELOCITY = 5
BIRD_GRAVITY = 1
BIRD_JUMP = -15
FPS = 30
# Colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
# Create the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Load game assets
bird_image = pygame.image.load("/home/nandanv/vscode/CSP/images/flappy.png")
bird_image = pygame.transform.scale(bird_image, (BIRD_WIDTH, BIRD_HEIGHT))
pipe_image = pygame.image.load("/home/nandanv/vscode/CSP/images/pipe.png")
pipe_image = pygame.transform.scale(pipe_image, (PIPE_WIDTH, HEIGHT - GROUND_HEIGHT))
ground_image = pygame.Surface((WIDTH, GROUND_HEIGHT))
ground_image.fill(GREEN)
# Initialize game variables
bird_x = 100
bird_y = (HEIGHT - GROUND_HEIGHT) // 2
bird_velocity = 0
pipes = []
# Game loop
clock = pygame.time.Clock()
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_velocity = BIRD_JUMP
# Update bird position and velocity
bird_y += bird_velocity
bird_velocity += BIRD_GRAVITY
# Spawn pipes
if len(pipes) == 0 or pipes[-1][0] < WIDTH - 200:
pipe_height = random.randint(100, HEIGHT - GROUND_HEIGHT - 200)
pipes.append([WIDTH, pipe_height])
# Move pipes
for pipe in pipes:
pipe[0] -= PIPE_VELOCITY
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if pipe[0] > -PIPE_WIDTH]
# Check for collisions
bird_rect = pygame.Rect(bird_x, bird_y, BIRD_WIDTH, BIRD_HEIGHT)
for pipe in pipes:
pipe_rect = pygame.Rect(pipe[0], 0, PIPE_WIDTH, pipe[1]) # Upper pipe
if bird_rect.colliderect(pipe_rect):
pygame.quit()
sys.exit()
pipe_rect = pygame.Rect(pipe[0], pipe[1] + PIPE_GAP, PIPE_WIDTH, HEIGHT - GROUND_HEIGHT - pipe[1] - PIPE_GAP) # Lower pipe
if bird_rect.colliderect(pipe_rect):
pygame.quit()
sys.exit()
# Check for ground collision
if bird_y + BIRD_HEIGHT > HEIGHT - GROUND_HEIGHT:
pygame.quit()
sys.exit()
# Update score
for pipe in pipes:
if pipe[0] + PIPE_WIDTH < bird_x and not pipe[2]:
score += 1
pipe[2] = True
# Draw everything
screen.fill(WHITE)
screen.blit(ground_image, (0, HEIGHT - GROUND_HEIGHT))
for pipe in pipes:
screen.blit(pipe_image, (pipe[0], 0))
screen.blit(pygame.transform.flip(pipe_image, False, True), (pipe[0], pipe[1] + PIPE_GAP))
screen.blit(bird_image, (bird_x, bird_y))
# Display the score
font = pygame.font.Font(None, 36)
text = font.render(f"Score: {score}", True, (0, 0, 0))
screen.blit(text, (10, 10))
pygame.display.flip()
# Cap the frame rate
clock.tick(FPS)