Esempio n. 1
0
    def __init__(self,
                 replay_file_path,
                 agent,
                 player_id=1,
                 screen_size_px=(64, 64),
                 minimap_size_px=(64, 64),
                 discount=1.,
                 step_mul=1):

        self.agent = agent
        self.discount = discount
        self.step_mul = step_mul
        self.skip = 10
        self.replay_file_name = replay_file_path.split("/")[-1].split(".")[0]

        self.run_config = run_configs.get()
        self.sc2_proc = self.run_config.start()
        self.controller = self.sc2_proc.controller

        replay_data = self.run_config.replay_data(replay_file_path)
        ping = self.controller.ping()
        self.info = self.controller.replay_info(replay_data)

        if not self._valid_replay(self.info, ping):
            raise Exception(
                "{} is not a valid replay file!".format(replay_file_path))

        screen_size_px = point.Point(*screen_size_px)
        minimap_size_px = point.Point(*minimap_size_px)
        interface = sc_pb.InterfaceOptions(
            raw=False,
            score=True,
            feature_layer=sc_pb.SpatialCameraSetup(width=24))
        screen_size_px.assign_to(interface.feature_layer.resolution)
        minimap_size_px.assign_to(interface.feature_layer.minimap_resolution)

        map_data = None
        if self.info.local_map_path:
            map_data = self.run_config.map_data(self.info.local_map_path)

        self._episode_length = self.info.game_duration_loops
        self._episode_steps = 0

        self.controller.start_replay(
            sc_pb.RequestStartReplay(replay_data=replay_data,
                                     map_data=map_data,
                                     options=interface,
                                     observed_player_id=player_id))

        self._state = StepType.FIRST
Esempio n. 2
0
def get_replay_actor_interface(map_name, crop=False):
    map_name = map_name_transform(map_name)
    map_size = MAP_PLAYABLE_SIZE_DICT[map_name] if crop else MAP_ORI_SIZE_DICT[
        map_name]
    screen_size = point.Point(16, 16)
    minimap_size = point.Point(int(map_size[0]), int(map_size[1]))
    interface = sc_pb.InterfaceOptions(
        raw=True, score=True, feature_layer=sc_pb.SpatialCameraSetup(width=24))
    screen_size.assign_to(interface.feature_layer.resolution)
    minimap_size.assign_to(interface.feature_layer.minimap_resolution)
    if crop:
        interface.feature_layer.crop_to_playable_area = True
        interface.raw_crop_to_playable_area = True
    return interface
Esempio n. 3
0
    def __init__(self, env, mode):
        os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide'

        self.env = env
        self.mode = mode
        self.obs = None
        self._window_scale = 0.75
        self.game_info = game_info = self.env._controller.game_info()
        self.static_data = self.env._controller.data()

        self._obs_queue = queue.Queue()
        self._game_times = collections.deque(maxlen=100)  # Avg FPS over 100 frames.  # pytype: disable=wrong-keyword-args
        self._render_times = collections.deque(maxlen=100)  # pytype: disable=wrong-keyword-args
        self._last_time = time.time()
        self._last_game_loop = 0
        self._name_lengths = {}

        self._map_size = point.Point.build(game_info.start_raw.map_size)
        self._playable = point.Rect(
            point.Point.build(game_info.start_raw.playable_area.p0),
            point.Point.build(game_info.start_raw.playable_area.p1))

        window_size_px = point.Point(self.env.window_size[0],
                                     self.env.window_size[1])
        window_size_px = self._map_size.scale_max_size(
            window_size_px * self._window_scale).ceil()
        self._scale = window_size_px.y // 32

        self.display = pygame.Surface(window_size_px)

        if mode == "human":
            self.display = pygame.display.set_mode(window_size_px, 0, 32)
            pygame.display.init()

            pygame.display.set_caption("Starcraft Viewer")
        pygame.font.init()
        self._world_to_world_tl = transform.Linear(
            point.Point(1, -1), point.Point(0, self._map_size.y))
        self._world_tl_to_screen = transform.Linear(scale=window_size_px / 32)
        self.screen_transform = transform.Chain(self._world_to_world_tl,
                                                self._world_tl_to_screen)

        surf_loc = point.Rect(point.origin, window_size_px)
        sub_surf = self.display.subsurface(
            pygame.Rect(surf_loc.tl, surf_loc.size))
        self._surf = _Surface(sub_surf, None, surf_loc, self.screen_transform,
                              None, self.draw_screen)

        self._font_small = pygame.font.Font(None, int(self._scale * 0.5))
        self._font_large = pygame.font.Font(None, self._scale)
