python
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
import matplotlib.widgets as widgets
import numpy as np
import math
# --- 配置参数 ---
# 使用相对距离,不是实际天文单位,仅用于视觉效果
# (距离, 相对大小比例, 颜色, 轨道速度因子)
# 轨道速度因子越大,转得越快
PLANET_DATA = {
'sun': (0.0, 1.5, 'yellow', 0), # 太阳的位置和大小比例
'mercury': (0.5, 0.1, 'gray', 0.03),
'venus': (0.8, 0.2, 'orange', 0.02),
'earth': (1.2, 0.25, 'blue', 0.015),
'mars': (1.6, 0.15, 'red', 0.01),
'jupiter': (2.5, 0.8, 'brown', 0.005),
'saturn': (3.5, 0.6, 'sandybrown', 0.004), # 可以加个环,这里简化
'uranus': (4.2, 0.4, 'skyblue', 0.003),
'neptune': (4.8, 0.4, 'dodgerblue', 0.002),
}
ORBIT_LIMIT = 5.5 # 决定图形显示的范围
BACKGROUND_COLOR = 'black'
ORBIT_COLOR = 'dimgray'
PLANET_LABEL_COLOR = 'white'
SUN_EXPLOSION_COLOR = 'orangered'
PLANET_EXPLOSION_SPEED_FACTOR = 0.05 # 行星爆炸飞出的速度增量
# --- 全局状态 ---
explosion_active = False
planet_positions = {} # 存储行星当前的 (distance, angle)
planet_patches = {} # 存储行星的 matplotlib patch 对象
sun_patch = None
sun_initial_radius = 0 # 存储太阳初始半径,用于爆炸效果
explosion_frame_count = 0 # 爆炸发生后的帧计数
# --- 设置图形 ---
fig, ax = plt.subplots(figsize=(10, 10))
fig.patch.set_facecolor(BACKGROUND_COLOR) # 设置图窗背景色
ax.set_facecolor(BACKGROUND_COLOR) # 设置坐标系背景色
ax.set_xlim([-ORBIT_LIMIT, ORBIT_LIMIT])
ax.set_ylim([-ORBIT_LIMIT, ORBIT_LIMIT])
ax.set_aspect('equal', adjustable='box') # 保持 x, y 轴比例一致
# 隐藏坐标轴
ax.set_xticks([])
ax.set_yticks([])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
# --- 绘制太阳和行星 ---
def setup_solar_system():
global sun_patch, sun_initial_radius
# 绘制太阳
sun_radius = PLANET_DATA['sun'][1]
sun_initial_radius = sun_radius # Store for explosion
sun_patch = patches.Circle((0, 0), radius=sun_radius, color=PLANET_DATA['sun'][2], zorder=10)
ax.add_patch(sun_patch)
# 绘制行星和轨道
for name, (distance, size, color, speed) in PLANET_DATA.items():
if name == 'sun': continue
# 绘制轨道
orbit = patches.Circle((0, 0), radius=distance, color=ORBIT_COLOR, fill=False, linestyle='--', linewidth=0.5, zorder=0)
ax.add_patch(orbit)
# 绘制行星
# 初始位置随机,角度在 0 到 2pi 之间
initial_angle = np.random.rand() * 2 * np.pi
x = distance * np.cos(initial_angle)
y = distance * np.sin(initial_angle)
planet_patch = patches.Circle((x, y), radius=size, color=color, zorder=5)
ax.add_patch(planet_patch)
# 存储行星状态和 patch
planet_positions[name] = {'distance': distance, 'angle': initial_angle, 'speed': speed}
planet_patches[name] = planet_patch
# 添加行星名称标签
# position label slightly outside the planet
label_offset = size * 2 # adjust offset based on planet size
label_x = (distance + label_offset) * np.cos(initial_angle)
label_y = (distance + label_offset) * np.sin(initial_angle)
ax.text(x, y, name.capitalize(), color=PLANET_LABEL_COLOR, fontsize=8, ha='center', va='center', zorder=15) # Initial label position
# --- 动画更新函数 ---
def update(frame):
global explosion_active, explosion_frame_count
if not explosion_active:
# 正常轨道模式
for name, data in planet_positions.items():
# 更新角度
data['angle'] = (data['angle'] + data['speed']) % (2 * np.pi) # Ensure angle stays within 0-2pi
# 计算新位置
x = data['distance'] * np.cos(data['angle'])
y = data['distance'] * np.sin(data['angle'])
# 更新 patch 位置
planet_patches[name].set_center((x, y))
# Update label position (optional, can be performance heavy for many labels)
# Find the corresponding text label (this is inefficient, better ways exist if many labels)
# For this example, we'll just update the planet patch position.
# If updating labels is critical, managing them in a list like patches is needed.
# Here, we'll omit dynamic label updates to keep it simple and fast.
pass # Labels are static in this simple version
else:
# 爆炸模式
explosion_frame_count += 1
# 太阳爆炸效果
sun_patch.set_radius(sun_initial_radius + explosion_frame_count * 0.1) # 太阳膨胀
sun_patch.set_color(SUN_EXPLOSION_COLOR) # 太阳变色
sun_patch.set_alpha(max(0, 1 - explosion_frame_count * 0.01)) # 太阳逐渐透明
# 行星飞离效果
for name, data in planet_positions.items():
# 增加距离(飞离)
# Use the angle *at the moment of explosion*
# Assuming detonation_angle was stored when button was pressed
# If not stored, just use current_angle, which might not look right if explosion happens mid-update
# Let's ensure detonation_angle is stored in the button callback
# Simple outward speed increase
data['current_explosion_distance'] += data['explosion_radial_speed']
data['explosion_radial_speed'] += data['explosion_radial_acceleration'] # Simple acceleration model
x = data['current_explosion_distance'] * np.cos(data['detonation_angle'])
y = data['current_explosion_distance'] * np.sin(data['detonation_angle'])
# 更新 patch 位置
planet_patches[name].set_center((x, y))
# 可选:行星也变色或变大
# planet_patches[name].set_facecolor('lightgray') # planets getting burnt
# planet_patches[name].set_radius(PLANET_DATA[name][1] * (1 + explosion_frame_count * 0.005)) # planets expanding/burning
# Return patches that were modified
return list(planet_patches.values()) + [sun_patch]
# --- 按钮回调函数 ---
def detonate_sun(event):
global explosion_active, explosion_frame_count, planet_positions
if not explosion_active: # Only detonate if not already detonated
explosion_active = True
explosion_frame_count = 0
# Store current angle and distance for each planet at the moment of detonation
for name, data in planet_positions.items():
data['detonation_angle'] = data['angle'] # Store angle at explosion moment
data['current_explosion_distance'] = data['distance'] # Start explosion distance from current orbital distance
data['explosion_radial_speed'] = 0 # Initial speed outwards
data['explosion_radial_acceleration'] = PLANET_EXPLOSION_SPEED_FACTOR # Acceleration outwards
print("太阳已引爆!")
# --- 主执行部分 ---
if __name__ == '__main__':
setup_solar_system()
# 创建按钮所在的 axes
# [left, bottom, width, height] in figure coordinates (0 to 1)
ax_button = plt.axes([0.8, 0.01, 0.15, 0.05])
btn_detonate = widgets.Button(ax_button, '引爆太阳!', color='red', hovercolor='darkred')
# 绑定按钮点击事件
btn_detonate.on_clicked(detonate_sun)
# 创建动画
# blit=True means only re-draw the parts that have changed. Can improve performance.
# interval is delay between frames in milliseconds.
ani = animation.FuncAnimation(fig, update, frames=None, blit=True, interval=50)
# 显示图形
plt.show()