def main(): ferengi = Planet(distance=500, speed=-1) betasoide = Planet(distance=2000, speed=-3) vulcan = Planet(distance=1000, speed=5) star_trek_galaxy = Galaxy([ferengi, betasoide, vulcan]) draft_days = 0 perfect_days = 0 rainy_day = 0 most_rain_day = -1 most_rain_perimeter = 0 for day in range(3650): alignment = star_trek_galaxy.planets_are_aligned(day) if alignment is PlanetsPosition.ALIGNED_WITH_THE_SUN: draft_days += 1 elif alignment is PlanetsPosition.ALIGNED_WITH_EACHOTHER: perfect_days += 1 else: # if we are here, planets are forming a polygon (sunsPosition, per) = star_trek_galaxy.calculate_suns_position(day) if sunsPosition is PlanetsPosition.SUN_INSIDE_POLYGON: rainy_day += 1 if per > most_rain_perimeter: most_rain_day = day most_rain_perimeter = per print('Draft:', draft_days) print('Perfect:', perfect_days) print('Rainy:', rainy_day) print('Most rain:', most_rain_day)
def on_touch_down(self, touch): self.touch_start = touch.pos self.touch_end = touch.pos if HAS_CHARGE: charge = self.def_charge ''' if 'button' in touch.profile: if touch.button == 'right': charge = -1. ''' # print(f'keyboard_modifiers {self._keyboard_modifiers}') if 'ctrl' in self._keyboard_modifiers: charge *= -1. # print(f'charge {charge}') self.touch_planet = Planet(pos=list( self.to_num_dimension(touch.pos)), mass=1, num_dimension=self.num_dimension, charge=charge) else: self.touch_planet = Planet(pos=list( self.to_num_dimension(touch.pos)), mass=1, num_dimension=self.num_dimension) self.append(self.touch_planet) return False
def __init__(self, total_time, dt): self.solver = Solver(total_time, dt) self.planets = np.array([ Planet(self.solver, 1, [0, 0], [0, 0], True), Planet(self.solver, 3e-6, [1, 0], [0, 2 * np.pi]), Planet(self.solver, 9.5e-4, [5.2, 0], [0, 2.75]) ])
def load_planets(self): self.orbit_root_mercury = render.attachNewNode('orbit_root_mercury') self.orbit_root_venus = render.attachNewNode('orbit_root_venus') self.orbit_root_mars = render.attachNewNode('orbit_root_mars') self.orbit_root_earth = render.attachNewNode('orbit_root_earth') self.orbit_root_moon = ( self.orbit_root_earth.attachNewNode('orbit_root_moon')) self.sky = loader.loadModel("models/sky_dome.blend") self.sky_tex = loader.loadTexture("models/sky_tex2_cut.jpg") self.sky_tex.setWrapU(Texture.WM_clamp) self.sky.setTexture(self.sky_tex, 1) self.sky.reparentTo(render) self.sky.setScale(300) self.sky.setHpr(270, 0, 0) self.Sun = Star(self, 'Sun', 'models/planet_sphere', 'models/sun_1k_tex.jpg', 2) self.Mercury = Planet(self, 'Mercury', 'models/planet_sphere', 'models/mercury_1k_tex.jpg', self.orbit_root_mercury, 0.385, 0.38, False, 1, { 'Coal': 'Common', 'Iron': 'Common' }) self.Venus = Planet(self, 'Venus', 'models/planet_sphere', 'models/venus_1k_tex.jpg', self.orbit_root_venus, 0.923, 0.72, False, 2, { 'Coal': 'Common', 'Uranium': 'Normal' }) self.Mars = Planet(self, 'Mars', 'models/planet_sphere', 'models/mars_1k_tex.jpg', self.orbit_root_mars, 0.512, 1.52, False, 1, { 'Gemstone': 'Rare', 'Iron': 'Rare' }) self.Mars.probed = True self.Earth = Planet(self, 'Earth', 'models/planet_sphere', 'models/earth_1k_tex.jpg', self.orbit_root_earth, 1, 1, True, 1, { 'Iron': 'Normal', 'Coal': 'Common' }) self.orbit_root_moon.setPos(self.orbitscale, 0, 0) self.Earth_Moon = Moon(self, 'Moon', 'models/planet_sphere', 'models/moon_1k_tex.jpg', self.orbit_root_moon, 0.1, 0.1, False, 0, { 'Cheese': 'Rare', 'Coal': 'Common' })
def test_axial_tilt(): planet = Planet(SUN) planet.mass = planet.earth_in_solar_masses planet.axis = 1 tilts = set() for i in range(0, 100): tilts.add(Planet(SUN).axial_tilt()) assert len(tilts) > 0 assert min(tilts) > 0 assert max(tilts) < 360
def __init__(self, no_name_level, battery): ##width height tile rover x y list, battery """ Initialises the rover """ self.no_name_level = no_name_level self.rover_map = [] self.battery = battery self.width = self.no_name_level[0] self.height = self.no_name_level[1] self.tile = self.no_name_level[2] self.x = self.no_name_level[3] self.y = self.no_name_level[4] self.rover_coordinates = [self.x, self.y] self.tiles = [] for i in self.tile: i = i[:-1] self.tiles.append(i) self.tiles_arranged = [ self.tiles[i:i + self.width] for i in range(0, len(self.tile), self.width) ] planet_co = [] for i in self.tiles_arranged: self.planet = [] for n in i: n = n.split(',') if len(n) != 3: a = ['-'] n += a self.planet.append(n) else: self.planet.append(n) planet_co.append(self.planet) self.planet_map = Planet(planet_co, self.width, self.height) self.coordinates = Planet(planet_co, self.width, self.height) self.coordinates = Planet.coordinates(self.coordinates) self.planet_map = Planet.coordinates_dict( self.planet_map ) #this is my map in dictionary format(coordinates : tile) pass
def load_planets(self): ''' Load the planets for this system. ''' if not self.planets: if self.name.lower() == "sol": self.add_planet( Planet("Mercury", [.24 * 365, .39, .2056, 7.01, .034, 5.43, 440])) self.add_planet( Planet("Venus", [.62 * 365, .72, .0068, 3.39, .085, 5.25, 735])) self.add_planet( Planet("Earth", [365, 1.0, .0167, 0.0, 0.089, 5.52, 288])) self.add_planet( Planet("Mars", [1.88 * 365, 1.52, .0934, 1.85, .048, 3.93, 218])) self.add_planet( Planet("Jupiter", [11.86 * 365, 5.2, .0483, 1.31, 1.00, 1.33, 123])) self.add_planet( Planet("Saturn", [29.46 * 365, 9.5, .0560, 2.49, .84, 0.71, 103])) self.add_planet( Planet("Uranus", [84.01 * 365, 19.2, .0461, 0.77, .36, 1.24, 73])) self.add_planet( Planet("Neptune", [164.8 * 365, 30.0, .0097, 1.77, .35, 1.67, 63])) else: self.get_exoplanets() return self.planets
def solar_system(): # distance : in millions of km # radius : in thousands of km, all get divided by 2 and the sun by 10 on top for size on screen # velocity : in km/s # mass : in kg sun = Planet([center_w, center_h], 696.340 / 20, [0, 0], 1.989 * 10**30, (255, 255, 0), "Sun") mercury = Planet([center_w - 69.8, center_h], 2.439, [0, 38.86], 3.301 * 10**23, (128, 128, 128), "Mercury") venus = Planet([center_w - 108, center_h], 6.051, [0, 35], 4.8675 * 10**24, (255, 128, 0), "Venus") earth = Planet([center_w - 152.1, center_h], 6.371, [0, 29.3], 5.972 * 10**24, BLUE, "Earth") mars = Planet([center_w - 228, center_h], 3.390, [0, 21.972], 6.4185 * 10**23, RED, "Mars") m = 1.5 * 10**29 x = 97.000436 y = 24.308753 vx = 9.3240737 vy = 8.6473146 p1 = Planet([center_w + x, center_h + y], 10, [vx / 2, -vy / 2], m, BLUE) p2 = Planet([center_w - x, center_h - y], 10, [vx / 2, -vy / 2], m, RED) p3 = Planet([center_w, center_h], 10, [-vx, vy], m, WHITE) # planets = [p1, p2, p3] # 8 figure planets = [sun, mercury, venus, mars, earth] # solar system return planets, SolarSystem(planets)
def __init__(self): #initialise pygame pg.init() # Initialise the planets and sun self.sun = Planet("sprites/sun.png", 0, 0, True) self.earth = Planet("sprites/earth.png", 250, 1, False) self.mercury = Planet("sprites/mercury.png", 150, 3, False) # Initialise the screen and set screem size self.screen = pg.display.set_mode(gb.WORLD_SIZE) # Initialise clock to keep track of FPS self.clock = pg.time.Clock()
def collide(self, p1, p2, t): pos = list((p1.pos * p1.mass + p2.pos * p2.mass) / (p1.mass + p2.mass)) vel = list((p1.vel * p1.mass + p2.vel * p2.mass) / (p1.mass + p2.mass)) acc = list(np.array([0.] * self.num_dimension)) mass = p1.mass + p2.mass self.tails.append([ deque(p1.tail_coords), p1.tail_back, len(p1.tail_coords) + p1.tail_back, p1.round_size() ]) self.tails.append([ deque(p2.tail_coords), p2.tail_back, len(p2.tail_coords) + p2.tail_back, p2.round_size() ]) p3 = Planet(pos=pos, vel=vel, acc=acc, mass=mass, num_dimension=self.num_dimension, tail_back=max( len(p1.tail_coords) + p1.tail_back, len(p2.tail_coords) + p2.tail_back)) for i in range(len(self.objects)): if p1 is self.objects[i]: self.objects.pop(i) break for i in range(len(self.objects)): if p2 is self.objects[i]: self.objects.pop(i) break self.objects.append(p3)
def test_orbit_zone(): planet = Planet(SUN) assert planet.orbit_zone() == 1 planet.axis = 4 assert planet.orbit_zone() == 2 planet.axis = 22 assert planet.orbit_zone() == 3
def test_orbital_period(): planet = Planet(SUN) planet.mass = planet.earth_in_solar_masses planet.axis = 1 assert round(planet.orbital_period(), 2) == 365.25 planet.axis = 5.2 assert round(planet.orbital_period(), 2) == 4331.13
def __init__(self): """Inits the SolarSystem class.""" self.planets = [] for i in range(9): self.planets.append(Planet(planet_id=i))
def find_inactive_nearby(self, from_planet, radius=100, min_ponts=20000): self.logger.info("Searching inactives near %s in radius %s" % (from_planet, radius)) scores = etree.parse('general.xml').getroot() military_scores = etree.parse('military.xml').getroot() players = etree.parse('players.xml').getroot() galaxy = etree.parse('galaxy.xml').getroot() inactives = [] for player in players.findall('player'): status = player.get('status') if status == 'i' or status == 'I': p = Player(idx=player.get('id'), name=player.get('name')) p.score = self.get_score(player=p, scores=scores) p.military_score = self.get_score(player=p, scores=military_scores) if int(p.score) > min_ponts: inactives.append(p) for planet in galaxy.findall('planet[@player=\'' + p.idx + '\']'): pl = Planet(id=planet.get('id'), name=planet.get('name'), coords=planet.get('coords'), url=None) if from_planet.is_in_range(coords=pl.coords, radius=radius): self.logger.info(pl.coords) p.planets.append(pl) return inactives
def assign_home_sector(self, player, planet_name, ship_name): """Find an unused sector and assign this player to it. This should only run if the player doesn't have a parent (which means they don't have a ship).'""" if player.parent: self.log.debug( "assign_home_sector(): Player %s already has a parent, returning True" % player.name) return True home_sector = self._find_empty_sector() self.log.debug( "assign_home_sector(): Home sector determined to be %s" % home_sector.name) #We call get_sector, which will create it if it doesn't exist home_sector = self.get_sector( "%s-%s" % (home_sector.cluster_name, home_sector.name)) if home_sector: #Create planet planet = Planet(initial_state={'name': planet_name}) self.log.debug("assign_home_sector(): Adding planet %s" % planet) self.assign_child(home_sector, planet) #Create ship ship = Ship(initial_state={'name': ship_name}) self.assign_child(home_sector, ship) #Move player to ship self.assign_child(ship, player) return True else: self.log.error( "assign_home_sector(): db.add_sector() returned None, so the sector was not successfully created" ) return False
def on_touch_down(self, touch): self.touch_start = touch.pos self.touch_end = touch.pos self.touch_planet = Planet(pos=list(self.to_num_dimension(touch.pos)), mass=1, num_dimension=self.num_dimension) self.objects.append(self.touch_planet)
def fetch_planets(self): self.logger.info('Fetching planets..') resp = self.br.open(self.PAGES['main']).read() self.calc_time(resp) soup = BeautifulSoup(resp) self.planets = [] self.moons = [] try: for i, c in enumerate(soup.find('select').findAll('option')): url = c['value'] name, coords = c.contents[0].split(' ')[0:2] p = Planet('1', name, coords[1:-1], url, False) if i == 0: p.mother = True self.planets.append(p) #p_id = int(c.parent.get('id').split('-')[1]) # construct_mode = len( # c.parent.findAll( # 'a', # 'constructionIcon')) != 0 # check if planet has moon # moon = c.parent.find('a', 'moonlink') # if moon and 'moonlink' in moon['class']: # url = moon.get('href') # m_id = url.split('cp=')[1] # m = Moon(m_id, coords, url) # self.moons.append(m) except: self.logger.exception('Exception while fetching planets')
def setUp(self): """ Instantiates the planet data structure and fills it with paths example planet: +--+ | | +-0,3------+ | | 0,2-----2,2 (target) | / +-0,1 / | | / +-0,0-1,0 | (start) """ # set your data structure self.planet = Planet() # add the paths self.planet.add_path(((0, 0), Direction.NORTH), ((0, 1), Direction.SOUTH), 1) self.planet.add_path(((0, 1), Direction.WEST), ((0, 0), Direction.WEST), 1)
def setUp(self): """ Planet: +--+ | | +-0,3------+ | | 0,2-----2,2 (target) | / +-0,1 / | | / +-0,0-1,0 | (start) Instantiates the planet data structure and fills it with paths MODEL YOUR TEST PLANET HERE (if you'd like): """ # set your data structure self.planet = Planet() # ADD YOUR PATHS HERE: # self.planet.add_path(...) '''
def _read_json(self,filename): """Read a file's content as json to create an object.""" self.log.debug("_read_file(): Opening %s for reading" % os.path.join(self.path,filename)) f = open(os.path.join(self.path,filename),'r') with f: json_str = f.read() self.log.debug("JSON read from file as string: %s" % json_str) try: json_dict = json.loads(json_str) self.log.debug("JSON converted to dictionary: %s" % str(json_dict)) #TODO: Can this be generic? To create a class from a variable? if json_dict['type'] == "Cluster": return Cluster(initial_state = json_dict) elif json_dict['type'] == "Sector": return Sector(initial_state = json_dict) elif json_dict['type'] == "Player": return Player(initial_state = json_dict) elif json_dict['type'] == "Planet": return Planet(initial_state = json_dict) elif json_dict['type'] == "Ship": return Ship(initial_state = json_dict) else: return Entity(initial_state = json_dict) except TypeError,te: self.log.error("File %s does not appear to be valid JSON: %s" % (filename,te))
def setUp(self): self._solarsystem = Solar_system() #self._planet_1 = None route_1_x = [1000, 0, 0] route_1_v = [0, -1000, 0] route_1 = Route(route_1_x, route_1_v) name_1 = "Aalto-3" mass_1 = 10 state_1 = State.ALIVE self._satellite_1 = Satellite(name_1, route_1, mass_1, state_1) route_1_x = [152100000000, 0, 0] route_1_v = [0, 29780, 0] route_1 = Route(route_1_x, route_1_v) name_1 = "Earth" mass_1 = 5.97237*10**24 diameter = 2*6371000 self._planet_1 = Planet(name_1, route_1, mass_1, diameter) self.pos_test_string = "x:220my:100kmz:20m" self.test_read = Read_planets() test_file = open("test_read.txt") self._solarsystem.read_planets(test_file) test_file.close()
def test_add_rover(self): planet = Planet(2, 2) rover = Rover(1, 2, 'N', planet) self.assertEqual(len(planet.rovers), 0) planet.add_rover(rover) self.assertEqual(len(planet.rovers), 1)
def __init__(self, data_name, time_step, satelite=False): # Open and read the JSON data for the planets with open(data_name + '.json') as json_data: data = json.load(json_data) # Create a list containing all the planets self.bodies = [Planet(*[body] + data[body]) for body in data] for body in self.bodies: # Initialize acceleration for all planets body.update_acc(self.bodies, first=True) if satelite: # If a satelite file has been given # Open and read the JSON data for the satelite with open(satelite + '.json') as json_data: sat_data = json.load(json_data)['Satelite'] # Looking for the origin and the target of the satelite for body in self.bodies: if body.name == sat_data[0]: origin = body elif body.name == sat_data[1]: target = body # Initialize the satelite and append it to the list of bodies. self.bodies.append(Satelite(*[origin, target] + sat_data[2:] + [data[body.name][4], self.bodies])) self.energies = ([], []) self.t = time_step self.time = 0
def test_regular_density(): planet = Planet(SUN) planet.mass = planet.earth_in_solar_masses assert round(planet.density(), 2) == 5.43 planet.gas_giant = True planet.mass *= 20 assert round(planet.density(), 2) == 1.75
def __init__(self, mqtt_client): """ Initializes communication module, connect to server, subscribe, etc. """ # THESE TWO VARIABLES MUST NOT BE CHANGED self.client = mqtt_client self.client.on_message = self.on_message # ADD YOUR VARIABLES HERE # Basic configuration of MQTT # Wichtig? self.client.on_message = self.on_message_excepthandler self.client.username_pw_set('118', password='******') # Your group credentials self.client.connect('mothership.inf.tu-dresden.de', port=8883) self.client.subscribe('explorer/118', qos=1) # Subscribe to topic explorer/xxx # self.send_ready() # Start listening to incoming messages self.client.loop_start() #self.timer() self.planet = Planet() #Parameter: self.data = None self.topic = "explorer/118" self.planet_Chan = None self.aktX = None self.aktY = None self.direc = None
def test_gas_giant_density(): planet = Planet(SUN) planet.mass = planet.earth_in_solar_masses planet.gas_giant = True assert planet.density() == 1.2 planet.mass *= 2.0 assert round(planet.density(), 2) == 1.31
def fetch_planets(self): self.logger.info('Fetching planets..') resp = self.br.open(self.PAGES['main']).read() self.calc_time(resp) soup = BeautifulSoup(resp) self.planets = [] self.moons = [] try: for i, c in enumerate(soup.findAll('a', 'planetlink')): name = c.find('span', 'planet-name').text coords = c.find('span', 'planet-koords').text[1:-1] url = c.get('href') p_id = int(c.parent.get('id').split('-')[1]) construct_mode = len(c.parent.findAll('a', 'constructionIcon')) != 0 p = Planet(p_id, name, coords, url, construct_mode) if i == 0: p.mother = True self.planets.append(p) #check if planet has moon moon = c.parent.find('a', 'moonlink') if moon and 'moonlink' in moon['class']: url = moon.get('href') m_id = url.split('cp=')[1] m = Moon(m_id, coords, url) self.moons.append(m) except: self.logger.exception('Exception while fetching planets') else: self.check_attacks(soup)
def test_radius(): planet = Planet(SUN) planet.mass = planet.earth_in_solar_masses assert round(planet.radius(), 2) == 6403.97 planet.gas_giant = True planet.mass *= 20 assert round(planet.radius(), 2) == 25382.72
def __init__(self, root=None): self.canvas = tk.Canvas(root) self.canvas.pack(expand=True, fill="both") sun = Sun(engine=self, mass=1000) sun_graphic = self.canvas.create_oval(sun.x - sun.radius, sun.y - sun.radius, sun.x + sun.radius, sun.y + sun.radius, fill="yellow") planet = Planet(engine=self, sun=sun) planet_graphic = self.canvas.create_oval(planet.x - planet.radius, planet.y - planet.radius, planet.x + planet.radius, planet.y + planet.radius, fill="green") lander = NaiveLander(engine=self, sun=sun, planet=planet, acceleration_cap=0.5) lander_graphic = self.canvas.create_oval(lander.x - lander.radius, lander.y - lander.radius, lander.x + lander.radius, lander.y + lander.radius, fill="grey") self.graphic_dict = { sun: sun_graphic, planet: planet_graphic, lander: lander_graphic } self.update()
def run(self, request): response = self.action(request) errors = response.errors if len(errors) > 0: for error in errors: logDebug("error:%s" % error) if len(response.planets) > 0: self._start_game("Game begin") if not self.testMode: self.log.start() self.step += 1 planets = {} for planet in response.planets: p = Planet(planet, planets, self.user) planets[p.id] = p request = Request(self.token, planets) start = datetime.now() try: self.handle(planets, request) except Win, e: self._end_game("You win") except GameOver, e: self._end_game("Game over")