import tkinter as tk
import random
import math

class DragonRiderGame:
    def __init__(self, root):
        self.root = root
        self.root.title("骑龙勇士历险记")
        self.root.resizable(False, False)

        self.width = 900
        self.height = 600
        self.canvas = tk.Canvas(root, width=self.width, height=self.height, bg="#1a1a3e")
        self.canvas.pack()

        # 游戏状态
        self.game_over = False
        self.win = False
        self.paused = False
        self.frames = 0
        self.score = 0
        self.hp = 100
        self.level = 1

        # 骑士与龙参数
        self.dragon_x = 150
        self.dragon_y = self.height // 2
        self.dragon_vy = 0
        self.dragon_size = 50
        self.gravity = 0.5
        self.flap_power = -8
        self.keys = {}

        # 动态对象
        self.obstacles = []    # 障碍物（山峰/火球）
        self.coins = []        # 金币
        self.enemies = []      # 敌人（飞龙/蝙蝠）
        self.particles = []    # 粒子特效
        self.clouds = []

        # 生成计时
        self.obs_timer = 0
        self.coin_timer = 0
        self.enemy_timer = 0
        self.spawn_interval_obs = 90
        self.spawn_interval_coin = 60
        self.spawn_interval_enemy = 150

        # 图形对象
        self.dragon_items = []
        self.ui_items = []

        # 背景星星
        self.stars = [(random.randint(0, self.width), random.randint(0, self.height),
                       random.choice([1, 1, 2, 2, 3])) for _ in range(100)]
        self.clouds_data = []
        for _ in range(5):
            cx = random.randint(0, self.width)
            cy = random.randint(50, 300)
            cw = random.randint(60, 120)
            self.clouds_data.append([cx, cy, cw])

        self.draw_background()
        self.create_dragon()
        self.create_ui()

        root.bind("<KeyPress>", self.key_press)
        root.bind("<KeyRelease>", self.key_release)

        self.game_loop()

    # ---------------- 背景 ----------------
    def draw_background(self):
        self.canvas.delete("bg")
        # 深空渐变（用几条色带模拟）
        colors = ["#0d0d2b", "#141440", "#1a1a4e", "#20205c", "#26266a"]
        band = self.height // len(colors)
        for i, c in enumerate(colors):
            self.canvas.create_rectangle(0, i * band, self.width, (i + 1) * band,
                                         fill=c, outline="", tags="bg")
        # 星星
        for x, y, r in self.stars:
            self.canvas.create_oval(x - r, y - r, x + r, y + r,
                                    fill="white", outline="", tags="bg")
        # 月亮
        self.canvas.create_oval(self.width - 120, 40, self.width - 40, 120,
                                fill="#f5f5dc", outline="", tags="bg")
        self.canvas.create_oval(self.width - 100, 50, self.width - 60, 90,
                                fill="#141440", outline="", tags="bg")

    # ---------------- 龙 ----------------
    def create_dragon(self):
        for it in self.dragon_items:
            self.canvas.delete(it)
        self.dragon_items = []
        x, y = self.dragon_x, self.dragon_y
        s = self.dragon_size

        # 翅膀（根据竖直速度扇动）
        wing_angle = math.sin(self.frames * 0.3) * 15
        # 上翅膀
        self.dragon_items.append(self.canvas.create_polygon(
            x - 10, y - 10, x - 30, y - 40 + wing_angle, x + 5, y - 25,
            fill="#2e8b57", outline="#1f5f3f", width=2))
        # 下翅膀
        self.dragon_items.append(self.canvas.create_polygon(
            x - 10, y + 10, x - 30, y + 40 - wing_angle, x + 5, y + 25,
            fill="#2e8b57", outline="#1f5f3f", width=2))

        # 尾巴
        self.dragon_items.append(self.canvas.create_polygon(
            x - s, y, x - s - 30, y - 10, x - s - 20, y + 5, x - s - 35, y + 15,
            fill="#3cb371", outline="#1f5f3f"))

        # 身体
        self.dragon_items.append(self.canvas.create_oval(
            x - s, y - s * 0.6, x + s * 0.6, y + s * 0.6,
            fill="#3cb371", outline="#1f5f3f", width=2))
        # 头
        self.dragon_items.append(self.canvas.create_oval(
            x + 10, y - 25, x + 55, y + 15,
            fill="#3cb371", outline="#1f5f3f", width=2))
        # 眼睛
        self.dragon_items.append(self.canvas.create_oval(
            x + 38, y - 15, x + 48, y - 5, fill="white", outline=""))
        self.dragon_items.append(self.canvas.create_oval(
            x + 42, y - 13, x + 46, y - 7, fill="black", outline=""))
        # 鼻孔
        self.dragon_items.append(self.canvas.create_oval(
            x + 50, y - 2, x + 54, y + 2, fill="#1f5f3f", outline=""))
        # 角
        self.dragon_items.append(self.canvas.create_polygon(
            x + 20, y - 25, x + 25, y - 45, x + 35, y - 22,
            fill="#daa520", outline="#8b6914"))
        # 背刺
        for i in range(4):
            bx = x - s + 15 + i * 15
            self.dragon_items.append(self.canvas.create_polygon(
                bx, y - s * 0.5, bx + 8, y - s * 0.5 - 12, bx + 16, y - s * 0.5,
                fill="#daa520", outline="#8b6914"))
        # 骑士（小人在龙背上）
        kx, ky = x - 10, y - s * 0.6 - 12
        self.dragon_items.append(self.canvas.create_rectangle(
            kx - 10, ky - 5, kx + 10, ky + 15, fill="#c0c0c0", outline="#555"))
        self.dragon_items.append(self.canvas.create_oval(
            kx - 8, ky - 20, kx + 8, ky - 4, fill="#ffdab9", outline="#555"))
        # 头盔
        self.dragon_items.append(self.canvas.create_arc(
            kx - 10, ky - 24, kx + 10, ky - 4, start=0, extent=180,
            fill="#c0c0c0", outline="#555"))
        # 长矛
        self.dragon_items.append(self.canvas.create_line(
            kx + 5, ky + 10, kx + 35, ky - 25, fill="#8b4513", width=3))
        self.dragon_items.append(self.canvas.create_polygon(
            kx + 35, ky - 25, kx + 42, ky - 35, kx + 38, ky - 20,
            fill="#c0c0c0", outline="#555"))
        # 火焰效果（偶尔喷火）
        if self.frames % 40 < 10:
            fx = x + 55
            fy = y - 5
            for i in range(3):
                fx2 = fx + 15 + i * 8
                fy2 = fy - 5 + i * 5
                self.dragon_items.append(self.canvas.create_oval(
                    fx2, fy2, fx2 + 15, fy2 + 10,
                    fill=random.choice(["#ff4500", "#ff8c00", "#ffd700"]),
                    outline=""))

    # ---------------- UI ----------------
    def create_ui(self):
        for it in self.ui_items:
            self.canvas.delete(it)
        self.ui_items = []
        # 分数
        self.ui_items.append(self.canvas.create_text(
            20, 20, text=f"分数: {self.score}", font=("Arial", 18, "bold"),
            fill="white", anchor="nw"))
        # 生命值条
        self.ui_items.append(self.canvas.create_text(
            20, 50, text="生命:", font=("Arial", 14), fill="white", anchor="nw"))
        self.hp_bg = self.canvas.create_rectangle(
            70, 52, 270, 72, fill="#333", outline="white")
        self.hp_bar = self.canvas.create_rectangle(
            70, 52, 70 + self.hp * 2, 72, fill="#00ff00", outline="")
        self.ui_items.append(self.hp_bg)
        self.ui_items.append(self.hp_bar)
        # 关卡
        self.ui_items.append(self.canvas.create_text(
            self.width - 20, 20, text=f"关卡: {self.level}",
            font=("Arial", 18, "bold"), fill="gold", anchor="ne"))
        # 操作提示
        self.ui_items.append(self.canvas.create_text(
            self.width // 2, self.height - 20,
            text="空格/↑ 扇动翅膀   ↓ 俯冲   躲避障碍，收集金币，击败敌人",
            font=("Arial", 12), fill="#cccccc", anchor="s"))

    def update_ui(self):
        self.canvas.itemconfig(self.ui_items[0], text=f"分数: {self.score}")
        self.canvas.itemconfig(self.ui_items[5], text=f"关卡: {self.level}")
        self.canvas.coords(self.hp_bar, 70, 52, 70 + max(0, self.hp) * 2, 72)
        color = "#00ff00" if self.hp > 60 else "#ffff00" if self.hp > 30 else "#ff0000"
        self.canvas.itemconfig(self.hp_bar, fill=color)

    # ---------------- 输入 ----------------
    def key_press(self, event):
        k = event.keysym.lower()
        self.keys[k] = True
        if k == "space" and not self.game_over and not self.win:
            self.dragon_vy = self.flap_power
        if k == "up" and not self.game_over and not self.win:
            self.dragon_vy = self.flap_power
        if k == "down" and not self.game_over and not self.win:
            self.dragon_vy += 3
        if k == "r":
            self.restart()
        if k == "p" and not self.game_over and not self.win:
            self.paused = not self.paused

    def key_release(self, event):
        self.keys[event.keysym.lower()] = False

    # ---------------- 粒子 ----------------
    def spawn_particles(self, x, y, color, count=10):
        for _ in range(count):
            angle = random.uniform(0, math.tau)
            speed = random.uniform(1, 4)
            self.particles.append({
                'x': x, 'y': y,
                'vx': math.cos(angle) * speed,
                'vy': math.sin(angle) * speed,
                'life': random.randint(15, 30),
                'max_life': 30,
                'color': color,
                'item': None
            })

    def update_particles(self):
        for p in self.particles[:]:
            p['x'] += p['vx']
            p['y'] += p['vy']
            p['vy'] += 0.1
            p['life'] -= 1
            if p['item']:
                self.canvas.delete(p['item'])
            if p['life'] <= 0:
                self.particles.remove(p)
                continue
            size = max(1, p['life'] // 5)
            p['item'] = self.canvas.create_oval(
                p['x'] - size, p['y'] - size, p['x'] + size, p['y'] + size,
                fill=p['color'], outline="")

    # ---------------- 障碍物 ----------------
    def spawn_obstacle(self):
        obs_type = random.choice(["rock", "fireball", "spike"])
        y = random.randint(80, self.height - 80)
        if obs_type == "rock":
            size = random.randint(30, 50)
            items = []
            items.append(self.canvas.create_polygon(
                self.width + 60, y, self.width + 60 + size, y - size // 2,
                self.width + 60 + size, y + size // 2,
                fill="#696969", outline="#404040", width=2))
            items.append(self.canvas.create_polygon(
                self.width + 65, y, self.width + 60 + size // 2, y - size // 4,
                self.width + 60 + size // 2, y + size // 4,
                fill="#8b8b8b", outline=""))
            w, h = size, size
        elif obs_type == "fireball":
            size = random.randint(20, 30)
            items = []
            for i in range(3):
                r = size - i * 6
                items.append(self.canvas.create_oval(
                    self.width + 60 - r, y - r, self.width + 60 + r, y + r,
                    fill=["#ff4500", "#ff8c00", "#ffd700"][i], outline=""))
            w, h = size * 2, size * 2
        else:  # spike
            size = random.randint(25, 40)
            items = []
            items.append(self.canvas.create_polygon(
                self.width + 60, y - size // 2,
                self.width + 60 + size, y,
                self.width + 60, y + size // 2,
                fill="#8b0000", outline="#ff0000", width=2))
            w, h = size, size
        self.obstacles.append({
            'x': self.width + 60, 'y': y, 'w': w, 'h': h,
            'speed': 4 + self.level * 0.5,
            'type': obs_type, 'items': items
        })

    def update_obstacles(self):
        for o in self.obstacles[:]:
            o['x'] -= o['speed']
            for it in o['items']:
                self.canvas.move(it, -o['speed'], 0)
            if o['x'] < -100:
                for it in o['items']:
                    self.canvas.delete(it)
                self.obstacles.remove(o)
                continue
            if self.hit_test(o['x'], o['y'], o['w'] // 2, o['h'] // 2):
                self.damage(15)
                self.spawn_particles(o['x'], o['y'], "#ff4500", 15)
                for it in o['items']:
                    self.canvas.delete(it)
                self.obstacles.remove(o)

    # ---------------- 金币 ----------------
    def spawn_coin(self):
        y = random.randint(60, self.height - 60)
        items = []
        items.append(self.canvas.create_oval(
            self.width + 40, y - 12, self.width + 64, y + 12,
            fill="#ffd700", outline="#b8860b", width=2))
        items.append(self.canvas.create_text(
            self.width + 52, y, text="$", font=("Arial", 12, "bold"),
            fill="#b8860b"))
        self.coins.append({
            'x': self.width + 52, 'y': y, 'r': 12,
            'items': items, 'angle': 0
        })

    def update_coins(self):
        for c in self.coins[:]:
            c['x'] -= 3
            for it in c['items']:
                self.canvas.move(it, -3, 0)
            c['angle'] += 0.1
            if c['x'] < -40:
                for it in c['items']:
                    self.canvas.delete(it)
                self.coins.remove(c)
                continue
            if self.hit_test(c['x'], c['y'], c['r'] + 5, c['r'] + 5):
                self.score += 10
                self.spawn_particles(c['x'], c['y'], "#ffd700", 12)
                for it in c['items']:
                    self.canvas.delete(it)
                self.coins.remove(c)

    # ---------------- 敌人 ----------------
    def spawn_enemy(self):
        y = random.randint(80, self.height - 80)
        items = []
        # 敌方飞龙（红色）
        items.append(self.canvas.create_oval(
            self.width + 60, y - 15, self.width + 100, y + 15,
            fill="#dc143c", outline="#8b0000", width=2))
        items.append(self.canvas.create_oval(
            self.width + 80, y - 25, self.width + 110, y + 5,
            fill="#dc143c", outline="#8b0000", width=2))
        # 眼睛
        items.append(self.canvas.create_oval(
            self.width + 95, y - 15, self.width + 103, y - 7,
            fill="yellow", outline=""))
        # 翅膀
        items.append(self.canvas.create_polygon(
            self.width + 70, y - 10, self.width + 55, y - 35,
            self.width + 85, y - 20, fill="#8b0000", outline=""))
        self.enemies.append({
            'x': self.width + 80, 'y': y,
            'hp': 1, 'speed': 3 + self.level * 0.3,
            'items': items, 'vy': random.choice([-1, 0, 1])
        })

    def update_enemies(self):
        for e in self.enemies[:]:
            e['x'] -= e['speed']
            e['y'] += e['vy']
            if e['y'] < 50 or e['y'] > self.height - 50:
                e['vy'] = -e['vy']
            for it in e['items']:
                self.canvas.move(it, -e['speed'], e['vy'])
            if e['x'] < -100:
                for it in e['items']:
                    self.canvas.delete(it)
                self.enemies.remove(e)
                continue
            if self.hit_test(e['x'], e['y'], 35, 25):
                self.damage(20)
                self.spawn_particles(e['x'], e['y'], "#ff0000", 15)
                for it in e['items']:
                    self.canvas.delete(it)
                self.enemies.remove(e)

    # ---------------- 碰撞检测 ----------------
    def hit_test(self, ox, oy, ow, oh):
        # 龙的碰撞盒（较小，让操作更宽容）
        dx, dy = self.dragon_x, self.dragon_y
        dw, dh = 35, 25
        return (dx + dw > ox - ow and dx - dw < ox + ow and
                dy + dh > oy - oh and dy - dh < oy + oh)

    def damage(self, amount):
        self.hp -= amount
        self.canvas.create_rectangle(0, 0, self.width, self.height,
                                     fill="red", outline="", stipple="gray25",
                                     tags="flash")
        self.root.after(80, lambda: self.canvas.delete("flash"))
        if self.hp <= 0:
            self.hp = 0
            self.game_over = True
            self.show_game_over()

    # ---------------- 结算 ----------------
    def show_game_over(self):
        self.canvas.create_rectangle(
            self.width // 2 - 220, self.height // 2 - 100,
            self.width // 2 + 220, self.height // 2 + 100,
            fill="black", outline="#ff4500", width=4)
        self.canvas.create_text(self.width // 2, self.height // 2 - 50,
                                text="💀 勇士阵亡 💀", font=("Arial", 30, "bold"),
                                fill="#ff4500")
        self.canvas.create_text(self.width // 2, self.height // 2,
                                text=f"最终分数: {self.score}", font=("Arial", 20),
                                fill="white")
        self.canvas.create_text(self.width // 2, self.height // 2 + 40,
                                text=f"到达关卡: {self.level}", font=("Arial", 16),
                                fill="gold")
        self.canvas.create_text(self.width // 2, self.height // 2 + 80,
                                text="按 R 重新开始", font=("Arial", 16),
                                fill="yellow")

    def show_win(self):
        self.win = True
        self.canvas.create_rectangle(
            self.width // 2 - 240, self.height // 2 - 100,
            self.width // 2 + 240, self.height // 2 + 100,
            fill="black", outline="#ffd700", width=4)
        self.canvas.create_text(self.width // 2, self.height // 2 - 50,
                                text="🐉 冒险完成！🐉", font=("Arial", 30, "bold"),
                                fill="#ffd700")
        self.canvas.create_text(self.width // 2, self.height // 2,
                                text=f"最终分数: {self.score}", font=("Arial", 20),
                                fill="white")
        self.canvas.create_text(self.width // 2, self.height // 2 + 50,
                                text="按 R 重新开始", font=("Arial", 16),
                                fill="yellow")

    def restart(self):
        self.game_over = False
        self.win = False
        self.paused = False
        self.frames = 0
        self.score = 0
        self.hp = 100
        self.level = 1
        self.dragon_y = self.height // 2
        self.dragon_vy = 0
        self.spawn_interval_obs = 90
        self.spawn_interval_coin = 60
        self.spawn_interval_enemy = 150

        for group in [self.obstacles, self.coins, self.enemies]:
            for obj in group:
                for it in obj['items']:
                    self.canvas.delete(it)
            group.clear()
        for p in self.particles:
            if p['item']:
                self.canvas.delete(p['item'])
        self.particles.clear()

        self.canvas.delete("all")
        self.draw_background()
        self.create_dragon()
        self.create_ui()

    # ---------------- 主循环 ----------------
    def game_loop(self):
        if not self.game_over and not self.win and not self.paused:
            self.frames += 1

            # 龙物理
            self.dragon_vy += self.gravity
            if self.keys.get("space"):
                self.dragon_vy = self.flap_power
            self.dragon_y += self.dragon_vy
            # 边界
            if self.dragon_y < 40:
                self.dragon_y = 40
                self.dragon_vy = 0
            if self.dragon_y > self.height - 40:
                self.dragon_y = self.height - 40
                self.dragon_vy = 0

            # 动态背景云
            for c in self.clouds_data:
                c[0] -= 0.5
                if c[0] < -c[2]:
                    c[0] = self.width + c[2]
                    c[1] = random.randint(50, 300)
            self.canvas.delete("cloud")
            for cx, cy, cw in self.clouds_data:
                self.canvas.create_oval(cx, cy, cx + cw, cy + cw * 0.5,
                                        fill="#2a2a5e", outline="", tags="cloud")

            # 生成
            self.obs_timer += 1
            self.coin_timer += 1
            self.enemy_timer += 1
            if self.obs_timer >= self.spawn_interval_obs:
                self.obs_timer = 0
                self.spawn_obstacle()
            if self.coin_timer >= self.spawn_interval_coin:
                self.coin_timer = 0
                self.spawn_coin()
            if self.enemy_timer >= self.spawn_interval_enemy:
                self.enemy_timer = 0
                self.spawn_enemy()

            # 更新
            self.update_obstacles()
            self.update_coins()
            self.update_enemies()
            self.update_particles()

            # 关卡推进（每 30 秒提升）
            new_level = self.frames // 900 + 1
            if new_level > self.level and new_level <= 10:
                self.level = new_level
                self.spawn_interval_obs = max(40, self.spawn_interval_obs - 5)
                self.spawn_interval_enemy = max(60, self.spawn_interval_enemy - 10)
            if new_level > 10 and not self.win:
                self.show_win()

            # 刷新龙
            self.create_dragon()
            self.update_ui()

        elif self.paused and not self.game_over and not self.win:
            self.canvas.create_text(self.width // 2, self.height // 2,
                                    text="⏸ 暂停中 (按 P 继续)", font=("Arial", 30, "bold"),
                                    fill="white", tags="pause_text")
        else:
            self.canvas.delete("pause_text")

        self.root.after(30, self.game_loop)


if __name__ == "__main__":
    root = tk.Tk()
    game = DragonRiderGame(root)
    root.mainloop()