import pygame
import sys
import random

# 初始化 Pygame
pygame.init()

# 屏幕设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('打砖块小游戏')

# 颜色定义
WHITE = (255, 255, 255)
RED = (255, 50, 50)
BLUE = (0, 0, 255)

# 挡板
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 20
paddle_x = (SCREEN_WIDTH - PADDLE_WIDTH) // 2
paddle_y = SCREEN_HEIGHT - 50
paddle_speed = 13

# 小球
BALL_DIAMETER = 20
ball_x = SCREEN_WIDTH // 2
ball_y = 300
ball_speed_x = 5
ball_speed_y = 5

# 砖块
BRICK_WIDTH = 75
BRICK_HEIGHT = 25
BRICK_ROWS = 5
BRICK_COLS = 33
bricks = []
for row in range(BRICK_ROWS):
    for col in range(BRICK_COLS):
        brick_x = col * BRICK_WIDTH
        brick_y = row * BRICK_HEIGHT + 50
        if not random.randint(1, 3) == 3:
            bricks.append(pygame.Rect(brick_x, brick_y, BRICK_WIDTH, BRICK_HEIGHT))

# 得分
score = 0
font = pygame.font.Font(None, 36)

# 游戏循环标志
running = True

# 游戏主循环
while running:
    screen.fill(WHITE)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 挡板移动
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle_x > 0:
        paddle_x -= paddle_speed
    if keys[pygame.K_RIGHT] and paddle_x < SCREEN_WIDTH - PADDLE_WIDTH:
        paddle_x += paddle_speed

    # 小球移动
    ball_x += ball_speed_x
    ball_y += ball_speed_y

    # 碰撞检测
    # 碰到墙壁就反弹
    if ball_x < 0 or ball_x > SCREEN_WIDTH - BALL_DIAMETER:
        ball_speed_x = -ball_speed_x
    if ball_y < 0:
        ball_speed_y = -ball_speed_y
    # 点到挡板就反弹
    paddle = pygame.Rect(paddle_x, paddle_y, PADDLE_WIDTH, PADDLE_HEIGHT)
    if paddle.colliderect(pygame.Rect(ball_x, ball_y, BALL_DIAMETER, BALL_DIAMETER)):
        ball_speed_y = -ball_speed_y
        ball_speed_y -= 3
        ball_speed_y += 1.5

    # 击破砖块
    for brick in bricks[:]:
        if brick.colliderect(pygame.Rect(ball_x, ball_y, BALL_DIAMETER, BALL_DIAMETER)):
            bricks.remove(brick)
            score += 1
            ball_speed_y = -ball_speed_y
            break

    # 小球落下游戏结束
    if ball_y > SCREEN_HEIGHT:
        running = False

    # 游戏胜利
    if len(bricks) == 0:
        running = False

    # 绘制挡板、小球、砖块
    pygame.draw.rect(screen, BLUE, paddle)
    pygame.draw.circle(screen, RED, (ball_x, ball_y), BALL_DIAMETER // 2)
    for brick in bricks:
        pygame.draw.rect(screen, RED, brick)

    # 显示得分
    score_text = font.render('Score: ' + str(score), True, BLUE)
    screen.blit(score_text, (10, 10))

    pygame.display.flip()
    pygame.time.delay(20)

# 游戏结束
pygame.quit()
sys.exit()
