当前位置:   article > 正文

python简单的画图代码爱心,python画爱心代码大全_爱心画图源代码

爱心画图源代码

大家好,本文将围绕用python画一个心形怎么编程展开说明,python简单的画图代码爱心是一个很多人都想弄明白的事情,想搞清楚python画爱心代码大全需要先了解以下几个事情。

python爱心源代码集锦(18款)

        本文目录:

一、代码效果预览索引图

二、爱心源代码集锦

1)、爱心图形1(弧线型)(显示的文字写在代码里)

(2)、爱心图形2(直线型)(显示的文字写在代码里)

(3)、爱心图形3(弧线型)(通过输入方式显示文字)

(4)、用python绘制爱心树

(5)、粒子系统组成爱心,中间加字

(6)、粒子系统组成爱心

(7)、粒子系统组成爱心

(8)、最先复现“李峋爱心”代码的作者

(9)、跳动爱心

(10)、空心爱心

11)、空心立体爱心

(12)、李峋同款爱心代码【有声版】

 三、python字符画爱心 

(1)、一行代码画爱心

(2)、用字符输出 I 爱 U (2种形式)

(3)、输出五个爱心,由Dear I love you forever! 五个单词填充而成

(4)、字符输出爱心曲线公式爱心1

(5)、字符输出爱心曲线公式爱心2


  这篇文章是python 绘制爱心动画的源码集锦合集,每篇都附有原作者的名字博客链接。使用时将代码复制后在相关的编程语言环境下运行python简单代码案例

  代码仅供学习参考,请尊重原作者的创作和版权!

  如果代码作者转载地址有错,请原作者留言,我会更正相应的代码原作者博客链接。

一、代码效果预览索引图

  本文收集的python绘制的爱心动画源代码,主要涉及的模块有turtle、tkinter、math等。代码涉及的库,学习研究运行前需确保代码需要的库函数有安装。

11、空心立体爱心12、李峋同款爱心代码【有声版】

8、最先复现李峋爱心代码的作者9、跳动爱心10、爱心

5、粒子组成爱心,中间加字

6、粒子组成爱心

7、粒子组成爱心

1、(弧线型)(显示文字)

2、(直线型)(显示文字)

3、(弧线型)(输入显示文字)

4、爱心树

python字符画爱心

此部分的代码会显示在终端,如果你没有打开终端会看不到效果。如果你没有专业的代码编辑器,只想试试效果,运行方式:

1、安装python配置好环境

2、将代码完整复制,保存成:你的文件名.py

3、同时按window+R键,输入cmd,打开命令提示符窗口

输入:python 你的文件名.py

(1)一行代码画爱心(2)用字符输出 I 爱 U (2种形式)(2)用字符输出 I 爱 U (2种形式)

(3)输出五个爱心(Dear I love you forever! )五个单词填充而成(4)爱心(5)爱心

二、爱心源代码集锦

如果你没有专业的代码编辑器,只想试试效果,运行方式:

1、安装python配置好环境

2、将代码完整复制,保存成:你的文件名.py

3、同时按window+R键,输入cmd,打开命令提示符窗口

输入:python 你的文件名.py(注:python后面有空格)

 (1)、爱心图形1(弧线型)(显示的文字写在代码里)

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

  1. import turtle
  2. import time
  3. def LittleHeart():
  4. for i in range(200):
  5. turtle.right(1)
  6. turtle.forward(2)
  7. # love = input('请输入表白语句,然后回车,默认为"I Love You":\n')
  8. # me = input('请输入要表白的人:\n')
  9. # if love=='':
  10. # # 如果未输入表白语句,则使用默认语句
  11. # love='I Love you'
  12. love='I Love you'
  13. me = '卧槽,这年轻人。'
  14. turtle.setup(width=900,height=600) # 爱心的画布的大小
  15. turtle.color('red','red') # 爱心的颜色及外边笔的颜色
  16. turtle.pensize(5) # 画笔的粗细
  17. turtle.speed(1000000) # 绘制速度
  18. turtle.up() # 画笔向上
  19. turtle.hideturtle()
  20. turtle.goto(0,-180)
  21. turtle.showturtle()
  22. turtle.down()
  23. turtle.speed(5)
  24. turtle.begin_fill()
  25. # 开始填充
  26. turtle.left(140)
  27. turtle.forward(224)
  28. LittleHeart()
  29. turtle.left(120)
  30. LittleHeart()
  31. turtle.forward(224)
  32. turtle.end_fill()
  33. turtle.pensize(5)
  34. turtle.up()
  35. turtle.hideturtle()
  36. turtle.goto(0,0)
  37. turtle.showturtle()
  38. turtle.color('#CD5C5C','pink')
  39. turtle.write(love,font=('gungsuh',30,),align="center")
  40. turtle.up()
  41. turtle.hideturtle()
  42. if me !='':
  43. turtle.color('black', 'pink')
  44. time.sleep(2)
  45. turtle.goto(180,-180)
  46. turtle.showturtle()
  47. turtle.write(me, font=(20,), align="center", move=True)
  48. window=turtle.Screen()
  49. window.exitonclick()


 

(2)、爱心图形2(直线型)(显示的文字写在代码里)

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

  1. import turtle
  2. import math
  3. turtle.pen()
  4. t=turtle
  5. t.up()
  6. t.goto(0,150)
  7. t.down()
  8. t.color('red')
  9. t.begin_fill()
  10. t.fillcolor('red')
  11. t.speed(1)
  12. t.left(45)
  13. t.forward(150)
  14. t.right(45)
  15. t.forward(100)
  16. t.right(45)
  17. t.forward(100)
  18. t.right(45)
  19. t.forward(100)
  20. t.right(45)
  21. t.forward(250+math.sqrt(2)*100)
  22. t.right (90)
  23. t.speed(2)
  24. t.forward(250+100*math.sqrt(2))
  25. t.right(45)
  26. t.forward(100)
  27. t.right(45)
  28. t.forward(100)
  29. t.right(45)
  30. t.forward(100)
  31. t.right(45)
  32. t.forward(150)
  33. t.end_fill()
  34. t.goto(-10,0)
  35. t.pencolor('white')
  36. # L
  37. t.pensize(10)
  38. t.goto(-50,0)
  39. t.goto(-50,80)
  40. t.up ()
  41. # I
  42. t.goto(-100,0)
  43. t.down()
  44. t.goto(-160,0)
  45. t.goto(-130,0)
  46. t.goto(-130,80)
  47. t.goto(-160,80)
  48. t.goto(-100,80)
  49. t.up()
  50. # O
  51. t.goto(10,25)
  52. t.down()
  53. t.right(45)
  54. t.circle(25,extent=180)
  55. t.goto(60,55)
  56. t.circle(25,extent=180)
  57. t.goto(10,25)
  58. t.up()
  59. t.goto(75,80)
  60. t.down()
  61. t.goto(100,0)
  62. t.goto(125,80)
  63. t.up()
  64. t.goto(180,80)
  65. t.down()
  66. t.goto(140,80)
  67. t.goto(140,0)
  68. t.goto(180,0)
  69. t.up()
  70. t.goto(180,40)
  71. t.down()
  72. t.goto(140,40)
  73. # U
  74. t.up()
  75. t.goto(-40,-30)
  76. t.down()
  77. t.goto(-40,-80)
  78. t.circle(40,extent=180)
  79. t.goto(40,-30)
  80. t.hideturtle()
  81. window=turtle.Screen()
  82. window.exitonclick()

