import pygame
import sys

# 1. 初始化 Pygame
pygame.init()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (50, 120, 200)
RED = (200, 50, 50)
GRAY = (200, 200, 200)

# 屏幕设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame 成绩走势图")

# 字体设置 (请确保系统中有中文字体，Windows通常用 simhei.ttf)
try:
    font = pygame.font.SysFont("SimHei", 24)
    small_font = pygame.font.SysFont("SimHei", 18)
    title_font = pygame.font.SysFont("SimHei", 36)
except:
    font = pygame.font.SysFont("arial", 24)

# --- 2. 准备数据 ---
data = [75, 82, 78, 95, 88, 92, 98]  # 成绩数据
exams = ["第一次", "第二次", "第三次", "期中", "第五次", "第六次", "期末"]

# 图表边距和区域
MARGIN = 80
CHART_WIDTH = WIDTH - 2 * MARGIN
CHART_HEIGHT = HEIGHT - 2 * MARGIN

def draw_chart():
    screen.fill(WHITE)

    # 3. 绘制坐标轴
    # Y轴 (分数线)
    pygame.draw.line(screen, BLACK, (MARGIN, MARGIN), (MARGIN, HEIGHT - MARGIN), 2)
    # X轴 (场次线)
    pygame.draw.line(screen, BLACK, (MARGIN, HEIGHT - MARGIN), (WIDTH - MARGIN, HEIGHT - MARGIN), 2)

    # 4. 计算坐标并绘制参考线 (0-100分)
    for i in range(0, 11):
        score_val = i * 10
        y = (HEIGHT - MARGIN) - (score_val / 100 * CHART_HEIGHT)
        # 绘制水平灰色背景线
        if i > 0:
            pygame.draw.line(screen, GRAY, (MARGIN, y), (WIDTH - MARGIN, y), 1)
        # 绘制Y轴刻度文字
        txt = small_font.render(str(score_val), True, BLACK)
        screen.blit(txt, (MARGIN - 30, y - 10))

    # 5. 绘制折线和点
    points = []
    x_step = CHART_WIDTH / (len(data) - 1)

    for i, score in enumerate(data):
        # 计算每个点的像素位置
        x = MARGIN + i * x_step
        y = (HEIGHT - MARGIN) - (score / 100 * CHART_HEIGHT)
        points.append((x, y))

        # 绘制考试名称文字
        label = small_font.render(exams[i], True, BLACK)
        screen.blit(label, (x - 20, HEIGHT - MARGIN + 10))

        # 绘制分数数字
        score_txt = small_font.render(str(score), True, RED)
        screen.blit(score_txt, (x - 10, y - 25))

    # 绘制连接线
    if len(points) > 1:
        pygame.draw.lines(screen, BLUE, False, points, 3)

    # 绘制数据点圆圈
    for p in points:
        pygame.draw.circle(screen, RED, (int(p[0]), int(p[1])), 6)

    # 6. 绘制标题
    title = title_font.render("个人成绩走势分析 (Pygame版)", True, BLACK)
    screen.blit(title, (WIDTH // 2 - title.get_width() // 2, 20))

# --- 主循环 ---
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    draw_chart()
    pygame.display.flip()

pygame.quit()
sys.exit()