From b50fcd26ffeebb07d9527c8b951976907ef2acfe Mon Sep 17 00:00:00 2001 From: mihahauke Date: Thu, 5 Jul 2018 01:12:37 +0200 Subject: [PATCH] Added argparse and changed import in most of python examples. --- examples/python/automap.py | 126 +++++++-------- examples/python/basic.py | 211 +++++++++++++------------ examples/python/buffers.py | 159 ++++++++++--------- examples/python/delta_buttons.py | 91 ++++++----- examples/python/fps.py | 89 +++++++---- examples/python/labels.py | 171 +++++++++++--------- examples/python/learning_tensorflow.py | 40 +++-- examples/python/pyoblige.py | 54 +++++-- examples/python/scenarios.py | 122 +++++++------- examples/python/seed.py | 152 +++++++++--------- examples/python/shaping.py | 99 +++++++----- examples/python/spectator.py | 85 +++++----- examples/python/ticrate.py | 67 ++++---- 13 files changed, 798 insertions(+), 668 deletions(-) diff --git a/examples/python/automap.py b/examples/python/automap.py index d0195759d..b9b716ae9 100755 --- a/examples/python/automap.py +++ b/examples/python/automap.py @@ -1,93 +1,95 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from __future__ import print_function from random import choice -from vizdoom import * - +import vizdoom as vzd +from argparse import ArgumentParser import cv2 -game = DoomGame() +DEFAULT_CONFIG = "../../scenarios/defend_the_center.cfg" + +if __name__ == "__main__": + parser = ArgumentParser("ViZDoom example showing how to use the 'automap' (top-down view map).") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + + args = parser.parse_args() + game = vzd.DoomGame() -# Use other config file if you wish. -# game.load_config("../../scenarios/basic.cfg") -# game.load_config("../../scenarios/simpler_basic.cfg") -# game.load_config("../../scenarios/rocket_basic.cfg") -# game.load_config("../../scenarios/deadly_corridor.cfg") -# game.load_config("../../scenarios/deathmatch.cfg") -game.load_config("../../scenarios/defend_the_center.cfg") -# game.load_config("../../scenarios/defend_the_line.cfg") -# game.load_config("../../scenarios/health_gathering.cfg") -# game.load_config("../../scenarios/my_way_home.cfg") -# game.load_config("../../scenarios/predict_position.cfg") -# game.load_config("../../scenarios/take_cover.cfg") -game.set_render_hud(False) + game.load_config(args.config) + game.set_render_hud(False) -game.set_screen_resolution(ScreenResolution.RES_640X480) + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) -# Set cv2 friendly format. -game.set_screen_format(ScreenFormat.BGR24) + # Set cv2 friendly format. + game.set_screen_format(vzd.ScreenFormat.BGR24) -# Enables rendering of automap. -game.set_automap_buffer_enabled(True) + # Enables rendering of automap. + game.set_automap_buffer_enabled(True) -# All map's geometry and objects will be displayed. -game.set_automap_mode(AutomapMode.OBJECTS_WITH_SIZE) + # All map's geometry and objects will be displayed. + game.set_automap_mode(vzd.AutomapMode.OBJECTS_WITH_SIZE) -game.add_available_game_variable(GameVariable.POSITION_X) -game.add_available_game_variable(GameVariable.POSITION_Y) -game.add_available_game_variable(GameVariable.POSITION_Z) + 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) -# Disables game window (FPP view), we just want to see the automap. -game.set_window_visible(False) + # Disables game window (FPP view), we just want to see the automap. + game.set_window_visible(False) -# This CVAR can be used to make a map follow a player. -game.add_game_args("+am_followplayer 1") + # 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 10") + # This CVAR controls scale of rendered map (higher valuer means bigger zoom). + game.add_game_args("+viz_am_scale 10") -# This CVAR shows the whole map centered (overrides am_followplayer and viz_am_scale). -game.add_game_args("+viz_am_center 1") + # This CVAR shows the whole map centered (overrides am_followplayer and viz_am_scale). + game.add_game_args("+viz_am_center 1") -# Map's colors can be changed using CVARs, full list is available here: https://zdoom.org/wiki/CVARs:Automap#am_backcolor -game.add_game_args("+am_backcolor 000000") -game.init() + # Map's colors can be changed using CVARs, full list is available here: https://zdoom.org/wiki/CVARs:Automap#am_backcolor + game.add_game_args("+am_backcolor 000000") + game.init() -actions = [[True, False, False], [False, True, False], [False, False, True]] + actions = [[True, False, False], [False, True, False], [False, False, True]] -episodes = 10 + episodes = 10 -# Sleep time between actions in ms -sleep_time = 28 + # Sleep time between actions in ms + sleep_time = 28 -for i in range(episodes): - print("Episode #" + str(i + 1)) - seen_in_this_episode = set() + for i in range(episodes): + print("Episode #" + str(i + 1)) + seen_in_this_episode = set() - # Not needed for the first episode but the loop is nicer. - game.new_episode() + # Not needed for the first episode but the loop is nicer. + game.new_episode() - while not game.is_episode_finished(): - # Gets the state - state = game.get_state() + while not game.is_episode_finished(): + # Gets the state + state = game.get_state() - # Shows automap buffer - map = state.automap_buffer - if map is not None: - cv2.imshow('ViZDoom Automap Buffer', map) + # Shows automap buffer + map = state.automap_buffer + if map is not None: + cv2.imshow('ViZDoom Automap Buffer', map) - cv2.waitKey(sleep_time) + cv2.waitKey(sleep_time) - game.make_action(choice(actions)) + game.make_action(choice(actions)) - print("State #" + str(state.number)) - print("Player position X:", state.game_variables[0], "Y:", state.game_variables[1], "Z:", state.game_variables[2]) + print("State #" + str(state.number)) + print("Player position X:", state.game_variables[0], "Y:", state.game_variables[1], "Z:", + state.game_variables[2]) - print("=====================") + print("=====================") - print("Episode finished!") + print("Episode finished!") - print("************************") + print("************************") -cv2.destroyAllWindows() \ No newline at end of file + cv2.destroyAllWindows() diff --git a/examples/python/basic.py b/examples/python/basic.py index 924cae080..299c04dea 100755 --- a/examples/python/basic.py +++ b/examples/python/basic.py @@ -12,146 +12,147 @@ ##################################################################### from __future__ import print_function -from vizdoom import * +import vizdoom as vzd from random import choice from time import sleep -# Create DoomGame instance. It will run the game and communicate with you. -game = DoomGame() +if __name__ == "__main__": + # Create DoomGame instance. It will run the game and communicate with you. + game = vzd.DoomGame() -# Now it's time for configuration! -# load_config could be used to load configuration instead of doing it here with code. -# If load_config is used in-code configuration will also work - most recent changes will add to previous ones. -# game.load_config("../../scenarios/basic.cfg") + # Now it's time for configuration! + # load_config could be used to load configuration instead of doing it here with code. + # If load_config is used in-code configuration will also work - most recent changes will add to previous ones. + # game.load_config("../../scenarios/basic.cfg") -# Sets path to additional resources wad file which is basically your scenario wad. -# If not specified default maps will be used and it's pretty much useless... unless you want to play good old Doom. -game.set_doom_scenario_path("../../scenarios/basic.wad") + # Sets path to additional resources wad file which is basically your scenario wad. + # If not specified default maps will be used and it's pretty much useless... unless you want to play good old Doom. + game.set_doom_scenario_path("../../scenarios/basic.wad") -# Sets map to start (scenario .wad files can contain many maps). -game.set_doom_map("map01") + # Sets map to start (scenario .wad files can contain many maps). + game.set_doom_map("map01") -# Sets resolution. Default is 320X240 -game.set_screen_resolution(ScreenResolution.RES_640X480) + # Sets resolution. Default is 320X240 + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) -# Sets the screen buffer format. Not used here but now you can change it. Defalut is CRCGCB. -game.set_screen_format(ScreenFormat.RGB24) + # Sets the screen buffer format. Not used here but now you can change it. Defalut is CRCGCB. + game.set_screen_format(vzd.ScreenFormat.RGB24) -# Enables depth buffer. -game.set_depth_buffer_enabled(True) + # Enables depth buffer. + game.set_depth_buffer_enabled(True) -# Enables labeling of in game objects labeling. -game.set_labels_buffer_enabled(True) + # Enables labeling of in game objects labeling. + game.set_labels_buffer_enabled(True) -# Enables buffer with top down map of the current episode/level. -game.set_automap_buffer_enabled(True) + # Enables buffer with top down map of the current episode/level. + game.set_automap_buffer_enabled(True) -# Sets other rendering options (all of these options except crosshair are enabled (set to True) by default) -game.set_render_hud(False) -game.set_render_minimal_hud(False) # If hud is enabled -game.set_render_crosshair(False) -game.set_render_weapon(True) -game.set_render_decals(False) # Bullet holes and blood on the walls -game.set_render_particles(False) -game.set_render_effects_sprites(False) # Smoke and blood -game.set_render_messages(False) # In-game messages -game.set_render_corpses(False) -game.set_render_screen_flashes(True) # Effect upon taking damage or picking up items + # Sets other rendering options (all of these options except crosshair are enabled (set to True) by default) + game.set_render_hud(False) + game.set_render_minimal_hud(False) # If hud is enabled + game.set_render_crosshair(False) + game.set_render_weapon(True) + game.set_render_decals(False) # Bullet holes and blood on the walls + game.set_render_particles(False) + game.set_render_effects_sprites(False) # Smoke and blood + game.set_render_messages(False) # In-game messages + game.set_render_corpses(False) + game.set_render_screen_flashes(True) # Effect upon taking damage or picking up items -# Adds buttons that will be allowed. -game.add_available_button(Button.MOVE_LEFT) -game.add_available_button(Button.MOVE_RIGHT) -game.add_available_button(Button.ATTACK) + # Adds buttons that will be allowed. + game.add_available_button(vzd.Button.MOVE_LEFT) + game.add_available_button(vzd.Button.MOVE_RIGHT) + game.add_available_button(vzd.Button.ATTACK) -# Adds game variables that will be included in state. -game.add_available_game_variable(GameVariable.AMMO2) + # Adds game variables that will be included in state. + game.add_available_game_variable(vzd.GameVariable.AMMO2) -# Causes episodes to finish after 200 tics (actions) -game.set_episode_timeout(200) + # Causes episodes to finish after 200 tics (actions) + game.set_episode_timeout(200) -# Makes episodes start after 10 tics (~after raising the weapon) -game.set_episode_start_time(10) + # 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) + # 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) + # 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 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(Mode.PLAYER) + # 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) + # 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() + # 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]] + # 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 + # Run this many episodes + episodes = 10 -# Sets time that will pause the engine after each action (in seconds) -# Without this everything would go too fast for you to keep track of what's happening. -sleep_time = 1.0 / DEFAULT_TICRATE # = 0.028 + # Sets time that will pause the engine after each action (in seconds) + # Without this everything would go too fast for you to keep track of what's happening. + sleep_time = 1.0 / vzd.DEFAULT_TICRATE # = 0.028 -for i in range(episodes): - print("Episode #" + str(i + 1)) + for i in range(episodes): + print("Episode #" + str(i + 1)) - # Starts a new episode. It is not needed right after init() but it doesn't cost much. At least the loop is nicer. - game.new_episode() + # Starts a new episode. It is not needed right after init() but it doesn't cost much. At least the loop is nicer. + game.new_episode() - while not game.is_episode_finished(): + while not game.is_episode_finished(): - # Gets the state - state = game.get_state() + # Gets the state + state = game.get_state() - # Which consists of: - n = state.number - vars = state.game_variables - screen_buf = state.screen_buffer - depth_buf = state.depth_buffer - labels_buf = state.labels_buffer - automap_buf = state.automap_buffer - labels = state.labels + # Which consists of: + n = state.number + vars = state.game_variables + screen_buf = state.screen_buffer + depth_buf = state.depth_buffer + labels_buf = state.labels_buffer + automap_buf = state.automap_buffer + labels = state.labels - # Games variables can be also accessed via: - #game.get_game_variable(GameVariable.AMMO2) + # Games variables can be also accessed via: + #game.get_game_variable(GameVariable.AMMO2) - # Makes a random action and get remember reward. - r = game.make_action(choice(actions)) + # Makes a random action and get remember reward. + r = game.make_action(choice(actions)) - # Makes a "prolonged" action and skip frames: - # skiprate = 4 - # r = game.make_action(choice(actions), skiprate) + # Makes a "prolonged" action and skip frames: + # skiprate = 4 + # r = game.make_action(choice(actions), skiprate) - # The same could be achieved with: - # game.set_action(choice(actions)) - # game.advance_action(skiprate) - # r = game.get_last_reward() + # The same could be achieved with: + # game.set_action(choice(actions)) + # game.advance_action(skiprate) + # r = game.get_last_reward() - # Prints state's game variables and reward. - print("State #" + str(n)) - print("Game variables:", vars) - print("Reward:", r) - print("=====================") + # Prints state's game variables and reward. + print("State #" + str(n)) + print("Game variables:", vars) + print("Reward:", r) + print("=====================") - if sleep_time > 0: - sleep(sleep_time) - - # Check how the episode went. - print("Episode finished.") - print("Total reward:", game.get_total_reward()) - print("************************") + if sleep_time > 0: + sleep(sleep_time) + + # Check how the episode went. + print("Episode finished.") + print("Total reward:", game.get_total_reward()) + print("************************") -# It will be done automatically anyway but sometimes you need to do it in the middle of the program... -game.close() + # It will be done automatically anyway but sometimes you need to do it in the middle of the program... + game.close() diff --git a/examples/python/buffers.py b/examples/python/buffers.py index 62b870c80..4c77fbcc0 100755 --- a/examples/python/buffers.py +++ b/examples/python/buffers.py @@ -14,104 +14,119 @@ from __future__ import print_function from random import choice -from vizdoom import * +import vizdoom as vzd +from argparse import ArgumentParser + +DEFAULT_CONFIG = "../../scenarios/deadly_corridor.cfg" import cv2 -game = DoomGame() +if __name__ == "__main__": + + parser = ArgumentParser("ViZDoom example showing different buffers (screen, depth, labels).") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + + args = parser.parse_args() + + game = vzd.DoomGame() -# Use other config file if you wish. -game.load_config("../../scenarios/deadly_corridor.cfg") + # Use other config file if you wish. + game.load_config(args.config) -# game.set_console_enabled(True) -# game.set_window_visible(False) + # game.set_console_enabled(True) + # game.set_window_visible(False) -# Just umcomment desired format for screen buffer (and map buffer). -# The last uncommented will be applied. -# Formats with C (CRCGCB and CBCGCR) were omitted cause they are not cv2 friendly. -# Default format is ScreenFormat.CRCGCB. + # Just umcomment desired format for screen buffer (and map buffer). + # The last uncommented will be applied. + # Formats with C (CRCGCB and CBCGCR) were omitted cause they are not cv2 friendly. + # Default format is ScreenFormat.CRCGCB. -# OpenCV uses a BGR colorspace by default. -game.set_screen_format(ScreenFormat.BGR24) + # OpenCV uses a BGR colorspace by default. + game.set_screen_format(vzd.ScreenFormat.BGR24) -# game.set_screen_format(ScreenFormat.RGB24) -# game.set_screen_format(ScreenFormat.RGBA32) -# game.set_screen_format(ScreenFormat.ARGB32) -# game.set_screen_format(ScreenFormat.BGRA32) -# game.set_screen_format(ScreenFormat.ABGR32) -# game.set_screen_format(ScreenFormat.GRAY8) + # game.set_screen_format(ScreenFormat.RGB24) + # game.set_screen_format(ScreenFormat.RGBA32) + # game.set_screen_format(ScreenFormat.ARGB32) + # game.set_screen_format(ScreenFormat.BGRA32) + # game.set_screen_format(ScreenFormat.ABGR32) + # game.set_screen_format(ScreenFormat.GRAY8) -# Raw Doom buffer with palette's values. This one makes no sense in particular -# game.set_screen_format(ScreenFormat.DOOM_256_COLORS) + # Raw Doom buffer with palette's values. This one makes no sense in particular + # game.set_screen_format(ScreenFormat.DOOM_256_COLORS) -# Sets resolution for all buffers. -game.set_screen_resolution(ScreenResolution.RES_640X480) + # Sets resolution for all buffers. + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) -# Enables depth buffer. -game.set_depth_buffer_enabled(True) + # Enables depth buffer. + game.set_depth_buffer_enabled(True) -# Enables labeling of in game objects labeling. -game.set_labels_buffer_enabled(True) + # Enables labeling of in game objects labeling. + game.set_labels_buffer_enabled(True) -# Enables buffer with top down map of he current episode/level . -game.set_automap_buffer_enabled(True) -game.set_automap_mode(AutomapMode.OBJECTS) -game.set_automap_rotate(False) -game.set_automap_render_textures(False) + # Enables buffer with top down map of he current episode/level . + game.set_automap_buffer_enabled(True) + game.set_automap_mode(vzd.AutomapMode.OBJECTS) + game.set_automap_rotate(False) + game.set_automap_render_textures(False) -game.set_render_hud(True) -game.set_render_minimal_hud(False) + game.set_render_hud(True) + game.set_render_minimal_hud(False) -game.set_mode(Mode.SPECTATOR) -game.init() + game.set_mode(vzd.Mode.SPECTATOR) + game.init() -actions = [[True, False, False], [False, True, False], [False, False, True]] + actions = [[True, False, False], [False, True, False], [False, False, True]] -episodes = 10 -sleep_time = 0.028 + episodes = 10 + sleep_time = 0.028 -for i in range(episodes): - print("Episode #" + str(i + 1)) + for i in range(episodes): + print("Episode #" + str(i + 1)) - # Not needed for the first episode but the loop is nicer. - game.new_episode() - while not game.is_episode_finished(): - # Gets the state and possibly do something with it - state = game.get_state() + # Not needed for the first episode but the loop is nicer. + game.new_episode() + while not game.is_episode_finished(): + # Gets the state and possibly do something with it + state = game.get_state() - # Display all the buffers here! + # Display all the buffers here! - # Just screen buffer, given in selected format. This buffer is always available. - screen = state.screen_buffer - cv2.imshow('ViZDoom Screen Buffer', screen) + # Just screen buffer, given in selected format. This buffer is always available. + screen = state.screen_buffer + cv2.imshow('ViZDoom Screen Buffer', screen) - # Depth buffer, always in 8-bit gray channel format. - # This is most fun. It looks best if you inverse colors. - depth = state.depth_buffer - if depth is not None: - cv2.imshow('ViZDoom Depth Buffer', depth) + # Depth buffer, always in 8-bit gray channel format. + # This is most fun. It looks best if you inverse colors. + depth = state.depth_buffer + if depth is not None: + cv2.imshow('ViZDoom Depth Buffer', depth) - # Labels buffer, always in 8-bit gray channel format. - # Shows only visible game objects (enemies, pickups, exploding barrels etc.), each with unique label. - # Labels data are available in state.labels, also see labels.py example. - labels = state.labels_buffer - if labels is not None: - cv2.imshow('ViZDoom Labels Buffer', labels) + # Labels buffer, always in 8-bit gray channel format. + # Shows only visible game objects (enemies, pickups, exploding barrels etc.), each with unique label. + # Labels data are available in state.labels, also see labels.py example. + labels = state.labels_buffer + if labels is not None: + cv2.imshow('ViZDoom Labels Buffer', labels) - # Map buffer, in the same format as screen buffer. - # Shows top down map of the current episode/level. - automap = state.automap_buffer - if automap is not None: - cv2.imshow('ViZDoom Map Buffer', automap) + # Map buffer, in the same format as screen buffer. + # Shows top down map of the current episode/level. + automap = state.automap_buffer + if automap is not None: + cv2.imshow('ViZDoom Map Buffer', automap) - cv2.waitKey(int(sleep_time * 1000)) + cv2.waitKey(int(sleep_time * 1000)) - game.make_action(choice(actions)) + game.make_action(choice(actions)) - print("State #" + str(state.number)) - print("=====================") + print("State #" + str(state.number)) + print("=====================") - print("Episode finished!") - print("************************") + print("Episode finished!") + print("************************") -cv2.destroyAllWindows() \ No newline at end of file + cv2.destroyAllWindows() \ No newline at end of file diff --git a/examples/python/delta_buttons.py b/examples/python/delta_buttons.py index 336cddbca..c44753f05 100755 --- a/examples/python/delta_buttons.py +++ b/examples/python/delta_buttons.py @@ -3,67 +3,66 @@ from __future__ import print_function from time import sleep -from vizdoom import * +import vizdoom as vzd -game = DoomGame() +if __name__ == "__main__": + game = vzd.DoomGame() -# Adds delta buttons that will be allowed and set the maximum allowed value (optional). -game.add_available_button(Button.MOVE_FORWARD_BACKWARD_DELTA, 10) -game.add_available_button(Button.MOVE_LEFT_RIGHT_DELTA, 5) -game.add_available_button(Button.TURN_LEFT_RIGHT_DELTA, 5) -game.add_available_button(Button.LOOK_UP_DOWN_DELTA) + # Adds delta buttons that will be allowed and set the maximum allowed value (optional). + game.add_available_button(vzd.Button.MOVE_FORWARD_BACKWARD_DELTA, 10) + game.add_available_button(vzd.Button.MOVE_LEFT_RIGHT_DELTA, 5) + game.add_available_button(vzd.Button.TURN_LEFT_RIGHT_DELTA, 5) + game.add_available_button(vzd.Button.LOOK_UP_DOWN_DELTA) -# For normal buttons (binary) all values other than 0 are interpreted as pushed. -# For delta buttons values determine a precision/speed. -# -# For TURN_LEFT_RIGHT_DELTA and LOOK_UP_DOWN_DELTA value is the angle (in degrees) -# of which the viewing angle will change. -# -# For MOVE_FORWARD_BACKWARD_DELTA, MOVE_LEFT_RIGHT_DELTA, MOVE_UP_DOWN_DELTA (rarely used) -# value is the speed of movement in a given direction (100 is close to the maximum speed). -action = [100, 10, 10, 1] # floating point values can be used + # For normal buttons (binary) all values other than 0 are interpreted as pushed. + # For delta buttons values determine a precision/speed. + # + # For TURN_LEFT_RIGHT_DELTA and LOOK_UP_DOWN_DELTA value is the angle (in degrees) + # of which the viewing angle will change. + # + # For MOVE_FORWARD_BACKWARD_DELTA, MOVE_LEFT_RIGHT_DELTA, MOVE_UP_DOWN_DELTA (rarely used) + # value is the speed of movement in a given direction (100 is close to the maximum speed). + action = [100, 10, 10, 1] # floating point values can be used -# If button's absolute value > max button's value then value = max value with original value sign. + # If button's absolute value > max button's value then value = max value with original value sign. -# Delta buttons in spectator modes correspond to mouse movements. -# Maximum allowed values also apply to spectator modes. -# game.add_game_args("+freelook 1") # Use this to enable looking around with the mouse. -# game.set_mode(Mode.SPECTATOR) + # Delta buttons in spectator modes correspond to mouse movements. + # Maximum allowed values also apply to spectator modes. + # game.add_game_args("+freelook 1") # Use this to enable looking around with the mouse. + # game.set_mode(Mode.SPECTATOR) -game.set_window_visible(True) + game.set_window_visible(True) -game.init() + game.init() -episodes = 10 -sleep_time = 0.028 + episodes = 10 + sleep_time = 0.028 -for i in range(episodes): - print("Episode #" + str(i + 1)) + for i in range(episodes): + print("Episode #" + str(i + 1)) - game.new_episode() + game.new_episode() - while not game.is_episode_finished(): + while not game.is_episode_finished(): - state = game.get_state() - reward = game.make_action(action) + state = game.get_state() + reward = game.make_action(action) - time = game.get_episode_time() + time = game.get_episode_time() - action[0] = time % 100 - 50 - action[1] = time % 100 - 50 - action[2] = time % 100 - 50 - if not time % 50: - action[3] = -action[3] + action[0] = time % 100 - 50 + action[1] = time % 100 - 50 + action[2] = time % 100 - 50 + if not time % 50: + action[3] = -action[3] - print("State #" + str(state.number)) - print("Action made: ", action) - print("=====================") + print("State #" + str(state.number)) + print("Action made: ", action) + print("=====================") - if sleep_time > 0: - sleep(sleep_time) + if sleep_time > 0: + sleep(sleep_time) - print("Episode finished.") - print("************************") - -game.close() + print("Episode finished.") + print("************************") diff --git a/examples/python/fps.py b/examples/python/fps.py index 9c0453afb..da34a0bad 100755 --- a/examples/python/fps.py +++ b/examples/python/fps.py @@ -13,58 +13,77 @@ from random import choice from time import time -from vizdoom import * +import vizdoom as vzd +from argparse import ArgumentParser +import tqdm # Options: -resolution = ScreenResolution.RES_320X240 -screen_format = ScreenFormat.CRCGCB +resolution = vzd.ScreenResolution.RES_320X240 +screen_format = vzd.ScreenFormat.CRCGCB depth_buffer = False labels_buffer = False automap_buffer = False -iterations = 10000 - ##################################################################### +DEFAULT_CONFIG = "../../scenarios/basic.cfg" +DEFAULT_ITERATIONS = 10000 + +if __name__ == "__main__": + + parser = ArgumentParser("ViZDoom example showing possible framerates.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + parser.add_argument("-i", "--iterations", + default=DEFAULT_ITERATIONS, + type=int, + help="Number of iterations(actions) to run") + args = parser.parse_args() + + game = vzd.DoomGame() -game = DoomGame() -game.load_config("../../scenarios/basic.cfg") + # Use other config file if you wish. + game.load_config(args.config) -game.set_screen_resolution(resolution) -game.set_screen_format(screen_format) + game.set_screen_resolution(resolution) + game.set_screen_format(screen_format) -game.set_depth_buffer_enabled(depth_buffer) -game.set_labels_buffer_enabled(labels_buffer) -game.set_automap_buffer_enabled(automap_buffer) + game.set_depth_buffer_enabled(depth_buffer) + game.set_labels_buffer_enabled(labels_buffer) + game.set_automap_buffer_enabled(automap_buffer) -game.set_window_visible(False) + game.set_window_visible(False) -game.init() + game.init() -actions = [[True, False, False], [False, True, False], [False, False, True]] -left = actions[0] -right = actions[1] -shoot = actions[2] -idle = [False, False, False] + actions = [[True, False, False], [False, True, False], [False, False, True]] + left = actions[0] + right = actions[1] + shoot = actions[2] + idle = [False, False, False] -start = time() + start = time() -print("Checking FPS rating. It may take some time. Be patient.") + print("Checking FPS rating. It may take some time. Be patient.") -for i in range(iterations): + for i in tqdm.trange(args.iterations, leave=False): - if game.is_episode_finished(): - game.new_episode() + if game.is_episode_finished(): + game.new_episode() - # Copying happens here - s = game.get_state() - game.make_action(choice(actions)) + # Copying happens here + s = game.get_state() + game.make_action(choice(actions)) -end = time() -t = end - start -print("Results:") -print("Iterations:", iterations) -print("Resolution:", resolution) -print("time:", round(t, 3)) -print("fps: ", round(iterations / t, 2)) + end = time() + t = end - start + print("Results:") + print("Iterations:", args.iterations) + print("Resolution:", resolution) + print("time:", round(t, 3), "s") + print("fps: ", round(args.iterations / t, 2)) -game.close() + game.close() diff --git a/examples/python/labels.py b/examples/python/labels.py index 7fdf38c80..9a9421a73 100755 --- a/examples/python/labels.py +++ b/examples/python/labels.py @@ -16,115 +16,128 @@ from __future__ import print_function from random import choice -from vizdoom import * +import vizdoom as vzd +from argparse import ArgumentParser import cv2 -game = DoomGame() +DEFAULT_CONFIG = "../../scenarios/deadly_corridor.cfg" +if __name__ =="__main__": + parser = ArgumentParser("ViZDoom example showing how to use labels and labels buffer.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") -# Use other config file if you wish. -game.load_config("../../scenarios/deadly_corridor.cfg") -game.set_render_hud(False) + args = parser.parse_args() -game.set_screen_resolution(ScreenResolution.RES_640X480) + game = vzd.DoomGame() -# Set cv2 friendly format. -game.set_screen_format(ScreenFormat.BGR24) + # Use other config file if you wish. + game.load_config(args.config) + game.set_render_hud(False) -# Enables labeling of the in game objects. -game.set_labels_buffer_enabled(True) + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) -game.clear_available_game_variables() -game.add_available_game_variable(GameVariable.POSITION_X) -game.add_available_game_variable(GameVariable.POSITION_Y) -game.add_available_game_variable(GameVariable.POSITION_Z) + # Set cv2 friendly format. + game.set_screen_format(vzd.ScreenFormat.BGR24) -game.init() + # Enables labeling of the in game objects. + game.set_labels_buffer_enabled(True) -actions = [[True, False, False], [False, True, False], [False, False, True]] + game.clear_available_game_variables() + 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) -episodes = 10 + game.init() -# Sleep time between actions in ms -sleep_time = 28 + actions = [[True, False, False], [False, True, False], [False, False, True]] + episodes = 10 -# Prepare some colors and drawing function -# Colors in in BGR order -doom_red_color = [0, 0, 203] -doom_blue_color = [203, 0, 0] + # Sleep time between actions in ms + sleep_time = 28 -def draw_bounding_box(buffer, x, y, width, height, color): - for i in range(width): - buffer[y, x + i, :] = color - buffer[y + height, x + i, :] = color - for i in range(height): - buffer[y + i, x, :] = color - buffer[y + i, x + width, :] = color + # Prepare some colors and drawing function + # Colors in in BGR order + doom_red_color = [0, 0, 203] + doom_blue_color = [203, 0, 0] + def draw_bounding_box(buffer, x, y, width, height, color): + for i in range(width): + buffer[y, x + i, :] = color + buffer[y + height, x + i, :] = color -for i in range(episodes): - print("Episode #" + str(i + 1)) - seen_in_this_episode = set() + for i in range(height): + buffer[y + i, x, :] = color + buffer[y + i, x + width, :] = color - # Not needed for the first episode but the loop is nicer. - game.new_episode() - while not game.is_episode_finished(): - # Gets the state - state = game.get_state() + for i in range(episodes): + print("Episode #" + str(i + 1)) + seen_in_this_episode = set() - # Labels buffer, always in 8-bit gray channel format. - # Shows only visible game objects (enemies, pickups, exploding barrels etc.), each with unique label. - # Labels data are available in state.labels. - labels = state.labels_buffer - if labels is not None: - cv2.imshow('ViZDoom Labels Buffer', labels) + # Not needed for the first episode but the loop is nicer. + game.new_episode() + while not game.is_episode_finished(): - # Screen buffer, given in selected format. This buffer is always available. - # Using information from state.labels draw bounding boxes. - screen = state.screen_buffer - for l in state.labels: - if l.object_name in ["Medkit", "GreenArmor"]: - draw_bounding_box(screen, l.x, l.y, l.width, l.height, doom_blue_color) - else: - draw_bounding_box(screen, l.x, l.y, l.width, l.height, doom_red_color) - cv2.imshow('ViZDoom Screen Buffer', screen) + # Gets the state + state = game.get_state() - cv2.waitKey(sleep_time) + # Labels buffer, always in 8-bit gray channel format. + # Shows only visible game objects (enemies, pickups, exploding barrels etc.), each with unique label. + # Labels data are available in state.labels. + labels = state.labels_buffer + if labels is not None: + cv2.imshow('ViZDoom Labels Buffer', labels) - game.make_action(choice(actions)) + # Screen buffer, given in selected format. This buffer is always available. + # Using information from state.labels draw bounding boxes. + screen = state.screen_buffer + for l in state.labels: + if l.object_name in ["Medkit", "GreenArmor"]: + draw_bounding_box(screen, l.x, l.y, l.width, l.height, doom_blue_color) + else: + draw_bounding_box(screen, l.x, l.y, l.width, l.height, doom_red_color) + cv2.imshow('ViZDoom Screen Buffer', screen) - print("State #" + str(state.number)) - print("Player position X:", state.game_variables[0], "Y:", state.game_variables[1], "Z:", state.game_variables[2]) - print("Labels:") + cv2.waitKey(sleep_time) - # Print information about objects visible on the screen. - # object_id identifies specific in game object. - # object_name contains name of object. - # value tells which value represents object in labels_buffer. - for l in state.labels: - seen_in_this_episode.add(l.object_name) - # print("---------------------") - print("Label:", l.value, "object id:", l.object_id, "object name:", l.object_name) - print("Object position x:", l.object_position_x, "y:", l.object_position_y, "z:", l.object_position_z) + game.make_action(choice(actions)) - # Other available fields: - #print("Object rotation angle", l.object_angle, "pitch:", l.object_pitch, "roll:", l.object_roll) - #print("Object velocity x:", l.object_velocity_x, "y:", l.object_velocity_y, "z:", l.object_velocity_z) - print("Bounding box: x:", l.x, "y:", l.y, "width:", l.width, "height:", l.height) + print("State #" + str(state.number)) + print("Player position X:", state.game_variables[0], "Y:", state.game_variables[1], "Z:", state.game_variables[2]) + print("Labels:") - print("=====================") + # Print information about objects visible on the screen. + # object_id identifies specific in game object. + # object_name contains name of object. + # value tells which value represents object in labels_buffer. + for l in state.labels: + seen_in_this_episode.add(l.object_name) + # print("---------------------") + print("Label:", l.value, "object id:", l.object_id, "object name:", l.object_name) + print("Object position x:", l.object_position_x, "y:", l.object_position_y, "z:", l.object_position_z) + + # Other available fields: + #print("Object rotation angle", l.object_angle, "pitch:", l.object_pitch, "roll:", l.object_roll) + #print("Object velocity x:", l.object_velocity_x, "y:", l.object_velocity_y, "z:", l.object_velocity_z) + print("Bounding box: x:", l.x, "y:", l.y, "width:", l.width, "height:", l.height) - print("Episode finished!") + print("=====================") - print("=====================") + print("Episode finished!") + + print("=====================") - print("Seen in this episode:") - for l in seen_in_this_episode: - print(l) + print("Seen in this episode:") + for l in seen_in_this_episode: + print(l) - print("************************") + print("************************") -cv2.destroyAllWindows() \ No newline at end of file + cv2.destroyAllWindows() \ No newline at end of file diff --git a/examples/python/learning_tensorflow.py b/examples/python/learning_tensorflow.py index 72511b760..11ced52b8 100755 --- a/examples/python/learning_tensorflow.py +++ b/examples/python/learning_tensorflow.py @@ -2,7 +2,6 @@ # -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function -from vizdoom import * import itertools as it from random import sample, randint, random from time import time, sleep @@ -10,6 +9,8 @@ import skimage.color, skimage.transform import tensorflow as tf from tqdm import trange +import vizdoom as vzd +from argparse import ArgumentParser # Q-learning settings learning_rate = 0.00025 @@ -30,12 +31,15 @@ resolution = (30, 45) episodes_to_watch = 10 -model_savefile = "/tmp/model.ckpt" + +# TODO move to argparser save_model = True load_model = False skip_learning = False + # Configuration file path -config_file_path = "../../scenarios/simpler_basic.cfg" +DEFAULT_MODEL_SAVEFILE = "/tmp/model" +DEFAULT_CONFIG = "../../scenarios/simpler_basic.cfg" # config_file_path = "../../scenarios/rocket_basic.cfg" @@ -185,20 +189,30 @@ def exploration_rate(epoch): # Creates and initializes ViZDoom environment. def initialize_vizdoom(config_file_path): print("Initializing doom...") - game = DoomGame() + game = vzd.DoomGame() game.load_config(config_file_path) game.set_window_visible(False) - game.set_mode(Mode.PLAYER) - game.set_screen_format(ScreenFormat.GRAY8) - game.set_screen_resolution(ScreenResolution.RES_640X480) + 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 if __name__ == '__main__': + parser = ArgumentParser("ViZDoom example showing how to train a simple agent using simplified DQN.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + + args = parser.parse_args() + # Create Doom instance - game = initialize_vizdoom(config_file_path) + game = initialize_vizdoom(args.config) # Action = which buttons are pressed n = game.get_available_buttons_size() @@ -211,8 +225,8 @@ def initialize_vizdoom(config_file_path): learn, get_q_values, get_best_action = create_network(session, len(actions)) saver = tf.train.Saver() if load_model: - print("Loading model from: ", model_savefile) - saver.restore(session, model_savefile) + print("Loading model from: ", DEFAULT_MODEL_SAVEFILE) + saver.restore(session, DEFAULT_MODEL_SAVEFILE) else: init = tf.global_variables_initializer() session.run(init) @@ -260,8 +274,8 @@ def initialize_vizdoom(config_file_path): test_scores.mean(), test_scores.std()), "min: %.1f" % test_scores.min(), "max: %.1f" % test_scores.max()) - print("Saving the network weigths to:", model_savefile) - saver.save(session, model_savefile) + 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)) @@ -271,7 +285,7 @@ def initialize_vizdoom(config_file_path): # Reinitialize the game with window visible game.set_window_visible(True) - game.set_mode(Mode.ASYNC_PLAYER) + game.set_mode(vzd.Mode.ASYNC_PLAYER) game.init() for _ in range(episodes_to_watch): diff --git a/examples/python/pyoblige.py b/examples/python/pyoblige.py index 9a10d0e6b..995f3c6ae 100755 --- a/examples/python/pyoblige.py +++ b/examples/python/pyoblige.py @@ -10,36 +10,70 @@ import os import vizdoom as vzd +from argparse import ArgumentParser import oblige +DEFAULT_CONFIG = "../../scenarios/oblige.cfg" +DEFAULT_SEED = 666 +DEFAULT_OUTPUT_FILE = "test.wad" if __name__ == "__main__": - game = vzd.DoomGame() + parser = ArgumentParser("An example showing how to generate maps with PyOblige.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + parser.add_argument("-s", "--seed", + default=DEFAULT_SEED, + type=int, + help="Number of iterations(actions) to run") + parser.add_argument("-v", "--verbose", + action="store_true", + help="Use verbose mode during map generation.") + parser.add_argument("-o", "--output_file", + default=DEFAULT_OUTPUT_FILE, + help="Where the wad file will be created.") + parser.add_argument("-x", "--exit", + action="store_true", + help="Do not test the wad, just leave after generation.") + + args = parser.parse_args() + game = vzd.DoomGame() # Use your config - game.load_config("../../scenarios/oblige.cfg") + game.load_config(args.config) game.set_doom_map("map01") game.set_doom_skill(3) # Create Doom Level Generator instance and set optional seed. generator = oblige.DoomLevelGenerator() - generator.set_seed(666) + generator.set_seed(args.seed) # Set generator configs, specified keys will be overwritten. - generator.set_config({"size": "micro", "health": "more", "weapons": "sooner"}) + generator.set_config({ + "size": "micro", + "health": "more", + "weapons": "sooner"}) # There are few predefined sets of settings already defined in Oblige package, like test_wad and childs_play_wad - generator.set_config(oblige.test_wad) + generator.set_config(oblige.childs_play_wad) # Tell generator to generate few maps (options for "length": "single", "few", "episode", "game"). generator.set_config({"length": "few"}) # Generate method will return number of maps inside wad file. - wad_path = "test.wad" - maps = generator.generate(wad_path) + wad_path = args.output_file + print("Generating {} ...".format(wad_path)) + num_maps = generator.generate(wad_path, verbose=args.verbose) + print("Generated {} maps.".format(num_maps)) + + if args.exit: + exit(0) # Set Scenario to the new generated WAD - game.set_doom_scenario_path(wad_path) + game.set_doom_scenario_path(args.output_file) # Sets up game for spectator (you) game.add_game_args("+freelook 1") @@ -50,7 +84,7 @@ game.init() # Play as many episodes as maps in the new generated WAD file. - episodes = maps + episodes = num_maps # Play until the game (episode) is over. for i in range(1, episodes + 1): @@ -90,4 +124,4 @@ # Remove output of generator os.remove(wad_path) os.remove(wad_path.replace("wad", "old")) - os.remove(wad_path.replace("wad", "txt")) \ No newline at end of file + os.remove(wad_path.replace("wad", "txt")) diff --git a/examples/python/scenarios.py b/examples/python/scenarios.py index 727c967ba..0b35d560e 100755 --- a/examples/python/scenarios.py +++ b/examples/python/scenarios.py @@ -15,63 +15,65 @@ import itertools as it from random import choice from time import sleep -from vizdoom import DoomGame, ScreenResolution - -game = DoomGame() - -# Choose scenario config file you wish to watch. -# Don't load two configs cause the second will overrite the first one. -# Multiple config files are ok but combining these ones doesn't make much sense. - -# game.load_config("../../scenarios/basic.cfg") -# game.load_config("../../scenarios/simpler_basic.cfg") -game.load_config("../../scenarios/rocket_basic.cfg") -# game.load_config("../../scenarios/deadly_corridor.cfg") -# game.load_config("../../scenarios/deathmatch.cfg") -# game.load_config("../../scenarios/defend_the_center.cfg") -# game.load_config("../../scenarios/defend_the_line.cfg") -# game.load_config("../../scenarios/health_gathering.cfg") -# game.load_config("../../scenarios/my_way_home.cfg") -# game.load_config("../../scenarios/predict_position.cfg") -# game.load_config("../../scenarios/take_cover.cfg") - -# Makes the screen bigger to see more details. -game.set_screen_resolution(ScreenResolution.RES_640X480) -game.set_window_visible(True) -game.init() - -# Creates all possible actions depending on how many buttons there are. -actions_num = game.get_available_buttons_size() -actions = [] -for perm in it.product([False, True], repeat=actions_num): - actions.append(list(perm)) - -episodes = 10 -sleep_time = 0.028 - -for i in range(episodes): - print("Episode #" + str(i + 1)) - - # Not needed for the first episode but the loop is nicer. - game.new_episode() - while not game.is_episode_finished(): - - # Gets the state and possibly to something with it - state = game.get_state() - - # Makes a random action and save the reward. - reward = game.make_action(choice(actions)) - - print("State #" + str(state.number)) - print("Game Variables:", state.game_variables) - print("Performed action:", game.get_last_action()) - print("Last Reward:", reward) - print("=====================") - - # Sleep some time because processing is too fast to watch. - if sleep_time > 0: - sleep(sleep_time) - - print("Episode finished!") - print("total reward:", game.get_total_reward()) - print("************************") +import vizdoom as vzd +from argparse import ArgumentParser + +DEFAULT_CONFIG = "../../scenarios/rocket_basic.cfg" +if __name__ == "__main__": + + parser = ArgumentParser("ViZDoom scenarios example.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + + args = parser.parse_args() + game = vzd.DoomGame() + + # Choose scenario config file you wish to watch. + # Don't load two configs cause the second will overwrite the first one. + # Multiple config files are ok but combining these ones doesn't make much sense. + game.load_config(args.config) + + # Makes the screen bigger to see more details. + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) + game.set_window_visible(True) + game.init() + + # Creates all possible actions depending on how many buttons there are. + actions_num = game.get_available_buttons_size() + actions = [] + for perm in it.product([False, True], repeat=actions_num): + actions.append(list(perm)) + + episodes = 10 + sleep_time = 0.028 + + for i in range(episodes): + print("Episode #" + str(i + 1)) + + # Not needed for the first episode but the loop is nicer. + game.new_episode() + while not game.is_episode_finished(): + + # Gets the state and possibly to something with it + state = game.get_state() + + # Makes a random action and save the reward. + reward = game.make_action(choice(actions)) + + print("State #" + str(state.number)) + print("Game Variables:", state.game_variables) + print("Performed action:", game.get_last_action()) + print("Last Reward:", reward) + print("=====================") + + # Sleep some time because processing is too fast to watch. + if sleep_time > 0: + sleep(sleep_time) + + print("Episode finished!") + print("total reward:", game.get_total_reward()) + print("************************") diff --git a/examples/python/seed.py b/examples/python/seed.py index f1e83400c..b7616f811 100755 --- a/examples/python/seed.py +++ b/examples/python/seed.py @@ -18,74 +18,84 @@ import itertools as it from random import choice from time import sleep -from vizdoom import * - -game = DoomGame() - -# Choose the scenario config file you wish to watch. -# Don't load two configs cause the second will overrite the first one. -# Multiple config files are ok but combining these ones doesn't make much sense. - -game.load_config("../../scenarios/basic.cfg") -# game.load_config("../../scenarios/simpler_basic.cfg") -# game.load_config("../../scenarios/rocket_basic.cfg") -# game.load_config("../../scenarios/deadly_corridor.cfg") -# game.load_config("../../scenarios/deathmatch.cfg") -# game.load_config("../../scenarios/defend_the_center.cfg") -# game.load_config("../../scenarios/defend_the_line.cfg") -# game.load_config("../../scenarios/health_gathering.cfg") -# game.load_config("../../scenarios/my_way_home.cfg") -# game.load_config("../../scenarios/predict_position.cfg") -# game.load_config("../../scenarios/take_cover.cfg") - -game.set_screen_resolution(ScreenResolution.RES_640X480) - -# Lets make episode shorter and observe starting position of Cacodemon. -game.set_episode_timeout(50) - -seed = 666 -# Sets the seed. It can be change after init. -game.set_seed(seed) - -game.init() - -# Creates all possible actions depending on how many buttons there are. -actions_num = game.get_available_buttons_size() -actions = [] -for perm in it.product([False, True], repeat=actions_num): - actions.append(list(perm)) - -episodes = 10 -sleep_time = 0.028 - -for i in range(episodes): - print("Episode #" + str(i + 1)) - - # Seed can be changed anytime. It will take effect from next episodes. - # game.set_seed(seed) - game.new_episode() - - while not game.is_episode_finished(): - # Gets the state and possibly to something with it - state = game.get_state() - screen_buf = state.screen_buffer - vars = state.game_variables - - # Check which action you chose! - reward = game.make_action(choice(actions)) - - print("State #" + str(state.number)) - print("Game Variables:", vars) - print("Last Reward:", reward) - print("Seed:", game.get_seed()) - print("=====================") - - # Sleep some time because processing is too fast to watch. - if sleep_time > 0: - sleep(sleep_time) - - print("Episode finished!") - print("Total reward:", game.get_total_reward()) - print("************************") - -game.close() +from argparse import ArgumentParser +import vizdoom as vzd + +DEFAULT_CONFIG = "../../scenarios/basic.cfg" + +if __name__ == "__main__": + parser = ArgumentParser("ViZDoom example showing how to set seed to have deterministic episodes.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + parser.add_argument("-s", "--seed", + default=666, + type=int, + help="Seed for the random generator in DoomGame.") + parser.add_argument("-e", "--per_episode", + action="store_true", + help="Set seed for every episode.") + args = parser.parse_args() + + game = vzd.DoomGame() + + # Choose the scenario config file you wish to watch. + # Don't load two configs cause the second will overrite the first one. + # Multiple config files are ok but combining these ones doesn't make much sense. + + game.load_config(args.config) + + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) + + # Lets make episode shorter and observe starting position of Cacodemon. + game.set_episode_timeout(50) + + if args.seed is not None: + # Sets the seed. It can be change after init. + game.set_seed(args.seed) + + game.init() + + # Creates all possible actions depending on how many buttons there are. + actions_num = game.get_available_buttons_size() + actions = [] + for perm in it.product([False, True], repeat=actions_num): + actions.append(list(perm)) + + episodes = 10 + sleep_time = 0.028 + + for i in range(episodes): + print("Episode #" + str(i + 1)) + + # Seed can be changed anytime. It will take effect from next episodes. + # game.set_seed(seed) + if args.seed is not None and args.per_episode: + game.set_seed(args.seed) + game.new_episode() + + while not game.is_episode_finished(): + # Gets the state and possibly to something with it + state = game.get_state() + screen_buf = state.screen_buffer + vars = state.game_variables + + # Check which action you chose! + reward = game.make_action(choice(actions)) + + print("State #" + str(state.number)) + print("Game Variables:", vars) + print("Last Reward:", reward) + print("Seed:", game.get_seed()) + print("=====================") + + # Sleep some time because processing is too fast to watch. + if sleep_time > 0: + sleep(sleep_time) + + print("Episode finished!") + print("Total reward:", game.get_total_reward()) + print("************************") diff --git a/examples/python/shaping.py b/examples/python/shaping.py index 8673bb7a0..95747253c 100755 --- a/examples/python/shaping.py +++ b/examples/python/shaping.py @@ -18,63 +18,76 @@ import itertools as it from random import choice from time import sleep -from vizdoom import * +from argparse import ArgumentParser +import vizdoom as vzd -game = DoomGame() +DEFAULT_CONFIG = "../../scenarios/health_gathering.cfg" -# Choose scenario config file you wish to watch. -# Don't load two configs cause the second will overrite the first one. -# Multiple config files are ok but combining these ones doesn't make much sense. +if __name__ == "__main__": + parser = ArgumentParser("ViZDoom example showing how to use shaping for health gathering scenario.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") -game.load_config("../../scenarios/health_gathering.cfg") -game.set_screen_resolution(ScreenResolution.RES_640X480) + args = parser.parse_args() -game.init() + game = vzd.DoomGame() -# Creates all possible actions. -actions_num = game.get_available_buttons_size() -actions = [] -for perm in it.product([False, True], repeat=actions_num): - actions.append(list(perm)) + # Choose scenario config file you wish to watch. + # Don't load two configs cause the second will overrite the first one. + # Multiple config files are ok but combining these ones doesn't make much sense. -episodes = 10 -sleep_time = 0.028 + game.load_config(args.config) + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) -for i in range(episodes): + game.init() - print("Episode #" + str(i + 1)) - # Not needed for the first episode but the loop is nicer. - game.new_episode() + # Creates all possible actions. + actions_num = game.get_available_buttons_size() + actions = [] + for perm in it.product([False, True], repeat=actions_num): + actions.append(list(perm)) - # Use this to remember last shaping reward value. - last_total_shaping_reward = 0 + episodes = 10 + sleep_time = 0.028 - while not game.is_episode_finished(): + for i in range(episodes): - # Gets the state and possibly to something with it - state = game.get_state() + print("Episode #" + str(i + 1)) + # Not needed for the first episode but the loop is nicer. + game.new_episode() - # Makes a random action and save the reward. - reward = game.make_action(choice(actions)) + # Use this to remember last shaping reward value. + last_total_shaping_reward = 0 - # Retrieve the shaping reward - fixed_shaping_reward = game.get_game_variable(GameVariable.USER1) # Get value of scripted variable - shaping_reward = doom_fixed_to_double(fixed_shaping_reward) # If value is in DoomFixed format project it to double - shaping_reward = shaping_reward - last_total_shaping_reward - last_total_shaping_reward += shaping_reward + while not game.is_episode_finished(): - print("State #" + str(state.number)) - print("Health: ", state.game_variables[0]) - print("Last Reward:", reward) - print("Last Shaping Reward:", shaping_reward) - print("=====================") + # Gets the state and possibly to something with it + state = game.get_state() - # Sleep some time because processing is too fast to watch. - if sleep_time > 0: - sleep(sleep_time) + # Makes a random action and save the reward. + reward = game.make_action(choice(actions)) - print("Episode finished!") - print("Total reward:", game.get_total_reward()) - print("************************") + # Retrieve the shaping reward + fixed_shaping_reward = game.get_game_variable(vzd.GameVariable.USER1) # Get value of scripted variable + shaping_reward = vzd.doom_fixed_to_double( + fixed_shaping_reward) # If value is in DoomFixed format project it to double + shaping_reward = shaping_reward - last_total_shaping_reward + last_total_shaping_reward += shaping_reward -game.close() + print("State #" + str(state.number)) + print("Health: ", state.game_variables[0]) + print("Last Reward:", reward) + print("Last Shaping Reward:", shaping_reward) + print("=====================") + + # Sleep some time because processing is too fast to watch. + if sleep_time > 0: + sleep(sleep_time) + + print("Episode finished!") + print("Total reward:", game.get_total_reward()) + print("************************") diff --git a/examples/python/spectator.py b/examples/python/spectator.py index 33c5bc67e..16ed27d61 100755 --- a/examples/python/spectator.py +++ b/examples/python/spectator.py @@ -11,60 +11,61 @@ from __future__ import print_function from time import sleep -from vizdoom import * +import vizdoom as vzd +from argparse import ArgumentParser -game = DoomGame() +DEFAULT_CONFIG = "../../scenarios/deathmatch.cfg" -# Choose scenario config file you wish to watch. -# Don't load two configs cause the second will overrite the first one. -# Multiple config files are ok but combining these ones doesn't make much sense. +if __name__ == "__main__": + parser = ArgumentParser("ViZDoom example showing how to use SPECTATOR mode.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + args = parser.parse_args() + game = vzd.DoomGame() -# game.load_config("../../scenarios/basic.cfg") -# game.load_config("../../scenarios/simpler_basic.cfg") -# game.load_config("../../scenarios/rocket_basic.cfg") -# game.load_config("../../scenarios/deadly_corridor.cfg") -game.load_config("../../scenarios/deathmatch.cfg") -# game.load_config("../../scenarios/defend_the_center.cfg") -# game.load_config("../../scenarios/defend_the_line.cfg") -# game.load_config("../../scenarios/health_gathering.cfg") -# game.load_config("../../scenarios/my_way_home.cfg") -# game.load_config("../../scenarios/predict_position.cfg") -# game.load_config("../../scenarios/take_cover.cfg") + # Choose scenario config file you wish to watch. + # Don't load two configs cause the second will overrite the first one. + # Multiple config files are ok but combining these ones doesn't make much sense. + game.load_config(args.config) -# Enables freelook in engine -game.add_game_args("+freelook 1") + # Enables freelook in engine + game.add_game_args("+freelook 1") -game.set_screen_resolution(ScreenResolution.RES_640X480) + game.set_screen_resolution(vzd.ScreenResolution.RES_640X480) -# Enables spectator mode, so you can play. Sounds strange but it is the agent who is supposed to watch not you. -game.set_window_visible(True) -game.set_mode(Mode.SPECTATOR) + # Enables spectator mode, so you can play. Sounds strange but it is the agent who is supposed to watch not you. + game.set_window_visible(True) + game.set_mode(vzd.Mode.SPECTATOR) -game.init() + game.init() -episodes = 10 + episodes = 10 -for i in range(episodes): - print("Episode #" + str(i + 1)) + for i in range(episodes): + print("Episode #" + str(i + 1)) - game.new_episode() - while not game.is_episode_finished(): - state = game.get_state() + game.new_episode() + while not game.is_episode_finished(): + state = game.get_state() - game.advance_action() - last_action = game.get_last_action() - reward = game.get_last_reward() + game.advance_action() + last_action = game.get_last_action() + reward = game.get_last_reward() - print("State #" + str(state.number)) - print("Game variables: ", state.game_variables) - print("Action:", last_action) - print("Reward:", reward) - print("=====================") + print("State #" + str(state.number)) + print("Game variables: ", state.game_variables) + print("Action:", last_action) + print("Reward:", reward) + print("=====================") - print("Episode finished!") - print("Total reward:", game.get_total_reward()) - print("************************") - sleep(2.0) + print("Episode finished!") + print("Total reward:", game.get_total_reward()) + print("************************") + sleep(2.0) -game.close() + game.close() diff --git a/examples/python/ticrate.py b/examples/python/ticrate.py index 92b42fd88..53fdd1c17 100755 --- a/examples/python/ticrate.py +++ b/examples/python/ticrate.py @@ -3,13 +3,25 @@ from __future__ import print_function from multiprocessing import Process from random import choice -from vizdoom import * +import vizdoom as vzd +from argparse import ArgumentParser +DEFAULT_CONFIG = "../../scenarios/basic.cfg" + + +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) -def play(game): game.init() - actions = [[True, False, False], [False, True, False], [False, False, True]] + actions = [[True, False, False], + [False, True, False], + [False, False, True]] episodes = 10 for i in range(episodes): @@ -21,31 +33,26 @@ def play(game): game.close() -def player1(): - game = DoomGame() - - game.load_config('../../scenarios/basic.cfg') - game.set_mode(Mode.ASYNC_PLAYER) - - # Default Doom's ticrate is 35 per second, so this one will work 2 times faster. - game.set_ticrate(70) - - play(game) - - -def player2(): - game = DoomGame() - - game.load_config('../../scenarios/basic.cfg') - game.set_mode(Mode.ASYNC_PLAYER) - - # And this one will work 2 times slower. - game.set_ticrate(17) - - play(game) - - if __name__ == '__main__': - p1 = Process(target=player1) - p1.start() - player2() + if __name__ == "__main__": + parser = ArgumentParser("ViZDoom example showing how to change the ticrate for asynchronous mode.") + parser.add_argument(dest="config", + default=DEFAULT_CONFIG, + nargs="?", + help="Path to the configuration file of the scenario." + " Please see " + "../../scenarios/*cfg for more scenarios.") + parser.add_argument("-t", "--ticrates", + default=[17,35,70], + nargs="+", + help="List of ticrates to show.") + args = parser.parse_args() + + processes= [] + for ticrate in args.ticrates: + p = Process(target=play, args=[args.config, ticrate]) + p.start() + processes.append(p) + + for p in processes: + p.join()