Instruction:
Create a Python 3 function for
selecting all warp gates.

Response:
def select_warp_gates(action, action_space, select_add):
  """Select all warp gates."""
  del action_space
  action.action_ui.select_warp_gates.selection_add = select_add


Instruction:
Can you generate a brief explanation for the following Python 3 code
def select_unit(action, action_space, select_unit_act, select_unit_id):
  del action_space
  select = action.action_ui.multi_panel
  select.type = select_unit_act
  select.unit_index = select_unit_id

Response: Select a specific unit from the multi - unit selection.


Instruction:
Can you generate the documentation for the following Python 3 function
def control_group(action, action_space, control_group_act, control_group_id):
  del action_space
  select = action.action_ui.control_group
  select.action = control_group_act
  select.control_group_index = control_group_id

Response: Act on a control group selecting setting etc.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unload(action, action_space, unload_id):
  del action_space
  action.action_ui.cargo_panel.unit_index = unload_id

Response: Unload a unit from a transport


Instruction:
Can you generate a brief explanation for the following Python 3 code
def build_queue(action, action_space, build_queue_id):
  del action_space
  action.action_ui.production_panel.unit_index = build_queue_id

Response: Cancel a unit in the build queue.


Instruction:
Can you write a function in Python 3 where it
does a quick command like Stop or Stim.

Response:
def cmd_quick(action, action_space, ability_id, queued):
  """Do a quick command like 'Stop' or 'Stim'."""
  action_cmd = spatial(action, action_space).unit_command
  action_cmd.ability_id = ability_id
  action_cmd.queue_command = queued


Instruction:
Can you generate the documentation for the following Python 3 function
def cmd_screen(action, action_space, ability_id, queued, screen):
  action_cmd = spatial(action, action_space).unit_command
  action_cmd.ability_id = ability_id
  action_cmd.queue_command = queued
  screen.assign_to(action_cmd.target_screen_coord)

Response: Do a command that needs a point on the screen.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cmd_minimap(action, action_space, ability_id, queued, minimap):
  action_cmd = spatial(action, action_space).unit_command
  action_cmd.ability_id = ability_id
  action_cmd.queue_command = queued
  minimap.assign_to(action_cmd.target_minimap_coord)

Response: Do a command that needs a point on the minimap.


Instruction:
Given the following Python 3 function, write the documentation
def enum(cls, options, values):
    names, real = zip(*options)
    del names  # unused

    def factory(i, name):
      return cls(i, name, (len(real),), lambda a: real[a[0]], values)
    return factory

Response: Create an ArgumentType where you choose one of a set of known values.


Instruction:
Write a Python 3 script to
create an ArgumentType with a single scalar in range value.

Response:
def scalar(cls, value):
    """Create an ArgumentType with a single scalar in range(value)."""
    return lambda i, name: cls(i, name, (value,), lambda a: a[0], None)


Instruction:
Implement a Python 3 function for
creating an ArgumentType that is represented by a point. Point.

Response:
def point(cls):  # No range because it's unknown at this time.
    """Create an ArgumentType that is represented by a point.Point."""
    def factory(i, name):
      return cls(i, name, (0, 0), lambda a: point.Point(*a).floor(), None)
    return factory


Instruction:
Can you generate the documentation for the following Python 3 function
def types(cls, **kwargs):
    named = {name: factory(Arguments._fields.index(name), name)
             for name, factory in six.iteritems(kwargs)}
    return cls(**named)

Response: Create an Arguments of the possible Types.


Instruction:
Make a summary of the following Python 3 code
def ui_func(cls, id_, name, function_type, avail_fn=always):
    return cls(id_, name, 0, 0, function_type, FUNCTION_TYPES[function_type],
               avail_fn)

Response: Define a function representing a ui action.


Instruction:
Make a summary of the following Python 3 code
def ability(cls, id_, name, function_type, ability_id, general_id=0):
    assert function_type in ABILITY_FUNCTIONS
    return cls(id_, name, ability_id, general_id, function_type,
               FUNCTION_TYPES[function_type], None)

Response: Define a function represented as a game ability.


Instruction:
Write a Python 3 function that can
string version of the object.

Response:
def str(self, space=False):
    """String version. Set space=True to line them all up nicely."""
    return "%s/%s (%s)" % (str(int(self.id)).rjust(space and 4),
                           self.name.ljust(space and 50),
                           "; ".join(str(a) for a in self.args))


Instruction:
Can you write a function in Python 3 where it
initializes a new FunctionCall instance with some validation for the function and arguments.

Response:
def init_with_validation(cls, function, arguments):
    """Return a `FunctionCall` given some validation for the function and args.

    Args:
      function: A function name or id, to be converted into a function id enum.
      arguments: An iterable of function arguments. Arguments that are enum
          types can be passed by name. Arguments that only take one value (ie
          not a point) don't need to be wrapped in a list.

    Returns:
      A new `FunctionCall` instance.

    Raises:
      KeyError: if the enum name doesn't exist.
      ValueError: if the enum id doesn't exist.
    """
    func = FUNCTIONS[function]
    args = []
    for arg, arg_type in zip(arguments, func.args):
      if arg_type.values:  # Allow enum values by name or int.
        if isinstance(arg, six.string_types):
          try:
            args.append([arg_type.values[arg]])
          except KeyError:
            raise KeyError("Unknown argument value: %s, valid values: %s" % (
                arg, [v.name for v in arg_type.values]))
        else:
          if isinstance(arg, (list, tuple)):
            arg = arg[0]
          try:
            args.append([arg_type.values(arg)])
          except ValueError:
            raise ValueError("Unknown argument value: %s, valid values: %s" % (
                arg, list(arg_type.values)))
      elif isinstance(arg, int):  # Allow bare ints.
        args.append([arg])
      else:  # Allow tuples or iterators.
        args.append(list(arg))
    return cls(func.id, args)


Instruction:
Implement a Python 3 function for
printing the valid actions.

Response:
def main(unused_argv):
  """Print the valid actions."""
  feats = features.Features(
      # Actually irrelevant whether it's feature or rgb size.
      features.AgentInterfaceFormat(
          feature_dimensions=features.Dimensions(
              screen=FLAGS.screen_size,
              minimap=FLAGS.minimap_size)))
  action_spec = feats.action_spec()
  flattened = 0
  count = 0
  for func in action_spec.functions:
    if FLAGS.hide_specific and actions.FUNCTIONS[func.id].general_id != 0:
      continue
    count += 1
    act_flat = 1
    for arg in func.args:
      for size in arg.sizes:
        act_flat *= size
    flattened += act_flat
    print(func.str(True))
  print("Total base actions:", count)
  print("Total possible actions (flattened):", flattened)


Instruction:
Given the following Python 3 function, write the documentation
def pick_unused_ports(num_ports, retry_interval_secs=3, retry_attempts=5):
  ports = set()
  for _ in range(retry_attempts):
    ports.update(
        portpicker.pick_unused_port() for _ in range(num_ports - len(ports)))
    ports.discard(None)  # portpicker returns None on error.
    if len(ports) == num_ports:
      return list(ports)
    # Duplicate ports can be returned, especially when insufficient ports are
    # free. Wait for more ports to be freed and retry.
    time.sleep(retry_interval_secs)

  # Could not obtain enough ports. Release what we do have.
  return_ports(ports)

  raise RuntimeError("Unable to obtain %d unused ports." % num_ports)

Response: Reserves and returns a list of num_ports unused ports.


Instruction:
Write a Python 3 script for
reserving and returns a list of num_ports contiguous unused ports.

Response:
def pick_contiguous_unused_ports(
    num_ports,
    retry_interval_secs=3,
    retry_attempts=5):
  """Reserves and returns a list of `num_ports` contiguous unused ports."""
  for _ in range(retry_attempts):
    start_port = portpicker.pick_unused_port()
    if start_port is not None:
      ports = [start_port + p for p in range(num_ports)]
      if all(portpicker.is_port_free(p) for p in ports):
        return ports
      else:
        return_ports(ports)

    time.sleep(retry_interval_secs)

  raise RuntimeError("Unable to obtain %d contiguous unused ports." % num_ports)


Instruction:
Can you generate the documentation for the following Python 3 function
def run_thread(agent_classes, players, map_name, visualize):
  with sc2_env.SC2Env(
      map_name=map_name,
      players=players,
      agent_interface_format=sc2_env.parse_agent_interface_format(
          feature_screen=FLAGS.feature_screen_size,
          feature_minimap=FLAGS.feature_minimap_size,
          rgb_screen=FLAGS.rgb_screen_size,
          rgb_minimap=FLAGS.rgb_minimap_size,
          action_space=FLAGS.action_space,
          use_feature_units=FLAGS.use_feature_units),
      step_mul=FLAGS.step_mul,
      game_steps_per_episode=FLAGS.game_steps_per_episode,
      disable_fog=FLAGS.disable_fog,
      visualize=visualize) as env:
    env = available_actions_printer.AvailableActionsPrinter(env)
    agents = [agent_cls() for agent_cls in agent_classes]
    run_loop.run_loop(agents, env, FLAGS.max_agent_steps, FLAGS.max_episodes)
    if FLAGS.save_replay:
      env.save_replay(agent_classes[0].__name__)

Response: Runs one thread worth of the environment with agents.


Instruction:
Can you generate the documentation for the following Python 3 function
def check_error(res, error_enum):
  if res.HasField("error"):
    enum_name = error_enum.DESCRIPTOR.full_name
    error_name = error_enum.Name(res.error)
    details = getattr(res, "error_details", "<none>")
    raise RequestError("%s.%s: '%s'" % (enum_name, error_name, details), res)
  return res

