Untitled
unknown
plain_text
2 years ago
2.4 kB
13
Indexable
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 600, 400
FPS = 60
GRAVITY = 0.5
JUMP_HEIGHT = 10
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# Create window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Load images
bird_img = pygame.image.load('bird.png')
pipe_img = pygame.image.load('pipe.png')
background_img = pygame.image.load('background.png')
ground_img = pygame.image.load('ground.png')
# Resize images
bird_img = pygame.transform.scale(bird_img, (50, 50))
pipe_img = pygame.transform.scale(pipe_img, (50, 300))
ground_img = pygame.transform.scale(ground_img, (WIDTH, 100))
# Load sounds
flap_sound = pygame.mixer.Sound('flap.wav')
collision_sound = pygame.mixer.Sound('collision.wav')
# Game variables
bird_rect = bird_img.get_rect(center=(100, HEIGHT // 2))
bird_velocity = 0
pipes = []
SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE, 1200)
pipe_heights = [200, 250, 300, 350]
# Game loop
clock = pygame.time.Clock()
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 = -JUMP_HEIGHT
flap_sound.play()
if event.type == SPAWNPIPE:
pipe_height = random.choice(pipe_heights)
pipes.append(pipe_img.get_rect(midtop=(WIDTH, pipe_height)))
# Move bird
bird_velocity += GRAVITY
bird_rect.centery += bird_velocity
# Move pipes
pipes = [pipe.move(-5, 0) for pipe in pipes]
# Check for collisions
if bird_rect.colliderect(ground_img.get_rect(bottom=HEIGHT)):
collision_sound.play()
pygame.quit()
sys.exit()
for pipe in pipes:
if bird_rect.colliderect(pipe):
collision_sound.play()
pygame.quit()
sys.exit()
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if pipe.right > 0]
# Draw background
screen.blit(background_img, (0, 0))
# Draw pipes
for pipe in pipes:
screen.blit(pipe_img, pipe)
# Draw bird
screen.blit(bird_img, bird_rect)
# Draw ground
screen.blit(ground_img, (0, HEIGHT - 100))
# Update display
pygame.display.flip()
# Cap the frame rate
clock.tick(FPS)
Editor is loading...
Leave a Comment