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... | 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>sel... | 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... | 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())<... | 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>",... | 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.... | 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>s... | 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>",<... | 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>... | 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.ad... | 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... | 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>f... | 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.... | 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... | 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... | 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 = featu... | 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... | 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=FLA... | 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=F... | 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... | 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.ad... | 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 uni... | 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><D... | 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 s... | 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... | 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:... | 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><IND... | 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>versi... | 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 confi... | 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>]... | 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 surf... | 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 < radi... | 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() + p... | 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_t... | 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.
... | 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.featu... | 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:
... | 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><DE... | 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>)<EO... | 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 =... | 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>retur... | 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... | 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:<E... | 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.targe... | 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><DEDEN... | 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 > ... | 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.dra... | 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.wor... | 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>... | 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... | 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... | 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_LI... | 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, <N... | 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... | 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.observ... | 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_FEATURE... | 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_... | 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... | 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.ActionRe... | 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_... | 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_... | 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... | 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 fun... | 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>... | 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><INDE... | 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
No community queries yet
The top public SQL queries from the community will appear here once available.