# -*- coding: utf-8 -*-
"""
捕鱼达人 —— Python + Tkinter 版
直接运行：python main.py
操作：鼠标移动瞄准，点击左键开炮
"""

import tkinter as tk
import math
import random

# ---------------- 全局常量 ----------------
W, H = 960, 680                 # 画布尺寸
CANNON_X = W // 2               # 炮台中心 X
CANNON_Y = H - 34               # 炮台中心 Y
BARREL_LEN = 62                 # 炮管长度

# 鱼的种类配置：size 体型 / smin,smax 速度 / color 颜色 / value 分值 / weight 出现权重
FISH_KINDS = [
    {"size": 11, "smin": 3.2, "smax": 4.4, "color": "#7fd8ff", "value": 2,  "weight": 18},
    {"size": 11, "smin": 3.2, "smax": 4.4, "color": "#ffd166", "value": 2,  "weight": 18},
    {"size": 15, "smin": 2.3, "smax": 3.2, "color": "#95e06c", "value": 4,  "weight": 15},
    {"size": 15, "smin": 2.3, "smax": 3.2, "color": "#f78fb3", "value": 4,  "weight": 15},
    {"size": 20, "smin": 1.8, "smax": 2.5, "color": "#ff9f68", "value": 8,  "weight": 11},
    {"size": 27, "smin": 1.3, "smax": 1.9, "color": "#b28dff", "value": 15, "weight": 6},
    {"size": 36, "smin": 0.9, "smax": 1.4, "color": "#ff6b6b", "value": 30, "weight": 2},
]


def darken(hex_color, factor=0.62):
    """把颜色变暗，用于鱼鳍、描边"""
    r = int(hex_color[1:3], 16)
    g = int(hex_color[3:5], 16)
    b = int(hex_color[5:7], 16)
    return "#{:02x}{:02x}{:02x}".format(
        int(r * factor), int(g * factor), int(b * factor)
    )


# ---------------- 鱼类 ----------------
class Fish:
    def __init__(self, canvas, x, base_y, size, color, speed, direction, value):
        self.canvas = canvas
        self.x = x
        self.y = base_y
        self.base_y = base_y
        self.size = size
        self.color = color
        self.speed = speed
        self.direction = direction      # 1 向右，-1 向左
        self.value = value
        self.alive = True

        self.phase = random.random() * math.pi * 2   # 正弦摆动相位
        self.amp = 4 + random.random() * 10          # 摆动幅度

        L = size * 2.6      # 身体长度
        Hh = size * 1.5     # 身体高度
        self.L, self.Hh = L, Hh
        d = direction
        dark = darken(color, 0.65)

        # 尾巴
        self.tail = canvas.create_polygon(
            x - L * 0.40 * d, base_y,
            x - L * 0.95 * d, base_y - Hh * 0.62,
            x - L * 0.95 * d, base_y + Hh * 0.62,
            fill=dark, outline=dark)

        # 背鳍
        self.fin = canvas.create_polygon(
            x - L * 0.15 * d, base_y - Hh * 0.45,
            x + L * 0.15 * d, base_y - Hh * 0.45,
            x - L * 0.02 * d, base_y - Hh * 0.95,
            fill=dark, outline=dark)

        # 身体
        self.body = canvas.create_oval(
            x - L * 0.5, base_y - Hh * 0.5,
            x + L * 0.5, base_y + Hh * 0.5,
            fill=color, outline=dark, width=2)

        # 眼睛
        ex = x + L * 0.30 * d
        ey = base_y - Hh * 0.16
        r = max(2.0, Hh * 0.14)
        self.eye = canvas.create_oval(
            ex - r, ey - r, ex + r, ey + r,
            fill="white", outline=dark, width=1.5)

        # 瞳孔
        self.pupil = canvas.create_oval(
            ex - r * 0.52, ey - r * 0.52,
            ex + r * 0.52, ey + r * 0.52,
            fill="#12202b", outline="")

        self.items = [self.tail, self.fin, self.body, self.eye, self.pupil]

    def move(self, dx, dy):
        for item in self.items:
            self.canvas.move(item, dx, dy)

    def destroy(self):
        for item in self.items:
            self.canvas.delete(item)


