import tkinter as tk
import math
import random
import time

# ========================
# 全局配置
# ========================
WIDTH, HEIGHT = 900, 600
FPS = 60

# ========================
# 玩家状态
# ========================
px, py = WIDTH // 2, HEIGHT // 2
vx, vy = 0, 0
oxygen = 200
max_oxygen = 200
health = 3
max_health = 3
coins = 0
depth = 0
inv = []
harpoons = []
score = 0

# ========================
# 游戏状态
# ========================
mode = "dive"  # dive / shop
paused = False
game_over = False
day = 1
time_of_day = "day"

# ========================
# 世界对象
# ========================
fishes = []
sharks = []
boss = None
items = []
bubbles = []

# ========================
# Tkinter
# ========================
root = tk.Tk()
root.title("🤿 潜水员戴夫")
root.resizable(False, False)

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, highlightthickness=0)
canvas.pack()

panel = tk.Frame(root)
panel.pack(fill="x")

info = tk.Label(panel, font=("Consolas", 10))
info.pack(side="left", padx=10)

mode_btn = tk.Button(panel, text="🌙 切换到夜晚(商店)")
mode_btn.pack(side="right", padx=5)

# ========================
# 主题
# ========================
themes = {
    "🌊 经典深海": {"bg": "#0B3D91", "fg": "#FFFFFF"},
    "🌑 午夜深渊": {"bg": "#02010A", "fg": "#CCCCCC"},
    "🪸 珊瑚礁": {"bg": "#0077B6", "fg": "#FFD166"},
    "🧊 冰海": {"bg": "#CAF0F8", "fg": "#023047"},
    "🌋 火山口": {"bg": "#6F1A07", "fg": "#FFBA08"},
    "✨ 荧光海": {"bg": "#03045E", "fg": "#9D4EDD"},
}

def apply_theme(name):
    t = themes[name]
    root.configure(bg=t["bg"])
    panel.configure(bg=t["bg"])
    info.configure(bg=t["bg"], fg=t["fg"])
    canvas.configure(background=t["bg"])

# ========================
# 初始化世界
# ========================
def spawn_world():
    global fishes, sharks, boss, items, bubbles
    fishes.clear()
    sharks.clear()
    items.clear()
    bubbles.clear()
    boss = None

    for _ in range(20):
        fishes.append({
            "x": random.randint(0, WIDTH),
            "y": random.randint(100, HEIGHT - 100),
            "t": random.choice(["clown", "gold", "lantern", "sword", "tuna"]),
            "dx": random.uniform(-1, 1),
            "dy": random.uniform(-0.5, 0.5),
            "hp": 1
        })

    for _ in range(3):
        sharks.append({
            "x": random.randint(0, WIDTH),
            "y": random.randint(150, HEIGHT - 100),
            "t": random.choice(["grey", "tiger", "white"]),
            "dx": random.uniform(-2, 2),
            "dy": random.uniform(-1, 1),
            "hp": 3
        })

    for _ in range(10):
        items.append({
            "x": random.randint(0, WIDTH),
            "y": random.randint(200, HEIGHT - 100),
            "t": random.choice(["pearl", "chest", "coral"])
        })

# ========================
# 绘制海水
# ========================
def draw_sea():
    canvas.delete("sea")
    for y in range(HEIGHT):
        ratio = y / HEIGHT
        r = int(5 + 30 * ratio)
        g = int(30 + 80 * ratio)
        b = int(100 + 100 * ratio)
        canvas.create_line(0, y, WIDTH, y, fill=f"#{r:02x}{g:02x}{b:02x}", tags="sea")

# ========================
# 绘制玩家
# ========================
def draw_player():
    canvas.delete("player")
    # 身体
    canvas.create_oval(px - 12, py - 18, px + 12, py + 18,
                       fill="#FFD166", outline="#023047", width=2, tags="player")
    # 面罩
    canvas.create_oval(px - 6, py - 8, px + 6, py + 4,
                       fill="#90E0EF", outline="", tags="player")
    # 气泡
    if random.random() < 0.3:
        bubbles.append([px, py - 20])
    for b in bubbles[:]:
        b[1] -= 2
        if b[1] < 0:
            bubbles.remove(b)
        else:
            canvas.create_oval(b[0] - 3, b[1] - 3, b[0] + 3, b[1] + 3,
                               fill="#CAF0F8", outline="", tags="player")

