signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
@sw.decorate<EOL><INDENT>def reset(self):<DEDENT> | self._episode_steps = <NUM_LIT:0><EOL>if self._episode_count:<EOL><INDENT>self._restart()<EOL><DEDENT>self._episode_count += <NUM_LIT:1><EOL>logging.info("<STR_LIT>", self._episode_count)<EOL>self._metrics.increment_episode()<EOL>self._last_score = [<NUM_LIT:0>] * self._num_agents<EOL>self._state = environment.StepType.FIRST<EOL>if self._realtime:<EOL><INDENT>self._last_step_time = time.time()<EOL>self._target_step = <NUM_LIT:0><EOL><DEDENT>return self._observe()<EOL> | Start a new episode. | f1568:c3:m8 |
@sw.decorate("<STR_LIT>")<EOL><INDENT>def step(self, actions, step_mul=None):<DEDENT> | if self._state == environment.StepType.LAST:<EOL><INDENT>return self.reset()<EOL><DEDENT>skip = not self._ensure_available_actions<EOL>self._parallel.run(<EOL>(c.act, f.transform_action(o.observation, a, skip_available=skip))<EOL>for c, f, o, a in zip(<EOL>self._controllers, self._features, self._obs, actions))<EOL>self._state = environment.StepType.MID<EOL>return self._step(step_mul)<EOL> | Apply actions, step the world forward, and return observations.
Args:
actions: A list of actions meeting the action spec, one per agent.
step_mul: If specified, use this rather than the environment's default.
Returns:
A tuple of TimeStep namedtuples, one per agent. | f1568:c3:m9 |
def send_chat_messages(self, messages): | self._parallel.run(<EOL>(c.chat, message) for c, message in zip(self._controllers, messages))<EOL> | Useful for logging messages into the replay. | f1568:c3:m13 |
def get_maps(): | maps = {}<EOL>for mp in Map.all_subclasses():<EOL><INDENT>if mp.filename:<EOL><INDENT>map_name = mp.__name__<EOL>if map_name in maps:<EOL><INDENT>raise DuplicateMapException("<STR_LIT>" + map_name)<EOL><DEDENT>maps[map_name] = mp<EOL><DEDENT><DEDENT>return maps<EOL> | Get the full dict of maps {map_name: map_class}. | f1569:m0 |
def get(map_name): | if isinstance(map_name, Map):<EOL><INDENT>return map_name<EOL><DEDENT>maps = get_maps()<EOL>map_class = maps.get(map_name)<EOL>if map_class:<EOL><INDENT>return map_class()<EOL><DEDENT>raise NoMapException("<STR_LIT>" % map_name)<EOL> | Get an instance of a map by name. Errors if the map doesn't exist. | f1569:m1 |
@property<EOL><INDENT>def path(self):<DEDENT> | if self.filename:<EOL><INDENT>map_path = os.path.join(self.directory, self.filename)<EOL>if not map_path.endswith("<STR_LIT>"):<EOL><INDENT>map_path += "<STR_LIT>"<EOL><DEDENT>return map_path<EOL><DEDENT> | The full path to the map file: directory, filename and file ending. | f1569:c2:m0 |
def data(self, run_config): | try:<EOL><INDENT>return run_config.map_data(self.path)<EOL><DEDENT>except (IOError, OSError) as e: <EOL><INDENT>if self.download and hasattr(e, "<STR_LIT:filename>"):<EOL><INDENT>logging.error("<STR_LIT>", self.name, e.filename)<EOL>logging.error("<STR_LIT>", self.download)<EOL><DEDENT>raise<EOL><DEDENT> | Return the map data. | f1569:c2:m1 |
@classmethod<EOL><INDENT>def all_subclasses(cls):<DEDENT> | for s in cls.__subclasses__():<EOL><INDENT>yield s<EOL>for c in s.all_subclasses():<EOL><INDENT>yield c<EOL><DEDENT><DEDENT> | An iterator over all subclasses of `cls`. | f1569:c2:m4 |
def valid_replay(info, ping): | if (info.HasField("<STR_LIT:error>") or<EOL>info.base_build != ping.base_build or <EOL>info.game_duration_loops < <NUM_LIT:1000> or<EOL>len(info.player_info) != <NUM_LIT:2>):<EOL><INDENT>return False<EOL><DEDENT>for p in info.player_info:<EOL><INDENT>if p.player_apm < <NUM_LIT:10> or p.player_mmr < <NUM_LIT:1000>:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL> | Make sure the replay isn't corrupt, and is worth looking at. | f1574:m1 |
def stats_printer(stats_queue): | proc_stats = [ProcessStats(i) for i in range(FLAGS.parallel)]<EOL>print_time = start_time = time.time()<EOL>width = <NUM_LIT><EOL>running = True<EOL>while running:<EOL><INDENT>print_time += <NUM_LIT:10><EOL>while time.time() < print_time:<EOL><INDENT>try:<EOL><INDENT>s = stats_queue.get(True, print_time - time.time())<EOL>if s is None: <EOL><INDENT>running = False<EOL>break<EOL><DEDENT>proc_stats[s.proc_id] = s<EOL><DEDENT>except queue.Empty:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>replay_stats = ReplayStats()<EOL>for s in proc_stats:<EOL><INDENT>replay_stats.merge(s.replay_stats)<EOL><DEDENT>print(("<STR_LIT>" % (print_time - start_time)).center(width, "<STR_LIT:=>"))<EOL>print(replay_stats)<EOL>print("<STR_LIT>".center(width, "<STR_LIT:->"))<EOL>print("<STR_LIT:\n>".join(str(s) for s in proc_stats))<EOL>print("<STR_LIT:=>" * width)<EOL><DEDENT> | A thread that consumes stats_queue and prints them every 10 seconds. | f1574:m2 |
def replay_queue_filler(replay_queue, replay_list): | for replay_path in replay_list:<EOL><INDENT>replay_queue.put(replay_path)<EOL><DEDENT> | A thread that fills the replay_queue with replay filenames. | f1574:m3 |
def main(unused_argv): | run_config = run_configs.get()<EOL>if not gfile.Exists(FLAGS.replays):<EOL><INDENT>sys.exit("<STR_LIT>".format(FLAGS.replays))<EOL><DEDENT>stats_queue = multiprocessing.Queue()<EOL>stats_thread = threading.Thread(target=stats_printer, args=(stats_queue,))<EOL>stats_thread.start()<EOL>try:<EOL><INDENT>print("<STR_LIT>", FLAGS.replays)<EOL>replay_list = sorted(run_config.replay_paths(FLAGS.replays))<EOL>print(len(replay_list), "<STR_LIT>")<EOL>replay_queue = multiprocessing.JoinableQueue(FLAGS.parallel * <NUM_LIT:10>)<EOL>replay_queue_thread = threading.Thread(target=replay_queue_filler,<EOL>args=(replay_queue, replay_list))<EOL>replay_queue_thread.daemon = True<EOL>replay_queue_thread.start()<EOL>for i in range(FLAGS.parallel):<EOL><INDENT>p = ReplayProcessor(i, run_config, replay_queue, stats_queue)<EOL>p.daemon = True<EOL>p.start()<EOL>time.sleep(<NUM_LIT:1>) <EOL><DEDENT>replay_queue.join() <EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>finally:<EOL><INDENT>stats_queue.put(None) <EOL>stats_thread.join()<EOL><DEDENT> | Dump stats about all the actions that are in use in a set of replays. | f1574:m4 |
def merge(self, other): | def merge_dict(a, b):<EOL><INDENT>for k, v in six.iteritems(b):<EOL><INDENT>a[k] += v<EOL><DEDENT><DEDENT>self.replays += other.replays<EOL>self.steps += other.steps<EOL>self.camera_move += other.camera_move<EOL>self.select_pt += other.select_pt<EOL>self.select_rect += other.select_rect<EOL>self.control_group += other.control_group<EOL>merge_dict(self.maps, other.maps)<EOL>merge_dict(self.races, other.races)<EOL>merge_dict(self.unit_ids, other.unit_ids)<EOL>merge_dict(self.valid_abilities, other.valid_abilities)<EOL>merge_dict(self.made_abilities, other.made_abilities)<EOL>merge_dict(self.valid_actions, other.valid_actions)<EOL>merge_dict(self.made_actions, other.made_actions)<EOL>self.crashing_replays |= other.crashing_replays<EOL>self.invalid_replays |= other.invalid_replays<EOL> | Merge another ReplayStats into this one. | f1574:c0:m1 |
def process_replay(self, controller, replay_data, map_data, player_id): | self._update_stage("<STR_LIT>")<EOL>controller.start_replay(sc_pb.RequestStartReplay(<EOL>replay_data=replay_data,<EOL>map_data=map_data,<EOL>options=interface,<EOL>observed_player_id=player_id))<EOL>feat = features.features_from_game_info(controller.game_info())<EOL>self.stats.replay_stats.replays += <NUM_LIT:1><EOL>self._update_stage("<STR_LIT>")<EOL>controller.step()<EOL>while True:<EOL><INDENT>self.stats.replay_stats.steps += <NUM_LIT:1><EOL>self._update_stage("<STR_LIT>")<EOL>obs = controller.observe()<EOL>for action in obs.actions:<EOL><INDENT>act_fl = action.action_feature_layer<EOL>if act_fl.HasField("<STR_LIT>"):<EOL><INDENT>self.stats.replay_stats.made_abilities[<EOL>act_fl.unit_command.ability_id] += <NUM_LIT:1><EOL><DEDENT>if act_fl.HasField("<STR_LIT>"):<EOL><INDENT>self.stats.replay_stats.camera_move += <NUM_LIT:1><EOL><DEDENT>if act_fl.HasField("<STR_LIT>"):<EOL><INDENT>self.stats.replay_stats.select_pt += <NUM_LIT:1><EOL><DEDENT>if act_fl.HasField("<STR_LIT>"):<EOL><INDENT>self.stats.replay_stats.select_rect += <NUM_LIT:1><EOL><DEDENT>if action.action_ui.HasField("<STR_LIT>"):<EOL><INDENT>self.stats.replay_stats.control_group += <NUM_LIT:1><EOL><DEDENT>try:<EOL><INDENT>func = feat.reverse_action(action).function<EOL><DEDENT>except ValueError:<EOL><INDENT>func = -<NUM_LIT:1><EOL><DEDENT>self.stats.replay_stats.made_actions[func] += <NUM_LIT:1><EOL><DEDENT>for valid in obs.observation.abilities:<EOL><INDENT>self.stats.replay_stats.valid_abilities[valid.ability_id] += <NUM_LIT:1><EOL><DEDENT>for u in obs.observation.raw_data.units:<EOL><INDENT>self.stats.replay_stats.unit_ids[u.unit_type] += <NUM_LIT:1><EOL><DEDENT>for ability_id in feat.available_actions(obs.observation):<EOL><INDENT>self.stats.replay_stats.valid_actions[ability_id] += <NUM_LIT:1><EOL><DEDENT>if obs.player_result:<EOL><INDENT>break<EOL><DEDENT>self._update_stage("<STR_LIT>")<EOL>controller.step(FLAGS.step_mul)<EOL><DEDENT> | Process a single replay, updating the stats. | f1574:c2:m4 |
def _replay_index(replay_dir): | run_config = run_configs.get()<EOL>replay_dir = run_config.abs_replay_path(replay_dir)<EOL>print("<STR_LIT>", replay_dir)<EOL>with run_config.start(want_rgb=False) as controller:<EOL><INDENT>print("<STR_LIT:->" * <NUM_LIT>)<EOL>print("<STR_LIT:U+002C>".join((<EOL>"<STR_LIT:filename>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)))<EOL>try:<EOL><INDENT>bad_replays = []<EOL>for file_path in run_config.replay_paths(replay_dir):<EOL><INDENT>file_name = os.path.basename(file_path)<EOL>try:<EOL><INDENT>info = controller.replay_info(run_config.replay_data(file_path))<EOL><DEDENT>except remote_controller.RequestError as e:<EOL><INDENT>bad_replays.append("<STR_LIT>" % (file_name, e))<EOL>continue<EOL><DEDENT>if info.HasField("<STR_LIT:error>"):<EOL><INDENT>print("<STR_LIT>", file_name, info.error, info.error_details)<EOL>bad_replays.append(file_name)<EOL><DEDENT>else:<EOL><INDENT>out = [<EOL>file_name,<EOL>info.base_build,<EOL>info.map_name,<EOL>info.game_duration_loops,<EOL>len(info.player_info),<EOL>sc_pb.Result.Name(info.player_info[<NUM_LIT:0>].player_result.result),<EOL>sc_common.Race.Name(info.player_info[<NUM_LIT:0>].player_info.race_actual),<EOL>info.player_info[<NUM_LIT:0>].player_apm,<EOL>]<EOL>if len(info.player_info) >= <NUM_LIT:2>:<EOL><INDENT>out += [<EOL>sc_common.Race.Name(<EOL>info.player_info[<NUM_LIT:1>].player_info.race_actual),<EOL>info.player_info[<NUM_LIT:1>].player_apm,<EOL>]<EOL><DEDENT>print(u"<STR_LIT:U+002C>".join(str(s) for s in out))<EOL><DEDENT><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>finally:<EOL><INDENT>if bad_replays:<EOL><INDENT>print("<STR_LIT:\n>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT:\n>".join(bad_replays))<EOL><DEDENT><DEDENT><DEDENT> | Output information for a directory of replays. | f1576:m0 |
def _replay_info(replay_path): | if not replay_path.lower().endswith("<STR_LIT>"):<EOL><INDENT>print("<STR_LIT>")<EOL>return<EOL><DEDENT>run_config = run_configs.get()<EOL>with run_config.start(want_rgb=False) as controller:<EOL><INDENT>info = controller.replay_info(run_config.replay_data(replay_path))<EOL><DEDENT>print("<STR_LIT:->" * <NUM_LIT>)<EOL>print(info)<EOL> | Query a replay for information. | f1576:m1 |
def get_data(): | run_config = run_configs.get()<EOL>with run_config.start(want_rgb=False) as controller:<EOL><INDENT>m = maps.get("<STR_LIT>") <EOL>create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(<EOL>map_path=m.path, map_data=m.data(run_config)))<EOL>create.player_setup.add(type=sc_pb.Participant)<EOL>create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random,<EOL>difficulty=sc_pb.VeryEasy)<EOL>join = sc_pb.RequestJoinGame(race=sc_common.Random,<EOL>options=sc_pb.InterfaceOptions(raw=True))<EOL>controller.create_game(create)<EOL>controller.join_game(join)<EOL>return controller.data()<EOL><DEDENT> | Retrieve static data from the game. | f1577:m0 |
def generate_csv(data): | print("<STR_LIT:U+002C>".join([<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>]))<EOL>for ability in sorted(six.itervalues(data.abilities),<EOL>key=lambda a: sort_key(data, a)):<EOL><INDENT>ab_id = ability.ability_id<EOL>if ab_id in skip_abilities or (ab_id not in data.general_abilities and<EOL>ab_id not in used_abilities):<EOL><INDENT>continue<EOL><DEDENT>general = "<STR_LIT>"<EOL>if ab_id in data.general_abilities:<EOL><INDENT>general = "<STR_LIT>"<EOL><DEDENT>elif ability.remaps_to_ability_id:<EOL><INDENT>general = ability.remaps_to_ability_id<EOL><DEDENT>mismatch = "<STR_LIT>"<EOL>if ability.remaps_to_ability_id:<EOL><INDENT>def check_mismatch(ability, parent, attr):<EOL><INDENT>if getattr(ability, attr) != getattr(parent, attr):<EOL><INDENT>return "<STR_LIT>" % (attr, getattr(ability, attr))<EOL><DEDENT><DEDENT>parent = data.abilities[ability.remaps_to_ability_id]<EOL>mismatch = "<STR_LIT>".join(filter(None, [<EOL>check_mismatch(ability, parent, "<STR_LIT>"),<EOL>check_mismatch(ability, parent, "<STR_LIT:target>"),<EOL>check_mismatch(ability, parent, "<STR_LIT>"),<EOL>check_mismatch(ability, parent, "<STR_LIT>"),<EOL>check_mismatch(ability, parent, "<STR_LIT>"),<EOL>check_mismatch(ability, parent, "<STR_LIT>"),<EOL>check_mismatch(ability, parent, "<STR_LIT>"),<EOL>check_mismatch(ability, parent, "<STR_LIT>"),<EOL>]))<EOL><DEDENT>print("<STR_LIT:U+002C>".join(str(s) for s in [<EOL>ability.ability_id,<EOL>ability.link_name,<EOL>ability.link_index,<EOL>ability.button_name,<EOL>ability.hotkey,<EOL>ability.friendly_name,<EOL>general,<EOL>mismatch,<EOL>]))<EOL><DEDENT> | Generate a CSV of the abilities for easy commenting. | f1577:m3 |
def generate_py_abilities(data): | def print_action(func_id, name, func, ab_id, general_id):<EOL><INDENT>args = [func_id, '<STR_LIT>' % name, func, ab_id]<EOL>if general_id:<EOL><INDENT>args.append(general_id)<EOL><DEDENT>print("<STR_LIT>" % "<STR_LIT:U+002CU+0020>".join(str(v) for v in args))<EOL><DEDENT>func_ids = itertools.count(<NUM_LIT:12>) <EOL>for ability in sorted(six.itervalues(data.abilities),<EOL>key=lambda a: sort_key(data, a)):<EOL><INDENT>ab_id = ability.ability_id<EOL>if ab_id in skip_abilities or (ab_id not in data.general_abilities and<EOL>ab_id not in used_abilities):<EOL><INDENT>continue<EOL><DEDENT>name = generate_name(ability).replace("<STR_LIT:U+0020>", "<STR_LIT:_>")<EOL>if ability.target in (sc_data.AbilityData.Target.Value("<STR_LIT:None>"),<EOL>sc_data.AbilityData.PointOrNone):<EOL><INDENT>print_action(next(func_ids), name + "<STR_LIT>", "<STR_LIT>", ab_id,<EOL>ability.remaps_to_ability_id)<EOL><DEDENT>if ability.target != sc_data.AbilityData.Target.Value("<STR_LIT:None>"):<EOL><INDENT>print_action(next(func_ids), name+ "<STR_LIT>", "<STR_LIT>", ab_id,<EOL>ability.remaps_to_ability_id)<EOL>if ability.allow_minimap:<EOL><INDENT>print_action(next(func_ids), name + "<STR_LIT>", "<STR_LIT>", ab_id,<EOL>ability.remaps_to_ability_id)<EOL><DEDENT><DEDENT>if ability.allow_autocast:<EOL><INDENT>print_action(next(func_ids), name + "<STR_LIT>", "<STR_LIT>", ab_id,<EOL>ability.remaps_to_ability_id)<EOL><DEDENT><DEDENT> | Generate the list of functions in actions.py. | f1577:m4 |
def main(unused_argv): | feats = features.Features(<EOL>features.AgentInterfaceFormat(<EOL>feature_dimensions=features.Dimensions(<EOL>screen=FLAGS.screen_size,<EOL>minimap=FLAGS.minimap_size)))<EOL>action_spec = feats.action_spec()<EOL>flattened = <NUM_LIT:0><EOL>count = <NUM_LIT:0><EOL>for func in action_spec.functions:<EOL><INDENT>if FLAGS.hide_specific and actions.FUNCTIONS[func.id].general_id != <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>count += <NUM_LIT:1><EOL>act_flat = <NUM_LIT:1><EOL>for arg in func.args:<EOL><INDENT>for size in arg.sizes:<EOL><INDENT>act_flat *= size<EOL><DEDENT><DEDENT>flattened += act_flat<EOL>print(func.str(True))<EOL><DEDENT>print("<STR_LIT>", count)<EOL>print("<STR_LIT>", flattened)<EOL> | Print the valid actions. | f1578:m0 |
def agent(): | agent_module, agent_name = FLAGS.agent.rsplit("<STR_LIT:.>", <NUM_LIT:1>)<EOL>agent_cls = getattr(importlib.import_module(agent_module), agent_name)<EOL>logging.info("<STR_LIT>")<EOL>with lan_sc2_env.LanSC2Env(<EOL>host=FLAGS.host,<EOL>config_port=FLAGS.config_port,<EOL>race=sc2_env.Race[FLAGS.agent_race],<EOL>step_mul=FLAGS.step_mul,<EOL>agent_interface_format=sc2_env.parse_agent_interface_format(<EOL>feature_screen=FLAGS.feature_screen_size,<EOL>feature_minimap=FLAGS.feature_minimap_size,<EOL>rgb_screen=FLAGS.rgb_screen_size,<EOL>rgb_minimap=FLAGS.rgb_minimap_size,<EOL>action_space=FLAGS.action_space,<EOL>use_feature_units=FLAGS.use_feature_units),<EOL>visualize=FLAGS.render) as env:<EOL><INDENT>agents = [agent_cls()]<EOL>logging.info("<STR_LIT>")<EOL>try:<EOL><INDENT>run_loop.run_loop(agents, env)<EOL><DEDENT>except lan_sc2_env.RestartException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>logging.info("<STR_LIT>")<EOL> | Run the agent, connecting to a (remote) host started independently. | f1579:m1 |
def human(): | run_config = run_configs.get()<EOL>map_inst = maps.get(FLAGS.map)<EOL>if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>ports = [FLAGS.config_port + p for p in range(<NUM_LIT:5>)] <EOL>if not all(portpicker.is_port_free(p) for p in ports):<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>proc = None<EOL>ssh_proc = None<EOL>tcp_conn = None<EOL>udp_sock = None<EOL>try:<EOL><INDENT>proc = run_config.start(extra_ports=ports[<NUM_LIT:1>:], timeout_seconds=<NUM_LIT>,<EOL>host=FLAGS.host, window_loc=(<NUM_LIT:50>, <NUM_LIT:50>))<EOL>tcp_port = ports[<NUM_LIT:0>]<EOL>settings = {<EOL>"<STR_LIT>": FLAGS.remote,<EOL>"<STR_LIT>": proc.version.game_version,<EOL>"<STR_LIT>": FLAGS.realtime,<EOL>"<STR_LIT>": map_inst.name,<EOL>"<STR_LIT>": map_inst.path,<EOL>"<STR_LIT>": map_inst.data(run_config),<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {"<STR_LIT>": ports[<NUM_LIT:1>], "<STR_LIT>": ports[<NUM_LIT:2>]},<EOL>"<STR_LIT>": {"<STR_LIT>": ports[<NUM_LIT:3>], "<STR_LIT>": ports[<NUM_LIT:4>]},<EOL>}<EOL>}<EOL>create = sc_pb.RequestCreateGame(<EOL>realtime=settings["<STR_LIT>"],<EOL>local_map=sc_pb.LocalMap(map_path=settings["<STR_LIT>"]))<EOL>create.player_setup.add(type=sc_pb.Participant)<EOL>create.player_setup.add(type=sc_pb.Participant)<EOL>controller = proc.controller<EOL>controller.save_map(settings["<STR_LIT>"], settings["<STR_LIT>"])<EOL>controller.create_game(create)<EOL>if FLAGS.remote:<EOL><INDENT>ssh_proc = lan_sc2_env.forward_ports(<EOL>FLAGS.remote, proc.host, [settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]],<EOL>[tcp_port, settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]])<EOL><DEDENT>print("<STR_LIT:->" * <NUM_LIT>)<EOL>print("<STR_LIT>" % (proc.host,<EOL>tcp_port))<EOL>print("<STR_LIT:->" * <NUM_LIT>)<EOL>tcp_conn = lan_sc2_env.tcp_server(<EOL>lan_sc2_env.Addr(proc.host, tcp_port), settings)<EOL>if FLAGS.remote:<EOL><INDENT>udp_sock = lan_sc2_env.udp_server(<EOL>lan_sc2_env.Addr(proc.host, settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]))<EOL>lan_sc2_env.daemon_thread(<EOL>lan_sc2_env.tcp_to_udp,<EOL>(tcp_conn, udp_sock,<EOL>lan_sc2_env.Addr(proc.host, settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"])))<EOL>lan_sc2_env.daemon_thread(lan_sc2_env.udp_to_tcp, (udp_sock, tcp_conn))<EOL><DEDENT>join = sc_pb.RequestJoinGame()<EOL>join.shared_port = <NUM_LIT:0> <EOL>join.server_ports.game_port = settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]<EOL>join.server_ports.base_port = settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]<EOL>join.client_ports.add(game_port=settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"],<EOL>base_port=settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"])<EOL>join.race = sc2_env.Race[FLAGS.user_race]<EOL>join.player_name = FLAGS.user_name<EOL>if FLAGS.render:<EOL><INDENT>join.options.raw = True<EOL>join.options.score = True<EOL>if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:<EOL><INDENT>fl = join.options.feature_layer<EOL>fl.width = <NUM_LIT><EOL>FLAGS.feature_screen_size.assign_to(fl.resolution)<EOL>FLAGS.feature_minimap_size.assign_to(fl.minimap_resolution)<EOL><DEDENT>if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:<EOL><INDENT>FLAGS.rgb_screen_size.assign_to(join.options.render.resolution)<EOL>FLAGS.rgb_minimap_size.assign_to(join.options.render.minimap_resolution)<EOL><DEDENT><DEDENT>controller.join_game(join)<EOL>if FLAGS.render:<EOL><INDENT>renderer = renderer_human.RendererHuman(<EOL>fps=FLAGS.fps, render_feature_grid=False)<EOL>renderer.run(run_configs.get(), controller, max_episodes=<NUM_LIT:1>)<EOL><DEDENT>else: <EOL><INDENT>while True:<EOL><INDENT>frame_start_time = time.time()<EOL>if not FLAGS.realtime:<EOL><INDENT>controller.step()<EOL><DEDENT>obs = controller.observe()<EOL>if obs.player_result:<EOL><INDENT>break<EOL><DEDENT>time.sleep(max(<NUM_LIT:0>, frame_start_time - time.time() + <NUM_LIT:1> / FLAGS.fps))<EOL><DEDENT><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>finally:<EOL><INDENT>if tcp_conn:<EOL><INDENT>tcp_conn.close()<EOL><DEDENT>if proc:<EOL><INDENT>proc.close()<EOL><DEDENT>if udp_sock:<EOL><INDENT>udp_sock.close()<EOL><DEDENT>if ssh_proc:<EOL><INDENT>ssh_proc.terminate()<EOL>for _ in range(<NUM_LIT:5>):<EOL><INDENT>if ssh_proc.poll() is not None:<EOL><INDENT>break<EOL><DEDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>if ssh_proc.poll() is None:<EOL><INDENT>ssh_proc.kill()<EOL>ssh_proc.wait()<EOL><DEDENT><DEDENT><DEDENT> | Run a host which expects one player to connect remotely. | f1579:m2 |
def interface_options(score=False, raw=False, features=None, rgb=None): | interface = sc_pb.InterfaceOptions()<EOL>interface.score = score<EOL>interface.raw = raw<EOL>if features:<EOL><INDENT>interface.feature_layer.width = <NUM_LIT><EOL>interface.feature_layer.resolution.x = features<EOL>interface.feature_layer.resolution.y = features<EOL>interface.feature_layer.minimap_resolution.x = features<EOL>interface.feature_layer.minimap_resolution.y = features<EOL><DEDENT>if rgb:<EOL><INDENT>interface.render.resolution.x = rgb<EOL>interface.render.resolution.y = rgb<EOL>interface.render.minimap_resolution.x = rgb<EOL>interface.render.minimap_resolution.y = rgb<EOL><DEDENT>return interface<EOL> | Get an InterfaceOptions for the config. | f1580:m0 |
def agent(): | agent_module, agent_name = FLAGS.agent.rsplit("<STR_LIT:.>", <NUM_LIT:1>)<EOL>agent_cls = getattr(importlib.import_module(agent_module), agent_name)<EOL>logging.info("<STR_LIT>")<EOL>with remote_sc2_env.RemoteSC2Env(<EOL>map_name=FLAGS.map,<EOL>host=FLAGS.host,<EOL>host_port=FLAGS.host_port,<EOL>lan_port=FLAGS.lan_port,<EOL>name=FLAGS.agent_name or agent_name,<EOL>race=sc2_env.Race[FLAGS.agent_race],<EOL>step_mul=FLAGS.step_mul,<EOL>agent_interface_format=sc2_env.parse_agent_interface_format(<EOL>feature_screen=FLAGS.feature_screen_size,<EOL>feature_minimap=FLAGS.feature_minimap_size,<EOL>rgb_screen=FLAGS.rgb_screen_size,<EOL>rgb_minimap=FLAGS.rgb_minimap_size,<EOL>action_space=FLAGS.action_space,<EOL>use_feature_units=FLAGS.use_feature_units),<EOL>visualize=FLAGS.render) as env:<EOL><INDENT>agents = [agent_cls()]<EOL>logging.info("<STR_LIT>")<EOL>try:<EOL><INDENT>run_loop.run_loop(agents, env)<EOL><DEDENT>except remote_sc2_env.RestartException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>logging.info("<STR_LIT>")<EOL> | Run the agent, connecting to a (remote) host started independently. | f1581:m1 |
def human(): | run_config = run_configs.get()<EOL>map_inst = maps.get(FLAGS.map)<EOL>if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>ports = portspicker.pick_contiguous_unused_ports(<NUM_LIT:4>) <EOL>host_proc = run_config.start(extra_ports=ports, host=FLAGS.host,<EOL>timeout_seconds=FLAGS.timeout_seconds,<EOL>window_loc=(<NUM_LIT:50>, <NUM_LIT:50>))<EOL>client_proc = run_config.start(extra_ports=ports, host=FLAGS.host,<EOL>connect=False, window_loc=(<NUM_LIT>, <NUM_LIT:50>))<EOL>create = sc_pb.RequestCreateGame(<EOL>realtime=FLAGS.realtime, local_map=sc_pb.LocalMap(map_path=map_inst.path))<EOL>create.player_setup.add(type=sc_pb.Participant)<EOL>create.player_setup.add(type=sc_pb.Participant)<EOL>controller = host_proc.controller<EOL>controller.save_map(map_inst.path, map_inst.data(run_config))<EOL>controller.create_game(create)<EOL>print("<STR_LIT:->" * <NUM_LIT>)<EOL>print("<STR_LIT>"<EOL>"<STR_LIT>" % (FLAGS.map, FLAGS.host, client_proc.port, ports[<NUM_LIT:0>]))<EOL>print("<STR_LIT:->" * <NUM_LIT>)<EOL>sys.stdout.flush()<EOL>join = sc_pb.RequestJoinGame()<EOL>join.shared_port = <NUM_LIT:0> <EOL>join.server_ports.game_port = ports.pop(<NUM_LIT:0>)<EOL>join.server_ports.base_port = ports.pop(<NUM_LIT:0>)<EOL>join.client_ports.add(game_port=ports.pop(<NUM_LIT:0>), base_port=ports.pop(<NUM_LIT:0>))<EOL>join.race = sc2_env.Race[FLAGS.user_race]<EOL>join.player_name = FLAGS.user_name<EOL>if FLAGS.render:<EOL><INDENT>join.options.raw = True<EOL>join.options.score = True<EOL>if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:<EOL><INDENT>fl = join.options.feature_layer<EOL>fl.width = <NUM_LIT><EOL>FLAGS.feature_screen_size.assign_to(fl.resolution)<EOL>FLAGS.feature_minimap_size.assign_to(fl.minimap_resolution)<EOL><DEDENT>if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:<EOL><INDENT>FLAGS.rgb_screen_size.assign_to(join.options.render.resolution)<EOL>FLAGS.rgb_minimap_size.assign_to(join.options.render.minimap_resolution)<EOL><DEDENT><DEDENT>controller.join_game(join)<EOL>if FLAGS.render:<EOL><INDENT>renderer = renderer_human.RendererHuman(<EOL>fps=FLAGS.fps, render_feature_grid=False)<EOL>renderer.run(run_configs.get(), controller, max_episodes=<NUM_LIT:1>)<EOL><DEDENT>else: <EOL><INDENT>try:<EOL><INDENT>while True:<EOL><INDENT>frame_start_time = time.time()<EOL>if not FLAGS.realtime:<EOL><INDENT>controller.step()<EOL><DEDENT>obs = controller.observe()<EOL>if obs.player_result:<EOL><INDENT>break<EOL><DEDENT>time.sleep(max(<NUM_LIT:0>, frame_start_time - time.time() + <NUM_LIT:1> / FLAGS.fps))<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>for p in [host_proc, client_proc]:<EOL><INDENT>p.close()<EOL><DEDENT>portspicker.return_ports(ports)<EOL> | Run a host which expects one player to connect remotely. | f1581:m2 |
def run_thread(agent_classes, players, map_name, visualize): | with sc2_env.SC2Env(<EOL>map_name=map_name,<EOL>players=players,<EOL>agent_interface_format=sc2_env.parse_agent_interface_format(<EOL>feature_screen=FLAGS.feature_screen_size,<EOL>feature_minimap=FLAGS.feature_minimap_size,<EOL>rgb_screen=FLAGS.rgb_screen_size,<EOL>rgb_minimap=FLAGS.rgb_minimap_size,<EOL>action_space=FLAGS.action_space,<EOL>use_feature_units=FLAGS.use_feature_units),<EOL>step_mul=FLAGS.step_mul,<EOL>game_steps_per_episode=FLAGS.game_steps_per_episode,<EOL>disable_fog=FLAGS.disable_fog,<EOL>visualize=visualize) as env:<EOL><INDENT>env = available_actions_printer.AvailableActionsPrinter(env)<EOL>agents = [agent_cls() for agent_cls in agent_classes]<EOL>run_loop.run_loop(agents, env, FLAGS.max_agent_steps, FLAGS.max_episodes)<EOL>if FLAGS.save_replay:<EOL><INDENT>env.save_replay(agent_classes[<NUM_LIT:0>].__name__)<EOL><DEDENT><DEDENT> | Run one thread worth of the environment with agents. | f1582:m0 |
def main(unused_argv): | stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace<EOL>stopwatch.sw.trace = FLAGS.trace<EOL>map_inst = maps.get(FLAGS.map)<EOL>agent_classes = []<EOL>players = []<EOL>agent_module, agent_name = FLAGS.agent.rsplit("<STR_LIT:.>", <NUM_LIT:1>)<EOL>agent_cls = getattr(importlib.import_module(agent_module), agent_name)<EOL>agent_classes.append(agent_cls)<EOL>players.append(sc2_env.Agent(sc2_env.Race[FLAGS.agent_race],<EOL>FLAGS.agent_name or agent_name))<EOL>if map_inst.players >= <NUM_LIT:2>:<EOL><INDENT>if FLAGS.agent2 == "<STR_LIT>":<EOL><INDENT>players.append(sc2_env.Bot(sc2_env.Race[FLAGS.agent2_race],<EOL>sc2_env.Difficulty[FLAGS.difficulty]))<EOL><DEDENT>else:<EOL><INDENT>agent_module, agent_name = FLAGS.agent2.rsplit("<STR_LIT:.>", <NUM_LIT:1>)<EOL>agent_cls = getattr(importlib.import_module(agent_module), agent_name)<EOL>agent_classes.append(agent_cls)<EOL>players.append(sc2_env.Agent(sc2_env.Race[FLAGS.agent2_race],<EOL>FLAGS.agent2_name or agent_name))<EOL><DEDENT><DEDENT>threads = []<EOL>for _ in range(FLAGS.parallel - <NUM_LIT:1>):<EOL><INDENT>t = threading.Thread(target=run_thread,<EOL>args=(agent_classes, players, FLAGS.map, False))<EOL>threads.append(t)<EOL>t.start()<EOL><DEDENT>run_thread(agent_classes, players, FLAGS.map, FLAGS.render)<EOL>for t in threads:<EOL><INDENT>t.join()<EOL><DEDENT>if FLAGS.profile:<EOL><INDENT>print(stopwatch.sw)<EOL><DEDENT> | Run an agent. | f1582:m1 |
def get_data(): | run_config = run_configs.get()<EOL>with run_config.start(want_rgb=False) as controller:<EOL><INDENT>m = maps.get("<STR_LIT>") <EOL>create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(<EOL>map_path=m.path, map_data=m.data(run_config)))<EOL>create.player_setup.add(type=sc_pb.Participant)<EOL>create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random,<EOL>difficulty=sc_pb.VeryEasy)<EOL>join = sc_pb.RequestJoinGame(race=sc_common.Random,<EOL>options=sc_pb.InterfaceOptions(raw=True))<EOL>controller.create_game(create)<EOL>controller.join_game(join)<EOL>return controller.data_raw()<EOL><DEDENT> | Get the game's static data from an actual game. | f1584:m0 |
def generate_py_units(data): | units = collections.defaultdict(list)<EOL>for unit in sorted(data.units, key=lambda a: a.name):<EOL><INDENT>if unit.unit_id in static_data.UNIT_TYPES:<EOL><INDENT>units[unit.race].append(unit)<EOL><DEDENT><DEDENT>def print_race(name, race):<EOL><INDENT>print("<STR_LIT>" % name)<EOL>print('<STR_LIT>' % name)<EOL>for unit in units[race]:<EOL><INDENT>print("<STR_LIT>" % (unit.name, unit.unit_id))<EOL><DEDENT>print("<STR_LIT:\n>")<EOL><DEDENT>print_race("<STR_LIT>", sc_common.NoRace)<EOL>print_race("<STR_LIT>", sc_common.Protoss)<EOL>print_race("<STR_LIT>", sc_common.Terran)<EOL>print_race("<STR_LIT>", sc_common.Zerg)<EOL> | Generate the list of units in units.py. | f1584:m1 |
def main(unused_argv): | stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace<EOL>stopwatch.sw.trace = FLAGS.trace<EOL>if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay):<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>if FLAGS.replay and not FLAGS.replay.lower().endswith("<STR_LIT>"):<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>if FLAGS.realtime and FLAGS.replay:<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>if FLAGS.render and (FLAGS.realtime or FLAGS.full_screen):<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>if platform.system() == "<STR_LIT>" and (FLAGS.realtime or FLAGS.full_screen):<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>if not FLAGS.render and FLAGS.render_sync:<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>run_config = run_configs.get()<EOL>interface = sc_pb.InterfaceOptions()<EOL>interface.raw = FLAGS.render<EOL>interface.score = True<EOL>interface.feature_layer.width = <NUM_LIT><EOL>if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:<EOL><INDENT>FLAGS.feature_screen_size.assign_to(interface.feature_layer.resolution)<EOL>FLAGS.feature_minimap_size.assign_to(<EOL>interface.feature_layer.minimap_resolution)<EOL><DEDENT>if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:<EOL><INDENT>FLAGS.rgb_screen_size.assign_to(interface.render.resolution)<EOL>FLAGS.rgb_minimap_size.assign_to(interface.render.minimap_resolution)<EOL><DEDENT>max_episode_steps = FLAGS.max_episode_steps<EOL>if FLAGS.map:<EOL><INDENT>map_inst = maps.get(FLAGS.map)<EOL>if map_inst.game_steps_per_episode:<EOL><INDENT>max_episode_steps = map_inst.game_steps_per_episode<EOL><DEDENT>create = sc_pb.RequestCreateGame(<EOL>realtime=FLAGS.realtime,<EOL>disable_fog=FLAGS.disable_fog,<EOL>local_map=sc_pb.LocalMap(map_path=map_inst.path,<EOL>map_data=map_inst.data(run_config)))<EOL>create.player_setup.add(type=sc_pb.Participant)<EOL>create.player_setup.add(type=sc_pb.Computer,<EOL>race=sc2_env.Race[FLAGS.bot_race],<EOL>difficulty=sc2_env.Difficulty[FLAGS.difficulty])<EOL>join = sc_pb.RequestJoinGame(<EOL>options=interface, race=sc2_env.Race[FLAGS.user_race],<EOL>player_name=FLAGS.user_name)<EOL>version = None<EOL><DEDENT>else:<EOL><INDENT>replay_data = run_config.replay_data(FLAGS.replay)<EOL>start_replay = sc_pb.RequestStartReplay(<EOL>replay_data=replay_data,<EOL>options=interface,<EOL>disable_fog=FLAGS.disable_fog,<EOL>observed_player_id=FLAGS.observed_player)<EOL>version = get_replay_version(replay_data)<EOL><DEDENT>with run_config.start(version=version,<EOL>full_screen=FLAGS.full_screen) as controller:<EOL><INDENT>if FLAGS.map:<EOL><INDENT>controller.create_game(create)<EOL>controller.join_game(join)<EOL><DEDENT>else:<EOL><INDENT>info = controller.replay_info(replay_data)<EOL>print("<STR_LIT>".center(<NUM_LIT>, "<STR_LIT:->"))<EOL>print(info)<EOL>print("<STR_LIT:->" * <NUM_LIT>)<EOL>map_path = FLAGS.map_path or info.local_map_path<EOL>if map_path:<EOL><INDENT>start_replay.map_data = run_config.map_data(map_path)<EOL><DEDENT>controller.start_replay(start_replay)<EOL><DEDENT>if FLAGS.render:<EOL><INDENT>renderer = renderer_human.RendererHuman(<EOL>fps=FLAGS.fps, step_mul=FLAGS.step_mul,<EOL>render_sync=FLAGS.render_sync, video=FLAGS.video)<EOL>renderer.run(<EOL>run_config, controller, max_game_steps=FLAGS.max_game_steps,<EOL>game_steps_per_episode=max_episode_steps,<EOL>save_replay=FLAGS.save_replay)<EOL><DEDENT>else: <EOL><INDENT>try:<EOL><INDENT>while True:<EOL><INDENT>frame_start_time = time.time()<EOL>if not FLAGS.realtime:<EOL><INDENT>controller.step(FLAGS.step_mul)<EOL><DEDENT>obs = controller.observe()<EOL>if obs.player_result:<EOL><INDENT>break<EOL><DEDENT>time.sleep(max(<NUM_LIT:0>, frame_start_time + <NUM_LIT:1> / FLAGS.fps - time.time()))<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>print("<STR_LIT>", obs.observation.score.score)<EOL>print("<STR_LIT>", obs.player_result)<EOL>if FLAGS.map and FLAGS.save_replay:<EOL><INDENT>replay_save_loc = run_config.save_replay(<EOL>controller.save_replay(), "<STR_LIT>", FLAGS.map)<EOL>print("<STR_LIT>", replay_save_loc)<EOL>with open(replay_save_loc.replace("<STR_LIT>", "<STR_LIT>"), "<STR_LIT:w>") as f:<EOL><INDENT>f.write("<STR_LIT>".format(obs.observation.score.score))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if FLAGS.profile:<EOL><INDENT>print(stopwatch.sw)<EOL><DEDENT> | Run SC2 to play a game or a replay. | f1587:m0 |
def __init__(self, replay_dir, data_dir, tmp_dir, cwd=None, env=None): | self.replay_dir = replay_dir<EOL>self.data_dir = data_dir<EOL>self.tmp_dir = tmp_dir<EOL>self.cwd = cwd<EOL>self.env = env<EOL> | Initialize the runconfig with the various directories needed.
Args:
replay_dir: Where to find replays. Might not be accessible to SC2.
data_dir: Where SC2 should find the data and battle.net cache.
tmp_dir: The temporary directory. None is system default.
cwd: Where to set the current working directory.
env: What to pass as the environment variables. | f1588:c1:m0 |
def map_data(self, map_name): | with gfile.Open(os.path.join(self.data_dir, "<STR_LIT>", map_name), "<STR_LIT:rb>") as f:<EOL><INDENT>return f.read()<EOL><DEDENT> | Return the map data for a map by name or path. | f1588:c1:m1 |
def abs_replay_path(self, replay_path): | return os.path.join(self.replay_dir, replay_path)<EOL> | Return the absolute path to the replay, outside the sandbox. | f1588:c1:m2 |
def replay_data(self, replay_path): | with gfile.Open(self.abs_replay_path(replay_path), "<STR_LIT:rb>") as f:<EOL><INDENT>return f.read()<EOL><DEDENT> | Return the replay data given a path to the replay. | f1588:c1:m3 |
def replay_paths(self, replay_dir): | replay_dir = self.abs_replay_path(replay_dir)<EOL>if replay_dir.lower().endswith("<STR_LIT>"):<EOL><INDENT>yield replay_dir<EOL>return<EOL><DEDENT>for f in gfile.ListDir(replay_dir):<EOL><INDENT>if f.lower().endswith("<STR_LIT>"):<EOL><INDENT>yield os.path.join(replay_dir, f)<EOL><DEDENT><DEDENT> | A generator yielding the full path to the replays under `replay_dir`. | f1588:c1:m4 |
def save_replay(self, replay_data, replay_dir, prefix=None): | if not prefix:<EOL><INDENT>replay_filename = "<STR_LIT>"<EOL><DEDENT>elif os.path.sep in prefix:<EOL><INDENT>raise ValueError("<STR_LIT>" % (<EOL>prefix, os.path.sep))<EOL><DEDENT>else:<EOL><INDENT>replay_filename = prefix + "<STR_LIT:_>"<EOL><DEDENT>now = datetime.datetime.utcnow().replace(microsecond=<NUM_LIT:0>)<EOL>replay_filename += "<STR_LIT>" % now.isoformat("<STR_LIT:->").replace("<STR_LIT::>", "<STR_LIT:->")<EOL>replay_dir = self.abs_replay_path(replay_dir)<EOL>if not gfile.Exists(replay_dir):<EOL><INDENT>gfile.MakeDirs(replay_dir)<EOL><DEDENT>replay_path = os.path.join(replay_dir, replay_filename)<EOL>with gfile.Open(replay_path, "<STR_LIT:wb>") as f:<EOL><INDENT>f.write(replay_data)<EOL><DEDENT>return replay_path<EOL> | Save a replay to a directory, returning the path to the replay.
Args:
replay_data: The result of controller.save_replay(), ie the binary data.
replay_dir: Where to save the replay. This can be absolute or relative.
prefix: Optional prefix for the replay filename.
Returns:
The full path where the replay is saved.
Raises:
ValueError: If the prefix contains the path seperator. | f1588:c1:m5 |
def start(self, version=None, **kwargs): | raise NotImplementedError()<EOL> | Launch the game. Find the version and run sc_process.StarcraftProcess. | f1588:c1:m6 |
@classmethod<EOL><INDENT>def all_subclasses(cls):<DEDENT> | for s in cls.__subclasses__():<EOL><INDENT>yield s<EOL>for c in s.all_subclasses():<EOL><INDENT>yield c<EOL><DEDENT><DEDENT> | An iterator over all subclasses of `cls`. | f1588:c1:m7 |
@classmethod<EOL><INDENT>def priority(cls):<DEDENT> | return None<EOL> | None means this isn't valid. Run the one with the max priority. | f1588:c1:m9 |
def get_versions(self): | return VERSIONS<EOL> | Return a dict of all versions that can be run. | f1588:c1:m10 |
def _read_execute_info(path, parents): | path = os.path.join(path, "<STR_LIT>")<EOL>if os.path.exists(path):<EOL><INDENT>with open(path, "<STR_LIT:rb>") as f: <EOL><INDENT>for line in f:<EOL><INDENT>parts = [p.strip() for p in line.decode("<STR_LIT:utf-8>").split("<STR_LIT:=>")]<EOL>if len(parts) == <NUM_LIT:2> and parts[<NUM_LIT:0>] == "<STR_LIT>":<EOL><INDENT>exec_path = parts[<NUM_LIT:1>].replace("<STR_LIT:\\>", "<STR_LIT:/>") <EOL>for _ in range(parents):<EOL><INDENT>exec_path = os.path.dirname(exec_path)<EOL><DEDENT>return exec_path<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Read the ExecuteInfo.txt file and return the base directory. | f1589:m0 |
def start(self, version=None, want_rgb=True, **kwargs): | del want_rgb <EOL>if not os.path.isdir(self.data_dir):<EOL><INDENT>raise sc_process.SC2LaunchError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % self.data_dir)<EOL><DEDENT>version = version or FLAGS.sc2_version<EOL>if isinstance(version, lib.Version) and not version.data_version:<EOL><INDENT>version = self._get_version(version.game_version)<EOL><DEDENT>elif isinstance(version, six.string_types):<EOL><INDENT>version = self._get_version(version)<EOL><DEDENT>elif not version:<EOL><INDENT>version = self._get_version("<STR_LIT>")<EOL><DEDENT>if version.build_version < lib.VERSIONS["<STR_LIT>"].build_version:<EOL><INDENT>raise sc_process.SC2LaunchError(<EOL>"<STR_LIT>")<EOL><DEDENT>if FLAGS.sc2_dev_build:<EOL><INDENT>version = version._replace(build_version=<NUM_LIT:0>)<EOL><DEDENT>exec_path = os.path.join(<EOL>self.data_dir, "<STR_LIT>" % version.build_version,<EOL>self._exec_name)<EOL>if not os.path.exists(exec_path):<EOL><INDENT>raise sc_process.SC2LaunchError("<STR_LIT>" % exec_path)<EOL><DEDENT>return sc_process.StarcraftProcess(<EOL>self, exec_path=exec_path, version=version, **kwargs)<EOL> | Launch the game. | f1589:c0:m1 |
def get(): | configs = {c.name(): c<EOL>for c in lib.RunConfig.all_subclasses() if c.priority()}<EOL>if not configs:<EOL><INDENT>raise sc_process.SC2LaunchError("<STR_LIT>")<EOL><DEDENT>if FLAGS.sc2_run_config is None: <EOL><INDENT>return max(configs.values(), key=lambda c: c.priority())()<EOL><DEDENT>try:<EOL><INDENT>return configs[FLAGS.sc2_run_config]()<EOL><DEDENT>except KeyError:<EOL><INDENT>raise sc_process.SC2LaunchError(<EOL>"<STR_LIT>" % (<EOL>"<STR_LIT:U+002CU+0020>".join(sorted(configs.keys()))))<EOL><DEDENT> | Get the config chosen by the flags. | f1590:m0 |
def with_lock(lock): | def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def _with_lock(*args, **kwargs):<EOL><INDENT>with lock:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT><DEDENT>return _with_lock<EOL><DEDENT>return decorator<EOL> | Make sure the lock is held while in this function. | f1592:m0 |
def _get_desktop_size(): | if platform.system() == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>xrandr_query = subprocess.check_output(["<STR_LIT>", "<STR_LIT>"])<EOL>sizes = re.findall(r"<STR_LIT>", str(xrandr_query))<EOL>if sizes[<NUM_LIT:0>]:<EOL><INDENT>return point.Point(int(sizes[<NUM_LIT:0>][<NUM_LIT:0>]), int(sizes[<NUM_LIT:0>][<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>except: <EOL><INDENT>logging.error("<STR_LIT>")<EOL><DEDENT><DEDENT>display_info = pygame.display.Info()<EOL>return point.Point(display_info.current_w, display_info.current_h)<EOL> | Get the desktop size. | f1592:m2 |
def __init__(self, surf, surf_type, surf_rect, world_to_surf, world_to_obs,<EOL>draw): | self.surf = surf<EOL>self.surf_type = surf_type<EOL>self.surf_rect = surf_rect<EOL>self.world_to_surf = world_to_surf<EOL>self.world_to_obs = world_to_obs<EOL>self.draw = draw<EOL> | A surface to display on screen.
Args:
surf: The actual pygame.Surface (or subsurface).
surf_type: A SurfType, used to tell how to treat clicks in that area.
surf_rect: Rect of the surface relative to the window.
world_to_surf: Convert a world point to a pixel on the surface.
world_to_obs: Convert a world point to a pixel in the observation.
draw: A function that draws onto the surface. | f1592:c4:m0 |
def draw_arc(self, color, world_loc, world_radius, start_angle, stop_angle,<EOL>thickness=<NUM_LIT:1>): | center = self.world_to_surf.fwd_pt(world_loc).round()<EOL>radius = max(<NUM_LIT:1>, int(self.world_to_surf.fwd_dist(world_radius)))<EOL>rect = pygame.Rect(center - radius, (radius * <NUM_LIT:2>, radius * <NUM_LIT:2>))<EOL>pygame.draw.arc(self.surf, color, rect, start_angle, stop_angle,<EOL>thickness if thickness < radius else <NUM_LIT:0>)<EOL> | Draw an arc using world coordinates, radius, start and stop angles. | f1592:c4:m1 |
def draw_circle(self, color, world_loc, world_radius, thickness=<NUM_LIT:0>): | if world_radius > <NUM_LIT:0>:<EOL><INDENT>center = self.world_to_surf.fwd_pt(world_loc).round()<EOL>radius = max(<NUM_LIT:1>, int(self.world_to_surf.fwd_dist(world_radius)))<EOL>pygame.draw.circle(self.surf, color, center, radius,<EOL>thickness if thickness < radius else <NUM_LIT:0>)<EOL><DEDENT> | Draw a circle using world coordinates and radius. | f1592:c4:m2 |
def draw_rect(self, color, world_rect, thickness=<NUM_LIT:0>): | tl = self.world_to_surf.fwd_pt(world_rect.tl).round()<EOL>br = self.world_to_surf.fwd_pt(world_rect.br).round()<EOL>rect = pygame.Rect(tl, br - tl)<EOL>pygame.draw.rect(self.surf, color, rect, thickness)<EOL> | Draw a rectangle using world coordinates. | f1592:c4:m3 |
def blit_np_array(self, array): | with sw("<STR_LIT>"):<EOL><INDENT>raw_surface = pygame.surfarray.make_surface(array.transpose([<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:2>]))<EOL><DEDENT>with sw("<STR_LIT>"):<EOL><INDENT>pygame.transform.scale(raw_surface, self.surf.get_size(), self.surf)<EOL><DEDENT> | Fill this surface using the contents of a numpy array. | f1592:c4:m4 |
def write_screen(self, font, color, screen_pos, text, align="<STR_LIT:left>",<EOL>valign="<STR_LIT>"): | pos = point.Point(*screen_pos) * point.Point(<NUM_LIT>, <NUM_LIT:1>) * font.get_linesize()<EOL>text_surf = font.render(str(text), True, color)<EOL>rect = text_surf.get_rect()<EOL>if pos.x >= <NUM_LIT:0>:<EOL><INDENT>setattr(rect, align, pos.x)<EOL><DEDENT>else:<EOL><INDENT>setattr(rect, align, self.surf.get_width() + pos.x)<EOL><DEDENT>if pos.y >= <NUM_LIT:0>:<EOL><INDENT>setattr(rect, valign, pos.y)<EOL><DEDENT>else:<EOL><INDENT>setattr(rect, valign, self.surf.get_height() + pos.y)<EOL><DEDENT>self.surf.blit(text_surf, rect)<EOL> | Write to the screen in font.size relative coordinates. | f1592:c4:m5 |
def action_spatial(self, action): | if self.surf.surf_type & SurfType.FEATURE:<EOL><INDENT>return action.action_feature_layer<EOL><DEDENT>elif self.surf.surf_type & SurfType.RGB:<EOL><INDENT>return action.action_render<EOL><DEDENT>else:<EOL><INDENT>assert self.surf.surf_type & (SurfType.RGB | SurfType.FEATURE)<EOL><DEDENT> | Given an Action, return the right spatial action. | f1592:c5:m2 |
def __init__(self, fps=<NUM_LIT>, step_mul=<NUM_LIT:1>, render_sync=False,<EOL>render_feature_grid=True, video=None): | self._fps = fps<EOL>self._step_mul = step_mul<EOL>self._render_sync = render_sync or bool(video)<EOL>self._render_rgb = None<EOL>self._render_feature_grid = render_feature_grid<EOL>self._window = None<EOL>self._desktop_size = None<EOL>self._window_scale = <NUM_LIT><EOL>self._obs_queue = queue.Queue()<EOL>self._render_thread = threading.Thread(target=self.render_thread,<EOL>name="<STR_LIT>")<EOL>self._render_thread.start()<EOL>self._game_times = collections.deque(maxlen=<NUM_LIT:100>) <EOL>self._render_times = collections.deque(maxlen=<NUM_LIT:100>) <EOL>self._last_time = time.time()<EOL>self._last_game_loop = <NUM_LIT:0><EOL>self._name_lengths = {}<EOL>self._video_writer = video_writer.VideoWriter(video, fps) if video else None<EOL> | Create a renderer for use by humans.
Make sure to call `init` with the game info, or just use `run`.
Args:
fps: How fast should the game be run.
step_mul: How many game steps to take per observation.
render_sync: Whether to wait for the obs to render before continuing.
render_feature_grid: When RGB and feature layers are available, whether
to render the grid of feature layers.
video: A filename to write the video to. Implicitly enables render_sync. | f1592:c7:m0 |
def init(self, game_info, static_data): | self._game_info = game_info<EOL>self._static_data = static_data<EOL>if not game_info.HasField("<STR_LIT>"):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._map_size = point.Point.build(game_info.start_raw.map_size)<EOL>if game_info.options.HasField("<STR_LIT>"):<EOL><INDENT>fl_opts = game_info.options.feature_layer<EOL>self._feature_screen_px = point.Point.build(fl_opts.resolution)<EOL>self._feature_minimap_px = point.Point.build(fl_opts.minimap_resolution)<EOL>self._feature_camera_width_world_units = fl_opts.width<EOL>self._render_rgb = False<EOL><DEDENT>else:<EOL><INDENT>self._feature_screen_px = self._feature_minimap_px = None<EOL><DEDENT>if game_info.options.HasField("<STR_LIT>"):<EOL><INDENT>render_opts = game_info.options.render<EOL>self._rgb_screen_px = point.Point.build(render_opts.resolution)<EOL>self._rgb_minimap_px = point.Point.build(render_opts.minimap_resolution)<EOL>self._render_rgb = True<EOL><DEDENT>else:<EOL><INDENT>self._rgb_screen_px = self._rgb_minimap_px = None<EOL><DEDENT>if not self._feature_screen_px and not self._rgb_screen_px:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>self.init_window()<EOL>self._initialized = True<EOL><DEDENT>except pygame.error as e:<EOL><INDENT>self._initialized = False<EOL>logging.error("<STR_LIT:->" * <NUM_LIT>)<EOL>logging.error("<STR_LIT>", e)<EOL>logging.error("<STR_LIT>")<EOL>logging.error("<STR_LIT>")<EOL>logging.error("<STR_LIT:->" * <NUM_LIT>)<EOL><DEDENT>self._obs = sc_pb.ResponseObservation()<EOL>self._queued_action = None<EOL>self._queued_hotkey = "<STR_LIT>"<EOL>self._select_start = None<EOL>self._alerts = {}<EOL>self._past_actions = []<EOL>self._help = False<EOL> | Take the game info and the static data needed to set up the game.
This must be called before render or get_actions for each game or restart.
Args:
game_info: A `sc_pb.ResponseGameInfo` object for this game.
static_data: A `StaticData` object for this game.
Raises:
ValueError: if there is nothing to render. | f1592:c7:m2 |
@with_lock(render_lock)<EOL><INDENT>@sw.decorate<EOL>def init_window(self):<DEDENT> | if platform.system() == "<STR_LIT>":<EOL><INDENT>ctypes.windll.user32.SetProcessDPIAware() <EOL><DEDENT>pygame.init()<EOL>if self._desktop_size is None:<EOL><INDENT>self._desktop_size = _get_desktop_size()<EOL><DEDENT>if self._render_rgb and self._rgb_screen_px:<EOL><INDENT>main_screen_px = self._rgb_screen_px<EOL><DEDENT>else:<EOL><INDENT>main_screen_px = self._feature_screen_px<EOL><DEDENT>window_size_ratio = main_screen_px<EOL>if self._feature_screen_px and self._render_feature_grid:<EOL><INDENT>num_feature_layers = (len(features.SCREEN_FEATURES) +<EOL>len(features.MINIMAP_FEATURES))<EOL>feature_cols = math.ceil(math.sqrt(num_feature_layers))<EOL>feature_rows = math.ceil(num_feature_layers / feature_cols)<EOL>features_layout = point.Point(feature_cols,<EOL>feature_rows * <NUM_LIT>) <EOL>features_aspect_ratio = (features_layout * main_screen_px.y /<EOL>features_layout.y)<EOL>window_size_ratio += point.Point(features_aspect_ratio.x, <NUM_LIT:0>)<EOL><DEDENT>window_size_px = window_size_ratio.scale_max_size(<EOL>self._desktop_size * self._window_scale).ceil()<EOL>self._window = pygame.display.set_mode(window_size_px, <NUM_LIT:0>, <NUM_LIT:32>)<EOL>pygame.display.set_caption("<STR_LIT>")<EOL>self._surfaces = []<EOL>def add_surface(surf_type, surf_loc, world_to_surf, world_to_obs, draw_fn):<EOL><INDENT>"""<STR_LIT>"""<EOL>sub_surf = self._window.subsurface(<EOL>pygame.Rect(surf_loc.tl, surf_loc.size))<EOL>self._surfaces.append(_Surface(<EOL>sub_surf, surf_type, surf_loc, world_to_surf, world_to_obs, draw_fn))<EOL><DEDENT>self._scale = window_size_px.y // <NUM_LIT:32><EOL>self._font_small = pygame.font.Font(None, int(self._scale * <NUM_LIT:0.5>))<EOL>self._font_large = pygame.font.Font(None, self._scale)<EOL>def check_eq(a, b):<EOL><INDENT>"""<STR_LIT>"""<EOL>assert (a - b).len() < <NUM_LIT>, "<STR_LIT>" % (a, b)<EOL><DEDENT>self._world_to_world_tl = transform.Linear(<EOL>point.Point(<NUM_LIT:1>, -<NUM_LIT:1>), point.Point(<NUM_LIT:0>, self._map_size.y))<EOL>check_eq(self._world_to_world_tl.fwd_pt(point.Point(<NUM_LIT:0>, <NUM_LIT:0>)),<EOL>point.Point(<NUM_LIT:0>, self._map_size.y))<EOL>check_eq(self._world_to_world_tl.fwd_pt(point.Point(<NUM_LIT:5>, <NUM_LIT:10>)),<EOL>point.Point(<NUM_LIT:5>, self._map_size.y - <NUM_LIT:10>))<EOL>self._world_tl_to_world_camera_rel = transform.Linear(<EOL>offset=-self._map_size / <NUM_LIT:4>)<EOL>check_eq(self._world_tl_to_world_camera_rel.fwd_pt(self._map_size / <NUM_LIT:4>),<EOL>point.Point(<NUM_LIT:0>, <NUM_LIT:0>))<EOL>check_eq(<EOL>self._world_tl_to_world_camera_rel.fwd_pt(<EOL>(self._map_size / <NUM_LIT:4>) + point.Point(<NUM_LIT:5>, <NUM_LIT:10>)),<EOL>point.Point(<NUM_LIT:5>, <NUM_LIT:10>))<EOL>if self._feature_screen_px:<EOL><INDENT>feature_world_per_pixel = (self._feature_screen_px /<EOL>self._feature_camera_width_world_units)<EOL>world_camera_rel_to_feature_screen = transform.Linear(<EOL>feature_world_per_pixel, self._feature_screen_px / <NUM_LIT:2>)<EOL>check_eq(world_camera_rel_to_feature_screen.fwd_pt(point.Point(<NUM_LIT:0>, <NUM_LIT:0>)),<EOL>self._feature_screen_px / <NUM_LIT:2>)<EOL>check_eq(<EOL>world_camera_rel_to_feature_screen.fwd_pt(<EOL>point.Point(-<NUM_LIT:0.5>, -<NUM_LIT:0.5>) * self._feature_camera_width_world_units),<EOL>point.Point(<NUM_LIT:0>, <NUM_LIT:0>))<EOL>self._world_to_feature_screen = transform.Chain(<EOL>self._world_to_world_tl,<EOL>self._world_tl_to_world_camera_rel,<EOL>world_camera_rel_to_feature_screen)<EOL>self._world_to_feature_screen_px = transform.Chain(<EOL>self._world_to_feature_screen,<EOL>transform.PixelToCoord())<EOL>world_tl_to_feature_minimap = transform.Linear(<EOL>self._feature_minimap_px / self._map_size.max_dim())<EOL>check_eq(world_tl_to_feature_minimap.fwd_pt(point.Point(<NUM_LIT:0>, <NUM_LIT:0>)),<EOL>point.Point(<NUM_LIT:0>, <NUM_LIT:0>))<EOL>check_eq(world_tl_to_feature_minimap.fwd_pt(self._map_size),<EOL>self._map_size.scale_max_size(self._feature_minimap_px))<EOL>self._world_to_feature_minimap = transform.Chain(<EOL>self._world_to_world_tl,<EOL>world_tl_to_feature_minimap)<EOL>self._world_to_feature_minimap_px = transform.Chain(<EOL>self._world_to_feature_minimap,<EOL>transform.PixelToCoord())<EOL><DEDENT>if self._rgb_screen_px:<EOL><INDENT>rgb_world_per_pixel = (self._rgb_screen_px / <NUM_LIT>)<EOL>world_camera_rel_to_rgb_screen = transform.Linear(<EOL>rgb_world_per_pixel, self._rgb_screen_px / <NUM_LIT:2>)<EOL>check_eq(world_camera_rel_to_rgb_screen.fwd_pt(point.Point(<NUM_LIT:0>, <NUM_LIT:0>)),<EOL>self._rgb_screen_px / <NUM_LIT:2>)<EOL>check_eq(<EOL>world_camera_rel_to_rgb_screen.fwd_pt(<EOL>point.Point(-<NUM_LIT:0.5>, -<NUM_LIT:0.5>) * <NUM_LIT>),<EOL>point.Point(<NUM_LIT:0>, <NUM_LIT:0>))<EOL>self._world_to_rgb_screen = transform.Chain(<EOL>self._world_to_world_tl,<EOL>self._world_tl_to_world_camera_rel,<EOL>world_camera_rel_to_rgb_screen)<EOL>self._world_to_rgb_screen_px = transform.Chain(<EOL>self._world_to_rgb_screen,<EOL>transform.PixelToCoord())<EOL>world_tl_to_rgb_minimap = transform.Linear(<EOL>self._rgb_minimap_px / self._map_size.max_dim())<EOL>check_eq(world_tl_to_rgb_minimap.fwd_pt(point.Point(<NUM_LIT:0>, <NUM_LIT:0>)),<EOL>point.Point(<NUM_LIT:0>, <NUM_LIT:0>))<EOL>check_eq(world_tl_to_rgb_minimap.fwd_pt(self._map_size),<EOL>self._map_size.scale_max_size(self._rgb_minimap_px))<EOL>self._world_to_rgb_minimap = transform.Chain(<EOL>self._world_to_world_tl,<EOL>world_tl_to_rgb_minimap)<EOL>self._world_to_rgb_minimap_px = transform.Chain(<EOL>self._world_to_rgb_minimap,<EOL>transform.PixelToCoord())<EOL><DEDENT>screen_size_px = main_screen_px.scale_max_size(window_size_px)<EOL>minimap_size_px = self._map_size.scale_max_size(screen_size_px / <NUM_LIT:4>)<EOL>minimap_offset = point.Point(<NUM_LIT:0>, (screen_size_px.y - minimap_size_px.y))<EOL>if self._render_rgb:<EOL><INDENT>rgb_screen_to_main_screen = transform.Linear(<EOL>screen_size_px / self._rgb_screen_px)<EOL>add_surface(SurfType.RGB | SurfType.SCREEN,<EOL>point.Rect(point.origin, screen_size_px),<EOL>transform.Chain( <EOL>self._world_to_rgb_screen,<EOL>rgb_screen_to_main_screen),<EOL>self._world_to_rgb_screen_px,<EOL>self.draw_screen)<EOL>rgb_minimap_to_main_minimap = transform.Linear(<EOL>minimap_size_px / self._rgb_minimap_px)<EOL>add_surface(SurfType.RGB | SurfType.MINIMAP,<EOL>point.Rect(minimap_offset,<EOL>minimap_offset + minimap_size_px),<EOL>transform.Chain( <EOL>self._world_to_rgb_minimap,<EOL>rgb_minimap_to_main_minimap),<EOL>self._world_to_rgb_minimap_px,<EOL>self.draw_mini_map)<EOL><DEDENT>else:<EOL><INDENT>feature_screen_to_main_screen = transform.Linear(<EOL>screen_size_px / self._feature_screen_px)<EOL>add_surface(SurfType.FEATURE | SurfType.SCREEN,<EOL>point.Rect(point.origin, screen_size_px),<EOL>transform.Chain( <EOL>self._world_to_feature_screen,<EOL>feature_screen_to_main_screen),<EOL>self._world_to_feature_screen_px,<EOL>self.draw_screen)<EOL>feature_minimap_to_main_minimap = transform.Linear(<EOL>minimap_size_px / self._feature_minimap_px)<EOL>add_surface(SurfType.FEATURE | SurfType.MINIMAP,<EOL>point.Rect(minimap_offset,<EOL>minimap_offset + minimap_size_px),<EOL>transform.Chain( <EOL>self._world_to_feature_minimap,<EOL>feature_minimap_to_main_minimap),<EOL>self._world_to_feature_minimap_px,<EOL>self.draw_mini_map)<EOL><DEDENT>if self._feature_screen_px and self._render_feature_grid:<EOL><INDENT>features_loc = point.Point(screen_size_px.x, <NUM_LIT:0>)<EOL>feature_pane = self._window.subsurface(<EOL>pygame.Rect(features_loc, window_size_px - features_loc))<EOL>feature_pane.fill(colors.white / <NUM_LIT:2>)<EOL>feature_pane_size = point.Point(*feature_pane.get_size())<EOL>feature_grid_size = feature_pane_size / point.Point(feature_cols,<EOL>feature_rows)<EOL>feature_layer_area = self._feature_screen_px.scale_max_size(<EOL>feature_grid_size)<EOL>feature_layer_padding = feature_layer_area // <NUM_LIT:20><EOL>feature_layer_size = feature_layer_area - feature_layer_padding * <NUM_LIT:2><EOL>feature_font_size = int(feature_grid_size.y * <NUM_LIT>)<EOL>feature_font = pygame.font.Font(None, feature_font_size)<EOL>feature_counter = itertools.count()<EOL>def add_feature_layer(feature, surf_type, world_to_surf, world_to_obs):<EOL><INDENT>"""<STR_LIT>"""<EOL>i = next(feature_counter)<EOL>grid_offset = point.Point(i % feature_cols,<EOL>i // feature_cols) * feature_grid_size<EOL>text = feature_font.render(feature.full_name, True, colors.white)<EOL>rect = text.get_rect()<EOL>rect.center = grid_offset + point.Point(feature_grid_size.x / <NUM_LIT:2>,<EOL>feature_font_size)<EOL>feature_pane.blit(text, rect)<EOL>surf_loc = (features_loc + grid_offset + feature_layer_padding +<EOL>point.Point(<NUM_LIT:0>, feature_font_size))<EOL>add_surface(surf_type,<EOL>point.Rect(surf_loc, surf_loc + feature_layer_size),<EOL>world_to_surf, world_to_obs,<EOL>lambda surf: self.draw_feature_layer(surf, feature))<EOL><DEDENT>feature_minimap_to_feature_minimap_surf = transform.Linear(<EOL>feature_layer_size / self._feature_minimap_px)<EOL>world_to_feature_minimap_surf = transform.Chain(<EOL>self._world_to_feature_minimap,<EOL>feature_minimap_to_feature_minimap_surf)<EOL>for feature in features.MINIMAP_FEATURES:<EOL><INDENT>add_feature_layer(feature, SurfType.FEATURE | SurfType.MINIMAP,<EOL>world_to_feature_minimap_surf,<EOL>self._world_to_feature_minimap_px)<EOL><DEDENT>feature_screen_to_feature_screen_surf = transform.Linear(<EOL>feature_layer_size / self._feature_screen_px)<EOL>world_to_feature_screen_surf = transform.Chain(<EOL>self._world_to_feature_screen,<EOL>feature_screen_to_feature_screen_surf)<EOL>for feature in features.SCREEN_FEATURES:<EOL><INDENT>add_feature_layer(feature, SurfType.FEATURE | SurfType.SCREEN,<EOL>world_to_feature_screen_surf,<EOL>self._world_to_feature_screen_px)<EOL><DEDENT><DEDENT>help_size = point.Point(<EOL>(max(len(s) for s, _ in self.shortcuts) +<EOL>max(len(s) for _, s in self.shortcuts)) * <NUM_LIT> + <NUM_LIT:4>,<EOL>len(self.shortcuts) + <NUM_LIT:3>) * self._scale<EOL>help_rect = point.Rect(window_size_px / <NUM_LIT:2> - help_size / <NUM_LIT:2>,<EOL>window_size_px / <NUM_LIT:2> + help_size / <NUM_LIT:2>)<EOL>add_surface(SurfType.CHROME, help_rect, None, None, self.draw_help)<EOL>self._update_camera(self._map_size / <NUM_LIT:2>)<EOL> | Initialize the pygame window and lay out the surfaces. | f1592:c7:m3 |
def _update_camera(self, camera_center): | self._world_tl_to_world_camera_rel.offset = (<EOL>-self._world_to_world_tl.fwd_pt(camera_center) *<EOL>self._world_tl_to_world_camera_rel.scale)<EOL>if self._feature_screen_px:<EOL><INDENT>camera_radius = (self._feature_screen_px / self._feature_screen_px.x *<EOL>self._feature_camera_width_world_units / <NUM_LIT:2>)<EOL>center = camera_center.bound(camera_radius,<EOL>self._map_size - camera_radius)<EOL>self._camera = point.Rect(<EOL>(center - camera_radius).bound(self._map_size),<EOL>(center + camera_radius).bound(self._map_size))<EOL><DEDENT> | Update the camera transform based on the new camera center. | f1592:c7:m4 |
def zoom(self, factor): | self._window_scale *= factor<EOL>self.init_window()<EOL> | Zoom the window in/out. | f1592:c7:m5 |
def get_mouse_pos(self, window_pos=None): | window_pos = window_pos or pygame.mouse.get_pos()<EOL>window_pt = point.Point(*window_pos) + <NUM_LIT:0.5><EOL>for surf in reversed(self._surfaces):<EOL><INDENT>if (surf.surf_type != SurfType.CHROME and<EOL>surf.surf_rect.contains_point(window_pt)):<EOL><INDENT>surf_rel_pt = window_pt - surf.surf_rect.tl<EOL>world_pt = surf.world_to_surf.back_pt(surf_rel_pt)<EOL>return MousePos(world_pt, surf)<EOL><DEDENT><DEDENT> | Return a MousePos filled with the world position and surf it hit. | f1592:c7:m6 |
@sw.decorate<EOL><INDENT>def get_actions(self, run_config, controller):<DEDENT> | if not self._initialized:<EOL><INDENT>return ActionCmd.STEP<EOL><DEDENT>for event in pygame.event.get():<EOL><INDENT>ctrl = pygame.key.get_mods() & pygame.KMOD_CTRL<EOL>shift = pygame.key.get_mods() & pygame.KMOD_SHIFT<EOL>alt = pygame.key.get_mods() & pygame.KMOD_ALT<EOL>if event.type == pygame.QUIT:<EOL><INDENT>return ActionCmd.QUIT<EOL><DEDENT>elif event.type == pygame.KEYDOWN:<EOL><INDENT>if self._help:<EOL><INDENT>self._help = False<EOL><DEDENT>elif event.key in (pygame.K_QUESTION, pygame.K_SLASH):<EOL><INDENT>self._help = True<EOL><DEDENT>elif event.key == pygame.K_PAUSE:<EOL><INDENT>pause = True<EOL>while pause:<EOL><INDENT>time.sleep(<NUM_LIT:0.1>)<EOL>for event2 in pygame.event.get():<EOL><INDENT>if event2.type == pygame.KEYDOWN:<EOL><INDENT>if event2.key in (pygame.K_PAUSE, pygame.K_ESCAPE):<EOL><INDENT>pause = False<EOL><DEDENT>elif event2.key == pygame.K_F4:<EOL><INDENT>return ActionCmd.QUIT<EOL><DEDENT>elif event2.key == pygame.K_F5:<EOL><INDENT>return ActionCmd.RESTART<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>elif event.key == pygame.K_F4:<EOL><INDENT>return ActionCmd.QUIT<EOL><DEDENT>elif event.key == pygame.K_F5:<EOL><INDENT>return ActionCmd.RESTART<EOL><DEDENT>elif event.key == pygame.K_F7: <EOL><INDENT>if self._rgb_screen_px and self._feature_screen_px:<EOL><INDENT>self._render_rgb = not self._render_rgb<EOL>print("<STR_LIT>", self._render_rgb and "<STR_LIT>" or "<STR_LIT>")<EOL>self.init_window()<EOL><DEDENT><DEDENT>elif event.key == pygame.K_F8: <EOL><INDENT>self._render_sync = not self._render_sync<EOL>print("<STR_LIT>", self._render_sync and "<STR_LIT>" or "<STR_LIT>")<EOL><DEDENT>elif event.key == pygame.K_F9: <EOL><INDENT>self.save_replay(run_config, controller)<EOL><DEDENT>elif event.key in (pygame.K_PLUS, pygame.K_EQUALS) and ctrl:<EOL><INDENT>self.zoom(<NUM_LIT>) <EOL><DEDENT>elif event.key in (pygame.K_MINUS, pygame.K_UNDERSCORE) and ctrl:<EOL><INDENT>self.zoom(<NUM_LIT:1> / <NUM_LIT>) <EOL><DEDENT>elif event.key in (pygame.K_PAGEUP, pygame.K_PAGEDOWN):<EOL><INDENT>if ctrl:<EOL><INDENT>if event.key == pygame.K_PAGEUP:<EOL><INDENT>self._step_mul += <NUM_LIT:1><EOL><DEDENT>elif self._step_mul > <NUM_LIT:1>:<EOL><INDENT>self._step_mul -= <NUM_LIT:1><EOL><DEDENT>print("<STR_LIT>", self._step_mul)<EOL><DEDENT>else:<EOL><INDENT>self._fps *= <NUM_LIT> if event.key == pygame.K_PAGEUP else <NUM_LIT:1> / <NUM_LIT><EOL>print("<STR_LIT>" % self._fps)<EOL><DEDENT><DEDENT>elif event.key == pygame.K_F1:<EOL><INDENT>if self._obs.observation.player_common.idle_worker_count > <NUM_LIT:0>:<EOL><INDENT>controller.act(self.select_idle_worker(ctrl, shift))<EOL><DEDENT><DEDENT>elif event.key == pygame.K_F2:<EOL><INDENT>if self._obs.observation.player_common.army_count > <NUM_LIT:0>:<EOL><INDENT>controller.act(self.select_army(shift))<EOL><DEDENT><DEDENT>elif event.key == pygame.K_F3:<EOL><INDENT>if self._obs.observation.player_common.warp_gate_count > <NUM_LIT:0>:<EOL><INDENT>controller.act(self.select_warp_gates(shift))<EOL><DEDENT>if self._obs.observation.player_common.larva_count > <NUM_LIT:0>:<EOL><INDENT>controller.act(self.select_larva())<EOL><DEDENT><DEDENT>elif event.key in self.cmd_group_keys:<EOL><INDENT>controller.act(self.control_group(self.cmd_group_keys[event.key],<EOL>ctrl, shift, alt))<EOL><DEDENT>elif event.key in self.camera_actions:<EOL><INDENT>if self._obs:<EOL><INDENT>controller.act(self.camera_action_raw(<EOL>point.Point.build(<EOL>self._obs.observation.raw_data.player.camera) +<EOL>self.camera_actions[event.key]))<EOL><DEDENT><DEDENT>elif event.key == pygame.K_ESCAPE:<EOL><INDENT>if self._queued_action:<EOL><INDENT>self.clear_queued_action()<EOL><DEDENT>else:<EOL><INDENT>cmds = self._abilities(lambda cmd: cmd.hotkey == "<STR_LIT>") <EOL>for cmd in cmds: <EOL><INDENT>assert not cmd.requires_point<EOL>controller.act(self.unit_action(cmd, None, shift))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if not self._queued_action:<EOL><INDENT>key = pygame.key.name(event.key).lower()<EOL>new_cmd = self._queued_hotkey + key<EOL>cmds = self._abilities(lambda cmd, n=new_cmd: ( <EOL>cmd.hotkey != "<STR_LIT>" and cmd.hotkey.startswith(n)))<EOL>if cmds:<EOL><INDENT>self._queued_hotkey = new_cmd<EOL>if len(cmds) == <NUM_LIT:1>:<EOL><INDENT>cmd = cmds[<NUM_LIT:0>]<EOL>if cmd.hotkey == self._queued_hotkey:<EOL><INDENT>if cmd.requires_point:<EOL><INDENT>self.clear_queued_action()<EOL>self._queued_action = cmd<EOL><DEDENT>else:<EOL><INDENT>controller.act(self.unit_action(cmd, None, shift))<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>elif event.type == pygame.MOUSEBUTTONDOWN:<EOL><INDENT>mouse_pos = self.get_mouse_pos(event.pos)<EOL>if event.button == MouseButtons.LEFT and mouse_pos:<EOL><INDENT>if self._queued_action:<EOL><INDENT>controller.act(self.unit_action(<EOL>self._queued_action, mouse_pos, shift))<EOL><DEDENT>elif mouse_pos.surf.surf_type & SurfType.MINIMAP:<EOL><INDENT>controller.act(self.camera_action(mouse_pos))<EOL><DEDENT>else:<EOL><INDENT>self._select_start = mouse_pos<EOL><DEDENT><DEDENT>elif event.button == MouseButtons.RIGHT:<EOL><INDENT>if self._queued_action:<EOL><INDENT>self.clear_queued_action()<EOL><DEDENT>cmds = self._abilities(lambda cmd: cmd.name == "<STR_LIT>")<EOL>if cmds:<EOL><INDENT>controller.act(self.unit_action(cmds[<NUM_LIT:0>], mouse_pos, shift))<EOL><DEDENT><DEDENT><DEDENT>elif event.type == pygame.MOUSEBUTTONUP:<EOL><INDENT>mouse_pos = self.get_mouse_pos(event.pos)<EOL>if event.button == MouseButtons.LEFT and self._select_start:<EOL><INDENT>if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and<EOL>mouse_pos.surf.surf_type == self._select_start.surf.surf_type):<EOL><INDENT>controller.act(self.select_action(<EOL>self._select_start, mouse_pos, ctrl, shift))<EOL><DEDENT>self._select_start = None<EOL><DEDENT><DEDENT><DEDENT>return ActionCmd.STEP<EOL> | Get actions from the UI, apply to controller, and return an ActionCmd. | f1592:c7:m9 |
def camera_action(self, mouse_pos): | action = sc_pb.Action()<EOL>action_spatial = mouse_pos.action_spatial(action)<EOL>mouse_pos.obs_pos.assign_to(action_spatial.camera_move.center_minimap)<EOL>return action<EOL> | Return a `sc_pb.Action` with the camera movement filled. | f1592:c7:m10 |
def camera_action_raw(self, world_pos): | action = sc_pb.Action()<EOL>world_pos.assign_to(action.action_raw.camera_move.center_world_space)<EOL>return action<EOL> | Return a `sc_pb.Action` with the camera movement filled. | f1592:c7:m11 |
def select_action(self, pos1, pos2, ctrl, shift): | assert pos1.surf.surf_type == pos2.surf.surf_type<EOL>assert pos1.surf.world_to_obs == pos2.surf.world_to_obs<EOL>action = sc_pb.Action()<EOL>action_spatial = pos1.action_spatial(action)<EOL>if pos1.world_pos == pos2.world_pos: <EOL><INDENT>select = action_spatial.unit_selection_point<EOL>pos1.obs_pos.assign_to(select.selection_screen_coord)<EOL>mod = sc_spatial.ActionSpatialUnitSelectionPoint<EOL>if ctrl:<EOL><INDENT>select.type = mod.AddAllType if shift else mod.AllType<EOL><DEDENT>else:<EOL><INDENT>select.type = mod.Toggle if shift else mod.Select<EOL><DEDENT><DEDENT>else:<EOL><INDENT>select = action_spatial.unit_selection_rect<EOL>rect = select.selection_screen_coord.add()<EOL>pos1.obs_pos.assign_to(rect.p0)<EOL>pos2.obs_pos.assign_to(rect.p1)<EOL>select.selection_add = shift<EOL><DEDENT>units = self._units_in_area(point.Rect(pos1.world_pos, pos2.world_pos))<EOL>if units:<EOL><INDENT>self.clear_queued_action()<EOL><DEDENT>return action<EOL> | Return a `sc_pb.Action` with the selection filled. | f1592:c7:m12 |
def select_idle_worker(self, ctrl, shift): | action = sc_pb.Action()<EOL>mod = sc_ui.ActionSelectIdleWorker<EOL>if ctrl:<EOL><INDENT>select_worker = mod.AddAll if shift else mod.All<EOL><DEDENT>else:<EOL><INDENT>select_worker = mod.Add if shift else mod.Set<EOL><DEDENT>action.action_ui.select_idle_worker.type = select_worker<EOL>return action<EOL> | Select an idle worker. | f1592:c7:m13 |
def select_army(self, shift): | action = sc_pb.Action()<EOL>action.action_ui.select_army.selection_add = shift<EOL>return action<EOL> | Select the entire army. | f1592:c7:m14 |
def select_warp_gates(self, shift): | action = sc_pb.Action()<EOL>action.action_ui.select_warp_gates.selection_add = shift<EOL>return action<EOL> | Select all warp gates. | f1592:c7:m15 |
def select_larva(self): | action = sc_pb.Action()<EOL>action.action_ui.select_larva.SetInParent() <EOL>return action<EOL> | Select all larva. | f1592:c7:m16 |
def control_group(self, control_group_id, ctrl, shift, alt): | action = sc_pb.Action()<EOL>select = action.action_ui.control_group<EOL>mod = sc_ui.ActionControlGroup<EOL>if not ctrl and not shift and not alt:<EOL><INDENT>select.action = mod.Recall<EOL><DEDENT>elif ctrl and not shift and not alt:<EOL><INDENT>select.action = mod.Set<EOL><DEDENT>elif not ctrl and shift and not alt:<EOL><INDENT>select.action = mod.Append<EOL><DEDENT>elif not ctrl and not shift and alt:<EOL><INDENT>select.action = mod.SetAndSteal<EOL><DEDENT>elif not ctrl and shift and alt:<EOL><INDENT>select.action = mod.AppendAndSteal<EOL><DEDENT>else:<EOL><INDENT>return <EOL><DEDENT>select.control_group_index = control_group_id<EOL>return action<EOL> | Act on a control group, selecting, setting, etc. | f1592:c7:m17 |
def unit_action(self, cmd, pos, shift): | action = sc_pb.Action()<EOL>if pos:<EOL><INDENT>action_spatial = pos.action_spatial(action)<EOL>unit_command = action_spatial.unit_command<EOL>unit_command.ability_id = cmd.ability_id<EOL>unit_command.queue_command = shift<EOL>if pos.surf.surf_type & SurfType.SCREEN:<EOL><INDENT>pos.obs_pos.assign_to(unit_command.target_screen_coord)<EOL><DEDENT>elif pos.surf.surf_type & SurfType.MINIMAP:<EOL><INDENT>pos.obs_pos.assign_to(unit_command.target_minimap_coord)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self._feature_screen_px:<EOL><INDENT>action.action_feature_layer.unit_command.ability_id = cmd.ability_id<EOL><DEDENT>else:<EOL><INDENT>action.action_render.unit_command.ability_id = cmd.ability_id<EOL><DEDENT><DEDENT>self.clear_queued_action()<EOL>return action<EOL> | Return a `sc_pb.Action` filled with the cmd and appropriate target. | f1592:c7:m18 |
def _abilities(self, fn=None): | out = {}<EOL>for cmd in self._obs.observation.abilities:<EOL><INDENT>ability = _Ability(cmd, self._static_data.abilities)<EOL>if not fn or fn(ability):<EOL><INDENT>out[ability.ability_id] = ability<EOL><DEDENT><DEDENT>return list(out.values())<EOL> | Return the list of abilities filtered by `fn`. | f1592:c7:m19 |
def _visible_units(self): | <EOL>for u in sorted(self._obs.observation.raw_data.units,<EOL>key=lambda u: (u.pos.z, u.owner != <NUM_LIT:16>, -u.radius, u.tag)):<EOL><INDENT>yield u, point.Point.build(u.pos)<EOL><DEDENT> | A generator of visible units and their positions as `Point`s, sorted. | f1592:c7:m20 |
def _units_in_area(self, rect): | player_id = self._obs.observation.player_common.player_id<EOL>return [u for u, p in self._visible_units()<EOL>if rect.intersects_circle(p, u.radius) and u.owner == player_id]<EOL> | Return the list of units that intersect the rect. | f1592:c7:m21 |
def get_unit_name(self, surf, name, radius): | key = (name, radius)<EOL>if key not in self._name_lengths:<EOL><INDENT>max_len = surf.world_to_surf.fwd_dist(radius * <NUM_LIT>)<EOL>for i in range(len(name)):<EOL><INDENT>if self._font_small.size(name[:i + <NUM_LIT:1>])[<NUM_LIT:0>] > max_len:<EOL><INDENT>self._name_lengths[key] = name[:i]<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._name_lengths[key] = name<EOL><DEDENT><DEDENT>return self._name_lengths[key]<EOL> | Get a length limited unit name for drawing units. | f1592:c7:m22 |
@sw.decorate<EOL><INDENT>def draw_units(self, surf):<DEDENT> | for u, p in self._visible_units():<EOL><INDENT>if self._camera.intersects_circle(p, u.radius):<EOL><INDENT>fraction_damage = clamp((u.health_max - u.health) / (u.health_max or <NUM_LIT:1>),<EOL><NUM_LIT:0>, <NUM_LIT:1>)<EOL>surf.draw_circle(colors.PLAYER_ABSOLUTE_PALETTE[u.owner], p, u.radius)<EOL>if fraction_damage > <NUM_LIT:0>:<EOL><INDENT>surf.draw_circle(colors.PLAYER_ABSOLUTE_PALETTE[u.owner] // <NUM_LIT:2>,<EOL>p, u.radius * fraction_damage)<EOL><DEDENT>if u.shield and u.shield_max:<EOL><INDENT>surf.draw_arc(colors.blue, p, u.radius, <NUM_LIT:0>,<EOL><NUM_LIT:2> * math.pi * u.shield / u.shield_max)<EOL><DEDENT>if u.energy and u.energy_max:<EOL><INDENT>surf.draw_arc(colors.purple * <NUM_LIT>, p, u.radius - <NUM_LIT>, <NUM_LIT:0>,<EOL><NUM_LIT:2> * math.pi * u.energy / u.energy_max)<EOL><DEDENT>name = self.get_unit_name(<EOL>surf, self._static_data.units.get(u.unit_type, "<STR_LIT>"), u.radius)<EOL>if name:<EOL><INDENT>text = self._font_small.render(name, True, colors.white)<EOL>rect = text.get_rect()<EOL>rect.center = surf.world_to_surf.fwd_pt(p)<EOL>surf.surf.blit(text, rect)<EOL><DEDENT>if u.is_selected:<EOL><INDENT>surf.draw_circle(colors.green, p, u.radius + <NUM_LIT:0.1>, <NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT> | Draw the units and buildings. | f1592:c7:m23 |
@sw.decorate<EOL><INDENT>def draw_selection(self, surf):<DEDENT> | select_start = self._select_start <EOL>if select_start:<EOL><INDENT>mouse_pos = self.get_mouse_pos()<EOL>if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and<EOL>mouse_pos.surf.surf_type == select_start.surf.surf_type):<EOL><INDENT>rect = point.Rect(select_start.world_pos, mouse_pos.world_pos)<EOL>surf.draw_rect(colors.green, rect, <NUM_LIT:1>)<EOL><DEDENT><DEDENT> | Draw the selection rectange. | f1592:c7:m24 |
@sw.decorate<EOL><INDENT>def draw_build_target(self, surf):<DEDENT> | round_half = lambda v, cond: round(v - <NUM_LIT:0.5>) + <NUM_LIT:0.5> if cond else round(v)<EOL>queued_action = self._queued_action<EOL>if queued_action:<EOL><INDENT>radius = queued_action.footprint_radius<EOL>if radius:<EOL><INDENT>pos = self.get_mouse_pos()<EOL>if pos:<EOL><INDENT>pos = point.Point(round_half(pos.world_pos.x, (radius * <NUM_LIT:2>) % <NUM_LIT:2>),<EOL>round_half(pos.world_pos.y, (radius * <NUM_LIT:2>) % <NUM_LIT:2>))<EOL>surf.draw_circle(<EOL>colors.PLAYER_ABSOLUTE_PALETTE[<EOL>self._obs.observation.player_common.player_id],<EOL>pos, radius)<EOL><DEDENT><DEDENT><DEDENT> | Draw the build target. | f1592:c7:m25 |
@sw.decorate<EOL><INDENT>def draw_overlay(self, surf):<DEDENT> | obs = self._obs.observation<EOL>player = obs.player_common<EOL>surf.write_screen(<EOL>self._font_large, colors.green, (<NUM_LIT>, <NUM_LIT>),<EOL>"<STR_LIT>" % (<EOL>player.minerals, player.vespene, player.food_used, player.food_cap))<EOL>times, steps = zip(*self._game_times)<EOL>sec = obs.game_loop // <NUM_LIT> <EOL>surf.write_screen(<EOL>self._font_large, colors.green, (-<NUM_LIT>, <NUM_LIT>),<EOL>"<STR_LIT>" % (<EOL>obs.score.score, obs.game_loop, sum(steps) / (sum(times) or <NUM_LIT:1>),<EOL>sec // <NUM_LIT>, sec % <NUM_LIT>),<EOL>align="<STR_LIT:right>")<EOL>surf.write_screen(<EOL>self._font_large, colors.green * <NUM_LIT>, (-<NUM_LIT>, <NUM_LIT>),<EOL>"<STR_LIT>" % (<EOL>len(times) / (sum(times) or <NUM_LIT:1>),<EOL>len(self._render_times) / (sum(self._render_times) or <NUM_LIT:1>)),<EOL>align="<STR_LIT:right>")<EOL>line = <NUM_LIT:3><EOL>for alert, ts in sorted(self._alerts.items(), key=lambda item: item[<NUM_LIT:1>]):<EOL><INDENT>if time.time() < ts + <NUM_LIT:3>: <EOL><INDENT>surf.write_screen(self._font_large, colors.red, (<NUM_LIT:20>, line), alert)<EOL>line += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>del self._alerts[alert]<EOL><DEDENT><DEDENT> | Draw the overlay describing resources. | f1592:c7:m26 |
@sw.decorate<EOL><INDENT>def draw_help(self, surf):<DEDENT> | if not self._help:<EOL><INDENT>return<EOL><DEDENT>def write(loc, text):<EOL><INDENT>surf.write_screen(self._font_large, colors.black, loc, text)<EOL><DEDENT>surf.surf.fill(colors.white * <NUM_LIT>)<EOL>write((<NUM_LIT:1>, <NUM_LIT:1>), "<STR_LIT>")<EOL>max_len = max(len(s) for s, _ in self.shortcuts)<EOL>for i, (hotkey, description) in enumerate(self.shortcuts, start=<NUM_LIT:2>):<EOL><INDENT>write((<NUM_LIT:2>, i), hotkey)<EOL>write((<NUM_LIT:3> + max_len * <NUM_LIT>, i), description)<EOL><DEDENT> | Draw the help dialog. | f1592:c7:m27 |
@sw.decorate<EOL><INDENT>def draw_commands(self, surf):<DEDENT> | past_abilities = {act.ability for act in self._past_actions if act.ability}<EOL>for y, cmd in enumerate(sorted(self._abilities(<EOL>lambda c: c.name != "<STR_LIT>"), key=lambda c: c.name), start=<NUM_LIT:2>):<EOL><INDENT>if self._queued_action and cmd == self._queued_action:<EOL><INDENT>color = colors.green<EOL><DEDENT>elif self._queued_hotkey and cmd.hotkey.startswith(self._queued_hotkey):<EOL><INDENT>color = colors.green * <NUM_LIT><EOL><DEDENT>elif cmd.ability_id in past_abilities:<EOL><INDENT>color = colors.red<EOL><DEDENT>else:<EOL><INDENT>color = colors.yellow<EOL><DEDENT>hotkey = cmd.hotkey[<NUM_LIT:0>:<NUM_LIT:3>] <EOL>surf.write_screen(self._font_large, color, (<NUM_LIT>, y), hotkey)<EOL>surf.write_screen(self._font_large, color, (<NUM_LIT:3>, y), cmd.name)<EOL><DEDENT> | Draw the list of available commands. | f1592:c7:m28 |
@sw.decorate<EOL><INDENT>def draw_panel(self, surf):<DEDENT> | left = -<NUM_LIT:12> <EOL>def unit_name(unit_type):<EOL><INDENT>return self._static_data.units.get(unit_type, "<STR_LIT>")<EOL><DEDENT>def write(loc, text, color=colors.yellow):<EOL><INDENT>surf.write_screen(self._font_large, color, loc, text)<EOL><DEDENT>def write_single(unit, line):<EOL><INDENT>write((left + <NUM_LIT:1>, next(line)), unit_name(unit.unit_type))<EOL>write((left + <NUM_LIT:1>, next(line)), "<STR_LIT>" % unit.health)<EOL>write((left + <NUM_LIT:1>, next(line)), "<STR_LIT>" % unit.shields)<EOL>write((left + <NUM_LIT:1>, next(line)), "<STR_LIT>" % unit.energy)<EOL>if unit.build_progress > <NUM_LIT:0>:<EOL><INDENT>write((left + <NUM_LIT:1>, next(line)),<EOL>"<STR_LIT>" % (unit.build_progress * <NUM_LIT:100>))<EOL><DEDENT>if unit.transport_slots_taken > <NUM_LIT:0>:<EOL><INDENT>write((left + <NUM_LIT:1>, next(line)), "<STR_LIT>" % unit.transport_slots_taken)<EOL><DEDENT><DEDENT>def write_multi(units, line):<EOL><INDENT>counts = collections.defaultdict(int)<EOL>for unit in units:<EOL><INDENT>counts[unit_name(unit.unit_type)] += <NUM_LIT:1><EOL><DEDENT>for name, count in sorted(counts.items()):<EOL><INDENT>y = next(line)<EOL>write((left + <NUM_LIT:1>, y), count)<EOL>write((left + <NUM_LIT:3>, y), name)<EOL><DEDENT><DEDENT>ui = self._obs.observation.ui_data<EOL>line = itertools.count(<NUM_LIT:3>)<EOL>if ui.groups:<EOL><INDENT>write((left, next(line)), "<STR_LIT>", colors.green)<EOL>for group in ui.groups:<EOL><INDENT>y = next(line)<EOL>write((left + <NUM_LIT:1>, y), "<STR_LIT>" % group.control_group_index, colors.green)<EOL>write((left + <NUM_LIT:3>, y), "<STR_LIT>" % (group.count,<EOL>unit_name(group.leader_unit_type)))<EOL><DEDENT>next(line)<EOL><DEDENT>if ui.HasField("<STR_LIT>"):<EOL><INDENT>write((left, next(line)), "<STR_LIT>", colors.green)<EOL>write_single(ui.single.unit, line)<EOL><DEDENT>elif ui.HasField("<STR_LIT>"):<EOL><INDENT>write((left, next(line)), "<STR_LIT>", colors.green)<EOL>write_multi(ui.multi.units, line)<EOL><DEDENT>elif ui.HasField("<STR_LIT>"):<EOL><INDENT>write((left, next(line)), "<STR_LIT>", colors.green)<EOL>write_single(ui.cargo.unit, line)<EOL>next(line)<EOL>write((left, next(line)), "<STR_LIT>", colors.green)<EOL>write((left + <NUM_LIT:1>, next(line)),<EOL>"<STR_LIT>" % ui.cargo.slots_available)<EOL>write_multi(ui.cargo.passengers, line)<EOL><DEDENT>elif ui.HasField("<STR_LIT>"):<EOL><INDENT>write((left, next(line)), "<STR_LIT>", colors.green)<EOL>write_single(ui.production.unit, line)<EOL>next(line)<EOL>write((left, next(line)), "<STR_LIT>", colors.green)<EOL>for unit in ui.production.build_queue:<EOL><INDENT>s = unit_name(unit.unit_type)<EOL>if unit.build_progress > <NUM_LIT:0>:<EOL><INDENT>s += "<STR_LIT>" % (unit.build_progress * <NUM_LIT:100>)<EOL><DEDENT>write((left + <NUM_LIT:1>, next(line)), s)<EOL><DEDENT><DEDENT> | Draw the unit selection or build queue. | f1592:c7:m29 |
@sw.decorate<EOL><INDENT>def draw_actions(self):<DEDENT> | now = time.time()<EOL>for act in self._past_actions:<EOL><INDENT>if act.pos and now < act.deadline:<EOL><INDENT>remain = (act.deadline - now) / (act.deadline - act.time)<EOL>if isinstance(act.pos, point.Point):<EOL><INDENT>size = remain / <NUM_LIT:3><EOL>self.all_surfs(_Surface.draw_circle, act.color, act.pos, size, <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>self.all_surfs(_Surface.draw_rect, act.color, act.pos, <NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT> | Draw the actions so that they can be inspected for accuracy. | f1592:c7:m30 |
@sw.decorate<EOL><INDENT>def prepare_actions(self, obs):<DEDENT> | now = time.time()<EOL>while self._past_actions and self._past_actions[<NUM_LIT:0>].deadline < now:<EOL><INDENT>self._past_actions.pop(<NUM_LIT:0>)<EOL><DEDENT>def add_act(ability_id, color, pos, timeout=<NUM_LIT:1>):<EOL><INDENT>if ability_id:<EOL><INDENT>ability = self._static_data.abilities[ability_id]<EOL>if ability.remaps_to_ability_id: <EOL><INDENT>ability_id = ability.remaps_to_ability_id<EOL><DEDENT><DEDENT>self._past_actions.append(<EOL>PastAction(ability_id, color, pos, now, now + timeout))<EOL><DEDENT>for act in obs.actions:<EOL><INDENT>if (act.HasField("<STR_LIT>") and<EOL>act.action_raw.HasField("<STR_LIT>") and<EOL>act.action_raw.unit_command.HasField("<STR_LIT>")):<EOL><INDENT>pos = point.Point.build(<EOL>act.action_raw.unit_command.target_world_space_pos)<EOL>add_act(act.action_raw.unit_command.ability_id, colors.yellow, pos)<EOL><DEDENT>if act.HasField("<STR_LIT>"):<EOL><INDENT>act_fl = act.action_feature_layer<EOL>if act_fl.HasField("<STR_LIT>"):<EOL><INDENT>if act_fl.unit_command.HasField("<STR_LIT>"):<EOL><INDENT>pos = self._world_to_feature_screen_px.back_pt(<EOL>point.Point.build(act_fl.unit_command.target_screen_coord))<EOL>add_act(act_fl.unit_command.ability_id, colors.cyan, pos)<EOL><DEDENT>elif act_fl.unit_command.HasField("<STR_LIT>"):<EOL><INDENT>pos = self._world_to_feature_minimap_px.back_pt(<EOL>point.Point.build(act_fl.unit_command.target_minimap_coord))<EOL>add_act(act_fl.unit_command.ability_id, colors.cyan, pos)<EOL><DEDENT>else:<EOL><INDENT>add_act(act_fl.unit_command.ability_id, None, None)<EOL><DEDENT><DEDENT>if (act_fl.HasField("<STR_LIT>") and<EOL>act_fl.unit_selection_point.HasField("<STR_LIT>")):<EOL><INDENT>pos = self._world_to_feature_screen_px.back_pt(point.Point.build(<EOL>act_fl.unit_selection_point.selection_screen_coord))<EOL>add_act(None, colors.cyan, pos)<EOL><DEDENT>if act_fl.HasField("<STR_LIT>"):<EOL><INDENT>for r in act_fl.unit_selection_rect.selection_screen_coord:<EOL><INDENT>rect = point.Rect(<EOL>self._world_to_feature_screen_px.back_pt(<EOL>point.Point.build(r.p0)),<EOL>self._world_to_feature_screen_px.back_pt(<EOL>point.Point.build(r.p1)))<EOL>add_act(None, colors.cyan, rect, <NUM_LIT>)<EOL><DEDENT><DEDENT><DEDENT>if act.HasField("<STR_LIT>"):<EOL><INDENT>act_rgb = act.action_render<EOL>if act_rgb.HasField("<STR_LIT>"):<EOL><INDENT>if act_rgb.unit_command.HasField("<STR_LIT>"):<EOL><INDENT>pos = self._world_to_rgb_screen_px.back_pt(<EOL>point.Point.build(act_rgb.unit_command.target_screen_coord))<EOL>add_act(act_rgb.unit_command.ability_id, colors.red, pos)<EOL><DEDENT>elif act_rgb.unit_command.HasField("<STR_LIT>"):<EOL><INDENT>pos = self._world_to_rgb_minimap_px.back_pt(<EOL>point.Point.build(act_rgb.unit_command.target_minimap_coord))<EOL>add_act(act_rgb.unit_command.ability_id, colors.red, pos)<EOL><DEDENT>else:<EOL><INDENT>add_act(act_rgb.unit_command.ability_id, None, None)<EOL><DEDENT><DEDENT>if (act_rgb.HasField("<STR_LIT>") and<EOL>act_rgb.unit_selection_point.HasField("<STR_LIT>")):<EOL><INDENT>pos = self._world_to_rgb_screen_px.back_pt(point.Point.build(<EOL>act_rgb.unit_selection_point.selection_screen_coord))<EOL>add_act(None, colors.red, pos)<EOL><DEDENT>if act_rgb.HasField("<STR_LIT>"):<EOL><INDENT>for r in act_rgb.unit_selection_rect.selection_screen_coord:<EOL><INDENT>rect = point.Rect(<EOL>self._world_to_rgb_screen_px.back_pt(<EOL>point.Point.build(r.p0)),<EOL>self._world_to_rgb_screen_px.back_pt(<EOL>point.Point.build(r.p1)))<EOL>add_act(None, colors.red, rect, <NUM_LIT>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Keep a list of the past actions so they can be drawn. | f1592:c7:m31 |
@sw.decorate<EOL><INDENT>def draw_base_map(self, surf):<DEDENT> | hmap_feature = features.SCREEN_FEATURES.height_map<EOL>hmap = hmap_feature.unpack(self._obs.observation)<EOL>if not hmap.any():<EOL><INDENT>hmap = hmap + <NUM_LIT:100> <EOL><DEDENT>hmap_color = hmap_feature.color(hmap)<EOL>creep_feature = features.SCREEN_FEATURES.creep<EOL>creep = creep_feature.unpack(self._obs.observation)<EOL>creep_mask = creep > <NUM_LIT:0><EOL>creep_color = creep_feature.color(creep)<EOL>power_feature = features.SCREEN_FEATURES.power<EOL>power = power_feature.unpack(self._obs.observation)<EOL>power_mask = power > <NUM_LIT:0><EOL>power_color = power_feature.color(power)<EOL>visibility = features.SCREEN_FEATURES.visibility_map.unpack(<EOL>self._obs.observation)<EOL>visibility_fade = np.array([[<NUM_LIT:0.5>] * <NUM_LIT:3>, [<NUM_LIT>]*<NUM_LIT:3>, [<NUM_LIT:1>]*<NUM_LIT:3>])<EOL>out = hmap_color * <NUM_LIT><EOL>out[creep_mask, :] = (<NUM_LIT> * out[creep_mask, :] +<EOL><NUM_LIT> * creep_color[creep_mask, :])<EOL>out[power_mask, :] = (<NUM_LIT> * out[power_mask, :] +<EOL><NUM_LIT> * power_color[power_mask, :])<EOL>out *= visibility_fade[visibility]<EOL>surf.blit_np_array(out)<EOL> | Draw the base map. | f1592:c7:m32 |
@sw.decorate<EOL><INDENT>def draw_mini_map(self, surf):<DEDENT> | if (self._render_rgb and self._obs.observation.HasField("<STR_LIT>") and<EOL>self._obs.observation.render_data.HasField("<STR_LIT>")):<EOL><INDENT>surf.blit_np_array(features.Feature.unpack_rgb_image(<EOL>self._obs.observation.render_data.minimap))<EOL><DEDENT>else: <EOL><INDENT>hmap_feature = features.MINIMAP_FEATURES.height_map<EOL>hmap = hmap_feature.unpack(self._obs.observation)<EOL>if not hmap.any():<EOL><INDENT>hmap = hmap + <NUM_LIT:100> <EOL><DEDENT>hmap_color = hmap_feature.color(hmap)<EOL>creep_feature = features.MINIMAP_FEATURES.creep<EOL>creep = creep_feature.unpack(self._obs.observation)<EOL>creep_mask = creep > <NUM_LIT:0><EOL>creep_color = creep_feature.color(creep)<EOL>if self._obs.observation.player_common.player_id in (<NUM_LIT:0>, <NUM_LIT:16>): <EOL><INDENT>player_feature = features.MINIMAP_FEATURES.player_id<EOL><DEDENT>else:<EOL><INDENT>player_feature = features.MINIMAP_FEATURES.player_relative<EOL><DEDENT>player_data = player_feature.unpack(self._obs.observation)<EOL>player_mask = player_data > <NUM_LIT:0><EOL>player_color = player_feature.color(player_data)<EOL>visibility = features.MINIMAP_FEATURES.visibility_map.unpack(<EOL>self._obs.observation)<EOL>visibility_fade = np.array([[<NUM_LIT:0.5>] * <NUM_LIT:3>, [<NUM_LIT>]*<NUM_LIT:3>, [<NUM_LIT:1>]*<NUM_LIT:3>])<EOL>out = hmap_color * <NUM_LIT><EOL>out[creep_mask, :] = (<NUM_LIT> * out[creep_mask, :] +<EOL><NUM_LIT> * creep_color[creep_mask, :])<EOL>out[player_mask, :] = player_color[player_mask, :]<EOL>out *= visibility_fade[visibility]<EOL>shape = self._map_size.scale_max_size(<EOL>self._feature_minimap_px).floor()<EOL>surf.blit_np_array(out[:shape.y, :shape.x, :])<EOL>surf.draw_rect(colors.white * <NUM_LIT>, self._camera, <NUM_LIT:1>) <EOL>pygame.draw.rect(surf.surf, colors.red, surf.surf.get_rect(), <NUM_LIT:1>)<EOL><DEDENT> | Draw the minimap. | f1592:c7:m33 |
@sw.decorate<EOL><INDENT>def draw_rendered_map(self, surf):<DEDENT> | surf.blit_np_array(features.Feature.unpack_rgb_image(<EOL>self._obs.observation.render_data.map))<EOL> | Draw the rendered pixels. | f1592:c7:m35 |
def draw_screen(self, surf): | <EOL>if (self._render_rgb and self._obs.observation.HasField("<STR_LIT>") and<EOL>self._obs.observation.render_data.HasField("<STR_LIT>")):<EOL><INDENT>self.draw_rendered_map(surf)<EOL><DEDENT>else:<EOL><INDENT>self.draw_base_map(surf)<EOL>self.draw_units(surf)<EOL><DEDENT>self.draw_selection(surf)<EOL>self.draw_build_target(surf)<EOL>self.draw_overlay(surf)<EOL>self.draw_commands(surf)<EOL>self.draw_panel(surf)<EOL> | Draw the screen area. | f1592:c7:m36 |
@sw.decorate<EOL><INDENT>def draw_feature_layer(self, surf, feature):<DEDENT> | layer = feature.unpack(self._obs.observation)<EOL>if layer is not None:<EOL><INDENT>surf.blit_np_array(feature.color(layer))<EOL><DEDENT>else: <EOL><INDENT>surf.surf.fill(colors.black)<EOL><DEDENT> | Draw a feature layer. | f1592:c7:m37 |
@sw.decorate<EOL><INDENT>def render(self, obs):<DEDENT> | if not self._initialized:<EOL><INDENT>return<EOL><DEDENT>now = time.time()<EOL>self._game_times.append(<EOL>(now - self._last_time,<EOL>max(<NUM_LIT:1>, obs.observation.game_loop - self._obs.observation.game_loop)))<EOL>self._last_time = now<EOL>self._last_game_loop = self._obs.observation.game_loop<EOL>self._obs_queue.put(obs)<EOL>if self._render_sync:<EOL><INDENT>self._obs_queue.join()<EOL><DEDENT> | Push an observation onto the queue to be rendered. | f1592:c7:m39 |
def render_thread(self): | obs = True<EOL>while obs: <EOL><INDENT>obs = self._obs_queue.get()<EOL>if obs:<EOL><INDENT>for alert in obs.observation.alerts:<EOL><INDENT>self._alerts[sc_pb.Alert.Name(alert)] = time.time()<EOL><DEDENT>for err in obs.action_errors:<EOL><INDENT>if err.result != sc_err.Success:<EOL><INDENT>self._alerts[sc_err.ActionResult.Name(err.result)] = time.time()<EOL><DEDENT><DEDENT>self.prepare_actions(obs)<EOL>if self._obs_queue.empty():<EOL><INDENT>self.render_obs(obs)<EOL><DEDENT>if self._video_writer:<EOL><INDENT>self._video_writer.add(np.transpose(<EOL>pygame.surfarray.pixels3d(self._window), axes=(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:2>)))<EOL><DEDENT><DEDENT>self._obs_queue.task_done()<EOL><DEDENT> | A render loop that pulls observations off the queue to render. | f1592:c7:m40 |
@with_lock(render_lock)<EOL><INDENT>@sw.decorate<EOL>def render_obs(self, obs):<DEDENT> | start_time = time.time()<EOL>self._obs = obs<EOL>self.check_valid_queued_action()<EOL>self._update_camera(point.Point.build(<EOL>self._obs.observation.raw_data.player.camera))<EOL>for surf in self._surfaces:<EOL><INDENT>surf.draw(surf)<EOL><DEDENT>mouse_pos = self.get_mouse_pos()<EOL>if mouse_pos:<EOL><INDENT>self.all_surfs(_Surface.draw_circle, colors.green, mouse_pos.world_pos,<EOL><NUM_LIT:0.1>)<EOL><DEDENT>self.draw_actions()<EOL>with sw("<STR_LIT>"):<EOL><INDENT>pygame.display.flip()<EOL><DEDENT>self._render_times.append(time.time() - start_time)<EOL> | Render a frame given an observation. | f1592:c7:m41 |
def run(self, run_config, controller, max_game_steps=<NUM_LIT:0>, max_episodes=<NUM_LIT:0>,<EOL>game_steps_per_episode=<NUM_LIT:0>, save_replay=False): | is_replay = (controller.status == remote_controller.Status.in_replay)<EOL>total_game_steps = <NUM_LIT:0><EOL>start_time = time.time()<EOL>num_episodes = <NUM_LIT:0><EOL>try:<EOL><INDENT>while True:<EOL><INDENT>self.init(controller.game_info(), controller.data())<EOL>episode_steps = <NUM_LIT:0><EOL>num_episodes += <NUM_LIT:1><EOL>controller.step()<EOL>while True:<EOL><INDENT>total_game_steps += self._step_mul<EOL>episode_steps += self._step_mul<EOL>frame_start_time = time.time()<EOL>obs = controller.observe()<EOL>self.render(obs)<EOL>if obs.player_result:<EOL><INDENT>break<EOL><DEDENT>cmd = self.get_actions(run_config, controller)<EOL>if cmd == ActionCmd.STEP:<EOL><INDENT>pass<EOL><DEDENT>elif cmd == ActionCmd.QUIT:<EOL><INDENT>if not is_replay and save_replay:<EOL><INDENT>self.save_replay(run_config, controller)<EOL><DEDENT>return<EOL><DEDENT>elif cmd == ActionCmd.RESTART:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % cmd)<EOL><DEDENT>controller.step(self._step_mul)<EOL>if max_game_steps and total_game_steps >= max_game_steps:<EOL><INDENT>return<EOL><DEDENT>if game_steps_per_episode and episode_steps >= game_steps_per_episode:<EOL><INDENT>break<EOL><DEDENT>with sw("<STR_LIT>"):<EOL><INDENT>elapsed_time = time.time() - frame_start_time<EOL>time.sleep(max(<NUM_LIT:0>, <NUM_LIT:1> / self._fps - elapsed_time))<EOL><DEDENT><DEDENT>if is_replay:<EOL><INDENT>break<EOL><DEDENT>if save_replay:<EOL><INDENT>self.save_replay(run_config, controller)<EOL><DEDENT>if max_episodes and num_episodes >= max_episodes:<EOL><INDENT>break<EOL><DEDENT>print("<STR_LIT>")<EOL>controller.restart()<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>finally:<EOL><INDENT>self.close()<EOL>elapsed_time = time.time() - start_time<EOL>print("<STR_LIT>" %<EOL>(elapsed_time, total_game_steps, total_game_steps / elapsed_time))<EOL><DEDENT> | Run loop that gets observations, renders them, and sends back actions. | f1592:c7:m42 |
def measure_step_time(self, num_steps=<NUM_LIT:1>): | del num_steps<EOL>return _EventTimer()<EOL> | Return a context manager to measure the time to perform N game steps. | f1593:c1:m3 |
def measure_observation_time(self): | return _EventTimer()<EOL> | Return a context manager to measure the time to get an observation. | f1593:c1:m4 |
def add(self, frame): | self.writeFrame(frame)<EOL> | Add a frame to the video based on a numpy array. | f1594:c0:m1 |
@property<EOL><INDENT>def dev(self):<DEDENT> | if self.num == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return math.sqrt(max(<NUM_LIT:0>, self.sum_sq / self.num - (self.sum / self.num)**<NUM_LIT:2>))<EOL> | Standard deviation. | f1596:c0:m4 |
def decorate(self, name_or_func): | if os.environ.get("<STR_LIT>"):<EOL><INDENT>return name_or_func if callable(name_or_func) else lambda func: func<EOL><DEDENT>def decorator(name, func):<EOL><INDENT>@functools.wraps(func)<EOL>def _stopwatch(*args, **kwargs):<EOL><INDENT>with self(name):<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT><DEDENT>return _stopwatch<EOL><DEDENT>if callable(name_or_func):<EOL><INDENT>return decorator(name_or_func.__name__, name_or_func)<EOL><DEDENT>else:<EOL><INDENT>return lambda func: decorator(name_or_func, func)<EOL><DEDENT> | Decorate a function/method to check its timings.
To use the function's name:
@sw.decorate
def func():
pass
To name it explicitly:
@sw.decorate("name")
def random_func_name():
pass
Args:
name_or_func: the name or the function to decorate.
Returns:
If a name is passed, returns this as a decorator, otherwise returns the
decorated function. | f1596:c4:m2 |
@staticmethod<EOL><INDENT>def parse(s):<DEDENT> | stopwatch = StopWatch()<EOL>for line in s.splitlines():<EOL><INDENT>if line.strip():<EOL><INDENT>parts = line.split(None)<EOL>name = parts[<NUM_LIT:0>]<EOL>if name != "<STR_LIT:%>": <EOL><INDENT>rest = (float(v) for v in parts[<NUM_LIT:2>:])<EOL>stopwatch.times[parts[<NUM_LIT:0>]].merge(Stat.build(*rest))<EOL><DEDENT><DEDENT><DEDENT>return stopwatch<EOL> | Parse the output below to create a new StopWatch. | f1596:c4:m11 |
def str(self, threshold=<NUM_LIT:0.1>): | if not self._times:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>total = sum(s.sum for k, s in six.iteritems(self._times) if "<STR_LIT:.>" not in k)<EOL>table = [["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]]<EOL>for k, v in sorted(self._times.items()):<EOL><INDENT>percent = <NUM_LIT:100> * v.sum / (total or <NUM_LIT:1>)<EOL>if percent > threshold: <EOL><INDENT>table.append([<EOL>k,<EOL>"<STR_LIT>" % percent,<EOL>"<STR_LIT>" % v.sum,<EOL>"<STR_LIT>" % v.avg,<EOL>"<STR_LIT>" % v.dev,<EOL>"<STR_LIT>" % v.min,<EOL>"<STR_LIT>" % v.max,<EOL>"<STR_LIT>" % v.num,<EOL>])<EOL><DEDENT><DEDENT>col_widths = [max(len(row[i]) for row in table)<EOL>for i in range(len(table[<NUM_LIT:0>]))]<EOL>out = "<STR_LIT>"<EOL>for row in table:<EOL><INDENT>out += "<STR_LIT:U+0020>" + row[<NUM_LIT:0>].ljust(col_widths[<NUM_LIT:0>]) + "<STR_LIT:U+0020>"<EOL>out += "<STR_LIT:U+0020>".join(<EOL>val.rjust(width) for val, width in zip(row[<NUM_LIT:1>:], col_widths[<NUM_LIT:1>:]))<EOL>out += "<STR_LIT:\n>"<EOL><DEDENT>return out<EOL> | Return a string representation of the timings. | f1596:c4:m12 |
@classmethod<EOL><INDENT>def build(cls, obj):<DEDENT> | return cls(obj.x, obj.y)<EOL> | Build a Point from an object that has properties `x` and `y`. | f1598:c0:m0 |
@classmethod<EOL><INDENT>def unit_rand(cls):<DEDENT> | return cls(random.random(), random.random())<EOL> | Return a Point with x, y chosen randomly with 0 <= x < 1, 0 <= y < 1. | f1598:c0:m1 |
def assign_to(self, obj): | obj.x = self.x<EOL>obj.y = self.y<EOL> | Assign `x` and `y` to an object that has properties `x` and `y`. | f1598:c0:m2 |
Subsets and Splits