Python绘制爱心代码,书写爱情故事

简介: 在本篇博客中,将为大家介绍3种绘画爱心的python代码。通过这个有趣的项目,不仅可以提升编程技能,还能为程序世界增添一份浪漫和温暖。

1.文本绘制

def draw_heart(color):
    for y in range(15, -15, -1):
        for x in range(-30, 30):
            if ((x * 0.04)**2 + (y * 0.1)**2 - 1)**3 - (x * 0.04)**2 * (y * 0.1)**3 <= 0:
                print("\033[{}m*\033[0m".format(color), end="")
            else:
                print(" ", end="")
        print()
# 使用ANSI转义码设置颜色
draw_heart(31)

在这个例子中,使用ANSI转义码 \033[31m 来设置文本的颜色为红色。可以通过修改 31 来改变颜色。以下是一些常见的ANSI颜色代码:

  • 30:黑色
  • 31:红色
  • 32:绿色
  • 33:黄色
  • 34:蓝色
  • 35:洋红色
  • 36:青色
  • 37:白色

    2.turtle库绘制

    import turtle
    # 初始化画布
    screen = turtle.Screen()
    screen.bgcolor('black')
    # 初始化画笔
    pen = turtle.Turtle()
    pen.speed(2)
    pen.color('red')
    pen.penup()
    # 绘制爱心
    pen.goto(0, -100)
    pen.pendown()
    pen.begin_fill()
    pen.left(140)
    pen.forward(224)
    for i in range(200):
        pen.right(1)
        pen.forward(2)
    pen.left(120)
    for i in range(200):
        pen.right(1)
        pen.forward(2)
    pen.forward(224)
    pen.end_fill()
    # 结束绘制
    pen.hideturtle()
    screen.mainloop()

    这段代码使用turtle库绘制了一个红色的爱心形状,可以将其保存为.py文件,运行后即可看到绘制出的爱心图案

    3.Mathlotlib绘制

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib
    matplotlib.use('TkAgg')
    # 创建画布
    fig, ax = plt.subplots(figsize=(6, 6))
    ax.set_aspect('equal')
    # 绘制爱心曲线
    t = np.linspace(0, 2 * np.pi, 1000)
    x = 16 * np.sin(t) ** 3
    y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
    ax.plot(x, y, color='red', linewidth=2)
    # 添加装饰
    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20)
    ax.axis('off')
    # 显示图像
    plt.show()

    通过运行以上代码,你将得到一个精美的爱心图案。你可以根据需要调整画布大小、线条颜色和粗细等参数,让爱心图案展现出你独特的风格