Untitled
unknown
plain_text
10 months ago
2.6 kB
5
Indexable
python flappy_bird.pyimport pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# Create the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Clock for controlling the frame rate
clock = pygame.time.Clock()
# Load images
bird_img = pygame.image.load("bird.png") # Replace with your bird image
pipe_img = pygame.image.load("pipe.png") # Replace with your pipe image
background_img = pygame.image.load("background.png") # Replace with your background image
# Scale images
bird_img = pygame.transform.scale(bird_img, (40, 40))
pipe_img = pygame.transform.scale(pipe_img, (60, 300))
# Bird properties
bird_x = 50
bird_y = SCREEN_HEIGHT // 2
bird_velocity = 0
gravity = 0.5
# Pipe properties
pipe_width = 60
pipe_height = 300
pipe_gap = 150
pipe_x = SCREEN_WIDTH
pipe_y = random.randint(200, 400)
# Score
score = 0
font = pygame.font.SysFont("Arial", 30)
# Game loop
running = True
while running:
# Handle events
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_velocity = -8 # Flap the bird
# Update bird position
bird_velocity += gravity
bird_y += bird_velocity
# Update pipe position
pipe_x -= 5
if pipe_x < -pipe_width:
pipe_x = SCREEN_WIDTH
pipe_y = random.randint(200, 400)
score += 1
# Collision detection
bird_rect = pygame.Rect(bird_x, bird_y, 40, 40)
pipe_rect_top = pygame.Rect(pipe_x, pipe_y - pipe_height - pipe_gap, pipe_width, pipe_height)
pipe_rect_bottom = pygame.Rect(pipe_x, pipe_y, pipe_width, pipe_height)
if bird_rect.colliderect(pipe_rect_top) or bird_rect.colliderect(pipe_rect_bottom) or bird_y > SCREEN_HEIGHT:
print("Game Over! Score:", score)
running = False
# Draw everything
screen.blit(background_img, (0, 0)) # Draw background
screen.blit(bird_img, (bird_x, bird_y)) # Draw bird
screen.blit(pipe_img, (pipe_x, pipe_y - pipe_height - pipe_gap)) # Draw top pipe
screen.blit(pipe_img, (pipe_x, pipe_y)) # Draw bottom pipe
# Draw score
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
# Update the display
pygame.display.update()
# Cap the frame rate
clock.tick(30)
# Quit Pygame
pygame.quit()Editor is loading...
Leave a Comment