Esempio n. 4
0
    def __init__(self):
        self._feature_layer_screen_size = point.Point(84.0, 84.0)
        self._camera_width_world_units = 24.0
        self._map_size = point.Point(64, 64)
        self._camera_center = point.Point(33.0, 25.0)

        self._world_to_screen = transform.Linear(
            point.Point(1, -1), point.Point(0, self._map_size.y))
        self._screen_to_fl_screen = transform.Linear(
            self._feature_layer_screen_size / self._camera_width_world_units)
        self._world_to_fl_screen = transform.Chain(self._world_to_screen,
                                                   self._screen_to_fl_screen,
                                                   transform.Floor())
        self._update_camera(self._camera_center)
Esempio n. 5
0
    def __init__(self,
                 game_info=None,
                 map_size=None,
                 camera_width_world_units=None,
                 screen_size_px=None,
                 minimap_size_px=None,
                 hide_specific_actions=True):
        """Initialize a Features instance.

    Args:
      game_info: A `sc_pb.ResponseGameInfo` from the game. Can be None if you
          instead set `screen_size_px` and `minimap_size_px`.
      screen_size_px: The screen resolution.
      minimap_size_px: The minimap resolution.
      hide_specific_actions: [bool] Some actions (eg cancel) have many
          specific versions (cancel this building, cancel that spell) and can
          be represented in a more general form. If a specific action is
          available, the general will also be available. If you set
          `hide_specific_actions` to False, the specific versions will also be
          available, but if it's True, the specific ones will be hidden.
          Similarly, when transforming back, a specific action will be returned
          as the general action. This simplifies the action space, though can
          lead to some actions in replays not being exactly representable using
          only the general actions.
        map_size: The map size.
        camera_width_world_units: The camera width in world units.
    Raises:
      ValueError: if game_info is None and screen or minimap sizes are missing.
    """
        if game_info:
            fl_opts = game_info.options.feature_layer
            screen_size_px = point.Point.build(fl_opts.resolution)
            minimap_size_px = point.Point.build(fl_opts.minimap_resolution)
        elif not (screen_size_px and minimap_size_px):
            raise ValueError(
                "Must provide either game_info or screen and minimap sizes")
        self._screen_size_px = point.Point(*screen_size_px)
        self._minimap_size_px = point.Point(*minimap_size_px)
        self._hide_specific_actions = hide_specific_actions
        self._valid_functions = self._init_valid_functions()

        self._feature_units = (map_size and camera_width_world_units)
        if self._feature_units:
            self._map_size = point.Point.build(map_size)
            self._camera_width_world_units = camera_width_world_units
            self._init_camera()
        else:
            self._map_size = None
            self._camera_width_world_units = None
Esempio n. 6
0
  def draw_help(self, surf):
    """Draw the help dialog."""
    if not self._help:
      return

    def write(line, loc):
      surf.surf.blit(self._font_large.render(line, True, colors.black), loc)

    surf.surf.fill(colors.white * 0.8)
    write("Shortcuts:", point.Point(self._scale, self._scale))

    align = max(len(s) for s, _ in self.shortcuts) * 0.4 + 3
    for i, (hotkey, description) in enumerate(self.shortcuts, start=2):
      write(hotkey, point.Point(self._scale * 2, self._scale * i))
      write(description, point.Point(self._scale * align, self._scale * i))
Esempio n. 7
0
def _get_desktop_size():
    """Get the desktop size."""
    if platform.system() == "Linux":
        try:
            xrandr_query = subprocess.check_output(["xrandr", "--query"])
            sizes = re.findall(r"\bconnected primary (\d+)x(\d+)",
                               str(xrandr_query))
            if sizes[0]:
                return point.Point(int(sizes[0][0]), int(sizes[0][1]))
        except ValueError:
            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)