# ========================
# 绘制鱼类
# ========================
def draw_fishes():
    canvas.delete("fish")
    for f in fishes:
        x, y = f["x"], f["y"]
        color = {
            "clown": "#FF9F1C",
            "gold": "#FFD166",
            "lantern": "#9D4EDD",
            "sword": "#EF233C",
            "tuna": "#8D99AE"
        }[f["t"]]
        canvas.create_oval(x - 10, y - 6, x + 10, y + 6,
                           fill=color, outline="", tags="fish")
        canvas.create_polygon(x + 10, y, x + 18, y - 4, x + 18, y + 4,
                              fill=color, outline="", tags="fish")

# ========================
# 绘制鲨鱼
# ========================
def draw_sharks():
    canvas.delete("shark")
    for s in sharks:
        x, y = s["x"], s["y"]
        canvas.create_oval(x - 20, y - 10, x + 20, y + 10,
                           fill="#6C757D", outline="", tags="shark")
        canvas.create_polygon(x + 20, y, x + 35, y - 8, x + 35, y + 8,
                              fill="#6C757D", outline="", tags="shark")

# ========================
# 绘制物品
# ========================
def draw_items():
    canvas.delete("item")
    for it in items:
        x, y = it["x"], it["y"]
        if it["t"] == "pearl":
            canvas.create_oval(x - 6, y - 6, x + 6, y + 6,
                               fill="#F8F9FA", outline="#CCCCCC", tags="item")
        elif it["t"] == "chest":
            canvas.create_rectangle(x - 10, y - 8, x + 10, y + 8,
                                    fill="#8D775A", outline="#5C3D2E", tags="item")
        else:
            canvas.create_polygon(x, y - 10, x - 8, y + 6, x + 8, y + 6,
                                  fill="#FF6B6B", outline="", tags="item")

# ========================
# 绘制鱼叉
# ========================
def draw_harpoons():
    canvas.delete("harpoon")
    for h in harpoons:
        canvas.create_line(h["x"], h["y"], h["x"] + h["dx"] * 10,
                           h["y"] + h["dy"] * 10,
                           fill="#FFD166", width=3, tags="harpoon")

# ========================
# 绘制UI
# ========================
def draw_ui():
    canvas.delete("ui")
    # 氧气条
    ox, oy = 20, 20
    canvas.create_rectangle(ox, oy, ox + 200, oy + 15,
                            outline="#FFFFFF", width=2, tags="ui")
    canvas.create_rectangle(ox, oy, ox + int(200 * oxygen / max_oxygen),
                            oy + 15, fill="#00B4D8", outline="", tags="ui")

    # 生命
    for i in range(max_health):
        color = "#EF233C" if i < health else "#6C757D"
        canvas.create_oval(20 + i * 25, 40, 35 + i * 25, 55,
                           fill=color, outline="", tags="ui")

    # 信息
    canvas.create_text(WIDTH - 20, 20, anchor="ne",
                       text=f"金币: {coins}\n深度: {int(depth)}m\n天数: {day}",
                       fill="#FFFFFF", font=("Consolas", 10), tags="ui")

# ========================
# 物理更新
# ========================
def update_physics():
    global px, py, vx, vy, oxygen, health, depth, score, game_over

    if paused or game_over:
        return

    px += vx
    py += vy
    px = max(20, min(WIDTH - 20, px))
    py = max(20, min(HEIGHT - 20, py))

    depth = py - 100
    if depth < 0:
        oxygen = min(max_oxygen, oxygen + 0.5)
    else:
        oxygen -= 0.1 + depth * 0.001

    if oxygen <= 0:
        health -= 0.02

    if health <= 0:
        game_over = True