Response: Raise if the result has an error otherwise return the result.


Instruction:
Can you tell what is the following Python 3 function doing
def decorate_check_error(error_enum):
  def decorator(func):
    @functools.wraps(func)
    def _check_error(*args, **kwargs):
      return check_error(func(*args, **kwargs), error_enum)
    return _check_error
  return decorator

Response: Decorator to call check_error on the return value.


Instruction:
Can you generate the documentation for the following Python 3 function
def catch_game_end(func):
  @functools.wraps(func)
  def _catch_game_end(self, *args, **kwargs):
    """Decorator to handle 'Game has already ended' exceptions."""
    prev_status = self.status
    try:
      return func(self, *args, **kwargs)
    except protocol.ProtocolError as protocol_error:
      if prev_status == Status.in_game and (
          "Game has already ended" in str(protocol_error)):
        # It's currently possible for us to receive this error even though
        # our previous status was in_game. This shouldn't happen according
        # to the protocol. It does happen sometimes when we don't observe on
        # every step (possibly also requiring us to be playing against a
        # built-in bot). To work around the issue, we catch the exception
        # and so let the client code continue.
        logging.warning(
            "Received a 'Game has already ended' error from SC2 whilst status "
            "in_game. Suppressing the exception, returning None.")

        return None
      else:
        raise

  return _catch_game_end

Response: Decorator to catch Game has already ended exceptions.


Instruction:
Create a Python 3 function for
connecting to the SC2 websocket.

Response:
def _connect(self, host, port, proc, timeout_seconds):
    """Connect to the websocket, retrying as needed. Returns the socket."""
    if ":" in host and not host.startswith("["):  # Support ipv6 addresses.
      host = "[%s]" % host
    url = "ws://%s:%s/sc2api" % (host, port)

    was_running = False
    for i in range(timeout_seconds):
      is_running = proc and proc.running
      was_running = was_running or is_running
      if (i >= timeout_seconds // 4 or was_running) and not is_running:
        logging.warning(
            "SC2 isn't running, so bailing early on the websocket connection.")
        break
      logging.info("Connecting to: %s, attempt: %s, running: %s", url, i,
                   is_running)
      try:
        return websocket.create_connection(url, timeout=timeout_seconds)
      except socket.error:
        pass  # SC2 hasn't started listening yet.
      except websocket.WebSocketBadStatusException as err:
        if err.status_code == 404:
          pass  # SC2 is listening, but hasn't set up the /sc2api endpoint yet.
        else:
          raise
      time.sleep(1)
    raise ConnectError("Failed to connect to the SC2 websocket. Is it up?")


Instruction:
How would you code a function in Python 3 to
save a map into temp dir so create game can access it in multiplayer.

Response:
def save_map(self, map_path, map_data):
    """Save a map into temp dir so create game can access it in multiplayer."""
    return self._client.send(save_map=sc_pb.RequestSaveMap(
        map_path=map_path, map_data=map_data))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def data_raw(self):
    return self._client.send(data=sc_pb.RequestData(
        ability_id=True, unit_type_id=True))

Response: Get the raw static data for the current game. Prefer data instead.


Instruction:
Can you write a function in Python 3 where it
steps the engine forward by one step.

Response:
def step(self, count=1):
    """Step the engine forward by one (or more) step."""
    return self._client.send(step=sc_pb.RequestStep(count=count))


Instruction:
Can you write a function in Python 3 where it
sends a sc_pb. RequestAction which may include multiple actions.

Response:
def actions(self, req_action):
    """Send a `sc_pb.RequestAction`, which may include multiple actions."""
    if FLAGS.sc2_log_actions:
      for action in req_action.actions:
        sys.stderr.write(str(action))
        sys.stderr.flush()

    return self._client.send(action=req_action)


Instruction:
Can you generate the documentation for the following Python 3 function
def act(self, action):
    if action and action.ListFields():  # Skip no-ops.
      return self.actions(sc_pb.RequestAction(actions=[action]))

Response: Send a single action. This is a shortcut for actions.


Instruction:
How would you explain what the following Python 3 function does
def chat(self, message):
    if message:
      action_chat = sc_pb.ActionChat(
          channel=sc_pb.ActionChat.Broadcast, message=message)
      action = sc_pb.Action(action_chat=action_chat)
      return self.act(action)

Response: Send chat message as a broadcast.


Instruction:
Explain what the following Python 3 code does
def save_replay(self):
    res = self._client.send(save_replay=sc_pb.RequestSaveReplay())
    return res.data

Response: Save a replay returning the data.


Instruction:
Create a Python 3 function to
run a debug command.

Response:
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))


Instruction:
Can you create a Python 3 function that
shuts down the SC2 process.

Response:
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()


Instruction:
How would you implement a function in Python 3 that
returns the map data for a map by name or path.

Response:
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()


Instruction:
How would you explain what the following Python 3 function does
def replay_data(self, replay_path):
    with gfile.Open(self.abs_replay_path(replay_path), "rb") as f:
      return f.read()

Response: Return the replay data given a path to the replay.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def replay_paths(self, 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(".sc2replay"):
        yield os.path.join(replay_dir, f)

Response: A generator yielding the full path to the replays under replay_dir.


Instruction:
Write a Python 3 function that can
save a replay to a directory.

Response:
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: Optional prefix for the replay filename.

    Returns:
      The full path where the replay is saved.

    Raises:
      ValueError: If the prefix contains the path seperator.
    """
    if not prefix:
      replay_filename = ""
    elif os.path.sep in prefix:
      raise ValueError("Prefix '%s' contains '%s', use replay_dir instead." % (
          prefix, os.path.sep))
    else:
      replay_filename = prefix + "_"
    now = datetime.datetime.utcnow().replace(microsecond=0)
    replay_filename += "%s.SC2Replay" % now.isoformat("-").replace(":", "-")
    replay_dir = self.abs_replay_path(replay_dir)
    if not gfile.Exists(replay_dir):
      gfile.MakeDirs(replay_dir)
    replay_path = os.path.join(replay_dir, replay_filename)
    with gfile.Open(replay_path, "wb") as f:
      f.write(replay_data)
    return replay_path


Instruction:
Can you generate a brief explanation for the following Python 3 code
def all_subclasses(cls):
    for s in cls.__subclasses__():
      yield s
      for c in s.all_subclasses():
        yield c

Response: An iterator over all subclasses of cls.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _indices(self, indices):
    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
        else:
          out.append(self._get_index(dim, index))
        dim += 1
      return tuple(out)
    else:
      return self._get_index(0, indices)

Response: Turn all string indices into int indices preserving ellipsis.


Instruction:
Given the following Python 3 function, write the documentation
def _get_index(self, dim, 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 TypeError:
        raise TypeError(
            "Trying to access an unnamed axis %s by name: '%s'" % (dim, index))
    else:
      return index

Response: Turn a string into a real index otherwise return the index.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def assign_to(self, obj):
    obj.x = self.x
    obj.y = self.y

Response: Assign x and y to an object that has properties x and y.


Instruction:
Given the following Python 3 function, write the documentation
def dist(self, other):
    dx = self.x - other.x
    dy = self.y - other.y
    return math.sqrt(dx**2 + dy**2)

Response: Distance to some other point.


Instruction:
Can you tell what is the following Python 3 function doing
def dist_sq(self, other):
    dx = self.x - other.x
    dy = self.y - other.y
    return dx**2 + dy**2

Response: Distance squared to some other point.


Instruction:
Can you tell what is the following Python 3 function doing
def round(self):
    return Point(int(round(self.x)), int(round(self.y)))

Response: Round x and y to integers.


Instruction:
Can you generate the documentation for the following Python 3 function
def floor(self):
    return Point(int(math.floor(self.x)), int(math.floor(self.y)))

Response: Round x and y down to integers.


Instruction:
Can you generate the documentation for the following Python 3 function
def ceil(self):
    return Point(int(math.ceil(self.x)), int(math.ceil(self.y)))

Response: Round x and y up to integers.


Instruction:
Create a Python 3 function to
bind this point within the rect defined by p1 and p2.

Response:
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))


Instruction:
Make a summary of the following Python 3 code
def contains_point(self, pt):
    return (self.l < pt.x and self.r > pt.x and
            self.t < pt.y and self.b > pt.y)

Response: Is the point inside this rect?


Instruction:
Implement a function in Python 3 to
am the circle completely inside this rect?

Response:
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)


Instruction:
Implement a Python 3 function for
returning True if the circle intersects with this rect.

Response:
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 the rect?
    if (circle_center.x > rect_corner.x + radius or
        circle_center.y > rect_corner.y + radius):
      return False

    # Is the circle center inside the rect or near one of the edges?
    if (circle_center.x <= rect_corner.x or
        circle_center.y <= rect_corner.y):
      return True

    # Does the circle contain the corner of the rect?
    return circle_center.dist_sq(rect_corner) <= radius**2


Instruction:
Can you generate the documentation for the following Python 3 function
def _read_execute_info(path, parents):
  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() for p in line.decode("utf-8").split("=")]
        if len(parts) == 2 and parts[0] == "executable":
          exec_path = parts[1].replace("\\", "/")  # For windows compatibility.
          for _ in range(parents):
            exec_path = os.path.dirname(exec_path)
          return exec_path

Response: Read the ExecuteInfo. txt file and return the base directory.


Instruction:
Can you write a function in Python 3 where it
creates a game for the agents to join.

Response:
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_map(map_inst.path, map_data)
      self._saved_maps.add(map_name)

    # Form the create game message.
    create = sc_pb.RequestCreateGame(
        local_map=sc_pb.LocalMap(map_path=map_inst.path),
        disable_fog=False)

    # Set up for two agents.
    for _ in range(self._num_agents):
      create.player_setup.add(type=sc_pb.Participant)

    # Create the game.
    self._controllers[0].create_game(create)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def close(self):
    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 = []

Response: Shutdown and free all resources.


Instruction:
Can you tell what is the following Python 3 function doing
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_race: The race for the bot.
      bot_first: Whether the bot should be player 1 (else is player 2).
    """
    self._controller.ping()

    # Form the create game message.
    map_inst = maps.get(map_name)
    map_data = map_inst.data(self._run_config)
    if map_name not in self._saved_maps:
      self._controller.save_map(map_inst.path, map_data)
      self._saved_maps.add(map_name)

    create = sc_pb.RequestCreateGame(
        local_map=sc_pb.LocalMap(map_path=map_inst.path, map_data=map_data),
        disable_fog=False)

    # Set up for one bot, one agent.
    if not bot_first:
      create.player_setup.add(type=sc_pb.Participant)

    create.player_setup.add(
        type=sc_pb.Computer, race=bot_race, difficulty=bot_difficulty)

    if bot_first:
      create.player_setup.add(type=sc_pb.Participant)

    # Create the game.
    self._controller.create_game(create)

Response: Create a game for one remote agent vs the specified bot.


Instruction:
Make a summary of the following Python 3 code
def agent():
  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_port=FLAGS.config_port,
      race=sc2_env.Race[FLAGS.agent_race],
      step_mul=FLAGS.step_mul,
      agent_interface_format=sc2_env.parse_agent_interface_format(
          feature_screen=FLAGS.feature_screen_size,
          feature_minimap=FLAGS.feature_minimap_size,
          rgb_screen=FLAGS.rgb_screen_size,
          rgb_minimap=FLAGS.rgb_minimap_size,
          action_space=FLAGS.action_space,
          use_feature_units=FLAGS.use_feature_units),
      visualize=FLAGS.render) as env:
    agents = [agent_cls()]
    logging.info("Connected, starting run_loop.")
    try:
      run_loop.run_loop(agents, env)
    except lan_sc2_env.RestartException:
      pass
  logging.info("Done.")

