import pygame
import sys
import math
import random

# 初始化 Pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 800, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("🍉 扎西瓜")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 50, 50)
DARK_RED = (200, 0, 0)
GREEN = (50, 200, 50)
DARK_GREEN = (0, 150, 0)
LIGHT_GREEN = (144, 238, 144)
YELLOW = (255, 255, 100)
GOLD = (255, 215, 0)
ORANGE = (255, 165, 0)
PINK = (255, 182, 193)
LIGHT_PINK = (255, 220, 225)
DARK_PINK = (255, 150, 180)
GRAY = (150, 150, 150)
DARK_GRAY = (80, 80, 80)
LIGHT_GRAY = (200, 200, 200)
BROWN = (139, 69, 19)
LIGHT_BROWN = (160, 120, 80)
SKY_BLUE = (135, 206, 235)
WATERMELON_GREEN = (60, 120, 40)
WATERMELON_LIGHT = (100, 180, 80)
WATERMELON_RED = (255, 50, 50)
WATERMELON_DARK_RED = (200, 20, 20)
SEED_BLACK = (30, 30, 30)

# 帧率控制
clock = pygame.time.Clock()
FPS = 60

# 中文字体
def get_chinese_font(size):
    font_names = ["SimHei", "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", "WenQuanYi Micro Hei", "Arial"]
    for name in font_names:
        try:
            return pygame.font.SysFont(name, size)
        except:
            continue
    return pygame.font.Font(None, size)

font = get_chinese_font(28)
small_font = get_chinese_font(18)
big_font = get_chinese_font(48)
huge_font = get_chinese_font(72)

# 目标点类
class TargetPoint:
    def __init__(self, x, y, size=12):
        self.x = x
        self.y = y
        self.size = size
        self.radius = size
        self.alive = True
        self.pulse = 0
        self.pulse_direction = 1
        self.hit_animation = 0
        self.hit = False
    
    def update(self):
        if not self.alive:
            return
        
        # 脉冲动画
        self.pulse += 0.05 * self.pulse_direction
        if self.pulse > 1 or self.pulse < 0:
            self.pulse_direction *= -1
        
        # 击中动画
        if self.hit:
            self.hit_animation += 1
            if self.hit_animation > 20:
                self.alive = False
    
    def draw(self, surface):
        if not self.alive:
            return
        
        # 目标光环
        pulse_size = self.radius + self.pulse * 4
        for i in range(3):
            alpha = 80 - i * 25
            ring_radius = pulse_size + i * 8
            ring_surf = pygame.Surface((ring_radius * 2, ring_radius * 2), pygame.SRCALPHA)
            temp_surf = pygame.Surface((ring_radius * 2, ring_radius * 2), pygame.SRCALPHA)
            pygame.draw.circle(temp_surf, (255, 200, 50, alpha), (ring_radius, ring_radius), ring_radius)
            temp_surf.set_alpha(alpha)
            ring_surf.blit(temp_surf, (0, 0))
            surface.blit(ring_surf, (self.x - ring_radius, self.y - ring_radius))
        
        # 目标点 - 红色十字准心
        if self.hit:
            # 击中爆炸效果
            for i in range(8):
                angle = i * math.pi / 4 + self.hit_animation * 0.2
                dist = self.hit_animation * 2
                px = self.x + dist * math.cos(angle)
                py = self.y + dist * math.sin(angle)
                size = max(2, 8 - self.hit_animation * 0.3)
                pygame.draw.circle(surface, (255, 200, 50), (int(px), int(py)), int(size))
            return
        
        # 外圈
        pygame.draw.circle(surface, (255, 200, 50), (int(self.x), int(self.y)), self.radius + 4, 2)
        
        # 内圈（红色）
        inner_radius = self.radius - 2
        pygame.draw.circle(surface, RED, (int(self.x), int(self.y)), inner_radius)
        pygame.draw.circle(surface, DARK_RED, (int(self.x), int(self.y)), inner_radius, 1)
        
        # 十字准心
        cross_len = self.radius + 6
        pygame.draw.line(surface, WHITE, (self.x - cross_len, self.y), (self.x + cross_len, self.y), 2)
        pygame.draw.line(surface, WHITE, (self.x, self.y - cross_len), (self.x, self.y + cross_len), 2)
        
        # 中心点
        pygame.draw.circle(surface, WHITE, (int(self.x), int(self.y)), 2)

