Untitled
unknown
plain_text
10 months ago
3.1 kB
5
Indexable
pip install pygame
import pygame
import random
import sys
# Initialize pygame
pygame.init()
# Set up game constants
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
GRAVITY = 0.25
JUMP_STRENGTH = -5
PIPE_WIDTH = 60
PIPE_GAP = 150
FPS = 60
# Set up colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
# Set up the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Set up the clock
clock = pygame.time.Clock()
# Set up font for score
font = pygame.font.SysFont("Arial", 30)
class Bird:
def __init__(self):
self.x = 50
self.y = SCREEN_HEIGHT // 2
self.velocity = 0
def jump(self):
self.velocity = JUMP_STRENGTH
def move(self):
self.velocity += GRAVITY
self.y += self.velocity
def draw(self, screen):
pygame.draw.rect(screen, BLUE, (self.x, self.y, 40, 40))
class Pipe:
def __init__(self):
self.x = SCREEN_WIDTH
self.height = random.randint(150, SCREEN_HEIGHT - 150)
self.gap = PIPE_GAP
def move(self):
self.x -= 5
def draw(self, screen):
pygame.draw.rect(screen, GREEN, (self.x, 0, PIPE_WIDTH, self.height))
pygame.draw.rect(screen, GREEN, (self.x, self.height + self.gap, PIPE_WIDTH, SCREEN_HEIGHT - self.height - self.gap))
def check_collision(bird, pipes):
for pipe in pipes:
if pipe.x < bird.x + 40 and pipe.x + PIPE_WIDTH > bird.x:
if bird.y < pipe.height or bird.y + 40 > pipe.height + pipe.gap:
return True
return False
def main():
bird = Bird()
pipes = []
score = 0
pipe_timer = 0
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 and event.key == pygame.K_SPACE:
bird.jump()
# Bird movement
bird.move()
# Pipe generation
pipe_timer += 1
if pipe_timer > 60:
pipes.append(Pipe())
pipe_timer = 0
# Move pipes
for pipe in pipes:
pipe.move()
# Remove pipes that are off-screen
pipes = [pipe for pipe in pipes if pipe.x + PIPE_WIDTH > 0]
# Check for collision
if bird.y > SCREEN_HEIGHT or bird.y < 0 or check_collision(bird, pipes):
pygame.quit()
sys.exit()
# Draw everything
bird.draw(screen)
for pipe in pipes:
pipe.draw(screen)
# Update score
for pipe in pipes:
if pipe.x + PIPE_WIDTH < bird.x and not hasattr(pipe, "scored"):
score += 1
pipe.scored = True
# Display score
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.update()
clock.tick(FPS)
if __name__ == "__main__":
main()Editor is loading...
Leave a Comment