```
import pygame
import math
import numpy as np
# 初始化Pygame
pygame.init()
# 设置屏幕参数
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("3D Dynamic Heart")
# 颜色定义
BLACK = (0, 0, 0)
def create_heart_points():
"""生成三维心形点云"""
points = []
for z in np.linspace(-2, 2, 25):
for theta in np.linspace(0, 2 * math.pi, 100): # 二维心形参数
# 经典心形方程
x = 16 * (math.sin(theta) ** 3)
y = 13 * math.cos(theta) - 5 * math.cos(2*theta) - 2 * math.cos(3*theta) - math.cos(4*theta)
# 三维扩展
scale = 1 / (1 + z**2) # z值影响缩放
x = x * scale * 0.05
y = y * scale * 0.05
z_pos = z * 0.3 # 调整z轴比例
points.append([x, y, z_pos])
return np.array(points)
# 创建心形点云
points = create_heart_points()
# 主循环参数
angle = 0
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(BLACK)
# 更新旋转角度
angle += 0.02
# 旋转矩阵(绕Y轴和Z轴旋转)
rot_y = np.array([
[math.cos(angle), 0, math.sin(angle)],
[0, 1, 0],
[-math.sin(angle), 0, math.cos(angle)]
])
rot_z = np.array([
[math.cos(angle), -math.sin(angle), 0],
[math.sin(angle), math.cos(angle), 0],
[0, 0, 1]
])
# 组合旋转矩阵
rotation_matrix = rot_y @ rot_z
# 应用旋转变换
rotated_points = np.dot(points, rotation_matrix.T)
# 透视投影参数
distance = 4
fov = 300 # 视场控制
# 计算投影坐标和深度
z_values = rotated_points[:, 2] + distance
x_proj = rotated_points[:, 0] * fov / z_values
y_proj = rotated_points[:, 1] * fov / z_values
# 转换到屏幕坐标
screen_coords = np.column_stack([
x_proj + WIDTH/2,
-y_proj + HEIGHT/2 # 反转Y轴方向
])
# 根据深度计算颜色
depths = (rotated_points[:, 2] + 2) / 4 # 归一化深度值
colors = np.clip(255 * depths, 50, 255).astype(int)
# 绘制所有点
for (x, y), color in zip(screen_coords, colors):
if 0 <= x < WIDTH and 0 <= y < HEIGHT:
pygame.draw.circle(screen, (color, 0, 0), (int(x), int(y)), 1)
pygame.display.flip()
clock.tick(30)
pygame.quit()```分析代码并改进