Esempio n. 8
0
 def add_feature_layer(feature, surf_type, world_to_surf):
   """Add a feature layer surface."""
   i = next(feature_counter)
   grid_offset = point.Point(i % cols, i // 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,
               lambda surf: self.draw_feature_layer(surf, feature))
    def __init__(self,
                 replay_file_path,
                 agent,
                 player_id=1,
                 discount=1.,
                 step_mul=1):

        self.agent = agent
        self.discount = discount
        self.step_mul = step_mul
        # lib.version_dict
        self.run_config = run_configs.get()
        # self.run_config.lib.
        self.sc2_proc = self.run_config.start()
        self.controller = self.sc2_proc.controller
        # self.sc2_proc.version = sc_pb.RequestReplayInfo.download_data
        replay_data = self.run_config.replay_data(replay_file_path)
        ping = self.controller.ping()
        # sc_process.
        self.info = self.controller.replay_info(replay_data)
        if not self._valid_replay(self.info, ping):
            raise Exception(
                "{} is not a valid replay file!".format(replay_file_path))

        _screen_size_px = point.Point(*self.screen_size_px)
        _minimap_size_px = point.Point(*self.minimap_size_px)
        interface = sc_pb.InterfaceOptions(
            raw=False,
            score=True,
            feature_layer=sc_pb.SpatialCameraSetup(width=self.camera_width,
                                                   crop_to_playable_area=True))
        _screen_size_px.assign_to(interface.feature_layer.resolution)
        _minimap_size_px.assign_to(interface.feature_layer.minimap_resolution)

        map_data = None
        if self.info.local_map_path:
            map_data = self.run_config.map_data(self.info.local_map_path)

        self._episode_length = self.info.game_duration_loops
        self._episode_steps = 0

        self.controller.start_replay(
            sc_pb.RequestStartReplay(replay_data=replay_data,
                                     map_data=map_data,
                                     options=interface,
                                     observed_player_id=player_id))

        self._state = StepType.FIRST
Esempio n. 10
0
def _get_max_window_size():  # pylint: disable=g-wrong-blank-lines
  global max_window_size
  if max_window_size is None:
    display_info = pygame.display.Info()
    desktop_size = point.Point(display_info.current_w, display_info.current_h)
    max_window_size = desktop_size * 0.75
  return max_window_size
Esempio n. 11
0
  def __translate__(tf, tf_dir, x, y = None):

    # Either a point or a distance
    pt = None
    dist = None

    # Convert any integers to floats
    if type(x) is int:
      x = float(x)
    if type(y) is int:
      y = float(y)

    if type(x) is point.Point:
      pt = x
    elif (type(x) is float) and (type(y) is float):
      pt = point.Point(x, y)
    elif (type(x) is float) and (y == None):
      dist = x

    func_pt   = getattr(tf, '{}_pt'  .format(tf_dir))
    func_dist = getattr(tf, '{}_dist'.format(tf_dir))

    if   pt   and func_pt:
      return func_pt  (pt  )
    elif dist and func_dist:
      return func_dist(dist)
    else:
      raise ValueError
Esempio n. 12
0
 def testAssignTo(self):
     f = FakePoint()
     self.assertEqual(5, f.x)
     self.assertEqual(8, f.y)
     point.Point(1, 2).assign_to(f)
     self.assertEqual(1, f.x)
     self.assertEqual(2, f.y)
Esempio n. 13
0
    def __init__(self):
        # Environment.
        self.map_name = 'NewkirkPrecinct'
        self.screen_size_px = (32, 32)
        self.minimap_size_px = (32, 32)
        self.camera_width = 24
        self.random_seed = 42

        self.interface = sc_pb.InterfaceOptions(
            raw=True,
            score=True,
            feature_layer=sc_pb.SpatialCameraSetup(width=self.camera_width))
        resolution = point.Point(*self.screen_size_px)
        resolution.assign_to(self.interface.feature_layer.resolution)
        minimap_resolution = point.Point(*self.minimap_size_px)
        minimap_resolution.assign_to(
            self.interface.feature_layer.minimap_resolution)

        # Feature layer with the unit types.
        self.unit_type_id = features.SCREEN_FEATURES.unit_type.index
        self.num_observations = 3000
        self.player_id = 1

        # Hard code an action sequence.
        # TODO(petkoig): This is very brittle. A random seed reduces flakiness, but
        # isn't guaranteed to give the same actions between game versions. The pixel
        # coords should be computed at run-time, maybe with a trigger type system in
        # case build times also change.
        self.action_sequence = {
            507: ('select_point', [[1], [9, 18]]),  # Target an SCV.
            963: ('Build_SupplyDepot_screen', [[0], [4, 19]]),
            1152: ('select_point', [[0], [15,
                                          13]]),  # Select the Command Center.
            1320: ('Train_SCV_quick', [[0]]),
            1350: ('Train_SCV_quick', [[0]]),
            1393: ('Train_SCV_quick', [[0]]),
            1437: ('Train_SCV_quick', [[0]]),
            1564: ('Train_SCV_quick', [[0]]),
            1602: ('Train_SCV_quick', [[0]]),
            1822: ('select_idle_worker', [[2]]),
            2848: ('Build_Barracks_screen', [[0], [22, 22]])
        }

        self.actions = {
            frame: self.action_to_function_call(*action)
            for frame, action in six.iteritems(self.action_sequence)
        }
