import pygame

# ====================
# 初始化
# ====================
pygame.init()
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("简易画图板")

font = pygame.font.SysFont("simhei", 20)
clock = pygame.time.Clock()

# ====================
# 参数
# ====================
drawing = False
color = (255, 0, 0)
size = 5
bg_color = (255, 255, 255)

screen.fill(bg_color)

# ====================
# 颜色按钮
# ====================
colors = {
    "红": (255, 0, 0),
    "绿": (0, 200, 0),
    "蓝": (0, 0, 255),
    "黑": (0, 0, 0)
}

buttons = {}
x = 10
for name, c in colors.items():
    buttons[name] = pygame.Rect(x, 10, 40, 30)
    x += 55

clear_btn = pygame.Rect(250, 10, 60, 30)

# ====================
# 主循环
# ====================
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                drawing = True
            if event.button == 3:
                color = bg_color

            # 颜色选择
            for name, rect in buttons.items():
                if rect.collidepoint(event.pos):
                    color = colors[name]

            if clear_btn.collidepoint(event.pos):
                screen.fill(bg_color)

        if event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                drawing = False

    # ====================
    # 绘画
    # ====================
    if drawing:
        mx, my = pygame.mouse.get_pos()
        pygame.draw.circle(screen, color, (mx, my), size)

    # ====================
    # 工具栏
    # ====================
    pygame.draw.rect(screen, (220, 220, 220), (0, 0, WIDTH, 50))

    for name, rect in buttons.items():
        pygame.draw.rect(screen, colors[name], rect)

    pygame.draw.rect(screen, (180, 180, 180), clear_btn)
    screen.blit(font.render("清屏", True, (0, 0, 0)), (265, 16))

    # 画笔大小
    size_text = font.render(f"大小:{size}", True, (0, 0, 0))
    screen.blit(size_text, (330, 16))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
