Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates to some of the examples #583

Merged
merged 4 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions examples/python/buffers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

#####################################################################
# This script presents different buffers and formats.
# OpenCV is used here to display images, install it or remove any
# references to cv2
#
# Note: OpenCV is used here to display images, install it:
# pip install opencv-python
# or remove any references to cv2.
#
# Configuration is loaded from "../../scenarios/basic.cfg" file.
# <episodes> number of episodes are played.
# Random combination of buttons is chosen for every action.
Expand Down Expand Up @@ -70,13 +73,17 @@

# Enables labeling of in game objects labeling.
game.set_labels_buffer_enabled(True)
# See also labels_buffer.py example for more explanations.

# Enables buffer with top down map of he current episode/level .
# Enables buffer with top down map of the 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)

# There is also audio buffer which is not present here.
# See audio_buffer.py example for more explanations.

game.set_render_hud(True)
game.set_render_minimal_hud(False)

Expand Down
16 changes: 11 additions & 5 deletions examples/python/record_episodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,20 @@
while not game.is_episode_finished():
s = game.get_state()

a = choice(actions)
r = game.make_action(choice(actions))

print(f"State #{s.number}")
print("Action:", a)
print("Game variables:", s.game_variables[0])
print("Reward:", r)
print("=====================")

print("Episode", i, "finished.")
print("total reward:", game.get_total_reward())
print(f"Episode {i} finished. Saved to file episode{i}_rec.lmp")
print("Total reward:", game.get_total_reward())
print("************************\n")

game.new_episode() # This is currently required to stop and save the previous recording.
game.close()

# New render settings for replay
Expand All @@ -76,21 +79,24 @@
game.replay_episode(f"episode{i}_rec.lmp")

while not game.is_episode_finished():
# Get a state
s = game.get_state()

# Use advance_action instead of make_action.
# Use advance_action instead of make_action to proceed
game.advance_action()

# Retrieve the last actions and the reward
a = game.get_last_action()
r = game.get_last_reward()
# game.get_last_action is not supported and don't work for replay at the moment.

print(f"State #{s.number}")
print("Action:", a)
print("Game variables:", s.game_variables[0])
print("Reward:", r)
print("=====================")

print("Episode", i, "finished.")
print("total reward:", game.get_total_reward())
print("Total reward:", game.get_total_reward())
print("************************")

game.close()
Expand Down
4 changes: 2 additions & 2 deletions examples/python/scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# To see the scenario description go to "../../scenarios/README.md"
#####################################################################

import itertools as it
import itertools
import os
from argparse import ArgumentParser
from random import choice
Expand Down Expand Up @@ -48,7 +48,7 @@
# 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):
for perm in itertools.product([False, True], repeat=actions_num):
actions.append(list(perm))

episodes = 10
Expand Down
2 changes: 1 addition & 1 deletion scenarios/predict_position.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ doom_skill = 1
living_reward = -0.001

# Rendering options
screen_resolution = RES_800X450
screen_resolution = RES_320X240
screen_format = CRCGCB
render_hud = false
render_crosshair = false
Expand Down
139 changes: 139 additions & 0 deletions tests/manual_test_seed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
#!/usr/bin/env python3ch

# Tests ViZDoom seed option.
# This test can be run as Python script or via PyTest

import itertools
import os
import random

import cv2
import numpy as np

import vizdoom as vzd


def test_seed(repeats=10, tics=8, audio_buffer=False, seed=1993):
scenarios_to_skip = [
# "deadly_corridor.cfg",
# "defend_the_center.cfg",
# "deathmatch.cfg",
# "health_gathering.cfg",
# "health_gathering_supreme.cfg",
# "deathmatch.cfg",
# Multiplayer scenarios
"cig.cfg",
"multi_duel.cfg",
"multi.cfg",
"oblige.cfg",
]
configs = [
file
for file in os.listdir(vzd.scenarios_path)
if file.endswith(".cfg") and file not in scenarios_to_skip
]
print(configs)
game = vzd.DoomGame()

for config in configs:
print(config)
initial_states = []
states_after_action = []

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

# Creates all possible actions depending on how many buttons there are.
actions_num = game.get_available_buttons_size()
actions = []
for perm in itertools.product([False, True], repeat=actions_num):
actions.append(list(perm))

# Enable all buffers
buffers = ["screen_buffer", "depth_buffer", "labels_buffer", "automap_buffer"]
game.set_depth_buffer_enabled(True)
game.set_labels_buffer_enabled(True)
game.set_automap_buffer_enabled(True)
game.set_objects_info_enabled(True)
game.set_sectors_info_enabled(True)
game.set_audio_buffer_enabled(audio_buffer)
if audio_buffer:
buffers.append("audio_buffer")

game.set_screen_format(vzd.ScreenFormat.BGR24)

game.init()

for i in range(repeats):
game.set_seed(1993)
random.seed(seed)
# game.init()
game.new_episode()

