Untitled
unknown
plain_text
a year ago
2.6 kB
5
Indexable
import pygame
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 400, 600
FPS = 60
GRAVITY = 0.5
FLAP_STRENGTH = -10
PIPE_SPEED = 3
PIPE_GAP = 150
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# Setup the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird Clone")
# Load images
bird_img = pygame.Surface((30, 30))
bird_img.fill((255, 255, 0))
pipe_img = pygame.Surface((60, HEIGHT))
pipe_img.fill(GREEN)
class Bird:
def __init__(self):
self.rect = bird_img.get_rect(center=(100, HEIGHT // 2))
self.velocity = 0
def flap(self):
self.velocity = FLAP_STRENGTH
def update(self):
self.velocity += GRAVITY
self.rect.y += self.velocity
if self.rect.bottom > HEIGHT:
self.rect.bottom = HEIGHT
class Pipe:
def __init__(self):
self.height = random.randint(100, 400)
self.top = pipe_img.get_rect(topleft=(WIDTH, self.height - HEIGHT))
self.bottom = pipe_img.get_rect(topleft=(WIDTH, self.height + PIPE_GAP))
def update(self):
self.top.x -= PIPE_SPEED
self.bottom.x -= PIPE_SPEED
def off_screen(self):
return self.top.x < -self.top.width
def main():
clock = pygame.time.Clock()
bird = Bird()
pipes = [Pipe()]
score = 0
running = True
while running:
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.flap()
bird.update()
# Pipe logic
if pipes[-1].top.x < WIDTH - 200:
pipes.append(Pipe())
for pipe in pipes:
pipe.update()
if pipe.off_screen():
pipes.remove(pipe)
score += 1 # Increment score when a pipe is passed
# Collision detection
for pipe in pipes:
if bird.rect.colliderect(pipe.top) or bird.rect.colliderect(pipe.bottom):
running = False # Game over
# Drawing
screen.fill(WHITE)
screen.blit(bird_img, bird.rect)
for pipe in pipes:
screen.blit(pipe_img, pipe.top)
screen.blit(pipe_img, pipe.bottom)
# Display score
font = pygame.font.Font(None, 36)
score_surface = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_surface, (10, 10))
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
if __name__ == "__main__":
main()
Editor is loading...
Leave a Comment