# ========================
# 鱼/鲨AI
# ========================
def update_entities():
    global coins, health, score

    for f in fishes[:]:
        f["x"] += f["dx"]
        f["y"] += f["dy"]
        if f["x"] < 0 or f["x"] > WIDTH:
            f["dx"] *= -1
        if f["y"] < 100 or f["y"] > HEIGHT - 100:
            f["dy"] *= -1

    for s in sharks[:]:
        dx = px - s["x"]
        dy = py - s["y"]
        dist = math.hypot(dx, dy)
        if dist < 200:
            s["dx"] += dx * 0.001
            s["dy"] += dy * 0.001
        s["x"] += s["dx"]
        s["y"] += s["dy"]

        if math.hypot(px - s["x"], py - s["y"]) < 25:
            health -= 0.5
            score -= 50

    for h in harpoons[:]:
        h["x"] += h["dx"] * 8
        h["y"] += h["dy"] * 8
        if h["x"] < 0 or h["x"] > WIDTH or h["y"] < 0 or h["y"] > HEIGHT:
            harpoons.remove(h)
            continue

        for f in fishes[:]:
            if math.hypot(h["x"] - f["x"], h["y"] - f["y"]) < 20:
                score += {"clown": 50, "gold": 30, "lantern": 80,
                          "sword": 150, "tuna": 200}[f["t"]]
                coins += {"clown": 5, "gold": 3, "lantern": 8,
                          "sword": 15, "tuna": 20}[f["t"]]
                fishes.remove(f)
                if h in harpoons:
                    harpoons.remove(h)
                break

# ========================
# 收集物品
# ========================
def collect_items():
    global coins, score
    for it in items[:]:
        if math.hypot(px - it["x"], py - it["y"]) < 25:
            if it["t"] == "pearl":
                coins += 10
                score += 100
            elif it["t"] == "chest":
                coins += 30
                score += 300
            else:
                coins += 5
                score += 50
            items.remove(it)

# ========================
# 场景绘制
# ========================
def draw_scene():
    draw_sea()
    draw_items()
    draw_fishes()
    draw_sharks()
    draw_harpoons()
    draw_player()
    draw_ui()

# ========================
# 游戏循环
# ========================
def game_loop():
    update_physics()
    update_entities()
    collect_items()
    draw_scene()

    if game_over:
        canvas.create_text(WIDTH // 2, HEIGHT // 2,
                           text="💀 GAME OVER",
                           fill="#EF233C",
                           font=("Consolas", 36, "bold"))

    root.after(int(1000 / FPS), game_loop)

# ========================
# 控制
# ========================
def key_down(e):
    global vx, vy, harpoons, paused, game_over, px, py, oxygen, health
    global coins, score, day, mode, time_of_day

    if game_over:
        if e.keysym == "r":
            game_over = False
            oxygen = max_oxygen
            health = max_health
            coins = score = 0
            px, py = WIDTH // 2, HEIGHT // 2
            spawn_world()
        return

    if e.keysym in ("w", "Up"):
        vy = -2
    if e.keysym in ("s", "Down"):
        vy = 2
    if e.keysym in ("a", "Left"):
        vx = -2
    if e.keysym in ("d", "Right"):
        vx = 2
    if e.keysym == "space":
        angle = math.atan2(py - HEIGHT // 2, px - WIDTH // 2)
        harpoons.append({
            "x": px,
            "y": py,
            "dx": math.cos(angle),
            "dy": math.sin(angle)
        })
    if e.keysym == "e":
        if mode == "shop":
            mode = "dive"
            time_of_day = "day"
            spawn_world()
        else:
            mode = "shop"
            time_of_day = "night"
    if e.keysym == "p":
        paused = not paused
    if e.keysym == "r":
        spawn_world()
        px, py = WIDTH // 2, HEIGHT // 2
        oxygen = max_oxygen
        health = max_health
        coins = score = 0
        day += 1

def key_up(e):
    global vx, vy
    if e.keysym in ("w", "s", "Up", "Down"):
        vy = 0
    if e.keysym in ("a", "d", "Left", "Right"):
        vx = 0

root.bind("<KeyPress>", key_down)
root.bind("<KeyRelease>", key_up)

mode_btn.config(command=lambda: key_down(type("E", (), {"keysym": "e"})()))

# ========================
# 启动
# ========================
apply_theme("🌊 经典深海")
spawn_world()
game_loop()
root.mainloop()