(3)、爱心图形3(弧线型)(通过输入方式显示文字)

请输入表白语句,然后回车,(例如"I Love You"):

请输入要表白的人(例如"李思思"):

转载地址:https://changxin.blog.csdn.net/article/details/109842795 

  1. # coding: utf-8
  2. import turtle
  3. import time
  4. def LittleHeart():
  5. for i in range(200):
  6. turtle.right(1)
  7. turtle.forward(2)
  8. love=input('请输入表白语句,然后回车,(例如"I Love You"):\n')
  9. me=input('请输入要表白的人(例如"李思思"):\n')
  10. if love=='':
  11. love='I Love you'
  12. turtle.setup(width=900,height=600)
  13. turtle.color('red','pink')
  14. turtle.pensize(15)
  15. turtle.speed(1000)
  16. turtle.up()
  17. turtle.hideturtle()
  18. turtle.goto(0,-180)
  19. turtle.showturtle()
  20. turtle.down()
  21. turtle.speed(500)
  22. turtle.begin_fill()
  23. turtle.left(140)
  24. turtle.forward(224)
  25. LittleHeart()
  26. turtle.left(120)
  27. LittleHeart()
  28. turtle.forward(224)
  29. turtle.end_fill()
  30. turtle.pensize(12)
  31. turtle.up()
  32. turtle.hideturtle()
  33. turtle.goto(0,-20)
  34. turtle.showturtle()
  35. turtle.color('#CD5C5C','pink')
  36. turtle.write(love,font=('gungsuh',50,),align="center")
  37. turtle.up()
  38. turtle.hideturtle()
  39. if me !='':
  40. turtle.color('black', 'pink')
  41. time.sleep(1)
  42. turtle.goto(180,-180)
  43. turtle.showturtle()
  44. turtle.write(me, font=(20,25), align="center", move=True)
  45. window=turtle.Screen()
  46. window.exitonclick()

(4)、用python绘制爱心树

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

  1. import turtle
  2. import random
  3. def love(x, y): # 在(x,y)处画爱心lalala
  4. lv = turtle.Turtle()
  5. lv.hideturtle()
  6. lv.up()
  7. lv.goto(x, y) # 定位到(x,y)
  8. def curvemove(): # 画圆弧
  9. for i in range(20):
  10. lv.right(10)
  11. lv.forward(2)
  12. lv.color('red', 'pink')
  13. lv.speed(10000000)
  14. lv.pensize(1)
  15. # 开始画爱心lalala
  16. lv.down()
  17. lv.begin_fill()
  18. lv.left(140)
  19. lv.forward(22)
  20. curvemove()
  21. lv.left(120)
  22. curvemove()
  23. lv.forward(22)
  24. lv.write("YZ", font=("Arial", 12, "normal"), align="center") # 写上表白的人的名字
  25. lv.left(140) # 画完复位
  26. lv.end_fill()
  27. def tree(branchLen, t):
  28. if branchLen > 5: # 剩余树枝太少要结束递归
  29. if branchLen < 20: # 如果树枝剩余长度较短则变绿
  30. t.color("green")
  31. t.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))
  32. t.down()
  33. t.forward(branchLen)
  34. love(t.xcor(), t.ycor()) # 传输现在turtle的坐标
  35. t.up()
  36. t.backward(branchLen)
  37. t.color("brown")
  38. return
  39. t.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))
  40. t.down()
  41. t.forward(branchLen)
  42. # 以下递归
  43. ang = random.uniform(15, 45)
  44. t.right(ang)
  45. tree(branchLen - random.uniform(12, 16), t) # 随机决定减小长度
  46. t.left(2 * ang)
  47. tree(branchLen - random.uniform(12, 16), t) # 随机决定减小长度
  48. t.right(ang)
  49. t.up()
  50. t.backward(branchLen)
  51. myWin = turtle.Screen()
  52. t = turtle.Turtle()
  53. t.hideturtle()
  54. t.speed(1000)
  55. t.left(90)
  56. t.up()
  57. t.backward(200)
  58. t.down()
  59. t.color("brown")
  60. t.pensize(32)
  61. t.forward(60)
  62. tree(100, t)
  63. myWin.exitonclick()

(5)、粒子系统组成爱心,中间加字

注释

调参改变下面这里的代码 text=“”位置 改成自己想要的文字, 不想要可以直接去掉代码

text:想要表现的文本   fg:文字颜色   bg文字的背景颜色(其实有瑕疵的因为文字是更上一层的图层会有覆盖)

    text1 = Label(root, text="By SilverPriest ᏊˊꈊˋᏊ", font=("Helvetica", 18), fg="#c12bec",bg = "black")
    text1.place(x=650, y=500)
 
    text2 = Label(root, text="爱你",font = ("Helvetica", 18), fg = "#c12bec" ,bg = "black") #
    text2.place(x=460, y=350)

