|
import pygame
import sys
import math
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("爱心曲线")
BACKGROUND = (10, 10, 30) # 深蓝色背景
HEART_COLOR = (255, 0, 85) # 鲜艳的粉红色
TEXT_COLOR = (200, 200, 255) # 淡蓝色文字
font = pygame.font.SysFont('kaiti', 36)
font1 = pygame.font.SysFont(None, 36)
# 坐标转换函数:将数学坐标转换为屏幕坐标
def to_screen(x, y):
scale = 180 # 缩放比例
# 将坐标原点移到屏幕中心,并翻转y轴
return WIDTH // 2 + int(x * scale), HEIGHT // 2 - int(y * scale)
# 计算爱心方程
def heart_equation(x, y):
# 计算方程左边的值
return (x ** 2 + y ** 2 - 1) ** 3 - (x ** 2) * (y ** 3)
# 主函数
def main():
clock = pygame.time.Clock()
points = []
animation_phase = 0 # 动画相位
# 预计算点集
for x in [i * 0.005 for i in range(-300, 301)]:
for y in [i * 0.005 for i in range(-300, 301)]:
# 检查点是否满足方程(允许一定误差)
if abs(heart_equation(x, y)) < 0.005:
points.append((x, y))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# 填充背景
screen.fill(BACKGROUND)
# 绘制坐标轴
pygame.draw.line(screen, (50, 50, 80), (0, HEIGHT // 2), (WIDTH, HEIGHT // 2), 1)
pygame.draw.line(screen, (50, 50, 80), (WIDTH // 2, 0), (WIDTH // 2, HEIGHT), 1)
# 更新动画参数
animation_phase = (animation_phase + 0.02) % (2 * math.pi)
pulse_size = 1.0 + 0.1 * math.sin(animation_phase)
# 绘制所有点(带缩放动画)
for (x, y) in points:
sx, sy = to_screen(x * pulse_size, y * pulse_size)
pygame.draw.circle(screen, HEART_COLOR, (sx, sy), 15)
# 绘制标题和方程
title = font.render("爱心曲线", True, TEXT_COLOR)
equation = font1.render("(x² + y² - 1)³ - x²y³ = 0", True, TEXT_COLOR)
screen.blit(title, (WIDTH // 2 - title.get_width() // 2, 20))
screen.blit(equation, (WIDTH // 2 - equation.get_width() // 2, HEIGHT - 50))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main() |
|