# ---------------- 子弹 ----------------
class Bullet:
    RADIUS = 8
    SPEED = 15

    def __init__(self, canvas, x, y, vx, vy):
        self.canvas = canvas
        self.x, self.y = x, y
        self.vx, self.vy = vx, vy
        self.r = Bullet.RADIUS
        self.alive = True

        self.item = canvas.create_oval(
            x - self.r, y - self.r, x + self.r, y + self.r,
            fill="#ffe066", outline="#ff9f1c", width=2)
        self.highlight = canvas.create_oval(
            x - 5, y - 5, x - 1, y - 1,
            fill="#fff9d6", outline="")

    def move(self):
        self.x += self.vx
        self.y += self.vy
        self.canvas.move(self.item, self.vx, self.vy)
        self.canvas.move(self.highlight, self.vx, self.vy)

    def out_of_screen(self):
        return (self.x < -30 or self.x > W + 30 or
                self.y < -30 or self.y > H + 30)

    def destroy(self):
        self.canvas.delete(self.item)
        self.canvas.delete(self.highlight)


# ---------------- 命中特效 ----------------
class Effect:
    def __init__(self, canvas, x, y, color, text):
        self.canvas = canvas
        self.x, self.y = x, y
        self.r = 6
        self.life = 20

        self.ring = canvas.create_oval(
            x - 6, y - 6, x + 6, y + 6,
            outline=color, width=3)
        self.text = canvas.create_text(
            x, y, text=text, fill="#ffd166",
            font=("Microsoft YaHei", 14, "bold")) if text else None

    def update(self):
        """返回 True 表示还活着"""
        self.r += 2.2
        self.life -= 1
        self.canvas.coords(
            self.ring, self.x - self.r, self.y - self.r,
            self.x + self.r, self.y + self.r)
        if self.text:
            self.canvas.move(self.text, 0, -1.4)
        return self.life > 0

    def destroy(self):
        self.canvas.delete(self.ring)
        if self.text:
            self.canvas.delete(self.text)