Response: Run the agent connecting to a remote host.


Instruction:
Given the following Python 3 function, write the documentation
def human():
  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.")

  ports = [FLAGS.config_port + p for p in range(5)]  # tcp + 2 * num_players
  if not all(portpicker.is_port_free(p) for p in ports):
    sys.exit("Need 5 free ports after the config port.")

  proc = None
  ssh_proc = None
  tcp_conn = None
  udp_sock = None
  try:
    proc = run_config.start(extra_ports=ports[1:], timeout_seconds=300,
                            host=FLAGS.host, window_loc=(50, 50))

    tcp_port = ports[0]
    settings = {
        "remote": FLAGS.remote,
        "game_version": proc.version.game_version,
        "realtime": FLAGS.realtime,
        "map_name": map_inst.name,
        "map_path": map_inst.path,
        "map_data": map_inst.data(run_config),
        "ports": {
            "server": {"game": ports[1], "base": ports[2]},
            "client": {"game": ports[3], "base": ports[4]},
        }
    }

    create = sc_pb.RequestCreateGame(
        realtime=settings["realtime"],
        local_map=sc_pb.LocalMap(map_path=settings["map_path"]))
    create.player_setup.add(type=sc_pb.Participant)
    create.player_setup.add(type=sc_pb.Participant)

    controller = proc.controller
    controller.save_map(settings["map_path"], settings["map_data"])
    controller.create_game(create)

    if FLAGS.remote:
      ssh_proc = lan_sc2_env.forward_ports(
          FLAGS.remote, proc.host, [settings["ports"]["client"]["base"]],
          [tcp_port, settings["ports"]["server"]["base"]])

    print("-" * 80)
    print("Join: play_vs_agent --host %s --config_port %s" % (proc.host,
                                                              tcp_port))
    print("-" * 80)

    tcp_conn = lan_sc2_env.tcp_server(
        lan_sc2_env.Addr(proc.host, tcp_port), settings)

    if FLAGS.remote:
      udp_sock = lan_sc2_env.udp_server(
          lan_sc2_env.Addr(proc.host, settings["ports"]["client"]["game"]))

      lan_sc2_env.daemon_thread(
          lan_sc2_env.tcp_to_udp,
          (tcp_conn, udp_sock,
           lan_sc2_env.Addr(proc.host, settings["ports"]["server"]["game"])))

      lan_sc2_env.daemon_thread(lan_sc2_env.udp_to_tcp, (udp_sock, tcp_conn))

    join = sc_pb.RequestJoinGame()
    join.shared_port = 0  # unused
    join.server_ports.game_port = settings["ports"]["server"]["game"]
    join.server_ports.base_port = settings["ports"]["server"]["base"]
    join.client_ports.add(game_port=settings["ports"]["client"]["game"],
                          base_port=settings["ports"]["client"]["base"])

    join.race = sc2_env.Race[FLAGS.user_race]
    join.player_name = FLAGS.user_name
    if FLAGS.render:
      join.options.raw = True
      join.options.score = True
      if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:
        fl = join.options.feature_layer
        fl.width = 24
        FLAGS.feature_screen_size.assign_to(fl.resolution)
        FLAGS.feature_minimap_size.assign_to(fl.minimap_resolution)
      if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:
        FLAGS.rgb_screen_size.assign_to(join.options.render.resolution)
        FLAGS.rgb_minimap_size.assign_to(join.options.render.minimap_resolution)
    controller.join_game(join)

    if FLAGS.render:
      renderer = renderer_human.RendererHuman(
          fps=FLAGS.fps, render_feature_grid=False)
      renderer.run(run_configs.get(), controller, max_episodes=1)
    else:  # Still step forward so the Mac/Windows renderer works.
      while True:
        frame_start_time = time.time()
        if not FLAGS.realtime:
          controller.step()
        obs = controller.observe()

        if obs.player_result:
          break
        time.sleep(max(0, frame_start_time - time.time() + 1 / FLAGS.fps))
  except KeyboardInterrupt:
    pass
  finally:
    if tcp_conn:
      tcp_conn.close()
    if proc:
      proc.close()
    if udp_sock:
      udp_sock.close()
    if ssh_proc:
      ssh_proc.terminate()
      for _ in range(5):
        if ssh_proc.poll() is not None:
          break
        time.sleep(1)
      if ssh_proc.poll() is None:
        ssh_proc.kill()
        ssh_proc.wait()

Response: Run a host which expects one player to connect remotely.


Instruction:
Can you create a Python 3 function that
connects to the remote controller.

Response:
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)]
    logging.info("Connected")

    if map_inst and save_map:
      run_config = run_configs.get()
      self._controllers[0].save_map(map_inst.path, map_inst.data(run_config))

    # Create the join request.
    join = sc_pb.RequestJoinGame(options=interface)
    join.race = race
    join.player_name = name
    join.shared_port = 0  # unused
    join.server_ports.game_port = lan_ports.pop(0)
    join.server_ports.base_port = lan_ports.pop(0)
    join.client_ports.add(
        game_port=lan_ports.pop(0), base_port=lan_ports.pop(0))

    logging.info("Joining game.")
    self._controllers[0].join_game(join)
    self._in_game = True
    logging.info("Game joined.")


Instruction:
Write a Python 3 function for
getting the config chosen by the flags.

Response:
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.
    return max(configs.values(), key=lambda c: c.priority())()

  try:
    return configs[FLAGS.sc2_run_config]()
  except KeyError:
    raise sc_process.SC2LaunchError(
        "Invalid run_config. Valid configs are: %s" % (
            ", ".join(sorted(configs.keys()))))


Instruction:
How would you explain what the following Python 3 function does
def reset(self):
    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._last_score = [0] * self._num_agents
    self._state = environment.StepType.FIRST
    if self._realtime:
      self._last_step_time = time.time()
      self._target_step = 0

    return self._observe()

Response: Start a new episode.


Instruction:
How would you explain what the following Python 3 function does
def step(self, actions, step_mul=None):
    if self._state == environment.StepType.LAST:
      return self.reset()

    skip = not self._ensure_available_actions
    self._parallel.run(
        (c.act, f.transform_action(o.observation, a, skip_available=skip))
        for c, f, o, a in zip(
            self._controllers, self._features, self._obs, actions))

    self._state = environment.StepType.MID
    return self._step(step_mul)

Response: Apply actions step the world forward and return observations.


Instruction:
Write a Python 3 function that can
send a list of messages to the chat.

Response:
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))


Instruction:
Can you generate the documentation for the following Python 3 function
def valid_replay(info, ping):
  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 interesting.
    return False
  for p in info.player_info:
    if p.player_apm < 10 or p.player_mmr < 1000:
      # Low APM = player just standing around.
      # Low MMR = corrupt replay or player who is weak.
      return False
  return True

Response: Make sure the replay isn t corrupt and is worth looking at.


Instruction:
Make a summary of the following Python 3 code
def main(unused_argv):
  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_printer, args=(stats_queue,))
  stats_thread.start()
  try:
    # For some reason buffering everything into a JoinableQueue makes the
    # program not exit, so save it into a list then slowly fill it into the
    # queue in a separate thread. Grab the list synchronously so we know there
    # is work in the queue before the SC2 processes actually run, otherwise
    # The replay_queue.join below succeeds without doing any work, and exits.
    print("Getting replay list:", FLAGS.replays)
    replay_list = sorted(run_config.replay_paths(FLAGS.replays))
    print(len(replay_list), "replays found.\n")
    replay_queue = multiprocessing.JoinableQueue(FLAGS.parallel * 10)
    replay_queue_thread = threading.Thread(target=replay_queue_filler,
                                           args=(replay_queue, replay_list))
    replay_queue_thread.daemon = True
    replay_queue_thread.start()

    for i in range(FLAGS.parallel):
      p = ReplayProcessor(i, run_config, replay_queue, stats_queue)
      p.daemon = True
      p.start()
      time.sleep(1)  # Stagger startups, otherwise they seem to conflict somehow

    replay_queue.join()  # Wait for the queue to empty.
  except KeyboardInterrupt:
    print("Caught KeyboardInterrupt, exiting.")
  finally:
    stats_queue.put(None)  # Tell the stats_thread to print and exit.
    stats_thread.join()

