def get_selected_configuration(): try: return configurations[command_line.args.configuration] except: ui.fatal( "no such configuration: {}, perhaps try one of these: {}".format( command_line.args.configuration, ", ".join(configurations)))
def init(): """Description: Starts up the application normally by asking the user about the server they want to connect to""" if ui.ask_yes_no(constants.Strings.server_prompt.value): domain = ui.ask_string(constants.Strings.server_ip.value) if domain is None: ui.fatal(constants.Exceptions.invalid_ip.value) else: domain = "play.pommerman.com:5050" ui.info( constants.Strings.server_connecting_p1.value, ui.yellow, constants.Strings.server_connecting_p2.value, ui.reset, constants.Strings.server_connecting_p3.value, ) network = Network(domain) try: status = network.server_status() except Exception as e: ui.fatal(e) signal.signal(signal.SIGINT, _exit_handler) ui.info( constants.Strings.server_connected.value, ui.yellow, constants.Strings.server_players.value, str(status[0]) + ",", constants.Strings.server_matches.value, status[1], ) intent(network)
def link_application(self, out_filename, in_filenames, link_with, library_dirs): if fsutils.is_any_newer_than( in_filenames, out_filename) or self.__are_libs_newer_than_target( link_with, out_filename): ui.debug("linking application") ui.debug(" files: " + str(in_filenames)) ui.debug(" with libs: " + str(link_with)) ui.debug(" lib dirs: " + str(library_dirs)) parameters = " ".join("-L " + lib_dir for lib_dir in library_dirs) ui.bigstep("linking", out_filename) try: shell.execute(" ".join([ configurations.compiler(), configurations.linker_flags(), "-o", out_filename, " ".join(in_filenames), self.__prepare_linker_flags(link_with), parameters ])) except Exception as e: ui.fatal("cannot link {}, reason: {!s}".format( out_filename, e)) else: ui.bigstep("up to date", out_filename)
def build(name): configuration = configurations.get_selected_configuration() fsutils.make_build_dir(configuration.name) ui.debug("building {} with configuration {!s}".format(name, configuration)) with ui.ident: if name in _built_targets: ui.debug("{} already build, skipping".format(name)) return else: _built_targets.append(name) if name not in targets: ui.fatal("target {} not found".format(name)) target = targets[name] if not target.is_visible(configuration): ui.fatal("target {} is not visible in {!s}".format( name, configuration)) for dependency in target.common_parameters.depends_on.eval(): ui.debug("{} depends on {}".format(name, dependency)) build(dependency) toolchain = compiler.Gnu() target.before() target.build(toolchain) target.after() target.copy_resources(toolchain)
def replay(network, id=False, ui_en=False): """Description: This replays a particular match Arguments: * network: An `network`(pommerman.network.ion_client.network) object * id: The ID of a match to be played. If False, the user is prompted about \ it. * ui_en: If the UI is enabled or disabled (This also controls if exception are\ raised or not)""" if not id and ui_en: id = ui.ask_string(constants.Strings.replay_prompt.value) if id is None: ui.fatal(constants.Strings.error_invalid_id.value) id = str(id) if id[0] == "#": id = id[1:] ui.info( constants.Strings.server_replay_p1.value, ui.yellow, "#" + str(id), ui.reset, constants.Strings.server_replay_p2.value, ) try: replay_obj = network.get_replay(id) except Exception as e: if ui_en: ui.fatal(e) raise e if ui_en: ui.info(constants.Strings.replay_start.value, ui.yellow, "#" + str(id)) env = pommerman.make( replay_obj["mode"], [ pommerman.agents.BaseAgent(), pommerman.agents.BaseAgent(), pommerman.agents.BaseAgent(), pommerman.agents.BaseAgent(), ], ) env.reset() env._board = numpy.array(replay_obj["board"]) # Note: Render FPS is set to 30 as it'll be smoother env._render_fps = 30 for i in replay_obj["actions"]: env.render() reward, done = env.step(i)[1:3] if done: break if reward != replay_obj["reward"]: if ui_en: ui.info(ui.yellow, constants.Exceptions.replay_no_reward.value) else: raise Exception(constants.Exceptions.replay_no_reward.value) env.close() if ui_en: ui.info(ui.yellow, constants.Strings.replay_end.value) intent(network)
def get_project_name(repo_path): rc, out = tsrc.git.run_git(repo_path, "remote", "get-url", "origin", raises=False) if rc != 0: ui.fatal("Could not get url of 'origin' remote:", out) repo_url = out return project_name_from_url(repo_url)
def _agent_prompt(): """Description: Prompt the user to import their agent""" sys.path.append(os.getcwd()) agent = importlib.import_module(ui.ask_string(constants.Strings.match_import.value)) agent_class = ui.ask_string(constants.Strings.match_class_name.value) if agent_class not in agent.__dir__(): ui.fatal(constants.Strings.error_invalid_class.value) agent = getattr(agent, agent_class) if getattr(agent, "act"): ui.info(ui.green, constants.Strings.match_agent_success.value) return agent
def get_emails_from_file(targets_file): email_obj_list = [] try: target_fd = open(targets_file).readlines() for line in target_fd: e = fetch_emails(line) if e is None: continue else: email_obj_list.append(e) return email_obj_list except Exception as ex: ui.fatal("Problems occurred while trying to get emails from file", ex)
def init(): """Description: Initiate the application by asking questions.""" ui.info(ui.yellow, constants.Strings.sever_starting.value) port = int(ui.ask_string(constants.Strings.server_port.value)) max_players = int(ui.ask_string(constants.Strings.server_maxp.value)) if max_players < 4: # If the maximum players allowed on the server is less than 4 # which is the minimum required for a pommerman match then # notify the user about that and quit. ui.fatal(ui.yellow, constants.Strings.server_playercount_too_low.value) modes = [] for i in pommerman.configs.__dir__(): if i[-4:] == "_env": id = getattr(pommerman.configs, i)()["env_id"] if id[-2:] != "v2": modes.append(id) timeout = float(ui.ask_string(constants.Strings.server_timeout.value)) mode = str(ui.ask_choice(constants.Strings.server_mode.value, modes)) run(port, max_players, timeout, mode, ui_en=True, exit_handler=True)
def build_objects(self, toolchain): object_files = [] evaluated_sources = self.cxx_parameters.sources.eval() evaluated_include_dirs = self.cxx_parameters.include_dirs.eval() evaluated_compiler_flags = self.cxx_parameters.compiler_flags.eval() ui.debug("building objects from {!s}".format(evaluated_sources)) ui.push() threads = [] jobs = command_line.args.jobs limit_semaphore = threading.Semaphore(int(jobs)) ui.debug("limiting jobs to {!s}".format(jobs)) for source in evaluated_sources: object_file = toolchain.object_filename( self.common_parameters.name, source) object_files.append(object_file) thread = threading.Thread( target=self._build_object, args=(limit_semaphore, toolchain, self.common_parameters.name, object_file, source, evaluated_include_dirs, evaluated_compiler_flags)) threads.append(thread) thread.daemon = True thread.start() assert len(threads) <= jobs for t in threads: t.join() if self.error: ui.fatal("failed building {!s}: {!s}".format( self.common_parameters.name, self.error_reason)) ui.pop() return object_files
def link_application(self, out_filename, in_filenames, link_with, library_dirs): if fsutils.is_any_newer_than(in_filenames, out_filename) or self.__are_libs_newer_than_target(link_with, out_filename): ui.debug("linking application") ui.debug(" files: " + str(in_filenames)) ui.debug(" with libs: " + str(link_with)) ui.debug(" lib dirs: " + str(library_dirs)) parameters = " ".join("-L " + lib_dir for lib_dir in library_dirs) ui.bigstep("linking", out_filename) try: shell.execute(" ".join([configurations.compiler(), configurations.linker_flags(), "-o", out_filename, " ".join(in_filenames), self.__prepare_linker_flags(link_with), parameters])) except Exception as e: ui.fatal("cannot link {}, reason: {!s}".format(out_filename, e)) else: ui.bigstep("up to date", out_filename)
def eval(self): ui.debug("evaluating {!s}".format(self)) parts = self.name.split(".") if len(parts) == 1: self.module = self.module self.name = parts[0] elif len(parts) == 2: self.module = parts[0][1:] # lose the $ self.name = "$" + parts[1] global modules if self.module not in modules: ui.parse_error(msg="no such module: " + self.module) if self.name not in modules[self.module]: ui.fatal("{!s} does not exist".format(self)) return modules[self.module][self.name].eval()
def build_objects(self, toolchain): object_files = [] evaluated_sources = self.cxx_parameters.sources.eval() evaluated_include_dirs = self.cxx_parameters.include_dirs.eval() evaluated_compiler_flags = self.cxx_parameters.compiler_flags.eval() ui.debug("building objects from {!s}".format(evaluated_sources)) ui.push() threads = [] jobs = command_line.args.jobs limit_semaphore = threading.Semaphore(int(jobs)) ui.debug("limiting jobs to {!s}".format(jobs)) for source in evaluated_sources: object_file = toolchain.object_filename(self.common_parameters.name, source) object_files.append(object_file) thread = threading.Thread(target=self._build_object, args=(limit_semaphore, toolchain, self.common_parameters.name, object_file, source, evaluated_include_dirs, evaluated_compiler_flags)) threads.append(thread) thread.daemon = True thread.start() assert len(threads) <= jobs for t in threads: t.join() if self.error: ui.fatal("failed building {!s}: {!s}" .format(self.common_parameters.name, self.error_reason)) ui.pop() return object_files
def get_config_from_file(user_args): try: config_file = user_args.config_file config = configparser.ConfigParser() config.read(config_file) ui.debug(ui.check, "Correctly read config file") if user_args.cli_apikeys: user_cli_keys = user_args.cli_apikeys.split(",") for user_key in user_cli_keys: if user_key: config.set("DEFAULT", user_key.split(":", maxsplit=1)[0], user_key.split(":", maxsplit=1)[1]) ui.debug( "Added", user_key.split(":", maxsplit=1)[0], config.get('DEFAULT', option=user_key.split(":")[0])) return config except Exception as ex: ui.fatal("Problems occurred while trying to get configuration file", ex)
def _build_and_track_single_target(name): """ tracking means putting it to special container, when this function is called with the same target, it will be skipped """ configuration = configurations.get_selected_configuration() fsutils.make_build_dir(configuration.name) ui.debug("building {} with configuration {!s}".format(name, configuration)) with ui.ident: if name in _built_targets: ui.debug("{} already build, skipping".format(name)) return else: _built_targets.append(name) if name not in targets: ui.fatal("target {} not found".format(name)) target = targets[name] if not target.is_visible(configuration): ui.fatal("target {} is not visible in {!s}" .format(name, configuration)) for dependency in target.common_parameters.depends_on.eval(): ui.debug("{} depends on {}".format(name, dependency)) build(dependency) toolchain = compiler.Gnu() target.before() target.build(toolchain) target.after() target.copy_resources(toolchain)
def match(network, room=False, agent=False, ui_en=False): """Description: This facilitates playing a match Arguments: * network: An `network`(pommerman.network.ion_client.network) object * room: If String, The room to be created/joined. If False, the public \ room will be joined * agent: The class of the agent should be a derivative of BaseAgent * ui_en: If the UI is enabled or disabled (This also controls if exception \ are raised or not) Returns: Array [reward, match_id]""" agent = agent() if ui_en: ui.info(ui.yellow, constants.Strings.server_comm.value) try: network.join_list(room) except Exception as e: if ui_en: ui.fatal(e) raise e if ui_en: ui.info(constants.Strings.match_variant.value, ui.yellow, network.mode) ui.info(ui.yellow, constants.Strings.match_wait.value) try: network.wait_match() except Exception as e: if ui_en: ui.fatal(e) raise e if ui_en: ui.info(constants.Strings.match_run.value, "#" + network.match_id) for mode in pommerman.constants.GameType: if mode.name in network.mode: agent.init_agent( id=0, game_type=mode ) # We always use ID as 0 as the server doesn't return it while True: try: match_obj = network.match_get() except Exception as e: if ui_en: ui.fatal(e) raise e # match_obj[0] is the intent: 0 = OBS, 1 = Agent Dead, 2 = Match End if match_obj[0] is 0: action = agent.act(match_obj[1], gym.spaces.Discrete(6)) try: network.send_move(action, match_obj[2]) except Exception as e: if ui_en: ui.fatal(e) raise e elif match_obj[0] is 2: agent.episode_end(reward=match_obj[1]) if ui_en: if match_obj[1] == 1: ui.info(constants.Strings.match_won.value) if match_obj[1] == -1: ui.info(constants.Strings.match_loss_draw.value) ui.info( constants.Strings.match_agent.value, ui.yellow, pommerman.constants.Item(match_obj[2]).name, ) else: return [match_obj[1], network.match_id] break ui.info(constants.Strings.match_replay.value, ui.yellow, network.match_id) if ui.ask_yes_no(constants.Strings.match_ask_replay.value): replay(network, network.match_id) else: intent(network)
def get_selected_configuration(): try: return configurations[command_line.args.configuration] except: ui.fatal("no such configuration: {}, perhaps try one of these: {}" .format(command_line.args.configuration, ", ".join(configurations)))