Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if sound:
doom.set_sound_enabled(True)
if force_freedoom:
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)
def play(config_file, ticrate=35):
game = vzd.DoomGame()
game.load_config(config_file)
game.set_mode(vzd.Mode.ASYNC_PLAYER)
game.set_ticrate(ticrate)
game.init()
actions = [[True, False, False],
[False, True, False],
[False, False, True]]
episodes = 10
for i in range(episodes):
game.new_episode()
while not game.is_episode_finished():
game.make_action(choice(actions))
print("Results: mean: %.1f±%.1f," % (
test_scores.mean(), test_scores.std()), "min: %.1f" % test_scores.min(),
"max: %.1f" % test_scores.max())
print("Saving the network weigths to:", DEFAULT_MODEL_SAVEFILE)
saver.save(session, DEFAULT_MODEL_SAVEFILE)
print("Total elapsed time: %.2f minutes" % ((time() - time_start) / 60.0))
game.close()
print("======================================")
print("Training finished. It's time to watch!")
# Reinitialize the game with window visible
game.set_window_visible(True)
game.set_mode(vzd.Mode.ASYNC_PLAYER)
game.init()
for _ in range(episodes_to_watch):
game.new_episode()
while not game.is_episode_finished():
state = preprocess(game.get_state().screen_buffer)
best_action_index = get_best_action(state)
# Instead of make_action(a, frame_repeat) in order to make the animation smooth
game.set_action(actions[best_action_index])
for _ in range(frame_repeat):
game.advance_action()
# Sleep between episodes
sleep(1.0)
score = game.get_total_reward()
def run_test(self, args):
print("testing...")
model = self
sim = Simulator(model)
model.eval()
game = args.instance_class(
args.vizdoom_config, args.wad_path, args.skiprate, visible=True, mode=vizdoom.Mode.ASYNC_PLAYER,
actions=args.action_set)
step_state = game.get_state_normalized()
while True:
state = sim.get_state(step_state)
# compute an action
action = sim.get_action(state)
# render
step_state, _, finished = game.step_normalized(action[0][0])
if finished:
print("episode return: {}".format(game.get_episode_return()))
def run_test(self, args):
print("testing...")
self.eval()
game = args.instance_class(
args.vizdoom_config, args.wad_path, args.skiprate, visible=True, mode=vizdoom.Mode.ASYNC_PLAYER, actions=args.action_set)
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)
while True:
#im = np.flip(step_state.screen[[0, 1, 7]], axis=1).transpose(1, 2, 0)
#plt.imsave('map_view.png', im, cmap=cm.gray)
# convert state to torch tensors
state.screen[0, :] = torch.from_numpy(step_state.screen)
state.variables[0, :] = torch.from_numpy(step_state.variables)
# compute an action
action = self.get_action(state)
def run_test(self, args):
print("testing...")
controller = Model.create(AdvantageActorCriticController, args, args.load)
controller.eval()
assert args.state_model is not None
state_model = Model.create(StateModel, args, args.state_model)
state_model.eval()
game = args.instance_class(
args.vizdoom_config, args.wad_path, args.skiprate, visible=True, mode=vizdoom.Mode.ASYNC_PLAYER, actions=args.action_set)
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_onehot = torch.zeros(1, len(args.action_set), device=device)
cells = StateModel.get_cells(1)
while True:
# convert state to torch tensors
state.screen[0, :] = torch.from_numpy(step_state.screen)
state.variables[0, :] = torch.from_numpy(step_state.variables)
# compute an action
with torch.set_grad_enabled(False):
observation = state_model.features(state.screen.to(device), state.variables.to(device))
action = controller.forward(observation, cells[-2])
):
super().__init__()
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()
game.add_available_button(vzd.Button.TURN_RIGHT)
game.add_available_button(vzd.Button.MOVE_RIGHT)
game.add_available_button(vzd.Button.MOVE_LEFT)
game.add_available_button(vzd.Button.MOVE_FORWARD)
game.add_available_button(vzd.Button.MOVE_BACKWARD)
game.add_available_button(vzd.Button.TURN_LEFT_RIGHT_DELTA)
game.add_available_button(vzd.Button.LOOK_UP_DOWN_DELTA)
game.add_available_button(vzd.Button.SPEED)
game.add_available_button(vzd.Button.MOVE_UP)
game.add_available_button(vzd.Button.MOVE_DOWN)
if watch:
game.set_mode(vzd.Mode.ASYNC_SPECTATOR)
game.set_window_visible(True)
else:
game.set_mode(vzd.Mode.ASYNC_PLAYER)
game.set_window_visible(False)
game.set_screen_resolution(vzd.ScreenResolution.RES_1024X576)
plural = "s"
pn = "no"
if players_num > 1:
pn = players_num - 1
if players_num == 2:
plural = ""
if record_file is not None and bots_num > 0:
warn("Recording won't work properly with bots!")
print("Starting vizdoom CIG 2017 host for {} player{}.".format(pn, plural))
print("Configuration:")
if ret == 0:
completed_games += 1
else:
failed_games.append([wad_file, map_id+1])
break
time.sleep(0.035)
game.release()
print("Completed games = {}, {}%".format(completed_games, completed_games*100/len(game_levels)))
print("Failed games ({}):".format(len(failed_games)))
for wad_file, map_id in failed_games:
print("{}, map{:02d}".format(os.path.basename(wad_file), map_id))
else:
game = args.instance_class(
args.vizdoom_config, args.wad_path, args.skiprate, visible=True, mode=vizdoom.Mode.ASYNC_PLAYER,
actions=args.action_set)
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=False)
step_state, _, finished = game.step_normalized(action[0][0])
policy.set_non_terminal(torch.zeros(1, 1) if finished else torch.ones(1, 1))