https://blog.csdn.net/CL_Young/article/details/127893960 

  1. # Beating Heart
  2. # default input
  3. import random
  4. from math import sin, cos, pi, log
  5. from tkinter import *
  6. CANVAS_WIDTH = 980 # frame_width
  7. CANVAS_HEIGHT = 720 # frame_height
  8. CANVAS_CENTER_X = CANVAS_WIDTH / 2 # frame_center_x
  9. CANVAS_CENTER_Y = CANVAS_HEIGHT / 2 # center_y
  10. IMAGE_ENLARGE = 11 # ratio
  11. # color list
  12. HEART_COLOR_LIST = ["#d974ff", "#be77fa", "#a478f3", "#8b78ea", "#7377e0",
  13. "#4871c6", "#5c74d3", "#fa6ea9", "#dc6db1", "#ec2c2c",
  14. "#e91e41", "#8b4593", "#2bd3ec", "#00be93", "#2bec62"]
  15. def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
  16. """
  17. create a heart
  18. :param shrink_ratio: ratio
  19. :param t: parameter
  20. :return: x, y
  21. """
  22. # basic function, size
  23. x = 16 * (sin(t) ** 3)
  24. y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
  25. # zoom
  26. x *= shrink_ratio
  27. y *= shrink_ratio
  28. # center
  29. x += CANVAS_CENTER_X
  30. y += CANVAS_CENTER_Y
  31. return int(x), int(y)
  32. def scatter_inside(x, y, beta=1.15):
  33. """
  34. random inner spreading
  35. :param x: orig x
  36. :param y: orig y
  37. :param beta: strength
  38. :return: new x, y
  39. """
  40. ratio_x = - beta * log(random.random())
  41. ratio_y = - beta * log(random.random())
  42. dx = ratio_x * (x - CANVAS_CENTER_X)
  43. dy = ratio_y * (y - CANVAS_CENTER_Y)
  44. return x - dx, y - dy
  45. def shrink(x, y, ratio):
  46. """
  47. shrink
  48. :param x: orig x
  49. :param y: orig y
  50. :param ratio: ratio
  51. :return: new x,y
  52. """
  53. force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6) # 这个参数...
  54. dx = ratio * force * (x - CANVAS_CENTER_X)
  55. dy = ratio * force * (y - CANVAS_CENTER_Y)
  56. return x - dx, y - dy
  57. def curve(p):
  58. """
  59. tune beating period
  60. :param p: parameter
  61. :return: sin
  62. """
  63. # alg
  64. return 2 * (2 * sin(4 * p)) / (2 * pi)
  65. class Heart:
  66. def __init__(self, generate_frame=20):
  67. self._points = set()
  68. self._edge_diffusion_points = set()
  69. self._center_diffusion_points = set()
  70. self.all_points = {}
  71. self.build(2000)
  72. self.random_halo = 1000
  73. self.generate_frame = generate_frame
  74. for frame in range(generate_frame):
  75. self.calc(frame)
  76. def build(self, number):
  77. # heart
  78. for _ in range(number):
  79. t = random.uniform(0, 2 * pi)
  80. x, y = heart_function(t)
  81. self._points.add((x, y))
  82. # inner heart 1
  83. for _x, _y in list(self._points):
  84. for _ in range(3):
  85. x, y = scatter_inside(_x, _y, 0.05)
  86. self._edge_diffusion_points.add((x, y))
  87. # inner heart 2
  88. point_list = list(self._points)
  89. for _ in range(6000):
  90. x, y = random.choice(point_list)
  91. x, y = scatter_inside(x, y, 0.17)
  92. self._center_diffusion_points.add((x, y))
  93. @staticmethod
  94. def calc_position(x, y, ratio):
  95. # tune ratio
  96. force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520) # alg
  97. dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
  98. dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)
  99. return x - dx, y - dy
  100. def calc(self, generate_frame):
  101. ratio = 10 * curve(generate_frame / 10 * pi) # curve
  102. halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
  103. halo_number = int(3000 + 6000 * abs(curve(generate_frame / 10 * pi) ** 2))
  104. all_points = []
  105. # ring
  106. heart_halo_point = set() # x,y of ring pts
  107. for _ in range(halo_number):
  108. t = random.uniform(0, 2 * pi)
  109. x, y = heart_function(t, shrink_ratio=11.6) # alg
  110. x, y = shrink(x, y, halo_radius)
  111. if (x, y) not in heart_halo_point:
  112. # new pts
  113. heart_halo_point.add((x, y))
  114. x += random.randint(-14, 14)
  115. y += random.randint(-14, 14)
  116. size = random.choice((1, 2, 2))
  117. all_points.append((x, y, size))
  118. # appearance
  119. for x, y in self._points:
  120. x, y = self.calc_position(x, y, ratio)
  121. size = random.randint(1, 3)
  122. all_points.append((x, y, size))
  123. # content
  124. for x, y in self._edge_diffusion_points:
  125. x, y = self.calc_position(x, y, ratio)
  126. size = random.randint(1, 2)
  127. all_points.append((x, y, size))
  128. for x, y in self._center_diffusion_points:
  129. x, y = self.calc_position(x, y, ratio)
  130. size = random.randint(1, 2)
  131. all_points.append((x, y, size))
  132. self.all_points[generate_frame] = all_points
  133. def render(self, render_canvas, render_frame):
  134. for x, y, size in self.all_points[render_frame % self.generate_frame]:
  135. render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=random.choice(HEART_COLOR_LIST))
  136. def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
  137. render_canvas.delete('all')
  138. render_heart.render(render_canvas, render_frame)
  139. main.after(70, draw, main, render_canvas, render_heart, render_frame + 1)
  140. if __name__ == '__main__':
  141. root = Tk() # Tk
  142. canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
  143. canvas.pack()
  144. heart = Heart()
  145. draw(root, canvas, heart) # draw
  146. text1 = Label(root, text="By SilverPriest ᏊˊꈊˋᏊ", font=("Helvetica", 18), fg="#c12bec",bg = "black")
  147. text1.place(x=650, y=500)
  148. text2 = Label(root, text="爱你",font = ("Helvetica", 18), fg = "#c12bec" ,bg = "black") #
  149. text2.place(x=460, y=350)
  150. root.mainloop()

(6)、粒子系统组成爱心

https://blog.csdn.net/CL_Young/article/details/127808312

  1. import random
  2. from math import sin, cos, pi, log
  3. from tkinter import *
  4. CANVAS_WIDTH = 840 # 画布的宽
  5. CANVAS_HEIGHT = 680 # 画布的高
  6. CANVAS_CENTER_X = CANVAS_WIDTH / 2 # 画布中心的X轴坐标
  7. CANVAS_CENTER_Y = CANVAS_HEIGHT / 2 # 画布中心的Y轴坐标
  8. IMAGE_ENLARGE = 11 # 放大比例
  9. HEART_COLOR = "#EEAEEE" #引号内修改颜色!颜色代码放在文章末尾
  10. def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
  11. """
  12. “爱心函数生成器”
  13. :param shrink_ratio: 放大比例
  14. :param t: 参数
  15. :return: 坐标
  16. """
  17. # 基础函数
  18. x = 17 * (sin(t) ** 3)
  19. y = -(16 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(3 * t))
  20. # 放大
  21. #x *= shrink_ratio
  22. #y *= shrink_ratio
  23. x*=IMAGE_ENLARGE
  24. y*=IMAGE_ENLARGE
  25. # 移到画布中央
  26. x += CANVAS_CENTER_X
  27. y += CANVAS_CENTER_Y
  28. return int(x), int(y)
  29. def scatter_inside(x, y, beta=0.15):
  30. """
  31. 随机内部扩散
  32. :param x: 原x
  33. :param y: 原y
  34. :param beta: 强度
  35. :return: 新坐标
  36. """
  37. ratio_x = - beta * log(random.random())
  38. ratio_y = - beta * log(random.random())
  39. dx = ratio_x * (x - CANVAS_CENTER_X)
  40. dy = ratio_y * (y - CANVAS_CENTER_Y)
  41. return x - dx, y - dy
  42. def shrink(x, y, ratio):
  43. """
  44. 抖动
  45. :param x: 原x
  46. :param y: 原y
  47. :param ratio: 比例
  48. :return: 新坐标
  49. """
  50. force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6) # 这个参数...
  51. dx = ratio * force * (x - CANVAS_CENTER_X)
  52. dy = ratio * force * (y - CANVAS_CENTER_Y)
  53. return x - dx, y - dy
  54. def curve(p):
  55. """
  56. 自定义曲线函数,调整跳动周期
  57. :param p: 参数
  58. :return: 正弦
  59. """
  60. # 可以尝试换其他的动态函数,达到更有力量的效果(贝塞尔?)
  61. return 2 * (2 * sin(4 * p)) / (2 * pi)
  62. class Heart:
  63. """
  64. 爱心类
  65. """
  66. def __init__(self, generate_frame=20):
  67. self._points = set() # 原始爱心坐标集合
  68. self._edge_diffusion_points = set() # 边缘扩散效果点坐标集合
  69. self._center_diffusion_points = set() # 中心扩散效果点坐标集合
  70. self.all_points = {} # 每帧动态点坐标
  71. self.build(2000)
  72. self.random_halo = 1000
  73. self.generate_frame = generate_frame
  74. for frame in range(generate_frame):
  75. self.calc(frame)
  76. def build(self, number):
  77. # 爱心
  78. for _ in range(number):
  79. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  80. x, y = heart_function(t)
  81. self._points.add((x, y))
  82. # 爱心内扩散
  83. for _x, _y in list(self._points):
  84. for _ in range(3):
  85. x, y = scatter_inside(_x, _y, 0.05)
  86. self._edge_diffusion_points.add((x, y))
  87. # 爱心内再次扩散
  88. point_list = list(self._points)
  89. for _ in range(10000):
  90. x, y = random.choice(point_list)
  91. x, y = scatter_inside(x, y, 0.27)
  92. self._center_diffusion_points.add((x, y))
  93. @staticmethod
  94. def calc_position(x, y, ratio):
  95. # 调整缩放比例
  96. force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.420) # 魔法参数
  97. dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
  98. dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)
  99. return x - dx, y - dy
  100. def calc(self, generate_frame):
  101. ratio = 15 * curve(generate_frame / 10 * pi) # 圆滑的周期的缩放比例
  102. halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
  103. halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
  104. all_points = []
  105. # 光环
  106. heart_halo_point = set() # 光环的点坐标集合
  107. for _ in range(halo_number):
  108. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  109. x, y = heart_function(t, shrink_ratio=-15) # 魔法参数
  110. x, y = shrink(x, y, halo_radius)
  111. if (x, y) not in heart_halo_point:
  112. # 处理新的点
  113. heart_halo_point.add((x, y))
  114. x += random.randint(-60, 60)
  115. y += random.randint(-60, 60)
  116. size = random.choice((1, 1, 2))
  117. all_points.append((x, y, size))
  118. all_points.append((x+20, y+20, size))
  119. all_points.append((x-20, y -20, size))
  120. all_points.append((x+20, y - 20, size))
  121. all_points.append((x - 20, y +20, size))
  122. # 轮廓
  123. for x, y in self._points:
  124. x, y = self.calc_position(x, y, ratio)
  125. size = random.randint(1, 3)
  126. all_points.append((x, y, size))
  127. # 内容
  128. for x, y in self._edge_diffusion_points:
  129. x, y = self.calc_position(x, y, ratio)
  130. size = random.randint(1, 2)
  131. all_points.append((x, y, size))
  132. for x, y in self._center_diffusion_points:
  133. x, y = self.calc_position(x, y, ratio)
  134. size = random.randint(1, 2)
  135. all_points.append((x, y, size))
  136. self.all_points[generate_frame] = all_points
  137. def render(self, render_canvas, render_frame):
  138. for x, y, size in self.all_points[render_frame % self.generate_frame]:
  139. render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=HEART_COLOR)
  140. def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
  141. render_canvas.delete('all')
  142. render_heart.render(render_canvas, render_frame)
  143. main.after(1, draw, main, render_canvas, render_heart, render_frame + 1)
  144. if __name__ == '__main__':
  145. root = Tk()
  146. canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
  147. canvas.pack()
  148. heart = Heart()
  149. draw(root, canvas, heart)
  150. root.mainloop()

 (7)、粒子系统组成爱心