# ---------------- 游戏主体 ----------------
class FishGame:
    MAX_FISH = 18
    START_COINS = 150

    def __init__(self, root):
        self.root = root
        root.title("捕鱼达人 —— Tkinter")
        root.resizable(False, False)

        self.canvas = tk.Canvas(root, width=W, height=H,
                                highlightthickness=0, bg="#062b45")
        self.canvas.pack()

        # ---- 状态变量 ----
        self.fishes = []
        self.bullets = []
        self.effects = []
        self.overlay = []

        self.coins = FishGame.START_COINS
        self.score = 0
        self.caught = 0
        self.frame = 0
        self.spawn_counter = 0
        self.game_over = False

        self.angle = -math.pi / 2
        self.mouse_x = W / 2
        self.mouse_y = H / 2

        # ---- 场景 ----
        self.draw_background()
        self.create_cannon()
        self.create_hud()
        self.bind_events()
        self.update_barrel()
        self.update_hud()

        # ---- 启动主循环 ----
        self.root.after(16, self.loop)

    # ========== 背景 ==========
    def draw_background(self):
        c = self.canvas

        # 深水渐变（用横向细条纹模拟）
        for i in range(0, H, 4):
            t = i / H
            r = int(6 + (3 - 6) * t)
            g = int(43 + (30 - 43) * t)
            b = int(69 + (46 - 69) * t)
            c.create_rectangle(0, i, W, i + 4,
                               fill="#{:02x}{:02x}{:02x}".format(r, g, b),
                               outline="")

        # 静态气泡
        c.create_oval(76, 116, 84, 124, outline="#0d3d59")
        c.create_oval(225, 295, 235, 305, outline="#0d3d59")
        c.create_oval(417, 87, 423, 93, outline="#0d3d59")
        c.create_oval(594, 234, 606, 246, outline="#0d3d59")
        c.create_oval(776, 146, 784, 154, outline="#0d3d59")
        c.create_oval(885, 395, 895, 405, outline="#0d3d59")
        c.create_oval(144, 514, 156, 526, outline="#0d3d59")
        c.create_oval(344, 614, 352, 622, outline="#0d3d59")
        c.create_oval(694, 574, 704, 584, outline="#0d3d59")
        c.create_oval(516, 456, 522, 462, outline="#0d3d59")

        # 海底沙地
        c.create_rectangle(0, H - 20, W, H, fill="#0a3a52", outline="")
        c.create_oval(120 - 150, H - 34, 120 + 150, H + 10,
                      fill="#0d4a68", outline="")
        c.create_oval(760 - 190, H - 36, 760 + 190, H + 16,
                      fill="#0d4a68", outline="")

    # ========== 炮台 ==========
    def create_cannon(self):
        c = self.canvas
        # 炮管（先画粗的外轮廓，再画细的内芯）
        self.barrel_outline = c.create_line(
            CANNON_X, CANNON_Y, CANNON_X, CANNON_Y - BARREL_LEN,
            width=24, fill="#6b7b87", capstyle=tk.ROUND)
        self.barrel = c.create_line(
            CANNON_X, CANNON_Y, CANNON_X, CANNON_Y - BARREL_LEN,
            width=18, fill="#b9c6d1", capstyle=tk.ROUND)

        # 炮座
        c.create_oval(CANNON_X - 40, CANNON_Y - 40,
                      CANNON_X + 40, CANNON_Y + 40,
                      fill="#1d3b52", outline="#4f7d9c", width=3)
        c.create_oval(CANNON_X - 24, CANNON_Y - 24,
                      CANNON_X + 24, CANNON_Y + 24,
                      fill="#2b5a78", outline="#6fa8c9", width=2)

    def update_barrel(self):
        mx = CANNON_X + math.cos(self.angle) * (BARREL_LEN - 8)
        my = CANNON_Y + math.sin(self.angle) * (BARREL_LEN - 8)
        self.canvas.coords(self.barrel_outline, CANNON_X, CANNON_Y, mx, my)
        self.canvas.coords(self.barrel, CANNON_X, CANNON_Y, mx, my)

    # ========== 顶部信息栏 ==========
    def create_hud(self):
        c = self.canvas
        c.create_rectangle(0, 0, W, 52, fill="#031c2b", outline="")
        c.create_line(0, 52, W, 52, fill="#12506e", width=2)

        self.coin_text = c.create_text(
            24, 26, anchor="w", text="", fill="#ffd166",
            font=("Microsoft YaHei", 17, "bold"))
        self.score_text = c.create_text(
            W - 24, 26, anchor="e", text="", fill="#7fd8ff",
            font=("Microsoft YaHei", 17, "bold"))
        c.create_text(W / 2, 26, text="捕鱼达人", fill="#2a5a78",
                      font=("Microsoft YaHei", 13))

    def update_hud(self):
        self.canvas.itemconfig(self.coin_text, text="金币: {}".format(self.coins))
        self.canvas.itemconfig(self.score_text, text="得分: {}".format(self.score))

    # ========== 事件绑定 ==========
    def bind_events(self):
        self.canvas.bind("<Motion>", self.on_motion)
        self.canvas.bind("<Button-1>", self.on_click)

    def on_motion(self, event):
        self.mouse_x = event.x
        self.mouse_y = event.y
        self.update_angle()

    def update_angle(self):
        dx = self.mouse_x - CANNON_X
        dy = self.mouse_y - CANNON_Y
        ang = math.atan2(dy, dx)

        # 只允许炮口朝上
        if ang > 0:
            ang = -0.15 if dx >= 0 else -math.pi + 0.15
        ang = max(-math.pi + 0.15, min(-0.15, ang))

        self.angle = ang
        self.update_barrel()

    def on_click(self, event):
        if self.game_over:
            self.restart()
            return
        if self.coins <= 0:
            return
        self.coins -= 1
        self.fire()

    def fire(self):
        a = self.angle
        mx = CANNON_X + math.cos(a) * (BARREL_LEN - 6)
        my = CANNON_Y + math.sin(a) * (BARREL_LEN - 6)
        self.bullets.append(Bullet(
            self.canvas, mx, my,
            math.cos(a) * Bullet.SPEED,
            math.sin(a) * Bullet.SPEED))

    # ========== 鱼的生成 ==========
    def spawn_fish(self):
        total = sum(k["weight"] for k in FISH_KINDS)
        r = random.random() * total
        kind = FISH_KINDS[0]
        for k in FISH_KINDS:
            r -= k["weight"]
            if r <= 0:
                kind = k
                break

        direction = random.choice([1, -1])
        x = -60 if direction == 1 else W + 60
        base_y = random.uniform(80, H - 150)
        speed = random.uniform(kind["smin"], kind["smax"])

        self.fishes.append(Fish(
            self.canvas, x, base_y, kind["size"],
            kind["color"], speed, direction, kind["value"]))

    def try_spawn(self):
        self.spawn_counter += 1
        interval = max(16, 46 - self.frame // 240)   # 越玩鱼越密
        if self.spawn_counter >= interval and len(self.fishes) < FishGame.MAX_FISH:
            self.spawn_counter = 0
            self.spawn_fish()

    # ========== 每帧更新 ==========
    def update_bullets(self):
        keep = []
        for b in self.bullets:
            if not b.alive:
                continue
            b.move()
            if b.out_of_screen():
                b.destroy()
                continue
            keep.append(b)
        self.bullets = keep

    def update_fishes(self):
        keep = []
        for f in self.fishes:
            if not f.alive:
                continue
            f.phase += 0.09
            dx = f.speed * f.direction
            new_y = f.base_y + math.sin(f.phase) * f.amp
            dy = new_y - f.y
            f.x += dx
            f.y = new_y
            f.move(dx, dy)

            if (f.direction > 0 and f.x > W + 150) or \
               (f.direction < 0 and f.x < -150):
                f.destroy()
                continue
            keep.append(f)
        self.fishes = keep

    def update_effects(self):
        keep = []
        for e in self.effects:
            if e.update():
                keep.append(e)
            else:
                e.destroy()
        self.effects = keep

    def check_collisions(self):
        for b in self.bullets[:]:
            if not b.alive:
                continue
            for f in self.fishes[:]:
                if not f.alive:
                    continue
                dx = b.x - f.x
                dy = b.y - f.y
                rr = f.size * 1.15 + b.r
                if dx * dx + dy * dy <= rr * rr:
                    b.alive = False
                    f.alive = False
                    b.destroy()
                    f.destroy()
                    if b in self.bullets:
                        self.bullets.remove(b)
                    if f in self.fishes:
                        self.fishes.remove(f)

                    self.coins += f.value
                    self.score += f.value
                    self.caught += 1
                    self.effects.append(
                        Effect(self.canvas, f.x, f.y, f.color, "+{}".format(f.value)))
                    break

    # ========== 游戏结束 / 重开 ==========
    def end_game(self):
        self.game_over = True
        c = self.canvas
        self.overlay = [
            c.create_rectangle(0, 0, W, H, fill="black",
                               stipple="gray50", outline=""),
            c.create_text(W / 2, H / 2 - 50, text="游戏结束",
                          fill="#ff6b6b",
                          font=("Microsoft YaHei", 46, "bold")),
            c.create_text(W / 2, H / 2 + 20,
                          text="最终得分：{}   捕获：{} 条".format(self.score, self.caught),
                          fill="white",
                          font=("Microsoft YaHei", 20)),
            c.create_text(W / 2, H / 2 + 80, text="点击任意位置重新开始",
                          fill="#7fd8ff",
                          font=("Microsoft YaHei", 16)),
        ]

    def restart(self):
        for f in self.fishes:
            f.destroy()
        for b in self.bullets:
            b.destroy()
        for e in self.effects:
            e.destroy()
        for item in self.overlay:
            self.canvas.delete(item)

        self.fishes.clear()
        self.bullets.clear()
        self.effects.clear()
        self.overlay.clear()

        self.coins = FishGame.START_COINS
        self.score = 0
        self.caught = 0
        self.frame = 0
        self.spawn_counter = 0
        self.game_over = False

        self.update_hud()

    # ========== 主循环 ==========
    def loop(self):
        self.frame += 1

        self.update_bullets()
        self.update_fishes()
        self.update_effects()

        if not self.game_over:
            self.check_collisions()
            self.try_spawn()
            # 没钱且场上没子弹了 —— 游戏结束
            if self.coins <= 0 and not self.bullets:
                self.end_game()

        self.update_hud()
        self.root.after(16, self.loop)


# ---------------- 入口 ----------------
def main():
    root = tk.Tk()
    FishGame(root)
    root.mainloop()


if __name__ == "__main__":
    main()