# -*- coding: utf-8 -*-
"""
Python 带界面的捕鱼模拟器 (使用 turtle + tkinter)
运行方式: python main.py
"""

import random
import math
import turtle
import tkinter as tk

# ==================== 配置 ====================
WIDTH, HEIGHT = 900, 550
FISH_COUNT = 15
MIN_RADIUS = 12
MAX_RADIUS = 38
NET_RADIUS = 45
NET_LIFETIME = 25  # 帧数，约 0.4 秒

# ==================== 全局状态 ====================
fish_list = []
score = 0
net_active = False
net_x = net_y = 0
net_timer = 0

# ==================== 初始化 turtle 屏幕 ====================
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("🐟 Python 捕鱼模拟器")
screen.bgcolor("#0b2b4a")
screen.tracer(0)  # 关闭自动刷新，手动更新

# 创建画笔
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.penup()

# 创建得分显示
root = screen.getcanvas().winfo_toplevel()
score_var = tk.StringVar(value="得分: 0")
score_label = tk.Label(root, textvariable=score_var,
                       font=("Segoe UI", 16, "bold"),
                       fg="#f5e56b", bg="#041e2b",
                       padx=20, pady=6, relief="flat")
score_label.place(x=20, y=15)

# 提示标签
hint_label = tk.Label(root, text="🖱️ 点击画布撒网  |  越小的鱼越值钱",
                      font=("Segoe UI", 11),
                      fg="#b3e2ff", bg="#0a2d3d",
                      padx=15, pady=4)
hint_label.place(x=20, y=HEIGHT - 45)

# 重置按钮
reset_btn = tk.Button(root, text="🔄 重新开始",
                      font=("Segoe UI", 11, "bold"),
                      bg="#19455c", fg="#e0f2ff",
                      activebackground="#206f92",
                      relief="flat", padx=18, pady=6,
                      command=lambda: reset_game())
reset_btn.place(x=WIDTH - 160, y=HEIGHT - 48)


# ==================== 工具函数 ====================
def random_range(a, b):
    return random.uniform(a, b)


def clamp(v, lo, hi):
    return max(lo, min(hi, v))


def create_fish():
    """生成一条鱼的数据"""
    radius = random_range(MIN_RADIUS, MAX_RADIUS)
    value = int(30 - (radius - MIN_RADIUS) * 0.75)
    speed_factor = (MAX_RADIUS - radius) / (MAX_RADIUS - MIN_RADIUS)
    speed = 0.5 + speed_factor * 1.3

    angle = random_range(0, math.pi * 2)
    vx = math.cos(angle) * speed
    vy = math.sin(angle) * speed

    x = random_range(radius + 10, WIDTH - radius - 10)
    y = random_range(radius + 10, HEIGHT - radius - 10)

    return {
        "x": x, "y": y, "vx": vx, "vy": vy,
        "radius": radius, "value": value,
        "hue": random_range(180, 240),
        "is_warm": random.random() < 0.25,
        "tail_phase": random_range(0, math.pi * 2),
    }


def init_fish():
    global fish_list
    fish_list = [create_fish() for _ in range(FISH_COUNT)]


def update_score():
    score_var.set(f"得分: {score}")


def reset_game():
    global score, net_active, net_timer
    score = 0
    net_active = False
    net_timer = 0
    init_fish()
    update_score()


# ==================== 绘制函数 ====================
def draw_background():
    """绘制简单海底背景"""
    pen.penup()
    # 水草/石子装饰
    pen.color("#385d6b")
    for i in range(12):
        pen.goto(i * 80 + 40 - WIDTH / 2, -HEIGHT / 2 + 25)
        pen.setheading(0)
        pen.begin_fill()
        pen.circle(25)
        pen.end_fill()
    # 水泡
    pen.color("#d4f0ff")
    for i in range(15):
        x = random_range(-WIDTH / 2, WIDTH / 2)
        y = random_range(-HEIGHT / 2, HEIGHT / 2)
        pen.goto(x, y)
        pen.dot(random_range(3, 8))


def rgb_to_hex(r, g, b):
    """将 0-255 的 RGB 转为 #RRGGBB"""
    r = int(clamp(r, 0, 255))
    g = int(clamp(g, 0, 255))
    b = int(clamp(b, 0, 255))
    return f"#{r:02x}{g:02x}{b:02x}"


