def setUp(self): self.hash = '43228a6d34e15561dcb179a9e4388489e4634093348a57f34801a12fd548f203' self.root_path = str(os.path.dirname(os.path.abspath(__file__))).replace('tests', '') self.font_path = self.root_path + 'fonts' self.font_path_fn = self.root_path + 'fonts/DejaVuSansMono.ttf' self.icon_path = self.root_path + 'icons' self.cfg_path = self.root_path + 'mapcfgs' self.img_path = self.root_path + 'mapimgs' a = Node(self.font_path_fn, self.icon_path, x=300, y=30, label='host-A', icon='Router96.png') b = Node(self.font_path_fn, self.icon_path, x=750, y=30, label='host-B', icon='Router96.png') c = Node(self.font_path_fn, self.icon_path, x=30, y=750, label='host C', icon='Router96.png') d = Node(self.font_path_fn, self.icon_path, x=750, y=750, label='HOST-D', icon='Router96.png') e = Node(self.font_path_fn, self.icon_path, x=400, y=400, label='host-E', icon='Router96.png') link_a = Link(self.font_path_fn, a, e, bandwidth=1000, width=10) link_a.data(in_bps=0, out_bps=123345123) link_b = Link(self.font_path_fn, b, e, bandwidth=100, width=15) link_b.data(in_bps=54123456, out_bps=114987654) link_c = Link(self.font_path_fn, c, e, bandwidth=10000) link_c.data(in_bps=841123456, out_bps=5147987654) link_d = Link(self.font_path_fn, d, e, bandwidth=100, width=15) link_d.data(in_bps=73456852, out_bps=987654) link_e = Link(self.font_path_fn, a, b, bandwidth=100, width=15) link_e.data(in_bps=73456852, out_bps=987654) table = Table(self.font_path_fn, x=700, y=350, dt=False) self.new_map = Map([link_a, link_b, link_c, link_d, link_e], [a, b, c, d, e], table=table, len_x=800, len_y=800)
def setUp(self): self.hash = 'fd6069568a5d453a8572fbfafb517f14115bc093deee67554c468b61ac734d61' self.root_path = str(os.path.dirname( os.path.abspath(__file__))).replace('tests', '') self.font_path = self.root_path + 'fonts' self.font_path_fn = self.root_path + 'fonts/DejaVuSansMono.ttf' self.icon_path = self.root_path + 'icons' self.cfg_path = self.root_path + 'mapcfgs' self.img_path = self.root_path + 'mapimgs' a = Node(self.font_path_fn, self.icon_path, x=300, y=30, label='host-A', icon='Router96.png') b = Node(self.font_path_fn, self.icon_path, x=750, y=30, label='host-B', icon='Router96.png') c = Node(self.font_path_fn, self.icon_path, x=30, y=750, label='host C', icon='Router96.png') d = Node(self.font_path_fn, self.icon_path, x=750, y=750, label='HOST-D', icon='Router96.png') e = Node(self.font_path_fn, self.icon_path, x=400, y=400, label='host-E', icon='Router96.png') link_a = Link(self.font_path_fn, a, e, bandwidth=1000, width=10) link_a.data(in_bps=0, out_bps=123345123) link_b = Link(self.font_path_fn, b, e, bandwidth=100, width=15) link_b.data(in_bps=54123456, out_bps=114987654) link_c = Link(self.font_path_fn, c, e, bandwidth=10000) link_c.data(in_bps=841123456, out_bps=5147987654) link_d = Link(self.font_path_fn, d, e, bandwidth=100, width=15) link_d.data(in_bps=73456852, out_bps=987654) link_e = Link(self.font_path_fn, a, b, bandwidth=100, width=15) link_e.data(in_bps=73456852, out_bps=987654) table = Table(self.font_path_fn, x=700, y=350, dt=False) self.new_map = Map([link_a, link_b, link_c, link_d, link_e], [a, b, c, d, e], table=table, len_x=800, len_y=800)
def test_normalize(self): """ Test the method normalize """ self.assertTrue( np.array_equal(Map.normalize(np.array([1, 0, 0])), np.array([1, 0, 0]))) self.assertTrue( np.array_equal(Map.normalize(np.array([3, 4, 12])), np.array([3 / 13, 4 / 13, 12 / 13]))) self.assertRaises(ValueError, Map.normalize, (np.array([0, 0, 0]), ))
def crossover(armies, points, population, mapping): """ Permet de croiser 2 parents. Paramètres : armies : liste contenant tous les objets Army (armées alliées déjà créées) points : entier représentant les fonds disponibles pour créer l'armée population : entier représentant le nombre d'armée alliée à tester pour une génération mapping : objet Map (from mapping import Map) représentant la carte de combat Return : armies : liste contenant les objets Army après croisement """ offspring = [] for _ in range(int(population - len(armies))): parent1, parent2 = None, None while parent1 == parent2: parent1 = choice(armies) parent2 = choice(armies) army_parent1, points_used_parent1 = parent1_choice(parent1, points) army_parent2 = parent2_choice(parent2, points_used_parent1, parent1) child1 = army_parent1 + army_parent2 offspring.append( Army(Map(other_map=mapping), True, points, in_simulation=True, army_base=child1)) armies.extend(offspring) return armies
def play_select(): if channel_0_for_background_sound.get_volume() == 0 and sounds_volume != 0 and not music_muted: channel_0_for_background_sound.set_volume(sounds_volume) map_test = Map(box_size=20, nb_river=19, nb_mountain=35, nb_forest=61, nb_desert=35) points = random.randint(200, 500) left_army = Army(map_test, False, points, in_simulation=True) while run: for event in pygame.event.get(): main_events(event) screen.fill(BLACK) screen.blit(background_play_select, background_play_select_rect) if music_muted: screen.blit(sound_mute, (0, 0), (-940, -40, 1024, 768)) button("", 929, 37, 57, 57, BLACK_TRANSPARENT, "circle", unmute_music) else: screen.blit(sound_speaking, (0, 0), (-940, -40, 1024, 768)) button("", 929, 37, 57, 57, BLACK_TRANSPARENT, "circle", mute_music) display_army(left_army, 290, -140) button("", 482, 654, 55, 55, BLACK_TRANSPARENT, "circle", menu) button("OPTIMIZE", 87, 225, 281, 78, RED_TRANSPARENT, "box", play_opti, action_argument={'map_test': map_test, 'left_army': left_army, 'points': points}) button("CREATE", 87, 438, 281, 78, RED_TRANSPARENT, "box", play_create, action_argument={'map_test': map_test, 'left_army': left_army, 'points': points}) pygame.display.update() clock.tick(FPS)
def fitness(armies, left_army, mapping, points, in_simulation): """ Permet de calculer la résistance de l'armée après une simulation. Utilisation des simulations parallèles (from thread_simulation import SimulatorThreaded). Paramètres : armies : liste contenant toutes les objets Army créées left_army : objet Army (from army import Army) représentant l'armée ennemie mapping : objet Map (from mapping import Map) représentant la carte du combat points : entier représentant les fonds disponibles pour créer l'armée in_simulation : booléen (False si c'est pas une simulation, True si s'en est une) Return : armies : liste contenant les objets Army après combat """ # Thread thread_all = [ SimulatorThreaded(Map(other_map=armies[i].mapping.for_other_map()), armies[i], left_army.army_base, points, in_simulation=in_simulation) for i in range(len(armies)) ] for thread in thread_all: thread.start() for i in range(len(thread_all)): armies[i].fitness = thread_all[i].join() return armies
def setUp(self): self.hash = 'fd6069568a5d453a8572fbfafb517f14115bc093deee67554c468b61ac734d61' self.root_path = str(os.path.dirname(os.path.abspath(__file__))).replace('tests', '') self.font_path = self.root_path + 'fonts' self.font_path_fn = self.root_path + 'fonts/DejaVuSansMono.ttf' self.icon_path = self.root_path + 'icons' self.cfg_path = self.root_path + 'mapcfgs' self.img_path = self.root_path + 'mapimgs' a = Node(self.font_path_fn, self.icon_path, x=300, y=30, label='host-A', icon='Router96.png') b = Node(self.font_path_fn, self.icon_path, x=750, y=30, label='host-B', icon='Router96.png') c = Node(self.font_path_fn, self.icon_path, x=30, y=750, label='host C', icon='Router96.png') d = Node(self.font_path_fn, self.icon_path, x=750, y=750, label='HOST-D', icon='Router96.png') e = Node(self.font_path_fn, self.icon_path, x=400, y=400, label='host-E', icon='Router96.png') link_a = Link(self.font_path_fn, a, e, bandwidth=1000, width=10) link_a.data(in_bps=0, out_bps=123345123) link_b = Link(self.font_path_fn, b, e, bandwidth=100, width=15) link_b.data(in_bps=54123456, out_bps=114987654) link_c = Link(self.font_path_fn, c, e, bandwidth=10000) link_c.data(in_bps=841123456, out_bps=5147987654) link_d = Link(self.font_path_fn, d, e, bandwidth=100, width=15) link_d.data(in_bps=73456852, out_bps=987654) link_e = Link(self.font_path_fn, a, b, bandwidth=100, width=15) link_e.data(in_bps=73456852, out_bps=987654) table = Table(self.font_path_fn, x=700, y=350, dt=False) self.new_map = Map([link_a, link_b, link_c, link_d, link_e], [a, b, c, d, e], table=table, len_x=800, len_y=800)
def create_map(self, font_path_fn: str, icon_path: str): self.obj_nodes = {section: None for section in self.cfg_dict if 'node-' in section} self.obj_links = {section: None for section in self.cfg_dict if 'link-' in section} palette = self.cfg_dict['palette'] fontsize = int(self.cfg_dict['map']['fontsize']) for node in self.obj_nodes.keys(): x = int(self.cfg_dict[node]['x']) y = int(self.cfg_dict[node]['y']) if self.cfg_dict[node].get('label'): label = self.cfg_dict[node]['label'] else: label = None if self.cfg_dict[node].get('icon'): icon = self.cfg_dict[node]['icon'] else: icon = None self.obj_nodes[node] = (Node(font_path_fn, icon_path, x=x, y=y, label=label, icon=icon, fontsize=fontsize)) for link in self.obj_links.keys(): node1 = self.obj_nodes[self.cfg_dict[link]['node1']] node2 = self.obj_nodes[self.cfg_dict[link]['node2']] if self.cfg_dict[link].get('bandwidth'): bandwidth = self.cfg_dict[link]['bandwidth'] else: bandwidth = self.cfg_dict['link']['bandwidth'] if self.cfg_dict[link].get('width'): width = self.cfg_dict[link]['width'] else: width = self.cfg_dict['link']['width'] hostname = self.cfg_dict[link]['hostname'] item_in = self.cfg_dict[link]['itemin'] item_out = self.cfg_dict[link]['itemout'] self.obj_links[link] = (Link(font_path_fn, node1, node2, bandwidth=bandwidth, width=width, palette=palette, fontsize=fontsize)) data_in, data_out = self.zbx.get_item_data2(hostname, item_in, item_out) self.obj_links[link].data(in_bps=data_in, out_bps=data_out) if int(self.cfg_dict['table']['show']): table = Table(font_path_fn, x=int(self.cfg_dict['table']['x']), y=int(self.cfg_dict['table']['y']), palette=palette) else: table = None map_width = int(self.cfg_dict['map']['width']) map_height = int(self.cfg_dict['map']['height']) if self.cfg_dict['map']['bgcolor']: map_bgcolor = self.cfg_dict['map']['bgcolor'] else: map_bgcolor = None map_obj = Map(self.obj_links.values(), self.obj_nodes.values(), table=table, len_x=map_width, len_y=map_height, bgcolor=map_bgcolor) return map_obj
def create_fort(self): self.ords = Map.create() newid = self.getid(True) newfort = Fort(self.name) newfort.id = newid newfort.usr_name = self.usr_name newfort.ords = self.ords newfort.belonger_id = self.id forts[newid] = newfort return newid
def test_positions_close(self): """ Test the method are_positions_close """ self.assertTrue( Map.are_positions_close(np.array([100, 100, 100]), np.array([100, 100, 110]))) self.assertTrue( Map.are_positions_close(np.array([100, 102, 104]), np.array([100, 110, 110]))) self.assertTrue( Map.are_positions_close(np.array([98, 102, 103]), np.array([102, 99, 97]))) self.assertFalse( Map.are_positions_close(np.array([100, 111, 100]), np.array([100, 100, 100]))) self.assertFalse( Map.are_positions_close(np.array([104, 101, 99]), np.array([97, 96, 105])))
def __init__(self, params, cam): self.params = params self.cam = cam self.motion_model = MotionModel() self.map = Map() self.preceding = None # last keyframe self.current = None # current frame self.status = defaultdict(bool) self.optimizer = BundleAdjustment() self.bundle_adjustment = LocalBA() self.min_measurements = params.pnp_min_measurements self.max_iterations = params.pnp_max_iterations self.timer = RunningAverageTimer() self.lines = True
def test_point_on_surface(self): """ Test the method is_point_on_surface """ self.assertTrue( Map.is_point_on_surface( np.array([1, 1, 0]), np.array([[0, 5, 2], [0, 0, 3], [0, 0, 0]]))) self.assertTrue( Map.is_point_on_surface( np.array([1, 1, 0]), np.array([[3, 0, -1, 0, 4], [3, 2, 0, -3, -1], [0, 0, 0, 0, 0]]))) self.assertFalse( Map.is_point_on_surface( np.array([1, 1, 1]), np.array([[-1, 1, 4, 4], [3, -1, 0, 5], [0, 0, 0, 0]]))) self.assertFalse( Map.is_point_on_surface( np.array([3, -1, 0]), np.array([[-1, 1, 4, 4], [3, -1, 0, 5], [0, 0, 0, 0]])))
def __init__(self, name, seviye): self.getid() self.name = name global camps self.seviye = seviye if seviye == 0: seviye = 1 else: self.seviye = seviye self.ords = Map.create() camps[self.id] = self save()
def init_simu(population, in_simulation, mapping, points): """ Permet de créer les premières armées. Paramètres : population : entier représentant le nombre d'armée alliée à tester pour une génération in_simulation : booléen (False si c'est pas une simulation, True si s'en est une) mapping : objet Map (from mapping import Map) représentant la carte de combat points : entier représentant les fonds disponibles pour créer l'armée """ return [ Army(Map(other_map=mapping), True, points, in_simulation=in_simulation) for _ in range(population) ]
class TestMap(TestCase): def setUp(self): self.hash = '43228a6d34e15561dcb179a9e4388489e4634093348a57f34801a12fd548f203' self.root_path = str(os.path.dirname(os.path.abspath(__file__))).replace('tests', '') self.font_path = self.root_path + 'fonts' self.font_path_fn = self.root_path + 'fonts/DejaVuSansMono.ttf' self.icon_path = self.root_path + 'icons' self.cfg_path = self.root_path + 'mapcfgs' self.img_path = self.root_path + 'mapimgs' a = Node(self.font_path_fn, self.icon_path, x=300, y=30, label='host-A', icon='Router96.png') b = Node(self.font_path_fn, self.icon_path, x=750, y=30, label='host-B', icon='Router96.png') c = Node(self.font_path_fn, self.icon_path, x=30, y=750, label='host C', icon='Router96.png') d = Node(self.font_path_fn, self.icon_path, x=750, y=750, label='HOST-D', icon='Router96.png') e = Node(self.font_path_fn, self.icon_path, x=400, y=400, label='host-E', icon='Router96.png') link_a = Link(self.font_path_fn, a, e, bandwidth=1000, width=10) link_a.data(in_bps=0, out_bps=123345123) link_b = Link(self.font_path_fn, b, e, bandwidth=100, width=15) link_b.data(in_bps=54123456, out_bps=114987654) link_c = Link(self.font_path_fn, c, e, bandwidth=10000) link_c.data(in_bps=841123456, out_bps=5147987654) link_d = Link(self.font_path_fn, d, e, bandwidth=100, width=15) link_d.data(in_bps=73456852, out_bps=987654) link_e = Link(self.font_path_fn, a, b, bandwidth=100, width=15) link_e.data(in_bps=73456852, out_bps=987654) table = Table(self.font_path_fn, x=700, y=350, dt=False) self.new_map = Map([link_a, link_b, link_c, link_d, link_e], [a, b, c, d, e], table=table, len_x=800, len_y=800) def test_map(self): warnings.simplefilter("ignore", ResourceWarning) self.new_map.do() # new_map.show() self.new_map.save_img(self.img_path + '/test.png') self.assertEqual(self.hash, hashlib.sha256(open(self.img_path + '/test.png', 'rb').read()).hexdigest())
def test_enemy_base(self): map = Map() self.assertFalse(map.enemy_base_found()) map.update_tiles( [TileUpdate({ "x": 0, "y": 0, "units": [{ "type": "base" }] })]) self.assertTrue(map.enemy_base_found())
def create_map(self, font_path_fn, icon_path): palette = [self.cfg_dict['palette'][key] for key in sorted(self.cfg_dict['palette'])] fontsize = int(self.cfg_dict['map']['fontsize']) for node in self.obj_nodes.keys(): x = int(self.cfg_dict[node]['x']) y = int(self.cfg_dict[node]['y']) label = self.cfg_dict[node]['label'] icon = self.cfg_dict[node]['icon'] self.obj_nodes[node] = (Node(font_path_fn, icon_path, x=x, y=y, label=label, icon=icon, fontsize=fontsize)) for link in self.obj_links.keys(): node1 = self.obj_nodes[self.cfg_dict[link]['node1']] node2 = self.obj_nodes[self.cfg_dict[link]['node2']] bandwidth = int(self.cfg_dict[link]['bandwidth']) width = int(self.cfg_dict[link]['width']) hostname = self.cfg_dict[link]['hostname'] item_in = self.cfg_dict[link]['itemin'] item_out = self.cfg_dict[link]['itemout'] self.obj_links[link] = (Link(font_path_fn, node1, node2, bandwidth=bandwidth, width=width, palette=palette, fontsize=fontsize)) data_in, data_out = self.zbx.get_item_data2(hostname, item_in, item_out) self.obj_links[link].data(in_bps=data_in, out_bps=data_out) if int(self.cfg_dict['table']['show']): table = Table(font_path_fn, x=int(self.cfg_dict['table']['x']), y=int(self.cfg_dict['table']['y']), palette=palette) else: table = None map_width = int(self.cfg_dict['map']['width']) map_height = int(self.cfg_dict['map']['height']) if self.cfg_dict['map']['bgcolor']: map_bgcolor = self.cfg_dict['map']['bgcolor'] else: map_bgcolor = None map_obj = Map(self.obj_links.values(), self.obj_nodes.values(), table=table, len_x=map_width, len_y=map_height, bgcolor=map_bgcolor) return map_obj
#!/usr/bin/python import sys from communication import UpdateHandler, accept_connections from mapping import Map from state import UnitManager, GameStateManager from strategy import UnitStrategyFactory, AIStrategy if __name__ == "__main__": port = int(sys.argv[1]) if (len(sys.argv) > 1 and sys.argv[1]) else 9090 host = '' game_map = Map() unitManager = UnitManager(UnitStrategyFactory(), game_map) stateManager = GameStateManager(unitManager, game_map) gameStrategy = AIStrategy(unitManager, game_map) handler = UpdateHandler(stateManager, gameStrategy) accept_connections(host, port, handler)
self.attack_range = 4 self.armor = 25 self.cost = 10 self.enter_in_box(box) if __name__ == '__main__': from mapping import Map message = """0 - Test sur les unités (comabt entre 2 unités) 1 - Test des malus/bonus (vérification de l'application des malus et des bonus liées aux cases)""" print(message) choix = int(input('Quel test voulez-vous effectuer ? ')) map_test = Map(nb_river=200) ##### TEST SUR LES UNITÉS ##### if choix == 0: print("Caractéristiques bowman1 :") bowman1 = Bowman(False, map_test.research_one_box((10, 10)), mapping=map_test) # Unité ennemie print("Position bowman1 : x =", bowman1.x, "y =", bowman1.y) print("HP bowman1 :", bowman1.hp) print("Dégâts bowman1 :", bowman1.damage) print("Mouvement bowman1 :", bowman1.movement) print("Caractéristiques warrior1 :") warrior1 = Warrior(True, map_test.research_one_box((1010, 10)), mapping=map_test) # Unité alliée print("Position warrior1 : x =", warrior1.x, "y =", warrior1.y) print("PV warrior1 :", warrior1.hp) print("Degats warrior1 :", warrior1.damage)
for unit in self.army_base: dico[unit[0]] += 1 return dico if __name__ == '__main__': from mapping import Map message = """0 - Armée alliée 1 (en simulation) 1 - Armée alliée 2 (en réel) 2 - Armée ennemie 1 (en simulation) 3 - Armée ennemie 2 (en réel)""" print(message) choix = int(input('Quel test voulez-vous effectuer ? ')) map_test = Map(nb_river=200) ##### TEST 0 SUR LES ARMÉES ##### if choix == 0: army_test = Army(map_test, True, 300, in_simulation=True) ##### TEST 1 SUR LES ARMÉES ##### elif choix == 1: army_test = Army(map_test, True, 300, in_simulation=False) ##### TEST 2 SUR LES ARMÉES ##### elif choix == 2: army_test = Army(map_test, False, 300, in_simulation=True) ##### TEST 3 SUR LES ARMÉES ##### elif choix == 3:
import json from mapping import Map from NaturalClasses import NaturalClasses from csv_to_json import csv_to_json from settings import FILEPATH with open(filepath, encoding='utf-8', mode="r") as f: try: data = json.loads(f.read()) except: data = json.loads(csv_to_json(filepath)) with open(filepath.replace('.csv', '.txt'), "w", encoding='utf-8') as f: f.write(csv_to_json(filepath)) map = Map(data) nc = NaturalClasses(map, 3) with open("Natural classes.txt", "w", encoding='utf-8') as f: nc.output(f) with open("Feature combinations with no segments.txt", "w", encoding='utf-8') as f: f.write('\n'.join([ r for r in nc.featureCombo_to_segments if not nc.featureCombo_to_segments[r] ])) with open("Redundant natural classes.txt", "w", encoding="utf-8") as f: nc.output_redundant(f)
new_unit ] + single_army.army_base[index + 1:] break # Permet de muter seulement une unité dans l'armée single_army.create_army_from_base() # Recréation des armées return armies if __name__ == '__main__': from time import time population = 10 generations = 25 debut = time() # Création des constantes (listes de positions dispo, quantité de fonds dispo, ...) map_test = Map() other_map = map_test.for_other_map() points = 300 in_simulation = True # Choix ordinateur left_army = Army(map_test, False, points) best_army = genetic_algorithm_best_army(population, generations, in_simulation, other_map, points, left_army) print(best_army.army_base) print("Durée totale :", int(time() - debut), 'secondes.')
from time import time from mapping import Map message = """0 - Test sur l'exécution des simulations en parallèle""" print(message) choix = int(input('Quel test voulez-vous faire ? ')) debut_time = time() ##### TEST SUR LES SIMULATIONS PARALLELES ##### if choix == 0: population = 8 in_simulation = True # Création des constantes (carte, quantité de fonds dispo, ...) map_test = Map() other_map = map_test.for_other_map() points = 300 # Choix ordinateur left_army = Army(map_test, False, points) all_right_armies = [ Army(Map(other_map=other_map), True, points, in_simulation=in_simulation) for i in range(population) ] # Création des threads thread_all = [
print('Configuration:') print(' ', args) ### Load data and create world & robot rgbd_dir = os.path.join('data', 'dataRGBD') result_dir = 'results' if not os.path.exists(result_dir): os.mkdir(result_dir) plots_save_path = os.path.join(result_dir, str(args.dataset)) plots_save_path = check_and_rename(plots_save_path) os.mkdir(plots_save_path) data = load_and_process_data(dataset=args.dataset, texture_on=args.texture_on) world = Map(-10, -10, 15, 15, res=args.resolution, texture_on=args.texture_on) initial_state = ((0, 0), 0) N_particles = args.N_particles robot = Robot(initial_state, N_particles) # initialize map world.update_map(data['lidar_coords'][0], np.matmul(robot.T_wb, robot.T_bl)) for idx_t in tqdm.trange(1, len(data['stamps']), desc='Progress', unit='frame'): # for idx_t in tqdm.trange(1000, 1050): # extract sensor data
if __name__ == '__main__': from time import time from mapping import Map from army import Army message = """0 - Simple simulation (avec choix possible) 1 - Multiples simulations (choix impossible, exécution type algorithme génétique)""" print(message) choix = int(input("Choix de simulation : ")) debut_all = time() # Création des constantes (listes de positions dispo, quantité de fonds dispo, ...) map_test = Map() other_map = map_test.for_other_map() # print(other_map) points = 300 # Choix ordinateur left_army = Army(map_test, False, points) ##### SIMPLE SIMULATION ##### if choix == 0: # Choix joueur right_army = Army(map_test, True, points) nettoyageConsole() # Lancement simulation
def play(other_map, points, left_army_army_base, right_army_army_base, left_army=None, right_army=None, map_test=None, player_turn=None, object_to_move=[]): global effect_played, sounds_volume, pause channel_1_for_fight_effect_sound.unpause() effect_played = True sounds_volume = 0.4 channel_0_for_background_sound.set_volume(sounds_volume) channel_1_for_fight_effect_sound.set_volume(2 * sounds_volume) if music_paused: channel_1_for_fight_effect_sound.pause() if music_muted: mute_music() if map_test is None: map_test = Map(other_map=other_map) if left_army is None: left_army = Army(map_test, False, points, army_base=left_army_army_base) if right_army is None: right_army = Army(map_test, True, points, army_base=right_army_army_base) if player_turn is None: player_turn = False selected_unit = None selected_unit_boxes_movement = None selected_unit_boxes_attack = None unit_in_boxes_attack = None i = 0 while run: mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() for event in pygame.event.get(): main_events(event) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: if pause: Continue() else: pause = True paused(left_army, right_army, other_map, points, map_test, player_turn, object_to_move) if player_turn: if object_to_move == []: object_to_move = [unit for unit in right_army.full_army] else: in_progress = left_army_attack(i, left_army, right_army, True) i += 1 if i == len(left_army.full_army): i = 0 player_turn = True pygame.time.wait(int(random.uniform(100, 250))) screen.fill(BLACK) if selected_unit_boxes_movement is None and selected_unit is not None: selected_unit_boxes_movement = selected_unit.movement_boxes_valid() if selected_unit_boxes_attack is None and selected_unit is not None: unit_in_boxes_attack, selected_unit_boxes_attack = selected_unit.attack_boxes_valid() for box in map_test.boxes: if selected_unit is not None and selected_unit_boxes_attack is not None: if box in unit_in_boxes_attack: pygame.gfxdraw.box(screen, [box.box_position[0], box.box_position[1], box.box_size, box.box_size], RED) elif box in selected_unit_boxes_attack: pygame.gfxdraw.box(screen, [box.box_position[0], box.box_position[1], box.box_size, box.box_size], box.background_color_attack) else: pygame.gfxdraw.box(screen, [box.box_position[0], box.box_position[1], box.box_size, box.box_size], box.background_color) else: pygame.gfxdraw.box(screen, [box.box_position[0], box.box_position[1], box.box_size, box.box_size], box.background_color) if box.box_position[0] <= mouse[0] < box.box_position[0] + box.box_size + 2 and box.box_position[1] <= mouse[1] < box.box_position[1] + box.box_size + 2: pygame.gfxdraw.box(screen, [box.box_position[0], box.box_position[1], box.box_size, box.box_size], box.background_color_hover) if click[0]: if box.object is not None and selected_unit is None and box.object in object_to_move: selected_unit = box.object if selected_unit is not None and selected_unit_boxes_movement is not None and box in selected_unit_boxes_movement: selected_unit.out_box() selected_unit.x, selected_unit.y = box.center_box selected_unit.enter_in_box(box) object_to_move.remove(selected_unit) selected_unit_boxes_movement = None selected_unit_boxes_attack = None unit_in_boxes_attack = None selected_unit = None if object_to_move == []: player_turn = False pygame.time.wait(100) if selected_unit is not None and unit_in_boxes_attack is not None and box in unit_in_boxes_attack: enemy_index = left_army.full_army.index(box.object) selected_unit.attack(left_army.full_army[enemy_index]) if left_army.full_army[enemy_index].die(): left_army.full_army.remove(left_army.full_army[enemy_index]) box.object = None object_to_move.remove(selected_unit) selected_unit_boxes_movement = None selected_unit_boxes_attack = None unit_in_boxes_attack = None selected_unit = None if object_to_move == []: player_turn = False pygame.time.wait(100) if click[2]: if selected_unit == box.object: selected_unit = None selected_unit_boxes_movement = None selected_unit_boxes_attack = None unit_in_boxes_attack = None for unit in left_army.full_army: draw_units(unit, BLACK, circle_radius=5) for unit in right_army.full_army: if selected_unit is None: draw_units(unit, WHITE) else: if unit == selected_unit and selected_unit_boxes_movement is not None: for box in selected_unit_boxes_movement: draw_units(unit, WHITE, possible_movement=box) draw_units(unit, (0, 102, 102)) else: draw_units(unit, (0, 102, 102)) if left_army.full_army == [] or right_army.full_army == []: effect_played = False channel_0_for_background_sound.set_volume(0) channel_1_for_fight_effect_sound.pause() game_over(left_army, right_army) pygame.display.update() clock.tick(FPS)
class Tracker(object): def __init__(self, params, cam): self.params = params self.cam = cam self.motion_model = MotionModel() self.map = Map() self.preceding = None # last keyframe self.current = None # current frame self.status = defaultdict(bool) self.optimizer = BundleAdjustment() self.bundle_adjustment = LocalBA() self.min_measurements = params.pnp_min_measurements self.max_iterations = params.pnp_max_iterations self.timer = RunningAverageTimer() self.lines = True def initialize(self, frame): keyframe = frame.to_keyframe() mappoints, measurements = keyframe.create_mappoints_from_triangulation( ) assert len(mappoints) >= self.params.init_min_points, ( 'Not enough points to initialize map.') keyframe.set_fixed(True) self.extend_graph(keyframe, mappoints, measurements) if self.lines: maplines, line_measurements = keyframe.create_maplines_from_triangulation( ) print(f'Initialized {len(maplines)} lines') for mapline, measurement in zip(maplines, line_measurements): self.map.add_mapline(mapline) self.map.add_line_measurement(keyframe, mapline, measurement) keyframe.add_measurement(measurement) mapline.add_measurement(measurement) self.preceding = keyframe self.current = keyframe self.status['initialized'] = True self.motion_model.update_pose(frame.timestamp, frame.position, frame.orientation) # def clear_optimizer(self): # # Calling optimizer.clear() doesn't fully clear for some reason # # This prevents running time from scaling linearly with the number of frames # self.optimizer = BundleAdjustment() # self.bundle_adjustment = LocalBA() def refine_pose(self, pose, cam, measurements): assert len(measurements) >= self.min_measurements, ( 'Not enough points') self.optimizer = BundleAdjustment() self.optimizer.add_pose(0, pose, cam, fixed=False) for i, m in enumerate(measurements): self.optimizer.add_point(i, m.mappoint.position, fixed=True) self.optimizer.add_edge(0, i, 0, m) self.optimizer.optimize(self.max_iterations) return self.optimizer.get_pose(0) def update(self, i, left_img, right_img, timestamp): # Feature extraction takes 0.12s origin = g2o.Isometry3d() left_frame = Frame(i, origin, self.cam, self.params, left_img, timestamp) right_frame = Frame(i, self.cam.compute_right_camera_pose(origin), self.cam, self.params, right_img, timestamp) frame = StereoFrame(left_frame, right_frame) if i == 0: self.initialize(frame) return # All code in this functions below takes 0.05s self.current = frame predicted_pose, _ = self.motion_model.predict_pose(frame.timestamp) frame.update_pose(predicted_pose) # Get mappoints and measurements take 0.013s local_mappoints = self.get_local_map_points(frame) print(local_mappoints) if len(local_mappoints) == 0: print('Nothing in local_mappoints! Exiting.') exit() measurements = frame.match_mappoints(local_mappoints) # local_maplines = self.get_local_map_lines(frame) # line_measurements = frame.match_maplines(local_maplines) # Refined pose takes 0.02s try: pose = self.refine_pose(frame.pose, self.cam, measurements) frame.update_pose(pose) self.motion_model.update_pose(frame.timestamp, pose.position(), pose.orientation()) tracking_is_ok = True except: tracking_is_ok = False print('tracking failed!!!') if tracking_is_ok and self.should_be_keyframe(frame, measurements): # Keyframe creation takes 0.03s self.create_new_keyframe(frame) # self.optimize_map() def optimize_map(self): """ Python doesn't really work with the multithreading model, so just putting optimization on the main thread """ adjust_keyframes = self.map.search_adjust_keyframes() # Set data time increases with iterations! # self.timer = RunningAverageTimer() self.bundle_adjustment = LocalBA() self.bundle_adjustment.optimizer.set_verbose(True) # with self.timer: self.bundle_adjustment.set_data(adjust_keyframes, []) self.bundle_adjustment.optimize(2) self.bundle_adjustment.update_poses() self.bundle_adjustment.update_points() def extend_graph(self, keyframe, mappoints, measurements): self.map.add_keyframe(keyframe) for mappoint, measurement in zip(mappoints, measurements): self.map.add_mappoint(mappoint) self.map.add_point_measurement(keyframe, mappoint, measurement) keyframe.add_measurement(measurement) mappoint.add_measurement(measurement) def create_new_keyframe(self, frame): keyframe = frame.to_keyframe() keyframe.update_preceding(self.preceding) mappoints, measurements = keyframe.create_mappoints_from_triangulation( ) self.extend_graph(keyframe, mappoints, measurements) if self.lines: maplines, line_measurements = keyframe.create_maplines_from_triangulation( ) frame.visualise_measurements(line_measurements) print(f'New Keyframe with {len(maplines)} lines') for mapline, measurement in zip(maplines, line_measurements): self.map.add_mapline(mapline) self.map.add_line_measurement(keyframe, mapline, measurement) keyframe.add_measurement(measurement) mapline.add_measurement(measurement) self.preceding = keyframe def get_local_map_points(self, frame): checked = set() filtered = [] # Add in map points from preceding and reference for pt in self.preceding.mappoints(): # neglect can_view test # if pt in checked or pt.is_bad(): # print('bad') # continue pt.increase_projection_count() filtered.append(pt) return filtered def get_local_map_lines(self, frame): checked = set() filtered = [] # Add in map points from preceding and reference for ln in self.preceding.maplines(): # neglect can_view test if ln in checked or ln.is_bad(): continue ln.increase_projection_count() filtered.append(ln) return filtered def should_be_keyframe(self, frame, measurements): n_matches = len(measurements) n_matches_ref = len(self.preceding.measurements()) return ((n_matches / n_matches_ref) < self.params.min_tracked_points_ratio) or n_matches < 20