设计理念
- 数学之美:使用心形线的数学方程(心形曲线)生成爱心形状。
- 视觉吸引力:通过 Python 的
colorama
库添加颜色渐变效果。 - 动态感:加入简单的动画,让爱心“跳动”。
- 技术魅力:结合模块化编程和注释,展示代码的优雅与逻辑。
完整代码
import math
import time
from colorama import init, Fore, Style
init()def heart_function(t):"""心形曲线的参数方程"""x = 16 * math.sin(t) ** 3y = 13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t)return x, ydef plot_heart(scale=1, color=Fore.RED):"""绘制心形图案"""points = set()for t in [i * 0.01 for i in range(0, 628)]: x, y = heart_function(t)x = int(x * scale) y = int(y * scale) points.add((x, y + 15)) grid = [[' ' for _ in range(40)] for _ in range(20)]for x, y in points:if 0 <= x < 40 and 0 <= y < 20: grid[y][x] = '*'for row in grid:print(color + ''.join(row) + Style.RESET_ALL)def animate_heart():"""动态展示心形图案"""colors = [Fore.RED, Fore.MAGENTA, Fore.YELLOW, Fore.GREEN, Fore.CYAN, Fore.BLUE]print("\033[2J") for i in range(6):scale = 1 + 0.1 * math.sin(i) color = colors[i % len(colors)] print(f"\033[{i % 2 + 1};1H") plot_heart(scale, color)time.sleep(0.3) if __name__ == "__main__":print("欢迎体验 Python 的技术浪漫!")try:animate_heart()except KeyboardInterrupt:print(Fore.RESET + "\n爱心已停止跳动,感谢体验!")
运行效果
- 形状:代码使用心形曲线的参数方程生成一个优雅的爱心图案,以
*
字符绘制。 - 颜色:爱心会在红、洋红、黄、绿、青、蓝之间循环渐变。
- 动画:通过缩放因子模拟心跳效果,爱心会微微放大和缩小。
- 交互性:按 Ctrl+C 可优雅退出,并显示结束语。
如何运行
- 安装依赖:在终端运行
pip install colorama
以支持颜色输出。 - 将代码保存为
.py
文件(如 heart.py
),然后运行 python heart.py
。 - 在终端观看动态彩色爱心效果!
创意亮点
- 数学与艺术的结合:心形曲线方程不仅美观,还展示了数学在编程中的应用。
- 动态交互:动画和颜色切换让静态图案变得生动,激发视觉兴趣。
- 技术优雅:模块化设计(分离函数)和异常处理体现 Python 的简洁与强大。
- 浪漫寓意:代码以“技术浪漫”为主题,适合分享或作为礼物送给程序员朋友。
扩展创意
- 添加文字:在爱心下方输出自定义信息,如“Love Python!”。
- 声音效果:结合
winsound
或 playsound
模块,加入心跳声。 - 3D 效果:使用
matplotlib
将爱心升级为三维旋转图形。