Untitled
unknown
plain_text
a year ago
3.3 kB
6
Indexable
import pygame
import random
import sys
# Initialize Pygame
pygame.init()
# Set up the display
WIDTH = 400
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Set up colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
# Set up the game clock
clock = pygame.time.Clock()
# Bird class
class Bird:
def __init__(self):
self.x = 50
self.y = HEIGHT // 2
self.width = 40
self.height = 40
self.velocity = 0
self.gravity = 0.5
self.lift = -10
def update(self):
self.velocity += self.gravity
self.y += self.velocity
if self.y > HEIGHT - self.height:
self.y = HEIGHT - self.height
if self.y < 0:
self.y = 0
def jump(self):
self.velocity = self.lift
def draw(self, screen):
pygame.draw.rect(screen, BLUE, (self.x, self.y, self.width, self.height))
# Pipe class
class Pipe:
def __init__(self):
self.width = 60
self.gap = 150
self.x = WIDTH
self.height = random.randint(100, 400)
self.passed = False
def update(self):
self.x -= 3
def draw(self, screen):
pygame.draw.rect(screen, GREEN, (self.x, 0, self.width, self.height))
pygame.draw.rect(screen, GREEN, (self.x, self.height + self.gap, self.width, HEIGHT - (self.height + self.gap)))
def off_screen(self):
return self.x < -self.width
def collide(self, bird):
if bird.x + bird.width > self.x and bird.x < self.x + self.width:
if bird.y < self.height or bird.y + bird.height > self.height + self.gap:
return True
return False
# Main game loop
def main():
bird = Bird()
pipes = [Pipe()]
score = 0
running = True
while running:
screen.fill(WHITE)
# Handle events
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.jump()
# Update bird
bird.update()
# Update pipes
for pipe in pipes:
pipe.update()
# Remove pipes that are off screen
if pipes[0].off_screen():
pipes.pop(0)
# Add a new pipe
if pipes[-1].x < WIDTH - 200:
pipes.append(Pipe())
# Check for collisions
for pipe in pipes:
if pipe.collide(bird):
running = False
# Increase score
for pipe in pipes:
if not pipe.passed and pipe.x + pipe.width < bird.x:
pipe.passed = True
score += 1
# Draw everything
bird.draw(screen)
for pipe in pipes:
pipe.draw(screen)
# Draw score
font = pygame.font.SysFont("Arial", 30)
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
# Update the display
pygame.display.update()
# Set the frame rate
clock.tick(60)
# End game
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Editor is loading...
Leave a Comment