import tkinter as tk
from tkinter import messagebox
import random
import math
import os

class FlappyBird:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("🐦 像素鸟闯关 🐦")
        self.window.geometry("500x700")
        self.window.configure(bg='#1a1a2e')
        self.window.resizable(False, False)
        
        # 游戏设置
        self.width = 450
        self.height = 600
        self.gravity = 0.5
        self.jump_strength = -8
        self.pipe_width = 60
        self.pipe_gap = 150
        self.pipe_speed = 3
        self.bird_size = 25
        self.ground_height = 50
        
        # 游戏状态
        self.game_started = False
        self.game_over = False
        self.paused = False
        self.score = 0
        self.high_score = 0
        self.best_score = 0
        
        # 加载最高分
        self.load_high_score()
        
        # 创建界面
        self.create_widgets()
        
        # 初始化游戏对象
        self.init_game_objects()
        
        # 绑定事件
        self.window.bind('<space>', self.on_space)
        self.window.bind('<KeyPress>', self.on_key_press)
        self.window.bind('<Button-1>', self.on_click)
        self.window.focus_set()
        
    def create_widgets(self):
        """创建界面组件"""
        # 标题
        title_frame = tk.Frame(self.window, bg='#16213e', height=50)
        title_frame.pack(fill=tk.X)
        title_frame.pack_propagate(False)
        
        tk.Label(
            title_frame,
            text="🐦 像素鸟闯关 🐦",
            font=('微软雅黑', 20, 'bold'),
            bg='#16213e',
            fg='#f0c27f'
        ).pack(expand=True)
        
        # 游戏画布
        self.canvas = tk.Canvas(
            self.window,
            width=self.width,
            height=self.height,
            bg='#87CEEB',
            highlightthickness=0
        )
        self.canvas.pack(pady=5)
        
        # 绘制背景元素
        self.draw_background()
        
        # 分数显示
        self.score_display = self.canvas.create_text(
            self.width // 2,
            40,
            text="0",
            font=('Arial', 36, 'bold'),
            fill='white',
            tags='score'
        )
        
        # 最高分显示
        self.high_score_display = self.canvas.create_text(
            self.width - 10,
            20,
            text=f"🏆 {self.high_score}",
            font=('Arial', 14, 'bold'),
            fill='#f1c40f',
            anchor='ne',
            tags='high_score'
        )
        
        # 控制面板
        control_frame = tk.Frame(self.window, bg='#1a1a2e', height=50)
        control_frame.pack(fill=tk.X, padx=10, pady=5)
        control_frame.pack_propagate(False)
        
        tk.Button(
            control_frame,
            text="🔄 重新开始",
            font=('微软雅黑', 11, 'bold'),
            bg='#2ecc71',
            fg='white',
            relief=tk.FLAT,
            padx=15,
            pady=5,
            command=self.restart_game
        ).pack(side=tk.LEFT, padx=5)
        
        tk.Button(
            control_frame,
            text="⏸ 暂停",
            font=('微软雅黑', 11, 'bold'),
            bg='#f39c12',
            fg='white',
            relief=tk.FLAT,
            padx=15,
            pady=5,
            command=self.toggle_pause
        ).pack(side=tk.LEFT, padx=5)
        
        # 难度选择
        self.difficulty_var = tk.StringVar(value="normal")
        difficulties = [("简单", "easy"), ("普通", "normal"), ("困难", "hard")]
        
        diff_frame = tk.Frame(control_frame, bg='#1a1a2e')
        diff_frame.pack(side=tk.LEFT, padx=20)
        
        tk.Label(
            diff_frame,
            text="难度:",
            font=('微软雅黑', 10),
            bg='#1a1a2e',
            fg='#ecf0f1'
        ).pack(side=tk.LEFT)
        
        for text, value in difficulties:
            tk.Radiobutton(
                diff_frame,
                text=text,
                variable=self.difficulty_var,
                value=value,
                bg='#1a1a2e',
                fg='#ecf0f1',
                selectcolor='#1a1a2e',
                font=('微软雅黑', 9),
                command=self.change_difficulty
            ).pack(side=tk.LEFT, padx=3)
        
        # 底部提示
        info_frame = tk.Frame(self.window, bg='#16213e', height=30)
        info_frame.pack(fill=tk.X, side=tk.BOTTOM)
        info_frame.pack_propagate(False)
        
        self.info_label = tk.Label(
            info_frame,
            text="🎮 按 空格键/点击 跳跃 | 按 P 暂停",
            font=('微软雅黑', 9),
            bg='#16213e',
            fg='#bdc3c7'
        )
        self.info_label.pack(expand=True)
        
    def draw_background(self):
        """绘制背景"""
        # 天空渐变（用多个矩形模拟）
        for i in range(10):
            y = i * (self.height - self.ground_height) // 10
            color = f'#{int(135 - i*3):02x}{int(206 - i*4):02x}{int(235 - i*5):02x}'
            self.canvas.create_rectangle(
                0, y,
                self.width, y + (self.height - self.ground_height) // 10 + 1,
                fill=color,
                outline=''
            )
        
        # 地面
        self.ground = self.canvas.create_rectangle(
            0,
            self.height - self.ground_height,
            self.width,
            self.height,
            fill='#8B7355',
            outline='#6B5345',
            tags='ground'
        )
        
        # 草地
        self.canvas.create_rectangle(
            0,
            self.height - self.ground_height,
            self.width,
            self.height - self.ground_height + 10,
            fill='#7CCD7C',
            outline=''
        )
        
        # 云朵（装饰）
        self.create_clouds()
        
    def create_clouds(self):
        """创建云朵 - 修复rgba问题"""
        cloud_positions = [
            (50, 50, 40, 25),
            (150, 30, 50, 30),
            (300, 60, 35, 20),
            (400, 40, 45, 25),
            (100, 120, 30, 18),
            (350, 110, 40, 22)
        ]
        
        # 使用白色半透明效果 - tkinter不支持rgba，使用浅灰色模拟
        for x, y, w, h in cloud_positions:
            # 主云朵
            self.canvas.create_oval(
                x - w, y - h,
                x + w, y + h,
                fill='#F0F0F0',  # 使用浅灰色替代rgba
                outline='#E8E8E8',
                tags='cloud'
            )
            # 云朵顶部
            self.canvas.create_oval(
                x - w*0.6, y - h*1.2,
                x + w*0.6, y + h*0.2,
                fill='#F5F5F5',
                outline='#E8E8E8',
                tags='cloud'
            )
            # 云朵底部阴影
            self.canvas.create_oval(
                x - w*0.8, y + h*0.2,
                x + w*0.8, y + h*0.8,
                fill='#E8E8E8',
                outline='',
                tags='cloud'
            )
            
    def init_game_objects(self):
        """初始化游戏对象"""
        # 创建鸟
        self.bird = self.canvas.create_oval(
            self.width // 4 - self.bird_size // 2,
            self.height // 2 - self.bird_size // 2,
            self.width // 4 + self.bird_size // 2,
            self.height // 2 + self.bird_size // 2,
            fill='#FDB813',
            outline='#E8A800',
            width=2,
            tags='bird'
        )
        
        # 鸟的眼睛
        eye_x = self.width // 4 + 5
        eye_y = self.height // 2 - 2
        self.bird_eye = self.canvas.create_oval(
            eye_x - 4, eye_y - 4,
            eye_x + 4, eye_y + 4,
            fill='white',
            outline='#333',
            width=1,
            tags='bird'
        )
        self.bird_pupil = self.canvas.create_oval(
            eye_x + 1, eye_y - 2,
            eye_x + 4, eye_y + 1,
            fill='#333',
            outline='',
            tags='bird'
        )
        
        # 鸟的嘴
        self.bird_beak = self.canvas.create_polygon(
            self.width // 4 + self.bird_size // 2,
            self.height // 2,
            self.width // 4 + self.bird_size // 2 + 8,
            self.height // 2 - 2,
            self.width // 4 + self.bird_size // 2 + 8,
            self.height // 2 + 2,
            fill='#FF6B35',
            outline='#E0552A',
            width=1,
            tags='bird'
        )
        
        # 管道列表
        self.pipes = []
        
        # 物理变量
        self.bird_y_velocity = 0
        self.bird_rotation = 0
        
        # 初始状态
        self.bird_x = self.width // 4
        self.bird_y = self.height // 2
        
        # 显示开始提示
        self.show_start_prompt()
        
    def show_start_prompt(self):
        """显示开始提示"""
        # 创建半透明背景（使用灰色矩形+stipple）
        self.canvas.create_rectangle(
            0, 0,
            self.width, self.height,
            fill='black',
            stipple='gray25',  # 使用stipple实现半透明效果
            tags='start_prompt_bg'
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 - 50,
            text="🐦 点击或按空格开始",
            font=('微软雅黑', 24, 'bold'),
            fill='white',
            tags='start_prompt'
        )
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 20,
            text="按 P 暂停",
            font=('微软雅黑', 16),
            fill='#f1c40f',
            tags='start_prompt'
        )
        
    def reset_game(self):
        """重置游戏"""
        # 清空管道
        for pipe in self.pipes:
            self.canvas.delete(pipe['top'])
            self.canvas.delete(pipe['bottom'])
        self.pipes = []
        
        # 重置鸟的位置
        self.bird_x = self.width // 4
        self.bird_y = self.height // 2
        self.bird_y_velocity = 0
        self.bird_rotation = 0
        
        self.canvas.coords(
            self.bird,
            self.bird_x - self.bird_size // 2,
            self.bird_y - self.bird_size // 2,
            self.bird_x + self.bird_size // 2,
            self.bird_y + self.bird_size // 2
        )
        
        # 重置鸟的部件位置
        self.update_bird_parts()
        
        # 重置分数
        self.score = 0
        self.game_over = False
        self.game_started = False
        
        self.canvas.itemconfig(self.score_display, text="0")
        self.canvas.delete('game_over')
        self.canvas.delete('start_prompt')
        self.canvas.delete('start_prompt_bg')
        self.canvas.delete('pipe')
        
        self.show_start_prompt()
        
        # 更新最高分
        if self.high_score > self.best_score:
            self.best_score = self.high_score
            self.save_high_score()
            
    def restart_game(self):
        """重新开始游戏"""
        self.reset_game()
            
    def toggle_pause(self):
        """暂停/继续"""
        if self.game_started and not self.game_over:
            self.paused = not self.paused
            self.info_label.config(
                text="⏸ 已暂停" if self.paused else "🎮 游戏进行中..."
            )
            if self.paused:
                # 显示暂停遮罩
                self.canvas.create_rectangle(
                    0, 0,
                    self.width, self.height,
                    fill='black',
                    stipple='gray50',
                    tags='pause_overlay'
                )
                self.canvas.create_text(
                    self.width // 2,
                    self.height // 2,
                    text="⏸ 已暂停",
                    font=('微软雅黑', 36, 'bold'),
                    fill='white',
                    tags='pause_text'
                )
            else:
                self.canvas.delete('pause_overlay')
                self.canvas.delete('pause_text')
            
    def change_difficulty(self):
        """改变难度"""
        if not self.game_started:
            difficulty = self.difficulty_var.get()
            if difficulty == "easy":
                self.pipe_gap = 180
                self.pipe_speed = 2
            elif difficulty == "hard":
                self.pipe_gap = 120
                self.pipe_speed = 4
            else:  # normal
                self.pipe_gap = 150
                self.pipe_speed = 3
            self.reset_game()
            
    def load_high_score(self):
        """加载最高分"""
        try:
            # 使用临时文件存储
            import tempfile
            filepath = os.path.join(tempfile.gettempdir(), 'flappy_high_score.txt')
            with open(filepath, 'r') as f:
                self.best_score = int(f.read().strip())
        except:
            self.best_score = 0
        self.high_score = self.best_score
        
    def save_high_score(self):
        """保存最高分"""
        try:
            import tempfile
            filepath = os.path.join(tempfile.gettempdir(), 'flappy_high_score.txt')
            with open(filepath, 'w') as f:
                f.write(str(self.best_score))
        except:
            pass
            
    def update_bird_parts(self):
        """更新鸟的部件位置"""
        eye_x = self.bird_x + 5
        eye_y = self.bird_y - 2
        
        self.canvas.coords(
            self.bird_eye,
            eye_x - 4, eye_y - 4,
            eye_x + 4, eye_y + 4
        )
        self.canvas.coords(
            self.bird_pupil,
            eye_x + 1, eye_y - 2,
            eye_x + 4, eye_y + 1
        )
        self.canvas.coords(
            self.bird_beak,
            self.bird_x + self.bird_size // 2,
            self.bird_y,
            self.bird_x + self.bird_size // 2 + 8,
            self.bird_y - 2,
            self.bird_x + self.bird_size // 2 + 8,
            self.bird_y + 2
        )
        
        # 旋转鸟 - 改变颜色作为视觉反馈
        if self.bird_rotation < -20:
            self.canvas.itemconfig(self.bird, fill='#FF6B35')
        elif self.bird_rotation > 20:
            self.canvas.itemconfig(self.bird, fill='#FDB813')
        else:
            self.canvas.itemconfig(self.bird, fill='#FFD700')
            
    def jump(self):
        """跳跃"""
        if self.game_over:
            self.restart_game()
            return
            
        if not self.game_started:
            self.game_started = True
            self.canvas.delete('start_prompt')
            self.canvas.delete('start_prompt_bg')
            self.game_loop()
        
        if not self.game_over and not self.paused:
            self.bird_y_velocity = self.jump_strength
            
    def on_space(self, event):
        """空格键事件"""
        self.jump()
        
    def on_click(self, event):
        """点击事件"""
        # 检查是否点击在画布上
        if 0 <= event.x <= self.width and 0 <= event.y <= self.height:
            self.jump()
            
    def on_key_press(self, event):
        """键盘事件"""
        if event.keysym.lower() == 'p':
            self.toggle_pause()
        elif event.keysym.lower() == 'r':
            self.restart_game()
            
    def create_pipe(self):
        """创建管道"""
        pipe_x = self.width
        pipe_height = random.randint(50, self.height - self.ground_height - self.pipe_gap - 50)
        
        # 上管道
        top_pipe = self.canvas.create_rectangle(
            pipe_x, 0,
            pipe_x + self.pipe_width, pipe_height,
            fill='#2ECC71',
            outline='#1A7A3A',
            width=2,
            tags='pipe'
        )
        
        # 上管道装饰（管道口）
        self.canvas.create_rectangle(
            pipe_x - 5, pipe_height - 20,
            pipe_x + self.pipe_width + 5, pipe_height,
            fill='#27AE60',
            outline='#1A7A3A',
            width=2,
            tags='pipe'
        )
        
        # 管道内部阴影
        self.canvas.create_line(
            pipe_x + 5, 0,
            pipe_x + 5, pipe_height - 20,
            fill='#1A7A3A',
            width=2,
            tags='pipe'
        )
        
        # 下管道
        bottom_pipe = self.canvas.create_rectangle(
            pipe_x, pipe_height + self.pipe_gap,
            pipe_x + self.pipe_width, self.height - self.ground_height,
            fill='#2ECC71',
            outline='#1A7A3A',
            width=2,
            tags='pipe'
        )
        
        # 下管道装饰（管道口）
        self.canvas.create_rectangle(
            pipe_x - 5, pipe_height + self.pipe_gap,
            pipe_x + self.pipe_width + 5, pipe_height + self.pipe_gap + 20,
            fill='#27AE60',
            outline='#1A7A3A',
            width=2,
            tags='pipe'
        )
        
        # 管道内部阴影
        self.canvas.create_line(
            pipe_x + 5, pipe_height + self.pipe_gap + 20,
            pipe_x + 5, self.height - self.ground_height,
            fill='#1A7A3A',
            width=2,
            tags='pipe'
        )
        
        self.pipes.append({
            'top': top_pipe,
            'bottom': bottom_pipe,
            'x': pipe_x,
            'height': pipe_height,
            'scored': False
        })
        
    def check_collision(self):
        """检测碰撞"""
        # 获取鸟的位置
        bird_coords = self.canvas.coords(self.bird)
        bird_left = bird_coords[0]
        bird_right = bird_coords[2]
        bird_top = bird_coords[1]
        bird_bottom = bird_coords[3]
        
        # 检查是否碰到地面或天花板
        if bird_bottom >= self.height - self.ground_height or bird_top <= 0:
            return True
            
        # 检查是否碰到管道
        for pipe in self.pipes:
            pipe_x = pipe['x']
            pipe_height = pipe['height']
            
            # 上管道碰撞检测
            if (bird_right > pipe_x + 2 and bird_left < pipe_x + self.pipe_width - 2):
                if bird_top < pipe_height:
                    return True
                    
            # 下管道碰撞检测
            if (bird_right > pipe_x + 2 and bird_left < pipe_x + self.pipe_width - 2):
                if bird_bottom > pipe_height + self.pipe_gap:
                    return True
                    
        return False
        
    def update_score(self):
        """更新分数"""
        for pipe in self.pipes:
            if not pipe['scored'] and pipe['x'] + self.pipe_width < self.bird_x:
                pipe['scored'] = True
                self.score += 1
                self.canvas.itemconfig(self.score_display, text=str(self.score))
                
                # 更新最高分
                if self.score > self.high_score:
                    self.high_score = self.score
                    self.canvas.itemconfig(
                        self.high_score_display,
                        text=f"🏆 {self.high_score}"
                    )
                    
    def game_over_sequence(self):
        """游戏结束序列"""
        self.game_over = True
        self.game_started = False
        self.paused = False
        
        # 更新最高分
        if self.high_score > self.best_score:
            self.best_score = self.high_score
            self.save_high_score()
        
        # 显示游戏结束
        self.canvas.create_rectangle(
            0, 0,
            self.width, self.height,
            fill='black',
            stipple='gray50',
            tags='game_over'
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 - 80,
            text="💀 游戏结束 💀",
            font=('微软雅黑', 36, 'bold'),
            fill='#e74c3c',
            tags='game_over'
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 - 20,
            text=f"得分: {self.score}",
            font=('微软雅黑', 24, 'bold'),
            fill='white',
            tags='game_over'
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 30,
            text=f"最高分: {self.best_score}",
            font=('微软雅黑', 20, 'bold'),
            fill='#f1c40f',
            tags='game_over'
        )
        
        self.canvas.create_text(
            self.width // 2,
            self.height // 2 + 80,
            text="按 空格键/点击 重新开始",
            font=('微软雅黑', 16),
            fill='white',
            tags='game_over'
        )
        
        self.info_label.config(text="💀 游戏结束，按空格重新开始")
        
    def game_loop(self):
        """游戏主循环"""
        if not self.game_started or self.game_over:
            if not self.game_over:
                self.window.after(20, self.game_loop)
            return
            
        if self.paused:
            self.window.after(20, self.game_loop)
            return
            
        # 重力
        self.bird_y_velocity += self.gravity
        self.bird_y += self.bird_y_velocity
        
        # 鸟的旋转
        self.bird_rotation = self.bird_y_velocity * 3
        if self.bird_rotation > 30:
            self.bird_rotation = 30
        elif self.bird_rotation < -45:
            self.bird_rotation = -45
            
        # 更新鸟的位置
        self.canvas.move(self.bird, 0, self.bird_y_velocity)
        
        # 更新鸟的部件
        self.bird_x = (self.canvas.coords(self.bird)[0] + self.canvas.coords(self.bird)[2]) / 2
        self.bird_y = (self.canvas.coords(self.bird)[1] + self.canvas.coords(self.bird)[3]) / 2
        self.update_bird_parts()
        
        # 移动管道
        for pipe in self.pipes:
            self.canvas.move(pipe['top'], -self.pipe_speed, 0)
            self.canvas.move(pipe['bottom'], -self.pipe_speed, 0)
            pipe['x'] -= self.pipe_speed
            
        # 移除超出屏幕的管道
        self.pipes = [p for p in self.pipes if p['x'] > -self.pipe_width]
        
        # 创建新管道（增加随机性）
        if len(self.pipes) == 0 or self.pipes[-1]['x'] < self.width - random.randint(200, 300):
            self.create_pipe()
            
        # 更新分数
        self.update_score()
        
        # 检测碰撞
        if self.check_collision():
            self.game_over_sequence()
            return
            
        # 继续循环
        self.window.after(20, self.game_loop)
        
    def run(self):
        """运行游戏"""
        self.window.mainloop()


if __name__ == '__main__':
    game = FlappyBird()
    game.run()