Python:流动爱心图案

  1. from turtle import *:导入了Python标准库中的turtle模块,并使用通配符*导入了该模块中的所有函数和变量。turtle模块提供了一个绘图窗口和一些绘图函数,可以用来绘制简单的图形。

  2. from math import sqrt:导入了Python标准库中的math模块,并导入了该模块中的sqrt函数。sqrt函数用于计算平方根。

  3. from random import random, randint:导入了Python标准库中的random模块,并导入了该模块中的randomrandint函数。random函数用于生成一个0到1之间的随机浮点数,randint函数用于生成一个指定范围内的随机整数。

导入了几个Python标准库中的模块和函数,以便在代码中使用这些函数来绘制图形和生成随机数。

python中缺库将无法运行,具体操作可以在win+R 输入cmd中 输入 pip install +库名

代码如下:

from turtle import *
from math import sqrt
from random import random, randint
class Heart:
    def __init__(self, x, y, size):
        self.size = size    # 心形大小
        self.speed = size    # 移动速度根据大小变化
        # 设置画笔的统一属性
        t = Turtle(visible=False, shape='circle')
        t.shapesize(size, size)
        color = (1, 1- size/4, 1-size/4)     # 颜色修改为根据大小变化的粉色
        t.pencolor(color)
        t.fillcolor(color)
        t.penup()
        # 克隆一个圆形,设置位置
        self.circle1 = t.clone()
        self.circle1.goto(x-sqrt(size*size*160)/2, y)
        # 克隆第二个圆形,设置位置
        self.circle2 = t.clone()
        self.circle2.goto(x+sqrt(size*size*160)/2, y)
        # 克隆一个正方形,设置位置并旋转角度
        self.square = t.clone()
        self.square.shape("square")
        self.square.setheading(45)
        self.square.goto(x, y-sqrt(size * size * 160)/2)
        # 显示图形
        self.circle1.showturtle()
        self.circle2.showturtle()
        self.square.showturtle()
    def move(self):
        self.circle1.setx(self.circle1.xcor()-self.speed)
        self.square.setx(self.square.xcor() - self.speed)
        self.circle2.setx(self.circle2.xcor() - self.speed)
    def moveTo(self, x, y):
        # 隐藏形状后再移动防止看到移动轨迹
        self.circle1.hideturtle()
        self.circle2.hideturtle()
        self.square.hideturtle()
        # 移动到指定位置
        self.circle1.goto(x - sqrt(self.size * self.size * 160) / 2, y)
        self.circle2.goto(x + sqrt(self.size * self.size * 160) / 2, y)
        self.square.goto(x, y - sqrt(self.size * self.size * 160) / 2)
        # 恢复显示
        self.circle1.showturtle()
        self.circle2.showturtle()
        self.square.showturtle()


width, height = 800, 600
screen = Screen()     # 创建窗口对象
screen.setup(width, height)    # 设置窗口的宽高
screen.delay(0)    # 设置无延时绘画
screen.bgcolor('pink')     # 设置背景颜色为粉色

hearts = []
for i in range(25):
    heart = Heart(width/2 + randint(1, width), randint(-height/2,height/2), random()*3)
    hearts.append(heart)
while True:
    for heart in hearts:
        heart.move()
        if heart.square.xcor() < -width / 2:    # 如果爱心移动出屏幕左侧
            heart.moveTo(width / 2 + randint(1, width), randint(-height/2, height/2))   # 回到右侧随机位置

运行结果如下:

Python:流动爱心图案_第1张图片

 

你可能感兴趣的:(python源码分享,python,开发语言)