initial_states.append(game.get_state())
if i % 2 == 0:
game.make_action(random.choice(actions), tics=tics)
else:
action = random.choice(actions)
for _ in range(tics):
game.make_action(action, tics=1)

game.make_action(random.choice(actions), tics=tics)
states_after_action.append(game.get_state())

# game.close()

for s1, s2 in zip(initial_states[:-1], initial_states[1:]):
assert s1.tic == s2.tic
assert np.array_equal(s1.game_variables, s2.game_variables)

if not np.array_equal(s1.screen_buffer, s2.screen_buffer):
print("Initial states are not equal")
print(f"s1: {s1.tic}, {s1.game_variables}")
print(f"s2: {s2.tic}, {s2.game_variables}")
print(np.all(s1.screen_buffer == s2.screen_buffer))
print(np.array_equal(s1.screen_buffer, s2.screen_buffer))
cv2.imshow("s1", s1.screen_buffer)
cv2.imshow("s2", s2.screen_buffer)
cv2.imshow("s1 - s2", s1.screen_buffer - s2.screen_buffer)
cv2.waitKey(int(10000))

for b in buffers:
if not np.array_equal(getattr(s1, b), getattr(s2, b)):
print("Initial states are not equal")
cv2.imshow("s1", getattr(s1, b))
cv2.imshow("s2", getattr(s2, b))
cv2.imshow("s1 - s2", getattr(s1, b) - getattr(s2, b))
cv2.waitKey(int(10000))

# assert np.array_equal(getattr(s1, b), getattr(s2, b))

for s1, s2 in zip(states_after_action[:-1], states_after_action[1:]):
assert s1.tic == s2.tic
assert np.array_equal(s1.game_variables, s2.game_variables)

if not np.array_equal(s1.screen_buffer, s2.screen_buffer):
print("States after action are not equal")
print(f"s1: {s1.tic}, {s1.game_variables}")
print(f"s2: {s2.tic}, {s2.game_variables}")
print(np.all(s1.screen_buffer == s2.screen_buffer))
print(np.array_equal(s1.screen_buffer, s2.screen_buffer))
cv2.imshow("s1", s1.screen_buffer)
cv2.imshow("s2", s2.screen_buffer)
cv2.imshow("s1 - s2", s1.screen_buffer - s2.screen_buffer)
cv2.waitKey(int(10000))

for b in buffers:
if not np.array_equal(getattr(s1, b), getattr(s2, b)):
print("States after action are not equal")
cv2.imshow("s1", getattr(s1, b))
cv2.imshow("s2", getattr(s2, b))
cv2.imshow("s1 - s2", getattr(s1, b) - getattr(s2, b))
cv2.waitKey(int(10000))

# assert np.array_equal(getattr(s1, b), getattr(s2, b))


if __name__ == "__main__":
test_seed()
17 changes: 14 additions & 3 deletions tests/test_configs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python3

# Tests for ViZDoom enums and related methods.
# Tests ViZDoom load_config method and all the config files from the scenario directory.
# This test can be run as Python script or via PyTest

import os
Expand All @@ -9,10 +9,21 @@


def test_load_config():
print("Testing load_config() and default scenarios ...")

for file in os.listdir(vzd.scenarios_path):
if file.endswith(".cfg"):
vzd.DoomGame().load_config(os.path.join(vzd.scenarios_path, file))
vzd.DoomGame().load_config(file)
game = vzd.DoomGame()

# Both should work
game.load_config(os.path.join(vzd.scenarios_path, file))
game.load_config(file)

w = game.get_screen_width()
h = game.get_screen_height()
assert (
w == 320 and h == 240
), f"Config file {file} is using non-default screen resolution: {w}x{h} instead 320x240."


if __name__ == "__main__":
Expand Down
14 changes: 7 additions & 7 deletions tests/test_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,30 @@ def _test_enums(enum_name, func_name):
]
all_values_names = [v.name for v in all_values]

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

# add test
# add_X function 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
# Check if set function overwrites previous values
set_func(all_values)
get_values_names = [v.name for v in get_func()]
assert all_values_names == get_values_names

# multiple adds
# Multiple add_X functions test
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
# Test duplicated values in set_X function
set_func(all_values + all_values)
get_values_names = [v.name for v in get_func()]
assert all_values_names == get_values_names
Expand Down
5 changes: 3 additions & 2 deletions tests/test_game_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@


def test_game_args():
print("Testing setting custom game arguments...")

game = vzd.DoomGame()
game.set_window_visible(False)
Expand All @@ -16,12 +17,12 @@ def test_game_args():
args_all = args1 + " " + args2

game.set_game_args(args_all)
assert game.get_game_args() == args_all
assert game.get_game_args() == args_all, "Game args not set correctly."

game.clear_game_args()
game.add_game_args(args1)
game.add_game_args(args2)
assert game.get_game_args() == args_all
assert game.get_game_args() == args_all, "Game args not set correctly."


if __name__ == "__main__":
Expand Down
Loading
Loading