text stringlengths 81 112k |
|---|
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... |
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_ep... |
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, s... |
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.p... |
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
whi... |
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 = mul... |
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_... |
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_... |
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)
loggin... |
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("... |
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.... |
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... |
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["rem... |
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... |
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... |
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
# optimi... |
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], ... |
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)
ass... |
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(... |
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... |
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(wo... |
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... |
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_surfac... |
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 = f... |
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... |
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... |
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: disab... |
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_re... |
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.... |
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.... |
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 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_spa... |
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.se... |
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:... |
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_co... |
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] ... |
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... |
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 == p... |
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... |
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)
s... |
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
mous... |
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_mou... |
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" % (
... |
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, _ i... |
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):
... |
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):
su... |
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)... |
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, tim... |
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(hma... |
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(
... |
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_m... |
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.obse... |
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... |
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._s... |
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 == r... |
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... |
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.... |
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):
"""C... |
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)
... |
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 ProtocolEr... |
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) |
Get the full dict of maps {map_name: map_class}.
def get_maps():
"""Get the full dict of maps {map_name: map_class}."""
maps = {}
for mp in Map.all_subclasses():
if mp.filename:
map_name = mp.__name__
if map_name in maps:
raise DuplicateMapException("Duplicate map found: " + map_name)
... |
Get an instance of a map by name. Errors if the map doesn't exist.
def get(map_name):
"""Get an instance of a map by name. Errors if the map doesn't exist."""
if isinstance(map_name, Map):
return map_name
# Get the list of maps. This isn't at module scope to avoid problems of maps
# being defined after th... |
The full path to the map file: directory, filename and file ending.
def path(self):
"""The full path to the map file: directory, filename and file ending."""
if self.filename:
map_path = os.path.join(self.directory, self.filename)
if not map_path.endswith(".SC2Map"):
map_path += ".SC2Map"
... |
Return the map data.
def data(self, run_config):
"""Return the map data."""
try:
return run_config.map_data(self.path)
except (IOError, OSError) as e: # Catch both for python 2/3 compatibility.
if self.download and hasattr(e, "filename"):
logging.error("Error reading map '%s' from: %s"... |
Convert (width, height) or size -> point.Point.
def _to_point(dims):
"""Convert (width, height) or size -> point.Point."""
assert dims
if isinstance(dims, (tuple, list)):
if len(dims) != 2:
raise ValueError(
"A two element tuple or list is expected here, got {}.".format(dims))
else:
... |
Creates an AgentInterfaceFormat object from keyword args.
Convenient when using dictionaries or command-line arguments for config.
Note that the feature_* and rgb_* properties define the respective spatial
observation dimensions and accept:
* None or 0 to disable that spatial observation.
* A single... |
Construct a Features object using data extracted from game info.
Args:
game_info: A `sc_pb.ResponseGameInfo` from the game.
use_feature_units: Whether to include the feature unit observation.
use_raw_units: Whether to include raw unit data in observations. This
differs from feature_units because ... |
Initialize ValidFunctions and set up the callbacks.
def _init_valid_functions(action_dimensions):
"""Initialize ValidFunctions and set up the callbacks."""
sizes = {
"screen": tuple(int(i) for i in action_dimensions.screen),
"screen2": tuple(int(i) for i in action_dimensions.screen),
"minimap": t... |
Return a correctly shaped numpy array for this feature.
def unpack(self, obs):
"""Return a correctly shaped numpy array for this feature."""
planes = getattr(obs.feature_layer_data, self.layer_set)
plane = getattr(planes, self.name)
return self.unpack_layer(plane) |
Return a correctly shaped numpy array given the feature layer bytes.
def unpack_layer(plane):
"""Return a correctly shaped numpy array given the feature layer bytes."""
size = point.Point.build(plane.size)
if size == (0, 0):
# New layer that isn't implemented in this SC2 version.
return None
... |
Return a correctly shaped numpy array given the image bytes.
def unpack_rgb_image(plane):
"""Return a correctly shaped numpy array given the image bytes."""
assert plane.bits_per_pixel == 24, "{} != 24".format(plane.bits_per_pixel)
size = point.Point.build(plane.size)
data = np.frombuffer(plane.data, d... |
Initialize the camera (especially for feature_units).
This is called in the constructor and may be called repeatedly after
`Features` is constructed, since it deals with rescaling coordinates and not
changing environment/action specs.
Args:
feature_dimensions: See the documentation in `AgentInte... |
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_re... |
The observation spec for the SC2 environment.
It's worth noting that the image-like observations are in y,x/row,column
order which is different than the actions which are in x,y order. This is
due to conflicting conventions, and to facilitate printing of the images.
Returns:
The dict of observat... |
Render some SC2 observations into something an agent can handle.
def transform_obs(self, obs):
"""Render some SC2 observations into something an agent can handle."""
empty = np.array([], dtype=np.int32).reshape((0, 7))
out = named_array.NamedDict({ # Fill out some that are sometimes empty.
"single... |
Return the list of available action ids.
def available_actions(self, obs):
"""Return the list of available action ids."""
available_actions = set()
hide_specific_actions = self._agent_interface_format.hide_specific_actions
for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE):
if func.avail_f... |
Tranform an agent-style action to one that SC2 can consume.
Args:
obs: a `sc_pb.Observation` from the previous frame.
func_call: a `FunctionCall` to be turned into a `sc_pb.Action`.
skip_available: If True, assume the action is available. This should only
be used for testing or if you e... |
Transform an SC2-style action into an agent-style action.
This should be the inverse of `transform_action`.
Args:
action: a `sc_pb.Action` to be transformed.
Returns:
A corresponding `actions.FunctionCall`.
Raises:
ValueError: if it doesn't know how to transform this action.
def r... |
Mask should be a set of bools from comparison with a feature layer.
def _xy_locs(mask):
"""Mask should be a set of bools from comparison with a feature layer."""
y, x = mask.nonzero()
return list(zip(x, y)) |
Run SC2 to play a game or a replay.
def main(unused_argv):
"""Run SC2 to play a game or a replay."""
stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace
stopwatch.sw.trace = FLAGS.trace
if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay):
sys.exit("Must supply either a map or replay.")... |
Wait for a proc to shut down, then terminate or kill it after `timeout`.
def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for _ in range(1 + timeout * freq):
ret = p.poll()
if ret is not None:
l... |
Shut down the game and clean up.
def close(self):
"""Shut down the game and clean up."""
if hasattr(self, "_controller") and self._controller:
self._controller.quit()
self._controller.close()
self._controller = None
self._shutdown()
if hasattr(self, "_port") and self._port:
port... |
Launch the process and return the process object.
def _launch(self, run_config, args, **kwargs):
"""Launch the process and return the process object."""
del kwargs
try:
with sw("popen"):
return subprocess.Popen(args, cwd=run_config.cwd, env=run_config.env)
except OSError:
logging.ex... |
Terminate the sub-process.
def _shutdown(self):
"""Terminate the sub-process."""
if self._proc:
ret = _shutdown_proc(self._proc, 3)
logging.info("Shutdown with return code: %s", ret)
self._proc = None |
Retrieve static data from the game.
def get_data():
"""Retrieve static data from the game."""
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
m = maps.get("Sequencer") # Arbitrary ladder map.
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path... |
Generate a CSV of the abilities for easy commenting.
def generate_csv(data):
"""Generate a CSV of the abilities for easy commenting."""
print(",".join([
"ability_id",
"link_name",
"link_index",
"button_name",
"hotkey",
"friendly_name",
"remap_to",
"mismatch",
]))
... |
Generate the list of functions in actions.py.
def generate_py_abilities(data):
"""Generate the list of functions in actions.py."""
def print_action(func_id, name, func, ab_id, general_id):
args = [func_id, '"%s"' % name, func, ab_id]
if general_id:
args.append(general_id)
print(" Function.abil... |
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:"... |
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_mini... |
Standard deviation.
def dev(self):
"""Standard deviation."""
if self.num == 0:
return 0
return math.sqrt(max(0, self.sum_sq / self.num - (self.sum / self.num)**2)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.