Python创意爱心代码分享指南
以下是一些有创意的Python爱心代码示例,可以在终端或图形界面显示爱心图案:
1. 终端字符爱心
python
import time
def heart():
for row in range(6):
for col in range(7):
if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2) or (row + col == 8):
print("❤", end="")
else:
print(" ", end="")
print()
heart()
2. 动态跳动爱心(使用turtle模块)
python
import turtle
import math
t = turtle.Turtle()
t.speed(0)
t.color('red', 'pink')
t.pensize(3)
def draw_heart():
t.begin_fill()
for i in range(200):
t.right(1)
t.forward(2 * math.sin(i * math.pi / 100))
t.left(120)
for i in range(200):
t.right(1)
t.forward(2 * math.sin(i * math.pi / 100))
t.end_fill()
for i in range(3):
draw_heart()
t.penup()
t.goto(0, -i*20)
t.pendown()
t.clear()
turtle.done()
3. 数学函数绘制的爱心(使用matplotlib)
python
import numpy as np
import matplotlib.pyplot as plt
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)
plt.figure(figsize=(8, 6))
plt.plot(x, y, color='red', linewidth=2)
plt.fill(x, y, color='pink')
plt.axis('equal')
plt.axis('off')
plt.title('数学爱心函数', fontsize=14)
plt.show()
4. 彩色闪烁爱心(使用pygame)
python
import pygame
import sys
import random
import math
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("跳动的心")
def draw_heart(surface, color, pos, size):
x, y = pos
points = []
for i in range(100):
t = i * 2 * math.pi / 100
px = size * 16 * math.sin(t) ** 3
py = -size * (13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
points.append((x + px, y + py))
pygame.draw.polygon(surface, color, points)
clock = pygame.time.Clock()
size = 1
growing = True
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((0, 0, 0))
if growing:
size += 0.02
if size > 1.5:
growing = False
else:
size -= 0.02
if size < 1:
growing = True
color = (random.randint(200, 255), random.randint(0, 100), random.randint(100, 200))
draw_heart(screen, color, (width//2, height//2), size)
pygame.display.flip()
clock.tick(60)
5. ASCII艺术爱心(简单版)
python
print('''
@@@@ @@@@
@@@@@@ @@@@@@
@@@@@@@@ @@@@@@@@
@@@@@@@@@ @@@@@@@@@
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@
@@@@@@@@@@@@@
@@@@@@@@@@@
@@@@@@@@@
@@@@@@@
@@@@@
@@@
@
''')
你可以根据自己的喜好选择或修改这些代码。要运行图形化的示例,需要先安装相应的库(如turtle, matplotlib, pygame)。