用Python编程,编写爱心代码 - 分享

#创意Python爱心代码分享#

Python爱心代码实现(基础图形版)

import turtle 
 
# 初始化画布和画笔 
heart = turtle.Turtle()
heart.speed(5)   # 中速绘制 
heart.color('red',  'pink')  # 边框红色,填充粉色 
heart.begin_fill()   # 开始填充 
 
# 绘制爱心轮廓 
heart.left(140) 
heart.forward(113) 
for i in range(200):  # 绘制右侧曲线 
    heart.right(1) 
    heart.forward(1) 
heart.left(120) 
for i in range(200):  # 绘制左侧曲线 
    heart.right(1) 
    heart.forward(1) 
heart.forward(113) 
 
heart.end_fill()   # 结束填充 
turtle.done()   # 保持窗口显示 

动态爱心升级版

import turtle 
import math 
 
def draw_heart(size):
    t.penup() 
    t.goto(0,  -size*1.1)
    t.pendown() 
    
    angle = 0 
    t.begin_fill() 
    while angle <= 2 * math.pi: 
        x = 16 * (math.sin(angle)  ** 3)
        y = 13 * math.cos(angle)  - 5 * math.cos(2*angle)  - 2 * math.cos(3*angle)  - math.cos(4*angle) 
        t.goto(x  * size, y * size)
        angle += 0.1 
    t.end_fill() 
 
t = turtle.Turtle()
t.speed(0) 
t.color('red',  'pink')
 
# 实现心跳效果 
for i in range(30):
    t.clear() 
    size = 10 + 2 * math.sin(i/2)   # 动态调整大小 
    draw_heart(size)
    turtle.update() 
    turtle.delay(50) 
 
turtle.mainloop() 

控制台字符爱心版

heart = '''
    ❤️ ❤️ ❤️ 
  ❤️     ❤️ 
❤️         ❤️ 
  ❤️     ❤️ 
    ❤️ ❤️ 
      ❤️ 
'''
 
for line in heart.split('\n'): 
    print(line.center(50)) 

3D旋转爱心(需要matplotlib)

import numpy as np 
import matplotlib.pyplot  as plt 
from mpl_toolkits.mplot3d  import Axes3D 
 
theta = np.linspace(0,  2*np.pi,  100)
x = 16 * np.sin(theta)**3  
y = 13 * np.cos(theta)  - 5 * np.cos(2*theta)  - 2 * np.cos(3*theta)  - np.cos(4*theta) 
 
fig = plt.figure(figsize=(8,6)) 
ax = fig.add_subplot(111,  projection='3d')
 
for angle in range(0, 360, 5):
    ax.cla() 
    z = np.linspace(0,  1, len(x))
    ax.plot(x,  y, z, color='red', linewidth=4)
    ax.plot(x,  y, -z, color='red', linewidth=4)
    ax.view_init(30,  angle)
    plt.draw() 
    plt.pause(0.05) 
 
plt.show() 

注意:3D版本需要安装matplotlib库(`pip install matplotlib`)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ProgramHan

你的鼓励是我最大的动力!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值