Untitled
unknown
plain_text
9 months ago
2.8 kB
4
Indexable
import pygame
import random
import sys
# Initialize pygame
pygame.init()
# Game variables
WIDTH, HEIGHT = 400, 600
GRAVITY = 0.5
BIRD_JUMP = -10
PIPE_WIDTH = 60
PIPE_GAP = 150
PIPE_VELOCITY = 3
FPS = 60
# Set up display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Load bird image
bird_img = pygame.Surface((40, 40))
bird_img.fill(BLUE)
# Bird class
class Bird:
def __init__(self):
self.x = 50
self.y = HEIGHT // 2
self.velocity = 0
def jump(self):
self.velocity = BIRD_JUMP
def move(self):
self.velocity += GRAVITY
self.y += self.velocity
# Prevent bird from going off screen
if self.y < 0:
self.y = 0
if self.y > HEIGHT - 40:
self.y = HEIGHT - 40
# Pipe class
class Pipe:
def __init__(self):
self.x = WIDTH
self.height = random.randint(100, HEIGHT - PIPE_GAP - 100)
self.top_rect = pygame.Rect(self.x, 0, PIPE_WIDTH, self.height)
self.bottom_rect = pygame.Rect(self.x, self.height + PIPE_GAP, PIPE_WIDTH, HEIGHT - self.height - PIPE_GAP)
def move(self):
self.x -= PIPE_VELOCITY
self.top_rect.x = self.x
self.bottom_rect.x = self.x
def draw(self):
pygame.draw.rect(screen, GREEN, self.top_rect)
pygame.draw.rect(screen, GREEN, self.bottom_rect)
# Initialize bird
bird = Bird()
pipes = []
clock = pygame.time.Clock()
score = 0
# Game loop
while True:
screen.fill(WHITE)
# Event handling
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.jump()
# Bird movement
bird.move()
# Generate new pipes
if len(pipes) == 0 or pipes[-1].x < WIDTH - 300:
pipes.append(Pipe())
# Move and draw pipes
for pipe in pipes[:]:
pipe.move()
pipe.draw()
if pipe.x + PIPE_WIDTH < 0:
pipes.remove(pipe)
score += 1
# Check for collision with pipes
if bird.y < pipe.height or bird.y > pipe.height + PIPE_GAP:
if pipe.x < bird.x + 40 and pipe.x + PIPE_WIDTH > bird.x:
pygame.quit()
sys.exit()
# Draw the bird
screen.blit(bird_img, (bird.x, bird.y))
# Display score
font = pygame.font.SysFont("Arial", 32)
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
# Update the display
pygame.display.update()
# Control the frame rate
clock.tick(FPS)
Editor is loading...
Leave a Comment