[python趣味实战]----python动态爱心代码
下面是一个使用Python的turtle
库来绘制动态爱心的示例代码:
import turtle
import math
# 设置屏幕
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("动态爱心")
# 设置爱心参数
heart_color = "red"
heart_size = 8
heart_speed = 0.05
# 绘制爱心函数
def draw_heart(t, size, x, y):
t.penup()
t.goto(x, y)
t.pendown()
t.color(heart_color)
t.startfill()
a = size * 0.5522847498307933
t.left(40)
t.begin_poly()
for i in range(24):
if 0 <= i < 12:
t.left(30)
t.forward(a)
t.right(50)
t.forward(a)
else:
t.left(30)
t.forward(a)
t.right(40)
t.forward(a)
t.end_poly()
heart_points = t.get_poly()
t.fillcolor(heart_color)
t.endfill()
# 创建爱心对象
heart = turtle.Turtle()
draw_heart(heart, heart_size, 0, 0)
# 心跳动画
def beat():
for i in range(24):
t = heart_speed * (24 - i) / 24
heart.speed(99)
heart.setx(math.cos(t * 2 * math.pi) * (heart_size + 50))
heart.sety(math.sin(t * 2 * math.pi) * (heart_size + 50))
screen.update()
# 启动心跳动画
beat()
# 保持屏幕打开
screen.mainloop()
这段代码会创建一个动态的爱心在屏幕上跳动。你可以通过调整heart_size
、heart_color
和heart_speed
变量来改变爱心的大小、颜色和速度。
评论已关闭