import pygame import sys import random # Initialize pygame pygame.init() # Set up the screen WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Breakout") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0) ORANGE = (255, 165, 0) YELLOW = (255, 255, 0) SILVER = (192, 192, 192) # Set up the clock clock = pygame.time.Clock() # Game variables paddle_width, paddle_height = 120, 20 paddle_x = WIDTH // 2 - paddle_width // 2 paddle_y = HEIGHT - 50 paddle_speed = 8 ball_radius = 15 ball_x = random.randint(ball_radius, WIDTH - ball_radius) ball_y = HEIGHT // 2 ball_speed_x = 5 ball_speed_y = -5 brick_rows = 5 brick_cols = 10 brick_width = 70 brick_height = 20 brick_padding = 5 brick_offset_top = 50 bricks = [] score = 0 font = pygame.font.Font(None, 36) # Function to create bricks def create_bricks(): for row in range(brick_rows): for col in range(brick_cols): brick_x = col * (brick_width + brick_padding) + brick_padding brick_y = row * (brick_height + brick_padding) + brick_offset_top brick_color = (random.randint(100, 255), random.randint(100, 255), random.randint(100, 255)) bricks.append(pygame.Rect(brick_x, brick_y, brick_width, brick_height)) create_bricks() # Main game loop running = True while running: screen.fill(BLACK) # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Move paddle keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: paddle_x -= paddle_speed if keys[pygame.K_RIGHT]: paddle_x += paddle_speed # Keep paddle within screen boundaries paddle_x = max(0, min(paddle_x, WIDTH - paddle_width)) # Move ball ball_x += ball_speed_x ball_y += ball_speed_y # Check for collisions with walls if ball_x <= ball_radius or ball_x >= WIDTH - ball_radius: ball_speed_x *= -1 if ball_y <= ball_radius: ball_speed_y *= -1 # Check for collision with paddle if paddle_x < ball_x < paddle_x + paddle_width and paddle_y < ball_y < paddle_y + paddle_height: ball_speed_y *= -1 # Check for collision with bricks for brick in bricks[:]: if brick.colliderect(pygame.Rect(ball_x - ball_radius, ball_y - ball_radius, ball_radius * 2, ball_radius * 2)): bricks.remove(brick) score += 1 ball_speed_y *= -1 # Draw paddle pygame.draw.rect(screen, SILVER, (paddle_x, paddle_y, paddle_width, paddle_height)) # Draw ball with gradient effect for i in range(ball_radius): pygame.draw.circle(screen, (255 - i * 3, 255 - i * 3, 255 - i * 3), (ball_x, ball_y), ball_radius - i) # Draw bricks for brick in bricks: pygame.draw.rect(screen, ORANGE, brick) # Display score score_text = font.render("Score: " + str(score), True, WHITE) screen.blit(score_text, (20, 20)) # Update the display pygame.display.flip() # Cap the frame rate clock.tick(60) # Quit pygame pygame.quit() sys.exit()