https://blog.csdn.net/CL_Young/article/details/1270831

  1. import random
  2. from math import sin, cos, pi, log
  3. from tkinter import *
  4. CANVAS_WIDTH = 640 # 画布的宽
  5. CANVAS_HEIGHT = 480 # 画布的高
  6. CANVAS_CENTER_X = CANVAS_WIDTH / 2 # 画布中心的X轴坐标
  7. CANVAS_CENTER_Y = CANVAS_HEIGHT / 2 # 画布中心的Y轴坐标
  8. IMAGE_ENLARGE = 11 # 放大比例
  9. HEART_COLOR = "pink" # 心的颜色
  10. def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
  11. """
  12. “爱心函数生成器”
  13. :param shrink_ratio: 放大比例
  14. :param t: 参数
  15. :return: 坐标
  16. """
  17. # 基础函数
  18. x = 16 * (sin(t) ** 3)
  19. y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
  20. # 放大
  21. x *= shrink_ratio
  22. y *= shrink_ratio
  23. # 移到画布中央
  24. x += CANVAS_CENTER_X
  25. y += CANVAS_CENTER_Y
  26. return int(x), int(y)
  27. def scatter_inside(x, y, beta=0.15):
  28. """
  29. 随机内部扩散
  30. :param x: 原x
  31. :param y: 原y
  32. :param beta: 强度
  33. :return: 新坐标
  34. """
  35. ratio_x = - beta * log(random.random())
  36. ratio_y = - beta * log(random.random())
  37. dx = ratio_x * (x - CANVAS_CENTER_X)
  38. dy = ratio_y * (y - CANVAS_CENTER_Y)
  39. return x - dx, y - dy
  40. def shrink(x, y, ratio):
  41. """
  42. 抖动
  43. :param x: 原x
  44. :param y: 原y
  45. :param ratio: 比例
  46. :return: 新坐标
  47. """
  48. force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6) # 这个参数...
  49. dx = ratio * force * (x - CANVAS_CENTER_X)
  50. dy = ratio * force * (y - CANVAS_CENTER_Y)
  51. return x - dx, y - dy
  52. def curve(p):
  53. """
  54. 自定义曲线函数,调整跳动周期
  55. :param p: 参数
  56. :return: 正弦
  57. """
  58. return 4 * (2 * sin(4 * p)) / (2 * pi)
  59. class Heart:
  60. """
  61. 爱心类
  62. """
  63. def __init__(self, generate_frame=20):
  64. self._points = set() # 原始爱心坐标集合
  65. self._edge_diffusion_points = set() # 边缘扩散效果点坐标集合
  66. self._center_diffusion_points = set() # 中心扩散效果点坐标集合
  67. self.all_points = {} # 每帧动态点坐标
  68. self.build(2000)
  69. self.random_halo = 1000
  70. self.generate_frame = generate_frame
  71. for frame in range(generate_frame):
  72. self.calc(frame)
  73. def build(self, number):
  74. # 爱心
  75. for _ in range(number):
  76. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  77. x, y = heart_function(t)
  78. self._points.add((x, y))
  79. # 爱心内扩散
  80. for _x, _y in list(self._points):
  81. for _ in range(3):
  82. x, y = scatter_inside(_x, _y, 0.05)
  83. self._edge_diffusion_points.add((x, y))
  84. # 爱心内再次扩散
  85. point_list = list(self._points)
  86. for _ in range(4000):
  87. x, y = random.choice(point_list)
  88. x, y = scatter_inside(x, y, 0.17)
  89. self._center_diffusion_points.add((x, y))
  90. @staticmethod
  91. def calc_position(x, y, ratio):
  92. # 调整缩放比例
  93. force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520)
  94. dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
  95. dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)
  96. return x - dx, y - dy
  97. def calc(self, generate_frame):
  98. ratio = 10 * curve(generate_frame / 10 * pi) # 圆滑的周期的缩放比例
  99. halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
  100. halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
  101. all_points = []
  102. # 光环
  103. heart_halo_point = set() # 光环的点坐标集合
  104. for _ in range(halo_number):
  105. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  106. x, y = heart_function(t, shrink_ratio=11)
  107. x, y = shrink(x, y, halo_radius)
  108. if (x, y) not in heart_halo_point:
  109. # 处理新的点
  110. heart_halo_point.add((x, y))
  111. x += random.randint(-11, 11)
  112. y += random.randint(-11, 11)
  113. size = random.choice((1, 2, 2))#控制外围粒子的大小
  114. all_points.append((x, y, size))
  115. # 轮廓
  116. for x, y in self._points:
  117. x, y = self.calc_position(x, y, ratio)
  118. size = random.randint(1, 3)
  119. all_points.append((x, y, size))
  120. # 内容
  121. for x, y in self._center_diffusion_points:
  122. x, y = self.calc_position(x, y, ratio)
  123. size = random.randint(1, 2)
  124. all_points.append((x, y, size))
  125. self.all_points[generate_frame] = all_points
  126. def render(self, render_canvas, render_frame):
  127. for x, y, size in self.all_points[render_frame % self.generate_frame]:
  128. render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=HEART_COLOR)
  129. def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
  130. render_canvas.delete('all')
  131. render_heart.render(render_canvas, render_frame)
  132. main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)
  133. if __name__ == '__main__':
  134. root = Tk() # 一个Tk
  135. canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
  136. canvas.pack()
  137. heart = Heart() # 心
  138. draw(root, canvas, heart) # 开始画画~
  139. root.mainloop()

 (8)、最先复现“李峋爱心”代码的作者

