def check_space(internal, ha_offset_sec=0): internal = { 'ha': internal['ha'] + ha_offset_sec / 3600, 'de': internal['de'], } park_internal = altaz_to_internal( PARK_ALTAZ, get_chirality(), ) try: get_path(internal, park_internal) except NoPath: return False return True
def get_next_command(current_cords, target_cords): source = ",".join([str(x) for x in current_cords]) destination = ",".join([str(x) for x in target_cords]) path_list = get_path(source, destination) commands = [] if not path_list: return stop() for path in path_list: if 'F' in path: print("path val", path) value = 100 # value = int(path.replace('F', '0')) commands.append(move_forward(value)) commands.append(look_left()) commands.append(look_left()) commands.append(look_left()) commands.append(look_straight()) commands.append(look_right()) commands.append(look_right()) commands.append(look_right()) elif 'B' in path: commands.append(move_back()) elif 'L' in path: commands.append(turn_left()) elif 'R' in path: commands.append(turn_right()) print(commands) return commands
def get_file_path(filepath, filename): if filepath == False: _path = path.get_path()[1] else: _path = filepath file_list = find_all_file(_path) print(file_list[0][2][0])
def __init__(self, filename): # Der with Ausdruck ist unglaublich praktisch, # da Dateien damit automatisch geschlossen werden. with open(get_path(filename), 'r') as files: self.et = ET.parse(files) self.e = self.et.getroot() # Ausnahmebehandlung für die spawns.xml if filename != "spawns.xml": self.b = self.set_subelement()
def _loop_calculate_path_target(self): self.current['path'] = dagor_path.get_path( self.current['internal'], self.config['target_internal'], force=self.config['force'], ) self.current['path'] = self.update_path( self.current['path'], self.current['internal']) self.path_target = self.current['path'][1]
def move(self): bases_to_go_to = filter(lambda b: b.ownerId is not self.country.ownerId, self.all_bases.values()) print "bases_to_go_to:", bases_to_go_to for p in self.my_planes.values(): print "Plane state:", p.state() if p.state() == Plane.State.IDLE or p.state() == Plane.State.AT_AIRPORT: print "This plane is idle!" res = get_path(p, bases_to_go_to) if res: self.game.sendCommand(DropMilitarsCommand(p, res[0], 1))
def load_file(self,filename): '''Loads simple string table entries from a file. The file is a simple text file, lines beginning with ; are ignored. Other lines are split at the first space into a command and translation.''' f=codecs.open(os.path.join(get_path(),filename),"r","utf-8") for l in f.readlines(): if l[0]==";" or l[0]=="\n": continue words=l.split(" ") self.table[words[0]]=(" ".join(words[1:])).strip("\r\n") f.close()
def greedy(puzzle, puzzle_goal, heuristic): pq = PriorityQueue() visited = {} ''' Unique value for PQ because if there is equal priority of 2 items PQ will try compare items in PQ and you cant compare classes so it will compare unique values''' unique = count() start_state = State(puzzle) #First state does not have parent state and last operator move_cost = cost(puzzle, puzzle_goal, heuristic) #Calculate cost with chosen heuristic pq.put(((move_cost, next(unique)), start_state)) #Insert first state into PQ while True: if pq.empty(): print(f"Searched {next(unique)} states.") return None, None current_state = pq.get()[1] #Get state with lowest cost from PQ if is_goal(current_state.puzzle, puzzle_goal): print(f"Searched {next(unique)} states.") return get_path(current_state) hashable_puzzle = tuple([tuple(row) for row in current_state.puzzle]) if hashable_puzzle not in visited: visited[hashable_puzzle] = hashable_puzzle empty_box = find_box(current_state.puzzle, 0) #Generate new states and add to pq if it is possible to move up, down, left, right next_puzzle = [] if(current_state.last_operator != "down"): next_puzzle = up(current_state.puzzle, empty_box) if (next_puzzle): next_state = State(next_puzzle, current_state, "up") move_cost = cost(next_puzzle, puzzle_goal, heuristic) pq.put(((move_cost, next(unique)), next_state)) if (current_state.last_operator != "up"): next_puzzle = down(current_state.puzzle, empty_box) if (next_puzzle): next_state = State(next_puzzle, current_state, "down") move_cost = cost(next_puzzle, puzzle_goal, heuristic) pq.put(((move_cost, next(unique)), next_state)) if (current_state.last_operator != "right"): next_puzzle = left(current_state.puzzle, empty_box) if (next_puzzle): next_state = State(next_puzzle, current_state, "left") move_cost = cost(next_puzzle, puzzle_goal, heuristic) pq.put(((move_cost, next(unique)), next_state)) if (current_state.last_operator != "left"): next_puzzle = right(current_state.puzzle, empty_box) if (next_puzzle): next_state = State(next_puzzle, current_state, "right") move_cost = cost(next_puzzle, puzzle_goal, heuristic) pq.put(((move_cost, next(unique)), next_state))
def _open_texture(self, files): # Verhindert das Texturen mehrfach in den Speicher geladen # werden if files not in Texture.files: Texture.files.append(files) self._image = pyglet.image.load(get_path(files)) Texture.textures.append(self._image) else: count = 0 for i in Texture.files: if i == files: self._image = Texture.textures[count] break count += 1
def __init__(self, player): self.active = 0 self.fail = False self.default_str = "A_LV.xml" self._random_list = collections.deque() self.reverse_order_list = collections.deque() ort = sorted(os.listdir(get_path("spsh_xml"))) # Liest alle möglichen Level im Ordner aus # und weißt jeden eine Nummer zu self.level_dict = { k: value for k, value in enumerate(ort) if not value.startswith("s") } self.random_level() super(Level, self).__init__("spsh_xml/" + self.default_str) self.npc = npc.NpcFactory(self.level_dict[self.active]) self.player = player self.player.set_position(50, 500) self.key = misc.Key(400, 300)
def update_mob(self, mob, level): if mob.state == MobState.WANDERING: if mob.target is None or \ mob.target == mob.pos: if mob.leader and mob.leader.target: mob.target = mob.leader.target else: potential_targets = list( pos for pos in fov.calculate_fov(mob.pos, 5, level) if not level[pos].blocked) mob.target = random.choice(potential_targets) wander_path = path.get_path(mob.pos, mob.target, level) if wander_path: mob.move_to(wander_path[0]) if mob.pos.distance(mob.target) <= 1: mob.state = MobState.IDLE elif mob.state == MobState.IDLE: if mob.leader is None: if random.randint(1, 10) == 1: mob.state = MobState.WANDERING else: if mob.leader and mob.leader.state != MobState.IDLE: mob.state = mob.leader.state
def conquer(game, plane, bases, min_fuel, nb_drop=MINIMUM_BASE_GARRISON + MINIMUM_CAPTURE_GARRISON + 0.042 + 4): """ Description of conquer. Pop element from *bases*. Give a copy if you want to prevent modification. Arguments: game -- Game to use plane -- Plane used to conquer bases -- Conquerable bases min_fuel -- Amount of minimum fuel to release nb_drop -- Number of militar units to drop """ res = get_path(plane, bases, None, 1) if res: b = res[0] if b.id() in context.my_bases: b = context.my_bases[b.id()] deliver_petrol(game, plane, b, nb_drop, b.fuelInStock() - min_fuel) else: max_mili = plane.militaryInHold() mili = min(nb_drop, max_mili) try: n = b.militaryGarrison() except AttributeError: n = 0 if n != 0: mili = max(mili, n) mili = min(mili, plane.militaryInHold()) if not is_near(plane.position(), b.position(), 0.42): game.sendCommand( DropMilitarsCommand(plane, b, mili)) else: game.sendCommand( DropMilitarsCommand(plane, b, mili))
def __update_path(self, i): self.path = get_path() # TODO (3) make prettier # if r < 1/6: # logger.info('Environment: normal short') # self.path.slice(None, 20) # elif r < 2/6: # logger.info('Environment: backwards short') # self.path.slice(70, None) # self.path.invert() # elif if i % 4 is 0: logger.info('Environment: normal full') pass elif i % 4 is 1: logger.info('Environment: backwards full') self.path.invert() elif i % 4 is 2: logger.info('Environment: normal turn (left)') self.path.slice(30, 60) elif i % 4 is 3: logger.info('Environment: backwards turn (right)') self.path.slice(40, 70) self.path.invert()
def __init__(self, cuda_id=0, n_epochs=1000, batch_size=4, num_workers=4, optimizer='adam', lr=1e-2, weight_decay=0, model_name='simple', set_type='angles', is_balance_training=True, is_tiny=False, is_divergent_set=False, root_prefix=None, copy_tmp=None, init_model_path=None, is_snp=False): self.is_snp = is_snp self.n_epochs = n_epochs if torch.cuda.is_available(): print("THIS IS CUDA!!!!") dev_str = "cuda:" + str(cuda_id) else: dev_str = 'cpu' print(dev_str) self.device = torch.device(dev_str) self.fname, self.results_dir_root = get_path(set_type, platform=root_prefix) if copy_tmp is not None: self.fname = copy_data_to_tmp(self.fname, copy_tmp) if self.is_snp: return_label = False return_snp = True criterion = nn.MultiLabelSoftMarginLoss() else: return_label = True return_snp = False criterion = nn.CrossEntropyLoss() self.gen = SkelTrainer(fname=self.fname, is_balance_training=is_balance_training, is_tiny=is_tiny, is_divergent_set=is_divergent_set, return_label=return_label, return_snp=return_snp) self.loader = DataLoader(self.gen, batch_size=batch_size, collate_fn=collate_fn, num_workers=num_workers) self.num_classes = self.gen.num_classes self.embedding_size = self.gen.embedding_size if model_name == 'darknet': self.model = Darknet([1, 2, 2, 2, 2], self.num_classes) elif model_name == 'simple': self.model = CNNClf(self.num_classes) elif model_name == 'simple1d': self.model = CNNClf1D(self.embedding_size, self.num_classes) elif model_name == 'drn111111': self.model = drn111111(self.num_classes) elif model_name == 'simpledilated': self.model = SimpleDilated(self.num_classes) elif model_name == 'simpledilated1d': self.model = SimpleDilated1D(self.embedding_size, self.num_classes) else: raise ValueError('Invalid model name {}'.format(model_name)) if init_model_path: assert set_type in init_model_path if not os.path.exists(init_model_path): init_model_path = os.path.join(self.results_dir_root, init_model_path) state = torch.load(init_model_path, map_location=dev_str) self.model.load_state_dict(state['state_dict']) model_name = 'R_' + model_name self.lr_scheduler = None if optimizer == 'adam': self.optimizer = torch.optim.Adam(self.model.parameters(), lr=lr, weight_decay=weight_decay) elif optimizer == 'sgd': self.optimizer = torch.optim.SGD(self.model.parameters(), lr=lr, momentum=0.9, weight_decay=weight_decay) #self.lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, 'min', patience = 10) else: raise ValueError('Invalid optimizer name {}'.format(optimizer)) log_dir_root = os.path.join(self.results_dir_root, 'logs') add_postifx = '' if is_tiny: print("It's me, tiny-log!!!") log_dir_root = os.path.join(self.results_dir_root, 'tiny_log') add_postifx = '_tiny' elif is_divergent_set: print("Divergent set") log_dir_root = os.path.join(self.results_dir_root, 'log_divergent_set') add_postifx = '_div' if self.is_snp: log_dir_root = log_dir_root + '_snp' now = datetime.datetime.now() bn = now.strftime('%Y%m%d_%H%M%S') + '_' + model_name bn += add_postifx bn = '{}_{}_{}_lr{}_wd{}_batch{}'.format(set_type, bn, optimizer, lr, weight_decay, batch_size) print(bn) self.log_dir = os.path.join(log_dir_root, bn) self.logger = SummaryWriter(log_dir=self.log_dir) self.criterion = criterion self.model = self.model.to(self.device)
from flow import SkelTrainer, DIVERGENT_SET import tqdm if __name__ == '__main__': set_type = 'angles' #set_type = 'AE_emb32_20180613_l1' #set_type = 'AE2DWithSkels32_emb32_20180620' #model_path = 'logs/angles_20180531_125503_R_simpledilated_sgd_lr0.0001_wd0_batch8' #model_path = 'log_divergent_set/AE2DWithSkels32_emb32_20180620_20180622_121637_simpledilated1d_div_adam_lr1e-05_wd0_batch8' #model_path = 'log_divergent_set/AE_emb32_20180613_l1_20180620_002605_simpledilated1d_div_adam_lr0.0001_wd0_batch8' set_type = 'SWDB_angles' model_path = 'logs/SWDB_angles_20180627_184430_simpledilated_sgd_lr0.001_wd0.0001_batch8' fname, results_dir_root = get_path(set_type) model_path = os.path.join(results_dir_root, model_path, 'model_best.pth.tar') bn = model_path.split(os.sep)[-2] parts = bn[len(set_type) + 1:].split('_') model_name = parts[3] if parts[2] == 'R' else parts[2] save_path = os.path.join(results_dir_root, 'maps_clf', bn) if not os.path.exists(save_path): os.makedirs(save_path) cuda_id = 2
def __init__(self): self.w_width = 864 self.w_height = 640 self.start = True self.help = False self.trans = 1.0 self.trans_bool = True self.pos_menu = 0 config = pyglet.gl.Config(sample_buffers=1, samples=4, double_buffer=True, debug=False) super(GameWindow, self).__init__(self.w_width, self.w_height, config=config, vsync=False) if not debug: self.set_fullscreen() self.set_caption("Dungeon Runner") init_gl() # Instanzen des Spielers, der Lebensanzeige # und der Spielwelt werden erstellt self.player = player.Player() self.heartbar = misc.Heartbar() self.level = world.Level(self.player) # Hintergrundbilder des Menüs werden geladen self.menu_start = pyglet.image.load(get_path("Start.png")) self.menu_help = pyglet.image.load(get_path("Hilfe.png")) # Font wird aus der Datei geladen pyglet.font.add_file(get_path("font/Cardinal.ttf")) cardinal_s70 = pyglet.font.load("Cardinal", size=70, bold=False, italic=False) cardinal_s40 = pyglet.font.load("Cardinal", size=40, bold=False, italic=False) # Erstellen von Unicode Strings text_1 = u"~ Spiel ~" text_2 = u"~ Hilfe ~" text_3 = u"~ Ende ~" text_win = u"Gewonnen!" # Setzt die die Strings auf eine bestimmte Größe glyph_3 = cardinal_s40.get_glyphs(text_1) glyph_4 = cardinal_s40.get_glyphs(text_2) glyph_5 = cardinal_s40.get_glyphs(text_3) glyph_6 = cardinal_s70.get_glyphs(text_win) # Strings werden zu Glypen # um durch OpenGL darstellbar zu werden self.glyph_str_3 = GlyphString(text_1, glyph_3, self.w_width / 2 - 75, self.w_height / 2 - 50) # Start self.glyph_str_4 = GlyphString(text_2, glyph_4, self.w_width / 2 - 75, self.w_height / 2 - 150) # Hilfe self.glyph_str_5 = GlyphString(text_3, glyph_5, self.w_width / 2 - 75, self.w_height / 2 - 250) self.glyph_str_6 = GlyphString(text_win, glyph_6, 290, self.w_height / 2) # Fügt den KeyStateHandler zu den Events hinzu self.keys = pyglet.window.key.KeyStateHandler() self.push_handlers(self.keys) # Setzt die Wiederholungsrate der tick Methode und Animatione # fest, sowie die maximale Bildwiederholungsrate pyglet.clock.schedule_interval(self.tick, 1 / 60.) pyglet.clock.schedule_interval(self.on_animate, 1 / 5.) pyglet.clock.set_fps_limit(60.)