repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/tests/host_remote_agent_test.py | pysc2/tests/host_remote_agent_test.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test host_remote_agent.py."""
from absl.testing import absltest
from pysc2.env import host_remote_agent
from pysc2.lib import remote_controller
from pysc2.lib import run_parallel
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
NUM_MATCHES = 2
STEPS = 100
class TestHostRemoteAgent(utils.TestCase):
def testVsBot(self):
bot_first = True
for _ in range(NUM_MATCHES):
with host_remote_agent.VsBot() as game:
game.create_game(
map_name="Simple64",
bot_difficulty=sc_pb.VeryHard,
bot_first=bot_first)
controller = remote_controller.RemoteController(
host=game.host,
port=game.host_port)
join = sc_pb.RequestJoinGame(options=sc_pb.InterfaceOptions(raw=True))
join.race = sc_common.Random
controller.join_game(join)
for _ in range(STEPS):
controller.step()
response_observation = controller.observe()
if response_observation.player_result:
break
controller.leave()
controller.close()
bot_first = not bot_first
def testVsAgent(self):
parallel = run_parallel.RunParallel()
for _ in range(NUM_MATCHES):
with host_remote_agent.VsAgent() as game:
game.create_game("Simple64")
controllers = [
remote_controller.RemoteController( # pylint:disable=g-complex-comprehension
host=host,
port=host_port)
for host, host_port in zip(game.hosts, game.host_ports)]
join = sc_pb.RequestJoinGame(options=sc_pb.InterfaceOptions(raw=True))
join.race = sc_common.Random
join.shared_port = 0
join.server_ports.game_port = game.lan_ports[0]
join.server_ports.base_port = game.lan_ports[1]
join.client_ports.add(
game_port=game.lan_ports[2],
base_port=game.lan_ports[3])
parallel.run((c.join_game, join) for c in controllers)
for _ in range(STEPS):
parallel.run(c.step for c in controllers)
response_observations = [c.observe() for c in controllers]
if response_observations[0].player_result:
break
parallel.run(c.leave for c in controllers)
parallel.run(c.close for c in controllers)
parallel.shutdown()
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/tests/versions_test.py | pysc2/tests/versions_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that every version in run_configs actually runs."""
from absl import logging
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
def major_version(v):
return ".".join(v.split(".")[:2])
def log_center(s, *args):
logging.info(((" " + s + " ") % args).center(80, "-"))
class TestVersions(absltest.TestCase):
def test_version_numbers(self):
run_config = run_configs.get()
failures = []
for game_version, version in sorted(run_config.get_versions().items()):
try:
self.assertEqual(game_version, version.game_version)
log_center("starting version check: %s", game_version)
run_config = run_configs.get(version=game_version)
with run_config.start(want_rgb=False) as controller:
ping = controller.ping()
logging.info("expected: %s", version)
logging.info("actual: %s", ", ".join(str(ping).strip().split("\n")))
self.assertEqual(version.build_version, ping.base_build)
if version.game_version != "latest":
self.assertEqual(major_version(ping.game_version),
major_version(version.game_version))
self.assertEqual(version.data_version.lower(),
ping.data_version.lower())
log_center("success: %s", game_version)
except: # pylint: disable=bare-except
log_center("failure: %s", game_version)
logging.exception("Failed")
failures.append(game_version)
self.assertEmpty(failures)
def test_versions_create_game(self):
run_config = run_configs.get()
failures = []
for game_version in sorted(run_config.get_versions().keys()):
try:
log_center("starting create game: %s", game_version)
run_config = run_configs.get(version=game_version)
with run_config.start(want_rgb=False) as controller:
interface = sc_pb.InterfaceOptions()
interface.raw = True
interface.score = True
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 84
interface.feature_layer.resolution.y = 84
interface.feature_layer.minimap_resolution.x = 64
interface.feature_layer.minimap_resolution.y = 64
map_inst = maps.get("Simple64")
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=map_inst.path, map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Terran, options=interface)
controller.create_game(create)
controller.join_game(join)
for _ in range(5):
controller.step(16)
controller.observe()
log_center("success: %s", game_version)
except: # pylint: disable=bare-except
logging.exception("Failed")
log_center("failure: %s", game_version)
failures.append(game_version)
self.assertEmpty(failures)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/tests/obs_spec_test.py | pysc2/tests/obs_spec_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Verify that the observations match the observation spec."""
from absl.testing import absltest
from pysc2.agents import random_agent
from pysc2.env import sc2_env
from pysc2.tests import utils
class TestObservationSpec(utils.TestCase):
def test_observation_matches_obs_spec(self):
with sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.random),
sc2_env.Bot(sc2_env.Race.random, sc2_env.Difficulty.easy)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=(84, 87),
minimap=(64, 67)))) as env:
multiplayer_obs_spec = env.observation_spec()
self.assertIsInstance(multiplayer_obs_spec, tuple)
self.assertLen(multiplayer_obs_spec, 1)
obs_spec = multiplayer_obs_spec[0]
multiplayer_action_spec = env.action_spec()
self.assertIsInstance(multiplayer_action_spec, tuple)
self.assertLen(multiplayer_action_spec, 1)
action_spec = multiplayer_action_spec[0]
agent = random_agent.RandomAgent()
agent.setup(obs_spec, action_spec)
multiplayer_obs = env.reset()
agent.reset()
for _ in range(100):
self.assertIsInstance(multiplayer_obs, tuple)
self.assertLen(multiplayer_obs, 1)
raw_obs = multiplayer_obs[0]
obs = raw_obs.observation
self.check_observation_matches_spec(obs, obs_spec)
act = agent.step(raw_obs)
multiplayer_act = (act,)
multiplayer_obs = env.step(multiplayer_act)
def test_heterogeneous_observations(self):
with sc2_env.SC2Env(
map_name="Simple64",
players=[
sc2_env.Agent(sc2_env.Race.random),
sc2_env.Agent(sc2_env.Race.random)
],
agent_interface_format=[
sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=(84, 87),
minimap=(64, 67)
)
),
sc2_env.AgentInterfaceFormat(
rgb_dimensions=sc2_env.Dimensions(
screen=128,
minimap=64
)
)
]) as env:
obs_specs = env.observation_spec()
self.assertIsInstance(obs_specs, tuple)
self.assertLen(obs_specs, 2)
actions_specs = env.action_spec()
self.assertIsInstance(actions_specs, tuple)
self.assertLen(actions_specs, 2)
agents = []
for obs_spec, action_spec in zip(obs_specs, actions_specs):
agent = random_agent.RandomAgent()
agent.setup(obs_spec, action_spec)
agent.reset()
agents.append(agent)
time_steps = env.reset()
for _ in range(100):
self.assertIsInstance(time_steps, tuple)
self.assertLen(time_steps, 2)
actions = []
for i, agent in enumerate(agents):
time_step = time_steps[i]
obs = time_step.observation
self.check_observation_matches_spec(obs, obs_specs[i])
actions.append(agent.step(time_step))
time_steps = env.step(actions)
def check_observation_matches_spec(self, obs, obs_spec):
self.assertCountEqual(obs_spec.keys(), obs.keys())
for k, o in obs.items():
if k == "map_name":
self.assertIsInstance(o, str)
continue
descr = "%s: spec: %s != obs: %s" % (k, obs_spec[k], o.shape)
if o.shape == (0,): # Empty tensor can't have a shape.
self.assertIn(0, obs_spec[k], descr)
else:
self.assertEqual(len(obs_spec[k]), len(o.shape), descr)
for a, b in zip(obs_spec[k], o.shape):
if a != 0:
self.assertEqual(a, b, descr)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/tests/dummy_observation_test.py | pysc2/tests/dummy_observation_test.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import units
from pysc2.tests import dummy_observation
from s2clientprotocol import common_pb2
_PROBE = dummy_observation.Unit(
units.Protoss.Probe, features.PlayerRelative.SELF, 20, 20, 0, 0, 1.0)
_ZEALOT = dummy_observation.Unit(
units.Protoss.Zealot, features.PlayerRelative.SELF, 100, 50, 0, 0, 1.0)
_MOTHERSHIP = dummy_observation.Unit(
units.Protoss.Mothership, features.PlayerRelative.SELF, 350, 7, 200, 0, 1.0)
class DummyObservationTest(parameterized.TestCase):
def setUp(self):
super(DummyObservationTest, self).setUp()
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)
def testFeatureScreenMatchesSpec(self):
obs = self._get_obs()
for f in features.SCREEN_FEATURES:
self._check_layer(
getattr(obs.feature_layer_data.renders, f.name), 64, 60, 8)
def testFeatureMinimapMatchesSpec(self):
obs = self._get_obs()
for f in features.MINIMAP_FEATURES:
self._check_layer(
getattr(obs.feature_layer_data.minimap_renders, f.name), 32, 28, 8)
def testRgbScreenMatchesSpec(self):
obs = self._get_obs()
self._check_layer(obs.render_data.map, 128, 124, 24)
def testGameLoopCanBeSet(self):
self._builder.game_loop(1234)
obs = self._get_obs()
self.assertEqual(obs.game_loop, 1234)
def testPlayerCommonCanBeSet(self):
self._builder.player_common(
minerals=1000,
vespene=200,
food_cap=200,
food_used=198,
food_army=140,
food_workers=58,
army_count=92,
warp_gate_count=7,
larva_count=15)
obs = self._get_obs()
self.assertEqual(obs.player_common.player_id, 1) # (we didn't set it)
self.assertEqual(obs.player_common.minerals, 1000)
self.assertEqual(obs.player_common.vespene, 200)
self.assertEqual(obs.player_common.food_cap, 200)
self.assertEqual(obs.player_common.food_used, 198)
self.assertEqual(obs.player_common.food_army, 140)
self.assertEqual(obs.player_common.food_workers, 58)
self.assertEqual(obs.player_common.idle_worker_count, 2) # (didn't set it)
self.assertEqual(obs.player_common.army_count, 92)
self.assertEqual(obs.player_common.warp_gate_count, 7)
self.assertEqual(obs.player_common.larva_count, 15)
def testScoreCanBeSet(self):
self._builder.score(54321)
obs = self._get_obs()
self.assertEqual(obs.score.score, 54321)
def testScoreDetailsCanBeSet(self):
self._builder.score_details(
idle_production_time=1,
idle_worker_time=2,
total_value_units=3,
killed_value_units=5,
killed_value_structures=6,
collected_minerals=7,
collected_vespene=8,
collection_rate_minerals=9,
collection_rate_vespene=10,
spent_minerals=11,
spent_vespene=12,
)
obs = self._get_obs()
self.assertEqual(obs.score.score_details.idle_production_time, 1)
self.assertEqual(obs.score.score_details.idle_worker_time, 2)
self.assertEqual(obs.score.score_details.total_value_units, 3)
self.assertEqual(obs.score.score_details.total_value_structures, 230)
self.assertEqual(obs.score.score_details.killed_value_units, 5)
self.assertEqual(obs.score.score_details.killed_value_structures, 6)
self.assertEqual(obs.score.score_details.collected_minerals, 7)
self.assertEqual(obs.score.score_details.collected_vespene, 8)
self.assertEqual(obs.score.score_details.collection_rate_minerals, 9)
self.assertEqual(obs.score.score_details.collection_rate_vespene, 10)
self.assertEqual(obs.score.score_details.spent_minerals, 11)
self.assertEqual(obs.score.score_details.spent_vespene, 12)
def testScoreByCategorySpec(self):
# Note that if these dimensions are changed, client code is liable to break.
np.testing.assert_array_equal(
self._obs_spec.score_by_category,
np.array([11, 5], dtype=np.int32))
@parameterized.parameters([entry.name for entry in features.ScoreByCategory])
def testScoreByCategory(self, entry_name):
self._builder.score_by_category(
entry_name,
none=10,
army=1200,
economy=400,
technology=100,
upgrade=200)
response_observation = self._builder.build()
obs = response_observation.observation
entry = getattr(obs.score.score_details, entry_name)
self.assertEqual(entry.none, 10)
self.assertEqual(entry.army, 1200)
self.assertEqual(entry.economy, 400)
self.assertEqual(entry.technology, 100)
self.assertEqual(entry.upgrade, 200)
# Check the transform_obs does what we expect, too.
transformed_obs = self._features.transform_obs(response_observation)
transformed_entry = getattr(transformed_obs.score_by_category, entry_name)
self.assertEqual(transformed_entry.none, 10)
self.assertEqual(transformed_entry.army, 1200)
self.assertEqual(transformed_entry.economy, 400)
self.assertEqual(transformed_entry.technology, 100)
self.assertEqual(transformed_entry.upgrade, 200)
def testScoreByVitalSpec(self):
# Note that if these dimensions are changed, client code is liable to break.
np.testing.assert_array_equal(
self._obs_spec.score_by_vital,
np.array([3, 3], dtype=np.int32))
@parameterized.parameters([entry.name for entry in features.ScoreByVital])
def testScoreByVital(self, entry_name):
self._builder.score_by_vital(
entry_name,
life=1234,
shields=45,
energy=423)
response_observation = self._builder.build()
obs = response_observation.observation
entry = getattr(obs.score.score_details, entry_name)
self.assertEqual(entry.life, 1234)
self.assertEqual(entry.shields, 45)
self.assertEqual(entry.energy, 423)
# Check the transform_obs does what we expect, too.
transformed_obs = self._features.transform_obs(response_observation)
transformed_entry = getattr(transformed_obs.score_by_vital, entry_name)
self.assertEqual(transformed_entry.life, 1234)
self.assertEqual(transformed_entry.shields, 45)
self.assertEqual(transformed_entry.energy, 423)
def testRgbMinimapMatchesSpec(self):
obs = self._get_obs()
self._check_layer(obs.render_data.minimap, 64, 60, 24)
def testNoSingleSelect(self):
obs = self._get_obs()
self.assertFalse(obs.ui_data.HasField("single"))
def testWithSingleSelect(self):
self._builder.single_select(_PROBE)
obs = self._get_obs()
self._check_unit(obs.ui_data.single.unit, _PROBE)
def testNoMultiSelect(self):
obs = self._get_obs()
self.assertFalse(obs.ui_data.HasField("multi"))
def testWithMultiSelect(self):
nits = [_MOTHERSHIP, _PROBE, _PROBE, _ZEALOT]
self._builder.multi_select(nits)
obs = self._get_obs()
self.assertLen(obs.ui_data.multi.units, 4)
for proto, builder in zip(obs.ui_data.multi.units, nits):
self._check_unit(proto, builder)
def testBuildQueue(self):
nits = [_MOTHERSHIP, _PROBE]
production = [
{"ability_id": actions.FUNCTIONS.Train_Mothership_quick.ability_id,
"build_progress": 0.5},
{"ability_id": actions.FUNCTIONS.Train_Probe_quick.ability_id,
"build_progress": 0},
{"ability_id": actions.FUNCTIONS.Research_ShadowStrike_quick.ability_id,
"build_progress": 0},
]
self._builder.build_queue(nits, production)
obs = self._get_obs()
self.assertLen(obs.ui_data.production.build_queue, 2)
for proto, builder in zip(obs.ui_data.production.build_queue, nits):
self._check_unit(proto, builder)
self.assertLen(obs.ui_data.production.production_queue, 3)
for proto, p in zip(obs.ui_data.production.production_queue, production):
self.assertEqual(proto.ability_id, p["ability_id"])
self.assertEqual(proto.build_progress, p["build_progress"])
def testFeatureUnitsAreAdded(self):
feature_units = [
dummy_observation.FeatureUnit(
units.Protoss.Probe,
features.PlayerRelative.SELF,
owner=1,
pos=common_pb2.Point(x=10, y=10, z=0),
radius=1.0,
health=10,
health_max=20,
is_on_screen=True,
shield=0,
shield_max=20
),
dummy_observation.FeatureUnit(
units.Terran.Marine,
features.PlayerRelative.SELF,
owner=1,
pos=common_pb2.Point(x=11, y=12, z=0),
radius=1.0,
health=35,
health_max=45,
is_on_screen=True,
shield=0,
shield_max=0
)
]
self._builder.feature_units(feature_units)
obs = self._get_obs()
for proto, builder in zip(obs.raw_data.units, feature_units):
self._check_feature_unit(proto, builder)
def _get_obs(self):
return self._builder.build().observation
def _check_layer(self, layer, x, y, bits):
self.assertEqual(layer.size.x, x)
self.assertEqual(layer.size.y, y)
self.assertEqual(layer.bits_per_pixel, bits)
def _check_attributes_match(self, a, b, attributes):
for attribute in attributes:
self.assertEqual(getattr(a, attribute), getattr(b, attribute))
def _check_unit(self, proto, builder):
return self._check_attributes_match(proto, builder, vars(builder).keys())
def _check_feature_unit(self, proto, builder):
return self._check_attributes_match(proto, builder, [
"unit_type",
"alliance",
"owner",
"pos",
"radius",
"health",
"health_max",
"is_on_screen",
"shield",
"shield_max"
])
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/tests/replay_obs_test.py | pysc2/tests/replay_obs_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that a game and replay have equivalent observations and actions.
Here we verify that the observations processed by replays match the original
observations of the gameplay.
"""
from absl.testing import absltest
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import renderer_ascii
from pysc2.lib import units
from pysc2.tests import utils
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
_EMPTY = 0
def identity_function(name, args):
return lambda _: actions.FUNCTIONS[name](*args)
def any_point(unit_type, obs):
unit_layer = obs.feature_screen.unit_type
y, x = (unit_layer == unit_type).nonzero()
if not y.any():
return None, None
return [x[-1], y[-1]]
def avg_point(unit_type, obs):
unit_layer = obs.feature_screen.unit_type
y, x = (unit_layer == unit_type).nonzero()
if not y.any():
return None, None
return [int(x.mean()), int(y.mean())]
def select(func, unit_type):
return lambda o: actions.FUNCTIONS.select_point('select', func(unit_type, o))
class Config(object):
"""Holds the configuration options."""
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: identity_function('select_army', ['select']),
}
self.num_observations = max(self.actions.keys()) + 2
self.player_id = 1
class GameController(object):
"""Wrapper class for interacting with the game in play/replay mode."""
def __init__(self, config):
"""Constructs the game controller object.
Args:
config: Interface configuration options.
"""
self._config = config
self._sc2_proc = None
self._controller = None
self._initialize()
def _initialize(self):
"""Initialize play/replay connection."""
run_config = run_configs.get()
self._map_inst = maps.get(self._config.map_name)
self._map_data = self._map_inst.data(run_config)
self._sc2_proc = run_config.start(
want_rgb=self._config.interface.HasField('render'))
self._controller = self._sc2_proc.controller
def start_replay(self, replay_data):
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
map_data=self._map_data,
options=self._config.interface,
disable_fog=False,
observed_player_id=self._config.player_id)
self._controller.start_replay(start_replay)
def create_game(self):
create = sc_pb.RequestCreateGame(
random_seed=self._config.random_seed,
local_map=sc_pb.LocalMap(
map_path=self._map_inst.path, map_data=self._map_data))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(
type=sc_pb.Computer,
race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(
race=sc_common.Terran,
options=self._config.interface)
self._controller.create_game(create)
self._controller.join_game(join)
@property
def controller(self):
return self._controller
def close(self):
"""Close the controller connection."""
if self._controller:
self._controller.quit()
self._controller = None
if self._sc2_proc:
self._sc2_proc.close()
self._sc2_proc = None
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
self.close()
class ReplayObsTest(utils.TestCase):
def _get_replay_data(self, controller, config):
"""Runs a replay to get the replay data."""
f = features.features_from_game_info(game_info=controller.game_info())
observations = {}
last_actions = []
for _ in range(config.num_observations):
raw_obs = controller.observe()
o = raw_obs.observation
obs = f.transform_obs(raw_obs)
if raw_obs.action_errors:
print('action errors:', raw_obs.action_errors)
if o.game_loop == 2:
# Center camera is initiated automatically by the game and reported
# at frame 2.
last_actions = [actions.FUNCTIONS.move_camera.id]
self.assertEqual(last_actions, list(obs.last_actions))
unit_type = obs.feature_screen.unit_type
observations[o.game_loop] = unit_type
if o.game_loop in config.actions:
func = config.actions[o.game_loop](obs)
print(renderer_ascii.screen(obs))
scv_y, scv_x = (units.Terran.SCV == unit_type).nonzero()
print('scv locations: ', sorted(list(zip(scv_x, scv_y))))
print('available actions: ', list(sorted(obs.available_actions)))
print('Making action: %s' % (func,))
# Ensure action is available.
# If a build action is available, we have managed to target an SCV.
self.assertIn(func.function, obs.available_actions)
if (func.function in
(actions.FUNCTIONS.Build_SupplyDepot_screen.id,
actions.FUNCTIONS.Build_Barracks_screen.id)):
# Ensure we can build on that position.
x, y = func.arguments[1]
self.assertEqual(_EMPTY, unit_type[y, x])
action = f.transform_action(o, func)
last_actions = [func.function]
controller.act(action)
else:
last_actions = []
controller.step()
replay_data = controller.save_replay()
return replay_data, observations
def _process_replay(self, controller, observations, config):
f = features.features_from_game_info(game_info=controller.game_info())
while True:
o = controller.observe()
obs = f.transform_obs(o)
if o.player_result: # end of game
break
unit_type = obs.feature_screen.unit_type
self.assertEqual(
tuple(observations[o.observation.game_loop].flatten()),
tuple(unit_type.flatten()))
self.assertIn(len(o.actions), (0, 1), 'Expected 0 or 1 action')
if o.actions:
func = f.reverse_action(o.actions[0])
# Action is reported one frame later.
executed = config.actions.get(o.observation.game_loop - 1, None)
executed_func = executed(obs) if executed else None
print('%4d Sent: %s' % (o.observation.game_loop, executed_func))
print('%4d Returned: %s' % (o.observation.game_loop, func))
if o.observation.game_loop == 2:
# Center camera is initiated automatically by the game and reported
# at frame 2.
self.assertEqual(actions.FUNCTIONS.move_camera.id, func.function)
continue
self.assertEqual(func.function, executed_func.function)
if func.function != actions.FUNCTIONS.select_point.id:
# select_point likes to return Toggle instead of Select.
self.assertEqual(func.arguments, executed_func.arguments)
self.assertEqual(func.function, obs.last_actions[0])
controller.step()
return observations
def test_replay_observations_match(self):
config = Config()
with GameController(config) as game_controller:
game_controller.create_game()
replay_data, observations = self._get_replay_data(
game_controller.controller, config)
game_controller.start_replay(replay_data)
self._process_replay(game_controller.controller, observations, config)
if __name__ == '__main__':
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/tests/easy_scripted_test.py | pysc2/tests/easy_scripted_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Solve the nm_easy map using a fixed policy by reading the feature layers."""
from absl.testing import absltest
from pysc2.agents import scripted_agent
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.tests import utils
class TestEasy(utils.TestCase):
steps = 200
step_mul = 16
def test_move_to_beacon(self):
with sc2_env.SC2Env(
map_name="MoveToBeacon",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64)),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.MoveToBeacon()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_collect_mineral_shards(self):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64)),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.CollectMineralShards()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_collect_mineral_shards_feature_units(self):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64),
use_feature_units=True),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.CollectMineralShardsFeatureUnits()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_collect_mineral_shards_raw(self):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
action_space=sc2_env.ActionSpace.RAW, # or: use_raw_actions=True,
use_raw_units=True),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.CollectMineralShardsRaw()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_defeat_roaches(self):
with sc2_env.SC2Env(
map_name="DefeatRoaches",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
feature_dimensions=sc2_env.Dimensions(
screen=84,
minimap=64)),
step_mul=self.step_mul,
game_steps_per_episode=self.steps * self.step_mul) as env:
agent = scripted_agent.DefeatRoaches()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
def test_defeat_roaches_raw(self):
with sc2_env.SC2Env(
map_name="DefeatRoaches",
players=[sc2_env.Agent(sc2_env.Race.terran)],
agent_interface_format=sc2_env.AgentInterfaceFormat(
action_space=sc2_env.ActionSpace.RAW, # or: use_raw_actions=True,
use_raw_units=True),
step_mul=self.step_mul,
game_steps_per_episode=100*self.steps * self.step_mul) as env:
agent = scripted_agent.DefeatRoachesRaw()
run_loop.run_loop([agent], env, self.steps)
# Get some points
self.assertLessEqual(agent.episodes, agent.reward)
self.assertEqual(agent.steps, self.steps)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/tests/dummy_observation.py | pysc2/tests/dummy_observation.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""For test code - build a dummy ResponseObservation proto.
This can then e.g. be passed to features.transform_obs.
"""
import math
import numpy as np
from pysc2.lib import features
from s2clientprotocol import raw_pb2
from s2clientprotocol import sc2api_pb2 as sc_pb
from s2clientprotocol import score_pb2
class Unit(object):
"""Class to hold unit data for the builder."""
def __init__(
self,
unit_type, # see lib/units.py
player_relative, # features.PlayerRelative,
health,
shields=0,
energy=0,
transport_slots_taken=0,
build_progress=1.0):
self.unit_type = unit_type
self.player_relative = player_relative
self.health = health
self.shields = shields
self.energy = energy
self.transport_slots_taken = transport_slots_taken
self.build_progress = build_progress
def fill(self, unit_proto):
"""Fill a proto unit data object from this Unit."""
unit_proto.unit_type = self.unit_type
unit_proto.player_relative = self.player_relative
unit_proto.health = self.health
unit_proto.shields = self.shields
unit_proto.energy = self.energy
unit_proto.transport_slots_taken = self.transport_slots_taken
unit_proto.build_progress = self.build_progress
def as_array(self):
"""Return the unit represented as a numpy array."""
return np.array([
self.unit_type,
self.player_relative,
self.health,
self.shields,
self.energy,
self.transport_slots_taken,
int(self.build_progress * 100)
], dtype=np.int32)
def as_dict(self):
return vars(self)
class FeatureUnit(object):
"""Class to hold feature unit data for the builder."""
def __init__(
self,
unit_type, # see lib/units
alliance, # features.PlayerRelative,
owner, # 1-15, 16=neutral
pos, # common_pb2.Point,
radius,
health,
health_max,
is_on_screen,
shield=0,
shield_max=0,
energy=0,
energy_max=0,
cargo_space_taken=0,
cargo_space_max=0,
build_progress=1.0,
facing=0.0,
display_type=raw_pb2.Visible, # raw_pb.DisplayType
cloak=raw_pb2.NotCloaked, # raw_pb.CloakState
is_selected=False,
is_blip=False,
is_powered=True,
mineral_contents=0,
vespene_contents=0,
assigned_harvesters=0,
ideal_harvesters=0,
weapon_cooldown=0.0):
self.unit_type = unit_type
self.alliance = alliance
self.owner = owner
self.pos = pos
self.radius = radius
self.health = health
self.health_max = health_max
self.is_on_screen = is_on_screen
self.shield = shield
self.shield_max = shield_max
self.energy = energy
self.energy_max = energy_max
self.cargo_space_taken = cargo_space_taken
self.cargo_space_max = cargo_space_max
self.build_progress = build_progress
self.facing = facing
self.display_type = display_type
self.cloak = cloak
self.is_selected = is_selected
self.is_blip = is_blip
self.is_powered = is_powered
self.mineral_contents = mineral_contents
self.vespene_contents = vespene_contents
self.assigned_harvesters = assigned_harvesters
self.ideal_harvesters = ideal_harvesters
self.weapon_cooldown = weapon_cooldown
def as_dict(self):
return vars(self)
class Builder(object):
"""For test code - build a dummy ResponseObservation proto."""
def __init__(self, obs_spec):
self._game_loop = 1
self._player_common = sc_pb.PlayerCommon(
player_id=1,
minerals=20,
vespene=50,
food_cap=36,
food_used=21,
food_army=6,
food_workers=15,
idle_worker_count=2,
army_count=6,
warp_gate_count=0,
larva_count=0,
)
self._score = 300
self._score_details = score_pb2.ScoreDetails(
idle_production_time=0,
idle_worker_time=0,
total_value_units=190,
total_value_structures=230,
killed_value_units=0,
killed_value_structures=0,
collected_minerals=2130,
collected_vespene=560,
collection_rate_minerals=50,
collection_rate_vespene=20,
spent_minerals=2000,
spent_vespene=500,
)
self._obs_spec = obs_spec
self._single_select = None
self._multi_select = None
self._build_queue = None
self._production = None
self._feature_units = None
def game_loop(self, game_loop):
self._game_loop = game_loop
return self
# pylint:disable=unused-argument
def player_common(
self,
player_id=None,
minerals=None,
vespene=None,
food_cap=None,
food_used=None,
food_army=None,
food_workers=None,
idle_worker_count=None,
army_count=None,
warp_gate_count=None,
larva_count=None):
"""Update some or all of the fields in the PlayerCommon data."""
args = dict(locals())
for key, value in args.items():
if value is not None and key != 'self':
setattr(self._player_common, key, value)
return self
def score(self, score):
self._score = score
return self
def score_details(
self,
idle_production_time=None,
idle_worker_time=None,
total_value_units=None,
total_value_structures=None,
killed_value_units=None,
killed_value_structures=None,
collected_minerals=None,
collected_vespene=None,
collection_rate_minerals=None,
collection_rate_vespene=None,
spent_minerals=None,
spent_vespene=None):
"""Update some or all of the fields in the ScoreDetails data."""
args = dict(locals())
for key, value in args.items():
if value is not None and key != 'self':
setattr(self._score_details, key, value)
return self
# pylint:enable=unused-argument
def score_by_category(
self, entry_name, none, army, economy, technology, upgrade):
field = getattr(self._score_details, entry_name)
field.CopyFrom(
score_pb2.CategoryScoreDetails(
none=none,
army=army,
economy=economy,
technology=technology,
upgrade=upgrade))
def score_by_vital(self, entry_name, life, shields, energy):
field = getattr(self._score_details, entry_name)
field.CopyFrom(
score_pb2.VitalScoreDetails(
life=life,
shields=shields,
energy=energy))
def single_select(self, unit):
self._single_select = unit
return self
def multi_select(self, units):
self._multi_select = units
return self
def build_queue(self, build_queue, production=None):
self._build_queue = build_queue
self._production = production
return self
def feature_units(self, feature_units):
self._feature_units = feature_units
return self
def build(self):
"""Builds and returns a proto ResponseObservation."""
response_observation = sc_pb.ResponseObservation()
obs = response_observation.observation
obs.game_loop = self._game_loop
obs.player_common.CopyFrom(self._player_common)
obs.abilities.add(ability_id=1, requires_point=True) # Smart
obs.score.score = self._score
obs.score.score_details.CopyFrom(self._score_details)
def fill(image_data, size, bits):
image_data.bits_per_pixel = bits
image_data.size.y = size[0]
image_data.size.x = size[1]
image_data.data = b'\0' * int(math.ceil(size[0] * size[1] * bits / 8))
if 'feature_screen' in self._obs_spec:
for feature in features.SCREEN_FEATURES:
fill(getattr(obs.feature_layer_data.renders, feature.name),
self._obs_spec['feature_screen'][1:], 8)
if 'feature_minimap' in self._obs_spec:
for feature in features.MINIMAP_FEATURES:
fill(getattr(obs.feature_layer_data.minimap_renders, feature.name),
self._obs_spec['feature_minimap'][1:], 8)
if 'rgb_screen' in self._obs_spec:
fill(obs.render_data.map, self._obs_spec['rgb_screen'][:2], 24)
if 'rgb_minimap' in self._obs_spec:
fill(obs.render_data.minimap, self._obs_spec['rgb_minimap'][:2], 24)
if self._single_select:
self._single_select.fill(obs.ui_data.single.unit)
if self._multi_select:
for unit in self._multi_select:
obs.ui_data.multi.units.add(**unit.as_dict())
if self._build_queue:
for unit in self._build_queue:
obs.ui_data.production.build_queue.add(**unit.as_dict())
if self._production:
for item in self._production:
obs.ui_data.production.production_queue.add(**item)
if self._feature_units:
for tag, feature_unit in enumerate(self._feature_units, 1):
args = dict(tag=tag)
args.update(feature_unit.as_dict())
obs.raw_data.units.add(**args)
return response_observation
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/run_configs/lib.py | pysc2/run_configs/lib.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Configs for various ways to run starcraft."""
import collections
import datetime
import os
from pysc2.lib import gfile
class Version(collections.namedtuple("Version", [
"game_version", "build_version", "data_version", "binary"])):
"""Represents a single version of the game."""
__slots__ = ()
def version_dict(versions):
return {ver.game_version: ver for ver in versions}
# https://github.com/Blizzard/s2client-proto/blob/master/buildinfo/versions.json
# Generate with bin/gen_versions.py or bin/replay_version.py.
VERSIONS = version_dict([
Version("3.13.0", 52910, "8D9FEF2E1CF7C6C9CBE4FBCA830DDE1C", None),
Version("3.14.0", 53644, "CA275C4D6E213ED30F80BACCDFEDB1F5", None),
Version("3.15.0", 54518, "BBF619CCDCC80905350F34C2AF0AB4F6", None),
Version("3.15.1", 54518, "6EB25E687F8637457538F4B005950A5E", None),
Version("3.16.0", 55505, "60718A7CA50D0DF42987A30CF87BCB80", None),
Version("3.16.1", 55958, "5BD7C31B44525DAB46E64C4602A81DC2", None),
Version("3.17.0", 56787, "DFD1F6607F2CF19CB4E1C996B2563D9B", None),
Version("3.17.1", 56787, "3F2FCED08798D83B873B5543BEFA6C4B", None),
Version("3.17.2", 56787, "C690FC543082D35EA0AAA876B8362BEA", None),
Version("3.18.0", 57507, "1659EF34997DA3470FF84A14431E3A86", None),
Version("3.19.0", 58400, "2B06AEE58017A7DF2A3D452D733F1019", None),
Version("3.19.1", 58400, "D9B568472880CC4719D1B698C0D86984", None),
Version("4.0.0", 59587, "9B4FD995C61664831192B7DA46F8C1A1", None),
Version("4.0.2", 59587, "B43D9EE00A363DAFAD46914E3E4AF362", None),
Version("4.1.0", 60196, "1B8ACAB0C663D5510941A9871B3E9FBE", None),
Version("4.1.1", 60321, "5C021D8A549F4A776EE9E9C1748FFBBC", None),
Version("4.1.2", 60321, "33D9FE28909573253B7FC352CE7AEA40", None),
Version("4.1.3", 60321, "F486693E00B2CD305B39E0AB254623EB", None),
Version("4.1.4", 60321, "2E2A3F6E0BAFE5AC659C4D39F13A938C", None),
Version("4.2.0", 62347, "C0C0E9D37FCDBC437CE386C6BE2D1F93", None),
Version("4.2.1", 62848, "29BBAC5AFF364B6101B661DB468E3A37", None),
Version("4.2.2", 63454, "3CB54C86777E78557C984AB1CF3494A0", None),
Version("4.2.3", 63454, "5E3A8B21E41B987E05EE4917AAD68C69", None),
Version("4.2.4", 63454, "7C51BC7B0841EACD3535E6FA6FF2116B", None),
Version("4.3.0", 64469, "C92B3E9683D5A59E08FC011F4BE167FF", None),
Version("4.3.1", 65094, "E5A21037AA7A25C03AC441515F4E0644", None),
Version("4.3.2", 65384, "B6D73C85DFB70F5D01DEABB2517BF11C", None),
Version("4.4.0", 65895, "BF41339C22AE2EDEBEEADC8C75028F7D", None),
Version("4.4.1", 66668, "C094081D274A39219061182DBFD7840F", None),
Version("4.5.0", 67188, "2ACF84A7ECBB536F51FC3F734EC3019F", None),
Version("4.5.1", 67188, "6D239173B8712461E6A7C644A5539369", None),
Version("4.6.0", 67926, "7DE59231CBF06F1ECE9A25A27964D4AE", None),
Version("4.6.1", 67926, "BEA99B4A8E7B41E62ADC06D194801BAB", None),
Version("4.6.2", 69232, "B3E14058F1083913B80C20993AC965DB", None),
Version("4.7.0", 70154, "8E216E34BC61ABDE16A59A672ACB0F3B", None),
Version("4.7.1", 70154, "94596A85191583AD2EBFAE28C5D532DB", None),
Version("4.8.0", 71061, "760581629FC458A1937A05ED8388725B", None),
Version("4.8.1", 71523, "FCAF3F050B7C0CC7ADCF551B61B9B91E", None),
Version("4.8.2", 71663, "FE90C92716FC6F8F04B74268EC369FA5", None),
Version("4.8.3", 72282, "0F14399BBD0BA528355FF4A8211F845B", None),
Version("4.8.4", 73286, "CD040C0675FD986ED37A4CA3C88C8EB5", None),
Version("4.8.5", 73559, "B2465E73AED597C74D0844112D582595", None),
Version("4.8.6", 73620, "AA18FEAD6573C79EF707DF44ABF1BE61", None),
Version("4.9.0", 74071, "70C74A2DCA8A0D8E7AE8647CAC68ACCA", None),
Version("4.9.1", 74456, "218CB2271D4E2FA083470D30B1A05F02", None),
Version("4.9.2", 74741, "614480EF79264B5BD084E57F912172FF", None),
Version("4.9.3", 75025, "C305368C63621480462F8F516FB64374", None),
Version("4.10.0", 75689, "B89B5D6FA7CBF6452E721311BFBC6CB2", None),
Version("4.10.1", 75800, "DDFFF9EC4A171459A4F371C6CC189554", None),
Version("4.10.2", 76052, "D0F1A68AA88BA90369A84CD1439AA1C3", None),
Version("4.10.3", 76114, "CDB276D311F707C29BA664B7754A7293", None),
Version("4.10.4", 76811, "FF9FA4EACEC5F06DEB27BD297D73ED67", None),
Version("4.11.0", 77379, "70E774E722A58287EF37D487605CD384", None),
Version("4.11.1", 77379, "F92D1127A291722120AC816F09B2E583", None),
Version("4.11.2", 77535, "FC43E0897FCC93E4632AC57CBC5A2137", None),
Version("4.11.3", 77661, "A15B8E4247434B020086354F39856C51", None),
Version("4.11.4", 78285, "69493AFAB5C7B45DDB2F3442FD60F0CF", None),
Version("4.12.0", 79998, "B47567DEE5DC23373BFF57194538DFD3", None),
Version("4.12.1", 80188, "44DED5AED024D23177C742FC227C615A", None),
Version("5.0.0", 80949, "9AE39C332883B8BF6AA190286183ED72", None),
Version("5.0.1", 81009, "0D28678BC32E7F67A238F19CD3E0A2CE", None),
Version("5.0.2", 81102, "DC0A1182FB4ABBE8E29E3EC13CF46F68", None),
Version("5.0.3", 81433, "5FD8D4B6B52723B44862DF29F232CF31", None),
Version("5.0.4", 82457, "D2707E265785612D12B381AF6ED9DBF4", None),
Version("5.0.5", 82893, "D795328C01B8A711947CC62AA9750445", None),
Version("5.0.6", 83830, "B4745D6A4F982A3143C183D8ACB6C3E3", None),
Version("5.0.7", 84643, "A389D1F7DF9DD792FBE980533B7119FF", None),
Version("5.0.8", 86383, "22EAC562CD0C6A31FB2C2C21E3AA3680", None),
Version("5.0.9", 87702, "F799E093428D419FD634CCE9B925218C", None),
])
class RunConfig(object):
"""Base class for different run configs."""
def __init__(self, replay_dir, data_dir, tmp_dir, version,
cwd=None, env=None):
"""Initialize the runconfig with the various directories needed.
Args:
replay_dir: Where to find replays. Might not be accessible to SC2.
data_dir: Where SC2 should find the data and battle.net cache.
tmp_dir: The temporary directory. None is system default.
version: The game version to run, a string.
cwd: Where to set the current working directory.
env: What to pass as the environment variables.
"""
self.replay_dir = replay_dir
self.data_dir = data_dir
self.tmp_dir = tmp_dir
self.cwd = cwd
self.env = env
self.version = self._get_version(version)
def map_data(self, map_name, players=None):
"""Return the map data for a map by name or path."""
map_names = [map_name]
if players:
map_names.append(os.path.join(
os.path.dirname(map_name),
"(%s)%s" % (players, os.path.basename(map_name))))
for name in map_names:
path = os.path.join(self.data_dir, "Maps", name)
if gfile.Exists(path):
with gfile.Open(path, "rb") as f:
return f.read()
raise ValueError(f"Map {map_name} not found in {self.data_dir}/Maps.")
def abs_replay_path(self, replay_path):
"""Return the absolute path to the replay, outside the sandbox."""
return os.path.join(self.replay_dir, replay_path)
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()
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(".sc2replay"):
yield os.path.join(replay_dir, f)
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
def start(self, version=None, **kwargs):
"""Launch the game. Find the version and run sc_process.StarcraftProcess."""
raise NotImplementedError()
@classmethod
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
@classmethod
def name(cls):
return cls.__name__
@classmethod
def priority(cls):
"""None means this isn't valid. Run the one with the max priority."""
return None
def get_versions(self, containing=None):
"""Return a dict of all versions that can be run."""
if containing is not None and containing not in VERSIONS:
raise ValueError("Unknown game version: %s. Known versions: %s." % (
containing, sorted(VERSIONS.keys())))
return VERSIONS
def _get_version(self, game_version):
"""Get the full details for the specified game version."""
if isinstance(game_version, Version):
if not game_version.game_version:
raise ValueError(
"Version '%r' supplied without a game version." % (game_version,))
if (game_version.data_version and
game_version.binary and
game_version.build_version):
return game_version
# Some fields might be missing from serialized versions. Look them up.
game_version = game_version.game_version
if game_version.count(".") == 1:
game_version += ".0"
versions = self.get_versions(containing=game_version)
return versions[game_version]
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/run_configs/platforms.py | pysc2/run_configs/platforms.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Configs for how to run SC2 from a normal install on various platforms."""
import copy
import os
import platform
import subprocess
import sys
from absl import flags
from absl import logging
from pysc2.lib import sc_process
from pysc2.run_configs import lib
flags.DEFINE_enum("sc2_version", None, sorted(lib.VERSIONS.keys()),
"Which version of the game to use.")
flags.DEFINE_bool("sc2_dev_build", False,
"Use a dev build. Mostly useful for testing by Blizzard.")
FLAGS = flags.FLAGS
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() 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
class LocalBase(lib.RunConfig):
"""Base run config for public installs."""
def __init__(self, base_dir, exec_name, version, cwd=None, env=None):
base_dir = os.path.expanduser(base_dir)
version = version or FLAGS.sc2_version or "latest"
cwd = cwd and os.path.join(base_dir, cwd)
super(LocalBase, self).__init__(
replay_dir=os.path.join(base_dir, "Replays"),
data_dir=base_dir, tmp_dir=None, version=version, cwd=cwd, env=env)
if FLAGS.sc2_dev_build:
self.version = self.version._replace(build_version=0)
elif self.version.build_version < lib.VERSIONS["3.16.1"].build_version:
raise sc_process.SC2LaunchError(
"SC2 Binaries older than 3.16.1 don't support the api.")
self._exec_name = exec_name
def start(self, 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-detection works. If "
"auto-detection failed repeatedly, then set the SC2PATH environment "
"variable with the correct location." % self.data_dir)
exec_path = os.path.join(
self.data_dir, "Versions/Base%05d" % self.version.build_version,
self._exec_name)
if not os.path.exists(exec_path):
raise sc_process.SC2LaunchError("No SC2 binary found at: %s" % exec_path)
return sc_process.StarcraftProcess(
self, exec_path=exec_path, version=self.version, **kwargs)
def get_versions(self, containing=None):
versions_dir = os.path.join(self.data_dir, "Versions")
version_prefix = "Base"
versions_found = sorted(int(v[len(version_prefix):])
for v in os.listdir(versions_dir)
if v.startswith(version_prefix))
if not versions_found:
raise sc_process.SC2LaunchError(
"No SC2 Versions found in %s" % versions_dir)
known_versions = [v for v in lib.VERSIONS.values()
if v.build_version in versions_found]
# Add one more with the max version. That one doesn't need a data version
# since SC2 will find it in the .build.info file. This allows running
# versions newer than what are known by pysc2, and so is the default.
known_versions.append(
lib.Version("latest", max(versions_found), None, None))
ret = lib.version_dict(known_versions)
if containing is not None and containing not in ret:
raise ValueError("Unknown game version: %s. Known versions: %s." % (
containing, sorted(ret.keys())))
return ret
class Windows(LocalBase):
"""Run on Windows."""
def __init__(self, version=None):
exec_path = (os.environ.get("SC2PATH") or
_read_execute_info(os.path.expanduser("~/Documents"), 3) or
"C:/Program Files (x86)/StarCraft II")
super(Windows, self).__init__(exec_path, "SC2_x64.exe",
version=version, cwd="Support64")
@classmethod
def priority(cls):
if platform.system() == "Windows":
return 1
class Cygwin(LocalBase):
"""Run on Cygwin. This runs the windows binary within a cygwin terminal."""
def __init__(self, version=None):
exec_path = os.environ.get(
"SC2PATH", "/cygdrive/c/Program Files (x86)/StarCraft II")
super(Cygwin, self).__init__(exec_path, "SC2_x64.exe",
version=version, cwd="Support64")
@classmethod
def priority(cls):
if sys.platform == "cygwin":
return 1
class MacOS(LocalBase):
"""Run on MacOS."""
def __init__(self, version=None):
exec_path = (os.environ.get("SC2PATH") or
_read_execute_info(os.path.expanduser(
"~/Library/Application Support/Blizzard"), 6) or
"/Applications/StarCraft II")
super(MacOS, self).__init__(exec_path, "SC2.app/Contents/MacOS/SC2",
version=version)
@classmethod
def priority(cls):
if platform.system() == "Darwin":
return 1
class Linux(LocalBase):
"""Config to run on Linux."""
known_gl_libs = [ # In priority order. Prefer hardware rendering.
("-eglpath", "libEGL.so"),
("-eglpath", "libEGL.so.1"),
("-osmesapath", "libOSMesa.so"),
("-osmesapath", "libOSMesa.so.8"), # Ubuntu 16.04
("-osmesapath", "libOSMesa.so.6"), # Ubuntu 14.04
]
def __init__(self, version=None):
base_dir = os.environ.get("SC2PATH", "~/StarCraftII")
base_dir = os.path.expanduser(base_dir)
env = copy.deepcopy(os.environ)
env["LD_LIBRARY_PATH"] = ":".join(filter(None, [
os.environ.get("LD_LIBRARY_PATH"),
os.path.join(base_dir, "Libs/")]))
super(Linux, self).__init__(base_dir, "SC2_x64", version=version, env=env)
@classmethod
def priority(cls):
if platform.system() == "Linux":
return 1
def start(self, want_rgb=True, **kwargs):
extra_args = kwargs.pop("extra_args", [])
if want_rgb:
# Figure out whether the various GL libraries exist since SC2 sometimes
# fails if you ask to use a library that doesn't exist.
libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
libs = {lib.strip().split()[0] for lib in libs.split("\n") if lib}
for arg, lib_name in self.known_gl_libs:
if lib_name in libs:
extra_args += [arg, lib_name]
break
else:
extra_args += ["-headlessNoRender"]
logging.info(
"No GL library found, so RGB rendering will be disabled. "
"For software rendering install libosmesa.")
return super(Linux, self).start(
want_rgb=want_rgb, extra_args=extra_args, **kwargs)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/run_configs/__init__.py | pysc2/run_configs/__init__.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Configs for various ways to run starcraft."""
from absl import flags
from pysc2.lib import sc_process
from pysc2.run_configs import platforms
from pysc2.run_configs import lib
flags.DEFINE_string("sc2_run_config", None,
"Which run_config to use to spawn the binary.")
FLAGS = flags.FLAGS
def get(version=None):
"""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())(version=version)
try:
return configs[FLAGS.sc2_run_config](version=version)
except KeyError:
raise sc_process.SC2LaunchError(
"Invalid run_config. Valid configs are: %s" % (
", ".join(sorted(configs.keys()))))
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/check_apm.py | pysc2/bin/check_apm.py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test the apm values of various actions."""
import random
from absl import app
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import units
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import error_pb2 as sc_error
from s2clientprotocol import sc2api_pb2 as sc_pb
def get_units(obs, filter_fn=None, owner=None, unit_type=None, tag=None):
"""Return a dict of units that match the filter."""
if unit_type and not isinstance(unit_type, (list, tuple)):
unit_type = (unit_type,)
return {u.tag: u for u in obs.observation.raw_data.units # pylint: disable=g-complex-comprehension
if ((filter_fn is None or filter_fn(u)) and
(owner is None or u.owner == owner) and
(unit_type is None or u.unit_type in unit_type) and
(tag is None or u.tag == tag))}
def get_unit(*args, **kwargs):
"""Return the first unit that matches, or None."""
try:
return next(iter(get_units(*args, **kwargs).values()))
except StopIteration:
return None
def _xy_locs(mask):
"""Mask should be a set of bools from comparison with a feature layer."""
ys, xs = mask.nonzero()
return [point.Point(x, y) for x, y in zip(xs, ys)]
class Env(object):
"""Test the apm values of various actions."""
def __init__(self):
run_config = run_configs.get()
map_inst = maps.get("Flat64")
self._map_path = map_inst.path
self._map_data = map_inst.data(run_config)
self._sc2_proc = run_config.start(want_rgb=False)
self._controller = self._sc2_proc.controller
self._summary = []
self._features = None
def close(self):
self._controller.quit()
self._sc2_proc.close()
print(" apm name")
for name, info in self._summary:
print("%4d %s" % (info.player_info[0].player_apm, name))
def __enter__(self):
return self
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback):
self.close()
def __del__(self):
self.close()
def step(self, count=22):
self._controller.step(count)
return self._controller.observe()
def fl_obs(self, obs):
return self._features.transform_obs(obs)
def raw_unit_command(self, ability_id, unit_tags, pos=None, target=None):
"""Send a raw unit command."""
if isinstance(ability_id, str):
ability_id = actions.FUNCTIONS[ability_id].ability_id
action = sc_pb.Action()
cmd = action.action_raw.unit_command
cmd.ability_id = ability_id
if isinstance(unit_tags, (list, tuple)):
cmd.unit_tags.extend(unit_tags)
else:
cmd.unit_tags.append(unit_tags)
if pos:
cmd.target_world_space_pos.x = pos[0]
cmd.target_world_space_pos.y = pos[1]
elif target:
cmd.target_unit_tag = target
response = self._controller.act(action)
for result in response.result:
assert result == sc_error.Success
def fl_action(self, obs, act, *args):
return self._controller.act(self._features.transform_action(
obs.observation, actions.FUNCTIONS[act](*args), skip_available=True))
def check_apm(self, name):
"""Set up a game, yield, then check the apm in the replay."""
interface = sc_pb.InterfaceOptions(raw=True, score=False)
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 64
interface.feature_layer.resolution.y = 64
interface.feature_layer.minimap_resolution.x = 64
interface.feature_layer.minimap_resolution.y = 64
create = sc_pb.RequestCreateGame(
random_seed=1, local_map=sc_pb.LocalMap(map_path=self._map_path,
map_data=self._map_data))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Protoss,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Protoss, options=interface)
self._controller.create_game(create)
self._controller.join_game(join)
self._info = self._controller.game_info()
self._features = features.features_from_game_info(
self._info, use_feature_units=True, use_raw_units=True)
self._map_size = point.Point.build(self._info.start_raw.map_size)
for i in range(60):
yield i, self.step()
data = self._controller.save_replay()
replay_info = self._controller.replay_info(data)
self._summary.append((name, replay_info))
def main(unused_argv):
env = Env()
def rand_fl_coord():
return (point.Point.unit_rand() * 64).floor()
def rand_world_coord():
return (point.Point.unit_rand() * 20).floor() + 20
def random_probe_loc(obs):
return random.choice(_xy_locs(
env.fl_obs(obs).feature_screen.unit_type == units.Protoss.Probe))
def random_probe_tag(obs):
return random.choice(get_units(obs, unit_type=units.Protoss.Probe).keys())
for i, obs in env.check_apm("no-op"):
pass
for i, obs in env.check_apm("fl stop, single probe"):
if i == 0:
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Stop_quick", "now")
for i, obs in env.check_apm("fl smart, single probe, random location"):
if i == 0:
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Smart_screen", "now", rand_fl_coord())
for i, obs in env.check_apm("fl move, single probe, random location"):
if i == 0:
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Move_screen", "now", rand_fl_coord())
for i, obs in env.check_apm("fl stop, random probe"):
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Stop_quick", "now")
for i, obs in env.check_apm("fl move, random probe, random location"):
env.fl_action(obs, "select_point", "select", random_probe_loc(obs))
env.fl_action(obs, "Move_screen", "now", rand_fl_coord())
for i, obs in env.check_apm("raw stop, random probe"):
env.raw_unit_command("Stop_quick", random_probe_tag(obs))
for i, obs in env.check_apm("raw move, random probe, random location"):
env.raw_unit_command("Move_screen", random_probe_tag(obs),
rand_world_coord())
probe = None
for i, obs in env.check_apm("raw move, single probe, random location"):
if not probe:
probe = random_probe_tag(obs)
env.raw_unit_command("Move_screen", probe, rand_world_coord())
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/play.py | pysc2/bin/play.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run SC2 to play a game or a replay."""
import getpass
import platform
import sys
import time
from absl import app
from absl import flags
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import renderer_human
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("render", True, "Whether to render with pygame.")
flags.DEFINE_bool("realtime", False, "Whether to run in realtime mode.")
flags.DEFINE_bool("full_screen", False, "Whether to run full screen.")
flags.DEFINE_float("fps", 22.4, "Frames per second to run the game.")
flags.DEFINE_integer("step_mul", 1, "Game steps per observation.")
flags.DEFINE_bool("render_sync", False, "Turn on sync rendering.")
point_flag.DEFINE_point("feature_screen_size", "84",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
flags.DEFINE_integer("feature_camera_width", 24,
"Width of the feature layer camera.")
point_flag.DEFINE_point("rgb_screen_size", "256,192",
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", "128",
"Resolution for rendered minimap.")
point_flag.DEFINE_point("window_size", "640,480",
"Screen size if not full screen.")
flags.DEFINE_string("video", None, "Path to render a video of observations.")
flags.DEFINE_integer("max_game_steps", 0, "Total game steps to run.")
flags.DEFINE_integer("max_episode_steps", 0, "Total game steps per episode.")
flags.DEFINE_string("user_name", getpass.getuser(),
"Name of the human player for replays.")
flags.DEFINE_enum("user_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"User's race.")
flags.DEFINE_enum("bot_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"AI race.")
flags.DEFINE_enum("difficulty", "very_easy", sc2_env.Difficulty._member_names_, # pylint: disable=protected-access
"Bot's strength.")
flags.DEFINE_enum("bot_build", "random", sc2_env.BotBuild._member_names_, # pylint: disable=protected-access
"Bot's build strategy.")
flags.DEFINE_bool("disable_fog", False, "Disable fog of war.")
flags.DEFINE_integer("observed_player", 1, "Which player to observe.")
flags.DEFINE_bool("profile", False, "Whether to turn on code profiling.")
flags.DEFINE_bool("trace", False, "Whether to trace the code execution.")
flags.DEFINE_bool("save_replay", True, "Whether to save a replay at the end.")
flags.DEFINE_string("map", None, "Name of a map to use to play.")
flags.DEFINE_bool("battle_net_map", False, "Use the battle.net map version.")
flags.DEFINE_string("map_path", None, "Override the map for this replay.")
flags.DEFINE_string("replay", None, "Name of a replay to show.")
def main(unused_argv):
"""Run SC2 to play a game or a replay."""
if FLAGS.trace:
stopwatch.sw.trace()
elif FLAGS.profile:
stopwatch.sw.enable()
if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay):
sys.exit("Must supply either a map or replay.")
if FLAGS.replay and not FLAGS.replay.lower().endswith("sc2replay"):
sys.exit("Replay must end in .SC2Replay.")
if FLAGS.realtime and FLAGS.replay:
# TODO(tewalds): Support realtime in replays once the game supports it.
sys.exit("realtime isn't possible for replays yet.")
if FLAGS.render and (FLAGS.realtime or FLAGS.full_screen):
sys.exit("disable pygame rendering if you want realtime or full_screen.")
if platform.system() == "Linux" and (FLAGS.realtime or FLAGS.full_screen):
sys.exit("realtime and full_screen only make sense on Windows/MacOS.")
if not FLAGS.render and FLAGS.render_sync:
sys.exit("render_sync only makes sense with pygame rendering on.")
run_config = run_configs.get()
interface = sc_pb.InterfaceOptions()
interface.raw = FLAGS.render
interface.raw_affects_selection = True
interface.raw_crop_to_playable_area = True
interface.score = True
interface.show_cloaked = True
interface.show_burrowed_shadows = True
interface.show_placeholders = True
if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:
interface.feature_layer.width = FLAGS.feature_camera_width
FLAGS.feature_screen_size.assign_to(interface.feature_layer.resolution)
FLAGS.feature_minimap_size.assign_to(
interface.feature_layer.minimap_resolution)
interface.feature_layer.crop_to_playable_area = True
interface.feature_layer.allow_cheating_layers = True
if FLAGS.render and FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:
FLAGS.rgb_screen_size.assign_to(interface.render.resolution)
FLAGS.rgb_minimap_size.assign_to(interface.render.minimap_resolution)
max_episode_steps = FLAGS.max_episode_steps
if FLAGS.map:
create = sc_pb.RequestCreateGame(
realtime=FLAGS.realtime,
disable_fog=FLAGS.disable_fog)
try:
map_inst = maps.get(FLAGS.map)
except maps.lib.NoMapError:
if FLAGS.battle_net_map:
create.battlenet_map_name = FLAGS.map
else:
raise
else:
if map_inst.game_steps_per_episode:
max_episode_steps = map_inst.game_steps_per_episode
if FLAGS.battle_net_map:
create.battlenet_map_name = map_inst.battle_net
else:
create.local_map.map_path = map_inst.path
create.local_map.map_data = map_inst.data(run_config)
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer,
race=sc2_env.Race[FLAGS.bot_race],
difficulty=sc2_env.Difficulty[FLAGS.difficulty],
ai_build=sc2_env.BotBuild[FLAGS.bot_build])
join = sc_pb.RequestJoinGame(
options=interface, race=sc2_env.Race[FLAGS.user_race],
player_name=FLAGS.user_name)
version = None
else:
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=interface,
disable_fog=FLAGS.disable_fog,
observed_player_id=FLAGS.observed_player)
version = replay.get_replay_version(replay_data)
run_config = run_configs.get(version=version) # Replace the run config.
with run_config.start(
full_screen=FLAGS.full_screen,
window_size=FLAGS.window_size,
want_rgb=interface.HasField("render")) as controller:
if FLAGS.map:
controller.create_game(create)
controller.join_game(join)
else:
info = controller.replay_info(replay_data)
print(" Replay info ".center(60, "-"))
print(info)
print("-" * 60)
map_path = FLAGS.map_path or info.local_map_path
if map_path:
start_replay.map_data = run_config.map_data(map_path,
len(info.player_info))
controller.start_replay(start_replay)
if FLAGS.render:
renderer = renderer_human.RendererHuman(
fps=FLAGS.fps, step_mul=FLAGS.step_mul,
render_sync=FLAGS.render_sync, video=FLAGS.video)
renderer.run(
run_config, controller, max_game_steps=FLAGS.max_game_steps,
game_steps_per_episode=max_episode_steps,
save_replay=FLAGS.save_replay)
else: # Still step forward so the Mac/Windows renderer works.
try:
while True:
frame_start_time = time.time()
if not FLAGS.realtime:
controller.step(FLAGS.step_mul)
obs = controller.observe()
if obs.player_result:
break
time.sleep(max(0, frame_start_time + 1 / FLAGS.fps - time.time()))
except KeyboardInterrupt:
pass
print("Score: ", obs.observation.score.score)
print("Result: ", obs.player_result)
if FLAGS.map and FLAGS.save_replay:
replay_save_loc = run_config.save_replay(
controller.save_replay(), "local", FLAGS.map)
print("Replay saved to:", replay_save_loc)
# Save scores so we know how the human player did.
with open(replay_save_loc.replace("SC2Replay", "txt"), "w") as f:
f.write("{}\n".format(obs.observation.score.score))
if FLAGS.profile:
print(stopwatch.sw)
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/replay_info.py | pysc2/bin/replay_info.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Query one or more replays for information."""
import os
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import remote_controller
from pysc2.lib import replay
from pysc2.lib import gfile
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
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)
replay_paths = list(run_config.replay_paths(replay_dir))
print("Found %s replays" % len(replay_paths))
if not replay_paths:
return
data = run_config.replay_data(replay_paths[0])
ver = replay.get_replay_version(data)
FLAGS.set_default("sc2_version", ver.game_version)
run_config = run_configs.get() # In case the version changed.
print("Launching version:", run_config.version.game_version)
with run_config.start(want_rgb=False) as controller:
print("-" * 60)
print(",".join((
"filename",
"version",
"map_name",
"game_duration_loops",
"players",
"P1-outcome",
"P1-race",
"P1-apm",
"P2-race",
"P2-apm",
)))
bad_replays = []
try:
for file_path in replay_paths:
file_name = os.path.basename(file_path)
data = run_config.replay_data(file_path)
try:
info = controller.replay_info(data)
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.game_version,
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))
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()
data = run_config.replay_data(replay_path)
ver = replay.get_replay_version(data)
FLAGS.set_default("sc2_version", ver.game_version)
run_config = run_configs.get() # In case the version changed.
print("Launching version:", run_config.version.game_version)
with run_config.start(want_rgb=False) as controller:
info = controller.replay_info(data)
print("-" * 60)
print(info)
def main(argv):
if not argv:
raise ValueError("No replay directory or path specified.")
if len(argv) > 2:
raise ValueError("Too many arguments provided.")
path = argv[1]
try:
if gfile.IsDirectory(path):
return _replay_index(path)
else:
return _replay_info(path)
except KeyboardInterrupt:
pass
def entry_point(): # Needed so the setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/mem_leak_check.py | pysc2/bin/mem_leak_check.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for memory leaks."""
# pylint: disable=g-import-not-at-top
import collections
import random
import sys
import time
from absl import app
from absl import flags
try:
import psutil
except ImportError:
sys.exit(
"`psutil` library required to track memory. This can be installed with:\n"
"$ pip install psutil\n"
"and needs the python-dev headers installed, for example:\n"
"$ apt install python-dev")
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import protocol
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
# pylint: enable=g-import-not-at-top
races = {
"random": sc_common.Random,
"protoss": sc_common.Protoss,
"terran": sc_common.Terran,
"zerg": sc_common.Zerg,
}
flags.DEFINE_integer("mem_limit", 2000, "Max memory usage in Mb.")
flags.DEFINE_integer("episodes", 200, "Max number of episodes.")
flags.DEFINE_enum("race", "random", races.keys(), "Which race to play as.")
flags.DEFINE_list("map", "Catalyst", "Which map(s) to test on.")
FLAGS = flags.FLAGS
class Timestep(collections.namedtuple(
"Timestep", ["episode", "time", "cpu", "memory", "name"])):
def __str__(self):
return "[%3d: %7.3f] cpu: %5.1f s, mem: %4d Mb; %s" % self
def main(unused_argv):
for m in FLAGS.map: # Verify they're all valid.
maps.get(m)
interface = sc_pb.InterfaceOptions()
interface.raw = True
interface.score = True
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 84
interface.feature_layer.resolution.y = 84
interface.feature_layer.minimap_resolution.x = 64
interface.feature_layer.minimap_resolution.y = 64
timeline = []
start = time.time()
run_config = run_configs.get()
proc = run_config.start(want_rgb=interface.HasField("render"))
process = psutil.Process(proc.pid)
episode = 1
def add(s):
cpu_times = process.cpu_times() # pytype: disable=wrong-arg-count
cpu = cpu_times.user + cpu_times.system
mem = process.memory_info().rss / 2 ** 20 # In Mb # pytype: disable=wrong-arg-count
step = Timestep(episode, time.time() - start, cpu, mem, s)
print(step)
timeline.append(step)
if mem > FLAGS.mem_limit:
raise MemoryError("%s Mb mem limit exceeded" % FLAGS.mem_limit)
try:
add("Started process")
controller = proc.controller
for _ in range(FLAGS.episodes):
map_inst = maps.get(random.choice(FLAGS.map))
create = sc_pb.RequestCreateGame(
realtime=False, disable_fog=False, random_seed=episode,
local_map=sc_pb.LocalMap(map_path=map_inst.path,
map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=races[FLAGS.race],
difficulty=sc_pb.CheatInsane)
join = sc_pb.RequestJoinGame(race=races[FLAGS.race], options=interface)
controller.create_game(create)
add("Created game on %s" % map_inst.name)
controller.join_game(join)
add("Joined game")
for i in range(2000):
controller.step(16)
obs = controller.observe()
if obs.player_result:
add("Lost on step %s" % i)
break
if i > 0 and i % 100 == 0:
add("Step %s" % i)
episode += 1
add("Done")
except KeyboardInterrupt:
pass
except (MemoryError, protocol.ConnectionError) as e:
print(e)
finally:
proc.close()
print("Timeline:")
for t in timeline:
print(t)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/gen_data.py | pysc2/bin/gen_data.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate the unit definitions for units.py."""
import collections
from absl import app
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import static_data
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
def get_data():
"""Get the game's static data from an actual game."""
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
m = maps.get("Sequencer") # Arbitrary ladder map.
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=m.path, map_data=m.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Random,
options=sc_pb.InterfaceOptions(raw=True))
controller.create_game(create)
controller.join_game(join)
return controller.data_raw()
def generate_py_units(data):
"""Generate the list of units in units.py."""
units = collections.defaultdict(list)
for unit in sorted(data.units, key=lambda a: a.name):
if unit.unit_id in static_data.UNIT_TYPES:
units[unit.race].append(unit)
def print_race(name, race):
print("class %s(enum.IntEnum):" % name)
print(' """%s units."""' % name)
for unit in units[race]:
print(" %s = %s" % (unit.name, unit.unit_id))
print("\n")
print(" units.py ".center(60, "-"))
print_race("Neutral", sc_common.NoRace)
print_race("Protoss", sc_common.Protoss)
print_race("Terran", sc_common.Terran)
print_race("Zerg", sc_common.Zerg)
def generate_py_buffs(data):
"""Generate the list of buffs in buffs.py."""
print(" buffs.py ".center(60, "-"))
print("class Buffs(enum.IntEnum):")
print(' """The list of buffs, as returned from RequestData."""')
for buff in sorted(data.buffs, key=lambda a: a.name):
if buff.name and buff.buff_id in static_data.BUFFS:
print(" %s = %s" % (buff.name, buff.buff_id))
print("\n")
def generate_py_upgrades(data):
"""Generate the list of upgrades in upgrades.py."""
print(" upgrades.py ".center(60, "-"))
print("class Upgrades(enum.IntEnum):")
print(' """The list of upgrades, as returned from RequestData."""')
for upgrade in sorted(data.upgrades, key=lambda a: a.name):
if upgrade.name and upgrade.upgrade_id in static_data.UPGRADES:
print(" %s = %s" % (upgrade.name, upgrade.upgrade_id))
print("\n")
def main(unused_argv):
data = get_data()
generate_py_units(data)
generate_py_buffs(data)
generate_py_upgrades(data)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/valid_actions.py | pysc2/bin/valid_actions.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Print the valid actions."""
from absl import app
from absl import flags
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point_flag
FLAGS = flags.FLAGS
point_flag.DEFINE_point("screen_size", "84", "Resolution for screen actions.")
point_flag.DEFINE_point("minimap_size", "64", "Resolution for minimap actions.")
flags.DEFINE_bool("hide_specific", False, "Hide the specific 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)))
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)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/play_vs_agent.py | pysc2/bin/play_vs_agent.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Play as a human against an agent by setting up a LAN game.
This needs to be called twice, once for the human, and once for the agent.
The human plays on the host. There you run it as:
$ python -m pysc2.bin.play_vs_agent --human --map <map> --remote <agent ip>
And on the machine the agent plays on:
$ python -m pysc2.bin.play_vs_agent --agent <import path>
The `--remote` arg is used to create an SSH tunnel to the remote agent's
machine, so can be dropped if it's running on the same machine.
SC2 is limited to only allow LAN games on localhost, so we need to forward the
ports between machines. SSH is used to do this with the `--remote` arg. If the
agent is on the same machine as the host, this arg can be dropped. SSH doesn't
forward UDP, so this also sets up a UDP proxy. As part of that it sets up a TCP
server that is also used as a settings server. Note that you won't have an
opportunity to give ssh a password, so you must use ssh keys for authentication.
"""
import getpass
import importlib
import platform
import sys
import time
from absl import app
from absl import flags
from absl import logging
import portpicker
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import lan_sc2_env
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import renderer_human
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("render", platform.system() == "Linux",
"Whether to render with pygame.")
flags.DEFINE_bool("realtime", False, "Whether to run in realtime mode.")
flags.DEFINE_string("agent", "pysc2.agents.random_agent.RandomAgent",
"Which agent to run, as a python path to an Agent class.")
flags.DEFINE_string("agent_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent's race.")
flags.DEFINE_float("fps", 22.4, "Frames per second to run the game.")
flags.DEFINE_integer("step_mul", 8, "Game steps per agent step.")
point_flag.DEFINE_point("feature_screen_size", "84",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", "256",
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", "128",
"Resolution for rendered minimap.")
flags.DEFINE_enum("action_space", "FEATURES",
sc2_env.ActionSpace._member_names_, # pylint: disable=protected-access
"Which action space to use. Needed if you take both feature "
"and rgb observations.")
flags.DEFINE_bool("use_feature_units", False,
"Whether to include feature units.")
flags.DEFINE_string("user_name", getpass.getuser(),
"Name of the human player for replays.")
flags.DEFINE_enum("user_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"User's race.")
flags.DEFINE_string("host", "127.0.0.1", "Game Host. Can be 127.0.0.1 or ::1")
flags.DEFINE_integer(
"config_port", 14380,
"Where to set/find the config port. The host starts a tcp server to share "
"the config with the client, and to proxy udp traffic if played over an "
"ssh tunnel. This sets that port, and is also the start of the range of "
"ports used for LAN play.")
flags.DEFINE_string("remote", None,
"Where to set up the ssh tunnels to the client.")
flags.DEFINE_string("map", None, "Name of a map to use to play.")
flags.DEFINE_bool("human", False, "Whether to host a game as a human.")
def main(unused_argv):
if FLAGS.human:
human()
else:
agent()
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_port=FLAGS.config_port,
race=sc2_env.Race[FLAGS.agent_race],
step_mul=FLAGS.step_mul,
realtime=FLAGS.realtime,
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_unit_counts=True,
use_camera_position=True,
show_cloaked=True,
show_burrowed_shadows=True,
show_placeholders=True,
send_observation_proto=True,
crop_to_playable_area=True,
raw_crop_to_playable_area=True,
allow_cheating_layers=True,
add_cargo_to_units=True,
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.RestartError:
pass
logging.info("Done.")
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.")
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))
proc = run_config.start(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
join.options.raw_affects_selection = True
join.options.raw_crop_to_playable_area = True
join.options.show_cloaked = True
join.options.show_burrowed_shadows = True
join.options.show_placeholders = 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()
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/gen_actions.py | pysc2/bin/gen_actions.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate the action definitions for actions.py."""
import itertools
from absl import app
from absl import flags
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import static_data
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import data_pb2 as sc_data
from s2clientprotocol import sc2api_pb2 as sc_pb
flags.DEFINE_enum("command", None, ["csv", "python"], "What to generate.")
flags.DEFINE_string("map", "Acropolis", "Which map to use.")
flags.mark_flag_as_required("command")
FLAGS = flags.FLAGS
def get_data():
"""Retrieve static data from the game."""
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
m = maps.get(FLAGS.map)
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=m.path, map_data=m.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(race=sc_common.Random,
options=sc_pb.InterfaceOptions(raw=True))
controller.create_game(create)
controller.join_game(join)
return controller.data()
def generate_name(ability):
return (ability.friendly_name or ability.button_name or
ability.link_name)
def sort_key(data, ability):
# Alphabetical, with specifics immediately after their generals.
name = generate_name(ability)
if ability.remaps_to_ability_id:
general = data.abilities[ability.remaps_to_ability_id]
name = "%s %s" % (generate_name(general), name)
return name
def generate_csv(data):
"""Generate a CSV of the abilities for easy commenting."""
print(",".join([
"ability_id",
"link_name",
"link_index",
"button_name",
"hotkey",
"friendly_name",
"remap_to",
"mismatch",
]))
for ability in sorted(data.abilities.values(),
key=lambda a: sort_key(data, a)):
ab_id = ability.ability_id
if ab_id in skip_abilities or (ab_id not in data.general_abilities and
ab_id not in used_abilities):
continue
general = ""
if ab_id in data.general_abilities:
general = "general"
elif ability.remaps_to_ability_id:
general = ability.remaps_to_ability_id
mismatch = ""
if ability.remaps_to_ability_id:
def check_mismatch(ability, parent, attr):
if getattr(ability, attr) != getattr(parent, attr):
return "%s: %s" % (attr, getattr(ability, attr))
parent = data.abilities[ability.remaps_to_ability_id]
mismatch = "; ".join(filter(None, [
check_mismatch(ability, parent, "available"),
check_mismatch(ability, parent, "target"),
check_mismatch(ability, parent, "allow_minimap"),
check_mismatch(ability, parent, "allow_autocast"),
check_mismatch(ability, parent, "is_building"),
check_mismatch(ability, parent, "footprint_radius"),
check_mismatch(ability, parent, "is_instant_placement"),
check_mismatch(ability, parent, "cast_range"),
]))
print(",".join(map(str, [
ability.ability_id,
ability.link_name,
ability.link_index,
ability.button_name,
ability.hotkey,
ability.friendly_name,
general,
mismatch,
])))
def generate_py_abilities(data):
"""Generate the list of functions in actions.py."""
def print_action(func_id, name, func, ab_id, general_id):
args = [func_id, '"%s"' % name, func, ab_id]
if general_id:
args.append(general_id)
print(" Function.ability(%s)," % ", ".join(str(v) for v in args))
func_ids = itertools.count(12) # Leave room for the ui funcs.
for ability in sorted(data.abilities.values(),
key=lambda a: sort_key(data, a)):
ab_id = ability.ability_id
if ab_id in skip_abilities or (ab_id not in data.general_abilities and
ab_id not in used_abilities):
continue
name = generate_name(ability).replace(" ", "_")
if ability.target in (sc_data.AbilityData.Target.Value("None"),
sc_data.AbilityData.PointOrNone):
print_action(next(func_ids), name + "_quick", "cmd_quick", ab_id,
ability.remaps_to_ability_id)
if ability.target != sc_data.AbilityData.Target.Value("None"):
print_action(next(func_ids), name+ "_screen", "cmd_screen", ab_id,
ability.remaps_to_ability_id)
if ability.allow_minimap:
print_action(next(func_ids), name + "_minimap", "cmd_minimap", ab_id,
ability.remaps_to_ability_id)
if ability.allow_autocast:
print_action(next(func_ids), name + "_autocast", "autocast", ab_id,
ability.remaps_to_ability_id)
def main(unused_argv):
data = get_data()
print("-" * 60)
if FLAGS.command == "csv":
generate_csv(data)
elif FLAGS.command == "python":
generate_py_abilities(data)
used_abilities = set(static_data.ABILITIES)
frivolous = {6, 7} # Dance and Cheer
# These need a slot id and so are exposed differently.
cancel_slot = {313, 1039, 305, 307, 309, 1832, 1834, 3672}
unload_unit = {410, 415, 397, 1440, 2373, 1409, 914, 3670}
skip_abilities = cancel_slot | unload_unit | frivolous
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/benchmark_observe.py | pysc2/bin/benchmark_observe.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmark observation times."""
import time
from absl import app
from absl import flags
from pysc2 import maps
from pysc2 import run_configs
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
flags.DEFINE_integer("count", 1000, "How many observations to run.")
flags.DEFINE_integer("step_mul", 16, "How many game steps per observation.")
flags.DEFINE_string("replay", None, "Which replay to run.")
flags.DEFINE_string("map", "Catalyst", "Which map to run.")
FLAGS = flags.FLAGS
def interface_options(score=False, raw=False, features=None, rgb=None,
crop=True):
"""Get an InterfaceOptions for the config."""
interface = sc_pb.InterfaceOptions()
interface.score = score
interface.raw = raw
if features:
if isinstance(features, int):
screen, minimap = features, features
else:
screen, minimap = features
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = screen
interface.feature_layer.resolution.y = screen
interface.feature_layer.minimap_resolution.x = minimap
interface.feature_layer.minimap_resolution.y = minimap
interface.feature_layer.crop_to_playable_area = crop
if rgb:
if isinstance(rgb, int):
screen, minimap = rgb, rgb
else:
screen, minimap = rgb
interface.render.resolution.x = screen
interface.render.resolution.y = screen
interface.render.minimap_resolution.x = minimap
interface.render.minimap_resolution.y = minimap
return interface
configs = [
("raw", interface_options(raw=True)),
("raw-feat-48", interface_options(raw=True, features=48)),
("raw-feat-128", interface_options(raw=True, features=128)),
("raw-feat-128-48", interface_options(raw=True, features=(128, 48))),
("feat-32", interface_options(features=32)),
("feat-48", interface_options(features=48)),
("feat-72-no-crop", interface_options(features=72, crop=False)),
("feat-72", interface_options(features=72)),
("feat-96", interface_options(features=96)),
("feat-128", interface_options(features=128)),
("rgb-64", interface_options(rgb=64)),
("rgb-128", interface_options(rgb=128)),
]
def main(unused_argv):
stopwatch.sw.enable()
results = []
try:
for config, interface in configs:
print((" Starting: %s " % config).center(60, "-"))
timeline = []
run_config = run_configs.get()
if FLAGS.replay:
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data, options=interface, disable_fog=False,
observed_player_id=2)
version = replay.get_replay_version(replay_data)
run_config = run_configs.get(version=version) # Replace the run config.
else:
map_inst = maps.get(FLAGS.map)
create = sc_pb.RequestCreateGame(
realtime=False, disable_fog=False, random_seed=1,
local_map=sc_pb.LocalMap(map_path=map_inst.path,
map_data=map_inst.data(run_config)))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Computer, race=sc_common.Terran,
difficulty=sc_pb.VeryEasy)
join = sc_pb.RequestJoinGame(options=interface, race=sc_common.Protoss)
with run_config.start(
want_rgb=interface.HasField("render")) as controller:
if FLAGS.replay:
info = controller.replay_info(replay_data)
print(" Replay info ".center(60, "-"))
print(info)
print("-" * 60)
if info.local_map_path:
start_replay.map_data = run_config.map_data(info.local_map_path)
controller.start_replay(start_replay)
else:
controller.create_game(create)
controller.join_game(join)
for _ in range(FLAGS.count):
controller.step(FLAGS.step_mul)
start = time.time()
obs = controller.observe()
timeline.append(time.time() - start)
if obs.player_result:
break
results.append((config, timeline))
except KeyboardInterrupt:
pass
names, values = zip(*results)
print("\n\nTimeline:\n")
print(",".join(names))
for times in zip(*values):
print(",".join("%0.2f" % (t * 1000) for t in times))
print(stopwatch.sw)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/benchmark_replay.py | pysc2/bin/benchmark_replay.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmark observation times."""
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point_flag
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_integer("step_mul", 8, "Game steps per observation.")
point_flag.DEFINE_point("feature_screen_size", "64",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", None,
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", None,
"Resolution for rendered minimap.")
flags.DEFINE_bool("use_feature_units", True,
"Whether to include feature units.")
flags.DEFINE_bool("use_raw_units", True,
"Whether to include raw units.")
flags.DEFINE_string("replay", None, "Name of a replay to show.")
flags.DEFINE_string("map_path", None, "Override the map for this replay.")
flags.mark_flag_as_required("replay")
def main(argv):
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")
stopwatch.sw.enable()
interface = sc_pb.InterfaceOptions()
interface.raw = FLAGS.use_feature_units or FLAGS.use_raw_units
interface.score = True
interface.feature_layer.width = 24
if FLAGS.feature_screen_size and FLAGS.feature_minimap_size:
FLAGS.feature_screen_size.assign_to(interface.feature_layer.resolution)
FLAGS.feature_minimap_size.assign_to(
interface.feature_layer.minimap_resolution)
if FLAGS.rgb_screen_size and FLAGS.rgb_minimap_size:
FLAGS.rgb_screen_size.assign_to(interface.render.resolution)
FLAGS.rgb_minimap_size.assign_to(interface.render.minimap_resolution)
run_config = run_configs.get()
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=interface,
observed_player_id=1)
version = replay.get_replay_version(replay_data)
run_config = run_configs.get(version=version) # Replace the run config.
try:
with run_config.start(
want_rgb=interface.HasField("render")) as controller:
info = controller.replay_info(replay_data)
print(" Replay info ".center(60, "-"))
print(info)
print("-" * 60)
map_path = FLAGS.map_path or info.local_map_path
if map_path:
start_replay.map_data = run_config.map_data(map_path)
controller.start_replay(start_replay)
feats = features.features_from_game_info(
game_info=controller.game_info(),
use_feature_units=FLAGS.use_feature_units,
use_raw_units=FLAGS.use_raw_units,
use_unit_counts=interface.raw,
use_camera_position=False,
action_space=actions.ActionSpace.FEATURES)
while True:
controller.step(FLAGS.step_mul)
obs = controller.observe()
feats.transform_obs(obs)
if obs.player_result:
break
except KeyboardInterrupt:
pass
print(stopwatch.sw)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/update_battle_net_cache.py | pysc2/bin/update_battle_net_cache.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Download the battle.net cache files needed by replays.
Adapted from https://github.com/ggtracker/sc2reader .
"""
import binascii
import os
import urllib
from absl import app
from absl import flags
import mpyq
from s2protocol import versions as s2versions
from pysc2 import run_configs
FLAGS = flags.FLAGS
flags.DEFINE_string("bnet_base", None,
"Path to a Battle.net directory to update.")
DEPOT_URL_TEMPLATE = "http://us.depot.battle.net:1119/{hash}.{type}"
def mkdirs(*paths):
for path in paths:
if not os.path.exists(path):
os.makedirs(path)
def test_looks_like_battle_net(path):
path = path.rstrip("/").rstrip("\\")
if os.path.basename(path) != "Battle.net":
raise ValueError("Doesn't look like a Battle.net cache:", path)
if not os.path.isdir(os.path.join(path, "Cache")):
raise ValueError("Missing a Cache subdirectory:", path)
def replay_paths(paths):
"""A generator yielding the full path to the replays under `replay_dir`."""
for path in paths:
if path.lower().endswith(".sc2replay"):
yield path
else:
for f in os.listdir(path):
if f.lower().endswith(".sc2replay"):
yield os.path.join(path, f)
def update_battle_net_cache(replays, bnet_base):
"""Download the battle.net cache files needed by replays."""
test_looks_like_battle_net(bnet_base)
downloaded = 0
failed = set()
for replay_path in replays:
try:
archive = mpyq.MPQArchive(replay_path)
except ValueError:
print("Failed to parse replay:", replay_path)
continue
extracted = archive.extract()
contents = archive.header["user_data_header"]["content"]
header = s2versions.latest().decode_replay_header(contents)
base_build = header["m_version"]["m_baseBuild"]
prot = s2versions.build(base_build)
details_bytes = (extracted.get(b"replay.details") or
extracted.get(b"replay.details.backup"))
details = prot.decode_replay_details(details_bytes)
for map_handle in details["m_cacheHandles"]:
# server = map_handle[4:8].decode("utf-8").strip("\x00 ")
map_hash = binascii.b2a_hex(map_handle[8:]).decode("utf8")
file_type = map_handle[0:4].decode("utf8")
cache_path = os.path.join(
bnet_base, "Cache", map_hash[0:2], map_hash[2:4],
"%s.%s" % (map_hash, file_type))
url = DEPOT_URL_TEMPLATE.format(hash=map_hash, type=file_type)
if not os.path.exists(cache_path) and url not in failed:
mkdirs(os.path.dirname(cache_path))
print(url)
try:
urllib.request.urlretrieve(url, cache_path)
except urllib.error.HTTPError as e:
print("Download failed:", e)
failed.add(url)
else:
downloaded += 1
return downloaded
def main(argv):
replays = list(replay_paths(argv[1:]))
bnet_base = FLAGS.bnet_base or os.path.join(run_configs.get().data_dir,
"Battle.net")
print("Updating cache:", bnet_base)
print("Checking", len(replays), "replays")
downloaded = update_battle_net_cache(replays, bnet_base)
print("Downloaded", downloaded, "files")
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/replay_actions.py | pysc2/bin/replay_actions.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dump out stats about all the actions that are in use in a set of replays."""
import collections
import multiprocessing
import os
import queue
import signal
import sys
import threading
import time
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import features
from pysc2.lib import point
from pysc2.lib import protocol
from pysc2.lib import remote_controller
from pysc2.lib import replay
from pysc2.lib import static_data
from pysc2.lib import gfile
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_integer("parallel", 1, "How many instances to run in parallel.")
flags.DEFINE_integer("step_mul", 8, "How many game steps per observation.")
flags.DEFINE_string("replays", None, "Path to a directory of replays.")
flags.mark_flag_as_required("replays")
size = point.Point(16, 16)
interface = sc_pb.InterfaceOptions(
raw=True, score=False,
feature_layer=sc_pb.SpatialCameraSetup(width=24))
size.assign_to(interface.feature_layer.resolution)
size.assign_to(interface.feature_layer.minimap_resolution)
def sorted_dict_str(d):
return "{%s}" % ", ".join("%s: %s" % (k, d[k])
for k in sorted(d, key=d.get, reverse=True))
class ReplayStats(object):
"""Summary stats of the replays seen so far."""
def __init__(self):
self.replays = 0
self.steps = 0
self.camera_move = 0
self.select_pt = 0
self.select_rect = 0
self.control_group = 0
self.maps = collections.defaultdict(int)
self.races = collections.defaultdict(int)
self.unit_ids = collections.defaultdict(int)
self.valid_abilities = collections.defaultdict(int)
self.made_abilities = collections.defaultdict(int)
self.valid_actions = collections.defaultdict(int)
self.made_actions = collections.defaultdict(int)
self.buffs = collections.defaultdict(int)
self.upgrades = collections.defaultdict(int)
self.effects = collections.defaultdict(int)
self.crashing_replays = set()
self.invalid_replays = set()
def merge(self, other):
"""Merge another ReplayStats into this one."""
def merge_dict(a, b):
for k, v in b.items():
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)
merge_dict(self.buffs, other.buffs)
merge_dict(self.upgrades, other.upgrades)
merge_dict(self.effects, other.effects)
self.crashing_replays |= other.crashing_replays
self.invalid_replays |= other.invalid_replays
def __str__(self):
len_sorted_dict = lambda s: (len(s), sorted_dict_str(s))
len_sorted_list = lambda s: (len(s), sorted(s))
new_abilities = ((set(self.valid_abilities.keys())
| set(self.made_abilities.keys()))
- set(static_data.ABILITIES))
new_units = set(self.unit_ids) - set(static_data.UNIT_TYPES)
new_buffs = set(self.buffs) - set(static_data.BUFFS)
new_upgrades = set(self.upgrades) - set(static_data.UPGRADES)
return "\n\n".join((
"Replays: %s, Steps total: %s" % (self.replays, self.steps),
"Camera move: %s, Select pt: %s, Select rect: %s, Control group: %s" % (
self.camera_move, self.select_pt, self.select_rect,
self.control_group),
"Maps: %s\n%s" % len_sorted_dict(self.maps),
"Races: %s\n%s" % len_sorted_dict(self.races),
"Unit ids: %s\n%s" % len_sorted_dict(self.unit_ids),
"New units: %s \n%s" % len_sorted_list(new_units),
"Valid abilities: %s\n%s" % len_sorted_dict(self.valid_abilities),
"Made abilities: %s\n%s" % len_sorted_dict(self.made_abilities),
"New abilities: %s\n%s" % len_sorted_list(new_abilities),
"Valid actions: %s\n%s" % len_sorted_dict(self.valid_actions),
"Made actions: %s\n%s" % len_sorted_dict(self.made_actions),
"Buffs: %s\n%s" % len_sorted_dict(self.buffs),
"New buffs: %s\n%s" % len_sorted_list(new_buffs),
"Upgrades: %s\n%s" % len_sorted_dict(self.upgrades),
"New upgrades: %s\n%s" % len_sorted_list(new_upgrades),
"Effects: %s\n%s" % len_sorted_dict(self.effects),
"Crashing replays: %s\n%s" % len_sorted_list(self.crashing_replays),
"Invalid replays: %s\n%s" % len_sorted_list(self.invalid_replays),
))
class ProcessStats(object):
"""Stats for a worker process."""
def __init__(self, proc_id):
self.proc_id = proc_id
self.time = time.time()
self.stage = ""
self.replay = ""
self.replay_stats = ReplayStats()
def update(self, stage):
self.time = time.time()
self.stage = stage
def __str__(self):
return ("[%2d] replay: %10s, replays: %5d, steps: %7d, game loops: %7s, "
"last: %12s, %3d s ago" % (
self.proc_id, self.replay, self.replay_stats.replays,
self.replay_stats.steps,
self.replay_stats.steps * FLAGS.step_mul, self.stage,
time.time() - self.time))
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 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
class ReplayProcessor(multiprocessing.Process):
"""A Process that pulls replays and processes them."""
def __init__(self, proc_id, run_config, replay_queue, stats_queue):
super(ReplayProcessor, self).__init__()
self.stats = ProcessStats(proc_id)
self.run_config = run_config
self.replay_queue = replay_queue
self.stats_queue = stats_queue
def run(self):
signal.signal(signal.SIGTERM, lambda a, b: sys.exit()) # Exit quietly.
self._update_stage("spawn")
replay_name = "none"
while True:
self._print("Starting up a new SC2 instance.")
self._update_stage("launch")
try:
with self.run_config.start(
want_rgb=interface.HasField("render")) as controller:
self._print("SC2 Started successfully.")
ping = controller.ping()
for _ in range(300):
try:
replay_path = self.replay_queue.get()
except queue.Empty:
self._update_stage("done")
self._print("Empty queue, returning")
return
try:
replay_name = os.path.basename(replay_path)[:10]
self.stats.replay = replay_name
self._print("Got replay: %s" % replay_path)
self._update_stage("open replay file")
replay_data = self.run_config.replay_data(replay_path)
self._update_stage("replay_info")
info = controller.replay_info(replay_data)
self._print((" Replay Info %s " % replay_name).center(60, "-"))
self._print(info)
self._print("-" * 60)
if valid_replay(info, ping):
self.stats.replay_stats.maps[info.map_name] += 1
for player_info in info.player_info:
race_name = sc_common.Race.Name(
player_info.player_info.race_actual)
self.stats.replay_stats.races[race_name] += 1
map_data = None
if info.local_map_path:
self._update_stage("open map file")
map_data = self.run_config.map_data(info.local_map_path)
for player_id in [1, 2]:
self._print("Starting %s from player %s's perspective" % (
replay_name, player_id))
self.process_replay(controller, replay_data, map_data,
player_id)
else:
self._print("Replay is invalid.")
self.stats.replay_stats.invalid_replays.add(replay_name)
finally:
self.replay_queue.task_done()
self._update_stage("shutdown")
except (protocol.ConnectionError, protocol.ProtocolError,
remote_controller.RequestError):
self.stats.replay_stats.crashing_replays.add(replay_name)
except KeyboardInterrupt:
return
def _print(self, s):
for line in str(s).strip().splitlines():
print("[%s] %s" % (self.stats.proc_id, line))
def _update_stage(self, stage):
self.stats.update(stage)
self.stats_queue.put(self.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,
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 b in u.buff_ids:
self.stats.replay_stats.buffs[b] += 1
for u in obs.observation.raw_data.player.upgrade_ids:
self.stats.replay_stats.upgrades[u] += 1
for e in obs.observation.raw_data.effects:
self.stats.replay_stats.effects[e.effect_id] += 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)
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:
try:
s = stats_queue.get(True, print_time - time.time())
if s is None: # Signal to print and exit NOW!
running = False
break
proc_stats[s.proc_id] = s
except queue.Empty:
pass
replay_stats = ReplayStats()
for s in proc_stats:
replay_stats.merge(s.replay_stats)
print((" Summary %0d secs " % (print_time - start_time)).center(width, "="))
print(replay_stats)
print(" Process stats ".center(width, "-"))
print("\n".join(str(s) for s in proc_stats))
print("=" * width)
def replay_queue_filler(replay_queue, replay_list):
"""A thread that fills the replay_queue with replay filenames."""
for replay_path in replay_list:
replay_queue.put(replay_path)
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_printer, args=(stats_queue,))
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.")
if not replay_list:
return
if not FLAGS["sc2_version"].present: # ie not set explicitly.
version = replay.get_replay_version(
run_config.replay_data(replay_list[0]))
run_config = run_configs.get(version=version)
print("Assuming version:", version.game_version)
print()
stats_thread.start()
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(min(len(replay_list), 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.
if stats_thread.is_alive():
stats_thread.join()
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/reencode_replays.py | pysc2/bin/reencode_replays.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run through a set of replays, generating new replays from them."""
import os
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import replay
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_string("input_dir", None, "Directory of replays to modify.")
flags.DEFINE_string("output_dir", None, "Where to write them.")
def main(_):
run_config = run_configs.get()
replay_list = sorted(run_config.replay_paths(FLAGS.input_dir))
print(len(replay_list), "replays found.\n")
version = replay.get_replay_version(run_config.replay_data(replay_list[0]))
run_config = run_configs.get(version=version) # Replace the run config.
with run_config.start(want_rgb=False) as controller:
for replay_path in replay_list:
replay_data = run_config.replay_data(replay_path)
info = controller.replay_info(replay_data)
print(" Starting replay: ".center(60, "-"))
print("Path:", replay_path)
print("Size:", len(replay_data), "bytes")
print(" Replay info: ".center(60, "-"))
print(info)
print("-" * 60)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=sc_pb.InterfaceOptions(score=True),
record_replay=True,
observed_player_id=1)
if info.local_map_path:
start_replay.map_data = run_config.map_data(info.local_map_path,
len(info.player_info))
controller.start_replay(start_replay)
while True:
controller.step(1000)
obs = controller.observe()
if obs.player_result:
print("Stepped", obs.observation.game_loop, "game loops")
break
replay_data = controller.save_replay()
replay_save_loc = os.path.join(FLAGS.output_dir,
os.path.basename(replay_path))
with open(replay_save_loc, "wb") as f:
f.write(replay_data)
print("Wrote replay, ", len(replay_data), " bytes to:", replay_save_loc)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/gen_versions.py | pysc2/bin/gen_versions.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate the list of versions for run_configs."""
from absl import app
import requests
# raw version of:
# https://github.com/Blizzard/s2client-proto/blob/master/buildinfo/versions.json
VERSIONS_FILE = "https://raw.githubusercontent.com/Blizzard/s2client-proto/master/buildinfo/versions.json"
def main(argv):
del argv # Unused.
versions = requests.get(VERSIONS_FILE).json()
for v in versions:
version_str = v["label"]
if version_str.count(".") == 1:
version_str += ".0"
print(' Version("%s", %i, "%s", None),' % (
version_str, v["base-version"], v["data-hash"]))
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/run_tests.py | pysc2/bin/run_tests.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Find and run the tests.
Run as: python -m pysc2.bin.run_tests
"""
from absl.testing import absltest
import pysc2
import pysc2.run_configs.platforms # So that the version flags work.
if __name__ == '__main__':
absltest.main(module=pysc2)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/__init__.py | pysc2/bin/__init__.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/compare_binaries.py | pysc2/bin/compare_binaries.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Compare the observations from multiple binaries."""
import collections
import sys
from absl import app
from absl import flags
from pysc2 import run_configs
from pysc2.lib import image_differencer
from pysc2.lib import proto_diff
from pysc2.lib import remote_controller
from pysc2.lib import replay
from pysc2.lib import stopwatch
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("diff", False, "Whether to diff the observations.")
flags.DEFINE_integer("truncate", 0,
"Number of characters to truncate diff values to, or 0 "
"for no truncation.")
flags.DEFINE_integer("step_mul", 8, "Game steps per observation.")
flags.DEFINE_integer("count", 100000, "How many observations to run.")
flags.DEFINE_string("replay", None, "Name of a replay to show.")
def _clear_non_deterministic_fields(obs):
for unit in obs.observation.raw_data.units:
unit.ClearField("tag")
for order in unit.orders:
order.ClearField("target_unit_tag")
for action in obs.actions:
if action.HasField("action_raw"):
if action.action_raw.HasField("unit_command"):
action.action_raw.unit_command.ClearField("target_unit_tag")
def _is_remote(arg):
return ":" in arg
def main(argv):
"""Compare the observations from multiple binaries."""
if len(argv) <= 1:
sys.exit(
"Please specify binaries to run / to connect to. For binaries to run, "
"specify the executable name. For remote connections, specify "
"<hostname>:<port>. The version must match the replay.")
targets = argv[1:]
interface = sc_pb.InterfaceOptions()
interface.raw = True
interface.raw_affects_selection = True
interface.raw_crop_to_playable_area = True
interface.score = True
interface.show_cloaked = True
interface.show_placeholders = True
interface.feature_layer.width = 24
interface.feature_layer.resolution.x = 48
interface.feature_layer.resolution.y = 48
interface.feature_layer.minimap_resolution.x = 48
interface.feature_layer.minimap_resolution.y = 48
interface.feature_layer.crop_to_playable_area = True
interface.feature_layer.allow_cheating_layers = True
run_config = run_configs.get()
replay_data = run_config.replay_data(FLAGS.replay)
start_replay = sc_pb.RequestStartReplay(
replay_data=replay_data,
options=interface,
observed_player_id=1,
realtime=False)
version = replay.get_replay_version(replay_data)
timers = []
controllers = []
procs = []
for target in targets:
timer = stopwatch.StopWatch()
timers.append(timer)
with timer("launch"):
if _is_remote(target):
host, port = target.split(":")
controllers.append(remote_controller.RemoteController(host, int(port)))
else:
proc = run_configs.get(
version=version._replace(binary=target)).start(want_rgb=False)
procs.append(proc)
controllers.append(proc.controller)
diff_counts = [0] * len(controllers)
diff_paths = collections.Counter()
try:
print("-" * 80)
print(controllers[0].replay_info(replay_data))
print("-" * 80)
for controller, t in zip(controllers, timers):
with t("start_replay"):
controller.start_replay(start_replay)
# Check the static data.
static_data = []
for controller, t in zip(controllers, timers):
with t("data"):
static_data.append(controller.data_raw())
if FLAGS.diff:
diffs = {i: proto_diff.compute_diff(static_data[0], d)
for i, d in enumerate(static_data[1:], 1)}
if any(diffs.values()):
print(" Diff in static data ".center(80, "-"))
for i, diff in diffs.items():
if diff:
print(targets[i])
diff_counts[i] += 1
print(diff.report(truncate_to=FLAGS.truncate))
for path in diff.all_diffs():
diff_paths[path.with_anonymous_array_indices()] += 1
else:
print("No diffs in static data.")
# Run some steps, checking speed and diffing the observations.
for _ in range(FLAGS.count):
for controller, t in zip(controllers, timers):
with t("step"):
controller.step(FLAGS.step_mul)
obs = []
for controller, t in zip(controllers, timers):
with t("observe"):
obs.append(controller.observe())
if FLAGS.diff:
for o in obs:
_clear_non_deterministic_fields(o)
diffs = {i: proto_diff.compute_diff(obs[0], o)
for i, o in enumerate(obs[1:], 1)}
if any(diffs.values()):
print((" Diff on step: %s " %
obs[0].observation.game_loop).center(80, "-"))
for i, diff in diffs.items():
if diff:
print(targets[i])
diff_counts[i] += 1
print(diff.report([image_differencer.image_differencer],
truncate_to=FLAGS.truncate))
for path in diff.all_diffs():
diff_paths[path.with_anonymous_array_indices()] += 1
if obs[0].player_result:
break
except KeyboardInterrupt:
pass
finally:
for c in controllers:
c.quit()
c.close()
for p in procs:
p.close()
if FLAGS.diff:
print(" Diff Counts by target ".center(80, "-"))
for target, count in zip(targets, diff_counts):
print(" %5d %s" % (count, target))
print()
print(" Diff Counts by observation path ".center(80, "-"))
for path, count in diff_paths.most_common(100):
print(" %5d %s" % (count, path))
print()
print(" Timings ".center(80, "-"))
for v, t in zip(targets, timers):
print(v)
print(t)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/agent.py | pysc2/bin/agent.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run an agent."""
import importlib
import threading
from absl import app
from absl import flags
from pysc2 import maps
from pysc2.env import available_actions_printer
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import stopwatch
FLAGS = flags.FLAGS
# flags.DEFINE_bool("render", True, "Whether to render with pygame.")
flags.DEFINE_bool("render", False, "Whether to render with pygame.")
point_flag.DEFINE_point("feature_screen_size", "128",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", None,
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", None,
"Resolution for rendered minimap.")
flags.DEFINE_enum("action_space", None, sc2_env.ActionSpace._member_names_, # pylint: disable=protected-access
"Which action space to use. Needed if you take both feature "
"and rgb observations.")
flags.DEFINE_bool("use_feature_units", True,
"Whether to include feature units.")
flags.DEFINE_bool("use_raw_units", True,
"Whether to include raw units.")
flags.DEFINE_bool("disable_fog", False, "Whether to disable Fog of War.")
flags.DEFINE_integer("max_agent_steps", 0, "Total agent steps.")
flags.DEFINE_integer("game_steps_per_episode", None, "Game steps per episode.")
flags.DEFINE_integer("max_episodes", 1, "Total episodes.")
flags.DEFINE_integer("step_mul", 1, "Game steps per agent step.")
flags.DEFINE_string("agent", "pysc2.agents.random_agent.RandomAgent",
"Which agent to run, as a python path to an Agent class.")
flags.DEFINE_string("agent_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent 1's race.")
flags.DEFINE_string("agent2", "Bot", "Second agent, either Bot or agent class.")
flags.DEFINE_string("agent2_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent2_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent 2's race.")
# flags.DEFINE_enum("difficulty", "very_easy", sc2_env.Difficulty._member_names_, # pylint: disable=protected-access
# "If agent2 is a built-in Bot, it's strength.")
flags.DEFINE_enum("difficulty", "very_hard", sc2_env.Difficulty._member_names_, # pylint: disable=protected-access
"If agent2 is a built-in Bot, it's strength.")
flags.DEFINE_enum("bot_build", "random", sc2_env.BotBuild._member_names_, # pylint: disable=protected-access
"Bot's build strategy.")
flags.DEFINE_bool("profile", False, "Whether to turn on code profiling.")
flags.DEFINE_bool("trace", False, "Whether to trace the code execution.")
flags.DEFINE_integer("parallel", 1, "How many instances to run in parallel.")
flags.DEFINE_bool("save_replay", True, "Whether to save a replay at the end.")
flags.DEFINE_string("map", None, "Name of a map to use.")
flags.DEFINE_bool("battle_net_map", False, "Use the battle.net map version.")
flags.mark_flag_as_required("map")
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,
battle_net_map=FLAGS.battle_net_map,
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,
use_raw_units=FLAGS.use_raw_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__)
def main(unused_argv):
"""Run an agent."""
if FLAGS.trace:
stopwatch.sw.trace()
elif FLAGS.profile:
stopwatch.sw.enable()
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), agent_name)
agent_classes.append(agent_cls)
players.append(sc2_env.Agent(sc2_env.Race[FLAGS.agent_race],
FLAGS.agent_name or agent_name))
# print(f"map_inst.players = {map_inst.players}")
# print(f"FLAGS.agent2 = {FLAGS.agent2}")
# input()
if map_inst.players >= 2:
if FLAGS.agent2 == "Bot":
players.append(sc2_env.Bot(sc2_env.Race[FLAGS.agent2_race],
sc2_env.Difficulty[FLAGS.difficulty],
sc2_env.BotBuild[FLAGS.bot_build]))
else:
agent_module, agent_name = FLAGS.agent2.rsplit(".", 1)
agent_cls = getattr(importlib.import_module(agent_module), agent_name)
agent_classes.append(agent_cls)
players.append(sc2_env.Agent(sc2_env.Race[FLAGS.agent2_race],
FLAGS.agent2_name or agent_name))
threads = []
for _ in range(FLAGS.parallel - 1):
t = threading.Thread(target=run_thread,
args=(agent_classes, players, FLAGS.map, False))
threads.append(t)
t.start()
run_thread(agent_classes, players, FLAGS.map, FLAGS.render)
for t in threads:
t.join()
if FLAGS.profile:
print(stopwatch.sw)
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/battle_net_maps.py | pysc2/bin/battle_net_maps.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Print the list of available maps according to the game."""
from absl import app
from pysc2 import run_configs
def main(unused_argv):
with run_configs.get().start(want_rgb=False) as controller:
available_maps = controller.available_maps()
print("\n")
print("Local map paths:")
for m in sorted(available_maps.local_map_paths):
print(" ", m)
print()
print("Battle.net maps:")
for m in sorted(available_maps.battlenet_map_names):
print(" ", m)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/replay_version.py | pysc2/bin/replay_version.py | #!/usr/bin/python
# Copyright 2022 DeepMind Technologies Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate version information from replays."""
import os
from absl import app
from pysc2 import run_configs
from pysc2.lib import replay
def main(argv):
if len(argv) <= 1:
raise app.UsageError(
"Please give one or more replay files/directories to scan as argv.")
run_config = run_configs.get()
# Use a set over the full version struct to catch cases where Blizzard failed
# to update the version field properly (eg 5.0.0).
versions = set()
def replay_version(replay_path):
"""Query a replay for information."""
if replay_path.lower().endswith("sc2replay"):
data = run_config.replay_data(replay_path)
try:
version = replay.get_replay_version(data)
except (ValueError, KeyError):
pass # Either corrupt or just old.
except Exception as e: # pylint: disable=broad-except
print("Invalid replay:", replay_path, e)
else:
versions.add(version)
try:
for path in argv[1:]:
if os.path.isdir(path):
for root, _, files in os.walk(path):
for file in files:
replay_version(os.path.join(root, file))
else:
replay_version(path)
except KeyboardInterrupt:
pass
for version in sorted(versions):
print(version)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/map_list.py | pysc2/bin/map_list.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Print the list of defined maps."""
from absl import app
from pysc2 import maps
def main(unused_argv):
for _, map_class in sorted(maps.get_maps().items()):
mp = map_class()
if mp.path:
print(mp, "\n")
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/bin/agent_remote.py | pysc2/bin/agent_remote.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Play an agent with an SC2 instance that isn't owned.
This can be used to play on the sc2ai.net ladder, as well as to play vs humans.
To play on ladder:
$ python -m pysc2.bin.agent_remote --agent <import path> \
--host_port <GamePort> --lan_port <StartPort>
To play vs humans:
$ python -m pysc2.bin.agent_remote --human --map <MapName>
then copy the string it generates which is something similar to above
If you want to play remotely, you'll need to port forward (eg with ssh -L or -R)
the host_port from localhost on one machine to localhost on the other.
You can also set your race, observation options, etc by cmdline flags.
When playing vs humans it launches both instances on the human side. This means
you only need to port-forward a single port (ie the websocket betwen SC2 and the
agent), but you also need to transfer the entire observation, which is much
bigger than the actions transferred over the lan connection between the two SC2
instances. It also makes it easy to maintain version compatibility since they
are the same binary. Unfortunately it means higher cpu usage where the human is
playing, which on a Mac becomes problematic as OSX slows down the instance
running in the background. There can also be observation differences between
Mac/Win and Linux. For these reasons, prefer play_vs_agent which runs the
instance next to the agent, and tunnels the lan actions instead.
"""
import getpass
import importlib
import platform
import sys
import time
from absl import app
from absl import flags
from absl import logging
from pysc2 import maps
from pysc2 import run_configs
from pysc2.env import remote_sc2_env
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.lib import point_flag
from pysc2.lib import portspicker
from pysc2.lib import renderer_human
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_bool("render", platform.system() == "Linux",
"Whether to render with pygame.")
flags.DEFINE_bool("realtime", False, "Whether to run in realtime mode.")
flags.DEFINE_string("agent", "pysc2.agents.random_agent.RandomAgent",
"Which agent to run, as a python path to an Agent class.")
flags.DEFINE_string("agent_name", None,
"Name of the agent in replays. Defaults to the class name.")
flags.DEFINE_enum("agent_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"Agent's race.")
flags.DEFINE_float("fps", 22.4, "Frames per second to run the game.")
flags.DEFINE_integer("step_mul", 8, "Game steps per agent step.")
point_flag.DEFINE_point("feature_screen_size", "84",
"Resolution for screen feature layers.")
point_flag.DEFINE_point("feature_minimap_size", "64",
"Resolution for minimap feature layers.")
point_flag.DEFINE_point("rgb_screen_size", "256",
"Resolution for rendered screen.")
point_flag.DEFINE_point("rgb_minimap_size", "128",
"Resolution for rendered minimap.")
flags.DEFINE_enum("action_space", "FEATURES",
sc2_env.ActionSpace._member_names_, # pylint: disable=protected-access
"Which action space to use. Needed if you take both feature "
"and rgb observations.")
flags.DEFINE_bool("use_feature_units", False,
"Whether to include feature units.")
flags.DEFINE_string("user_name", getpass.getuser(),
"Name of the human player for replays.")
flags.DEFINE_enum("user_race", "random", sc2_env.Race._member_names_, # pylint: disable=protected-access
"User's race.")
flags.DEFINE_string("host", "127.0.0.1", "Game Host")
flags.DEFINE_integer("host_port", None, "Host port")
flags.DEFINE_integer("lan_port", None, "Host port")
flags.DEFINE_string("map", None, "Name of a map to use to play.")
flags.DEFINE_bool("human", False, "Whether to host a game as a human.")
flags.DEFINE_integer("timeout_seconds", 300,
"Time in seconds for the remote agent to connect to the "
"game before an exception is raised.")
def main(unused_argv):
if FLAGS.human:
human()
else:
agent()
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 remote_sc2_env.RemoteSC2Env(
map_name=FLAGS.map,
host=FLAGS.host,
host_port=FLAGS.host_port,
lan_port=FLAGS.lan_port,
name=FLAGS.agent_name or agent_name,
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 remote_sc2_env.RestartError:
pass
logging.info("Done.")
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.")
ports = portspicker.pick_contiguous_unused_ports(4) # 2 * num_players
host_proc = run_config.start(extra_ports=ports, host=FLAGS.host,
timeout_seconds=FLAGS.timeout_seconds,
window_loc=(50, 50))
client_proc = run_config.start(extra_ports=ports, host=FLAGS.host,
connect=False, window_loc=(700, 50))
create = sc_pb.RequestCreateGame(
realtime=FLAGS.realtime, local_map=sc_pb.LocalMap(map_path=map_inst.path))
create.player_setup.add(type=sc_pb.Participant)
create.player_setup.add(type=sc_pb.Participant)
controller = host_proc.controller
controller.save_map(map_inst.path, map_inst.data(run_config))
controller.create_game(create)
print("-" * 80)
print("Join host: agent_remote --map %s --host %s --host_port %s "
"--lan_port %s" % (FLAGS.map, FLAGS.host, client_proc.port, ports[0]))
print("-" * 80)
sys.stdout.flush()
join = sc_pb.RequestJoinGame()
join.shared_port = 0 # unused
join.server_ports.game_port = ports.pop(0)
join.server_ports.base_port = ports.pop(0)
join.client_ports.add(game_port=ports.pop(0), base_port=ports.pop(0))
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.
try:
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
for p in [host_proc, client_proc]:
p.close()
portspicker.return_ports(ports)
def entry_point(): # Needed so setup.py scripts work.
app.run(main)
if __name__ == "__main__":
app.run(main)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/maps/lib.py | pysc2/maps/lib.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The library and base Map for defining full maps.
To define your own map just import this library and subclass Map. It will be
automatically registered for creation by `get`.
class NewMap(lib.Map):
prefix = "map_dir"
filename = "map_name"
players = 3
You can build a hierarchy of classes to make your definitions less verbose.
To use a map, either import the map module and instantiate the map directly, or
import the maps lib and use `get`. Using `get` from this lib will work, but only
if you've imported the map module somewhere.
"""
import os
from absl import logging
class DuplicateMapError(Exception):
pass
class NoMapError(Exception):
pass
class Map(object):
"""Base map object to configure a map. To define a map just subclass this.
Attributes:
name: The name of the map/class.
path: Where to find the map file.
directory: Directory for the map
filename: Actual filename. You can skip the ".SC2Map" file ending.
download: Where to download the map.
game_steps_per_episode: Game steps per episode, independent of the step_mul.
0 (default) means no limit.
step_mul: How many game steps per agent step?
score_index: Which score to give for this map. -1 means the win/loss
reward. >=0 is the index into score_cumulative.
score_multiplier: A score multiplier to allow make small scores good.
players: Max number of players for this map.
battle_net: The map name on battle.net, if it exists.
"""
directory = ""
filename = None
download = None
game_steps_per_episode = 0
step_mul = 8
score_index = -1
score_multiplier = 1
players = None
battle_net = None
@property
def path(self):
"""The full path to the map file: directory, filename and file ending."""
if self.filename:
map_path = os.path.join(self.directory, self.filename)
if not map_path.endswith(".SC2Map"):
map_path += ".SC2Map"
return map_path
def data(self, run_config):
"""Return the map data."""
try:
return run_config.map_data(self.path, self.players)
except (IOError, OSError) as e: # Catch both for python 2/3 compatibility.
if self.download and hasattr(e, "filename"):
logging.error("Error reading map '%s' from: %s", self.name, e.filename)
logging.error("Download the map from: %s", self.download)
raise
@property
def name(self):
return self.__class__.__name__
def __str__(self):
return "\n".join(filter(None, [
self.name,
(" file: '%s'" % self.path) if self.path else None,
(" battle_net: '%s'" % self.battle_net) if self.battle_net else None,
" players: %s, score_index: %s, score_multiplier: %s" % (
self.players, self.score_index, self.score_multiplier),
" step_mul: %s, game_steps_per_episode: %s" % (
self.step_mul, self.game_steps_per_episode),
]))
@classmethod
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
def get_maps():
"""Get the full dict of maps {map_name: map_class}."""
maps = {}
for mp in Map.all_subclasses():
if mp.filename or mp.battle_net:
map_name = mp.__name__
if map_name in maps:
raise DuplicateMapError("Duplicate map found: " + map_name)
maps[map_name] = mp
return maps
def get(map_name):
"""Get an instance of a map by name. Errors if the map doesn't exist."""
if isinstance(map_name, Map):
return map_name
# Get the list of maps. This isn't at module scope to avoid problems of maps
# being defined after this module is imported.
maps = get_maps()
map_class = maps.get(map_name)
if map_class:
return map_class()
raise NoMapError("Map doesn't exist: %s" % map_name)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/maps/ladder.py | pysc2/maps/ladder.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the ladder map configs.
Refer to the map descriptions here:
http://wiki.teamliquid.net/starcraft2/Maps/Ladder_Maps/Legacy_of_the_Void
"""
import re
from pysc2.maps import lib
class Ladder(lib.Map):
players = 2
game_steps_per_episode = 16 * 60 * 30 # 30 minute limit.
download = "https://github.com/Blizzard/s2client-proto#map-packs"
ladder_seasons = [
"Ladder2017Season1",
"Ladder2017Season2",
"Ladder2017Season3",
"Ladder2017Season4",
"Ladder2018Season1",
"Ladder2018Season2",
"Ladder2018Season3",
"Ladder2018Season4",
"Ladder2019Season1",
"Ladder2019Season2",
"Ladder2019Season3",
]
for name in ladder_seasons:
globals()[name] = type(name, (Ladder,), dict(directory=name))
# pylint: disable=bad-whitespace, undefined-variable
# pytype: disable=name-error
ladder_maps = [
(Ladder2018Season2, "16-Bit LE", 2),
(Ladder2018Season1, "Abiogenesis LE", 2),
(Ladder2017Season4, "Abyssal Reef LE", 2),
(Ladder2018Season3, "Acid Plant LE", 2),
(Ladder2017Season3, "Acolyte LE", 2),
(Ladder2019Season3, "Acropolis LE", 2),
(Ladder2017Season4, "Ascension to Aiur LE", 2),
(Ladder2019Season1, "Automaton LE", 2),
(Ladder2018Season1, "Backwater LE", 2),
(Ladder2017Season4, "Battle on the Boardwalk LE", 2),
(Ladder2017Season1, "Bel'Shir Vestige LE", 2),
(Ladder2017Season2, "Blood Boil LE", 2),
(Ladder2018Season4, "Blueshift LE", 2),
(Ladder2017Season1, "Cactus Valley LE", 4),
(Ladder2018Season2, "Catalyst LE", 2),
(Ladder2018Season4, "Cerulean Fall LE", 2),
(Ladder2019Season2, "Cyber Forest LE", 2),
(Ladder2018Season2, "Darkness Sanctuary LE", 4),
(Ladder2017Season2, "Defender's Landing LE", 2),
(Ladder2019Season3, "Disco Bloodbath LE", 2),
(Ladder2018Season3, "Dreamcatcher LE", 2),
(Ladder2018Season1, "Eastwatch LE", 2),
(Ladder2019Season3, "Ephemeron LE", 2),
(Ladder2018Season3, "Fracture LE", 2),
(Ladder2017Season3, "Frost LE", 2),
(Ladder2017Season1, "Honorgrounds LE", 4),
(Ladder2017Season3, "Interloper LE", 2),
(Ladder2019Season2, "Kairos Junction LE", 2),
(Ladder2019Season2, "King's Cove LE", 2),
(Ladder2018Season3, "Lost and Found LE", 2),
(Ladder2017Season3, "Mech Depot LE", 2),
(Ladder2018Season1, "Neon Violet Square LE", 2),
(Ladder2019Season2, "New Repugnancy LE", 2),
(Ladder2017Season1, "Newkirk Precinct TE", 2),
(Ladder2017Season4, "Odyssey LE", 2),
(Ladder2017Season1, "Paladino Terminal LE", 2),
(Ladder2018Season4, "Para Site LE", 2),
(Ladder2019Season1, "Port Aleksander LE", 2),
(Ladder2017Season2, "Proxima Station LE", 2),
(Ladder2018Season2, "Redshift LE", 2),
(Ladder2017Season2, "Sequencer LE", 2),
(Ladder2018Season4, "Stasis LE", 2),
(Ladder2019Season3, "Thunderbird LE", 2),
(Ladder2019Season3, "Triton LE", 2),
(Ladder2019Season2, "Turbo Cruise '84 LE", 2),
(Ladder2019Season3, "Winter's Gate LE", 2),
(Ladder2019Season3, "World of Sleepers LE", 2),
(Ladder2019Season1, "Year Zero LE", 2),
# Disabled due to being renamed to Neo Seoul
# (Ladder2018Season1, "Blackpink LE", 2),
]
# pylint: enable=bad-whitespace, undefined-variable
# pytype: enable=name-error
# Create the classes dynamically, putting them into the module scope. They all
# inherit from a parent and set the players based on the map filename.
for parent, bnet, players in ladder_maps:
name = re.sub(r"[ '-]|[LTRS]E$", "", bnet)
map_file = re.sub(r"[ ']", "", bnet)
globals()[name] = type(name, (parent,), dict(
filename=map_file, players=players, battle_net=bnet))
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/maps/mini_games.py | pysc2/maps/mini_games.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the mini game map configs. These are maps made by Deepmind."""
from pysc2.maps import lib
class MiniGame(lib.Map):
directory = "mini_games"
download = "https://github.com/deepmind/pysc2#get-the-maps"
players = 1
score_index = 0
game_steps_per_episode = 0
step_mul = 8
mini_games = [
"BuildMarines", # 900s
"CollectMineralsAndGas", # 420s
"CollectMineralShards", # 120s
"DefeatRoaches", # 120s
"DefeatZerglingsAndBanelings", # 120s
"FindAndDefeatZerglings", # 180s
"MoveToBeacon", # 120s
]
for name in mini_games:
globals()[name] = type(name, (MiniGame,), dict(filename=name))
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/maps/__init__.py | pysc2/maps/__init__.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Register/import the maps, and offer a way to create one by name.
Users of maps should import this module:
from pysc2 import maps
and create the maps by name:
maps.get("MapName")
If you want to create your own map, then import the map lib and subclass Map.
Your subclass will be implicitly registered as a map that can be constructed by
name, as long as it is imported somewhere.
"""
from pysc2.maps import ladder
from pysc2.maps import lib
from pysc2.maps import melee
from pysc2.maps import mini_games
from pysc2.maps import llm_pysc2
from pysc2.maps import llm_smac
# Use `get` to create a map by name.
get = lib.get
get_maps = lib.get_maps
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/maps/llm_smac.py | pysc2/maps/llm_smac.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pysc2.maps import lib
class llm_smac(lib.Map):
directory = "llm_smac"
download = ""
players = 2
# game_steps_per_episode = 16 * 60 * 30 # 30 minute limit.
game_steps_per_episode = 22 * 60 * 30 # 30 minute limit.
llm_smac_maps = {
"1c3s5z",
"2c_vs_64zg",
"2s3z",
"2s_vs_1sc",
"3s5z",
"3s5z_vs_3s6z",
"3s_vs_3z",
"3s_vs_4z",
"3s_vs_5z",
}
def get_smac_map_registry():
return llm_smac_maps
for name in llm_smac_maps:
globals()[name] = type(name, (llm_smac,), dict(filename=name))
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/maps/melee.py | pysc2/maps/melee.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the melee map configs."""
from pysc2.maps import lib
class Melee(lib.Map):
directory = "Melee"
download = "https://github.com/Blizzard/s2client-proto#map-packs"
players = 2
# game_steps_per_episode = 16 * 60 * 30 # 30 minute limit.
game_steps_per_episode = 22 * 60 * 30 # 30 minute limit.
melee_maps = [
# "Empty128", # Not really playable, but may be useful in the future.
"Flat32",
"Flat48",
"Flat64",
"Flat96",
"Flat128",
"Simple64",
"Simple96",
"Simple128",
]
for name in melee_maps:
globals()[name] = type(name, (Melee,), dict(filename=name))
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/maps/llm_pysc2.py | pysc2/maps/llm_pysc2.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pysc2.maps import lib
class llm_pysc2(lib.Map):
directory = "llm_pysc2"
download = ""
players = 2
# game_steps_per_episode = 16 * 60 * 30 # 30 minute limit.
game_steps_per_episode = 22 * 60 * 30 # 30 minute limit.
llm_pysc2_maps = [
"debug_map",
"pvz_task1_level1",
"pvz_task2_level1",
"pvz_task3_level1",
"pvz_task4_level1",
"pvz_task5_level1",
"pvz_task6_level1",
"pvz_task7_level1",
"pvz_task8_level1",
"pvz_task1_level2",
"pvz_task2_level2",
"pvz_task3_level2",
"pvz_task4_level2",
"pvz_task5_level2",
"pvz_task6_level2",
"pvz_task7_level2",
"pvz_task8_level2",
"pvz_task1_level3",
"pvz_task2_level3",
"pvz_task3_level3",
"pvz_task4_level3",
"pvz_task5_level3",
"pvz_task6_level3",
"pvz_task7_level3",
"pvz_task8_level3",
]
for name in llm_pysc2_maps:
globals()[name] = type(name, (llm_pysc2,), dict(filename=name))
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/metrics.py | pysc2/lib/metrics.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Interface for tracking the number and/or latency of episodes and steps."""
class _EventTimer(object):
"""Example event timer to measure step and observation times."""
def __enter__(self):
pass
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback):
pass
class Metrics(object):
"""Interface for tracking the number and/or latency of episodes and steps."""
def __init__(self, map_name):
pass
def increment_instance(self):
pass
def increment_episode(self):
pass
def measure_step_time(self, num_steps=1):
"""Return a context manager to measure the time to perform N game steps."""
del num_steps
return _EventTimer()
def measure_observation_time(self):
"""Return a context manager to measure the time to get an observation."""
return _EventTimer()
def close(self):
pass
def __del__(self):
self.close()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/stopwatch_test.py | pysc2/lib/stopwatch_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for stopwatch."""
import os
from absl.testing import absltest
import mock
from pysc2.lib import stopwatch
def ham_dist(str1, str2):
"""Hamming distance. Count the number of differences between str1 and str2."""
assert len(str1) == len(str2)
return sum(c1 != c2 for c1, c2 in zip(str1, str2))
class StatTest(absltest.TestCase):
def testRange(self):
stat = stopwatch.Stat()
stat.add(1)
stat.add(5)
stat.add(3)
self.assertEqual(stat.num, 3)
self.assertEqual(stat.sum, 9)
self.assertEqual(stat.min, 1)
self.assertEqual(stat.max, 5)
self.assertEqual(stat.avg, 3)
def testParse(self):
stat = stopwatch.Stat()
stat.add(1)
stat.add(3)
out = str(stat)
self.assertEqual(out, "sum: 4.0000, avg: 2.0000, dev: 1.0000, "
"min: 1.0000, max: 3.0000, num: 2")
# Allow a few small rounding errors
self.assertLess(ham_dist(out, str(stopwatch.Stat.parse(out))), 5)
class StopwatchTest(absltest.TestCase):
@mock.patch("time.time")
def testStopwatch(self, mock_time):
mock_time.return_value = 0
sw = stopwatch.StopWatch()
with sw("one"):
mock_time.return_value += 0.002
with sw("one"):
mock_time.return_value += 0.004
with sw("two"):
with sw("three"):
mock_time.return_value += 0.006
@sw.decorate
def four():
mock_time.return_value += 0.004
four()
@sw.decorate("five")
def foo():
mock_time.return_value += 0.005
foo()
out = str(sw)
# The names should be in sorted order.
names = [l.split(None)[0] for l in out.splitlines()[1:]]
self.assertEqual(names, ["five", "four", "one", "two", "two.three"])
one_line = out.splitlines()[3].split(None)
self.assertLess(one_line[5], one_line[6]) # min < max
self.assertEqual(one_line[7], "2") # num
# Can't test the rest since they'll be flaky.
# Allow a few small rounding errors for the round trip.
round_trip = str(stopwatch.StopWatch.parse(out))
self.assertLess(ham_dist(out, round_trip), 15,
"%s != %s" % (out, round_trip))
def testDivideZero(self):
sw = stopwatch.StopWatch()
with sw("zero"):
pass
# Just make sure this doesn't have a divide by 0 for when the total is 0.
self.assertIn("zero", str(sw))
@mock.patch.dict(os.environ, {"SC2_NO_STOPWATCH": "1"})
def testDecoratorDisabled(self):
sw = stopwatch.StopWatch()
self.assertEqual(round, sw.decorate(round))
self.assertEqual(round, sw.decorate("name")(round))
@mock.patch.dict(os.environ, {"SC2_NO_STOPWATCH": ""})
def testDecoratorEnabled(self):
sw = stopwatch.StopWatch()
self.assertNotEqual(round, sw.decorate(round))
self.assertNotEqual(round, sw.decorate("name")(round))
def testSpeed(self):
count = 100
def run():
for _ in range(count):
with sw("name"):
pass
sw = stopwatch.StopWatch()
for _ in range(10):
sw.enable()
with sw("enabled"):
run()
sw.trace()
with sw("trace"):
run()
sw.enable() # To catch "disabled".
with sw("disabled"):
sw.disable()
run()
# No asserts. Succeed but print the timings.
print(sw)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/upgrades.py | pysc2/lib/upgrades.py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the static list of upgrades for SC2."""
import enum
# pylint: disable=invalid-name
class Upgrades(enum.IntEnum):
"""The list of upgrades, as generated by bin/gen_data.py."""
AdaptiveTalons = 293
AdrenalGlands = 65
AdvancedBallistics = 140
AnabolicSynthesis = 88
AnionPulseCrystals = 99
Blink = 87
Burrow = 64
CentrificalHooks = 75
Charge = 86
ChitinousPlating = 4
CloakingField = 20
CombatShield = 16
ConcussiveShells = 17
CorvidReactor = 22
CycloneRapidFireLaunchers = 291
DrillingClaws = 122
EnhancedShockwaves = 296
ExtendedThermalLance = 50
GlialReconstitution = 2
GraviticBooster = 48
GraviticDrive = 49
GravitonCatapult = 1
GroovedSpines = 134
HiSecAutoTracking = 5
HighCapacityFuelTanks = 139
HyperflightRotors = 136
InfernalPreigniter = 19
LockOn = 144
MetabolicBoost = 66
MuscularAugments = 135
NeosteelFrame = 10
NeuralParasite = 101
PathogenGlands = 74
PersonalCloaking = 25
PneumatizedCarapace = 62
ProtossAirArmorsLevel1 = 81
ProtossAirArmorsLevel2 = 82
ProtossAirArmorsLevel3 = 83
ProtossAirWeaponsLevel1 = 78
ProtossAirWeaponsLevel2 = 79
ProtossAirWeaponsLevel3 = 80
ProtossGroundArmorsLevel1 = 42
ProtossGroundArmorsLevel2 = 43
ProtossGroundArmorsLevel3 = 44
ProtossGroundWeaponsLevel1 = 39
ProtossGroundWeaponsLevel2 = 40
ProtossGroundWeaponsLevel3 = 41
ProtossShieldsLevel1 = 45
ProtossShieldsLevel2 = 46
ProtossShieldsLevel3 = 47
PsiStorm = 52
ResonatingGlaives = 130
ShadowStrike = 141
SmartServos = 289
Stimpack = 15
TerranInfantryArmorsLevel1 = 11
TerranInfantryArmorsLevel2 = 12
TerranInfantryArmorsLevel3 = 13
TerranInfantryWeaponsLevel1 = 7
TerranInfantryWeaponsLevel2 = 8
TerranInfantryWeaponsLevel3 = 9
TerranShipWeaponsLevel1 = 36
TerranShipWeaponsLevel2 = 37
TerranShipWeaponsLevel3 = 38
TerranStructureArmor = 6
TerranVehicleAndShipArmorsLevel1 = 116
TerranVehicleAndShipArmorsLevel2 = 117
TerranVehicleAndShipArmorsLevel3 = 118
TerranVehicleWeaponsLevel1 = 30
TerranVehicleWeaponsLevel2 = 31
TerranVehicleWeaponsLevel3 = 32
TunnelingClaws = 3
WarpGateResearch = 84
WeaponRefit = 76
ZergFlyerArmorsLevel1 = 71
ZergFlyerArmorsLevel2 = 72
ZergFlyerArmorsLevel3 = 73
ZergFlyerWeaponsLevel1 = 68
ZergFlyerWeaponsLevel2 = 69
ZergFlyerWeaponsLevel3 = 70
ZergGroundArmorsLevel1 = 56
ZergGroundArmorsLevel2 = 57
ZergGroundArmorsLevel3 = 58
ZergMeleeWeaponsLevel1 = 53
ZergMeleeWeaponsLevel2 = 54
ZergMeleeWeaponsLevel3 = 55
ZergMissileWeaponsLevel1 = 59
ZergMissileWeaponsLevel2 = 60
ZergMissileWeaponsLevel3 = 61
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/point_flag.py | pysc2/lib/point_flag.py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define a flag type for points."""
from absl import flags
from pysc2.lib import point
# Let absl.flags know that DEFINE_point should show up in the caller's module.
flags.disclaim_key_flags()
class PointParser(flags.ArgumentParser):
"""Parse a flag into a pysc2.lib.point.Point."""
def parse(self, argument):
if not argument or argument == "0":
return None
if isinstance(argument, int):
args = [argument]
elif isinstance(argument, (list, tuple)):
args = argument
elif isinstance(argument, str):
args = argument.split(",")
else:
raise ValueError(
"Invalid point: '%r'. Valid: '<int>' or '<int>,<int>'." % argument)
args = [int(v) for v in args]
if len(args) == 1:
args *= 2
if len(args) == 2:
return point.Point(args[0], args[1])
raise ValueError(
"Invalid point: '%s'. Valid: '<int>' or '<int>,<int>'." % argument)
def flag_type(self):
return "pysc2.lib.point.Point"
class PointSerializer(flags.ArgumentSerializer):
"""Custom serializer for pysc2.lib.point.Point."""
def serialize(self, value):
return str(value)
def DEFINE_point(name, default, help_string, flag_values=flags.FLAGS, **args): # pylint: disable=invalid-name,redefined-builtin
"""Registers a flag whose value parses as a point."""
flags.DEFINE(PointParser(), name, default, help_string, flag_values,
PointSerializer(), **args)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/buffs.py | pysc2/lib/buffs.py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the static list of buffs for SC2."""
import enum
# pylint: disable=invalid-name
class Buffs(enum.IntEnum):
"""The list of buffs, as generated by bin/gen_data.py."""
BansheeCloak = 7
BlindingCloud = 83
BlindingCloudStructure = 38
CarryHarvestableVespeneGeyserGas = 273
CarryHarvestableVespeneGeyserGasProtoss = 274
CarryHarvestableVespeneGeyserGasZerg = 275
CarryHighYieldMineralFieldMinerals = 272
CarryMineralFieldMinerals = 271
ChannelSnipeCombat = 145
Charging = 30
ChronoBoostEnergyCost = 281
CloakFieldEffect = 29
Contaminated = 36
EMPDecloak = 16
FungalGrowth = 17
GhostCloak = 6
GhostHoldFire = 12
GhostHoldFireB = 13
GravitonBeam = 5
GuardianShield = 18
ImmortalOverload = 102
InhibitorZoneTemporalField = 289
LockOn = 116
LurkerHoldFire = 136
LurkerHoldFireB = 137
MedivacSpeedBoost = 89
NeuralParasite = 22
OracleRevelation = 49
OracleStasisTrapTarget = 129
OracleWeapon = 99
ParasiticBomb = 132
ParasiticBombSecondaryUnitSearch = 134
ParasiticBombUnitKU = 133
PowerUserWarpable = 8
PsiStorm = 28
QueenSpawnLarvaTimer = 11
RavenScramblerMissile = 277
RavenShredderMissileArmorReduction = 280
RavenShredderMissileTint = 279
Slow = 33
Stimpack = 27
StimpackMarauder = 24
SupplyDrop = 25
TemporalField = 121
ViperConsumeStructure = 59
VoidRaySpeedUpgrade = 288
VoidRaySwarmDamageBoost = 122
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/features_test.py | pysc2/lib/features_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for features."""
import copy
import pickle
from absl.testing import absltest
from absl.testing import parameterized
import numpy
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.lib import point
from google.protobuf import text_format
from s2clientprotocol import sc2api_pb2 as sc_pb
# Heavily trimmed, so this is useful for testing actions, but not observations.
observation_text_proto = """
player_common {
player_id: 1
minerals: 0
vespene: 0
food_cap: 10
food_used: 0
food_army: 0
food_workers: 0
idle_worker_count: 0
army_count: 0
warp_gate_count: 0
larva_count: 0
}
game_loop: 20
"""
RECTANGULAR_DIMENSIONS = features.Dimensions(screen=(84, 80), minimap=(64, 67))
SQUARE_DIMENSIONS = features.Dimensions(screen=84, minimap=64)
class AvailableActionsTest(absltest.TestCase):
always_expected = {
"no_op", "move_camera", "select_point", "select_rect",
"select_control_group"
}
def setUp(self):
super(AvailableActionsTest, self).setUp()
self.obs = text_format.Parse(observation_text_proto, sc_pb.Observation())
self.hideSpecificActions(True)
def hideSpecificActions(self, hide_specific_actions): # pylint: disable=invalid-name
self.features = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
hide_specific_actions=hide_specific_actions))
def assertAvail(self, expected):
actual = self.features.available_actions(self.obs)
actual_names = {actions.FUNCTIONS[i].name for i in actual}
self.assertEqual(actual_names, set(expected) | self.always_expected)
def testAlways(self):
self.assertAvail([])
def testSelectUnit(self):
self.obs.ui_data.multi.units.add(unit_type=1)
self.assertAvail(["select_unit"])
def testSelectIdleWorkder(self):
self.obs.player_common.idle_worker_count = 1
self.assertAvail(["select_idle_worker"])
def testSelectArmy(self):
self.obs.player_common.army_count = 3
self.assertAvail(["select_army"])
def testSelectWarpGates(self):
self.obs.player_common.warp_gate_count = 1
self.assertAvail(["select_warp_gates"])
def testSelectLarva(self):
self.obs.player_common.larva_count = 2
self.assertAvail(["select_larva"])
def testQuick(self):
self.obs.abilities.add(ability_id=32)
self.assertAvail(["Effect_Salvage_quick"])
def testScreen(self):
self.obs.abilities.add(ability_id=326, requires_point=True)
self.assertAvail(["Build_SensorTower_screen"])
def testScreenMinimap(self):
self.obs.abilities.add(ability_id=17, requires_point=True)
self.assertAvail(["Patrol_screen", "Patrol_minimap"])
def testScreenAutocast(self):
self.obs.abilities.add(ability_id=386, requires_point=True)
self.assertAvail(["Effect_Heal_screen", "Effect_Heal_autocast"])
def testScreenQuick(self):
a = self.obs.abilities.add(ability_id=421)
self.hideSpecificActions(True)
a.requires_point = False
self.assertAvail(["Build_TechLab_quick"])
a.requires_point = True
self.assertAvail(["Build_TechLab_screen"])
self.hideSpecificActions(False)
a.requires_point = False
self.assertAvail(["Build_TechLab_Barracks_quick", "Build_TechLab_quick"])
a.requires_point = True
self.assertAvail(["Build_TechLab_Barracks_screen", "Build_TechLab_screen"])
def testGeneral(self):
self.obs.abilities.add(ability_id=1374)
self.hideSpecificActions(False)
self.assertAvail(["BurrowDown_quick", "BurrowDown_Baneling_quick"])
self.hideSpecificActions(True)
self.assertAvail(["BurrowDown_quick"])
def testGeneralType(self):
a = self.obs.abilities.add(ability_id=1376)
self.hideSpecificActions(False)
self.assertAvail(["BurrowUp_quick", "BurrowUp_Baneling_quick",
"BurrowUp_autocast", "BurrowUp_Baneling_autocast"])
self.hideSpecificActions(True)
self.assertAvail(["BurrowUp_quick", "BurrowUp_autocast"])
a.ability_id = 2110
self.hideSpecificActions(False)
self.assertAvail(["BurrowUp_quick", "BurrowUp_Lurker_quick"])
self.hideSpecificActions(True)
self.assertAvail(["BurrowUp_quick"])
def testMany(self):
add = [
(23, True), # Attack
(318, True), # Build_CommandCenter
(320, True), # Build_Refinery
(319, True), # Build_SupplyDepot
(316, True), # Effect_Repair_SCV
(295, True), # Harvest_Gather_SCV
(16, True), # Move
(17, True), # Patrol
(4, False), # Stop
]
for a, r in add:
self.obs.abilities.add(ability_id=a, requires_point=r)
self.hideSpecificActions(False)
self.assertAvail([
"Attack_Attack_minimap",
"Attack_Attack_screen",
"Attack_minimap",
"Attack_screen",
"Build_CommandCenter_screen",
"Build_Refinery_screen",
"Build_SupplyDepot_screen",
"Effect_Repair_screen",
"Effect_Repair_autocast",
"Effect_Repair_SCV_autocast",
"Effect_Repair_SCV_screen",
"Harvest_Gather_screen",
"Harvest_Gather_SCV_screen",
"Move_minimap",
"Move_screen",
"Move_Move_minimap",
"Move_Move_screen",
"Patrol_minimap",
"Patrol_screen",
"Patrol_Patrol_minimap",
"Patrol_Patrol_screen",
"Stop_quick",
"Stop_Stop_quick"
])
self.hideSpecificActions(True)
self.assertAvail([
"Attack_minimap",
"Attack_screen",
"Build_CommandCenter_screen",
"Build_Refinery_screen",
"Build_SupplyDepot_screen",
"Effect_Repair_screen",
"Effect_Repair_autocast",
"Harvest_Gather_screen",
"Move_minimap",
"Move_screen",
"Patrol_minimap",
"Patrol_screen",
"Stop_quick",
])
class ToPointTest(absltest.TestCase):
def testIntAsString(self):
value = features._to_point("32")
self.assertEqual(value, point.Point(32, 32))
def testIntStringTwoTuple(self):
value = features._to_point(("32", 64))
self.assertEqual(value, point.Point(32, 64))
def testNoneInputReturnsNoneOutput(self):
with self.assertRaises(AssertionError):
features._to_point(None)
def testNoneAsFirstElementOfTupleRaises(self):
with self.assertRaises(TypeError):
features._to_point((None, 32))
def testNoneAsSecondElementOfTupleRaises(self):
with self.assertRaises(TypeError):
features._to_point((32, None))
def testSingletonTupleRaises(self):
with self.assertRaises(ValueError):
features._to_point((32,))
def testThreeTupleRaises(self):
with self.assertRaises(ValueError):
features._to_point((32, 32, 32))
class DimensionsTest(absltest.TestCase):
def testScreenSizeWithoutMinimapRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=84)
def testScreenWidthWithoutHeightRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=(84, 0), minimap=64)
def testScreenWidthHeightWithoutMinimapRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=(84, 80))
def testMinimapWidthAndHeightWithoutScreenRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(minimap=(64, 67))
def testNoneNoneRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=None, minimap=None)
def testSingularZeroesRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=0, minimap=0)
def testTwoZeroesRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=(0, 0), minimap=(0, 0))
def testThreeTupleScreenRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=(1, 2, 3), minimap=32)
def testThreeTupleMinimapRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=64, minimap=(1, 2, 3))
def testNegativeScreenRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=-64, minimap=32)
def testNegativeMinimapRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=64, minimap=-32)
def testNegativeScreenTupleRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=(-64, -64), minimap=32)
def testNegativeMinimapTupleRaises(self):
with self.assertRaises(ValueError):
features.Dimensions(screen=64, minimap=(-32, -32))
def testEquality(self):
self.assertEqual(features.Dimensions(screen=64, minimap=64),
features.Dimensions(screen=64, minimap=64))
self.assertNotEqual(features.Dimensions(screen=64, minimap=64),
features.Dimensions(screen=64, minimap=32))
self.assertNotEqual(features.Dimensions(screen=64, minimap=64), None)
class TestParseAgentInterfaceFormat(parameterized.TestCase):
def test_no_arguments_raises(self):
with self.assertRaises(ValueError):
features.parse_agent_interface_format()
@parameterized.parameters((32, None), (None, 32))
def test_invalid_feature_combinations_raise(self, screen, minimap):
with self.assertRaises(ValueError):
features.parse_agent_interface_format(
feature_screen=screen,
feature_minimap=minimap)
def test_valid_feature_specification_is_parsed(self):
agent_interface_format = features.parse_agent_interface_format(
feature_screen=32,
feature_minimap=(24, 24))
self.assertEqual(
agent_interface_format.feature_dimensions.screen,
point.Point(32, 32))
self.assertEqual(
agent_interface_format.feature_dimensions.minimap,
point.Point(24, 24))
@parameterized.parameters((32, None), (None, 32), (32, 64))
def test_invalid_minimap_combinations_raise(self, screen, minimap):
with self.assertRaises(ValueError):
features.parse_agent_interface_format(
rgb_screen=screen,
rgb_minimap=minimap)
def test_valid_minimap_specification_is_parsed(self):
agent_interface_format = features.parse_agent_interface_format(
rgb_screen=32,
rgb_minimap=(24, 24))
self.assertEqual(
agent_interface_format.rgb_dimensions.screen,
point.Point(32, 32))
self.assertEqual(
agent_interface_format.rgb_dimensions.minimap,
point.Point(24, 24))
def test_invalid_action_space_raises(self):
with self.assertRaises(KeyError):
features.parse_agent_interface_format(
feature_screen=64,
feature_minimap=64,
action_space="UNKNOWN_ACTION_SPACE")
@parameterized.parameters(actions.ActionSpace.__members__.keys())
def test_valid_action_space_is_parsed(self, action_space):
agent_interface_format = features.parse_agent_interface_format(
feature_screen=32,
feature_minimap=(24, 24),
rgb_screen=64,
rgb_minimap=(48, 48),
use_raw_units=True,
action_space=action_space)
self.assertEqual(
agent_interface_format.action_space,
actions.ActionSpace[action_space])
def test_camera_width_world_units_are_parsed(self):
agent_interface_format = features.parse_agent_interface_format(
feature_screen=32,
feature_minimap=(24, 24),
camera_width_world_units=77)
self.assertEqual(agent_interface_format.camera_width_world_units, 77)
def test_use_feature_units_is_parsed(self):
agent_interface_format = features.parse_agent_interface_format(
feature_screen=32,
feature_minimap=(24, 24),
use_feature_units=True)
self.assertEqual(agent_interface_format.use_feature_units, True)
class FeaturesTest(absltest.TestCase):
def testFunctionsIdsAreConsistent(self):
for i, f in enumerate(actions.FUNCTIONS):
self.assertEqual(i, f.id, "id doesn't match for %s" % f.id)
def testAllVersionsOfAnAbilityHaveTheSameGeneral(self):
for ability_id, funcs in actions.ABILITY_IDS.items():
self.assertLen({f.general_id for f in funcs}, 1,
"Multiple generals for %s" % ability_id)
def testValidFunctionsAreConsistent(self):
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS))
valid_funcs = feats.action_spec()
for func_def in valid_funcs.functions:
func = actions.FUNCTIONS[func_def.id]
self.assertEqual(func_def.id, func.id)
self.assertEqual(func_def.name, func.name)
self.assertEqual(len(func_def.args), len(func.args)) # pylint: disable=g-generic-assert
def gen_random_function_call(self, action_spec, func_id):
args = [[numpy.random.randint(0, size) for size in arg.sizes] # pylint: disable=g-complex-comprehension
for arg in action_spec.functions[func_id].args]
return actions.FunctionCall(func_id, args)
def testIdsMatchIndex(self):
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS))
action_spec = feats.action_spec()
for func_index, func_def in enumerate(action_spec.functions):
self.assertEqual(func_index, func_def.id)
for type_index, type_def in enumerate(action_spec.types):
self.assertEqual(type_index, type_def.id)
def testReversingUnknownAction(self):
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
hide_specific_actions=False))
sc2_action = sc_pb.Action()
sc2_action.action_feature_layer.unit_command.ability_id = 6 # Cheer
func_call = feats.reverse_action(sc2_action)
self.assertEqual(func_call.function, 0) # No-op
def testSpecificActionsAreReversible(self):
"""Test that the `transform_action` and `reverse_action` are inverses."""
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
hide_specific_actions=False))
action_spec = feats.action_spec()
for func_def in action_spec.functions:
for _ in range(10):
func_call = self.gen_random_function_call(action_spec, func_def.id)
sc2_action = feats.transform_action(
None, func_call, skip_available=True)
func_call2 = feats.reverse_action(sc2_action)
sc2_action2 = feats.transform_action(
None, func_call2, skip_available=True)
if func_def.id == actions.FUNCTIONS.select_rect.id:
# Need to check this one manually since the same rect can be
# defined in multiple ways.
def rect(a):
return point.Rect(point.Point(*a[1]).floor(),
point.Point(*a[2]).floor())
self.assertEqual(func_call.function, func_call2.function)
self.assertEqual(len(func_call.arguments), len(func_call2.arguments)) # pylint: disable=g-generic-assert
self.assertEqual(func_call.arguments[0], func_call2.arguments[0])
self.assertEqual(rect(func_call.arguments),
rect(func_call2.arguments))
else:
self.assertEqual(func_call, func_call2, msg=sc2_action)
self.assertEqual(sc2_action, sc2_action2)
def testRawActionUnitTags(self):
feats = features.Features(
features.AgentInterfaceFormat(
use_raw_units=True,
action_space=actions.ActionSpace.RAW),
map_size=point.Point(100, 100))
tags = [numpy.random.randint(2**20, 2**24) for _ in range(10)]
ntags = numpy.array(tags, dtype=numpy.int64)
tag = tags[0]
ntag = numpy.array(tag, dtype=numpy.int64)
def transform(fn, *args):
func_call = actions.RAW_FUNCTIONS[fn]("now", *args)
proto = feats.transform_action(None, func_call, skip_available=True)
return proto.action_raw.unit_command
self.assertEqual(transform("Attack_pt", tag, [15, 20]).unit_tags, [tag])
self.assertEqual(transform("Attack_pt", ntag, [15, 20]).unit_tags, [tag])
self.assertEqual(transform("Attack_pt", [tag], [15, 20]).unit_tags, [tag])
self.assertEqual(transform("Attack_pt", [ntag], [15, 20]).unit_tags, [tag])
self.assertEqual(transform("Attack_pt", tags, [15, 20]).unit_tags, tags)
self.assertEqual(transform("Attack_pt", ntags, [15, 20]).unit_tags, tags)
# Weird, but needed for backwards compatibility
self.assertEqual(transform("Attack_pt", [tags], [15, 20]).unit_tags, tags)
self.assertEqual(transform("Attack_pt", [ntags], [15, 20]).unit_tags, tags)
self.assertEqual(transform("Attack_unit", tag, tag).target_unit_tag, tag)
self.assertEqual(transform("Attack_unit", tag, ntag).target_unit_tag, tag)
self.assertEqual(transform("Attack_unit", tag, [tag]).target_unit_tag, tag)
self.assertEqual(transform("Attack_unit", tag, [ntag]).target_unit_tag, tag)
def testCanPickleSpecs(self):
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=SQUARE_DIMENSIONS))
action_spec = feats.action_spec()
observation_spec = feats.observation_spec()
self.assertEqual(action_spec, pickle.loads(pickle.dumps(action_spec)))
self.assertEqual(observation_spec,
pickle.loads(pickle.dumps(observation_spec)))
def testCanPickleFunctionCall(self):
func = actions.FUNCTIONS.select_point("select", [1, 2])
self.assertEqual(func, pickle.loads(pickle.dumps(func)))
def testCanDeepcopyNumpyFunctionCall(self):
arguments = [numpy.float32] * len(actions.Arguments._fields)
dtypes = actions.FunctionCall(
function=numpy.float32,
arguments=actions.Arguments(*arguments))
self.assertEqual(dtypes, copy.deepcopy(dtypes))
def testSizeConstructors(self):
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=SQUARE_DIMENSIONS))
spec = feats.action_spec()
self.assertEqual(spec.types.screen.sizes, (84, 84))
self.assertEqual(spec.types.screen2.sizes, (84, 84))
self.assertEqual(spec.types.minimap.sizes, (64, 64))
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS))
spec = feats.action_spec()
self.assertEqual(spec.types.screen.sizes, (84, 80))
self.assertEqual(spec.types.screen2.sizes, (84, 80))
self.assertEqual(spec.types.minimap.sizes, (64, 67))
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS))
spec = feats.action_spec()
self.assertEqual(spec.types.screen.sizes, (84, 80))
self.assertEqual(spec.types.screen2.sizes, (84, 80))
self.assertEqual(spec.types.minimap.sizes, (64, 67))
# Missing one or the other of game_info and dimensions.
with self.assertRaises(ValueError):
features.Features()
# Resolution/action space mismatch.
with self.assertRaises(ValueError):
features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
action_space=actions.ActionSpace.RGB))
with self.assertRaises(ValueError):
features.Features(features.AgentInterfaceFormat(
rgb_dimensions=RECTANGULAR_DIMENSIONS,
action_space=actions.ActionSpace.FEATURES))
with self.assertRaises(ValueError):
features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
rgb_dimensions=RECTANGULAR_DIMENSIONS))
def testFlRgbActionSpec(self):
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
rgb_dimensions=features.Dimensions(screen=(128, 132), minimap=(74, 77)),
action_space=actions.ActionSpace.FEATURES))
spec = feats.action_spec()
self.assertEqual(spec.types.screen.sizes, (84, 80))
self.assertEqual(spec.types.screen2.sizes, (84, 80))
self.assertEqual(spec.types.minimap.sizes, (64, 67))
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
rgb_dimensions=features.Dimensions(screen=(128, 132), minimap=(74, 77)),
action_space=actions.ActionSpace.RGB))
spec = feats.action_spec()
self.assertEqual(spec.types.screen.sizes, (128, 132))
self.assertEqual(spec.types.screen2.sizes, (128, 132))
self.assertEqual(spec.types.minimap.sizes, (74, 77))
def testFlRgbObservationSpec(self):
feats = features.Features(features.AgentInterfaceFormat(
feature_dimensions=RECTANGULAR_DIMENSIONS,
rgb_dimensions=features.Dimensions(screen=(128, 132), minimap=(74, 77)),
action_space=actions.ActionSpace.FEATURES))
obs_spec = feats.observation_spec()
self.assertEqual(obs_spec["feature_screen"], # pylint: disable=g-generic-assert
(len(features.SCREEN_FEATURES), 80, 84))
self.assertEqual(obs_spec["feature_minimap"], # pylint: disable=g-generic-assert
(len(features.MINIMAP_FEATURES), 67, 64))
self.assertEqual(obs_spec["rgb_screen"], (132, 128, 3))
self.assertEqual(obs_spec["rgb_minimap"], (77, 74, 3))
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/proto_diff_test.py | pysc2/lib/proto_diff_test.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for proto_diff.py."""
from absl.testing import absltest
from pysc2.lib import proto_diff
from s2clientprotocol import sc2api_pb2 as sc_pb
from s2clientprotocol import score_pb2
class ProtoPathTest(absltest.TestCase):
def testCreationFromTuple(self):
self.assertEqual(
str(proto_diff.ProtoPath(("observation", "actions"))),
"observation.actions")
def testCreationFromList(self):
self.assertEqual(
str(proto_diff.ProtoPath(["observation", "actions"])),
"observation.actions")
def testCreationFromGenerator(self):
self.assertEqual(
str(proto_diff.ProtoPath(a for a in "abc")),
"a.b.c")
def testStringRepr(self):
self.assertEqual(
str(proto_diff.ProtoPath(("observation", "actions", 1, "target"))),
"observation.actions[1].target")
def testOrdering(self):
self.assertLess(
proto_diff.ProtoPath(("observation", "actions", 1, "game_loop")),
proto_diff.ProtoPath(("observation", "actions", 1, "target")))
self.assertLess(
proto_diff.ProtoPath(("observation", "actions", 1)),
proto_diff.ProtoPath(("observation", "actions", 1, "target")))
self.assertGreater(
proto_diff.ProtoPath(("observation", "actions", 1)),
proto_diff.ProtoPath(("observation",)))
def testEquals(self):
a = proto_diff.ProtoPath(("observation", "actions", 1))
b = proto_diff.ProtoPath(("observation", "actions", 1))
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
def testNotEqual(self):
a = proto_diff.ProtoPath(("observation", "actions", 1))
b = proto_diff.ProtoPath(("observation", "actions", 2))
self.assertNotEqual(a, b)
self.assertNotEqual(hash(a), hash(b))
def testIndexing(self):
path = proto_diff.ProtoPath(("observation", "actions", 1))
self.assertEqual(path[0], "observation")
self.assertEqual(path[1], "actions")
self.assertEqual(path[-2], "actions")
self.assertEqual(path[-1], 1)
def testGetField(self):
proto = sc_pb.ResponseObservation(
observation=sc_pb.Observation(game_loop=1, alerts=[sc_pb.AlertError]))
game_loop = proto_diff.ProtoPath(("observation", "game_loop"))
alert = proto_diff.ProtoPath(("observation", "alerts", 0))
self.assertEqual(game_loop.get_field(proto), 1)
self.assertEqual(alert.get_field(proto), sc_pb.AlertError)
self.assertEqual(
proto_diff.ProtoPath(game_loop.path[:-1]).get_field(proto),
sc_pb.Observation(game_loop=1, alerts=[sc_pb.AlertError]))
def testWithAnonymousArrayIndices(self):
a = proto_diff.ProtoPath(("observation", "actions"))
b = proto_diff.ProtoPath(("observation", "actions", 1))
c = proto_diff.ProtoPath(("observation", "actions", 2))
self.assertEqual(str(a), "observation.actions")
self.assertEqual(
str(b.with_anonymous_array_indices()), "observation.actions[*]")
self.assertEqual(
b.with_anonymous_array_indices(),
c.with_anonymous_array_indices())
def _alert_formatter(path, proto_a, proto_b):
field_a = path.get_field(proto_a)
if path[-2] == "alerts":
field_b = path.get_field(proto_b)
return "{} -> {}".format(
sc_pb.Alert.Name(field_a), sc_pb.Alert.Name(field_b))
class ProtoDiffTest(absltest.TestCase):
def testNoDiffs(self):
a = sc_pb.ResponseObservation()
b = sc_pb.ResponseObservation()
diff = proto_diff.compute_diff(a, b)
self.assertIsNone(diff)
def testAddedField(self):
a = sc_pb.ResponseObservation()
b = sc_pb.ResponseObservation(
observation=sc_pb.Observation(game_loop=1))
diff = proto_diff.compute_diff(a, b)
self.assertIsNotNone(diff)
self.assertLen(diff.added, 1, diff)
self.assertEqual(str(diff.added[0]), "observation")
self.assertEqual(diff.added, diff.all_diffs())
self.assertEqual(diff.report(), "Added observation.")
def testAddedFields(self):
a = sc_pb.ResponseObservation(
observation=sc_pb.Observation(
alerts=[sc_pb.AlertError]))
b = sc_pb.ResponseObservation(
observation=sc_pb.Observation(
alerts=[sc_pb.AlertError, sc_pb.MergeComplete]),
player_result=[sc_pb.PlayerResult()])
diff = proto_diff.compute_diff(a, b)
self.assertIsNotNone(diff)
self.assertLen(diff.added, 2, diff)
self.assertEqual(str(diff.added[0]), "observation.alerts[1]")
self.assertEqual(str(diff.added[1]), "player_result")
self.assertEqual(diff.added, diff.all_diffs())
self.assertEqual(
diff.report(),
"Added observation.alerts[1].\n"
"Added player_result.")
def testRemovedField(self):
a = sc_pb.ResponseObservation(observation=sc_pb.Observation(game_loop=1))
b = sc_pb.ResponseObservation(observation=sc_pb.Observation())
diff = proto_diff.compute_diff(a, b)
self.assertIsNotNone(diff)
self.assertLen(diff.removed, 1, diff)
self.assertEqual(str(diff.removed[0]), "observation.game_loop")
self.assertEqual(diff.removed, diff.all_diffs())
self.assertEqual(
diff.report(),
"Removed observation.game_loop.")
def testRemovedFields(self):
a = sc_pb.ResponseObservation(observation=sc_pb.Observation(
game_loop=1,
score=score_pb2.Score(),
alerts=[sc_pb.AlertError, sc_pb.MergeComplete]))
b = sc_pb.ResponseObservation(observation=sc_pb.Observation(
alerts=[sc_pb.AlertError]))
diff = proto_diff.compute_diff(a, b)
self.assertIsNotNone(diff)
self.assertLen(diff.removed, 3, diff)
self.assertEqual(str(diff.removed[0]), "observation.alerts[1]")
self.assertEqual(str(diff.removed[1]), "observation.game_loop")
self.assertEqual(str(diff.removed[2]), "observation.score")
self.assertEqual(diff.removed, diff.all_diffs())
self.assertEqual(
diff.report(),
"Removed observation.alerts[1].\n"
"Removed observation.game_loop.\n"
"Removed observation.score.")
def testChangedField(self):
a = sc_pb.ResponseObservation(observation=sc_pb.Observation(game_loop=1))
b = sc_pb.ResponseObservation(observation=sc_pb.Observation(game_loop=2))
diff = proto_diff.compute_diff(a, b)
self.assertIsNotNone(diff)
self.assertLen(diff.changed, 1, diff)
self.assertEqual(str(diff.changed[0]), "observation.game_loop")
self.assertEqual(diff.changed, diff.all_diffs())
self.assertEqual(diff.report(), "Changed observation.game_loop: 1 -> 2.")
def testChangedFields(self):
a = sc_pb.ResponseObservation(observation=sc_pb.Observation(
game_loop=1, alerts=[sc_pb.AlertError, sc_pb.LarvaHatched]))
b = sc_pb.ResponseObservation(observation=sc_pb.Observation(
game_loop=2, alerts=[sc_pb.AlertError, sc_pb.MergeComplete]))
diff = proto_diff.compute_diff(a, b)
self.assertIsNotNone(diff)
self.assertLen(diff.changed, 2, diff)
self.assertEqual(str(diff.changed[0]), "observation.alerts[1]")
self.assertEqual(str(diff.changed[1]), "observation.game_loop")
self.assertEqual(diff.changed, diff.all_diffs())
self.assertEqual(
diff.report(),
"Changed observation.alerts[1]: 7 -> 8.\n"
"Changed observation.game_loop: 1 -> 2.")
self.assertEqual(
diff.report([_alert_formatter]),
"Changed observation.alerts[1]: LarvaHatched -> MergeComplete.\n"
"Changed observation.game_loop: 1 -> 2.")
def testTruncation(self):
a = sc_pb.ResponseObservation(observation=sc_pb.Observation(
game_loop=1, alerts=[sc_pb.AlertError, sc_pb.LarvaHatched]))
b = sc_pb.ResponseObservation(observation=sc_pb.Observation(
game_loop=2, alerts=[sc_pb.AlertError, sc_pb.MergeComplete]))
diff = proto_diff.compute_diff(a, b)
self.assertIsNotNone(diff)
self.assertEqual(
diff.report([_alert_formatter], truncate_to=9),
"Changed observation.alerts[1]: LarvaH....\n"
"Changed observation.game_loop: 1 -> 2.")
self.assertEqual(
diff.report([_alert_formatter], truncate_to=-1),
"Changed observation.alerts[1]: ....\n"
"Changed observation.game_loop: ... -> ....")
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/memoize.py | pysc2/lib/memoize.py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A memoization decorator."""
def memoize(func):
"""Memoization decorator."""
class Memodict(dict):
"""A memoization decorator dict."""
__slots__ = ()
__name__ = func.__name__
__doc__ = func.__doc__
def __call__(self, *args):
return self[args]
def __missing__(self, args):
ret = self[args] = func(*args)
return ret
return Memodict()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/np_util_test.py | pysc2/lib/np_util_test.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for np_util.py."""
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from pysc2.lib import np_util
class NpUtilTest(parameterized.TestCase):
@parameterized.named_parameters(
("no_diff_1d", [1, 2, 3, 4], [1, 2, 3, 4], ""),
("no_diff_2d", [[1, 2], [3, 4]], [[1, 2], [3, 4]], ""),
("diff_1d", [1, 2, 3, 4], [1, 3, 2, 4],
"2 element(s) changed - [1]: 2 -> 3; [2]: 3 -> 2"),
("diff_2d", [[1, 2], [3, 4]], [[1, 3], [2, 4]],
"2 element(s) changed - [0][1]: 2 -> 3; [1][0]: 3 -> 2"))
def testSummarizeArrayDiffs(self, lhs, rhs, expected):
a = np.array(lhs)
b = np.array(rhs)
result = np_util.summarize_array_diffs(a, b)
self.assertEqual(result, expected)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/point.py | pysc2/lib/point.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Basic Point and Rect classes."""
import collections
import math
import random
class Point(collections.namedtuple("Point", ["x", "y"])):
"""A basic Point class."""
__slots__ = ()
@classmethod
def build(cls, obj):
"""Build a Point from an object that has properties `x` and `y`."""
return cls(obj.x, obj.y)
@classmethod
def unit_rand(cls):
"""Return a Point with x, y chosen randomly with 0 <= x < 1, 0 <= y < 1."""
return cls(random.random(), random.random())
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
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)
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
def round(self):
"""Round `x` and `y` to integers."""
return Point(int(round(self.x)), int(round(self.y)))
def floor(self):
"""Round `x` and `y` down to integers."""
return Point(int(math.floor(self.x)), int(math.floor(self.y)))
def ceil(self):
"""Round `x` and `y` up to integers."""
return Point(int(math.ceil(self.x)), int(math.ceil(self.y)))
def abs(self):
"""Take the absolute value of `x` and `y`."""
return Point(abs(self.x), abs(self.y))
def len(self):
"""Length of the vector to this point."""
return math.sqrt(self.x**2 + self.y**2)
def scale(self, target_len):
"""Scale the vector to have the target length."""
return self * (target_len / self.len())
def scale_max_size(self, max_size):
"""Scale this value, keeping aspect ratio, but fitting inside `max_size`."""
return self * (max_size / self).min_dim()
def scale_min_size(self, min_size):
"""Scale this value, keeping aspect ratio, but fitting around `min_size`."""
return self * (min_size / self).max_dim()
def min_dim(self):
return min(self.x, self.y)
def max_dim(self):
return max(self.x, self.y)
def transpose(self):
"""Flip x and y."""
return Point(self.y, self.x)
def rotate_deg(self, angle):
return self.rotate_rad(math.radians(angle))
def rotate_rad(self, angle):
return Point(self.x * math.cos(angle) - self.y * math.sin(angle),
self.x * math.sin(angle) + self.y * math.cos(angle))
def rotate_rand(self, angle=180):
return self.rotate_deg(random.uniform(-angle, angle))
def contained_circle(self, pt, radius):
"""Is this point inside the circle defined by (`pt`, `radius`)?"""
return self.dist(pt) < radius
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))
def __str__(self):
if all(isinstance(v, int) for v in self):
return "%d,%d" % self
else:
return "%.6f,%.6f" % self
def __neg__(self):
return Point(-self.x, -self.y)
def __add__(self, pt_or_val):
if isinstance(pt_or_val, Point):
return Point(self.x + pt_or_val.x, self.y + pt_or_val.y)
else:
return Point(self.x + pt_or_val, self.y + pt_or_val)
def __sub__(self, pt_or_val):
if isinstance(pt_or_val, Point):
return Point(self.x - pt_or_val.x, self.y - pt_or_val.y)
else:
return Point(self.x - pt_or_val, self.y - pt_or_val)
def __mul__(self, pt_or_val):
if isinstance(pt_or_val, Point):
return Point(self.x * pt_or_val.x, self.y * pt_or_val.y)
else:
return Point(self.x * pt_or_val, self.y * pt_or_val)
def __truediv__(self, pt_or_val):
if isinstance(pt_or_val, Point):
return Point(self.x / pt_or_val.x, self.y / pt_or_val.y)
else:
return Point(self.x / pt_or_val, self.y / pt_or_val)
def __floordiv__(self, pt_or_val):
if isinstance(pt_or_val, Point):
return Point(int(self.x // pt_or_val.x), int(self.y // pt_or_val.y))
else:
return Point(int(self.x // pt_or_val), int(self.y // pt_or_val))
__div__ = __truediv__
origin = Point(0, 0)
class Rect(collections.namedtuple("Rect", ["t", "l", "b", "r"])):
"""A basic Rect class. Assumes tl <= br."""
__slots__ = ()
def __new__(cls, *args):
if len(args) == 1 or (len(args) == 2 and args[1] is None):
args = (origin, args[0])
if len(args) == 2:
p1, p2 = args
if not isinstance(p1, Point) or not isinstance(p2, Point):
raise TypeError("Rect expected Points")
return super(Rect, cls).__new__(
cls,
min(p1.y, p2.y),
min(p1.x, p2.x),
max(p1.y, p2.y),
max(p1.x, p2.x))
if len(args) == 4:
if args[0] > args[2] or args[1] > args[3]:
raise TypeError("Rect requires: t <= b and l <= r")
# TODO(b/117657518): Remove the disable once the pytype bug is fixed.
return super(Rect, cls).__new__(cls, *args) # pytype: disable=missing-parameter
raise TypeError(
"Unexpected arguments to Rect. Takes 1 or 2 Points, or 4 coords.")
def __str__(self):
if all(isinstance(v, int) for v in self):
return "%d,%d,%d,%d" % self
else:
return "%.6f,%.6f,%.6f,%.6f" % self
@property
def center(self):
return Point(self.l + self.r, self.t + self.b) / 2
@property
def top(self):
return self.t
@property
def left(self):
return self.l
@property
def bottom(self):
return self.b
@property
def right(self):
return self.r
@property
def width(self):
return self.r - self.l
@property
def height(self):
return self.b - self.t
@property
def tl(self):
return Point(self.l, self.t)
@property
def br(self):
return Point(self.r, self.b)
@property
def tr(self):
return Point(self.r, self.t)
@property
def bl(self):
return Point(self.l, self.b)
@property
def diagonal(self):
return Point(self.width, self.height)
@property
def size(self):
return self.br - self.tl
@property
def area(self):
size = self.size
return size.x * size.y
def round(self):
return Rect(self.tl.round(), self.br.round())
def floor(self):
return Rect(self.tl.floor(), self.br.floor())
def ceil(self):
return Rect(self.tl.ceil(), self.br.ceil())
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)
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)
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
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/transform.py | pysc2/lib/transform.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Transform coordinates for rendering in various ways.
It's best to name these as `a_to_b` for example `screen_to_world`. The
`fwd` methods take a point or distance in coordinate system `a` and
convert it to a point or distance in coordinate system `b`. The `back` methods
do the reverse going from `b` to `a`.
These can then be chained as b_to_c.fwd(a_to_b.fwd(pt)) which will take
something in `a` and return something in `c`. It's better to use the Chain
transform to create `a_to_c`.
"""
import numbers
from pysc2.lib import point
class Transform(object):
"""Base class for coordinate transforms."""
def fwd_dist(self, dist):
raise NotImplementedError()
def fwd_pt(self, pt):
raise NotImplementedError()
def back_dist(self, dist):
raise NotImplementedError()
def back_pt(self, pt):
raise NotImplementedError()
class Linear(Transform):
"""A linear transform with a scale and offset."""
def __init__(self, scale=None, offset=None):
if scale is None:
self.scale = point.Point(1, 1)
elif isinstance(scale, numbers.Number):
self.scale = point.Point(scale, scale)
else:
self.scale = scale
assert self.scale.x != 0 and self.scale.y != 0
self.offset = offset or point.Point(0, 0)
def fwd_dist(self, dist):
return dist * self.scale.x
def fwd_pt(self, pt):
return pt * self.scale + self.offset
def back_dist(self, dist):
return dist / self.scale.x
def back_pt(self, pt):
return (pt - self.offset) / self.scale
def __str__(self):
return "Linear(scale=%s, offset=%s)" % (self.scale, self.offset)
class Chain(Transform):
"""Chain a set of transforms: Chain(a_to_b, b_to_c) => a_to_c."""
def __init__(self, *args):
self.transforms = args
def fwd_dist(self, dist):
for transform in self.transforms:
dist = transform.fwd_dist(dist)
return dist
def fwd_pt(self, pt):
for transform in self.transforms:
pt = transform.fwd_pt(pt)
return pt
def back_dist(self, dist):
for transform in reversed(self.transforms):
dist = transform.back_dist(dist)
return dist
def back_pt(self, pt):
for transform in reversed(self.transforms):
pt = transform.back_pt(pt)
return pt
def __str__(self):
return "Chain(%s)" % (self.transforms,)
class PixelToCoord(Transform):
"""Take a point within a pixel and use the tl, or tl to pixel center."""
def fwd_dist(self, dist):
return dist
def fwd_pt(self, pt):
return pt.floor()
def back_dist(self, dist):
return dist
def back_pt(self, pt):
return pt.floor() + 0.5
def __str__(self):
return "PixelToCoord()"
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/gfile.py | pysc2/lib/gfile.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This replaces google's gfile used for network storage.
A more complete public version of gfile:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/platform/gfile.py
"""
import os
# pylint: disable=invalid-name
Exists = os.path.exists
IsDirectory = os.path.isdir
ListDir = os.listdir
MakeDirs = os.makedirs
Open = open
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/remote_controller.py | pysc2/lib/remote_controller.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Controllers take actions and generates observations in proto format."""
import copy
import functools
import socket
import sys
import time
from absl import flags
from absl import logging
from pysc2.lib import protocol
from pysc2.lib import static_data
from pysc2.lib import stopwatch
import websocket
from s2clientprotocol import debug_pb2 as sc_debug
from s2clientprotocol import sc2api_pb2 as sc_pb
flags.DEFINE_bool("sc2_log_actions", False,
("Print all the actions sent to SC2. If you want observations"
" as well, consider using `sc2_verbose_protocol`."))
flags.DEFINE_integer("sc2_timeout", 360,
"Timeout to connect and wait for rpc responses.")
FLAGS = flags.FLAGS
sw = stopwatch.sw
Status = protocol.Status # pylint: disable=invalid-name
class ConnectError(Exception):
pass
class RequestError(Exception):
def __init__(self, description, res):
super(RequestError, self).__init__(description)
self.res = res
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'" % (enum_name, error_name, details), res)
return res
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
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
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)" % (
func.__name__, self.status, ",".join(map(str, valid))))
return func(self, *args, **kwargs)
return _valid_status
return decorator
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 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
class RemoteController(object):
"""Implements a python interface to interact with the SC2 binary.
All of these are implemented as blocking calls, so wait for the response
before returning.
Many of these functions take a Request* object and respond with the
corresponding Response* object as returned from SC2. The simpler functions
take a value and construct the Request itself, or return something more useful
than a Response* object.
"""
def __init__(self, host, port, proc=None, timeout_seconds=None):
timeout_seconds = timeout_seconds or FLAGS.sc2_timeout
sock = self._connect(host, port, proc, timeout_seconds)
self._client = protocol.StarcraftProtocol(sock)
self._last_obs = None
self.ping()
@sw.decorate
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.WebSocketConnectionClosedException:
raise ConnectError("Connection rejected. Is something else connected?")
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?")
def close(self):
self._client.close()
@property
def status_ended(self):
return self.status == protocol.Status.ended
@valid_status(Status.launched, Status.ended, Status.in_game, Status.in_replay)
@decorate_check_error(sc_pb.ResponseCreateGame.Error)
@sw.decorate
def create_game(self, req_create_game):
"""Create a new game. This can only be done by the host."""
return self._client.send(create_game=req_create_game)
@valid_status(Status.launched, Status.init_game)
@decorate_check_error(sc_pb.ResponseSaveMap.Error)
@sw.decorate
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))
@valid_status(Status.launched, Status.init_game)
@decorate_check_error(sc_pb.ResponseJoinGame.Error)
@sw.decorate
def join_game(self, req_join_game):
"""Join a game, done by all connected clients."""
return self._client.send(join_game=req_join_game)
@valid_status(Status.ended, Status.in_game)
@decorate_check_error(sc_pb.ResponseRestartGame.Error)
@sw.decorate
def restart(self):
"""Restart the game. Only done by the host."""
return self._client.send(restart_game=sc_pb.RequestRestartGame())
@valid_status(Status.launched, Status.ended, Status.in_game, Status.in_replay)
@decorate_check_error(sc_pb.ResponseStartReplay.Error)
@sw.decorate
def start_replay(self, req_start_replay):
"""Start a replay."""
return self._client.send(start_replay=req_start_replay)
@valid_status(Status.in_game, Status.in_replay)
@sw.decorate
def game_info(self):
"""Get the basic information about the game."""
return self._client.send(game_info=sc_pb.RequestGameInfo())
@valid_status(Status.in_game, Status.in_replay)
@sw.decorate
def data_raw(self, ability_id=True, unit_type_id=True, upgrade_id=True,
buff_id=True, effect_id=True):
"""Get the raw static data for the current game. Prefer `data` instead."""
return self._client.send(data=sc_pb.RequestData(
ability_id=ability_id, unit_type_id=unit_type_id, upgrade_id=upgrade_id,
buff_id=buff_id, effect_id=effect_id))
def data(self):
"""Get the static data for the current game."""
return static_data.StaticData(self.data_raw())
@valid_status(Status.in_game, Status.in_replay, Status.ended)
@sw.decorate
def observe(self, disable_fog=False, target_game_loop=0):
"""Get a current observation."""
obs = self._client.send(observation=sc_pb.RequestObservation(
game_loop=target_game_loop,
disable_fog=disable_fog))
if obs.observation.game_loop == 2**32 - 1:
logging.info("Received stub observation.")
if not obs.player_result:
raise ValueError("Expect a player result in a stub observation")
elif self._last_obs is None:
raise RuntimeError("Received stub observation with no previous obs")
# Rather than handling empty obs through the code, regurgitate the last
# observation (+ player result, sub actions).
new_obs = copy.deepcopy(self._last_obs)
del new_obs.actions[:]
new_obs.actions.extend(obs.actions)
new_obs.player_result.extend(obs.player_result)
obs = new_obs
self._last_obs = None
else:
self._last_obs = obs
if FLAGS.sc2_log_actions and obs.actions:
sys.stderr.write(" Executed actions ".center(60, "<") + "\n")
for action in obs.actions:
sys.stderr.write(str(action))
sys.stderr.flush()
return obs
def available_maps(self):
return self._client.send(available_maps=sc_pb.RequestAvailableMaps())
@valid_status(Status.in_game, Status.in_replay)
@catch_game_end
@sw.decorate
def step(self, count=1):
"""Step the engine forward by one (or more) step."""
return self._client.send(step=sc_pb.RequestStep(count=count))
@skip_status(Status.in_replay)
@valid_status(Status.in_game)
@catch_game_end
@sw.decorate
def actions(self, req_action):
"""Send a `sc_pb.RequestAction`, which may include multiple actions."""
if FLAGS.sc2_log_actions and req_action.actions:
sys.stderr.write(" Sending actions ".center(60, ">") + "\n")
for action in req_action.actions:
sys.stderr.write(str(action))
sys.stderr.flush()
return self._client.send(action=req_action)
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]))
@skip_status(Status.in_game)
@valid_status(Status.in_replay)
@sw.decorate
def observer_actions(self, req_observer_action):
"""Send a `sc_pb.RequestObserverAction`."""
if FLAGS.sc2_log_actions and req_observer_action.actions:
sys.stderr.write(" Sending observer actions ".center(60, ">") + "\n")
for action in req_observer_action.actions:
sys.stderr.write(str(action))
sys.stderr.flush()
return self._client.send(obs_action=req_observer_action)
def observer_act(self, action):
"""Send a single observer action. A shortcut for `observer_actions`."""
if action and action.ListFields(): # Skip no-ops.
return self.observer_actions(
sc_pb.RequestObserverAction(actions=[action]))
def chat(self, message, channel=sc_pb.ActionChat.Broadcast):
"""Send chat message as a broadcast."""
if message:
action_chat = sc_pb.ActionChat(
channel=channel, message=message)
action = sc_pb.Action(action_chat=action_chat)
return self.act(action)
@valid_status(Status.in_game, Status.ended)
@sw.decorate
def leave(self):
"""Disconnect from a multiplayer game."""
return self._client.send(leave_game=sc_pb.RequestLeaveGame())
@valid_status(Status.in_game, Status.in_replay, Status.ended)
@sw.decorate
def save_replay(self):
"""Save a replay, returning the data."""
res = self._client.send(save_replay=sc_pb.RequestSaveReplay())
return res.data
@valid_status(Status.in_game)
@sw.decorate
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))
@valid_status(Status.in_game, Status.in_replay)
@sw.decorate
def query(self, query):
"""Query the game state."""
return self._client.send(query=query)
@skip_status(Status.quit)
@sw.decorate
def quit(self):
"""Shut down the SC2 process."""
try:
# Don't expect a response.
self._client.write(sc_pb.Request(quit=sc_pb.RequestQuit(), id=999999999))
except protocol.ConnectionError:
pass # It's likely already (shutting) down, so continue as if it worked.
finally:
self.close()
@sw.decorate
def ping(self):
return self._client.send(ping=sc_pb.RequestPing())
@decorate_check_error(sc_pb.ResponseReplayInfo.Error)
@sw.decorate
def replay_info(self, replay_data):
return self._client.send(replay_info=sc_pb.RequestReplayInfo(
replay_data=replay_data))
@property
def status(self):
return self._client.status
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/proto_diff.py | pysc2/lib/proto_diff.py | # Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Diff proto objects returning paths to changed attributes."""
import deepdiff
from google.protobuf import json_format
_ARRAY_PLACEHOLDER = "*"
class ProtoPath(object):
"""Path to a proto field, from the root of the proto object."""
def __init__(self, path):
"""Initializer.
Args:
path: Tuple of attribute names / array indices on the path to a field.
"""
self._path = tuple(path)
def get_field(self, proto):
"""Returns field at this proto path, in the specified proto."""
value = proto
for k in self._path:
if isinstance(k, int):
value = value[k]
else:
value = getattr(value, k)
return value
def with_anonymous_array_indices(self):
"""Path with array indices replaced with '*' so that they compare equal."""
return ProtoPath(
tuple(_ARRAY_PLACEHOLDER if isinstance(t, int) else t
for t in self._path))
@property
def path(self):
return self._path
def __lt__(self, other):
for k1, k2 in zip(self._path, other.path):
if k1 < k2:
return True
elif k1 > k2:
return False
return len(self._path) < len(other.path)
def __getitem__(self, item):
return self._path.__getitem__(item)
def __len__(self):
return len(self._path)
def __eq__(self, o):
return self._path == o.path
def __hash__(self):
return hash(self._path)
def __repr__(self):
result = ""
for k in self._path:
if isinstance(k, int) or k == _ARRAY_PLACEHOLDER:
result += "[{}]".format(k)
else:
result += ("." if result else "") + k
return result
class ProtoDiffs(object):
"""Summary of diffs between two protos."""
def __init__(self, proto_a, proto_b, changed, added, removed):
"""Initializer.
Args:
proto_a: First proto.
proto_b: Second proto.
changed: List of paths to attributes which changed between the two.
added: List of paths to attributes added from proto_a -> proto_b.
removed: List of paths to attributes removed from proto_a -> proto_b.
"""
self._proto_a = proto_a
self._proto_b = proto_b
self._changed = sorted(changed)
self._added = sorted(added)
self._removed = sorted(removed)
@property
def proto_a(self):
return self._proto_a
@property
def proto_b(self):
return self._proto_b
@property
def changed(self):
return self._changed
@property
def added(self):
return self._added
@property
def removed(self):
return self._removed
def all_diffs(self):
return self.changed + self.added + self.removed
def report(self, differencers=None, truncate_to=0):
"""Returns a string report of diffs.
Additions and removals are identified by proto path. Changes in value are
reported as path: old_value -> new_value by default, though this can be
customized via the differencers argument.
Args:
differencers: Iterable of callable(path, proto_a, proto_b) -> str or None
If a string is returned it is used to represent the diff between
path.get_field(proto_a) and path.get_field(proto_b), and no further
differencers are invoked. If None is returned by all differencers, the
default string diff is used.
truncate_to: Number of characters to truncate diff output values to.
Zero, the default, means no truncation.
"""
results = []
for a in self._added:
results.append("Added {}.".format(a))
for r in self._removed:
results.append("Removed {}.".format(r))
for c in self._changed:
result = None
if differencers:
for d in differencers:
result = d(c, self._proto_a, self._proto_b)
if result:
break
if not result:
result = "{} -> {}".format(
_truncate(c.get_field(self._proto_a), truncate_to),
_truncate(c.get_field(self._proto_b), truncate_to))
else:
result = _truncate(result, truncate_to)
results.append("Changed {}: {}.".format(c, result))
if results:
return "\n".join(results)
else:
return "No diffs."
def __repr__(self):
return "changed: {}, added: {}, removed: {}".format(
self._changed, self._added, self._removed)
def _truncate(val, truncate_to):
string_val = str(val)
if truncate_to and len(string_val) > truncate_to:
return string_val[:max(truncate_to - 3, 0)] + "..."
else:
return string_val
def _dict_path_to_proto_path(dict_path):
dict_path = dict_path[5:-1] # strip off 'root[...]'
keys = dict_path.split("][") # tokenize
return ProtoPath(
(k[1:-1] if k[0] == "'" else int(k)) for k in keys) # key or idx
def compute_diff(proto_a, proto_b):
"""Returns `ProtoDiff` of two protos, else None if no diffs.
Args:
proto_a: First of the two protos to compare.
proto_b: Second of the two protos to compare.
"""
dict1 = json_format.MessageToDict(proto_a, preserving_proto_field_name=True)
dict2 = json_format.MessageToDict(proto_b, preserving_proto_field_name=True)
diff = deepdiff.DeepDiff(dict1, dict2, significant_digits=3)
if diff:
changed_paths = []
for key in diff.pop("values_changed", []):
changed_paths.append(_dict_path_to_proto_path(key))
added_paths = []
for key in diff.pop("dictionary_item_added", []):
added_paths.append(_dict_path_to_proto_path(key))
for key in diff.pop("iterable_item_added", []):
added_paths.append(_dict_path_to_proto_path(key))
removed_paths = []
for key in diff.pop("dictionary_item_removed", []):
removed_paths.append(_dict_path_to_proto_path(key))
for key in diff.pop("iterable_item_removed", []):
removed_paths.append(_dict_path_to_proto_path(key))
if diff:
raise ValueError("Unhandled diffs: {}".format(diff))
return ProtoDiffs(
proto_a=proto_a,
proto_b=proto_b,
changed=changed_paths,
added=added_paths,
removed=removed_paths)
else:
return None
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/stopwatch.py | pysc2/lib/stopwatch.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A stopwatch to check how much time is used by bits of code."""
import collections
import functools
import math
import os
import sys
import threading
import time
class Stat(object):
"""A set of statistics about a single value series."""
__slots__ = ("num", "min", "max", "sum", "sum_sq")
def __init__(self):
self.reset()
def reset(self):
self.num = 0
self.min = 1000000000
self.max = 0
self.sum = 0
self.sum_sq = 0
def add(self, val):
self.num += 1
if self.min > val:
self.min = val
if self.max < val:
self.max = val
self.sum += val
self.sum_sq += val**2
@property
def avg(self):
return 0 if self.num == 0 else self.sum / self.num
@property
def dev(self):
"""Standard deviation."""
if self.num == 0:
return 0
return math.sqrt(max(0, self.sum_sq / self.num - (self.sum / self.num)**2))
def merge(self, other):
self.num += other.num
self.min = min(self.min, other.min)
self.max = max(self.max, other.max)
self.sum += other.sum
self.sum_sq += other.sum_sq
@staticmethod
def build(summation, average, standard_deviation, minimum, maximum, number):
stat = Stat()
if number > 0:
stat.num = number
stat.min = minimum
stat.max = maximum
stat.sum = summation
stat.sum_sq = number * (standard_deviation**2 + average**2)
return stat
@staticmethod
def parse(s):
if s == "num=0":
return Stat()
parts = (float(p.split(":")[1]) for p in s.split(", "))
return Stat.build(*parts)
def __str__(self):
if self.num == 0:
return "num=0"
return "sum: %.4f, avg: %.4f, dev: %.4f, min: %.4f, max: %.4f, num: %d" % (
self.sum, self.avg, self.dev, self.min, self.max, self.num)
class StopWatchContext(object):
"""Time an individual call."""
__slots__ = ("_sw", "_start")
def __init__(self, stopwatch, name):
self._sw = stopwatch
self._sw.push(name)
def __enter__(self):
self._start = time.time()
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback):
self._sw.add(self._sw.pop(), time.time() - self._start)
class TracingStopWatchContext(StopWatchContext):
"""Time an individual call, but also output all the enter/exit calls."""
def __enter__(self):
super(TracingStopWatchContext, self).__enter__()
self._log(">>> %s" % self._sw.cur_stack())
def __exit__(self, *args, **kwargs):
self._log("<<< %s: %.6f secs" % (self._sw.cur_stack(),
time.time() - self._start))
super(TracingStopWatchContext, self).__exit__(*args, **kwargs)
def _log(self, s):
print(s, file=sys.stderr)
class FakeStopWatchContext(object):
"""A fake stopwatch context for when the stopwatch is too slow or unneeded."""
__slots__ = ()
def __enter__(self):
pass
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback):
pass
fake_context = FakeStopWatchContext()
class StopWatch(object):
"""A context manager that tracks call count and latency, and other stats.
Usage:
sw = stopwatch.Stopwatch()
with sw("foo"):
foo()
with sw("bar"):
bar()
@sw.decorate
def func():
pass
func()
print(sw)
"""
__slots__ = ("_times", "_local", "_factory")
def __init__(self, enabled=True, trace=False):
self._times = collections.defaultdict(Stat)
self._local = threading.local()
if trace:
self.trace()
elif enabled:
self.enable()
else:
self.disable()
def disable(self):
self._factory = lambda _: fake_context
def enable(self):
self._factory = lambda name: StopWatchContext(self, name)
def trace(self):
self._factory = lambda name: TracingStopWatchContext(self, name)
def custom(self, factory):
self._factory = factory
def __call__(self, name):
return self._factory(name)
def decorate(self, name_or_func):
"""Decorate a function/method to check its timings.
To use the function's name:
@sw.decorate
def func():
pass
To name it explicitly:
@sw.decorate("name")
def random_func_name():
pass
Args:
name_or_func: the name or the function to decorate.
Returns:
If a name is passed, returns this as a decorator, otherwise returns the
decorated function.
"""
if os.environ.get("SC2_NO_STOPWATCH"):
return name_or_func if callable(name_or_func) else lambda func: func
def decorator(name, func):
@functools.wraps(func)
def _stopwatch(*args, **kwargs):
with self(name):
return func(*args, **kwargs)
return _stopwatch
if callable(name_or_func):
return decorator(name_or_func.__name__, name_or_func)
else:
return lambda func: decorator(name_or_func, func)
def push(self, name):
try:
self._local.stack.append(name)
except AttributeError:
# Using an exception is faster than using hasattr.
self._local.stack = [name]
def pop(self):
stack = self._local.stack
ret = ".".join(stack)
stack.pop()
return ret
def cur_stack(self):
return ".".join(self._local.stack)
def clear(self):
self._times.clear()
def add(self, name, duration):
self._times[name].add(duration)
def __getitem__(self, name):
return self._times[name]
@property
def times(self):
return self._times
def merge(self, other):
for k, v in other.times.items():
self._times[k].merge(v)
@staticmethod
def parse(s):
"""Parse the output below to create a new StopWatch."""
stopwatch = StopWatch()
for line in s.splitlines():
if line.strip():
parts = line.split(None)
name = parts[0]
if name != "%": # ie not the header line
rest = (float(v) for v in parts[2:])
stopwatch.times[parts[0]].merge(Stat.build(*rest))
return stopwatch
def str(self, threshold=0.1):
"""Return a string representation of the timings."""
if not self._times:
return ""
total = sum(s.sum for k, s in self._times.items() if "." not in k)
table = [["", "% total", "sum", "avg", "dev", "min", "max", "num"]]
for k, v in sorted(self._times.items()):
percent = 100 * v.sum / (total or 1)
if percent > threshold: # ignore anything below the threshold
table.append([
k,
"%.2f%%" % percent,
"%.4f" % v.sum,
"%.4f" % v.avg,
"%.4f" % v.dev,
"%.4f" % v.min,
"%.4f" % v.max,
"%d" % v.num,
])
col_widths = [max(len(row[i]) for row in table)
for i in range(len(table[0]))]
out = ""
for row in table:
out += " " + row[0].ljust(col_widths[0]) + " "
out += " ".join(
val.rjust(width) for val, width in zip(row[1:], col_widths[1:]))
out += "\n"
return out
def __str__(self):
return self.str()
# Global stopwatch is disabled by default to not incur the performance hit if
# it's not wanted.
sw = StopWatch(enabled=False)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/renderer_human.py | pysc2/lib/renderer_human.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A viewer for starcraft observations/replays."""
import collections
import ctypes
import enum
import functools
import itertools
import math
import os
import platform
import queue
import re
import subprocess
import threading
import time
from absl import logging
import numpy as np
import pygame
from pysc2.lib import buffs
from pysc2.lib import colors
from pysc2.lib import features
from pysc2.lib import memoize
from pysc2.lib import point
from pysc2.lib import remote_controller
from pysc2.lib import stopwatch
from pysc2.lib import transform
from pysc2.lib import video_writer
from s2clientprotocol import error_pb2 as sc_err
from s2clientprotocol import raw_pb2 as sc_raw
from s2clientprotocol import sc2api_pb2 as sc_pb
from s2clientprotocol import spatial_pb2 as sc_spatial
from s2clientprotocol import ui_pb2 as sc_ui
# Disable attribute-error because of the multiple stages of initialization for
# RendererHuman.
# pytype: disable=attribute-error
sw = stopwatch.sw
render_lock = threading.Lock() # Serialize all window/render operations.
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
def clamp(n, smallest, largest):
return max(smallest, min(n, largest))
class MouseButtons(enum.IntEnum):
# https://www.pygame.org/docs/ref/mouse.html
LEFT = 1
MIDDLE = 2
RIGHT = 3
WHEEL_UP = 4
WHEEL_DOWN = 5
class SurfType(enum.IntEnum):
"""Used to tell what a mouse click refers to."""
CHROME = 1 # ie help, feature layer titles, etc
SCREEN = 2
MINIMAP = 4
FEATURE = 8
RGB = 16
class ActionCmd(enum.Enum):
STEP = 1
RESTART = 2
QUIT = 3
class _Ability(collections.namedtuple("_Ability", [
"ability_id", "name", "footprint_radius", "requires_point", "hotkey"])):
"""Hold the specifics of available abilities."""
def __new__(cls, ability, static_data):
specific_data = static_data[ability.ability_id]
if specific_data.remaps_to_ability_id:
general_data = static_data[specific_data.remaps_to_ability_id]
else:
general_data = specific_data
return super(_Ability, cls).__new__(
cls,
ability_id=general_data.ability_id,
name=(general_data.friendly_name or general_data.button_name or
general_data.link_name),
footprint_radius=general_data.footprint_radius,
requires_point=ability.requires_point,
hotkey=specific_data.hotkey)
class _Surface(object):
"""A surface to display on screen."""
def __init__(self, surf, surf_type, surf_rect, world_to_surf, world_to_obs,
draw):
"""A surface to display on screen.
Args:
surf: The actual pygame.Surface (or subsurface).
surf_type: A SurfType, used to tell how to treat clicks in that area.
surf_rect: Rect of the surface relative to the window.
world_to_surf: Convert a world point to a pixel on the surface.
world_to_obs: Convert a world point to a pixel in the observation.
draw: A function that draws onto the surface.
"""
self.surf = surf
self.surf_type = surf_type
self.surf_rect = surf_rect
self.world_to_surf = world_to_surf
self.world_to_obs = world_to_obs
self.draw = draw
def draw_line(self, color, start_loc, end_loc, thickness=1):
"""Draw a line using world coordinates and thickness."""
pygame.draw.line(self.surf, color,
self.world_to_surf.fwd_pt(start_loc).round(),
self.world_to_surf.fwd_pt(end_loc).round(),
max(1, thickness))
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)
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, color, center, radius,
thickness if thickness < radius else 0)
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)
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)
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)
def write_world(self, font, color, world_loc, text):
text_surf = font.render(text, True, color)
rect = text_surf.get_rect()
rect.center = self.world_to_surf.fwd_pt(world_loc)
self.surf.blit(text_surf, rect)
class MousePos(collections.namedtuple("MousePos", ["world_pos", "surf"])):
"""Holds the mouse position in world coordinates and the surf it came from."""
__slots__ = ()
@property
def surf_pos(self):
return self.surf.world_to_surf.fwd_pt(self.world_pos)
@property
def obs_pos(self):
return self.surf.world_to_obs.fwd_pt(self.world_pos)
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)
class PastAction(collections.namedtuple("PastAction", [
"ability", "color", "pos", "time", "deadline"])):
"""Holds a past action for drawing over time."""
@memoize.memoize
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: # 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)
def circle_mask(shape, pt, radius):
# ogrid is confusing but seems to be the best way to generate a circle mask.
# http://docs.scipy.org/doc/numpy/reference/generated/numpy.ogrid.html
# http://stackoverflow.com/questions/8647024/how-to-apply-a-disc-shaped-mask-to-a-numpy-array
y, x = np.ogrid[-pt.y:shape.y - pt.y, -pt.x:shape.x - pt.x]
# <= is important as radius will often come in as 0 due to rounding.
return x**2 + y**2 <= radius**2
# 在模块级别添加变量
global_surf_screen = None
class RendererHuman(object):
"""Render starcraft obs with pygame such that it's playable by humans."""
camera_actions = { # camera moves by 3 world units.
pygame.K_LEFT: point.Point(-3, 0),
pygame.K_RIGHT: point.Point(3, 0),
pygame.K_UP: point.Point(0, 3),
pygame.K_DOWN: point.Point(0, -3),
}
cmd_group_keys = {
pygame.K_0: 0,
pygame.K_1: 1,
pygame.K_2: 2,
pygame.K_3: 3,
pygame.K_4: 4,
pygame.K_5: 5,
pygame.K_6: 6,
pygame.K_7: 7,
pygame.K_8: 8,
pygame.K_9: 9,
}
shortcuts = [
("F1", "Select idle worker"),
("F2", "Select army"),
("F3", "Select larva (zerg) or warp gates (protoss)"),
("F4", "Quit the game"),
("F5", "Restart the map"),
("F8", "Save a replay"),
("F9", "Toggle RGB rendering"),
("F10", "Toggle rendering the player_relative layer."),
("F11", "Toggle synchronous rendering"),
("F12", "Toggle raw/feature layer actions"),
("Ctrl++", "Zoom in"),
("Ctrl+-", "Zoom out"),
("PgUp/PgDn", "Increase/decrease the max game speed"),
("Ctrl+PgUp/PgDn", "Increase/decrease the step multiplier"),
("Pause", "Pause the game"),
("?", "This help screen"),
]
upgrade_colors = [
colors.black, # unused...
colors.white * 0.6,
colors.white * 0.8,
colors.white,
]
def __init__(self, fps=22.4, step_mul=1, render_sync=False,
render_feature_grid=True, video=None):
"""Create a renderer for use by humans.
Make sure to call `init` with the game info, or just use `run`.
Args:
fps: How fast should the game be run.
step_mul: How many game steps to take per observation.
render_sync: Whether to wait for the obs to render before continuing.
render_feature_grid: When RGB and feature layers are available, whether
to render the grid of feature layers.
video: A filename to write the video to. Implicitly enables render_sync.
"""
self._fps = fps
self._step_mul = step_mul
self._render_sync = render_sync or bool(video)
self._raw_actions = False
self._render_player_relative = False
self._render_rgb = None
self._render_feature_grid = render_feature_grid
self._window = None
self._window_scale = 0.75
self._obs_queue = queue.Queue()
self._render_thread = threading.Thread(target=self.render_thread,
name="Renderer")
self._render_thread.start()
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._video_writer = video_writer.VideoWriter(video, fps) if video else None
def close(self):
if self._obs_queue:
self._obs_queue.put(None)
self._render_thread.join()
self._obs_queue = None
self._render_thread = None
if self._video_writer:
self._video_writer.close()
self._video_writer = None
def init(self, game_info, static_data):
"""Take the game info and the static data needed to set up the game.
This must be called before render or get_actions for each game or restart.
Args:
game_info: A `sc_pb.ResponseGameInfo` object for this game.
static_data: A `StaticData` object for this game.
Raises:
ValueError: if there is nothing to render.
"""
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)
self._playable = point.Rect(
point.Point.build(game_info.start_raw.playable_area.p0),
point.Point.build(game_info.start_raw.playable_area.p1))
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
if not fl_opts.crop_to_playable_area:
self._playable = point.Rect(self._map_size)
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
self._last_zoom_time = 0
@with_lock(render_lock)
@sw.decorate
def init_window(self):
"""Initialize the pygame window and lay out the surfaces."""
if platform.system() == "Windows":
# Enable DPI awareness on Windows to give the correct window size.
ctypes.windll.user32.SetProcessDPIAware() # pytype: disable=module-attr
pygame.init()
if self._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
num_feature_layers = 0
if self._render_feature_grid:
# Want a roughly square grid of feature layers, each being roughly square.
if self._game_info.options.raw:
num_feature_layers += 5
if self._feature_screen_px:
num_feature_layers += len(features.SCREEN_FEATURES)
num_feature_layers += len(features.MINIMAP_FEATURES)
if num_feature_layers > 0:
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(
_get_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._playable.diagonal.max_dim())
world_tl_to_feature_minimap.offset = world_tl_to_feature_minimap.fwd_pt(
-self._world_to_world_tl.fwd_pt(self._playable.bl))
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())
# These are confusing since self._playable is in world coords which is
# (bl <= tr), but stored in a Rect that is (tl <= br).
check_eq(self._world_to_feature_minimap.fwd_pt(self._playable.bl),
point.Point(0, 0))
check_eq(self._world_to_feature_minimap.fwd_pt(self._playable.tr),
self._playable.diagonal.scale_max_size(self._feature_minimap_px))
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._playable.diagonal.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 layer main screen
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.max_dim() / self._feature_minimap_px.max_dim())
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._render_feature_grid and num_feature_layers > 0:
# Add the raw and 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 = point.Point(1, 1).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_layer(surf_type, world_to_surf, world_to_obs, name, fn):
"""Add a layer surface."""
i = next(feature_counter)
grid_offset = point.Point(i % feature_cols,
i // feature_cols) * feature_grid_size
text = feature_font.render(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).round(),
world_to_surf, world_to_obs, fn)
raw_world_to_obs = transform.Linear()
raw_world_to_surf = transform.Linear(feature_layer_size / self._map_size)
def add_raw_layer(from_obs, name, color):
add_layer(SurfType.FEATURE | SurfType.MINIMAP,
raw_world_to_surf, raw_world_to_obs, "raw " + name,
lambda surf: self.draw_raw_layer(surf, from_obs, name, color))
if self._game_info.options.raw:
add_raw_layer(False, "terrain_height", colors.height_map(256))
add_raw_layer(False, "pathing_grid", colors.winter(2))
add_raw_layer(False, "placement_grid", colors.winter(2))
add_raw_layer(True, "visibility", colors.VISIBILITY_PALETTE)
add_raw_layer(True, "creep", colors.CREEP_PALETTE)
def add_feature_layer(feature, surf_type, world_to_surf, world_to_obs):
add_layer(surf_type, world_to_surf, world_to_obs, feature.full_name,
lambda surf: self.draw_feature_layer(surf, feature))
if self._feature_minimap_px:
# 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)
if self._feature_screen_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)
def _update_camera(self, camera_center):
"""Update the camera transform based on the new camera center."""
self._world_tl_to_world_camera_rel.offset = (
-self._world_to_world_tl.fwd_pt(camera_center) *
self._world_tl_to_world_camera_rel.scale)
if self._feature_screen_px:
camera_radius = (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))
def zoom(self, factor):
"""Zoom the window in/out."""
self._window_scale *= factor
if time.time() - self._last_zoom_time < 1:
# Avoid a deadlock in pygame if you zoom too quickly.
time.sleep(time.time() - self._last_zoom_time)
self.init_window()
self._last_zoom_time = time.time()
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)
def clear_queued_action(self):
self._queued_hotkey = ""
self._queued_action = None
def save_replay(self, run_config, controller):
if controller.status in (remote_controller.Status.in_game,
remote_controller.Status.ended):
prefix, _ = os.path.splitext(
os.path.basename(self._game_info.local_map_path))
replay_path = run_config.save_replay(
controller.save_replay(), "local", prefix)
print("Wrote replay to:", replay_path)
@sw.decorate
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_F9: # 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_F11: # Toggle synchronous rendering.
self._render_sync = not self._render_sync
print("Rendering", self._render_sync and "Sync" or "Async")
elif event.key == pygame.K_F12:
self._raw_actions = not self._raw_actions
print("Action space:", self._raw_actions and "Raw" or "Spatial")
elif event.key == pygame.K_F10: # Toggle player_relative layer.
self._render_player_relative = not self._render_player_relative
elif event.key == pygame.K_F8: # 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:
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | true |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/units.py | pysc2/lib/units.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the static list of units for SC2. Generated by bin/gen_data.py."""
import enum
# pylint: disable=invalid-name
class Neutral(enum.IntEnum):
"""Neutral units."""
BattleStationMineralField = 886
BattleStationMineralField750 = 887
CarrionBird = 322
CleaningBot = 612
CollapsibleRockTower = 609
CollapsibleRockTowerDebris = 490
CollapsibleRockTowerDebrisRampLeft = 518
CollapsibleRockTowerDebrisRampRight = 517
CollapsibleRockTowerDiagonal = 588
CollapsibleRockTowerPushUnit = 561
CollapsibleRockTowerPushUnitRampLeft = 564
CollapsibleRockTowerPushUnitRampRight = 563
CollapsibleRockTowerRampLeft = 664
CollapsibleRockTowerRampRight = 663
CollapsibleTerranTower = 610
CollapsibleTerranTowerDebris = 485
CollapsibleTerranTowerDiagonal = 589
CollapsibleTerranTowerPushUnit = 562
CollapsibleTerranTowerPushUnitRampLeft = 559
CollapsibleTerranTowerPushUnitRampRight = 560
CollapsibleTerranTowerRampLeft = 590
CollapsibleTerranTowerRampRight = 591
Crabeetle = 662
Debris2x2NonConjoined = 475
DebrisRampLeft = 486
DebrisRampRight = 487
DestructibleBillboardTall = 350
DestructibleCityDebris4x4 = 628
DestructibleCityDebris6x6 = 629
DestructibleCityDebrisHugeDiagonalBLUR = 630
DestructibleDebris4x4 = 364
DestructibleDebris6x6 = 365
DestructibleDebrisRampDiagonalHugeBLUR = 377
DestructibleDebrisRampDiagonalHugeULBR = 376
DestructibleIce4x4 = 648
DestructibleIce6x6 = 649
DestructibleIceDiagonalHugeBLUR = 651
DestructibleRampDiagonalHugeBLUR = 373
DestructibleRampDiagonalHugeULBR = 372
DestructibleRock6x6 = 371
DestructibleRockEx14x4 = 638
DestructibleRockEx16x6 = 639
DestructibleRockEx1DiagonalHugeBLUR = 641
DestructibleRockEx1DiagonalHugeULBR = 640
DestructibleRockEx1HorizontalHuge = 643
DestructibleRockEx1VerticalHuge = 642
Dog = 336
InhibitorZoneMedium = 1958
InhibitorZoneSmall = 1957
KarakFemale = 324
LabBot = 661
LabMineralField = 665
LabMineralField750 = 666
Lyote = 321
MineralField = 341
MineralField450 = 1961
MineralField750 = 483
ProtossVespeneGeyser = 608
PurifierMineralField = 884
PurifierMineralField750 = 885
PurifierRichMineralField = 796
PurifierRichMineralField750 = 797
PurifierVespeneGeyser = 880
ReptileCrate = 877
RichMineralField = 146
RichMineralField750 = 147
RichVespeneGeyser = 344
Scantipede = 335
ShakurasVespeneGeyser = 881
SpacePlatformGeyser = 343
UnbuildableBricksDestructible = 473
UnbuildablePlatesDestructible = 474
UnbuildableRocksDestructible = 472
UtilityBot = 330
VespeneGeyser = 342
XelNagaDestructibleBlocker8NE = 1904
XelNagaDestructibleBlocker8SW = 1908
XelNagaTower = 149
class Protoss(enum.IntEnum):
"""Protoss units."""
Adept = 311
AdeptPhaseShift = 801
Archon = 141
Assimilator = 61
AssimilatorRich = 1955
Carrier = 79
Colossus = 4
CyberneticsCore = 72
DarkShrine = 69
DarkTemplar = 76
Disruptor = 694
DisruptorPhased = 733
FleetBeacon = 64
ForceField = 135
Forge = 63
Gateway = 62
HighTemplar = 75
Immortal = 83
Interceptor = 85
Mothership = 10
MothershipCore = 488
Nexus = 59
Observer = 82
ObserverSurveillanceMode = 1911
Oracle = 495
Phoenix = 78
PhotonCannon = 66
Probe = 84
Pylon = 60
PylonOvercharged = 894
RoboticsBay = 70
RoboticsFacility = 71
Sentry = 77
ShieldBattery = 1910
Stalker = 74
Stargate = 67
StasisTrap = 732
Tempest = 496
TemplarArchive = 68
TwilightCouncil = 65
VoidRay = 80
WarpGate = 133
WarpPrism = 81
WarpPrismPhasing = 136
Zealot = 73
class Terran(enum.IntEnum):
"""Terran units."""
Armory = 29
AutoTurret = 31
Banshee = 55
Barracks = 21
BarracksFlying = 46
BarracksReactor = 38
BarracksTechLab = 37
Battlecruiser = 57
Bunker = 24
CommandCenter = 18
CommandCenterFlying = 36
Cyclone = 692
EngineeringBay = 22
Factory = 27
FactoryFlying = 43
FactoryReactor = 40
FactoryTechLab = 39
FusionCore = 30
Ghost = 50
GhostAcademy = 26
GhostAlternate = 144
GhostNova = 145
Hellion = 53
Hellbat = 484
KD8Charge = 830
Liberator = 689
LiberatorAG = 734
MULE = 268
Marauder = 51
Marine = 48
Medivac = 54
MissileTurret = 23
Nuke = 58
OrbitalCommand = 132
OrbitalCommandFlying = 134
PlanetaryFortress = 130
PointDefenseDrone = 11
Raven = 56
Reactor = 6
Reaper = 49
Refinery = 20
RefineryRich = 1960
RepairDrone = 1913
SCV = 45
SensorTower = 25
SiegeTank = 33
SiegeTankSieged = 32
Starport = 28
StarportFlying = 44
StarportReactor = 42
StarportTechLab = 41
SupplyDepot = 19
SupplyDepotLowered = 47
TechLab = 5
Thor = 52
ThorHighImpactMode = 691
VikingAssault = 34
VikingFighter = 35
WidowMine = 498
WidowMineBurrowed = 500
class Zerg(enum.IntEnum):
"""Zerg units."""
Baneling = 9
BanelingBurrowed = 115
BanelingCocoon = 8
BanelingNest = 96
BroodLord = 114
BroodLordCocoon = 113
Broodling = 289
BroodlingEscort = 143
Changeling = 12
ChangelingMarine = 15
ChangelingMarineShield = 14
ChangelingZealot = 13
ChangelingZergling = 17
ChangelingZerglingWings = 16
Cocoon = 103
Corruptor = 112
CreepTumor = 87
CreepTumorBurrowed = 137
CreepTumorQueen = 138
Drone = 104
DroneBurrowed = 116
EvolutionChamber = 90
Extractor = 88
ExtractorRich = 1956
GreaterSpire = 102
Hatchery = 86
Hive = 101
Hydralisk = 107
HydraliskBurrowed = 117
HydraliskDen = 91
InfestationPit = 94
InfestedTerran = 7
InfestedTerranBurrowed = 120
InfestedTerranCocoon = 150
Infestor = 111
InfestorBurrowed = 127
Lair = 100
Larva = 151
Locust = 489
LocustFlying = 693
Lurker = 502
LurkerBurrowed = 503
LurkerDen = 504
LurkerCocoon = 501
Mutalisk = 108
NydusCanal = 142
NydusNetwork = 95
Overlord = 106
OverlordTransport = 893
OverlordTransportCocoon = 892
Overseer = 129
OverseerCocoon = 128
OverseerOversightMode = 1912
ParasiticBombDummy = 824
Queen = 126
QueenBurrowed = 125
Ravager = 688
RavagerBurrowed = 690
RavagerCocoon = 687
Roach = 110
RoachBurrowed = 118
RoachWarren = 97
SpawningPool = 89
SpineCrawler = 98
SpineCrawlerUprooted = 139
Spire = 92
SporeCrawler = 99
SporeCrawlerUprooted = 140
SwarmHost = 494
SwarmHostBurrowed = 493
Ultralisk = 109
UltraliskBurrowed = 131
UltraliskCavern = 93
Viper = 499
Zergling = 105
ZerglingBurrowed = 119
def get_unit_type(unit_id):
for race in (Neutral, Protoss, Terran, Zerg):
try:
return race(unit_id)
except ValueError:
pass # Wrong race.
if __name__ == "__main__":
print(Protoss(311))
print(str(get_unit_type(311)))
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/resources.py | pysc2/lib/resources.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This replaces google's resources used for locating data deps."""
def GetResourceFilename(path):
return path
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/run_parallel.py | pysc2/lib/run_parallel.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A thread pool for running a set of functions synchronously in parallel.
This is mainly intended for use where the functions have a barrier and none will
return until all have been called.
"""
from concurrent import futures
import functools
class RunParallel(object):
"""Run all funcs in parallel."""
def __init__(self, timeout=None):
self._timeout = timeout
self._executor = None
self._workers = 0
def run(self, funcs):
"""Run a set of functions in parallel, returning their results.
Make sure any function you pass exits with a reasonable timeout. If it
doesn't return within the timeout or the result is ignored due an exception
in a separate thread it will continue to stick around until it finishes,
including blocking process exit.
Args:
funcs: An iterable of functions or iterable of args to functools.partial.
Returns:
A list of return values with the values matching the order in funcs.
Raises:
Propagates the first exception encountered in one of the functions.
"""
funcs = [f if callable(f) else functools.partial(*f) for f in funcs]
if len(funcs) == 1: # Ignore threads if it's not needed.
return [funcs[0]()]
if len(funcs) > self._workers: # Lazy init and grow as needed.
self.shutdown()
self._workers = len(funcs)
while True:
try:
# Temporary workaround for "<frozen importlib._bootstrap>", line 110.
# Race condition on import of ThreadPoolExecutor.
self._executor = futures.ThreadPoolExecutor(self._workers)
break
except KeyError:
pass
futs = [self._executor.submit(f) for f in funcs]
done, not_done = futures.wait(futs, self._timeout, futures.FIRST_EXCEPTION)
# Make sure to propagate any exceptions.
for f in done:
if not f.cancelled() and f.exception() is not None:
if not_done:
# If there are some calls that haven't finished, cancel and recreate
# the thread pool. Otherwise we may have a thread running forever
# blocking parallel calls.
for nd in not_done:
nd.cancel()
self.shutdown(False) # Don't wait, they may be deadlocked.
raise f.exception()
# Either done or timed out, so don't wait again.
return [f.result(timeout=0) for f in futs]
def shutdown(self, wait=True):
if self._executor:
self._executor.shutdown(wait)
self._executor = None
self._workers = 0
def __del__(self):
self.shutdown()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/image_differencer_test.py | pysc2/lib/image_differencer_test.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for image_differencer.py."""
from absl.testing import absltest
import numpy as np
from pysc2.lib import image_differencer
from pysc2.lib import proto_diff
from s2clientprotocol import common_pb2
from s2clientprotocol import sc2api_pb2 as sc_pb
from s2clientprotocol import spatial_pb2
class ImageDifferencerTest(absltest.TestCase):
def testFilteredOut(self):
result = image_differencer.image_differencer(
path=proto_diff.ProtoPath(("observation", "actions", 1)),
proto_a=None,
proto_b=None)
self.assertIsNone(result)
def testFilteredIn(self):
a = sc_pb.ResponseObservation(
observation=sc_pb.Observation(
feature_layer_data=spatial_pb2.ObservationFeatureLayer(
renders=spatial_pb2.FeatureLayers(
height_map=common_pb2.ImageData(
bits_per_pixel=32,
size=common_pb2.Size2DI(x=4, y=4),
data=np.array([[0, 0, 0, 0],
[1, 0, 1, 0],
[0, 0, 0, 1],
[1, 1, 1, 1]], dtype=np.int32).tobytes()
)
)
)))
b = sc_pb.ResponseObservation(
observation=sc_pb.Observation(
feature_layer_data=spatial_pb2.ObservationFeatureLayer(
renders=spatial_pb2.FeatureLayers(
height_map=common_pb2.ImageData(
bits_per_pixel=32,
size=common_pb2.Size2DI(x=4, y=4),
data=np.array([[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 1],
[1, 1, 1, 0]], dtype=np.int32).tobytes()
)
)
)))
result = image_differencer.image_differencer(
path=proto_diff.ProtoPath((
"observation",
"feature_layer_data",
"renders",
"height_map",
"data")),
proto_a=a,
proto_b=b)
self.assertEqual(
result,
"3 element(s) changed - [1][0]: 1 -> 0; [1][1]: 0 -> 1; [3][3]: 1 -> 0")
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/renderer_ascii.py | pysc2/lib/renderer_ascii.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Give a crude ascii rendering of the feature_screen."""
from pysc2.lib import units
def get_printable_unit_types():
"""Generate the list of printable unit type characters."""
types = {
units.Protoss.Assimilator: "a",
units.Protoss.Probe: "p",
units.Protoss.Stalker: "s",
units.Terran.SCV: "s",
units.Terran.Marine: "m",
units.Terran.SupplyDepot: "D",
units.Terran.SupplyDepotLowered: "D",
}
substrings = {
"MineralField": "$",
"VespeneGeyser": "&",
"Collapsible": "@",
"Debris": "@",
"Destructible": "@",
"Rock": "@",
}
for name, unit_type in units.Neutral.__members__.items():
for substring, char in substrings.items():
if substring in name:
types[unit_type] = char
for race in (units.Protoss, units.Terran, units.Zerg):
for name, unit_type in race.__members__.items():
if unit_type not in types:
types[unit_type] = name[0]
return types
_printable_unit_types = get_printable_unit_types()
VISIBILITY = "#+." # Fogged, seen, visible.
PLAYER_RELATIVE = ".SANE" # self, allied, neutral, enemy.
def _summary(obs, view, width):
s = " %s: p%s; step: %s; money: %s, %s; food: %s/%s " % (
view, obs.player.player_id, obs.game_loop[0], obs.player.minerals,
obs.player.vespene, obs.player.food_used, obs.player.food_cap)
return s.center(max(len(s) + 6, width), "-")
def screen(obs):
"""Give a crude ascii rendering of feature_screen."""
unit_type = obs.feature_screen.unit_type
selected = obs.feature_screen.selected
visibility = obs.feature_screen.visibility_map
max_y, max_x = unit_type.shape
out = _summary(obs, "screen", max_y * 2) + "\n"
for y in range(max_y):
started = False
for x in range(max_x):
s = selected[y, x]
u = unit_type[y, x]
v = visibility[y, x]
if started and not s:
out += ")"
elif not started and s:
out += "("
else:
out += " "
if u:
out += _printable_unit_types.get(u, str(u))
else:
out += VISIBILITY[v]
started = s
if started:
out += ")"
out += "\n"
return out
def minimap(obs):
"""Give a crude ascii rendering of feature_minimap."""
player = obs.feature_minimap.player_relative
selected = obs.feature_minimap.selected
visibility = obs.feature_minimap.visibility_map
max_y, max_x = visibility.shape
out = _summary(obs, "minimap", max_y * 2) + "\n"
for y in range(max_y):
started = False
for x in range(max_x):
s = selected[y, x]
p = player[y, x]
v = visibility[y, x]
if started and not s:
out += ")"
elif not started and s:
out += "("
else:
out += " "
if v:
out += PLAYER_RELATIVE[p]
else:
out += VISIBILITY[v]
started = s
if started:
out += ")"
out += "\n"
return out
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/point_test.py | pysc2/lib/point_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the point library."""
from absl.testing import absltest
from pysc2.lib import point
class FakePoint(object):
def __init__(self):
self.x = 5
self.y = 8
class PointTest(absltest.TestCase):
def testBuild(self):
self.assertEqual(point.Point(5, 8), point.Point.build(FakePoint()))
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)
def testDist(self):
a = point.Point(1, 1)
b = point.Point(4, 5)
self.assertEqual(5, a.dist(b))
def testDistSq(self):
a = point.Point(1, 1)
b = point.Point(4, 5)
self.assertEqual(25, a.dist_sq(b))
def testLen(self):
p = point.Point(3, 4)
self.assertEqual(5, p.len())
def testScale(self):
p = point.Point(3, 4)
self.assertAlmostEqual(2, p.scale(2).len())
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)))
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)))
def testMinDim(self):
self.assertEqual(5, point.Point(5, 10).min_dim())
def testMaxDim(self):
self.assertEqual(10, point.Point(5, 10).max_dim())
def testTranspose(self):
self.assertEqual(point.Point(4, 3), point.Point(3, 4).transpose())
def testRound(self):
p = point.Point(1.3, 2.6).round()
self.assertEqual(point.Point(1, 3), p)
self.assertIsInstance(p.x, int)
self.assertIsInstance(p.y, int)
def testCeil(self):
p = point.Point(1.3, 2.6).ceil()
self.assertEqual(point.Point(2, 3), p)
self.assertIsInstance(p.x, int)
self.assertIsInstance(p.y, int)
def testFloor(self):
p = point.Point(1.3, 2.6).floor()
self.assertEqual(point.Point(1, 2), p)
self.assertIsInstance(p.x, int)
self.assertIsInstance(p.y, int)
def testRotate(self):
p = point.Point(0, 100)
self.assertEqual(point.Point(-100, 0), p.rotate_deg(90).round())
self.assertEqual(point.Point(100, 0), p.rotate_deg(-90).round())
self.assertEqual(point.Point(0, -100), p.rotate_deg(180).round())
def testContainedCircle(self):
self.assertTrue(point.Point(2, 2).contained_circle(point.Point(1, 1), 2))
self.assertFalse(point.Point(2, 2).contained_circle(point.Point(1, 1), 0.5))
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))
class RectTest(absltest.TestCase):
def testInit(self):
r = point.Rect(1, 2, 3, 4)
self.assertEqual(r.t, 1)
self.assertEqual(r.l, 2)
self.assertEqual(r.b, 3)
self.assertEqual(r.r, 4)
self.assertEqual(r.tl, point.Point(2, 1))
self.assertEqual(r.tr, point.Point(4, 1))
self.assertEqual(r.bl, point.Point(2, 3))
self.assertEqual(r.br, point.Point(4, 3))
def testInitBad(self):
with self.assertRaises(TypeError):
point.Rect(4, 3, 2, 1) # require t <= b, l <= r
with self.assertRaises(TypeError):
point.Rect(1)
with self.assertRaises(TypeError):
point.Rect(1, 2, 3)
with self.assertRaises(TypeError):
point.Rect()
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)
def testInitTwoPoints(self):
r = point.Rect(point.Point(1, 2), point.Point(3, 4))
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)
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)
def testArea(self):
r = point.Rect(point.Point(1, 1), point.Point(3, 4))
self.assertEqual(r.area, 6)
def testContains(self):
r = point.Rect(point.Point(1, 1), point.Point(3, 3))
self.assertTrue(r.contains_point(point.Point(2, 2)))
self.assertFalse(r.contains_circle(point.Point(2, 2), 5))
self.assertFalse(r.contains_point(point.Point(4, 4)))
self.assertFalse(r.contains_circle(point.Point(4, 4), 5))
def testIntersectsCircle(self):
r = point.Rect(point.Point(1, 1), point.Point(3, 3))
self.assertFalse(r.intersects_circle(point.Point(0, 0), 0.5))
self.assertFalse(r.intersects_circle(point.Point(0, 0), 1))
self.assertTrue(r.intersects_circle(point.Point(0, 0), 1.5))
self.assertTrue(r.intersects_circle(point.Point(0, 0), 2))
if __name__ == '__main__':
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/run_parallel_test.py | pysc2/lib/run_parallel_test.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for lib.run_parallel."""
import threading
from absl.testing import absltest
from pysc2.lib import run_parallel
class Barrier(object):
def __init__(self, n):
self.n = n
self.count = 0
self.cond = threading.Condition()
def wait(self):
self.cond.acquire()
me = self.count
self.count += 1
if self.count < self.n:
self.cond.wait()
else:
self.count = 0
self.cond.notify_all()
self.cond.release()
return me
def clear(self):
self.cond.acquire()
self.cond.notify_all()
self.cond.release()
def bad():
raise ValueError()
class RunParallelTest(absltest.TestCase):
def test_returns_expected_values(self):
pool = run_parallel.RunParallel()
out = pool.run([int])
self.assertListEqual(out, [0])
out = pool.run([lambda: 1, lambda: 2, lambda: "asdf", lambda: {1: 2}])
self.assertListEqual(out, [1, 2, "asdf", {1: 2}])
pool.shutdown()
def test_run_in_parallel(self):
b = Barrier(3)
pool = run_parallel.RunParallel()
out = pool.run([b.wait, b.wait, b.wait])
self.assertCountEqual(out, [0, 1, 2])
pool.shutdown()
def test_avoids_deadlock(self):
b = Barrier(2)
pool = run_parallel.RunParallel(timeout=2)
with self.assertRaises(ValueError):
pool.run([int, b.wait, bad])
# Release the thread waiting on the barrier so the process can exit cleanly.
b.clear()
pool.shutdown()
def test_exception(self):
pool = run_parallel.RunParallel()
out = pool.run([lambda: 1, ValueError])
self.assertEqual(out[0], 1)
self.assertIsInstance(out[1], ValueError)
with self.assertRaises(ValueError):
pool.run([bad])
with self.assertRaises(ValueError):
pool.run([int, bad])
pool.shutdown()
def test_partial(self):
pool = run_parallel.RunParallel()
out = pool.run((max, 0, i - 2) for i in range(5))
self.assertListEqual(out, [0, 0, 0, 1, 2])
pool.shutdown()
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/named_array.py | pysc2/lib/named_array.py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Named numpy arrays for easier access to the observation data.
https://docs.scipy.org/doc/numpy/user/basics.rec.html are not enough since they
actually change the type and don't interoperate well with tensorflow.
"""
import enum
import numbers
import re
import numpy as np
class NamedDict(dict):
"""A dict where you can use `d["element"]` or `d.element`."""
def __init__(self, *args, **kwargs):
super(NamedDict, self).__init__(*args, **kwargs)
self.__dict__ = self
_NULL_SLICE = slice(None, None, None)
# pylint: disable=protected-access
class NamedNumpyArray(np.ndarray):
"""A subclass of ndarray that lets you give names to indices.
This is a normal ndarray in the sense that you can always index by numbers and
slices, though elipses don't work. Also, all elements have the same type,
unlike a record array.
Names should be a list of names per dimension in the ndarray shape. The names
should be a list or tuple of strings, a namedtuple class (with names taken
from _fields), or an IntEnum. Alternatively if you don't want to give a name
to a particular dimension, use None. If your array only has one dimension, the
second level of list can be skipped.
Example usage:
a = named_array.NamedNumpyArray([1, 3, 6], ["a", "b", "c"])
a.a, a[1], a["c"] => 1, 3, 6
b = named_array.NamedNumpyArray([[1, 3], [6, 8]], [["a", "b"], None])
b.a, b[1], b["a", 1] => [1, 3], [6, 8], 3
c = named_array.NamedNumpyArray([[1, 3], [6, 8]], [None, ["a", "b"]])
c[0].a, b[1, 0], b[1, "b"] => 1, 6, 8
Look at the tests for more examples including using enums and named tuples.
"""
# Details of how to subclass an ndarray are at:
# https://docs.scipy.org/doc/numpy-1.13.0/user/basics.subclassing.html
def __new__(cls, values, names, *args, **kwargs):
obj = np.array(values, *args, **kwargs)
if len(obj.shape) == 0: # pylint: disable=g-explicit-length-test
raise ValueError("Scalar arrays are unsupported.")
if len(obj.shape) == 1:
if obj.shape[0] == 0 and names and names[0] is None:
# Support arrays of length 0.
names = [None]
else:
# Allow just a single dimension if the array is also single dimension.
try:
if len(names) > 1:
names = [names]
except TypeError: # len of a namedtuple is a TypeError
names = [names]
# Validate names!
if not isinstance(names, (list, tuple)) or len(names) != len(obj.shape):
raise ValueError(
"Names must be a list of length equal to the array shape: %s != %s." %
(len(names), len(obj.shape)))
index_names = []
only_none = obj.shape[0] > 0
for i, o in enumerate(names):
if o is None:
index_names.append(o)
else:
only_none = False
if isinstance(o, enum.EnumMeta):
for j, n in enumerate(o._member_names_):
if j != o[n]:
raise ValueError("Enum has holes or doesn't start from 0.")
o = o._member_names_
elif isinstance(o, type): # Assume namedtuple
try:
o = o._fields
except AttributeError:
raise ValueError("Bad names. Must be None, a list of strings, "
"a namedtuple, or IntEnum.")
elif isinstance(o, (list, tuple)):
for n in o:
if not isinstance(n, str):
raise ValueError(
"Bad name, must be a list of strings, not %s" % type(n))
else:
raise ValueError("Bad names. Must be None, a list of strings, "
"a namedtuple, or IntEnum.")
if obj.shape[i] != len(o):
raise ValueError(
"Wrong number of names in dimension %s. Got %s, expected %s." % (
i, len(o), obj.shape[i]))
index_names.append({n: j for j, n in enumerate(o)})
if only_none:
raise ValueError("No names given. Use a normal numpy.ndarray instead.")
# Finally convert to a NamedNumpyArray.
obj = obj.view(cls)
obj._index_names = index_names # [{name: index}, ...], dict per dimension.
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self._index_names = getattr(obj, "_index_names", None)
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError("Bad attribute name: %s" % name)
def __setattr__(self, name, value):
if name == "_index_names": # Need special handling to avoid recursion.
super(NamedNumpyArray, self).__setattr__(name, value)
else:
self.__setitem__(name, value)
def __getitem__(self, indices):
"""Get by indexing lookup."""
indices = self._indices(indices)
obj = super(NamedNumpyArray, self).__getitem__(indices)
if (isinstance(indices, np.ndarray) and len(indices.shape) > 1 and
indices.dtype == bool):
# Is this a multi-dimensional mask, eg: obj[obj == 5] ?
# Multi-dimensional masks return a single dimensional array, and it's
# unclear what it means for the result to have names, so return a normal
# numpy array.
return np.array(obj)
if isinstance(obj, np.ndarray): # If this is a view, index the names too.
if not isinstance(indices, tuple):
indices = (indices,)
new_names = []
dim = 0
for i, index in enumerate(indices):
if isinstance(index, numbers.Integral):
dim += 1 # Drop this dimension's names.
elif index is Ellipsis:
# Copy all the dimensions' names through.
end = len(self.shape) - len(indices) + i + 1
for j in range(dim, end):
new_names.append(self._index_names[j])
dim = end
elif index is np.newaxis: # Add an unnamed dimension.
new_names.append(None)
# Don't modify dim, as we're still working on the same one.
elif (self._index_names[dim] is None or
(isinstance(index, slice) and index == _NULL_SLICE)):
# Keep unnamed dimensions or ones where the slice is a no-op.
new_names.append(self._index_names[dim])
dim += 1
elif isinstance(index, (slice, list, np.ndarray)):
if isinstance(index, np.ndarray) and len(index.shape) > 1:
raise TypeError("What does it mean to index into a named array by "
"a multidimensional array? %s" % index)
# Rebuild the index of names for the various forms of slicing.
names = sorted(self._index_names[dim].items(),
key=lambda item: item[1])
names = np.array(names, dtype=object) # Support full numpy slicing.
sliced = names[index] # Actually slice it.
indexed = {n: j for j, (n, _) in enumerate(sliced)} # Reindex.
if len(sliced) != len(indexed):
# Names aren't unique, so drop the names for this dimension.
indexed = None
new_names.append(indexed)
dim += 1
else:
raise TypeError("Unknown index: %s; %s" % (type(index), index))
obj._index_names = new_names + self._index_names[dim:]
if len(obj._index_names) != len(obj.shape):
raise IndexError("Names don't match object shape: %s != %s" % (
len(obj.shape), len(obj._index_names)))
return obj
def __setitem__(self, indices, value):
super(NamedNumpyArray, self).__setitem__(self._indices(indices), value)
def __getslice__(self, i, j): # deprecated, but still needed...
# https://docs.python.org/2.0/ref/sequence-methods.html
return self[max(0, i):max(0, j):]
def __setslice__(self, i, j, seq): # deprecated, but still needed...
self[max(0, i):max(0, j):] = seq
def __repr__(self):
"""A repr, parsing the original and adding the names param."""
names = []
for dim_names in self._index_names:
if dim_names:
dim_names = [n for n, _ in sorted(dim_names.items(),
key=lambda item: item[1])]
if len(dim_names) > 11:
dim_names = dim_names[:5] + ["..."] + dim_names[-5:]
names.append(dim_names)
if len(names) == 1:
names = names[0]
# "NamedNumpyArray([1, 3, 6], dtype=int32)" ->
# ["NamedNumpyArray", "[1, 3, 6]", ", dtype=int32"]
matches = re.findall(r"^(\w+)\(([\d\., \n\[\]]*)(,\s+\w+=.+)?\)$",
np.array_repr(self))[0]
space = "\n " if matches[2] and matches[2][1] == "\n" else ""
return "%s(%s,%s %s%s)" % (
matches[0], matches[1], space, names, matches[2])
def __reduce__(self):
# Support pickling: https://stackoverflow.com/a/26599346
state = super(NamedNumpyArray, self).__reduce__() # pytype: disable=attribute-error
assert len(state) == 3 # Verify numpy hasn't changed their protocol.
return (state[0], state[1], state[2] + (self._index_names,))
def __setstate__(self, state):
# Support pickling: https://stackoverflow.com/a/26599346
self._index_names = state[-1]
super(NamedNumpyArray, self).__setstate__(state[0:-1]) # pytype: disable=attribute-error
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 + 1
elif index is np.newaxis:
out.append(None)
else:
out.append(self._get_index(dim, index))
dim += 1
return tuple(out)
else:
return self._get_index(0, indices)
def _get_index(self, dim, index):
"""Turn a string into a real index, otherwise return the index."""
if isinstance(index, str):
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
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/portspicker.py | pysc2/lib/portspicker.py | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""portpicker for multiple ports."""
import time
import portpicker
# The set of ports returned by pick_contiguous_unused_ports and not by
# the underlying portpicker.
_contiguous_ports = set()
def pick_unused_ports(num_ports, retry_interval_secs=1, retry_attempts=5):
"""Reserves and returns a list of `num_ports` unused ports."""
if num_ports <= 0:
raise ValueError("Number of ports, must be >= 1, got: %s" % num_ports)
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)
def pick_contiguous_unused_ports(
num_ports,
retry_interval_secs=1,
retry_attempts=5):
"""Reserves and returns a list of `num_ports` contiguous unused ports."""
if num_ports <= 0:
raise ValueError("Number of ports, must be >= 1, got: %s" % num_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):
_contiguous_ports.update(ports[1:])
return ports
else:
portpicker.return_port(start_port)
time.sleep(retry_interval_secs)
raise RuntimeError("Unable to obtain %d contiguous unused ports." % num_ports)
def return_ports(ports):
"""Returns previously reserved ports so that may be reused."""
for port in ports:
if port in _contiguous_ports:
_contiguous_ports.discard(port)
else:
portpicker.return_port(port)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/video_writer.py | pysc2/lib/video_writer.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gwritererning permissions and
# limitations under the License.
"""Write a video based on a numpy array."""
from skvideo import io
class VideoWriter(io.FFmpegWriter):
"""Write a video based on a numpy array.
Subclass/wrap FFmpegWriter to make it easy to switch to a different library.
"""
def __init__(self, filename, frame_rate):
super(VideoWriter, self).__init__(
filename, outputdict={"-r": str(frame_rate)})
def add(self, frame):
"""Add a frame to the video based on a numpy array."""
self.writeFrame(frame)
def __del__(self):
self.close()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/__init__.py | pysc2/lib/__init__.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/protocol.py | pysc2/lib/protocol.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Protocol library to make communication easy."""
import contextlib
import enum
import itertools
import os
import socket
import sys
import time
from absl import flags
from absl import logging
from pysc2.lib import stopwatch
import websocket
from s2clientprotocol import sc2api_pb2 as sc_pb
flags.DEFINE_integer("sc2_verbose_protocol", 0,
("Print the communication packets with SC2. 0 disables. "
"-1 means all. >0 will print that many lines per "
"packet. 20 is a good starting value."))
FLAGS = flags.FLAGS
sw = stopwatch.sw
# Create a python version of the Status enum in the proto.
Status = enum.Enum("Status", sc_pb.Status.items()) # pylint: disable=invalid-name
MAX_WIDTH = int(os.getenv("COLUMNS", "200")) # Get your TTY width.
class ConnectionError(Exception): # pylint: disable=redefined-builtin
"""Failed to read/write a message, details in the error string."""
pass
class ProtocolError(Exception): # pylint: disable=g-bad-exception-name
"""SC2 responded with an error message likely due to a bad request or bug."""
pass
@contextlib.contextmanager
def catch_websocket_connection_errors():
"""A context manager that translates websocket errors into ConnectionError."""
try:
yield
except websocket.WebSocketConnectionClosedException as e:
raise ConnectionError("Connection already closed. SC2 probably crashed. "
"Check the error log.") from e
except websocket.WebSocketTimeoutException as e:
raise ConnectionError("Websocket timed out.") from e
except socket.error as e:
raise ConnectionError("Socket error: %s" % e) from e
class StarcraftProtocol(object):
"""Defines the protocol for chatting with starcraft."""
def __init__(self, sock):
self._status = Status.launched
self._sock = sock
self._port = sock.sock.getpeername()[1]
self._count = itertools.count(1)
@property
def status(self):
return self._status
def close(self):
if self._sock:
self._sock.close()
self._sock = None
self._status = Status.quit
@sw.decorate
def read(self):
"""Read a Response, do some validation, and return it."""
if FLAGS.sc2_verbose_protocol:
self._log("-------------- [%s] Reading response --------------",
self._port)
start = time.time()
response = self._read()
if FLAGS.sc2_verbose_protocol:
self._log("-------------- [%s] Read %s in %0.1f msec --------------\n%s",
self._port, response.WhichOneof("response"),
1000 * (time.time() - start), self._packet_str(response))
if not response.HasField("status"):
raise ProtocolError("Got an incomplete response without a status.")
prev_status = self._status
self._status = Status(response.status) # pytype: disable=not-callable
if response.error:
err_str = ("Error in RPC response (likely a bug). "
"Prev status: %s, new status: %s, error:\n%s" % (
prev_status, self._status, "\n".join(response.error)))
logging.error(err_str)
raise ProtocolError(err_str)
return response
@sw.decorate
def write(self, request):
"""Write a Request."""
if FLAGS.sc2_verbose_protocol:
self._log("-------------- [%s] Writing request: %s --------------\n%s",
self._port, request.WhichOneof("request"),
self._packet_str(request))
self._write(request)
def send_req(self, request):
"""Write a pre-filled Request and return the Response."""
self.write(request)
return self.read()
def send(self, **kwargs):
"""Create and send a specific request, and return the response.
For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing
Args:
**kwargs: A single kwarg with the name and value to fill in to Request.
Returns:
The Response corresponding to your request.
Raises:
ConnectionError: if it gets a different response.
"""
assert len(kwargs) == 1, "Must make a single request."
name = list(kwargs.keys())[0]
req = sc_pb.Request(**kwargs)
req.id = next(self._count)
try:
res = self.send_req(req)
except ConnectionError as e:
raise ConnectionError("Error during %s: %s" % (name, e)) from e
if res.HasField("id") and res.id != req.id:
raise ConnectionError(
"Error during %s: Got a response with a different id" % name)
return getattr(res, name)
def _packet_str(self, packet):
"""Return a string form of this packet."""
max_lines = FLAGS.sc2_verbose_protocol
packet_str = str(packet).strip()
if max_lines <= 0:
return packet_str
lines = packet_str.split("\n")
line_count = len(lines)
lines = [line[:MAX_WIDTH] for line in lines[:max_lines + 1]]
if line_count > max_lines + 1: # +1 to prefer the last line to skipped msg.
lines[-1] = "***** %s lines skipped *****" % (line_count - max_lines)
return "\n".join(lines)
def _log(self, s, *args):
r"""Log a string. It flushes but doesn't append \n, so do that yourself."""
# TODO(tewalds): Should this be using logging.info instead? How to see them
# outside of google infrastructure?
sys.stderr.write((s + "\n") % args)
sys.stderr.flush()
def _read(self):
"""Actually read the response and parse it, returning a Response."""
with sw("read_response"):
with catch_websocket_connection_errors():
response_str = self._sock.recv()
if not response_str:
raise ProtocolError("Got an empty response from SC2.")
with sw("parse_response"):
response = sc_pb.Response.FromString(response_str)
return response
def _write(self, request):
"""Actually serialize and write the request."""
with sw("serialize_request"):
request_str = request.SerializeToString()
with sw("write_request"):
with catch_websocket_connection_errors():
self._sock.send(request_str)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/image_differencer.py | pysc2/lib/image_differencer.py | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Compare the observations from multiple binaries."""
from pysc2.lib import features
from pysc2.lib import np_util
from pysc2.lib import proto_diff
from s2clientprotocol import common_pb2
def image_differencer(path, proto_a, proto_b):
"""proto_diff differencer for PySC2 image data."""
if path[-1] == "data" and len(path) >= 2:
image_data_path = proto_diff.ProtoPath(path[:-1])
image_data_a = image_data_path.get_field(proto_a)
if isinstance(image_data_a, common_pb2.ImageData):
image_data_b = image_data_path.get_field(proto_b)
image_a = features.Feature.unpack_layer(image_data_a)
image_b = features.Feature.unpack_layer(image_data_b)
return np_util.summarize_array_diffs(image_a, image_b)
return None
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay.py | pysc2/lib/replay.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for replays."""
import io
import json
import mpyq
from pysc2.run_configs import lib as run_configs_lib
def get_replay_version(replay_data):
replay_io = io.BytesIO()
replay_io.write(replay_data)
replay_io.seek(0)
archive = mpyq.MPQArchive(replay_io).extract()
metadata = json.loads(archive[b"replay.gamemetadata.json"].decode("utf-8"))
return run_configs_lib.Version(
game_version=".".join(metadata["GameVersion"].split(".")[:-1]),
build_version=int(metadata["BaseBuild"][4:]),
data_version=metadata.get("DataVersion"), # Only in replays version 4.1+.
binary=None)
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/named_array_test.py | pysc2/lib/named_array_test.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for lib.named_array."""
import collections
import enum
import pickle
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from pysc2.lib import named_array
class NamedDictTest(absltest.TestCase):
def test_named_dict(self):
a = named_array.NamedDict(a=2, b=(1, 2))
self.assertEqual(a["a"], a.a)
self.assertEqual(a["b"], a.b)
self.assertIs(a["b"], a.b)
self.assertNotEqual(a["a"], a.b)
a.c = 3
self.assertEqual(a["c"], 3)
class TestEnum(enum.IntEnum):
a = 0
b = 1
c = 2
class BadEnum(enum.IntEnum):
a = 1
b = 2
c = 3
class TestNamedTuple(collections.namedtuple("TestNamedTuple", ["a", "b", "c"])):
pass
class BadNamedTuple(collections.namedtuple("BadNamedTuple", ["a", "b"])):
pass
class NamedArrayTest(parameterized.TestCase):
def assertArrayEqual(self, a, b):
np.testing.assert_array_equal(a, b)
@parameterized.named_parameters(
("none", None),
("none2", [None]),
("short_list", ["a"]),
("long_list", ["a", "b", "c", "d"]),
("long_list2", [["a", "b", "c", "d"]]),
("ints", [[1, "b", 3]]),
("bad_enum", [BadEnum]),
("bad_namedtuple", [BadNamedTuple]),
("dict", [{"a": 0, "b": 1, "c": 2}]),
("set", [{"a", "b", "c"}]),
)
def test_bad_names(self, names):
with self.assertRaises(ValueError):
named_array.NamedNumpyArray([1, 3, 6], names)
@parameterized.named_parameters(
("list", ["a", "b", "c"]),
("tuple", ("a", "b", "c")),
("list2", [["a", "b", "c"]]),
("tuple2", (("a", "b", "c"))),
("list_tuple", [("a", "b", "c")]),
("named_tuple", TestNamedTuple),
("named_tuple2", [TestNamedTuple]),
("int_enum", TestEnum),
("int_enum2", [TestEnum]),
)
def test_single_dimension(self, names):
a = named_array.NamedNumpyArray([1, 3, 6], names)
self.assertEqual(a[0], 1)
self.assertEqual(a[1], 3)
self.assertEqual(a[2], 6)
self.assertEqual(a[-1], 6)
self.assertEqual(a.a, 1)
self.assertEqual(a.b, 3)
self.assertEqual(a.c, 6)
with self.assertRaises(AttributeError):
a.d # pylint: disable=pointless-statement
self.assertEqual(a["a"], 1)
self.assertEqual(a["b"], 3)
self.assertEqual(a["c"], 6)
with self.assertRaises(KeyError):
a["d"] # pylint: disable=pointless-statement
# New axis = None
self.assertArrayEqual(a, [1, 3, 6])
self.assertArrayEqual(a[np.newaxis], [[1, 3, 6]])
self.assertArrayEqual(a[None], [[1, 3, 6]])
self.assertArrayEqual(a[None, :], [[1, 3, 6]])
self.assertArrayEqual(a[:, None], [[1], [3], [6]])
self.assertArrayEqual(a[None, :, None], [[[1], [3], [6]]])
self.assertArrayEqual(a[None, a % 3 == 0, None], [[[3], [6]]])
self.assertArrayEqual(a[None][None], [[[1, 3, 6]]])
self.assertArrayEqual(a[None][0], [1, 3, 6])
self.assertEqual(a[None, 0], 1)
self.assertEqual(a[None, "a"], 1)
self.assertEqual(a[None][0].a, 1)
self.assertEqual(a[None][0, "b"], 3)
# range slicing
self.assertArrayEqual(a[0:2], [1, 3])
self.assertArrayEqual(a[1:3], [3, 6])
self.assertArrayEqual(a[0:2:], [1, 3])
self.assertArrayEqual(a[0:2:1], [1, 3])
self.assertArrayEqual(a[::2], [1, 6])
self.assertArrayEqual(a[::-1], [6, 3, 1])
self.assertEqual(a[1:3][0], 3)
self.assertEqual(a[1:3].b, 3)
self.assertEqual(a[1:3].c, 6)
# list slicing
self.assertArrayEqual(a[[0, 0]], [1, 1])
self.assertArrayEqual(a[[0, 1]], [1, 3])
self.assertArrayEqual(a[[1, 0]], [3, 1])
self.assertArrayEqual(a[[1, 2]], [3, 6])
self.assertArrayEqual(a[np.array([0, 2])], [1, 6])
self.assertEqual(a[[1, 2]].b, 3)
self.assertEqual(a[[2, 0]].c, 6)
with self.assertRaises(TypeError):
# Duplicates lead to unnamed dimensions.
a[[0, 0]].a # pylint: disable=pointless-statement
a[1] = 4
self.assertEqual(a[1], 4)
self.assertEqual(a.b, 4)
self.assertEqual(a["b"], 4)
a[1:2] = 2
self.assertEqual(a[1], 2)
self.assertEqual(a.b, 2)
self.assertEqual(a["b"], 2)
a[[1]] = 3
self.assertEqual(a[1], 3)
self.assertEqual(a.b, 3)
self.assertEqual(a["b"], 3)
a.b = 5
self.assertEqual(a[1], 5)
self.assertEqual(a.b, 5)
self.assertEqual(a["b"], 5)
def test_empty_array(self):
named_array.NamedNumpyArray([], [None, ["a", "b"]])
with self.assertRaises(ValueError):
# Must be the right length.
named_array.NamedNumpyArray([], [["a", "b"]])
with self.assertRaises(ValueError):
# Returning an empty slice is not supported, and it's not clear how or
# even if it should be supported.
named_array.NamedNumpyArray([], [["a", "b"], None])
with self.assertRaises(ValueError):
# Scalar arrays are unsupported.
named_array.NamedNumpyArray(1, [])
def test_named_array_multi_first(self):
a = named_array.NamedNumpyArray([[1, 3], [6, 8]], [["a", "b"], None])
self.assertArrayEqual(a.a, [1, 3])
self.assertArrayEqual(a[1], [6, 8])
self.assertArrayEqual(a["b"], [6, 8])
self.assertArrayEqual(a[::-1], [[6, 8], [1, 3]])
self.assertArrayEqual(a[::-1][::-1], [[1, 3], [6, 8]])
self.assertArrayEqual(a[::-1, ::-1], [[8, 6], [3, 1]])
self.assertArrayEqual(a[::-1][0], [6, 8])
self.assertArrayEqual(a[::-1, 0], [6, 1])
self.assertArrayEqual(a[::-1, 1], [8, 3])
self.assertArrayEqual(a[::-1].a, [1, 3])
self.assertArrayEqual(a[::-1].a[0], 1)
self.assertArrayEqual(a[::-1].b, [6, 8])
self.assertArrayEqual(a[[0, 0]], [[1, 3], [1, 3]])
with self.assertRaises(TypeError):
a[[0, 0]].a # pylint: disable=pointless-statement
self.assertEqual(a[0, 1], 3)
self.assertEqual(a[(0, 1)], 3)
self.assertEqual(a["a", 0], 1)
self.assertEqual(a["b", 0], 6)
self.assertEqual(a["b", 1], 8)
self.assertEqual(a.a[0], 1)
self.assertArrayEqual(a[a > 2], [3, 6, 8])
self.assertArrayEqual(a[a % 3 == 0], [3, 6])
with self.assertRaises(TypeError):
a[0].a # pylint: disable=pointless-statement
# New axis = None
self.assertArrayEqual(a, [[1, 3], [6, 8]])
self.assertArrayEqual(a[np.newaxis], [[[1, 3], [6, 8]]])
self.assertArrayEqual(a[None], [[[1, 3], [6, 8]]])
self.assertArrayEqual(a[None, :], [[[1, 3], [6, 8]]])
self.assertArrayEqual(a[None, "a"], [[1, 3]])
self.assertArrayEqual(a[:, None], [[[1, 3]], [[6, 8]]])
self.assertArrayEqual(a[None, :, None], [[[[1, 3]], [[6, 8]]]])
self.assertArrayEqual(a[None, 0, None], [[[1, 3]]])
self.assertArrayEqual(a[None, "a", None], [[[1, 3]]])
self.assertArrayEqual(a[None][None], [[[[1, 3], [6, 8]]]])
self.assertArrayEqual(a[None][0], [[1, 3], [6, 8]])
self.assertArrayEqual(a[None][0].a, [1, 3])
self.assertEqual(a[None][0].a[0], 1)
self.assertEqual(a[None][0, "b", 1], 8)
def test_named_array_multi_second(self):
a = named_array.NamedNumpyArray([[1, 3], [6, 8]], [None, ["a", "b"]])
self.assertArrayEqual(a[0], [1, 3])
self.assertEqual(a[0, 1], 3)
self.assertEqual(a[0, "a"], 1)
self.assertEqual(a[0, "b"], 3)
self.assertEqual(a[1, "b"], 8)
self.assertEqual(a[0].a, 1)
self.assertArrayEqual(a[a > 2], [3, 6, 8])
self.assertArrayEqual(a[a % 3 == 0], [3, 6])
with self.assertRaises(TypeError):
a.a # pylint: disable=pointless-statement
self.assertArrayEqual(a[None, :, "a"], [[1, 6]])
def test_masking(self):
a = named_array.NamedNumpyArray([[1, 2, 3, 4], [5, 6, 7, 8]],
[None, list("abcd")])
self.assertArrayEqual(a[a > 2], [3, 4, 5, 6, 7, 8])
self.assertArrayEqual(a[a < 4], [1, 2, 3])
self.assertArrayEqual(a[a % 2 == 0], [2, 4, 6, 8])
self.assertArrayEqual(a[a % 3 == 0], [3, 6])
def test_slicing(self):
a = named_array.NamedNumpyArray([1, 2, 3, 4, 5], list("abcde"))
self.assertArrayEqual(a[:], [1, 2, 3, 4, 5])
self.assertArrayEqual(a[::], [1, 2, 3, 4, 5])
self.assertArrayEqual(a[::2], [1, 3, 5])
self.assertArrayEqual(a[::-1], [5, 4, 3, 2, 1])
self.assertEqual(a[:].a, 1)
self.assertEqual(a[::].b, 2)
self.assertEqual(a[::2].c, 3)
with self.assertRaises(AttributeError):
a[::2].d # pylint: disable=pointless-statement
self.assertEqual(a[::-1].e, 5)
self.assertArrayEqual(a[a % 2 == 0], [2, 4])
self.assertEqual(a[a % 2 == 0].b, 2)
a = named_array.NamedNumpyArray([[1, 2, 3, 4], [5, 6, 7, 8]],
[None, list("abcd")])
self.assertArrayEqual(a[:], [[1, 2, 3, 4], [5, 6, 7, 8]])
self.assertArrayEqual(a[::], [[1, 2, 3, 4], [5, 6, 7, 8]])
self.assertArrayEqual(a[:, :], [[1, 2, 3, 4], [5, 6, 7, 8]])
self.assertArrayEqual(a[:, ...], [[1, 2, 3, 4], [5, 6, 7, 8]])
self.assertArrayEqual(a[..., ::], [[1, 2, 3, 4], [5, 6, 7, 8]])
self.assertArrayEqual(a[:, ::2], [[1, 3], [5, 7]])
self.assertArrayEqual(a[::-1], [[5, 6, 7, 8], [1, 2, 3, 4]])
self.assertArrayEqual(a[..., ::-1], [[4, 3, 2, 1], [8, 7, 6, 5]])
self.assertArrayEqual(a[:, ::-1], [[4, 3, 2, 1], [8, 7, 6, 5]])
self.assertArrayEqual(a[:, ::-2], [[4, 2], [8, 6]])
self.assertArrayEqual(a[:, -2::-2], [[3, 1], [7, 5]])
self.assertArrayEqual(a[::-1, -2::-2], [[7, 5], [3, 1]])
self.assertArrayEqual(a[..., 0, 0], 1) # weird scalar arrays...
a = named_array.NamedNumpyArray(
[[[[0, 1], [2, 3]], [[4, 5], [6, 7]]],
[[[8, 9], [10, 11]], [[12, 13], [14, 15]]]],
[["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"]])
self.assertEqual(a.a.c.e.g, 0)
self.assertEqual(a.b.c.f.g, 10)
self.assertEqual(a.b.d.f.h, 15)
self.assertArrayEqual(a[0, ..., 0], [[0, 2], [4, 6]])
self.assertArrayEqual(a[0, ..., 1], [[1, 3], [5, 7]])
self.assertArrayEqual(a[0, 0, ..., 1], [1, 3])
self.assertArrayEqual(a[0, ..., 1, 1], [3, 7])
self.assertArrayEqual(a[..., 1, 1], [[3, 7], [11, 15]])
self.assertArrayEqual(a[1, 0, ...], [[8, 9], [10, 11]])
self.assertArrayEqual(a["a", ..., "g"], [[0, 2], [4, 6]])
self.assertArrayEqual(a["a", ...], [[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
self.assertArrayEqual(a[..., "g"], [[[0, 2], [4, 6]], [[8, 10], [12, 14]]])
self.assertArrayEqual(a["a", "c"], [[0, 1], [2, 3]])
self.assertArrayEqual(a["a", ...].c, [[0, 1], [2, 3]])
self.assertArrayEqual(a["a", ..., "g"].c, [0, 2])
with self.assertRaises(TypeError):
a[np.array([[0, 1], [0, 1]])] # pylint: disable=pointless-statement, expression-not-assigned
with self.assertRaises(IndexError):
a[..., 0, ...] # pylint: disable=pointless-statement
def test_string(self):
a = named_array.NamedNumpyArray([1, 3, 6], ["a", "b", "c"], dtype=np.int32)
self.assertEqual(str(a), "[1 3 6]")
self.assertEqual(repr(a), ("NamedNumpyArray([1, 3, 6], ['a', 'b', 'c'], "
"dtype=int32)"))
a = named_array.NamedNumpyArray([[1, 3], [6, 8]], [None, ["a", "b"]])
self.assertEqual(str(a), "[[1 3]\n [6 8]]")
self.assertEqual(repr(a), ("NamedNumpyArray([[1, 3],\n"
" [6, 8]], [None, ['a', 'b']])"))
a = named_array.NamedNumpyArray([[1, 3], [6, 8]], [["a", "b"], None])
self.assertEqual(str(a), "[[1 3]\n [6 8]]")
self.assertEqual(repr(a), ("NamedNumpyArray([[1, 3],\n"
" [6, 8]], [['a', 'b'], None])"))
a = named_array.NamedNumpyArray([0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[str(i) for i in range(13)], dtype=np.int32)
numpy_repr = np.array_repr(a)
if "\n" in numpy_repr: # ie numpy > 1.14
self.assertEqual(repr(a), """
NamedNumpyArray([ 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0],
['0', '1', '2', '3', '4', '...', '8', '9', '10', '11', '12'],
dtype=int32)""".strip()) # Keep the middle newlines.
else:
self.assertEqual(repr(a), (
"NamedNumpyArray("
"[ 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0], "
"['0', '1', '2', '3', '4', '...', '8', '9', '10', '11', '12'], "
"dtype=int32)")) # Note the lack of newlines.
a = named_array.NamedNumpyArray([list(range(50))] * 50,
[None, ["a%s" % i for i in range(50)]])
self.assertIn("49", str(a))
self.assertIn("49", repr(a))
self.assertIn("a4", repr(a))
self.assertIn("a49", repr(a))
a = named_array.NamedNumpyArray([list(range(50))] * 50,
[["a%s" % i for i in range(50)], None])
self.assertIn("49", str(a))
self.assertIn("49", repr(a))
self.assertIn("a4", repr(a))
self.assertIn("a49", repr(a))
def test_pickle(self):
arr = named_array.NamedNumpyArray([1, 3, 6], ["a", "b", "c"])
pickled = pickle.loads(pickle.dumps(arr))
self.assertTrue(np.all(arr == pickled))
self.assertEqual(repr(pickled),
"NamedNumpyArray([1, 3, 6], ['a', 'b', 'c'])")
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/actions.py | pysc2/lib/actions.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the static list of types and actions for SC2."""
import collections
import enum
import numbers
import numpy
from pysc2.lib import point
from s2clientprotocol import spatial_pb2 as sc_spatial
from s2clientprotocol import ui_pb2 as sc_ui
class ActionSpace(enum.Enum):
FEATURES = 1 # Act in feature layer pixel space with FUNCTIONS below.
RGB = 2 # Act in RGB pixel space with FUNCTIONS below.
RAW = 3 # Act with unit tags with RAW_FUNCTIONS below.
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_space)
def no_op(action, action_space):
del action, action_space
def move_camera(action, action_space, minimap):
"""Move the camera."""
minimap.assign_to(spatial(action, action_space).camera_move.center_minimap)
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
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.assign_to(out_rect.p1)
select.selection_add = bool(select_add)
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
def select_army(action, action_space, select_add):
"""Select the entire army."""
del action_space
action.action_ui.select_army.selection_add = select_add
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
def select_larva(action, action_space):
"""Select all larva."""
del action_space
action.action_ui.select_larva.SetInParent() # Adds the empty proto field.
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
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
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
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
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
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)
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)
def autocast(action, action_space, ability_id):
"""Toggle autocast."""
del action_space
action.action_ui.toggle_autocast.ability_id = ability_id
def raw_no_op(action):
del action
def raw_move_camera(action, world):
"""Move the camera."""
action_cmd = action.action_raw.camera_move
world.assign_to(action_cmd.center_world_space)
def llm_pysc2_move_camera(action, action_space, world):
"""Move the camera."""
action_cmd = action.action_raw.camera_move
world.assign_to(action_cmd.center_world_space)
def raw_cmd(action, ability_id, queued, unit_tags):
"""Do a raw command to another unit."""
action_cmd = action.action_raw.unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
def raw_cmd_pt(action, ability_id, queued, unit_tags, world):
"""Do a raw command to another unit towards a point."""
action_cmd = action.action_raw.unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
world.assign_to(action_cmd.target_world_space_pos)
def raw_cmd_unit(action, ability_id, queued, unit_tags,
target_unit_tag):
"""Do a raw command to another unit towards a unit."""
action_cmd = action.action_raw.unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
action_cmd.target_unit_tag = target_unit_tag
def raw_autocast(action, ability_id, unit_tags):
"""Toggle autocast."""
action_cmd = action.action_raw.toggle_autocast
action_cmd.ability_id = ability_id
if not isinstance(unit_tags, (tuple, list)):
unit_tags = [unit_tags]
action_cmd.unit_tags.extend(unit_tags)
def numpy_to_python(val):
"""Convert numpy types to their corresponding python types."""
if isinstance(val, (int, float)):
return val
if isinstance(val, str):
return val
if (isinstance(val, numpy.number) or
isinstance(val, numpy.ndarray) and not val.shape): # numpy.array(1)
return val.item()
if isinstance(val, (list, tuple, numpy.ndarray)):
return [numpy_to_python(v) for v in val]
raise ValueError("Unknown value. Type: %s, repr: %s" % (type(val), repr(val)))
class ArgumentType(collections.namedtuple(
"ArgumentType", ["id", "name", "sizes", "fn", "values", "count"])):
"""Represents a single argument type.
Attributes:
id: The argument id. This is unique.
name: The name of the argument, also unique.
sizes: The max+1 of each of the dimensions this argument takes.
fn: The function to convert the list of integers into something more
meaningful to be set in the protos to send to the game.
values: An enum representing the values this argument type could hold. None
if this isn't an enum argument type.
count: Number of valid values. Only useful for unit_tags.
"""
__slots__ = ()
def __str__(self):
return "%s/%s %s" % (self.id, self.name, list(self.sizes))
def __reduce__(self):
return self.__class__, tuple(self)
@classmethod
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, None)
return factory
@classmethod
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, None)
@classmethod
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, None)
return factory
@classmethod
def spec(cls, id_, name, sizes):
"""Create an ArgumentType to be used in ValidActions."""
return cls(id_, name, sizes, None, None, None)
@classmethod
def unit_tags(cls, count, size):
"""Create an ArgumentType with a list of unbounded ints."""
def clean(arg):
arg = numpy_to_python(arg)
if isinstance(arg, list) and len(arg) == 1 and isinstance(arg[0], list):
arg = arg[0] # Support [[list, of, tags]].
return arg[:count]
return lambda i, name: cls(i, name, (size,), clean, None, count)
class Arguments(collections.namedtuple("Arguments", [
"screen", "minimap", "screen2", "queued", "control_group_act",
"control_group_id", "select_point_act", "select_add", "select_unit_act",
"select_unit_id", "select_worker", "build_queue_id", "unload_id"])):
"""The full list of argument types.
Take a look at TYPES and FUNCTION_TYPES for more details.
Attributes:
screen: A point on the screen.
minimap: A point on the minimap.
screen2: The second point for a rectangle. This is needed so that no
function takes the same type twice.
queued: Whether the action should be done immediately or after all other
actions queued for this unit.
control_group_act: What to do with the control group.
control_group_id: Which control group to do it with.
select_point_act: What to do with the unit at the point.
select_add: Whether to add the unit to the selection or replace it.
select_unit_act: What to do when selecting a unit by id.
select_unit_id: Which unit to select by id.
select_worker: What to do when selecting a worker.
build_queue_id: Which build queue index to target.
unload_id: Which unit to target in a transport/nydus/command center.
"""
__slots__ = ()
@classmethod
def types(cls, **kwargs):
"""Create an Arguments of the possible Types."""
named = {name: factory(Arguments._fields.index(name), name)
for name, factory in kwargs.items()}
return cls(**named)
def __reduce__(self):
return self.__class__, tuple(self)
class RawArguments(collections.namedtuple("RawArguments", [
"world", "queued", "unit_tags", "target_unit_tag"])):
"""The full list of argument types.
Take a look at TYPES and FUNCTION_TYPES for more details.
Attributes:
world: A point in world coordinates
queued: Whether the action should be done immediately or after all other
actions queued for this unit.
unit_tags: Which units should execute this action.
target_unit_tag: The target unit of this action.
"""
__slots__ = ()
@classmethod
def types(cls, **kwargs):
"""Create an Arguments of the possible Types."""
named = {name: factory(RawArguments._fields.index(name), name)
for name, factory in kwargs.items()}
return cls(**named)
def __reduce__(self):
return self.__class__, tuple(self)
def _define_position_based_enum(name, options):
return enum.IntEnum(
name, {opt_name: i for i, (opt_name, _) in enumerate(options)})
QUEUED_OPTIONS = [
("now", False),
("queued", True),
]
Queued = _define_position_based_enum( # pylint: disable=invalid-name
"Queued", QUEUED_OPTIONS)
CONTROL_GROUP_ACT_OPTIONS = [
("recall", sc_ui.ActionControlGroup.Recall),
("set", sc_ui.ActionControlGroup.Set),
("append", sc_ui.ActionControlGroup.Append),
("set_and_steal", sc_ui.ActionControlGroup.SetAndSteal),
("append_and_steal", sc_ui.ActionControlGroup.AppendAndSteal),
]
ControlGroupAct = _define_position_based_enum( # pylint: disable=invalid-name
"ControlGroupAct", CONTROL_GROUP_ACT_OPTIONS)
SELECT_POINT_ACT_OPTIONS = [
("select", sc_spatial.ActionSpatialUnitSelectionPoint.Select),
("toggle", sc_spatial.ActionSpatialUnitSelectionPoint.Toggle),
("select_all_type", sc_spatial.ActionSpatialUnitSelectionPoint.AllType),
("add_all_type", sc_spatial.ActionSpatialUnitSelectionPoint.AddAllType),
]
SelectPointAct = _define_position_based_enum( # pylint: disable=invalid-name
"SelectPointAct", SELECT_POINT_ACT_OPTIONS)
SELECT_ADD_OPTIONS = [
("select", False),
("add", True),
]
SelectAdd = _define_position_based_enum( # pylint: disable=invalid-name
"SelectAdd", SELECT_ADD_OPTIONS)
SELECT_UNIT_ACT_OPTIONS = [
("select", sc_ui.ActionMultiPanel.SingleSelect),
("deselect", sc_ui.ActionMultiPanel.DeselectUnit),
("select_all_type", sc_ui.ActionMultiPanel.SelectAllOfType),
("deselect_all_type", sc_ui.ActionMultiPanel.DeselectAllOfType),
]
SelectUnitAct = _define_position_based_enum( # pylint: disable=invalid-name
"SelectUnitAct", SELECT_UNIT_ACT_OPTIONS)
SELECT_WORKER_OPTIONS = [
("select", sc_ui.ActionSelectIdleWorker.Set),
("add", sc_ui.ActionSelectIdleWorker.Add),
("select_all", sc_ui.ActionSelectIdleWorker.All),
("add_all", sc_ui.ActionSelectIdleWorker.AddAll),
]
SelectWorker = _define_position_based_enum( # pylint: disable=invalid-name
"SelectWorker", SELECT_WORKER_OPTIONS)
# The list of known types.
TYPES = Arguments.types(
screen=ArgumentType.point(),
minimap=ArgumentType.point(),
screen2=ArgumentType.point(),
queued=ArgumentType.enum(QUEUED_OPTIONS, Queued),
control_group_act=ArgumentType.enum(
CONTROL_GROUP_ACT_OPTIONS, ControlGroupAct),
control_group_id=ArgumentType.scalar(10),
select_point_act=ArgumentType.enum(
SELECT_POINT_ACT_OPTIONS, SelectPointAct),
select_add=ArgumentType.enum(SELECT_ADD_OPTIONS, SelectAdd),
select_unit_act=ArgumentType.enum(SELECT_UNIT_ACT_OPTIONS, SelectUnitAct),
select_unit_id=ArgumentType.scalar(500), # Depends on current selection.
select_worker=ArgumentType.enum(SELECT_WORKER_OPTIONS, SelectWorker),
build_queue_id=ArgumentType.scalar(10), # Depends on current build queue.
unload_id=ArgumentType.scalar(500), # Depends on the current loaded units.
)
RAW_TYPES = RawArguments.types(
world=ArgumentType.point(),
queued=ArgumentType.enum(QUEUED_OPTIONS, Queued),
unit_tags=ArgumentType.unit_tags(512, 512),
target_unit_tag=ArgumentType.unit_tags(1, 512),
)
# Which argument types do each function need?
FUNCTION_TYPES = {
no_op: [],
move_camera: [TYPES.minimap],
select_point: [TYPES.select_point_act, TYPES.screen],
select_rect: [TYPES.select_add, TYPES.screen, TYPES.screen2],
select_unit: [TYPES.select_unit_act, TYPES.select_unit_id],
control_group: [TYPES.control_group_act, TYPES.control_group_id],
select_idle_worker: [TYPES.select_worker],
select_army: [TYPES.select_add],
select_warp_gates: [TYPES.select_add],
select_larva: [],
unload: [TYPES.unload_id],
build_queue: [TYPES.build_queue_id],
cmd_quick: [TYPES.queued],
cmd_screen: [TYPES.queued, TYPES.screen],
cmd_minimap: [TYPES.queued, TYPES.minimap],
autocast: [],
raw_no_op: [],
raw_cmd: [RAW_TYPES.queued, RAW_TYPES.unit_tags],
raw_cmd_pt: [RAW_TYPES.queued, RAW_TYPES.unit_tags, RAW_TYPES.world],
raw_cmd_unit: [RAW_TYPES.queued, RAW_TYPES.unit_tags,
RAW_TYPES.target_unit_tag],
raw_move_camera: [RAW_TYPES.world],
raw_autocast: [RAW_TYPES.unit_tags],
llm_pysc2_move_camera: [RAW_TYPES.world],
}
# Which ones need an ability?
ABILITY_FUNCTIONS = {cmd_quick, cmd_screen, cmd_minimap, autocast}
RAW_ABILITY_FUNCTIONS = {raw_cmd, raw_cmd_pt, raw_cmd_unit, raw_autocast}
# Which ones require a point?
POINT_REQUIRED_FUNCS = {
False: {cmd_quick, autocast},
True: {cmd_screen, cmd_minimap, autocast}}
always = lambda _: True
class Function(collections.namedtuple(
"Function", ["id", "name", "ability_id", "general_id", "function_type",
"args", "avail_fn", "raw"])):
"""Represents a function action.
Attributes:
id: The function id, which is what the agent will use.
name: The name of the function. Should be unique.
ability_id: The ability id to pass to sc2.
general_id: 0 for normal abilities, and the ability_id of another ability if
it can be represented by a more general action.
function_type: One of the functions in FUNCTION_TYPES for how to construct
the sc2 action proto out of python types.
args: A list of the types of args passed to function_type.
avail_fn: For non-abilities, this function returns whether the function is
valid.
raw: Whether the function is raw or not.
"""
__slots__ = ()
@classmethod
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, False)
@classmethod
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, False)
@classmethod
def raw_ability(cls, id_, name, function_type, ability_id, general_id=0,
avail_fn=always):
"""Define a function represented as a game ability."""
assert function_type in RAW_ABILITY_FUNCTIONS
return cls(id_, name, ability_id, general_id, function_type,
FUNCTION_TYPES[function_type], avail_fn, True)
@classmethod
def raw_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, True)
@classmethod
def spec(cls, id_, name, args):
"""Create a Function to be used in ValidActions."""
return cls(id_, name, None, None, None, args, None, False)
def __hash__(self): # So it can go in a set().
return self.id
def __str__(self):
return self.str()
def __call__(self, *args):
"""A convenient way to create a FunctionCall from this Function."""
return FunctionCall.init_with_validation(self.id, args, raw=self.raw)
def __reduce__(self):
return self.__class__, tuple(self)
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))
class Functions(object):
"""Represents the full set of functions.
Can't use namedtuple since python3 has a limit of 255 function arguments, so
build something similar.
"""
def __init__(self, functions):
functions = sorted(functions, key=lambda f: f.id)
self._func_list = functions
self._func_dict = {f.name: f for f in functions}
if len(self._func_dict) != len(self._func_list):
raise ValueError("Function names must be unique.")
def __getattr__(self, name):
return self._func_dict[name]
def __getitem__(self, key):
if isinstance(key, numbers.Integral):
return self._func_list[key]
return self._func_dict[key]
def __getstate__(self):
# Support pickling, which otherwise conflicts with __getattr__.
return self._func_list
def __setstate__(self, functions):
# Support pickling, which otherwise conflicts with __getattr__.
self.__init__(functions)
def __iter__(self):
return iter(self._func_list)
def __len__(self):
return len(self._func_list)
def __eq__(self, other):
return self._func_list == other._func_list # pylint: disable=protected-access
# The semantic meaning of these actions can mainly be found by searching:
# http://liquipedia.net/starcraft2/ or http://starcraft.wikia.com/ .
# pylint: disable=line-too-long
_FUNCTIONS = [
Function.ui_func(0, "no_op", no_op),
Function.ui_func(1, "move_camera", move_camera),
Function.ui_func(2, "select_point", select_point),
Function.ui_func(3, "select_rect", select_rect),
Function.ui_func(4, "select_control_group", control_group),
Function.ui_func(5, "select_unit", select_unit,
lambda obs: obs.ui_data.HasField("multi")),
Function.ui_func(6, "select_idle_worker", select_idle_worker,
lambda obs: obs.player_common.idle_worker_count > 0),
Function.ui_func(7, "select_army", select_army,
lambda obs: obs.player_common.army_count > 0),
Function.ui_func(8, "select_warp_gates", select_warp_gates,
lambda obs: obs.player_common.warp_gate_count > 0),
Function.ui_func(9, "select_larva", select_larva,
lambda obs: obs.player_common.larva_count > 0),
Function.ui_func(10, "unload", unload,
lambda obs: obs.ui_data.HasField("cargo")),
Function.ui_func(11, "build_queue", build_queue,
lambda obs: obs.ui_data.HasField("production")),
# Everything below here is generated with gen_actions.py
Function.ability(12, "Attack_screen", cmd_screen, 3674),
Function.ability(13, "Attack_minimap", cmd_minimap, 3674),
Function.ability(14, "Attack_Attack_screen", cmd_screen, 23, 3674),
Function.ability(15, "Attack_Attack_minimap", cmd_minimap, 23, 3674),
Function.ability(16, "Attack_AttackBuilding_screen", cmd_screen, 2048, 3674),
Function.ability(17, "Attack_AttackBuilding_minimap", cmd_minimap, 2048, 3674),
Function.ability(555, "Attack_Battlecruiser_screen", cmd_screen, 3771, 3674),
Function.ability(556, "Attack_Battlecruiser_minimap", cmd_minimap, 3771, 3674),
Function.ability(18, "Attack_Redirect_screen", cmd_screen, 1682, 3674),
Function.ability(19, "Scan_Move_screen", cmd_screen, 19, 3674),
Function.ability(20, "Scan_Move_minimap", cmd_minimap, 19, 3674),
Function.ability(21, "Behavior_BuildingAttackOff_quick", cmd_quick, 2082),
Function.ability(22, "Behavior_BuildingAttackOn_quick", cmd_quick, 2081),
Function.ability(23, "Behavior_CloakOff_quick", cmd_quick, 3677),
Function.ability(24, "Behavior_CloakOff_Banshee_quick", cmd_quick, 393, 3677),
Function.ability(25, "Behavior_CloakOff_Ghost_quick", cmd_quick, 383, 3677),
Function.ability(26, "Behavior_CloakOn_quick", cmd_quick, 3676),
Function.ability(27, "Behavior_CloakOn_Banshee_quick", cmd_quick, 392, 3676),
Function.ability(28, "Behavior_CloakOn_Ghost_quick", cmd_quick, 382, 3676),
Function.ability(29, "Behavior_GenerateCreepOff_quick", cmd_quick, 1693),
Function.ability(30, "Behavior_GenerateCreepOn_quick", cmd_quick, 1692),
Function.ability(31, "Behavior_HoldFireOff_quick", cmd_quick, 3689),
Function.ability(32, "Behavior_HoldFireOff_Ghost_quick", cmd_quick, 38, 3689),
Function.ability(33, "Behavior_HoldFireOff_Lurker_quick", cmd_quick, 2552, 3689),
Function.ability(34, "Behavior_HoldFireOn_quick", cmd_quick, 3688),
Function.ability(35, "Behavior_HoldFireOn_Ghost_quick", cmd_quick, 36, 3688),
Function.ability(36, "Behavior_HoldFireOn_Lurker_quick", cmd_quick, 2550, 3688),
Function.ability(37, "Behavior_PulsarBeamOff_quick", cmd_quick, 2376),
Function.ability(38, "Behavior_PulsarBeamOn_quick", cmd_quick, 2375),
Function.ability(39, "Build_Armory_screen", cmd_screen, 331),
Function.ability(40, "Build_Assimilator_screen", cmd_screen, 882),
Function.ability(41, "Build_BanelingNest_screen", cmd_screen, 1162),
Function.ability(42, "Build_Barracks_screen", cmd_screen, 321),
Function.ability(43, "Build_Bunker_screen", cmd_screen, 324),
Function.ability(44, "Build_CommandCenter_screen", cmd_screen, 318),
Function.ability(45, "Build_CreepTumor_screen", cmd_screen, 3691),
Function.ability(46, "Build_CreepTumor_Queen_screen", cmd_screen, 1694, 3691),
Function.ability(47, "Build_CreepTumor_Tumor_screen", cmd_screen, 1733, 3691),
Function.ability(48, "Build_CyberneticsCore_screen", cmd_screen, 894),
Function.ability(49, "Build_DarkShrine_screen", cmd_screen, 891),
Function.ability(50, "Build_EngineeringBay_screen", cmd_screen, 322),
Function.ability(51, "Build_EvolutionChamber_screen", cmd_screen, 1156),
Function.ability(52, "Build_Extractor_screen", cmd_screen, 1154),
Function.ability(53, "Build_Factory_screen", cmd_screen, 328),
Function.ability(54, "Build_FleetBeacon_screen", cmd_screen, 885),
Function.ability(55, "Build_Forge_screen", cmd_screen, 884),
Function.ability(56, "Build_FusionCore_screen", cmd_screen, 333),
Function.ability(57, "Build_Gateway_screen", cmd_screen, 883),
Function.ability(58, "Build_GhostAcademy_screen", cmd_screen, 327),
Function.ability(59, "Build_Hatchery_screen", cmd_screen, 1152),
Function.ability(60, "Build_HydraliskDen_screen", cmd_screen, 1157),
Function.ability(61, "Build_InfestationPit_screen", cmd_screen, 1160),
Function.ability(62, "Build_Interceptors_quick", cmd_quick, 1042),
Function.ability(63, "Build_Interceptors_autocast", autocast, 1042),
Function.ability(524, "Build_LurkerDen_screen", cmd_screen, 1163),
Function.ability(64, "Build_MissileTurret_screen", cmd_screen, 323),
Function.ability(65, "Build_Nexus_screen", cmd_screen, 880),
Function.ability(66, "Build_Nuke_quick", cmd_quick, 710),
Function.ability(67, "Build_NydusNetwork_screen", cmd_screen, 1161),
Function.ability(68, "Build_NydusWorm_screen", cmd_screen, 1768),
Function.ability(69, "Build_PhotonCannon_screen", cmd_screen, 887),
Function.ability(70, "Build_Pylon_screen", cmd_screen, 881),
Function.ability(71, "Build_Reactor_quick", cmd_quick, 3683),
Function.ability(72, "Build_Reactor_screen", cmd_screen, 3683),
Function.ability(73, "Build_Reactor_Barracks_quick", cmd_quick, 422, 3683),
Function.ability(74, "Build_Reactor_Barracks_screen", cmd_screen, 422, 3683),
Function.ability(75, "Build_Reactor_Factory_quick", cmd_quick, 455, 3683),
Function.ability(76, "Build_Reactor_Factory_screen", cmd_screen, 455, 3683),
Function.ability(77, "Build_Reactor_Starport_quick", cmd_quick, 488, 3683),
Function.ability(78, "Build_Reactor_Starport_screen", cmd_screen, 488, 3683),
Function.ability(79, "Build_Refinery_screen", cmd_screen, 320),
Function.ability(80, "Build_RoachWarren_screen", cmd_screen, 1165),
Function.ability(81, "Build_RoboticsBay_screen", cmd_screen, 892),
Function.ability(82, "Build_RoboticsFacility_screen", cmd_screen, 893),
Function.ability(83, "Build_SensorTower_screen", cmd_screen, 326),
Function.ability(525, "Build_ShieldBattery_screen", cmd_screen, 895),
Function.ability(84, "Build_SpawningPool_screen", cmd_screen, 1155),
Function.ability(85, "Build_SpineCrawler_screen", cmd_screen, 1166),
Function.ability(86, "Build_Spire_screen", cmd_screen, 1158),
Function.ability(87, "Build_SporeCrawler_screen", cmd_screen, 1167),
Function.ability(88, "Build_Stargate_screen", cmd_screen, 889),
Function.ability(89, "Build_Starport_screen", cmd_screen, 329),
Function.ability(90, "Build_StasisTrap_screen", cmd_screen, 2505),
Function.ability(91, "Build_SupplyDepot_screen", cmd_screen, 319),
Function.ability(92, "Build_TechLab_quick", cmd_quick, 3682),
Function.ability(93, "Build_TechLab_screen", cmd_screen, 3682),
Function.ability(94, "Build_TechLab_Barracks_quick", cmd_quick, 421, 3682),
Function.ability(95, "Build_TechLab_Barracks_screen", cmd_screen, 421, 3682),
Function.ability(96, "Build_TechLab_Factory_quick", cmd_quick, 454, 3682),
Function.ability(97, "Build_TechLab_Factory_screen", cmd_screen, 454, 3682),
Function.ability(98, "Build_TechLab_Starport_quick", cmd_quick, 487, 3682),
Function.ability(99, "Build_TechLab_Starport_screen", cmd_screen, 487, 3682),
Function.ability(100, "Build_TemplarArchive_screen", cmd_screen, 890),
Function.ability(101, "Build_TwilightCouncil_screen", cmd_screen, 886),
Function.ability(102, "Build_UltraliskCavern_screen", cmd_screen, 1159),
Function.ability(103, "BurrowDown_quick", cmd_quick, 3661),
Function.ability(104, "BurrowDown_Baneling_quick", cmd_quick, 1374, 3661),
Function.ability(105, "BurrowDown_Drone_quick", cmd_quick, 1378, 3661),
Function.ability(106, "BurrowDown_Hydralisk_quick", cmd_quick, 1382, 3661),
Function.ability(107, "BurrowDown_Infestor_quick", cmd_quick, 1444, 3661),
Function.ability(108, "BurrowDown_InfestorTerran_quick", cmd_quick, 1394, 3661),
Function.ability(109, "BurrowDown_Lurker_quick", cmd_quick, 2108, 3661),
Function.ability(110, "BurrowDown_Queen_quick", cmd_quick, 1433, 3661),
Function.ability(111, "BurrowDown_Ravager_quick", cmd_quick, 2340, 3661),
Function.ability(112, "BurrowDown_Roach_quick", cmd_quick, 1386, 3661),
Function.ability(113, "BurrowDown_SwarmHost_quick", cmd_quick, 2014, 3661),
Function.ability(114, "BurrowDown_Ultralisk_quick", cmd_quick, 1512, 3661),
Function.ability(115, "BurrowDown_WidowMine_quick", cmd_quick, 2095, 3661),
Function.ability(116, "BurrowDown_Zergling_quick", cmd_quick, 1390, 3661),
Function.ability(117, "BurrowUp_quick", cmd_quick, 3662),
Function.ability(118, "BurrowUp_autocast", autocast, 3662),
Function.ability(119, "BurrowUp_Baneling_quick", cmd_quick, 1376, 3662),
Function.ability(120, "BurrowUp_Baneling_autocast", autocast, 1376, 3662),
Function.ability(121, "BurrowUp_Drone_quick", cmd_quick, 1380, 3662),
Function.ability(122, "BurrowUp_Hydralisk_quick", cmd_quick, 1384, 3662),
Function.ability(123, "BurrowUp_Hydralisk_autocast", autocast, 1384, 3662),
Function.ability(124, "BurrowUp_Infestor_quick", cmd_quick, 1446, 3662),
Function.ability(125, "BurrowUp_InfestorTerran_quick", cmd_quick, 1396, 3662),
Function.ability(126, "BurrowUp_InfestorTerran_autocast", autocast, 1396, 3662),
Function.ability(127, "BurrowUp_Lurker_quick", cmd_quick, 2110, 3662),
Function.ability(128, "BurrowUp_Queen_quick", cmd_quick, 1435, 3662),
Function.ability(129, "BurrowUp_Queen_autocast", autocast, 1435, 3662),
Function.ability(130, "BurrowUp_Ravager_quick", cmd_quick, 2342, 3662),
Function.ability(131, "BurrowUp_Ravager_autocast", autocast, 2342, 3662),
Function.ability(132, "BurrowUp_Roach_quick", cmd_quick, 1388, 3662),
Function.ability(133, "BurrowUp_Roach_autocast", autocast, 1388, 3662),
Function.ability(134, "BurrowUp_SwarmHost_quick", cmd_quick, 2016, 3662),
Function.ability(135, "BurrowUp_Ultralisk_quick", cmd_quick, 1514, 3662),
Function.ability(136, "BurrowUp_Ultralisk_autocast", autocast, 1514, 3662),
Function.ability(137, "BurrowUp_WidowMine_quick", cmd_quick, 2097, 3662),
Function.ability(138, "BurrowUp_Zergling_quick", cmd_quick, 1392, 3662),
Function.ability(139, "BurrowUp_Zergling_autocast", autocast, 1392, 3662),
Function.ability(140, "Cancel_quick", cmd_quick, 3659),
Function.ability(141, "Cancel_AdeptPhaseShift_quick", cmd_quick, 2594, 3659),
Function.ability(142, "Cancel_AdeptShadePhaseShift_quick", cmd_quick, 2596, 3659),
Function.ability(143, "Cancel_BarracksAddOn_quick", cmd_quick, 451, 3659),
Function.ability(144, "Cancel_BuildInProgress_quick", cmd_quick, 314, 3659),
Function.ability(145, "Cancel_CreepTumor_quick", cmd_quick, 1763, 3659),
Function.ability(146, "Cancel_FactoryAddOn_quick", cmd_quick, 484, 3659),
Function.ability(147, "Cancel_GravitonBeam_quick", cmd_quick, 174, 3659),
Function.ability(148, "Cancel_LockOn_quick", cmd_quick, 2354, 3659),
Function.ability(149, "Cancel_MorphBroodlord_quick", cmd_quick, 1373, 3659),
Function.ability(150, "Cancel_MorphGreaterSpire_quick", cmd_quick, 1221, 3659),
Function.ability(151, "Cancel_MorphHive_quick", cmd_quick, 1219, 3659),
Function.ability(152, "Cancel_MorphLair_quick", cmd_quick, 1217, 3659),
Function.ability(153, "Cancel_MorphLurker_quick", cmd_quick, 2333, 3659),
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | true |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/portspicker_test.py | pysc2/lib/portspicker_test.py | #!/usr/bin/python
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for portspicker.py."""
from absl.testing import absltest
from absl.testing import parameterized
from pysc2.lib import portspicker
class PortsTest(parameterized.TestCase):
@parameterized.parameters(range(1, 10))
def testNonContiguousReservation(self, num_ports):
reserved = portspicker.pick_unused_ports(num_ports)
self.assertLen(reserved, num_ports)
portspicker.return_ports(reserved)
@parameterized.parameters(range(2, 5))
def testContiguousReservation(self, num_ports):
reserved = portspicker.pick_contiguous_unused_ports(num_ports)
self.assertLen(reserved, num_ports)
portspicker.return_ports(reserved)
def testInvalidReservation(self):
with self.assertRaises(ValueError):
portspicker.pick_unused_ports(0)
def testInvalidContiguousReservation(self):
with self.assertRaises(ValueError):
portspicker.pick_contiguous_unused_ports(0)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/static_data.py | pysc2/lib/static_data.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Expose static data in a more useful form than the raw protos."""
class StaticData(object):
"""Expose static data in a more useful form than the raw protos."""
def __init__(self, data):
"""Takes data from RequestData."""
self._units = {u.unit_id: u.name for u in data.units}
self._unit_stats = {u.unit_id: u for u in data.units}
self._upgrades = {a.upgrade_id: a for a in data.upgrades}
self._abilities = {a.ability_id: a for a in data.abilities}
self._general_abilities = {a.remaps_to_ability_id
for a in data.abilities
if a.remaps_to_ability_id}
for a in self._abilities.values():
a.hotkey = a.hotkey.lower()
@property
def abilities(self):
return self._abilities
@property
def upgrades(self):
return self._upgrades
@property
def units(self):
return self._units
@property
def unit_stats(self):
return self._unit_stats
@property
def general_abilities(self):
return self._general_abilities
# List of used/available abilities found by parsing replays.
ABILITIES = [
1, 4, 6, 7, 16, 17, 18, 19, 23, 26, 28, 30, 32, 36, 38, 42, 44, 46, 74, 76,
78, 80, 110, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162,
164, 166, 167, 169, 171, 173, 174, 181, 195, 199, 203, 207, 211, 212, 216,
217, 247, 249, 250, 251, 253, 255, 261, 263, 265, 295, 296, 298, 299, 304,
305, 306, 307, 308, 309, 312, 313, 314, 315, 316, 318, 319, 320, 321, 322,
323, 324, 326, 327, 328, 329, 331, 333, 348, 380, 382, 383, 386, 388, 390,
392, 393, 394, 396, 397, 399, 401, 403, 405, 407, 408, 410, 413, 415, 416,
417, 419, 421, 422, 451, 452, 454, 455, 484, 485, 487, 488, 517, 518, 520,
522, 524, 554, 556, 558, 560, 561, 562, 563, 591, 594, 595, 596, 597, 614,
620, 621, 622, 623, 624, 626, 650, 651, 652, 653, 654, 655, 656, 657, 658,
710, 730, 731, 732, 761, 764, 766, 768, 769, 790, 793, 799, 803, 804, 805,
820, 822, 855, 856, 857, 861, 862, 863, 864, 865, 866, 880, 881, 882, 883,
884, 885, 886, 887, 889, 890, 891, 892, 893, 894, 895, 911, 913, 914, 916,
917, 919, 920, 921, 922, 946, 948, 950, 954, 955, 976, 977, 978, 979, 994,
1006, 1036, 1038, 1039, 1042, 1062, 1063, 1064, 1065, 1066, 1067, 1068,
1069, 1070, 1093, 1094, 1097, 1126, 1152, 1154, 1155, 1156, 1157, 1158,
1159, 1160, 1161, 1162, 1163, 1165, 1166, 1167, 1183, 1184, 1186, 1187,
1188, 1189, 1190, 1191, 1192, 1193, 1194, 1216, 1217, 1218, 1219, 1220,
1221, 1223, 1225, 1252, 1253, 1282, 1283, 1312, 1313, 1314, 1315, 1316,
1317, 1342, 1343, 1344, 1345, 1346, 1348, 1351, 1352, 1353, 1354, 1356,
1372, 1373, 1374, 1376, 1378, 1380, 1382, 1384, 1386, 1388, 1390, 1392,
1394, 1396, 1406, 1408, 1409, 1413, 1414, 1416, 1417, 1418, 1419, 1433,
1435, 1437, 1438, 1440, 1442, 1444, 1446, 1448, 1449, 1450, 1451, 1454,
1455, 1482, 1512, 1514, 1516, 1517, 1518, 1520, 1522, 1524, 1526, 1528,
1530, 1532, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1592, 1593, 1594,
1622, 1623, 1628, 1632, 1664, 1682, 1683, 1684, 1691, 1692, 1693, 1694,
1725, 1727, 1729, 1730, 1731, 1732, 1733, 1763, 1764, 1766, 1768, 1819,
1825, 1831, 1832, 1833, 1834, 1847, 1848, 1853, 1974, 1978, 1998, 2014,
2016, 2048, 2057, 2063, 2067, 2073, 2081, 2082, 2095, 2097, 2099, 2108,
2110, 2112, 2113, 2114, 2116, 2146, 2162, 2244, 2324, 2328, 2330, 2331,
2332, 2333, 2338, 2340, 2342, 2346, 2350, 2354, 2358, 2362, 2364, 2365,
2368, 2370, 2371, 2373, 2375, 2376, 2387, 2389, 2391, 2393, 2505, 2535,
2542, 2544, 2550, 2552, 2558, 2560, 2588, 2594, 2596, 2700, 2704, 2708,
2709, 2714, 2720, 3707, 3709, 3739, 3741, 3743, 3745, 3747, 3749, 3751,
3753, 3755, 3757, 3765, 3771, 3776, 3777, 3778, 3783,
]
# List of known unit types. It is generated by parsing replays and from:
# https://github.com/Blizzard/s2client-api/blob/master/include/sc2api/sc2_typeenums.h
UNIT_TYPES = [
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 125, 126, 127, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 149,
150, 151, 268, 289, 311, 321, 322, 324, 330, 335, 336, 341, 342, 343, 344,
350, 364, 365, 371, 372, 373, 376, 377, 472, 473, 474, 475, 483, 484, 485,
486, 487, 488, 489, 490, 493, 494, 495, 496, 498, 499, 500, 501, 502, 503,
504, 517, 518, 559, 560, 561, 562, 563, 564, 588, 589, 590, 591, 608, 609,
610, 612, 628, 629, 630, 638, 639, 640, 641, 642, 643, 648, 649, 651, 661,
662, 663, 664, 665, 666, 687, 688, 689, 690, 691, 692, 693, 694, 732, 733,
734, 796, 797, 801, 824, 830, 877, 880, 881, 884, 885, 886, 887, 892, 893,
894, 1904, 1908, 1910, 1911, 1912, 1913, 1955, 1956, 1957, 1958, 1960, 1961,
]
# List of used buffs found by parsing replays.
BUFFS = [
5, 6, 7, 8, 11, 12, 13, 16, 17, 18, 22, 24, 25, 27, 28, 29, 30, 33, 36, 38,
49, 59, 83, 89, 99, 102, 116, 121, 122, 129, 132, 133, 134, 136, 137, 145,
271, 272, 273, 274, 275, 277, 279, 280, 281, 288, 289,
]
# List of used upgrades found by parsing replays.
UPGRADES = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 19, 20, 22, 25, 30,
31, 32, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74,
75, 76, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 99, 101, 116, 117, 118, 122,
130, 134, 135, 136, 139, 140, 141, 144, 289, 291, 293, 296,
]
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/features.py | pysc2/lib/features.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Render feature layers from SC2 Observation protos into numpy arrays."""
# pylint: disable=g-complex-comprehension
import collections
import enum
import random
from absl import logging
import numpy as np
from pysc2.lib import actions
from pysc2.lib import colors
from pysc2.lib import named_array
from pysc2.lib import point
from pysc2.lib import static_data
from pysc2.lib import stopwatch
from pysc2.lib import transform
from s2clientprotocol import raw_pb2 as sc_raw
from s2clientprotocol import sc2api_pb2 as sc_pb
sw = stopwatch.sw
EPSILON = 1e-5
class FeatureType(enum.Enum):
SCALAR = 1
CATEGORICAL = 2
class PlayerRelative(enum.IntEnum):
"""The values for the `player_relative` feature layers."""
NONE = 0
SELF = 1
ALLY = 2
NEUTRAL = 3
ENEMY = 4
class Visibility(enum.IntEnum):
"""Values for the `visibility` feature layers."""
HIDDEN = 0
SEEN = 1
VISIBLE = 2
class Effects(enum.IntEnum):
"""Values for the `effects` feature layer."""
# pylint: disable=invalid-name
none = 0
PsiStorm = 1
GuardianShield = 2
TemporalFieldGrowing = 3
TemporalField = 4
ThermalLance = 5
ScannerSweep = 6
NukeDot = 7
LiberatorDefenderZoneSetup = 8
LiberatorDefenderZone = 9
BlindingCloud = 10
CorrosiveBile = 11
LurkerSpines = 12
# pylint: enable=invalid-name
class ScoreCumulative(enum.IntEnum):
"""Indices into the `score_cumulative` observation."""
score = 0
idle_production_time = 1
idle_worker_time = 2
total_value_units = 3
total_value_structures = 4
killed_value_units = 5
killed_value_structures = 6
collected_minerals = 7
collected_vespene = 8
collection_rate_minerals = 9
collection_rate_vespene = 10
spent_minerals = 11
spent_vespene = 12
class ScoreByCategory(enum.IntEnum):
"""Indices for the `score_by_category` observation's first dimension."""
food_used = 0
killed_minerals = 1
killed_vespene = 2
lost_minerals = 3
lost_vespene = 4
friendly_fire_minerals = 5
friendly_fire_vespene = 6
used_minerals = 7
used_vespene = 8
total_used_minerals = 9
total_used_vespene = 10
class ScoreCategories(enum.IntEnum):
"""Indices for the `score_by_category` observation's second dimension."""
none = 0
army = 1
economy = 2
technology = 3
upgrade = 4
class ScoreByVital(enum.IntEnum):
"""Indices for the `score_by_vital` observation's first dimension."""
total_damage_dealt = 0
total_damage_taken = 1
total_healed = 2
class ScoreVitals(enum.IntEnum):
"""Indices for the `score_by_vital` observation's second dimension."""
life = 0
shields = 1
energy = 2
class Player(enum.IntEnum):
"""Indices into the `player` observation."""
player_id = 0
minerals = 1
vespene = 2
food_used = 3
food_cap = 4
food_army = 5
food_workers = 6
idle_worker_count = 7
army_count = 8
warp_gate_count = 9
larva_count = 10
class UnitLayer(enum.IntEnum):
"""Indices into the unit layers in the observations."""
unit_type = 0
player_relative = 1
health = 2
shields = 3
energy = 4
transport_slots_taken = 5
build_progress = 6
class UnitCounts(enum.IntEnum):
"""Indices into the `unit_counts` observations."""
unit_type = 0
count = 1
class FeatureUnit(enum.IntEnum):
"""Indices for the `feature_unit` observations."""
unit_type = 0
alliance = 1
health = 2
shield = 3
energy = 4
cargo_space_taken = 5
build_progress = 6
health_ratio = 7
shield_ratio = 8
energy_ratio = 9
display_type = 10
owner = 11
x = 12
y = 13
facing = 14
radius = 15
cloak = 16
is_selected = 17
is_blip = 18
is_powered = 19
mineral_contents = 20
vespene_contents = 21
cargo_space_max = 22
assigned_harvesters = 23
ideal_harvesters = 24
weapon_cooldown = 25
order_length = 26 # If zero, the unit is idle.
order_id_0 = 27
order_id_1 = 28
tag = 29 # Unique identifier for a unit (only populated for raw units).
hallucination = 30
buff_id_0 = 31
buff_id_1 = 32
addon_unit_type = 33
active = 34
is_on_screen = 35
order_progress_0 = 36
order_progress_1 = 37
order_id_2 = 38
order_id_3 = 39
is_in_cargo = 40
buff_duration_remain = 41
buff_duration_max = 42
attack_upgrade_level = 43
armor_upgrade_level = 44
shield_upgrade_level = 45
class EffectPos(enum.IntEnum):
"""Positions of the active effects."""
effect = 0
alliance = 1
owner = 2
radius = 3
x = 4
y = 5
class Radar(enum.IntEnum):
"""Positions of the Sensor towers."""
x = 0
y = 1
radius = 2
class ProductionQueue(enum.IntEnum):
"""Indices for the `production_queue` observations."""
ability_id = 0
build_progress = 1
class Feature(collections.namedtuple(
"Feature", ["index", "name", "layer_set", "full_name", "scale", "type",
"palette", "clip"])):
"""Define properties of a feature layer.
Attributes:
index: Index of this layer into the set of layers.
name: The name of the layer within the set.
layer_set: Which set of feature layers to look at in the observation proto.
full_name: The full name including for visualization.
scale: Max value (+1) of this layer, used to scale the values.
type: A FeatureType for scalar vs categorical.
palette: A color palette for rendering.
clip: Whether to clip the values for coloring.
"""
__slots__ = ()
dtypes = {
1: np.uint8,
8: np.uint8,
16: np.uint16,
32: np.int32,
}
def unpack(self, obs):
"""Return a correctly shaped numpy array for this feature."""
planes = getattr(obs.feature_layer_data, self.layer_set)
plane = getattr(planes, self.name)
return self.unpack_layer(plane)
@staticmethod
@sw.decorate
def unpack_layer(plane):
"""Return a correctly shaped numpy array given the feature layer bytes."""
size = point.Point.build(plane.size)
if size == (0, 0):
# New layer that isn't implemented in this SC2 version.
return None
data = np.frombuffer(plane.data, dtype=Feature.dtypes[plane.bits_per_pixel])
if plane.bits_per_pixel == 1:
data = np.unpackbits(data)
if data.shape[0] != size.x * size.y:
# This could happen if the correct length isn't a multiple of 8, leading
# to some padding bits at the end of the string which are incorrectly
# interpreted as data.
data = data[:size.x * size.y]
return data.reshape(size.y, size.x)
@staticmethod
@sw.decorate
def unpack_rgb_image(plane):
"""Return a correctly shaped numpy array given the image bytes."""
assert plane.bits_per_pixel == 24, "{} != 24".format(plane.bits_per_pixel)
size = point.Point.build(plane.size)
data = np.frombuffer(plane.data, dtype=np.uint8)
return data.reshape(size.y, size.x, 3)
@sw.decorate
def color(self, plane):
if self.clip:
plane = np.clip(plane, 0, self.scale - 1)
return self.palette[plane]
class ScreenFeatures(collections.namedtuple("ScreenFeatures", [
"height_map", "visibility_map", "creep", "power", "player_id",
"player_relative", "unit_type", "selected", "unit_hit_points",
"unit_hit_points_ratio", "unit_energy", "unit_energy_ratio", "unit_shields",
"unit_shields_ratio", "unit_density", "unit_density_aa", "effects",
"hallucinations", "cloaked", "blip", "buffs", "buff_duration", "active",
"build_progress", "pathable", "buildable", "placeholder"])):
"""The set of screen feature layers."""
__slots__ = ()
def __new__(cls, **kwargs):
feats = {}
for name, (scale, type_, palette, clip) in kwargs.items():
feats[name] = Feature(
index=ScreenFeatures._fields.index(name),
name=name,
layer_set="renders",
full_name="screen " + name,
scale=scale,
type=type_,
palette=palette(scale) if callable(palette) else palette,
clip=clip)
return super(ScreenFeatures, cls).__new__(cls, **feats) # pytype: disable=missing-parameter
class MinimapFeatures(collections.namedtuple("MinimapFeatures", [
"height_map", "visibility_map", "creep", "camera", "player_id",
"player_relative", "selected", "unit_type", "alerts", "pathable",
"buildable"])):
"""The set of minimap feature layers."""
__slots__ = ()
def __new__(cls, **kwargs):
feats = {}
for name, (scale, type_, palette) in kwargs.items():
feats[name] = Feature(
index=MinimapFeatures._fields.index(name),
name=name,
layer_set="minimap_renders",
full_name="minimap " + name,
scale=scale,
type=type_,
palette=palette(scale) if callable(palette) else palette,
clip=False)
return super(MinimapFeatures, cls).__new__(cls, **feats) # pytype: disable=missing-parameter
SCREEN_FEATURES = ScreenFeatures(
height_map=(256, FeatureType.SCALAR, colors.height_map, False),
visibility_map=(4, FeatureType.CATEGORICAL,
colors.VISIBILITY_PALETTE, False),
creep=(2, FeatureType.CATEGORICAL, colors.CREEP_PALETTE, False),
power=(2, FeatureType.CATEGORICAL, colors.POWER_PALETTE, False),
player_id=(17, FeatureType.CATEGORICAL,
colors.PLAYER_ABSOLUTE_PALETTE, False),
player_relative=(5, FeatureType.CATEGORICAL,
colors.PLAYER_RELATIVE_PALETTE, False),
unit_type=(max(static_data.UNIT_TYPES) + 1, FeatureType.CATEGORICAL,
colors.unit_type, False),
selected=(2, FeatureType.CATEGORICAL, colors.SELECTED_PALETTE, False),
unit_hit_points=(1600, FeatureType.SCALAR, colors.hot, True),
unit_hit_points_ratio=(256, FeatureType.SCALAR, colors.hot, False),
unit_energy=(1000, FeatureType.SCALAR, colors.hot, True),
unit_energy_ratio=(256, FeatureType.SCALAR, colors.hot, False),
unit_shields=(1000, FeatureType.SCALAR, colors.hot, True),
unit_shields_ratio=(256, FeatureType.SCALAR, colors.hot, False),
unit_density=(16, FeatureType.SCALAR, colors.hot, True),
unit_density_aa=(256, FeatureType.SCALAR, colors.hot, False),
effects=(16, FeatureType.CATEGORICAL, colors.effects, False),
hallucinations=(2, FeatureType.CATEGORICAL, colors.POWER_PALETTE, False),
cloaked=(2, FeatureType.CATEGORICAL, colors.POWER_PALETTE, False),
blip=(2, FeatureType.CATEGORICAL, colors.POWER_PALETTE, False),
buffs=(max(static_data.BUFFS) + 1, FeatureType.CATEGORICAL,
colors.buffs, False),
buff_duration=(256, FeatureType.SCALAR, colors.hot, False),
active=(2, FeatureType.CATEGORICAL, colors.POWER_PALETTE, False),
build_progress=(256, FeatureType.SCALAR, colors.hot, False),
pathable=(2, FeatureType.CATEGORICAL, colors.winter, False),
buildable=(2, FeatureType.CATEGORICAL, colors.winter, False),
placeholder=(2, FeatureType.CATEGORICAL, colors.winter, False),
)
MINIMAP_FEATURES = MinimapFeatures(
height_map=(256, FeatureType.SCALAR, colors.height_map),
visibility_map=(4, FeatureType.CATEGORICAL, colors.VISIBILITY_PALETTE),
creep=(2, FeatureType.CATEGORICAL, colors.CREEP_PALETTE),
camera=(2, FeatureType.CATEGORICAL, colors.CAMERA_PALETTE),
player_id=(17, FeatureType.CATEGORICAL, colors.PLAYER_ABSOLUTE_PALETTE),
player_relative=(5, FeatureType.CATEGORICAL,
colors.PLAYER_RELATIVE_PALETTE),
selected=(2, FeatureType.CATEGORICAL, colors.winter),
unit_type=(max(static_data.UNIT_TYPES) + 1, FeatureType.CATEGORICAL,
colors.unit_type),
alerts=(2, FeatureType.CATEGORICAL, colors.winter),
pathable=(2, FeatureType.CATEGORICAL, colors.winter),
buildable=(2, FeatureType.CATEGORICAL, colors.winter),
)
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)
class Dimensions(object):
"""Screen and minimap dimensions configuration.
Both screen and minimap must be specified. Sizes must be positive.
Screen size must be greater than or equal to minimap size in both dimensions.
Attributes:
screen: A (width, height) int tuple or a single int to be used for both.
minimap: A (width, height) int tuple or a single int to be used for both.
"""
def __init__(self, screen=None, minimap=None):
if not screen or not minimap:
raise ValueError(
"screen and minimap must both be set, screen={}, minimap={}".format(
screen, minimap))
self._screen = _to_point(screen)
self._minimap = _to_point(minimap)
@property
def screen(self):
return self._screen
@property
def minimap(self):
return self._minimap
def __repr__(self):
return "Dimensions(screen={}, minimap={})".format(self.screen, self.minimap)
def __eq__(self, other):
return (isinstance(other, Dimensions) and self.screen == other.screen and
self.minimap == other.minimap)
def __ne__(self, other):
return not self == other
class AgentInterfaceFormat(object):
"""Observation and action interface format specific to a particular agent."""
def __init__(
self,
feature_dimensions=None,
rgb_dimensions=None,
raw_resolution=None,
action_space=None,
camera_width_world_units=None,
use_feature_units=False,
use_raw_units=False,
use_raw_actions=False,
max_raw_actions=512,
max_selected_units=30,
use_unit_counts=False,
use_camera_position=False,
show_cloaked=False,
show_burrowed_shadows=False,
show_placeholders=False,
hide_specific_actions=True,
action_delay_fn=None,
send_observation_proto=False,
crop_to_playable_area=False,
raw_crop_to_playable_area=False,
allow_cheating_layers=False,
add_cargo_to_units=False):
"""Initializer.
Args:
feature_dimensions: Feature layer `Dimension`s. Either this or
rgb_dimensions (or both) must be set.
rgb_dimensions: RGB `Dimension`. Either this or feature_dimensions
(or both) must be set.
raw_resolution: Discretize the `raw_units` observation's x,y to this
resolution. Default is the map_size.
action_space: If you pass both feature and rgb sizes, then you must also
specify which you want to use for your actions as an ActionSpace enum.
camera_width_world_units: The width of your screen in world units. If your
feature_dimensions.screen=(64, 48) and camera_width is 24, then each
px represents 24 / 64 = 0.375 world units in each of x and y.
It'll then represent a camera of size (24, 0.375 * 48) = (24, 18)
world units.
use_feature_units: Whether to include feature_unit observations.
use_raw_units: Whether to include raw unit data in observations. This
differs from feature_units because it includes units outside the
screen and hidden units, and because unit positions are given in
terms of world units instead of screen units.
use_raw_actions: [bool] Whether to use raw actions as the interface.
Same as specifying action_space=ActionSpace.RAW.
max_raw_actions: [int] Maximum number of raw actions
max_selected_units: [int] The maximum number of selected units in the
raw interface.
use_unit_counts: Whether to include unit_counts observation. Disabled by
default since it gives information outside the visible area.
use_camera_position: Whether to include the camera's position (in minimap
coordinates) in the observations.
show_cloaked: Whether to show limited information for cloaked units.
show_burrowed_shadows: Whether to show limited information for burrowed
units that leave a shadow on the ground (ie widow mines and moving
roaches and infestors).
show_placeholders: Whether to show buildings that are queued for
construction.
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.
action_delay_fn: A callable which when invoked returns a delay in game
loops to apply to a requested action. Defaults to None, meaning no
delays are added (actions will be executed on the next game loop,
hence with the minimum delay of 1).
send_observation_proto: Whether or not to send the raw observation
response proto in the observations.
crop_to_playable_area: Crop the feature layer minimap observations down
from the full map area to just the playable area. Also improves the
heightmap rendering.
raw_crop_to_playable_area: Crop the raw units to the playable area. This
means units will show up closer to the origin with less dead space
around their valid locations.
allow_cheating_layers: Show the unit types and potentially other cheating
layers on the minimap.
add_cargo_to_units: Whether to add the units that are currently in cargo
to the feature_units and raw_units lists.
Raises:
ValueError: if the parameters are inconsistent.
"""
if not (feature_dimensions or rgb_dimensions or use_raw_units):
raise ValueError("Must set either the feature layer or rgb dimensions, "
"or use raw units.")
if action_space:
if not isinstance(action_space, actions.ActionSpace):
raise ValueError("action_space must be of type ActionSpace.")
if action_space == actions.ActionSpace.RAW:
use_raw_actions = True
elif ((action_space == actions.ActionSpace.FEATURES and
not feature_dimensions) or
(action_space == actions.ActionSpace.RGB and
not rgb_dimensions)):
raise ValueError(
"Action space must match the observations, action space={}, "
"feature_dimensions={}, rgb_dimensions={}".format(
action_space, feature_dimensions, rgb_dimensions))
else:
if use_raw_actions:
action_space = actions.ActionSpace.RAW
elif feature_dimensions and rgb_dimensions:
raise ValueError(
"You must specify the action space if you have both screen and "
"rgb observations.")
elif feature_dimensions:
action_space = actions.ActionSpace.FEATURES
else:
action_space = actions.ActionSpace.RGB
if raw_resolution:
raw_resolution = _to_point(raw_resolution)
if use_raw_actions:
if not use_raw_units:
raise ValueError(
"You must set use_raw_units if you intend to use_raw_actions")
if action_space != actions.ActionSpace.RAW:
raise ValueError(
"Don't specify both an action_space and use_raw_actions.")
if (rgb_dimensions and
(rgb_dimensions.screen.x < rgb_dimensions.minimap.x or
rgb_dimensions.screen.y < rgb_dimensions.minimap.y)):
raise ValueError(
"RGB Screen (%s) can't be smaller than the minimap (%s)." % (
rgb_dimensions.screen, rgb_dimensions.minimap))
self._feature_dimensions = feature_dimensions
self._rgb_dimensions = rgb_dimensions
self._action_space = action_space
self._camera_width_world_units = camera_width_world_units or 24
self._use_feature_units = use_feature_units
self._use_raw_units = use_raw_units
self._raw_resolution = raw_resolution
self._use_raw_actions = use_raw_actions
self._max_raw_actions = max_raw_actions
self._max_selected_units = max_selected_units
self._use_unit_counts = use_unit_counts
self._use_camera_position = use_camera_position
self._show_cloaked = show_cloaked
self._show_burrowed_shadows = show_burrowed_shadows
self._show_placeholders = show_placeholders
self._hide_specific_actions = hide_specific_actions
self._action_delay_fn = action_delay_fn
self._send_observation_proto = send_observation_proto
self._add_cargo_to_units = add_cargo_to_units
self._crop_to_playable_area = crop_to_playable_area
self._raw_crop_to_playable_area = raw_crop_to_playable_area
self._allow_cheating_layers = allow_cheating_layers
if action_space == actions.ActionSpace.FEATURES:
self._action_dimensions = feature_dimensions
else:
self._action_dimensions = rgb_dimensions
@property
def feature_dimensions(self):
return self._feature_dimensions
@property
def rgb_dimensions(self):
return self._rgb_dimensions
@property
def action_space(self):
return self._action_space
@property
def camera_width_world_units(self):
return self._camera_width_world_units
@property
def use_feature_units(self):
return self._use_feature_units
@property
def use_raw_units(self):
return self._use_raw_units
@property
def raw_resolution(self):
return self._raw_resolution
@raw_resolution.setter
def raw_resolution(self, value):
self._raw_resolution = value
@property
def use_raw_actions(self):
return self._use_raw_actions
@property
def max_raw_actions(self):
return self._max_raw_actions
@property
def max_selected_units(self):
return self._max_selected_units
@property
def use_unit_counts(self):
return self._use_unit_counts
@property
def use_camera_position(self):
return self._use_camera_position
@property
def show_cloaked(self):
return self._show_cloaked
@property
def show_burrowed_shadows(self):
return self._show_burrowed_shadows
@property
def show_placeholders(self):
return self._show_placeholders
@property
def hide_specific_actions(self):
return self._hide_specific_actions
@property
def action_delay_fn(self):
return self._action_delay_fn
@property
def send_observation_proto(self):
return self._send_observation_proto
@property
def add_cargo_to_units(self):
return self._add_cargo_to_units
@property
def action_dimensions(self):
return self._action_dimensions
@property
def crop_to_playable_area(self):
return self._crop_to_playable_area
@property
def raw_crop_to_playable_area(self):
return self._raw_crop_to_playable_area
@property
def allow_cheating_layers(self):
return self._allow_cheating_layers
def parse_agent_interface_format(
feature_screen=None,
feature_minimap=None,
rgb_screen=None,
rgb_minimap=None,
action_space=None,
action_delays=None,
**kwargs):
"""Creates an AgentInterfaceFormat object from keyword args.
Convenient when using dictionaries or command-line arguments for config.
Note that the feature_* and rgb_* properties define the respective spatial
observation dimensions and accept:
* None or 0 to disable that spatial observation.
* A single int for a square observation with that side length.
* A (int, int) tuple for a rectangular (width, height) observation.
Args:
feature_screen: If specified, so must feature_minimap be.
feature_minimap: If specified, so must feature_screen be.
rgb_screen: If specified, so must rgb_minimap be.
rgb_minimap: If specified, so must rgb_screen be.
action_space: ["FEATURES", "RGB", "RAW"].
action_delays: List of relative frequencies for each of [1, 2, 3, ...]
game loop delays on executed actions. Only used when the environment
is non-realtime. Intended to simulate the delays which can be
experienced when playing in realtime. Note that 1 is the minimum
possible delay; as actions can only ever be executed on a subsequent
game loop.
**kwargs: Anything else is passed through to AgentInterfaceFormat.
Returns:
An `AgentInterfaceFormat` object.
Raises:
ValueError: If an invalid parameter is specified.
"""
if feature_screen or feature_minimap:
feature_dimensions = Dimensions(feature_screen, feature_minimap)
else:
feature_dimensions = None
if rgb_screen or rgb_minimap:
rgb_dimensions = Dimensions(rgb_screen, rgb_minimap)
else:
rgb_dimensions = None
def _action_delay_fn(delays):
"""Delay frequencies per game loop delay -> fn returning game loop delay."""
if not delays:
return None
else:
total = sum(delays)
cumulative_sum = np.cumsum([delay / total for delay in delays])
def fn():
sample = random.uniform(0, 1) - EPSILON
for i, cumulative in enumerate(cumulative_sum):
if sample <= cumulative:
return i + 1
raise ValueError("Failed to sample action delay??")
return fn
return AgentInterfaceFormat(
feature_dimensions=feature_dimensions,
rgb_dimensions=rgb_dimensions,
action_space=(action_space and actions.ActionSpace[action_space.upper()]),
action_delay_fn=_action_delay_fn(action_delays),
**kwargs)
def features_from_game_info(game_info, agent_interface_format=None,
map_name=None, **kwargs):
"""Construct a Features object using data extracted from game info.
Args:
game_info: A `sc_pb.ResponseGameInfo` from the game.
agent_interface_format: an optional AgentInterfaceFormat.
map_name: an optional map name, which overrides the one in game_info.
**kwargs: Anything else is passed through to AgentInterfaceFormat. It's an
error to send any kwargs if you pass an agent_interface_format.
Returns:
A features object matching the specified parameterisation.
Raises:
ValueError: if you pass both agent_interface_format and kwargs.
ValueError: if you pass an agent_interface_format that doesn't match
game_info's resolutions.
"""
if isinstance(agent_interface_format, sc_pb.InterfaceOptions):
return Passthrough()
if not map_name:
map_name = game_info.map_name
if game_info.options.HasField("feature_layer"):
fl_opts = game_info.options.feature_layer
feature_dimensions = Dimensions(
screen=(fl_opts.resolution.x, fl_opts.resolution.y),
minimap=(fl_opts.minimap_resolution.x, fl_opts.minimap_resolution.y))
camera_width_world_units = game_info.options.feature_layer.width
else:
feature_dimensions = None
camera_width_world_units = None
if game_info.options.HasField("render"):
rgb_opts = game_info.options.render
rgb_dimensions = Dimensions(
screen=(rgb_opts.resolution.x, rgb_opts.resolution.y),
minimap=(rgb_opts.minimap_resolution.x, rgb_opts.minimap_resolution.y))
else:
rgb_dimensions = None
map_size = game_info.start_raw.map_size
requested_races = {
info.player_id: info.race_requested for info in game_info.player_info
if info.type != sc_pb.Observer}
if agent_interface_format:
if kwargs:
raise ValueError(
"Either give an agent_interface_format or kwargs, not both.")
aif = agent_interface_format
if (aif.rgb_dimensions != rgb_dimensions or
aif.feature_dimensions != feature_dimensions or
(feature_dimensions and
aif.camera_width_world_units != camera_width_world_units)):
raise ValueError("""
The supplied agent_interface_format doesn't match the resolutions computed from
the game_info:
rgb_dimensions: %s vs %s
feature_dimensions: %s vs %s
camera_width_world_units: %s vs %s
""" % (aif.rgb_dimensions, rgb_dimensions,
aif.feature_dimensions, feature_dimensions,
aif.camera_width_world_units, camera_width_world_units))
else:
agent_interface_format = AgentInterfaceFormat(
feature_dimensions=feature_dimensions,
rgb_dimensions=rgb_dimensions,
camera_width_world_units=camera_width_world_units,
**kwargs)
return Features(
agent_interface_format=agent_interface_format,
map_size=map_size,
map_name=map_name,
requested_races=requested_races)
def _init_valid_functions(action_dimensions):
"""Initialize ValidFunctions and set up the callbacks."""
sizes = {
"screen": tuple(int(i) for i in action_dimensions.screen),
"screen2": tuple(int(i) for i in action_dimensions.screen),
"minimap": tuple(int(i) for i in action_dimensions.minimap),
}
types = actions.Arguments(*[
actions.ArgumentType.spec(t.id, t.name, sizes.get(t.name, t.sizes))
for t in actions.TYPES])
functions = actions.Functions([
actions.Function.spec(f.id, f.name, tuple(types[t.id] for t in f.args))
for f in actions.FUNCTIONS])
return actions.ValidActions(types, functions)
def _init_valid_raw_functions(raw_resolution, max_selected_units):
"""Initialize ValidFunctions and set up the callbacks."""
sizes = {
"world": tuple(int(i) for i in raw_resolution),
"unit_tags": (max_selected_units,),
}
types = actions.RawArguments(*[
actions.ArgumentType.spec(t.id, t.name, sizes.get(t.name, t.sizes))
for t in actions.RAW_TYPES])
functions = actions.Functions([
actions.Function.spec(f.id, f.name, tuple(types[t.id] for t in f.args))
for f in actions.RAW_FUNCTIONS])
return actions.ValidActions(types, functions)
class Features(object):
"""Render feature layers from SC2 Observation protos into numpy arrays.
This has the implementation details of how to render a starcraft environment.
It translates between agent action/observation formats and starcraft
action/observation formats, which should not be seen by agent authors. The
starcraft protos contain more information than they should have access to.
This is outside of the environment so that it can also be used in other
contexts, eg a supervised dataset pipeline.
"""
def __init__(self, agent_interface_format=None, map_size=None,
requested_races=None, map_name="unknown"):
"""Initialize a Features instance matching the specified interface format.
Args:
agent_interface_format: See the documentation for `AgentInterfaceFormat`.
map_size: The size of the map in world units, needed for feature_units.
requested_races: Optional. Dict mapping `player_id`s to that player's
requested race. If present, will send player races in observation.
map_name: Optional name of the map, to be added to the observation.
Raises:
ValueError: if agent_interface_format isn't specified.
ValueError: if map_size isn't specified when use_feature_units or
use_camera_position is.
"""
if not agent_interface_format:
raise ValueError("Please specify agent_interface_format")
self._agent_interface_format = agent_interface_format
aif = self._agent_interface_format
if not aif.raw_resolution and map_size:
aif.raw_resolution = point.Point.build(map_size)
self._map_size = map_size
self._map_name = map_name
if (aif.use_feature_units
or aif.use_camera_position
or aif.use_raw_units):
self.init_camera(
aif.feature_dimensions,
map_size,
aif.camera_width_world_units,
aif.raw_resolution)
self._send_observation_proto = aif.send_observation_proto
self._raw = aif.use_raw_actions
if self._raw:
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | true |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/colors.py | pysc2/lib/colors.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A basic Color class."""
import collections
import math
import random
import numpy
from pysc2.lib import static_data
class Color(collections.namedtuple("Color", ["r", "g", "b"])):
"""A basic Color class."""
__slots__ = ()
def set(self, r=None, g=None, b=None):
return Color(r or self.r, b or self.b, g or self.g)
def round(self):
return Color(int(round(self.r)), int(round(self.g)), int(round(self.b)))
def floor(self):
return Color(int(math.floor(self.r)), int(math.floor(self.g)),
int(math.floor(self.b)))
def ceil(self):
return Color(int(math.ceil(self.r)), int(math.ceil(self.g)),
int(math.ceil(self.b)))
def __str__(self):
return "%d,%d,%d" % self
def __add__(self, o):
return Color(self.r + o.r, self.g + o.g, self.b + o.b)
def __sub__(self, o):
return Color(self.r - o.r, self.g - o.g, self.b - o.b)
def __mul__(self, val):
return Color(self.r * val, self.g * val, self.b * val)
def __truediv__(self, val):
return Color(self.r / val, self.g / val, self.b / val)
def __floordiv__(self, val):
return Color(self.r // val, self.g // val, self.b // val)
__div__ = __truediv__
black = Color(0, 0, 0)
white = Color(255, 255, 255)
red = Color(255, 0, 0)
green = Color(0, 255, 0)
blue = Color(0, 0, 255)
cyan = Color(0, 255, 255)
yellow = Color(255, 255, 0)
purple = Color(255, 0, 255)
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, 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
def shuffled_hue(scale):
palette = list(smooth_hue_palette(scale))
random.Random(21).shuffle(palette) # Return a fixed shuffle
return numpy.array(palette)
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): # Leave 0 as black.
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
def winter(scale):
return piece_wise_linear(scale, [(0, Color(0, 0.5, 0.4) * 255),
(1, Color(1, 1, 0.4) * 255)])
def hot(scale):
return piece_wise_linear(scale, [(0, Color(0.5, 0, 0) * 255),
(0.2, Color(1, 0, 0) * 255),
(0.6, Color(1, 1, 0) * 255),
(1, Color(1, 1, 1) * 255)])
def height_map(scale):
return piece_wise_linear(scale, [
(0, Color(0, 0, 0)), # Abyss
(40/255, Color(67, 109, 95)), # Water, little below this height.
(50/255, Color(168, 152, 129)), # Beach
(60/255, Color(154, 124, 90)), # Sand, the mode height.
(70/255, Color(117, 150, 96)), # Grass
(80/255, Color(166, 98, 97)), # Dirt, should be the top.
(1, Color(255, 255, 100)), # Heaven. Shouldn't be seen.
])
# Palette used to color player_relative features.
PLAYER_RELATIVE_PALETTE = numpy.array([
black, # Background.
Color(0, 142, 0), # Self. (Green).
yellow, # Ally.
Color(129, 166, 196), # Neutral. (Cyan.)
Color(113, 25, 34), # Enemy. (Red).
])
PLAYER_ABSOLUTE_PALETTE = numpy.array([
black, # Background
Color(0, 142, 0), # 1: Green
Color(113, 25, 34), # 2: Red
Color(223, 215, 67), # 3: Yellow
Color(66, 26, 121), # 4: Purple
Color(222, 144, 50), # 5: Orange
Color(46, 72, 237), # 6: Blue
Color(207, 111, 176), # 7: Pink
Color(189, 251, 157), # 8: Light green
white * 0.1, # 9: Does the game ever have more than 8 players?
white * 0.1, # 10: Does the game ever have more than 8 players?
white * 0.1, # 11: Does the game ever have more than 8 players?
white * 0.1, # 12: Does the game ever have more than 8 players?
white * 0.1, # 13: Does the game ever have more than 8 players?
white * 0.1, # 14: Does the game ever have more than 8 players?
white * 0.1, # 15: Does the game ever have more than 8 players?
Color(129, 166, 196), # 16 Neutral: Cyan
])
VISIBILITY_PALETTE = numpy.array([
black, # Hidden
white * 0.25, # Fogged
white * 0.6, # Visible
])
CAMERA_PALETTE = numpy.array([black, white * 0.6])
CREEP_PALETTE = numpy.array([black, purple * 0.4])
POWER_PALETTE = numpy.array([black, cyan * 0.7])
SELECTED_PALETTE = numpy.array([black, green * 0.7])
def unit_type(scale=None):
"""Returns a palette that maps unit types to rgb colors."""
return categorical(static_data.UNIT_TYPES, scale)
def buffs(scale=None):
"""Returns a palette that maps buffs to rgb colors."""
return categorical(static_data.BUFFS, scale)
def categorical(options, scale=None):
# Can specify a scale to match the api or to accept unknown unit types.
palette_size = scale or max(options) + 1
palette = shuffled_hue(palette_size)
assert len(options) <= len(distinct_colors)
for i, v in enumerate(options):
palette[v] = distinct_colors[i]
return palette
effects = numpy.array([
[0, 0, 0],
[72, 173, 207],
[203, 76, 49],
[122, 98, 209],
[109, 183, 67],
[192, 80, 181],
[86, 185, 138],
[211, 63, 115],
[81, 128, 60],
[182, 135, 208],
[182, 174, 73],
[95, 123, 196],
[220, 146, 71],
[187, 102, 147],
[138, 109, 48],
[197, 103, 99],
])
# Generated with http://tools.medialab.sciences-po.fr/iwanthue/
# 350 colors: H: 0-360, C: 0-100, L: 35-100; then shuffled.
distinct_colors = numpy.array([
[99, 91, 0],
[195, 211, 0],
[57, 206, 255],
[255, 172, 106],
[255, 187, 77],
[255, 195, 114],
[0, 102, 201],
[3, 249, 197],
[79, 84, 81],
[255, 252, 198],
[0, 132, 134],
[255, 155, 144],
[255, 211, 140],
[41, 91, 83],
[101, 77, 73],
[0, 144, 124],
[146, 41, 97],
[2, 223, 228],
[173, 77, 0],
[255, 93, 193],
[54, 92, 36],
[119, 255, 202],
[154, 0, 183],
[0, 156, 121],
[144, 173, 0],
[255, 254, 173],
[62, 90, 54],
[144, 54, 5],
[2, 169, 191],
[132, 255, 249],
[196, 158, 255],
[187, 8, 0],
[138, 255, 99],
[236, 163, 255],
[78, 255, 187],
[128, 64, 56],
[255, 195, 148],
[0, 101, 209],
[149, 193, 255],
[0, 239, 125],
[134, 65, 240],
[0, 222, 123],
[255, 249, 146],
[0, 247, 164],
[8, 169, 0],
[156, 36, 46],
[255, 174, 81],
[0, 102, 84],
[139, 213, 0],
[142, 87, 0],
[215, 255, 55],
[203, 255, 124],
[0, 96, 93],
[63, 78, 147],
[227, 255, 115],
[160, 0, 131],
[69, 148, 0],
[142, 149, 0],
[255, 72, 70],
[0, 229, 224],
[127, 63, 76],
[248, 139, 255],
[2, 188, 206],
[0, 128, 203],
[113, 151, 0],
[255, 203, 103],
[0, 178, 172],
[128, 53, 122],
[163, 4, 83],
[2, 79, 204],
[235, 128, 0],
[0, 106, 247],
[164, 156, 255],
[179, 173, 0],
[255, 124, 221],
[115, 209, 0],
[62, 249, 255],
[240, 118, 0],
[45, 84, 135],
[106, 96, 255],
[39, 89, 109],
[0, 86, 192],
[255, 133, 151],
[90, 192, 0],
[156, 0, 154],
[127, 51, 133],
[216, 255, 82],
[160, 255, 212],
[106, 43, 191],
[224, 255, 221],
[167, 47, 227],
[255, 217, 85],
[251, 173, 255],
[92, 55, 185],
[162, 28, 1],
[126, 102, 255],
[212, 140, 255],
[113, 66, 111],
[216, 0, 205],
[70, 242, 69],
[120, 109, 255],
[0, 132, 180],
[122, 67, 62],
[255, 166, 54],
[140, 173, 255],
[105, 79, 0],
[39, 227, 55],
[255, 71, 238],
[112, 75, 18],
[149, 83, 255],
[255, 130, 205],
[255, 138, 39],
[0, 184, 21],
[202, 154, 0],
[145, 52, 41],
[185, 255, 85],
[151, 46, 8],
[255, 215, 128],
[2, 192, 148],
[80, 81, 101],
[255, 166, 114],
[0, 161, 80],
[255, 56, 89],
[2, 223, 146],
[98, 246, 255],
[150, 251, 255],
[255, 125, 56],
[144, 51, 53],
[83, 133, 255],
[1, 82, 173],
[122, 118, 0],
[255, 86, 174],
[67, 87, 78],
[131, 65, 4],
[170, 255, 204],
[0, 108, 66],
[248, 96, 255],
[212, 101, 255],
[99, 230, 34],
[140, 41, 121],
[173, 0, 175],
[255, 190, 175],
[186, 179, 255],
[171, 221, 255],
[78, 255, 135],
[220, 0, 32],
[255, 217, 192],
[46, 58, 215],
[68, 255, 230],
[96, 81, 53],
[1, 174, 246],
[72, 70, 166],
[255, 233, 77],
[255, 166, 197],
[255, 208, 241],
[183, 255, 62],
[255, 226, 226],
[107, 255, 119],
[148, 122, 0],
[171, 255, 143],
[255, 109, 232],
[156, 142, 255],
[124, 148, 255],
[178, 236, 255],
[168, 91, 0],
[255, 255, 248],
[255, 92, 91],
[132, 238, 255],
[225, 131, 0],
[255, 149, 111],
[171, 157, 0],
[255, 133, 181],
[196, 158, 0],
[2, 162, 246],
[193, 110, 0],
[255, 243, 244],
[255, 180, 181],
[255, 79, 221],
[255, 211, 109],
[0, 99, 118],
[255, 167, 214],
[89, 81, 83],
[147, 255, 120],
[2, 210, 200],
[255, 244, 113],
[255, 197, 248],
[0, 122, 37],
[255, 194, 57],
[130, 130, 255],
[107, 77, 29],
[255, 153, 56],
[178, 104, 255],
[17, 98, 0],
[0, 119, 128],
[146, 106, 0],
[117, 255, 186],
[255, 155, 232],
[1, 87, 232],
[61, 83, 120],
[200, 255, 187],
[196, 221, 255],
[100, 73, 112],
[115, 218, 255],
[85, 114, 0],
[208, 142, 0],
[255, 30, 147],
[156, 0, 200],
[239, 0, 122],
[255, 43, 170],
[0, 87, 241],
[237, 255, 248],
[0, 151, 44],
[255, 155, 161],
[218, 0, 107],
[139, 57, 29],
[148, 255, 174],
[100, 69, 131],
[195, 0, 29],
[177, 64, 0],
[93, 81, 60],
[2, 162, 172],
[205, 0, 134],
[255, 168, 135],
[225, 93, 0],
[125, 39, 165],
[187, 255, 126],
[2, 196, 237],
[234, 119, 255],
[240, 0, 182],
[115, 181, 0],
[255, 125, 125],
[67, 90, 26],
[242, 255, 69],
[185, 81, 255],
[255, 195, 130],
[32, 95, 35],
[215, 0, 153],
[197, 125, 0],
[46, 104, 0],
[72, 73, 155],
[177, 183, 0],
[149, 40, 81],
[255, 145, 88],
[164, 16, 58],
[215, 187, 255],
[119, 204, 255],
[198, 255, 237],
[255, 92, 65],
[197, 244, 255],
[0, 146, 22],
[118, 179, 255],
[255, 94, 144],
[208, 1, 182],
[28, 200, 0],
[0, 121, 97],
[167, 0, 111],
[25, 84, 143],
[2, 191, 98],
[175, 0, 127],
[48, 92, 57],
[119, 71, 31],
[255, 169, 186],
[2, 115, 247],
[111, 74, 50],
[255, 82, 41],
[41, 94, 11],
[42, 155, 255],
[235, 52, 0],
[243, 167, 0],
[255, 96, 134],
[61, 255, 216],
[220, 255, 177],
[3, 162, 206],
[183, 0, 90],
[255, 237, 208],
[86, 153, 0],
[207, 255, 220],
[255, 194, 229],
[255, 93, 34],
[3, 95, 57],
[0, 160, 99],
[1, 89, 165],
[167, 128, 0],
[1, 215, 245],
[167, 255, 97],
[187, 0, 77],
[173, 0, 32],
[0, 101, 130],
[58, 90, 66],
[255, 102, 112],
[0, 120, 89],
[240, 182, 255],
[125, 90, 0],
[216, 210, 255],
[244, 0, 78],
[88, 85, 18],
[228, 181, 0],
[169, 207, 0],
[24, 134, 0],
[217, 255, 255],
[216, 255, 147],
[133, 55, 93],
[205, 90, 255],
[255, 119, 97],
[255, 227, 164],
[50, 129, 0],
[1, 138, 243],
[0, 134, 68],
[98, 255, 245],
[255, 94, 158],
[186, 204, 255],
[0, 191, 163],
[1, 141, 207],
[2, 228, 103],
[255, 208, 171],
[207, 78, 0],
[0, 147, 86],
[217, 32, 0],
[194, 0, 50],
[0, 122, 68],
[255, 235, 48],
[183, 28, 217],
[193, 167, 0],
[250, 0, 200],
[154, 36, 64],
[126, 58, 107],
[103, 127, 0],
[210, 106, 0],
[220, 0, 49],
[0, 107, 143],
[255, 181, 242],
[166, 255, 183],
[95, 66, 149],
[0, 210, 151],
[1, 217, 81],
[255, 238, 184],
[253, 255, 0],
[201, 0, 75],
[0, 170, 49],
[255, 215, 209],
[94, 61, 168],
[117, 54, 151],
[91, 83, 37],
[190, 1, 209],
[216, 241, 0],
[243, 230, 255],
[233, 255, 193],
[169, 141, 0],
[80, 96, 0],
[0, 101, 34],
])
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/sc_process.py | pysc2/lib/sc_process.py | # Copyright 2017-2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Launch the game and set up communication."""
import os
import platform
import shutil
import subprocess
import tempfile
import time
from absl import flags
from absl import logging
import portpicker
from pysc2.lib import remote_controller
from pysc2.lib import stopwatch
flags.DEFINE_bool(
"sc2_verbose", False, "Enable SC2 verbose logging.", allow_hide_cpp=True)
flags.DEFINE_bool(
"sc2_verbose_mp", False, "Enable SC2 verbose multiplayer logging.")
flags.DEFINE_bool("sc2_gdb", False, "Run SC2 in gdb.")
flags.DEFINE_bool("sc2_strace", False, "Run SC2 in strace.")
flags.DEFINE_integer("sc2_port", None,
"If set, connect to the instance on "
"localhost:sc2_port instead of launching one.")
FLAGS = flags.FLAGS
sw = stopwatch.sw
class SC2LaunchError(Exception):
pass
class StarcraftProcess(object):
"""Launch a starcraft server, initialize a controller, and later, clean up.
This is best used from run_configs, which decides which version to run, and
where to find it.
It is important to call `close` or use it as a context manager, otherwise
you'll likely leak temp files and SC2 processes.
"""
def __init__(self, run_config, exec_path, version, full_screen=False,
extra_args=None, verbose=False, host=None, port=None,
connect=True, timeout_seconds=None, window_size=(640, 480),
window_loc=(50, 50), **kwargs):
"""Launch the SC2 process.
Args:
run_config: `run_configs.lib.RunConfig` object.
exec_path: Path to the binary to run.
version: `run_configs.lib.Version` object.
full_screen: Whether to launch the game window full_screen on win/mac.
extra_args: List of additional args for the SC2 process.
verbose: Whether to have the SC2 process do verbose logging.
host: IP for the game to listen on for its websocket. This is
usually "127.0.0.1", or "::1", but could be others as well.
port: Port SC2 should listen on for the websocket.
connect: Whether to create a RemoteController to connect.
timeout_seconds: Timeout for the remote controller.
window_size: Screen size if not full screen.
window_loc: Screen location if not full screen.
**kwargs: Extra arguments for _launch (useful for subclasses).
"""
self._proc = None
self._controller = None
self._check_exists(exec_path)
self._tmp_dir = tempfile.mkdtemp(prefix="sc-", dir=run_config.tmp_dir)
self._host = host or "127.0.0.1"
self._port = FLAGS.sc2_port or port or portpicker.pick_unused_port()
self._version = version
args = [
exec_path,
"-listen", self._host,
"-port", str(self._port),
"-dataDir", os.path.join(run_config.data_dir, ""),
"-tempDir", os.path.join(self._tmp_dir, ""),
]
if ":" in self._host:
args += ["-ipv6"]
if platform.system() != "Linux":
if full_screen:
args += ["-displayMode", "1"]
else:
args += [
"-displayMode", "0",
"-windowwidth", str(window_size[0]),
"-windowheight", str(window_size[1]),
"-windowx", str(window_loc[0]),
"-windowy", str(window_loc[1]),
]
if verbose or FLAGS.sc2_verbose:
args += ["-verbose"]
if FLAGS.sc2_verbose_mp:
args += ["-verboseMP"]
if self._version and self._version.data_version:
args += ["-dataVersion", self._version.data_version.upper()]
if extra_args:
args += extra_args
if FLAGS.sc2_gdb:
print("Launching: gdb", args[0])
print("GDB run command:")
print(" run %s" % " ".join(args[1:]))
print("\n")
args = ["gdb", args[0]]
timeout_seconds = 3600 * 6
elif FLAGS.sc2_strace:
strace_out = "/tmp/sc2-strace.txt"
print("Launching in strace. Redirecting output to", strace_out)
args = ["strace", "-f", "-o", strace_out] + args
else:
logging.info("Launching SC2: %s", " ".join(args))
try:
with sw("startup"):
if not FLAGS.sc2_port:
self._proc = self._launch(run_config, args, **kwargs)
if connect:
self._controller = remote_controller.RemoteController(
self._host, self._port, self, timeout_seconds=timeout_seconds)
except:
self.close()
raise
@sw.decorate
def close(self):
"""Shut down the game and clean up."""
if hasattr(self, "_controller") and self._controller:
self._controller.quit()
self._controller.close()
self._controller = None
self._shutdown()
if hasattr(self, "_port") and self._port:
if not FLAGS.sc2_port:
portpicker.return_port(self._port)
self._port = None
if hasattr(self, "_tmp_dir") and os.path.exists(self._tmp_dir):
shutil.rmtree(self._tmp_dir)
@property
def controller(self):
return self._controller
@property
def host(self):
return self._host
@property
def port(self):
return self._port
@property
def version(self):
return self._version
def __enter__(self):
return self.controller
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback):
self.close()
def __del__(self):
# Prefer using a context manager, but this cleans most other cases.
self.close()
def _check_exists(self, exec_path):
if not os.path.isfile(exec_path):
raise RuntimeError("Trying to run '%s', but it doesn't exist" % exec_path)
if not os.access(exec_path, os.X_OK):
raise RuntimeError(
"Trying to run '%s', but it isn't executable." % exec_path)
def _launch(self, run_config, args, **kwargs):
"""Launch the process and return the process object."""
try:
with sw("popen"):
return subprocess.Popen(
args, cwd=run_config.cwd, env=run_config.env, **kwargs)
except OSError as e:
logging.exception("Failed to launch")
raise SC2LaunchError("Failed to launch: %s" % args) from e
def _shutdown(self):
"""Terminate the sub-process."""
if self._proc:
ret = _shutdown_proc(self._proc, 3)
logging.info("Shutdown with return code: %s", ret)
self._proc = None
@property
def running(self):
if FLAGS.sc2_port:
return True
# poll returns None if it's running, otherwise the exit code.
return self._proc and (self._proc.poll() is None)
@property
def pid(self):
return self._proc.pid if self.running else None
def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for _ in range(1 + timeout * freq):
p.terminate()
ret = p.poll()
if ret is not None:
logging.info("Shutdown gracefully.")
return ret
time.sleep(1 / freq)
logging.warning("Killing the process.")
p.kill()
return p.wait()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/np_util.py | pysc2/lib/np_util.py | # Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Diff proto objects returning paths to changed attributes."""
import numpy as np
def summarize_array_diffs(lhs, rhs):
"""Output value differences, with index for each, between two arrays."""
result = []
indices = np.transpose(np.nonzero(lhs - rhs))
for row in indices:
index = tuple(np.array([e]) for e in row.tolist())
lhs_element = lhs[index]
rhs_element = rhs[index]
result.append("{}: {} -> {}".format(
"".join("[{}]".format(i) for i in row), lhs_element[0], rhs_element[0]))
if indices.size:
return "{} element(s) changed - ".format(len(indices)) + "; ".join(result)
else:
return ""
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay/sc2_replay_utils_test.py | pysc2/lib/replay/sc2_replay_utils_test.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
from pysc2.lib.replay import sc2_replay
from pysc2.lib.replay import sc2_replay_utils
from pysc2.lib import gfile
from pysc2.lib import resources
FLAGS = flags.FLAGS
PATH = "pysc2/lib/replay/test_data"
def _read_replay(name):
replay_path = resources.GetResourceFilename(os.path.join(PATH, name))
with gfile.Open(replay_path, mode="rb") as f:
replay_data = f.read()
return sc2_replay.SC2Replay(replay_data)
def _read_skips(name):
skips_path = resources.GetResourceFilename(os.path.join(PATH, name))
with gfile.Open(skips_path, mode="r") as f:
return [int(i) for i in f.readlines()[0].split(",")]
class Sc2ReplayUtilsTest(parameterized.TestCase):
@parameterized.parameters(
((f"replay_0{i}.SC2Replay", f"replay_0{i}.skips.txt")
for i in range(1, 10)))
def test_raw_action_skips(self, replay_name, skips_file):
replay = _read_replay(replay_name)
skips = _read_skips(skips_file)
result = sc2_replay_utils.raw_action_skips(replay)
self.assertEqual(result[1], skips)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay/replay_observation_stream.py | pysc2/lib/replay/replay_observation_stream.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SC2 replays -> ResponseObservation proto streams."""
import io
import json
import time
from absl import logging
import mpyq
from pysc2 import run_configs
from s2clientprotocol import sc2api_pb2 as sc_pb
def _get_replay_version(replay_data):
replay_io = io.BytesIO()
replay_io.write(replay_data)
replay_io.seek(0)
archive = mpyq.MPQArchive(replay_io).extract()
metadata = json.loads(
bytes.decode(archive[b"replay.gamemetadata.json"], "utf-8"))
return run_configs.lib.Version(
game_version=".".join(metadata["GameVersion"].split(".")[:-1]),
build_version=int(metadata["BaseBuild"][4:]),
data_version=metadata.get("DataVersion"), # Only in replays version 4.1+.
binary=None)
class ReplayError(Exception):
pass
class ReplayObservationStream(object):
"""Wrapper class for iterating over replay observation data.
Yields the observations for a replay from player_id's perspective. The class
can throw connection errors from the controller. These should be caught
at the top level, since they are unrecoverable (the controller is unusable).
Determines the replay version from the protocol information in the replay
file. Uses a cache of processes, one for each binary version required
to process corresponding replays.
How to use the class:
with ReplayObservationStream() as replay_stream:
replay_stream.start_replay(replay_data, player_id)
# Get game data if needed.
info = replay_stream.game_info()
for observation in replay_stream.observations():
# Do something with each observation.
"""
def __init__(self,
interface_options: sc_pb.InterfaceOptions,
step_mul: int = 1,
disable_fog: bool = False,
game_steps_per_episode: int = 0,
add_opponent_observations: bool = False):
"""Constructs the replay stream object.
Args:
interface_options: Interface format to use.
step_mul: Number of skipped observations in between environment steps.
disable_fog: Bool, True to disable fog of war.
game_steps_per_episode: Int, truncate after this many steps (0 for inf.).
add_opponent_observations: Bool, True to return the opponent's
observations in addition to the observing player. Note that this will
start two SC2 processes simultaneously if set to True. By default is
False and returns observations from one player's perspective.
"""
self._step_mul = step_mul
self._disable_fog = disable_fog
self._game_steps_per_episode = game_steps_per_episode
self._add_opponent_observations = add_opponent_observations
self._packet_count = 0
self._info = None
self._player_id = None
if not interface_options:
raise ValueError("Please specify interface_options")
self._interface = interface_options
self._want_rgb = self._interface.HasField("render")
self._run_config = None
self._sc2_procs = []
self._controllers = []
def _get_controllers(self, version):
"""Get controllers."""
if not self._run_config or self._run_config.version != version:
# Close current process and create a new one.
self._close()
self._run_config = run_configs.get(version=version)
self._sc2_procs = [self._run_config.start(want_rgb=self._want_rgb)]
if self._add_opponent_observations:
self._sc2_procs.append(self._run_config.start(want_rgb=self._want_rgb))
self._controllers = [
proc.controller for proc in self._sc2_procs
]
return self._controllers
def _close(self):
self._run_config = None
for controller in self._controllers:
if controller:
controller.quit()
self._controllers = []
for proc in self._sc2_procs:
if proc:
proc.close()
self._sc2_procs = []
def start_replay_from_data(self, replay_data, player_id):
"""Starts the stream of replay observations from an in-memory replay."""
self._player_id = player_id
try:
version = _get_replay_version(replay_data)
except (ValueError, AttributeError) as err:
logging.exception("Error getting replay version from data: %s", err)
raise ReplayError(err)
if self._add_opponent_observations:
player_ids = [player_id, (player_id % 2) + 1]
else:
player_ids = [player_id]
start_requests = []
for p_id in player_ids:
start_requests.append(
sc_pb.RequestStartReplay(
replay_data=replay_data,
options=self._interface,
disable_fog=self._disable_fog,
observed_player_id=p_id))
logging.info("Starting replay...")
self._controllers = self._get_controllers(version)
self._info = info = self._controllers[0].replay_info(replay_data)
logging.info(" Replay info ".center(60, "-"))
logging.info(info)
logging.info("-" * 60)
if (info.local_map_path and
info.local_map_path.lower().endswith(".sc2map")):
logging.info("Map path: %s", info.local_map_path)
for start_replay in start_requests:
start_replay.map_data = self._run_config.map_data(info.local_map_path)
for controller, start_replay in zip(self._controllers, start_requests):
controller.start_replay(start_replay)
logging.info("Getting started...")
def replay_info(self):
return self._info
def game_info(self):
return self._controllers[0].game_info()
def static_data(self):
return self._controllers[0].data()
def observations(self, step_sequence=None):
"""Yields a ResponseObservation proto for each environment step.
If using the opponent's observations, this will yield a list of
observations, one for each player.
Args:
step_sequence: A list of integers, the step sizes to apply to the stream.
"""
self._packet_count = 0
period_start = time.time()
period = 1000 # log packet rate every 1000 packets
logging.info("Begin iterating over frames...")
while True:
obs = [controller.observe() for controller in self._controllers]
if self._packet_count == 0:
logging.info("The first packet has been read")
self._packet_count += 1
if len(obs) == 1:
yield obs[0]
else:
yield obs
if (obs[0].player_result or
(step_sequence and self._packet_count > len(step_sequence))):
# End of game.
break
if self._game_steps_per_episode > 0:
if obs[0].observation.game_loop >= self._game_steps_per_episode - 1:
break
for controller in self._controllers:
if step_sequence and self._packet_count <= len(step_sequence):
step_mul = step_sequence[self._packet_count - 1]
else:
step_mul = self._step_mul
controller.step(step_mul)
if self._packet_count % period == 0:
time_taken = time.time() - period_start
period_start = time.time()
logging.info(
"Frame: %d, packets per sec: %.1f",
obs[0].observation.game_loop, period / time_taken)
def close(self):
"""Close the replay process connection."""
logging.info("Quitting...")
self._close()
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
if exception_value:
logging.error("[%s]: %s", exception_type, exception_value)
self.close()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay/sc2_replay_test.py | pysc2/lib/replay/sc2_replay_test.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from absl import flags
from absl.testing import absltest
from pysc2.lib.replay import sc2_replay
from pysc2.lib import gfile
from pysc2.lib import resources
FLAGS = flags.FLAGS
PATH = "pysc2/lib/replay/test_data/replay_01.SC2Replay"
class Sc2ReplayTest(absltest.TestCase):
def setUp(self):
super(Sc2ReplayTest, self).setUp()
replay_path = resources.GetResourceFilename(PATH)
with gfile.Open(replay_path, mode="rb") as f:
replay_data = f.read()
self._replay = sc2_replay.SC2Replay(replay_data)
def testDetails(self):
replay_details = self._replay.details()
self.assertEmpty(replay_details["m_cacheHandles"])
self.assertEqual(replay_details["m_campaignIndex"], 0)
self.assertEqual(replay_details["m_defaultDifficulty"], 3)
self.assertEqual(replay_details["m_description"], "")
self.assertEqual(replay_details["m_difficulty"], "")
self.assertFalse(replay_details["m_disableRecoverGame"])
self.assertEqual(replay_details["m_gameSpeed"], 4)
self.assertEqual(replay_details["m_imageFilePath"], "")
self.assertFalse(replay_details["m_isBlizzardMap"])
self.assertEqual(
replay_details["m_mapFileName"],
"Ladder2019Season1May/CyberForestLE.SC2Map")
self.assertFalse(replay_details["m_miniSave"])
self.assertEqual(
replay_details["m_modPaths"], [
"Mods/Liberty.SC2Mod",
"Mods/Swarm.SC2Mod",
"Mods/Void.SC2Mod",
"Mods/VoidMulti.SC2Mod"
])
# (there is more data here, just listing the most interesting bits)
self.assertEqual(replay_details["m_playerList"][0]["m_name"], "Supervised")
self.assertFalse(replay_details["m_playerList"][0]["m_observe"])
self.assertEqual(replay_details["m_playerList"][0]["m_race"], "Protoss")
self.assertEqual(replay_details["m_playerList"][0]["m_result"], 2)
self.assertEqual(replay_details["m_playerList"][1]["m_name"],
"temp_x1_5_beast3f_6571236_final")
self.assertFalse(replay_details["m_playerList"][1]["m_observe"])
self.assertEqual(replay_details["m_playerList"][1]["m_race"], "Protoss")
self.assertEqual(replay_details["m_playerList"][1]["m_result"], 1)
self.assertFalse(replay_details["m_restartAsTransitionMap"])
self.assertEqual(replay_details["m_thumbnail"]["m_file"], "Minimap.tga")
self.assertEqual(replay_details["m_timeLocalOffset"], 0)
self.assertEqual(replay_details["m_timeUTC"], 132772394814660570)
self.assertEqual(replay_details["m_title"], "Cyber Forest LE")
def testInitData(self):
init_data = self._replay.init_data()
# (there is more data here, just listing the most interesting bits)
game_description = init_data["m_syncLobbyState"]["m_gameDescription"]
self.assertEqual(game_description["m_gameOptions"]["m_fog"], 0)
self.assertEqual(game_description["m_gameSpeed"], 4)
self.assertEqual(game_description["m_isBlizzardMap"], False)
self.assertEqual(game_description["m_isRealtimeMode"], False)
self.assertEqual(
game_description["m_mapFileName"],
"Ladder2019Season1May/CyberForestLE.SC2Map")
def testTrackerEvents(self):
events = list(self._replay.tracker_events())
event_types = set(s["_event"] for s in events)
self.assertEqual(
event_types,
{"NNet.Replay.Tracker.SPlayerSetupEvent",
"NNet.Replay.Tracker.SPlayerStatsEvent",
"NNet.Replay.Tracker.SUnitBornEvent",
"NNet.Replay.Tracker.SUnitDiedEvent",
"NNet.Replay.Tracker.SUnitDoneEvent",
"NNet.Replay.Tracker.SUnitInitEvent",
"NNet.Replay.Tracker.SUnitPositionsEvent",
"NNet.Replay.Tracker.SUnitTypeChangeEvent",
"NNet.Replay.Tracker.SUpgradeEvent"})
def testGameEvents(self):
events = list(self._replay.game_events())
event_types = set(s["_event"] for s in events)
self.assertEqual(
event_types,
{"NNet.Game.SCameraUpdateEvent",
"NNet.Game.SCmdEvent",
"NNet.Game.SCmdUpdateTargetPointEvent",
"NNet.Game.SCmdUpdateTargetUnitEvent",
"NNet.Game.SCommandManagerStateEvent",
"NNet.Game.SPeerSetSyncLoadingTimeEvent",
"NNet.Game.SPeerSetSyncPlayingTimeEvent",
"NNet.Game.SSelectionDeltaEvent",
"NNet.Game.SUserFinishedLoadingSyncEvent",
"NNet.Game.SUserOptionsEvent"})
def testMessageEvents(self):
events = list(self._replay.message_events())
event_types = set(s["_event"] for s in events)
self.assertEqual(
event_types,
{"NNet.Game.SLoadingProgressMessage"})
def testAttributesEvents(self):
events = list(self._replay.attributes_events())
self.assertEmpty(events)
if __name__ == "__main__":
absltest.main()
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay/sc2_replay_utils.py | pysc2/lib/replay/sc2_replay_utils.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities built on top of sc2_replay."""
import collections
import dataclasses
from typing import List, Mapping
from pysc2.lib.replay import sc2_replay
_EVENT_TYPES_TO_FILTER_OUT = frozenset([
# Not related to actions.
"SetSyncLoadingTime",
"SetSyncPlayingTime",
"TriggerSoundLengthSync",
"UserFinishedLoadingSync",
"UserOptions",
# Always accompanied by a CommandManagerState, which we track.
"CmdUpdateTargetPoint",
# Of interest for the visual interface, but skipped for now as we are
# targeting raw.
"CameraSave",
"ControlGroupUpdate",
"SelectionDelta",
])
def _readable_event_type(full_event_type):
return full_event_type[len("NNet.Game.S"):-5]
@dataclasses.dataclass
class EventData:
game_loop: int
event_type: str
def raw_action_skips(replay: sc2_replay.SC2Replay) -> Mapping[int, List[int]]:
"""Returns player id -> list, the game loops on which each player acted.
Args:
replay: An sc2_replay.SC2Replay instance.
Note that these skips are specific to the raw interface - further work will
be needed to support visual.
"""
action_frames = collections.defaultdict(list)
last_game_loop = None
# Extract per-user events of interest.
for event in replay.game_events():
event_type = _readable_event_type(event["_event"])
if event_type not in _EVENT_TYPES_TO_FILTER_OUT:
game_loop = event["_gameloop"]
last_game_loop = game_loop
# As soon as anyone leaves, we stop tracking events.
if event_type == "GameUserLeave":
break
user_id = event["_userid"]["m_userId"]
player_id = user_id + 1
if player_id < 1 or player_id > 2:
raise ValueError(f"Unexpected player_id: {player_id}")
if (action_frames[player_id] and
action_frames[player_id][-1].game_loop == game_loop):
# Later (non-camera) events on the same game loop take priority.
if event_type != "CameraUpdate":
action_frames[player_id][-1].event_type = event_type
else:
action_frames[player_id].append(EventData(game_loop, event_type))
for player_id in action_frames:
# Filter out repeated camera updates.
filtered = []
for v in action_frames[player_id]:
if (v.event_type == "CameraUpdate" and filtered and
filtered[-1].event_type == "CameraUpdate"):
filtered[-1].game_loop = v.game_loop
else:
filtered.append(v)
# If the last update is a camera move, remove it (only camera moves with a
# raw action following them should be added).
if filtered and filtered[-1].event_type == "CameraUpdate":
filtered.pop()
# Extract game loops.
action_frames[player_id] = [v.game_loop for v in filtered]
if not action_frames[player_id] or (action_frames[player_id][-1] !=
last_game_loop):
action_frames[player_id].append(last_game_loop)
return action_frames
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay/replay_converter.py | pysc2/lib/replay/replay_converter.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SC2 replay data -> converted observations."""
import collections
from typing import Any, Dict, Iterable, Sequence
import numpy as np
from pysc2.env.converter import converter as converter_lib
from pysc2.env.converter import derive_interface_options
from pysc2.env.converter.proto import converter_pb2
from pysc2.lib.replay import replay_observation_stream
from pysc2.lib.replay import sc2_replay
from pysc2.lib.replay import sc2_replay_utils
import tree
from s2clientprotocol import sc2api_pb2
def _unconverted_observation(observation, actions):
return converter_pb2.Observation(
player=observation[0],
opponent=observation[1],
force_action=sc2api_pb2.RequestAction(
actions=actions
),
# This will be populated when we look ahead.
force_action_delay=0,
)
def get_flat_action(obs: Dict[str, Any]) -> Dict[str, Any]:
"""Extracts action, with components starting action/, from an observation."""
result = {
k[len('action/'):]: v for k, v in obs.items() if k.startswith('action/')
}
if not result:
raise ValueError(f'Failed to parse action from observation: {obs}')
return result
def _convert_observation(converter, player_observation, force_action_delay,
force_action_fn):
"""Convert a raw observation proto and set action delay."""
player_observation.force_action_delay = force_action_delay
converted_observation = converter.convert_observation(player_observation)
converter.convert_action(force_action_fn(converted_observation))
def _squeeze_if_necessary(x):
if x.shape == (1,):
return np.squeeze(x)
return x
return tree.map_structure(_squeeze_if_necessary, converted_observation)
def converted_observations(observations_iterator, converter, accept_step_fn,
force_action_fn=get_flat_action):
"""Generator of transformed observations (incl. action and time delay)."""
current_observation = next(observations_iterator)
current_step = current_observation[0].observation.game_loop
assert current_step == 0
player_obs_queue = collections.deque()
for next_observation in observations_iterator:
step = next_observation[0].observation.game_loop
if (step == 0 or (current_step > 0 and not accept_step_fn(step - 1))):
# Save the observation even if it didn't have any actions. The step
# stream also yields the observations immediately before the actions
# are reported to capture the time the player actually issued the
# action. If actions were reported at time steps t1 and t2
# subsequently, we need to yield observation at step t2-1 instead of
# t1 (this is also what is recorded in the action skips dataset).
current_observation = next_observation
continue
player_obs_queue.append(_unconverted_observation(
observation=current_observation,
actions=next_observation[0].actions))
while len(player_obs_queue) >= 2:
# We have saved at least 2 observations in the queue, we can now
# correctly calculate the true action delay.
player_obs = player_obs_queue.popleft()
player_obs_next = player_obs_queue[0]
converted_observation = _convert_observation(
converter,
player_obs,
force_action_delay=(player_obs_next.player.observation.game_loop -
player_obs.player.observation.game_loop),
force_action_fn=force_action_fn)
yield converted_observation
current_step = step
current_observation = next_observation
# Always use last observation, it contains the player result.
player_obs_queue.append(_unconverted_observation(
observation=current_observation,
actions=current_observation[0].actions))
previous_delay = 1
while player_obs_queue:
player_obs = player_obs_queue.popleft()
if len(player_obs_queue) >= 1:
player_obs_next = player_obs_queue[0]
force_action_delay = (player_obs_next.player.observation.game_loop -
player_obs.player.observation.game_loop)
else:
# Use previous force action delay, this is only done in the last step.
# Preserve for reproducibility. In theory the actual delay value
# shouldn't matter if we retrain checkpoints, since the actions from
# the last step are never taken.
force_action_delay = previous_delay
converted_observation = _convert_observation(
converter,
player_obs,
force_action_delay=force_action_delay,
force_action_fn=force_action_fn)
previous_delay = force_action_delay
yield converted_observation
def converted_observation_stream(
replay_data: bytes,
player_id: int,
converter_settings: converter_pb2.ConverterSettings,
disable_fog: bool = False,
max_steps: int = int(1e6)):
"""Generator of transformed observations (incl. action and time delay)."""
with replay_observation_stream.ReplayObservationStream(
step_mul=1,
game_steps_per_episode=max_steps,
add_opponent_observations=True,
interface_options=derive_interface_options.from_settings(
converter_settings),
disable_fog=disable_fog,
) as replay_stream:
replay_stream.start_replay_from_data(replay_data, player_id=player_id)
obs_converter = converter_lib.Converter(
converter_settings,
environment_info=converter_pb2.EnvironmentInfo(
game_info=replay_stream.game_info(),
replay_info=replay_stream.replay_info()))
replay_file = sc2_replay.SC2Replay(replay_data)
action_skips = sc2_replay_utils.raw_action_skips(replay_file)
player_action_skips = action_skips[player_id]
step_sequence = get_step_sequence(player_action_skips)
observations_iterator = replay_stream.observations(
step_sequence=step_sequence)
def _accept_step_fn(step):
return step in player_action_skips
yield from converted_observations(observations_iterator, obs_converter,
_accept_step_fn)
# Current step sequence will yield observations right before
# the last camera move in a contiguous sequence of camera moves. Consider
# whether we want to change the observation at which the camera action is being
# reported.
def get_step_sequence(action_skips: Iterable[int]) -> Sequence[int]:
"""Generates a sequence of step muls for the replay stream.
In SC2 we train on observations with actions but actions in replays are
reported in frames after they were taken. We need a step sequence so we can
advance the SC2 environment to the relevant observations before the action was
taken and then step again with delta=1 to get the actual action on the next
frame. A step sequence is key from a performance point of view since at the
steps where no actions were taken we do not really need to render which is the
expensive part of processing a replay. We can advance the simulation without
rendering at a relatively low cost.
An example stream looks like this:
(obs_{0},)------(obs_{k-1},)---(obs_{k}, a_{k-1})---(obs_{k+1}, a_{k})...
The first observation where an action was taken is `obs_{k-1}`, but the replay
will not report the action until we request the next observation `obs_{k}`.
In the above case we also have an action taken at timestep k, but it will be
reported when we request `obs_{k+1}`. A step sequence would allow us to
get a union of the observations that we want to report for training and
those that have actions in them. An example step sequence for the above stream
would be `[k-1, 1, 1]` where we first step k-1 times to get to the first
observation where an action was taken, then step once to get the actual action
as it is reported late.
Args:
action_skips: A sequence of game loops where actions were taken in the
replay. This contains the game loops of the observations that happened
before the action was reported by the replay to align it with the time
step when the player took the action (replays report past actions). Note
that the provided action skips sequence is assumed to have already been
processed to include only relevant frames depending on the action types of
interest (e.g., with or without camera moves).
Returns:
A sequence of step_muls to use in the replay stream.
"""
prev_game_loop = 0
steps = []
for current_game_loop in action_skips:
if prev_game_loop == 0:
steps.append(current_game_loop)
elif current_game_loop - prev_game_loop > 1:
# We need to yield twice: to get the observation immediately before the
# action (this is the game loop number we stored in the index), and to
# get the replay observation that will return the actual actions. This
# is needed because replays return actions that humans have taken on
# previous frames.
steps.append(1)
steps.append(current_game_loop - prev_game_loop - 1)
elif current_game_loop - prev_game_loop == 1:
# Both previous and current observations had actions, step 1.
steps.append(1)
prev_game_loop = current_game_loop
return steps
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay/__init__.py | pysc2/lib/replay/__init__.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/pysc2/lib/replay/sc2_replay.py | pysc2/lib/replay/sc2_replay.py | # Copyright 2021 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility functions for loading replay data using the s2protocol library."""
import io
import json
import types
import mpyq
from s2protocol import versions as s2versions
import tree
def _convert_to_str(s):
if isinstance(s, bytes):
return bytes.decode(s)
else:
return s
def _convert_all_to_str(structure):
if isinstance(structure, types.GeneratorType):
return tree.map_structure(_convert_to_str, list(structure))
else:
return tree.map_structure(_convert_to_str, structure)
class SC2Replay(object):
"""Helper class for loading and extracting data using s2protocol library."""
def __init__(self, replay_data):
"""Construct SC2Replay helper for extracting data from a replay."""
(self._header, self._metadata, self._extracted,
self._protocol) = _extract(replay_data)
def details(self):
details_key = b"replay.details"
if details_key not in self._extracted:
details_key = b"replay.details.backup"
return _convert_all_to_str(
self._protocol.decode_replay_details(self._extracted[details_key]))
def init_data(self):
return _convert_all_to_str(
self._protocol.decode_replay_initdata(
self._extracted[b"replay.initData"]))
def tracker_events(self, filter_fn=None):
"""Yield tracker events from the replay in s2protocol format."""
for event in _convert_all_to_str(
self._protocol.decode_replay_tracker_events(
self._extracted[b"replay.tracker.events"])):
if not filter_fn or filter_fn(event):
yield event
def game_events(self, filter_fn=None):
"""Yield game events from the replay in s2protocol format."""
for event in _convert_all_to_str(
self._protocol.decode_replay_game_events(
self._extracted[b"replay.game.events"])):
if not filter_fn or filter_fn(event):
yield event
def message_events(self, filter_fn=None):
"""Yield message events from the replay in s2protocol format."""
for event in _convert_all_to_str(
self._protocol.decode_replay_message_events(
self._extracted[b"replay.message.events"])):
if not filter_fn or filter_fn(event):
yield event
def attributes_events(self, filter_fn=None):
"""Yield attribute events from the replay in s2protocol format."""
for event in _convert_all_to_str(
self._protocol.decode_replay_attributes_events(
self._extracted[b"replay.attributes.events"])):
if not filter_fn or filter_fn(event):
yield event
@property
def metadata(self):
return self._metadata
@property
def protocol(self):
return self._protocol
def _extract(contents):
"""Extract a replay using s2protocol."""
replay_io = io.BytesIO()
replay_io.write(contents)
replay_io.seek(0)
archive = mpyq.MPQArchive(replay_io)
extracted = archive.extract()
metadata = json.loads(
bytes.decode(extracted[b"replay.gamemetadata.json"], "utf-8"))
contents = archive.header["user_data_header"]["content"]
header = s2versions.latest().decode_replay_header(contents)
base_build = header["m_version"]["m_baseBuild"]
protocol = s2versions.build(base_build)
if protocol is None:
raise ValueError("Could not load protocol {} for replay".format(base_build))
return header, metadata, extracted, protocol
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/__init__.py | llm_pysc2/__init__.py | python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false | |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/llm_pysc2_agent_main.py | llm_pysc2/agents/llm_pysc2_agent_main.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.lib.llm_communicate import communication_info_transmission
from llm_pysc2.lib.data_recorder import DataRecorder
from llm_pysc2.agents.main_agent_funcs import *
from llm_pysc2.agents.configs import ProtossAgentConfig
from llm_pysc2.agents.llm_pysc2_agent import LLMAgent
from pysc2.agents import base_agent
from pysc2.lib import actions
from collections import deque
from shutil import copyfile
from loguru import logger
import threading
import datetime
import random
import time
import sys
import os
llm_pysc2_global_log_id = 0
# multi thread query, target function
def thread_act(agent, obs):
agent.query(obs)
# Main Agent, for interacting with pysc2 env
class MainAgent(base_agent.BaseAgent):
def __init__(self, config=ProtossAgentConfig(), SubAgent=LLMAgent):
super(MainAgent, self).__init__()
"""initalize the main agent"""
self.start_time = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
self.config = config
self.AGENT_NAMES = list(self.config.AGENTS.keys())
self.race = self.config.race
self._initialize_variables()
self._initialize_logger()
self.config.auto_check(self.log_id)
self._initialize_agents(SubAgent)
self._initialize_data_recorder()
logger.success(f"[ID {self.log_id}] Main Agent successfully initialized!")
def _logger_filter_function(self, record):
return f"[ID {self.log_id}]" in record["message"]
def _initialize_variables(self):
self.main_loop_lock = False
self.main_loop_step_old = 0
self.main_loop_step = 0
self.game_time_last = 0
self.unit_selected_tag_list = []
self.temp_team_unit_tags = None
self.temp_head_unit_tag = None
self.temp_curr_unit_tag = None
self.temp_head_unit = None
self.temp_curr_unit = None
self.agent_id = 0
self.size_screen = 0
self.size_minimap = 0
self.camera_threshold = 0.15
self.select_rect_threshold = 1
self.num_step = -1
self.world_range = 0
self.world_x_offset = 0
self.world_y_offset = 0
self.world_xy_calibration = False
self.first_select_unit_tag = None
self.last_two_camera_pos = deque(maxlen=2)
self.last_two_camera_pos.append([-1, -1])
self.last_two_camera_pos.append([-1, -1])
self.new_unit_tag = None
self.new_unit_type = None
self.temp_flag = None
self.unit_uid = list()
self.unit_uid_dead = list()
self.unit_uid_disappear = list()
self.unit_uid_appear = list()
self.unit_uid_total = list()
self.unit_disappear_steps = dict()
# self.possible_disappear_unit_list = list()
self.func_id_history = deque(maxlen=20)
self.obs_history = deque(maxlen=5)
self.nexus_info_dict = {}
self.possible_working_place_tag_list = []
self.possible_working_place_nexus = []
self.stop_worker_nexus_tag = None
self.stop_worker_at = None
self.stop_worker = None
self.idle_nexus = None
def _initialize_logger(self):
global llm_pysc2_global_log_id
time.sleep(random.random())
base_log_dir = f"{os.path.dirname(os.path.abspath(__file__))}/../../llm_log"
if not os.path.exists(base_log_dir):
os.mkdir(base_log_dir)
if not os.path.exists(base_log_dir + f"/log_show.py"):
copyfile(f"{os.path.dirname(os.path.abspath(__file__))}/../lib/log_show.py", base_log_dir + f"/log_show.py")
if not os.path.exists(base_log_dir + f"/log_analyse.py"):
copyfile(f"{os.path.dirname(os.path.abspath(__file__))}/../lib/log_analyse.py", base_log_dir + f"/log_analyse.py")
self.log_id = -1
while True:
self.log_id += 1
self.log_dir_path = f"{os.path.dirname(os.path.abspath(__file__))}/../../llm_log/{self.start_time}-{self.log_id}"
if not os.path.exists(self.log_dir_path) and self.log_id == llm_pysc2_global_log_id + 1:
llm_pysc2_global_log_id += 1
self.log_error_path = self.log_dir_path + f"/log_error.txt"
self.log_success_path = self.log_dir_path + f"/log_success.txt"
self.log_debug_path = self.log_dir_path + f"/log_debug.txt"
self.log_info_path = self.log_dir_path + f"/log_info.txt"
os.mkdir(self.log_dir_path)
break
if not os.path.exists(self.log_error_path):
with open(self.log_error_path, 'w') as f:
print(self.start_time, file=f)
if not os.path.exists(self.log_success_path):
with open(self.log_success_path, 'w') as f:
print(self.start_time, file=f)
if not os.path.exists(self.log_debug_path):
with open(self.log_debug_path, 'w') as f:
print(self.start_time, file=f)
if not os.path.exists(self.log_info_path):
with open(self.log_info_path, 'w') as f:
print(self.start_time, file=f)
logger.add(self.log_error_path, level="ERROR", rotation="100 MB", catch=True, filter=self._logger_filter_function)
logger.add(self.log_success_path, level="SUCCESS", rotation="100 MB", catch=True, filter=self._logger_filter_function)
logger.add(self.log_debug_path, level="DEBUG", rotation="100 MB", catch=True, filter=self._logger_filter_function)
logger.add(self.log_info_path, level="INFO", rotation="100 MB", catch=True, filter=self._logger_filter_function)
if self.log_id == 1:
try:
logger.remove(handler_id=0)
logger.add(sys.stderr, level="INFO", catch=True, filter=self._logger_filter_function)
except:
pass
def _initialize_agents(self, SubAgent):
self.agents = {}
self.agents_query_llm_times = {}
self.agents_executing_times = {}
for agent_name in self.AGENT_NAMES:
self.agents[agent_name] = SubAgent(agent_name, self.log_id, self.start_time, self.config)
self.agents[agent_name].enable = True if (agent_name in ['Commander', 'Developer']) else False
# self.agents[agent_name].flag_enable_empty_unit_group = True if (agent_name in ['Developer']) else False
for team in self.config.AGENTS[agent_name]['team']:
if team['name'] == 'Empty' and len(team['unit_type']) == 0:
self.agents[agent_name].flag_enable_empty_unit_group = True
self.agents_query_llm_times[agent_name] = 0
self.agents_executing_times[agent_name] = 0
self.agents[agent_name].log_id = self.log_id
def _initialize_data_recorder(self):
self.data_recorder = DataRecorder(self.log_dir_path, save_level=0)
def _all_agent_query_llm_finished(self):
for agent_name in self.AGENT_NAMES:
agent = self.agents[agent_name]
if agent.enable and agent.query_llm_times == self.main_loop_step:
return False
return True
def _all_agent_waiting_response_finished(self):
for agent_name in self.AGENT_NAMES:
agent = self.agents[agent_name]
if agent.enable and (agent.query_llm_times == self.main_loop_step + 1) and agent._is_waiting_response():
return False
return True
def _all_agent_executing_finished(self):
for agent_name in self.AGENT_NAMES:
agent = self.agents[agent_name]
if agent.enable and agent.executing_times == self.main_loop_step:
return False
return True
def step(self, obs):
super(MainAgent, self).step(obs)
# main agent control data updates
agent_name = None
self.obs_history.append(obs)
self.data_recorder.step(obs, self.episodes, self.steps)
if len(self.func_id_history) > 0 and self.func_id_history[-1] == 573:
self.camera_threshold += 0.05
elif len(self.func_id_history) > 0 and self.func_id_history[-1] == 3:
self.select_rect_threshold *= 2
else:
self.select_rect_threshold = 1 * int(self.size_screen / 128) if self.size_screen != 0 else 1
self.camera_threshold = 0.15
if self.main_loop_step_old != self.main_loop_step:
self.main_loop_step_old = self.main_loop_step
self.main_loop_lock = False
logger.success(f"[ID {self.log_id}] " + '========== ' + '==' * 25 + f" Loop {self.main_loop_step} " + '==' * 25 + ' ==========')
logger.success(f"[ID {self.log_id}] " + '---------- ' + '--' * 25 + f" Step {self.steps} " + '--' * 25 + ' ----------')
func_id, func_call = (0, actions.FUNCTIONS.no_op())
# initial steps and camera calibration (necessary)
func_call = main_agent_func0(self, obs)
if func_call is not None:
logger.success(f"[ID {self.log_id}] main_agent_func0: Func Call {func_call}")
return func_call
# unit grouping, add to relevant agent.teams (necessary)
func_call = main_agent_func1(self, obs)
if func_call is not None:
logger.success(f"[ID {self.log_id}] main_agent_func1: Func Call {func_call}")
return func_call
# auto worker-management (optional)
func_call = main_agent_func2(self, obs)
if func_call is not None:
logger.success(f"[ID {self.log_id}] main_agent_func2: Func Call {func_call}")
return func_call
# auto worker-training (optional)
func_call = main_agent_func3(self, obs)
if func_call is not None:
logger.success(f"[ID {self.log_id}] main_agent_func3: Func Call {func_call}")
return func_call
# auto team gathering (optional)
func_call = main_agent_func4(self, obs)
if func_call is not None:
logger.success(f"[ID {self.log_id}] main_agent_func4: Func Call {func_call}")
return func_call
# SubAgent data update
for agent_name in self.AGENT_NAMES:
agent = self.agents[agent_name]
agent.num_step = self.steps
agent.main_loop_step = self.main_loop_step
agent.world_range = self.world_range
agent.world_x_offset = self.world_x_offset
agent.world_y_offset = self.world_y_offset
agent.size_screen = self.size_screen
agent.size_minimap = self.size_minimap
agent.update(obs)
for agent_name in self.AGENT_NAMES:
agent = self.agents[agent_name]
agent.other_agents = {}
if agent.name in ['Commander', 'Developer']:
for agent_name2 in self.AGENT_NAMES:
if agent_name2 not in ['Commander', 'Developer']:
agent.other_agents[agent_name2] = self.agents[agent_name2]
# critical data log
main_agent_func_critical_data_log(self, obs)
# LLM decision frequency control
game_time_s = obs.observation.game_loop / 22.4
if not self.main_loop_lock and game_time_s - self.game_time_last < 1 / self.config.MAX_LLM_DECISION_FREQUENCY:
logger.warning(f"[ID {self.log_id}] Reach MAX_LLM_DECISION_FREQUENCY! return no_op()")
func_id, func_call = (0, actions.FUNCTIONS.no_op())
self.func_id_history.append(func_id)
return func_call
# skip main loop if no agent enabled
all_agent_disabled = True
for agent_name in self.AGENT_NAMES:
if self.agents[agent_name].enable:
all_agent_disabled = False
if all_agent_disabled:
logger.warning(f"[ID {self.log_id}] All agent disabled! return no_op()")
func_id, func_call = (0, actions.FUNCTIONS.no_op())
self.func_id_history.append(func_id)
return func_call
# communication and ready to enter main loop
if self.main_loop_lock is False:
self.main_loop_lock = True
self.game_time_last = game_time_s
communication_info_transmission(self)
logger.success(f"[ID {self.log_id}] 7.0 Main Loop Lock! Ignore outer-loop actions. ")
# Main Loop
t0 = float(time.time())
while float(time.time()) - t0 < self.config.MAX_LLM_WAITING_TIME:
time.sleep(0.001)
agent_name = self.AGENT_NAMES[self.agent_id]
agent = self.agents[self.AGENT_NAMES[self.agent_id]]
func_id, func_call = (None, None)
if not agent.enable: # agent finished query, skip current agent
self.agent_id = (self.agent_id + 1) % len(self.AGENT_NAMES)
continue
if not self._all_agent_query_llm_finished():
if not agent._is_waiting_query():
logger.error(f"[ID {self.log_id}] 7.0 Agent {agent_name}: status should not exist")
logger.debug(f"[ID {self.log_id}] Agent Info: {len(agent.func_list)} {len(agent.action_list)} {len(agent.action_lists)} {agent.is_waiting}")
# for team in agent.teams:
# logger.debug(f"[ID {self.log_id}] Team Infos:{team}")
agent.func_list, agent.action_list, agent.action_lists = [], [], [] # TODO: Test this
self.agent_id = (self.agent_id + 1) % len(self.AGENT_NAMES)
# continue
else: # collect obs and query llm
logger.info(f"[ID {self.log_id}] 7.1 Agent {agent_name}: query status")
# agent teams' obses all collected, start query llm
if agent._is_all_my_teams_ready_to_query():
if agent.flag_enable_empty_unit_group: # Commander Developer最后一个单位群是空群,用于作战部署或发布训练/研究动作
logger.info(f"[ID {self.log_id}] 7.1.1 Agent {agent_name}: Add obs for empty_unit_group")
for team in agent.teams:
if team['name'] == 'Empty':
agent.team_unit_obs_list.append(obs)
team['obs'].append(obs)
logger.info(f"[ID {self.log_id}] 7.1.2 Agent {agent_name}: Obs prepared, try calling LLM api")
logger.debug(f"[ID {self.log_id}] len(agent.team_unit_obs_list) = {len(agent.team_unit_obs_list)}")
logger.debug(f"[ID {self.log_id}] len(agent.team_unit_tag_list) = {len(agent.team_unit_tag_list)}")
logger.debug(f"[ID {self.log_id}] len(agent.team_unit_team_list) = {len(agent.team_unit_team_list)}")
agent.thread = threading.Thread(target=thread_act, args=(agent, obs))
agent.thread.start()
agent.query_llm_times += 1
self.agent_id = (self.agent_id + 1) % len(self.AGENT_NAMES)
self.unit_selected_tag_list = []
if self._all_agent_query_llm_finished():
logger.success(f"[ID {self.log_id}] 7.2 All Agent waiting for response")
else:
# obtain team and head unit tag
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.1.3")
team, tag = agent._get_unobsed_team_and_unit_tag()
# Move camera
func_id, func_call = get_camera_func_smart(self, obs, tag, threshold=self.camera_threshold)
if func_id == 573:
logger.success(f"[ID {self.log_id}] 7.1.4 Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
# Find team head unit
unit_f = None
for unit in obs.observation.feature_units:
if unit.tag == tag:
unit_f = unit
if unit_f is None:
logger.error(f"[ID {self.log_id}] Agent {agent_name}: unit of tag {tag} not found")
logger.error(f"[ID {self.log_id}] relative team = {team}")
logger.error(f"[ID {self.log_id}] unit_f is None")
if tag in team['unit_tags']:
team['unit_tags'].remove(tag)
if tag in agent.unit_tag_list:
agent.unit_tag_list.remove(tag)
agent.update(obs)
time.sleep(1)
continue
# Select unit
if not unit_f.is_selected:
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.1.5")
if team['select_type'] == 'select':
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.1.5.1")
if self.func_id_history[-1] in [2, 3]:
d = self.select_rect_threshold
x1, x2 = min(max(0, unit_f.x - d), self.size_screen), min(max(0, unit_f.x + d), self.size_screen)
y1, y2 = min(max(0, unit_f.y - d), self.size_screen), min(max(0, unit_f.y + d), self.size_screen)
func_id, func_call = (3, actions.FUNCTIONS.select_rect('select', (x1, y1), (x2, y2)))
else:
x, y = min(max(0, unit_f.x), self.size_screen), min(max(0, unit_f.y), self.size_screen)
func_id, func_call = (2, actions.FUNCTIONS.select_point('select', (x, y)))
logger.success(f"[ID {self.log_id}] 7.1.5.1 Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
elif team['select_type'] == 'select_all_type':
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.1.5.2")
if self.func_id_history[-1] in [2, 3]:
d = self.select_rect_threshold
x1, x2 = min(max(0, unit_f.x - d), self.size_screen), min(max(0, unit_f.x + d), self.size_screen)
y1, y2 = min(max(0, unit_f.y - d), self.size_screen), min(max(0, unit_f.y + d), self.size_screen)
func_id, func_call = (3, actions.FUNCTIONS.select_rect('select', (x1, y1), (x2, y2)))
else:
x, y = min(max(0, unit_f.x), self.size_screen), min(max(0, unit_f.y), self.size_screen)
func_id, func_call = (2, actions.FUNCTIONS.select_point('select_all_type', (x, y)))
logger.success(f"[ID {self.log_id}] 7.1.5.1 Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
elif team['select_type'] == 'group':
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.1.5.3")
func_id, func_call = (4, actions.FUNCTIONS.select_control_group('recall', int(team['game_group'])))
logger.success(f"[ID {self.log_id}] 7.1.5.1 Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
else:
logger.error(f"[ID {self.log_id}] 7.1.2.4 Agent {agent_name}: Un-Recogniziable select type")
time.sleep(5) # this error may lead to endless loop
pass
# # Recheck all required unit selected (Warning: May Lead To Possible Endless Loop)
# for unit in obs.observation.feature_units:
# if team['select_type'] == 'select_all_type' and \
# unit.unit_type == unit_f.unit_type and not unit.is_selected and \
# 0.15 * self.size_screen < unit.x < 0.85 * self.size_screen and \
# 0.15 * self.size_screen < unit.y < 0.85 * self.size_screen:
# logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.1.5.4")
# func_id, func_call = (2, actions.FUNCTIONS.select_point('select_all_type', (unit_f.x, unit_f.y)))
# logger.success(f"[ID {self.log_id}] 7.1.5.4 Agent {agent_name}: Func Call: {func_call}")
# self.func_id_history.append(func_id)
# return func_call
# collect obs for the team
if unit_f.is_selected:
logger.info(f"[ID {self.log_id}] 7.1.6 Agent {agent_name}: collect obs for team {team['name']}")
logger.info("--" * 25)
team['unit_tags_selected'] = []
for unit in obs.observation.raw_units:
if unit.tag == tag:
x, y = get_camera_xy(self, unit.x, unit.y)
team['pos'].append([x, y])
if unit.is_selected and unit.is_on_screen:
team['unit_tags_selected'].append(unit.tag)
team['obs'].append(obs)
agent.team_unit_obs_list.append(obs) # collect team obs
agent.team_unit_tag_list.append(tag)
agent.team_unit_team_list.append(team['name'])
idx = np.nonzero(obs.observation['feature_minimap']['camera']) # 获取特征图上非零值的坐标
minimap_x, minimap_y = int(idx[:][1].mean()), int(idx[:][0].mean())
team['minimap_pos'].append([minimap_x, minimap_y])
elif not self._all_agent_waiting_response_finished():
continue
elif not self._all_agent_executing_finished():
# agent's teams' actions all executed
if not agent._is_executing_actions():
logger.info(f"[ID {self.log_id}] 7.3.0 Agent {agent_name}: finished executing!")
agent.executing_times = self.main_loop_step + 1
agent.team_unit_obs_list = []
agent.team_unit_tag_list = []
agent.team_unit_team_list = []
for i in range(len(agent.teams)):
agent.teams[i]['obs'] = []
agent.teams[i]['pos'] = []
# agent.teams[i]['unit_tags_selected'] = []
self.agent_id = (self.agent_id + 1) % len(self.AGENT_NAMES)
continue
else:
logger.info(f"[ID {self.log_id}] 7.3.1 Agent {agent_name}: executing status")
# obtain actions of next team
if len(agent.func_list) == 0 and len(agent.action_list) == 0 and len(agent.action_lists) > 0:
# standard team
if len(agent.team_unit_tag_list) != 0: # not (agent.flag_enable_empty_unit_group) or
logger.debug(f"[ID {self.log_id}] Agent {agent_name}, status: 7.3.1.1")
agent.action_list = agent.action_lists.pop(0)
agent.team_unit_tag_curr = agent.team_unit_tag_list.pop(0)
agent.team_unit_team_curr = agent.team_unit_team_list.pop(0)
# empty team (only for spesified empty team)
else:
logger.debug(f"[ID {self.log_id}] Agent {agent_name}, status: 7.3.1.2")
agent.action_list = agent.action_lists.pop(0)
# empty team excuting actions (only for spesified empty team)
if (agent.flag_enable_empty_unit_group and len(agent.team_unit_tag_list) == 0):
logger.debug(f"[ID {self.log_id}] Agent {agent_name}, status: 7.3.5")
func_id, func_call = agent.get_func(obs)
self.func_id_history.append(func_id)
# standard team excuting actions
else:
# get current action name and args
if len(agent.func_list) == 0 and len(agent.action_list) != 0:
agent.curr_action_name = agent.action_list[0]['name']
agent.curr_action_args = agent.action_list[0]['arg']
# obtain team and head unit tag
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.3.2")
team, tag = agent._get_unacted_team_and_unit_tag()
if tag == None: # single select team, unit dead / multi select team, all unit dead, relese actions
agent.func_list = []
agent.action_list = []
continue
unit_f = None
unit_r = None
for unit in obs.observation.raw_units:
if unit.tag == tag:
unit_r = unit
if len(agent.func_list) == 0 and ('Select_Unit_' not in agent.curr_action_name):
# Move camera
func_id, func_call = get_camera_func_smart(self, obs, tag, threshold=self.camera_threshold, team=team)
if func_id == 573:
logger.success(f"[ID {self.log_id}] 7.3.2.0 Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
# Find team head unit
for unit in obs.observation.feature_units:
if unit.tag == tag:
unit_f = unit
if unit_f is None:
logger.error(f"[ID {self.log_id}] 7.3.2.1 Agent {agent_name}: unit of tag {tag} not found")
logger.error(f"[ID {self.log_id}] relative team = {team['name']} {team['unit_tags']}")
func_id, func_call = agent.get_func(obs) # 销掉这个动作
logger.error(f"[ID {self.log_id}] 7.3.4 Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
time.sleep(1)
# Unit select
if (unit_f is not None and not unit_f.is_selected):
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.3.3")
if team['select_type'] == 'select':
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.3.3.1")
if self.func_id_history[-1] in [2, 3]:
d = self.select_rect_threshold
x1, x2 = min(max(0, unit_f.x - d), self.size_screen), min(max(0, unit_f.x + d), self.size_screen)
y1, y2 = min(max(0, unit_f.y - d), self.size_screen), min(max(0, unit_f.y + d), self.size_screen)
func_id, func_call = (3, actions.FUNCTIONS.select_rect('select', (x1, y1), (x2, y2)))
else:
x, y = min(max(0, unit_f.x), self.size_screen), min(max(0, unit_f.y), self.size_screen)
func_id, func_call = (2, actions.FUNCTIONS.select_point('select', (x, y)))
logger.success(f"[ID {self.log_id}] Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
elif team['select_type'] == 'select_all_type':
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.3.3.2")
if self.func_id_history[-1] in [2, 3]:
d = self.select_rect_threshold
x1, x2 = min(max(0, unit_f.x - d), self.size_screen), min(max(0, unit_f.x + d), self.size_screen)
y1, y2 = min(max(0, unit_f.y - d), self.size_screen), min(max(0, unit_f.y + d), self.size_screen)
func_id, func_call = (3, actions.FUNCTIONS.select_rect('select', (x1, y1), (x2, y2)))
else:
x, y = min(max(0, unit_f.x), self.size_screen), min(max(0, unit_f.y), self.size_screen)
func_id, func_call = (2, actions.FUNCTIONS.select_point('select_all_type', (x, y)))
logger.success(f"[ID {self.log_id}] Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
elif team['select_type'] == 'group':
logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.3.3.3")
func_id, func_call = (4, actions.FUNCTIONS.select_control_group('recall', int(team['game_group'])))
logger.success(f"[ID {self.log_id}] Agent {agent_name}: Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
else:
logger.error(f"[ID {self.log_id}] 7.3.3.4 Agent {agent_name}: un-recogniziable select type")
time.sleep(5) # this error may lead to endless loop
pass
# # Recheck all required unit selected (Warning: May Lead To Possible Endless Loop)
# for unit in obs.observation.feature_units:
# if team['select_type'] == 'select_all_type' and \
# unit.unit_type == unit_f.unit_type and not unit.is_selected and \
# 0.15 * self.size_screen < unit.x < 0.85 * self.size_screen and \
# 0.15 * self.size_screen < unit.y < 0.85 * self.size_screen:
# logger.debug(f"[ID {self.log_id}] Agent {agent_name} status: 7.3.3.5")
# x, y = min(max(0, unit_f.x), self.size_screen), min(max(0, unit_f.y), self.size_screen)
# func_id, func_call = (2, actions.FUNCTIONS.select_point('select_all_type', (x, y)))
# logger.success(f"[ID {self.log_id}] 7.3.3.5 Agent {agent_name}: Func Call: {func_call}")
# self.func_id_history.append(func_id)
# return func_call
# get pysc2 function of current action
if (unit_f is not None and unit_f.is_selected) or \
('Select_Unit_' in agent.curr_action_name) or \
len(agent.func_list) != 0:
func_id, func_call = agent.get_func(obs)
logger.info(f"[ID {self.log_id}] 7.3.4 Agent {agent_name}: agent.get_func(obs): get {func_call}")
self.func_id_history.append(func_id)
# mark units that finished excution
for unit in obs.observation.raw_units:
if unit.is_selected and unit.is_on_screen:
self.unit_selected_tag_list.append(unit.tag)
self.unit_selected_tag_list = list(set(self.unit_selected_tag_list))
else:
# all agent' teams finished excution, release main_loop_lock to enable auto management fo workers, bases, etc.
logger.success(f"[ID {self.log_id}] 7.3.5 Agent {agent_name}: One loop finished, release self.main_loop_lock")
self.main_loop_step += 1
self.main_loop_lock = False # release main_loop_lock to enable auto management
func_id, func_call = (0, actions.FUNCTIONS.no_op())
self.func_id_history.append(func_id)
return func_call
# execute function of current agent's current action
if func_id != 0:
if func_id in obs.observation.available_actions:
logger.success(f"[ID {self.log_id}] 7.4 Agent {agent_name} Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
else:
if func_id is not None:
logger.error(f"[ID {self.log_id}] 7.5.1 Agent {agent_name} Func Call Invalid, Skipped: {func_call}")
# execute no-operation function while reach waiting time
func_id, func_call = (0, actions.FUNCTIONS.no_op())
logger.warning(f"[ID {self.log_id}] Reach MAX_LLM_WAITING_TIME! {agent_name} Call no_op()")
logger.warning(f"[ID {self.log_id}] Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/__init__.py | llm_pysc2/agents/__init__.py |
from llm_pysc2.agents.llm_pysc2_agent_main import MainAgent
from llm_pysc2.agents.llm_pysc2_agent import LLMAgent
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/llm_pysc2_agent.py | llm_pysc2/agents/llm_pysc2_agent.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs import AgentConfig, ProtossAgentConfig
from llm_pysc2.lib import llm_client, llm_observation, llm_action, llm_prompt, llm_communicate
from pysc2.lib import actions
from shutil import copyfile
from loguru import logger
import threading
import time
import json
import math
import os
class LLMAgent:
def __init__(self,
name: str,
log_id: int,
start_time: str,
config: "AgentConfig" = ProtossAgentConfig(),
):
# basic info
self.name = name
self.log_id = log_id
self.config = config
self.start_time = start_time
self.race = self.config.race
self.available_unit_type = []
for team in self.config.AGENTS[self.name]['team']:
self.available_unit_type += team['unit_type']
# llm client, obs wrapper and action recognizer initialize
basic_prompt = self.config.AGENTS[self.name]['llm']['basic_prompt']
translator_o = self.config.AGENTS[self.name]['llm']['translator_o']
translator_a = self.config.AGENTS[self.name]['llm']['translator_a']
communicator = self.config.communicator
self.api_key = self.config.AGENTS[self.name]['llm']['api_key']
self.api_base = self.config.AGENTS[self.name]['llm']['api_base']
self.model_name = self.config.AGENTS[self.name]['llm']['model_name']
self.basic_prompt = llm_prompt.FACTORY[self.race][basic_prompt](name, log_id, config)
self.translator_a = llm_action.FACTORY[self.race][translator_a](name, log_id, config)
self.translator_o = llm_observation.FACTORY[self.race][translator_o](name, log_id, config)
self.communicator = llm_communicate.FACTORY[self.race][communicator](name, log_id, config)
self.client = llm_client.FACTORY[self.model_name](name, log_id, config) # edit it to change llm client
self.client.system_prompt = self.basic_prompt.sp
self.client.example_i_prompt = self.basic_prompt.eip
self.client.example_o_prompt = self.basic_prompt.eop
# llm query thread initialize
self.thread = None
self.lock = threading.Lock()
self.enable = False
self.engage = False
self.is_waiting = False
# variables for main agent control
self.num_step = -1
self.main_loop_step = 0
self.query_llm_times = 0
self.executing_times = 0
# map info
self.world_range = -1
self.world_x_offset = -1
self.world_y_offset = -1
self.size_screen = 0
self.size_minimap = 0
# unit info
self.unit_tag_list_history = []
self.unit_raw_list = []
self.unit_tag_list = []
# team info
# [{'name': 'Z1', 'unit_type': [units.Protoss.Zealot], 'game_group': 1, 'select_type': 'group',
# 'unit_tags': [0x00012c0001, 0x00013a0001, 0x0001500001], 'unit_tags_selected': [0x00012c0001],
# 'obs':[], 'pos':[]}],
self.flag_enable_empty_unit_group = False
self.teams = self.config.AGENTS[self.name]['team']
for team in self.teams:
team['unit_tags'] = []
team['unit_tags_selected'] = []
team['obs'] = [] # collected observation
team['pos'] = [] # camera coordinate
team['minimap_pos'] = [] # for commander, get global deployment info
self.team_unit_obs_list = []
self.team_unit_tag_list = []
self.team_unit_team_list = []
self.team_unit_tag_curr = None
self.team_unit_team_curr = None
# obs
# self.agent_data_dict = {}
self.last_text_o = ''
# action
self.action_lists = []
self.action_list = []
self.func_list = []
self.curr_action_name = ''
self.curr_action_args = []
self.last_text_a_raw = ''
self.last_text_a_pro = ''
self.first_action = True
# communication
self.communication_message_i = {}
self.communication_message_o = {}
self.last_text_c_inp = ''
self.last_text_c_tar = ''
self.last_text_c_out = ''
# log
current_dir = os.path.dirname(os.path.abspath(__file__))
self.current_dir = current_dir
self.log_dir_path = f"{current_dir}/../../llm_log/{self.start_time}-{self.log_id}"
self.history_func_path = f"{current_dir}/../../llm_log/{self.start_time}-{self.log_id}/{self.name}/a_his.txt"
logger.success(f"[ID {self.log_id}] Agent {self.name} successfully initialized!")
# check if team_unit_tag_list contains all necessary unit
def _is_all_my_teams_ready_to_query(self):
for team in self.teams:
# True: all unit in team_unit_tag_list
if team['select_type'] == 'select':
ready = True
for unit_tag in team['unit_tags']:
if unit_tag not in self.team_unit_tag_list:
ready = False
# True: at least one unit in team_unit_tag_list
else:
ready = False
for unit_tag in team['unit_tags']:
if unit_tag in self.team_unit_tag_list:
ready = True
if len(team['unit_tags']) != 0 and not ready:
logger.debug(
f"[ID {self.log_id}] LLMAgent {self.name}, in _is_all_my_teams_ready_to_query(): team {team['name']} not ready")
logger.debug(
f"[ID {self.log_id}] LLMAgent {self.name}, in _is_all_my_teams_ready_to_query(): team['unit_tags'] = {team['unit_tags']}, self.team_unit_tag_list = {self.team_unit_tag_list}")
return False
return True
# get a team and its head unit to collect obs (strict pop-up order)
def _get_unobsed_team_and_unit_tag(self):
logger.debug(
f"[ID {self.log_id}] LLMAgent {self.name}, in _get_unobsed_team_and_unit_tag(): self.team_unit_tag_list = {self.team_unit_tag_list}")
for team in self.teams:
logger.debug(
f"[ID {self.log_id}] LLMAgent {self.name}, in _get_unobsed_team_and_unit_tag(): team['name'] = {team['name']}, team['unit_tags'] = {team['unit_tags']}")
if team['select_type'] == 'select':
for unit_tag in team['unit_tags']:
if unit_tag not in self.team_unit_tag_list:
return team, unit_tag
else:
if len(team['unit_tags']) > 0:
unit_tag = team['unit_tags'][0]
if unit_tag not in self.team_unit_tag_list:
return team, unit_tag
return None, None
# get a team and its head unit to execute actions (strict pop-up order)
def _get_unacted_team_and_unit_tag(self):
for team in self.teams:
if self.team_unit_team_curr == team['name']:
if team['select_type'] == 'select':
if self.team_unit_tag_curr in team['unit_tags']:
return team, self.team_unit_tag_curr
else:
return team, None
else:
if self.team_unit_tag_curr in team['unit_tags']:
return team, self.team_unit_tag_curr
elif len(team['unit_tags']) > 0:
return team, team['unit_tags'][0]
else:
return team, None
return None, None
# agent data update
def update(self, obs):
self.size_screen = obs.observation.feature_screen.height_map.shape[0]
self.size_minimap = obs.observation.feature_minimap.height_map.shape[0]
# enable agent if it has unit
if self.enable is False and len(self.unit_tag_list) > 0:
self.enable = True
self.query_llm_times = self.main_loop_step
self.executing_times = self.main_loop_step
if len(self.unit_tag_list) == 0 and 'CombatGroup' in self.name:
self.enable = False
if self.name in self.config.AGENTS_ALWAYS_DISABLE:
self.enable = False
# store all the unit tags
for tag in self.unit_tag_list:
if tag not in self.unit_tag_list_history:
self.unit_tag_list_history.append(tag)
# store all the raw unit by tags
self.unit_raw_list = []
for unit in obs.observation.raw_units:
if unit.tag in self.unit_tag_list:
self.unit_raw_list.append(unit)
# delete dead units and change head unit to the closest one (if former head unit dead)
for team in self.teams:
for unit_tag in team['unit_tags']:
if unit_tag not in self.unit_tag_list and unit_tag == team['unit_tags'][0]:
unit_r = None
unit_h = None
dist_min = 99999
for unit in self.unit_raw_list:
if unit.tag == unit_tag:
unit_r = unit
if unit_r is None:
logger.warning(
f"[ID {self.log_id}] Agent {self.name} team {team['name']} head unit {unit_tag} do not exist")
team['unit_tags'].remove(unit_tag)
continue
for unit in self.unit_raw_list:
if unit.tag in self.unit_tag_list and unit.tag in team['unit_tags']:
dist = math.sqrt((unit.x - unit_r.x) ** 2 + (unit.y - unit_r.y) ** 2)
if dist < dist_min:
dist_min = dist
unit_h = unit
if unit_h is not None:
team['unit_tags'].remove(unit_h.tag)
team['unit_tags'] = [unit_h.tag] + team['unit_tags']
if unit_tag not in self.unit_tag_list:
team['unit_tags'].remove(unit_tag)
team['unit_tags'] = list(set(team['unit_tags']))
# clear communication info for disabled agent
if not self.enable:
self.last_text_c_inp = ''
self.last_text_c_tar = ''
# log
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable:
if not os.path.exists(self.log_dir_path + f"/{self.name}"):
os.mkdir(self.log_dir_path + f"/{self.name}")
copyfile(self.current_dir + f"/../../llm_log/log_show.py", self.log_dir_path + f"/{self.name}/log_show.py")
if not os.path.exists(self.log_dir_path + f"/{self.name}/o.txt"):
with open(self.log_dir_path + f"/{self.name}/o.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/a_his.txt"):
with open(self.log_dir_path + f"/{self.name}/a_his.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/a_raw.txt"):
with open(self.log_dir_path + f"/{self.name}/a_raw.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/a_pro.txt"):
with open(self.log_dir_path + f"/{self.name}/a_pro.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/a_inp.txt") and self.config.LLM_SIMULATION_TIME > 0:
with open(self.log_dir_path + f"/{self.name}/a_inp.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/c_inp.txt") and self.config.ENABLE_COMMUNICATION:
with open(self.log_dir_path + f"/{self.name}/c_inp.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/c_out.txt") and self.config.ENABLE_COMMUNICATION:
with open(self.log_dir_path + f"/{self.name}/c_out.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/cost.txt"):
with open(self.log_dir_path + f"/{self.name}/cost.txt", "w") as f:
f.write('')
if not os.path.exists(self.log_dir_path + f"/{self.name}/prompt.txt"):
with open(self.log_dir_path + f"/{self.name}/prompt.txt", "w") as f:
f.write(self.basic_prompt.sp)
with open(self.log_dir_path + f"/{self.name}/prompt.txt", "a") as f:
f.write('--' * 25 + " example input prompt " + '--' * 25)
f.write(self.basic_prompt.eip)
f.write('--' * 25 + " example output prompt " + '--' * 25)
f.write(self.basic_prompt.eop)
# Main API Func, receive obs and get actions
def query(self, obs) -> None:
while self.is_waiting is False:
with self.lock:
self.is_waiting = True
logger.success(f"[ID {self.log_id}] LLMAgent {self.name}: Start waiting for response")
self.get_text_c_inp()
text_o = self.get_text_o(obs)
# raw_text_a = self.get_text_a(text_o)
if self.config.AGENTS[self.name]['llm']['img_rgb']:
base64_image = llm_observation.get_img_obs_rgb(self, obs)
raw_text_a = self.get_text_a(text_o, base64_image=base64_image)
elif self.config.AGENTS[self.name]['llm']['img_fea']:
base64_image = llm_observation.get_img_obs_fea(self, obs)
raw_text_a = self.get_text_a(text_o, base64_image=base64_image)
else:
raw_text_a = self.get_text_a(text_o)
action_lists, action_list_dict = self.get_func_a(raw_text_a)
self.get_info_c_out(raw_text_a)
logger.success(f"[ID {self.log_id}] LLMAgent {self.name}: Get response ")
self.first_action = True
logger.debug(f"[ID {self.log_id}] LLMAgent {self.name}: Listen to {self.communication_message_i}")
logger.debug(f"[ID {self.log_id}] LLMAgent {self.name}: Send info to {self.communication_message_o}")
with open(self.history_func_path, "a") as f:
print('--' * 50, file=f)
while self.is_waiting is True:
with self.lock:
self.is_waiting = False
self.action_lists = action_lists
# query step1: all teams' pysc2 obs to a llm obs text (or multimodal llm text)
def get_text_o(self, obs) -> str:
text_o = ''
# try:
# text_o = self.translator_o.translate(self)
# except Exception as e:
# logger.error(f"[ID {self.log_id}] Error in {self.name} get_text_o(): {e}")
text_o = self.translator_o.translate(self)
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable:
with open(self.log_dir_path + f"/{self.name}/o.txt", "a", newline='\n') as f:
print(json.dumps({self.main_loop_step: text_o}), file=f)
self.last_text_o = text_o
return text_o
# query step2: communicate with llm and get text actions
def get_text_a(self, text_o: str, base64_image=None) -> str:
text_a = ''
if self.config.LLM_SIMULATION_TIME > 0:
logger.warning(f"[ID {self.log_id}] LLM SIMULATION MODE, no remote llm involved")
time.sleep(self.config.LLM_SIMULATION_TIME) # simulate llm response, for debug
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable:
with open(self.log_dir_path + f"/{self.name}/a_inp.txt", "r") as f:
text_a = f.read() # simulate llm response by reading text in a_inp.txt
else:
if base64_image is None:
text_a = self.client.query(text_o) # Communicate with LLM
logger.debug(f"[ID {self.log_id}] LLMAgent {self.name}: No image provided to LLM.")
else:
text_a = self.client.query(text_o, base64_image=base64_image) # Communicate with VLLM
logger.debug(f"[ID {self.log_id}] LLMAgent {self.name}: Image provided to LLM.")
self.last_text_a_raw = text_a
return text_a
# query step3: text action to pysc2 functions
def get_func_a(self, raw_text_a) -> (list, dict):
new_action_lists = []
action_list_dict = {}
processed_text_a = ''
try:
new_action_lists, action_list_dict, processed_text_a = self.translator_a.translate(raw_text_a)
except Exception as e:
logger.error(f"[ID {self.log_id}] Error in {self.name} get_func_a(): {e}")
# new_action_lists, processed_text_a = self.translator_a.translate(raw_text_a)
self.last_text_a_pro = processed_text_a
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable:
with open(self.log_dir_path + f"/{self.name}/a_raw.txt", "a", newline='\n') as f:
print(json.dumps({self.main_loop_step: raw_text_a}), file=f)
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable:
with open(self.log_dir_path + f"/{self.name}/a_pro.txt", "a", newline='\n') as f:
print(json.dumps({self.main_loop_step: processed_text_a}), file=f)
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable:
with open(self.log_dir_path + f"/{self.name}/cost.txt", "a", newline='\n') as f:
c = self.client
client_cost = f"time={c.query_time:.2f}, ave_time={c.ave_query_time:.2f}, " \
f"token_in={c.query_token_in}, ave_token_in={c.ave_query_token_in:.2f}, " \
f"token_out={c.query_token_out}, ave_token_out = {c.ave_query_token_out:.2f}"
print(json.dumps({self.main_loop_step: client_cost}), file=f)
return new_action_lists, action_list_dict
# get text shaped communication
def get_text_c_inp(self) -> None:
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable and self.config.ENABLE_COMMUNICATION:
with open(self.log_dir_path + f"/{self.name}/c_inp.txt", "a", newline='\n') as f:
print(json.dumps({self.main_loop_step: self.last_text_c_inp}), file=f)
# get channel listen to and sort information to sent out
def get_info_c_out(self, raw_text_a) -> None:
self.communication_message_i, self.communication_message_o, self.last_text_c_out = self.communicator.send(raw_text_a)
if self.name not in self.config.AGENTS_ALWAYS_DISABLE and self.enable and self.config.ENABLE_COMMUNICATION:
with open(self.log_dir_path + f"/{self.name}/c_out.txt", "a", newline='\n') as f:
print(json.dumps({self.main_loop_step: self.last_text_c_out}), file=f)
def _is_waiting_query(self) -> bool:
action_lists = self._get_action_lists()
is_waiting = self._get_flag_is_waiting()
flag = True if (len(self.func_list) == 0 and len(self.action_list) == 0 and len(action_lists) == 0 and not is_waiting) else False
return flag
def _is_waiting_response(self) -> bool:
action_lists = self._get_action_lists()
is_waiting = self._get_flag_is_waiting()
flag = True if (len(self.func_list) == 0 and len(self.action_list) == 0 and len(action_lists) == 0 and is_waiting) else False
return flag
def _is_executing_actions(self) -> bool:
action_lists = self._get_action_lists()
is_waiting = self._get_flag_is_waiting()
flag = True if (len(self.func_list) != 0 or len(self.action_list) != 0 or len(action_lists) != 0) else False
return flag
def _get_flag_is_waiting(self):
# return self.is_waiting
with self.lock:
return self.is_waiting
def _get_action_lists(self):
# return self.action_lists
with self.lock:
return self.action_lists
def get_func(self, obs): # 该函数需要将当前text-pysc2动作对应的下一个pysc2函数取出,确认函数和参数是合法的,然后交给到主智能体
if len(self.func_list) == 0:
action = self.action_list.pop(0)
action = llm_action.add_func_for_select_workers(self, obs, action)
action = llm_action.add_func_for_train_and_research(self, obs, action)
self.func_list = action['func']
# self.func_list_standard = llm_a.get_text_action(self.name, action['name'])
self.curr_action_name = action['name']
self.curr_action_args = action['arg']
# for i in range(len(self.func_list)):
# logger.debug(f"[ID {self.log_id}] LLMAgent {self.name}, get_func(): self.func_list[{i}] = {self.func_list[i]}")
func_id, func, llm_pysc2_args = self.func_list.pop(0)
func_call = None
# func_id, func, llm_pysc2_arg_types = llm_a.get_action(self.name, )
pysc2_args = []
if func_id in obs.observation.available_actions: # 函数合法性检验,非法动作直接跳出
func_valid = True
pysc2_args = []
if len(llm_pysc2_args) == 0:
func_call = func()
# logger.debug(f"[ID {self.log_id}] LLMAgent {self.name}, call func() = {func()}")
if len(llm_pysc2_args) > 0:
for i in range(len(llm_pysc2_args)):
llm_pysc2_arg = llm_pysc2_args[i]
# logger.debug(f"[ID {self.log_id}] LLMAgent {self.name}, get_func(): llm_pysc2_arg= {llm_pysc2_arg}, type(llm_pysc2_arg) = {type(llm_pysc2_arg)}")
if isinstance(llm_pysc2_arg, str): # queued形式的flag
func_valid = False if llm_pysc2_arg not in ['now', 'queued', 'select', 'add'] else True
pysc2_arg = llm_pysc2_arg
if self.first_action and pysc2_arg in ['now', 'queued']:
pysc2_arg = 'now'
elif isinstance(llm_pysc2_arg, list) and len(llm_pysc2_arg) == 2: # 坐标
func_valid = False
if func.args[i].name == 'minimap': # 小地图坐标
pysc2_arg, func_valid = llm_action.get_arg_minimap(obs, llm_pysc2_arg, self.size_minimap, self.curr_action_name) # 小地图坐标合法性判断
elif func.args[i].name == 'screen' and 'Build' in func.name: # 建造
pysc2_arg, func_valid = llm_action.get_arg_screen_build(obs, llm_pysc2_arg, self.size_screen, self.curr_action_name) # 建筑的屏幕坐标合法性判断
elif func.args[i].name == 'screen' and 'Build' not in func.name: # 无限制
pysc2_arg, func_valid = llm_action.get_arg_screen(obs, llm_pysc2_arg, self.size_screen, self.curr_action_name) # 屏幕坐标合法性判断
else:
pysc2_arg = 'WrongType-Arg' # 错误处理,接受func_valid = False,使用no_op代替该动作
elif isinstance(llm_pysc2_arg, int):
func_valid = False
if func_id == 573 and ('Build_Nexus_' in self.curr_action_name or 'Lock_Nexus_' in self.curr_action_name):
pysc2_arg, func_valid = llm_action.get_arg_world_tag_base_building(
obs, llm_pysc2_arg, self.world_x_offset, self.world_y_offset, self.world_range)
elif func_id == 573:
pysc2_arg, func_valid = llm_action.get_arg_world_tag(
obs, llm_pysc2_arg, self.world_x_offset, self.world_y_offset, self.world_range) # tag转全局坐标
elif func.name == 'select_rect': # 单选单位
pysc2_arg, func_valid = llm_action.get_arg_screen_tag_sclect_rect(
obs, llm_pysc2_arg, self.size_screen, func.args[i].name) # tag转屏幕坐标
elif func.args[i].name == 'screen' and 'Recall' in func.name: # 召回,临近单位群的中心
pysc2_arg, func_valid = llm_action.get_arg_screen_tag_recall(
obs, llm_pysc2_arg, self.size_screen, self.curr_action_name) # tag转屏幕坐标
elif func.args[i].name == 'screen' and 'TrainWarp' in func.name: # 折跃,水晶塔/棱镜力场附近
pysc2_arg, func_valid = llm_action.get_arg_screen_tag_warp(
obs, llm_pysc2_arg, self.size_screen, self.curr_action_name) # tag转屏幕坐标
elif func.args[i].name == 'screen' and func_id in [65, 70]: # 建造主矿/水晶塔封矿
pysc2_arg, func_valid = llm_action.get_arg_screen_tag_base_building(
obs, llm_pysc2_arg, self.size_screen, self.curr_action_name) # tag转屏幕坐标
elif func.args[i].name == 'screen' and func_id in [40]: # 建造气站/封对面气
pysc2_arg, func_valid = llm_action.get_arg_screen_tag_gas_building(
obs, llm_pysc2_arg, self.size_screen, self.curr_action_name) # tag转屏幕坐标
elif func.args[i].name == 'screen': # 无限制
pysc2_arg, func_valid = llm_action.get_arg_screen_tag(
obs, llm_pysc2_arg, self.size_screen, self.curr_action_name) # tag转屏幕坐标
else:
func_valid = False
pysc2_arg = 'WrongType-Arg' # 错误处理
else:
func_valid = False
pysc2_arg = 'WrongType-Arg'
pysc2_args.append(pysc2_arg)
if func_valid is True and 'error' not in pysc2_args:
logger.info(
f"[ID {self.log_id}] LLMAgent {self.name}, get_func(): func avaliable, func {func} pysc2_args {pysc2_args}")
if len(pysc2_args) == 3:
func_call = func(pysc2_args[0], pysc2_args[1], pysc2_args[2])
elif len(pysc2_args) == 2:
func_call = func(pysc2_args[0], pysc2_args[1])
elif len(pysc2_args) == 1:
func_call = func(pysc2_args[0])
else:
with open(self.history_func_path, "a") as f: # 打开文件
print(f"{self.name}; loop{self.main_loop_step}; step{self.num_step}; [Invalid Args] {func.name} {pysc2_args}", file=f)
logger.warning(f"[ID {self.log_id}] LLMAgent {self.name} get_func() Error type 1: Arg quantity invalid: ({pysc2_args})! Replace with no_op().")
func_id, func_call = (0, actions.FUNCTIONS.no_op())
else:
with open(self.history_func_path, "a") as f: # 打开文件
print(f"{self.name}; loop{self.main_loop_step}; step{self.num_step}; [Invalid Args] {func.name} {pysc2_args} ", file=f)
logger.warning(f"[ID {self.log_id}] LLMAgent {self.name} get_func() Error type 2: Func {func} Arg invalid: {pysc2_args}! Replace with no_op()")
func_id, func_call = (0, actions.FUNCTIONS.no_op())
else:
with open(self.history_func_path, "a") as f: # 打开文件
print(f"{self.name}; loop{self.main_loop_step}; step{self.num_step}; [Invalid Func] {func.name} ", file=f)
logger.warning(f"[ID {self.log_id}] LLMAgent {self.name} get_func() Error type 3: Func invalid: {func}! Replace with no_op()")
func_id, func_call = (0, actions.FUNCTIONS.no_op())
# 保存动作信息
with open(self.history_func_path, "a") as f: # 打开文件
if func_id != 0:
print(f"{self.name}; loop{self.main_loop_step}; step{self.num_step}; [ Success ] {func_call}", file=f)
if self.first_action and 'now' in pysc2_args:
self.first_action = False
if len(self.action_list) == 0:
self.first_action = True # 本小队最后一个动作已经执行完毕
logger.info(f"[ID {self.log_id}] LLMAgent {self.name} get_func(): Get Func {func_id}, {func_call}")
return func_id, func_call
# 用户定制智能体
class Customized_LLMAgent(LLMAgent):
def __init__(self, name: str, log_id: int, start_time: str, config: "AgentConfig"=ProtossAgentConfig()):
super(Customized_LLMAgent, self).__init__(name, log_id, start_time, config)
# TODO: code here to redefine system prompt, example input prompt and example output prompt
basic_prompt = self.config.AGENTS[name]['llm']['basic_prompt'] # edit it to change basic prompt
translator_o = self.config.AGENTS[name]['llm']['translator_o'] # edit it to change obs translator
translator_a = self.config.AGENTS[name]['llm']['translator_a'] # edit it to change action translator, not recommended
communicator = self.config.communicator # edit it to change communicator, not recommended
self.api_key = self.config.AGENTS[name]['llm']['api_key']
self.api_base = self.config.AGENTS[name]['llm']['api_base']
self.model_name = self.config.AGENTS[name]['llm']['model_name']
self.basic_prompt = llm_prompt.FACTORY[self.race][basic_prompt](name, log_id, config)
self.translator_a = llm_action.FACTORY[self.race][translator_a](name, log_id, config)
self.translator_o = llm_observation.FACTORY[self.race][translator_o](name, log_id, config)
self.communicator = llm_communicate.FACTORY[self.race][communicator](name, log_id, config)
self.client = llm_client.FACTORY[self.model_name](name, log_id, config)
self.client.system_prompt = self.basic_prompt.sp
self.client.example_i_prompt = self.basic_prompt.eip
self.client.example_o_prompt = self.basic_prompt.eop
# 如需修改Agent与LLM的交互方式,重定义接口函数act即可
def query(self, obs) -> None:
while self.is_waiting is False:
with self.lock:
self.is_waiting = True
logger.success(f"[ID {self.log_id}] LLMAgent {self.name}: Start waiting for response")
# TODO: code here to redefine how to interact with LLM
self.get_text_c_inp()
text_o = self.get_text_o(obs)
if self.config.AGENTS[self.name]['llm']['img_rgb']:
base64_image = llm_observation.get_img_obs_rgb(self, obs)
raw_text_a = self.get_text_a(text_o, base64_image=base64_image)
elif self.config.AGENTS[self.name]['llm']['img_fea']:
base64_image = llm_observation.get_img_obs_fea(self, obs)
raw_text_a = self.get_text_a(text_o, base64_image=base64_image)
else:
raw_text_a = self.get_text_a(text_o)
action_lists, action_list_dict = self.get_func_a(raw_text_a)
self.get_info_c_out(raw_text_a)
logger.success(f"[ID {self.log_id}] LLMAgent {self.name}: Get response ")
self.first_action = True
with open(self.history_func_path, "a") as f:
print('--' * 50, file=f)
while self.is_waiting is True:
with self.lock:
self.is_waiting = False
self.action_lists = action_lists
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/main_agent_funcs.py | llm_pysc2/agents/main_agent_funcs.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
from pysc2.lib import features, actions
from llm_pysc2.lib.utils import *
from loguru import logger
def get_camera_xy(self, raw_x, raw_y):
x = max(0, raw_x + self.world_x_offset)
y = max(0, self.world_range - raw_y + self.world_y_offset)
return x, y
def get_camera_func_smart(self, obs, tag, threshold=0.15, team=None):
unit_r = None
unit_f = None
for unit in obs.observation.raw_units:
if unit.tag == tag:
unit_r = unit
for unit in obs.observation.feature_units:
if unit.tag == tag:
unit_f = unit
# 动作时,使用观测时锚定的坐标
if team is not None:
unit_ = None
logger.debug(f"[ID {self.log_id}] get_camera_func_smart(): team['obs'] mode")
agent_name = self.AGENT_NAMES[self.agent_id]
if len(team['obs']) != len(team['pos']):
logger.error(f"[ID {self.log_id}] {agent_name} {team['name']} len(team['obs']) != len(team['pos'])")
# elif unit_r is None:
# logger.error(f"[ID {self.log_id}] {agent_name} {team['name']} cannot find unit {str(units.get_unit_type(unit.unit_type))} {hex(tag)}")
else:
for i in range(len(team['obs'])):
obs_old = team['obs'][i]
unit_selected_in_obs = False
for unit_ in obs_old.observation.feature_units:
if unit_.tag == tag and unit_.is_selected and unit_.alliance == features.PlayerRelative.SELF and unit_.tag in \
team['unit_tags']:
unit_selected_in_obs = True
break
if unit_selected_in_obs:
x, y = team['pos'][i][0], team['pos'][i][1]
if self.last_two_camera_pos[0][0] == self.last_two_camera_pos[1][0] == x and \
self.last_two_camera_pos[0][1] == self.last_two_camera_pos[1][1] == y:
logger.debug(f"[ID {self.log_id}] {agent_name} {team['name']}: camera in correct position")
return (0, actions.FUNCTIONS.no_op())
else:
unit_type = unit_.unit_type if unit_ is not None else None
logger.info(f"[ID {self.log_id}] {agent_name} {team['name']}: use obs position ({x}, {y}) for unit {str(units.get_unit_type(unit_type))} {hex(tag)}")
self.last_two_camera_pos.append([x, y])
return (573, actions.FUNCTIONS.llm_pysc2_move_camera((x, y)))
unit_type = unit_.unit_type if unit_ is not None else None
logger.error(f"[ID {self.log_id}] {agent_name} {team['name']} cannot find unit {str(units.get_unit_type(unit_type))} {hex(tag)}")
logger.debug(f"[ID {self.log_id}] get_camera_func_smart(): standard mode")
if (unit_r is not None) and unit_f is None:
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
logger.info(f"[ID {self.log_id}] get_camera_func_smart(): (unit_r is not None) and unit_f is None")
self.last_two_camera_pos.append([x, y])
return (573, actions.FUNCTIONS.llm_pysc2_move_camera((x, y))) # 有这个单位,但是屏幕上没找到
elif (unit_r is not None) and (unit_f is not None) and \
not (abs(unit_f.x - self.size_screen / 2) < threshold * self.size_screen and
abs(unit_f.y - self.size_screen / 2) < threshold * self.size_screen):
# not (threshold * self.size_screen < unit_f.x < (1 - threshold) * self.size_screen and
# threshold * self.size_screen < unit_f.y < (1 - threshold) * self.size_screen):
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
logger.info(f"[ID {self.log_id}] get_camera_func_smart(): unit_f {str(units.get_unit_type(unit_f.unit_type))} "
f"{hex(unit_f.tag)} not near screen center, {unit_f.x} {unit_f.y}")
self.last_two_camera_pos.append([x, y])
return (573, actions.FUNCTIONS.llm_pysc2_move_camera((x, y))) # 有这个单位,屏幕上找到了,但太偏了
else:
return (0, actions.FUNCTIONS.no_op()) # 不动相机
def get_new_unit_agent(self, obs, unit) -> str: # 编队逻辑函数
if not unit.alliance == features.PlayerRelative.SELF or unit.build_progress != 100:
return f'unit build_progress {unit.build_progress} != 100'
# 空降部队编队
for agent_name in self.AGENT_NAMES:
if not agent_name in self.config.AGENTS_ALWAYS_DISABLE and \
unit.unit_type in self.agents[agent_name].available_unit_type and \
(agent_name == 'Airborne'):
# possible_transport_unit = self.agents[agent_name].unit_raw_list
possible_transport_unit = obs.observation.raw_units
dist_min = 999999
for unit_ in possible_transport_unit:
if unit_.unit_type in TRANSPORTER_TYPE and unit_.alliance == features.PlayerRelative.SELF \
and unit_.health > 0 and unit_.tag in self.unit_uid: # 确认一下该运输单位还活着
dist = get_dist(unit, unit_)
if dist < dist_min:
dist_min = dist
if dist_min < 4: # 出现在运输单位附近4距离内的默认为空降兵
return agent_name
for agent_name in self.AGENT_NAMES:
if agent_name in self.config.AGENTS_ALWAYS_DISABLE:
continue
if not unit.unit_type in self.agents[agent_name].available_unit_type:
continue
if unit.unit_type in WORKER_TYPE:
if 'CombatGroup' in agent_name and len(self.agents[agent_name].unit_tag_list) < 1:
return agent_name # 侦察农民
if agent_name == 'Builder' and len(
self.agents[agent_name].unit_tag_list) < obs.observation.player.food_workers / 30:
return agent_name # 建造农民
continue
if agent_name == 'Defender' and len(self.agents[agent_name].unit_tag_list) < obs.observation.player.food_army / 15:
return agent_name # 守备部队
if agent_name == 'Developer':
return agent_name # 后勤部队
if agent_name == 'Commander':
return agent_name # 指挥所
if 'CombatGroup' in agent_name:
return agent_name # 标准作战小组
continue
# if (unit.unit_type in self.agents[agent_name].available_unit_type) and ('CombatGroup' in agent_name) and (unit.unit_type in WORKER_TYPE) and len(self.agents[agent_name].unit_tag_list) != 0:
# continue # 一个作战小组最多一个probe
# if (unit.unit_type in self.agents[agent_name].available_unit_type) and ('CombatGroup' in agent_name):
# return agent_name
# if (unit.unit_type in self.agents[agent_name].available_unit_type) and ('CombatGroup' not in agent_name):
# return agent_name
return f'Can not find an agent the unit belongs to, unit {str(units.get_unit_type(unit.unit_type))}({unit.unit_type}) {str(hex(unit.tag))}'
def main_agent_func0(self, obs):
func_id, func_call = (None, None)
self.size_screen = obs.observation.feature_screen.height_map.shape[0]
self.size_minimap = obs.observation.feature_minimap.height_map.shape[0]
# region 1初始动作
# 选择枢纽,训练probe,加速枢纽
if self.race == 'protoss' and self.config.ENABLE_INIT_STEPS:
if self.num_step == 0:
for unit in obs.observation.feature_units:
if unit.alliance == features.PlayerRelative.SELF and unit.unit_type in BASE_BUILDING_TYPE:
x, y = min(max(0, unit.x), self.size_screen), min(max(0, unit.y), self.size_screen)
func_id, func_call = (2, actions.FUNCTIONS.select_point('select', (x, y)))
logger.info(f"[ID {self.log_id}] 1.1.1 Func Call: {func_call}")
func_call = func_call if func_id in obs.observation.available_actions else actions.FUNCTIONS.no_op()
func_id = func_id if func_id in obs.observation.available_actions else 0
self.func_id_history.append(func_id)
return func_call
if self.num_step == 1:
for unit in obs.observation.feature_units:
if unit.alliance == features.PlayerRelative.SELF and unit.unit_type in BASE_BUILDING_TYPE:
func_id, func_call = (485, actions.FUNCTIONS.Train_Probe_quick('now'))
logger.info(f"[ID {self.log_id}] 1.1.2 Func Call: {func_call}")
func_call = func_call if func_id in obs.observation.available_actions else actions.FUNCTIONS.no_op()
func_id = func_id if func_id in obs.observation.available_actions else 0
self.func_id_history.append(func_id)
return func_call
if self.num_step == 2:
for unit in obs.observation.feature_units:
if unit.alliance == features.PlayerRelative.SELF and unit.unit_type in BASE_BUILDING_TYPE:
func_id, func_call = (343, actions.FUNCTIONS.Rally_Workers_screen('now', (unit.x, unit.y)))
logger.info(f"[ID {self.log_id}] 1.1.3 Func Call: {func_call}")
func_call = func_call if func_id in obs.observation.available_actions else actions.FUNCTIONS.no_op()
func_id = func_id if func_id in obs.observation.available_actions else 0
self.func_id_history.append(func_id)
return func_call
if self.num_step == 3:
for unit in obs.observation.feature_units:
if unit.alliance == features.PlayerRelative.SELF and unit.unit_type in BASE_BUILDING_TYPE:
func_id, func_call = (
527, actions.FUNCTIONS.Effect_ChronoBoostEnergyCost_screen('now', (unit.x, unit.y)))
logger.info(f"[ID {self.log_id}] 1.1.4 Func Call: {func_call}")
func_call = func_call if func_id in obs.observation.available_actions else actions.FUNCTIONS.no_op()
func_id = func_id if func_id in obs.observation.available_actions else 0
self.func_id_history.append(func_id)
return func_call
if self.race == 'zerg' and self.config.ENABLE_INIT_STEPS:
pass
if self.race == 'terran' and self.config.ENABLE_INIT_STEPS:
pass
# endregion
# region 2相机校准(不要对nexus校准,而是对任意的第一个单位校准)
if self.world_range == 0:
self.size_screen = obs.observation.feature_screen.height_map.shape[0]
self.size_minimap = obs.observation.feature_minimap.height_map.shape[0]
unit_raw_x = None
for unit in obs.observation.raw_units:
if unit.alliance == features.PlayerRelative.SELF:
self.first_select_unit_tag = unit.tag
self.first_select_unit_type = unit.unit_type
for unit in obs.observation.raw_units:
if unit.alliance == features.PlayerRelative.SELF and unit.unit_type in BASE_BUILDING_TYPE:
self.first_select_unit_tag = unit.tag
self.first_select_unit_type = unit.unit_type
for unit in obs.observation.raw_units:
if unit.tag == self.first_select_unit_tag:
unit_raw_x = unit.x
# arr = obs.observation['feature_minimap']['camera']
arr = obs.observation['feature_minimap']['player_relative']
idx = np.nonzero(arr) # 获取特征图上非零值的坐标
minimap_x_predict = idx[:][1].mean()
minimap_y_predict = idx[:][0].mean()
self.world_range = round(int((self.size_minimap / minimap_x_predict) * unit_raw_x) / 32) * 32
# self.world_y_offset = self.world_range
logger.info(f"[ID {self.log_id}] 2.1 正在确定xy世界坐标范围:{self.world_range} ")
# time.sleep(0.5)
if self.world_xy_calibration == False:
unit_f = None
unit_r = None
for unit in obs.observation.feature_units:
if unit.tag == self.first_select_unit_tag:
unit_f = unit
for unit in obs.observation.raw_units:
if unit.tag == self.first_select_unit_tag:
unit_r = unit
self.world_xy_calibration = True
if unit_f is not None:
offset_min = 0.5 * 128 / self.size_screen
offset_x = (SCREEN_WORLD_GRID / 4) * abs(unit_f.x - self.size_screen / 2) / self.size_screen
offset_y = (SCREEN_WORLD_GRID / 4) * abs(unit_f.y - self.size_screen / 2) / self.size_screen
if unit_f.x > self.size_screen * 0.53:
self.world_x_offset += max(offset_min, offset_x)
self.world_xy_calibration = False
logger.debug("a1 unit_f.x > self.size_screen * 0.52")
if unit_f.x < self.size_screen * 0.47:
self.world_x_offset -= max(offset_min, offset_x)
self.world_xy_calibration = False
logger.debug("b1 unit_f.x < self.size_screen * 0.48")
if unit_f.y > self.size_screen * 0.53:
self.world_y_offset -= max(offset_min, offset_y)
self.world_xy_calibration = False
logger.debug("c1 unit_f.y > self.size_screen * 0.52")
if unit_f.y < self.size_screen * 0.47:
self.world_y_offset += max(offset_min, offset_y)
self.world_xy_calibration = False
logger.debug("d1 unit_f.y < self.size_screen * 0.48")
logger.info(
f"[ID {self.log_id}] 2.2 正在校准xy世界坐标:校准完成{self.world_xy_calibration} x偏移量{self.world_x_offset} y偏移量{self.world_y_offset}")
logger.info(f"[ID {self.log_id}] 2.2 unit_f.x={unit_f.x} unit_f.y={unit_f.y}")
logger.info(
f"[ID {self.log_id}] 2.2 unit_type={self.first_select_unit_type} unit_tag={self.first_select_unit_tag}")
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
func_id, func_call = (573, actions.FUNCTIONS.llm_pysc2_move_camera((x, y))) # 修改了pysc2的action
logger.info(f"[ID {self.log_id}] 2.2 Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
else:
self.world_xy_calibration = False
arr = obs.observation['feature_minimap']['camera']
idx = np.nonzero(arr) # 获取特征图上非零值的坐标
minimap_camera_x_predict = idx[:][1].mean()
minimap_camera_y_predict = idx[:][0].mean()
arr = obs.observation['feature_minimap']['player_relative']
arr = np.where(arr == features.PlayerRelative.SELF, 1, 0)
idx = np.nonzero(arr) # 获取特征图上非零值的坐标
minimap_unit_x_predict = idx[:][1].mean()
minimap_unit_y_predict = idx[:][0].mean()
if minimap_camera_x_predict > minimap_unit_x_predict + self.size_minimap * 0.1:
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
if 0 < x:
self.world_x_offset -= max(6, 0.5 * self.world_range * abs(
minimap_camera_x_predict - minimap_unit_x_predict) / self.size_minimap)
self.world_xy_calibration = False
logger.debug("a2 minimap_camera_x_predict > minimap_unit_x_predict + self.size_minimap * 0.1")
if minimap_camera_x_predict < minimap_unit_x_predict - self.size_minimap * 0.1:
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
if x < self.world_range + 64:
self.world_x_offset += max(6, 0.5 * self.world_range * abs(
minimap_camera_x_predict - minimap_unit_x_predict) / self.size_minimap)
self.world_xy_calibration = False
logger.debug("b2 minimap_camera_x_predict < minimap_unit_x_predict - self.size_minimap * 0.1")
if minimap_camera_y_predict > minimap_unit_y_predict + self.size_minimap * 0.1:
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
if y < self.world_range + 64:
self.world_y_offset += max(6, 0.5 * self.world_range * abs(
minimap_camera_y_predict - minimap_unit_y_predict) / self.size_minimap)
self.world_xy_calibration = False
logger.debug("c2 minimap_camera_y_predict > minimap_unit_y_predict + self.size_minimap * 0.1")
if minimap_camera_y_predict < minimap_unit_y_predict - self.size_minimap * 0.1:
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
if 0 < y:
self.world_y_offset -= max(6, 0.5 * self.world_range * abs(
minimap_camera_y_predict - minimap_unit_y_predict) / self.size_minimap)
self.world_xy_calibration = False
logger.debug("d2 minimap_camera_y_predict < minimap_unit_y_predict - self.size_minimap * 0.1")
logger.info(
f"[ID {self.log_id}] 2.3 正在校准xy世界坐标:校准完成{self.world_xy_calibration} x偏移量{self.world_x_offset} y偏移量{self.world_y_offset}")
logger.info(
f"[ID {self.log_id}] 2.3 minimap_camera_x_predict={minimap_camera_x_predict} minimap_camera_y_predict={minimap_camera_y_predict}")
logger.info(
f"[ID {self.log_id}] 2.3 minimap_unit_x_predict={minimap_unit_x_predict} minimap_unit_y_predict={minimap_unit_y_predict}")
logger.info(
f"[ID {self.log_id}] 2.3 unit_type={self.first_select_unit_type} unit_tag={self.first_select_unit_tag}")
x, y = get_camera_xy(self, unit_r.x, unit_r.y)
func_id, func_call = (573, actions.FUNCTIONS.llm_pysc2_move_camera((x, y))) # 修改了pysc2的action
logger.info(f"[ID {self.log_id}] 2.3 Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
# endregion
return func_call
def main_agent_func1(self, obs):
func_id, func_call = (None, None)
# region 3新生产单位编组 死亡单位的剔除
# 检测两步之间己方新增的单位和消失的单位
unit_uid_ = list()
for unit in obs.observation.raw_units:
if unit.alliance == features.PlayerRelative.SELF and unit.build_progress == 100:
unit_uid_.append(unit.tag)
if unit.tag in self.unit_uid and unit.tag not in unit_uid_:
self.unit_uid_disappear.append(unit.tag)
if unit.tag not in self.unit_uid and unit.tag in unit_uid_:
self.unit_uid_appear.append(unit.tag)
# for tag in self.unit_uid:
# if tag not in unit_uid_:
# self.unit_uid_disappear.append(tag)
# for tag in unit_uid_:
# if tag not in self.unit_uid:
# self.unit_uid_appear.append(tag)
self.unit_uid = unit_uid_
# 单位消失步数记录判断
for tag in self.unit_uid_total:
if tag not in self.unit_uid:
if tag in self.unit_disappear_steps.keys():
self.unit_disappear_steps[tag] += 1
else:
self.unit_disappear_steps[tag] = 1
else:
if tag in self.unit_disappear_steps.keys():
self.unit_disappear_steps.pop(tag)
# 验证可能消失的单位是否真的消失了,只保留真正消失了的
# possible_disappear_unit_list_ = []
# possible_disappear_unit_tag_list_ = []
# for unit in self.possible_disappear_unit_list:
# if unit.tag not in self.unit_uid:
# possible_disappear_unit_list_.append(unit)
# possible_disappear_unit_tag_list_.append(unit.tag)
# self.possible_disappear_unit_list = possible_disappear_unit_list_
# self.possible_disappear_unit_tag_list = possible_disappear_unit_tag_list_
# # print(f"self.possible_disappear_unit_list = {self.possible_disappear_unit_list}")
#
# for unit in obs.observation.raw_units: # 如果附近有可进入单位(含建筑),如运输机、瓦斯气站,则该单位可能消失
# if unit.tag not in get_tag_list(self.possible_disappear_unit_list) and \
# (unit.alliance == features.PlayerRelative.SELF) and \
# (unit.unit_type not in ACCESSBLE_UNIT_TYPE) and \
# (unit.build_progress == 100):
# nearby_unit_list = get_nearby_unit_list(unit, obs.observation.raw_units, dist=2.4)
# for unit_ in nearby_unit_list:
# if (unit_.alliance == features.PlayerRelative.SELF) and \
# (unit_.unit_type in ACCESSBLE_UNIT_TYPE) and \
# (unit_.build_progress == 100):
# self.possible_disappear_unit_list.append(unit)
# self.possible_disappear_unit_tag_list.append(unit.tag)
# # print(f"self.possible_disappear_unit_list = {self.possible_disappear_unit_list}")
# 新单位的编队编组
if not self.main_loop_lock:
while len(self.unit_uid_appear) != 0:
# logger.info(f"[ID {self.log_id}] MainAgent Status 3.0 ")
logger.info(f"[ID {self.log_id}] self.unit_uid_appear = {self.unit_uid_appear}")
curr_unit = None
for unit in obs.observation.raw_units:
if unit.tag == self.unit_uid_appear[0]:
curr_unit = unit
if curr_unit is None: # TODO: 确认这样是否有问题。为什么会找不到self.unit_uid_appear[0]对应的单位
logger.error(f"[ID {self.log_id}] 3.0 unit {self.unit_uid_appear[0]} not find")
self.unit_uid_appear.remove(self.unit_uid_appear[0])
continue
# 临时消失的单位:gas_building里面出来的单位/载具里面出来的单位
if (curr_unit.tag in self.unit_uid_appear) and (curr_unit.tag in self.unit_uid_total):
logger.info(f"[ID {self.log_id}] 3.1 {str(units.get_unit_type(curr_unit.unit_type))} {curr_unit.tag} re-appear")
# print('--' * 25)
# for agent_name in self.AGENT_NAMES:
# if curr_unit.tag in self.agents[agent_name].unit_tag_list_history:
# self.agents[agent_name].unit_tag_list.append(curr_unit.tag)
# self.unit_uid_appear.remove(curr_unit.tag)
# continue
# 获取所属小组,若没有所属小组,直接处理掉
agent_name = get_new_unit_agent(self, obs, curr_unit) # 编队逻辑在此函数中设置
logger.info(f"[ID {self.log_id}] agent_name = {agent_name}")
logger.info(f"[ID {self.log_id}] curr_unit = {str(units.get_unit_type(curr_unit.unit_type))} {curr_unit.tag}")
if agent_name not in self.config.AGENTS:
logger.debug(f"[ID {self.log_id}] 3.2 skip {str(units.get_unit_type(curr_unit.unit_type))} {curr_unit.tag}")
self.unit_uid_appear.remove(curr_unit.tag)
# print('--' * 25)
continue
# 移动相机
if not curr_unit.is_selected:
func_id, func_call = get_camera_func_smart(self, obs, curr_unit.tag)
if func_id == 573:
logger.info(f"[ID {self.log_id}] 3.3 Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
# 选择单位
unit_f = None
for unit in obs.observation.feature_units:
if curr_unit.tag == unit.tag:
unit_f = unit
if not unit_f.is_selected:
if self.func_id_history[-1] in [2, 3]:
d = self.select_rect_threshold
x1, x2 = min(max(0, unit_f.x - d), self.size_screen), min(max(0, unit_f.x + d), self.size_screen)
y1, y2 = min(max(0, unit_f.y - d), self.size_screen), min(max(0, unit_f.y + d), self.size_screen)
func_id, func_call = (3, actions.FUNCTIONS.select_rect('select', (x1, y1), (x2, y2)))
else:
x, y = min(max(0, unit_f.x), self.size_screen), min(max(0, unit_f.y), self.size_screen)
func_id, func_call = (2, actions.FUNCTIONS.select_point('select', (x, y)))
logger.info(f"[ID {self.log_id}] 3.4.1 Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
# if curr_unit.unit_type in WORKER_TYPE:
# func_id, func_call = (2, actions.FUNCTIONS.select_point('select', (unit_f.x, unit_f.y)))
# logger.info(f"[ID {self.log_id}] 3.4.1 Func Call: {func_call}")
# self.func_id_history.append(func_id)
# return func_call
# else:
# func_id, func_call = (2, actions.FUNCTIONS.select_point('select_all_type', (unit_f.x, unit_f.y)))
# logger.info(f"[ID {self.log_id}] 3.4.2 Func Call: {func_call}")
# self.func_id_history.append(func_id)
# return func_call
chosen_team = None
unit_in_team = False
for team in self.agents[agent_name].teams: #
if curr_unit.tag in team['unit_tags']:
unit_in_team = True
chosen_team = team
# 查找相关小组
if not unit_in_team:
relevant_team_list = []
relevant_team_unit_num = []
for team in self.agents[agent_name].teams:
if curr_unit.unit_type in team['unit_type']:
relevant_team_list.append(team)
relevant_team_unit_num.append(len(team['unit_tags']))
if len(relevant_team_unit_num) == 0:
logger.debug(f"[ID {self.log_id}] self.agents[{agent_name}].teams: {self.agents[agent_name].teams}")
# 加入小组
if max(relevant_team_unit_num) == 0: # 小组全空
idx = 0
relevant_team_list[idx]['unit_tags'].append(curr_unit.tag)
chosen_team = relevant_team_list[0]
else:
if relevant_team_list[0]['select_type'] == 'group': # 平均分配 哪组单位最少给哪组
relevant_team_dist = get_relevant_team_dist(relevant_team_list, obs, curr_unit)
if min(relevant_team_unit_num) < 4: # 平均分组
idx = relevant_team_unit_num.index(min(relevant_team_unit_num))
relevant_team_list[idx]['unit_tags'].append(curr_unit.tag)
chosen_team = relevant_team_list[idx]
else: # 分到最近的组
idx = relevant_team_dist.index(min(relevant_team_dist))
relevant_team_list[idx]['unit_tags'].append(curr_unit.tag)
chosen_team = relevant_team_list[idx]
else:
relevant_team_dist = get_relevant_team_dist(relevant_team_list, obs, curr_unit)
if min(relevant_team_dist) < 15: # 近距离
idx = relevant_team_dist.index(min(relevant_team_dist))
relevant_team_list[idx]['unit_tags'].append(curr_unit.tag)
chosen_team = relevant_team_list[idx]
elif 0 in relevant_team_unit_num:
idx = relevant_team_unit_num.index(0)
relevant_team_list[idx]['unit_tags'].append(curr_unit.tag)
chosen_team = relevant_team_list[idx]
else:
idx = relevant_team_dist.index(min(relevant_team_dist))
relevant_team_list[idx]['unit_tags'].append(curr_unit.tag)
chosen_team = relevant_team_list[idx]
# 移动到小组head的位置(可能是自己,但会不是空小组)
if chosen_team['select_type'] == 'select_all_type':
head_unit_tag = chosen_team['unit_tags'][0]
# 相机移动
func_id, func_call = get_camera_func_smart(self, obs, head_unit_tag)
if func_id == 573:
logger.info(f"[ID {self.log_id}] 3.5 Func Call: {func_call}")
self.func_id_history.append(func_id)
return func_call
# 加入到单位列表
self.agents[agent_name].unit_tag_list.append(curr_unit.tag)
self.agents[agent_name].unit_raw_list.append(curr_unit)
logger.info(
f"[ID {self.log_id}] 3.6 Finished dealling with {str(units.get_unit_type(curr_unit.unit_type))} {curr_unit.tag}")
self.unit_uid_appear.remove(curr_unit.tag)
# 加入编组
if chosen_team['game_group'] != -1:
func_id, func_call = (4, actions.FUNCTIONS.select_control_group('append', int(chosen_team['game_group'])))
logger.info(f"[ID {self.log_id}] 3.7.1 Func Call: {func_call}")
func_call = func_call if func_id in obs.observation.available_actions else actions.FUNCTIONS.no_op()
func_id = func_id if func_id in obs.observation.available_actions else 0
self.func_id_history.append(func_id)
return func_call
if chosen_team['select_type'] == 'select_all_type': # 聚拢单位的功能放到locked_func4
# 找到单位
unit_f = None
for unit in obs.observation.feature_units:
if unit.tag == head_unit_tag and unit.unit_type not in UNIT_DONOT_NEED_GATHER:
unit_f = unit
if unit_f is not None:
func_id, func_call = (331, actions.FUNCTIONS.Move_screen('now', (unit_f.x, unit_f.y)))
logger.info(f"[ID {self.log_id}] 3.7.2 Func Call: {func_call}")
func_call = func_call if func_id in obs.observation.available_actions else actions.FUNCTIONS.no_op()
func_id = func_id if func_id in obs.observation.available_actions else 0
self.func_id_history.append(func_id)
return func_call
else:
pass
# 死亡单位的处理
if not self.main_loop_lock:
for tag in self.unit_disappear_steps.keys():
if self.unit_disappear_steps[tag] < 40:
if tag in self.unit_uid_disappear:
self.unit_uid_disappear.remove(tag)
else:
if tag not in self.unit_uid_disappear:
self.unit_uid_disappear.append(tag)
for key in self.nexus_info_dict.keys():
if tag in self.nexus_info_dict[key]['worker_m_tag_list']:
self.nexus_info_dict[key]['worker_m_tag_list'].remove(tag)
if tag in self.nexus_info_dict[key]['worker_g_tag_list']:
self.nexus_info_dict[key]['worker_g_tag_list'].remove(tag)
if tag in self.nexus_info_dict[key]['worker_g1_tag_list']:
self.nexus_info_dict[key]['worker_g1_tag_list'].remove(tag)
if tag in self.nexus_info_dict[key]['worker_g2_tag_list']:
self.nexus_info_dict[key]['worker_g2_tag_list'].remove(tag)
# 死亡单位剔除出agent的unit_list
if len(self.unit_disappear_steps.keys()) != 0:
for agent_name in self.AGENT_NAMES:
agent = self.agents[agent_name]
unit_tag_list = []
for tag in agent.unit_tag_list:
if tag not in self.unit_disappear_steps.keys():
unit_tag_list.append(tag)
agent.unit_tag_list = unit_tag_list
# print(f"temp debug {self.unit_disappear_steps.keys()}")
self.unit_uid_total = set(list(self.unit_uid) + list(self.unit_uid_total))
return func_call
def main_agent_func2(self, obs):
func_id, func_call = (None, None)
# region 4处理闲置的工人和超采的工人
# 获取主矿附近的基本经济信息
for nexus in obs.observation.raw_units:
if nexus.alliance == features.PlayerRelative.SELF and nexus.unit_type in BASE_BUILDING_TYPE and nexus.build_progress == 100:
if str(nexus.tag) not in self.nexus_info_dict.keys():
self.nexus_info_dict[str(nexus.tag)] = {
'nexus': nexus,
'x': nexus.x,
'y': nexus.y,
'gas_building_1': None,
'gas_building_2': None,
'nearby_gas_building_tag_list': [],
'nearby_mineral_tag_list': [],
# 'nearby_worker_tag_list': [],
'num_worker_m_max': 0,
'num_worker_g_max': 0,
'worker_m_tag_list': [],
'worker_g_tag_list': [],
'worker_g1_tag_list': [],
'worker_g2_tag_list': [],
'num_worker_m': 0, # mineral
'num_worker_g': 0, # gas
}
# 查找附近的水晶矿、建成的气站、工人
for unit in get_nearby_unit_list(nexus, obs.observation.raw_units, dist=10):
if unit.alliance == features.PlayerRelative.SELF and unit.unit_type in GAS_BUILDING_TYPE and unit.build_progress == 100:
if unit.tag not in self.nexus_info_dict[str(nexus.tag)]['nearby_gas_building_tag_list']:
self.nexus_info_dict[str(nexus.tag)]['nearby_gas_building_tag_list'].append(unit.tag)
if self.nexus_info_dict[str(nexus.tag)]['gas_building_1'] is None:
self.nexus_info_dict[str(nexus.tag)]['gas_building_1'] = unit
else:
if self.nexus_info_dict[str(nexus.tag)]['gas_building_1'].tag != unit.tag:
self.nexus_info_dict[str(nexus.tag)]['gas_building_2'] = unit
if unit.unit_type in MINERAL_TYPE:
if unit.tag not in self.nexus_info_dict[str(nexus.tag)]['nearby_mineral_tag_list']:
self.nexus_info_dict[str(nexus.tag)]['nearby_mineral_tag_list'].append(unit.tag)
# if unit.alliance == features.PlayerRelative.SELF and unit.unit_type in WORKER_TYPE:
# nexus_info['nearby_worker_tag_list'].append(unit.tag)
# print(f"nexus {nexus.tag} {nexus.x} {nexus.x}, nearby_mineral_tag_list: {nexus_info['nearby_mineral_tag_list']}")
self.nexus_info_dict[str(nexus.tag)]['num_worker_m_max'] = min(16, 2 * len(
self.nexus_info_dict[str(nexus.tag)]['nearby_mineral_tag_list']))
self.nexus_info_dict[str(nexus.tag)]['num_worker_g_max'] = min(6, 3 * len(
self.nexus_info_dict[str(nexus.tag)]['nearby_gas_building_tag_list']))
# 抱着矿或者气的单位,确定工作场所
for worker in obs.observation.raw_units:
# 离职处理
if worker.alliance == features.PlayerRelative.SELF and worker.unit_type in WORKER_TYPE and \
worker.order_id_0 not in [356, 357, 358, 359, 102, 103, 154, 360, 361, 362]: # Harvest/HarvestReturn
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | true |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/config.py | llm_pysc2/agents/configs/config.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.lib.llm_action import PROTOSS_ACTION_BUILD, \
PROTOSS_BASIC_ACTION_1, PROTOSS_BASIC_ACTION_2, PROTOSS_BASIC_ACTION_3, \
PROTOSS_ACTION_WARPTRAIN, PROTOSS_ACTION_TRAIN, PROTOSS_ACTION_RESEARCH, F
from llm_pysc2.lib.llm_client import vision_model_names #, video_model_names
from pysc2.lib import units
from loguru import logger
import time
def wait(second, log_id, more_info=''):
for i in range(5):
logger.warning(f"[ID {log_id}] Experiment will start with UNSAFE settings in {5 - i} seconds. {more_info}")
time.sleep(1)
class AgentConfig:
def __init__(self):
self.race = 'protoss'
self.model_name = 'YOUR-MODEL-NAME' # 'gpt-3.5-turbo'
self.api_base = 'YOUR-API-BASE' # 'https://hk.xty.app/v1'
self.api_key = 'YOUR-API-KEY' # 'xxxxxxxxxxxxxxxxxxxxxxxx....'
self.temperature = 0.1
self.basic_prompt = 'default'
self.translator_o = 'default'
self.translator_a = 'default'
self.communicator = 'default'
self.ENABLE_INIT_STEPS = True
self.ENABLE_AUTO_WORKER_MANAGE = True
self.ENABLE_AUTO_WORKER_TRAINING = True
self.ENABLE_COMMUNICATION = False
self.ENABLE_IMAGE_RGB = False
self.ENABLE_IMAGE_FEATURE = False
self.ENABLE_SAVE_IMAGES = True
self.LLM_SIMULATION_TIME = 0
self.MAX_LLM_QUERY_TIMES = 5
self.MAX_LLM_WAITING_TIME = 15
self.MAX_LLM_RUNTIME_ERROR_TIME = 45
self.MAX_LLM_DECISION_FREQUENCY = 1
self.MAX_NUM_ACTIONS = 3
self.AGENTS = []
self.AGENTS_ALWAYS_DISABLE = []
def reset_llm(self, model_name=None, api_base=None, api_key=None, ENABLE_IMAGE_RGB=None, ENABLE_IMAGE_FEATURE=None):
if model_name is not None and model_name != 'YOUR-MODEL-NAME':
self.model_name = model_name
if api_base is not None and api_base != 'YOUR-API-BASE':
self.api_base = api_base
if api_key is not None and api_key != 'YOUR-API-KEY':
self.api_key = api_key
if ENABLE_IMAGE_RGB is not None:
self.ENABLE_IMAGE_RGB = ENABLE_IMAGE_RGB
if ENABLE_IMAGE_FEATURE is not None:
self.ENABLE_IMAGE_FEATURE = ENABLE_IMAGE_FEATURE
if ENABLE_IMAGE_RGB is True and ENABLE_IMAGE_FEATURE is True:
raise AssertionError("Do not support ENABLE_IMAGE_RGB and ENABLE_IMAGE_FEATURE at the same time, currently")
for agent_name in self.AGENTS.keys():
self.AGENTS[agent_name]['llm']['model_name'] = self.model_name
self.AGENTS[agent_name]['llm']['api_base'] = self.api_base
self.AGENTS[agent_name]['llm']['api_key'] = self.api_key
if self.ENABLE_IMAGE_RGB:
self.AGENTS[agent_name]['llm']['img_rgb'] = True
self.AGENTS[agent_name]['llm']['img_fea'] = False
elif self.ENABLE_IMAGE_FEATURE:
self.AGENTS[agent_name]['llm']['img_rgb'] = False
self.AGENTS[agent_name]['llm']['img_fea'] = True
else:
self.AGENTS[agent_name]['llm']['img_rgb'] = False
self.AGENTS[agent_name]['llm']['img_fea'] = False
def auto_check(self, log_id):
if not isinstance(self.LLM_SIMULATION_TIME, (int, float)) or self.LLM_SIMULATION_TIME <= 0:
error_in_llm_setting = False
if self.model_name == '' or self.model_name == 'YOUR-MODEL-NAME':
self.reset_llm(model_name='gpt-3.5-turbo')
logger.error(f"[ID {log_id}] No model_name set, please specify model_name in the config.")
self.LLM_SIMULATION_TIME = 5
error_in_llm_setting = True
if self.api_key == '' or self.api_key == 'YOUR-API-KEY':
logger.error(f"[ID {log_id}] No api_key set, please specify your api_key in the config.")
self.LLM_SIMULATION_TIME = 5
error_in_llm_setting = True
if self.model_name == '' or self.api_key == '':
self.LLM_SIMULATION_TIME = 5
error_in_llm_setting = True
if error_in_llm_setting:
wait(5, log_id, "(in LLM SIMULATION MODE)")
if self.ENABLE_IMAGE_RGB or self.ENABLE_IMAGE_FEATURE:
if self.ENABLE_IMAGE_RGB and self.ENABLE_IMAGE_FEATURE:
logger.error(f"[ID {log_id}] can not enable config.ENABLE_IMAGE_RGB and config.ENABLE_IMAGE_FEATURE together.")
AssertionError(f"config.ENABLE_IMAGE_RGB and config.ENABLE_IMAGE_FEATURE can not be True together")
if self.model_name not in vision_model_names:
logger.error(f"[ID {log_id}] config.ENABLE_IMAGE_RGB/FEATURE with large models that do not support images.")
wait(5, log_id)
if self.model_name in vision_model_names:
logger.warning(f"[ID {log_id}] You are using a vision model with image obs, this may cost a lot, be cautious.")
wait(5, log_id)
else:
if self.model_name in vision_model_names:
logger.warning(f"[ID {log_id}] You are using a vision avaliable model without using any image obs.")
wait(5, log_id)
class ProtossAgentConfig(AgentConfig):
def __init__(self):
super(ProtossAgentConfig, self).__init__()
# Program control parameters in class AgentConfig (above)
self.AGENTS_ALWAYS_DISABLE = []
self.AGENTS = {
'Airborne': {
'describe': "Protoss airborne commander, controls units airborne/warptrain from WarpPrism. "
"Responsible for quick reinforcing nearby units or executing multiline combat.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Airborne-Zealot-1', 'unit_type': [units.Protoss.Zealot],
'game_group': -1, 'select_type': 'select_all_type'}, # , 'max_unit_num': {units.Protoss.Zealot: -1}
],
'action': {
units.Protoss.Zealot: PROTOSS_BASIC_ACTION_2,
},
},
'Builder': {
'describe': "Protoss builder, controls several Probe. Responsible for build buildings",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Builder-Probe-1', 'unit_type': [units.Protoss.Probe],
'game_group': -1, 'select_type': 'select'}, # , 'max_unit_num': {units.Protoss.Probe: -1}
],
'action': {
units.Protoss.Probe: PROTOSS_BASIC_ACTION_2 + PROTOSS_ACTION_BUILD,
},
},
'Commander': {
'describe': "Protoss military supreme commander. "
"Responsible for making macro decision through communication, and controls nexus for massrecall "
"for tactical objectives. When make deployment, describe the time, location, and objectives of the "
"mission as clearly as possible",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': 'commander',
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Empty', 'unit_type': [],
'game_group': -1, 'select_type': 'select'},
],
'action': {
'EmptyGroup': [],
},
},
'Developer': {
'describe': "Protoss logistics commander. "
"Responsible for unit trainning, unit warp trainning, technology upgrade and order the Builder "
"to build.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': 'developer',
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'WarpGate-1', 'unit_type': [units.Protoss.WarpGate],
'game_group': -1, 'select_type': 'select_all_type'}, # , 'max_unit_num': {units.Protoss.WarpGate: -1}
{'name': 'Empty', 'unit_type': [],
'game_group': -1, 'select_type': 'select'},
],
'action': {
units.Protoss.WarpGate: PROTOSS_ACTION_WARPTRAIN,
'EmptyGroup': PROTOSS_BASIC_ACTION_1 + PROTOSS_ACTION_RESEARCH + PROTOSS_ACTION_TRAIN + [
{'name': 'Stop_Building_Unit', 'arg': ['tag'],
'func': [(573, F.llm_pysc2_move_camera, ('world_tag')),
(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(454, F.Stop_Building_quick, ('queued'))]}
],
},
},
'Defender': {
'describe': "Protoss garrison troops commander, controls several Stalkers. "
"Responsible for intercepting enemy infiltrating forces.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
# {'name': 'Nexus', 'unit_type': [units.Protoss.Nexus],
# 'game_group': -1, 'select_type': 'select', 'max_unit_num': {units.Protoss.Nexus: 8}},
{'name': 'Stalker-1', 'unit_type': [units.Protoss.Stalker],
'game_group': 1, 'select_type': 'group'}, # , 'max_unit_num': {units.Protoss.Stalker: 8}
],
'action': {
# units.Protoss.Nexus: [
# {'name': 'No_Operation', 'arg': [], 'func': [(0, F.no_op, ())]},
# {'name': 'Select_Workers_Attack_Screen', 'arg': ['screen'],
# 'func': [(12, F.Attack_screen, ('queued', 'screen'))]},
# {'name': 'Select_Workers_Move_Screen', 'arg': ['screen'],
# 'func': [(331, F.Move_screen, ('queued', 'screen'))]},
# ],
units.Protoss.Stalker: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_Blink_Screen', 'arg': ['screen'],
'func': [(180, F.Effect_Blink_screen, ('queued', 'screen'))]},
{'name': 'Select_Unit_Blink_Screen', 'arg': ['tag', 'screen'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(180, F.Effect_Blink_screen, ('now', 'screen'))]},
]
},
},
'CombatGroup0': {
'describe': "Protoss frontline commander, controls several Zealots. "
"Responsible for providing cover for the main force and executing multi line combat.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Zealot-1', 'unit_type': [units.Protoss.Zealot],
'game_group': 2, 'select_type': 'group'}, # , 'max_unit_num': {units.Protoss.Zealot: -1}, -1 for unlimited
{'name': 'Zealot-2', 'unit_type': [units.Protoss.Zealot],
'game_group': 3, 'select_type': 'group'}, # , 'max_unit_num': {units.Protoss.Zealot: -1}, -1 for unlimited
],
'action': {
units.Protoss.Zealot: PROTOSS_BASIC_ACTION_2,
},
},
'CombatGroup1': {
'describe': "Protoss frontline commander, controls several Stalkers. "
"Responsible for providing cover for the main force and restraining enemy forces.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Stalker-1', 'unit_type': [units.Protoss.Stalker],
'game_group': 4, 'select_type': 'group'},
{'name': 'Stalker-2', 'unit_type': [units.Protoss.Stalker],
'game_group': 5, 'select_type': 'group'},
{'name': 'Stalker-3', 'unit_type': [units.Protoss.Stalker],
'game_group': 6, 'select_type': 'group'},
],
'action': {
units.Protoss.Stalker: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_Blink_Screen', 'arg': ['screen'],
'func': [(180, F.Effect_Blink_screen, ('queued', 'screen'))]},
{'name': 'Select_Unit_Blink_Screen', 'arg': ['tag', 'screen'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(180, F.Effect_Blink_screen, ('now', 'screen'))]},
]
},
},
'CombatGroup2': {
'describe': "Protoss frontline commander, controls ground main force such as Immortal, Colossus and Archon. "
"Responsible for frontal combat.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Immortal-1', 'unit_type': [units.Protoss.Immortal],
'game_group': -1, 'select_type': 'select_all_type'},
# {'name': 'Immortal-2', 'unit_type': [units.Protoss.Immortal],
# 'game_group': -1, 'select_type': 'select_all_type'}, # more than 1 select_all_type not currently supported
{'name': 'Colossus-1', 'unit_type': [units.Protoss.Colossus],
'game_group': -1, 'select_type': 'select_all_type'},
# {'name': 'Colossus-2', 'unit_type': [units.Protoss.Colossus],
# 'game_group': -1, 'select_type': 'select_all_type'}, # more than 1 select_all_type not currently supported
{'name': 'Archon-1', 'unit_type': [units.Protoss.Archon],
'game_group': -1, 'select_type': 'select_all_type'},
# {'name': 'Archon-2', 'unit_type': [units.Protoss.Archon],
# 'game_group': -1, 'select_type': 'select_all_type'}, # more than 1 select_all_type not currently supported
],
'action': {
units.Protoss.Immortal: PROTOSS_BASIC_ACTION_2,
units.Protoss.Colossus: PROTOSS_BASIC_ACTION_2,
units.Protoss.Archon: PROTOSS_BASIC_ACTION_2,
},
},
'CombatGroup3': {
'describe': "Protoss frontline commander, controls air main force such as VoidRay, Carrier and Tempest. "
"Responsible for frontal combat.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'VoidRay-1', 'unit_type': [units.Protoss.VoidRay],
'game_group': -1, 'select_type': 'select_all_type'},
# {'name': 'VoidRay-2', 'unit_type': [units.Protoss.VoidRay],
# 'game_group': -1, 'select_type': 'select_all_type'}, # more than 1 select_all_type not currently supported
{'name': 'Carrier-1', 'unit_type': [units.Protoss.Carrier],
'game_group': -1, 'select_type': 'select_all_type'},
# {'name': 'Carrier-2', 'unit_type': [units.Protoss.Carrier],
# 'game_group': -1, 'select_type': 'select_all_type'}, # more than 1 select_all_type not currently supported
{'name': 'Tempest-1', 'unit_type': [units.Protoss.Tempest],
'game_group': -1, 'select_type': 'select_all_type'},
# {'name': 'Tempest-2', 'unit_type': [units.Protoss.Tempest],
# 'game_group': -1, 'select_type': 'select_all_type'}, # more than 1 select_all_type not currently supported
],
'action': {
units.Protoss.Carrier: PROTOSS_BASIC_ACTION_2,
units.Protoss.Tempest: PROTOSS_BASIC_ACTION_2,
units.Protoss.VoidRay: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_PrismaticAlignment', 'arg': [],
'func': [(244, F.Effect_VoidRayPrismaticAlignment_quick, ('queued'))]},
],
},
},
'CombatGroup4': {
'describe': "Protoss reconnaissance commander, controls Observer and several Probe. "
"Responsible for providing reconnaissance infomation and detect cloak unit for main force",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Probe', 'unit_type': [units.Protoss.Probe],
'game_group': -1, 'select_type': 'select'},
{'name': 'Observer', 'unit_type': [units.Protoss.Observer, units.Protoss.ObserverSurveillanceMode],
'game_group': -1, 'select_type': 'select'},
],
'action': {
units.Protoss.Probe: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Lock_Nexus_Near', 'arg': ['tag'],
'func': [(70, F.Build_Pylon_screen, ('queued', 'screen_tag'))]},
{'name': 'Lock_Assimilator_Near', 'arg': ['tag'],
'func': [(40, F.Build_Assimilator_screen, ('queued', 'screen_tag'))]},
],
units.Protoss.Observer: PROTOSS_BASIC_ACTION_3 + [
{'name': 'Morph_SurveillanceMode', 'arg': [],
'func': [(538, F.Morph_SurveillanceMode_quick, ('queued'))]},
],
units.Protoss.ObserverSurveillanceMode: [
{'name': 'Continuously_Monitor_Here', 'arg': [],
'func': [(0, F.no_op, ())]},
{'name': 'Morph_ObserverMode', 'arg': [],
'func': [(535, F.Morph_ObserverMode_quick, ('queued'))]},
],
},
},
'CombatGroup5': {
'describe': "Protoss AOE commander, controls HighTemplar and Disruptor. "
"Responsible for dealing high damage to clustered enemies",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'HighTemplar-1', 'unit_type': [units.Protoss.HighTemplar],
'game_group': 7, 'select_type': 'group'},
{'name': 'Disruptor-1', 'unit_type': [units.Protoss.Disruptor],
'game_group': 8, 'select_type': 'group'},
],
'action': {
units.Protoss.HighTemplar: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_PsiStorm_Screen', 'arg': ['screen'],
'func': [(218, F.Effect_PsiStorm_screen, ('queued', 'screen'))]},
{'name': 'Ability_PsiStorm_Attack_Unit', 'arg': ['tag'],
'func': [(218, F.Effect_PsiStorm_screen, ('queued', 'screen_tag'))]},
{'name': 'Morph_Archon', 'arg': [],
'func': [(296, F.Morph_Archon_quick, ('queued'))]},
{'name': 'Select_Two_Unit_Morph_Archon', 'arg': ['tag', 'tag'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(3, F.select_rect, ('add', 'screen1_tag2', 'screen2_tag2')),
(296, F.Morph_Archon_quick, ('queued'))]},
],
units.Protoss.Disruptor: PROTOSS_BASIC_ACTION_3 + [
{'name': 'Ability_PurificationNova_Attack_Unit', 'arg': ['tag'],
'func': [(219, F.Effect_PurificationNova_screen, ('queued', 'screen_tag'))]},
],
# units.Protoss.DisruptorPhased: PROTOSS_BASIC_ACTION_2,
},
},
'CombatGroup6': {
'describe': "Protoss tactical support commander, controls Sentry and Mothership. "
"Responsible for providing tactical support by using skills",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Sentry-1', 'unit_type': [units.Protoss.Sentry],
'game_group': 9, 'select_type': 'group'},
{'name': 'Mothership', 'unit_type': [units.Protoss.Mothership],
'game_group': -1, 'select_type': 'select'}
],
'action': {
units.Protoss.Sentry: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_ForceField_Screen', 'arg': ['screen'],
'func': [(193, F.Effect_ForceField_screen, ('queued', 'screen'))]},
{'name': 'Ability_GuardianShield', 'arg': [],
'func': [(197, F.Effect_GuardianShield_quick, ('queued'))]},
# # Hallucination not supported in pysc2
# {'name': 'Hallucination_Adept', 'arg': [],
# 'func': [(248, F.Hallucination_Adept_quick, ('queued'))]},
# {'name': 'Hallucination_Archon', 'arg': [],
# 'func': [(249, F.Hallucination_Archon_quick, ('queued'))]},
# {'name': 'Hallucination_Colossus', 'arg': [],
# 'func': [(250, F.Hallucination_Colossus_quick, ('queued'))]},
# {'name': 'Hallucination_Disruptor', 'arg': [],
# 'func': [(251, F.Hallucination_Disruptor_quick, ('queued'))]},
# {'name': 'Hallucination_HighTemplar', 'arg': [],
# 'func': [(252, F.Hallucination_HighTemplar_quick, ('queued'))]},
# {'name': 'Hallucination_Immortal', 'arg': [],
# 'func': [(253, F.Hallucination_Immortal_quick, ('queued'))]},
# {'name': 'Hallucination_Oracle', 'arg': [],
# 'func': [(254, F.Hallucination_Oracle_quick, ('queued'))]},
# {'name': 'Hallucination_Phoenix', 'arg': [],
# 'func': [(255, F.Hallucination_Phoenix_quick, ('queued'))]},
# {'name': 'Hallucination_Probe', 'arg': [],
# 'func': [(256, F.Hallucination_Probe_quick, ('queued'))]},
# {'name': 'Hallucination_Stalker', 'arg': [],
# 'func': [(257, F.Hallucination_Stalker_quick, ('queued'))]},
# {'name': 'Hallucination_VoidRay', 'arg': [],
# 'func': [(258, F.Hallucination_VoidRay_quick, ('queued'))]},
# {'name': 'Hallucination_WarpPrism', 'arg': [],
# 'func': [(259, F.Hallucination_WarpPrism_quick, ('queued'))]},
# {'name': 'Hallucination_Zealot', 'arg': [],
# 'func': [(260, F.Hallucination_Zealot_quick, ('queued'))]},
],
units.Protoss.Mothership: PROTOSS_BASIC_ACTION_3 + [
# Ability_CloakingField not supported in pysc2
# Ability_MothershipMassRecall not neccessary in simple combat tasks
# {'name': 'Ability_MothershipMassRecall_Near', 'arg': ['tag'],
# 'func': [(573, F.llm_pysc2_move_camera, ('world_tag')), (208, F.Effect_MassRecall_screen, ('queued', 'screen_tag'))]},
{'name': 'Ability_TimeWarp_Attack', 'arg': ['tag'],
'func': [(241, F.Effect_TimeWarp_screen, ('queued', 'screen_tag'))]},
{'name': 'Ability_TimeWarp_Screen', 'arg': ['screen'],
'func': [(241, F.Effect_TimeWarp_screen, ('queued', 'screen'))]},
],
},
},
'CombatGroup7': {
'describe': "Protoss special force commander, controls Adept and DarkTemplar. "
"Responsible for infiltrating the enemy's rear and disrupt economic production, sometimes "
"collecting reconnaissance infomation, participating in frontline combat.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Adept-1', 'unit_type': [units.Protoss.Adept],
'game_group': -1, 'select_type': 'select_all_type'},
{'name': 'AdeptPhase-1', 'unit_type': [units.Protoss.AdeptPhaseShift],
'game_group': -1, 'select_type': 'select_all_type'},
{'name': 'DarkTemplar-1', 'unit_type': [units.Protoss.DarkTemplar],
'game_group': -1, 'select_type': 'select_all_type'},
# {'name': 'DarkTemplar-2', 'unit_type': [units.Protoss.DarkTemplar],
# 'game_group': -1, 'select_type': 'select_all_type'}, # more than one select_all_type not currently supported
],
'action': {
units.Protoss.AdeptPhaseShift: PROTOSS_BASIC_ACTION_3,
units.Protoss.Adept: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_AdeptPhaseShift_Screen', 'arg': ['screen'],
'func': [(177, F.Effect_AdeptPhaseShift_screen, ('queued', 'screen'))]},
{'name': 'Ability_AdeptPhaseShift_Minimap', 'arg': ['minimap'],
'func': [(547, F.Effect_AdeptPhaseShift_minimap, ('queued', 'minimap'))]},
{'name': 'Ability_CancelPhaseShift', 'arg': [], 'func': [(141, F.Cancel_AdeptPhaseShift_quick, ('queued'))]},
],
units.Protoss.DarkTemplar: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_ShadowStride_Unit', 'arg': ['tag'],
'func': [(182, F.Effect_ShadowStride_screen, ('queued', 'screen_tag'))]},
{'name': 'Morph_Archon', 'arg': [],
'func': [(296, F.Morph_Archon_quick, ('queued'))]},
{'name': 'Select_Two_Unit_Morph_Archon', 'arg': ['tag', 'tag'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(3, F.select_rect, ('add', 'screen1_tag2', 'screen2_tag2')), # screen1/2_tag2 not realized yet
(296, F.Morph_Archon_quick, ('queued'))]},
],
},
},
'CombatGroup8': {
'describe': "Protoss air special force commander, controls Oracle and Phoenix. "
"Responsible for infiltrating the enemy's rear and disrupt economic production, sometimes "
"collecting reconnaissance infomation, participating in frontline combat, or build StasisTrap "
"to block the enemy's main force.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Oracle-1', 'unit_type': [units.Protoss.Oracle],
'game_group': -1, 'select_type': 'select_all_type'},
{'name': 'Phoenix-1', 'unit_type': [units.Protoss.Phoenix],
'game_group': -1, 'select_type': 'select_all_type'},
],
'action': {
units.Protoss.Oracle: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_PulsarBeamOn', 'arg': [],
'func': [(38, F.Behavior_PulsarBeamOn_quick, ('queued'))]},
{'name': 'Ability_OracleRevelation_Screen', 'arg': ['screen'],
'func': [(214, F.Effect_OracleRevelation_screen, ('queued', 'screen'))]},
{'name': 'Build_StasisTrap_Screen', 'arg': ['screen'],
'func': [(90, F.Build_StasisTrap_screen, ('queued', 'screen'))]},
{'name': 'Select_Unit_Ability_PulsarBeamOn', 'arg': ['tag'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(38, F.Behavior_PulsarBeamOn_quick, ('queued'))]},
{'name': 'Select_Unit_OracleRevelation_Screen', 'arg': ['tag', 'screen'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(214, F.Effect_OracleRevelation_screen, ('queued', 'screen'))]},
{'name': 'Select_Unit_Build_StasisTrap_Screen', 'arg': ['tag', 'screen'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(90, F.Build_StasisTrap_screen, ('queued', 'screen'))]},
],
units.Protoss.Phoenix: PROTOSS_BASIC_ACTION_2 + [
{'name': 'Ability_GravitonBeam_Unit', 'arg': ['tag'],
'func': [(196, F.Effect_GravitonBeam_screen, ('queued', 'screen_tag'))]},
{'name': 'Select_Unit_Ability_GravitonBeam_Unit', 'arg': ['tag', 'tag'],
'func': [(3, F.select_rect, ('select', 'screen1_tag', 'screen2_tag')),
(196, F.Effect_GravitonBeam_screen, ('queued', 'screen_tag2'))]},
],
},
},
'CombatGroup9': {
'describe': "Protoss airborne commander, controls WarpPrism and airborne units like Zealots, Stalkers."
"Responsible for supplement troops on the front line, or executing multi line combat. "
"Keep stability as much as possible in WarpRismPhashing mode to provide stable power field for "
"unit warpping.",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'WarpPrism', 'unit_type': [units.Protoss.WarpPrism, units.Protoss.WarpPrismPhasing],
'game_group': -1, 'select_type': 'select'},
],
'action': {
units.Protoss.WarpPrism: PROTOSS_BASIC_ACTION_3 + [
{'name': 'Morph_WarpPrismPhasingMode', 'arg': [],
'func': [(329, F.Morph_WarpPrismPhasingMode_quick, ('queued'))]},
{'name': 'Load_Unit', 'arg': ['tag'], 'func': [(287, F.Load_screen, ('queued', 'screen_tag'))]},
{'name': 'Unload_Screen', 'arg': ['screen'],
'func': [(516, F.UnloadAllAt_screen, ('queued', 'screen'))]},
],
units.Protoss.WarpPrismPhasing: [
{'name': 'Wait_For_Unit_Warp', 'arg': [], 'func': [(0, F.no_op, ())]},
{'name': 'Morph_WarpPrismTransportMode', 'arg': [],
'func': [(330, F.Morph_WarpPrismTransportMode_quick, ('queued'))]},
],
},
},
}
# TerranAgentConfig part undergoing
class TerranAgentConfig(AgentConfig):
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | true |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/__init__.py | llm_pysc2/agents/configs/__init__.py |
from llm_pysc2.agents.configs.config import *
from llm_pysc2.agents.configs.llm_pysc2 import *
from llm_pysc2.agents.configs.llm_smac import * | python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_smac/config_2c.py | llm_pysc2/agents/configs/llm_smac/config_2c.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs.config import ProtossAgentConfig
from llm_pysc2.lib.llm_action import *
class ConfigSmac_2c(ProtossAgentConfig):
def __init__(self):
super(ConfigSmac_2c, self).__init__()
self.ENABLE_INIT_STEPS = False
self.ENABLE_AUTO_WORKER_MANAGE = False
self.ENABLE_AUTO_WORKER_TRAINING = False
# self.LLM_SIMULATION_TIME = 0
# self.MAX_LLM_QUERY_TIMES = 5
# self.MAX_LLM_WAITING_TIME = 10
# self.MAX_LLM_RUNTIME_ERROR_TIME = 30
# self.MAX_LLM_DECISION_FREQUENCY = 1
# self.MAX_NUM_ACTIONS = 3
self.AGENTS_ALWAYS_DISABLE = []
self.AGENTS = {
'CombatGroupSmac': {
'describe': "Protoss military commander, controls units to fight against enemy. ",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Colossus-1', 'unit_type': [units.Protoss.Colossus],
'game_group': 1, 'select_type': 'group'},
{'name': 'Colossus-2', 'unit_type': [units.Protoss.Colossus],
'game_group': 2, 'select_type': 'group'},
],
'action': {
units.Protoss.Colossus: PROTOSS_BASIC_ACTION_SMAC2,
},
},
}
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_smac/config_3s.py | llm_pysc2/agents/configs/llm_smac/config_3s.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs.config import ProtossAgentConfig
from llm_pysc2.lib.llm_action import *
class ConfigSmac_3s(ProtossAgentConfig):
def __init__(self):
super(ConfigSmac_3s, self).__init__()
self.ENABLE_INIT_STEPS = False
self.ENABLE_AUTO_WORKER_MANAGE = False
self.ENABLE_AUTO_WORKER_TRAINING = False
# self.LLM_SIMULATION_TIME = 0
# self.MAX_LLM_QUERY_TIMES = 5
# self.MAX_LLM_WAITING_TIME = 10
# self.MAX_LLM_RUNTIME_ERROR_TIME = 30
# self.MAX_LLM_DECISION_FREQUENCY = 1
# self.MAX_NUM_ACTIONS = 3
self.AGENTS_ALWAYS_DISABLE = []
self.AGENTS = {
'CombatGroupSmac': {
'describe': "Protoss military commander, controls units to fight against enemy. ",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Stalker-1', 'unit_type': [units.Protoss.Stalker],
'game_group': 4, 'select_type': 'group'},
{'name': 'Stalker-2', 'unit_type': [units.Protoss.Stalker],
'game_group': 5, 'select_type': 'group'},
{'name': 'Stalker-3', 'unit_type': [units.Protoss.Stalker],
'game_group': 6, 'select_type': 'group'},
],
'action': {
units.Protoss.Stalker: PROTOSS_BASIC_ACTION_SMAC2,
},
},
}
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_smac/config_3s5z.py | llm_pysc2/agents/configs/llm_smac/config_3s5z.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs.config import ProtossAgentConfig
from llm_pysc2.lib.llm_action import *
class ConfigSmac_3s5z(ProtossAgentConfig):
def __init__(self):
super(ConfigSmac_3s5z, self).__init__()
self.ENABLE_INIT_STEPS = False
self.ENABLE_AUTO_WORKER_MANAGE = False
self.ENABLE_AUTO_WORKER_TRAINING = False
# self.LLM_SIMULATION_TIME = 0
# self.MAX_LLM_QUERY_TIMES = 5
# self.MAX_LLM_WAITING_TIME = 10
# self.MAX_LLM_RUNTIME_ERROR_TIME = 30
# self.MAX_LLM_DECISION_FREQUENCY = 1
# self.MAX_NUM_ACTIONS = 3
self.AGENTS_ALWAYS_DISABLE = []
self.AGENTS = {
'CombatGroupSmac': {
'describe': "Protoss military commander, controls units to fight against enemy. ",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Zealot-1', 'unit_type': [units.Protoss.Zealot],
'game_group': 1, 'select_type': 'group'},
{'name': 'Zealot-2', 'unit_type': [units.Protoss.Zealot],
'game_group': 2, 'select_type': 'group'},
{'name': 'Zealot-3', 'unit_type': [units.Protoss.Zealot],
'game_group': 3, 'select_type': 'group'},
{'name': 'Stalker-1', 'unit_type': [units.Protoss.Stalker],
'game_group': 4, 'select_type': 'group'},
],
'action': {
units.Protoss.Zealot: PROTOSS_BASIC_ACTION_SMAC,
units.Protoss.Stalker: PROTOSS_BASIC_ACTION_SMAC,
},
},
}
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_smac/config_2s3z.py | llm_pysc2/agents/configs/llm_smac/config_2s3z.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs.config import ProtossAgentConfig
from llm_pysc2.lib.llm_action import *
class ConfigSmac_2s3z(ProtossAgentConfig):
def __init__(self):
super(ConfigSmac_2s3z, self).__init__()
self.ENABLE_INIT_STEPS = False
self.ENABLE_AUTO_WORKER_MANAGE = False
self.ENABLE_AUTO_WORKER_TRAINING = False
# self.LLM_SIMULATION_TIME = 0
# self.MAX_LLM_QUERY_TIMES = 5
# self.MAX_LLM_WAITING_TIME = 10
# self.MAX_LLM_RUNTIME_ERROR_TIME = 30
# self.MAX_LLM_DECISION_FREQUENCY = 1
# self.MAX_NUM_ACTIONS = 3
self.AGENTS = {
'CombatGroupSmac': {
'describe': "Protoss military commander, controls units to fight against enemy. ",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Zealot-1', 'unit_type': [units.Protoss.Zealot],
'game_group': 1, 'select_type': 'group'},
{'name': 'Zealot-2', 'unit_type': [units.Protoss.Zealot],
'game_group': 2, 'select_type': 'group'},
{'name': 'Stalker-1', 'unit_type': [units.Protoss.Stalker],
'game_group': 4, 'select_type': 'group'},
],
'action': {
units.Protoss.Zealot: PROTOSS_BASIC_ACTION_SMAC,
units.Protoss.Stalker: PROTOSS_BASIC_ACTION_SMAC,
},
},
}
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_smac/config_2s.py | llm_pysc2/agents/configs/llm_smac/config_2s.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs.config import ProtossAgentConfig
from llm_pysc2.lib.llm_action import *
class ConfigSmac_2s(ProtossAgentConfig):
def __init__(self):
super(ConfigSmac_2s, self).__init__()
self.ENABLE_INIT_STEPS = False
self.ENABLE_AUTO_WORKER_MANAGE = False
self.ENABLE_AUTO_WORKER_TRAINING = False
# self.LLM_SIMULATION_TIME = 0
# self.MAX_LLM_QUERY_TIMES = 5
# self.MAX_LLM_WAITING_TIME = 10
# self.MAX_LLM_RUNTIME_ERROR_TIME = 30
# self.MAX_LLM_DECISION_FREQUENCY = 1
# self.MAX_NUM_ACTIONS = 3
self.AGENTS_ALWAYS_DISABLE = []
self.AGENTS = {
'CombatGroupSmac': {
'describe': "Protoss military commander, controls units to fight against enemy. ",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Stalker-1', 'unit_type': [units.Protoss.Stalker],
'game_group': 4, 'select_type': 'group'},
{'name': 'Stalker-2', 'unit_type': [units.Protoss.Stalker],
'game_group': 5, 'select_type': 'group'},
],
'action': {
units.Protoss.Stalker: PROTOSS_BASIC_ACTION_SMAC2,
},
},
}
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_smac/__init__.py | llm_pysc2/agents/configs/llm_smac/__init__.py |
from llm_pysc2.agents.configs.llm_smac.config_2c import ConfigSmac_2c
from llm_pysc2.agents.configs.llm_smac.config_1c3s5z import ConfigSmac_1c3s5z
from llm_pysc2.agents.configs.llm_smac.config_3s import ConfigSmac_3s
from llm_pysc2.agents.configs.llm_smac.config_2s import ConfigSmac_2s
from llm_pysc2.agents.configs.llm_smac.config_2s3z import ConfigSmac_2s3z
from llm_pysc2.agents.configs.llm_smac.config_3s5z import ConfigSmac_3s5z
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_smac/config_1c3s5z.py | llm_pysc2/agents/configs/llm_smac/config_1c3s5z.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs.config import ProtossAgentConfig
from llm_pysc2.lib.llm_action import *
class ConfigSmac_1c3s5z(ProtossAgentConfig):
def __init__(self):
super(ConfigSmac_1c3s5z, self).__init__()
self.ENABLE_INIT_STEPS = False
self.ENABLE_AUTO_WORKER_MANAGE = False
self.ENABLE_AUTO_WORKER_TRAINING = False
# self.LLM_SIMULATION_TIME = 0
# self.MAX_LLM_QUERY_TIMES = 5
# self.MAX_LLM_WAITING_TIME = 10
# self.MAX_LLM_RUNTIME_ERROR_TIME = 30
# self.MAX_LLM_DECISION_FREQUENCY = 1
# self.MAX_NUM_ACTIONS = 3
self.AGENTS_ALWAYS_DISABLE = []
self.AGENTS = {
'CombatGroupSmac': {
'describe': "Protoss military commander, controls units to fight against enemy. ",
'llm': {
'basic_prompt': self.basic_prompt,
'translator_o': self.translator_o,
'translator_a': self.translator_a,
'img_fea': self.ENABLE_IMAGE_FEATURE,
'img_rgb': self.ENABLE_IMAGE_RGB,
'model_name': self.model_name,
'api_base': self.api_base,
'api_key': self.api_key,
},
'team': [
{'name': 'Zealot-1', 'unit_type': [units.Protoss.Zealot],
'game_group': 1, 'select_type': 'group'},
{'name': 'Zealot-2', 'unit_type': [units.Protoss.Zealot],
'game_group': 2, 'select_type': 'group'},
{'name': 'Zealot-3', 'unit_type': [units.Protoss.Zealot],
'game_group': 3, 'select_type': 'group'},
{'name': 'Stalker-1', 'unit_type': [units.Protoss.Stalker],
'game_group': 4, 'select_type': 'group'},
{'name': 'Colossus-1', 'unit_type': [units.Protoss.Colossus],
'game_group': 5, 'select_type': 'group'},
],
'action': {
units.Protoss.Zealot: PROTOSS_BASIC_ACTION_SMAC,
units.Protoss.Stalker: PROTOSS_BASIC_ACTION_SMAC2,
units.Protoss.Colossus: PROTOSS_BASIC_ACTION_SMAC2,
},
},
}
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_pysc2/config_combat.py | llm_pysc2/agents/configs/llm_pysc2/config_combat.py | # Copyright 2024, LLM-PySC2 Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from llm_pysc2.agents.configs.config import ProtossAgentConfig
class ConfigPysc2_Combat(ProtossAgentConfig):
def __init__(self):
super(ConfigPysc2_Combat, self).__init__()
self.AGENTS_ALWAYS_DISABLE = [
'Airborne', 'Builder', 'Commander', 'Developer', 'Defender', 'CombatGroup4',
]
self.ENABLE_INIT_STEPS = False
self.ENABLE_AUTO_WORKER_MANAGE = False
self.ENABLE_AUTO_WORKER_TRAINING = False
# self.LLM_SIMULATION_TIME = 0
# self.MAX_LLM_QUERY_TIMES = 5
# self.MAX_LLM_WAITING_TIME = 10
# self.MAX_LLM_RUNTIME_ERROR_TIME = 30
# self.MAX_LLM_DECISION_FREQUENCY = 1
# self.MAX_NUM_ACTIONS = 3
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
NKAI-Decision-Team/LLM-PySC2 | https://github.com/NKAI-Decision-Team/LLM-PySC2/blob/551c863475c0c4a96a181080974d24b59589e9f3/llm_pysc2/agents/configs/llm_pysc2/__init__.py | llm_pysc2/agents/configs/llm_pysc2/__init__.py |
from llm_pysc2.agents.configs.llm_pysc2.config_combat import ConfigPysc2_Combat
from llm_pysc2.agents.configs.llm_pysc2.config_defend import ConfigPysc2_Defend
from llm_pysc2.agents.configs.llm_pysc2.config_harass import ConfigPysc2_Harass
| python | Apache-2.0 | 551c863475c0c4a96a181080974d24b59589e9f3 | 2026-01-05T07:14:50.369338Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.