Esempio n. 14
0
    def __init__(self):
        # Environment.
        self.map_name = 'NewkirkPrecinct'
        self.screen_size_px = (32, 32)
        self.minimap_size_px = (32, 32)
        self.camera_width = 24
        self.random_seed = 42

        self.interface = sc_pb.InterfaceOptions(
            raw=True,
            score=True,
            feature_layer=sc_pb.SpatialCameraSetup(width=self.camera_width))
        resolution = point.Point(*self.screen_size_px)
        resolution.assign_to(self.interface.feature_layer.resolution)
        minimap_resolution = point.Point(*self.minimap_size_px)
        minimap_resolution.assign_to(
            self.interface.feature_layer.minimap_resolution)

        # Magic unit ids.
        self.scv_unit_id = 45
        self.command_center_id = 18

        # Feature layer with the unit types.
        self.unit_type_id = features.SCREEN_FEATURES.unit_type.index
        self.num_observations = 3000
        self.player_id = 1

        # Hard code an action sequence.
        self.action_sequence = {
            507: ('select_point', [[1], [9, 15]]),  # Target an SCV.
            963: ('Build_SupplyDepot_screen', [[0], [4, 19]]),
            1152: ('select_point', [[0], [15,
                                          10]]),  # Select the Command Center.
            1320: ('Train_SCV_quick', [[0]]),
            1350: ('Train_SCV_quick', [[0]]),
            1393: ('Train_SCV_quick', [[0]]),
            1437: ('Train_SCV_quick', [[0]]),
            1564: ('Train_SCV_quick', [[0]]),
            1602: ('Train_SCV_quick', [[0]]),
            1822: ('select_idle_worker', [[2]]),
            2848: ('Build_Barracks_screen', [[0], [22, 22]])
        }

        self.actions = {
            frame: self.action_to_function_call(*action)
            for frame, action in six.iteritems(self.action_sequence)
        }
Esempio n. 15
0
def world_to_minimap_pos(game_info, pos):

    map_size = point.Point.build(game_info.start_raw.map_size)
    fl_opts = game_info.options.feature_layer
    feature_layer_minimap_size = point.Point.build(fl_opts.minimap_resolution)

    max_map_dim = map_size.max_dim()

    world_to_minimap = transform.Linear(point.Point(1, -1),
                                        point.Point(0, map_size.y))
    minimap_to_fl_minimap = transform.Linear(feature_layer_minimap_size /
                                             max_map_dim)
    world_to_fl_minimap = transform.Chain(world_to_minimap,
                                          minimap_to_fl_minimap,
                                          transform.Floor())

    trans_pos = world_to_fl_minimap.fwd_pt(point.Point.build(pos))
    return np.clip(np.array(trans_pos), 0, 63).tolist()
Esempio n. 16
0
 def _init_camera(self, feature_dimensions, map_size,
                  camera_width_world_units):
     """Initialize the feature_units camera."""
     if not map_size or not camera_width_world_units:
         raise ValueError(
             "Either pass the game_info with raw enabled, or map_size and "
             "camera_width_world_units in order to use feature_units.")
     map_size = point.Point.build(map_size)
     self._world_to_world_tl = transform.Linear(point.Point(1, -1),
                                                point.Point(0, map_size.y))
     self._world_tl_to_world_camera_rel = transform.Linear(
         offset=-map_size / 4)
     world_camera_rel_to_feature_screen = transform.Linear(
         feature_dimensions.screen / camera_width_world_units,
         feature_dimensions.screen / 2)
     self._world_to_feature_screen_px = transform.Chain(
         self._world_to_world_tl, self._world_tl_to_world_camera_rel,
         world_camera_rel_to_feature_screen, transform.PixelToCoord())