def draw_fish(fish):
    """绘制一条鱼（简化并修复颜色格式）"""
    x = fish["x"] - WIDTH / 2
    y = fish["y"] - HEIGHT / 2
    r = fish["radius"]
    hue = fish["hue"]
    is_warm = fish["is_warm"]
    tail_phase = fish["tail_phase"]

    angle = math.degrees(math.atan2(fish["vy"], fish["vx"]))
    tail_swing = math.sin(tail_phase) * 12

    # -------- 颜色（用 #RRGGBB） --------
    if is_warm:
        # 暖色：橙/红
        rr = 255
        gg = int(140 + math.sin(tail_phase) * 20)
        bb = 60
        body_color = rgb_to_hex(rr, gg, bb)
        fin_color = rgb_to_hex(255, 170, 85)
    else:
        # 冷色：蓝/青，由 hue 映射
        t = (hue - 180) / 60.0  # 0~1
        rr = int(70 + t * 90)
        gg = int(160 + t * 40)
        bb = 210
        body_color = rgb_to_hex(rr, gg, bb)
        fin_color = rgb_to_hex(120, 200, 255)

    # -------- 鱼身（用 dot 椭圆近似——简化为圆点，保证稳定） --------
    pen.penup()
    pen.goto(x, y)
    pen.color(body_color)
    pen.dot(r * 2.0)   # 用圆点画鱼身，稳定不报错

    # -------- 鱼尾巴（三角形） --------
    pen.penup()
    pen.goto(x, y)
    pen.setheading(angle + 180)      # 朝尾部方向
    pen.forward(r * 0.7)
    pen.setheading(angle + 180 + tail_swing)
    pen.color(fin_color)
    pen.begin_fill()
    pen.forward(r * 0.9)
    pen.left(135)
    pen.forward(r * 0.6)
    pen.goto(x, y)
    pen.end_fill()

    # -------- 鱼鳍（小三角，背鳍） --------
    pen.penup()
    pen.goto(x, y)
    pen.setheading(angle + 90)       # 垂直鱼身方向
    pen.forward(r * 0.55)
    pen.setheading(angle - 30)
    pen.color(fin_color)
    pen.begin_fill()
    pen.forward(r * 0.6)
    pen.right(120)
    pen.forward(r * 0.5)
    pen.goto(x, y)
    pen.end_fill()

    # -------- 眼睛（白 + 黑） --------
    eye_x = x + math.cos(math.radians(angle)) * r * 0.45
    eye_y = y + math.sin(math.radians(angle)) * r * 0.45
    # 白眼球
    pen.penup()
    pen.goto(eye_x, eye_y)
    pen.color("white")
    pen.dot(r * 0.32)
    # 黑瞳孔（稍微偏向鱼头方向）
    pupil_x = eye_x + math.cos(math.radians(angle)) * r * 0.08
    pupil_y = eye_y + math.sin(math.radians(angle)) * r * 0.08
    pen.goto(pupil_x, pupil_y)
    pen.color("black")
    pen.dot(r * 0.15)


def draw_net():
    """绘制渔网特效"""
    if not net_active or net_timer <= 0:
        return
    pen.penup()
    pen.goto(net_x - WIDTH / 2, net_y - HEIGHT / 2)
    pen.setheading(0)
    pen.color("#d9f0ff")
    pen.pensize(3)
    pen.circle(NET_RADIUS)
    # 网格线
    pen.color("#ffffff")
    pen.pensize(1)
    for i in range(-NET_RADIUS, NET_RADIUS, 15):
        # 竖线
        pen.penup()
        pen.goto(net_x - WIDTH / 2 + i, net_y - HEIGHT / 2 - NET_RADIUS * 0.9)
        pen.setheading(90)
        pen.pendown()
        pen.forward(NET_RADIUS * 1.8)
        # 横线
        pen.penup()
        pen.goto(net_x - WIDTH / 2 - NET_RADIUS * 0.9, net_y - HEIGHT / 2 + i)
        pen.setheading(0)
        pen.pendown()
        pen.forward(NET_RADIUS * 1.8)
    pen.penup()
    pen.pensize(1)


# ==================== 游戏逻辑 ====================
def update_fish():
    for fish in fish_list:
        fish["x"] += fish["vx"]
        fish["y"] += fish["vy"]
        r = fish["radius"]

        if fish["x"] - r < 0:
            fish["x"] = r
            fish["vx"] = abs(fish["vx"])
        elif fish["x"] + r > WIDTH:
            fish["x"] = WIDTH - r
            fish["vx"] = -abs(fish["vx"])

        if fish["y"] - r < 0:
            fish["y"] = r
            fish["vy"] = abs(fish["vy"])
        elif fish["y"] + r > HEIGHT:
            fish["y"] = HEIGHT - r
            fish["vy"] = -abs(fish["vy"])

        if random.random() < 0.005:
            ang = math.atan2(fish["vy"], fish["vx"]) + random_range(-0.5, 0.5)
            spd = math.hypot(fish["vx"], fish["vy"])
            fish["vx"] = math.cos(ang) * spd
            fish["vy"] = math.sin(ang) * spd

        fish["tail_phase"] += 0.15


def try_catch(click_x, click_y):
    global score, net_active, net_x, net_y, net_timer
    net_active = True
    net_x, net_y = click_x, click_y
    net_timer = NET_LIFETIME

    for i in range(len(fish_list) - 1, -1, -1):
        fish = fish_list[i]
        dx = click_x - fish["x"]
        dy = click_y - fish["y"]
        dist = math.hypot(dx, dy)
        if dist < NET_RADIUS + fish["radius"] * 0.3:
            score += fish["value"]
            fish_list.pop(i)
            fish_list.append(create_fish())
    update_score()


# ==================== 主循环 ====================
def game_loop():
    global net_timer, net_active

    update_fish()

    if net_timer > 0:
        net_timer -= 1
        if net_timer <= 0:
            net_active = False

    pen.clear()
    draw_background()
    for fish in fish_list:
        draw_fish(fish)
    draw_net()

    screen.update()
    screen.ontimer(game_loop, 30)


# ==================== 点击事件 ====================
def on_click(x, y):
    world_x = x + WIDTH / 2
    world_y = y + HEIGHT / 2
    if 0 <= world_x <= WIDTH and 0 <= world_y <= HEIGHT:
        try_catch(world_x, world_y)


# ==================== 启动 ====================
def main():
    init_fish()
    update_score()
    screen.onclick(on_click)
    game_loop()
    screen.mainloop()


if __name__ == "__main__":
    main()