电视剧 【点燃我,温暖你】让“李峋爱心”红起来,网上有很多转载的,原来的作者是谁,我一直找不到,刚刚才发现作者Littlesbai,“李峋爱心代码”发布博客时间是 2022.11.08,而且文中有对代码优化的部分,应该是最先复现“李峋爱心”代码的作者。原创不易,请大家多支持原创作者。

转载地址:李峋爱心代码_Littlesbai的博客-CSDN博客

  1. import random
  2. from math import sin, cos, pi, log
  3. from tkinter import *
  4. CANVAS_WIDTH = 640
  5. CANVAS_HEIGHT = 480
  6. CANVAS_CENTER_X = CANVAS_WIDTH / 2
  7. CANVAS_CENTER_Y = CANVAS_HEIGHT / 2
  8. IMAGE_ENLARGE = 11
  9. HEART_COLOR = "#FF99CC"
  10. def center_window(root, width, height):
  11. screenwidth = root.winfo_screenwidth() # 获取显示屏宽度
  12. screenheight = root.winfo_screenheight() # 获取显示屏高度
  13. size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) /
  14. 2, (screenheight - height) / 2) # 设置窗口居中参数
  15. root.geometry(size) # 让窗口居中显示
  16. def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
  17. x = 16 * (sin(t) ** 3)
  18. y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
  19. # 放大
  20. x *= shrink_ratio
  21. y *= shrink_ratio
  22. # 移到画布中央
  23. x += CANVAS_CENTER_X
  24. y += CANVAS_CENTER_Y
  25. return int(x), int(y)
  26. def scatter_inside(x, y, beta=0.15):
  27. ratio_x = - beta * log(random.random())
  28. ratio_y = - beta * log(random.random())
  29. dx = ratio_x * (x - CANVAS_CENTER_X)
  30. dy = ratio_y * (y - CANVAS_CENTER_Y)
  31. return x - dx, y - dy
  32. def shrink(x, y, ratio):
  33. force = -1 / (((x - CANVAS_CENTER_X) ** 2 +
  34. (y - CANVAS_CENTER_Y) ** 2) ** 0.6)
  35. dx = ratio * force * (x - CANVAS_CENTER_X)
  36. dy = ratio * force * (y - CANVAS_CENTER_Y)
  37. return x - dx, y - dy
  38. def curve(p):
  39. return 2 * (2 * sin(4 * p)) / (2 * pi)
  40. class Heart:
  41. def __init__(self, generate_frame=20):
  42. self._points = set() # 原始爱心坐标集合
  43. self._edge_diffusion_points = set() # 边缘扩散效果点坐标集合
  44. self._center_diffusion_points = set() # 中心扩散效果点坐标集合
  45. self.all_points = {} # 每帧动态点坐标
  46. self.build(2000)
  47. self.random_halo = 1000
  48. self.generate_frame = generate_frame
  49. for frame in range(generate_frame):
  50. self.calc(frame)
  51. def build(self, number):
  52. for _ in range(number):
  53. t = random.uniform(0, 2 * pi)
  54. x, y = heart_function(t)
  55. self._points.add((x, y))
  56. # 爱心内扩散
  57. for _x, _y in list(self._points):
  58. for _ in range(3):
  59. x, y = scatter_inside(_x, _y, 0.05)
  60. self._edge_diffusion_points.add((x, y))
  61. # 爱心内再次扩散
  62. point_list = list(self._points)
  63. for _ in range(4000):
  64. x, y = random.choice(point_list)
  65. x, y = scatter_inside(x, y, 0.17)
  66. self._center_diffusion_points.add((x, y))
  67. @staticmethod
  68. def calc_position(x, y, ratio):
  69. force = 1 / (((x - CANVAS_CENTER_X) ** 2 +
  70. (y - CANVAS_CENTER_Y) ** 2) ** 0.520)
  71. dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
  72. dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)
  73. return x - dx, y - dy
  74. def calc(self, generate_frame):
  75. ratio = 10 * curve(generate_frame / 10 * pi)
  76. halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
  77. halo_number = int(
  78. 3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
  79. all_points = []
  80. # 光环
  81. heart_halo_point = set()
  82. for _ in range(halo_number):
  83. t = random.uniform(0, 2 * pi)
  84. x, y = heart_function(t, shrink_ratio=11.6)
  85. x, y = shrink(x, y, halo_radius)
  86. if (x, y) not in heart_halo_point:
  87. heart_halo_point.add((x, y))
  88. x += random.randint(-14, 14)
  89. y += random.randint(-14, 14)
  90. size = random.choice((1, 2, 2))
  91. all_points.append((x, y, size))
  92. # 轮廓
  93. for x, y in self._points:
  94. x, y = self.calc_position(x, y, ratio)
  95. size = random.randint(1, 3)
  96. all_points.append((x, y, size))
  97. # 内容
  98. for x, y in self._edge_diffusion_points:
  99. x, y = self.calc_position(x, y, ratio)
  100. size = random.randint(1, 2)
  101. all_points.append((x, y, size))
  102. self.all_points[generate_frame] = all_points
  103. for x, y in self._center_diffusion_points:
  104. x, y = self.calc_position(x, y, ratio)
  105. size = random.randint(1, 2)
  106. all_points.append((x, y, size))
  107. self.all_points[generate_frame] = all_points
  108. def render(self, render_canvas, render_frame):
  109. for x, y, size in self.all_points[render_frame % self.generate_frame]:
  110. render_canvas.create_rectangle(
  111. x, y, x + size, y + size, width=0, fill=HEART_COLOR)
  112. def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
  113. render_canvas.delete('all')
  114. render_heart.render(render_canvas, render_frame)
  115. main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)
  116. if __name__ == '__main__':
  117. root = Tk()
  118. root.title("爱心")
  119. center_window(root, CANVAS_WIDTH, CANVAS_HEIGHT) # 窗口居中显示
  120. canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
  121. canvas.pack()
  122. heart = Heart()
  123. draw(root, canvas, heart)
  124. Label(root, text="你想要替换的文字", bg="black", fg="#FF99CC", font="Helvetic 20 bold").place(
  125. relx=.5, rely=.5, anchor=CENTER)
  126. root.mainloop()

 (9)、跳动爱心

此代码需要用到import pgzrun,安装方式不是pgzrun,而是pgzero,请留意
pip install pgzero

