예제 #1
0
    def __init__(
            self,
            render=False,
            config_path='/home/gberseth/playground/BayesianSurpriseCode/surprise/envs/vizdoom/scenarios/take_cover.cfg',
            god=False,
            respawn=True):
        # Start game
        self.game = vzd.DoomGame()

        # Set sleep time (for visualization)
        self.sleep_time = 0
        self.game.set_window_visible(render)
        self.sleep_time = .02 * int(render)

        # Game Configs
        self.game.load_config(config_path)
        self.game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
        self.game.set_render_screen_flashes(True)  # Effect upon taking damage
        self.episode_length = 1000
        self.skiprate = 2
        self.game.set_episode_timeout(self.episode_length * self.skiprate)

        # Initialize the game
        self.game.init()

        # Actions are left or right
        self.actions = [[True, False], [False, True]]

        # Env Variables
        self.done = False
        self.time = 1
        self.downsample_factor = .02
        self.obs_hist = [self.get_random_state(res=(48, 64)) for _ in range(4)]
        self.god = god
        self.respawn = respawn
        self.deaths = 0
        self.fireball = 0

        # Spaces
        self.action_space = spaces.Discrete(2)
        self.observation_space = spaces.Box(0,
                                            self.episode_length,
                                            shape=(4, 48, 64))

        # RND stuff
        self.buffer = SimpleBuffer(device=device)
        self.target_net = VizdoomFeaturizer(64).to(device)
        self.target_net.eval()
        self.pred_net = VizdoomFeaturizer(64).to(device)
        self.optimizer = optim.Adam(self.pred_net.parameters(), lr=1e-4)
        self.step_freq = 8
        self.loss = torch.zeros(1)

        self.reset()
예제 #2
0
def initialize_vizdoom(args):
    print("[1.] Initializing ViZDoom...")
    game = vizdoom.DoomGame()
    game.load_config(args.config_file)
    game.set_window_visible(args.enable_training_view)
    game.set_mode(vizdoom.Mode.PLAYER)
    game.set_screen_format(vizdoom.ScreenFormat.GRAY8)
    game.set_screen_resolution(vizdoom.ScreenResolution.RES_640X480)
    game.init()
    print("[.1] ... ViZDoom initialized.")
    return game
예제 #3
0
    def __init__(
            self,
            render=False,
            config_path='./surprise/envs/vizdoom/scenarios/take_cover.cfg',
            god=True,
            num_actions=2,
            **kwargs):
        #def __init__(self, render=False, config_path='/home/dangengdg/minimalEntropy/tree_search/vizdoom/scenarios/take_cover.cfg', vae=False, god=True, respawn=True):
        # Start game
        self.game = vzd.DoomGame()

        # Set sleep time (for visualization)
        self.sleep_time = 0
        self.__render = render
        if (self.__render == True):
            self.game.set_window_visible(self.__render)
            self.sleep_time = .02 * int(self.__render)
        else:
            self.game.set_window_visible(False)

        # Game Configs
        self.game.load_config(config_path)
        self.game.set_screen_resolution(vzd.ScreenResolution.RES_160X120)
        #         self.game.set_screen_format(vzd.ScreenFormat.BGR24)
        #         self.game.set_screen_format(vzd.ScreenFormat.DOOM_256_COLORS8)
        self.game.set_render_screen_flashes(True)  # Effect upon taking damage
        self.episode_length = 1000
        self.skiprate = 2
        self.game.set_episode_timeout(self.episode_length * self.skiprate)

        # Initialize the game
        self.game.init()

        # Actions are left or right
        #         self.actions = [[True, False], [False, True]]
        self.actions = [
            list(x) for x in np.eye(
                self.game.get_available_buttons_size()).astype(bool)
        ]

        # Env Variables
        self.done = False
        self.time = 1
        self.downsample_factor = .02
        self.god = god
        self.fireball = 0
        self.in_fireball = 0
        self.health = 100

        # Buffer
        self.action_space = spaces.Discrete(len(self.actions))
        self.observation_space = spaces.Box(-1, 1, shape=(120, 160, 3))

        self.reset()
