import pygame
import sys
import random
import math
from pygame.locals import *

# 初始化pygame
pygame.init()

# 屏幕设置
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 700
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("爱国知识小游戏")

# 颜色定义
BACKGROUND = (240, 248, 255)  # 淡蓝色背景
RED = (220, 20, 60)           # 中国红
GOLD = (255, 215, 0)          # 金色
BLUE = (70, 130, 180)         # 钢蓝色
WHITE = (255, 255, 255)
BLACK = (30, 30, 30)

# 字体
title_font = pygame.font.SysFont('simhei', 60, bold=True)
question_font = pygame.font.SysFont('simhei', 32)
option_font = pygame.font.SysFont('simhei', 28)
score_font = pygame.font.SysFont('simhei', 36)
button_font = pygame.font.SysFont('simhei', 32)

# 爱国知识题库
questions = [
    {
        "question": "中华人民共和国成立于哪一年？",
        "options": ["1945年", "1949年", "1950年", "1951年"],
        "answer": 1
    },
    {
        "question": "中国的首都是哪个城市？",
        "options": ["上海", "广州", "北京", "重庆"],
        "answer": 2
    },
    {
        "question": "五星红旗上有几颗五角星？",
        "options": ["3颗", "4颗", "5颗", "6颗"],
        "answer": 2
    },
    {
        "question": "中国的国歌是什么？",
        "options": ["《歌唱祖国》", "《义勇军进行曲》", "《我的祖国》", "《东方红》"],
        "answer": 1
    },
    {
        "question": "长江是亚洲第几长河？",
        "options": ["第一长河", "第二长河", "第三长河", "第四长河"],
        "answer": 2
    },
    {
        "question": "中国有多少个民族？",
        "options": ["50个", "55个", "56个", "58个"],
        "answer": 2
    },
    {
        "question": "端午节是为了纪念哪位爱国诗人？",
        "options": ["李白", "杜甫", "屈原", "白居易"],
        "answer": 2
    },
    {
        "question": "世界上最长的城墙是什么？",
        "options": ["英国哈德良长城", "中国万里长城", "印度长城", "罗马长城"],
        "answer": 1
    },
    {
        "question": "2022年冬奥会在中国哪个城市举办？",
        "options": ["哈尔滨", "北京", "上海", "广州"],
        "answer": 1
    },
    {
        "question": "以下哪个是中国自主研制的卫星导航系统？",
        "options": ["GPS", "伽利略", "北斗", "格洛纳斯"],
        "answer": 2
    }
]

