Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""Player with actions coming from gamepad."""
from absl import logging
import pygame
from gfootball.env import controller_base
from gfootball.env import football_action_set
from gfootball.env import event_queue
BUTTON_TO_ACTIONS = {
0: [football_action_set.action_short_pass,
football_action_set.action_pressure],
1: [football_action_set.action_shot,
football_action_set.action_team_pressure],
2: [football_action_set.action_high_pass,
football_action_set.action_sliding],
3: [football_action_set.action_long_pass,
football_action_set.action_keeper_rush],
4: [football_action_set.action_switch],
5: [football_action_set.action_dribble],
}
class Player(controller_base.Controller):
"""Player with actions coming from gamepad."""
def __init__(self, player_config, env_config):
controller_base.Controller.__init__(self, player_config, env_config)
self._can_play_right = True
pygame.init()
self._index = player_config['player_gamepad']
event_queue.add_controller('gamepad', self._index)
#
# 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.
"""Player with actions coming from specific game replay."""
from gfootball.env import player_base
from gfootball.env import script_helpers
class Player(player_base.PlayerBase):
"""Player with actions coming from specific game replay."""
def __init__(self, player_config, env_config):
player_base.PlayerBase.__init__(self, player_config)
self._can_play_right = True
self._replay = script_helpers.ScriptHelpers().load_dump(player_config['path'])
self._step = 0
self._player = player_config['index']
def take_action(self, observations):
if self._step == len(self._replay):
print("Replay finished.")
exit(0)
actions = self._replay[self._step]['debug']['action'][
self._player:self.num_controlled_players() + self._player]
self._step += 1
def _process_reward_wrappers(env, rewards):
assert 'scoring' in rewards.split(',')
if 'checkpoints' in rewards.split(','):
env = wrappers.CheckpointRewardWrapper(env)
return env
def _construct_players(self, definitions, config):
result = []
left_position = 0
right_position = 0
for definition in definitions:
(name, d) = cfg.parse_player_definition(definition)
config_name = 'player_{}'.format(name)
if config_name in config:
config[config_name] += 1
else:
config[config_name] = 0
try:
player_factory = importlib.import_module(
'gfootball.env.players.{}'.format(name))
except ImportError as e:
logging.error('Failed loading player "%s"', name)
logging.error(e)
exit(1)
player_config = copy.deepcopy(config)
player_config.update(d)
player = player_factory.Player(player_config, self._config)
if name == 'agent':
def main(_):
players = FLAGS.players.split(';') if FLAGS.players else ''
assert not (any(['agent' in player for player in players])
), ('Player type \'agent\' can not be used with play_game.')
cfg = config.Config({
'action_set': FLAGS.action_set,
'dump_full_episodes': True,
'players': players,
'real_time': FLAGS.real_time,
})
if FLAGS.level:
cfg['level'] = FLAGS.level
env = football_env.FootballEnv(cfg)
if FLAGS.render:
env.render()
env.reset()
try:
while True:
_, _, done, _ = env.step([])
if done:
env.reset()
def _get_action(self):
"""Returns action to perform for the current observations."""
active = self._observation['left_team'][self._observation['active']]
# Corner etc. - just pass the ball
if self._observation['game_mode'] != 0:
return football_action_set.action_long_pass
if self._observation['ball_owned_team'] == 1:
if self._last_action == football_action_set.action_pressure:
return football_action_set.action_sprint
self._pressure_enabled = True
return football_action_set.action_pressure
if self._pressure_enabled:
self._pressure_enabled = False
return football_action_set.action_release_pressure
target_x = 0.85
if (self._shoot_distance >
np.linalg.norm(self._observation['ball'][:2] - [target_x, 0])):
return football_action_set.action_shot
def _get_action(self):
"""Returns action to perform for the current observations."""
active = self._observation['left_team'][self._observation['active']]
# Corner etc. - just pass the ball
if self._observation['game_mode'] != 0:
return football_action_set.action_long_pass
if self._observation['ball_owned_team'] == 1:
if self._last_action == football_action_set.action_pressure:
return football_action_set.action_sprint
self._pressure_enabled = True
return football_action_set.action_pressure
if self._pressure_enabled:
self._pressure_enabled = False
return football_action_set.action_release_pressure
target_x = 0.85
if (self._shoot_distance >
np.linalg.norm(self._observation['ball'][:2] - [target_x, 0])):
return football_action_set.action_shot
move_target = [target_x, 0]
# Compute run direction.
move_action = self._direction_action(move_target - active)
closest_front_opponent = self._closest_front_opponent(active, move_target)
if closest_front_opponent is not None:
dist_front_opp = self._object_distance(active, closest_front_opponent)
else:
dist_front_opp = 2.0
def reset(self):
"""Reset environment for a new episode using a given config."""
self._episode_start = timeit.default_timer()
self._action_set = football_action_set.get_action_set(self._config)
self._trace = observation_processor.ObservationProcessor(self._config)
self._cumulative_reward = 0
self._step_count = 0
self._env.reset(self._trace)
self._env_state = 'game_started'
def flip_single_action(action, config):
"""Actions corresponding to the field rotated by 180 degrees."""
action = football_action_set.named_action_from_action_set(
football_action_set.get_action_set(config), action)
if action == football_action_set.action_left:
return football_action_set.action_right
if action == football_action_set.action_top_left:
return football_action_set.action_bottom_right
if action == football_action_set.action_top:
return football_action_set.action_bottom
if action == football_action_set.action_top_right:
return football_action_set.action_bottom_left
if action == football_action_set.action_right:
return football_action_set.action_left
if action == football_action_set.action_bottom_right:
return football_action_set.action_top_left
if action == football_action_set.action_bottom:
return football_action_set.action_top
if action == football_action_set.action_bottom_left:
return football_action_set.action_top_right
return action
self._last_action = football_action_set.action_idle
self._check_action(football_action_set.action_long_pass,
active_actions)
self._check_action(football_action_set.action_high_pass,
active_actions)
self._check_action(football_action_set.action_short_pass,
active_actions)
self._check_action(football_action_set.action_shot, active_actions)
self._check_action(football_action_set.action_keeper_rush,
active_actions)
self._check_action(football_action_set.action_sliding, active_actions)
self._check_action(football_action_set.action_pressure,
active_actions)
self._check_action(football_action_set.action_team_pressure,
active_actions)
self._check_action(football_action_set.action_sprint, active_actions)
self._check_action(football_action_set.action_dribble, active_actions)
return self._last_action