写一个地球月球和太阳相对运动的代码
时间: 2024-02-13 16:04:10 浏览: 25
以下是一个使用 Python 和 Pygame 库编写的简单代码,用于可视化地球、月球和太阳的相对运动:
```python
import pygame
import math
# 定义常量
AU = 149597870700 # 天文单位(米)
EARTH_RADIUS = 6371000 # 地球半径(米)
MOON_RADIUS = 1737100 # 月球半径(米)
SUN_RADIUS = 696340000 # 太阳半径(米)
# 初始化 Pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption("Solar System")
# 加载图片
earth_img = pygame.image.load("earth.png")
moon_img = pygame.image.load("moon.png")
sun_img = pygame.image.load("sun.png")
# 时间参数
d = 1 # 天数
t = 0 # 时间(秒)
dt = 60 # 时间步长(秒)
# 初始位置
earth_x = 0
earth_y = 0
earth_z = 0
moon_x = AU
moon_y = 0
moon_z = 0
sun_x = 0
sun_y = 0
sun_z = 0
# 循环事件
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 计算位置
earth_theta = t * math.pi / 43200 # 地球公转角度(弧度)
earth_x = AU * math.cos(earth_theta)
earth_y = AU * math.sin(earth_theta)
moon_theta = t * math.pi / 21600 # 月球公转角度(弧度)
moon_x = earth_x + 384400000 * math.cos(moon_theta)
moon_y = earth_y + 384400000 * math.sin(moon_theta)
sun_theta = t * math.pi / 43200 # 太阳公转角度(弧度)
sun_x = AU * math.cos(sun_theta)
sun_y = AU * math.sin(sun_theta)
# 渲染画面
screen.fill((0, 0, 0))
screen.blit(sun_img, (400 - SUN_RADIUS * 1e-6, 400 - SUN_RADIUS * 1e-6))
screen.blit(earth_img, (400 + earth_x * 1e-6 - EARTH_RADIUS * 1e-6, 400 + earth_y * 1e-6 - EARTH_RADIUS * 1e-6))
screen.blit(moon_img, (400 + moon_x * 1e-6 - MOON_RADIUS * 1e-6, 400 + moon_y * 1e-6 - MOON_RADIUS * 1e-6))
pygame.display.update()
# 更新时间
t += dt
# 退出 Pygame
pygame.quit()
```
这个代码使用了 Pygame 库来渲染图像,需要在同级目录下放置名为 "earth.png"、"moon.png" 和 "sun.png" 的图片。代码计算了地球、月球和太阳的位置,并且每隔一定时间更新一次图像。你可以根据自己的需求调整时间步长和图像大小。