# 游戏状态
class GameState:
    def __init__(self):
        self.mode = "menu"  # menu, quiz, puzzle, result
        self.score = 0
        self.current_question = 0
        self.total_questions = 5
        self.quiz_questions = []
        self.selected_option = -1
        self.correct_answer = -1
        self.show_feedback = False
        
        # 拼图设置
        self.puzzle_pieces = []
        self.puzzle_size = 3
        self.puzzle_completed = False
        self.init_puzzle()
    
    def init_puzzle(self):
        # 创建拼图块
        self.puzzle_pieces = []
        piece_width = 200
        piece_height = 200
        
        # 创建正确的拼图位置
        positions = []
        for i in range(self.puzzle_size):
            for j in range(self.puzzle_size):
                positions.append((j, i))
        
        # 打乱位置
        random.shuffle(positions)
        
        # 创建拼图块
        for idx, (row, col) in enumerate(positions):
            x = 300 + col * piece_width
            y = 200 + row * piece_height
            self.puzzle_pieces.append({
                "rect": pygame.Rect(x, y, piece_width, piece_height),
                "correct_pos": (row, col),
                "current_pos": (row, col),
                "image": pygame.Surface((piece_width, piece_height)),
                "idx": idx
            })
        
        # 设置拼图块颜色
        for i, piece in enumerate(self.puzzle_pieces):
            color = (random.randint(150, 200), random.randint(50, 100), random.randint(50, 100))
            piece["image"].fill(color)
            
            # 在拼图块上绘制编号
            font = pygame.font.SysFont('simhei', 80)
            text = font.render(str(i+1), True, WHITE)
            text_rect = text.get_rect(center=(piece["rect"].width//2, piece["rect"].height//2))
            piece["image"].blit(text, text_rect)
        
        self.puzzle_completed = False
    
    def start_quiz(self):
        self.mode = "quiz"
        self.score = 0
        self.current_question = 0
        self.quiz_questions = random.sample(questions, self.total_questions)
        self.show_feedback = False
    
    def start_puzzle(self):
        self.mode = "puzzle"
        self.init_puzzle()
    
    def check_puzzle_completion(self):
        for piece in self.puzzle_pieces:
            if piece["current_pos"] != piece["correct_pos"]:
                return False
        return True

# 创建游戏状态
game = GameState()

# 按钮类
class Button:
    def __init__(self, x, y, width, height, text, color, hover_color):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        self.hover_color = hover_color
        self.current_color = color
        self.text_surface = button_font.render(text, True, WHITE)
        self.text_rect = self.text_surface.get_rect(center=self.rect.center)
    
    def draw(self, surface):
        pygame.draw.rect(surface, self.current_color, self.rect, border_radius=12)
        pygame.draw.rect(surface, BLACK, self.rect, 3, border_radius=12)
        surface.blit(self.text_surface, self.text_rect)
    
    def check_hover(self, pos):
        if self.rect.collidepoint(pos):
            self.current_color = self.hover_color
            return True
        self.current_color = self.color
        return False
    
    def is_clicked(self, pos, event):
        if event.type == MOUSEBUTTONDOWN and event.button == 1:
            return self.rect.collidepoint(pos)
        return False

# 创建按钮
quiz_button = Button(SCREEN_WIDTH//2 - 150, 350, 300, 80, "知识问答挑战", RED, (255, 99, 71))
puzzle_button = Button(SCREEN_WIDTH//2 - 150, 470, 300, 80, "中国地图拼图", BLUE, (100, 149, 237))
next_button = Button(SCREEN_WIDTH//2 - 100, 550, 200, 60, "下一题", BLUE, (100, 149, 237))
result_button = Button(SCREEN_WIDTH//2 - 100, 550, 200, 60, "查看结果", GOLD, (255, 165, 0))
menu_button = Button(SCREEN_WIDTH//2 - 100, 550, 200, 60, "返回菜单", RED, (255, 99, 71))
restart_button = Button(SCREEN_WIDTH//2 - 100, 550, 200, 60, "重新开始", BLUE, (100, 149, 237))

def draw_menu():
    # 绘制标题
    title_text = title_font.render("爱国知识小游戏", True, RED)
    title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, 150))
    
    # 绘制副标题
    subtitle_text = question_font.render("学习爱国知识，弘扬爱国精神", True, BLUE)
    subtitle_rect = subtitle_text.get_rect(center=(SCREEN_WIDTH//2, 220))
    
    # 绘制装饰性图案
    pygame.draw.rect(screen, GOLD, (SCREEN_WIDTH//2 - 200, 250, 400, 10), border_radius=5)
    pygame.draw.circle(screen, RED, (SCREEN_WIDTH//2 - 200, 255), 15)
    pygame.draw.circle(screen, RED, (SCREEN_WIDTH//2 + 200, 255), 15)
    
    # 绘制按钮
    screen.blit(title_text, title_rect)
    screen.blit(subtitle_text, subtitle_rect)
    quiz_button.draw(screen)
    puzzle_button.draw(screen)
    
    # 绘制装饰元素
    for i in range(5):
        x = 150 + i * 180
        pygame.draw.circle(screen, RED, (x, 600), 15)
        pygame.draw.circle(screen, GOLD, (x+40, 650), 15)

def draw_quiz():
    # 绘制标题
    title_text = title_font.render("爱国知识问答", True, RED)
    title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, 80))
    screen.blit(title_text, title_rect)
    
    # 绘制进度
    progress_text = question_font.render(f"问题: {game.current_question+1}/{game.total_questions}", True, BLUE)
    progress_rect = progress_text.get_rect(left=50, top=30)
    screen.blit(progress_text, progress_rect)
    
    # 绘制分数
    score_text = question_font.render(f"得分: {game.score}", True, BLUE)
    score_rect = score_text.get_rect(right=SCREEN_WIDTH-50, top=30)
    screen.blit(score_text, score_rect)
    
    # 绘制问题
    if game.current_question < len(game.quiz_questions):
        question = game.quiz_questions[game.current_question]
        q_text = question_font.render(question["question"], True, BLACK)
        q_rect = q_text.get_rect(center=(SCREEN_WIDTH//2, 180))
        screen.blit(q_text, q_rect)
        
        # 绘制选项
        option_height = 70
        option_width = 600
        option_y_start = 250
        
        for i, option in enumerate(question["options"]):
            y = option_y_start + i * option_height
            
            # 选项背景
            option_color = WHITE
            if game.show_feedback:
                if i == question["answer"]:
                    option_color = (152, 251, 152)  # 正确答案绿色
                elif i == game.selected_option and i != question["answer"]:
                    option_color = (255, 182, 193)  # 错误答案红色
            
            pygame.draw.rect(screen, option_color, 
                            (SCREEN_WIDTH//2 - option_width//2, y, 
                             option_width, option_height - 10), 
                            border_radius=10)
            pygame.draw.rect(screen, BLACK, 
                            (SCREEN_WIDTH//2 - option_width//2, y, 
                             option_width, option_height - 10), 
                            2, border_radius=10)
            
            # 选项文本
            opt_text = option_font.render(f"{chr(65+i)}. {option}", True, BLACK)
            opt_rect = opt_text.get_rect(center=(SCREEN_WIDTH//2, y + (option_height - 10)//2))
            screen.blit(opt_text, opt_rect)
        
        # 绘制反馈
        if game.show_feedback:
            if game.selected_option == question["answer"]:
                feedback = "回答正确！"
                color = (0, 100, 0)  # 深绿色
            else:
                feedback = f"回答错误！正确答案是: {chr(65 + question['answer'])}"
                color = (139, 0, 0)  # 深红色
                
            feedback_text = option_font.render(feedback, True, color)
            feedback_rect = feedback_text.get_rect(center=(SCREEN_WIDTH//2, 520))
            screen.blit(feedback_text, feedback_rect)
            
            # 绘制按钮
            if game.current_question < game.total_questions - 1:
                next_button.draw(screen)
            else:
                result_button.draw(screen)
    
    # 装饰元素
    for i in range(3):
        pygame.draw.circle(screen, RED, (50 + i*100, 600), 20, 3)
        pygame.draw.circle(screen, GOLD, (SCREEN_WIDTH - 50 - i*100, 650), 15, 3)

def draw_puzzle():
    # 绘制标题
    title_text = title_font.render("中国地图拼图", True, BLUE)
    title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, 80))
    screen.blit(title_text, title_rect)
    
    # 绘制说明
    instruction = "将拼图块拖动到正确位置，完成中国地图"
    instr_text = question_font.render(instruction, True, BLACK)
    instr_rect = instr_text.get_rect(center=(SCREEN_WIDTH//2, 140))
    screen.blit(instr_text, instr_rect)
    
    # 绘制拼图块
    for piece in game.puzzle_pieces:
        screen.blit(piece["image"], piece["rect"])
        pygame.draw.rect(screen, BLACK, piece["rect"], 3)
    
    # 绘制完成信息
    if game.puzzle_completed:
        pygame.draw.rect(screen, (240, 255, 240), (SCREEN_WIDTH//2 - 200, 20, 400, 50), border_radius=10)
        pygame.draw.rect(screen, (0, 100, 0), (SCREEN_WIDTH//2 - 200, 20, 400, 50), 2, border_radius=10)
        complete_text = score_font.render("拼图完成！中国地图复原成功！", True, (0, 100, 0))
        complete_rect = complete_text.get_rect(center=(SCREEN_WIDTH//2, 45))
        screen.blit(complete_text, complete_rect)
    
    # 绘制按钮
    menu_button.draw(screen)
    restart_button.draw(screen)
    
    # 绘制装饰元素
    pygame.draw.polygon(screen, RED, [(50, 600), (70, 550), (90, 600)])
    pygame.draw.polygon(screen, RED, [(SCREEN_WIDTH-50, 650), (SCREEN_WIDTH-70, 600), (SCREEN_WIDTH-90, 650)])
    for i in range(5):
        pygame.draw.circle(screen, GOLD, (150 + i*50, 650), 10)

def draw_result():
    # 绘制背景
    pygame.draw.rect(screen, (240, 248, 255), (100, 100, SCREEN_WIDTH-200, SCREEN_HEIGHT-200), border_radius=20)
    pygame.draw.rect(screen, RED, (100, 100, SCREEN_WIDTH-200, SCREEN_HEIGHT-200), 4, border_radius=20)
    
    # 绘制标题
    title_text = title_font.render("答题结果", True, RED)
    title_rect = title_text.get_rect(center=(SCREEN_WIDTH//2, 180))
    screen.blit(title_text, title_rect)
    
    # 绘制分数
    score_percent = int(game.score / game.total_questions * 100)
    score_text = score_font.render(f"最终得分: {game.score}/{game.total_questions} ({score_percent}%)", True, BLUE)
    score_rect = score_text.get_rect(center=(SCREEN_WIDTH//2, 280))
    screen.blit(score_text, score_rect)
    
    # 绘制评价
    if score_percent == 100:
        comment = "太棒了！您是一位爱国知识专家！"
        color = (0, 100, 0)  # 深绿色
    elif score_percent >= 70:
        comment = "很好！您对祖国了解很深！"
        color = (0, 100, 0)
    elif score_percent >= 40:
        comment = "不错！继续学习爱国知识！"
        color = (218, 165, 32)  # 金色
    else:
        comment = "加油！多了解我们伟大的祖国！"
        color = (139, 0, 0)  # 深红色
    
    comment_text = score_font.render(comment, True, color)
    comment_rect = comment_text.get_rect(center=(SCREEN_WIDTH//2, 350))
    screen.blit(comment_text, comment_rect)
    
    # 绘制鼓励语
    encouragement = "热爱祖国是中华民族的传统美德，让我们共同建设美好家园！"
    encourage_text = question_font.render(encouragement, True, BLACK)
    encourage_rect = encourage_text.get_rect(center=(SCREEN_WIDTH//2, 420))
    screen.blit(encourage_text, encourage_rect)
    
    # 绘制按钮
    menu_button.draw(screen)
    restart_button.draw(screen)
    
    # 绘制装饰元素
    pygame.draw.circle(screen, RED, (150, 150), 30, 5)
    pygame.draw.circle(screen, GOLD, (SCREEN_WIDTH-150, SCREEN_HEIGHT-150), 30, 5)
    for i in range(3):
        pygame.draw.circle(screen, BLUE, (200 + i*100, 500), 10)

# 主游戏循环
dragging = False
selected_piece = None
offset_x, offset_y = 0, 0

clock = pygame.time.Clock()

while True:
    mouse_pos = pygame.mouse.get_pos()
    
    # 事件处理
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        
        # 菜单界面
        if game.mode == "menu":
            quiz_button.check_hover(mouse_pos)
            puzzle_button.check_hover(mouse_pos)
            
            if quiz_button.is_clicked(mouse_pos, event):
                game.start_quiz()
            elif puzzle_button.is_clicked(mouse_pos, event):
                game.start_puzzle()
        
        # 知识问答界面
        elif game.mode == "quiz":
            if not game.show_feedback:
                if event.type == MOUSEBUTTONDOWN:
                    option_height = 70
                    option_y_start = 250
                    
                    for i in range(4):
                        y = option_y_start + i * option_height
                        option_rect = pygame.Rect(SCREEN_WIDTH//2 - 300, y, 600, option_height - 10)
                        
                        if option_rect.collidepoint(mouse_pos):
                            game.selected_option = i
                            question = game.quiz_questions[game.current_question]
                            
                            if i == question["answer"]:
                                game.score += 1
                            
                            game.show_feedback = True
            else:
                if game.current_question < game.total_questions - 1:
                    next_button.check_hover(mouse_pos)
                    if next_button.is_clicked(mouse_pos, event):
                        game.current_question += 1
                        game.show_feedback = False
                        game.selected_option = -1
                else:
                    result_button.check_hover(mouse_pos)
                    if result_button.is_clicked(mouse_pos, event):
                        game.mode = "result"
        
        # 拼图界面
        elif game.mode == "puzzle":
            menu_button.check_hover(mouse_pos)
            restart_button.check_hover(mouse_pos)
            
            if menu_button.is_clicked(mouse_pos, event):
                game.mode = "menu"
            elif restart_button.is_clicked(mouse_pos, event):
                game.start_puzzle()
            
            # 拼图块拖动
            if event.type == MOUSEBUTTONDOWN and event.button == 1:
                for piece in game.puzzle_pieces:
                    if piece["rect"].collidepoint(mouse_pos):
                        dragging = True
                        selected_piece = piece
                        offset_x = piece["rect"].x - mouse_pos[0]
                        offset_y = piece["rect"].y - mouse_pos[1]
                        break
            
            elif event.type == MOUSEBUTTONUP and event.button == 1:
                if dragging and selected_piece:
                    # 确定当前所在网格位置
                    grid_x = round((selected_piece["rect"].x - 300) / 200)
                    grid_y = round((selected_piece["rect"].y - 200) / 200)
                    
                    # 确保在网格范围内
                    if 0 <= grid_x < game.puzzle_size and 0 <= grid_y < game.puzzle_size:
                        selected_piece["current_pos"] = (grid_y, grid_x)
                        selected_piece["rect"].x = 300 + grid_x * 200
                        selected_piece["rect"].y = 200 + grid_y * 200
                    
                    # 检查拼图是否完成
                    game.puzzle_completed = game.check_puzzle_completion()
                    
                dragging = False
                selected_piece = None
            
            elif event.type == MOUSEMOTION and dragging and selected_piece:
                selected_piece["rect"].x = mouse_pos[0] + offset_x
                selected_piece["rect"].y = mouse_pos[1] + offset_y
        
        # 结果界面
        elif game.mode == "result":
            menu_button.check_hover(mouse_pos)
            restart_button.check_hover(mouse_pos)
            
            if menu_button.is_clicked(mouse_pos, event):
                game.mode = "menu"
            elif restart_button.is_clicked(mouse_pos, event):
                game.start_quiz()
    
    # 绘制界面
    screen.fill(BACKGROUND)
    
    # 绘制背景装饰
    for i in range(20):
        x = random.randint(0, SCREEN_WIDTH)
        y = random.randint(0, SCREEN_HEIGHT)
        size = random.randint(2, 5)
        color = random.choice([(255, 200, 200), (200, 200, 255), (255, 255, 200)])
        pygame.draw.circle(screen, color, (x, y), size)
    
    # 根据游戏模式绘制不同界面
    if game.mode == "menu":
        draw_menu()
    elif game.mode == "quiz":
        draw_quiz()
    elif game.mode == "puzzle":
        draw_puzzle()
    elif game.mode == "result":
        draw_result()
    
    # 绘制版权信息
    footer_text = option_font.render("爱国教育小游戏 © 2023", True, (100, 100, 100))
    footer_rect = footer_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT - 20))
    screen.blit(footer_text, footer_rect)
    
    pygame.display.flip()
    clock.tick(60)