cuju-engine 0.3.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cuju/__init__.py +217 -0
- cuju/__main__.py +262 -0
- cuju/_batch/__init__.py +4 -0
- cuju/_batch/allocator.py +52 -0
- cuju/_batch/assets.py +68 -0
- cuju/_batch/environment.py +1890 -0
- cuju/_batch/frame_stack.py +114 -0
- cuju/_batch/library.py +190 -0
- cuju/_batch/log.py +103 -0
- cuju/_batch/memory.py +70 -0
- cuju/_batch/operators.py +55 -0
- cuju/_batch/pinned.py +39 -0
- cuju/_batch/pixels.py +207 -0
- cuju/_batch/state.py +77 -0
- cuju/_checksums.py +60 -0
- cuju/_cli_contract.py +244 -0
- cuju/_cli_parsers.py +191 -0
- cuju/_completion.py +277 -0
- cuju/_dump_to_txt.py +66 -0
- cuju/_grf_config.py +331 -0
- cuju/_library_path.py +141 -0
- cuju/_media.py +113 -0
- cuju/_pixels.py +276 -0
- cuju/_plugins.py +106 -0
- cuju/_python_players.py +224 -0
- cuju/_replay_command.py +109 -0
- cuju/_replay_player.py +42 -0
- cuju/_replays.py +414 -0
- cuju/_script_helpers.py +109 -0
- cuju/_version.py +6 -0
- cuju/action_log.py +371 -0
- cuju/check.py +596 -0
- cuju/cuju_cpu.dll +0 -0
- cuju/cuju_cuda.dll +0 -0
- cuju/cuju_render.dll +0 -0
- cuju/data/SHA256SUMS +20 -0
- cuju/data/animations.bin +0 -0
- cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
- cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
- cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
- cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
- cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
- cuju/data/digests.json +186 -0
- cuju/data/render_digests.json.z +0 -0
- cuju/data/scenarios/11_vs_11_competition.py +45 -0
- cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
- cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
- cuju/data/scenarios/1_vs_1_easy.py +25 -0
- cuju/data/scenarios/5_vs_5.py +33 -0
- cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
- cuju/data/scenarios/academy_corner.py +45 -0
- cuju/data/scenarios/academy_counterattack_easy.py +45 -0
- cuju/data/scenarios/academy_counterattack_hard.py +45 -0
- cuju/data/scenarios/academy_empty_goal.py +25 -0
- cuju/data/scenarios/academy_empty_goal_close.py +25 -0
- cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_to_score.py +30 -0
- cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
- cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
- cuju/data/scenarios/test_example_multiagent.py +28 -0
- cuju/dumps.py +942 -0
- cuju/engine_status.py +106 -0
- cuju/env.py +1168 -0
- cuju/errors.py +108 -0
- cuju/gfootball/GRF_SOURCES +86 -0
- cuju/gfootball/__init__.py +60 -0
- cuju/gfootball/_cv2.py +43 -0
- cuju/gfootball/_gym/__init__.py +88 -0
- cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
- cuju/gfootball/_gym/_vendored/__init__.py +43 -0
- cuju/gfootball/_gym/_vendored/core.py +361 -0
- cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
- cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
- cuju/gfootball/_gym/_vendored/error.py +230 -0
- cuju/gfootball/_gym/_vendored/logger.py +56 -0
- cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
- cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
- cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
- cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
- cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
- cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
- cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
- cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
- cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
- cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
- cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
- cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
- cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
- cuju/gfootball/_gym/_vendored/version.py +5 -0
- cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
- cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
- cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
- cuju/gfootball/dump_to_txt.py +49 -0
- cuju/gfootball/dump_to_video.py +33 -0
- cuju/gfootball/env/__init__.py +271 -0
- cuju/gfootball/env/config.py +163 -0
- cuju/gfootball/env/constants.py +33 -0
- cuju/gfootball/env/controller_base.py +114 -0
- cuju/gfootball/env/event_queue.py +54 -0
- cuju/gfootball/env/football_action_set.py +220 -0
- cuju/gfootball/env/football_action_set_test.py +76 -0
- cuju/gfootball/env/football_env.py +225 -0
- cuju/gfootball/env/football_env_core.py +447 -0
- cuju/gfootball/env/football_env_test.py +692 -0
- cuju/gfootball/env/gym_test.py +47 -0
- cuju/gfootball/env/observation_preprocessing.py +94 -0
- cuju/gfootball/env/observation_processor.py +526 -0
- cuju/gfootball/env/observation_rotation.py +163 -0
- cuju/gfootball/env/observation_rotation_test.py +84 -0
- cuju/gfootball/env/player_base.py +46 -0
- cuju/gfootball/env/players/__init__.py +16 -0
- cuju/gfootball/env/players/agent.py +39 -0
- cuju/gfootball/env/players/bot.py +217 -0
- cuju/gfootball/env/players/gamepad.py +81 -0
- cuju/gfootball/env/players/keyboard.py +72 -0
- cuju/gfootball/env/players/lazy.py +31 -0
- cuju/gfootball/env/players/ppo2_cnn.py +119 -0
- cuju/gfootball/env/players/replay.py +40 -0
- cuju/gfootball/env/remote_football_env.py +189 -0
- cuju/gfootball/env/scenario_builder.py +125 -0
- cuju/gfootball/env/script_helpers.py +130 -0
- cuju/gfootball/env/script_helpers_test.py +107 -0
- cuju/gfootball/env/wrappers.py +440 -0
- cuju/gfootball/env/wrappers_test.py +150 -0
- cuju/gfootball/eval_server/__init__.py +17 -0
- cuju/gfootball/eval_server/config.py +30 -0
- cuju/gfootball/eval_server/example_client.py +107 -0
- cuju/gfootball/eval_server/proto/game_server.proto +62 -0
- cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
- cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
- cuju/gfootball/eval_server/proto/master.proto +25 -0
- cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
- cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
- cuju/gfootball/eval_server/utils.py +52 -0
- cuju/gfootball/examples/__init__.py +16 -0
- cuju/gfootball/examples/models.py +66 -0
- cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
- cuju/gfootball/examples/run_ppo2.py +123 -0
- cuju/gfootball/play_game.py +73 -0
- cuju/gfootball/replay.py +43 -0
- cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
- cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
- cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
- cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
- cuju/gfootball/scenarios/5_vs_5.py +46 -0
- cuju/gfootball/scenarios/__init__.py +31 -0
- cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
- cuju/gfootball/scenarios/academy_corner.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
- cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
- cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
- cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
- cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
- cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
- cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
- cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
- cuju/gfootball/scenarios/tests/__init__.py +31 -0
- cuju/gfootball/scenarios/tests/corner_test.py +38 -0
- cuju/gfootball/scenarios/tests/goal_test.py +35 -0
- cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
- cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
- cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
- cuju/gfootball/scenarios/tests/offside_test.py +39 -0
- cuju/gfootball/scenarios/tests/penalty.py +34 -0
- cuju/gfootball/scenarios/tests/second_half.py +33 -0
- cuju/gfootball/scenarios/tests/symmetric.py +53 -0
- cuju/gfootball_engine/__init__.py +31 -0
- cuju/gfootball_engine/_gameplayfootball.py +1624 -0
- cuju/gfootball_engine/_native.py +193 -0
- cuju/gfootball_engine/_pickle_names.py +114 -0
- cuju/gfootball_engine/_render_hooks.py +156 -0
- cuju/kaggle.py +425 -0
- cuju/multi_device.py +401 -0
- cuju/players.py +260 -0
- cuju/raw.py +93 -0
- cuju/scenarios.py +661 -0
- cuju/state.py +211 -0
- cuju/wrappers.py +325 -0
- cuju_engine-0.3.0.dist-info/METADATA +325 -0
- cuju_engine-0.3.0.dist-info/RECORD +222 -0
- cuju_engine-0.3.0.dist-info/WHEEL +5 -0
- cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
- cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# coding=utf-8
|
|
2
|
+
# Copyright 2019 Google LLC
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# Modified by the cuju Authors in 2026, in the import lines that ci/port_gfootball.py lists.
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
"""Set of functions used by command line scripts."""
|
|
19
|
+
|
|
20
|
+
from __future__ import absolute_import
|
|
21
|
+
from __future__ import division
|
|
22
|
+
from __future__ import print_function
|
|
23
|
+
|
|
24
|
+
from cuju.gfootball.env import config
|
|
25
|
+
from cuju.gfootball.env import football_action_set
|
|
26
|
+
from cuju.gfootball.env import football_env
|
|
27
|
+
from cuju.gfootball.env import observation_processor
|
|
28
|
+
|
|
29
|
+
import copy
|
|
30
|
+
import six.moves.cPickle
|
|
31
|
+
import os
|
|
32
|
+
import tempfile
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ScriptHelpers(object):
|
|
36
|
+
"""Set of methods used by command line scripts."""
|
|
37
|
+
|
|
38
|
+
def __init__(self):
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
def __modify_trace(self, replay, fps):
|
|
42
|
+
"""Adopt replay to the new framerate and add additional steps at the end."""
|
|
43
|
+
trace = []
|
|
44
|
+
min_fps = replay[0]['debug']['config']['physics_steps_per_frame']
|
|
45
|
+
assert fps % min_fps == 0, (
|
|
46
|
+
'Trace has to be rendered in framerate being multiple of {}'.format(
|
|
47
|
+
min_fps))
|
|
48
|
+
assert fps <= 100, ('Framerate of up to 100 is supported')
|
|
49
|
+
empty_steps = int(fps / min_fps) - 1
|
|
50
|
+
for f in replay:
|
|
51
|
+
trace.append(f)
|
|
52
|
+
idle_step = copy.deepcopy(f)
|
|
53
|
+
idle_step['debug']['action'] = [football_action_set.action_idle
|
|
54
|
+
] * len(f['debug']['action'])
|
|
55
|
+
for _ in range(empty_steps):
|
|
56
|
+
trace.append(idle_step)
|
|
57
|
+
# Add some empty steps at the end, so that we can record videos.
|
|
58
|
+
for _ in range(10):
|
|
59
|
+
trace.append(idle_step)
|
|
60
|
+
return trace
|
|
61
|
+
|
|
62
|
+
def __build_players(self, dump_file, spec):
|
|
63
|
+
players = []
|
|
64
|
+
for player in spec:
|
|
65
|
+
players.extend(['replay:path={},left_players=1'.format(
|
|
66
|
+
dump_file)] * config.count_left_players(player))
|
|
67
|
+
players.extend(['replay:path={},right_players=1'.format(
|
|
68
|
+
dump_file)] * config.count_right_players(player))
|
|
69
|
+
return players
|
|
70
|
+
|
|
71
|
+
def load_dump(self, dump_file):
|
|
72
|
+
dump = []
|
|
73
|
+
with open(dump_file, 'rb') as in_fd:
|
|
74
|
+
while True:
|
|
75
|
+
try:
|
|
76
|
+
step = six.moves.cPickle.load(in_fd)
|
|
77
|
+
except EOFError:
|
|
78
|
+
return dump
|
|
79
|
+
dump.append(step)
|
|
80
|
+
|
|
81
|
+
def dump_to_txt(self, dump_file, output, include_debug):
|
|
82
|
+
with open(output, 'w') as out_fd:
|
|
83
|
+
dump = self.load_dump(dump_file)
|
|
84
|
+
if not include_debug:
|
|
85
|
+
for s in dump:
|
|
86
|
+
if 'debug' in s:
|
|
87
|
+
del s['debug']
|
|
88
|
+
with open(output, 'w') as f:
|
|
89
|
+
f.write(str(dump))
|
|
90
|
+
|
|
91
|
+
def dump_to_video(self, dump_file):
|
|
92
|
+
dump = self.load_dump(dump_file)
|
|
93
|
+
cfg = config.Config(dump[0]['debug']['config'])
|
|
94
|
+
cfg['dump_full_episodes'] = True
|
|
95
|
+
cfg['write_video'] = True
|
|
96
|
+
cfg['display_game_stats'] = True
|
|
97
|
+
processor = observation_processor.ObservationProcessor(cfg)
|
|
98
|
+
processor.write_dump('episode_done')
|
|
99
|
+
for frame in dump:
|
|
100
|
+
processor.update(frame)
|
|
101
|
+
|
|
102
|
+
def replay(self, dump, fps=10, config_update={}, directory=None, render=True):
|
|
103
|
+
replay = self.load_dump(dump)
|
|
104
|
+
trace = self.__modify_trace(replay, fps)
|
|
105
|
+
fd, temp_path = tempfile.mkstemp(suffix='.dump')
|
|
106
|
+
with open(temp_path, 'wb') as f:
|
|
107
|
+
for step in trace:
|
|
108
|
+
six.moves.cPickle.dump(step, f)
|
|
109
|
+
assert replay[0]['debug']['frame_cnt'] == 0, (
|
|
110
|
+
'Trace does not start from the beginning of the episode, can not replay')
|
|
111
|
+
cfg = config.Config(replay[0]['debug']['config'])
|
|
112
|
+
cfg['players'] = self.__build_players(temp_path, cfg['players'])
|
|
113
|
+
config_update['physics_steps_per_frame'] = int(100 / fps)
|
|
114
|
+
config_update['real_time'] = False
|
|
115
|
+
if directory:
|
|
116
|
+
config_update['tracesdir'] = directory
|
|
117
|
+
config_update['write_video'] = True
|
|
118
|
+
cfg.update(config_update)
|
|
119
|
+
env = football_env.FootballEnv(cfg)
|
|
120
|
+
if render:
|
|
121
|
+
env.render()
|
|
122
|
+
env.reset()
|
|
123
|
+
done = False
|
|
124
|
+
try:
|
|
125
|
+
while not done:
|
|
126
|
+
_, _, done, _ = env.step([])
|
|
127
|
+
except KeyboardInterrupt:
|
|
128
|
+
env.write_dump('shutdown')
|
|
129
|
+
exit(1)
|
|
130
|
+
os.close(fd)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# coding=utf-8
|
|
2
|
+
# Copyright 2019 Google LLC
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# Modified by the cuju Authors in 2026, in the import lines that ci/port_gfootball.py lists.
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
"""Script helpers test."""
|
|
19
|
+
|
|
20
|
+
from __future__ import absolute_import
|
|
21
|
+
from __future__ import division
|
|
22
|
+
from __future__ import print_function
|
|
23
|
+
|
|
24
|
+
import glob
|
|
25
|
+
import os
|
|
26
|
+
import zlib
|
|
27
|
+
import tempfile
|
|
28
|
+
from absl.testing import absltest
|
|
29
|
+
|
|
30
|
+
from cuju.gfootball.env import config
|
|
31
|
+
from cuju.gfootball.env import football_action_set
|
|
32
|
+
from cuju.gfootball.env import football_env
|
|
33
|
+
from cuju.gfootball.env import script_helpers
|
|
34
|
+
|
|
35
|
+
test_tmpdir = os.path.join(tempfile.gettempdir(), 'gfootball_test')
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ScriptHelpersTest(absltest.TestCase):
|
|
39
|
+
|
|
40
|
+
def generate_replay(self):
|
|
41
|
+
"""Generates replay of an episode."""
|
|
42
|
+
cfg = config.Config()
|
|
43
|
+
left_players = 2
|
|
44
|
+
cfg.update({
|
|
45
|
+
'action_set': 'full',
|
|
46
|
+
'level': 'tests.corner_test',
|
|
47
|
+
'dump_full_episodes': True,
|
|
48
|
+
'players': ['agent:left_players={}'.format(left_players),
|
|
49
|
+
'bot:right_players=1', 'lazy:right_players=1'],
|
|
50
|
+
'tracesdir': test_tmpdir
|
|
51
|
+
})
|
|
52
|
+
env = football_env.FootballEnv(cfg)
|
|
53
|
+
env.reset()
|
|
54
|
+
actions_cnt = len(football_action_set.get_action_set(cfg))
|
|
55
|
+
done = False
|
|
56
|
+
step = 0
|
|
57
|
+
while not done:
|
|
58
|
+
step += 1
|
|
59
|
+
actions = [(step + x) % actions_cnt for x in range(left_players)]
|
|
60
|
+
_, _, done, _ = env.step(actions)
|
|
61
|
+
env.close()
|
|
62
|
+
|
|
63
|
+
def compute_hash(self, trace_file):
|
|
64
|
+
replay = script_helpers.ScriptHelpers().load_dump(trace_file)
|
|
65
|
+
hash_value = 0
|
|
66
|
+
for frame in replay:
|
|
67
|
+
del frame['debug']
|
|
68
|
+
hash_value = zlib.adler32(str(tuple(sorted(frame.items()))).encode(),
|
|
69
|
+
hash_value)
|
|
70
|
+
return hash_value
|
|
71
|
+
|
|
72
|
+
def current_dumps(self):
|
|
73
|
+
return set(glob.glob(os.path.join(test_tmpdir, 'episode_done*dump')))
|
|
74
|
+
|
|
75
|
+
def test__replay(self):
|
|
76
|
+
"""Has to run first, as it generates dumps for other tests."""
|
|
77
|
+
dumps_before = self.current_dumps()
|
|
78
|
+
self.generate_replay()
|
|
79
|
+
dumps_after = self.current_dumps()
|
|
80
|
+
dump1 = dumps_after - dumps_before
|
|
81
|
+
assert len(dump1) == 1, dump1
|
|
82
|
+
hash1 = self.compute_hash(list(dump1)[0])
|
|
83
|
+
cfg = {
|
|
84
|
+
'dump_full_episodes': True,
|
|
85
|
+
}
|
|
86
|
+
script_helpers.ScriptHelpers().replay(list(dump1)[0],
|
|
87
|
+
directory=test_tmpdir,
|
|
88
|
+
config_update=cfg,
|
|
89
|
+
render=False)
|
|
90
|
+
dump2 = self.current_dumps() - dumps_after
|
|
91
|
+
assert len(dump2) == 1, dump2
|
|
92
|
+
hash2 = self.compute_hash(list(dump2)[0])
|
|
93
|
+
self.assertEqual(hash1, hash2)
|
|
94
|
+
|
|
95
|
+
def test_dump_to_txt(self):
|
|
96
|
+
dump = list(self.current_dumps())[0]
|
|
97
|
+
out_file = dump.replace('dump', 'txt')
|
|
98
|
+
script_helpers.ScriptHelpers().dump_to_txt(dump, out_file, True)
|
|
99
|
+
self.assertTrue(os.path.isfile(out_file))
|
|
100
|
+
|
|
101
|
+
def test_dump_to_video(self):
|
|
102
|
+
dump = list(self.current_dumps())[0]
|
|
103
|
+
script_helpers.ScriptHelpers().dump_to_video(dump)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == '__main__':
|
|
107
|
+
absltest.main()
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
# coding=utf-8
|
|
2
|
+
# Copyright 2019 Google LLC
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# Modified by the cuju Authors in 2026, in the import lines that ci/port_gfootball.py lists.
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
"""Environment that can be used with OpenAI Baselines."""
|
|
19
|
+
|
|
20
|
+
from __future__ import absolute_import
|
|
21
|
+
from __future__ import division
|
|
22
|
+
from __future__ import print_function
|
|
23
|
+
|
|
24
|
+
import collections
|
|
25
|
+
from cuju.gfootball import _cv2 as cv2
|
|
26
|
+
from cuju.gfootball.env import football_action_set
|
|
27
|
+
from cuju.gfootball.env import observation_preprocessing
|
|
28
|
+
from cuju.gfootball import _gym as gym
|
|
29
|
+
import numpy as np
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class GetStateWrapper(gym.Wrapper):
|
|
33
|
+
"""A wrapper that only dumps traces/videos periodically."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, env):
|
|
36
|
+
gym.Wrapper.__init__(self, env)
|
|
37
|
+
self._wrappers_with_support = {
|
|
38
|
+
'CheckpointRewardWrapper', 'FrameStack', 'GetStateWrapper',
|
|
39
|
+
'SingleAgentRewardWrapper', 'SingleAgentObservationWrapper',
|
|
40
|
+
'SMMWrapper', 'PeriodicDumpWriter', 'Simple115StateWrapper',
|
|
41
|
+
'PixelsStateWrapper'
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
def _check_state_supported(self):
|
|
45
|
+
o = self
|
|
46
|
+
while True:
|
|
47
|
+
name = o.__class__.__name__
|
|
48
|
+
if o.__class__.__name__ == 'FootballEnv':
|
|
49
|
+
break
|
|
50
|
+
assert name in self._wrappers_with_support, (
|
|
51
|
+
'get/set state not supported'
|
|
52
|
+
' by {} wrapper').format(name)
|
|
53
|
+
o = o.env
|
|
54
|
+
|
|
55
|
+
def get_state(self):
|
|
56
|
+
self._check_state_supported()
|
|
57
|
+
to_pickle = {}
|
|
58
|
+
return self.env.get_state(to_pickle)
|
|
59
|
+
|
|
60
|
+
def set_state(self, state):
|
|
61
|
+
self._check_state_supported()
|
|
62
|
+
self.env.set_state(state)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class PeriodicDumpWriter(gym.Wrapper):
|
|
66
|
+
"""A wrapper that only dumps traces/videos periodically."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, env, dump_frequency, render=False):
|
|
69
|
+
gym.Wrapper.__init__(self, env)
|
|
70
|
+
self._dump_frequency = dump_frequency
|
|
71
|
+
self._render = render
|
|
72
|
+
self._original_dump_config = {
|
|
73
|
+
'write_video': env._config['write_video'],
|
|
74
|
+
'dump_full_episodes': env._config['dump_full_episodes'],
|
|
75
|
+
'dump_scores': env._config['dump_scores'],
|
|
76
|
+
}
|
|
77
|
+
self._current_episode_number = 0
|
|
78
|
+
|
|
79
|
+
def step(self, action):
|
|
80
|
+
return self.env.step(action)
|
|
81
|
+
|
|
82
|
+
def reset(self):
|
|
83
|
+
if (self._dump_frequency > 0 and
|
|
84
|
+
(self._current_episode_number % self._dump_frequency == 0)):
|
|
85
|
+
self.env._config.update(self._original_dump_config)
|
|
86
|
+
if self._render:
|
|
87
|
+
self.env.render()
|
|
88
|
+
else:
|
|
89
|
+
self.env._config.update({'write_video': False,
|
|
90
|
+
'dump_full_episodes': False,
|
|
91
|
+
'dump_scores': False})
|
|
92
|
+
if self._render:
|
|
93
|
+
self.env.disable_render()
|
|
94
|
+
self._current_episode_number += 1
|
|
95
|
+
return self.env.reset()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Simple115StateWrapper(gym.ObservationWrapper):
|
|
99
|
+
"""A wrapper that converts an observation to 115-features state."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, env, fixed_positions=False):
|
|
102
|
+
"""Initializes the wrapper.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
env: an envorinment to wrap
|
|
106
|
+
fixed_positions: whether to fix observation indexes corresponding to teams
|
|
107
|
+
Note: simple115v2 enables fixed_positions option.
|
|
108
|
+
"""
|
|
109
|
+
gym.ObservationWrapper.__init__(self, env)
|
|
110
|
+
action_shape = np.shape(self.env.action_space)
|
|
111
|
+
shape = (action_shape[0] if len(action_shape) else 1, 115)
|
|
112
|
+
self.observation_space = gym.spaces.Box(
|
|
113
|
+
low=-np.inf, high=np.inf, shape=shape, dtype=np.float32)
|
|
114
|
+
self._fixed_positions = fixed_positions
|
|
115
|
+
|
|
116
|
+
def observation(self, observation):
|
|
117
|
+
"""Converts an observation into simple115 (or simple115v2) format."""
|
|
118
|
+
return Simple115StateWrapper.convert_observation(observation, self._fixed_positions)
|
|
119
|
+
|
|
120
|
+
@staticmethod
|
|
121
|
+
def convert_observation(observation, fixed_positions):
|
|
122
|
+
"""Converts an observation into simple115 (or simple115v2) format.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
observation: observation that the environment returns
|
|
126
|
+
fixed_positions: Players and positions are always occupying 88 fields
|
|
127
|
+
(even if the game is played 1v1).
|
|
128
|
+
If True, the position of the player will be the same - no
|
|
129
|
+
matter how many players are on the field:
|
|
130
|
+
(so first 11 pairs will belong to the first team, even
|
|
131
|
+
if it has less players).
|
|
132
|
+
If False, then the position of players from team2
|
|
133
|
+
will depend on number of players in team1).
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
(N, 115) shaped representation, where N stands for the number of players
|
|
137
|
+
being controlled.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def do_flatten(obj):
|
|
141
|
+
"""Run flatten on either python list or numpy array."""
|
|
142
|
+
if type(obj) == list:
|
|
143
|
+
return np.array(obj).flatten()
|
|
144
|
+
return obj.flatten()
|
|
145
|
+
|
|
146
|
+
final_obs = []
|
|
147
|
+
for obs in observation:
|
|
148
|
+
o = []
|
|
149
|
+
if fixed_positions:
|
|
150
|
+
for i, name in enumerate(['left_team', 'left_team_direction',
|
|
151
|
+
'right_team', 'right_team_direction']):
|
|
152
|
+
o.extend(do_flatten(obs[name]))
|
|
153
|
+
# If there were less than 11vs11 players we backfill missing values
|
|
154
|
+
# with -1.
|
|
155
|
+
if len(o) < (i + 1) * 22:
|
|
156
|
+
o.extend([-1] * ((i + 1) * 22 - len(o)))
|
|
157
|
+
else:
|
|
158
|
+
o.extend(do_flatten(obs['left_team']))
|
|
159
|
+
o.extend(do_flatten(obs['left_team_direction']))
|
|
160
|
+
o.extend(do_flatten(obs['right_team']))
|
|
161
|
+
o.extend(do_flatten(obs['right_team_direction']))
|
|
162
|
+
|
|
163
|
+
# If there were less than 11vs11 players we backfill missing values with
|
|
164
|
+
# -1.
|
|
165
|
+
# 88 = 11 (players) * 2 (teams) * 2 (positions & directions) * 2 (x & y)
|
|
166
|
+
if len(o) < 88:
|
|
167
|
+
o.extend([-1] * (88 - len(o)))
|
|
168
|
+
|
|
169
|
+
# ball position
|
|
170
|
+
o.extend(obs['ball'])
|
|
171
|
+
# ball direction
|
|
172
|
+
o.extend(obs['ball_direction'])
|
|
173
|
+
# one hot encoding of which team owns the ball
|
|
174
|
+
if obs['ball_owned_team'] == -1:
|
|
175
|
+
o.extend([1, 0, 0])
|
|
176
|
+
if obs['ball_owned_team'] == 0:
|
|
177
|
+
o.extend([0, 1, 0])
|
|
178
|
+
if obs['ball_owned_team'] == 1:
|
|
179
|
+
o.extend([0, 0, 1])
|
|
180
|
+
|
|
181
|
+
active = [0] * 11
|
|
182
|
+
if obs['active'] != -1:
|
|
183
|
+
active[obs['active']] = 1
|
|
184
|
+
o.extend(active)
|
|
185
|
+
|
|
186
|
+
game_mode = [0] * 7
|
|
187
|
+
game_mode[obs['game_mode']] = 1
|
|
188
|
+
o.extend(game_mode)
|
|
189
|
+
final_obs.append(o)
|
|
190
|
+
return np.array(final_obs, dtype=np.float32)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class PixelsStateWrapper(gym.ObservationWrapper):
|
|
194
|
+
"""A wrapper that extracts pixel representation."""
|
|
195
|
+
|
|
196
|
+
def __init__(self, env, grayscale=True,
|
|
197
|
+
channel_dimensions=(observation_preprocessing.SMM_WIDTH,
|
|
198
|
+
observation_preprocessing.SMM_HEIGHT)):
|
|
199
|
+
gym.ObservationWrapper.__init__(self, env)
|
|
200
|
+
self._grayscale = grayscale
|
|
201
|
+
self._channel_dimensions = channel_dimensions
|
|
202
|
+
action_shape = np.shape(self.env.action_space)
|
|
203
|
+
self.observation_space = gym.spaces.Box(
|
|
204
|
+
low=0,
|
|
205
|
+
high=255,
|
|
206
|
+
shape=(action_shape[0] if len(action_shape) else 1,
|
|
207
|
+
channel_dimensions[1], channel_dimensions[0],
|
|
208
|
+
1 if grayscale else 3),
|
|
209
|
+
dtype=np.uint8)
|
|
210
|
+
|
|
211
|
+
def observation(self, obs):
|
|
212
|
+
o = []
|
|
213
|
+
for observation in obs:
|
|
214
|
+
assert 'frame' in observation, ("Missing 'frame' in observations. Pixel "
|
|
215
|
+
"representation requires rendering and is"
|
|
216
|
+
" supported only for players on the left "
|
|
217
|
+
"team.")
|
|
218
|
+
frame = observation['frame']
|
|
219
|
+
if self._grayscale:
|
|
220
|
+
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
|
|
221
|
+
frame = cv2.resize(frame, (self._channel_dimensions[0],
|
|
222
|
+
self._channel_dimensions[1]),
|
|
223
|
+
interpolation=cv2.INTER_AREA)
|
|
224
|
+
if self._grayscale:
|
|
225
|
+
frame = np.expand_dims(frame, -1)
|
|
226
|
+
o.append(frame)
|
|
227
|
+
return np.array(o, dtype=np.uint8)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class SMMWrapper(gym.ObservationWrapper):
|
|
231
|
+
"""A wrapper that convers observations into a minimap format."""
|
|
232
|
+
|
|
233
|
+
def __init__(self, env,
|
|
234
|
+
channel_dimensions=(observation_preprocessing.SMM_WIDTH,
|
|
235
|
+
observation_preprocessing.SMM_HEIGHT)):
|
|
236
|
+
gym.ObservationWrapper.__init__(self, env)
|
|
237
|
+
self._channel_dimensions = channel_dimensions
|
|
238
|
+
action_shape = np.shape(self.env.action_space)
|
|
239
|
+
shape = (action_shape[0] if len(action_shape) else 1, channel_dimensions[1],
|
|
240
|
+
channel_dimensions[0],
|
|
241
|
+
len(
|
|
242
|
+
observation_preprocessing.get_smm_layers(
|
|
243
|
+
self.env.unwrapped._config)))
|
|
244
|
+
self.observation_space = gym.spaces.Box(
|
|
245
|
+
low=0, high=255, shape=shape, dtype=np.uint8)
|
|
246
|
+
|
|
247
|
+
def observation(self, obs):
|
|
248
|
+
return observation_preprocessing.generate_smm(
|
|
249
|
+
obs, channel_dimensions=self._channel_dimensions,
|
|
250
|
+
config=self.env.unwrapped._config)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class SingleAgentObservationWrapper(gym.ObservationWrapper):
|
|
254
|
+
"""A wrapper that returns an observation only for the first agent."""
|
|
255
|
+
|
|
256
|
+
def __init__(self, env):
|
|
257
|
+
gym.ObservationWrapper.__init__(self, env)
|
|
258
|
+
self.observation_space = gym.spaces.Box(
|
|
259
|
+
low=env.observation_space.low[0],
|
|
260
|
+
high=env.observation_space.high[0],
|
|
261
|
+
dtype=env.observation_space.dtype)
|
|
262
|
+
|
|
263
|
+
def observation(self, obs):
|
|
264
|
+
return obs[0]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class SingleAgentRewardWrapper(gym.RewardWrapper):
|
|
268
|
+
"""A wrapper that converts an observation to a minimap."""
|
|
269
|
+
|
|
270
|
+
def __init__(self, env):
|
|
271
|
+
gym.RewardWrapper.__init__(self, env)
|
|
272
|
+
|
|
273
|
+
def reward(self, reward):
|
|
274
|
+
return reward[0]
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class CheckpointRewardWrapper(gym.RewardWrapper):
|
|
278
|
+
"""A wrapper that adds a dense checkpoint reward."""
|
|
279
|
+
|
|
280
|
+
def __init__(self, env):
|
|
281
|
+
gym.RewardWrapper.__init__(self, env)
|
|
282
|
+
self._collected_checkpoints = {}
|
|
283
|
+
self._num_checkpoints = 10
|
|
284
|
+
self._checkpoint_reward = 0.1
|
|
285
|
+
|
|
286
|
+
def reset(self):
|
|
287
|
+
self._collected_checkpoints = {}
|
|
288
|
+
return self.env.reset()
|
|
289
|
+
|
|
290
|
+
def get_state(self, to_pickle):
|
|
291
|
+
to_pickle['CheckpointRewardWrapper'] = self._collected_checkpoints
|
|
292
|
+
return self.env.get_state(to_pickle)
|
|
293
|
+
|
|
294
|
+
def set_state(self, state):
|
|
295
|
+
from_pickle = self.env.set_state(state)
|
|
296
|
+
self._collected_checkpoints = from_pickle['CheckpointRewardWrapper']
|
|
297
|
+
return from_pickle
|
|
298
|
+
|
|
299
|
+
def reward(self, reward):
|
|
300
|
+
observation = self.env.unwrapped.observation()
|
|
301
|
+
if observation is None:
|
|
302
|
+
return reward
|
|
303
|
+
|
|
304
|
+
assert len(reward) == len(observation)
|
|
305
|
+
|
|
306
|
+
for rew_index in range(len(reward)):
|
|
307
|
+
o = observation[rew_index]
|
|
308
|
+
if reward[rew_index] == 1:
|
|
309
|
+
reward[rew_index] += self._checkpoint_reward * (
|
|
310
|
+
self._num_checkpoints -
|
|
311
|
+
self._collected_checkpoints.get(rew_index, 0))
|
|
312
|
+
self._collected_checkpoints[rew_index] = self._num_checkpoints
|
|
313
|
+
continue
|
|
314
|
+
|
|
315
|
+
# Check if the active player has the ball.
|
|
316
|
+
if ('ball_owned_team' not in o or
|
|
317
|
+
o['ball_owned_team'] != 0 or
|
|
318
|
+
'ball_owned_player' not in o or
|
|
319
|
+
o['ball_owned_player'] != o['active']):
|
|
320
|
+
continue
|
|
321
|
+
|
|
322
|
+
d = ((o['ball'][0] - 1) ** 2 + o['ball'][1] ** 2) ** 0.5
|
|
323
|
+
|
|
324
|
+
# Collect the checkpoints.
|
|
325
|
+
# We give reward for distance 1 to 0.2.
|
|
326
|
+
while (self._collected_checkpoints.get(rew_index, 0) <
|
|
327
|
+
self._num_checkpoints):
|
|
328
|
+
if self._num_checkpoints == 1:
|
|
329
|
+
threshold = 0.99 - 0.8
|
|
330
|
+
else:
|
|
331
|
+
threshold = (0.99 - 0.8 / (self._num_checkpoints - 1) *
|
|
332
|
+
self._collected_checkpoints.get(rew_index, 0))
|
|
333
|
+
if d > threshold:
|
|
334
|
+
break
|
|
335
|
+
reward[rew_index] += self._checkpoint_reward
|
|
336
|
+
self._collected_checkpoints[rew_index] = (
|
|
337
|
+
self._collected_checkpoints.get(rew_index, 0) + 1)
|
|
338
|
+
return reward
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
class FrameStack(gym.Wrapper):
|
|
342
|
+
"""Stack k last observations."""
|
|
343
|
+
|
|
344
|
+
def __init__(self, env, k):
|
|
345
|
+
gym.Wrapper.__init__(self, env)
|
|
346
|
+
self.obs = collections.deque([], maxlen=k)
|
|
347
|
+
low = env.observation_space.low
|
|
348
|
+
high = env.observation_space.high
|
|
349
|
+
low = np.concatenate([low] * k, axis=-1)
|
|
350
|
+
high = np.concatenate([high] * k, axis=-1)
|
|
351
|
+
self.observation_space = gym.spaces.Box(
|
|
352
|
+
low=low, high=high, dtype=env.observation_space.dtype)
|
|
353
|
+
|
|
354
|
+
def reset(self):
|
|
355
|
+
observation = self.env.reset()
|
|
356
|
+
self.obs.extend([observation] * self.obs.maxlen)
|
|
357
|
+
return self._get_observation()
|
|
358
|
+
|
|
359
|
+
def get_state(self, to_pickle):
|
|
360
|
+
to_pickle['FrameStack'] = self.obs
|
|
361
|
+
return self.env.get_state(to_pickle)
|
|
362
|
+
|
|
363
|
+
def set_state(self, state):
|
|
364
|
+
from_pickle = self.env.set_state(state)
|
|
365
|
+
self.obs = from_pickle['FrameStack']
|
|
366
|
+
return from_pickle
|
|
367
|
+
|
|
368
|
+
def step(self, action):
|
|
369
|
+
observation, reward, done, info = self.env.step(action)
|
|
370
|
+
self.obs.append(observation)
|
|
371
|
+
return self._get_observation(), reward, done, info
|
|
372
|
+
|
|
373
|
+
def _get_observation(self):
|
|
374
|
+
return np.concatenate(list(self.obs), axis=-1)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class MultiAgentToSingleAgent(gym.Wrapper):
|
|
378
|
+
"""Converts raw multi-agent observations to single-agent observation.
|
|
379
|
+
|
|
380
|
+
It returns observations of the designated player on the team, so that
|
|
381
|
+
using this wrapper in multi-agent setup is equivalent to controlling a single
|
|
382
|
+
player. This wrapper is used for scenarios with control_all_players set when
|
|
383
|
+
agent controls only one player on the team. It can also be used
|
|
384
|
+
in a standalone manner:
|
|
385
|
+
|
|
386
|
+
env = gfootball.env.create_environment(env_name='tests/multiagent_wrapper',
|
|
387
|
+
number_of_left_players_agent_controls=11)
|
|
388
|
+
observations = env.reset()
|
|
389
|
+
single_observation = MultiAgentToSingleAgent.get_observation(observations)
|
|
390
|
+
single_action = agent.run(single_observation)
|
|
391
|
+
actions = MultiAgentToSingleAgent.get_action(single_action, observations)
|
|
392
|
+
env.step(actions)
|
|
393
|
+
"""
|
|
394
|
+
|
|
395
|
+
def __init__(self, env, left_players, right_players):
|
|
396
|
+
assert left_players < 2
|
|
397
|
+
assert right_players < 2
|
|
398
|
+
players = left_players + right_players
|
|
399
|
+
gym.Wrapper.__init__(self, env)
|
|
400
|
+
self._observation = None
|
|
401
|
+
if players > 1:
|
|
402
|
+
self.action_space = gym.spaces.MultiDiscrete([env._num_actions] * players)
|
|
403
|
+
else:
|
|
404
|
+
self.action_space = gym.spaces.Discrete(env._num_actions)
|
|
405
|
+
|
|
406
|
+
def reset(self):
|
|
407
|
+
self._observation = self.env.reset()
|
|
408
|
+
return self._get_observation()
|
|
409
|
+
|
|
410
|
+
def step(self, action):
|
|
411
|
+
assert self._observation, 'Reset must be called before step'
|
|
412
|
+
action = MultiAgentToSingleAgent.get_action(action, self._observation)
|
|
413
|
+
self._observation, reward, done, info = self.env.step(action)
|
|
414
|
+
return self._get_observation(), reward, done, info
|
|
415
|
+
|
|
416
|
+
def _get_observation(self):
|
|
417
|
+
return MultiAgentToSingleAgent.get_observation(self._observation)
|
|
418
|
+
|
|
419
|
+
@staticmethod
|
|
420
|
+
def get_observation(observation):
|
|
421
|
+
assert 'designated' in observation[
|
|
422
|
+
0], 'Only raw observations can be converted'
|
|
423
|
+
result = []
|
|
424
|
+
for obs in observation:
|
|
425
|
+
if obs['designated'] == obs['active']:
|
|
426
|
+
result.append(obs)
|
|
427
|
+
return result
|
|
428
|
+
|
|
429
|
+
@staticmethod
|
|
430
|
+
def get_action(actions, orginal_observation):
|
|
431
|
+
assert 'designated' in orginal_observation[
|
|
432
|
+
0], 'Only raw observations can be converted'
|
|
433
|
+
result = [football_action_set.action_builtin_ai] * len(orginal_observation)
|
|
434
|
+
action_idx = 0
|
|
435
|
+
for idx, obs in enumerate(orginal_observation):
|
|
436
|
+
if obs['designated'] == obs['active']:
|
|
437
|
+
assert action_idx < len(actions)
|
|
438
|
+
result[idx] = actions[action_idx]
|
|
439
|
+
action_idx += 1
|
|
440
|
+
return result
|