以下文字转自作者:
https://blog.csdn.net/qq_40523737/article/details/127967411
1、用pgzero 库。然后结合最后那个极坐标爱心曲线代码,先绘制出曲线上离散的点。
2. 把点的数量增加,同时沿着原点到每个点的径向加一个随机数,并且这个随机数是按照正态分布来的(半个正态分布),大概率分布在曲线上,向曲线内部递减。这样,就得到这样一个随机分布的爱心效果。
3. 下面就是让点动起来,将每个点自定义成了一个Particle类的实例。从原理上来说,就是给每个点加一个缩放系数,这个系数是根据时间变化的正弦函数,看起来就会像呼吸的节律一样。
4. 剧中爱心跳动时,靠中间的点波动的幅度更大,有一种扩张的效果。所以再根据每个点距离原点的远近,再加上一个系数,离得越近,系数越大。
5. 最后再用同样的方法画一个更大一点的爱心,这个爱心不需要跳动,只要每一帧随机绘制就可以了。
合在一起,搞定!
总结一下,就是在原本的基础爱心曲线上加上一个正态分布的随机量、一个随时间变化的正弦函数和一个跟距离成反比的系数,外面再套一层更大的随机爱心,就得到类似剧中的跳动爱心效果。

电视剧里的代码真能运行吗?_Crossin的编程教室的博客-CSDN博客

  1. # 代码使用到 pygame-zero 框架,看起来与一般代码稍有不同,会有很多未定义的方法和变量,
  2. # 在一些编辑器里会报错,但其实是可以运行的,无需手动增加 import。
  3. # pgzero有两种方式运行(https://pygame-zero.readthedocs.io/zh_CN/latest/ide-mode.html)
  4. # 本代码用的是第二种直接运行的方式(需新版pgzero)。
  5. # 有部分读者反馈此代码在spyder上无法运行,类似情况可以尝试第一种传统方法:
  6. # 把最后的pgzrun.go()去掉,然后直接在命令行该目录下运行: pgzrun sheep.py
  7. import pgzrun
  8. from math import pi, sin, cos
  9. import random
  10. # 粒子类,图像上每一个小点都是一个粒子对象
  11. class Particle():
  12. def __init__(self, pos, size, f):
  13. self.pos = pos # 粒子当前位置(后面会变动)
  14. self.pos0 = pos # 粒子的原始位置
  15. self.size = size # 粒子大小
  16. self.f = f # 粒子的随机位移比例
  17. def draw(self):
  18. global L
  19. # 用矩形绘制粒子
  20. screen.draw.filled_rect(Rect((L*self.f*self.pos[0] + 400, -L*self.f*self.pos[1] + 300), self.size), 'hot pink')
  21. def update(self, t):
  22. # 根据程序运行时间计算一个正弦函数作为位移量
  23. # 如果要调整爱心跳动的频率、幅度等效果,可修改这里面的数字
  24. df = 1 + (4 - 3 * self.f) * sin(t * 3) / 12
  25. self.pos = self.pos0[0] * df, self.pos0[1] * df
  26. tt = [105, 102, 98, 115, 117, 33, 112, 103, 33, 106, 108, 118, 111, 33, 46, 33, 68, 115, 112, 116, 116, 106, 111, 30341, 32535, 31244, 25946, 23461]
  27. no_p = 20000
  28. dt = 2*pi/no_p
  29. particles = []
  30. t = 0
  31. c = 0
  32. # 采用极坐标下的爱心曲线,计算出爱心图案上的基准点,创建粒子对象
  33. # 每个点会有一个延轴向的随机位移,随机采用正态分布
  34. while t < 2*pi:
  35. c += 1
  36. sigma = 0.15 if c % 5 else 0.3
  37. f = 1 - abs(random.gauss(1, sigma) - 1)
  38. x = 16*sin(t)**3
  39. y = 13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
  40. size = (random.uniform(0.5,2.5), random.uniform(0.5,2.5))
  41. particles.append(Particle((x, y), size, f))
  42. t += dt
  43. def draw():
  44. screen.clear()
  45. # 绘制爱心粒子
  46. for p in particles:
  47. p.draw()
  48. if L == 10:
  49. # 采用同样原理,绘制外层大爱心,但生成粒子,只是每帧随机绘制
  50. t = 0
  51. while t < 2*pi:
  52. f = random.gauss(1.1, 0.1)
  53. x = 16*sin(t)**3
  54. y = 13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
  55. size = (random.uniform(0.5,2.5), random.uniform(0.5,2.5))
  56. screen.draw.filled_rect(Rect((10*f*x + 400, -10*f*y + 300), size), 'hot pink')
  57. t += dt * 3
  58. screen.draw.filled_rect(Rect((-10*11 + 400, 11*20 + 200), (2, 2)), 'hot pink')
  59. TITLE = ''.join([chr(i-1) for i in tt])
  60. status = 0
  61. L = 100
  62. elapsed = 0
  63. def update(dt):
  64. global elapsed, L, status
  65. elapsed += dt
  66. if status == 0:
  67. # 为了初始的集聚效果,加了一个很大的倍数L,并不断缩小至正常值
  68. L -= dt * 200
  69. if L <= 10:
  70. status = 1
  71. L = 10
  72. elif status == 2:
  73. L += dt * 200
  74. # 根据时间更新粒子位置
  75. for p in particles:
  76. p.update(elapsed)
  77. TITLE = 'heart of ikun - Crossin的编程教室'
  78. pgzrun.go()

 (10)、空心爱心

此代码需要用到import pgzrun,安装方式不是pgzrun,而是pgzero,请留意
pip install pgzero

基于极坐标的爱心曲线,是遍历角度来计算点的位置

电视剧里的代码真能运行吗?_Crossin的编程教室的博客-CSDN博客

  1. import pgzrun
  2. from math import pi, sin, cos
  3. no_p = 100
  4. dt = 2*3/no_p
  5. t = 0
  6. x = []
  7. y = []
  8. while t <= 2*3:
  9. x.append(16*sin(t)**3)
  10. y.append(13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t))
  11. t += dt
  12. def draw():
  13. screen.clear()
  14. for i in range(len(x)):
  15. screen.draw.filled_rect(Rect((x[i]*10+400, -y[i]*10+300), (4, 4)), 'pink')
  16. pgzrun.go()

11、空心立体爱心

  1. import turtle as t
  2. t.penup()
  3. t.seth(-90)
  4. t.fd(160)
  5. t.pendown()
  6. t.pensize(20)
  7. t.colormode(255)
  8. for j in range(10):
  9. t.speed(0)
  10. t.pencolor(20*j,2*j,20*j)
  11. t.seth(130)
  12. t.fd(215)
  13. for i in range(23):
  14. t.circle(-80,10)
  15. t.seth(100)
  16. for i in range(23):
  17. t.circle(-80,10)
  18. t.fd(215)
  19. t.hideturtle()
  20. t.done()

 12、李峋同款爱心代码【有声版】
