import turtle
import math
import colorsys
# 初始化设置
turtle.setup(800, 800) # 设置窗口大小
turtle.title("绚丽旋转爱心") # 窗口标题
turtle.bgcolor('black') # 背景设为黑色
turtle.colormode(1.0) # 颜色模式设为0-1范围
turtle.tracer(0) # 关闭自动刷新
pen = turtle.Turtle() # 创建画笔对象
pen.hideturtle() # 隐藏乌龟图标
pen.speed(0) # 最快绘制速度
pen.pensize(3) # 画笔粗细
# 爱心参数
scale = 15 # 缩放系数
rotation_speed = 1 # 旋转速度(度/帧)
color_speed = 0.1 # 颜色变化速度
def draw_heart(angle):
pen.clear()
for theta in range(0, 628, 2): # 0到2π(步长0.02π)
# 计算原始坐标
theta_rad = theta / 100
x = 16 * (math.sin(theta_rad) ** 3) * scale
y = (13 * math.cos(theta_rad) - 5 * math.cos(2*theta_rad)
- 2 * math.cos(3*theta_rad) - math.cos(4*theta_rad)) * scale
# 坐标旋转
rad = math.radians(angle)
x_rot = x * math.cos(rad) - y * math.sin(rad)
y_rot = x * math.sin(rad) + y * math.cos(rad)
# 动态颜色计算
h = (theta_rad/(2*math.pi) + angle*color_speed/360) % 1
r, g, b = colorsys.hsv_to_rgb(h, 1.0, 1.0)
# 绘制操作
pen.color(r, g, b)
if theta == 0:
pen.penup()
pen.goto(x_rot, y_rot)
pen.pendown()
else:
pen.goto(x_rot, y_rot)
# 动画循环
angle = 0
while True:
draw_heart(angle)
turtle.update() # 刷新画面
angle += rotation_speed # 更新旋转角度
angle %= 360 # 保持角度在0-360度之间