# 西瓜类
class Watermelon:
    def __init__(self, x, y, size=120):
        self.x = x
        self.y = y
        self.size = size
        self.rotation = 0
        self.target_points = []
        self.create_targets()
        self.hit_count = 0
        self.max_hits = 5
        self.alive = True
        self.combo = 0
        self.combo_timer = 0
    
    def create_targets(self):
        self.target_points = []
        # 在西瓜表面生成目标点
        num_targets = 5
        for i in range(num_targets):
            angle = random.uniform(0, 2 * math.pi)
            distance = random.uniform(20, self.size // 2 - 10)
            x = self.x + distance * math.cos(angle)
            y = self.y + distance * math.sin(angle) - 10
            size = random.randint(8, 14)
            target = TargetPoint(x, y, size)
            self.target_points.append(target)
    
    def update(self):
        # 旋转动画
        self.rotation += 0.005
        
        # 更新目标点
        alive_targets = 0
        for target in self.target_points:
            target.update()
            if target.alive:
                alive_targets += 1
        
        # 检查是否所有目标都被击中
        if alive_targets == 0 and self.alive:
            self.alive = False
        
        # 连击计时器
        if self.combo_timer > 0:
            self.combo_timer -= 1
            if self.combo_timer == 0:
                self.combo = 0
    
    def check_hit(self, pos):
        if not self.alive:
            return False
        
        mouse_x, mouse_y = pos
        for target in self.target_points:
            if target.alive and not target.hit:
                dist = math.hypot(mouse_x - target.x, mouse_y - target.y)
                if dist < target.radius + 10:
                    target.hit = True
                    self.hit_count += 1
                    self.combo += 1
                    self.combo_timer = 60
                    return True
        return False
    
    def draw(self, surface):
        if not self.alive:
            return
        
        cx, cy = self.x, self.y
        size = self.size
        
        # 西瓜阴影
        shadow_surf = pygame.Surface((size + 20, size + 20), pygame.SRCALPHA)
        pygame.draw.ellipse(shadow_surf, (0, 0, 0, 50), 
                          (10, 10, size, size - 5))
        surface.blit(shadow_surf, (cx - size//2 - 10, cy - size//2))
        
        # 西瓜身体 - 椭圆
        w_rect = pygame.Rect(cx - size//2, cy - size//2 + 5, size, size - 10)
        
        # 西瓜皮（绿色渐变）
        for i in range(5):
            offset = i * 2
            pygame.draw.ellipse(surface, 
                              (60 - i * 5, 140 - i * 10, 50 - i * 5),
                              (w_rect.x + offset, w_rect.y + offset, 
                               w_rect.width - offset * 2, w_rect.height - offset * 2))
        
        # 西瓜内部（红色）
        inner_rect = pygame.Rect(cx - size//2 + 15, cy - size//2 + 20, 
                                size - 30, size - 40)
        pygame.draw.ellipse(surface, WATERMELON_RED, inner_rect)
        
        # 西瓜瓤纹理
        for i in range(30):
            angle = random.uniform(0, 2 * math.pi)
            dist = random.uniform(0, size//2 - 20)
            px = cx + dist * math.cos(angle)
            py = cy + 5 + dist * math.sin(angle) * 0.8
            alpha = random.randint(20, 60)
            dot_surf = pygame.Surface((4, 4), pygame.SRCALPHA)
            temp_surf = pygame.Surface((4, 4), pygame.SRCALPHA)
            pygame.draw.circle(temp_surf, (200, 30, 30), (2, 2), 2)
            temp_surf.set_alpha(alpha)
            dot_surf.blit(temp_surf, (0, 0))
            surface.blit(dot_surf, (int(px) - 2, int(py) - 2))
        
        # 西瓜籽
        seeds = [
            (cx - 25, cy - 10, 4, 7),
            (cx + 20, cy - 15, 4, 7),
            (cx - 10, cy + 15, 4, 7),
            (cx + 30, cy + 10, 4, 7),
            (cx - 40, cy + 5, 4, 7),
            (cx + 10, cy - 25, 4, 7),
        ]
        for sx, sy, sw, sh in seeds:
            pygame.draw.ellipse(surface, SEED_BLACK, (sx - sw//2, sy - sh//2, sw, sh))
        
        # 绘制目标点
        for target in self.target_points:
            target.draw(surface)
        
        # 显示击中进度
        progress = self.hit_count / self.max_hits
        bar_width = 100
        bar_height = 8
        bar_x = cx - bar_width//2
        bar_y = cy + size//2 + 15
        
        pygame.draw.rect(surface, GRAY, (bar_x, bar_y, bar_width, bar_height), border_radius=4)
        pygame.draw.rect(surface, GREEN, (bar_x, bar_y, bar_width * min(progress, 1), bar_height), border_radius=4)
        pygame.draw.rect(surface, BLACK, (bar_x, bar_y, bar_width, bar_height), 1, border_radius=4)
        
        # 进度文字
        progress_text = small_font.render(f"{self.hit_count}/{self.max_hits}", True, WHITE)
        progress_rect = progress_text.get_rect(center=(cx, bar_y + bar_height + 15))
        surface.blit(progress_text, progress_rect)

# 粒子系统
class Particle:
    def __init__(self, x, y, color, vx=None, vy=None, life=30, size=4):
        self.x = x
        self.y = y
        self.vx = vx if vx is not None else random.uniform(-5, 5)
        self.vy = vy if vy is not None else random.uniform(-8, -2)
        self.life = life
        self.max_life = life
        self.size = size
        self.color = color
        self.alive = True
        self.gravity = 0.2
    
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += self.gravity
        self.life -= 1
        if self.life <= 0:
            self.alive = False
    
    def draw(self, surface):
        if not self.alive:
            return
        alpha = int(255 * (self.life / self.max_life))
        size = int(self.size * (self.life / self.max_life))
        if size < 1:
            return
        particle_surf = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)
        temp_surf = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)
        pygame.draw.circle(temp_surf, self.color, (size, size), size)
        temp_surf.set_alpha(alpha)
        particle_surf.blit(temp_surf, (0, 0))
        surface.blit(particle_surf, (int(self.x) - size, int(self.y) - size))

# 游戏主类
class WatermelonGame:
    def __init__(self):
        self.watermelon = Watermelon(WIDTH // 2, HEIGHT // 2 - 20, 140)
        self.score = 0
        self.total_hits = 0
        self.misses = 0
        self.time = 0
        self.game_time = 60  # 60秒游戏时间
        self.game_over = False
        self.win = False
        self.particles = []
        self.combo_display = 0
        self.combo_display_timer = 0
        self.difficulty = 1
        self.target_spawn_timer = 0
        self.max_targets = 5
        
        # 统计
        self.perfect_hits = 0
        self.best_combo = 0
    
    def update(self, keys):
        if self.game_over or self.win:
            if keys[pygame.K_r]:
                self.__init__()
            return
        
        # 计时
        self.time += 1 / FPS
        if self.time >= self.game_time:
            self.game_over = True
            return
        
        # 更新西瓜
        self.watermelon.update()
        
        # 检查西瓜是否被完全扎完
        if not self.watermelon.alive:
            self.win = True
            return
        
        # 更新粒子
        for p in self.particles[:]:
            p.update()
            if not p.alive:
                self.particles.remove(p)
        
        # 连击显示
        if self.combo_display_timer > 0:
            self.combo_display_timer -= 1
    
    def handle_click(self, pos):
        if self.game_over or self.win:
            return
        
        # 检查是否击中目标
        if self.watermelon.check_hit(pos):
            self.total_hits += 1
            self.score += 10 * (1 + self.watermelon.combo // 3)
            
            # 更新最佳连击
            if self.watermelon.combo > self.best_combo:
                self.best_combo = self.watermelon.combo
            
            # 连击显示
            self.combo_display = self.watermelon.combo
            self.combo_display_timer = 30
            
            # 粒子效果
            for _ in range(20):
                color = random.choice([RED, YELLOW, ORANGE, PINK, (255, 200, 50)])
                p = Particle(pos[0], pos[1], color, 
                           random.uniform(-6, 6), random.uniform(-8, -2),
                           random.randint(20, 40), random.randint(3, 6))
                self.particles.append(p)
            
            # 检查是否完成
            if self.watermelon.hit_count >= self.watermelon.max_hits:
                self.win = True
        else:
            # 未击中 - 产生提示粒子
            self.misses += 1
            for _ in range(8):
                p = Particle(pos[0], pos[1], GRAY,
                           random.uniform(-3, 3), random.uniform(-4, -1),
                           15, 3)
                self.particles.append(p)
    
    def draw(self, surface):
        # 背景 - 渐变
        for y in range(HEIGHT):
            color = (220 - y * 0.1, 240 - y * 0.1, 255 - y * 0.05)
            pygame.draw.line(surface, color, (0, y), (WIDTH, y))
        
        # 装饰 - 草地
        for i in range(0, WIDTH, 20):
            grass_height = 10 + math.sin(i * 0.1 + self.time) * 5
            pygame.draw.line(surface, (60, 160, 60), 
                           (i, HEIGHT - 20), (i, HEIGHT - 20 - grass_height), 2)
            pygame.draw.line(surface, (80, 180, 80), 
                           (i + 10, HEIGHT - 20), (i + 10, HEIGHT - 20 - grass_height * 0.7), 2)
        
        # 绘制西瓜
        self.watermelon.draw(surface)
        
        # 绘制粒子
        for p in self.particles:
            p.draw(surface)
        
        # UI
        self.draw_ui(surface)
        
        # 游戏结束/胜利
        if self.game_over:
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 180))
            surface.blit(overlay, (0, 0))
            
            game_over_text = big_font.render("⏰ 时间到！", True, RED)
            text_rect = game_over_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 60))
            surface.blit(game_over_text, text_rect)
            
            score_text = font.render(f"得分: {self.score}", True, WHITE)
            score_rect = score_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
            surface.blit(score_text, score_rect)
            
            hits_text = font.render(f"击中: {self.total_hits}  失误: {self.misses}", True, WHITE)
            hits_rect = hits_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40))
            surface.blit(hits_text, hits_rect)
            
            if self.best_combo > 0:
                combo_text = font.render(f"最佳连击: {self.best_combo}", True, GOLD)
                combo_rect = combo_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 80))
                surface.blit(combo_text, combo_rect)
            
            restart_text = font.render("按 R 重新开始", True, WHITE)
            restart_rect = restart_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 130))
            surface.blit(restart_text, restart_rect)
        
        if self.win:
            overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 180))
            surface.blit(overlay, (0, 0))
            
            win_text = big_font.render("🎉 西瓜扎完了！", True, GREEN)
            text_rect = win_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 60))
            surface.blit(win_text, text_rect)
            
            score_text = font.render(f"得分: {self.score}", True, WHITE)
            score_rect = score_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
            surface.blit(score_text, score_rect)
            
            time_text = font.render(f"用时: {int(self.time)} 秒", True, WHITE)
            time_rect = time_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40))
            surface.blit(time_text, time_rect)
            
            if self.best_combo > 0:
                combo_text = font.render(f"最佳连击: {self.best_combo}", True, GOLD)
                combo_rect = combo_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 80))
                surface.blit(combo_text, combo_rect)
            
            restart_text = font.render("按 R 重新开始", True, WHITE)
            restart_rect = restart_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 130))
            surface.blit(restart_text, restart_rect)
    
    def draw_ui(self, surface):
        # 分数面板
        ui_bg = pygame.Surface((WIDTH, 60), pygame.SRCALPHA)
        ui_bg.fill((0, 0, 0, 80))
        surface.blit(ui_bg, (0, 0))
        
        # 得分
        score_text = font.render(f"⭐ {self.score}", True, GOLD)
        surface.blit(score_text, (20, 10))
        
        # 时间
        time_left = max(0, int(self.game_time - self.time))
        time_color = GREEN if time_left > 20 else ORANGE if time_left > 10 else RED
        time_text = font.render(f"⏱️ {time_left}s", True, time_color)
        surface.blit(time_text, (180, 10))
        
        # 击中数
        hits_text = font.render(f"🎯 {self.total_hits}", True, WHITE)
        surface.blit(hits_text, (340, 10))
        
        # 连击
        if self.combo_display_timer > 0 and self.combo_display >= 2:
            combo_text = big_font.render(f"🔥 {self.combo_display} 连击!", True, ORANGE)
            combo_rect = combo_text.get_rect(center=(WIDTH // 2, 100))
            surface.blit(combo_text, combo_rect)
        
        # 进度
        progress = self.watermelon.hit_count / self.watermelon.max_hits
        bar_width = 150
        bar_height = 12
        bar_x = WIDTH - bar_width - 20
        bar_y = 15
        
        pygame.draw.rect(surface, (60, 60, 60), (bar_x, bar_y, bar_width, bar_height), border_radius=6)
        pygame.draw.rect(surface, (255, 50, 50), (bar_x, bar_y, bar_width * progress, bar_height), border_radius=6)
        pygame.draw.rect(surface, WHITE, (bar_x, bar_y, bar_width, bar_height), 2, border_radius=6)
        
        progress_text = small_font.render(f"{self.watermelon.hit_count}/{self.watermelon.max_hits}", True, WHITE)
        progress_rect = progress_text.get_rect(center=(bar_x + bar_width//2, bar_y + bar_height//2))
        surface.blit(progress_text, progress_rect)
        
        # 提示
        if self.time < 5:
            hint = font.render("⚡ 快扎！时间不多了！", True, RED)
            hint_rect = hint.get_rect(center=(WIDTH // 2, HEIGHT - 40))
            surface.blit(hint, hint_rect)

# 主游戏函数
def main():
    game = WatermelonGame()
    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:  # 左键
                    game.handle_click(event.pos)
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    game = WatermelonGame()
        
        keys = pygame.key.get_pressed()
        
        # 更新游戏
        game.update(keys)
        
        # 绘制
        game.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()