import tkinter as tk
from tkinter import colorchooser
import math

class ShapeFactory:
    def __init__(self, root):
        self.root = root
        self.root.title("图形工厂 - Python 版")
        self.root.configure(bg="#1a1e2b")
        self.root.resizable(False, False)

        # ===== 参数 =====
        self.current_color = "#F4C542"
        self.current_shape = "circle"
        self.current_size = 32
        self.shapes = []  # 保存已绘制的图形

        # ===== 主布局 =====
        main_frame = tk.Frame(root, bg="#1a1e2b")
        main_frame.pack(padx=15, pady=15)

        # ---- 画布 ----
        self.canvas = tk.Canvas(
            main_frame, width=520, height=520,
            bg="#0e1014", highlightthickness=2,
            highlightbackground="#f4c542"
        )
        self.canvas.grid(row=0, column=0, padx=(0, 20))
        self.canvas.bind("<Button-1>", self.on_canvas_click)

        # ---- 控制面板 ----
        panel = tk.Frame(main_frame, bg="#12161f", padx=15, pady=15)
        panel.grid(row=0, column=1, sticky="n")

        # 颜色选择
        tk.Label(panel, text="🎨 颜色", fg="#ccd6ec", bg="#12161f",
                 font=("微软雅黑", 11, "bold")).pack(anchor="w")

        color_frame = tk.Frame(panel, bg="#12161f")
        color_frame.pack(pady=5, anchor="w")

        self.color_buttons = []
        preset_colors = ["#F4C542", "#4A9EFF", "#FF6B9D", "#63E6BE", "#B197FC"]
        for c in preset_colors:
            btn = tk.Button(color_frame, bg=c, width=3, height=1,
                            relief="flat", bd=2,
                            command=lambda col=c: self.set_color(col))
            btn.pack(side="left", padx=3)
            self.color_buttons.append((btn, c))

        tk.Button(panel, text="自定义颜色", bg="#2b3242", fg="white",
                  command=self.pick_custom_color).pack(anchor="w", pady=(5, 10))

        # 形状选择
        tk.Label(panel, text="📐 形状", fg="#ccd6ec", bg="#12161f",
                 font=("微软雅黑", 11, "bold")).pack(anchor="w")

        shape_frame = tk.Frame(panel, bg="#12161f")
        shape_frame.pack(pady=5, anchor="w")

        self.shape_btns = {}
        shapes = [("●", "circle"), ("■", "square"), ("▲", "triangle"), ("★", "star")]
        for sym, key in shapes:
            btn = tk.Button(shape_frame, text=sym, width=3, height=1,
                            font=("Arial", 14), bg="#1e2433", fg="#b5c0da",
                            relief="flat", command=lambda k=key: self.set_shape(k))
            btn.pack(side="left", padx=3)
            self.shape_btns[key] = btn

        # 大小滑块
        tk.Label(panel, text="📏 大小", fg="#ccd6ec", bg="#12161f",
                 font=("微软雅黑", 11, "bold")).pack(anchor="w", pady=(10, 0))

        self.size_var = tk.IntVar(value=32)
        size_slider = tk.Scale(panel, from_=10, to=90, orient="horizontal",
                               variable=self.size_var, bg="#12161f", fg="#f4c542",
                               highlightthickness=0, troughcolor="#2b3242",
                               activebackground="#f4c542", length=240,
                               command=self.on_size_change)
        size_slider.pack(anchor="w", pady=5)

        self.size_label = tk.Label(panel, text="32 px", fg="#f4c542", bg="#12161f")
        self.size_label.pack(anchor="w")

        # 按钮
        btn_frame = tk.Frame(panel, bg="#12161f")
        btn_frame.pack(pady=15, fill="x")

        tk.Button(btn_frame, text="↩ 撤销", bg="#1b212e", fg="white",
                  relief="flat", width=10, command=self.undo).pack(side="left", padx=2)

        tk.Button(btn_frame, text="🗑 清空", bg="#1b212e", fg="white",
                  relief="flat", width=10, command=self.clear).pack(side="left", padx=2)

        # 高亮当前形状
        self.set_shape("circle")

    # ===== 交互方法 =====
    def set_color(self, color):
        self.current_color = color
        for btn, c in self.color_buttons:
            btn.configure(relief="sunken" if c == color else "flat", bd=3 if c == color else 2)

    def pick_custom_color(self):
        color = colorchooser.askcolor(title="选择颜色", initialcolor=self.current_color)[1]
        if color:
            self.current_color = color
            for btn, _ in self.color_buttons:
                btn.configure(relief="flat")

    def set_shape(self, shape):
        self.current_shape = shape
        for key, btn in self.shape_btns.items():
            if key == shape:
                btn.configure(bg="#f4c542", fg="#1a1e2b")
            else:
                btn.configure(bg="#1e2433", fg="#b5c0da")

    def on_size_change(self, value):
        self.current_size = int(value)
        self.size_label.configure(text=f"{self.current_size} px")

    # ===== 画布点击 =====
    def on_canvas_click(self, event):
        x, y = event.x, event.y
        half = self.current_size / 2
        # 边界限制
        x = max(half, min(x, 520 - half))
        y = max(half, min(y, 520 - half))

        shape = {
            "type": self.current_shape,
            "color": self.current_color,
            "size": self.current_size,
            "x": x, "y": y
        }
        self.shapes.append(shape)
        self.draw_shape(shape)

    # ===== 绘制图形 =====
    def draw_shape(self, s):
        t, c, size, x, y = s["type"], s["color"], s["size"], s["x"], s["y"]
        half = size / 2

        if t == "circle":
            self.canvas.create_oval(x - half, y - half, x + half, y + half,
                                    fill=c, outline="white", width=1)
        elif t == "square":
            self.canvas.create_rectangle(x - half, y - half, x + half, y + half,
                                         fill=c, outline="white", width=1)
        elif t == "triangle":
            height = size * 0.866
            bottom_y = y + height * 0.6
            top_y = bottom_y - height
            self.canvas.create_polygon(
                x, top_y, x - half, bottom_y, x + half, bottom_y,
                fill=c, outline="white", width=1
            )
        elif t == "star":
            spikes = 5
            outer_r = half
            inner_r = half * 0.45
            rot = math.pi / 2 * 3
            step = math.pi / spikes
            points = []
            for _ in range(spikes):
                points.extend([x + math.cos(rot) * outer_r,
                               y + math.sin(rot) * outer_r])
                rot += step
                points.extend([x + math.cos(rot) * inner_r,
                               y + math.sin(rot) * inner_r])
                rot += step
            self.canvas.create_polygon(points, fill=c, outline="white", width=1)

    # ===== 撤销 & 清空 =====
    def undo(self):
        if self.shapes:
            self.shapes.pop()
            self.canvas.delete("all")
            for s in self.shapes:
                self.draw_shape(s)

    def clear(self):
        self.shapes.clear()
        self.canvas.delete("all")


if __name__ == "__main__":
    root = tk.Tk()
    app = ShapeFactory(root)
    root.mainloop()