예제 #4
0
 def initialize_vizdoom(self, 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
예제 #5
0
    def __init__(self, cfg_config_path, window_visible=False):
        super(AtariDoom, self).__init__()
        game = vzd.DoomGame()
        game.load_config(cfg_config_path)
        game.set_window_visible(window_visible)
        game.init()
        self.game = game
        self.timestep = 0
        self.timeout = game.get_episode_timeout()
        # print(self.timeout)

        self.cfg_config_path = cfg_config_path
예제 #6
0
    def __init__(self, args):
        self.modalities = args['modalities']
        self.outputs = args['outputs']
        self.config = args['config']
        self.resolution = (args['width'], args['height'])
        self.frame_skip = args['frame_skip']
        self.color_mode = args['color_mode']
        #self.use_shaping_reward = args['use_shaping_reward']
        self.switch_maps = args['switch_maps']
        self.maps = args['maps']
        self.game_args = args['game_args']

        self._game = vizdoom.DoomGame()
        #self._game.set_vizdoom_path(os.path.join(vizdoom_path,'bin/vizdoom'))
        #self._game.set_doom_game_path(os.path.join(vizdoom_path,'bin/freedoom2.wad'))
        self._game.load_config(self.config)
        self._game.add_game_args(self.game_args)
        self.curr_map = 0
        #if not self.multiplayer:
        self._game.set_doom_map(self.maps[self.curr_map])

        # set resolution
        try:
            self._game.set_screen_resolution(getattr(vizdoom.ScreenResolution, 'RES_%dX%d' % self.resolution))
            self.resize = False
        except:
            print("Requested resolution not supported:", sys.exc_info()[0], ". Setting to 160x120 and resizing")
            self._game.set_screen_resolution(getattr(vizdoom.ScreenResolution, 'RES_160X120'))
            self.resize = True

        # set color mode
        if self.color_mode == 'RGB':
            self._game.set_screen_format(vizdoom.ScreenFormat.CRCGCB)
            self.num_channels = 3
        elif self.color_mode == 'GRAY':
            self._game.set_screen_format(vizdoom.ScreenFormat.GRAY8)
            self.num_channels = 1
        else:
            print("Unknown color mode")
            raise

        self.available_controls, self.continuous_controls, self.discrete_controls = self.analyze_controls(self.config)
        self.num_buttons = self._game.get_available_buttons_size()
        assert(self.num_buttons == len(self.discrete_controls) + len(self.continuous_controls))
        assert(len(self.continuous_controls) == 0) # only discrete for now
        self.num_meas = self._game.get_available_game_variables_size()

        self.meas_tags = []
        for nm in range(self.num_meas):
            self.meas_tags.append('meas' + str(nm))

        self.episode_count = 0
        self.game_initialized = False
def initialize_doom(game):
    game = vzd.DoomGame()
    game.load_config("basic.cfg")

    game.set_mode(vzd.Mode.PLAYER)
    game.set_screen_format(vzd.ScreenFormat.GRAY8)
    game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
    game.init()

    game.set_window_visible(False)

    return game
def Create_environment():
    game = vzd.DoomGame()
    config_path = r"C:\Users\PC\Miniconda3\envs\tensorflow\Lib\site-packages\vizdoom\scenarios\basic.cfg"
    game.load_config(config_path)
    scenario_path = r"C:\Users\PC\Miniconda3\envs\tensorflow\Lib\site-packages\vizdoom\scenarios\basic.wad"
    game.set_doom_scenario_path(scenario_path)
    game.init()
    left = [1, 0, 0]
    right = [0, 1, 0]
    shoot = [0, 0, 1]
    possible_actions = [left, right, shoot]
    return game, possible_actions
예제 #9
0
def measure(name, iters=5000, **settings):
    print(name)
    for k, v in settings.items():
        print("\t{}: {}".format(k, v))

    # Vizdoom wrapper
    doom_wrapper = VizdoomWrapper(**settings)
    start = time()
    for _ in trange(iters, leave=False):
        current_img, current_misc = doom_wrapper.get_current_state()
        action_index = randint(0, doom_wrapper.actions_num - 1)
        doom_wrapper.make_action(action_index)

        if doom_wrapper.is_terminal():
            doom_wrapper.reset()
    end = time()
    wrapper_t = (end - start)

    # Vanilla vizdoom:
    doom = vzd.DoomGame()
    if "scenarios_path" not in settings:
        scenarios_path = vzd.__path__[0] + "/scenarios"
    else:
        scenarios_path = settings["scenarios_path"]
    config_file = scenarios_path + "/" + settings["config_file"]
    doom.load_config(config_file)
    doom.set_window_visible(False)
    doom.set_screen_format(vzd.ScreenFormat.GRAY8)
    doom.set_screen_resolution(vzd.ScreenResolution.RES_160X120)
    doom.init()
    actions = [
        list(a)
        for a in it.product([0, 1],
                            repeat=len(doom.get_available_game_variables()))
    ]
    start = time()
    frame_skip = settings["frame_skip"]
    for _ in trange(iters, leave=False):
        if doom.is_episode_finished():
            doom.new_episode()
        doom.make_action(choice(actions), frame_skip)

    end = time()
    vanilla_t = end - start
    print(green("\twrapper: {:0.2f} steps/s".format(iters / wrapper_t)))
    print(
        green("\twrapper: {:0.2f} s/1000 steps".format(wrapper_t / iters *
                                                       1000)))
    print(blue("\tvanilla: {:0.2f} steps/s".format(iters / vanilla_t)))
    print(
        blue("\tvanilla: {:0.2f} s/1000 steps\n".format(vanilla_t / iters *
                                                        1000)))
예제 #10
0
    def __init__(self, cfg):
        super(VizDoom, self).__init__()

        # Global vars
        self.skiprate = cfg.skiprate
        self.num_channels = cfg.num_channels
        self.resolution = cfg.resolution
        self.terminal = np.zeros(
            [self.resolution[0], self.resolution[1], cfg.num_channels])

        # Init game, set params
        self.game = vzd.DoomGame()
        # Scenario
        self.game.set_doom_scenario_path(cfg.vizdoom_dir +
                                         "/scenarios/basic.wad")
        self.game.set_doom_map("map01")
        # Screen
        self.game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
        self.game.set_screen_format(vzd.ScreenFormat.RGB24)
        self.game.set_window_visible(True)
        self.game.set_sound_enabled(True)
        # Buffers
        #self.game.set_depth_buffer_enabled(True)
        #self.game.set_labels_buffer_enabled(True)
        #self.game.set_automap_buffer_enabled(True)
        # Rendering
        self.game.set_render_hud(False)
        self.game.set_render_minimal_hud(False)  # If HUD enabled
        self.game.set_render_crosshair(False)
        self.game.set_render_weapon(False)
        self.game.set_render_decals(
            False)  # Bullet holes and blood on the walls
        self.game.set_render_particles(False)
        self.game.set_render_effects_sprites(False)  # Smoke and blood
        self.game.set_render_messages(False)  # In-game messages
        self.game.set_render_corpses(False)
        self.game.set_render_screen_flashes(
            True)  # Effect upon taking damage or picking up items
        # Actions
        self.game.set_available_buttons(
            [vzd.Button.MOVE_LEFT, vzd.Button.MOVE_RIGHT, vzd.Button.ATTACK])
        # Variables included in state
        self.game.set_available_game_variables([vzd.GameVariable.AMMO2])
        # Start/end time
        self.game.set_episode_start_time(14)
        self.game.set_episode_timeout(300)
        # Reward
        self.game.set_living_reward(-1)
        self.game.set_doom_skill(5)
        # Game mode
        self.game.set_mode(vzd.Mode.PLAYER)
        self.game.init()
예제 #11
0
def init_watching_environment(configuration):
    print("Initializing doom...")
    game = vzd.DoomGame()
    game.load_config(configuration)
    game.set_window_visible(True)
    game.set_mode(vzd.Mode.ASYNC_PLAYER)
    game.set_screen_format(vzd.ScreenFormat.GRAY8)
    game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
    n = game.get_available_buttons_size()
    actions = [list(a) for a in it.product([0, 1], repeat=n)]
    game.init()
    print("Doom initialized. It's time to watch!")
    return game, actions
예제 #12
0
def setup_game_test(wad):
    game = vzd.DoomGame()

    # Use your config
    game.load_config(DEFAULT_CONFIG)

    # Set Scenario to the new generated WAD
    game.set_doom_scenario_path(wad)

    # Sets up game for spectator (you)
    game.set_window_visible(True)
    game.set_mode(vzd.Mode.PLAYER)
    game.set_render_hud(False)

    # Set cv2 friendly format.
    game.set_screen_format(vzd.ScreenFormat.BGR24)

    # Enables rendering of automap.
    game.set_automap_buffer_enabled(True)
    game.set_labels_buffer_enabled(True)
    game.set_depth_buffer_enabled(True)

    # All map's geometry and objects will be displayed.
    game.set_automap_mode(vzd.AutomapMode.OBJECTS_WITH_SIZE)

    game.add_available_game_variable(vzd.GameVariable.POSITION_X)
    game.add_available_game_variable(vzd.GameVariable.POSITION_Y)
    game.add_available_game_variable(vzd.GameVariable.POSITION_Z)

    game.add_available_game_variable(vzd.GameVariable.ANGLE)
    game.add_available_game_variable(vzd.GameVariable.PITCH)
    game.add_available_game_variable(vzd.GameVariable.ROLL)

    game.add_available_game_variable(vzd.GameVariable.VELOCITY_X)
    game.add_available_game_variable(vzd.GameVariable.VELOCITY_Y)
    game.add_available_game_variable(vzd.GameVariable.VELOCITY_Z)

    # This CVAR can be used to make a map follow a player.
    game.add_game_args("+am_followplayer 1")

    # This CVAR controls scale of rendered map (higher valuer means bigger zoom).
    game.add_game_args("+viz_am_scale 3")

    game.add_game_args("+am_showthingsprites 3")
    game.add_game_args("+am_cheat 1")
    game.add_game_args("+sv_cheats 1")

    game.init()
    game.send_game_command("iddqd")

    return game
예제 #13
0
def create_env(game_state_only=False, actions_only=False, render_screen=False):
    """
        Sets up the game environment
    """
    scenarios = '/usr/local/lib/python3.7/dist-packages/vizdoom/scenarios/'
    # global GAME
    doom = vz.DoomGame()
    doom.load_config(os.path.join(scenarios, 'basic.cfg'))  # Config
    doom.set_doom_scenario_path(os.path.join(scenarios,
                                             'basic.wad'))  # Scenario

    if game_state_only:
        return doom
    return initialize_game(doom, render_screen, actions_only=actions_only)
예제 #14
0
    def configure_game_training(self):
        print("Initializing game environment...")
        game = vizdoom.DoomGame()
        game.load_config("basic.cfg")
        game.set_window_visible(False)
        game.set_screen_format(vizdoom.ScreenFormat.GRAY8)

        left = [1, 0, 0]
        right = [0, 1, 0]
        shoot = [0, 0, 1]
        possible_actions = [left, right, shoot]

        print("Finished game environment!")
        return game, possible_actions
예제 #15
0
def test_get_state():
    print("Testing get_state() ...")

    episodes = 10000
    episode_timeout = 1000
    buttons = [vzd.Button.MOVE_FORWARD, vzd.Button.MOVE_BACKWARD,
               vzd.Button.MOVE_LEFT, vzd.Button.MOVE_RIGHT,
               vzd.Button.TURN_LEFT, vzd.Button.TURN_RIGHT,
               vzd.Button.ATTACK, vzd.Button.USE]
    actions = [list(i) for i in product([0, 1], repeat=len(buttons))]

    game = vzd.DoomGame()
    game.set_window_visible(False)
    game.set_episode_timeout(episode_timeout)
    game.set_available_buttons(buttons)
    game.init()

    prev_mem = 0
    prev_len = 0
    mem_eta = 1
    for i in range(episodes):
        game.new_episode()

        states = []
        states_copies = []

        while not game.is_episode_finished():
            state = game.get_state()
            states.append(state.screen_buffer)
            states_copies.append(np.copy(state.screen_buffer))

            game.make_action(choice(actions), 4)

        # Compare states with their copies
        for s, s_copy in zip(states, states_copies):
            assert np.array_equal(s, s_copy)

        # Check memory
        process = psutil.Process(os.getpid())
        mem = process.memory_info().rss / 1024 / 1024

        if i % 100 == 0:
            print("Memory, with {} states saved, after episode {} / {}: {} MB".format(len(states), i, episodes, mem))

        if prev_len < len(states):
            prev_mem = mem
            prev_len = len(states)
        elif prev_len == len(states):
            assert abs(prev_mem - mem) < mem_eta
예제 #16
0
    def __init__(self, level=0, enable_sound=False):
        # tue.
        self.enable_sound = enable_sound
        self.is_initialized = False
        self.screen_height = 480
        self.screen_width = 640

        self.observation_space = spaces.Box(low=0, high=255, shape=(self.screen_height, self.screen_width, 3))
        self.game = vizdoom.DoomGame()
        self.accumulated_reward = 0

        self.curr_seed = 0
        self.mode = CPU # or human
        self.level = level
        self.reset() # load buttons, etc.
예제 #17
0
def setup_player():
    game = vzd.DoomGame()

    game.load_config(config)
    game.set_mode(mode)
    game.add_game_args(args)
    game.set_screen_resolution(resolution)
    game.set_console_enabled(console)
    game.set_window_visible(window)
    game.set_ticrate(ticrate)

    actions = [[1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 1, 0, 0, 0, 0, 0, 0]]

    return game, actions
예제 #18
0
    def __init__(self, args):

        self.config = args['config']
        self.resolution = args['resolution']
        self.frame_skip = args['frame_skip']
        self.color_mode = args['color_mode']
        self.game_args = args['game_args']

        self._game = vizdoom.DoomGame()
        self._game.load_config(self.config)
        self._game.add_game_args(self.game_args)

        if 'ticrate' in args:
            self._game.set_ticrate(args['ticrate'])

        # set resolution
        try:
            self._game.set_screen_resolution(
                getattr(vizdoom.ScreenResolution,
                        'RES_%dX%d' % self.resolution))
        except:
            print("Requested resolution not supported:", sys.exc_info()[0])
            raise

        # set color mode
        if self.color_mode == 'RGB':
            self._game.set_screen_format(vizdoom.ScreenFormat.CRCGCB)
            self.num_channels = 3
        elif self.color_mode == 'RGB24':
            self._game.set_screen_format(vizdoom.ScreenFormat.RGB24)
            self.num_channels = 3
        elif self.color_mode == 'GRAY':
            self._game.set_screen_format(vizdoom.ScreenFormat.GRAY8)
            self.num_channels = 1
        else:
            print("Unknown color mode")

        print("Simulator: colour format: ", self.color_mode)

        self.available_controls, self.continuous_controls, self.discrete_controls = self.analyze_controls(
            self.config)
        self.num_buttons = self._game.get_available_buttons_size()
        assert (self.num_buttons == len(self.discrete_controls) +
                len(self.continuous_controls))
        #        assert (len(self.continuous_controls) == 0)  # only discrete for now
        self.num_meas = self._game.get_available_game_variables_size()

        self.game_initialized = False
예제 #19
0
    def _init_game(self):
        self.close()

        game = vd.DoomGame()
        game = player_setup(game, self.cfg)
        if self.cfg.is_multiplayer_game:
            if self.cfg.host_cfg is not None:
                game = player_host_setup(game, self.cfg.host_cfg)
            elif self.cfg.join_cfg is not None:
                game = player_join_setup(game, self.cfg.join_cfg)
            else:
                raise ValueError('neither host nor join, error!')
        game.init()
        self.game = game
        self._game_var_list = self.game.get_available_game_variables()
        self._update_vars()
예제 #20
0
def create_env(visible=False):
    """
        Creates an instance of the game environment
    """
    path = '/usr/local/lib/python3.7/dist-packages/vizdoom/scenarios/'

    doom = vz.DoomGame()
    doom.load_config(os.path.join(path, 'deadly_corridor.cfg'))
    doom.set_doom_scenario_path(os.path.join(path, 'deadly_corridor.wad'))

    doom.set_window_visible(visible)
    doom.init()

    actions = np.identity(doom.get_available_buttons_size())

    return doom, actions
예제 #21
0
    def _init_game(self):
        self.close()

        game = vd.DoomGame()
        game = player_setup(game, self.cfg)

        if self.cfg.is_multiplayer_game:
            if self.cfg.host_cfg is not None:
                game = player_host_setup(game, self.cfg.host_cfg)
            elif self.cfg.join_cfg is not None:
                game = player_join_setup(game, self.cfg.join_cfg)
            else:
                raise ValueError('neither host nor join, error!')

        game.init()
        self.game = game
예제 #22
0
def initialize_vizdoom(config_file_path, seed):
    print("Initializing doom...")
    game = vzd.DoomGame()
    game.load_config(config_file_path)
    game.set_window_visible(True)
    game.set_labels_buffer_enabled(True)
    game.add_available_game_variable(vzd.GameVariable.HEALTH)
    # game.set_mode(vzd.Mode.PLAYER)
    game.set_mode(vzd.Mode.SPECTATOR)
    game.set_screen_format(vzd.ScreenFormat.GRAY8)
    game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
    # TO-DO: set seed
    game.set_seed(seed)
    game.init()
    print("Doom initialized.")
    return game
예제 #23
0
    def __init__(self, WAD_FILE='wad_files/test_6.wad', visible=False):

        CONFIG = "standard_config.cfg"
        #WAD_FILE

        self.game = vzd.DoomGame()

        self.game.load_config(CONFIG)
        self.game.set_doom_map("map01")
        self.game.set_doom_skill(2)

        # This line connects to the actual wad file we just generated
        self.game.set_doom_scenario_path(WAD_FILE)

        # Sets up game for spectator (you)
        # Do I want this for RL env, need to look into it
        #self.game.add_game_args("+freelook 1")
        self.game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
        self.game.set_window_visible(visible)
        #self.game.set_mode(vzd.Mode.SPECTATOR)
        self.game.set_mode(vzd.Mode.PLAYER)

        self.game.add_available_game_variable(vzd.GameVariable.POSITION_X)
        self.game.add_available_game_variable(vzd.GameVariable.POSITION_Y)

        self.game.init()

        self.game.set_doom_map("map{:02}".format(1))
        self.game.new_episode()

        self.max_ep_steps = 2000

        self.action_list = [[0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0],
                            [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0],
                            [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0],
                            [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 1, 0],
                            [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 1, 0],
                            [0, 0, 0, 0, 1, 0, 0, 1], [1, 0, 0, 0, 0, 1, 0, 0],
                            [1, 0, 0, 0, 1, 0, 0, 0], [1, 0, 0, 1, 0, 1, 0, 0],
                            [1, 0, 0, 1, 1, 0, 0, 0], [1, 0, 0, 0, 0, 1, 1, 0],
                            [1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 1, 0, 1, 0],
                            [1, 0, 0, 0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 1, 0, 0],
                            [0, 1, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1, 1, 0],
                            [0, 1, 0, 0, 0, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 0],
                            [0, 1, 0, 0, 1, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1],
                            [1, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 1],
                            [0, 1, 0, 0, 0, 0, 1, 0]]
예제 #24
0
    def __init__(self, behaviour, server=False, map_name="map01", players=2):
        self.behaviour = behaviour
        self.is_server = server

        # init game
        self.game = vizdoom.DoomGame()

        scenarios_dir = os.path.join(os.path.dirname(__file__), 'scenarios')
        self.game.load_config(os.path.join(scenarios_dir, 'duel.cfg'))

        self.game.set_window_visible(False)

        self.map_name = map_name
        self.game.set_doom_map(map_name)

        if server:
            self.game.add_game_args("-host {} "
                                    "-deathmatch "
                                    "+timelimit 15.0 "
                                    "+sv_forcerespawn 1 "
                                    "+sv_noautoaim 1 "
                                    "+sv_respawnprotect 1 "
                                    "+sv_spawnfarthest 1 "
                                    "+sv_nocrouch 1 "
                                    "+viz_respawn_delay 5 ".format(players))
        else:
            self.game.add_game_args("-join 127.0.0.1")

        self.game.set_mode(vizdoom.Mode.PLAYER)

        self.behaviour.init(self.game)

        init_passed = False
        while not init_passed:
            try:
                self.game.init()
                init_passed = True
            except vizdoom.ViZDoomUnexpectedExitException as e:
                print(
                    'Exception caught while initializing the game! Retrying...'
                )
                time.sleep(0.5)

        self.action_space = self.behaviour.action_space
        self.observation_space = self.behaviour.observation_space

        self.viewer = None
예제 #25
0
    def __init__(self, params):

        super().__init__()
        try:
            import vizdoom
            from argparse import ArgumentParser
        except:
            print(
                "Failed to import ViZDoom, make sure you have ViZDoom installed!"
            )

        # Check if config is sent in params
        if 'config' in params:
            DEFAULT_CONFIG = params['config']
        # If not, pull config from env_name
        else:
            file_path = 'AIQ/test_suite/VizDoom/vizdoom_scenarios/'
            # Input --> env_name = vizdoom_stuff_name
            DEFAULT_CONFIG = file_path + params['env_name'] + '.cfg'

        self.env = vizdoom.DoomGame()

        # Incase cfg path is incorrect
        try:
            self.env.load_config(DEFAULT_CONFIG)

        except Exception as inst:
            print(inst)
            print(DEFAULT_CONFIG)

        # This will disable popup window for vizdoom
        # Should allow it to work in docker
        self.env.set_window_visible(False)
        self.env.set_sound_enabled(False)

        # Define header
        self.header = header(env_name="ViZDoom_" + params['env_name'],
                             input_dim=[len(self.env.get_available_buttons())],
                             output_dim=[
                                 self.env.get_screen_channels(),
                                 self.env.get_screen_height(),
                                 self.env.get_screen_width(),
                             ],
                             info="ViZDoom simulator",
                             env_min_score=-200.0,
                             env_max_score=100.0,
                             rl=True)
예제 #26
0
    def __init__(self, render=False, config_path='surprise/envs/vizdoom/scenarios/take_cover.cfg', vae=False, god=True, respawn=True):
    #def __init__(self, render=False, config_path='/home/dangengdg/minimalEntropy/tree_search/vizdoom/scenarios/take_cover.cfg', vae=False, god=True, respawn=True):
        # Start game
        self.game = vzd.DoomGame()

        # Set sleep time (for visualization)
        self.sleep_time = 0
        self.game.set_window_visible(render)
        self.sleep_time = .02 * int(render)

        # Game Configs
        self.game.load_config(config_path)
        self.game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)
        self.game.set_render_screen_flashes(True)  # Effect upon taking damage
        self.episode_length = 1000
        self.skiprate = 2
        self.game.set_episode_timeout(self.episode_length * self.skiprate)

        # Initialize the game
        self.game.init()

        # Actions are left or right
        self.actions = [[True, False], [False, True]]

        # Env Variables
        self.done = False
        self.time = 1
        self.downsample_factor = .02
        self.obs_hist = [self.get_random_state(res=48*64) for _ in range(4)]
        self.god = god
        self.respawn = respawn
        self.fireball = 0
        self.in_fireball = 0

        # Buffer
        self.buffer = [self.get_random_state(10*13) for _ in range(2)]
        self.vae = None
        if vae:
            self.vae = VAE().to(0)
            chkpt = torch.load('/home/dangengdg/minimalEntropy/tree_search/vizdoom/checkpoints/vae.pth')
            self.vae.load_state_dict(chkpt['state_dict'])

        # Spaces
        self.action_space = spaces.Discrete(2)
        self.observation_space = spaces.Box(0, self.episode_length, shape=(12289,))

        self.reset()
