INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Save a replay, returning the data.
def save_replay(self): """Save a replay, returning the data.""" res = self._client.send(save_replay=sc_pb.RequestSaveReplay()) return res.data
Run a debug command.
def debug(self, debug_commands): """Run a debug command.""" if isinstance(debug_commands, sc_debug.DebugCommand): debug_commands = [debug_commands] return self._client.send(debug=sc_pb.RequestDebug(debug=debug_commands))
Shut down the SC2 process.
def quit(self): """Shut down the SC2 process.""" try: # Don't expect a response. self._client.write(sc_pb.Request(quit=sc_pb.RequestQuit())) except protocol.ConnectionError: pass # It's likely already (shutting) down, so continue as if it worked. finally: self.close()
A run loop to have agents and an environment interact.
def run_loop(agents, env, max_frames=0, max_episodes=0): """A run loop to have agents and an environment interact.""" total_frames = 0 total_episodes = 0 start_time = time.time() observation_spec = env.observation_spec() action_spec = env.action_spec() for agent, obs_spec, act_spec in zip(agents, observa...
Return the map data for a map by name or path.
def map_data(self, map_name): """Return the map data for a map by name or path.""" with gfile.Open(os.path.join(self.data_dir, "Maps", map_name), "rb") as f: return f.read()
Return the replay data given a path to the replay.
def replay_data(self, replay_path): """Return the replay data given a path to the replay.""" with gfile.Open(self.abs_replay_path(replay_path), "rb") as f: return f.read()
A generator yielding the full path to the replays under `replay_dir`.
def replay_paths(self, replay_dir): """A generator yielding the full path to the replays under `replay_dir`.""" replay_dir = self.abs_replay_path(replay_dir) if replay_dir.lower().endswith(".sc2replay"): yield replay_dir return for f in gfile.ListDir(replay_dir): if f.lower().endswith(...
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...
def save_replay(self, replay_data, replay_dir, prefix=None): """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: Option...
An iterator over all subclasses of `cls`.
def all_subclasses(cls): """An iterator over all subclasses of `cls`.""" for s in cls.__subclasses__(): yield s for c in s.all_subclasses(): yield c
Turn all string indices into int indices, preserving ellipsis.
def _indices(self, indices): """Turn all string indices into int indices, preserving ellipsis.""" if isinstance(indices, tuple): out = [] dim = 0 for i, index in enumerate(indices): if index is Ellipsis: out.append(index) dim = len(self.shape) - len(indices) + i ...
Turn a string into a real index, otherwise return the index.
def _get_index(self, dim, index): """Turn a string into a real index, otherwise return the index.""" if isinstance(index, six.string_types): try: return self._index_names[dim][index] except KeyError: raise KeyError("Name '%s' is invalid for axis %s." % (index, dim)) except Type...
Assign `x` and `y` to an object that has properties `x` and `y`.
def assign_to(self, obj): """Assign `x` and `y` to an object that has properties `x` and `y`.""" obj.x = self.x obj.y = self.y
Distance to some other point.
def dist(self, other): """Distance to some other point.""" dx = self.x - other.x dy = self.y - other.y return math.sqrt(dx**2 + dy**2)
Distance squared to some other point.
def dist_sq(self, other): """Distance squared to some other point.""" dx = self.x - other.x dy = self.y - other.y return dx**2 + dy**2
Round `x` and `y` to integers.
def round(self): """Round `x` and `y` to integers.""" return Point(int(round(self.x)), int(round(self.y)))
Round `x` and `y` down to integers.
def floor(self): """Round `x` and `y` down to integers.""" return Point(int(math.floor(self.x)), int(math.floor(self.y)))
Round `x` and `y` up to integers.
def ceil(self): """Round `x` and `y` up to integers.""" return Point(int(math.ceil(self.x)), int(math.ceil(self.y)))
Bound this point within the rect defined by (`p1`, `p2`).
def bound(self, p1, p2=None): """Bound this point within the rect defined by (`p1`, `p2`).""" r = Rect(p1, p2) return Point(min(max(self.x, r.l), r.r), min(max(self.y, r.t), r.b))
Is the point inside this rect?
def contains_point(self, pt): """Is the point inside this rect?""" return (self.l < pt.x and self.r > pt.x and self.t < pt.y and self.b > pt.y)
Is the circle completely inside this rect?
def contains_circle(self, pt, radius): """Is the circle completely inside this rect?""" return (self.l < pt.x - radius and self.r > pt.x + radius and self.t < pt.y - radius and self.b > pt.y + radius)
Does the circle intersect with this rect?
def intersects_circle(self, pt, radius): """Does the circle intersect with this rect?""" # How this works: http://stackoverflow.com/a/402010 rect_corner = self.size / 2 # relative to the rect center circle_center = (pt - self.center).abs() # relative to the rect center # Is the circle far from th...
Read the ExecuteInfo.txt file and return the base directory.
def _read_execute_info(path, parents): """Read the ExecuteInfo.txt file and return the base directory.""" path = os.path.join(path, "StarCraft II/ExecuteInfo.txt") if os.path.exists(path): with open(path, "rb") as f: # Binary because the game appends a '\0' :(. for line in f: parts = [p.strip()...
Launch the game.
def start(self, version=None, want_rgb=True, **kwargs): """Launch the game.""" del want_rgb # Unused if not os.path.isdir(self.data_dir): raise sc_process.SC2LaunchError( "Expected to find StarCraft II installed at '%s'. If it's not " "installed, do that and run it once so auto-de...
Create a game for the agents to join. Args: map_name: The map to use.
def create_game(self, map_name): """Create a game for the agents to join. Args: map_name: The map to use. """ map_inst = maps.get(map_name) map_data = map_inst.data(self._run_config) if map_name not in self._saved_maps: for controller in self._controllers: controller.save_ma...
Shutdown and free all resources.
def close(self): """Shutdown and free all resources.""" for controller in self._controllers: controller.quit() self._controllers = [] for process in self._processes: process.close() self._processes = [] portspicker.return_ports(self._lan_ports) self._lan_ports = []
Create a game, one remote agent vs the specified bot. Args: map_name: The map to use. bot_difficulty: The difficulty of the bot to play against. bot_race: The race for the bot. bot_first: Whether the bot should be player 1 (else is player 2).
def create_game( self, map_name, bot_difficulty=sc_pb.VeryEasy, bot_race=sc_common.Random, bot_first=False): """Create a game, one remote agent vs the specified bot. Args: map_name: The map to use. bot_difficulty: The difficulty of the bot to play against. bot_ra...
Shutdown and free all resources.
def close(self): """Shutdown and free all resources.""" if self._controller is not None: self._controller.quit() self._controller = None if self._process is not None: self._process.close() self._process = None
Run the agent, connecting to a (remote) host started independently.
def agent(): """Run the agent, connecting to a (remote) host started independently.""" agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module), agent_name) logging.info("Starting agent:") with lan_sc2_env.LanSC2Env( host=FLAGS.host, config_p...
Run a host which expects one player to connect remotely.
def human(): """Run a host which expects one player to connect remotely.""" run_config = run_configs.get() map_inst = maps.get(FLAGS.map) if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size: logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb " "observations....
Make sure this stays synced with bin/agent_remote.py.
def _connect_remote(self, host, host_port, lan_ports, race, name, map_inst, save_map, interface): """Make sure this stays synced with bin/agent_remote.py.""" # Connect! logging.info("Connecting...") self._controllers = [remote_controller.RemoteController(host, host_port)] loggi...
Get the config chosen by the flags.
def get(): """Get the config chosen by the flags.""" configs = {c.name(): c for c in lib.RunConfig.all_subclasses() if c.priority()} if not configs: raise sc_process.SC2LaunchError("No valid run_configs found.") if FLAGS.sc2_run_config is None: # Find the highest priority as default. ret...
Start a new episode.
def reset(self): """Start a new episode.""" self._episode_steps = 0 if self._episode_count: # No need to restart for the first episode. self._restart() self._episode_count += 1 logging.info("Starting episode: %s", self._episode_count) self._metrics.increment_episode() self._las...
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.
def step(self, actions, step_mul=None): """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 namedtu...
Useful for logging messages into the replay.
def send_chat_messages(self, messages): """Useful for logging messages into the replay.""" self._parallel.run( (c.chat, message) for c, message in zip(self._controllers, messages))
Make sure the replay isn't corrupt, and is worth looking at.
def valid_replay(info, ping): """Make sure the replay isn't corrupt, and is worth looking at.""" if (info.HasField("error") or info.base_build != ping.base_build or # different game version info.game_duration_loops < 1000 or len(info.player_info) != 2): # Probably corrupt, or just not interes...
A thread that consumes stats_queue and prints them every 10 seconds.
def stats_printer(stats_queue): """A thread that consumes stats_queue and prints them every 10 seconds.""" proc_stats = [ProcessStats(i) for i in range(FLAGS.parallel)] print_time = start_time = time.time() width = 107 running = True while running: print_time += 10 while time.time() < print_time: ...
Dump stats about all the actions that are in use in a set of replays.
def main(unused_argv): """Dump stats about all the actions that are in use in a set of replays.""" run_config = run_configs.get() if not gfile.Exists(FLAGS.replays): sys.exit("{} doesn't exist.".format(FLAGS.replays)) stats_queue = multiprocessing.Queue() stats_thread = threading.Thread(target=stats_pri...
Merge another ReplayStats into this one.
def merge(self, other): """Merge another ReplayStats into this one.""" def merge_dict(a, b): for k, v in six.iteritems(b): a[k] += v self.replays += other.replays self.steps += other.steps self.camera_move += other.camera_move self.select_pt += other.select_pt self.select_rect...
Process a single replay, updating the stats.
def process_replay(self, controller, replay_data, map_data, player_id): """Process a single replay, updating the stats.""" self._update_stage("start_replay") controller.start_replay(sc_pb.RequestStartReplay( replay_data=replay_data, map_data=map_data, options=interface, obser...
Start up the tcp server, send the settings.
def tcp_server(tcp_addr, settings): """Start up the tcp server, send the settings.""" family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP) sock.bind(tcp_addr) sock.listen(1) logging.info("Waiting for connection on %s", tcp_ad...
Connect to the tcp server, and return the settings.
def tcp_client(tcp_addr): """Connect to the tcp server, and return the settings.""" family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP) for i in range(300): logging.info("Connecting to: %s, attempt %d", tcp_addr, i) try:...
Read `size` number of bytes from `conn`, retrying as needed.
def read_tcp_size(conn, size): """Read `size` number of bytes from `conn`, retrying as needed.""" chunks = [] bytes_read = 0 while bytes_read < size: chunk = conn.recv(size - bytes_read) if not chunk: if bytes_read > 0: logging.warning("Incomplete read: %s of %s.", bytes_read, size) ...
Forwards ports such that multiplayer works between machines. Args: remote_host: Where to ssh to. local_host: "127.0.0.1" or "::1". local_listen_ports: Which ports to listen on locally to forward remotely. remote_listen_ports: Which ports to listen on remotely to forward locally. Returns: The s...
def forward_ports(remote_host, local_host, local_listen_ports, remote_listen_ports): """Forwards ports such that multiplayer works between machines. Args: remote_host: Where to ssh to. local_host: "127.0.0.1" or "::1". local_listen_ports: Which ports to listen on locally to forward re...
Make sure this stays synced with bin/play_vs_agent.py.
def _launch_remote(self, host, config_port, race, name, interface): """Make sure this stays synced with bin/play_vs_agent.py.""" self._tcp_conn, settings = tcp_client(Addr(host, config_port)) self._map_name = settings["map_name"] if settings["remote"]: self._udp_sock = udp_server( Addr...
Output information for a directory of replays.
def _replay_index(replay_dir): """Output information for a directory of replays.""" run_config = run_configs.get() replay_dir = run_config.abs_replay_path(replay_dir) print("Checking: ", replay_dir) with run_config.start(want_rgb=False) as controller: print("-" * 60) print(",".join(( "filenam...
Query a replay for information.
def _replay_info(replay_path): """Query a replay for information.""" if not replay_path.lower().endswith("sc2replay"): print("Must be a replay.") return run_config = run_configs.get() with run_config.start(want_rgb=False) as controller: info = controller.replay_info(run_config.replay_data(replay_pa...
Takes an array of ints and returns a corresponding colored rgb array.
def smooth_hue_palette(scale): """Takes an array of ints and returns a corresponding colored rgb array.""" # http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL # Based on http://stackoverflow.com/a/17382854 , with simplifications and # optimizations. Assumes S=1, L=0.5, meaning C=1 and m=0. # 0 stays black, ev...
Create a palette that is piece-wise linear given some colors at points.
def piece_wise_linear(scale, points): """Create a palette that is piece-wise linear given some colors at points.""" assert len(points) >= 2 assert points[0][0] == 0 assert points[-1][0] == 1 assert all(i < j for i, j in zip(points[:-1], points[1:])) out = numpy.zeros((scale, 3)) p1, c1 = points[0] p2, c...
Returns a palette that maps unit types to rgb colors.
def unit_type(scale=None): """Returns a palette that maps unit types to rgb colors.""" # Can specify a scale to match the api or to accept unknown unit types. palette_size = scale or max(static_data.UNIT_TYPES) + 1 palette = shuffled_hue(palette_size) assert len(static_data.UNIT_TYPES) <= len(distinct_colors)...
Make sure the lock is held while in this function.
def with_lock(lock): """Make sure the lock is held while in this function.""" def decorator(func): @functools.wraps(func) def _with_lock(*args, **kwargs): with lock: return func(*args, **kwargs) return _with_lock return decorator
Get the desktop size.
def _get_desktop_size(): """Get the desktop size.""" if platform.system() == "Linux": try: xrandr_query = subprocess.check_output(["xrandr", "--query"]) sizes = re.findall(r"\bconnected primary (\d+)x(\d+)", str(xrandr_query)) if sizes[0]: return point.Point(int(sizes[0][0]), int(sizes...
Draw an arc using world coordinates, radius, start and stop angles.
def draw_arc(self, color, world_loc, world_radius, start_angle, stop_angle, thickness=1): """Draw an arc using world coordinates, radius, start and stop angles.""" center = self.world_to_surf.fwd_pt(world_loc).round() radius = max(1, int(self.world_to_surf.fwd_dist(world_radius))) rect = ...
Draw a circle using world coordinates and radius.
def draw_circle(self, color, world_loc, world_radius, thickness=0): """Draw a circle using world coordinates and radius.""" if world_radius > 0: center = self.world_to_surf.fwd_pt(world_loc).round() radius = max(1, int(self.world_to_surf.fwd_dist(world_radius))) pygame.draw.circle(self.surf, c...
Draw a rectangle using world coordinates.
def draw_rect(self, color, world_rect, thickness=0): """Draw a rectangle using world coordinates.""" tl = self.world_to_surf.fwd_pt(world_rect.tl).round() br = self.world_to_surf.fwd_pt(world_rect.br).round() rect = pygame.Rect(tl, br - tl) pygame.draw.rect(self.surf, color, rect, thickness)
Fill this surface using the contents of a numpy array.
def blit_np_array(self, array): """Fill this surface using the contents of a numpy array.""" with sw("make_surface"): raw_surface = pygame.surfarray.make_surface(array.transpose([1, 0, 2])) with sw("draw"): pygame.transform.scale(raw_surface, self.surf.get_size(), self.surf)
Write to the screen in font.size relative coordinates.
def write_screen(self, font, color, screen_pos, text, align="left", valign="top"): """Write to the screen in font.size relative coordinates.""" pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize() text_surf = font.render(str(text), True, color) rect = text_surf....
Given an Action, return the right spatial action.
def action_spatial(self, action): """Given an Action, return the right spatial action.""" if self.surf.surf_type & SurfType.FEATURE: return action.action_feature_layer elif self.surf.surf_type & SurfType.RGB: return action.action_render else: assert self.surf.surf_type & (SurfType.RGB ...
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 i...
def init(self, game_info, static_data): """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 ...
Initialize the pygame window and lay out the surfaces.
def init_window(self): """Initialize the pygame window and lay out the surfaces.""" if platform.system() == "Windows": # Enable DPI awareness on Windows to give the correct window size. ctypes.windll.user32.SetProcessDPIAware() # pytype: disable=module-attr pygame.init() if self._desktop_...
Update the camera transform based on the new camera center.
def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._world_to_world_tl.fwd_pt(camera_center) * self._world_tl_to_world_camera_rel.scale) if self._feature_screen_px: camera_radius...
Return a MousePos filled with the world position and surf it hit.
def get_mouse_pos(self, window_pos=None): """Return a MousePos filled with the world position and surf it hit.""" window_pos = window_pos or pygame.mouse.get_pos() # +0.5 to center the point on the middle of the pixel. window_pt = point.Point(*window_pos) + 0.5 for surf in reversed(self._surfaces): ...
Get actions from the UI, apply to controller, and return an ActionCmd.
def get_actions(self, run_config, controller): """Get actions from the UI, apply to controller, and return an ActionCmd.""" if not self._initialized: return ActionCmd.STEP for event in pygame.event.get(): ctrl = pygame.key.get_mods() & pygame.KMOD_CTRL shift = pygame.key.get_mods() & pyga...
Return a `sc_pb.Action` with the camera movement filled.
def camera_action(self, mouse_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() action_spatial = mouse_pos.action_spatial(action) mouse_pos.obs_pos.assign_to(action_spatial.camera_move.center_minimap) return action
Return a `sc_pb.Action` with the camera movement filled.
def camera_action_raw(self, world_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() world_pos.assign_to(action.action_raw.camera_move.center_world_space) return action
Return a `sc_pb.Action` with the selection filled.
def select_action(self, pos1, pos2, ctrl, shift): """Return a `sc_pb.Action` with the selection filled.""" assert pos1.surf.surf_type == pos2.surf.surf_type assert pos1.surf.world_to_obs == pos2.surf.world_to_obs action = sc_pb.Action() action_spatial = pos1.action_spatial(action) if pos1.worl...
Select an idle worker.
def select_idle_worker(self, ctrl, shift): """Select an idle worker.""" action = sc_pb.Action() mod = sc_ui.ActionSelectIdleWorker if ctrl: select_worker = mod.AddAll if shift else mod.All else: select_worker = mod.Add if shift else mod.Set action.action_ui.select_idle_worker.type = ...
Select the entire army.
def select_army(self, shift): """Select the entire army.""" action = sc_pb.Action() action.action_ui.select_army.selection_add = shift return action
Select all warp gates.
def select_warp_gates(self, shift): """Select all warp gates.""" action = sc_pb.Action() action.action_ui.select_warp_gates.selection_add = shift return action
Select all larva.
def select_larva(self): """Select all larva.""" action = sc_pb.Action() action.action_ui.select_larva.SetInParent() # Adds the empty proto field. return action
Act on a control group, selecting, setting, etc.
def control_group(self, control_group_id, ctrl, shift, alt): """Act on a control group, selecting, setting, etc.""" action = sc_pb.Action() select = action.action_ui.control_group mod = sc_ui.ActionControlGroup if not ctrl and not shift and not alt: select.action = mod.Recall elif ctrl an...
Return a `sc_pb.Action` filled with the cmd and appropriate target.
def unit_action(self, cmd, pos, shift): """Return a `sc_pb.Action` filled with the cmd and appropriate target.""" action = sc_pb.Action() if pos: action_spatial = pos.action_spatial(action) unit_command = action_spatial.unit_command unit_command.ability_id = cmd.ability_id unit_comma...
Return the list of abilities filtered by `fn`.
def _abilities(self, fn=None): """Return the list of abilities filtered by `fn`.""" out = {} for cmd in self._obs.observation.abilities: ability = _Ability(cmd, self._static_data.abilities) if not fn or fn(ability): out[ability.ability_id] = ability return list(out.values())
A generator of visible units and their positions as `Point`s, sorted.
def _visible_units(self): """A generator of visible units and their positions as `Point`s, sorted.""" # Sort the units by elevation, then owned (eg refinery) above world (ie 16) # (eg geiser), small above big, and otherwise arbitrary but stable. for u in sorted(self._obs.observation.raw_data.units, ...
Return the list of units that intersect the rect.
def _units_in_area(self, rect): """Return the list of units that intersect the rect.""" player_id = self._obs.observation.player_common.player_id return [u for u, p in self._visible_units() if rect.intersects_circle(p, u.radius) and u.owner == player_id]
Get a length limited unit name for drawing units.
def get_unit_name(self, surf, name, radius): """Get a length limited unit name for drawing units.""" key = (name, radius) if key not in self._name_lengths: max_len = surf.world_to_surf.fwd_dist(radius * 1.6) for i in range(len(name)): if self._font_small.size(name[:i + 1])[0] > max_len: ...
Draw the units and buildings.
def draw_units(self, surf): """Draw the units and buildings.""" for u, p in self._visible_units(): if self._camera.intersects_circle(p, u.radius): fraction_damage = clamp((u.health_max - u.health) / (u.health_max or 1), 0, 1) surf.draw_circle(colors.PLAYER_A...
Draw the build target.
def draw_build_target(self, surf): """Draw the build target.""" round_half = lambda v, cond: round(v - 0.5) + 0.5 if cond else round(v) queued_action = self._queued_action if queued_action: radius = queued_action.footprint_radius if radius: pos = self.get_mouse_pos() if pos:...
Draw the selection rectange.
def draw_selection(self, surf): """Draw the selection rectange.""" select_start = self._select_start # Cache to avoid a race condition. if select_start: mouse_pos = self.get_mouse_pos() if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and mouse_pos.surf.surf_type == select...
Draw the overlay describing resources.
def draw_overlay(self, surf): """Draw the overlay describing resources.""" obs = self._obs.observation player = obs.player_common surf.write_screen( self._font_large, colors.green, (0.2, 0.2), "Minerals: %s, Vespene: %s, Food: %s / %s" % ( player.minerals, player.vespene, pla...
Draw the help dialog.
def draw_help(self, surf): """Draw the help dialog.""" if not self._help: return def write(loc, text): surf.write_screen(self._font_large, colors.black, loc, text) surf.surf.fill(colors.white * 0.8) write((1, 1), "Shortcuts:") max_len = max(len(s) for s, _ in self.shortcuts) f...
Draw the list of available commands.
def draw_commands(self, surf): """Draw the list of available commands.""" past_abilities = {act.ability for act in self._past_actions if act.ability} for y, cmd in enumerate(sorted(self._abilities( lambda c: c.name != "Smart"), key=lambda c: c.name), start=2): if self._queued_action and cmd ==...
Draw the unit selection or build queue.
def draw_panel(self, surf): """Draw the unit selection or build queue.""" left = -12 # How far from the right border def unit_name(unit_type): return self._static_data.units.get(unit_type, "<unknown>") def write(loc, text, color=colors.yellow): surf.write_screen(self._font_large, color, ...
Keep a list of the past actions so they can be drawn.
def prepare_actions(self, obs): """Keep a list of the past actions so they can be drawn.""" now = time.time() while self._past_actions and self._past_actions[0].deadline < now: self._past_actions.pop(0) def add_act(ability_id, color, pos, timeout=1): if ability_id: ability = self._s...
Draw the actions so that they can be inspected for accuracy.
def draw_actions(self): """Draw the actions so that they can be inspected for accuracy.""" now = time.time() for act in self._past_actions: if act.pos and now < act.deadline: remain = (act.deadline - now) / (act.deadline - act.time) if isinstance(act.pos, point.Point): size =...
Draw the base map.
def draw_base_map(self, surf): """Draw the base map.""" hmap_feature = features.SCREEN_FEATURES.height_map hmap = hmap_feature.unpack(self._obs.observation) if not hmap.any(): hmap = hmap + 100 # pylint: disable=g-no-augmented-assignment hmap_color = hmap_feature.color(hmap) creep_featur...
Draw the minimap.
def draw_mini_map(self, surf): """Draw the minimap.""" if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("minimap")): # Draw the rendered version. surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.obs...
Draw the rendered pixels.
def draw_rendered_map(self, surf): """Draw the rendered pixels.""" surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.observation.render_data.map))
Draw the screen area.
def draw_screen(self, surf): """Draw the screen area.""" # surf.fill(colors.black) if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("map")): self.draw_rendered_map(surf) else: self.draw_base_map(surf) self.dra...
Draw a feature layer.
def draw_feature_layer(self, surf, feature): """Draw a feature layer.""" layer = feature.unpack(self._obs.observation) if layer is not None: surf.blit_np_array(feature.color(layer)) else: # Ignore layers that aren't in this version of SC2. surf.surf.fill(colors.black)
Push an observation onto the queue to be rendered.
def render(self, obs): """Push an observation onto the queue to be rendered.""" if not self._initialized: return now = time.time() self._game_times.append( (now - self._last_time, max(1, obs.observation.game_loop - self._obs.observation.game_loop))) self._last_time = now s...
A render loop that pulls observations off the queue to render.
def render_thread(self): """A render loop that pulls observations off the queue to render.""" obs = True while obs: # Send something falsy through the queue to shut down. obs = self._obs_queue.get() if obs: for alert in obs.observation.alerts: self._alerts[sc_pb.Alert.Name(ale...
Render a frame given an observation.
def render_obs(self, obs): """Render a frame given an observation.""" start_time = time.time() self._obs = obs self.check_valid_queued_action() self._update_camera(point.Point.build( self._obs.observation.raw_data.player.camera)) for surf in self._surfaces: # Render that surface. ...
Run loop that gets observations, renders them, and sends back actions.
def run(self, run_config, controller, max_game_steps=0, max_episodes=0, game_steps_per_episode=0, save_replay=False): """Run loop that gets observations, renders them, and sends back actions.""" is_replay = (controller.status == remote_controller.Status.in_replay) total_game_steps = 0 start_ti...
A context manager that translates websocket errors into ConnectionError.
def catch_websocket_connection_errors(): """A context manager that translates websocket errors into ConnectionError.""" try: yield except websocket.WebSocketConnectionClosedException: raise ConnectionError("Connection already closed. SC2 probably crashed. " "Check the error log."...
Read a Response, do some validation, and return it.
def read(self): """Read a Response, do some validation, and return it.""" if FLAGS.sc2_verbose_protocol: self._log(" Reading response ".center(60, "-")) start = time.time() response = self._read() if FLAGS.sc2_verbose_protocol: self._log(" %0.1f msec\n" % (1000 * (time.time() - start))...
Write a Request.
def write(self, request): """Write a Request.""" if FLAGS.sc2_verbose_protocol: self._log(" Writing request ".center(60, "-") + "\n") self._log_packet(request) self._write(request)
Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request.
def send(self, **kwargs): """Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request. ...
r"""Log a string. It flushes but doesn't append \n, so do that yourself.
def _log(self, s): r"""Log a string. It flushes but doesn't append \n, so do that yourself.""" # TODO(tewalds): Should this be using logging.info instead? How to see them # outside of google infrastructure? sys.stderr.write(s) sys.stderr.flush()
Actually read the response and parse it, returning a Response.
def _read(self): """Actually read the response and parse it, returning a Response.""" with sw("read_response"): with catch_websocket_connection_errors(): response_str = self._sock.recv() if not response_str: raise ProtocolError("Got an empty response from SC2.") response = sc_pb.Resp...
Actually serialize and write the request.
def _write(self, request): """Actually serialize and write the request.""" with sw("serialize_request"): request_str = request.SerializeToString() with sw("write_request"): with catch_websocket_connection_errors(): self._sock.send(request_str)