Response: Dump stats about all the actions that are in use in a set of replays.


Instruction:
Can you tell what is the following Python 3 function doing
def merge(self, other):
    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 += other.select_rect
    self.control_group += other.control_group
    merge_dict(self.maps, other.maps)
    merge_dict(self.races, other.races)
    merge_dict(self.unit_ids, other.unit_ids)
    merge_dict(self.valid_abilities, other.valid_abilities)
    merge_dict(self.made_abilities, other.made_abilities)
    merge_dict(self.valid_actions, other.valid_actions)
    merge_dict(self.made_actions, other.made_actions)
    self.crashing_replays |= other.crashing_replays
    self.invalid_replays |= other.invalid_replays

Response: Merge another ReplayStats into this one.


Instruction:
Implement a function in Python 3 to
process a single replay and updates the stats.

Response:
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,
        observed_player_id=player_id))

    feat = features.features_from_game_info(controller.game_info())

    self.stats.replay_stats.replays += 1
    self._update_stage("step")
    controller.step()
    while True:
      self.stats.replay_stats.steps += 1
      self._update_stage("observe")
      obs = controller.observe()

      for action in obs.actions:
        act_fl = action.action_feature_layer
        if act_fl.HasField("unit_command"):
          self.stats.replay_stats.made_abilities[
              act_fl.unit_command.ability_id] += 1
        if act_fl.HasField("camera_move"):
          self.stats.replay_stats.camera_move += 1
        if act_fl.HasField("unit_selection_point"):
          self.stats.replay_stats.select_pt += 1
        if act_fl.HasField("unit_selection_rect"):
          self.stats.replay_stats.select_rect += 1
        if action.action_ui.HasField("control_group"):
          self.stats.replay_stats.control_group += 1

        try:
          func = feat.reverse_action(action).function
        except ValueError:
          func = -1
        self.stats.replay_stats.made_actions[func] += 1

      for valid in obs.observation.abilities:
        self.stats.replay_stats.valid_abilities[valid.ability_id] += 1

      for u in obs.observation.raw_data.units:
        self.stats.replay_stats.unit_ids[u.unit_type] += 1

      for ability_id in feat.available_actions(obs.observation):
        self.stats.replay_stats.valid_actions[ability_id] += 1

      if obs.player_result:
        break

      self._update_stage("step")
      controller.step(FLAGS.step_mul)


Instruction:
Make a summary of the following Python 3 code
def tcp_server(tcp_addr, 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_addr)
  conn, addr = sock.accept()
  logging.info("Accepted connection from %s", Addr(*addr))

  # Send map_data independently for py2/3 and json encoding reasons.
  write_tcp(conn, settings["map_data"])
  send_settings = {k: v for k, v in settings.items() if k != "map_data"}
  logging.debug("settings: %s", send_settings)
  write_tcp(conn, json.dumps(send_settings).encode())
  return conn

Response: Start up the tcp server send the settings.


Instruction:
Create a Python 3 function for
connecting to the tcp server and return the settings.

Response:
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:
      sock.connect(tcp_addr)
      break
    except socket.error:
      time.sleep(1)
  else:
    sock.connect(tcp_addr)  # One last try, but don't catch this error.
  logging.info("Connected.")

  map_data = read_tcp(sock)
  settings_str = read_tcp(sock)
  if not settings_str:
    raise socket.error("Failed to read")
  settings = json.loads(settings_str.decode())
  logging.info("Got settings. map_name: %s.", settings["map_name"])
  logging.debug("settings: %s", settings)
  settings["map_data"] = map_data
  return sock, settings


Instruction:
How would you explain what the following Python 3 function does
def read_tcp_size(conn, size):
  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)
      return
    chunks.append(chunk)
    bytes_read += len(chunk)
  return b"".join(chunks)