예제 #27
0
def create_env(visible=False, scene=''):
    """
        Creates an instance of the game environment
    """
    path = '/usr/local/lib/python3.7/dist-packages/vizdoom/scenarios/'
    scene = 'defend_the_center' if not scene else scene

    doom = vz.DoomGame()
    doom.load_config(os.path.join(path, f'{scene}.cfg'))
    doom.set_doom_scenario_path(os.path.join(path, f'{scene}.wad'))

    doom.set_window_visible(visible)
    doom.init()

    actions = np.identity(doom.get_available_buttons_size(), dtype=np.bool)

    return doom, actions
예제 #28
0
def initialize_vizdoom():
    vizdoom_home = os.path.split(vizdoom.__file__)[0]

    game = vizdoom.DoomGame()

    game.load_config(FLAGS.config)
    game.set_doom_game_path(f"{vizdoom_home}/doom2.wad")
    game.set_doom_scenario_path(f"{vizdoom_home}/scenarios/basic.wad")
    game.set_window_visible(False)
    game.set_sound_enabled(FLAGS.skip_training)
    game.set_mode(vizdoom.Mode.PLAYER)
    game.set_screen_format(vizdoom.ScreenFormat.GRAY8)
    game.set_screen_resolution(vizdoom.ScreenResolution.RES_640X480)

    game.init()

    return game
