while running:
clock.tick(FPS)
screen.fill(WHITE)
# Event-Handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
bird.jump()
# Vogel bewegen
bird.move()
# Rohre bewegen
for pipe in pipes:
pipe.move()
pipe.draw(screen)
if pipe.collide(bird):
running = False # Kollision beendet das Spiel
if pipe.x + PIPE_WIDTH < 0:
pipes.remove(pipe)
if not pipe.passed and pipe.x < bird.x:
pipe.passed = True
score += 1
pipes.append(Pipe())
# Vogel zeichnen
bird.draw(screen)
# Punktzahl anzeigen
font = pygame.font.SysFont(None, 36)
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
# Aktualisiere den Bildschirm
pygame.display.flip()
# Überprüfen, ob der Vogel auf den Boden oder aus dem Bildschirm gefallen ist
if bird.y + bird.height > SCREEN_HEIGHT or bird.y < 0:
running = False
pygame.quit()
import pygame import random
Pygame initialisieren
pygame.init()
Konstanten
SCREEN_WIDTH = 400 SCREEN_HEIGHT = 600 GRAVITY = 0.5 BIRD_JUMP = -10 PIPE_GAP = 150 PIPE_WIDTH = 70 PIPE_SPEED = 3 FPS = 60
Farben
WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0)
Bildschirm erstellen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) clock = pygame.time.Clock()
Vogelklasse
class Bird: def init(self): self.x = 50 self.y = SCREEN_HEIGHT // 2 self.width = 30 self.height = 30 self.velocity = 0
Rohrklasse
class Pipe: def init(self): self.x = SCREEN_WIDTH self.height = random.randint(100, SCREEN_HEIGHT - PIPE_GAP - 100) self.passed = False
Hauptspiel-Funktion
def main(): bird = Bird() pipes = [Pipe()] score = 0 running = True
if name == "main": main()