李峋同款爱心代码【有声版】_李峋爱心代码_cs阿坤dn的博客-CSDN博客
建立mp3目录,下载
https://img-qn.51miz.com/preview/sound/00/28/31/51miz-S283175-043A2FE9.mp3
保存到mp3目录
安装相应的模块包
运行代码,有心跳声音
  1. import random # 随机函数模块
  2. import pyttsx3 # 文字转语音模块
  3. from pygame import mixer # mp3播放模块
  4. from math import sin, cos, pi, log # 核心模块,数学函数
  5. from tkinter import * # 窗口主体模块
  6. CANVAS_WIDTH = 1920 # 画布的宽
  7. CANVAS_HEIGHT = 1080 # 画布的高
  8. CANVAS_CENTER_X = CANVAS_WIDTH / 2 # 画布中心的X轴坐标
  9. CANVAS_CENTER_Y = CANVAS_HEIGHT / 2 # 画布中心的Y轴坐标
  10. IMAGE_ENLARGE = 15 # 放大比例
  11. HEART_COLOR = "#Fd789f" # 心的颜色,少女粉
  12. def speak_voice(message, speak_mode=0):
  13. """
  14. “文字转语音”
  15. :param message: 文本消息
  16. :param speak_mode: 语音包,0 中文女声,1 英文女声,2 英文男声
  17. """
  18. # 初始化
  19. engine = pyttsx3.init()
  20. voices = engine.getProperty('voices')
  21. # 改变语速 范围为0-200 默认值为200
  22. rate = engine.getProperty('rate')
  23. engine.setProperty('rate', rate - 100)
  24. # 设置音量 范围为0.0-1.0 默认值为1.0
  25. engine.setProperty('volume', 0.8)
  26. # 设置发音人,目前只有0可以说中文
  27. engine.setProperty('voice', voices[speak_mode].id)
  28. # 预设要朗读的文本数据
  29. engine.say(message)
  30. # 读出声音
  31. engine.runAndWait()
  32. def heart_voice(file_path, playback_mode=-1):
  33. """
  34. “噗噗的心跳声”
  35. :param file_path: mp3文件路径
  36. :param playback_mode: 播放模式,-1 为循环播放
  37. """
  38. # 初始化
  39. mixer.init()
  40. # 加载文件路径
  41. mixer.music.load(file_path)
  42. # 播放mp3文件
  43. mixer.music.play(playback_mode)
  44. def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
  45. """
  46. “爱心函数生成器”
  47. :param shrink_ratio: 放大比例
  48. :param t: 参数
  49. :return: 坐标
  50. """
  51. # 基础函数
  52. x = 16 * (sin(t) ** 3)
  53. y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
  54. # 放大
  55. x *= shrink_ratio
  56. y *= shrink_ratio
  57. # 移到画布中央
  58. x += CANVAS_CENTER_X
  59. y += CANVAS_CENTER_Y
  60. return int(x), int(y)
  61. def scatter_inside(x, y, beta=0.15):
  62. """
  63. 随机内部扩散
  64. :param x: 原x
  65. :param y: 原y
  66. :param beta: 强度
  67. :return: 新坐标
  68. """
  69. ratio_x = - beta * log(random.random())
  70. ratio_y = - beta * log(random.random())
  71. dx = ratio_x * (x - CANVAS_CENTER_X)
  72. dy = ratio_y * (y - CANVAS_CENTER_Y)
  73. return x - dx, y - dy
  74. def shrink(x, y, ratio):
  75. """
  76. 抖动
  77. :param x: 原x
  78. :param y: 原y
  79. :param ratio: 比例
  80. :return: 新坐标
  81. """
  82. force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6) # 这个参数...
  83. dx = ratio * force * (x - CANVAS_CENTER_X)
  84. dy = ratio * force * (y - CANVAS_CENTER_Y)
  85. return x - dx, y - dy
  86. def curve(p):
  87. """
  88. 自定义曲线函数,调整跳动周期
  89. :param p: 参数
  90. :return: 正弦
  91. """
  92. # 可以尝试换其他的动态函数,达到更有力量的效果(贝塞尔?)
  93. return 2 * (2 * sin(4 * p)) / (2 * pi)
  94. class Heart:
  95. """
  96. 爱心类
  97. """
  98. def __init__(self, generate_frame=20):
  99. self._points = set() # 原始爱心坐标集合
  100. self._edge_diffusion_points = set() # 边缘扩散效果点坐标集合
  101. self._center_diffusion_points = set() # 中心扩散效果点坐标集合
  102. self.all_points = {} # 每帧动态点坐标
  103. self.build(2000)
  104. self.random_halo = 1000
  105. self.generate_frame = generate_frame
  106. for frame in range(generate_frame):
  107. self.calc(frame)
  108. def build(self, number):
  109. # 爱心
  110. for _ in range(number):
  111. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  112. x, y = heart_function(t)
  113. self._points.add((x, y))
  114. # 爱心内扩散
  115. for _x, _y in list(self._points):
  116. for _ in range(3):
  117. x, y = scatter_inside(_x, _y, 0.05)
  118. self._edge_diffusion_points.add((x, y))
  119. # 爱心内再次扩散
  120. point_list = list(self._points)
  121. for _ in range(4000):
  122. x, y = random.choice(point_list)
  123. x, y = scatter_inside(x, y, 0.17)
  124. self._center_diffusion_points.add((x, y))
  125. @staticmethod
  126. def calc_position(x, y, ratio):
  127. # 调整缩放比例
  128. force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520) # 魔法参数
  129. dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
  130. dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)
  131. return x - dx, y - dy
  132. def calc(self, generate_frame):
  133. ratio = 10 * curve(generate_frame / 10 * pi) # 圆滑的周期的缩放比例
  134. halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
  135. halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
  136. all_points = []
  137. # 光环
  138. heart_halo_point = set() # 光环的点坐标集合
  139. for _ in range(halo_number):
  140. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  141. x, y = heart_function(t, shrink_ratio=11.6) # 魔法参数
  142. x, y = shrink(x, y, halo_radius)
  143. if (x, y) not in heart_halo_point:
  144. # 处理新的点
  145. heart_halo_point.add((x, y))
  146. x += random.randint(-14, 14)
  147. y += random.randint(-14, 14)
  148. size = random.choice((1, 2, 2))
  149. all_points.append((x, y, size))
  150. # 轮廓
  151. for x, y in self._points:
  152. x, y = self.calc_position(x, y, ratio)
  153. size = random.randint(1, 3)
  154. all_points.append((x, y, size))
  155. # 内容
  156. for x, y in self._edge_diffusion_points:
  157. x, y = self.calc_position(x, y, ratio)
  158. size = random.randint(1, 2)
  159. all_points.append((x, y, size))
  160. for x, y in self._center_diffusion_points:
  161. x, y = self.calc_position(x, y, ratio)
  162. size = random.randint(1, 2)
  163. all_points.append((x, y, size))
  164. self.all_points[generate_frame] = all_points
  165. def render(self, render_canvas, render_frame):
  166. for x, y, size in self.all_points[render_frame % self.generate_frame]:
  167. render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=HEART_COLOR)
  168. def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
  169. render_canvas.delete('all')
  170. render_heart.render(render_canvas, render_frame)
  171. main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)
  172. if __name__ == '__main__':
  173. root = Tk() # 一个Tk
  174. root.title("李峋同款代码【有声版】") #标题
  175. canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
  176. canvas.pack()
  177. heart = Heart() # 心
  178. draw(root, canvas, heart) # 开始画画
  179. speak_voice("请收下我的心!") # 要对她说的话
  180. heart_voice("mp3/51miz-S283175-043A2FE9.mp3") # 心跳声音
  181. root.mainloop()

 三、python字符画爱心 

此部分的代码会显示在终端,如果你没有打开终端会看不到效果。如果你没有专业的代码编辑器,只想试试效果,运行方式:

