用python生成一个运行的太阳系
- User
用python生成一个运行的太阳系
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
用python生成一个运行的太阳系
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
下面是一个使用Python和Pygame库创建的简单太阳系模拟程序。这个程序会显示太阳和八大行星围绕太阳运行的动画。
import pygame
import math
import sys
# 初始化pygame
pygame.init()
# 设置窗口
WIDTH, HEIGHT = 1000, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("太阳系模拟")
# 颜色定义
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
BLUE = (100, 149, 237)
RED = (188, 39, 50)
DARK_GRAY = (80, 78, 81)
LIGHT_BLUE = (0, 191, 255)
GOLD = (255, 215, 0)
LIGHT_GRAY = (211, 211, 211)
DARK_BLUE = (0, 0, 139)
BROWN = (165, 42, 42)
# 天体类
class CelestialBody:
def __init__(self, name, radius, color, distance, speed):
self.name = name
self.radius = radius
self.color = color
self.distance = distance
self.angle = 0
self.speed = speed
self.x = 0
self.y = 0
def update(self):
self.angle += self.speed
self.x = WIDTH // 2 + math.cos(self.angle) * self.distance
self.y = HEIGHT // 2 + math.sin(self.angle) * self.distance
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
# 绘制轨道
pygame.draw.circle(screen, (100, 100, 100), (WIDTH//2, HEIGHT//2), self.distance, 1)
# 创建天体
sun = CelestialBody("太阳", 30, YELLOW, 0, 0)
mercury = CelestialBody("水星", 5, DARK_GRAY, 60, 0.02)
venus = CelestialBody("金星", 8, LIGHT_GRAY, 90, 0.015)
earth = CelestialBody("地球", 9, BLUE, 130, 0.01)
mars = CelestialBody("火星", 6, RED, 170, 0.008)
jupiter = CelestialBody("木星", 20, BROWN, 230, 0.004)
saturn = CelestialBody("土星", 17, GOLD, 290, 0.003)
uranus = CelestialBody("天王星", 14, LIGHT_BLUE, 350, 0.002)
neptune = CelestialBody("海王星", 14, DARK_BLUE, 410, 0.001)
# 天体列表
bodies = [sun, mercury, venus, earth, mars, jupiter, saturn, uranus, neptune]
# 字体
font = pygame.font.SysFont('Arial', 12)
# 主循环
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 填充背景
screen.fill(BLACK)
# 更新和绘制天体
for body in bodies:
body.update()
body.draw(screen)
# 显示天体名称
text = font.render(body.name, True, (255, 255, 255))
screen.blit(text, (body.x - text.get_width() // 2, body.y - body.radius - 20))
# 显示标题
title = pygame.font.SysFont('Arial', 24).render("太阳系模拟", True, (255, 255, 255))
screen.blit(title, (WIDTH//2 - title.get_width()//2, 20))
# 显示说明
info = font.render("按ESC或关闭窗口退出", True, (200, 200, 200))
screen.blit(info, (WIDTH - info.get_width() - 10, HEIGHT - 20))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
pip install pygame安装)solar_system.py)你可以通过修改以下参数来自定义模拟:
WIDTH和HEIGHT改变窗口大小radius、color、distance和speed参数这个模拟是简化的,行星大小和距离不是按真实比例缩放的(否则太阳会太大而其他行星几乎看不见)。