SOLAR SYSTEM/ PLANET SIMULATOR PROJECT
I was scrolling through my YouTube feed and came across a planet simulator tutorial video for Python.
Before starting the project I had to install a few things, being Pygame and PyMunk. I can’t exactly remember what I did on the first day.
import pygame
import math
pygame.init()
WIDTH, HEIGHT = 800, 800
WIN = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Planet Simluator")
WHITE = ("#e6e6e6")
YELLOW = (255, 191, 0)
BLUE = (23, 128, 209)
RED = (209, 79, 23)
DARK_GREY = ("#595757")
class Planet:
AU = 149.6e6 * 1000
G = 6.67428e-11
SCALE = 200 / AU #1AU = 100 pixels
TIMESTEP = 3600*24 #1 day
def __init__(self, x, y, radius, color, mass):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.mass = mass
self.orbit = []
self.sun = False
self.dis_to_sun = 0
self.x_vel = 0
self.y_vel = 0
def draw(self, win ):
x = self.x * self.SCALE + WIDTH / 2
y = self.y* self.SCALE + HEIGHT / 2
pygame.draw.circle(win, self.color, (x,y), self.radius)
def attraction(self, other):
other_x, other_y = other.x, other.y
distance_x = other_x - self.x
distance_y = other_y - self.y
distance = math.sqrt(distance_x ** 2 + distance_y ** 2)
if other.sun:
self.dis_to_sun = distance
force = self.G * self.mass * other.mass / distance**2
theta = math.atan2(distance_y, distance_x)
force_x = math.cos(theta) * force
force_y = math.sin(theta) * force
return force_x, force_y
def update_position(self, planets):
total_fx = total_fy = 0
for planet in planets:
if self == planet:
continue
fx, fy = self.attraction(planet)
total_fx += fx
total_fy += fy
self.x_vel += total_fx / self.mass * self.TIMESTEP
F = m / a
a = f / m
def main():
run = True
clock = pygame.time.Clock()
sun = Planet(0,0, 30, YELLOW, 1.98892 * 10**30 )
sun.sun =True
earth = Planet(-1 * Planet.AU, 0, 16, BLUE, 5.9742 * 10**24)
mars = Planet(-1.524 * Planet.AU, 0, 12, RED, 6.39 * 10**29)
mercury = Planet(0.387 * Planet.AU, 0, 8, DARK_GREY, 3.30 * 10**23)
venus = Planet(0.723 * Planet.AU, 0, 14, WHITE, 4.8685 * 10**24)
planets = [sun, earth, mars, mercury, venus]
while run:
clock.tick(60)
#WIN.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for planet in planets:
planet.draw(WIN)
pygame.display.update()
pygame.quit()
main()
This is all the code from day one.
On the second day of working on this project, the video covered the psychics of how to make the planets move and the distance of the outer planets for those who wanted to add it later on. I didn’t understand a bit of it.
On the 3rd day I tried working on the project at home but I was having trouble installing Python on my laptop and also pip wasn’t working. so I spent a good amount of time trying to figure out how to make that work.
Leave a Reply