1、安装python配置好环境

2、将代码完整复制,保存成:你的文件名.py

3、同时按window+R键,输入cmd,打开命令提示符窗口

输入:python 你的文件名.py

 (1)、一行代码画爱心

print('\n'.join([''.join([('Love'[(x-y)%len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ') for x in range(-30,30)]) for y in range(15,-15,-1)]))

a = [
        ''.join(
            [
                (
                    'Love'[(x-y)%len('Love')]
                    if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' '
                )
                for x in range(-30,30)
            ]
        )
        for y in range(15,-15,-1)
    ]

print('\n'.join(a))
 

 (2)、用字符输出 I 爱 U (2种形式)

  1. import time
  2. y = 2.5
  3. while y>=-1.6:
  4. x = -3.0
  5. while x<=4.0:
  6. if (x*x+y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.2):
  7. print(' ',end="")
  8. else:
  9. print('*',end="")
  10. x += 0.1
  11. print()
  12. time.sleep(0.25)
  13. y -= 0.2

参考:https://blog.csdn.net/qq_55342245/article/details/120904578

  1. import time
  2. y = 2.5
  3. while y>=-1.6:
  4. x = -3.0
  5. while x<=4.0:
  6. if (x*x+y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.2):
  7. print('*',end="")
  8. else:
  9. print(' ',end="")
  10. x += 0.1
  11. print()
  12. time.sleep(0.25)
  13. y -= 0.2

 (3)、输出五个爱心,由Dear I love you forever! 五个单词填充而成

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

  1. import time
  2. sentence = "Dear, I love you forever!"
  3. for char in sentence.split():
  4. allChar = []
  5. for y in range(12, -12, -1):
  6. lst = []
  7. lst_con = ''
  8. for x in range(-30, 30):
  9. formula = ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3
  10. if formula <= 0:
  11. lst_con += char[(x) % len(char)]
  12. else:
  13. lst_con += ' '
  14. lst.append(lst_con)
  15. allChar += lst
  16. print('\n'.join(allChar))
  17. time.sleep(1)

 (4)、字符输出爱心曲线公式爱心1

用是这个爱心曲线公式,然后遍历一个15*17的方阵,计算每个坐标是在曲线内还是曲线外,在内部就输出#或*,外部就是-

电视剧里的代码真能运行吗?_Crossin的编程教室的博客-CSDN博客
for y in range(9, -6, -1):
    for x in range(-8, 9):
        print('*##*'[(x+10)%4] if (x*x+y*y-25)**3 < 25*x*x*y*y*y else '_', end=' ')
    print()

(5)、字符输出爱心曲线公式爱心2

用是这个爱心曲线公式,然后遍历一个15*17的方阵,计算每个坐标是在曲线内还是曲线外

电视剧里的代码真能运行吗?_Crossin的编程教室的博客-CSDN博客
for y in range(9, -6, -1):
    for x in range(-8, 9):
        print('❤' if (x*x+y*y-25)**3 < 25*x*x*y*y*y else ' ', end=' ')
    print()

持续更新中。。。

           推荐阅读:

29

SVG实例详解系列(一)(svg概述、位图和矢量图区别(图解)、SVG应用实例)

28

查看jdk安装路径,在windows上实现多个java jdk的共存解决办法,安装java19后终端乱码的解决

27bba02a1c4617422c9fbccbf5325850d9.png

别具一格,原创唯美浪漫情人节表白专辑,(复制就可用)(html5,css3,svg)表白爱心代码(1)

26fea225cb9ec14b60b2d1b797dd8278a2.png

2023年春节祝福第二弹——送你一只守护兔,让它温暖每一个你【html5 css3】画会动的小兔子,炫酷充电,字体特

251f53fb9c6e8b4482813326affe6a82ff.png

2023春节祝福系列第一弹(上)(放飞祈福孔明灯,祝福大家身体健康)(附完整源代码及资源免费下载)

246176c4061c72430eb100750af6fc4d0e.png

HTML+CSS+svg绘制精美彩色闪灯圣诞树,HTML+CSS+Js实时新年时间倒数倒计时(附源代码)

2317b403c4307c4141b8544d02f95ea06c.png

​草莓熊python绘图(春节版,圣诞倒数雪花版)附源代码

225d409c8f397a45c986ca2af7b7e725c9.png

【程序人生】卡塔尔世界杯元素python海龟绘图(附源代码),世界杯主题前端特效5个(附源码)

210a4256d5e96d4624bdca36433237080b.png

python爱心源代码集锦(18款)

204d9032c9cdf54f5f9193e45e4532898c.png

巴斯光年python turtle绘图__附源代码

19074cd3c255224c5aa21ff18fdc25053c.png

Three.js实例详解___旋转的精灵女孩(附完整代码和资源)(一)

18daecd7067e7c45abb875fc7a1a469f23.png

​草莓熊python turtle绘图代码(玫瑰花版)附源代码

17fe88b78e78694570bf2d850ce83b1f69.png

立体多层玫瑰绘图源码__玫瑰花python 绘图源码集锦

16c5feeb25880d49c085b808bf4e041c86.png

皮卡丘python turtle海龟绘图(电力球版)附源代码

1538266b5036414624875447abd5311e4d.png

【CSDN云IDE】个人使用体验和建议(含超详细操作教程)(python、webGL方向)

1403ed644f9b1d411ba41c59e0a5bdcc61.png

草莓熊python turtle绘图(风车版)附源代码

1309e08f86f127431cbfdfe395aa2f8bc9.png

用代码过中秋,python海龟月饼你要不要尝一口?

1240e8b4631e2b486bab2a4ebb5bc9f410.png

《 Python List 列表全实例详解系列(一)》__系列总目录、列表概念

11938bc5a8bb454a41bfe0d4185da845dc.jpeg

用代码写出浪漫__合集(python、matplotlib、Matlab、java绘制爱心、玫瑰花、前端特效玫瑰、爱心)

100f09e73712d149ff90f0048a096596c6.png

Python函数方法实例详解全集(更新中...)

993d65dbd09604c4a8ed2c01df0eebc38.png

matplotlib 自带绘图样式效果展示速查(28种,全)

8aa17177aec9b4e5eb19b5d9675302de8.png

手机屏幕坏了____怎么把里面的资料导出(18种方法)

71750390dd9da4b39938a23ab447c6fb6.jpeg

2023年6月TIOBE 指数头条:编程语言 Go 进入 TIOBE 指数前 10 名,多家权威机构____编程语言排行榜__薪酬状

6dc8796ddccbf4aec98ac5d3e09001348.jpeg

Python中Print()函数的用法___实例详解(全,例多)

51ab685d264ed4ae5b510dc7fbd0d1e55.jpeg

色彩颜色对照表(一)(16进制、RGB、CMYK、HSV、中英文名)

480007dbf51944725bf9cf4cfc75c5a13.png

Node.js (v19.1.0npm 8.19.3) vue.js安装配置教程(超详细)

3c6374d75c29942f2aa577ce9c5c2e12b.png

Tomcat 启动闪退问题解决集(八大类详细)

25218ac5338014f389c21bdf1bfa1c599.png

Tomcat端口配置(详细)

1fffa2098008b4dc68c00a172f67c538d.png

tomcat11、tomcat10 安装配置(Windows环境)(详细图文)

文章知识点与官方知识档案匹配,可进一步学习相关知识
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号