priej k nasledujciu kodu pridavat nebo odebirat číslo počet dnu, mesicu a roku. format tlačítek bude nasledujici - den číslo (lze zapsat) plus minus. obdobne pro mesice a roky. po kazdem pridani ci odebrani se zmeni datum a graficky vystup planet se posune do spravne polohy.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button
import numpy as np
import sys
Definice třídy pro Planet
class Planet:
def init(self, name, distance, speed, initial_angle=1):
"""
Inicializuje planetu s jejími vlastnostmi.
code
:param name: Název planety
:param distance: Vzdálenost od hvězdy (AU)
:param speed: Orbitalní rychlost (degrees per frame)
:param initial_angle: Počáteční úhel (degrees), defaultně 1°
"""
self.name = name
self.distance = distance # V astronomických jednotkách (AU)
self.speed = speed # Rychlost v °/krok
self.angle = initial_angle # Počáteční úhel
def update_position(self):
"""
Aktualizuje aktuální úhel planety na základě její rychlosti.
Pohyb je proti směru hodinových ručiček.
"""
self.angle = (self.angle + self.speed) % 360
def get_cartesian(self):
"""
Převádí aktuální polohu z polárních souřadnic do kartézských.
:return: (x, y) pozice planety
"""
rad = np.deg2rad(self.angle)
x = self.distance * np.cos(rad)
y = self.distance * np.sin(rad)
return (x, y)
Funkce pro získání vstupu od uživatele
def get_number_of_planets():
while True:
try:
num = int(input("Zadejte počet planet (1-12): "))
if 1 <= num <= 12:
return num
else:
print("Prosím zadejte číslo mezi 1 a 12.")
except ValueError:
print("Neplatný vstup. Zadejte celé číslo mezi 1 a 12.")
Inicializace planetárního systému podle počtu planet
def initialize_system(number_of_planets):
planets = []
# Dynamické nastavení rychlosti a vzdáleností
max_speed = 12 # Rychlost nejbližší planety
if number_of_planets > 1:
speed_decrement = (max_speed - 1) / (number_of_planets - 1) # Snížení rychlosti pro každou planetu
else:
speed_decrement = 0
Assistant
code
base_distance = 1 # Vzdálenost nejbližší planety (AU)
distance_increment = 1 # Přírůstek vzdálenosti pro každou planetu (AU)
initial_base_angle = 1 # Základní úhel 1°
for i in range(1, number_of_planets + 1):
distance = base_distance + (i - 1) * distance_increment # 1 AU, 2 AU, ..., n AU
speed = max_speed - (i - 1) * speed_decrement # Dynamicky snížená rychlost
initial_angle = initial_base_angle # Všechny planety začínají na 1°
planet = Planet(name=f"Planet {i}", distance=distance, speed=speed, initial_angle=initial_angle)
planets.append(planet)
return planets
Třída pro řízení simulace
class PlanetarySystemSimulation:
def init(self, number_of_planets):
# Inicializace systému
self.planets = initialize_system(number_of_planets)
code
# Datumové proměnné
self.day = 1
self.month = 1
self.year = 1
# Nastavení grafu s GridSpec pro rozdělení na plot a sidebar
self.fig = plt.figure(figsize=(12, 8))
gs = self.fig.add_gridspec(1, 2, width_ratios=[3, 1])
# Hlavní plot pro planetární systém
self.ax = self.fig.add_subplot(gs[0, 0])
self.ax.set_aspect('equal')
# Dynamické nastavení hranic grafu podle počtu planet
max_distance = max(planet.distance for planet in self.planets) + 2 # Přidáme trochu prostoru
self.ax.set_xlim(-max_distance, max_distance)
self.ax.set_ylim(-max_distance, max_distance)
self.ax.set_xlabel('X (AU)')
self.ax.set_ylabel('Y (AU)')
self.ax.set_title(f'Simulace Planetárního Systému s {number_of_planets} Planetami')
# Zobrazení hvězdy
self.ax.plot(0, 0, 'yo', markersize=12, label='Hvězda')
# Kreslení orbitálních drah
for planet in self.planets:
orbit = plt.Circle((0, 0), planet.distance, color='gray', linestyle='dashed', fill=False, alpha=0.5)
self.ax.add_artist(orbit)
# Inicializace planet jako scatter body
self.scatters = []
for planet in self.planets:
x, y = planet.get_cartesian()
scatter, = self.ax.plot([x], [y], 'o', markersize=6, label=planet.name)
self.scatters.append(scatter)
# Sidebar pro tlačítka a datum
self.ax_sidebar = self.fig.add_subplot(gs[0, 1])
self.ax_sidebar.axis('off') # Skrýt osu
# Přidání tlačítek
self.add_buttons()
# Přidání textu pro datum do sidebaru
self.date_text = self.ax_sidebar.text(0.5, 0.8, '', ha='center', va='center', fontsize=12, transform=self.ax_sidebar.transAxes)
# Inicializace animace
self.ani = None
# Aktualizace data text na startovní hodnotu
self.update_date_text()
def add_buttons(self):
# Definice prostoru pro tlačítka v sidebaru
ax_start = self.ax_sidebar.inset_axes([0.1, 0.6, 0.8, 0.1]) # [left, bottom, width, height]
ax_stop = self.ax_sidebar.inset_axes([0.1, 0.4, 0.8, 0.1])
# Vytvoření tlačítek
self.button_start = Button(ax_start, 'Start')
self.button_stop = Button(ax_stop, 'Stop')
# Přiřazení callbacků
self.button_start.on_clicked(self.start_animation)
self.button_stop.on_clicked(self.stop_animation)
# Přidání popisků
self.ax_sidebar.text(0.5, 0.75, 'Pohyb:', ha='center', va='center', fontsize=12, transform=self.ax_sidebar.transAxes)
self.ax_sidebar.text(0.5, 0.55, 'Ovládání:', ha='center', va='center', fontsize=12, transform=self.ax_sidebar.transAxes)
def start_animation(self, event):
"""Spustí animaci."""
if self.ani is None:
print("Spouštím animaci...")
self.ani = animation.FuncAnimation(
self.fig,
self.animate,
fargs=(self.scatters,),
frames=360,
interval=100,
blit=False,
repeat=True
)
self.fig.canvas.draw_idle() # Aktualizace GUI
else:
print("Animace již běží.")
self.ani.event_source.start()
def stop_animation(self, event):
"""Zastaví animaci."""
if self.ani is not None:
print("Zastavuji animaci...")
self.ani.event_source.stop()
else:
print("Animace ještě neběží.")
def update_date(self, days):
"""Aktualizuje datum na základě počtu dní."""
self.day += int(days) # Zajistíme, že day bude vždy int
# Přepočet dnů a měsíců
while self.day > 30:
self.day -= 30
self.month += 1
if self.month > 12:
self.month = 1
self.year += 1
def update_date_text(self):
"""Aktualizuje text zobrazující datum."""
self.date_text.set_text(f"Datum: {self.day:02d}-{self.month:02d}-{self.year:02d}")
def animate(self, frame, scatters):
"""Aktualizuje pozice planet a datum."""
for planet, scatter in zip(self.planets, scatters):
planet.update_position()
x, y = planet.get_cartesian()
scatter.set_data([x], [y]) # Předání seznamů místo jednotlivých hodnot
# Aktualizace data na základě rychlosti Planet 1
if self.planets:
planet1 = self.planets[0] # Nejbližší planeta
days_passed = planet1.speed # Jeden krok odpovídá planet1.speed dnům
self.update_date(days_passed)
self.update_date_text()
return scatters
def show(self):
"""Zobrazuje graf a spustí interaktivní mód."""
# Pokud potřebujete legendu, můžete ji odkomentovat, ale s 12 planetami by mohla být přeplněná
# self.ax.legend(loc='upper right', fontsize='small', ncol=2)
plt.tight_layout()
plt.show()
Certainly! Below is the enhanced version of your planetary system simulation. This update includes interactive controls that allow users to add or subtract days, months, and years. Each date component has plus and minus buttons alongside a display of the current value. Whenever the date is modified, the simulation updates the planet positions accordingly to reflect the new date.
Key Enhancements:
Date Controls: Added buttons to increment and decrement days, months, and years.
Dynamic Planet Positions: Planet positions are recalculated based on the updated date.
User Interface Layout: Organized the sidebar to accommodate the new controls without cluttering.
Here's the complete updated code with detailed comments explaining each modification:
python
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button
import numpy as np
import sys
# Definice třídy pro Planet
class Planet:
def __init__(self, name, distance, speed, initial_angle=1):
"""
Inicializuje planetu s jejími vlastnostmi.
:param name: Název planety
:param distance: Vzdálenost od hvězdy (AU)
:param speed: Orbitalní rychlost (degrees per day)
:param initial_angle: Počáteční úhel (degrees), defaultně 1°
"""
self.name = name
self.distance = distance # V astronomických jednotkách (AU)
self.speed = speed # Rychlost v °/den
self.initial_angle = initial_angle # Počáteční úhel
self.angle = initial_angle # Aktuální úhel
def update_position(self, days=1):
"""
Aktualizuje aktuální úhel planety na základě její rychlosti.
:param days: Počet dní, o které se úhel aktualizuje
"""
self.angle = (self.angle + self.speed * days) % 360
def set_angle(self, total_days):
"""
Nastaví úhel planety na základě celkového počtu dní.
:param total_days: Celkový počet dní od začátku simulace
"""
self.angle = (self.initial_angle + self.speed * total_days) % 360
def get_cartesian(self):
"""
Převádí aktuální polohu z polárních souřadnic do kartézských.
:return: (x, y) pozice planety
"""
rad = np.deg2rad(self.angle)
x = self.distance * np.cos(rad)
y = self.distance * np.sin(rad)
return (x, y)
# Funkce pro získání vstupu od uživatele
def get_number_of_planets():
while True:
try:
num = int(input("Zadejte počet planet (1-12): "))
if 1 <= num <= 12:
return num
else:
print("Prosím zadejte číslo mezi 1 a 12.")
except ValueError:
print("Neplatný vstup. Zadejte celé číslo mezi 1 a 12.")
# Inicializace planetárního systému podle počtu planet
def initialize_system(number_of_planets):
planets = []
# Dynamické nastavení rychlosti a vzdáleností
max_speed = 5 # Rychlost nejbližší planety (degrees per day)
if number_of_planets > 1:
speed_decrement = (max_speed - 0.5) / (number_of_planets - 1) # Snížení rychlosti pro každou planetu
else:
speed_decrement = 0
base_distance = 1 # Vzdálenost nejbližší planety (AU)
distance_increment = 1 # Přírůstek vzdálenosti pro každou planetu (AU)
initial_base_angle = 1 # Základní úhel 1°
for i in range(1, number_of_planets + 1):
distance = base_distance + (i - 1) * distance_increment # 1 AU, 2 AU, ..., n AU
speed = max_speed - (i - 1) * speed_decrement # Dynamicky snížená rychlost
initial_angle = initial_base_angle # Všechny planety začínají na 1°
planet = Planet(name=f"Planeta {i}", distance=distance, speed=speed, initial_angle=initial_angle)
planets.append(planet)
return planets
# Třída pro řízení simulace
class PlanetarySystemSimulation:
def __init__(self, number_of_planets):
# Inicializace systému
self.planets = initialize_system(number_of_planets)
# Datumové proměnné
self.day = 1
self.month = 1
self.year = 1
self.total_days = 0 # Celkový počet dní od začátku
# Nastavení grafu s GridSpec pro rozdělení na plot a sidebar
self.fig = plt.figure(figsize=(14, 8))
gs = self.fig.add_gridspec(1, 3, width_ratios=[3, 1, 1])
# Hlavní plot pro planetární systém
self.ax = self.fig.add_subplot(gs[0, 0])
self.ax.set_aspect('equal')
# Dynamické nastavení hranic grafu podle počtu planet
max_distance = max(planet.distance for planet in self.planets) + 2 # Přidáme trochu prostoru
self.ax.set_xlim(-max_distance, max_distance)
self.ax.set_ylim(-max_distance, max_distance)
self.ax.set_xlabel('X (AU)')
self.ax.set_ylabel('Y (AU)')
self.ax.set_title(f'Simulace Planetárního Systému s {number_of_planets} Planetami')
# Zobrazení hvězdy
self.ax.plot(0, 0, 'yo', markersize=12, label='Hvězda')
# Kreslení orbitálních drah
for planet in self.planets:
orbit = plt.Circle((0, 0), planet.distance, color='gray', linestyle='dashed', fill=False, alpha=0.5)
self.ax.add_artist(orbit)
# Inicializace planet jako scatter body
self.scatters = []
for planet in self.planets:
x, y = planet.get_cartesian()
scatter, = self.ax.plot([x], [y], 'o', markersize=6, label=planet.name)
self.scatters.append(scatter)
# Sidebar pro tlačítka a datum
self.ax_sidebar = self.fig.add_subplot(gs[0, 1])
self.ax_sidebar.axis('off') # Skrýt osu
# Přidání tlačítek a ovládání data
self.add_controls()
# Inicializace animace
self.ani = None
# Aktualizace data text na startovní hodnotu
self.update_date_text()
def add_controls(self):
"""
Přidává kontrolní prvky do sidebaru, včetně tlačítek pro start/stop a ovládání data.
"""
# Definice rozmístění tlačítek a textů
# Použijeme relativní souřadnice [left, bottom, width, height]
# Ovládání data
button_width = 0.2
button_height = 0.05
gap = 0.05
start_y = 0.8
# Day Controls
ax_day_dec = self.ax_sidebar.inset_axes([0.1, start_y, button_width, button_height])
self.button_day_dec = Button(ax_day_dec, '-', hovercolor='0.975')
self.button_day_dec.on_clicked(self.decrement_day)
ax_day_inc = self.ax_sidebar.inset_axes([0.3, start_y, button_width, button_height])
self.button_day_inc = Button(ax_day_inc, '+', hovercolor='0.975')
self.button_day_inc.on_clicked(self.increment_day)
self.text_day = self.ax_sidebar.text(0.6, start_y + button_height/2, f"Den: {self.day}",
ha='left', va='center', fontsize=10, transform=self.ax_sidebar.transAxes)
# Month Controls
ax_month_dec = self.ax_sidebar.inset_axes([0.1, start_y - (button_height + gap), button_width, button_height])
self.button_month_dec = Button(ax_month_dec, '-', hovercolor='0.975')
self.button_month_dec.on_clicked(self.decrement_month)
ax_month_inc = self.ax_sidebar.inset_axes([0.3, start_y - (button_height + gap), button_width, button_height])
self.button_month_inc = Button(ax_month_inc, '+', hovercolor='0.975')
self.button_month_inc.on_clicked(self.increment_month)
self.text_month = self.ax_sidebar.text(0.6, start_y - (button_height + gap) + button_height/2,
f"Měsíc: {self.month}",
ha='left', va='center', fontsize=10, transform=self.ax_sidebar.transAxes)
# Year Controls
ax_year_dec = self.ax_sidebar.inset_axes([0.1, start_y - 2*(button_height + gap), button_width, button_height])
self.button_year_dec = Button(ax_year_dec, '-', hovercolor='0.975')
self.button_year_dec.on_clicked(self.decrement_year)
ax_year_inc = self.ax_sidebar.inset_axes([0.3, start_y - 2*(button_height + gap), button_width, button_height])
self.button_year_inc = Button(ax_year_inc, '+', hovercolor='0.975')
self.button_year_inc.on_clicked(self.increment_year)
self.text_year = self.ax_sidebar.text(0.6, start_y - 2*(button_height + gap) + button_height/2,
f"Rok: {self.year}",
ha='left', va='center', fontsize=10, transform=self.ax_sidebar.transAxes)
# Start and Stop Buttons
ax_start = self.ax_sidebar.inset_axes([0.1, 0.2, 0.8, 0.07])
self.button_start = Button(ax_start, 'Start')
self.button_start.on_clicked(self.start_animation)
ax_stop = self.ax_sidebar.inset_axes([0.1, 0.1, 0.8, 0.07])
self.button_stop = Button(ax_stop, 'Stop')
self.button_stop.on_clicked(self.stop_animation)
# Text pro datum
self.date_text = self.ax_sidebar.text(0.5, 0.95, '', ha='center', va='center',
fontsize=12, transform=self.ax_sidebar.transAxes)
self.update_date_text()
def increment_day(self, event):
"""Zvyšuje den o 1."""
self.day += 1
if self.day > 30:
self.day = 1
self.increment_month(None)
self.total_days += 1
self.update_date_text()
self.update_planets()
def decrement_day(self, event):
"""Snižuje den o 1."""
self.day -= 1
if self.day < 1:
self.day = 30
self.decrement_month(None)
self.total_days -= 1
self.update_date_text()
self.update_planets()
def increment_month(self, event):
"""Zvyšuje měsíc o 1."""
self.month += 1
if self.month > 12:
self.month = 1
self.increment_year(None)
self.total_days += 30
self.update_date_text()
self.update_planets()
def decrement_month(self, event):
"""Snižuje měsíc o 1."""
self.month -= 1
if self.month < 1:
self.month = 12
self.decrement_year(None)
self.total_days -= 30
self.update_date_text()
self.update_planets()
def increment_year(self, event):
"""Zvyšuje rok o 1."""
self.year += 1
self.total_days += 360
self.update_date_text()
self.update_planets()
def decrement_year(self, event):
"""Snižuje rok o 1."""
if self.year > 1:
self.year -= 1
self.total_days -= 360
self.update_date_text()
self.update_planets()
else:
print("Rok nemůže být menší než 1.")
def update_date_text(self):
"""Aktualizuje text zobrazující aktuální datum."""
self.date_text.set_text(f"Datum: {self.day:02d}-{self.month:02d}-{self.year:02d}")
# Aktualizace textů pro den, měsíc, rok
self.text_day.set_text(f"Den: {self.day}")
self.text_month.set_text(f"Měsíc: {self.month}")
self.text_year.set_text(f"Rok: {self.year}")
def update_planets(self):
"""Nastaví úhly planet na základě aktuálního data."""
for planet in self.planets:
planet.set_angle(self.total_days)
self.update_scatter_positions()
self.fig.canvas.draw_idle()
def update_scatter_positions(self):
"""Aktualizuje pozice planet na grafu."""
for planet, scatter in zip(self.planets, self.scatters):
x, y = planet.get_cartesian()
scatter.set_data([x], [y])
def start_animation(self, event):
"""Spustí animaci."""
if self.ani is None:
print("Spouštím animaci...")
self.ani = animation.FuncAnimation(
self.fig,
self.animate,
fargs=(self.scatters,),
frames=360,
interval=100,
blit=False,
repeat=True
)
self.fig.canvas.draw_idle() # Aktualizace GUI
else:
print("Animace již běží.")
self.ani.event_source.start()
def stop_animation(self, event):
"""Zastaví animaci."""
if self.ani is not None:
print("Zastavuji animaci...")
self.ani.event_source.stop()
else:
print("Animace ještě neběží.")
def animate(self, frame, scatters):
"""Aktualizuje pozice planet a datum."""
# Aktualizace planet a posun dne
self.update_date(1) # Jeden den na frame
return scatters
def update_date(self, days):
"""Aktualizuje datum na základě počtu dní."""
self.day += int(days) # Zajistíme, že day bude vždy int
# Přepočet dnů a měsíců
while self.day > 30:
self.day -= 30
self.month += 1
if self.month > 12:
self.month = 1
self.year += 1
while self.day < 1:
self.day += 30
self.month -= 1
if self.month < 1:
self.month = 12
self.year -= 1
if self.year < 1:
self.year = 1
self.day = 1
self.month = 1
break
self.total_days += days
self.update_date_text()
# Aktualizace planet na základě nového data
self.update_planets()
def show(self):
"""Zobrazuje graf a spustí interaktivní mód."""
# Pokud potřebujete legendu, můžete ji odkomentovat, ale s 12 planetami by mohla být přeplněná
# self.ax.legend(loc='upper right', fontsize='small', ncol=2)
plt.tight_layout()
plt.show()
def main():
print("=== Simulace Planetárního Systému ===")
number_of_planets = get_number_of_planets()
simulation = PlanetarySystemSimulation(number_of_planets)
simulation.show()
if __name__ == "__main__":
main()
Detailed Explanation of the Enhancements:
Planet Class Updates:
set_angle Method:
Purpose: Allows setting the planet's angle based on the total number of days elapsed.
Usage: Called whenever the date is changed to recalculate planet positions.
update_position Method:
Adjusted to take an argument days with a default value of 1.
Purpose: Updates the planet's angle based on days passed during animation.
PlanetarySystemSimulation Class Updates:
Date Variables:
self.total_days: Keeps track of the total number of days since the start of the simulation.
UI Layout:
Sidebar (self.ax_sidebar): Organized into three main sections for days, months, and years, each with decrement and increment buttons.
Buttons: Created using matplotlib.widgets.Button and positioned using inset_axes for precise placement.
Text Displays: Show current values of day, month, and year, updating dynamically with interactions.
Control Methods:
Increment/Decrement Methods: For days, months, and years, ensuring that the values wrap around appropriately (e.g., 31st day becomes 1st day of the next month).
update_date_text: Refreshes the displayed date whenever changes occur.
update_planets: Recalculates planet positions based on the new date and updates the scatter plot.
Animation Integration:
animate Method: Advances the simulation by one day per frame, updating both the date and planet positions.
Start/Stop Buttons: Allow users to control the animation flow.
User Interaction Flow:
Manual Adjustments: Users can manually change the date using the plus and minus buttons. Each change recalculates and updates the planet positions instantly.
Usage Instructions:
Running the Simulation:
Execute the script. You'll be prompted to enter the number of planets (between 1 and 12).
After entering a valid number, the simulation window will appear.
Interacting with the Simulation:
Start: Click the "Start" button to begin the animation, which advances the date automatically.
Stop: Click the "Stop" button to pause the animation.
Date Controls:
Days: Use the "-" and "+" buttons to decrease or increase the day.
Months: Use the "-" and "+" buttons to decrease or increase the month.
Years: Use the "-" and "+" buttons to decrease or increase the year.
Observing Changes: Each adjustment will instantly update the positions of the planets to reflect the new date.
Note:
Speed Configuration: The max_speed parameter in the initialize_system function determines how fast the closest planet moves. Adjusting this value changes the simulation dynamics.
Orbit Representation: Planetary orbits are depicted as dashed gray circles for visual reference.
This enhanced simulation provides a more interactive and educational experience, allowing users to explore how astronomical dates influence planetary positions within a system.
Not yet included in a published release.
Animation: When running, the simulation automatically advances the date, updating planet positions in sync with the time progression.
UI Aesthetics:
Button Layout: Positioned evenly to ensure a clean and intuitive interface.
Text Alignment: Centrally aligned for better readability.
Responsive Updates: The simulation reflects changes in real-time, providing immediate visual feedback.