Esempio n. 17
0
def screen_to_minimap_pos(game_info, screen_pos, obs):

    screen_pos = Pos(screen_pos[0], screen_pos[1])

    # init parameter and define
    map_size = point.Point.build(game_info.start_raw.map_size)
    fl_opts = game_info.options.feature_layer
    feature_layer_screen_size = point.Point.build(fl_opts.resolution)
    feature_layer_minimap_size = point.Point.build(fl_opts.minimap_resolution)

    # screen to world
    camera_width_world_units = fl_opts.width

    world_to_screen = transform.Linear(point.Point(1, -1),
                                       point.Point(0, map_size.y))
    screen_to_fl_screen = transform.Linear(feature_layer_screen_size /
                                           camera_width_world_units)
    world_to_fl_screen = transform.Chain(world_to_screen, screen_to_fl_screen,
                                         transform.Floor())

    # Update the camera transform based on the new camera center.
    camera_center = obs.raw_observation.observation.raw_data.player.camera
    camera_radius = (feature_layer_screen_size / feature_layer_screen_size.x *
                     camera_width_world_units / 2)
    camera_center = point.Point.build(camera_center)
    center = camera_center.bound(camera_radius, map_size - camera_radius)
    camera = point.Rect((center - camera_radius).bound(map_size),
                        (center + camera_radius).bound(map_size))
    world_to_screen.offset = (-camera.bl * world_to_screen.scale)

    world_pos = world_to_fl_screen.back_pt(point.Point.build(screen_pos))

    # world to minimap
    max_map_dim = map_size.max_dim()

    world_to_minimap = transform.Linear(point.Point(1, -1),
                                        point.Point(0, map_size.y))
    minimap_to_fl_minimap = transform.Linear(feature_layer_minimap_size /
                                             max_map_dim)
    world_to_fl_minimap = transform.Chain(world_to_minimap,
                                          minimap_to_fl_minimap,
                                          transform.Floor())
    minimap_pos = world_to_fl_minimap.fwd_pt(point.Point.build(world_pos))
    return np.clip(np.array(minimap_pos), 0, 63).tolist()
 def testScaleMinSize(self):
     p = point.Point(3, 4)
     self.assertEqual(p, p.scale_min_size(p))
     self.assertEqual(point.Point(6, 8), p.scale_min_size(point.Point(6,
                                                                      6)))
     self.assertEqual(point.Point(6, 8), p.scale_min_size(point.Point(2,
                                                                      8)))
     self.assertEqual(point.Point(6, 8), p.scale_min_size(point.Point(6,
                                                                      2)))
Esempio n. 19
0
 def testScaleMaxSize(self):
     p = point.Point(3, 4)
     self.assertEqual(p, p.scale_max_size(p))
     self.assertEqual(point.Point(6, 8), p.scale_max_size(point.Point(8,
                                                                      8)))
     self.assertEqual(point.Point(6, 8),
                      p.scale_max_size(point.Point(100, 8)))
     self.assertEqual(point.Point(6, 8),
                      p.scale_max_size(point.Point(6, 100)))
Esempio n. 20
0
 def get_mouse_pos(self, window_pos=None):
   """Return a MousePos filled with the world and screen/minimap positions."""
   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.surf_type)
Esempio n. 21
0
 def setUp(self):
     self._features = features.Features(features.AgentInterfaceFormat(
         feature_dimensions=features.Dimensions(screen=(64, 60),
                                                minimap=(32, 28)),
         rgb_dimensions=features.Dimensions(screen=(128, 124),
                                            minimap=(64, 60)),
         action_space=actions.ActionSpace.FEATURES,
         use_feature_units=True),
                                        map_size=point.Point(256, 256))
     self._obs_spec = self._features.observation_spec()
     self._builder = dummy_observation.Builder(self._obs_spec)
