import pygame import random # Initialize Pygame pygame.init() # Constants SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 PADDLE_WIDTH = 100 PADDLE_HEIGHT = 20 BRICK_WIDTH = 80 BRICK_HEIGHT = 30 BALL_RADIUS = 10 WHITE = (255, 255, 255) BLACK = (0, 0, 0) BLUE = (0, 0, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) # Create the screen screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Breakout") clock = pygame.time.Clock() # Paddle class class Paddle(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface([PADDLE_WIDTH, PADDLE_HEIGHT]) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.x = SCREEN_WIDTH // 2 - PADDLE_WIDTH // 2 self.rect.y = SCREEN_HEIGHT - PADDLE_HEIGHT self.speed = 0 def update(self): self.rect.x += self.speed if self.rect.left < 0: self.rect.left = 0 elif self.rect.right > SCREEN_WIDTH: self.rect.right = SCREEN_WIDTH # Ball class class Ball(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface([BALL_RADIUS * 2, BALL_RADIUS * 2]) self.image.fill(RED) pygame.draw.circle(self.image, WHITE, (BALL_RADIUS, BALL_RADIUS), BALL_RADIUS) self.rect = self.image.get_rect() self.rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2) self.speed_x = random.choice([-5, 5]) self.speed_y = -5 def update(self): self.rect.x += self.speed_x self.rect.y += self.speed_y if self.rect.left <= 0 or self.rect.right >= SCREEN_WIDTH: self.speed_x *= -1 if self.rect.top <= 0: self.speed_y *= -1 # Brick class class Brick(pygame.sprite.Sprite): def __init__(self, color, x, y): super().__init__() self.image = pygame.Surface([BRICK_WIDTH, BRICK_HEIGHT]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y # Create sprites all_sprites = pygame.sprite.Group() bricks = pygame.sprite.Group() paddle = Paddle() ball = Ball() all_sprites.add(paddle, ball) # Create bricks for row in range(5): for column in range(10): brick = Brick(BLUE, column * (BRICK_WIDTH + 2), row * (BRICK_HEIGHT + 2) + 50) bricks.add(brick) all_sprites.add(brick) # Game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: paddle.speed = -10 elif event.key == pygame.K_RIGHT: paddle.speed = 10 elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: paddle.speed = 0 # Update all_sprites.update() # Check collisions if pygame.sprite.collide_rect(ball, paddle): ball.speed_y *= -1 collided_bricks = pygame.sprite.spritecollide(ball, bricks, True) if collided_bricks: ball.speed_y *= -1 # Draw screen.fill(BLACK) all_sprites.draw(screen) pygame.display.flip() # Cap the frame rate clock.tick(60) # Quit pygame.quit()