Untitled
unknown
plain_text
2 years ago
2.4 kB
7
Indexable
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up display
WIDTH, HEIGHT = 500, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Fonts
FONT = pygame.font.SysFont(None, 40)
# Bird attributes
BIRD_WIDTH, BIRD_HEIGHT = 50, 50
BIRD_X = 50
BIRD_Y = HEIGHT // 2 - BIRD_HEIGHT // 2
GRAVITY = 0.25
JUMP = -5
# Pipe attributes
PIPE_WIDTH = 70
PIPE_GAP = 200
PIPE_VELOCITY = -3
pipes = []
# Score
score = 0
# Functions
def draw_bird():
pygame.draw.rect(WIN, RED, (BIRD_X, BIRD_Y, BIRD_WIDTH, BIRD_HEIGHT))
def draw_pipes():
for pipe in pipes:
pygame.draw.rect(WIN, BLACK, pipe)
def move_pipes():
for pipe in pipes:
pipe.x += PIPE_VELOCITY
def generate_pipe():
gap_y = random.randint(50, HEIGHT - 250)
top_pipe = pygame.Rect(WIDTH, 0, PIPE_WIDTH, gap_y)
bottom_pipe = pygame.Rect(WIDTH, gap_y + PIPE_GAP, PIPE_WIDTH, HEIGHT - gap_y - PIPE_GAP)
pipes.extend([top_pipe, bottom_pipe])
def update_score():
global score
score += 1
def display_score():
score_surface = FONT.render(f"Score: {score}", True, WHITE)
WIN.blit(score_surface, (10, 10))
# Main loop
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
# 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_Y += JUMP
# Bird movement
BIRD_Y += GRAVITY
move_pipes()
# Collisions
bird_rect = pygame.Rect(BIRD_X, BIRD_Y, BIRD_WIDTH, BIRD_HEIGHT)
for pipe in pipes:
if bird_rect.colliderect(pipe):
running = False
if pipe.right < 0:
pipes.remove(pipe)
update_score()
# Bird off-screen
if BIRD_Y > HEIGHT or BIRD_Y < 0:
running = False
# Generate pipes
if len(pipes) == 0 or pipes[-1].x < WIDTH - 200:
generate_pipe()
# Draw everything
WIN.fill(WHITE)
draw_bird()
draw_pipes()
display_score()
pygame.display.update()
# Game over
game_over_surface = FONT.render("Game Over!", True, RED)
WIN.blit(game_over_surface, (WIDTH // 2 - 100, HEIGHT // 2))
pygame.display.update()
# Delay before closing
pygame.time.delay(2000)
pygame.quit()
Editor is loading...
Leave a Comment