Esempio n. 22
0
 def testInitTwoPointsReversed(self):
     r = point.Rect(point.Point(3, 4), point.Point(1, 2))
     self.assertEqual(r.t, 2)
     self.assertEqual(r.l, 1)
     self.assertEqual(r.b, 4)
     self.assertEqual(r.r, 3)
     self.assertEqual(r.tl, point.Point(1, 2))
     self.assertEqual(r.tr, point.Point(3, 2))
     self.assertEqual(r.bl, point.Point(1, 4))
     self.assertEqual(r.br, point.Point(3, 4))
     self.assertEqual(r.size, point.Point(2, 2))
     self.assertEqual(r.center, point.Point(2, 3))
     self.assertEqual(r.area, 4)
Esempio n. 23
0
def get_dft_sc2_interface():
    """get default sc2 interface when starting the game.

  It uses a small enough size (16, 16) for the irrelevant feature layers"""
    size = point.Point(16, 16)
    sc_interface = sc_pb.InterfaceOptions(
        raw=True,
        score=False,
        feature_layer=sc_pb.SpatialCameraSetup(width=24))
    size.assign_to(sc_interface.feature_layer.resolution)
    size.assign_to(sc_interface.feature_layer.minimap_resolution)
    return sc_interface
Esempio n. 24
0
  def update_transformations(self):

    # Create transformations
    self._world_to_minimap = transform.Linear(point.Point(1, -1),
                                              point.Point(0, self._map_size.y))
    max_map_dim = self._map_size.max_dim()
    self._minimap_to_fl_minimap = transform.Linear(
        self._minimap_size / max_map_dim)
    self._world_to_fl_minimap = transform.Chain(
        self._world_to_minimap,
        self._minimap_to_fl_minimap,
        transform.Floor())

    # Flip and zoom to the camera area. Update the offset as the camera moves.
    # Get camera corner
    cam_x   = -1 * (self._camera_pos['x'] - (self._camera_width / 2))
    cam_y   =  1 * (self._camera_pos['y'] + (self._camera_width / 2))
    cam_pos = point.Point(x = cam_x, y = cam_y)

    self._reorient_world  = transform.Linear(point.Point(1, -1), offset=cam_pos)
    self._world_to_screen = transform.Linear(point.Point(1, 1),
                                             point.Point(0, 0))
    #self._world_to_screen = transform.Linear(point.Point(1, -1),
    #                                         point.Point(0, self._map_size.y))
    self._screen_to_fl_screen = transform.Linear(
        self._screen_size / self._camera_width)
    self._world_to_fl_screen = transform.Chain(
        self._reorient_world,
        self._world_to_screen,
        self._screen_to_fl_screen,
        transform.PixelToCoord())
Esempio n. 25
0
 def testBound(self):
     tl = point.Point(1, 2)
     br = point.Point(3, 4)
     self.assertEqual(tl, point.Point(0, 0).bound(tl, br))
     self.assertEqual(br, point.Point(10, 10).bound(tl, br))
     self.assertEqual(point.Point(1.5, 2),
                      point.Point(1.5, 0).bound(tl, br))
Esempio n. 26
0
    def __init__(self):
        # Environment.
        self.map_name = 'Flat64'
        screen_resolution = point.Point(32, 32)
        minimap_resolution = point.Point(32, 32)
        self.camera_width = 24
        self.random_seed = 42

        self.interface = sc_pb.InterfaceOptions(
            raw=True,
            score=True,
            feature_layer=sc_pb.SpatialCameraSetup(width=self.camera_width))
        screen_resolution.assign_to(self.interface.feature_layer.resolution)
        minimap_resolution.assign_to(
            self.interface.feature_layer.minimap_resolution)

        # Hard code an action sequence.
        # TODO(petkoig): Consider whether the Barracks and Supply Depot positions
        # need to be dynamically determined.
        self.actions = {
            507: select(any_point, units.Terran.SCV),
            963: identity_function('Build_SupplyDepot_screen',
                                   ['now', [25, 15]]),
            1152: select(avg_point, units.Terran.CommandCenter),
            1320: identity_function('Train_SCV_quick', ['now']),
            1350: identity_function('Train_SCV_quick', ['now']),
            1393: identity_function('Train_SCV_quick', ['now']),
            1437: identity_function('Train_SCV_quick', ['now']),
            1522: select(any_point, units.Terran.SCV),
            1548: identity_function('Build_Barracks_screen',
                                    ['now', [25, 25]]),
            1752: select(avg_point, units.Terran.CommandCenter),
            1937: identity_function('Train_SCV_quick', ['now']),
            2400: select(avg_point, units.Terran.Barracks),
            2700: identity_function('Train_Marine_quick', ['now']),
            3300: select(any_point, units.Terran.Marine),
        }
        self.num_observations = max(self.actions.keys()) + 2
        self.player_id = 1
