import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
import math
import os

# 适配无弹窗环境，开启自动保存
plt.switch_backend('Agg')

# 创建画布
fig, ax = plt.subplots(figsize=(16, 16), dpi=120)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.set_aspect("equal")
ax.axis("off")

# ---------------------- 1. 曼德博集合（经典分形） ----------------------
def mandelbrot(c, max_iter):
    z = complex(0, 0)
    for n in range(max_iter):
        if abs(z) > 2:
            return n
        z = z * z + c
    return max_iter

width, height = 700, 700
x_axis = np.linspace(-2.2, 0.8, width)
y_axis = np.linspace(-1.5, 1.5, height)
X_grid, Y_grid = np.meshgrid(x_axis, y_axis)
iter_max = 100
escape_data = np.zeros((height, width), dtype=np.uint16)

# 逐像素计算逃逸迭代数
for y_idx in range(height):
    for x_idx in range(width):
        complex_num = X_grid[y_idx, x_idx] + 1j * Y_grid[y_idx, x_idx]
        escape_data[y_idx, x_idx] = mandelbrot(complex_num, iter_max)

ax.imshow(escape_data, extent=(-2.2, 0.8, -1.5, 1.5), cmap="twilight_shifted", alpha=0.82, origin="lower")

# ---------------------- 2. 多层旋转正多边形嵌套 3~12边形 ----------------------
center_x, center_y = 0, 0
side_counts = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
poly_color_list = ["#ff2266", "#ffaa00", "#ffee00", "#88ee22", "#00ddbb", "#0099ff", "#7733ff", "#dd33ff", "#ff66aa", "#996633"]
current_radius = 9
angle_rotate_step = 14

for index, side in enumerate(side_counts):
    polygon = RegularPolygon(
        xy=(center_x, center_y),
        numVertices=side,
        radius=current_radius,
        orientation=np.radians(angle_rotate_step * index),
        edgecolor=poly_color_list[index],
        facecolor="none",
        linewidth=1.3
    )
    ax.add_patch(polygon)
    current_radius *= 0.74

# ---------------------- 3. 双向黄金斐波那契螺旋 ----------------------
golden_ratio = (1 + math.sqrt(5)) / 2
theta_range = np.linspace(0, 8 * math.pi, 2000)
radius_spiral = golden_ratio ** (theta_range / (2 * math.pi)) / 12
spiral_x = radius_spiral * np.cos(theta_range)
spiral_y = radius_spiral * np.sin(theta_range)
ax.plot(spiral_x, spiral_y, color="#ffffff", linewidth=1.2, alpha=0.7)

# 反向螺旋
theta_rev = np.linspace(0, -8 * math.pi, 2000)
radius_rev = golden_ratio ** (abs(theta_rev) / (2 * math.pi)) / 12
spiral_x2 = radius_rev * np.cos(theta_rev)
spiral_y2 = radius_rev * np.sin(theta_rev)
ax.plot(spiral_x2, spiral_y2, color="#ffffff", linewidth=1.2, alpha=0.7)

# ---------------------- 4. 多层环形点阵（极坐标星光点） ----------------------
ring_total = 20
point_per_ring = 55
ring_radii = np.linspace(2, 9, ring_total)
for r in ring_radii:
    angle_arr = np.linspace(0, 2 * math.pi, point_per_ring)
    dot_x = r * np.cos(angle_arr)
    dot_y = r * np.sin(angle_arr)
    ax.scatter(dot_x, dot_y, s=1.1, color="#f0f8ff", alpha=0.5)

# ---------------------- 5. 科赫雪花装饰 ----------------------
def draw_snowflake(ox, oy, size, color):
    angle_list = np.radians([0, 60, 120, 180, 240, 300])
    sx = ox + size * np.cos(angle_list)
    sy = oy + size * np.sin(angle_list)
    ax.plot(sx, sy, color=color, lw=1, alpha=0.8)
    # 雪花分叉
    for ang in angle_list:
        ax.plot([ox, ox+size*0.6*math.cos(ang)], [oy, oy+size*0.6*math.sin(ang)], color=color, lw=1, alpha=0.7)

draw_snowflake(-7, 7, 1.7, "#00ffff")
draw_snowflake(7, 7, 1.7, "#ffccff")
draw_snowflake(0, -8, 2.1, "#ffffcc")

# ---------------------- 6. 洛伦兹混沌吸引子 ----------------------
lor_x, lor_y = [], []
x, y, z = 0.2, 0.5, 0.3
sigma, rho, beta = 10, 28, 8/3
dt_step = 0.008

for _ in range(11000):
    dx = sigma * (y - x)
    dy = x * (rho - z) - y
    dz = x * y - beta * z
    x += dx * dt_step
    y += dy * dt_step
    z += dz * dt_step
    lor_x.append(x / 4)
    lor_y.append(y / 4 - 7)

ax.plot(lor_x, lor_y, color="#ff4477", linewidth=0.32, alpha=0.62)

# ---------------------- 7. 多层渐变同心圆外框 ----------------------
outer_circle_colors = ["#222277", "#331166", "#551155", "#772244", "#996633"]
outer_radius_list = np.linspace(9.2, 1.2, len(outer_circle_colors))
for r_val, c_val in zip(outer_radius_list, outer_circle_colors):
    outer_circle = Circle((0, 0), radius=r_val, edgecolor=c_val, facecolor="none", linewidth=1.1, alpha=0.6)
    ax.add_patch(outer_circle)

plt.tight_layout()
# 保存图片到代码同文件夹，文件名 complex_art.png
save_path = "complex_art.png"
plt.savefig(save_path, bbox_inches="tight", pad_inches=0, dpi=120)
print(f"图片已成功保存，路径：{os.path.abspath(save_path)}")

# 恢复后端，支持本地电脑弹窗
try:
    plt.switch_backend('TkAgg')
    plt.show()
except Exception:
    print("当前环境不支持弹窗预览，请打开上面路径的png图片查看")