Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def recording_test(buttons, variables, actions, recording_file="test_recording.lmp", sleep_time=0, mode=vzd.Mode.PLAYER,
verbose=0, verbose_sleep_time=0.1, title="Unnamed test"):
print("Test: {}".format(title))
game = setup_test(buttons, variables, visible=verbose)
# Append all zeros action
actions.append([0.0] * game.get_available_buttons_size())
history_of_actions = []
history_of_variables = []
history_of_rewards = []
game.init()
game.new_episode(recording_file)
for i, action in enumerate(actions):
print(" Playing:", i, "/", len(actions), end = '\r')
game.set_window_visible(visible)
if visible:
game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
# Test if everything is alright with variables
game.set_available_game_variables(variables)
assert len(variables) == game.get_available_game_variables_size()
assert variables == game.get_available_game_variables()
# Test if everything is alright with buttons
game.set_available_buttons(buttons)
assert len(buttons) == game.get_available_buttons_size()
assert buttons == game.get_available_buttons()
game.set_mode(vzd.Mode.PLAYER)
return game
game.set_episode_timeout(200)
# Makes episodes start after 10 tics (~after raising the weapon)
game.set_episode_start_time(10)
# Makes the window appear (turned on by default)
game.set_window_visible(True)
# Turns on the sound. (turned off by default)
game.set_sound_enabled(True)
# Sets the livin reward (for each move) to -1
game.set_living_reward(-1)
# Sets ViZDoom mode (PLAYER, ASYNC_PLAYER, SPECTATOR, ASYNC_SPECTATOR, PLAYER mode is default)
game.set_mode(vzd.Mode.PLAYER)
# Enables engine output to console.
#game.set_console_enabled(True)
# Initialize the game. Further configuration won't take any effect from now on.
game.init()
# Define some actions. Each list entry corresponds to declared buttons:
# MOVE_LEFT, MOVE_RIGHT, ATTACK
# game.get_available_buttons_size() can be used to check the number of available buttons.
# 5 more combinations are naturally possible but only 3 are included for transparency when watching.
actions = [[True, False, False], [False, True, False], [False, False, True]]
# Run this many episodes
episodes = 10
def run_test(self, args):
policy = self
print("testing...")
policy.eval()
if "oblige" in args.vizdoom_config:
game_levels = args.instance_class.get_game_levels(args.vizdoom_config)
print('Game levels: ', len(game_levels))
completed_games = 0
failed_games = []
for i, [wad_file, map_id] in enumerate(game_levels):
print('Game: ', os.path.basename(wad_file), map_id)
game = args.instance_class(
args.vizdoom_config, args.wad_path, args.skiprate, visible=True, mode=vizdoom.Mode.PLAYER, actions=args.action_set, id=i, wad_file=wad_file, map_id=map_id, max_steps=1000, eval_mode=False)
step_state = game.get_state_normalized()
state = args.instance_class.NormalizedState(screen=None, depth=None, labels=None, variables=None)
state.screen = torch.Tensor(1, *args.screen_size)
state.variables = torch.Tensor(1, args.variable_num)
action = torch.zeros(1, 1, dtype=torch.long, device=device)
while True:
# convert state to torch tensors
state.screen[0, :] = torch.from_numpy(step_state.screen)[None, :]
state.variables[0, :] = torch.from_numpy(step_state.variables)
# compute an action
action = policy.get_action(state, action, action_dist=True)
step_state, _, finished = game.step_normalized(action[0][0])
policy.set_non_terminal(torch.zeros(1, 1) if finished else torch.ones(1, 1))
if finished:
from vizdoom import DoomGame, Mode, ScreenFormat, ScreenResolution
self.config_file = level
self.include_variables = include_variables
self.factored_action = factored_action
self.visualize = visualize
self.frame_skip = frame_skip
self.environment = DoomGame()
self.environment.load_config(self.config_file)
if self.visualize:
self.environment.set_window_visible(True)
self.environment.set_mode(Mode.ASYNC_PLAYER)
else:
self.environment.set_window_visible(False)
self.environment.set_mode(Mode.PLAYER)
# e.g. CRCGCB, RGB24, GRAY8
self.environment.set_screen_format(ScreenFormat.RGB24)
# e.g. RES_320X240, RES_640X480, RES_1920X1080
self.environment.set_screen_resolution(ScreenResolution.RES_640X480)
self.environment.set_depth_buffer_enabled(False)
self.environment.set_labels_buffer_enabled(False)
self.environment.set_automap_buffer_enabled(False)
if seed is not None:
self.environment.setSeed(seed)
self.environment.init()
self.state_shape = (480, 640, 3)
self.num_variables = self.environment.get_available_game_variables_size()
self.num_buttons = self.environment.get_available_buttons_size()
self.available_actions = [
tuple(a) for a in itertools.product([0, 1], repeat=self.num_buttons)
doom.set_doom_game_path(vzd.__path__[0] + "/freedoom2.wad")
doom.load_config(os.path.join(scenarios_path, str(config_file)))
if hide_hood:
doom.set_render_hud(not hide_hood)
doom.set_window_visible(display)
if display and smooth_display:
doom.add_game_args("+viz_render_all 1")
# TODO support for colors
doom.set_screen_format(vzd.ScreenFormat.GRAY8)
if vizdoom_async_mode:
doom.set_mode(vzd.Mode.ASYNC_PLAYER)
doom.set_ticrate(int(fps))
else:
doom.set_mode(vzd.Mode.PLAYER)
if seed is not None:
doom.set_seed(seed)
# TODO if eval fails, show some warning
doom.set_screen_resolution(eval("vzd.ScreenResolution." + vizdoom_resolution))
if not noinit:
doom.init()
self.doom = doom
self._stack_n_frames = stack_n_frames
assert len(resolution) == 2
self._resolution = tuple(resolution)
self.frameskip = frameskip
self._reward_scale = reward_scale
def initialize_vizdoom(config_file_path):
print("Initializing doom...")
game = vzd.DoomGame()
game.load_config(config_file_path)
game.set_window_visible(False)
game.set_mode(vzd.Mode.PLAYER)
game.set_screen_format(vzd.ScreenFormat.GRAY8)
game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
game.init()
print("Doom initialized.")
return game
self.game.set_doom_skill(DOOM_SETTINGS[self.level][DIFFICULTY])
self.allowed_actions = DOOM_SETTINGS[self.level][ACTIONS]
self.game.set_screen_resolution(self.screen_resolution)
self.previous_level = self.level
self._closed = False
# Algo mode
if 'human' != self._mode:
if NO_MONSTERS:
print('\t=> Special Config: Monsters Removed.')
self.game.add_game_args('-nomonsters 1')
self.game
self.game.set_window_visible(False)
self.game.set_mode(Mode.PLAYER)
self.no_render = False
try:
with self.lock:
self.game.init()
except (ViZDoomUnexpectedExitException, ViZDoomErrorException):
raise error.Error(
'VizDoom exited unexpectedly. This is likely caused by a missing multiprocessing lock. ' +
'To run VizDoom across multiple processes, you need to pass a lock when you configure the env ' +
'[e.g. env.configure(lock=my_multiprocessing_lock)], or create and close an env ' +
'before starting your processes [e.g. env = gym.make("DoomBasic-v0"); env.close()] to cache a ' +
'singleton lock in memory.')
self._start_episode()
self.is_initialized = True
return self.game.get_state().image_buffer.copy()
# Human mode