首页 > 编程语言 >Python:动态爱心代码

Python:动态爱心代码

时间:2024-07-20 23:30:07浏览次数:15  
标签:CANVAS ratio Python 代码 random 爱心 points frame self

import random

from math import sin, cos, pi, log

from tkinter import *

CANVAS_WIDTH = 640

CANVAS_HEIGHT = 480

CANVAS_CENTER_X = CANVAS_WIDTH / 2

CANVAS_CENTER_Y = CANVAS_HEIGHT / 2

IMAGE_ENLARGE = 11

HEART_COLOR = "#FF99CC"


def center_window(root, width, height):
    screenwidth = root.winfo_screenwidth()  # 获取显示屏宽度

    screenheight = root.winfo_screenheight()  # 获取显示屏高度

    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) /

                            2, (screenheight - height) / 2)  # 设置窗口居中参数

    root.geometry(size)  # 让窗口居中显示


def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
    x = 16 * (sin(t) ** 3)

    y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))

    # 放大

    x *= shrink_ratio
    y *= shrink_ratio
    # 移到画布中央

    x += CANVAS_CENTER_X

    y += CANVAS_CENTER_Y

    return int(x), int(y)


def scatter_inside(x, y, beta=0.15):
    ratio_x = - beta * log(random.random())

    ratio_y = - beta * log(random.random())

    dx = ratio_x * (x - CANVAS_CENTER_X)

    dy = ratio_y * (y - CANVAS_CENTER_Y)

    return x - dx, y - dy


def shrink(x, y, ratio):
    force = -1 / (((x - CANVAS_CENTER_X) ** 2 +

                   (y - CANVAS_CENTER_Y) ** 2) ** 0.6)

    dx = ratio * force * (x - CANVAS_CENTER_X)

    dy = ratio * force * (y - CANVAS_CENTER_Y)

    return x - dx, y - dy


def curve(p):
    return 2 * (2 * sin(4 * p)) / (2 * pi)


class Heart:

    def __init__(self, generate_frame=20):

        self._points = set()  # 原始爱心坐标集合

        self._edge_diffusion_points = set()  # 边缘扩散效果点坐标集合

        self._center_diffusion_points = set()  # 中心扩散效果点坐标集合

        self.all_points = {}  # 每帧动态点坐标

        self.build(2000)

        self.random_halo = 1000

        self.generate_frame = generate_frame

        for frame in range(generate_frame):
            self.calc(frame)

    def build(self, number):

        for _ in range(number):
            t = random.uniform(0, 2 * pi)

            x, y = heart_function(t)

            self._points.add((x, y))

        # 爱心内扩散

        for _x, _y in list(self._points):

            for _ in range(3):
                x, y = scatter_inside(_x, _y, 0.05)

                self._edge_diffusion_points.add((x, y))

        # 爱心内再次扩散

        point_list = list(self._points)

        for _ in range(4000):
            x, y = random.choice(point_list)

            x, y = scatter_inside(x, y, 0.17)

            self._center_diffusion_points.add((x, y))

    @staticmethod
    def calc_position(x, y, ratio):

        force = 1 / (((x - CANVAS_CENTER_X) ** 2 +

                      (y - CANVAS_CENTER_Y) ** 2) ** 0.520)

        dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)

        dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)

        return x - dx, y - dy

    def calc(self, generate_frame):

        ratio = 10 * curve(generate_frame / 10 * pi)

        halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))

        halo_number = int(

            3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))

        all_points = []

        # 光环

        heart_halo_point = set()

        for _ in range(halo_number):

            t = random.uniform(0, 2 * pi)

            x, y = heart_function(t, shrink_ratio=11.6)

            x, y = shrink(x, y, halo_radius)

            if (x, y) not in heart_halo_point:
                heart_halo_point.add((x, y))

                x += random.randint(-14, 14)

                y += random.randint(-14, 14)

                size = random.choice((1, 2, 2))

                all_points.append((x, y, size))

        # 轮廓

        for x, y in self._points:
            x, y = self.calc_position(x, y, ratio)

            size = random.randint(1, 3)

            all_points.append((x, y, size))

        # 内容

        for x, y in self._edge_diffusion_points:
            x, y = self.calc_position(x, y, ratio)

            size = random.randint(1, 2)

            all_points.append((x, y, size))

        self.all_points[generate_frame] = all_points

        for x, y in self._center_diffusion_points:
            x, y = self.calc_position(x, y, ratio)

            size = random.randint(1, 2)

            all_points.append((x, y, size))

        self.all_points[generate_frame] = all_points

    def render(self, render_canvas, render_frame):

        for x, y, size in self.all_points[render_frame % self.generate_frame]:
            render_canvas.create_rectangle(

                x, y, x + size, y + size, width=0, fill=HEART_COLOR)


def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
    render_canvas.delete('all')

    render_heart.render(render_canvas, render_frame)

    main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)