예제 #29
0
def _test_enums(enum_name, func_name):
    print("Testing vzd.{} enum ...".format(enum_name))

    game = vzd.DoomGame()
    game.set_window_visible(False)

    add_func = eval("game.add_" + func_name)
    get_func = eval("game.get_" + func_name + "s")
    set_func = eval("game.set_" + func_name + "s")
    clear_func = eval("game.clear_" + func_name + "s")

    all_values = [
        eval("vzd." + enum_name + "." + v)
        for v in dir(eval("vzd." + enum_name))
        if not v.startswith('__') and not v == 'name' and not v == 'value'
    ]
    all_values_names = [v.name for v in all_values]

    # set test
    set_func(all_values)
    get_buttons_names = [v.name for v in get_func()]
    assert all_values_names == get_buttons_names

    # add test
    clear_func()
    for i, v in enumerate(all_values):
        add_func(v)
        get_values_names = [v.name for v in get_func()]
        assert all_values_names[:i + 1] == get_values_names

    # again set test
    set_func(all_values)
    get_values_names = [v.name for v in get_func()]
    assert all_values_names == get_values_names

    # multiple adds
    for i, v in enumerate(all_values):
        add_func(v)
        get_values_names = [v.name for v in get_func()]
        assert all_values_names == get_values_names

    # multiple in set
    set_func(all_values + all_values)
    get_values_names = [v.name for v in get_func()]
    assert all_values_names == get_values_names
예제 #30
0
파일: train.py 프로젝트: trizin/A2C-Doom
def create_environment():
    game = vzd.DoomGame()

    # Load the game
    game.set_doom_scenario_path("basic.wad")
    game.load_config("./basic.cfg")

    # Possible actions
    left = [1, 0, 0]
    right = [0, 1, 0]
    shoot = [0, 0, 1]
    possible_actions = [left, right, shoot]
    game.set_window_visible(True)  # Render game
    game.set_screen_format(vzd.ScreenFormat.GRAY8)
    game.set_screen_resolution(vzd.ScreenResolution.RES_160X120)
    game.init()

    return game, possible_actions