INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Fit X into an embedded space and return that transformed output.
def fit_transform(self, X, y=None): """Fit X into an embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance mat...
Transform X into the existing embedded space and return that transformed output.
def transform(self, X): """Transform X into the existing embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) New data to be transformed. Returns ------- X_new : array, shape (n_sam...
Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments on sparse matrix data provided in CSR ind indptr and data format. Numba doesn t support higher order functions directly but we can instead JIT compile the version of NN - descent for any given m...
def make_sparse_nn_descent(sparse_dist, dist_args): """Create a numba accelerated version of nearest neighbor descent specialised for the given distance metric and metric arguments on sparse matrix data provided in CSR ind, indptr and data format. Numba doesn't support higher order functions directly, b...
Get an InterfaceOptions for the config.
def interface_options(score=False, raw=False, features=None, rgb=None): """Get an InterfaceOptions for the config.""" interface = sc_pb.InterfaceOptions() interface.score = score interface.raw = raw if features: interface.feature_layer.width = 24 interface.feature_layer.resolution.x = features int...
Registers a flag whose value parses as a point.
def DEFINE_point(name, default, help): # pylint: disable=invalid-name,redefined-builtin """Registers a flag whose value parses as a point.""" flags.DEFINE(PointParser(), name, default, help)
Choose the action space for the action proto.
def spatial(action, action_space): """Choose the action space for the action proto.""" if action_space == ActionSpace.FEATURES: return action.action_feature_layer elif action_space == ActionSpace.RGB: return action.action_render else: raise ValueError("Unexpected value for action_space: %s" % action...
Move the camera.
def move_camera(action, action_space, minimap): """Move the camera.""" minimap.assign_to(spatial(action, action_space).camera_move.center_minimap)
Select a unit at a point.
def select_point(action, action_space, select_point_act, screen): """Select a unit at a point.""" select = spatial(action, action_space).unit_selection_point screen.assign_to(select.selection_screen_coord) select.type = select_point_act
Select units within a rectangle.
def select_rect(action, action_space, select_add, screen, screen2): """Select units within a rectangle.""" select = spatial(action, action_space).unit_selection_rect out_rect = select.selection_screen_coord.add() screen_rect = point.Rect(screen, screen2) screen_rect.tl.assign_to(out_rect.p0) screen_rect.br....
Select an idle worker.
def select_idle_worker(action, action_space, select_worker): """Select an idle worker.""" del action_space action.action_ui.select_idle_worker.type = select_worker
Select the entire army.
def select_army(action, action_space, select_add): """Select the entire army.""" del action_space action.action_ui.select_army.selection_add = select_add
Select all warp gates.
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
Select a specific unit from the multi - unit selection.
def select_unit(action, action_space, select_unit_act, select_unit_id): """Select a specific unit from the multi-unit selection.""" del action_space select = action.action_ui.multi_panel select.type = select_unit_act select.unit_index = select_unit_id
Act on a control group selecting setting etc.
def control_group(action, action_space, control_group_act, control_group_id): """Act on a control group, selecting, setting, etc.""" del action_space select = action.action_ui.control_group select.action = control_group_act select.control_group_index = control_group_id
Unload a unit from a transport/ bunker/ nydus/ etc.
def unload(action, action_space, unload_id): """Unload a unit from a transport/bunker/nydus/etc.""" del action_space action.action_ui.cargo_panel.unit_index = unload_id
Cancel a unit in the build queue.
def build_queue(action, action_space, build_queue_id): """Cancel a unit in the build queue.""" del action_space action.action_ui.production_panel.unit_index = build_queue_id
Do a quick command like Stop or Stim.
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
Do a command that needs a point on the screen.
def cmd_screen(action, action_space, ability_id, queued, screen): """Do a command that needs a point on the 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)
Do a command that needs a point on the minimap.
def cmd_minimap(action, action_space, ability_id, queued, minimap): """Do a command that needs a point on the 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)
Toggle autocast.
def autocast(action, action_space, ability_id): """Toggle autocast.""" del action_space action.action_ui.toggle_autocast.ability_id = ability_id
Create an ArgumentType where you choose one of a set of known values.
def enum(cls, options, values): """Create an ArgumentType where you choose one of a set of known 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
Create an ArgumentType with a single scalar in range ( value ).
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)
Create an ArgumentType that is represented by a point. Point.
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
Create an Arguments of the possible Types.
def types(cls, **kwargs): """Create an Arguments of the possible Types.""" named = {name: factory(Arguments._fields.index(name), name) for name, factory in six.iteritems(kwargs)} return cls(**named)
Define a function representing a ui action.
def ui_func(cls, id_, name, function_type, avail_fn=always): """Define a function representing a ui action.""" return cls(id_, name, 0, 0, function_type, FUNCTION_TYPES[function_type], avail_fn)
Define a function represented as a game ability.
def ability(cls, id_, name, function_type, ability_id, general_id=0): """Define a function represented as a game ability.""" assert function_type in ABILITY_FUNCTIONS return cls(id_, name, ability_id, general_id, function_type, FUNCTION_TYPES[function_type], None)
String version. Set space = True to line them all up nicely.
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))
Return a FunctionCall given some validation for the function and args.
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 b...
Helper function for creating FunctionCall s with Arguments.
def all_arguments(cls, function, arguments): """Helper function for creating `FunctionCall`s with `Arguments`. Args: function: The value to store for the action function. arguments: The values to store for the arguments of the action. Can either be an `Arguments` object, a `dict`, or an ite...
Print the valid actions.
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))) ...
Reserves and returns a list of num_ports unused ports.
def pick_unused_ports(num_ports, retry_interval_secs=3, retry_attempts=5): """Reserves and returns a list of `num_ports` unused ports.""" ports = set() for _ in range(retry_attempts): ports.update( portpicker.pick_unused_port() for _ in range(num_ports - len(ports))) ports.discard(None) # portpic...
Reserves and returns a list of num_ports contiguous unused ports.
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...
Run one thread worth of the environment with agents.
def run_thread(agent_classes, players, map_name, visualize): """Run one thread worth of the environment with agents.""" 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, ...
Run an agent.
def main(unused_argv): """Run an agent.""" stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace stopwatch.sw.trace = FLAGS.trace map_inst = maps.get(FLAGS.map) agent_classes = [] players = [] agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module...
Raise if the result has an error otherwise return the result.
def check_error(res, error_enum): """Raise if the result has an error, otherwise return the result.""" 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'" % (e...
Decorator to call check_error on the return value.
def decorate_check_error(error_enum): """Decorator to call `check_error` on the return value.""" def decorator(func): @functools.wraps(func) def _check_error(*args, **kwargs): return check_error(func(*args, **kwargs), error_enum) return _check_error return decorator
Decorator to skip this call if we re in one of the skipped states.
def skip_status(*skipped): """Decorator to skip this call if we're in one of the skipped states.""" def decorator(func): @functools.wraps(func) def _skip_status(self, *args, **kwargs): if self.status not in skipped: return func(self, *args, **kwargs) return _skip_status return decorator
Decorator to assert that we re in a valid state.
def valid_status(*valid): """Decorator to assert that we're in a valid state.""" def decorator(func): @functools.wraps(func) def _valid_status(self, *args, **kwargs): if self.status not in valid: raise protocol.ProtocolError( "`%s` called while in state: %s, valid: (%s)" % ( ...
Decorator to handle Game has already ended exceptions.
def catch_game_end(func): """Decorator to handle 'Game has already ended' exceptions.""" @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 ...
Connect to the websocket retrying as needed. Returns the socket.
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 ran...
Save a map into temp dir so create game can access it in multiplayer.
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))
Get the raw static data for the current game. Prefer data instead.
def data_raw(self): """Get the raw static data for the current game. Prefer `data` instead.""" return self._client.send(data=sc_pb.RequestData( ability_id=True, unit_type_id=True))
Step the engine forward by one ( or more ) step.
def step(self, count=1): """Step the engine forward by one (or more) step.""" return self._client.send(step=sc_pb.RequestStep(count=count))
Send a sc_pb. RequestAction which may include multiple actions.
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)
Send a single action. This is a shortcut for actions.
def act(self, action): """Send a single action. This is a shortcut for `actions`.""" if action and action.ListFields(): # Skip no-ops. return self.actions(sc_pb.RequestAction(actions=[action]))
Send chat message as a broadcast.
def chat(self, message): """Send chat message as a broadcast.""" 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)
Save a replay returning the data.
def save_replay(self): """Save a replay, returning the data.""" res = self._client.send(save_replay=sc_pb.RequestSaveReplay()) return res.data
Run a debug command.
def debug(self, debug_commands): """Run a debug command.""" if isinstance(debug_commands, sc_debug.DebugCommand): debug_commands = [debug_commands] return self._client.send(debug=sc_pb.RequestDebug(debug=debug_commands))
Shut down the SC2 process.
def quit(self): """Shut down the SC2 process.""" try: # Don't expect a response. self._client.write(sc_pb.Request(quit=sc_pb.RequestQuit())) except protocol.ConnectionError: pass # It's likely already (shutting) down, so continue as if it worked. finally: self.close()
A run loop to have agents and an environment interact.
def run_loop(agents, env, max_frames=0, max_episodes=0): """A run loop to have agents and an environment interact.""" total_frames = 0 total_episodes = 0 start_time = time.time() observation_spec = env.observation_spec() action_spec = env.action_spec() for agent, obs_spec, act_spec in zip(agents, observa...
Return the map data for a map by name or path.
def map_data(self, map_name): """Return the map data for a map by name or path.""" with gfile.Open(os.path.join(self.data_dir, "Maps", map_name), "rb") as f: return f.read()
Return the replay data given a path to the replay.
def replay_data(self, replay_path): """Return the replay data given a path to the replay.""" with gfile.Open(self.abs_replay_path(replay_path), "rb") as f: return f.read()
A generator yielding the full path to the replays under replay_dir.
def replay_paths(self, replay_dir): """A generator yielding the full path to the replays under `replay_dir`.""" replay_dir = self.abs_replay_path(replay_dir) if replay_dir.lower().endswith(".sc2replay"): yield replay_dir return for f in gfile.ListDir(replay_dir): if f.lower().endswith(...
Save a replay to a directory returning the path to the replay.
def save_replay(self, replay_data, replay_dir, prefix=None): """Save a replay to a directory, returning the path to the replay. Args: replay_data: The result of controller.save_replay(), ie the binary data. replay_dir: Where to save the replay. This can be absolute or relative. prefix: Option...
An iterator over all subclasses of cls.
def all_subclasses(cls): """An iterator over all subclasses of `cls`.""" for s in cls.__subclasses__(): yield s for c in s.all_subclasses(): yield c
Turn all string indices into int indices preserving ellipsis.
def _indices(self, indices): """Turn all string indices into int indices, preserving ellipsis.""" if isinstance(indices, tuple): out = [] dim = 0 for i, index in enumerate(indices): if index is Ellipsis: out.append(index) dim = len(self.shape) - len(indices) + i ...
Turn a string into a real index otherwise return the index.
def _get_index(self, dim, index): """Turn a string into a real index, otherwise return the index.""" if isinstance(index, six.string_types): try: return self._index_names[dim][index] except KeyError: raise KeyError("Name '%s' is invalid for axis %s." % (index, dim)) except Type...
Assign x and y to an object that has properties x and y.
def assign_to(self, obj): """Assign `x` and `y` to an object that has properties `x` and `y`.""" obj.x = self.x obj.y = self.y
Distance to some other point.
def dist(self, other): """Distance to some other point.""" dx = self.x - other.x dy = self.y - other.y return math.sqrt(dx**2 + dy**2)
Distance squared to some other point.
def dist_sq(self, other): """Distance squared to some other point.""" dx = self.x - other.x dy = self.y - other.y return dx**2 + dy**2
Round x and y to integers.
def round(self): """Round `x` and `y` to integers.""" return Point(int(round(self.x)), int(round(self.y)))
Round x and y down to integers.
def floor(self): """Round `x` and `y` down to integers.""" return Point(int(math.floor(self.x)), int(math.floor(self.y)))
Round x and y up to integers.
def ceil(self): """Round `x` and `y` up to integers.""" return Point(int(math.ceil(self.x)), int(math.ceil(self.y)))
Bound this point within the rect defined by ( p1 p2 ).
def bound(self, p1, p2=None): """Bound this point within the rect defined by (`p1`, `p2`).""" r = Rect(p1, p2) return Point(min(max(self.x, r.l), r.r), min(max(self.y, r.t), r.b))
Is the point inside this rect?
def contains_point(self, pt): """Is the point inside this rect?""" return (self.l < pt.x and self.r > pt.x and self.t < pt.y and self.b > pt.y)
Is the circle completely inside this rect?
def contains_circle(self, pt, radius): """Is the circle completely inside this rect?""" return (self.l < pt.x - radius and self.r > pt.x + radius and self.t < pt.y - radius and self.b > pt.y + radius)
Does the circle intersect with this rect?
def intersects_circle(self, pt, radius): """Does the circle intersect with this rect?""" # How this works: http://stackoverflow.com/a/402010 rect_corner = self.size / 2 # relative to the rect center circle_center = (pt - self.center).abs() # relative to the rect center # Is the circle far from th...
Read the ExecuteInfo. txt file and return the base directory.
def _read_execute_info(path, parents): """Read the ExecuteInfo.txt file and return the base directory.""" path = os.path.join(path, "StarCraft II/ExecuteInfo.txt") if os.path.exists(path): with open(path, "rb") as f: # Binary because the game appends a '\0' :(. for line in f: parts = [p.strip()...
Launch the game.
def start(self, version=None, want_rgb=True, **kwargs): """Launch the game.""" del want_rgb # Unused if not os.path.isdir(self.data_dir): raise sc_process.SC2LaunchError( "Expected to find StarCraft II installed at '%s'. If it's not " "installed, do that and run it once so auto-de...
Create a game for the agents to join.
def create_game(self, map_name): """Create a game for the agents to join. Args: map_name: The map to use. """ map_inst = maps.get(map_name) map_data = map_inst.data(self._run_config) if map_name not in self._saved_maps: for controller in self._controllers: controller.save_ma...
Shutdown and free all resources.
def close(self): """Shutdown and free all resources.""" for controller in self._controllers: controller.quit() self._controllers = [] for process in self._processes: process.close() self._processes = [] portspicker.return_ports(self._lan_ports) self._lan_ports = []
Create a game one remote agent vs the specified bot.
def create_game( self, map_name, bot_difficulty=sc_pb.VeryEasy, bot_race=sc_common.Random, bot_first=False): """Create a game, one remote agent vs the specified bot. Args: map_name: The map to use. bot_difficulty: The difficulty of the bot to play against. bot_ra...
Shutdown and free all resources.
def close(self): """Shutdown and free all resources.""" if self._controller is not None: self._controller.quit() self._controller = None if self._process is not None: self._process.close() self._process = None
Run the agent connecting to a ( remote ) host started independently.
def agent(): """Run the agent, connecting to a (remote) host started independently.""" agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module), agent_name) logging.info("Starting agent:") with lan_sc2_env.LanSC2Env( host=FLAGS.host, config_p...
Run a host which expects one player to connect remotely.
def human(): """Run a host which expects one player to connect remotely.""" run_config = run_configs.get() map_inst = maps.get(FLAGS.map) if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size: logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb " "observations....
Make sure this stays synced with bin/ agent_remote. py.
def _connect_remote(self, host, host_port, lan_ports, race, name, map_inst, save_map, interface): """Make sure this stays synced with bin/agent_remote.py.""" # Connect! logging.info("Connecting...") self._controllers = [remote_controller.RemoteController(host, host_port)] loggi...
Get the config chosen by the flags.
def get(): """Get the config chosen by the flags.""" configs = {c.name(): c for c in lib.RunConfig.all_subclasses() if c.priority()} if not configs: raise sc_process.SC2LaunchError("No valid run_configs found.") if FLAGS.sc2_run_config is None: # Find the highest priority as default. ret...
Start a new episode.
def reset(self): """Start a new episode.""" self._episode_steps = 0 if self._episode_count: # No need to restart for the first episode. self._restart() self._episode_count += 1 logging.info("Starting episode: %s", self._episode_count) self._metrics.increment_episode() self._las...
Apply actions step the world forward and return observations.
def step(self, actions, step_mul=None): """Apply actions, step the world forward, and return observations. Args: actions: A list of actions meeting the action spec, one per agent. step_mul: If specified, use this rather than the environment's default. Returns: A tuple of TimeStep namedtu...
Useful for logging messages into the replay.
def send_chat_messages(self, messages): """Useful for logging messages into the replay.""" self._parallel.run( (c.chat, message) for c, message in zip(self._controllers, messages))
Make sure the replay isn t corrupt and is worth looking at.
def valid_replay(info, ping): """Make sure the replay isn't corrupt, and is worth looking at.""" if (info.HasField("error") or info.base_build != ping.base_build or # different game version info.game_duration_loops < 1000 or len(info.player_info) != 2): # Probably corrupt, or just not interes...
A thread that consumes stats_queue and prints them every 10 seconds.
def stats_printer(stats_queue): """A thread that consumes stats_queue and prints them every 10 seconds.""" proc_stats = [ProcessStats(i) for i in range(FLAGS.parallel)] print_time = start_time = time.time() width = 107 running = True while running: print_time += 10 while time.time() < print_time: ...
Dump stats about all the actions that are in use in a set of replays.
def main(unused_argv): """Dump stats about all the actions that are in use in a set of replays.""" run_config = run_configs.get() if not gfile.Exists(FLAGS.replays): sys.exit("{} doesn't exist.".format(FLAGS.replays)) stats_queue = multiprocessing.Queue() stats_thread = threading.Thread(target=stats_pri...
Merge another ReplayStats into this one.
def merge(self, other): """Merge another ReplayStats into this one.""" def merge_dict(a, b): for k, v in six.iteritems(b): a[k] += v self.replays += other.replays self.steps += other.steps self.camera_move += other.camera_move self.select_pt += other.select_pt self.select_rect...
Process a single replay updating the stats.
def process_replay(self, controller, replay_data, map_data, player_id): """Process a single replay, updating the stats.""" self._update_stage("start_replay") controller.start_replay(sc_pb.RequestStartReplay( replay_data=replay_data, map_data=map_data, options=interface, obser...
Start up the tcp server send the settings.
def tcp_server(tcp_addr, settings): """Start up the tcp server, send the settings.""" family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP) sock.bind(tcp_addr) sock.listen(1) logging.info("Waiting for connection on %s", tcp_ad...
Connect to the tcp server and return the settings.
def tcp_client(tcp_addr): """Connect to the tcp server, and return the settings.""" family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP) for i in range(300): logging.info("Connecting to: %s, attempt %d", tcp_addr, i) try:...
Read size number of bytes from conn retrying as needed.
def read_tcp_size(conn, size): """Read `size` number of bytes from `conn`, retrying as needed.""" chunks = [] bytes_read = 0 while bytes_read < size: chunk = conn.recv(size - bytes_read) if not chunk: if bytes_read > 0: logging.warning("Incomplete read: %s of %s.", bytes_read, size) ...
Forwards ports such that multiplayer works between machines.
def forward_ports(remote_host, local_host, local_listen_ports, remote_listen_ports): """Forwards ports such that multiplayer works between machines. Args: remote_host: Where to ssh to. local_host: "127.0.0.1" or "::1". local_listen_ports: Which ports to listen on locally to forward re...
Make sure this stays synced with bin/ play_vs_agent. py.
def _launch_remote(self, host, config_port, race, name, interface): """Make sure this stays synced with bin/play_vs_agent.py.""" self._tcp_conn, settings = tcp_client(Addr(host, config_port)) self._map_name = settings["map_name"] if settings["remote"]: self._udp_sock = udp_server( Addr...
Output information for a directory of replays.
def _replay_index(replay_dir): """Output information for a directory of replays.""" run_config = run_configs.get() replay_dir = run_config.abs_replay_path(replay_dir) print("Checking: ", replay_dir) with run_config.start(want_rgb=False) as controller: print("-" * 60) print(",".join(( "filenam...
Query a replay for information.
def _replay_info(replay_path): """Query a replay for information.""" if not replay_path.lower().endswith("sc2replay"): print("Must be a replay.") return run_config = run_configs.get() with run_config.start(want_rgb=False) as controller: info = controller.replay_info(run_config.replay_data(replay_pa...
Takes an array of ints and returns a corresponding colored rgb array.
def smooth_hue_palette(scale): """Takes an array of ints and returns a corresponding colored rgb array.""" # http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL # Based on http://stackoverflow.com/a/17382854 , with simplifications and # optimizations. Assumes S=1, L=0.5, meaning C=1 and m=0. # 0 stays black, ev...
Create a palette that is piece - wise linear given some colors at points.
def piece_wise_linear(scale, points): """Create a palette that is piece-wise linear given some colors at points.""" assert len(points) >= 2 assert points[0][0] == 0 assert points[-1][0] == 1 assert all(i < j for i, j in zip(points[:-1], points[1:])) out = numpy.zeros((scale, 3)) p1, c1 = points[0] p2, c...
Returns a palette that maps unit types to rgb colors.
def unit_type(scale=None): """Returns a palette that maps unit types to rgb colors.""" # Can specify a scale to match the api or to accept unknown unit types. palette_size = scale or max(static_data.UNIT_TYPES) + 1 palette = shuffled_hue(palette_size) assert len(static_data.UNIT_TYPES) <= len(distinct_colors)...
Make sure the lock is held while in this function.
def with_lock(lock): """Make sure the lock is held while in this function.""" def decorator(func): @functools.wraps(func) def _with_lock(*args, **kwargs): with lock: return func(*args, **kwargs) return _with_lock return decorator
Get the desktop size.
def _get_desktop_size(): """Get the desktop size.""" if platform.system() == "Linux": try: xrandr_query = subprocess.check_output(["xrandr", "--query"]) sizes = re.findall(r"\bconnected primary (\d+)x(\d+)", str(xrandr_query)) if sizes[0]: return point.Point(int(sizes[0][0]), int(sizes...
Draw an arc using world coordinates radius start and stop angles.
def draw_arc(self, color, world_loc, world_radius, start_angle, stop_angle, thickness=1): """Draw an arc using world coordinates, radius, start and stop angles.""" center = self.world_to_surf.fwd_pt(world_loc).round() radius = max(1, int(self.world_to_surf.fwd_dist(world_radius))) rect = ...
Draw a circle using world coordinates and radius.
def draw_circle(self, color, world_loc, world_radius, thickness=0): """Draw a circle using world coordinates and radius.""" if world_radius > 0: center = self.world_to_surf.fwd_pt(world_loc).round() radius = max(1, int(self.world_to_surf.fwd_dist(world_radius))) pygame.draw.circle(self.surf, c...
Draw a rectangle using world coordinates.
def draw_rect(self, color, world_rect, thickness=0): """Draw a rectangle using world coordinates.""" tl = self.world_to_surf.fwd_pt(world_rect.tl).round() br = self.world_to_surf.fwd_pt(world_rect.br).round() rect = pygame.Rect(tl, br - tl) pygame.draw.rect(self.surf, color, rect, thickness)