if __name__ == '__main__':
    root = Tk()

    root.title("爱心")

    center_window(root, CANVAS_WIDTH, CANVAS_HEIGHT)  # 窗口居中显示

    canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)

    canvas.pack()

    heart = Heart()

    draw(root, canvas, heart)

    Label(root, text="I LOVE YOU", bg="black", fg="#FF99CC", font="Helvetic 20 bold").place(

        relx=.5, rely=.5, anchor=CENTER)

    root.mainloop()

Python是一种通用的编程语言,而Python爱心代码是用Python语言编写的,因此需要在电脑上安装Python环境才能运行这些代码。

其次,除了Python环境外,还需要安装turtle库。turtle库是Python的标准库之一,用于简单的图形绘制。安装turtle库可以通过运行命令pip install turtle来完成。这个库将用于在Python程序中绘制爱心图案。

可在倒数第三行Lable-----text中修改自己想输出的语句

See you next time

标签:CANVAS,ratio,Python,代码,random,爱心,points,frame,self
From: https://blog.csdn.net/2401_82455776/article/details/140579299

相关文章

  • 如何在 PYTHON 中查找输入数字的千位、百位、十位和个位中的数字?例如:256 有 6 个一、5
    num=int(input("Pleasegivemeanumber:"))print(num)thou=int((num//1000))print(thou)hun=int((num//100))print(hun)ten=int((num//10))print(ten)one=int((num//1))print(one)我尝试过这个,但它不起作用,我被困住了。代码几乎是正确的,但需......
  • ModuleNotFoundError:没有名为“pyaes”的模块 python 虚拟机
    在此处输入图像描述当我在启动python项目的虚拟机上构建某个工具时,几秒钟后会出现此消息。我已经尝试重新安装pyaes但无济于事。谁能帮我?非常感谢我已经尝试重新安装pyaes但无济于事,我搜索了tepyaes模块的十个路径,但我没有找到它,而我在另一台虚拟机上完成了......
  • 如何通过 mutagen (Python) 为 mp3 文件中的情绪添加价值?
    我找不到通过mutagen(Python库)将情绪写入mp3文件的方法初始化:frommutagen.mp3importMP3frommutagen.id3importID3,TIT2,TALB,TPE1,TPE2,TCON,TPUB,TENC,TIT3,APIC,WOAR,PRIVaudio=MP3(mp3_file,ID3=ID3)我可以使用audio['TIT3']=TIT3(......
  • 使用 Python 操作 Splunk
    使用Python操作Splunk目录使用Python操作Splunk1参考文档2安装PythonSplunk-SDK3连接splunk4配置查询5参考1参考文档SplunkGithub地址:GitHub-splunk/splunk-sdk-python:SplunkSoftwareDevelopmentKitforPythonSplunk开发者文档地址:Pythontools|......
  • 我如何修复我的代码,它返回一个空列表?
    我正在抓取一个电子商务网站,它返回一个空列表这是我编写的代码。importrequestsfrombs4importBeautifulSoupbaseurl='https://www.thewhiskyexchange.com/'headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,l......
  • 代码随想录算法训练营第十七天 | 530.二叉搜索树的最小绝对差 、 501.二叉搜索树中的
    530.二叉搜索树的最小绝对差 题目:.-力扣(LeetCode)思路:中序遍历搜索二叉树,使用双指针来计算绝对值。代码:/***Definitionforabinarytreenode.*structTreeNode{*intval;*TreeNode*left;*TreeNode*right;*TreeNode():val(0),......
  • 代码随想录算法训练营第十五天 | 110.平衡二叉树、257. 二叉树的所有路径 、404.左叶
    110.平衡二叉树题目:.-力扣(LeetCode)思路:后序遍历计算高度代码:/***Definitionforabinarytreenode.*structTreeNode{*intval;*TreeNode*left;*TreeNode*right;*TreeNode():val(0),left(nullptr),right(nullptr){}*......
  • Python:如何通过请求帖子对评论进行投票?
    我对评论进行投票的代码无法正常工作。它返回一个http500错误。我有一个使用用户登录的Python程序,它应该自动对评论进行投票。我的代码如下:frombs4importBeautifulSoupimportrequestslogin_url="https://xxxxxxxxxxx/auth/login"login_url_post="http......
  • python_day7(补1)
    数据类型​ 之前为列表类型​ 插入一个元组的介绍 之后还有字典,三者区别为括号方式()[]{}元组类型(tuple)使用:先定义一个元组数据​ vegetable_tuple='(tomato','corn','cucumber','carrot','corn','pumpkin)'与列表类型格式很像,不过只能取不能改,需要特......
  • 基于 T4 模板生成代码
    Asp.NetCore系列:基于T4模板生成代码  目录简介组成部分分类VisualStudio中使用T4模板1.创建T4模板文件2.编写T4模板3.转换模板中心控制Manager根据MySQL数据库生成实体 简介T4模板,即TextTemplateTransformationToolkit,是微软官方在Visua......