Response: Read size number of bytes from conn retrying as needed.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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 remotely.
    remote_listen_ports: Which ports to listen on remotely to forward locally.

  Returns:
    The ssh process.

  Raises:
    ValueError: if it can't find ssh.
  """
  if ":" in local_host and not local_host.startswith("["):
    local_host = "[%s]" % local_host

  ssh = whichcraft.which("ssh") or whichcraft.which("plink")
  if not ssh:
    raise ValueError("Couldn't find an ssh client.")

  args = [ssh, remote_host]
  for local_port in local_listen_ports:
    args += ["-L", "%s:%s:%s:%s" % (local_host, local_port,
                                    local_host, local_port)]
  for remote_port in remote_listen_ports:
    args += ["-R", "%s:%s:%s:%s" % (local_host, remote_port,
                                    local_host, remote_port)]

  logging.info("SSH port forwarding: %s", " ".join(args))
  return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                          stdin=subprocess.PIPE, close_fds=(os.name == "posix"))

Response: Forwards ports such that multiplayer works between machines.


Instruction:
Create a Python 3 function to
make sure this stays synced with bin/play_vs_agent.py.

Response:
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(host, settings["ports"]["server"]["game"]))

      daemon_thread(tcp_to_udp,
                    (self._tcp_conn, self._udp_sock,
                     Addr(host, settings["ports"]["client"]["game"])))

      daemon_thread(udp_to_tcp, (self._udp_sock, self._tcp_conn))

    extra_ports = [
        settings["ports"]["server"]["game"],
        settings["ports"]["server"]["base"],
        settings["ports"]["client"]["game"],
        settings["ports"]["client"]["base"],
    ]

    self._sc2_procs = [self._run_config.start(
        extra_ports=extra_ports, host=host, version=settings["game_version"],
        window_loc=(700, 50), want_rgb=interface.HasField("render"))]
    self._controllers = [p.controller for p in self._sc2_procs]

    # Create the join request.
    join = sc_pb.RequestJoinGame(options=interface)
    join.race = race
    join.player_name = name
    join.shared_port = 0  # unused
    join.server_ports.game_port = settings["ports"]["server"]["game"]
    join.server_ports.base_port = settings["ports"]["server"]["base"]
    join.client_ports.add(game_port=settings["ports"]["client"]["game"],
                          base_port=settings["ports"]["client"]["base"])

    self._controllers[0].save_map(settings["map_path"], settings["map_data"])
    self._controllers[0].join_game(join)


Instruction:
Given the following Python 3 function, write the documentation
def _replay_index(replay_dir):
  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((
        "filename",
        "build",
        "map_name",
        "game_duration_loops",
        "players",
        "P1-outcome",
        "P1-race",
        "P1-apm",
        "P2-race",
        "P2-apm",
    )))

    try:
      bad_replays = []
      for file_path in run_config.replay_paths(replay_dir):
        file_name = os.path.basename(file_path)
        try:
          info = controller.replay_info(run_config.replay_data(file_path))
        except remote_controller.RequestError as e:
          bad_replays.append("%s: %s" % (file_name, e))
          continue
        if info.HasField("error"):
          print("failed:", file_name, info.error, info.error_details)
          bad_replays.append(file_name)
        else:
          out = [
              file_name,
              info.base_build,
              info.map_name,
              info.game_duration_loops,
              len(info.player_info),
              sc_pb.Result.Name(info.player_info[0].player_result.result),
              sc_common.Race.Name(info.player_info[0].player_info.race_actual),
              info.player_info[0].player_apm,
          ]
          if len(info.player_info) >= 2:
            out += [
                sc_common.Race.Name(
                    info.player_info[1].player_info.race_actual),
                info.player_info[1].player_apm,
            ]
          print(u",".join(str(s) for s in out))
    except KeyboardInterrupt:
      pass
    finally:
      if bad_replays:
        print("\n")
        print("Replays with errors:")
        print("\n".join(bad_replays))

Response: Output information for a directory of replays.


Instruction:
How would you implement a function in Python 3 that
queries a replay for information.

Response:
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_path))
  print("-" * 60)
  print(info)


Instruction:
How would you explain what the following Python 3 function does
def smooth_hue_palette(scale):
  # 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, everything else moves into a hue.

  # Some initial values and scaling. Check wikipedia for variable meanings.
  array = numpy.arange(scale)
  h = array * (6 / scale)  # range of [0,6)
  x = 255 * (1 - numpy.absolute(numpy.mod(h, 2) - 1))
  c = 255

  # Initialize outputs to zero/black
  out = numpy.zeros(h.shape + (3,), float)
  r = out[..., 0]
  g = out[..., 1]
  b = out[..., 2]

  mask = (0 < h) & (h < 1)
  r[mask] = c
  g[mask] = x[mask]

  mask = (1 <= h) & (h < 2)
  r[mask] = x[mask]
  g[mask] = c

  mask = (2 <= h) & (h < 3)
  g[mask] = c
  b[mask] = x[mask]

  mask = (3 <= h) & (h < 4)
  g[mask] = x[mask]
  b[mask] = c

  mask = (4 <= h) & (h < 5)
  r[mask] = x[mask]
  b[mask] = c

  mask = 5 <= h
  r[mask] = c
  b[mask] = x[mask]

  return out

Response: Takes an array of ints and returns a corresponding colored rgb array.


Instruction:
Write a Python 3 function that can
create a palette that is piece - wise linear given some colors at points.

Response:
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, c2 = points[1]
  next_pt = 2

  for i in range(1, scale):
    v = i / scale
    if v > p2:
      p1, c1 = p2, c2
      p2, c2 = points[next_pt]
      next_pt += 1
    frac = (v - p1) / (p2 - p1)
    out[i, :] = c1 * (1 - frac) + c2 * frac
  return out


Instruction:
Create a Python 3 function to
return a palette that maps unit types to rgb colors.

Response:
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)
  for i, v in enumerate(static_data.UNIT_TYPES):
    palette[v] = distinct_colors[i]
  return palette


Instruction:
Write a Python 3 script to
make sure the lock is held while in this function.

Response:
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


Instruction:
Can you tell what is the following Python 3 function doing
def _get_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[0][1]))
    except:  # pylint: disable=bare-except
      logging.error("Failed to get the resolution from xrandr.")

  # Most general, but doesn't understand multiple monitors.
  display_info = pygame.display.Info()
  return point.Point(display_info.current_w, display_info.current_h)

Response: Get the desktop size.


Instruction:
Create a Python 3 function to
draw an arc using world coordinates radius start and stop angles.

Response:
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 = pygame.Rect(center - radius, (radius * 2, radius * 2))
    pygame.draw.arc(self.surf, color, rect, start_angle, stop_angle,
                    thickness if thickness < radius else 0)


Instruction:
Explain what the following Python 3 code does
def draw_circle(self, color, world_loc, world_radius, thickness=0):
    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, color, center, radius,
                         thickness if thickness < radius else 0)

Response: Draw a circle using world coordinates and radius.


Instruction:
Here you have a function in Python 3, explain what it does
def draw_rect(self, color, world_rect, thickness=0):
    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)

Response: Draw a rectangle using world coordinates.


Instruction:
Write a Python 3 script to
fill this surface using the contents of a numpy array.

Response:
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)


Instruction:
Write a Python 3 script for
writing text to the screen in font. size relative coordinates.

Response:
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.get_rect()
    if pos.x >= 0:
      setattr(rect, align, pos.x)
    else:
      setattr(rect, align, self.surf.get_width() + pos.x)
    if pos.y >= 0:
      setattr(rect, valign, pos.y)
    else:
      setattr(rect, valign, self.surf.get_height() + pos.y)
    self.surf.blit(text_surf, rect)


Instruction:
Create a Python 3 function for
giving an Action return the right spatial action.

Response:
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 | SurfType.FEATURE)


Instruction:
Here you have a function in Python 3, explain what it does
def init(self, game_info, static_data):
    self._game_info = game_info
    self._static_data = static_data

    if not game_info.HasField("start_raw"):
      raise ValueError("Raw observations are required for the renderer.")

    self._map_size = point.Point.build(game_info.start_raw.map_size)

    if game_info.options.HasField("feature_layer"):
      fl_opts = game_info.options.feature_layer
      self._feature_screen_px = point.Point.build(fl_opts.resolution)
      self._feature_minimap_px = point.Point.build(fl_opts.minimap_resolution)
      self._feature_camera_width_world_units = fl_opts.width
      self._render_rgb = False
    else:
      self._feature_screen_px = self._feature_minimap_px = None
    if game_info.options.HasField("render"):
      render_opts = game_info.options.render
      self._rgb_screen_px = point.Point.build(render_opts.resolution)
      self._rgb_minimap_px = point.Point.build(render_opts.minimap_resolution)
      self._render_rgb = True
    else:
      self._rgb_screen_px = self._rgb_minimap_px = None

    if not self._feature_screen_px and not self._rgb_screen_px:
      raise ValueError("Nothing to render.")

    try:
      self.init_window()
      self._initialized = True
    except pygame.error as e:
      self._initialized = False
      logging.error("-" * 60)
      logging.error("Failed to initialize pygame: %s", e)
      logging.error("Continuing without pygame.")
      logging.error("If you're using ssh and have an X server, try ssh -X.")
      logging.error("-" * 60)

    self._obs = sc_pb.ResponseObservation()
    self._queued_action = None
    self._queued_hotkey = ""
    self._select_start = None
    self._alerts = {}
    self._past_actions = []
    self._help = False

Response: Initialize the object with the game info and static data.


Instruction:
Given the following Python 3 function, write the documentation
def init_window(self):
    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_size is None:
      self._desktop_size = _get_desktop_size()

    if self._render_rgb and self._rgb_screen_px:
      main_screen_px = self._rgb_screen_px
    else:
      main_screen_px = self._feature_screen_px

    window_size_ratio = main_screen_px
    if self._feature_screen_px and self._render_feature_grid:
      # Want a roughly square grid of feature layers, each being roughly square.
      num_feature_layers = (len(features.SCREEN_FEATURES) +
                            len(features.MINIMAP_FEATURES))
      feature_cols = math.ceil(math.sqrt(num_feature_layers))
      feature_rows = math.ceil(num_feature_layers / feature_cols)
      features_layout = point.Point(feature_cols,
                                    feature_rows * 1.05)  # make room for titles

      # Scale features_layout to main_screen_px height so we know its width.
      features_aspect_ratio = (features_layout * main_screen_px.y /
                               features_layout.y)
      window_size_ratio += point.Point(features_aspect_ratio.x, 0)

    window_size_px = window_size_ratio.scale_max_size(
        self._desktop_size * self._window_scale).ceil()

    # Create the actual window surface. This should only be blitted to from one
    # of the sub-surfaces defined below.
    self._window = pygame.display.set_mode(window_size_px, 0, 32)
    pygame.display.set_caption("Starcraft Viewer")

    # The sub-surfaces that the various draw functions will draw to.
    self._surfaces = []
    def add_surface(surf_type, surf_loc, world_to_surf, world_to_obs, draw_fn):
      """Add a surface. Drawn in order and intersect in reverse order."""
      sub_surf = self._window.subsurface(
          pygame.Rect(surf_loc.tl, surf_loc.size))
      self._surfaces.append(_Surface(
          sub_surf, surf_type, surf_loc, world_to_surf, world_to_obs, draw_fn))

    self._scale = window_size_px.y // 32
    self._font_small = pygame.font.Font(None, int(self._scale * 0.5))
    self._font_large = pygame.font.Font(None, self._scale)

    def check_eq(a, b):
      """Used to run unit tests on the transforms."""
      assert (a - b).len() < 0.0001, "%s != %s" % (a, b)

    # World has origin at bl, world_tl has origin at tl.
    self._world_to_world_tl = transform.Linear(
        point.Point(1, -1), point.Point(0, self._map_size.y))

    check_eq(self._world_to_world_tl.fwd_pt(point.Point(0, 0)),
             point.Point(0, self._map_size.y))
    check_eq(self._world_to_world_tl.fwd_pt(point.Point(5, 10)),
             point.Point(5, self._map_size.y - 10))

    # Move the point to be relative to the camera. This gets updated per frame.
    self._world_tl_to_world_camera_rel = transform.Linear(
        offset=-self._map_size / 4)

    check_eq(self._world_tl_to_world_camera_rel.fwd_pt(self._map_size / 4),
             point.Point(0, 0))
    check_eq(
        self._world_tl_to_world_camera_rel.fwd_pt(
            (self._map_size / 4) + point.Point(5, 10)),
        point.Point(5, 10))

    if self._feature_screen_px:
      # Feature layer locations in continuous space.
      feature_world_per_pixel = (self._feature_screen_px /
                                 self._feature_camera_width_world_units)
      world_camera_rel_to_feature_screen = transform.Linear(
          feature_world_per_pixel, self._feature_screen_px / 2)

      check_eq(world_camera_rel_to_feature_screen.fwd_pt(point.Point(0, 0)),
               self._feature_screen_px / 2)
      check_eq(
          world_camera_rel_to_feature_screen.fwd_pt(
              point.Point(-0.5, -0.5) * self._feature_camera_width_world_units),
          point.Point(0, 0))

      self._world_to_feature_screen = transform.Chain(
          self._world_to_world_tl,
          self._world_tl_to_world_camera_rel,
          world_camera_rel_to_feature_screen)
      self._world_to_feature_screen_px = transform.Chain(
          self._world_to_feature_screen,
          transform.PixelToCoord())

      world_tl_to_feature_minimap = transform.Linear(
          self._feature_minimap_px / self._map_size.max_dim())

      check_eq(world_tl_to_feature_minimap.fwd_pt(point.Point(0, 0)),
               point.Point(0, 0))
      check_eq(world_tl_to_feature_minimap.fwd_pt(self._map_size),
               self._map_size.scale_max_size(self._feature_minimap_px))

      self._world_to_feature_minimap = transform.Chain(
          self._world_to_world_tl,
          world_tl_to_feature_minimap)
      self._world_to_feature_minimap_px = transform.Chain(
          self._world_to_feature_minimap,
          transform.PixelToCoord())

    if self._rgb_screen_px:
      # RGB pixel locations in continuous space.

      # TODO(tewalds): Use a real 3d projection instead of orthogonal.
      rgb_world_per_pixel = (self._rgb_screen_px / 24)
      world_camera_rel_to_rgb_screen = transform.Linear(
          rgb_world_per_pixel, self._rgb_screen_px / 2)

      check_eq(world_camera_rel_to_rgb_screen.fwd_pt(point.Point(0, 0)),
               self._rgb_screen_px / 2)
      check_eq(
          world_camera_rel_to_rgb_screen.fwd_pt(
              point.Point(-0.5, -0.5) * 24),
          point.Point(0, 0))

      self._world_to_rgb_screen = transform.Chain(
          self._world_to_world_tl,
          self._world_tl_to_world_camera_rel,
          world_camera_rel_to_rgb_screen)
      self._world_to_rgb_screen_px = transform.Chain(
          self._world_to_rgb_screen,
          transform.PixelToCoord())

      world_tl_to_rgb_minimap = transform.Linear(
          self._rgb_minimap_px / self._map_size.max_dim())

      check_eq(world_tl_to_rgb_minimap.fwd_pt(point.Point(0, 0)),
               point.Point(0, 0))
      check_eq(world_tl_to_rgb_minimap.fwd_pt(self._map_size),
               self._map_size.scale_max_size(self._rgb_minimap_px))

      self._world_to_rgb_minimap = transform.Chain(
          self._world_to_world_tl,
          world_tl_to_rgb_minimap)
      self._world_to_rgb_minimap_px = transform.Chain(
          self._world_to_rgb_minimap,
          transform.PixelToCoord())

    # Renderable space for the screen.
    screen_size_px = main_screen_px.scale_max_size(window_size_px)
    minimap_size_px = self._map_size.scale_max_size(screen_size_px / 4)
    minimap_offset = point.Point(0, (screen_size_px.y - minimap_size_px.y))

    if self._render_rgb:
      rgb_screen_to_main_screen = transform.Linear(
          screen_size_px / self._rgb_screen_px)
      add_surface(SurfType.RGB | SurfType.SCREEN,
                  point.Rect(point.origin, screen_size_px),
                  transform.Chain(  # surf
                      self._world_to_rgb_screen,
                      rgb_screen_to_main_screen),
                  self._world_to_rgb_screen_px,
                  self.draw_screen)
      rgb_minimap_to_main_minimap = transform.Linear(
          minimap_size_px / self._rgb_minimap_px)
      add_surface(SurfType.RGB | SurfType.MINIMAP,
                  point.Rect(minimap_offset,
                             minimap_offset + minimap_size_px),
                  transform.Chain(  # surf
                      self._world_to_rgb_minimap,
                      rgb_minimap_to_main_minimap),
                  self._world_to_rgb_minimap_px,
                  self.draw_mini_map)
    else:
      feature_screen_to_main_screen = transform.Linear(
          screen_size_px / self._feature_screen_px)
      add_surface(SurfType.FEATURE | SurfType.SCREEN,
                  point.Rect(point.origin, screen_size_px),
                  transform.Chain(  # surf
                      self._world_to_feature_screen,
                      feature_screen_to_main_screen),
                  self._world_to_feature_screen_px,
                  self.draw_screen)
      feature_minimap_to_main_minimap = transform.Linear(
          minimap_size_px / self._feature_minimap_px)
      add_surface(SurfType.FEATURE | SurfType.MINIMAP,
                  point.Rect(minimap_offset,
                             minimap_offset + minimap_size_px),
                  transform.Chain(  # surf
                      self._world_to_feature_minimap,
                      feature_minimap_to_main_minimap),
                  self._world_to_feature_minimap_px,
                  self.draw_mini_map)

    if self._feature_screen_px and self._render_feature_grid:
      # Add the feature layers
      features_loc = point.Point(screen_size_px.x, 0)
      feature_pane = self._window.subsurface(
          pygame.Rect(features_loc, window_size_px - features_loc))
      feature_pane.fill(colors.white / 2)
      feature_pane_size = point.Point(*feature_pane.get_size())
      feature_grid_size = feature_pane_size / point.Point(feature_cols,
                                                          feature_rows)
      feature_layer_area = self._feature_screen_px.scale_max_size(
          feature_grid_size)
      feature_layer_padding = feature_layer_area // 20
      feature_layer_size = feature_layer_area - feature_layer_padding * 2

      feature_font_size = int(feature_grid_size.y * 0.09)
      feature_font = pygame.font.Font(None, feature_font_size)

      feature_counter = itertools.count()
      def add_feature_layer(feature, surf_type, world_to_surf, world_to_obs):
        """Add a feature layer surface."""
        i = next(feature_counter)
        grid_offset = point.Point(i % feature_cols,
                                  i // feature_cols) * feature_grid_size
        text = feature_font.render(feature.full_name, True, colors.white)
        rect = text.get_rect()
        rect.center = grid_offset + point.Point(feature_grid_size.x / 2,
                                                feature_font_size)
        feature_pane.blit(text, rect)
        surf_loc = (features_loc + grid_offset + feature_layer_padding +
                    point.Point(0, feature_font_size))
        add_surface(surf_type,
                    point.Rect(surf_loc, surf_loc + feature_layer_size),
                    world_to_surf, world_to_obs,
                    lambda surf: self.draw_feature_layer(surf, feature))

      # Add the minimap feature layers
      feature_minimap_to_feature_minimap_surf = transform.Linear(
          feature_layer_size / self._feature_minimap_px)
      world_to_feature_minimap_surf = transform.Chain(
          self._world_to_feature_minimap,
          feature_minimap_to_feature_minimap_surf)
      for feature in features.MINIMAP_FEATURES:
        add_feature_layer(feature, SurfType.FEATURE | SurfType.MINIMAP,
                          world_to_feature_minimap_surf,
                          self._world_to_feature_minimap_px)

      # Add the screen feature layers
      feature_screen_to_feature_screen_surf = transform.Linear(
          feature_layer_size / self._feature_screen_px)
      world_to_feature_screen_surf = transform.Chain(
          self._world_to_feature_screen,
          feature_screen_to_feature_screen_surf)
      for feature in features.SCREEN_FEATURES:
        add_feature_layer(feature, SurfType.FEATURE | SurfType.SCREEN,
                          world_to_feature_screen_surf,
                          self._world_to_feature_screen_px)

    # Add the help screen
    help_size = point.Point(
        (max(len(s) for s, _ in self.shortcuts) +
         max(len(s) for _, s in self.shortcuts)) * 0.4 + 4,
        len(self.shortcuts) + 3) * self._scale
    help_rect = point.Rect(window_size_px / 2 - help_size / 2,
                           window_size_px / 2 + help_size / 2)
    add_surface(SurfType.CHROME, help_rect, None, None, self.draw_help)

    # Arbitrarily set the initial camera to the center of the map.
    self._update_camera(self._map_size / 2)

Response: Initialize the pygame window and lay out the surfaces.


Instruction:
How would you explain what the following Python 3 function does
def _update_camera(self, 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 = (self._feature_screen_px / self._feature_screen_px.x *
                       self._feature_camera_width_world_units / 2)
      center = camera_center.bound(camera_radius,
                                   self._map_size - camera_radius)
      self._camera = point.Rect(
          (center - camera_radius).bound(self._map_size),
          (center + camera_radius).bound(self._map_size))

Response: Update the camera transform based on the new camera center.


Instruction:
Implement a function in Python 3 to
return a MousePos filled with the world position and surf it hit.

Response:
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):
      if (surf.surf_type != SurfType.CHROME and
          surf.surf_rect.contains_point(window_pt)):
        surf_rel_pt = window_pt - surf.surf_rect.tl
        world_pt = surf.world_to_surf.back_pt(surf_rel_pt)
        return MousePos(world_pt, surf)


Instruction:
Implement a Python 3 function for
getting actions from the UI apply to controller and return an ActionCmd.

Response:
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() & pygame.KMOD_SHIFT
      alt = pygame.key.get_mods() & pygame.KMOD_ALT
      if event.type == pygame.QUIT:
        return ActionCmd.QUIT
      elif event.type == pygame.KEYDOWN:
        if self._help:
          self._help = False
        elif event.key in (pygame.K_QUESTION, pygame.K_SLASH):
          self._help = True
        elif event.key == pygame.K_PAUSE:
          pause = True
          while pause:
            time.sleep(0.1)
            for event2 in pygame.event.get():
              if event2.type == pygame.KEYDOWN:
                if event2.key in (pygame.K_PAUSE, pygame.K_ESCAPE):
                  pause = False
                elif event2.key == pygame.K_F4:
                  return ActionCmd.QUIT
                elif event2.key == pygame.K_F5:
                  return ActionCmd.RESTART
        elif event.key == pygame.K_F4:
          return ActionCmd.QUIT
        elif event.key == pygame.K_F5:
          return ActionCmd.RESTART
        elif event.key == pygame.K_F7:  # Toggle rgb rendering.
          if self._rgb_screen_px and self._feature_screen_px:
            self._render_rgb = not self._render_rgb
            print("Rendering", self._render_rgb and "RGB" or "Feature Layers")
            self.init_window()
        elif event.key == pygame.K_F8:  # Toggle synchronous rendering.
          self._render_sync = not self._render_sync
          print("Rendering", self._render_sync and "Sync" or "Async")
        elif event.key == pygame.K_F9:  # Save a replay.
          self.save_replay(run_config, controller)
        elif event.key in (pygame.K_PLUS, pygame.K_EQUALS) and ctrl:
          self.zoom(1.1)  # zoom in
        elif event.key in (pygame.K_MINUS, pygame.K_UNDERSCORE) and ctrl:
          self.zoom(1 / 1.1)  # zoom out
        elif event.key in (pygame.K_PAGEUP, pygame.K_PAGEDOWN):
          if ctrl:
            if event.key == pygame.K_PAGEUP:
              self._step_mul += 1
            elif self._step_mul > 1:
              self._step_mul -= 1
            print("New step mul:", self._step_mul)
          else:
            self._fps *= 1.25 if event.key == pygame.K_PAGEUP else 1 / 1.25
            print("New max game speed: %.1f" % self._fps)
        elif event.key == pygame.K_F1:
          if self._obs.observation.player_common.idle_worker_count > 0:
            controller.act(self.select_idle_worker(ctrl, shift))
        elif event.key == pygame.K_F2:
          if self._obs.observation.player_common.army_count > 0:
            controller.act(self.select_army(shift))
        elif event.key == pygame.K_F3:
          if self._obs.observation.player_common.warp_gate_count > 0:
            controller.act(self.select_warp_gates(shift))
          if self._obs.observation.player_common.larva_count > 0:
            controller.act(self.select_larva())
        elif event.key in self.cmd_group_keys:
          controller.act(self.control_group(self.cmd_group_keys[event.key],
                                            ctrl, shift, alt))
        elif event.key in self.camera_actions:
          if self._obs:
            controller.act(self.camera_action_raw(
                point.Point.build(
                    self._obs.observation.raw_data.player.camera) +
                self.camera_actions[event.key]))
        elif event.key == pygame.K_ESCAPE:
          if self._queued_action:
            self.clear_queued_action()
          else:
            cmds = self._abilities(lambda cmd: cmd.hotkey == "escape")  # Cancel
            for cmd in cmds:  # There could be multiple cancels.
              assert not cmd.requires_point
              controller.act(self.unit_action(cmd, None, shift))
        else:
          if not self._queued_action:
            key = pygame.key.name(event.key).lower()
            new_cmd = self._queued_hotkey + key
            cmds = self._abilities(lambda cmd, n=new_cmd: (  # pylint: disable=g-long-lambda
                cmd.hotkey != "escape" and cmd.hotkey.startswith(n)))
            if cmds:
              self._queued_hotkey = new_cmd
              if len(cmds) == 1:
                cmd = cmds[0]
                if cmd.hotkey == self._queued_hotkey:
                  if cmd.requires_point:
                    self.clear_queued_action()
                    self._queued_action = cmd
                  else:
                    controller.act(self.unit_action(cmd, None, shift))
      elif event.type == pygame.MOUSEBUTTONDOWN:
        mouse_pos = self.get_mouse_pos(event.pos)
        if event.button == MouseButtons.LEFT and mouse_pos:
          if self._queued_action:
            controller.act(self.unit_action(
                self._queued_action, mouse_pos, shift))
          elif mouse_pos.surf.surf_type & SurfType.MINIMAP:
            controller.act(self.camera_action(mouse_pos))
          else:
            self._select_start = mouse_pos
        elif event.button == MouseButtons.RIGHT:
          if self._queued_action:
            self.clear_queued_action()
          cmds = self._abilities(lambda cmd: cmd.name == "Smart")
          if cmds:
            controller.act(self.unit_action(cmds[0], mouse_pos, shift))
      elif event.type == pygame.MOUSEBUTTONUP:
        mouse_pos = self.get_mouse_pos(event.pos)
        if event.button == MouseButtons.LEFT and self._select_start:
          if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and
              mouse_pos.surf.surf_type == self._select_start.surf.surf_type):
            controller.act(self.select_action(
                self._select_start, mouse_pos, ctrl, shift))
          self._select_start = None
    return ActionCmd.STEP


Instruction:
Can you tell what is the following Python 3 function doing
def camera_action(self, mouse_pos):
    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

Response: Return a sc_pb. Action with the camera movement filled.


Instruction:
Explain what the following Python 3 code does
def camera_action_raw(self, world_pos):
    action = sc_pb.Action()
    world_pos.assign_to(action.action_raw.camera_move.center_world_space)
    return action

Response: Return a sc_pb. Action with the camera movement filled.


Instruction:
Can you generate the documentation for the following Python 3 function
def select_action(self, pos1, pos2, ctrl, shift):
    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.world_pos == pos2.world_pos:  # select a point
      select = action_spatial.unit_selection_point
      pos1.obs_pos.assign_to(select.selection_screen_coord)
      mod = sc_spatial.ActionSpatialUnitSelectionPoint
      if ctrl:
        select.type = mod.AddAllType if shift else mod.AllType
      else:
        select.type = mod.Toggle if shift else mod.Select
    else:
      select = action_spatial.unit_selection_rect
      rect = select.selection_screen_coord.add()
      pos1.obs_pos.assign_to(rect.p0)
      pos2.obs_pos.assign_to(rect.p1)
      select.selection_add = shift

    # Clear the queued action if something will be selected. An alternative
    # implementation may check whether the selection changed next frame.
    units = self._units_in_area(point.Rect(pos1.world_pos, pos2.world_pos))
    if units:
      self.clear_queued_action()

    return action

Response: Select an action with the selection filled.


Instruction:
Write a Python 3 script to
select an idle worker.

Response:
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_worker
    return action


Instruction:
Can you generate the documentation for the following Python 3 function
def select_army(self, shift):
    action = sc_pb.Action()
    action.action_ui.select_army.selection_add = shift
    return action

Response: Select the entire army.


Instruction:
Can you implement a function in Python 3 that
selects all warp gates.

Response:
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


Instruction:
Write a Python 3 function for
acting on a control group selecting setting etc.

Response:
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 and not shift and not alt:
      select.action = mod.Set
    elif not ctrl and shift and not alt:
      select.action = mod.Append
    elif not ctrl and not shift and alt:
      select.action = mod.SetAndSteal
    elif not ctrl and shift and alt:
      select.action = mod.AppendAndSteal
    else:
      return  # unknown
    select.control_group_index = control_group_id
    return action


Instruction:
How would you implement a function in Python 3 that
returns a sc_pb. Action filled with the cmd and appropriate target.

Response:
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_command.queue_command = shift
      if pos.surf.surf_type & SurfType.SCREEN:
        pos.obs_pos.assign_to(unit_command.target_screen_coord)
      elif pos.surf.surf_type & SurfType.MINIMAP:
        pos.obs_pos.assign_to(unit_command.target_minimap_coord)
    else:
      if self._feature_screen_px:
        action.action_feature_layer.unit_command.ability_id = cmd.ability_id
      else:
        action.action_render.unit_command.ability_id = cmd.ability_id

    self.clear_queued_action()
    return action


Instruction:
Given the following Python 3 function, write the documentation
def _abilities(self, fn=None):
    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())

Response: Return the list of abilities filtered by fn.


Instruction:
Can you generate the documentation for the following Python 3 function
def _visible_units(self):
    # 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,
                    key=lambda u: (u.pos.z, u.owner != 16, -u.radius, u.tag)):
      yield u, point.Point.build(u.pos)

Response: A generator of visible units and their positions as Points sorted.


Instruction:
Implement a Python 3 function for
returning the list of units that intersect the rect.

Response:
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]


Instruction:
How would you implement a function in Python 3 that
gets a length limited unit name for drawing units.

Response:
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:
          self._name_lengths[key] = name[:i]
          break
      else:
        self._name_lengths[key] = name
    return self._name_lengths[key]


Instruction:
Explain what the following Python 3 code does
def draw_units(self, surf):
    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_ABSOLUTE_PALETTE[u.owner], p, u.radius)

        if fraction_damage > 0:
          surf.draw_circle(colors.PLAYER_ABSOLUTE_PALETTE[u.owner] // 2,
                           p, u.radius * fraction_damage)

        if u.shield and u.shield_max:
          surf.draw_arc(colors.blue, p, u.radius, 0,
                        2 * math.pi * u.shield / u.shield_max)
        if u.energy and u.energy_max:
          surf.draw_arc(colors.purple * 0.75, p, u.radius - 0.05, 0,
                        2 * math.pi * u.energy / u.energy_max)

        name = self.get_unit_name(
            surf, self._static_data.units.get(u.unit_type, "<none>"), u.radius)
        if name:
          text = self._font_small.render(name, True, colors.white)
          rect = text.get_rect()
          rect.center = surf.world_to_surf.fwd_pt(p)
          surf.surf.blit(text, rect)

        if u.is_selected:
          surf.draw_circle(colors.green, p, u.radius + 0.1, 1)

Response: Draw the units and buildings.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def draw_selection(self, surf):
    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_start.surf.surf_type):
        rect = point.Rect(select_start.world_pos, mouse_pos.world_pos)
        surf.draw_rect(colors.green, rect, 1)

Response: Draw the selection rectange.


Instruction:
Make a summary of the following Python 3 code
def draw_build_target(self, surf):
    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:
          pos = point.Point(round_half(pos.world_pos.x, (radius * 2) % 2),
                            round_half(pos.world_pos.y, (radius * 2) % 2))
          surf.draw_circle(
              colors.PLAYER_ABSOLUTE_PALETTE[
                  self._obs.observation.player_common.player_id],
              pos, radius)

Response: Draw the build target.


Instruction:
Can you tell what is the following Python 3 function doing
def draw_overlay(self, surf):
    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, player.food_used, player.food_cap))
    times, steps = zip(*self._game_times)
    sec = obs.game_loop // 22.4  # http://liquipedia.net/starcraft2/Game_Speed
    surf.write_screen(
        self._font_large, colors.green, (-0.2, 0.2),
        "Score: %s, Step: %s, %.1f/s, Time: %d:%02d" % (
            obs.score.score, obs.game_loop, sum(steps) / (sum(times) or 1),
            sec // 60, sec % 60),
        align="right")
    surf.write_screen(
        self._font_large, colors.green * 0.8, (-0.2, 1.2),
        "FPS: O:%.1f, R:%.1f" % (
            len(times) / (sum(times) or 1),
            len(self._render_times) / (sum(self._render_times) or 1)),
        align="right")
    line = 3
    for alert, ts in sorted(self._alerts.items(), key=lambda item: item[1]):
      if time.time() < ts + 3:  # Show for 3 seconds.
        surf.write_screen(self._font_large, colors.red, (20, line), alert)
        line += 1
      else:
        del self._alerts[alert]

Response: Draw the overlay describing resources.


Instruction:
Here you have a function in Python 3, explain what it does
def draw_help(self, surf):
    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)
    for i, (hotkey, description) in enumerate(self.shortcuts, start=2):
      write((2, i), hotkey)
      write((3 + max_len * 0.7, i), description)

Response: Draw the help dialog.


Instruction:
How would you explain what the following Python 3 function does
def draw_commands(self, surf):
    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 == self._queued_action:
        color = colors.green
      elif self._queued_hotkey and cmd.hotkey.startswith(self._queued_hotkey):
        color = colors.green * 0.75
      elif cmd.ability_id in past_abilities:
        color = colors.red
      else:
        color = colors.yellow
      hotkey = cmd.hotkey[0:3]  # truncate "escape" -> "esc"
      surf.write_screen(self._font_large, color, (0.2, y), hotkey)
      surf.write_screen(self._font_large, color, (3, y), cmd.name)

Response: Draw the list of available commands.


Instruction:
Create a Python 3 function to
draw the unit selection or build queue.

Response:
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, loc, text)

    def write_single(unit, line):
      write((left + 1, next(line)), unit_name(unit.unit_type))
      write((left + 1, next(line)), "Health: %s" % unit.health)
      write((left + 1, next(line)), "Shields: %s" % unit.shields)
      write((left + 1, next(line)), "Energy: %s" % unit.energy)
      if unit.build_progress > 0:
        write((left + 1, next(line)),
              "Progress: %d%%" % (unit.build_progress * 100))
      if unit.transport_slots_taken > 0:
        write((left + 1, next(line)), "Slots: %s" % unit.transport_slots_taken)

    def write_multi(units, line):
      counts = collections.defaultdict(int)
      for unit in units:
        counts[unit_name(unit.unit_type)] += 1
      for name, count in sorted(counts.items()):
        y = next(line)
        write((left + 1, y), count)
        write((left + 3, y), name)

    ui = self._obs.observation.ui_data
    line = itertools.count(3)

    if ui.groups:
      write((left, next(line)), "Control Groups:", colors.green)
      for group in ui.groups:
        y = next(line)
        write((left + 1, y), "%s:" % group.control_group_index, colors.green)
        write((left + 3, y), "%s %s" % (group.count,
                                        unit_name(group.leader_unit_type)))
      next(line)

    if ui.HasField("single"):
      write((left, next(line)), "Selection:", colors.green)
      write_single(ui.single.unit, line)
    elif ui.HasField("multi"):
      write((left, next(line)), "Selection:", colors.green)
      write_multi(ui.multi.units, line)
    elif ui.HasField("cargo"):
      write((left, next(line)), "Selection:", colors.green)
      write_single(ui.cargo.unit, line)
      next(line)
      write((left, next(line)), "Cargo:", colors.green)
      write((left + 1, next(line)),
            "Empty slots: %s" % ui.cargo.slots_available)
      write_multi(ui.cargo.passengers, line)
    elif ui.HasField("production"):
      write((left, next(line)), "Selection:", colors.green)
      write_single(ui.production.unit, line)
      next(line)
      write((left, next(line)), "Build Queue:", colors.green)
      for unit in ui.production.build_queue:
        s = unit_name(unit.unit_type)
        if unit.build_progress > 0:
          s += ": %d%%" % (unit.build_progress * 100)
        write((left + 1, next(line)), s)


Instruction:
Can you implement a function in Python 3 that
draws the actions so that they can be inspected for accuracy.

Response:
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 = remain / 3
          self.all_surfs(_Surface.draw_circle, act.color, act.pos, size, 1)
        else:
          # Fade with alpha would be nice, but doesn't seem to work.
          self.all_surfs(_Surface.draw_rect, act.color, act.pos, 1)


Instruction:
Implement a function in Python 3 to
prepare the list of past actions so they can be drawn.

Response:
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._static_data.abilities[ability_id]
        if ability.remaps_to_ability_id:  # Prefer general abilities.
          ability_id = ability.remaps_to_ability_id
      self._past_actions.append(
          PastAction(ability_id, color, pos, now, now + timeout))

    for act in obs.actions:
      if (act.HasField("action_raw") and
          act.action_raw.HasField("unit_command") and
          act.action_raw.unit_command.HasField("target_world_space_pos")):
        pos = point.Point.build(
            act.action_raw.unit_command.target_world_space_pos)
        add_act(act.action_raw.unit_command.ability_id, colors.yellow, pos)
      if act.HasField("action_feature_layer"):
        act_fl = act.action_feature_layer
        if act_fl.HasField("unit_command"):
          if act_fl.unit_command.HasField("target_screen_coord"):
            pos = self._world_to_feature_screen_px.back_pt(
                point.Point.build(act_fl.unit_command.target_screen_coord))
            add_act(act_fl.unit_command.ability_id, colors.cyan, pos)
          elif act_fl.unit_command.HasField("target_minimap_coord"):
            pos = self._world_to_feature_minimap_px.back_pt(
                point.Point.build(act_fl.unit_command.target_minimap_coord))
            add_act(act_fl.unit_command.ability_id, colors.cyan, pos)
          else:
            add_act(act_fl.unit_command.ability_id, None, None)
        if (act_fl.HasField("unit_selection_point") and
            act_fl.unit_selection_point.HasField("selection_screen_coord")):
          pos = self._world_to_feature_screen_px.back_pt(point.Point.build(
              act_fl.unit_selection_point.selection_screen_coord))
          add_act(None, colors.cyan, pos)
        if act_fl.HasField("unit_selection_rect"):
          for r in act_fl.unit_selection_rect.selection_screen_coord:
            rect = point.Rect(
                self._world_to_feature_screen_px.back_pt(
                    point.Point.build(r.p0)),
                self._world_to_feature_screen_px.back_pt(
                    point.Point.build(r.p1)))
            add_act(None, colors.cyan, rect, 0.3)
      if act.HasField("action_render"):
        act_rgb = act.action_render
        if act_rgb.HasField("unit_command"):
          if act_rgb.unit_command.HasField("target_screen_coord"):
            pos = self._world_to_rgb_screen_px.back_pt(
                point.Point.build(act_rgb.unit_command.target_screen_coord))
            add_act(act_rgb.unit_command.ability_id, colors.red, pos)
          elif act_rgb.unit_command.HasField("target_minimap_coord"):
            pos = self._world_to_rgb_minimap_px.back_pt(
                point.Point.build(act_rgb.unit_command.target_minimap_coord))
            add_act(act_rgb.unit_command.ability_id, colors.red, pos)
          else:
            add_act(act_rgb.unit_command.ability_id, None, None)
        if (act_rgb.HasField("unit_selection_point") and
            act_rgb.unit_selection_point.HasField("selection_screen_coord")):
          pos = self._world_to_rgb_screen_px.back_pt(point.Point.build(
              act_rgb.unit_selection_point.selection_screen_coord))
          add_act(None, colors.red, pos)
        if act_rgb.HasField("unit_selection_rect"):
          for r in act_rgb.unit_selection_rect.selection_screen_coord:
            rect = point.Rect(
                self._world_to_rgb_screen_px.back_pt(
                    point.Point.build(r.p0)),
                self._world_to_rgb_screen_px.back_pt(
                    point.Point.build(r.p1)))
            add_act(None, colors.red, rect, 0.3)


Instruction:
Write a Python 3 function that can
draw the base map.

Response:
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_feature = features.SCREEN_FEATURES.creep
    creep = creep_feature.unpack(self._obs.observation)
    creep_mask = creep > 0
    creep_color = creep_feature.color(creep)

    power_feature = features.SCREEN_FEATURES.power
    power = power_feature.unpack(self._obs.observation)
    power_mask = power > 0
    power_color = power_feature.color(power)

    visibility = features.SCREEN_FEATURES.visibility_map.unpack(
        self._obs.observation)
    visibility_fade = np.array([[0.5] * 3, [0.75]*3, [1]*3])

    out = hmap_color * 0.6
    out[creep_mask, :] = (0.4 * out[creep_mask, :] +
                          0.6 * creep_color[creep_mask, :])
    out[power_mask, :] = (0.7 * out[power_mask, :] +
                          0.3 * power_color[power_mask, :])
    out *= visibility_fade[visibility]

    surf.blit_np_array(out)


Instruction:
Can you generate the documentation for the following Python 3 function
def draw_rendered_map(self, surf):
    surf.blit_np_array(features.Feature.unpack_rgb_image(
        self._obs.observation.render_data.map))

Response: Draw the rendered pixels.


Instruction:
Implement a Python 3 function for
drawing the screen area.

Response:
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.draw_units(surf)
    self.draw_selection(surf)
    self.draw_build_target(surf)
    self.draw_overlay(surf)
    self.draw_commands(surf)
    self.draw_panel(surf)


Instruction:
Can you create a Python 3 function that
draws a feature layer.

Response:
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)


Instruction:
Write a Python 3 function for
pushing an observation onto the queue to be rendered.

Response:
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
    self._last_game_loop = self._obs.observation.game_loop
    self._obs_queue.put(obs)
    if self._render_sync:
      self._obs_queue.join()


Instruction:
Can you generate the documentation for the following Python 3 function
def render_obs(self, obs):
    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.
      surf.draw(surf)

    mouse_pos = self.get_mouse_pos()
    if mouse_pos:
      # Draw a small mouse cursor
      self.all_surfs(_Surface.draw_circle, colors.green, mouse_pos.world_pos,
                     0.1)

    self.draw_actions()

    with sw("flip"):
      pygame.display.flip()

    self._render_times.append(time.time() - start_time)

Response: Render a frame given an observation.