Untitled
unknown
plain_text
10 months ago
2.8 kB
4
Indexable
import pygame
import random
# Initialize pygame
pygame.init()
# Set up display
WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Game settings
gravity = 0.25
bird_movement = 0
game_speed = 5
# Load images
bird = pygame.image.load("bird.png")
bird = pygame.transform.scale(bird, (40, 40))
# Create bird object
bird_rect = bird.get_rect(center=(100, HEIGHT // 2))
# Pipe settings
pipe_width = 70
pipe_height = random.randint(100, 300)
pipe_gap = 150
pipes = []
# Font for score
font = pygame.font.SysFont("Arial", 32)
# Function to create pipes
def create_pipe():
height = random.randint(100, 300)
top_pipe = pygame.Rect(WIDTH, 0, pipe_width, height)
bottom_pipe = pygame.Rect(WIDTH, height + pipe_gap, pipe_width, HEIGHT - height - pipe_gap)
return top_pipe, bottom_pipe
# Function to move pipes
def move_pipes(pipes):
for pipe in pipes:
pipe.x -= game_speed
return [pipe for pipe in pipes if pipe.x > -pipe_width]
# Function to draw pipes
def draw_pipes(pipes):
for pipe in pipes:
pygame.draw.rect(screen, GREEN, pipe)
# Function to check for collisions
def check_collision(pipes, bird_rect):
for pipe in pipes:
if bird_rect.colliderect(pipe):
return True
if bird_rect.top <= 0 or bird_rect.bottom >= HEIGHT:
return True
return False
# Main game loop
running = True
score = 0
pipes = [create_pipe()]
clock = pygame.time.Clock()
while running:
screen.fill(BLUE)
# Event handling
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_movement = 0
bird_movement -= 8 # Move bird upwards
# Bird movement
bird_movement += gravity
bird_rect.centery += bird_movement
# Draw bird
screen.blit(bird, bird_rect)
# Move and draw pipes
pipes = move_pipes(pipes)
draw_pipes(pipes)
# Create new pipes
if pipes[-1][0].x < WIDTH - 200:
pipes.extend(create_pipe())
# Increase score
for pipe in pipes:
if pipe.x == bird_rect.x:
score += 1
# Check for collisions
if check_collision(pipes, bird_rect):
running = False
# Display score
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
# Update the screen
pygame.display.update()
# Control the frame rate
clock.tick(60)
# End of game
pygame.quit()
Editor is loading...
Leave a Comment