Esempio n. 27
0
    async def join_game(self,
                        race=None,
                        observed_player_id=None,
                        portconfig=None):
        # Note modified by Davey for pysc2
        screen_size_px = (64, 64)
        minimap_size_px = (64, 64)
        screen_size_px = point.Point(*screen_size_px)
        minimap_size_px = point.Point(*minimap_size_px)
        ifopts = sc_pb.InterfaceOptions(
            raw=True,
            score=True,
            feature_layer=sc_pb.SpatialCameraSetup(width=24))
        screen_size_px.assign_to(ifopts.feature_layer.resolution)
        minimap_size_px.assign_to(ifopts.feature_layer.minimap_resolution)

        if race is None:
            assert isinstance(observed_player_id, int)
            # join as observer
            req = sc_pb.RequestJoinGame(observed_player_id=observed_player_id,
                                        options=ifopts)
        else:
            assert isinstance(race, Race)
            req = sc_pb.RequestJoinGame(race=race.value, options=ifopts)

        if portconfig:
            req.shared_port = portconfig.shared
            req.server_ports.game_port = portconfig.server[0]
            req.server_ports.base_port = portconfig.server[1]

            for ppc in portconfig.players:
                p = req.client_ports.add()
                p.game_port = ppc[0]
                p.base_port = ppc[1]

        result = await self._execute(join_game=req)
        self._game_result = None
        self._player_id = result.join_game.player_id
        return result.join_game.player_id
Esempio n. 28
0
def _to_point(dims):
  """Convert (width, height) or size -> point.Point."""
  assert dims

  if isinstance(dims, (tuple, list)):
    if len(dims) != 2:
      raise ValueError(
          "A two element tuple or list is expected here, got {}.".format(dims))
    else:
      width = int(dims[0])
      height = int(dims[1])
      if width <= 0 or height <= 0:
        raise ValueError("Must specify +ve dims, got {}.".format(dims))
      else:
        return point.Point(width, height)
  else:
    size = int(dims)
    if size <= 0:
      raise ValueError(
          "Must specify a +ve value for size, got {}.".format(dims))
    else:
      return point.Point(size, size)
Esempio n. 29
0
def _get_interface(map_name, game_core_config={}):
    crop = (game_core_config['crop_to_playable_area']
            if 'crop_to_playable_area' in game_core_config else False)
    map_name = map_name_transform(map_name)
    map_size = MAP_PLAYABLE_SIZE_DICT[map_name] if crop else MAP_ORI_SIZE_DICT[
        map_name]
    screen_size = point.Point(16, 16)
    minimap_size = point.Point(int(map_size[0]), int(map_size[1]))
    interface = sc_pb.InterfaceOptions(
        raw=True, score=True, feature_layer=sc_pb.SpatialCameraSetup(width=24))
    screen_size.assign_to(interface.feature_layer.resolution)
    minimap_size.assign_to(interface.feature_layer.minimap_resolution)
    if crop:
        interface.feature_layer.crop_to_playable_area = True
        interface.raw_crop_to_playable_area = True
    if 'show_cloaked' in game_core_config:
        interface.show_cloaked = game_core_config['show_cloaked']
    if 'show_burrowed_shadows' in game_core_config:
        interface.show_burrowed_shadows = game_core_config[
            'show_burrowed_shadows']
    if 'show_placeholders' in game_core_config:
        interface.show_placeholders = game_core_config['show_placeholders']
    return interface
Esempio n. 30
0
 def testInitOnePoint(self):
     r = point.Rect(point.Point(1, 2))
     self.assertEqual(r.t, 0)
     self.assertEqual(r.l, 0)
     self.assertEqual(r.b, 2)
     self.assertEqual(r.r, 1)
     self.assertEqual(r.tl, point.Point(0, 0))
     self.assertEqual(r.tr, point.Point(1, 0))
     self.assertEqual(r.bl, point.Point(0, 2))
     self.assertEqual(r.br, point.Point(1, 2))
     self.assertEqual(r.size, point.Point(1, 2))
     self.assertEqual(r.center, point.Point(1, 2) / 2)
     self.assertEqual(r.area, 2)