import pygame
import math
import random

# ====================
# 初始化
# ====================
pygame.init()
WIDTH, HEIGHT = 500, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("转盘抽奖")

font = pygame.font.SysFont("simhei", 22)
clock = pygame.time.Clock()

# ====================
# 奖项
# ====================
prizes = ["一等奖", "二等奖", "三等奖", "谢谢参与", "再接再厉", "幸运奖"]
colors = [(255, 99, 71), (135, 206, 250), (144, 238, 144),
          (255, 215, 0), (221, 160, 221), (175, 238, 238)]

num = len(prizes)
angle_per = 360 / num

# ====================
# 状态
# ====================
angle = 0
speed = 0
spinning = False
result = ""

button_rect = pygame.Rect(200, 420, 100, 40)

# ====================
# 主循环
# ====================
running = True
while running:
    screen.fill((30, 30, 40))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            if button_rect.collidepoint(event.pos) and not spinning:
                speed = random.uniform(15, 25)
                spinning = True
                result = ""

    # ====================
    # 转盘旋转
    # ====================
    if spinning:
        angle += speed
        speed -= 0.2
        if speed <= 0:
            speed = 0
            spinning = False
            index = int((360 - (angle % 360)) // angle_per)
            result = prizes[index]

    # ====================
    # 画转盘
    # ====================
    cx, cy = 250, 230
    r = 160

    for i in range(num):
        start = math.radians(angle + i * angle_per)
        end = math.radians(angle + (i + 1) * angle_per)

        points = [(cx, cy),
                  (cx + math.cos(start) * r, cy + math.sin(start) * r),
                  (cx + math.cos(end) * r, cy + math.sin(end) * r)]
        pygame.draw.polygon(screen, colors[i], points)

        tx = cx + math.cos(math.radians(angle + i *
                           angle_per + angle_per / 2)) * 100
        ty = cy + math.sin(math.radians(angle + i *
                           angle_per + angle_per / 2)) * 100
        text = font.render(prizes[i], True, (0, 0, 0))
        screen.blit(text, (tx - text.get_width() //
                    2, ty - text.get_height() // 2))

    # 指针
    pygame.draw.polygon(screen, (255, 0, 0), [
                        (cx, cy - 170), (cx - 10, cy - 140), (cx + 10, cy - 140)])

    # 按钮
    pygame.draw.rect(screen, (0, 200, 100), button_rect)
    btn_text = font.render("开始", True, (255, 255, 255))
    screen.blit(btn_text, (button_rect.x + 30, button_rect.y + 10))

    # 结果
    res = font.render("结果: " + result, True, (255, 215, 0))
    screen.blit(res, (160, 370))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
