-
Notifications
You must be signed in to change notification settings - Fork 30
Open
Description
import pygame
import random
import sys
Initialize pygame
pygame.init()
Set up display
WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird")
Set up clock
clock = pygame.time.Clock()
FONT = pygame.font.SysFont("Arial", 30)
Game variables
gravity = 0.25
bird_movement = 0
game_active = True
score = 0
Load bird
bird = pygame.Rect(100, 250, 30, 30)
Pipes
pipe_gap = 150
pipe_width = 70
pipe_height = 400
pipe_speed = 3
pipes = []
def create_pipe():
height = random.randint(100, 400)
bottom_pipe = pygame.Rect(WIDTH, height + pipe_gap, pipe_width, HEIGHT)
top_pipe = pygame.Rect(WIDTH, 0, pipe_width, height)
return top_pipe, bottom_pipe
SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE, 1500)
Main loop
while True:
screen.fill((135, 206, 250)) # Sky blue background
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and game_active:
if event.key == pygame.K_SPACE:
bird_movement = 0
bird_movement -= 6
if event.type == SPAWNPIPE and game_active:
pipes.extend(create_pipe())
if event.type == pygame.KEYDOWN and not game_active:
if event.key == pygame.K_SPACE:
bird.center = (100, 250)
bird_movement = 0
pipes.clear()
score = 0
game_active = True
if game_active:
# Bird
bird_movement += gravity
bird.y += int(bird_movement)
pygame.draw.rect(screen, (255, 255, 0), bird) # Yellow bird
# Pipes
pipes = [pipe.move(-pipe_speed, 0) for pipe in pipes]
for pipe in pipes:
pygame.draw.rect(screen, (0, 255, 0), pipe)
# Collision
for pipe in pipes:
if bird.colliderect(pipe):
game_active = False
if bird.top <= 0 or bird.bottom >= HEIGHT:
game_active = False
# Score
for pipe in pipes:
if pipe.centerx == bird.centerx:
score += 0.5
score_display = FONT.render(f"Score: {int(score)}", True, (255, 255, 255))
screen.blit(score_display, (10, 10))
else:
game_over_text = FONT.render("Game Over! Press SPACE to Restart", True, (255, 0, 0))
screen.blit(game_over_text, (20, HEIGHT // 2))
pygame.display.update()
clock.tick(60)
adeshrajputrajputtuguzD
Metadata
Metadata
Assignees
Labels
No labels