diff --git a/.clang-tidy b/.clang-tidy index 8b97676c0..0d5484af8 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,4 +1,4 @@ -Checks: "*,-fuchsia-*,-google-*,-zircon-*,-abseil-*,-modernize-use-trailing-return-type,-llvm-*,-llvmlibc-*,-altera-struct-pack-align*" -WarningsAsErrors: "*" -HeaderFilterRegex: "" -FormatStyle: none +Checks: "modernize-*,-clang*,-android-*,-fuchsia-*,-google-*,-zircon-*,-abseil-*,-modernize-use-trailing-return-type,-llvm-*,-llvmlibc-*,-altera-struct-pack-align*" +WarningsAsErrors: "" +HeaderFilterRegex: "Griddly/Core/.*hpp" +FormatStyle: "{ BasedOnStyle: Google, ColumnLimit: 0 }" diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index fdc4c8716..24ded8bba 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -24,7 +24,7 @@ If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. mac/linux/windows] - - Version [e.g. 1.2.35] + - Version [e.g. 1.2.36] **Additional context** Add any other context about the problem here. diff --git a/CMakeLists.txt b/CMakeLists.txt index 15ea23ef2..53a75e31e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.10.0) set(CMAKE_OSX_DEPLOYMENT_TARGET "10.9" CACHE STRING "Minimum OS X deployment version") -project(Griddly VERSION 1.2.35) +project(Griddly VERSION 1.2.36) set(BINARY ${CMAKE_PROJECT_NAME}) diff --git a/bindings/python.cpp b/bindings/python.cpp index 6dfef1492..3f882dbd8 100644 --- a/bindings/python.cpp +++ b/bindings/python.cpp @@ -12,7 +12,7 @@ namespace griddly { PYBIND11_MODULE(python_griddly, m) { m.doc() = "Griddly python bindings"; - m.attr("version") = "1.2.35"; + m.attr("version") = "1.2.36"; #ifndef NDEBUG spdlog::set_level(spdlog::level::debug); diff --git a/bindings/wrapper/GDYWrapper.cpp b/bindings/wrapper/GDYWrapper.cpp index c7670623a..d0eac2331 100644 --- a/bindings/wrapper/GDYWrapper.cpp +++ b/bindings/wrapper/GDYWrapper.cpp @@ -40,7 +40,7 @@ class Py_GDYWrapper { } py::dict getActionInputMappings() const { - auto actionInputsDefinitions = gdyFactory_->getActionInputsDefinitions(); + const auto& actionInputsDefinitions = gdyFactory_->getActionInputsDefinitions(); py::dict py_actionInputsDefinitions; for (auto actionInputDefinitionPair : actionInputsDefinitions) { auto actionName = actionInputDefinitionPair.first; diff --git a/docs/conf.py b/docs/conf.py index 18ee59e13..a26661266 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -22,7 +22,7 @@ author = 'Chris Bamford' # The full version, including alpha/beta/rc tags -release = '1.2.35' +release = '1.2.36' # -- General configuration --------------------------------------------------- @@ -68,4 +68,4 @@ master_doc = 'index' def setup(app): - app.add_css_file('custom.css') \ No newline at end of file + app.add_css_file('custom.css') diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-0.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-0.png index 5c29b1032..99b5f4839 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-0.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-0.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-1.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-1.png index af8ed2503..5e2617ef5 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-1.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-1.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-2.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-2.png index 40d23010b..2d8c88ebd 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-2.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-2.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-3.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-3.png index bed940f2b..99b066699 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-3.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Block2D-3.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-0.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-0.png index dab6f0806..98c4e02b8 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-0.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-0.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-1.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-1.png index e43b91a99..30da9cdc9 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-1.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-1.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-2.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-2.png index 4e16ca6fe..76432e2db 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-2.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-2.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-3.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-3.png index fa3426c08..ff2b45eaa 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-3.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-level-Sprite2D-3.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Block2D.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Block2D.png index 7532c63f4..755575c32 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Block2D.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Block2D.png differ diff --git a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Sprite2D.png b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Sprite2D.png index 5c1c492c6..1db9c0209 100644 Binary files a/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Sprite2D.png and b/docs/games/Robot_Tag_12v12/img/Robot_Tag_12v12-tile-tagger-Sprite2D.png differ diff --git a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-1.png b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-1.png index 7662b15b5..3e6708e09 100644 Binary files a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-1.png and b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-1.png differ diff --git a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-2.png b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-2.png index 55fc04c4e..8f4d8ba76 100644 Binary files a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-2.png and b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-2.png differ diff --git a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-3.png b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-3.png index b1d24a6fb..a7228553f 100644 Binary files a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-3.png and b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Block2D-3.png differ diff --git a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-0.png b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-0.png index aa190b14c..d88b4b907 100644 Binary files a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-0.png and b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-0.png differ diff --git a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-1.png b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-1.png index ec3a96a35..32d03217c 100644 Binary files a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-1.png and b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-1.png differ diff --git a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-2.png b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-2.png index b90ce2e77..96390b7ab 100644 Binary files a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-2.png and b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-2.png differ diff --git a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-3.png b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-3.png index be96b2c87..194d8d60d 100644 Binary files a/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-3.png and b/docs/games/Robot_Tag_4v4/img/Robot_Tag_4v4-level-Sprite2D-3.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-0.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-0.png index 4d43a5f77..e12a98f0d 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-0.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-0.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-1.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-1.png index 07eaa5871..119d581d1 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-1.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-1.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-2.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-2.png index b0ff752b2..77a96189f 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-2.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-2.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-3.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-3.png index 88921f221..8e32dbff8 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-3.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Block2D-3.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-0.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-0.png index 458f4e078..a869d86d0 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-0.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-0.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-1.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-1.png index e8292f96c..a1a3b2a18 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-1.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-1.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-2.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-2.png index 44c3393d3..34b2e3275 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-2.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-2.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-3.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-3.png index 73d55deda..86bce9e79 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-3.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-level-Sprite2D-3.png differ diff --git a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-tile-tagger-Block2D.png b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-tile-tagger-Block2D.png index 755575c32..7532c63f4 100644 Binary files a/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-tile-tagger-Block2D.png and b/docs/games/Robot_Tag_8v8/img/Robot_Tag_8v8-tile-tagger-Block2D.png differ diff --git a/docs/games/img/Robot_Tag_12v12-taster.png b/docs/games/img/Robot_Tag_12v12-taster.png index fa3426c08..ff2b45eaa 100644 Binary files a/docs/games/img/Robot_Tag_12v12-taster.png and b/docs/games/img/Robot_Tag_12v12-taster.png differ diff --git a/docs/games/img/Robot_Tag_4v4-taster.png b/docs/games/img/Robot_Tag_4v4-taster.png index be96b2c87..194d8d60d 100644 Binary files a/docs/games/img/Robot_Tag_4v4-taster.png and b/docs/games/img/Robot_Tag_4v4-taster.png differ diff --git a/docs/games/img/Robot_Tag_8v8-taster.png b/docs/games/img/Robot_Tag_8v8-taster.png index 73d55deda..86bce9e79 100644 Binary files a/docs/games/img/Robot_Tag_8v8-taster.png and b/docs/games/img/Robot_Tag_8v8-taster.png differ diff --git a/python/benchmarks/benchmark.py b/python/benchmarks/benchmark.py index 997d77527..d02257237 100755 --- a/python/benchmarks/benchmark.py +++ b/python/benchmarks/benchmark.py @@ -6,7 +6,7 @@ import psutil from gym import register -#from griddly.util.wrappers import InvalidMaskingRTSWrapper +# from griddly.util.wrappers import InvalidMaskingRTSWrapper process = psutil.Process(os.getpid()) @@ -15,40 +15,45 @@ def griddly(gdy_file): from griddly import GymWrapperFactory, gd wrapper = GymWrapperFactory() - wrapper.build_gym_from_yaml("Griddly", gdy_file, player_observer_type=gd.ObserverType.SPRITE_2D, - level=0) - return gym.make(f'GDY-Griddly-v0') + wrapper.build_gym_from_yaml( + "Griddly", gdy_file, player_observer_type=gd.ObserverType.SPRITE_2D, level=0 + ) + return gym.make(f"GDY-Griddly-v0") def micro_rts_test(): import gym_microrts - return gym.make('MicrortsMining-v4') + + return gym.make("MicrortsMining-v4") def minigrid_test(): import gym_minigrid + return gym.make("MiniGrid-FourRooms-v0") def gvgai_test(): import gvgai + return gym.make("gvgai-sokoban-lvl0-v0") def gvgai_test_old(): import gym_gvgai + return gym_gvgai.make("gvgai-sokoban-lvl0-v0") -if __name__ == '__main__': +if __name__ == "__main__": # env = griddly('dmlab_pushbox.yaml') # env = minigrid_test() - env = griddly('Single-Player/Mini-Grid/minigrid-eyeball.yaml') + env = griddly("Single-Player/Mini-Grid/minigrid-eyeball.yaml") # env = micro_rts_test() - #env = griddly('MicrortsMining.yaml') + # env = griddly('MicrortsMining.yaml') # memory usage recorded in these tests is inaccurate because the GVGAI environment is in a different process # env = gvgai_test() @@ -56,7 +61,7 @@ def gvgai_test_old(): # env = griddly('Single-Player/GVGAI/sokoban.yaml') env.reset() - #env = InvalidMaskingRTSWrapper(env) + # env = InvalidMaskingRTSWrapper(env) start = timer() frames = 0 @@ -72,20 +77,20 @@ def gvgai_test_old(): # env.render() # rendered_obs = env.render(mode='rgb_array') - #state = env.get_state() + # state = env.get_state() if frames % 1000 == 0: end = timer() - fps = (frames / (end - start)) + fps = frames / (end - start) mem = process.memory_info().rss mem_samples.append(mem) fps_samples.append(fps) - print(f'fps: {fps}') - print(f'mem: {mem}') + print(f"fps: {fps}") + print(f"mem: {mem}") frames = 0 start = timer() if done: env.reset() - print(f'mean fps: {np.mean(fps_samples)}, std: {np.std(fps_samples)}') - print(f'mean mem: {np.mean(mem_samples)}') + print(f"mean fps: {np.mean(fps_samples)}, std: {np.std(fps_samples)}") + print(f"mean mem: {np.mean(mem_samples)}") diff --git a/python/docs/sphinxdocs/game_docs.py b/python/docs/sphinxdocs/game_docs.py index b1b635ff0..07918a4a6 100644 --- a/python/docs/sphinxdocs/game_docs.py +++ b/python/docs/sphinxdocs/game_docs.py @@ -9,11 +9,10 @@ from griddly.util.breakdown import EnvironmentBreakdown -class GamesToSphix(): - +class GamesToSphix: def __init__(self, docs_root, gallery_width=3): logging.basicConfig(level=logging.DEBUG) - self._logger = logging.getLogger('Game Doc Generator') + self._logger = logging.getLogger("Game Doc Generator") self._docs_root = docs_root.resolve() @@ -27,36 +26,40 @@ def _generate_object_description(self, game_description): name = game_description.name - sphinx_string = '' + sphinx_string = "" - key_table_name_header = ' * - Name ->\n' - key_table_mapchar_header = ' * - Map Char ->\n' - key_table_render_row = defaultdict(lambda: '') + key_table_name_header = " * - Name ->\n" + key_table_mapchar_header = " * - Map Char ->\n" + key_table_render_row = defaultdict(lambda: "") - sphinx_string += '.. list-table:: Tiles\n :header-rows: 2\n\n' + sphinx_string += ".. list-table:: Tiles\n :header-rows: 2\n\n" object_images = {} for object_name, object_data in game_description.objects.items(): - map_character = object_data['MapCharacter'] + map_character = object_data["MapCharacter"] if map_character is None: continue - key_table_name_header += f' - {object_name}\n' - key_table_mapchar_header += f' - `{map_character}`\n' - for observer_type_string, tile_data in object_data['Tiles'].items(): - relative_image_path = os.path.join('img', - f'{name.replace(" ", "_")}-tile-{object_name}-{observer_type_string}.png') + key_table_name_header += f" - {object_name}\n" + key_table_mapchar_header += f" - `{map_character}`\n" + for observer_type_string, tile_data in object_data["Tiles"].items(): + relative_image_path = os.path.join( + "img", + f'{name.replace(" ", "_")}-tile-{object_name}-{observer_type_string}.png', + ) object_images[relative_image_path] = tile_data["Image"] - key_table_render_row[observer_type_string] += f' - .. image:: {relative_image_path}\n' + key_table_render_row[ + observer_type_string + ] += f" - .. image:: {relative_image_path}\n" sphinx_string += key_table_name_header sphinx_string += key_table_mapchar_header for observer_type_string, key_table_data in key_table_render_row.items(): - sphinx_string += f' * - {observer_type_string}\n{key_table_data}' + sphinx_string += f" * - {observer_type_string}\n{key_table_data}" - sphinx_string += '\n\n' + sphinx_string += "\n\n" return sphinx_string, object_images def _generate_levels_description(self, game_breakdown): @@ -66,34 +69,38 @@ def _generate_levels_description(self, game_breakdown): levels = game_breakdown.levels supported_observer_types = game_breakdown.supported_observers - sphinx_string = '' + sphinx_string = "" - level_table_header = '.. list-table:: Levels\n :header-rows: 1\n\n' - level_table_header += ' * - \n' + level_table_header = ".. list-table:: Levels\n :header-rows: 1\n\n" + level_table_header += " * - \n" for observer_name, observer_type in supported_observer_types.items(): - level_table_header += f' - {observer_name}\n' + level_table_header += f" - {observer_name}\n" - level_table_string = '' + level_table_string = "" level_images = {} for level_id, level_data in levels.items(): - level_size = level_data['Size'] - level_size_string = f'{level_size[0]}x{level_size[1]}' - level_table_string += f' * - .. list-table:: \n\n' \ - f' * - Level ID\n' \ - f' - {level_id}\n' \ - f' * - Size\n' \ - f' - {level_size_string}\n' - - observer_rendered_levels = level_data['Observers'] + level_size = level_data["Size"] + level_size_string = f"{level_size[0]}x{level_size[1]}" + level_table_string += ( + f" * - .. list-table:: \n\n" + f" * - Level ID\n" + f" - {level_id}\n" + f" * - Size\n" + f" - {level_size_string}\n" + ) + + observer_rendered_levels = level_data["Observers"] for observer_name, np_level_image in observer_rendered_levels.items(): - relative_image_path = os.path.join('img', - f'{game_name.replace(" ", "_")}-level-{observer_name}-{level_id}.png') + relative_image_path = os.path.join( + "img", + f'{game_name.replace(" ", "_")}-level-{observer_name}-{level_id}.png', + ) level_images[relative_image_path] = np_level_image - level_table_string += f' - .. thumbnail:: {relative_image_path}\n' + level_table_string += f" - .. thumbnail:: {relative_image_path}\n" - level_table_string += '\n' + level_table_string += "\n" sphinx_string += level_table_header sphinx_string += level_table_string @@ -106,11 +113,11 @@ def _generate_code_example(self, game_breakdown): player_count = game_breakdown.player_count has_avatar = game_breakdown.has_avatar - formatted_game_name = name.replace(' ', '-') + formatted_game_name = name.replace(" ", "-") - wrapper = '' - imports = '' - code_example_sphinx = '' + wrapper = "" + imports = "" + code_example_sphinx = "" if player_count == 1: single_step_code = """ @@ -120,8 +127,8 @@ def _generate_code_example(self, game_breakdown): elif player_count > 1: if not has_avatar: - wrapper = 'env = InvalidMaskingRTSWrapper(env)\n' - imports = 'from griddly.util.wrappers import InvalidMaskingRTSWrapper\n' + wrapper = "env = InvalidMaskingRTSWrapper(env)\n" + imports = "from griddly.util.wrappers import InvalidMaskingRTSWrapper\n" single_step_code = """ obs, reward, done, info = env.step(env.action_space.sample()) @@ -146,8 +153,10 @@ def _generate_code_example(self, game_breakdown): env.reset() """ - code_example_sphinx += 'The most basic way to create a Griddly Gym Environment. ' \ - 'Defaults to level 0 and SPRITE_2D rendering.\n\n' + code_example_sphinx += ( + "The most basic way to create a Griddly Gym Environment. " + "Defaults to level 0 and SPRITE_2D rendering.\n\n" + ) code_example_sphinx += f'.. code-block:: python\n\n{textwrap.indent(basic_code_example, " ")}\n\n' return code_example_sphinx @@ -157,29 +166,35 @@ def _generate_actions_description(self, game_breakdown): # load a simple griddly env with each tile printed action_mappings = game_breakdown.action_mappings - sphinx_string = '' + sphinx_string = "" for action_name, action_details in action_mappings.items(): - sphinx_string += f'{action_name}\n' - sphinx_string += '^' * len(action_name) + '\n\n' + sphinx_string += f"{action_name}\n" + sphinx_string += "^" * len(action_name) + "\n\n" - mapToGrid = 'MapToGrid' in action_details and action_details['MapToGrid'] + mapToGrid = "MapToGrid" in action_details and action_details["MapToGrid"] - if 'Relative' in action_details and action_details['Relative']: - sphinx_string += ':Relative: The actions are calculated relative to the object being controlled.\n\n' - if 'Internal' in action_details and action_details['Internal']: - sphinx_string += ':Internal: This action can only be called from other actions, not by the player.\n\n' + if "Relative" in action_details and action_details["Relative"]: + sphinx_string += ":Relative: The actions are calculated relative to the object being controlled.\n\n" + if "Internal" in action_details and action_details["Internal"]: + sphinx_string += ":Internal: This action can only be called from other actions, not by the player.\n\n" if mapToGrid: - sphinx_string += ':MapToGrid: This action is mapped to any grid location.\n\n' + sphinx_string += ( + ":MapToGrid: This action is mapped to any grid location.\n\n" + ) if not mapToGrid: - sphinx_string += f'.. list-table:: \n :header-rows: 1\n\n' - sphinx_string += ' * - Action Id\n - Mapping\n' - for action_id, details in sorted(action_details['InputMappings'].items()): - description = details['Description'] if 'Description' in details else '' - sphinx_string += f' * - {action_id}\n - {description}\n' - - sphinx_string += '\n\n' + sphinx_string += f".. list-table:: \n :header-rows: 1\n\n" + sphinx_string += " * - Action Id\n - Mapping\n" + for action_id, details in sorted( + action_details["InputMappings"].items() + ): + description = ( + details["Description"] if "Description" in details else "" + ) + sphinx_string += f" * - {action_id}\n - {description}\n" + + sphinx_string += "\n\n" return sphinx_string @@ -193,49 +208,50 @@ def _generate_game_doc(self, game_breakdown, relative_gdy_path): sphinx_string = f'.. _doc_{name.lower().replace(" ", "_")}:\n\n' - sphinx_string += name + '\n' - sphinx_string += '=' * len(name) + '\n\n' + sphinx_string += name + "\n" + sphinx_string += "=" * len(name) + "\n\n" - sphinx_string +=f'.. code-block::\n\n {filename}\n\n' + sphinx_string += f".. code-block::\n\n {filename}\n\n" - sphinx_string += 'Description\n' - sphinx_string += '-------------\n\n' + sphinx_string += "Description\n" + sphinx_string += "-------------\n\n" - sphinx_string += f'{description}\n\n' + sphinx_string += f"{description}\n\n" - sphinx_string += 'Levels\n' - sphinx_string += '---------\n\n' + sphinx_string += "Levels\n" + sphinx_string += "---------\n\n" - level_sphinx_string, level_images = self._generate_levels_description(game_breakdown) + level_sphinx_string, level_images = self._generate_levels_description( + game_breakdown + ) images.update(level_images) sphinx_string += level_sphinx_string - sphinx_string += 'Code Example\n' - sphinx_string += '------------\n\n' + sphinx_string += "Code Example\n" + sphinx_string += "------------\n\n" sphinx_string += self._generate_code_example(game_breakdown) - sphinx_string += 'Objects\n' - sphinx_string += '-------\n\n' + sphinx_string += "Objects\n" + sphinx_string += "-------\n\n" - object_sphinx_string, object_images = self._generate_object_description(game_breakdown) + object_sphinx_string, object_images = self._generate_object_description( + game_breakdown + ) images.update(object_images) sphinx_string += object_sphinx_string - sphinx_string += 'Actions\n' - sphinx_string += '-------\n\n' + sphinx_string += "Actions\n" + sphinx_string += "-------\n\n" sphinx_string += self._generate_actions_description(game_breakdown) - sphinx_string += 'YAML\n' - sphinx_string += '----\n\n' - sphinx_string += '.. code-block:: YAML\n\n' + sphinx_string += "YAML\n" + sphinx_string += "----\n\n" + sphinx_string += ".. code-block:: YAML\n\n" sphinx_string += f'{textwrap.indent(game_breakdown.gdy_string, " ")}\n\n' - return { - 'sphinx': sphinx_string, - 'images': images - } + return {"sphinx": sphinx_string, "images": images} def _generate_taster_image(self, game_breakdown): @@ -244,47 +260,47 @@ def _generate_taster_image(self, game_breakdown): level_data = levels[len(levels) - 1] - if 'Isometric' in level_data['Observers']: - np_last_image = level_data['Observers']['Isometric'] - elif 'Sprite2D' in level_data['Observers']: - np_last_image = level_data['Observers']['Sprite2D'] - elif 'Block2D' in level_data['Observers']: - np_last_image = level_data['Observers']['Block2D'] + if "Isometric" in level_data["Observers"]: + np_last_image = level_data["Observers"]["Isometric"] + elif "Sprite2D" in level_data["Observers"]: + np_last_image = level_data["Observers"]["Sprite2D"] + elif "Block2D" in level_data["Observers"]: + np_last_image = level_data["Observers"]["Block2D"] else: - np_last_image = level_data['Observers']['Vector'] + np_last_image = level_data["Observers"]["Vector"] - relative_image_path = os.path.join('img', - f'{name.replace(" ", "_")}-taster.png') + relative_image_path = os.path.join( + "img", f'{name.replace(" ", "_")}-taster.png' + ) images = {relative_image_path: np_last_image} - sphinx_string = f' .. image:: {relative_image_path}\n' \ - f' :target: __relative__doc__link__\n' \ - f' :width: 200\n\n' + sphinx_string = ( + f" .. image:: {relative_image_path}\n" + f" :target: __relative__doc__link__\n" + f" :width: 200\n\n" + ) return sphinx_string, images def _generate_game_taster(self, game_breakdown): images = {} - sphinx_string = f'**{game_breakdown.name}**\n\n' + sphinx_string = f"**{game_breakdown.name}**\n\n" image_sphinx_string, taster_images = self._generate_taster_image(game_breakdown) images.update(taster_images) sphinx_string += image_sphinx_string - description = textwrap.indent(game_breakdown.description, ' ') + description = textwrap.indent(game_breakdown.description, " ") - sphinx_string += f'{description}\n' + sphinx_string += f"{description}\n" - return { - 'sphinx': sphinx_string, - 'images': images - } + return {"sphinx": sphinx_string, "images": images} def add_game(self, category, gdy_file, relative_gdy_path): game_breakdown = EnvironmentBreakdown(gdy_file) - self._logger.debug(f'Game description loaded: {game_breakdown.name}') + self._logger.debug(f"Game description loaded: {game_breakdown.name}") if game_breakdown.name not in self._env_names: self._env_names.add(game_breakdown.name) @@ -293,13 +309,13 @@ def add_game(self, category, gdy_file, relative_gdy_path): game_docs = {} - self._logger.debug(f'Generating game taster for: {game_breakdown.name}') - game_docs['taster'] = self._generate_game_taster(game_breakdown) + self._logger.debug(f"Generating game taster for: {game_breakdown.name}") + game_docs["taster"] = self._generate_game_taster(game_breakdown) - self._logger.debug(f'Generating game doc for: {game_breakdown.name}') - game_docs['doc'] = self._generate_game_doc(game_breakdown, relative_gdy_path) + self._logger.debug(f"Generating game doc for: {game_breakdown.name}") + game_docs["doc"] = self._generate_game_doc(game_breakdown, relative_gdy_path) - game_docs['breakdown'] = game_breakdown + game_docs["breakdown"] = game_breakdown self._game_documentation[category].append(game_docs) @@ -308,96 +324,110 @@ def generate(self): # generate all the images renderer = RenderToFile() - sphinx_string = '.. _doc_games:\n\n' + sphinx_string = ".. _doc_games:\n\n" - taster_img_path = self._docs_root.joinpath('img') + taster_img_path = self._docs_root.joinpath("img") taster_img_path.mkdir(parents=True, exist_ok=True) for category, games_in_category in self._game_documentation.items(): - sphinx_string += '*' * len(category) + '\n' - sphinx_string += f'{category}\n' - sphinx_string += '*' * len(category) + '\n\n' + sphinx_string += "*" * len(category) + "\n" + sphinx_string += f"{category}\n" + sphinx_string += "*" * len(category) + "\n\n" # Build toc tree for index of games - sphinx_string += '.. toctree::\n' - sphinx_string += ' :hidden:\n\n' + sphinx_string += ".. toctree::\n" + sphinx_string += " :hidden:\n\n" for g, game_data in enumerate(games_in_category): - game_breakdown = game_data['breakdown'] + game_breakdown = game_data["breakdown"] sphinx_string += f' {game_breakdown.name.replace(" ", "_")}/index\n' - sphinx_string += '\n' + sphinx_string += "\n" # Build games gallery - sphinx_string += '.. list-table::\n' - sphinx_string += ' :class: game-gallery\n\n' + sphinx_string += ".. list-table::\n" + sphinx_string += " :class: game-gallery\n\n" remaining_cols = 0 for g, game_data in enumerate(games_in_category): - game_breakdown = game_data['breakdown'] + game_breakdown = game_data["breakdown"] name = game_breakdown.name # Create doc page - doc_data = game_data['doc'] - doc_sphinx = doc_data['sphinx'] - doc_images = doc_data['images'] + doc_data = game_data["doc"] + doc_sphinx = doc_data["sphinx"] + doc_images = doc_data["images"] game_doc_root = Path(f'{name.replace(" ", "_")}/') doc_sphinx_root = self._docs_root.joinpath(game_doc_root) - doc_image_root = doc_sphinx_root.joinpath('img') + doc_image_root = doc_sphinx_root.joinpath("img") doc_image_root.mkdir(parents=True, exist_ok=True) # Save the doc images for doc_image_filename, np_doc_image in doc_images.items(): - self._logger.debug(f'Writing image {doc_image_filename}') - renderer.render(np_doc_image.swapaxes(0, 2), doc_sphinx_root.joinpath(doc_image_filename)) + self._logger.debug(f"Writing image {doc_image_filename}") + renderer.render( + np_doc_image.swapaxes(0, 2), + doc_sphinx_root.joinpath(doc_image_filename), + ) - relative_doc_path = game_doc_root.joinpath('index.rst') + relative_doc_path = game_doc_root.joinpath("index.rst") - with open(self._docs_root.joinpath(relative_doc_path), 'w') as f: - self._logger.debug(f'Writing doc {relative_doc_path}') + with open(self._docs_root.joinpath(relative_doc_path), "w") as f: + self._logger.debug(f"Writing doc {relative_doc_path}") f.write(doc_sphinx) - taster_data = game_data['taster'] - taster_sphinx = taster_data['sphinx'] - taster_images = taster_data['images'] + taster_data = game_data["taster"] + taster_sphinx = taster_data["sphinx"] + taster_images = taster_data["images"] - taster_sphinx = taster_sphinx.replace('__relative__doc__link__', - str(relative_doc_path).replace('rst', 'html')) + taster_sphinx = taster_sphinx.replace( + "__relative__doc__link__", + str(relative_doc_path).replace("rst", "html"), + ) col_index = g % self._gallery_width if col_index == 0: - sphinx_string += f' * - {taster_sphinx}' + sphinx_string += f" * - {taster_sphinx}" else: - sphinx_string += f' - {taster_sphinx}' + sphinx_string += f" - {taster_sphinx}" # Save the taster images for taster_image_filename, np_taster_image in taster_images.items(): - renderer.render(np_taster_image.swapaxes(0, 2), self._docs_root.joinpath(taster_image_filename)) + renderer.render( + np_taster_image.swapaxes(0, 2), + self._docs_root.joinpath(taster_image_filename), + ) remaining_cols = 2 - col_index # Make sure the last row has the same number of columns even if there are no games for _ in range(remaining_cols): - sphinx_string += f' - \n' - sphinx_string += '\n\n' + sphinx_string += f" - \n" + sphinx_string += "\n\n" - with open(self._docs_root.joinpath('index.rst'), 'w') as f: + with open(self._docs_root.joinpath("index.rst"), "w") as f: f.write(sphinx_string) -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Automatically generate documentation for games.') - parser.add_argument('--filename-suffix', default='.yaml', help='Suffix for filenames to create documentation') +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Automatically generate documentation for games." + ) + parser.add_argument( + "--filename-suffix", + default=".yaml", + help="Suffix for filenames to create documentation", + ) args = parser.parse_args() filename_suffix = args.filename_suffix - games_path = Path('../../../resources/games') + games_path = Path("../../../resources/games") - docs_root = Path('../../../docs/games') + docs_root = Path("../../../docs/games") generator = GamesToSphix(docs_root) for directory_dir, directory_names, filenames in os.walk(games_path): directory_path = Path(directory_dir) @@ -405,7 +435,7 @@ def generate(self): continue gdy_subdirectory = directory_path.relative_to(games_path) - print(f'Directories: {gdy_subdirectory}') + print(f"Directories: {gdy_subdirectory}") for filename in filenames: if filename.endswith(filename_suffix): diff --git a/python/docs/sphinxdocs/schema_docs.py b/python/docs/sphinxdocs/schema_docs.py index c25d9568f..086a4c664 100644 --- a/python/docs/sphinxdocs/schema_docs.py +++ b/python/docs/sphinxdocs/schema_docs.py @@ -5,12 +5,19 @@ from collections import defaultdict -class ObjectToSphinx(): - - def __init__(self, node_name, node, id_to_nodes, refs_to_node, parent_node_path=None, is_array_item=False, - option=None): - - self._sphinx_string = '' +class ObjectToSphinx: + def __init__( + self, + node_name, + node, + id_to_nodes, + refs_to_node, + parent_node_path=None, + is_array_item=False, + option=None, + ): + + self._sphinx_string = "" self._id_to_nodes = id_to_nodes self._refs_to_node = refs_to_node @@ -22,9 +29,9 @@ def __init__(self, node_name, node, id_to_nodes, refs_to_node, parent_node_path= if parent_node_path is not None: if self._option is not None: - self._node_path = parent_node_path + '/oneOf/' + str(option) + self._node_path = parent_node_path + "/oneOf/" + str(option) else: - self._node_path = parent_node_path + '/' + node_name + self._node_path = parent_node_path + "/" + node_name else: self._node_path = node_name @@ -32,89 +39,106 @@ def _get_or_default(self, node, key, default=None): return default if key not in node else node[key] def _generate_sphinx_node_description(self, node, node_name): - node_type = node['type'] if 'type' in node else 'any' - node_description = '' + node_type = node["type"] if "type" in node else "any" + node_description = "" description_table_map = {} - if node_type != 'any': - description_table_map['Data Type'] = node_type + if node_type != "any": + description_table_map["Data Type"] = node_type if node_name is not None and not self._is_array_item: - description_table_map['YAML Key'] = f'``{node_name}``' + description_table_map["YAML Key"] = f"``{node_name}``" node_description += f':Description: {node["description"]}\n\n' - if node_type == 'array': - if 'maxItems' in node: - description_table_map['Max Items'] = node['maxItems'] - if 'minItems' in node: - description_table_map['Min Items'] = node['minItems'] + if node_type == "array": + if "maxItems" in node: + description_table_map["Max Items"] = node["maxItems"] + if "minItems" in node: + description_table_map["Min Items"] = node["minItems"] else: - if 'minValue' in node: - description_table_map['Min Value'] = f'``{node["minValue"]}``' - if 'maxValue' in node: - description_table_map['Max Value'] = f'``{node["maxValue"]}``' + if "minValue" in node: + description_table_map["Min Value"] = f'``{node["minValue"]}``' + if "maxValue" in node: + description_table_map["Max Value"] = f'``{node["maxValue"]}``' - if 'oneOf' in node: + if "oneOf" in node: one_of_table_data = [] - for option in node['oneOf']: - if '$ref' in option: - (option_name, option_path, option) = self._id_to_nodes[option['$ref']] + for option in node["oneOf"]: + if "$ref" in option: + (option_name, option_path, option) = self._id_to_nodes[ + option["$ref"] + ] - option_type = option['type'] - option_value = '' - if option_type == 'string': - if 'const' in option: + option_type = option["type"] + option_value = "" + if option_type == "string": + if "const" in option: option_value = f'``{option["const"]}``' - elif 'pattern' in option: + elif "pattern" in option: option_value = f'``{option["pattern"]}``' else: - option_value = f'``[string]``' - elif option_type == 'integer': - option_value = '``[integer]``' - elif option_type == 'object': - option_node_title = option['title'] - option_node_id = option['$id'] - option_value = f':ref:`{option_node_title} <{option_node_id}>`' - elif option_type == 'array': - option_node_title = option['title'] - if '$id' in option: - option_node_id = option['$id'] - option_value = f':ref:`{option_node_title} <{option_node_id}>`' + option_value = f"``[string]``" + elif option_type == "integer": + option_value = "``[integer]``" + elif option_type == "object": + option_node_title = option["title"] + option_node_id = option["$id"] + option_value = f":ref:`{option_node_title} <{option_node_id}>`" + elif option_type == "array": + option_node_title = option["title"] + if "$id" in option: + option_node_id = option["$id"] + option_value = ( + f":ref:`{option_node_title} <{option_node_id}>`" + ) else: - option_value = f'{option_node_title}' + option_value = f"{option_node_title}" one_of_table_data.append( - {'Value': option_value, 'Type': option_type, 'Description': option['description']}) - - node_description += f':Possible Values:\n\n' + self._generate_sphinx_list_table( - ['Value', 'Type', 'Description'], one_of_table_data) - if 'enum' in node: - description_table_map['Allowed Values'] = f'``{"``, ``".join(node["enum"])}``' - if 'const' in node: - description_table_map['Allowed Values'] = f'``{node["const"]}``' - if 'default' in node: - description_table_map['Default Value'] = f'``{node["default"]}``' - - node_description += self._generate_sphinx_list_table(description_table_map.keys(), [description_table_map]) + { + "Value": option_value, + "Type": option_type, + "Description": option["description"], + } + ) + + node_description += ( + f":Possible Values:\n\n" + + self._generate_sphinx_list_table( + ["Value", "Type", "Description"], one_of_table_data + ) + ) + if "enum" in node: + description_table_map[ + "Allowed Values" + ] = f'``{"``, ``".join(node["enum"])}``' + if "const" in node: + description_table_map["Allowed Values"] = f'``{node["const"]}``' + if "default" in node: + description_table_map["Default Value"] = f'``{node["default"]}``' + + node_description += self._generate_sphinx_list_table( + description_table_map.keys(), [description_table_map] + ) return node_description def _generate_sphinx_list_table(self, headers, data_rows): if len(headers) == 0: - return '' + return "" - sphinx_list_table = '.. list-table::\n\n' + sphinx_list_table = ".. list-table::\n\n" - sphinx_headers = '' + sphinx_headers = "" for i, header in enumerate(headers): if i == 0: - sphinx_headers += f' * - **{header}**\n' + sphinx_headers += f" * - **{header}**\n" else: - sphinx_headers += f' - **{header}**\n' + sphinx_headers += f" - **{header}**\n" - sphinx_values = '' + sphinx_values = "" for row in data_rows: for i, header in enumerate(headers): if i == 0: @@ -122,177 +146,264 @@ def _generate_sphinx_list_table(self, headers, data_rows): else: sphinx_values += f' - {self._get_or_default(row, header, "")}\n' - sphinx_list_table += sphinx_headers + sphinx_values + '\n\n' + sphinx_list_table += sphinx_headers + sphinx_values + "\n\n" return sphinx_list_table def register_definitions(self, definition_node): if len(definition_node) > 0: for definition_name, new_definition in definition_node.items(): - definition_path = self._node_path + '/' + definition_name - self._id_to_nodes[new_definition['$id']] = (definition_name, definition_path, new_definition) + definition_path = self._node_path + "/" + definition_name + self._id_to_nodes[new_definition["$id"]] = ( + definition_name, + definition_path, + new_definition, + ) def parse_definitions(self, definition_node): if len(definition_node) > 0: for defined_node_name, defined_node in definition_node.items(): - generator = ObjectToSphinx(defined_node_name, defined_node, self._id_to_nodes, self._refs_to_node, - parent_node_path=self._node_path, is_array_item=True) + generator = ObjectToSphinx( + defined_node_name, + defined_node, + self._id_to_nodes, + self._refs_to_node, + parent_node_path=self._node_path, + is_array_item=True, + ) generator.generate() def parse_items(self, item_node, parent_node_name, parent_node_path, parent_node): array_type_table_data = [] - toc_references = '' + toc_references = "" if len(item_node) > 0: - if '$ref' in item_node: - ref = item_node['$ref'] - self._refs_to_node[ref].append((parent_node_name, parent_node_path, parent_node)) - (referenced_node_name, referenced_node_path, referenced_node) = self._id_to_nodes[ref] - referenced_node_title = self._get_or_default(referenced_node, 'title', 'FIXME') - referenced_node_description = self._get_or_default(referenced_node, 'description', '') + if "$ref" in item_node: + ref = item_node["$ref"] + self._refs_to_node[ref].append( + (parent_node_name, parent_node_path, parent_node) + ) + ( + referenced_node_name, + referenced_node_path, + referenced_node, + ) = self._id_to_nodes[ref] + referenced_node_title = self._get_or_default( + referenced_node, "title", "FIXME" + ) + referenced_node_description = self._get_or_default( + referenced_node, "description", "" + ) referenced_node_id = item_node["$ref"] - toc_references += f' {referenced_node_path}/index\n' - self._sphinx_string += f':Array Type:\n\n' - - array_type_table_data = [{ - 'Type': f' :ref:`{referenced_node_title}<{referenced_node_id}>` ', - 'Description': referenced_node_description - }] - - elif 'oneOf' in item_node: - self._sphinx_string += f':Choose Between:\n\n' - for option in item_node['oneOf']: - if '$ref' in option: - ref = option['$ref'] - self._refs_to_node[ref].append((parent_node_name, parent_node_path, parent_node)) - (referenced_node_name, referenced_node_path, referenced_node) = self._id_to_nodes[ref] - referenced_node_title = self._get_or_default(referenced_node, 'title', 'FIXME') - referenced_node_description = self._get_or_default(referenced_node, 'description', '') + toc_references += f" {referenced_node_path}/index\n" + self._sphinx_string += f":Array Type:\n\n" + + array_type_table_data = [ + { + "Type": f" :ref:`{referenced_node_title}<{referenced_node_id}>` ", + "Description": referenced_node_description, + } + ] + + elif "oneOf" in item_node: + self._sphinx_string += f":Choose Between:\n\n" + for option in item_node["oneOf"]: + if "$ref" in option: + ref = option["$ref"] + self._refs_to_node[ref].append( + (parent_node_name, parent_node_path, parent_node) + ) + ( + referenced_node_name, + referenced_node_path, + referenced_node, + ) = self._id_to_nodes[ref] + referenced_node_title = self._get_or_default( + referenced_node, "title", "FIXME" + ) + referenced_node_description = self._get_or_default( + referenced_node, "description", "" + ) referenced_node_id = option["$ref"] - toc_references += f' {referenced_node_path}/index\n' - array_type_table_data.append({ - 'Type': f' :ref:`{referenced_node_title}<{referenced_node_id}>` ', - 'Description': referenced_node_description - }) - - - elif 'anyOf' in item_node: - self._sphinx_string += f':Array Types:\n\n' - for option in item_node['anyOf']: - if '$ref' in option: - ref = option['$ref'] - self._refs_to_node[ref].append((parent_node_name, parent_node_path, parent_node)) - (referenced_node_name, referenced_node_path, referenced_node) = self._id_to_nodes[ref] - referenced_node_title = self._get_or_default(referenced_node, 'title', 'FIXME') - referenced_node_description = self._get_or_default(referenced_node, 'description', '') + toc_references += f" {referenced_node_path}/index\n" + array_type_table_data.append( + { + "Type": f" :ref:`{referenced_node_title}<{referenced_node_id}>` ", + "Description": referenced_node_description, + } + ) + + elif "anyOf" in item_node: + self._sphinx_string += f":Array Types:\n\n" + for option in item_node["anyOf"]: + if "$ref" in option: + ref = option["$ref"] + self._refs_to_node[ref].append( + (parent_node_name, parent_node_path, parent_node) + ) + ( + referenced_node_name, + referenced_node_path, + referenced_node, + ) = self._id_to_nodes[ref] + referenced_node_title = self._get_or_default( + referenced_node, "title", "FIXME" + ) + referenced_node_description = self._get_or_default( + referenced_node, "description", "" + ) referenced_node_id = option["$ref"] - toc_references += f' {referenced_node_path}/index\n' - array_type_table_data.append({ - 'Type': f' :ref:`{referenced_node_title}<{referenced_node_id}>` ', - 'Description': referenced_node_description - }) + toc_references += f" {referenced_node_path}/index\n" + array_type_table_data.append( + { + "Type": f" :ref:`{referenced_node_title}<{referenced_node_id}>` ", + "Description": referenced_node_description, + } + ) else: - generator = ObjectToSphinx('items', item_node, self._id_to_nodes, self._refs_to_node, - parent_node_path=self._node_path, is_array_item=True) + generator = ObjectToSphinx( + "items", + item_node, + self._id_to_nodes, + self._refs_to_node, + parent_node_path=self._node_path, + is_array_item=True, + ) generator.generate() - toc_references += f' items/index\n' + toc_references += f" items/index\n" - item_node_description = item_node['title'] - item_node_title = item_node['title'] - item_node_id = item_node['$id'] + item_node_description = item_node["title"] + item_node_title = item_node["title"] + item_node_id = item_node["$id"] - self._sphinx_string += f':Array Type: \n\n' - array_type_table_data = [{ - 'Type': f' :ref:`{item_node_title}<{item_node_id}>` ', - 'Description': item_node_description - }] + self._sphinx_string += f":Array Type: \n\n" + array_type_table_data = [ + { + "Type": f" :ref:`{item_node_title}<{item_node_id}>` ", + "Description": item_node_description, + } + ] - self._sphinx_string += self._generate_sphinx_list_table(['Type', 'Description'], - array_type_table_data) + self._sphinx_string += self._generate_sphinx_list_table( + ["Type", "Description"], array_type_table_data + ) # generate toc tree for the array item - self._sphinx_string += '.. toctree:: \n :maxdepth: 5\n :hidden:\n\n' + self._sphinx_string += ".. toctree:: \n :maxdepth: 5\n :hidden:\n\n" self._sphinx_string += toc_references def parse_properties(self, properties_node, required_properties=None): if len(properties_node) > 0: data_rows = [] - self._sphinx_string += ':Properties:\n\n' + self._sphinx_string += ":Properties:\n\n" for property_name, new_property in properties_node.items(): - property_id = '' - if '$ref' in new_property: - property_id = new_property['$ref'] + property_id = "" + if "$ref" in new_property: + property_id = new_property["$ref"] else: - property_id = new_property['$id'] - - is_required = required_properties is not None and (property_name in required_properties) - required_img = '``true``' if is_required else '' - data_rows.append({'Property': f' :ref:`{property_name} <{property_id}>` ', 'Required': required_img}) - - self._sphinx_string += self._generate_sphinx_list_table(['Property', 'Required'], data_rows) + property_id = new_property["$id"] + + is_required = required_properties is not None and ( + property_name in required_properties + ) + required_img = "``true``" if is_required else "" + data_rows.append( + { + "Property": f" :ref:`{property_name} <{property_id}>` ", + "Required": required_img, + } + ) + + self._sphinx_string += self._generate_sphinx_list_table( + ["Property", "Required"], data_rows + ) for child_node_name, child_node in properties_node.items(): - if '$ref' not in child_node: - generator = ObjectToSphinx(child_node_name, child_node, self._id_to_nodes, self._refs_to_node, - parent_node_path=self._node_path) + if "$ref" not in child_node: + generator = ObjectToSphinx( + child_node_name, + child_node, + self._id_to_nodes, + self._refs_to_node, + parent_node_path=self._node_path, + ) generator.generate() # generate toc tree for these properties - self._sphinx_string += '.. toctree:: \n :hidden:\n\n' + self._sphinx_string += ".. toctree:: \n :hidden:\n\n" for child_node_name, child_node in properties_node.items(): - if '$ref' in child_node: - ref = child_node['$ref'] - (referenced_node_name, referenced_node_path, referenced_node) = self._id_to_nodes[ref] - self._sphinx_string += f' {referenced_node_path}/index\n' + if "$ref" in child_node: + ref = child_node["$ref"] + ( + referenced_node_name, + referenced_node_path, + referenced_node, + ) = self._id_to_nodes[ref] + self._sphinx_string += f" {referenced_node_path}/index\n" else: - self._sphinx_string += f' {child_node_name}/index\n' + self._sphinx_string += f" {child_node_name}/index\n" def generate(self): print(self._node_name) - self._id_to_nodes[self._node['$id']] = (self._node_name, self._node_path, self._node) + self._id_to_nodes[self._node["$id"]] = ( + self._node_name, + self._node_path, + self._node, + ) self._sphinx_string += f'.. _{self._node["$id"]}:\n\n' self._sphinx_string += f'.. {self._node["$id"]}\n\n' - title = self._get_or_default(self._node, 'title', 'FIXME') - self._sphinx_string += title + '\n' - self._sphinx_string += '=' * len(title) + '\n\n' + title = self._get_or_default(self._node, "title", "FIXME") + self._sphinx_string += title + "\n" + self._sphinx_string += "=" * len(title) + "\n\n" # Create the description - self._sphinx_string += self._generate_sphinx_node_description(self._node, self._node_name) + self._sphinx_string += self._generate_sphinx_node_description( + self._node, self._node_name + ) - if 'definitions' in self._node: - self.register_definitions(self._node['definitions']) + if "definitions" in self._node: + self.register_definitions(self._node["definitions"]) - if 'items' in self._node: - self.parse_items(self._node['items'], parent_node_name=self._node_name, parent_node_path=self._node_path, - parent_node=self._node) + if "items" in self._node: + self.parse_items( + self._node["items"], + parent_node_name=self._node_name, + parent_node_path=self._node_path, + parent_node=self._node, + ) - if 'properties' in self._node: - required_properties = self._get_or_default(self._node, 'required', []) - self.parse_properties(self._node['properties'], required_properties) + if "properties" in self._node: + required_properties = self._get_or_default(self._node, "required", []) + self.parse_properties(self._node["properties"], required_properties) - if 'definitions' in self._node: - self.parse_definitions(self._node['definitions']) + if "definitions" in self._node: + self.parse_definitions(self._node["definitions"]) - file_path = Path(f'../../../docs/{self._node_path}') + file_path = Path(f"../../../docs/{self._node_path}") file_path.mkdir(parents=True, exist_ok=True) - with open(f'{file_path.resolve()}/index.rst', 'w') as f: + with open(f"{file_path.resolve()}/index.rst", "w") as f: f.write(self._sphinx_string) def write_doc(schema, schema_title): - generator = ObjectToSphinx(schema_title, schema, id_to_nodes={}, parent_node_path='/reference/GDY', - refs_to_node=defaultdict(list)) + generator = ObjectToSphinx( + schema_title, + schema, + id_to_nodes={}, + parent_node_path="/reference/GDY", + refs_to_node=defaultdict(list), + ) generator.generate() -if __name__ == '__main__': - with open(os.path.realpath('../../../resources/gdy-schema.json')) as schema_file: +if __name__ == "__main__": + with open(os.path.realpath("../../../resources/gdy-schema.json")) as schema_file: gdy_schema = json.load(schema_file) - write_doc(gdy_schema['properties']['Environment'], 'Environment') - write_doc(gdy_schema['properties']['Objects'], 'Objects') - write_doc(gdy_schema['properties']['Actions'], 'Actions') + write_doc(gdy_schema["properties"]["Environment"], "Environment") + write_doc(gdy_schema["properties"]["Objects"], "Objects") + write_doc(gdy_schema["properties"]["Actions"], "Actions") diff --git a/python/examples/AStar Search/astar.py b/python/examples/AStar Search/astar.py index 1483ec4e8..74c183128 100644 --- a/python/examples/AStar Search/astar.py +++ b/python/examples/AStar Search/astar.py @@ -3,10 +3,10 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'astar_opponent_environment' + name = "astar_opponent_environment" current_path = os.path.dirname(os.path.realpath(__file__)) @@ -23,23 +23,25 @@ # level=0) # Uncommment to see multiple spiders chasing! - env = GymWrapper('astar_opponent_rotation_actions_environment.yaml', - player_observer_type=gd.ObserverType.VECTOR, - global_observer_type=gd.ObserverType.SPRITE_2D, - level=1) + env = GymWrapper( + "astar_opponent_rotation_actions_environment.yaml", + player_observer_type=gd.ObserverType.VECTOR, + global_observer_type=gd.ObserverType.SPRITE_2D, + level=1, + ) env.reset() global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(1000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) diff --git a/python/examples/AStar Search/astar_opponent_rotation_actions_environment.yaml b/python/examples/AStar Search/astar_opponent_rotation_actions_environment.yaml index 695287cbd..eed50107f 100644 --- a/python/examples/AStar Search/astar_opponent_rotation_actions_environment.yaml +++ b/python/examples/AStar Search/astar_opponent_rotation_actions_environment.yaml @@ -176,4 +176,4 @@ Objects: - oryx/oryx_fantasy/wall2-15.png Block2D: - Color: [ 0.5, 0.5, 0.5 ] - Shape: square \ No newline at end of file + Shape: square diff --git a/python/examples/Custom Shaders/Global Lighting/lighting_graphs.py b/python/examples/Custom Shaders/Global Lighting/lighting_graphs.py index fb9324ac8..dd4638b93 100644 --- a/python/examples/Custom Shaders/Global Lighting/lighting_graphs.py +++ b/python/examples/Custom Shaders/Global Lighting/lighting_graphs.py @@ -15,13 +15,14 @@ def print_day_night_naive(): fig.savefig("daynight_naive.png") + def print_day_night_better(): x = np.arange(0, 1000) - y = np.minimum(1, np.cos((np.pi*x)/360)+1) + y = np.minimum(1, np.cos((np.pi * x) / 360) + 1) fig, ax = plt.subplots() - ax.plot(x,y) + ax.plot(x, y) ax.set_title("Day/Night Cycle") ax.set_xlabel("_steps") ax.set_ylabel("Light Level") diff --git a/python/examples/Custom Shaders/Global Lighting/main.py b/python/examples/Custom Shaders/Global Lighting/main.py index 3ad8719d4..205cad052 100644 --- a/python/examples/Custom Shaders/Global Lighting/main.py +++ b/python/examples/Custom Shaders/Global Lighting/main.py @@ -3,38 +3,40 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder, RenderToFile -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'projectiles_env' + name = "projectiles_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('global_lighting.yaml', - shader_path='shaders', - player_observer_type=gd.ObserverType.SPRITE_2D, - global_observer_type=gd.ObserverType.SPRITE_2D, - level=0) + env = GymWrapper( + "global_lighting.yaml", + shader_path="shaders", + player_observer_type=gd.ObserverType.SPRITE_2D, + global_observer_type=gd.ObserverType.SPRITE_2D, + level=0, + ) env.reset() - reset_global_obs = env.render(observer='global', mode='rgb_array') - reset_player_obs = env.render(mode='rgb_array') + reset_global_obs = env.render(observer="global", mode="rgb_array") + reset_player_obs = env.render(mode="rgb_array") render_to_file = RenderToFile() - render_to_file.render(reset_global_obs, 'reset_global.png') - render_to_file.render(reset_player_obs, 'reset_partial.png') + render_to_file.render(reset_global_obs, "reset_global.png") + render_to_file.render(reset_player_obs, "reset_partial.png") global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(1000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) if done: env.reset() - global_recorder.close() \ No newline at end of file + global_recorder.close() diff --git a/python/examples/Custom Shaders/Health Bars/main.py b/python/examples/Custom Shaders/Health Bars/main.py index d796a4324..7902deadd 100644 --- a/python/examples/Custom Shaders/Health Bars/main.py +++ b/python/examples/Custom Shaders/Health Bars/main.py @@ -3,38 +3,40 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder, RenderToFile -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'projectiles_env' + name = "projectiles_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('health_bars.yaml', - shader_path='shaders', - player_observer_type=gd.ObserverType.SPRITE_2D, - global_observer_type=gd.ObserverType.SPRITE_2D, - level=0) + env = GymWrapper( + "health_bars.yaml", + shader_path="shaders", + player_observer_type=gd.ObserverType.SPRITE_2D, + global_observer_type=gd.ObserverType.SPRITE_2D, + level=0, + ) env.reset() - reset_global_obs = env.render(observer='global', mode='rgb_array') - reset_player_obs = env.render(mode='rgb_array') + reset_global_obs = env.render(observer="global", mode="rgb_array") + reset_player_obs = env.render(mode="rgb_array") render_to_file = RenderToFile() - render_to_file.render(reset_global_obs, 'reset_global.png') - render_to_file.render(reset_player_obs, 'reset_partial.png') + render_to_file.render(reset_global_obs, "reset_global.png") + render_to_file.render(reset_player_obs, "reset_partial.png") global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(1000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) if done: env.reset() - global_recorder.close() \ No newline at end of file + global_recorder.close() diff --git a/python/examples/Custom Shaders/Object Lighting/lighting_graphs.py b/python/examples/Custom Shaders/Object Lighting/lighting_graphs.py index d98b64978..e23d1b96b 100644 --- a/python/examples/Custom Shaders/Object Lighting/lighting_graphs.py +++ b/python/examples/Custom Shaders/Object Lighting/lighting_graphs.py @@ -1,9 +1,9 @@ import matplotlib.pyplot as plt import numpy as np -def distance(a, b): - return np.abs(a-b) +def distance(a, b): + return np.abs(a - b) def plot_lighting_distance(light_objects, filename): @@ -13,11 +13,10 @@ def plot_lighting_distance(light_objects, filename): fig, ax = plt.subplots() for lo in light_objects: - ax.axvline(x=lo, c='r') - y += 1.0/np.power(distance(lo, x) / 30.0, 2.0) - 0.1 - - y = np.maximum(0,np.minimum(1.0, y)) + ax.axvline(x=lo, c="r") + y += 1.0 / np.power(distance(lo, x) / 30.0, 2.0) - 0.1 + y = np.maximum(0, np.minimum(1.0, y)) ax.plot(x, y) ax.set_title("Object Light Levels") @@ -30,6 +29,7 @@ def plot_lighting_distance(light_objects, filename): def print_lighting_single(): plot_lighting_distance([100.0], "lighting_single.png") + def print_lighting_multiple(): plot_lighting_distance([100.0, 300.0], "lighting_multiple.png") diff --git a/python/examples/Custom Shaders/Object Lighting/main.py b/python/examples/Custom Shaders/Object Lighting/main.py index a02835645..5c27808e7 100644 --- a/python/examples/Custom Shaders/Object Lighting/main.py +++ b/python/examples/Custom Shaders/Object Lighting/main.py @@ -3,38 +3,40 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder, RenderToFile -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'projectiles_env' + name = "projectiles_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('object_lighting.yaml', - shader_path='shaders', - player_observer_type=gd.ObserverType.SPRITE_2D, - global_observer_type=gd.ObserverType.SPRITE_2D, - level=0) + env = GymWrapper( + "object_lighting.yaml", + shader_path="shaders", + player_observer_type=gd.ObserverType.SPRITE_2D, + global_observer_type=gd.ObserverType.SPRITE_2D, + level=0, + ) env.reset() - reset_global_obs = env.render(observer='global', mode='rgb_array') - reset_player_obs = env.render(mode='rgb_array') + reset_global_obs = env.render(observer="global", mode="rgb_array") + reset_player_obs = env.render(mode="rgb_array") render_to_file = RenderToFile() - render_to_file.render(reset_global_obs, 'reset_global.png') - render_to_file.render(reset_player_obs, 'reset_partial.png') + render_to_file.render(reset_global_obs, "reset_global.png") + render_to_file.render(reset_player_obs, "reset_partial.png") global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(1000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) if done: env.reset() - global_recorder.close() \ No newline at end of file + global_recorder.close() diff --git a/python/examples/Level Design/main.py b/python/examples/Level Design/main.py index 41d640c8c..348f00ecb 100644 --- a/python/examples/Level Design/main.py +++ b/python/examples/Level Design/main.py @@ -3,43 +3,41 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import RenderToFile -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'levels_env' + name = "levels_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('levels.yaml', - player_observer_type=gd.ObserverType.BLOCK_2D, - global_observer_type=gd.ObserverType.BLOCK_2D) + env = GymWrapper( + "levels.yaml", + player_observer_type=gd.ObserverType.BLOCK_2D, + global_observer_type=gd.ObserverType.BLOCK_2D, + ) image_renderer = RenderToFile() for i in range(3): env.reset(level_id=i) - obs = env.render(mode='rgb_array', observer='global') + obs = env.render(mode="rgb_array", observer="global") image_renderer.render(obs, f"level_{i}_global.png") if i > 0: - obs = env.render(mode='rgb_array', observer=0) + obs = env.render(mode="rgb_array", observer=0) image_renderer.render(obs, f"level_{i}_player_1.png") - obs = env.render(mode='rgb_array', observer=1) + obs = env.render(mode="rgb_array", observer=1) image_renderer.render(obs, f"level_{i}_player_2.png") - - - level_string = \ -""". c c c c c c . . c c c c c c . . c c . c c c c c c . . c c c c c c . . c c . . . . . . c c . . . . c c . + level_string = """. c c c c c c . . c c c c c c . . c c . c c c c c c . . c c c c c c . . c c . . . . . . c c . . . . c c . c c . . . . . . . c c . . . c c . c c . c c . . . c c . c c . . . c c . c c . . . . . . . c c . . c c . . c c . . . c c c . c c c c c c . . c c . c c . . . c c . c c . . . c c . c c . . . . . . . . c c c c . . . c c . . . . c c . c c . . . c c . c c . c c . . . c c . c c . . . c c . c c . . . . . . . . . c c . . . . . c c c c c c . . c c . . . c c . c c . c c c c c c . . c c c c c c . . c c c c c c c . . . . c c . . . . """ env.reset(level_string=level_string) - obs = env.render(mode='rgb_array', observer='global') + obs = env.render(mode="rgb_array", observer="global") image_renderer.render(obs, f"custom_level_global.png") - obs = env.render(mode='rgb_array', observer=0) + obs = env.render(mode="rgb_array", observer=0) image_renderer.render(obs, f"custom_level_string_player_1.png") - obs = env.render(mode='rgb_array', observer=1) + obs = env.render(mode="rgb_array", observer=1) image_renderer.render(obs, f"custom_level_string_player_2.png") - diff --git a/python/examples/Projectiles/main.py b/python/examples/Projectiles/main.py index 813b848d4..bb90cbaa8 100644 --- a/python/examples/Projectiles/main.py +++ b/python/examples/Projectiles/main.py @@ -3,30 +3,32 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'projectiles_env' + name = "projectiles_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('projectiles.yaml', - player_observer_type=gd.ObserverType.ISOMETRIC, - global_observer_type=gd.ObserverType.ISOMETRIC, - level=0) + env = GymWrapper( + "projectiles.yaml", + player_observer_type=gd.ObserverType.ISOMETRIC, + global_observer_type=gd.ObserverType.ISOMETRIC, + level=0, + ) env.reset() global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(10000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) diff --git a/python/examples/Stochasticity/main.py b/python/examples/Stochasticity/main.py index 0017acf84..e863d9c8c 100644 --- a/python/examples/Stochasticity/main.py +++ b/python/examples/Stochasticity/main.py @@ -3,31 +3,33 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'stochasticity_env' + name = "stochasticity_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('stochasticity.yaml', - player_observer_type=gd.ObserverType.SPRITE_2D, - global_observer_type=gd.ObserverType.SPRITE_2D, - image_path='./assets/', - level=0) + env = GymWrapper( + "stochasticity.yaml", + player_observer_type=gd.ObserverType.SPRITE_2D, + global_observer_type=gd.ObserverType.SPRITE_2D, + image_path="./assets/", + level=0, + ) env.reset() global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(10000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) diff --git a/python/examples/clone_environments/clone_environments.py b/python/examples/clone_environments/clone_environments.py index 9e3a7ce9b..5cb4c21d4 100644 --- a/python/examples/clone_environments/clone_environments.py +++ b/python/examples/clone_environments/clone_environments.py @@ -2,20 +2,24 @@ import griddly import numpy as np -env = gym.make('GDY-Sokoban-v0') +env = gym.make("GDY-Sokoban-v0") env.reset() available_actions = env.game.get_available_actions(1) print(available_actions) player_pos = list(available_actions)[0] -actions = env.game.get_available_action_ids(player_pos, list(available_actions[player_pos])) +actions = env.game.get_available_action_ids( + player_pos, list(available_actions[player_pos]) +) print(actions) clone_env = env.clone() clone_available_actions = clone_env.game.get_available_actions(1) print(clone_available_actions) clone_player_pos = list(clone_available_actions)[0] -clone_actions = clone_env.game.get_available_action_ids(clone_player_pos, list(clone_available_actions[clone_player_pos])) +clone_actions = clone_env.game.get_available_action_ids( + clone_player_pos, list(clone_available_actions[clone_player_pos]) +) print(clone_actions) @@ -34,8 +38,8 @@ env_state = env.get_state() cloned_state = clone_env.get_state() - assert env_state['Hash'] == cloned_state['Hash'] + assert env_state["Hash"] == cloned_state["Hash"] if done and c_done: env.reset() - clone_env.reset() \ No newline at end of file + clone_env.reset() diff --git a/python/examples/griddlyrts/play_griddlyrts_gym.py b/python/examples/griddlyrts/play_griddlyrts_gym.py index a7b048513..fcad6ac6a 100644 --- a/python/examples/griddlyrts/play_griddlyrts_gym.py +++ b/python/examples/griddlyrts/play_griddlyrts_gym.py @@ -6,16 +6,18 @@ from griddly.RenderTools import VideoRecorder, RenderToFile from griddly.util.wrappers import ValidActionSpaceWrapper -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - wrapper.build_gym_from_yaml("GriddlyRTS-Adv", - 'RTS/GriddlyRTS.yaml', - global_observer_type=gd.ObserverType.SPRITE_2D, - player_observer_type=gd.ObserverType.ISOMETRIC, - level=0) + wrapper.build_gym_from_yaml( + "GriddlyRTS-Adv", + "RTS/GriddlyRTS.yaml", + global_observer_type=gd.ObserverType.SPRITE_2D, + player_observer_type=gd.ObserverType.ISOMETRIC, + level=0, + ) - env_original = gym.make(f'GDY-GriddlyRTS-Adv-v0') + env_original = gym.make(f"GDY-GriddlyRTS-Adv-v0") # env_original = gym.make(f'GDY-GriddlyRTS-Adv-v0') env_original.reset() @@ -31,19 +33,19 @@ image_output = RenderToFile() player1_recorder = VideoRecorder() - player1_visualization = env.render(observer=0, mode='rgb_array') + player1_visualization = env.render(observer=0, mode="rgb_array") player1_recorder.start("player1_video_test.mp4", player1_visualization.shape) - image_output.render(player1_visualization, 'griddly_rts_p1.png') + image_output.render(player1_visualization, "griddly_rts_p1.png") player2_recorder = VideoRecorder() - player2_visualization = env.render(observer=1, mode='rgb_array') + player2_visualization = env.render(observer=1, mode="rgb_array") player2_recorder.start("player2_video_test.mp4", player2_visualization.shape) - image_output.render(player2_visualization, 'griddly_rts_p2.png') + image_output.render(player2_visualization, "griddly_rts_p2.png") global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) - image_output.render(global_visualization, 'griddly_rts_global.png') + image_output.render(global_visualization, "griddly_rts_global.png") for s in range(10000): @@ -58,12 +60,14 @@ # get masks for all move functions for x, y in zip(valid_locations[0], valid_locations[1]): action_names = env.gdy.get_action_names() - action_mask = env.get_unit_action_mask([x,y], action_names) - #print(action_mask) + action_mask = env.get_unit_action_mask([x, y], action_names) + # print(action_mask) - action_masks = env.get_unit_action_mask([6, 3], ['gather', 'move'], padded=False) + action_masks = env.get_unit_action_mask( + [6, 3], ["gather", "move"], padded=False + ) - global_obs = env.render(observer='global') + global_obs = env.render(observer="global") p1_obs = env.render(observer=0) p2_obs = env.render(observer=1) @@ -80,9 +84,9 @@ if frames % 1000 == 0: end = timer() - fps = (frames / (end - start)) + fps = frames / (end - start) fps_samples.append(fps) - print(f'fps: {fps}') + print(f"fps: {fps}") frames = 0 start = timer() @@ -90,4 +94,4 @@ # player1_recorder.close() # player2_recorder.close() # global_recorder.close() - print(f'mean fps: {np.mean(fps_samples)}') + print(f"mean fps: {np.mean(fps_samples)}") diff --git a/python/examples/gvgai/play_gvgai_gym.py b/python/examples/gvgai/play_gvgai_gym.py index b1afdcd5c..65750981a 100644 --- a/python/examples/gvgai/play_gvgai_gym.py +++ b/python/examples/gvgai/play_gvgai_gym.py @@ -4,21 +4,25 @@ from griddly import GymWrapperFactory, gd + def make_env(name): wrapper = GymWrapperFactory() - wrapper.build_gym_from_yaml(name, 'Single-Player/GVGAI/sokoban.yaml', - player_observer_type=gd.ObserverType.SPRITE_2D, - global_observer_type=gd.ObserverType.BLOCK_2D, - level=0) - - env = gym.make(f'GDY-{name}-v0') + wrapper.build_gym_from_yaml( + name, + "Single-Player/GVGAI/sokoban.yaml", + player_observer_type=gd.ObserverType.SPRITE_2D, + global_observer_type=gd.ObserverType.BLOCK_2D, + level=0, + ) + + env = gym.make(f"GDY-{name}-v0") env.enable_history(True) env.reset() return env -if __name__ == '__main__': +if __name__ == "__main__": env = make_env("Sokoban_Manual") @@ -28,7 +32,6 @@ def make_env(name): fps_samples = [] - for s in range(1000): action = env.action_space.sample() @@ -36,13 +39,13 @@ def make_env(name): frames += 1 obs, reward, done, info = env.step(action) env.render() - #env.render(observer='global') + # env.render(observer='global') if frames % 1000 == 0: end = timer() - fps = (frames / (end - start)) + fps = frames / (end - start) fps_samples.append(fps) - print(f'fps: {fps}') + print(f"fps: {fps}") frames = 0 start = timer() - print(f'mean fps: {np.mean(fps_samples)}') \ No newline at end of file + print(f"mean fps: {np.mean(fps_samples)}") diff --git a/python/examples/gym/gym_human_player.py b/python/examples/gym/gym_human_player.py index b10ca6e9f..8d74b0d49 100644 --- a/python/examples/gym/gym_human_player.py +++ b/python/examples/gym/gym_human_player.py @@ -18,9 +18,9 @@ def _callback(prev_obs, obs, action, rew, env_done, info): global_obs = env.render(observer=0, mode="rgb_array") recorder.add_frame(global_obs) if rew != 0: - print(f'\nReward: {rew}') + print(f"\nReward: {rew}") if env_done: - print(f'Done!') + print(f"Done!") if len(info) > 0: print(info) @@ -28,10 +28,10 @@ def _callback(prev_obs, obs, action, rew, env_done, info): return _callback -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - environment_name = 'TestEnv' + environment_name = "TestEnv" # yaml_path = 'Single-Player/GVGAI/bait.yaml' # yaml_path = 'Single-Player/GVGAI/butterflies.yaml' @@ -39,7 +39,7 @@ def _callback(prev_obs, obs, action, rew, env_done, info): # yaml_path = 'Single-Player/GVGAI/bait_keys.yaml' # yaml_path = 'Single-Player/Mini-Grid/minigrid-drunkdwarf.yaml' # yaml_path = 'Single-Player/Mini-Grid/minigrid-spiders.yaml' - yaml_path = 'Single-Player/GVGAI/spider-nest.yaml' + yaml_path = "Single-Player/GVGAI/spider-nest.yaml" # yaml_path = 'Single-Player/GVGAI/cookmepasta.yaml' # yaml_path = 'Single-Player/GVGAI/clusters.yaml' # yaml_path = 'Single-Player/GVGAI/zenpuzzle.yaml' @@ -54,13 +54,16 @@ def _callback(prev_obs, obs, action, rew, env_done, info): # yaml_path = '../resources/rataban.yaml' - level = 0 - wrapper.build_gym_from_yaml(environment_name, yaml_path, - player_observer_type=gd.ObserverType.BLOCK_2D, - global_observer_type=gd.ObserverType.BLOCK_2D, level=level) - env = gym.make(f'GDY-{environment_name}-v0') + wrapper.build_gym_from_yaml( + environment_name, + yaml_path, + player_observer_type=gd.ObserverType.BLOCK_2D, + global_observer_type=gd.ObserverType.BLOCK_2D, + level=level, + ) + env = gym.make(f"GDY-{environment_name}-v0") # env.enable_history(True) env.reset() play(env, callback=callback(env), fps=10, zoom=3) diff --git a/python/examples/minigrid/play_minigrid_gym.py b/python/examples/minigrid/play_minigrid_gym.py index c6a58cb1a..f58551364 100644 --- a/python/examples/minigrid/play_minigrid_gym.py +++ b/python/examples/minigrid/play_minigrid_gym.py @@ -5,18 +5,20 @@ from griddly import GymWrapperFactory, gd from griddly.RenderTools import VideoRecorder -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = '4rooms' + name = "4rooms" - wrapper.build_gym_from_yaml(name, - 'Single-Player/Mini-Grid/minigrid-spiders.yaml', - player_observer_type=gd.ObserverType.SPRITE_2D, - global_observer_type=gd.ObserverType.SPRITE_2D, - level=4) + wrapper.build_gym_from_yaml( + name, + "Single-Player/Mini-Grid/minigrid-spiders.yaml", + player_observer_type=gd.ObserverType.SPRITE_2D, + global_observer_type=gd.ObserverType.SPRITE_2D, + level=4, + ) - env = gym.make(f'GDY-{name}-v0') + env = gym.make(f"GDY-{name}-v0") env.reset() @@ -27,11 +29,11 @@ fps_samples = [] player_recorder = VideoRecorder() - player_visualization = env.render(mode='rgb_array') + player_visualization = env.render(mode="rgb_array") player_recorder.start("player_video_test.mp4", player_visualization.shape) global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for s in range(100000): @@ -41,20 +43,20 @@ env.render() - player_observation = env.render(mode='rgb_array') - global_observation = env.render(observer='global', mode='rgb_array') + player_observation = env.render(mode="rgb_array") + global_observation = env.render(observer="global", mode="rgb_array") player_recorder.add_frame(player_observation) global_recorder.add_frame(global_observation) if frames % 1000 == 0: end = timer() - fps = (frames / (end - start)) + fps = frames / (end - start) fps_samples.append(fps) - print(f'fps: {fps}') + print(f"fps: {fps}") frames = 0 start = timer() if done: env.reset() - print(f'mean fps: {np.mean(fps_samples)}') + print(f"mean fps: {np.mean(fps_samples)}") diff --git a/python/examples/proximity triggers 2/human_player.py b/python/examples/proximity triggers 2/human_player.py index 3501cc7b3..eb1ff55d5 100644 --- a/python/examples/proximity triggers 2/human_player.py +++ b/python/examples/proximity triggers 2/human_player.py @@ -18,9 +18,9 @@ def _callback(prev_obs, obs, action, rew, env_done, info): global_obs = env.render(observer=0, mode="rgb_array") recorder.add_frame(global_obs) if rew != 0: - print(f'\nReward: {rew}') + print(f"\nReward: {rew}") if env_done: - print(f'Done!') + print(f"Done!") if len(info) > 0: print(info) @@ -28,14 +28,16 @@ def _callback(prev_obs, obs, action, rew, env_done, info): return _callback -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - environment_name = 'TestEnv' + environment_name = "TestEnv" - env = GymWrapper('proximity_env.yaml', - player_observer_type=gd.ObserverType.ISOMETRIC, - global_observer_type=gd.ObserverType.ISOMETRIC, - level=0) + env = GymWrapper( + "proximity_env.yaml", + player_observer_type=gd.ObserverType.ISOMETRIC, + global_observer_type=gd.ObserverType.ISOMETRIC, + level=0, + ) env.reset() play(env, callback=callback(env), fps=10, zoom=3) diff --git a/python/examples/proximity_triggers/proximity_test.py b/python/examples/proximity_triggers/proximity_test.py index d7c0dc6fe..04ce544c2 100644 --- a/python/examples/proximity_triggers/proximity_test.py +++ b/python/examples/proximity_triggers/proximity_test.py @@ -3,30 +3,32 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'proximity_env' + name = "proximity_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('proximity_env.yaml', - player_observer_type=gd.ObserverType.VECTOR, - global_observer_type=gd.ObserverType.ISOMETRIC, - level=0) + env = GymWrapper( + "proximity_env.yaml", + player_observer_type=gd.ObserverType.VECTOR, + global_observer_type=gd.ObserverType.ISOMETRIC, + level=0, + ) env.reset() global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(1000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) diff --git a/python/examples/random_movement/random_spiders.py b/python/examples/random_movement/random_spiders.py index 5be634fb2..ab10ecfb2 100644 --- a/python/examples/random_movement/random_spiders.py +++ b/python/examples/random_movement/random_spiders.py @@ -3,30 +3,32 @@ from griddly import GymWrapperFactory, gd, GymWrapper from griddly.RenderTools import VideoRecorder -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - name = 'random_spiders_env' + name = "random_spiders_env" current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper('random_spiders.yaml', - player_observer_type=gd.ObserverType.VECTOR, - global_observer_type=gd.ObserverType.ISOMETRIC, - level=0) + env = GymWrapper( + "random_spiders.yaml", + player_observer_type=gd.ObserverType.VECTOR, + global_observer_type=gd.ObserverType.ISOMETRIC, + level=0, + ) env.reset() global_recorder = VideoRecorder() - global_visualization = env.render(observer='global', mode='rgb_array') + global_visualization = env.render(observer="global", mode="rgb_array") global_recorder.start("global_video_test.mp4", global_visualization.shape) for i in range(1000): obs, reward, done, info = env.step(env.action_space.sample()) - env.render(observer='global') - frame = env.render(observer='global', mode='rgb_array') + env.render(observer="global") + frame = env.render(observer="global", mode="rgb_array") global_recorder.add_frame(frame) diff --git a/python/examples/rllib/rllib_multi_agent.py b/python/examples/rllib/rllib_multi_agent.py index ffffda056..0ae3005c7 100644 --- a/python/examples/rllib/rllib_multi_agent.py +++ b/python/examples/rllib/rllib_multi_agent.py @@ -12,67 +12,52 @@ from griddly.util.rllib.environment.core import RLlibMultiAgentWrapper, RLlibEnv from griddly.util.rllib.torch.agents.conv_agent import SimpleConvAgent -if __name__ == '__main__': +if __name__ == "__main__": sep = os.pathsep - os.environ['PYTHONPATH'] = sep.join(sys.path) + os.environ["PYTHONPATH"] = sep.join(sys.path) ray.init(num_gpus=1) - env_name = 'ray-ma-env' - + env_name = "ray-ma-env" # Create the gridnet environment and wrap it in a multi-agent wrapper for self-play def _create_env(env_config): env = RLlibEnv(env_config) return RLlibMultiAgentWrapper(env, env_config) - register_env(env_name, _create_env) - ModelCatalog.register_custom_model('SimpleConv', SimpleConvAgent) + ModelCatalog.register_custom_model("SimpleConv", SimpleConvAgent) max_training_steps = 50000000 config = { - 'framework': 'torch', - 'num_workers': 3, - 'num_envs_per_worker': 1, - - 'callbacks': VideoCallbacks, - - 'model': { - 'custom_model': 'SimpleConv', - 'custom_model_config': {} - }, - 'env': env_name, - 'env_config': { + "framework": "torch", + "num_workers": 3, + "num_envs_per_worker": 1, + "callbacks": VideoCallbacks, + "model": {"custom_model": "SimpleConv", "custom_model_config": {}}, + "env": env_name, + "env_config": { # in the griddly environment we set a variable to let the training environment # know if that player is no longer active # 'player_done_variable': 'player_done', - # 'record_video_config': { # 'frequency': 20000, # number of rollouts # 'directory': 'videos' # }, - - 'random_level_on_reset': False, - 'yaml_file': 'Multi-Agent/robot_tag_12.yaml', - 'global_observer_type': gd.ObserverType.VECTOR, - 'player_observer_type': gd.ObserverType.VECTOR, + "random_level_on_reset": False, + "yaml_file": "Multi-Agent/robot_tag_12.yaml", + "global_observer_type": gd.ObserverType.VECTOR, + "player_observer_type": gd.ObserverType.VECTOR, # 'max_steps': 500, }, - 'entropy_coeff_schedule': [ - [0, 0.01], - [max_training_steps, 0.0] - ], - 'lr_schedule': [ - [0, 0.0005], - [max_training_steps, 0.0] - ] + "entropy_coeff_schedule": [[0, 0.01], [max_training_steps, 0.0]], + "lr_schedule": [[0, 0.0005], [max_training_steps, 0.0]], } stop = { - 'timesteps_total': max_training_steps, + "timesteps_total": max_training_steps, } result = tune.run(ImpalaTrainer, config=config, stop=stop) diff --git a/python/examples/rllib/rllib_rts.py b/python/examples/rllib/rllib_rts.py index a419a5701..562783e27 100644 --- a/python/examples/rllib/rllib_rts.py +++ b/python/examples/rllib/rllib_rts.py @@ -11,66 +11,48 @@ from griddly.util.rllib.callbacks import ActionTrackerCallbacks, VideoCallbacks from griddly.util.rllib.environment.core import RLlibMultiAgentWrapper, RLlibEnv from griddly.util.rllib.torch.agents.impala_cnn import ImpalaCNNAgent -from griddly.util.rllib.torch.conditional_actions.conditional_action_policy_trainer import \ - ConditionalActionImpalaTrainer +from griddly.util.rllib.torch.conditional_actions.conditional_action_policy_trainer import ( + ConditionalActionImpalaTrainer, +) -if __name__ == '__main__': +if __name__ == "__main__": sep = os.pathsep - os.environ['PYTHONPATH'] = sep.join(sys.path) + os.environ["PYTHONPATH"] = sep.join(sys.path) ray.init(num_gpus=1) env_name = "griddly-rts-env" - def _create_env(env_config): env = RLlibEnv(env_config) return RLlibMultiAgentWrapper(env, env_config) - register_env(env_name, _create_env) ModelCatalog.register_custom_model("ImpalaCNN", ImpalaCNNAgent) max_training_steps = 100000000 config = { - 'framework': 'torch', - - 'num_workers': 3, - 'num_envs_per_worker': 2, - - 'callbacks': MultiCallbacks([ - ActionTrackerCallbacks, - VideoCallbacks - ]), - - 'model': { - 'custom_model': 'ImpalaCNN', - 'custom_model_config': {} - }, - 'env': env_name, - 'env_config': { - 'generate_valid_action_trees': True, - 'yaml_file': 'RTS/GriddlyRTS.yaml', - 'global_observer_type': gd.ObserverType.ISOMETRIC, - 'level': 0, - 'record_actions': True, - 'max_steps': 1000, - - 'record_video_config': { - 'frequency': 20000, # number of rollouts - 'directory': 'videos' + "framework": "torch", + "num_workers": 3, + "num_envs_per_worker": 2, + "callbacks": MultiCallbacks([ActionTrackerCallbacks, VideoCallbacks]), + "model": {"custom_model": "ImpalaCNN", "custom_model_config": {}}, + "env": env_name, + "env_config": { + "generate_valid_action_trees": True, + "yaml_file": "RTS/GriddlyRTS.yaml", + "global_observer_type": gd.ObserverType.ISOMETRIC, + "level": 0, + "record_actions": True, + "max_steps": 1000, + "record_video_config": { + "frequency": 20000, # number of rollouts + "directory": "videos", }, }, - 'entropy_coeff_schedule': [ - [0, 0.001], - [max_training_steps, 0.0] - ], - 'lr_schedule': [ - [0, 0.0005], - [max_training_steps, 0.0] - ], - + "entropy_coeff_schedule": [[0, 0.001], [max_training_steps, 0.0]], + "lr_schedule": [[0, 0.0005], [max_training_steps, 0.0]], } stop = { diff --git a/python/examples/rllib/rllib_single_agent.py b/python/examples/rllib/rllib_single_agent.py index c188d9de6..58333ea6e 100644 --- a/python/examples/rllib/rllib_single_agent.py +++ b/python/examples/rllib/rllib_single_agent.py @@ -12,9 +12,9 @@ from griddly.util.rllib.environment.core import RLlibEnv from griddly.util.rllib.torch import GAPAgent -if __name__ == '__main__': +if __name__ == "__main__": sep = os.pathsep - os.environ['PYTHONPATH'] = sep.join(sys.path) + os.environ["PYTHONPATH"] = sep.join(sys.path) ray.init(num_gpus=1) @@ -26,38 +26,22 @@ max_training_steps = 100000000 config = { - 'framework': 'torch', - 'num_workers': 8, - 'num_envs_per_worker': 4, - 'num_gpus': 1, - - 'callbacks': VideoCallbacks, - - 'model': { - 'custom_model': 'GAP', - 'custom_model_config': {} - }, - 'env': env_name, - 'env_config': { - - 'record_video_config': { - 'frequency': 100000, - 'directory': 'videos' - }, - - 'random_level_on_reset': True, - 'yaml_file': 'Single-Player/GVGAI/clusters_partially_observable.yaml', - 'global_observer_type': gd.ObserverType.SPRITE_2D, - 'max_steps': 1000, + "framework": "torch", + "num_workers": 8, + "num_envs_per_worker": 4, + "num_gpus": 1, + "callbacks": VideoCallbacks, + "model": {"custom_model": "GAP", "custom_model_config": {}}, + "env": env_name, + "env_config": { + "record_video_config": {"frequency": 100000, "directory": "videos"}, + "random_level_on_reset": True, + "yaml_file": "Single-Player/GVGAI/clusters_partially_observable.yaml", + "global_observer_type": gd.ObserverType.SPRITE_2D, + "max_steps": 1000, }, - 'entropy_coeff_schedule': [ - [0, 0.01], - [max_training_steps, 0.0] - ], - 'lr_schedule': [ - [0, 0.0005], - [max_training_steps, 0.0] - ] + "entropy_coeff_schedule": [[0, 0.01], [max_training_steps, 0.0]], + "lr_schedule": [[0, 0.0005], [max_training_steps, 0.0]], } stop = { diff --git a/python/examples/snippet.py b/python/examples/snippet.py index e3ee33ac8..22cf36425 100644 --- a/python/examples/snippet.py +++ b/python/examples/snippet.py @@ -8,20 +8,23 @@ def make_env(name): wrapper = GymWrapperFactory() - wrapper.build_gym_from_yaml(name, 'Single-Player/GVGAI/spider-nest.yaml', - player_observer_type=gd.ObserverType.SPRITE_2D, - global_observer_type=gd.ObserverType.ASCII, - level=0, - max_steps=200) - - env = gym.make(f'GDY-{name}-v0') + wrapper.build_gym_from_yaml( + name, + "Single-Player/GVGAI/spider-nest.yaml", + player_observer_type=gd.ObserverType.SPRITE_2D, + global_observer_type=gd.ObserverType.ASCII, + level=0, + max_steps=200, + ) + + env = gym.make(f"GDY-{name}-v0") env.enable_history(True) env.reset() return ValidActionSpaceWrapper(env) -if __name__ == '__main__': +if __name__ == "__main__": env = make_env("Test") @@ -31,7 +34,6 @@ def make_env(name): fps_samples = [] - for s in range(100000): action = env.action_space.sample() @@ -39,16 +41,16 @@ def make_env(name): frames += 1 obs, reward, done, info = env.step(action) env.render() - print(env.render(observer='global')) + print(env.render(observer="global")) if frames % 1000 == 0: end = timer() - fps = (frames / (end - start)) + fps = frames / (end - start) fps_samples.append(fps) - print(f'fps: {fps}') + print(f"fps: {fps}") frames = 0 start = timer() if done: env.reset() - print(f'mean fps: {np.mean(fps_samples)}') + print(f"mean fps: {np.mean(fps_samples)}") diff --git a/python/griddly/GymWrapper.py b/python/griddly/GymWrapper.py index 81ca4b113..f74d5131b 100644 --- a/python/griddly/GymWrapper.py +++ b/python/griddly/GymWrapper.py @@ -9,12 +9,23 @@ class GymWrapper(gym.Env): - metadata = {'render.modes': ['human', 'rgb_array']} - - def __init__(self, yaml_file=None, yaml_string=None, level=0, global_observer_type=gd.ObserverType.VECTOR, - player_observer_type=gd.ObserverType.VECTOR, max_steps=None, gdy_path=None, image_path=None, - shader_path=None, - gdy=None, game=None, **kwargs): + metadata = {"render.modes": ["human", "rgb_array"]} + + def __init__( + self, + yaml_file=None, + yaml_string=None, + level=0, + global_observer_type=gd.ObserverType.VECTOR, + player_observer_type=gd.ObserverType.VECTOR, + max_steps=None, + gdy_path=None, + image_path=None, + shader_path=None, + gdy=None, + game=None, + **kwargs, + ): """ Currently only supporting a single player (player 1 as defined in the environment yaml :param yaml_file: @@ -61,7 +72,9 @@ def __init__(self, yaml_file=None, yaml_string=None, level=0, global_observer_ty self._player_observer_type = [] for p in range(self.player_count): - self._players.append(self.game.register_player(f'Player {p + 1}', player_observer_type)) + self._players.append( + self.game.register_player(f"Player {p + 1}", player_observer_type) + ) self._player_observer_type.append(player_observer_type) self._player_last_observation = [] @@ -106,8 +119,10 @@ def step(self, action): elif np.ndim(action) == 2: action_data = np.array(action) else: - raise ValueError(f'The supplied action is in the wrong format for this environment.\n\n' - f'A valid example: {self.action_space.sample()}') + raise ValueError( + f"The supplied action is in the wrong format for this environment.\n\n" + f"A valid example: {self.action_space.sample()}" + ) reward, done, info = self._players[player_id].step_multi(action_data, True) @@ -117,7 +132,9 @@ def step(self, action): multi_action = False for a in action: if a is None: - processed_action = np.zeros((len(self.action_space_parts)), dtype=np.int32) + processed_action = np.zeros( + (len(self.action_space_parts)), dtype=np.int32 + ) else: processed_action = np.array(a, dtype=np.int32) if len(processed_action.shape) > 1 and processed_action.shape[0] > 1: @@ -129,7 +146,9 @@ def step(self, action): # Used in RTS games reward = [] for p in range(self.player_count): - player_action = processed_actions[p].reshape(-1, len(self.action_space_parts)) + player_action = processed_actions[p].reshape( + -1, len(self.action_space_parts) + ) final = p == self.player_count - 1 rew, done, info = self._players[p].step_multi(player_action, final) reward.append(rew) @@ -142,30 +161,40 @@ def step(self, action): reward, done, info = self.game.step_parallel(action_data) else: - raise ValueError(f'The supplied action is in the wrong format for this environment.\n\n' - f'A valid example: {self.action_space.sample()}') + raise ValueError( + f"The supplied action is in the wrong format for this environment.\n\n" + f"A valid example: {self.action_space.sample()}" + ) # In the case where the environment is cloned, but no step has happened to replace the last obs, # we can do that here if len(self._player_last_observation) == 0: for p in range(self.player_count): - self._player_last_observation.append(np.array(self._players[p].observe(), copy=False)) + self._player_last_observation.append( + np.array(self._players[p].observe(), copy=False) + ) else: for p in range(self.player_count): # Copy only if the environment is done (it will reset itself) # This is because the underlying data will be released - self._player_last_observation[p] = np.array(self._players[p].observe(), copy=False) - - obs = self._player_last_observation[0] if self.player_count == 1 else self._player_last_observation + self._player_last_observation[p] = np.array( + self._players[p].observe(), copy=False + ) + + obs = ( + self._player_last_observation[0] + if self.player_count == 1 + else self._player_last_observation + ) if self._enable_history: - info['History'] = self.game.get_history() + info["History"] = self.game.get_history() return obs, reward, done, info def reset(self, level_id=None, level_string=None, global_observations=False): if level_string is not None: self.game.load_level_string(level_string) - self.level_id = 'custom' + self.level_id = "custom" elif level_id is not None: self.game.load_level(level_id) self.level_id = level_id @@ -175,17 +204,25 @@ def reset(self, level_id=None, level_string=None, global_observations=False): self.initialize_spaces() for p in range(self.player_count): - self._player_last_observation.append(np.array(self._players[p].observe(), copy=False)) + self._player_last_observation.append( + np.array(self._players[p].observe(), copy=False) + ) if global_observations: self._global_last_observation = np.array(self.game.observe(), copy=False) return { - 'global': self._global_last_observation, - 'player': self._player_last_observation[0] if self.player_count == 1 else self._player_last_observation + "global": self._global_last_observation, + "player": self._player_last_observation[0] + if self.player_count == 1 + else self._player_last_observation, } else: - return self._player_last_observation[0] if self.player_count == 1 else self._player_last_observation + return ( + self._player_last_observation[0] + if self.player_count == 1 + else self._player_last_observation + ) def initialize_spaces(self): self._player_last_observation = [] @@ -193,14 +230,19 @@ def initialize_spaces(self): self.player_observation_shape = self.game.get_player_observation_shape() self.global_observation_shape = self.game.get_global_observation_shape() - self.global_observation_space = gym.spaces.Box(low=0, high=255, shape=self.global_observation_shape, - dtype=np.uint8) + self.global_observation_space = gym.spaces.Box( + low=0, high=255, shape=self.global_observation_shape, dtype=np.uint8 + ) self._observation_shape = self.player_observation_shape - observation_space = gym.spaces.Box(low=0, high=255, shape=self._observation_shape, dtype=np.uint8) + observation_space = gym.spaces.Box( + low=0, high=255, shape=self._observation_shape, dtype=np.uint8 + ) if self.player_count > 1: - observation_space = MultiAgentObservationSpace([observation_space for _ in range(self.player_count)]) + observation_space = MultiAgentObservationSpace( + [observation_space for _ in range(self.player_count)] + ) self.observation_space = observation_space @@ -211,20 +253,25 @@ def initialize_spaces(self): self.action_space = self._create_action_space() - def render(self, mode='human', observer=0): + def render(self, mode="human", observer=0): - if observer == 'global': + if observer == "global": observation = np.array(self.game.observe(), copy=False) if self._global_observer_type == gd.ObserverType.VECTOR: observation = self._vector2rgb.convert(observation) if self._global_observer_type == gd.ObserverType.ASCII: - observation = observation \ - .swapaxes(2, 0) \ - .reshape(-1, observation.shape[0] * observation.shape[1]) \ - .view('c') - ascii_string = ''.join(np.column_stack( - (observation, np.repeat(['\n'], observation.shape[0])) - ).flatten().tolist()) + observation = ( + observation.swapaxes(2, 0) + .reshape(-1, observation.shape[0] * observation.shape[1]) + .view("c") + ) + ascii_string = "".join( + np.column_stack( + (observation, np.repeat(["\n"], observation.shape[0])) + ) + .flatten() + .tolist() + ) return ascii_string else: @@ -232,36 +279,46 @@ def render(self, mode='human', observer=0): # we can do that here if len(self._player_last_observation) == 0: for p in range(self.player_count): - self._player_last_observation.append(np.array(self._players[p].observe(), copy=False)) + self._player_last_observation.append( + np.array(self._players[p].observe(), copy=False) + ) observation = self._player_last_observation[observer] if self._player_observer_type[observer] == gd.ObserverType.VECTOR: observation = self._vector2rgb.convert(observation) if self._player_observer_type[observer] == gd.ObserverType.ASCII: - observation = observation \ - .swapaxes(2, 0) \ - .reshape(-1, observation.shape[0] * observation.shape[1]) \ - .view('c') - ascii_string = ''.join(np.column_stack( - (observation, np.repeat(['\n'], observation.shape[0])) - ).flatten().tolist()) + observation = ( + observation.swapaxes(2, 0) + .reshape(-1, observation.shape[0] * observation.shape[1]) + .view("c") + ) + ascii_string = "".join( + np.column_stack( + (observation, np.repeat(["\n"], observation.shape[0])) + ) + .flatten() + .tolist() + ) return ascii_string - if mode == 'human': + if mode == "human": if self._renderWindow.get(observer) is None: from griddly.RenderTools import RenderWindow - self._renderWindow[observer] = RenderWindow(observation.shape[1], observation.shape[2]) + + self._renderWindow[observer] = RenderWindow( + observation.shape[1], observation.shape[2] + ) self._renderWindow[observer].render(observation) return observation.swapaxes(0, 2) def get_keys_to_action(self): keymap = { - (ord('a'),): 1, - (ord('w'),): 2, - (ord('d'),): 3, - (ord('s'),): 4, - (ord('e'),): 5 + (ord("a"),): 1, + (ord("w"),): 2, + (ord("d"),): 3, + (ord("s"),): 4, + (ord("e"),): 5, } return keymap @@ -303,8 +360,8 @@ def _create_action_space(self): self.max_action_ids = 0 for action_name, mapping in sorted(self.action_input_mappings.items()): - if not mapping['Internal']: - num_action_ids = len(mapping['InputMappings']) + 1 + if not mapping["Internal"]: + num_action_ids = len(mapping["InputMappings"]) + 1 self.num_action_ids[action_name] = num_action_ids if self.max_action_ids < num_action_ids: self.max_action_ids = num_action_ids @@ -317,7 +374,9 @@ def _create_action_space(self): action_space = gym.spaces.MultiDiscrete(self.action_space_parts) if self.player_count > 1: - action_space = MultiAgentActionSpace([action_space for _ in range(self.player_count)]) + action_space = MultiAgentActionSpace( + [action_space for _ in range(self.player_count)] + ) if self.action_space is not None: for old_space, space in zip(self.action_space, action_space): space._np_random = old_space._np_random @@ -337,7 +396,7 @@ def clone(self): global_observer_type=self._global_observer_type, player_observer_type=self._player_observer_type[0], gdy=self.gdy, - game=game_copy + game=game_copy, ) cloned_wrapper.initialize_spaces() @@ -353,32 +412,45 @@ def seed(self, seed=None): self.observation_space.seed(seed) -class GymWrapperFactory(): - - def build_gym_from_yaml(self, environment_name, yaml_file, global_observer_type=gd.ObserverType.SPRITE_2D, - player_observer_type=gd.ObserverType.SPRITE_2D, level=None, max_steps=None): +class GymWrapperFactory: + def build_gym_from_yaml( + self, + environment_name, + yaml_file, + global_observer_type=gd.ObserverType.SPRITE_2D, + player_observer_type=gd.ObserverType.SPRITE_2D, + level=None, + max_steps=None, + ): register( - id=f'GDY-{environment_name}-v0', - entry_point='griddly:GymWrapper', + id=f"GDY-{environment_name}-v0", + entry_point="griddly:GymWrapper", kwargs={ - 'yaml_file': yaml_file, - 'level': level, - 'max_steps': max_steps, - 'global_observer_type': global_observer_type, - 'player_observer_type': player_observer_type - } + "yaml_file": yaml_file, + "level": level, + "max_steps": max_steps, + "global_observer_type": global_observer_type, + "player_observer_type": player_observer_type, + }, ) - def build_gym_from_yaml_string(self, environment_name, yaml_string, global_observer_type=gd.ObserverType.SPRITE_2D, - player_observer_type=gd.ObserverType.SPRITE_2D, level=None, max_steps=None): + def build_gym_from_yaml_string( + self, + environment_name, + yaml_string, + global_observer_type=gd.ObserverType.SPRITE_2D, + player_observer_type=gd.ObserverType.SPRITE_2D, + level=None, + max_steps=None, + ): register( - id=f'GDY-{environment_name}-v0', - entry_point='griddly:GymWrapper', + id=f"GDY-{environment_name}-v0", + entry_point="griddly:GymWrapper", kwargs={ - 'yaml_string': yaml_string, - 'level': level, - 'max_steps': max_steps, - 'global_observer_type': global_observer_type, - 'player_observer_type': player_observer_type - } + "yaml_string": yaml_string, + "level": level, + "max_steps": max_steps, + "global_observer_type": global_observer_type, + "player_observer_type": player_observer_type, + }, ) diff --git a/python/griddly/RenderTools.py b/python/griddly/RenderTools.py index b95386afd..3245c061a 100644 --- a/python/griddly/RenderTools.py +++ b/python/griddly/RenderTools.py @@ -3,15 +3,14 @@ import os -class RenderWindow(): - +class RenderWindow: def __init__(self, width, height, caption="Griddly"): super().__init__() self._width = width self._height = height self._caption = caption - self._pyglet = __import__('pyglet') + self._pyglet = __import__("pyglet") self._gl = self._pyglet.gl self._initialized = False @@ -24,7 +23,7 @@ def init(self): caption=self._caption, width=self._width, height=self._height, - resizable=False + resizable=False, ) def render(self, observation): @@ -35,21 +34,20 @@ def render(self, observation): obs = observation.swapaxes(0, 2) self._window.switch_to() - image = self._pyglet.image.ImageData(obs.shape[1], - obs.shape[0], - 'RGB', - obs.tobytes(), - pitch=obs.shape[1] * -3 - ) + image = self._pyglet.image.ImageData( + obs.shape[1], obs.shape[0], "RGB", obs.tobytes(), pitch=obs.shape[1] * -3 + ) texture = image.get_texture() texture.width = self._width texture.height = self._height self._window.clear() self._gl.glTexParameteri( - self._gl.GL_TEXTURE_2D, self._gl.GL_TEXTURE_MAG_FILTER, self._gl.GL_NEAREST) + self._gl.GL_TEXTURE_2D, self._gl.GL_TEXTURE_MAG_FILTER, self._gl.GL_NEAREST + ) self._gl.glTexParameteri( - self._gl.GL_TEXTURE_2D, self._gl.GL_TEXTURE_MIN_FILTER, self._gl.GL_NEAREST) + self._gl.GL_TEXTURE_2D, self._gl.GL_TEXTURE_MIN_FILTER, self._gl.GL_NEAREST + ) self._window.dispatch_events() texture.blit(0, 0) # draw @@ -63,8 +61,7 @@ def __del__(self): self.close() -class RenderToFile(): - +class RenderToFile: def __init__(self): super().__init__() @@ -72,7 +69,7 @@ def render(self, observation, string_filename): imageio.imwrite(string_filename, observation) -class VideoRecorder(): +class VideoRecorder: """ Use ImageEncoder gym.wrappers.monitoring.video_recorder because it make really nice videos using .mp4 and ffmpeg """ diff --git a/python/griddly/__init__.py b/python/griddly/__init__.py index cd32ca910..09a71bdf3 100644 --- a/python/griddly/__init__.py +++ b/python/griddly/__init__.py @@ -5,31 +5,54 @@ # The python libs are found in the current directory module_path = os.path.dirname(os.path.realpath(__file__)) -libs_path = os.path.join(module_path, 'libs') +libs_path = os.path.join(module_path, "libs") sys.path.extend([libs_path]) -debug_path = os.path.join(module_path, '../../Debug/bin') +debug_path = os.path.join(module_path, "../../Debug/bin") sys.path.extend([debug_path]) # Load the binary -gd = importlib.import_module('python_griddly') +gd = importlib.import_module("python_griddly") -class GriddlyLoader(): +class GriddlyLoader: def __init__(self, gdy_path=None, image_path=None, shader_path=None): module_path = os.path.dirname(os.path.realpath(__file__)) - self._image_path = os.path.join(module_path, 'resources', 'images') if image_path is None else image_path - self._shader_path = os.path.join(module_path, 'resources', 'shaders') if shader_path is None else shader_path - self._gdy_path = os.path.join(module_path, 'resources', 'games') if gdy_path is None else gdy_path + self._image_path = ( + os.path.join(module_path, "resources", "images") + if image_path is None + else image_path + ) + self._shader_path = ( + os.path.join(module_path, "resources", "shaders") + if shader_path is None + else shader_path + ) + self._gdy_path = ( + os.path.join(module_path, "resources", "games") + if gdy_path is None + else gdy_path + ) self._gdy_reader = gd.GDYReader(self._image_path, self._shader_path) def get_full_path(self, gdy_path): # Assume the file is relative first and if not, try to find it in the pre-defined games - fullpath = gdy_path if os.path.exists(gdy_path) else os.path.join(self._gdy_path, gdy_path) + fullpath = ( + gdy_path + if os.path.exists(gdy_path) + else os.path.join(self._gdy_path, gdy_path) + ) # (for debugging only) look in parent directory resources because we might not have built the latest version - fullpath = fullpath if os.path.exists(fullpath) else os.path.realpath( - os.path.join(self._gdy_path + '../../../../../resources/games', gdy_path)) + fullpath = ( + fullpath + if os.path.exists(fullpath) + else os.path.realpath( + os.path.join( + self._gdy_path + "../../../../../resources/games", gdy_path + ) + ) + ) return fullpath def load(self, gdy_path): @@ -42,29 +65,28 @@ def load_gdy(self, gdy_path): with open(self.get_full_path(gdy_path)) as gdy_file: return yaml.load(gdy_file) + from griddly.GymWrapper import GymWrapper, GymWrapperFactory + def preload_default_envs(): module_path = os.path.dirname(os.path.realpath(__file__)) - game_path = os.path.join(module_path, 'resources', 'games') + game_path = os.path.join(module_path, "resources", "games") wrapper_factory = GymWrapperFactory() for directory_path, directory_names, filenames in os.walk(game_path): for filename in filenames: - if filename.endswith('.yaml'): + if filename.endswith(".yaml"): full_path = os.path.join(directory_path, filename) - with open(full_path, 'r') as game_file: + with open(full_path, "r") as game_file: gdy = yaml.load(game_file, Loader=yaml.FullLoader) - environment = gdy['Environment'] + environment = gdy["Environment"] - formatted_env_name = environment["Name"].replace(' ', '-') + formatted_env_name = environment["Name"].replace(" ", "-") wrapper_factory.build_gym_from_yaml( - formatted_env_name, - full_path, - level=0 + formatted_env_name, full_path, level=0 ) -preload_default_envs() - +preload_default_envs() diff --git a/python/griddly/util/action_space.py b/python/griddly/util/action_space.py index 930a179f2..9bfa564a9 100644 --- a/python/griddly/util/action_space.py +++ b/python/griddly/util/action_space.py @@ -11,8 +11,16 @@ def __init__(self, agents_action_space): self.agents_action_space = agents_action_space def sample(self): - """ samples action for each agent from uniform distribution""" - return [agent_action_space.sample() for agent_action_space in self.agents_action_space] + """samples action for each agent from uniform distribution""" + return [ + agent_action_space.sample() + for agent_action_space in self.agents_action_space + ] + + def seed(self, seed): + for space in self.agents_action_space: + space.seed(seed) + class ValidatedActionSpace(gym.spaces.space.Space, list): @@ -26,7 +34,9 @@ def __init__(self, action_space, masking_wrapper): shape = None dtype = None - if isinstance(action_space, gym.spaces.Discrete) or isinstance(action_space, gym.spaces.MultiDiscrete): + if isinstance(action_space, gym.spaces.Discrete) or isinstance( + action_space, gym.spaces.MultiDiscrete + ): shape = action_space.shape dtype = action_space.dtype elif isinstance(action_space, MultiAgentActionSpace): @@ -50,18 +60,22 @@ def __getitem__(self, y): raise IndexError() def __getattr__(self, name): - if name.startswith('_'): - raise AttributeError("attempted to get missing private attribute '{}'".format(name)) + if name.startswith("_"): + raise AttributeError( + "attempted to get missing private attribute '{}'".format(name) + ) return getattr(self.action_space, name) - def _sample_valid(self, player_id): # Sample a location with valid actions assert player_id <= self._masking_wrapper.player_count, "Player does not exist." assert player_id > 0, "Player 0 is reserved for internal actions only." - available_actions = [a for a in self._masking_wrapper.game.get_available_actions(player_id).items()] + available_actions = [ + a + for a in self._masking_wrapper.game.get_available_actions(player_id).items() + ] num_available = len(available_actions) if num_available == 0: return [0, 0, 0, 0] @@ -70,13 +84,16 @@ def _sample_valid(self, player_id): location, actions = available_actions[available_actions_choice] - available_action_ids = [aid for aid in - self._masking_wrapper.game.get_available_action_ids(location, list( - actions)).items() if len(aid[1]) > 0] + available_action_ids = [ + aid + for aid in self._masking_wrapper.game.get_available_action_ids( + location, list(actions) + ).items() + if len(aid[1]) > 0 + ] num_action_ids = len(available_action_ids) - # If there are no available actions at all, we do a NOP (which is any action_name with action_id 0) if num_action_ids == 0: action_name_idx = 0 @@ -110,6 +127,6 @@ def sample(self, player_id=None): sampled_actions = [] for player_id in range(self._masking_wrapper.player_count): - sampled_actions.append(self._sample_valid(player_id+1)) + sampled_actions.append(self._sample_valid(player_id + 1)) return sampled_actions diff --git a/python/griddly/util/breakdown.py b/python/griddly/util/breakdown.py index bbe380341..c2108e765 100644 --- a/python/griddly/util/breakdown.py +++ b/python/griddly/util/breakdown.py @@ -4,7 +4,7 @@ from griddly.util.vector_visualization import Vector2RGB -class TemporaryEnvironment(): +class TemporaryEnvironment: """ Because we have to laod the game many different times with different configurations, this class makes sure we clean up objects we dont need """ @@ -17,7 +17,7 @@ def __enter__(self): self.game = self.gdy.create_game(self.observer_type) self.players = [] for p in range(self.gdy.get_player_count()): - self.players.append(self.game.register_player(f'P{p}', self.observer_type)) + self.players.append(self.game.register_player(f"P{p}", self.observer_type)) self.game.init(False) return self @@ -37,14 +37,13 @@ def render_rgb(self): return observation -class EnvironmentBreakdown(): - +class EnvironmentBreakdown: def __init__(self, gdy_filename): """ Creates a breakdown of the and. """ - with open(gdy_filename, 'r') as gdy_file: + with open(gdy_filename, "r") as gdy_file: self.gdy_string = gdy_file.read() self.gdy_resource_path = gdy_filename @@ -73,27 +72,27 @@ def _env(self, observer_type): def _get_observer_yaml_key(self, observer_type): if observer_type is gd.ObserverType.VECTOR: - return 'Vector' + return "Vector" if observer_type is gd.ObserverType.SPRITE_2D: - return 'Sprite2D' + return "Sprite2D" elif observer_type is gd.ObserverType.BLOCK_2D: - return 'Block2D' + return "Block2D" elif observer_type is gd.ObserverType.ISOMETRIC: - return 'Isometric' + return "Isometric" else: - return 'Unknown' + return "Unknown" def _populate_objects(self): - for object in self.gdy['Objects']: - self.objects[object['Name']] = { - 'MapCharacter': object.get('MapCharacter', None), - 'Tiles': {}, + for object in self.gdy["Objects"]: + self.objects[object["Name"]] = { + "MapCharacter": object.get("MapCharacter", None), + "Tiles": {}, } def _populate_common_properties(self): - self.name = self.gdy['Environment']['Name'] - self.description = self.gdy['Environment'].get('Description', '') + self.name = self.gdy["Environment"]["Name"] + self.description = self.gdy["Environment"].get("Description", "") self.player_count = 1 @@ -104,8 +103,7 @@ def _populate_common_properties(self): self.player_count = env.gdy.get_player_count() self.action_mappings = env.gdy.get_action_input_mappings() - self.has_avatar = 'AvatarObject' in self.gdy['Environment']['Player'] - + self.has_avatar = "AvatarObject" in self.gdy["Environment"]["Player"] for observer_type in self._all_observer_types: try: @@ -122,18 +120,18 @@ def _populate_tiles(self): all_tiles = [] ordered_object_names = [] for object_name, object in self.objects.items(): - if object['MapCharacter'] is not None: + if object["MapCharacter"] is not None: all_tiles.append(object["MapCharacter"]) ordered_object_names.append(object_name) - join_string = '.' + join_string = "." all_tiles_string = join_string.join(all_tiles) + join_string for observer_name, observer_type in self.supported_observers.items(): with self._env(observer_type) as env: - env.game.load_level_string(f'{all_tiles_string}\n') + env.game.load_level_string(f"{all_tiles_string}\n") env.game.reset() rendered_sprite_map = env.render_rgb() @@ -143,14 +141,18 @@ def _populate_tiles(self): if observer_type == gd.ObserverType.VECTOR: tile_size = [10, 10] - tile_pos_x = (2 * i * tile_size[0]) + tile_pos_x = 2 * i * tile_size[0] tile_width = tile_size[0] tile_pos_y = 0 tile_height = tile_size[1] elif observer_type == gd.ObserverType.ISOMETRIC: - iso_tile_height = int(self.gdy['Environment']['Observers']['Isometric']['IsoTileHeight']) + iso_tile_height = int( + self.gdy["Environment"]["Observers"]["Isometric"][ + "IsoTileHeight" + ] + ) tile_pos_x = i * int(tile_size[0]) tile_width = tile_size[0] @@ -159,29 +161,26 @@ def _populate_tiles(self): else: - tile_pos_x = (2 * i * tile_size[0]) + tile_pos_x = 2 * i * tile_size[0] tile_width = tile_size[0] tile_pos_y = 0 tile_height = tile_size[1] tile_image = rendered_sprite_map[ - :, - tile_pos_x:tile_pos_x + tile_width, - tile_pos_y:tile_pos_y + tile_height - ] - - self.objects[object_name]['Tiles'][observer_name] = { - 'Image': tile_image, - 'Size': tile_size, + :, + tile_pos_x : tile_pos_x + tile_width, + tile_pos_y : tile_pos_y + tile_height, + ] + + self.objects[object_name]["Tiles"][observer_name] = { + "Image": tile_image, + "Size": tile_size, } def _populate_levels(self): - for i, level in enumerate(self.gdy['Environment']['Levels']): - self.levels[i] = { - 'Map': level, - 'Observers': {} - } + for i, level in enumerate(self.gdy["Environment"]["Levels"]): + self.levels[i] = {"Map": level, "Observers": {}} for observer_name, observer_type in self.supported_observers.items(): with self._env(observer_type) as env: @@ -190,5 +189,8 @@ def _populate_levels(self): env.game.load_level(l) env.game.reset() rendered_level = env.render_rgb() - self.levels[l]['Observers'][observer_name] = rendered_level - self.levels[l]['Size'] = [env.game.get_width(), env.game.get_height()] + self.levels[l]["Observers"][observer_name] = rendered_level + self.levels[l]["Size"] = [ + env.game.get_width(), + env.game.get_height(), + ] diff --git a/python/griddly/util/environment_generator_generator.py b/python/griddly/util/environment_generator_generator.py index 4f1726a24..85021fa9a 100644 --- a/python/griddly/util/environment_generator_generator.py +++ b/python/griddly/util/environment_generator_generator.py @@ -9,83 +9,95 @@ from griddly.util.wrappers import ValidActionSpaceWrapper -class EnvironmentGeneratorGenerator(): - +class EnvironmentGeneratorGenerator: def __init__(self, gdy_path=None, yaml_file=None): module_path = os.path.dirname(os.path.realpath(__file__)) - self._gdy_path = os.path.realpath( - os.path.join(module_path, '../', 'resources', 'games')) if gdy_path is None else gdy_path + self._gdy_path = ( + os.path.realpath(os.path.join(module_path, "../", "resources", "games")) + if gdy_path is None + else gdy_path + ) self._input_yaml_file = self._get_full_path(yaml_file) def _get_full_path(self, gdy_path): # Assume the file is relative first and if not, try to find it in the pre-defined games - fullpath = gdy_path if os.path.exists(gdy_path) else os.path.join(self._gdy_path, gdy_path) + fullpath = ( + gdy_path + if os.path.exists(gdy_path) + else os.path.join(self._gdy_path, gdy_path) + ) # (for debugging only) look in parent directory resources because we might not have built the latest version - fullpath = fullpath if os.path.exists(fullpath) else os.path.realpath( - os.path.join(self._gdy_path + '../../../../resources/games', gdy_path)) + fullpath = ( + fullpath + if os.path.exists(fullpath) + else os.path.realpath( + os.path.join(self._gdy_path + "../../../../resources/games", gdy_path) + ) + ) return fullpath def generate_env_yaml(self, level_shape): level_generator_gdy = {} - with open(self._input_yaml_file, 'r') as fs: + with open(self._input_yaml_file, "r") as fs: self._gdy = yaml.load(fs, Loader=yaml.FullLoader) - objects = [o for o in self._gdy['Objects'] if 'MapCharacter' in o] - environment = self._gdy['Environment'] + objects = [o for o in self._gdy["Objects"] if "MapCharacter" in o] + environment = self._gdy["Environment"] # Create the placement actions actions = [] for obj in objects: object_name = obj["Name"] place_action = { - 'InputMapping': { - 'Inputs': { - '1': {'Description': f'Places objects of type \"{object_name}\"'} + "InputMapping": { + "Inputs": { + "1": {"Description": f'Places objects of type "{object_name}"'} } }, - 'Name': f'place_{object_name.lower()}', - 'Behaviours': [{ - 'Src': { - 'Object': '_empty', - 'Commands': [ - {'spawn': object_name} - ] - } - }] - + "Name": f"place_{object_name.lower()}", + "Behaviours": [ + {"Src": {"Object": "_empty", "Commands": [{"spawn": object_name}]}} + ], } actions.append(place_action) - level_generator_gdy['Actions'] = actions + level_generator_gdy["Actions"] = actions # Copy the Objects - level_generator_gdy['Objects'] = [{ - 'Name': o['Name'], - 'MapCharacter': o['MapCharacter'], - 'Observers': o['Observers'] - } for o in objects] + level_generator_gdy["Objects"] = [ + { + "Name": o["Name"], + "MapCharacter": o["MapCharacter"], + "Observers": o["Observers"], + } + for o in objects + ] # Generate a default empty level - empty_level = np.empty(level_shape, dtype='str') - empty_level[:] = '.' + empty_level = np.empty(level_shape, dtype="str") + empty_level[:] = "." - level_0_string = '\n'.join([' '.join(list(r)) for r in empty_level]) + level_0_string = "\n".join([" ".join(list(r)) for r in empty_level]) # Create the environment template - level_generator_gdy['Environment'] = { - 'Name': f'{environment["Name"]} Generator', - 'Description': f'Level Generator environment for {environment["Name"]}', - 'Observers': {k: v for k, v in environment['Observers'].items() if k in ['Sprite2D', 'Isometric']}, - 'Player': { - 'Observer': { - 'TrackAvatar': False, - 'Height': level_shape[1], - 'Width': level_shape[0], - 'OffsetX': 0, - 'OffsetY': 0, + level_generator_gdy["Environment"] = { + "Name": f'{environment["Name"]} Generator', + "Description": f'Level Generator environment for {environment["Name"]}', + "Observers": { + k: v + for k, v in environment["Observers"].items() + if k in ["Sprite2D", "Isometric"] + }, + "Player": { + "Observer": { + "TrackAvatar": False, + "Height": level_shape[1], + "Width": level_shape[0], + "OffsetX": 0, + "OffsetY": 0, } }, - 'Levels': [level_0_string], + "Levels": [level_0_string], } return yaml.dump(level_generator_gdy) @@ -95,22 +107,22 @@ def generate_env(self, size, **env_kwargs): env_args = { **env_kwargs, - 'yaml_string': env_yaml, + "yaml_string": env_yaml, } return GymWrapper(*env_args) -if __name__ == '__main__': +if __name__ == "__main__": wrapper_factory = GymWrapperFactory() - yaml_file = 'Single-Player/GVGAI/sokoban.yaml' + yaml_file = "Single-Player/GVGAI/sokoban.yaml" egg = EnvironmentGeneratorGenerator(yaml_file=yaml_file) for i in range(100): generator_yaml = egg.generate_env_yaml((10, 10)) - env_name = f'test_{i}' + env_name = f"test_{i}" wrapper_factory.build_gym_from_yaml_string( env_name, yaml_string=generator_yaml, @@ -119,9 +131,9 @@ def generate_env(self, size, **env_kwargs): player_observer_type=gd.ObserverType.VECTOR, ) - env = gym.make(f'GDY-{env_name}-v0') + env = gym.make(f"GDY-{env_name}-v0") env.reset() - #env = ValidActionSpaceWrapper(env) + # env = ValidActionSpaceWrapper(env) # visualization = env.render(observer=0, mode='rgb_array') # video_recorder = VideoRecorder() @@ -132,8 +144,7 @@ def generate_env(self, size, **env_kwargs): action = env.action_space.sample() obs, reward, done, info = env.step(action) - #state = env.get_state() + # state = env.get_state() - #visual = env.render(observer=0, mode='rgb_array') + # visual = env.render(observer=0, mode='rgb_array') # video_recorder.add_frame(visual) - diff --git a/python/griddly/util/observation_space.py b/python/griddly/util/observation_space.py index 7a43a527c..04da39e04 100644 --- a/python/griddly/util/observation_space.py +++ b/python/griddly/util/observation_space.py @@ -10,13 +10,20 @@ def __init__(self, agents_observation_space): self._agents_observation_space = agents_observation_space def sample(self): - """ samples observations for each agent from uniform distribution""" - return [agent_observation_space.sample() for agent_observation_space in self._agents_observation_space] + """samples observations for each agent from uniform distribution""" + return [ + agent_observation_space.sample() + for agent_observation_space in self._agents_observation_space + ] def contains(self, obs): - """ contains observation """ + """contains observation""" for space, ob in zip(self._agents_observation_space, obs): if not space.contains(ob): return False else: - return True \ No newline at end of file + return True + + def seed(self, seed): + for space in self._agents_observation_space: + space.seed(seed) diff --git a/python/griddly/util/rllib/callbacks.py b/python/griddly/util/rllib/callbacks.py index dfbfd0a09..d55cd919d 100644 --- a/python/griddly/util/rllib/callbacks.py +++ b/python/griddly/util/rllib/callbacks.py @@ -9,8 +9,7 @@ class GriddlyRLLibCallbacks(DefaultCallbacks): - """Contains helper functions for Griddly callbacks - """ + """Contains helper functions for Griddly callbacks""" def _get_envs(self, base_env): if isinstance(base_env, _VectorEnvToBaseEnv): @@ -22,105 +21,130 @@ def _get_player_ids(self, base_env, env_index): envs = self._get_envs(base_env) player_count = envs[env_index].player_count if player_count == 1: - return ['agent0'] + return ["agent0"] else: - return [p for p in range(1, player_count+1)] + return [p for p in range(1, player_count + 1)] -class VideoCallbacks(GriddlyRLLibCallbacks): - def on_episode_start(self, - *, - worker: "RolloutWorker", - base_env: BaseEnv, - policies: Dict[PolicyID, Policy], - episode: MultiAgentEpisode, - env_index: Optional[int] = None, - **kwargs) -> None: +class VideoCallbacks(GriddlyRLLibCallbacks): + def on_episode_start( + self, + *, + worker: "RolloutWorker", + base_env: BaseEnv, + policies: Dict[PolicyID, Policy], + episode: MultiAgentEpisode, + env_index: Optional[int] = None, + **kwargs, + ) -> None: envs = self._get_envs(base_env) envs[env_index].on_episode_start(worker.worker_index, env_index) - def on_episode_end(self, - *, - worker: "RolloutWorker", - base_env: BaseEnv, - policies: Dict[PolicyID, Policy], - episode: MultiAgentEpisode, - env_index: Optional[int] = None, - **kwargs) -> None: + def on_episode_end( + self, + *, + worker: "RolloutWorker", + base_env: BaseEnv, + policies: Dict[PolicyID, Policy], + episode: MultiAgentEpisode, + env_index: Optional[int] = None, + **kwargs, + ) -> None: envs = self._get_envs(base_env) for video in envs[env_index].videos: - level = video['level'] - path = video['path'] - episode.media[f'level_{level}'] = Video(path) + level = video["level"] + path = video["path"] + episode.media[f"level_{level}"] = Video(path) envs[env_index].videos = [] class ActionTrackerCallbacks(GriddlyRLLibCallbacks): - def __init__(self): super().__init__() self._action_frequency_trackers = {} - def on_episode_start(self, - *, - worker: "RolloutWorker", - base_env: BaseEnv, - policies: Dict[PolicyID, Policy], - episode: MultiAgentEpisode, - env_index: Optional[int] = None, - **kwargs) -> None: + def on_episode_start( + self, + *, + worker: "RolloutWorker", + base_env: BaseEnv, + policies: Dict[PolicyID, Policy], + episode: MultiAgentEpisode, + env_index: Optional[int] = None, + **kwargs, + ) -> None: self._action_frequency_trackers[episode.episode_id] = [] for _ in self._get_player_ids(base_env, env_index): self._action_frequency_trackers[episode.episode_id].append(Counter()) - def on_episode_step(self, - *, - worker: "RolloutWorker", - base_env: BaseEnv, - episode: MultiAgentEpisode, - env_index: Optional[int] = None, - **kwargs) -> None: + def on_episode_step( + self, + *, + worker: "RolloutWorker", + base_env: BaseEnv, + episode: MultiAgentEpisode, + env_index: Optional[int] = None, + **kwargs, + ) -> None: for p, id in enumerate(self._get_player_ids(base_env, env_index)): info = episode.last_info_for(id) - if 'History' in info: - history = info['History'] + if "History" in info: + history = info["History"] for event in history: - action_name = event['ActionName'] - self._action_frequency_trackers[episode.episode_id][p][action_name] += 1 - - def on_episode_end(self, *, worker: "RolloutWorker", base_env: BaseEnv, policies: Dict[PolicyID, Policy], - episode: MultiAgentEpisode, env_index: Optional[int] = None, **kwargs) -> None: + action_name = event["ActionName"] + self._action_frequency_trackers[episode.episode_id][p][ + action_name + ] += 1 + + def on_episode_end( + self, + *, + worker: "RolloutWorker", + base_env: BaseEnv, + policies: Dict[PolicyID, Policy], + episode: MultiAgentEpisode, + env_index: Optional[int] = None, + **kwargs, + ) -> None: for p, id in enumerate(self._get_player_ids(base_env, env_index)): - for action_name, frequency in self._action_frequency_trackers[episode.episode_id][p].items(): - episode.custom_metrics[f'agent_info/{id}/{action_name}'] = frequency + for action_name, frequency in self._action_frequency_trackers[ + episode.episode_id + ][p].items(): + episode.custom_metrics[f"agent_info/{id}/{action_name}"] = frequency del self._action_frequency_trackers[episode.episode_id] -class WinLoseMetricCallbacks(GriddlyRLLibCallbacks): +class WinLoseMetricCallbacks(GriddlyRLLibCallbacks): def __init__(self): super().__init__() - def on_episode_end(self, - *, - worker: "RolloutWorker", - base_env: BaseEnv, - policies: Dict[PolicyID, Policy], - episode: MultiAgentEpisode, - env_index: Optional[int] = None, - **kwargs) -> None: + def on_episode_end( + self, + *, + worker: "RolloutWorker", + base_env: BaseEnv, + policies: Dict[PolicyID, Policy], + episode: MultiAgentEpisode, + env_index: Optional[int] = None, + **kwargs, + ) -> None: for p, id in enumerate(self._get_player_ids(base_env, env_index)): info = episode.last_info_for(id) - episode.custom_metrics[f'agent_info/{id}/win'] = 1 if info['PlayerResults'][f'{p+1}'] == 'Win' else 0 - episode.custom_metrics[f'agent_info/{id}/lose'] = 1 if info['PlayerResults'][f'{p+1}'] == 'Lose' else 0 - episode.custom_metrics[f'agent_info/{id}/end'] = 1 if info['PlayerResults'][f'{p+1}'] == 'End' else 0 - - + episode.custom_metrics[f"agent_info/{id}/win"] = ( + 1 if info["PlayerResults"][f"{p+1}"] == "Win" else 0 + ) + episode.custom_metrics[f"agent_info/{id}/lose"] = ( + 1 if info["PlayerResults"][f"{p+1}"] == "Lose" else 0 + ) + episode.custom_metrics[f"agent_info/{id}/end"] = ( + 1 if info["PlayerResults"][f"{p+1}"] == "End" else 0 + ) diff --git a/python/griddly/util/rllib/environment/core.py b/python/griddly/util/rllib/environment/core.py index 49353ef2d..ae0d265e7 100644 --- a/python/griddly/util/rllib/environment/core.py +++ b/python/griddly/util/rllib/environment/core.py @@ -7,7 +7,9 @@ from ray.rllib.utils.typing import MultiAgentDict from griddly import GymWrapper -from griddly.util.rllib.environment.observer_episode_recorder import ObserverEpisodeRecorder +from griddly.util.rllib.environment.observer_episode_recorder import ( + ObserverEpisodeRecorder, +) class RLlibEnv(GymWrapper): @@ -52,27 +54,35 @@ def __init__(self, env_config): self.video_initialized = False - self.record_video_config = env_config.get('record_video_config', None) + self.record_video_config = env_config.get("record_video_config", None) self.videos = [] if self.record_video_config is not None: - self.video_frequency = self.record_video_config.get('frequency', 1000) - self.video_directory = os.path.realpath(self.record_video_config.get('directory', '.')) - self.include_global_video = self.record_video_config.get('include_global', True) - self.include_agent_videos = self.record_video_config.get('include_agents', False) + self.video_frequency = self.record_video_config.get("frequency", 1000) + self.video_directory = os.path.realpath( + self.record_video_config.get("directory", ".") + ) + self.include_global_video = self.record_video_config.get( + "include_global", True + ) + self.include_agent_videos = self.record_video_config.get( + "include_agents", False + ) os.makedirs(self.video_directory, exist_ok=True) - self.record_actions = env_config.get('record_actions', False) + self.record_actions = env_config.get("record_actions", False) - self.generate_valid_action_trees = env_config.get('generate_valid_action_trees', False) - self._random_level_on_reset = env_config.get('random_level_on_reset', False) - level_generator_rllib_config = env_config.get('level_generator', None) + self.generate_valid_action_trees = env_config.get( + "generate_valid_action_trees", False + ) + self._random_level_on_reset = env_config.get("random_level_on_reset", False) + level_generator_rllib_config = env_config.get("level_generator", None) self._level_generator = None if level_generator_rllib_config is not None: - level_generator_class = level_generator_rllib_config['class'] - level_generator_config = level_generator_rllib_config['config'] + level_generator_class = level_generator_rllib_config["class"] + level_generator_config = level_generator_rllib_config["config"] self._level_generator = level_generator_class(level_generator_config) self.reset() @@ -82,10 +92,14 @@ def __init__(self, env_config): def _transform(self, observation): if self.player_count > 1: - transformed_obs = [obs.transpose(1, 2, 0).astype(np.float) for obs in observation] + transformed_obs = [ + obs.transpose(1, 2, 0).astype(np.float) for obs in observation + ] elif isinstance(observation, dict): - transformed_obs = {k: v.transpose(1, 2, 0).astype(np.float) for k, v in observation.items()} - else: + transformed_obs = { + k: v.transpose(1, 2, 0).astype(np.float) for k, v in observation.items() + } + else: transformed_obs = observation.transpose(1, 2, 0).astype(np.float) return transformed_obs @@ -98,11 +112,15 @@ def _after_step(self, observation, reward, done, info): if self.is_video_enabled(): videos_list = [] if self.include_agent_videos: - video_info = self._agent_recorder.step(self.level_id, self.env_steps, done) + video_info = self._agent_recorder.step( + self.level_id, self.env_steps, done + ) if video_info is not None: videos_list.append(video_info) if self.include_global_video: - video_info = self._global_recorder.step(self.level_id, self.env_steps, done) + video_info = self._global_recorder.step( + self.level_id, self.env_steps, done + ) if video_info is not None: videos_list.append(video_info) @@ -137,9 +155,9 @@ def _get_valid_action_trees(self): def reset(self, **kwargs): if self._level_generator is not None: - kwargs['level_string'] = self._level_generator.generate() + kwargs["level_string"] = self._level_generator.generate() elif self._random_level_on_reset: - kwargs['level_id'] = np.random.choice(self.level_count) + kwargs["level_id"] = np.random.choice(self.level_count) observation = super().reset(**kwargs) self.set_transform() @@ -158,17 +176,21 @@ def step(self, action): if self.generate_valid_action_trees: self.last_valid_action_trees = self._get_valid_action_trees() - info['valid_action_tree'] = self.last_valid_action_trees.copy() + info["valid_action_tree"] = self.last_valid_action_trees.copy() self.env_steps += 1 return self._transform(observation), reward, done, info - def render(self, mode='human', observer=0): - return super().render(mode, observer='global') + def render(self, mode="human", observer=0): + return super().render(mode, observer="global") def is_video_enabled(self): - return self.record_video_config is not None and self._env_idx is not None and self._env_idx == 0 + return ( + self.record_video_config is not None + and self._env_idx is not None + and self._env_idx == 0 + ) def on_episode_start(self, worker_idx, env_idx): self._env_idx = env_idx @@ -182,26 +204,19 @@ def init_video_recording(self): if self.player_count == 1: if self.include_agent_videos: self._agent_recorder = ObserverEpisodeRecorder( - self, - 1, - self.video_frequency, - self.video_directory + self, 1, self.video_frequency, self.video_directory ) if self.include_global_video: self._global_recorder = ObserverEpisodeRecorder( - self, - 'global', - self.video_frequency, - self.video_directory + self, "global", self.video_frequency, self.video_directory ) class RLlibMultiAgentWrapper(gym.Wrapper, MultiAgentEnv): - def __init__(self, env, env_config): super().__init__(env) - self._player_done_variable = env_config.get('player_done_variable', None) + self._player_done_variable = env_config.get("player_done_variable", None) # Used to keep track of agents that are active in the environment self._active_agents = set() @@ -212,7 +227,9 @@ def __init__(self, env, env_config): self._worker_idx = None self._env_idx = None - assert self.player_count > 1, 'RLlibMultiAgentWrapper can only be used with environments that have multiple agents' + assert ( + self.player_count > 1 + ), "RLlibMultiAgentWrapper can only be used with environments that have multiple agents" def _to_multi_agent_map(self, data): return {a: data[a - 1] for a in self._active_agents} @@ -233,11 +250,15 @@ def _after_step(self, obs_map, reward_map, done_map, info_map): videos_list = [] if self.include_agent_videos: for a in self._active_agents: - video_info = self._agent_recorders[a].step(self.level_id, self.env_steps, done_map[a - 1]) + video_info = self._agent_recorders[a].step( + self.level_id, self.env_steps, done_map[a - 1] + ) if video_info is not None: videos_list.append(video_info) if self.include_global_video: - video_info = self._global_recorder.step(self.level_id, self.env_steps, done_map['__all__']) + video_info = self._global_recorder.step( + self.level_id, self.env_steps, done_map["__all__"] + ) if video_info is not None: videos_list.append(video_info) @@ -252,7 +273,7 @@ def step(self, action_dict: MultiAgentDict): obs, reward, all_done, info = super().step(actions_array) - done_map = {'__all__': all_done} + done_map = {"__all__": all_done} if self._player_done_variable is not None: griddly_players_done = self._resolve_player_done_variable() @@ -264,19 +285,22 @@ def step(self, action_dict: MultiAgentDict): done_map[p] = False if self.generate_valid_action_trees: - info_map = self._to_multi_agent_map([ - {'valid_action_tree': valid_action_tree} for valid_action_tree in info['valid_action_tree'] - ]) + info_map = self._to_multi_agent_map( + [ + {"valid_action_tree": valid_action_tree} + for valid_action_tree in info["valid_action_tree"] + ] + ) else: info_map = self._to_multi_agent_map(defaultdict(dict)) if self.record_actions: - for event in info['History']: - event_player_id = event['PlayerId'] + for event in info["History"]: + event_player_id = event["PlayerId"] if event_player_id != 0: - if 'History' not in info_map[event_player_id]: - info_map[event_player_id]['History'] = [] - info_map[event_player_id]['History'].append(event) + if "History" not in info_map[event_player_id]: + info_map[event_player_id]["History"] = [] + info_map[event_player_id]["History"].append(event) obs_map = self._to_multi_agent_map(obs) reward_map = self._to_multi_agent_map(reward) @@ -295,7 +319,11 @@ def step(self, action_dict: MultiAgentDict): return obs_map, reward_map, done_map, info_map def is_video_enabled(self): - return self.record_video_config is not None and self._env_idx is not None and self._env_idx == 0 + return ( + self.record_video_config is not None + and self._env_idx is not None + and self._env_idx == 0 + ) def on_episode_start(self, worker_idx, env_idx): self._env_idx = env_idx @@ -311,15 +339,9 @@ def init_video_recording(self): for a in range(self.player_count): agent_id = a + 1 self._agent_recorders[agent_id] = ObserverEpisodeRecorder( - self, - agent_id, - self.video_frequency, - self.video_directory + self, agent_id, self.video_frequency, self.video_directory ) if self.include_global_video: self._global_recorder = ObserverEpisodeRecorder( - self, - 'global', - self.video_frequency, - self.video_directory + self, "global", self.video_frequency, self.video_directory ) diff --git a/python/griddly/util/rllib/environment/level_generator.py b/python/griddly/util/rllib/environment/level_generator.py index c7ae47da5..9fbfb6a53 100644 --- a/python/griddly/util/rllib/environment/level_generator.py +++ b/python/griddly/util/rllib/environment/level_generator.py @@ -1,7 +1,6 @@ class LevelGenerator: - def __init__(self, config): self._config = config def generate(self): - raise NotImplementedError() \ No newline at end of file + raise NotImplementedError() diff --git a/python/griddly/util/rllib/environment/observer_episode_recorder.py b/python/griddly/util/rllib/environment/observer_episode_recorder.py index c943cf07f..6cc53800e 100644 --- a/python/griddly/util/rllib/environment/observer_episode_recorder.py +++ b/python/griddly/util/rllib/environment/observer_episode_recorder.py @@ -11,8 +11,8 @@ class RecordingState(Enum): BEFORE_RECORDING = 3 RECORDING = 4 -class ObserverEpisodeRecorder(): +class ObserverEpisodeRecorder: def __init__(self, env, observer, video_frequency, video_directory="."): self._video_frequency = video_frequency @@ -26,35 +26,35 @@ def step(self, level_id, step_count, done): video_info = None - if self._recording_state is RecordingState.NOT_RECORDING and step_count % self._video_frequency == 0: + if ( + self._recording_state is RecordingState.NOT_RECORDING + and step_count % self._video_frequency == 0 + ): self._recording_state = RecordingState.WAITING_FOR_EPISODE_START if self._recording_state == RecordingState.BEFORE_RECORDING: - obs = self._env.render(observer=self._observer, mode='rgb_array') + obs = self._env.render(observer=self._observer, mode="rgb_array") self._recorder = VideoRecorder() video_filename = os.path.join( self._video_directory, - f'episode_video_{self._observer}_{uuid1()}_{level_id}_{step_count}.mp4' + f"episode_video_{self._observer}_{uuid1()}_{level_id}_{step_count}.mp4", ) self._recorder.start(video_filename, obs.shape) self._recording_state = RecordingState.RECORDING if self._recording_state == RecordingState.RECORDING: - obs = self._env.render(observer=self._observer, mode='rgb_array') + obs = self._env.render(observer=self._observer, mode="rgb_array") self._recorder.add_frame(obs) if done: self._recording_state = RecordingState.NOT_RECORDING self._recorder.close() - video_info = { - 'level': level_id, - 'path': self._recorder.output_file - } + video_info = {"level": level_id, "path": self._recorder.output_file} if self._recording_state == RecordingState.WAITING_FOR_EPISODE_START: if done: self._recording_state = RecordingState.BEFORE_RECORDING - return video_info \ No newline at end of file + return video_info diff --git a/python/griddly/util/rllib/torch/__init__.py b/python/griddly/util/rllib/torch/__init__.py index aeeda35cb..781eeae0b 100644 --- a/python/griddly/util/rllib/torch/__init__.py +++ b/python/griddly/util/rllib/torch/__init__.py @@ -1 +1 @@ -from griddly.util.rllib.torch.agents.global_average_pooling_agent import GAPAgent \ No newline at end of file +from griddly.util.rllib.torch.agents.global_average_pooling_agent import GAPAgent diff --git a/python/griddly/util/rllib/torch/agents/conv_agent.py b/python/griddly/util/rllib/torch/agents/conv_agent.py index ff1ddd9b4..b72a9d4cd 100644 --- a/python/griddly/util/rllib/torch/agents/conv_agent.py +++ b/python/griddly/util/rllib/torch/agents/conv_agent.py @@ -4,6 +4,7 @@ from griddly.util.rllib.torch.agents.common import layer_init + class SimpleConvAgent(TorchModelV2, nn.Module): """ Simple Convolution agent that calculates the required linear output layer @@ -16,7 +17,7 @@ def __init__(self, obs_space, action_space, num_outputs, model_config, name): self._num_objects = obs_space.shape[2] self._num_actions = num_outputs - linear_flatten = np.prod(obs_space.shape[:2])*64 + linear_flatten = np.prod(obs_space.shape[:2]) * 64 self.network = nn.Sequential( layer_init(nn.Conv2d(self._num_objects, 32, 3, padding=1)), @@ -33,15 +34,13 @@ def __init__(self, obs_space, action_space, num_outputs, model_config, name): self._actor_head = nn.Sequential( layer_init(nn.Linear(512, 256), std=0.01), nn.ReLU(), - layer_init(nn.Linear(256, self._num_actions), std=0.01) + layer_init(nn.Linear(256, self._num_actions), std=0.01), ) - self._critic_head = nn.Sequential( - layer_init(nn.Linear(512, 1), std=0.01) - ) + self._critic_head = nn.Sequential(layer_init(nn.Linear(512, 1), std=0.01)) def forward(self, input_dict, state, seq_lens): - obs_transformed = input_dict['obs'].permute(0, 3, 1, 2) + obs_transformed = input_dict["obs"].permute(0, 3, 1, 2) network_output = self.network(obs_transformed) value = self._critic_head(network_output) self._value = value.reshape(-1) diff --git a/python/griddly/util/rllib/torch/agents/global_average_pooling_agent.py b/python/griddly/util/rllib/torch/agents/global_average_pooling_agent.py index 8fab31c26..0f73c4e67 100644 --- a/python/griddly/util/rllib/torch/agents/global_average_pooling_agent.py +++ b/python/griddly/util/rllib/torch/agents/global_average_pooling_agent.py @@ -7,13 +7,11 @@ class GlobalAvePool(nn.Module): - def __init__(self, final_channels): super().__init__() self._final_channels = final_channels self._pool = nn.Sequential( - nn.AdaptiveAvgPool3d((final_channels, 1, 1)), - nn.Flatten(), + nn.AdaptiveAvgPool3d((final_channels, 1, 1)), nn.Flatten(), ) def forward(self, input): @@ -51,15 +49,13 @@ def __init__(self, obs_space, action_space, num_outputs, model_config, name): self._actor_head = nn.Sequential( layer_init(nn.Linear(512, 256), std=0.01), nn.ReLU(), - layer_init(nn.Linear(256, self._num_actions), std=0.01) + layer_init(nn.Linear(256, self._num_actions), std=0.01), ) - self._critic_head = nn.Sequential( - layer_init(nn.Linear(512, 1), std=0.01) - ) + self._critic_head = nn.Sequential(layer_init(nn.Linear(512, 1), std=0.01)) def forward(self, input_dict, state, seq_lens): - obs_transformed = input_dict['obs'].permute(0, 3, 1, 2) + obs_transformed = input_dict["obs"].permute(0, 3, 1, 2) network_output = self.network(obs_transformed) value = self._critic_head(network_output) self._value = value.reshape(-1) diff --git a/python/griddly/util/rllib/torch/agents/impala_cnn.py b/python/griddly/util/rllib/torch/agents/impala_cnn.py index 70291c7fa..f2a0c87cf 100644 --- a/python/griddly/util/rllib/torch/agents/impala_cnn.py +++ b/python/griddly/util/rllib/torch/agents/impala_cnn.py @@ -7,8 +7,12 @@ class ResidualBlock(nn.Module): def __init__(self, channels): super().__init__() - self.conv0 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1) - self.conv1 = nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, padding=1) + self.conv0 = nn.Conv2d( + in_channels=channels, out_channels=channels, kernel_size=3, padding=1 + ) + self.conv1 = nn.Conv2d( + in_channels=channels, out_channels=channels, kernel_size=3, padding=1 + ) def forward(self, x): inputs = x @@ -24,8 +28,12 @@ def __init__(self, input_shape, out_channels): super().__init__() self._input_shape = input_shape self._out_channels = out_channels - self.conv = nn.Conv2d(in_channels=self._input_shape[0], out_channels=self._out_channels, kernel_size=3, - padding=1) + self.conv = nn.Conv2d( + in_channels=self._input_shape[0], + out_channels=self._out_channels, + kernel_size=3, + padding=1, + ) self.res_block0 = ResidualBlock(self._out_channels) self.res_block1 = ResidualBlock(self._out_channels) @@ -69,7 +77,7 @@ def __init__(self, obs_space, action_space, num_outputs, model_config, name): self._critic_head = layer_init(nn.Linear(256, 1), std=1) def forward(self, input_dict, state, seq_lens): - obs_transformed = input_dict['obs'].permute(0, 3, 1, 2) + obs_transformed = input_dict["obs"].permute(0, 3, 1, 2) network_output = self.network(obs_transformed) value = self._critic_head(network_output) self._value = value.reshape(-1) diff --git a/python/griddly/util/rllib/torch/conditional_actions/conditional_action_exploration.py b/python/griddly/util/rllib/torch/conditional_actions/conditional_action_exploration.py index 61298d426..2033cd74f 100644 --- a/python/griddly/util/rllib/torch/conditional_actions/conditional_action_exploration.py +++ b/python/griddly/util/rllib/torch/conditional_actions/conditional_action_exploration.py @@ -6,8 +6,7 @@ import numpy as np -class TorchConditionalMaskingExploration(): - +class TorchConditionalMaskingExploration: def __init__(self, model, dist_inputs, valid_action_trees, explore=False): self._valid_action_trees = valid_action_trees @@ -67,8 +66,12 @@ def _process_valid_action_tree_batched(self, valid_action_tree): def get_actions_and_mask(self): - actions = torch.zeros([self._num_inputs, self._num_action_parts]).to(self.device) - masked_logits = torch.zeros([self._num_inputs, self._num_action_logits]).to(self.device) + actions = torch.zeros([self._num_inputs, self._num_action_parts]).to( + self.device + ) + masked_logits = torch.zeros([self._num_inputs, self._num_action_logits]).to( + self.device + ) mask = torch.zeros([self._num_inputs, self._num_action_logits]).to(self.device) logp_sums = torch.zeros([self._num_inputs]).to(self.device) @@ -76,18 +79,30 @@ def get_actions_and_mask(self): if len(self._valid_action_trees) >= 1: - subtrees = [self._process_valid_action_tree_batched(tree) for tree in self._valid_action_trees] + subtrees = [ + self._process_valid_action_tree_batched(tree) + for tree in self._valid_action_trees + ] mask_offset = 0 for a in range(self._num_action_parts): dist_part = self._inputs_split[a] - sampled, subtrees, masked_part_logits, logp, mask_part = self._mask_and_sample(subtrees, - dist_part) + ( + sampled, + subtrees, + masked_part_logits, + logp, + mask_part, + ) = self._mask_and_sample(subtrees, dist_part) # Set the action and the mask for each part of the action actions[:, a] = sampled - masked_logits[:, mask_offset:mask_offset + self._action_space_shape[a]] = masked_part_logits - mask[:, mask_offset:mask_offset + self._action_space_shape[a]] = mask_part + masked_logits[ + :, mask_offset : mask_offset + self._action_space_shape[a] + ] = masked_part_logits + mask[ + :, mask_offset : mask_offset + self._action_space_shape[a] + ] = mask_part logp_sums += logp diff --git a/python/griddly/util/rllib/torch/conditional_actions/conditional_action_mixin.py b/python/griddly/util/rllib/torch/conditional_actions/conditional_action_mixin.py index 18ac6b45b..56860879d 100644 --- a/python/griddly/util/rllib/torch/conditional_actions/conditional_action_mixin.py +++ b/python/griddly/util/rllib/torch/conditional_actions/conditional_action_mixin.py @@ -5,7 +5,9 @@ from ray.rllib.utils import override from ray.rllib.utils.torch_ops import convert_to_non_torch_type -from griddly.util.rllib.torch.conditional_actions.conditional_action_exploration import TorchConditionalMaskingExploration +from griddly.util.rllib.torch.conditional_actions.conditional_action_exploration import ( + TorchConditionalMaskingExploration, +) class ConditionalActionMixin: @@ -14,14 +16,10 @@ def __init__(self): SampleBatch.INFOS: ViewRequirement(data_col=SampleBatch.INFOS, shift=-1) } - @override(Policy) def compute_actions_from_input_dict( - self, - input_dict, - explore=None, - timestep = None, - **kwargs): + self, input_dict, explore=None, timestep=None, **kwargs + ): explore = explore if explore is not None else self.config["explore"] timestep = timestep if timestep is not None else self.global_timestep @@ -34,62 +32,61 @@ def compute_actions_from_input_dict( input_dict[k] for k in input_dict.keys() if "state_in" in k[:8] ] # Calculate RNN sequence lengths. - seq_lens = np.array([1] * len(input_dict["obs"])) \ - if state_batches else None + seq_lens = np.array([1] * len(input_dict["obs"])) if state_batches else None self._is_recurrent = state_batches is not None and state_batches != [] # Switch to eval mode. self.model.eval() - dist_inputs, state_out = self.model(input_dict, state_batches, - seq_lens) + dist_inputs, state_out = self.model(input_dict, state_batches, seq_lens) - generate_valid_action_trees = self.config['env_config'].get('generate_valid_action_trees', False) + generate_valid_action_trees = self.config["env_config"].get( + "generate_valid_action_trees", False + ) extra_fetches = {} if generate_valid_action_trees: - infos = input_dict[SampleBatch.INFOS] if SampleBatch.INFOS in input_dict else {} + infos = ( + input_dict[SampleBatch.INFOS] + if SampleBatch.INFOS in input_dict + else {} + ) valid_action_trees = [] for info in infos: - if isinstance(info, dict) and 'valid_action_tree' in info: - valid_action_trees.append(info['valid_action_tree']) + if isinstance(info, dict) and "valid_action_tree" in info: + valid_action_trees.append(info["valid_action_tree"]) else: valid_action_trees.append({}) exploration = TorchConditionalMaskingExploration( - self.model, - dist_inputs, - valid_action_trees, - explore + self.model, dist_inputs, valid_action_trees, explore ) actions, masked_logits, logp, mask = exploration.get_actions_and_mask() - extra_fetches.update({ - 'invalid_action_mask': mask - }) + extra_fetches.update({"invalid_action_mask": mask}) else: action_dist = self.dist_class(dist_inputs, self.model) # Get the exploration action from the forward results. - actions, logp = \ - self.exploration.get_exploration_action( - action_distribution=action_dist, - timestep=timestep, - explore=explore) + actions, logp = self.exploration.get_exploration_action( + action_distribution=action_dist, timestep=timestep, explore=explore + ) masked_logits = dist_inputs input_dict[SampleBatch.ACTIONS] = actions - extra_fetches.update({ - SampleBatch.ACTION_DIST_INPUTS: masked_logits, - SampleBatch.ACTION_PROB: torch.exp(logp.float()), - SampleBatch.ACTION_LOGP: logp, - }) + extra_fetches.update( + { + SampleBatch.ACTION_DIST_INPUTS: masked_logits, + SampleBatch.ACTION_PROB: torch.exp(logp.float()), + SampleBatch.ACTION_LOGP: logp, + } + ) # Update our global timestep by the batch size. self.global_timestep += len(input_dict[SampleBatch.CUR_OBS]) diff --git a/python/griddly/util/rllib/torch/conditional_actions/conditional_action_policy_trainer.py b/python/griddly/util/rllib/torch/conditional_actions/conditional_action_policy_trainer.py index 40bac0a26..d8a044bc2 100644 --- a/python/griddly/util/rllib/torch/conditional_actions/conditional_action_policy_trainer.py +++ b/python/griddly/util/rllib/torch/conditional_actions/conditional_action_policy_trainer.py @@ -3,12 +3,18 @@ import torch from ray.rllib import SampleBatch from ray.rllib.agents.impala import ImpalaTrainer -from ray.rllib.agents.impala.vtrace_torch_policy import VTraceTorchPolicy, VTraceLoss, make_time_major +from ray.rllib.agents.impala.vtrace_torch_policy import ( + VTraceTorchPolicy, + VTraceLoss, + make_time_major, +) from ray.rllib.models.torch.torch_action_dist import TorchCategorical from ray.rllib.policy.torch_policy import LearningRateSchedule, EntropyCoeffSchedule from ray.rllib.utils.torch_ops import sequence_mask -from griddly.util.rllib.torch.conditional_actions.conditional_action_mixin import ConditionalActionMixin +from griddly.util.rllib.torch.conditional_actions.conditional_action_mixin import ( + ConditionalActionMixin, +) def build_invalid_masking_vtrace_loss(policy, model, dist_class, train_batch): @@ -26,8 +32,7 @@ def build_invalid_masking_vtrace_loss(policy, model, dist_class, train_batch): output_hidden_shape = 1 def _make_time_major(*args, **kw): - return make_time_major(policy, train_batch.get("seq_lens"), *args, - **kw) + return make_time_major(policy, train_batch.get("seq_lens"), *args, **kw) actions = train_batch[SampleBatch.ACTIONS] dones = train_batch[SampleBatch.DONES] @@ -35,45 +40,43 @@ def _make_time_major(*args, **kw): behaviour_action_logp = train_batch[SampleBatch.ACTION_LOGP] behaviour_logits = train_batch[SampleBatch.ACTION_DIST_INPUTS] - invalid_action_mask = train_batch['invalid_action_mask'] + invalid_action_mask = train_batch["invalid_action_mask"] - if 'seq_lens' in train_batch: - max_seq_len = policy.config['rollout_fragment_length'] + if "seq_lens" in train_batch: + max_seq_len = policy.config["rollout_fragment_length"] mask_orig = sequence_mask(train_batch["seq_lens"], max_seq_len) mask = torch.reshape(mask_orig, [-1]) else: mask = torch.ones_like(rewards) - model_out += torch.maximum(torch.tensor(torch.finfo().min), torch.log(invalid_action_mask)) + model_out += torch.maximum( + torch.tensor(torch.finfo().min), torch.log(invalid_action_mask) + ) action_dist = dist_class(model_out, model) if isinstance(output_hidden_shape, (list, tuple, np.ndarray)): unpacked_behaviour_logits = torch.split( - behaviour_logits, list(output_hidden_shape), dim=1) - unpacked_outputs = torch.split( - model_out, list(output_hidden_shape), dim=1) + behaviour_logits, list(output_hidden_shape), dim=1 + ) + unpacked_outputs = torch.split(model_out, list(output_hidden_shape), dim=1) else: unpacked_behaviour_logits = torch.chunk( - behaviour_logits, output_hidden_shape, dim=1) + behaviour_logits, output_hidden_shape, dim=1 + ) unpacked_outputs = torch.chunk(model_out, output_hidden_shape, dim=1) values = model.value_function() # Prepare actions for loss. - loss_actions = actions if is_multidiscrete else torch.unsqueeze( - actions, dim=1) + loss_actions = actions if is_multidiscrete else torch.unsqueeze(actions, dim=1) # Inputs are reshaped from [B * T] => [T - 1, B] for V-trace calc. policy.loss = VTraceLoss( actions=_make_time_major(loss_actions, drop_last=True), - actions_logp=_make_time_major( - action_dist.logp(actions), drop_last=True), - actions_entropy=_make_time_major( - action_dist.entropy(), drop_last=True), + actions_logp=_make_time_major(action_dist.logp(actions), drop_last=True), + actions_entropy=_make_time_major(action_dist.entropy(), drop_last=True), dones=_make_time_major(dones, drop_last=True), - behaviour_action_logp=_make_time_major( - behaviour_action_logp, drop_last=True), - behaviour_logits=_make_time_major( - unpacked_behaviour_logits, drop_last=True), + behaviour_action_logp=_make_time_major(behaviour_action_logp, drop_last=True), + behaviour_logits=_make_time_major(unpacked_behaviour_logits, drop_last=True), target_logits=_make_time_major(unpacked_outputs, drop_last=True), discount=policy.config["gamma"], rewards=_make_time_major(rewards, drop_last=True), @@ -86,15 +89,17 @@ def _make_time_major(*args, **kw): vf_loss_coeff=policy.config["vf_loss_coeff"], entropy_coeff=policy.entropy_coeff, clip_rho_threshold=policy.config["vtrace_clip_rho_threshold"], - clip_pg_rho_threshold=policy.config["vtrace_clip_pg_rho_threshold"]) + clip_pg_rho_threshold=policy.config["vtrace_clip_pg_rho_threshold"], + ) return policy.loss.total_loss def setup_mixins(policy, obs_space, action_space, config): ConditionalActionMixin.__init__(policy) - EntropyCoeffSchedule.__init__(policy, config["entropy_coeff"], - config["entropy_coeff_schedule"]) + EntropyCoeffSchedule.__init__( + policy, config["entropy_coeff"], config["entropy_coeff_schedule"] + ) LearningRateSchedule.__init__(policy, config["lr"], config["lr_schedule"]) @@ -102,17 +107,19 @@ def setup_mixins(policy, obs_space, action_space, config): name="ConditionalActionVTraceTorchPolicy", loss_fn=build_invalid_masking_vtrace_loss, before_init=setup_mixins, - mixins=[LearningRateSchedule, EntropyCoeffSchedule, ConditionalActionMixin] + mixins=[LearningRateSchedule, EntropyCoeffSchedule, ConditionalActionMixin], ) def get_vtrace_policy_class(config): - if config['framework'] == 'torch': + if config["framework"] == "torch": return ConditionalActionVTraceTorchPolicy else: - raise NotImplementedError('Tensorflow not supported') + raise NotImplementedError("Tensorflow not supported") -ConditionalActionImpalaTrainer = ImpalaTrainer.with_updates(name="ConditionalActionImpalaTrainer", - default_policy=ConditionalActionVTraceTorchPolicy, - get_policy_class=get_vtrace_policy_class) +ConditionalActionImpalaTrainer = ImpalaTrainer.with_updates( + name="ConditionalActionImpalaTrainer", + default_policy=ConditionalActionVTraceTorchPolicy, + get_policy_class=get_vtrace_policy_class, +) diff --git a/python/griddly/util/vector_visualization.py b/python/griddly/util/vector_visualization.py index 21f8dca08..27152984f 100644 --- a/python/griddly/util/vector_visualization.py +++ b/python/griddly/util/vector_visualization.py @@ -2,31 +2,35 @@ import colorsys -class Vector2RGB(): - +class Vector2RGB: def __init__(self, scale, object_channels): self._vector_observer_scale = scale self._object_channels = object_channels # Create a colour palette for rendering vector observers - HSV_tuples = [(x * 1.0 / (object_channels + 1), 1.0, 1.0) for x in range(object_channels + 1)] + HSV_tuples = [ + (x * 1.0 / (object_channels + 1), 1.0, 1.0) + for x in range(object_channels + 1) + ] vector_rgb = [] for hsv in HSV_tuples: vector_rgb.append(colorsys.hsv_to_rgb(*hsv)) - self._vector_rgb_palette = (np.array(vector_rgb) * 255).astype('uint8') + self._vector_rgb_palette = (np.array(vector_rgb) * 255).astype("uint8") def convert(self, observation): # Add extra dimension so argmax does not get confused by 0 index and empty space - palette_buffer = np.ones([self._object_channels + 1, *observation.shape[1:]]) * 0.5 + palette_buffer = ( + np.ones([self._object_channels + 1, *observation.shape[1:]]) * 0.5 + ) # only used for debugging offset = 0 # Only consider the object type when rendering - palette_buffer[1:] = observation[offset:self._object_channels+offset, :, :] + palette_buffer[1:] = observation[offset : self._object_channels + offset, :, :] # Convert to RGB pallette vector_pallette = np.argmax(palette_buffer, axis=0).swapaxes(0, 1) @@ -34,7 +38,8 @@ def convert(self, observation): buffer = self._vector_rgb_palette[vector_pallette] # Make the observation much bigger by repeating (this is horribly expensive) - return buffer \ - .repeat(self._vector_observer_scale, 0) \ - .repeat(self._vector_observer_scale, 1) \ + return ( + buffer.repeat(self._vector_observer_scale, 0) + .repeat(self._vector_observer_scale, 1) .swapaxes(0, 2) + ) diff --git a/python/griddly/util/wrappers/__init__.py b/python/griddly/util/wrappers/__init__.py index 2da6ac188..03f89a766 100644 --- a/python/griddly/util/wrappers/__init__.py +++ b/python/griddly/util/wrappers/__init__.py @@ -1 +1 @@ -from griddly.util.wrappers.valid_action_space_wrapper import ValidActionSpaceWrapper \ No newline at end of file +from griddly.util.wrappers.valid_action_space_wrapper import ValidActionSpaceWrapper diff --git a/python/griddly/util/wrappers/valid_action_space_wrapper.py b/python/griddly/util/wrappers/valid_action_space_wrapper.py index 68496a18d..00596e200 100644 --- a/python/griddly/util/wrappers/valid_action_space_wrapper.py +++ b/python/griddly/util/wrappers/valid_action_space_wrapper.py @@ -7,13 +7,13 @@ class ValidActionSpaceWrapper(gym.Wrapper): """ Creates a wrapper that can produce invalid action masking. - + the action space returned is a special case of MultiDiscrete called ValidatedMultiDiscrete. The ValidatedMultiDiscrete actions space only produces actions that are valid in the game when sampling. - + The action space shape is in the following format: [player_id, grid_height, grid_width, action_name_id, action_id] - + The action_name_id is an index of the action name in self.action_names object. The action_id is the action_id of an action. @@ -25,12 +25,14 @@ class ValidActionSpaceWrapper(gym.Wrapper): def __init__(self, env): if env.action_space is None or env.observation_space is None: - raise RuntimeError("Please reset the environment before applying the InvalidMaskingRTSWrapper") + raise RuntimeError( + "Please reset the environment before applying the InvalidMaskingRTSWrapper" + ) super().__init__(env) self.action_space = self._override_action_space() - def get_unit_location_mask(self, player_id, mask_type='full'): + def get_unit_location_mask(self, player_id, mask_type="full"): """ Returns a mask for grid_height and grid_width giving the available action locations. :param player_id: The player to generate masks for @@ -42,18 +44,22 @@ def get_unit_location_mask(self, player_id, mask_type='full'): assert player_id <= self.player_count, "Player does not exist." assert player_id > 0, "Player 0 is reserved for internal actions only." - if mask_type == 'full': + if mask_type == "full": grid_mask = np.zeros((self.grid_width, self.grid_height)) - for location, action_names in self.env.game.get_available_actions(player_id).items(): + for location, action_names in self.env.game.get_available_actions( + player_id + ).items(): grid_mask[[location[0]], [location[1]]] = 1 return grid_mask - elif mask_type == 'reduced': + elif mask_type == "reduced": grid_width_mask = np.zeros(self._grid_width) grid_height_mask = np.zeros(self._grid_height) - for location, action_names in self.env.game.get_available_actions(player_id).items(): + for location, action_names in self.env.game.get_available_actions( + player_id + ).items(): grid_width_mask[location[0]] = 1 grid_height_mask[location[1]] = 1 return grid_height_mask, grid_width_mask @@ -68,8 +74,12 @@ def get_unit_action_mask(self, location, action_names, padded=True): :return: """ action_masks = {} - for action_name, action_ids in self.env.game.get_available_action_ids(location, action_names).items(): - mask_size = self.max_action_ids if padded else self.num_action_ids[action_name] + for action_name, action_ids in self.env.game.get_available_action_ids( + location, action_names + ).items(): + mask_size = ( + self.max_action_ids if padded else self.num_action_ids[action_name] + ) action_ids_mask = np.zeros(mask_size) # action_id 0 is always a NOP action_ids_mask[0] = 1 diff --git a/python/requirements.txt b/python/requirements.txt index 4a9b04397..3c924c5b4 100644 --- a/python/requirements.txt +++ b/python/requirements.txt @@ -6,4 +6,5 @@ pygame>=2.0.0 matplotlib>=3.3.3 pyglet pytest>=6.2.1 +black diff --git a/python/setup.py b/python/setup.py index 4cde7369c..872fd55af 100644 --- a/python/setup.py +++ b/python/setup.py @@ -71,7 +71,7 @@ def griddly_package_data(config='Debug'): setup( name='griddly', - version="1.2.35", + version="1.2.36", author_email="chrisbam4d@gmail.com", description="Griddly Python Libraries", long_description=long_description, diff --git a/python/tests/cat_test.py b/python/tests/cat_test.py index 4d3fa4236..e18a7aba6 100644 --- a/python/tests/cat_test.py +++ b/python/tests/cat_test.py @@ -19,29 +19,24 @@ def build_test_env(test_name, yaml_file): player_observer_type=gd.ObserverType.VECTOR, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() return env def test_CAT_depth_1(test_name): - env = build_test_env( - test_name, - "tests/gdy/test_CAT_depth_1.yaml" - ) + env = build_test_env(test_name, "tests/gdy/test_CAT_depth_1.yaml") valid_action_trees = env.game.build_valid_action_trees() assert len(valid_action_trees) == 1 assert set(valid_action_trees[0].keys()) == {0, 1, 2, 3} + def test_CAT_depth_2(test_name): - env = build_test_env( - test_name, - "tests/gdy/test_CAT_depth_2.yaml" - ) + env = build_test_env(test_name, "tests/gdy/test_CAT_depth_2.yaml") valid_action_trees = env.game.build_valid_action_trees() @@ -51,12 +46,10 @@ def test_CAT_depth_2(test_name): assert set(valid_action_trees[0][0].keys()) == {0, 1, 2, 3} assert set(valid_action_trees[0][1].keys()) == {0, 4} + def test_CAT_depth_3(test_name): - env = build_test_env( - test_name, - "tests/gdy/test_CAT_depth_3.yaml" - ) + env = build_test_env(test_name, "tests/gdy/test_CAT_depth_3.yaml") valid_action_trees = env.game.build_valid_action_trees() @@ -65,12 +58,10 @@ def test_CAT_depth_3(test_name): assert set(valid_action_trees[0][1].keys()) == {1} assert set(valid_action_trees[0][1][1].keys()) == {0, 1, 2, 3} + def test_CAT_depth_4(test_name): - env = build_test_env( - test_name, - "tests/gdy/test_CAT_depth_4.yaml" - ) + env = build_test_env(test_name, "tests/gdy/test_CAT_depth_4.yaml") valid_action_trees = env.game.build_valid_action_trees() @@ -84,10 +75,7 @@ def test_CAT_depth_4(test_name): def test_CAT_depth_4_2_players(test_name): - env = build_test_env( - test_name, - "tests/gdy/test_CAT_depth_4_2_players.yaml" - ) + env = build_test_env(test_name, "tests/gdy/test_CAT_depth_4_2_players.yaml") valid_action_trees = env.game.build_valid_action_trees() @@ -104,4 +92,4 @@ def test_CAT_depth_4_2_players(test_name): assert set(valid_action_trees[1][3][1].keys()) == {0, 1} assert set(valid_action_trees[1][3][1][0].keys()) == {0, 1, 2, 3} - assert set(valid_action_trees[1][3][1][1].keys()) == {0, 4} \ No newline at end of file + assert set(valid_action_trees[1][3][1][1].keys()) == {0, 4} diff --git a/python/tests/cloned_env_test.py b/python/tests/cloned_env_test.py index 98e6547a7..9bb2d7818 100644 --- a/python/tests/cloned_env_test.py +++ b/python/tests/cloned_env_test.py @@ -12,7 +12,11 @@ def test_name(request): def test_action_and_object_names(test_name): for i in range(20): - env = gym.make('GDY-Sokoban-v0', global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR) + env = gym.make( + "GDY-Sokoban-v0", + global_observer_type=gd.ObserverType.VECTOR, + player_observer_type=gd.ObserverType.VECTOR, + ) env.reset() clone_env = env.clone() @@ -21,25 +25,39 @@ def test_action_and_object_names(test_name): assert object_names == cloned_object_names + def test_available_actions(test_name): - env = gym.make('GDY-Sokoban-v0', global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR) + env = gym.make( + "GDY-Sokoban-v0", + global_observer_type=gd.ObserverType.VECTOR, + player_observer_type=gd.ObserverType.VECTOR, + ) env.reset() clone_env = env.clone() available_actions = env.game.get_available_actions(1) player_pos = list(available_actions)[0] - actions = env.game.get_available_action_ids(player_pos, list(available_actions[player_pos])) + actions = env.game.get_available_action_ids( + player_pos, list(available_actions[player_pos]) + ) clone_available_actions = clone_env.game.get_available_actions(1) clone_player_pos = list(clone_available_actions)[0] - clone_actions = clone_env.game.get_available_action_ids(clone_player_pos, list(clone_available_actions[clone_player_pos])) + clone_actions = clone_env.game.get_available_action_ids( + clone_player_pos, list(clone_available_actions[clone_player_pos]) + ) assert actions == clone_actions + def test_random_trajectory_states(test_name): - env = gym.make('GDY-Sokoban-v0', global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR) + env = gym.make( + "GDY-Sokoban-v0", + global_observer_type=gd.ObserverType.VECTOR, + player_observer_type=gd.ObserverType.VECTOR, + ) env.reset() clone_env = env.clone() @@ -57,14 +75,21 @@ def test_random_trajectory_states(test_name): env_state = env.get_state() cloned_state = clone_env.get_state() - assert env_state['Hash'] == cloned_state['Hash'], f'state: {env_state}, cloned: {cloned_state}' + assert ( + env_state["Hash"] == cloned_state["Hash"] + ), f"state: {env_state}, cloned: {cloned_state}" if done and c_done: env.reset() clone_env.reset() + def test_vector_observer(test_name): - env = gym.make('GDY-Sokoban-v0', global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR) + env = gym.make( + "GDY-Sokoban-v0", + global_observer_type=gd.ObserverType.VECTOR, + player_observer_type=gd.ObserverType.VECTOR, + ) env.reset() clone_env = env.clone() @@ -73,12 +98,17 @@ def test_vector_observer(test_name): assert np.all(obs == c_obs) + def test_clone_multi_agent_done(test_name): """ In multi agent scenario we want to test that if one of the agents in multi-agent game is "done" then we can clone the environment without issue """ - env = GymWrapper(yaml_file='tests/gdy/multi_agent_remove.yaml', global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR) + env = GymWrapper( + yaml_file="tests/gdy/multi_agent_remove.yaml", + global_observer_type=gd.ObserverType.VECTOR, + player_observer_type=gd.ObserverType.VECTOR, + ) env.reset() # Remove one of the agents @@ -95,4 +125,3 @@ def test_clone_multi_agent_done(test_name): assert np.all(np.array(obs_2) == np.array(c_obs)) assert np.all(reward_2 == c_reward) assert np.all(done_2 == c_done) - diff --git a/python/tests/egg_test.py b/python/tests/egg_test.py index 633b1a153..a72bb72d7 100644 --- a/python/tests/egg_test.py +++ b/python/tests/egg_test.py @@ -9,10 +9,11 @@ def test_name(request): return request.node.name + def build_generator(test_name, yaml_file): wrapper_factory = GymWrapperFactory() egg = EnvironmentGeneratorGenerator(yaml_file=yaml_file) - generator_yaml = egg.generate_env_yaml((10,10)) + generator_yaml = egg.generate_env_yaml((10, 10)) wrapper_factory.build_gym_from_yaml_string( test_name, @@ -21,16 +22,17 @@ def build_generator(test_name, yaml_file): player_observer_type=gd.ObserverType.ASCII, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() return env + def test_spider_nest_generator(test_name): - yaml_file = 'Single-Player/GVGAI/spider-nest.yaml' + yaml_file = "Single-Player/GVGAI/spider-nest.yaml" for i in range(10): - genv = build_generator(test_name+f'{i}', yaml_file) + genv = build_generator(test_name + f"{i}", yaml_file) # Place 10 Random Objects for i in range(0, 100): @@ -38,6 +40,6 @@ def test_spider_nest_generator(test_name): obs, reward, done, info = genv.step(action) player_ascii_string = genv.render(observer=0) - global_ascii_string = genv.render(observer='global') + global_ascii_string = genv.render(observer="global") assert player_ascii_string == global_ascii_string diff --git a/python/tests/entity_observer_test.py b/python/tests/entity_observer_test.py index 35d68ecf7..1427e7769 100644 --- a/python/tests/entity_observer_test.py +++ b/python/tests/entity_observer_test.py @@ -17,10 +17,10 @@ def build_test_env(test_name, yaml_file, **kwargs): yaml_file, global_observer_type=gd.ObserverType.NONE, player_observer_type=gd.ObserverType.NONE, - **kwargs + **kwargs, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() return env @@ -33,8 +33,8 @@ def test_entity_observations(test_name): object_variable_map = env.game.get_object_variable_map() assert global_variables == ["_steps", "test_global_variable"] - assert object_variable_map['entity_1'] == ['entity_1_variable'] - assert object_variable_map['entity_2'] == ['entity_2_variable'] + assert object_variable_map["entity_1"] == ["entity_1_variable"] + assert object_variable_map["entity_2"] == ["entity_2_variable"] entity_observer = env.game.get_entity_observer() @@ -43,16 +43,16 @@ def test_entity_observations(test_name): entity_ids = entity_observation["EntityIds"] entity_masks = entity_observation["EntityMasks"] - entity_mask_one = entity_masks['move_one'] - actors_one = entity_mask_one['ActorEntityIds'] + entity_mask_one = entity_masks["move_one"] + actors_one = entity_mask_one["ActorEntityIds"] mask_one = entity_mask_one["Masks"] - assert actors_one == [entity_ids['entity_1'][0]] + assert actors_one == [entity_ids["entity_1"][0]] assert mask_one == [[1, 1, 1, 1, 0]] - entity_mask_two = entity_masks['move_two'] - actors_two = entity_mask_two['ActorEntityIds'] + entity_mask_two = entity_masks["move_two"] + actors_two = entity_mask_two["ActorEntityIds"] mask_two = entity_mask_two["Masks"] - assert actors_two == [entity_ids['entity_1'][0]] + assert actors_two == [entity_ids["entity_1"][0]] assert mask_two == [[1, 1, 1, 1]] diff --git a/python/tests/env_state_test.py b/python/tests/env_state_test.py index 2793960fc..2643f7640 100644 --- a/python/tests/env_state_test.py +++ b/python/tests/env_state_test.py @@ -3,6 +3,7 @@ import pytest from griddly import GymWrapperFactory, gd + @pytest.fixture def test_name(request): return request.node.name @@ -18,24 +19,24 @@ def build_test_env(test_name, yaml_file): player_observer_type=gd.ObserverType.VECTOR, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() return env + def test_state_hash_consistent_under_nop(test_name): """ Test that under NOP actions, the state hash stays the same no state change other than environment steps """ env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" ) first_state = env.get_state() env.step(0) second_state = env.get_state() - assert first_state['Hash'] == second_state['Hash'] + assert first_state["Hash"] == second_state["Hash"] def test_state_hash_consistent_return_to_state(test_name): @@ -43,22 +44,21 @@ def test_state_hash_consistent_return_to_state(test_name): Test that if we move to one state and back, the two states should have consistent states """ env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" ) first_state_hashes = [] second_state_hashes = [] - first_state_hashes.append(env.get_state()['Hash']) + first_state_hashes.append(env.get_state()["Hash"]) env.step(1) - second_state_hashes.append(env.get_state()['Hash']) + second_state_hashes.append(env.get_state()["Hash"]) env.step(3) - first_state_hashes.append(env.get_state()['Hash']) + first_state_hashes.append(env.get_state()["Hash"]) env.step(1) - second_state_hashes.append(env.get_state()['Hash']) + second_state_hashes.append(env.get_state()["Hash"]) assert len(set(first_state_hashes)) == 1 - assert len(set(second_state_hashes)) == 1 \ No newline at end of file + assert len(set(second_state_hashes)) == 1 diff --git a/python/tests/example_mechanics/project_lines/test_project_lines.py b/python/tests/example_mechanics/project_lines/test_project_lines.py index f8f594d82..c91edfcf6 100644 --- a/python/tests/example_mechanics/project_lines/test_project_lines.py +++ b/python/tests/example_mechanics/project_lines/test_project_lines.py @@ -18,153 +18,355 @@ def verify_state(env, action, state_vector): def test_project_lines(): current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper(current_path + '/project_lines.yaml', - player_observer_type=gd.ObserverType.VECTOR, - global_observer_type=gd.ObserverType.VECTOR, - level=0) + env = GymWrapper( + current_path + "/project_lines.yaml", + player_observer_type=gd.ObserverType.VECTOR, + global_observer_type=gd.ObserverType.VECTOR, + level=0, + ) env.reset() # Replace with your own control algorithm! - verify_state(env, [1, 1], np.array([[[0, 0, 0, 0, 0, 0,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[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]])) # place bomb - verify_state(env, [0, 1], np.array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0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], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]])) # move left - verify_state(env, [0, 2], np.array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [[0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0], - [0, 0, 0, 0, 0, 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, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0]], - [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]])) # move up - verify_state(env, [0, 1], np.array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0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 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]])) # NOP - verify_state(env, [0, 1], np.array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]])) # NOP + verify_state( + env, + [1, 1], + np.array( + [ + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ], + ] + ), + ) # place bomb + verify_state( + env, + [0, 1], + np.array( + [ + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ], + ] + ), + ) # move left + verify_state( + env, + [0, 2], + np.array( + [ + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 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, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ], + ] + ), + ) # move up + verify_state( + env, + [0, 1], + np.array( + [ + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 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, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ], + ] + ), + ) # NOP + verify_state( + env, + [0, 1], + np.array( + [ + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + [ + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ], + ] + ), + ) # NOP print("complete") diff --git a/python/tests/example_mechanics/projectile_objects/test_projectiles.py b/python/tests/example_mechanics/projectile_objects/test_projectiles.py index e133fc838..383ebc367 100644 --- a/python/tests/example_mechanics/projectile_objects/test_projectiles.py +++ b/python/tests/example_mechanics/projectile_objects/test_projectiles.py @@ -19,582 +19,710 @@ def verify_state(env, action, state_vector): def test_projectiles(): current_path = os.path.dirname(os.path.realpath(__file__)) - env = GymWrapper(current_path + '/projectiles.yaml', - player_observer_type=gd.ObserverType.VECTOR, - global_observer_type=gd.ObserverType.VECTOR, - level=0) + env = GymWrapper( + current_path + "/projectiles.yaml", + player_observer_type=gd.ObserverType.VECTOR, + global_observer_type=gd.ObserverType.VECTOR, + level=0, + ) env.reset() # Fire spider - verify_state(env, [1, 1], np.array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + ] + ), + ) print("complete") diff --git a/python/tests/history_test.py b/python/tests/history_test.py index e2a020f6b..f80586ca4 100644 --- a/python/tests/history_test.py +++ b/python/tests/history_test.py @@ -19,7 +19,7 @@ def build_test_env(test_name, yaml_file, enable_history=True): player_observer_type=gd.ObserverType.VECTOR, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() env.enable_history(enable_history) return env @@ -32,27 +32,28 @@ def test_history_SinglePlayer_HasHistory(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" ) obs, reward, done, info = env.step(1) - expected_history = [{ - 'PlayerId': 1, - 'ActionName': 'move', - 'Tick': 0, - 'Rewards': {}, - 'Delay': 0, - 'SourceObjectName': 'avatar', - 'DestinationObjectName': '_empty', - 'SourceObjectPlayerId': 1, - 'DestinationObjectPlayerId': 0, - 'SourceLocation': [2.0, 3.0], - 'DestinationLocation': [1.0, 3.0] - }] - - assert info['History'] == expected_history + expected_history = [ + { + "PlayerId": 1, + "ActionName": "move", + "Tick": 0, + "Rewards": {}, + "Delay": 0, + "SourceObjectName": "avatar", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 1, + "DestinationObjectPlayerId": 0, + "SourceLocation": [2.0, 3.0], + "DestinationLocation": [1.0, 3.0], + } + ] + + assert info["History"] == expected_history def test_history_SinglePlayer_NoHistory(test_name): @@ -64,12 +65,12 @@ def test_history_SinglePlayer_NoHistory(test_name): env = build_test_env( test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml", - enable_history=False + enable_history=False, ) obs, reward, done, info = env.step(1) - assert 'History' not in info + assert "History" not in info sample = env.action_space.sample() assert isinstance(sample, int) @@ -77,35 +78,51 @@ def test_history_SinglePlayer_NoHistory(test_name): def test_history_SinglePlayer_MultipleAction(test_name): """ - There is no avatar - Player performing multiple actions in a single step - - env.step([ - [x1, y1, actionId1], - [x2, y2, actionId2] - ]) - """ + There is no avatar + Player performing multiple actions in a single step + + env.step([ + [x1, y1, actionId1], + [x2, y2, actionId2] + ]) + """ env = build_test_env( test_name, - "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType_MultipleAction.yaml" + "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType_MultipleAction.yaml", ) - obs, reward, done, info = env.step([ - [2, 3, 1], - [1, 4, 3], - ]) + obs, reward, done, info = env.step([[2, 3, 1], [1, 4, 3],]) expected_history = [ - {'PlayerId': 1, 'ActionName': 'move', 'Tick': 0, 'Rewards': {}, 'Delay': 0, 'SourceObjectName': 'avatar1', - 'DestinationObjectName': '_empty', - 'SourceObjectPlayerId': 1, 'DestinationObjectPlayerId': 0, 'SourceLocation': [2.0, 3.0], - 'DestinationLocation': [1.0, 3.0]}, - {'PlayerId': 1, 'ActionName': 'move', 'Tick': 0, 'Rewards': {}, 'Delay': 0, 'SourceObjectName': 'avatar2', - 'DestinationObjectName': '_empty', - 'SourceObjectPlayerId': 1, 'DestinationObjectPlayerId': 0, 'SourceLocation': [1.0, 4.0], - 'DestinationLocation': [2.0, 4.0]}] - - assert info['History'] == expected_history + { + "PlayerId": 1, + "ActionName": "move", + "Tick": 0, + "Rewards": {}, + "Delay": 0, + "SourceObjectName": "avatar1", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 1, + "DestinationObjectPlayerId": 0, + "SourceLocation": [2.0, 3.0], + "DestinationLocation": [1.0, 3.0], + }, + { + "PlayerId": 1, + "ActionName": "move", + "Tick": 0, + "Rewards": {}, + "Delay": 0, + "SourceObjectName": "avatar2", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 1, + "DestinationObjectPlayerId": 0, + "SourceLocation": [1.0, 4.0], + "DestinationLocation": [2.0, 4.0], + }, + ] + + assert info["History"] == expected_history def test_history_MultiplePlayer_History(test_name): @@ -119,24 +136,41 @@ def test_history_MultiplePlayer_History(test_name): ]) """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" ) - obs, reward, done, info = env.step([ - 1, - 3, - ]) + obs, reward, done, info = env.step([1, 3,]) expected_history = [ - {'PlayerId': 1, 'ActionName': 'move', 'Tick': 0, 'Rewards': {}, 'Delay': 0, 'SourceObjectName': 'avatar', - 'DestinationObjectName': '_empty', 'SourceObjectPlayerId': 1, 'DestinationObjectPlayerId': 0, - 'SourceLocation': [1.0, 3.0], 'DestinationLocation': [0.0, 3.0]}, - {'PlayerId': 2, 'ActionName': 'move', 'Tick': 0, 'Rewards': {}, 'Delay': 0, 'SourceObjectName': 'avatar', - 'DestinationObjectName': '_empty', 'SourceObjectPlayerId': 2, 'DestinationObjectPlayerId': 0, - 'SourceLocation': [3.0, 3.0], 'DestinationLocation': [4.0, 3.0]}] - - assert info['History'] == expected_history + { + "PlayerId": 1, + "ActionName": "move", + "Tick": 0, + "Rewards": {}, + "Delay": 0, + "SourceObjectName": "avatar", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 1, + "DestinationObjectPlayerId": 0, + "SourceLocation": [1.0, 3.0], + "DestinationLocation": [0.0, 3.0], + }, + { + "PlayerId": 2, + "ActionName": "move", + "Tick": 0, + "Rewards": {}, + "Delay": 0, + "SourceObjectName": "avatar", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 2, + "DestinationObjectPlayerId": 0, + "SourceLocation": [3.0, 3.0], + "DestinationLocation": [4.0, 3.0], + }, + ] + + assert info["History"] == expected_history def test_history_MultiplePlayer_MultipleAction_History(test_name): @@ -155,29 +189,53 @@ def test_history_MultiplePlayer_MultipleAction_History(test_name): """ env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType_MultipleAction.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType_MultipleAction.yaml", ) - obs, reward, done, info = env.step([ - [ - [1, 3, 0, 1], - [3, 4, 1, 3], - ], - [ - [3, 3, 0, 1], - ] - ]) + obs, reward, done, info = env.step( + [[[1, 3, 0, 1], [3, 4, 1, 3],], [[3, 3, 0, 1],],] + ) expected_history = [ - {'PlayerId': 1, 'ActionName': 'move', 'Tick': 0, 'Rewards': {}, 'Delay': 0, 'SourceObjectName': 'avatar1', - 'DestinationObjectName': '_empty', 'SourceObjectPlayerId': 1, 'DestinationObjectPlayerId': 0, - 'SourceLocation': [1.0, 3.0], 'DestinationLocation': [0.0, 3.0]}, - {'PlayerId': 1, 'ActionName': 'other_move', 'Tick': 0, 'Rewards': {1: 1}, 'Delay': 0, - 'SourceObjectName': 'avatar2', - 'DestinationObjectName': '_empty', 'SourceObjectPlayerId': 1, 'DestinationObjectPlayerId': 0, - 'SourceLocation': [3.0, 4.0], 'DestinationLocation': [4.0, 4.0]}, - {'PlayerId': 2, 'ActionName': 'move', 'Tick': 0, 'Rewards': {}, 'Delay': 0, 'SourceObjectName': 'avatar1', - 'DestinationObjectName': '_empty', 'SourceObjectPlayerId': 2, 'DestinationObjectPlayerId': 0, - 'SourceLocation': [3.0, 3.0], 'DestinationLocation': [2.0, 3.0]}] - - assert info['History'] == expected_history + { + "PlayerId": 1, + "ActionName": "move", + "Tick": 0, + "Rewards": {}, + "Delay": 0, + "SourceObjectName": "avatar1", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 1, + "DestinationObjectPlayerId": 0, + "SourceLocation": [1.0, 3.0], + "DestinationLocation": [0.0, 3.0], + }, + { + "PlayerId": 1, + "ActionName": "other_move", + "Tick": 0, + "Rewards": {1: 1}, + "Delay": 0, + "SourceObjectName": "avatar2", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 1, + "DestinationObjectPlayerId": 0, + "SourceLocation": [3.0, 4.0], + "DestinationLocation": [4.0, 4.0], + }, + { + "PlayerId": 2, + "ActionName": "move", + "Tick": 0, + "Rewards": {}, + "Delay": 0, + "SourceObjectName": "avatar1", + "DestinationObjectName": "_empty", + "SourceObjectPlayerId": 2, + "DestinationObjectPlayerId": 0, + "SourceLocation": [3.0, 3.0], + "DestinationLocation": [2.0, 3.0], + }, + ] + + assert info["History"] == expected_history diff --git a/python/tests/random_seed_test.py b/python/tests/random_seed_test.py index 411a9b4fe..77dc35b90 100644 --- a/python/tests/random_seed_test.py +++ b/python/tests/random_seed_test.py @@ -1,17 +1,19 @@ from griddly import GymWrapper, gd import numpy as np + def create_env(): env = GymWrapper( - yaml_file='Single-Player/Mini-Grid/minigrid-spiders.yaml', + yaml_file="Single-Player/Mini-Grid/minigrid-spiders.yaml", global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR, - level=3 + level=3, ) env.reset() return env + def test_random_seed_consistency(): env1 = create_env() env2 = create_env() @@ -27,10 +29,12 @@ def test_random_seed_consistency(): obs1, reward1, done1, info1 = env1.step(action1) obs2, reward2, done2, info2 = env2.step(action2) - global_obs1 = env1.render(observer='global', mode='rgb_array') - global_obs2 = env2.render(observer='global', mode='rgb_array') + global_obs1 = env1.render(observer="global", mode="rgb_array") + global_obs2 = env2.render(observer="global", mode="rgb_array") - assert np.all(global_obs1 == global_obs2), f'global obs differ at test 1 step {i}' + assert np.all( + global_obs1 == global_obs2 + ), f"global obs differ at test 1 step {i}" assert np.all(obs1 == obs2) assert reward1 == reward2 @@ -53,10 +57,12 @@ def test_random_seed_consistency(): obs1, reward1, done1, info1 = env1.step(action1) obs2, reward2, done2, info2 = env2.step(action2) - global_obs1 = env1.render(observer='global', mode='rgb_array') - global_obs2 = env2.render(observer='global', mode='rgb_array') + global_obs1 = env1.render(observer="global", mode="rgb_array") + global_obs2 = env2.render(observer="global", mode="rgb_array") - assert np.all(global_obs1 == global_obs2), f' global obs differ at test 2 step {i}' + assert np.all( + global_obs1 == global_obs2 + ), f" global obs differ at test 2 step {i}" assert np.all(obs1 == obs2) assert reward1 == reward2 @@ -67,6 +73,7 @@ def test_random_seed_consistency(): env1.reset() env2.reset() + def test_random_seed_consistency_after_reset(): env1 = create_env() env2 = create_env() @@ -82,10 +89,12 @@ def test_random_seed_consistency_after_reset(): obs1, reward1, done1, info1 = env1.step(action1) obs2, reward2, done2, info2 = env2.step(action2) - global_obs1 = env1.render(observer='global', mode='rgb_array') - global_obs2 = env2.render(observer='global', mode='rgb_array') + global_obs1 = env1.render(observer="global", mode="rgb_array") + global_obs2 = env2.render(observer="global", mode="rgb_array") - assert np.all(global_obs1 == global_obs2), f'global obs differ at test 1 step {i}' + assert np.all( + global_obs1 == global_obs2 + ), f"global obs differ at test 1 step {i}" assert np.all(obs1 == obs2) assert reward1 == reward2 @@ -104,13 +113,14 @@ def test_random_seed_consistency_after_reset(): obs1, reward1, done1, info1 = env1.step(action1) obs2, reward2, done2, info2 = env2.step(action2) - global_obs1 = env1.render(observer='global', mode='rgb_array') - global_obs2 = env2.render(observer='global', mode='rgb_array') + global_obs1 = env1.render(observer="global", mode="rgb_array") + global_obs2 = env2.render(observer="global", mode="rgb_array") - assert np.all(global_obs1 == global_obs2), f' global obs differ at test 2 step {i}' + assert np.all( + global_obs1 == global_obs2 + ), f" global obs differ at test 2 step {i}" assert np.all(obs1 == obs2) assert reward1 == reward2 assert done1 == done2 assert info1 == info2 - diff --git a/python/tests/reset_test.py b/python/tests/reset_test.py index 3896b65ac..d11a8965e 100644 --- a/python/tests/reset_test.py +++ b/python/tests/reset_test.py @@ -21,7 +21,7 @@ def build_env(test_name, yaml_file, global_observations=False): player_observer_type=gd.ObserverType.VECTOR, ) - return gym.make(f'GDY-{test_name}-v0') + return gym.make(f"GDY-{test_name}-v0") def test_reset_SinglePlayer(test_name): @@ -32,10 +32,7 @@ def test_reset_SinglePlayer(test_name): np.array([player observations]) """ - env = build_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" - ) + env = build_env(test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml") obs = env.reset() assert isinstance(obs, np.ndarray) @@ -67,14 +64,11 @@ def test_reset_SinglePlayer_Global(test_name): """ - env = build_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" - ) + env = build_env(test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml") obs = env.reset(global_observations=True) - global_obs = obs['global'] - player_obs = obs['player'] + global_obs = obs["global"] + player_obs = obs["player"] assert isinstance(player_obs, np.ndarray) assert isinstance(global_obs, np.ndarray) @@ -87,8 +81,8 @@ def test_reset_SinglePlayer_Global(test_name): obs = env.reset(global_observations=True) - global_obs = obs['global'] - player_obs = obs['player'] + global_obs = obs["global"] + player_obs = obs["player"] assert isinstance(player_obs, np.ndarray) assert isinstance(global_obs, np.ndarray) @@ -112,10 +106,7 @@ def test_reset_MultiPlayer(test_name): """ - env = build_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" - ) + env = build_env(test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml") obs = env.reset() for p in range(env.player_count): @@ -137,7 +128,6 @@ def test_reset_MultiPlayer(test_name): assert env.action_space[p].n == 5 - def test_reset_MultiPlayer_Global(test_name): """ Multiple players. reset should return: @@ -152,14 +142,11 @@ def test_reset_MultiPlayer_Global(test_name): } """ - env = build_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" - ) + env = build_env(test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml") obs = env.reset(global_observations=True) - global_obs = obs['global'] - player_obs = obs['player'] + global_obs = obs["global"] + player_obs = obs["player"] assert isinstance(global_obs, np.ndarray) assert global_obs.shape == (1, 5, 6) @@ -174,8 +161,8 @@ def test_reset_MultiPlayer_Global(test_name): obs = env.reset(global_observations=True) - global_obs = obs['global'] - player_obs = obs['player'] + global_obs = obs["global"] + player_obs = obs["player"] assert isinstance(global_obs, np.ndarray) assert global_obs.shape == (1, 5, 6) @@ -204,13 +191,12 @@ def test_reset_MultiPlayer_MultiActionSpace(test_name): """ env = build_env( - test_name, - "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" ) obs = env.reset(global_observations=True) - global_obs = obs['global'] - player_obs = obs['player'] + global_obs = obs["global"] + player_obs = obs["player"] assert isinstance(global_obs, np.ndarray) assert global_obs.shape == (1, 5, 6) @@ -224,8 +210,8 @@ def test_reset_MultiPlayer_MultiActionSpace(test_name): obs = env.reset(global_observations=True) - global_obs = obs['global'] - player_obs = obs['player'] + global_obs = obs["global"] + player_obs = obs["player"] assert isinstance(global_obs, np.ndarray) assert global_obs.shape == (1, 5, 6) diff --git a/python/tests/step_test.py b/python/tests/step_test.py index 486ffa719..9e6087ed8 100644 --- a/python/tests/step_test.py +++ b/python/tests/step_test.py @@ -19,15 +19,15 @@ def build_test_env(test_name, yaml_file): player_observer_type=gd.ObserverType.VECTOR, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() return env def get_object_state(env, object_name, player=1): state = env.get_state() - for object in state['Objects']: - if object['Name'] == object_name and object['PlayerId'] == player: + for object in state["Objects"]: + if object["Name"] == object_name and object["PlayerId"] == player: return object @@ -38,8 +38,7 @@ def test_step_SinglePlayer_SingleActionType_SingleValue(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" ) assert env.observation_space.shape == (1, 5, 6) @@ -47,12 +46,12 @@ def test_step_SinglePlayer_SingleActionType_SingleValue(test_name): assert env.action_space.shape == () assert env.action_space.n == 5 - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] obs, reward, done, info = env.step(1) - avatar_state = get_object_state(env, 'avatar') + avatar_state = get_object_state(env, "avatar") - assert avatar_state['Location'] == [1, 3] + assert avatar_state["Location"] == [1, 3] sample = env.action_space.sample() assert isinstance(sample, int) @@ -64,8 +63,7 @@ def test_step_SinglePlayer_SingleActionType_ArrayValue(test_name): Action is in form env.step([actionId]) """ env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" ) assert env.observation_space.shape == (1, 5, 6) @@ -73,7 +71,7 @@ def test_step_SinglePlayer_SingleActionType_ArrayValue(test_name): assert env.action_space.shape == () assert env.action_space.n == 5 - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] obs, reward, done, info = env.step([1]) @@ -82,9 +80,9 @@ def test_step_SinglePlayer_SingleActionType_ArrayValue(test_name): assert not done assert info == {} - avatar_state = get_object_state(env, 'avatar') + avatar_state = get_object_state(env, "avatar") - assert avatar_state['Location'] == [1, 3] + assert avatar_state["Location"] == [1, 3] sample = env.action_space.sample() assert isinstance(sample, int) @@ -98,8 +96,7 @@ def test_step_SinglePlayer_SelectSource_SingleActionType(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType.yaml" ) assert env.observation_space.shape == (1, 5, 6) @@ -107,7 +104,7 @@ def test_step_SinglePlayer_SelectSource_SingleActionType(test_name): assert env.action_space.shape == (3,) assert np.all(env.action_space.nvec == [5, 6, 5]) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] obs, reward, done, info = env.step([2, 3, 1]) @@ -116,9 +113,9 @@ def test_step_SinglePlayer_SelectSource_SingleActionType(test_name): assert not done assert info == {} - avatar_state = get_object_state(env, 'avatar') + avatar_state = get_object_state(env, "avatar") - assert avatar_state['Location'] == [1, 3] + assert avatar_state["Location"] == [1, 3] sample = env.action_space.sample() assert sample.shape == (3,) @@ -136,7 +133,7 @@ def test_step_SinglePlayer_SelectSource_SingleActionType_MultipleAction(test_nam """ env = build_test_env( test_name, - "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType_MultipleAction.yaml" + "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType_MultipleAction.yaml", ) assert env.observation_space.shape == (2, 5, 6) @@ -144,26 +141,22 @@ def test_step_SinglePlayer_SelectSource_SingleActionType_MultipleAction(test_nam assert env.action_space.shape == (3,) assert np.all(env.action_space.nvec == [5, 6, 5]) - - obs, reward, done, info = env.step([ - [2, 3, 1], - [1, 4, 3], - ]) + obs, reward, done, info = env.step([[2, 3, 1], [1, 4, 3],]) assert obs.shape == (2, 5, 6) assert reward == 0 assert not done assert info == {} - avatar1_state = get_object_state(env, 'avatar1') - avatar2_state = get_object_state(env, 'avatar2') + avatar1_state = get_object_state(env, "avatar1") + avatar2_state = get_object_state(env, "avatar2") - assert avatar1_state['Location'] == [1, 3] - assert avatar2_state['Location'] == [2, 4] + assert avatar1_state["Location"] == [1, 3] + assert avatar2_state["Location"] == [2, 4] object_names = env.game.get_object_names() - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[avartar1_id, 1, 3] == 1 assert obs[avartar2_id, 2, 4] == 1 @@ -179,8 +172,7 @@ def test_step_SinglePlayer_MultipleActionType(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_MultipleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_MultipleActionType.yaml" ) assert env.observation_space.shape == (1, 5, 6) @@ -188,7 +180,7 @@ def test_step_SinglePlayer_MultipleActionType(test_name): assert env.action_space.shape == (2,) assert np.all(env.action_space.nvec == [2, 5]) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] obs, reward, done, info = env.step([0, 1]) @@ -197,8 +189,8 @@ def test_step_SinglePlayer_MultipleActionType(test_name): assert not done assert info == {} - avatar_state = get_object_state(env, 'avatar') - assert avatar_state['Location'] == [1, 3] + avatar_state = get_object_state(env, "avatar") + assert avatar_state["Location"] == [1, 3] obs, reward, done, info = env.step([1, 3]) @@ -207,8 +199,8 @@ def test_step_SinglePlayer_MultipleActionType(test_name): assert not done assert info == {} - avatar_state = get_object_state(env, 'avatar') - assert avatar_state['Location'] == [2, 3] + avatar_state = get_object_state(env, "avatar") + assert avatar_state["Location"] == [2, 3] sample = env.action_space.sample() assert sample.shape == (2,) @@ -222,7 +214,7 @@ def test_step_SinglePlayer_SelectSource_MultipleActionType(test_name): """ env = build_test_env( test_name, - "tests/gdy/test_step_SinglePlayer_SelectSource_MultipleActionType.yaml" + "tests/gdy/test_step_SinglePlayer_SelectSource_MultipleActionType.yaml", ) assert env.observation_space.shape == (1, 5, 6) @@ -230,7 +222,7 @@ def test_step_SinglePlayer_SelectSource_MultipleActionType(test_name): assert env.action_space.shape == (4,) assert np.all(env.action_space.nvec == [5, 6, 2, 5]) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] obs, reward, done, info = env.step([2, 3, 0, 1]) @@ -239,8 +231,8 @@ def test_step_SinglePlayer_SelectSource_MultipleActionType(test_name): assert not done assert info == {} - avatar_state = get_object_state(env, 'avatar') - assert avatar_state['Location'] == [1, 3] + avatar_state = get_object_state(env, "avatar") + assert avatar_state["Location"] == [1, 3] obs, reward, done, info = env.step([1, 3, 1, 3]) @@ -249,8 +241,8 @@ def test_step_SinglePlayer_SelectSource_MultipleActionType(test_name): assert not done assert info == {} - avatar_state = get_object_state(env, 'avatar') - assert avatar_state['Location'] == [2, 3] + avatar_state = get_object_state(env, "avatar") + assert avatar_state["Location"] == [2, 3] sample = env.action_space.sample() assert sample.shape == (4,) @@ -268,7 +260,7 @@ def test_step_SinglePlayer_SelectSource_MultipleActionType_MultipleAction(test_n """ env = build_test_env( test_name, - "tests/gdy/test_step_SinglePlayer_SelectSource_MultipleActionType_MultipleAction.yaml" + "tests/gdy/test_step_SinglePlayer_SelectSource_MultipleActionType_MultipleAction.yaml", ) assert env.observation_space.shape == (2, 5, 6) @@ -276,42 +268,36 @@ def test_step_SinglePlayer_SelectSource_MultipleActionType_MultipleAction(test_n assert env.action_space.shape == (4,) assert np.all(env.action_space.nvec == [5, 6, 2, 5]) - obs, reward, done, info = env.step([ - [2, 3, 0, 1], - [1, 4, 0, 1] - ]) + obs, reward, done, info = env.step([[2, 3, 0, 1], [1, 4, 0, 1]]) assert obs.shape == (2, 5, 6) assert reward == 0 assert not done assert info == {} - - avatar1_state = get_object_state(env, 'avatar1') - avatar2_state = get_object_state(env, 'avatar2') - assert avatar1_state['Location'] == [1, 3] - assert avatar2_state['Location'] == [0, 4] + + avatar1_state = get_object_state(env, "avatar1") + avatar2_state = get_object_state(env, "avatar2") + assert avatar1_state["Location"] == [1, 3] + assert avatar2_state["Location"] == [0, 4] object_names = env.game.get_object_names() - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[avartar1_id, 1, 3] == 1 assert obs[avartar2_id, 0, 4] == 1 - obs, reward, done, info = env.step([ - [1, 3, 1, 3], - [0, 4, 1, 3] - ]) + obs, reward, done, info = env.step([[1, 3, 1, 3], [0, 4, 1, 3]]) assert obs.shape == (2, 5, 6) assert reward == 2 assert not done assert info == {} - - avatar1_state = get_object_state(env, 'avatar1') - avatar2_state = get_object_state(env, 'avatar2') - assert avatar1_state['Location'] == [2, 3] - assert avatar2_state['Location'] == [1, 4] + + avatar1_state = get_object_state(env, "avatar1") + avatar2_state = get_object_state(env, "avatar2") + assert avatar1_state["Location"] == [2, 3] + assert avatar2_state["Location"] == [1, 4] sample = env.action_space.sample() assert sample.shape == (4,) @@ -328,36 +314,32 @@ def test_step_MultiplePlayer_SingleActionType_SingleValue(test_name): ]) """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == () assert env.action_space[p].n == 5 - obs, reward, done, info = env.step([ - 1, - 3, - ]) + obs, reward, done, info = env.step([1, 3,]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 assert obs[1].shape == (1, 5, 6) assert reward[1] == 0 - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [4, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [4, 3] sample = env.action_space.sample() assert len(sample) == 2 @@ -374,25 +356,21 @@ def test_step_MultiplePlayer_SingleActionType_ArrayValue(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == () assert env.action_space[p].n == 5 - obs, reward, done, info = env.step([ - [1], - [3], - ]) + obs, reward, done, info = env.step([[1], [3],]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -401,11 +379,11 @@ def test_step_MultiplePlayer_SingleActionType_ArrayValue(test_name): assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [4, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [4, 3] sample = env.action_space.sample() assert len(sample) == 2 @@ -423,25 +401,21 @@ def test_step_MultiplePlayer_MultipleActionType(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == (2,) assert np.all(env.action_space[p].nvec == [2, 5]) - obs, reward, done, info = env.step([ - [0, 1], - [1, 3], - ]) + obs, reward, done, info = env.step([[0, 1], [1, 3],]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -450,11 +424,11 @@ def test_step_MultiplePlayer_MultipleActionType(test_name): assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [4, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [4, 3] sample = env.action_space.sample() assert len(sample) == 2 @@ -464,33 +438,29 @@ def test_step_MultiplePlayer_MultipleActionType(test_name): def test_step_MultiplePlayer_SelectSource_SingleActionType(test_name): """ - There no avatar, multiple players, single action type + There no avatar, multiple players, single action type - env.step([ - [x1, y1, actionId1], - [x2, y2, actionId2] - ]) - """ + env.step([ + [x1, y1, actionId1], + [x2, y2, actionId2] + ]) + """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == (3,) assert np.all(env.action_space[p].nvec == [5, 6, 5]) - obs, reward, done, info = env.step([ - [1, 3, 1], - [3, 3, 3], - ]) + obs, reward, done, info = env.step([[1, 3, 1], [3, 3, 3],]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -499,17 +469,18 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType(test_name): assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [4, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [4, 3] sample = env.action_space.sample() assert len(sample) == 2 assert sample[0].shape == (3,) assert sample[1].shape == (3,) + def test_step_MultiplePlayer_SelectSource_MultipleActionType(test_name): """ There no avatar, multiple players @@ -521,24 +492,21 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType(test_name): """ env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType.yaml", ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == (4,) assert np.all(env.action_space[p].nvec == [5, 6, 2, 5]) - obs, reward, done, info = env.step([ - [1, 3, 0, 1], - [3, 3, 1, 3], - ]) + obs, reward, done, info = env.step([[1, 3, 0, 1], [3, 3, 1, 3],]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -547,11 +515,11 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType(test_name): assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [4, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [4, 3] sample = env.action_space.sample() assert len(sample) == 2 @@ -575,7 +543,7 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction(test_n """ env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType_MultipleAction.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType_MultipleAction.yaml", ) assert len(env.observation_space) == 2 @@ -588,15 +556,7 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction(test_n assert env.action_space[p].shape == (3,) assert np.all(env.action_space[p].nvec == [5, 6, 5]) - obs, reward, done, info = env.step([ - [ - [1, 3, 1], - [3, 4, 3], - ], - [ - [3, 3, 1], - ] - ]) + obs, reward, done, info = env.step([[[1, 3, 1], [3, 4, 3],], [[3, 3, 1],],]) assert obs[0].shape == (2, 5, 6) assert reward[0] == 0 @@ -605,24 +565,24 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction(test_n assert not done assert info == {} - player1_avatar1_state = get_object_state(env, 'avatar1', player=1) - player1_avatar2_state = get_object_state(env, 'avatar2', player=1) + player1_avatar1_state = get_object_state(env, "avatar1", player=1) + player1_avatar2_state = get_object_state(env, "avatar2", player=1) - assert player1_avatar1_state['Location'] == [0, 3] - assert player1_avatar2_state['Location'] == [4, 4] + assert player1_avatar1_state["Location"] == [0, 3] + assert player1_avatar2_state["Location"] == [4, 4] object_names = env.game.get_object_names() - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[0][avartar1_id, 0, 3] == 1 assert obs[0][avartar2_id, 4, 4] == 1 - player2_avatar1_state = get_object_state(env, 'avatar1', player=2) - player2_avatar2_state = get_object_state(env, 'avatar2', player=2) + player2_avatar1_state = get_object_state(env, "avatar1", player=2) + player2_avatar2_state = get_object_state(env, "avatar2", player=2) - assert player2_avatar1_state['Location'] == [2, 3] - assert player2_avatar2_state['Location'] == [1, 4] + assert player2_avatar1_state["Location"] == [2, 3] + assert player2_avatar2_state["Location"] == [1, 4] assert obs[0][avartar1_id, 2, 3] == 1 assert obs[0][avartar2_id, 1, 4] == 1 @@ -649,7 +609,7 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction(test """ env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType_MultipleAction.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType_MultipleAction.yaml", ) assert len(env.observation_space) == 2 @@ -662,15 +622,9 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction(test assert env.action_space[p].shape == (4,) assert np.all(env.action_space[p].nvec == [5, 6, 2, 5]) - obs, reward, done, info = env.step([ - [ - [1, 3, 0, 1], - [3, 4, 1, 3], - ], - [ - [3, 3, 0, 1], - ] - ]) + obs, reward, done, info = env.step( + [[[1, 3, 0, 1], [3, 4, 1, 3],], [[3, 3, 0, 1],],] + ) assert obs[0].shape == (2, 5, 6) assert reward[0] == 1 @@ -679,27 +633,27 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction(test assert not done assert info == {} - player1_avatar1_state = get_object_state(env, 'avatar1', player=1) - player1_avatar2_state = get_object_state(env, 'avatar2', player=1) + player1_avatar1_state = get_object_state(env, "avatar1", player=1) + player1_avatar2_state = get_object_state(env, "avatar2", player=1) - assert player1_avatar1_state['Location'] == [0, 3] - assert player1_avatar2_state['Location'] == [4, 4] + assert player1_avatar1_state["Location"] == [0, 3] + assert player1_avatar2_state["Location"] == [4, 4] object_names = env.game.get_object_names() - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[0][avartar1_id, 0, 3] == 1 assert obs[0][avartar2_id, 4, 4] == 1 - player2_avatar1_state = get_object_state(env, 'avatar1', player=2) - player2_avatar2_state = get_object_state(env, 'avatar2', player=2) + player2_avatar1_state = get_object_state(env, "avatar1", player=2) + player2_avatar2_state = get_object_state(env, "avatar2", player=2) - assert player2_avatar1_state['Location'] == [2, 3] - assert player2_avatar2_state['Location'] == [1, 4] + assert player2_avatar1_state["Location"] == [2, 3] + assert player2_avatar2_state["Location"] == [1, 4] - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[1][avartar1_id, 2, 3] == 1 assert obs[1][avartar2_id, 1, 4] == 1 @@ -709,6 +663,7 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction(test assert sample[0].shape == (4,) assert sample[1].shape == (4,) + def test_step_MultiplePlayer_SingleActionType_SingleValue_Agent_DONE(test_name): """ There is an avatar @@ -720,36 +675,32 @@ def test_step_MultiplePlayer_SingleActionType_SingleValue_Agent_DONE(test_name): ]) """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == () assert env.action_space[p].n == 5 - obs, reward, done, info = env.step([ - 1, - None, - ]) + obs, reward, done, info = env.step([1, None,]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 assert obs[1].shape == (1, 5, 6) assert reward[1] == 0 - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [3, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [3, 3] sample = env.action_space.sample() assert len(sample) == 2 @@ -766,25 +717,21 @@ def test_step_MultiplePlayer_SingleActionType_ArrayValue_Agent_DONE(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == () assert env.action_space[p].n == 5 - obs, reward, done, info = env.step([ - [1], - None, - ]) + obs, reward, done, info = env.step([[1], None,]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -793,11 +740,11 @@ def test_step_MultiplePlayer_SingleActionType_ArrayValue_Agent_DONE(test_name): assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [3, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [3, 3] def test_step_MultiplePlayer_MultipleActionType_Agent_DONE(test_name): @@ -812,25 +759,21 @@ def test_step_MultiplePlayer_MultipleActionType_Agent_DONE(test_name): """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == (2,) assert np.all(env.action_space[p].nvec == [2, 5]) - obs, reward, done, info = env.step([ - [0, 1], - None, - ]) + obs, reward, done, info = env.step([[0, 1], None,]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -839,41 +782,38 @@ def test_step_MultiplePlayer_MultipleActionType_Agent_DONE(test_name): assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) + + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [3, 3] - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [3, 3] def test_step_MultiplePlayer_SelectSource_SingleActionType_Agent_DONE(test_name): """ - There no avatar, multiple players, single action type + There no avatar, multiple players, single action type - env.step([ - [x1, y1, actionId1], - None - ]) - """ + env.step([ + [x1, y1, actionId1], + None + ]) + """ env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType.yaml" ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == (3,) assert np.all(env.action_space[p].nvec == [5, 6, 5]) - obs, reward, done, info = env.step([ - [1, 3, 1], - None, - ]) + obs, reward, done, info = env.step([[1, 3, 1], None,]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -882,11 +822,12 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_Agent_DONE(test_name) assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) + + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [3, 3] - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [3, 3] def test_step_MultiplePlayer_SelectSource_MultipleActionType_Agent_DONE(test_name): """ @@ -899,24 +840,21 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_Agent_DONE(test_nam """ env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType.yaml", ) assert len(env.observation_space) == 2 assert len(env.action_space) == 2 assert env.global_observation_space.shape == (1, 5, 6) - assert env.game.get_object_names() == ['avatar'] + assert env.game.get_object_names() == ["avatar"] for p in range(env.player_count): assert env.observation_space[p].shape == (1, 5, 6) assert env.action_space[p].shape == (4,) assert np.all(env.action_space[p].nvec == [5, 6, 2, 5]) - obs, reward, done, info = env.step([ - [1, 3, 0, 1], - None, - ]) + obs, reward, done, info = env.step([[1, 3, 0, 1], None,]) assert obs[0].shape == (1, 5, 6) assert reward[0] == 0 @@ -925,11 +863,11 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_Agent_DONE(test_nam assert not done assert info == {} - player1_avatar_state = get_object_state(env, 'avatar', player=1) - player2_avatar_state = get_object_state(env, 'avatar', player=2) + player1_avatar_state = get_object_state(env, "avatar", player=1) + player2_avatar_state = get_object_state(env, "avatar", player=2) - assert player1_avatar_state['Location'] == [0, 3] - assert player2_avatar_state['Location'] == [3, 3] + assert player1_avatar_state["Location"] == [0, 3] + assert player2_avatar_state["Location"] == [3, 3] sample = env.action_space.sample() assert len(sample) == 2 @@ -937,7 +875,9 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_Agent_DONE(test_nam assert sample[1].shape == (4,) -def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction_Agent_DONE(test_name): +def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction_Agent_DONE( + test_name, +): """ There no avatar, multiple players @@ -953,7 +893,7 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction_Agent_ """ env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType_MultipleAction.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType_MultipleAction.yaml", ) assert len(env.observation_space) == 2 @@ -966,13 +906,7 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction_Agent_ assert env.action_space[p].shape == (3,) assert np.all(env.action_space[p].nvec == [5, 6, 5]) - obs, reward, done, info = env.step([ - [ - [1, 3, 1], - [3, 4, 3], - ], - None, - ]) + obs, reward, done, info = env.step([[[1, 3, 1], [3, 4, 3],], None,]) assert obs[0].shape == (2, 5, 6) assert reward[0] == 0 @@ -981,24 +915,24 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction_Agent_ assert not done assert info == {} - player1_avatar1_state = get_object_state(env, 'avatar1', player=1) - player1_avatar2_state = get_object_state(env, 'avatar2', player=1) + player1_avatar1_state = get_object_state(env, "avatar1", player=1) + player1_avatar2_state = get_object_state(env, "avatar2", player=1) - assert player1_avatar1_state['Location'] == [0, 3] - assert player1_avatar2_state['Location'] == [4, 4] + assert player1_avatar1_state["Location"] == [0, 3] + assert player1_avatar2_state["Location"] == [4, 4] object_names = env.game.get_object_names() - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[0][avartar1_id, 0, 3] == 1 assert obs[0][avartar2_id, 4, 4] == 1 - player2_avatar1_state = get_object_state(env, 'avatar1', player=2) - player2_avatar2_state = get_object_state(env, 'avatar2', player=2) + player2_avatar1_state = get_object_state(env, "avatar1", player=2) + player2_avatar2_state = get_object_state(env, "avatar2", player=2) - assert player2_avatar1_state['Location'] == [3, 3] - assert player2_avatar2_state['Location'] == [1, 4] + assert player2_avatar1_state["Location"] == [3, 3] + assert player2_avatar2_state["Location"] == [1, 4] assert obs[0][avartar1_id, 3, 3] == 1 assert obs[0][avartar2_id, 1, 4] == 1 @@ -1009,7 +943,9 @@ def test_step_MultiplePlayer_SelectSource_SingleActionType_MultipleAction_Agent_ assert sample[1].shape == (3,) -def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction_Agent_DONE(test_name): +def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction_Agent_DONE( + test_name, +): """ There no avatar, multiple players @@ -1025,7 +961,7 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction_Agen """ env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType_MultipleAction.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType_MultipleAction.yaml", ) assert len(env.observation_space) == 2 @@ -1038,14 +974,7 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction_Agen assert env.action_space[p].shape == (4,) assert np.all(env.action_space[p].nvec == [5, 6, 2, 5]) - obs, reward, done, info = env.step([ - [ - [1, 3, 0, 1], - [3, 4, 1, 3], - ], - None, - - ]) + obs, reward, done, info = env.step([[[1, 3, 0, 1], [3, 4, 1, 3],], None,]) assert obs[0].shape == (2, 5, 6) assert reward[0] == 1 @@ -1054,27 +983,27 @@ def test_step_MultiplePlayer_SelectSource_MultipleActionType_MultipleAction_Agen assert not done assert info == {} - player1_avatar1_state = get_object_state(env, 'avatar1', player=1) - player1_avatar2_state = get_object_state(env, 'avatar2', player=1) + player1_avatar1_state = get_object_state(env, "avatar1", player=1) + player1_avatar2_state = get_object_state(env, "avatar2", player=1) - assert player1_avatar1_state['Location'] == [0, 3] - assert player1_avatar2_state['Location'] == [4, 4] + assert player1_avatar1_state["Location"] == [0, 3] + assert player1_avatar2_state["Location"] == [4, 4] object_names = env.game.get_object_names() - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[0][avartar1_id, 0, 3] == 1 assert obs[0][avartar2_id, 4, 4] == 1 - player2_avatar1_state = get_object_state(env, 'avatar1', player=2) - player2_avatar2_state = get_object_state(env, 'avatar2', player=2) + player2_avatar1_state = get_object_state(env, "avatar1", player=2) + player2_avatar2_state = get_object_state(env, "avatar2", player=2) - assert player2_avatar1_state['Location'] == [3, 3] - assert player2_avatar2_state['Location'] == [1, 4] + assert player2_avatar1_state["Location"] == [3, 3] + assert player2_avatar2_state["Location"] == [1, 4] - avartar1_id = object_names.index('avatar1') - avartar2_id = object_names.index('avatar2') + avartar1_id = object_names.index("avatar1") + avartar2_id = object_names.index("avatar2") assert obs[1][avartar1_id, 3, 3] == 1 assert obs[1][avartar2_id, 1, 4] == 1 diff --git a/python/tests/termination_test.py b/python/tests/termination_test.py index 49f8a7857..ae8d233c8 100644 --- a/python/tests/termination_test.py +++ b/python/tests/termination_test.py @@ -3,6 +3,7 @@ import pytest from griddly import GymWrapperFactory, gd + @pytest.fixture def test_name(request): return request.node.name @@ -16,22 +17,20 @@ def build_test_env(test_name, yaml_file, **kwargs): yaml_file, global_observer_type=gd.ObserverType.VECTOR, player_observer_type=gd.ObserverType.VECTOR, - **kwargs + **kwargs, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() return env + def test_termination_steps(test_name): """ Test that when we reach 100 steps the environment resets """ - env = build_test_env( - test_name, - "tests/gdy/test_termination_steps.yaml" - ) + env = build_test_env(test_name, "tests/gdy/test_termination_steps.yaml") for i in range(102): obs, reward, done, info = env.step(0) @@ -44,15 +43,14 @@ def test_termination_steps(test_name): assert reward == -1, "Reward should be -1" break + def test_override_termination_steps(test_name): """ Test that when we reach 50 steps, (as overridden) the environment resets """ env = build_test_env( - test_name, - "tests/gdy/test_termination_steps.yaml", - max_steps=50 + test_name, "tests/gdy/test_termination_steps.yaml", max_steps=50 ) for i in range(102): @@ -63,4 +61,4 @@ def test_override_termination_steps(test_name): if i == 50: assert done, "environment should be reset" - break \ No newline at end of file + break diff --git a/python/tests/valid_action_space_wrapper_test.py b/python/tests/valid_action_space_wrapper_test.py index 4ee2aaea0..096b1e60c 100644 --- a/python/tests/valid_action_space_wrapper_test.py +++ b/python/tests/valid_action_space_wrapper_test.py @@ -20,7 +20,7 @@ def build_test_env(test_name, yaml_file): player_observer_type=gd.ObserverType.VECTOR, ) - env = gym.make(f'GDY-{test_name}-v0') + env = gym.make(f"GDY-{test_name}-v0") env.reset() env = ValidActionSpaceWrapper(env) return env @@ -28,8 +28,8 @@ def build_test_env(test_name, yaml_file): def get_object_state(env, object_name, player=1): state = env.get_state() - for object in state['Objects']: - if object['Name'] == object_name and object['PlayerId'] == player: + for object in state["Objects"]: + if object["Name"] == object_name and object["PlayerId"] == player: return object @@ -43,8 +43,7 @@ def check_valid_actions(sampled_actions, possible_actions): def test_vasw_SinglePlayer_SingleActionType(test_name): env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SingleActionType.yaml" ) assert env.action_space.shape == () @@ -58,7 +57,7 @@ def test_vasw_SinglePlayer_SingleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask == expected_location_mask) @@ -66,7 +65,7 @@ def test_vasw_SinglePlayer_SingleActionType(test_name): expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) possible_actions = [[0], [1], [2], [3], [4]] @@ -79,8 +78,7 @@ def test_vasw_SinglePlayer_SingleActionType(test_name): def test_vasw_SinglePlayer_SelectSource_SingleActionType(test_name): env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_SelectSource_SingleActionType.yaml" ) assert env.action_space.shape == (3,) @@ -94,7 +92,7 @@ def test_vasw_SinglePlayer_SelectSource_SingleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask == expected_location_mask) @@ -102,15 +100,9 @@ def test_vasw_SinglePlayer_SelectSource_SingleActionType(test_name): expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) - possible_actions = [ - [2, 3, 0], - [2, 3, 1], - [2, 3, 2], - [2, 3, 3], - [2, 3, 4] - ] + possible_actions = [[2, 3, 0], [2, 3, 1], [2, 3, 2], [2, 3, 3], [2, 3, 4]] # Sample a valid action sampled = env.action_space.sample() @@ -120,8 +112,7 @@ def test_vasw_SinglePlayer_SelectSource_SingleActionType(test_name): def test_vasw_SinglePlayer_MultipleActionType(test_name): env = build_test_env( - test_name, - "tests/gdy/test_step_SinglePlayer_MultipleActionType.yaml" + test_name, "tests/gdy/test_step_SinglePlayer_MultipleActionType.yaml" ) assert env.action_space.shape == (2,) @@ -135,29 +126,34 @@ def test_vasw_SinglePlayer_MultipleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask == expected_location_mask) action_mask1 = env.get_unit_action_mask((2, 3), ["move"]) expected_action_id_mask1 = [1, 1, 1, 1, 1] - assert np.all(action_mask1['move'] == expected_action_id_mask1) + assert np.all(action_mask1["move"] == expected_action_id_mask1) action_mask2 = env.get_unit_action_mask((2, 3), ["other_move"]) expected_action_id_mask2 = [1, 1, 1, 1, 1] - assert np.all(action_mask2['other_move'] == expected_action_id_mask2) + assert np.all(action_mask2["other_move"] == expected_action_id_mask2) all_action_mask = env.get_unit_action_mask((2, 3), ["move", "other_move"]) - assert np.all(all_action_mask['move'] == expected_action_id_mask1) - assert np.all(all_action_mask['other_move'] == expected_action_id_mask2) + assert np.all(all_action_mask["move"] == expected_action_id_mask1) + assert np.all(all_action_mask["other_move"] == expected_action_id_mask2) possible_actions = [ - [0, 0], [1, 0], - [0, 1], [1, 1], - [0, 2], [1, 2], - [0, 3], [1, 3], - [0, 4], [1, 4], + [0, 0], + [1, 0], + [0, 1], + [1, 1], + [0, 2], + [1, 2], + [0, 3], + [1, 3], + [0, 4], + [1, 4], ] # Sample a valid action @@ -169,7 +165,7 @@ def test_vasw_SinglePlayer_MultipleActionType(test_name): def test_vasw_SinglePlayer_SelectSource_MultipleActionType(test_name): env = build_test_env( test_name, - "tests/gdy/test_step_SinglePlayer_SelectSource_MultipleActionType.yaml" + "tests/gdy/test_step_SinglePlayer_SelectSource_MultipleActionType.yaml", ) assert env.action_space.shape == (4,) @@ -183,29 +179,44 @@ def test_vasw_SinglePlayer_SelectSource_MultipleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask == expected_location_mask) action_mask1 = env.get_unit_action_mask((2, 3), ["move"]) expected_action_id_mask1 = [1, 1, 1, 1, 1] - assert np.all(action_mask1['move'] == expected_action_id_mask1) + assert np.all(action_mask1["move"] == expected_action_id_mask1) action_mask2 = env.get_unit_action_mask((2, 3), ["other_move"]) expected_action_id_mask2 = [1, 1, 1, 1, 1] - assert np.all(action_mask2['other_move'] == expected_action_id_mask2) + assert np.all(action_mask2["other_move"] == expected_action_id_mask2) all_action_mask = env.get_unit_action_mask((2, 3), ["move", "other_move"]) - assert np.all(all_action_mask['move'] == expected_action_id_mask1) - assert np.all(all_action_mask['other_move'] == expected_action_id_mask2) + assert np.all(all_action_mask["move"] == expected_action_id_mask1) + assert np.all(all_action_mask["other_move"] == expected_action_id_mask2) possible_actions = [ - [2, 3, 0, 0], [2, 3, 1, 0], [1, 4, 0, 0], [1, 4, 1, 0], - [2, 3, 0, 1], [2, 3, 1, 1], [1, 4, 0, 1], [1, 4, 1, 1], - [2, 3, 0, 2], [2, 3, 1, 2], [1, 4, 0, 2], [1, 4, 1, 2], - [2, 3, 0, 3], [2, 3, 1, 3], [1, 4, 0, 3], [1, 4, 1, 3], - [2, 3, 0, 4], [2, 3, 1, 4], [1, 4, 0, 4], [1, 4, 1, 4], + [2, 3, 0, 0], + [2, 3, 1, 0], + [1, 4, 0, 0], + [1, 4, 1, 0], + [2, 3, 0, 1], + [2, 3, 1, 1], + [1, 4, 0, 1], + [1, 4, 1, 1], + [2, 3, 0, 2], + [2, 3, 1, 2], + [1, 4, 0, 2], + [1, 4, 1, 2], + [2, 3, 0, 3], + [2, 3, 1, 3], + [1, 4, 0, 3], + [1, 4, 1, 3], + [2, 3, 0, 4], + [2, 3, 1, 4], + [1, 4, 0, 4], + [1, 4, 1, 4], ] # Sample a valid action @@ -216,8 +227,7 @@ def test_vasw_SinglePlayer_SelectSource_MultipleActionType(test_name): def test_vasw_MultiPlayer_SingleActionType(test_name): env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SingleActionType.yaml" ) assert len(env.action_space) == 2 @@ -234,7 +244,7 @@ def test_vasw_MultiPlayer_SingleActionType(test_name): [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask1 == expected_location_mask1) @@ -246,18 +256,18 @@ def test_vasw_MultiPlayer_SingleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask2 == expected_location_mask2) action_mask = env.get_unit_action_mask((1, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) action_mask = env.get_unit_action_mask((3, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) possible_actions = [[0], [1], [2], [3], [4]] @@ -272,8 +282,7 @@ def test_vasw_MultiPlayer_SingleActionType(test_name): def test_vasw_MultiplePlayer_SelectSource_SingleActionType(test_name): env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_SelectSource_SingleActionType.yaml" ) assert len(env.action_space) == 2 @@ -290,7 +299,7 @@ def test_vasw_MultiplePlayer_SelectSource_SingleActionType(test_name): [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask1 == expected_location_mask1) @@ -302,35 +311,22 @@ def test_vasw_MultiplePlayer_SelectSource_SingleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask2 == expected_location_mask2) action_mask = env.get_unit_action_mask((1, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) action_mask = env.get_unit_action_mask((3, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) possible_actions = [ - [ - [1, 3, 0], - [1, 3, 1], - [1, 3, 2], - [1, 3, 3], - [1, 3, 4] - ], - [ - [3, 3, 0], - [3, 3, 1], - [3, 3, 2], - [3, 3, 3], - [3, 3, 4] - ], - + [[1, 3, 0], [1, 3, 1], [1, 3, 2], [1, 3, 3], [1, 3, 4]], + [[3, 3, 0], [3, 3, 1], [3, 3, 2], [3, 3, 3], [3, 3, 4]], ] # Sample a valid action @@ -341,10 +337,10 @@ def test_vasw_MultiplePlayer_SelectSource_SingleActionType(test_name): assert check_valid_actions(sampled[0], possible_actions[0]) assert check_valid_actions(sampled[1], possible_actions[1]) + def test_vasw_MultiplePlayer_MultipleActionType(test_name): env = build_test_env( - test_name, - "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" + test_name, "tests/gdy/test_step_MultiPlayer_MultipleActionType.yaml" ) assert len(env.action_space) == 2 @@ -361,7 +357,7 @@ def test_vasw_MultiplePlayer_MultipleActionType(test_name): [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask1 == expected_location_mask1) @@ -373,35 +369,44 @@ def test_vasw_MultiplePlayer_MultipleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask2 == expected_location_mask2) action_mask = env.get_unit_action_mask((1, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) action_mask = env.get_unit_action_mask((3, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) possible_actions = [ [ - [0, 0], [1, 0], - [0, 1], [1, 1], - [0, 2], [1, 2], - [0, 3], [1, 3], - [0, 4], [1, 4], + [0, 0], + [1, 0], + [0, 1], + [1, 1], + [0, 2], + [1, 2], + [0, 3], + [1, 3], + [0, 4], + [1, 4], ], [ - [0, 0], [1, 0], - [0, 1], [1, 1], - [0, 2], [1, 2], - [0, 3], [1, 3], - [0, 4], [1, 4], + [0, 0], + [1, 0], + [0, 1], + [1, 1], + [0, 2], + [1, 2], + [0, 3], + [1, 3], + [0, 4], + [1, 4], ], - ] # Sample a valid action @@ -416,7 +421,7 @@ def test_vasw_MultiplePlayer_MultipleActionType(test_name): def test_vasw_MultiplePlayer_SelectSource_MultipleActionType(test_name): env = build_test_env( test_name, - "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType.yaml" + "tests/gdy/test_step_MultiPlayer_SelectSource_MultipleActionType.yaml", ) assert len(env.action_space) == 2 @@ -433,7 +438,7 @@ def test_vasw_MultiplePlayer_SelectSource_MultipleActionType(test_name): [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask1 == expected_location_mask1) @@ -445,35 +450,44 @@ def test_vasw_MultiplePlayer_SelectSource_MultipleActionType(test_name): [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], - [0, 0, 0, 0, 0, 0] + [0, 0, 0, 0, 0, 0], ] assert np.all(unit_location_mask2 == expected_location_mask2) action_mask = env.get_unit_action_mask((1, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) action_mask = env.get_unit_action_mask((3, 3), ["move"]) expected_action_id_mask = [1, 1, 1, 1, 1] - assert np.all(action_mask['move'] == expected_action_id_mask) + assert np.all(action_mask["move"] == expected_action_id_mask) possible_actions = [ [ - [1, 3, 0, 0], [1, 3, 1, 0], - [1, 3, 0, 1], [1, 3, 1, 1], - [1, 3, 0, 2], [1, 3, 1, 2], - [1, 3, 0, 3], [1, 3, 1, 3], - [1, 3, 0, 4], [1, 3, 1, 4] + [1, 3, 0, 0], + [1, 3, 1, 0], + [1, 3, 0, 1], + [1, 3, 1, 1], + [1, 3, 0, 2], + [1, 3, 1, 2], + [1, 3, 0, 3], + [1, 3, 1, 3], + [1, 3, 0, 4], + [1, 3, 1, 4], ], [ - [3, 3, 0, 0], [3, 3, 1, 0], - [3, 3, 0, 1], [3, 3, 1, 1], - [3, 3, 0, 2], [3, 3, 1, 2], - [3, 3, 0, 3], [3, 3, 1, 3], - [3, 3, 0, 4], [3, 3, 1, 4] + [3, 3, 0, 0], + [3, 3, 1, 0], + [3, 3, 0, 1], + [3, 3, 1, 1], + [3, 3, 0, 2], + [3, 3, 1, 2], + [3, 3, 0, 3], + [3, 3, 1, 3], + [3, 3, 0, 4], + [3, 3, 1, 4], ], - ] # Sample a valid action diff --git a/python/tools/flamegraph/shader_benchmark/benchmark.py b/python/tools/flamegraph/shader_benchmark/benchmark.py index 23c6d0509..136eacc2b 100644 --- a/python/tools/flamegraph/shader_benchmark/benchmark.py +++ b/python/tools/flamegraph/shader_benchmark/benchmark.py @@ -1,13 +1,16 @@ from griddly import GymWrapperFactory, gd, GymWrapper import timeit -if __name__ == '__main__': +if __name__ == "__main__": wrapper = GymWrapperFactory() - env = GymWrapper('Single-Player/GVGAI/sokoban.yaml', - player_observer_type=gd.ObserverType.BLOCK_2D, - global_observer_type=gd.ObserverType.BLOCK_2D, - level=0, max_steps=500) + env = GymWrapper( + "Single-Player/GVGAI/sokoban.yaml", + player_observer_type=gd.ObserverType.BLOCK_2D, + global_observer_type=gd.ObserverType.BLOCK_2D, + level=0, + max_steps=500, + ) env.reset() @@ -24,11 +27,10 @@ # env.render() # env.render(observer='global') - if done: end = timeit.default_timer() - print(f'{frames/(end - start)} SPS') + print(f"{frames/(end - start)} SPS") frames = 0 env.reset() - start = timeit.default_timer() \ No newline at end of file + start = timeit.default_timer() diff --git a/src/Griddly/Core/AStarPathFinder.cpp b/src/Griddly/Core/AStarPathFinder.cpp index 25420afe9..fb70dd107 100644 --- a/src/Griddly/Core/AStarPathFinder.cpp +++ b/src/Griddly/Core/AStarPathFinder.cpp @@ -1,10 +1,10 @@ -#include "AStarPathFinder.hpp" - #include #include #include +#include +#include "AStarPathFinder.hpp" #include "GDY/Actions/Action.hpp" #include "GDY/Objects/Object.hpp" #include "Grid.hpp" @@ -12,16 +12,16 @@ namespace griddly { AStarPathFinder::AStarPathFinder(std::shared_ptr grid, std::set impassableObjects, ActionInputsDefinition actionInputs) - : PathFinder(grid, impassableObjects), actionInputs_(actionInputs) { + : PathFinder(std::move(grid), std::move(impassableObjects)), actionInputs_(std::move(std::move(actionInputs))) { } -SearchOutput AStarPathFinder::reconstructPath(std::shared_ptr currentBestNode) { +SearchOutput AStarPathFinder::reconstructPath(const std::shared_ptr& currentBestNode) { if (currentBestNode->parent->parent == nullptr) { return {currentBestNode->actionId}; - } else { - spdlog::debug("Reconstructing path: [{0},{1}]->[{2},{3}] actionId: {4}", currentBestNode->parent->location.x, currentBestNode->parent->location.y, currentBestNode->location.x, currentBestNode->location.y, currentBestNode->parent->actionId); - return reconstructPath(currentBestNode->parent); } + spdlog::debug("Reconstructing path: [{0},{1}]->[{2},{3}] actionId: {4}", currentBestNode->parent->location.x, currentBestNode->parent->location.y, currentBestNode->location.x, currentBestNode->location.y, currentBestNode->parent->actionId); + return reconstructPath(currentBestNode->parent); + return {0}; } @@ -49,7 +49,7 @@ SearchOutput AStarPathFinder::search(glm::ivec2 startLocation, glm::ivec2 endLoc auto rotationMatrix = DiscreteOrientation(currentBestNode->orientationVector).getRotationMatrix(); - for (auto& inputMapping : actionInputs_.inputMappings) { + for (const auto& inputMapping : actionInputs_.inputMappings) { const auto actionId = inputMapping.first; const auto mapping = inputMapping.second; diff --git a/src/Griddly/Core/AStarPathFinder.hpp b/src/Griddly/Core/AStarPathFinder.hpp index 45d15fa28..62580863d 100644 --- a/src/Griddly/Core/AStarPathFinder.hpp +++ b/src/Griddly/Core/AStarPathFinder.hpp @@ -9,7 +9,7 @@ namespace griddly { struct SortAStarPathNodes { - bool operator()(std::shared_ptr a, std::shared_ptr b) { + bool operator()(const std::shared_ptr& a, const std::shared_ptr& b) { return a->scoreFromStart > b->scoreFromStart; }; }; @@ -18,9 +18,9 @@ class AStarPathFinder : public PathFinder { public: AStarPathFinder(std::shared_ptr grid, std::set impassableObjects, ActionInputsDefinition actionInputs); - SearchOutput reconstructPath(std::shared_ptr currentBestNode); + SearchOutput reconstructPath(const std::shared_ptr& currentBestNode); - virtual SearchOutput search(glm::ivec2 startLocation, glm::ivec2 endLocation, glm::ivec2 startOrientationVector, uint32_t maxDepth) override; + SearchOutput search(glm::ivec2 startLocation, glm::ivec2 endLocation, glm::ivec2 startOrientationVector, uint32_t maxDepth) override; private: const std::string targetAction_; diff --git a/src/Griddly/Core/CollisionDetectorFactory.hpp b/src/Griddly/Core/CollisionDetectorFactory.hpp index 112cc5f82..df4797540 100644 --- a/src/Griddly/Core/CollisionDetectorFactory.hpp +++ b/src/Griddly/Core/CollisionDetectorFactory.hpp @@ -11,7 +11,7 @@ struct ActionTriggerDefinition; class CollisionDetectorFactory { public: virtual ~CollisionDetectorFactory() = default; - virtual std::shared_ptr newCollisionDetector(uint32_t gridHeight, uint32_t gridWidth, ActionTriggerDefinition actionTriggerDefinition); + virtual std::shared_ptr newCollisionDetector(uint32_t gridWidth, uint32_t gridHeight, ActionTriggerDefinition actionTriggerDefinition); }; } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/DelayedActionQueueItem.cpp b/src/Griddly/Core/DelayedActionQueueItem.cpp index 1efddcad4..128e0c026 100644 --- a/src/Griddly/Core/DelayedActionQueueItem.cpp +++ b/src/Griddly/Core/DelayedActionQueueItem.cpp @@ -1,9 +1,13 @@ #include "DelayedActionQueueItem.hpp" +#include + +#include + namespace griddly { DelayedActionQueueItem::DelayedActionQueueItem(uint32_t _playerId, uint32_t _priority, std::shared_ptr _action) - : playerId(_playerId), priority(_priority), action(_action) { + : playerId(_playerId), priority(_priority), action(std::move(std::move(_action))) { } } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/DelayedActionQueueItem.hpp b/src/Griddly/Core/DelayedActionQueueItem.hpp index 0a0f97611..dca316c9a 100644 --- a/src/Griddly/Core/DelayedActionQueueItem.hpp +++ b/src/Griddly/Core/DelayedActionQueueItem.hpp @@ -17,11 +17,11 @@ class DelayedActionQueueItem { }; struct SortDelayedActionQueue { - bool operator()(std::shared_ptr a, std::shared_ptr b) { + bool operator()(const std::shared_ptr& a, const std::shared_ptr& b) { return a->priority > b->priority; }; }; -typedef VectorPriorityQueue, std::vector>, SortDelayedActionQueue> DelayedActionQueue; +using DelayedActionQueue = VectorPriorityQueue, std::vector >, SortDelayedActionQueue>; } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/GDY/Actions/Action.cpp b/src/Griddly/Core/GDY/Actions/Action.cpp index 010d5cc40..845fd10ff 100644 --- a/src/Griddly/Core/GDY/Actions/Action.cpp +++ b/src/Griddly/Core/GDY/Actions/Action.cpp @@ -3,14 +3,16 @@ #define SPDLOG_HEADER_ONLY #include +#include + namespace griddly { Action::Action(std::shared_ptr grid, std::string actionName, uint32_t playerId, uint32_t delay, std::unordered_map metaData) - : actionName_(actionName), + : actionName_(std::move(actionName)), delay_(delay), playerId_(playerId), grid_(grid), - metaData_(metaData) { + metaData_(std::move(metaData)) { } std::string Action::getDescription() const { diff --git a/src/Griddly/Core/GDY/Actions/Direction.hpp b/src/Griddly/Core/GDY/Actions/Direction.hpp index 2cc21c8db..68fe1a91f 100644 --- a/src/Griddly/Core/GDY/Actions/Direction.hpp +++ b/src/Griddly/Core/GDY/Actions/Direction.hpp @@ -62,7 +62,7 @@ class DiscreteOrientation { } } - float getAngleRadians() const { + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] float getAngleRadians() const { switch (direction_) { case Direction::NONE: case Direction::UP: @@ -78,7 +78,7 @@ class DiscreteOrientation { } } - glm::ivec2 getUnitVector() const { + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] glm::ivec2 getUnitVector() const { return unitVector_; } @@ -100,11 +100,11 @@ class DiscreteOrientation { } // If the current direction is DOWN and the input vector is "right" we return "left" etc.. - glm::ivec2 getRelativeUnitVector(glm::ivec2 vector) const { + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] glm::ivec2 getRelativeUnitVector(glm::ivec2 vector) const { return vector * getRotationMatrix(); } - glm::imat2x2 getRotationMatrix() const { + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] glm::imat2x2 getRotationMatrix() const { switch (direction_) { default: case Direction::NONE: @@ -119,7 +119,7 @@ class DiscreteOrientation { } } - Direction getDirection() const { + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] Direction getDirection() const { return direction_; } diff --git a/src/Griddly/Core/GDY/GDYFactory.cpp b/src/Griddly/Core/GDY/GDYFactory.cpp index d08e3c3df..8e4786fa8 100644 --- a/src/Griddly/Core/GDY/GDYFactory.cpp +++ b/src/Griddly/Core/GDY/GDYFactory.cpp @@ -3,6 +3,7 @@ #include #include +#include #define SPDLOG_HEADER_ONLY #include @@ -17,9 +18,9 @@ namespace griddly { GDYFactory::GDYFactory(std::shared_ptr objectGenerator, std::shared_ptr terminationGenerator, ResourceConfig resourceConfig) - : objectGenerator_(objectGenerator), - terminationGenerator_(terminationGenerator), - resourceConfig_(resourceConfig) { + : objectGenerator_(std::move(objectGenerator)), + terminationGenerator_(std::move(terminationGenerator)), + resourceConfig_(std::move(resourceConfig)) { #ifndef NDEBUG spdlog::set_level(spdlog::level::debug); #else @@ -82,8 +83,8 @@ void GDYFactory::loadEnvironment(YAML::Node environment) { parseTerminationConditions(environment["Termination"]); auto levels = environment["Levels"]; - for (std::size_t l = 0; l < levels.size(); l++) { - auto levelStringStream = std::stringstream(levels[l].as()); + for (auto&& level : levels) { + auto levelStringStream = std::stringstream(level.as()); auto mapGenerator = std::make_shared(MapGenerator(playerCount_, objectGenerator_)); mapGenerator->parseFromStream(levelStringStream); @@ -101,8 +102,8 @@ void GDYFactory::parseShaderVariableConfig(YAML::Node shaderConfigNode) { auto globalVariableNode = shaderConfigNode["GlobalVariables"]; if (globalVariableNode.IsDefined()) { - for (std::size_t i = 0; i < globalVariableNode.size(); i++) { - auto globalVariableName = globalVariableNode[i].as(); + for (auto&& i : globalVariableNode) { + auto globalVariableName = i.as(); // Check the global variable exists if (globalVariableDefinitions_.find(globalVariableName) == globalVariableDefinitions_.end()) { @@ -116,8 +117,8 @@ void GDYFactory::parseShaderVariableConfig(YAML::Node shaderConfigNode) { auto objectVariableNode = shaderConfigNode["ObjectVariables"]; if (objectVariableNode.IsDefined()) { - for (std::size_t i = 0; i < objectVariableNode.size(); i++) { - auto objectVariableName = objectVariableNode[i].as(); + for (auto&& i : objectVariableNode) { + auto objectVariableName = i.as(); // Check the global variable exists if (objectVariableNames_.find(objectVariableName) == objectVariableNames_.end()) { @@ -286,8 +287,8 @@ YAML::iterator GDYFactory::validateCommandPairNode(YAML::Node commandPairNodeLis } void GDYFactory::parseTerminationConditionV1(TerminationState state, YAML::Node conditionNode) { - for (std::size_t c = 0; c < conditionNode.size(); c++) { - auto commandIt = validateCommandPairNode(conditionNode[c]); + for (auto&& c : conditionNode) { + auto commandIt = validateCommandPairNode(c); auto commandName = commandIt->first.as(); auto commandArguments = singleOrListNodeToList(commandIt->second); @@ -296,20 +297,20 @@ void GDYFactory::parseTerminationConditionV1(TerminationState state, YAML::Node } bool GDYFactory::parseTerminationConditionV2(TerminationState state, YAML::Node conditionListNode) { - for (std::size_t c = 0; c < conditionListNode.size(); c++) { - auto conditionNode = conditionListNode[c]["Conditions"]; + for (auto&& c : conditionListNode) { + auto conditionNode = c["Conditions"]; if (!conditionNode.IsDefined()) { return false; } - auto rewardNode = conditionListNode[c]["Reward"]; - auto opposingRewardNode = conditionListNode[c]["OpposingReward"]; + auto rewardNode = c["Reward"]; + auto opposingRewardNode = c["OpposingReward"]; auto reward = rewardNode.as(0); auto opposingReward = opposingRewardNode.as(0); - for (std::size_t i = 0; i < conditionNode.size(); i++) { - auto commandIt = validateCommandPairNode(conditionNode[i]); + for (auto&& i : conditionNode) { + auto commandIt = validateCommandPairNode(i); auto commandName = commandIt->first.as(); auto commandArguments = singleOrListNodeToList(commandIt->second); @@ -359,8 +360,8 @@ void GDYFactory::parseGlobalVariables(YAML::Node variablesNode) { return; } - for (std::size_t p = 0; p < variablesNode.size(); p++) { - auto variable = variablesNode[p]; + for (auto&& p : variablesNode) { + auto variable = p; auto variableName = variable["Name"].as(); auto variableInitialValue = variable["InitialValue"].as(0); auto variablePerPlayer = variable["PerPlayer"].as(false); @@ -377,8 +378,8 @@ void GDYFactory::parseGlobalVariables(YAML::Node variablesNode) { void GDYFactory::loadObjects(YAML::Node objects) { spdlog::info("Loading {0} objects...", objects.size()); - for (std::size_t i = 0; i < objects.size(); i++) { - auto object = objects[i]; + for (auto&& i : objects) { + auto object = i; auto objectName = object["Name"].as(); auto mapCharacter = object["MapCharacter"].as('?'); auto observerDefinitions = object["Observers"]; @@ -393,8 +394,8 @@ void GDYFactory::loadObjects(YAML::Node objects) { std::unordered_map variableDefinitions; if (variables.IsDefined()) { - for (std::size_t p = 0; p < variables.size(); p++) { - auto variable = variables[p]; + for (auto&& p : variables) { + auto variable = p; auto variableName = variable["Name"].as(); auto variableInitialValue = variable["InitialValue"].as(0); variableDefinitions.insert({variableName, variableInitialValue}); @@ -413,8 +414,8 @@ void GDYFactory::loadObjects(YAML::Node objects) { auto initialActionsNode = object["InitialActions"]; if (initialActionsNode.IsDefined()) { - for (std::size_t a = 0; a < initialActionsNode.size(); a++) { - auto initialActionNode = initialActionsNode[a]; + for (auto&& a : initialActionsNode) { + auto initialActionNode = a; auto actionName = initialActionNode["Action"].as(); auto actionId = initialActionNode["ActionId"].as(0); auto delay = initialActionNode["Delay"].as(0); @@ -427,8 +428,8 @@ void GDYFactory::loadObjects(YAML::Node objects) { // Validate we have observer definitions for each objects if (spriteObserverDefinitions_.size() > 0) { - for (std::size_t i = 0; i < objects.size(); i++) { - auto object = objects[i]; + for (auto&& i : objects) { + auto object = i; auto objectName = object["Name"].as(); auto observerDefinitions = object["Observers"]; if (!observerDefinitions["Sprite2D"].IsDefined()) { @@ -438,8 +439,8 @@ void GDYFactory::loadObjects(YAML::Node objects) { } if (blockObserverDefinitions_.size() > 0) { - for (std::size_t i = 0; i < objects.size(); i++) { - auto object = objects[i]; + for (auto&& i : objects) { + auto object = i; auto objectName = object["Name"].as(); auto observerDefinitions = object["Observers"]; if (!observerDefinitions["Block2D"].IsDefined()) { @@ -449,8 +450,8 @@ void GDYFactory::loadObjects(YAML::Node objects) { } if (isometricObserverDefinitions_.size() > 0) { - for (std::size_t i = 0; i < objects.size(); i++) { - auto object = objects[i]; + for (auto&& i : objects) { + auto object = i; auto objectName = object["Name"].as(); auto observerDefinitions = object["Observers"]; if (!observerDefinitions["Isometric"].IsDefined()) { @@ -599,14 +600,14 @@ void GDYFactory::parseActionBehaviours(ActionBehaviourType actionBehaviourType, CommandList actionPreconditions; if (preconditionsNode.IsDefined()) { - for (std::size_t c = 0; c < preconditionsNode.size(); c++) { - auto preconditionsIt = validateCommandPairNode(preconditionsNode[c]); + for (auto&& c : preconditionsNode) { + auto preconditionsIt = validateCommandPairNode(c); auto preconditionCommandName = preconditionsIt->first.as(); auto preconditionCommandArgumentsNode = preconditionsIt->second; auto preconditionCommandArgumentMap = singleOrListNodeToCommandArguments(preconditionCommandArgumentsNode); - actionPreconditions.push_back(std::make_pair(preconditionCommandName, preconditionCommandArgumentMap)); + actionPreconditions.emplace_back(preconditionCommandName, preconditionCommandArgumentMap); } } @@ -619,8 +620,8 @@ void GDYFactory::parseActionBehaviours(ActionBehaviourType actionBehaviourType, return; } - for (std::size_t c = 0; c < commandsNode.size(); c++) { - auto commandIt = validateCommandPairNode(commandsNode[c]); + for (auto&& c : commandsNode) { + auto commandIt = validateCommandPairNode(c); // iterate through keys auto commandName = commandIt->first.as(); auto commandNode = commandIt->second; @@ -667,8 +668,8 @@ void GDYFactory::parseCommandNode( auto commandArgumentMap = singleOrListNodeToCommandArguments(conditionArguments); CommandList parsedSubCommands; - for (std::size_t sc = 0; sc < conditionSubCommands.size(); sc++) { - auto subCommandIt = validateCommandPairNode(conditionSubCommands[sc]); + for (auto&& conditionSubCommand : conditionSubCommands) { + auto subCommandIt = validateCommandPairNode(conditionSubCommand); auto subCommandName = subCommandIt->first.as(); auto subCommandArguments = subCommandIt->second; @@ -676,7 +677,7 @@ void GDYFactory::parseCommandNode( spdlog::debug("Parsing subcommand {0} conditions", subCommandName); - parsedSubCommands.push_back(std::make_pair(subCommandName, subCommandArgumentMap)); + parsedSubCommands.emplace_back(subCommandName, subCommandArgumentMap); } for (auto associatedObjectName : associatedObjectNames) { @@ -789,8 +790,8 @@ void GDYFactory::loadActionInputsDefinition(std::string actionName, YAML::Node I auto metaDataNode = mappingNodeData["MetaData"]; if (metaDataNode.IsDefined()) { for (YAML::const_iterator it = metaDataNode.begin(); it != metaDataNode.end(); ++it) { - std::string key = it->first.as(); - int32_t value = it->second.as(); + auto key = it->first.as(); + auto value = it->second.as(); inputMapping.metaData[key] = value; } } @@ -805,8 +806,8 @@ void GDYFactory::loadActionInputsDefinition(std::string actionName, YAML::Node I void GDYFactory::loadActions(YAML::Node actions) { spdlog::info("Loading {0} actions...", actions.size()); - for (std::size_t i = 0; i < actions.size(); i++) { - auto action = actions[i]; + for (auto&& i : actions) { + auto action = i; auto actionName = action["Name"].as(); auto probability = action["Probability"].as(1.0); auto behavioursNode = action["Behaviours"]; @@ -817,8 +818,8 @@ void GDYFactory::loadActions(YAML::Node actions) { std::unordered_set allSrcObjectNames; std::unordered_set allDstObjectNames; - for (std::size_t b = 0; b < behavioursNode.size(); b++) { - auto behaviourNode = behavioursNode[b]; + for (auto&& b : behavioursNode) { + auto behaviourNode = b; auto srcNode = behaviourNode["Src"]; auto dstNode = behaviourNode["Dst"]; diff --git a/src/Griddly/Core/GDY/Objects/Object.cpp b/src/Griddly/Core/GDY/Objects/Object.cpp index 16e667c65..0e91f9178 100644 --- a/src/Griddly/Core/GDY/Objects/Object.cpp +++ b/src/Griddly/Core/GDY/Objects/Object.cpp @@ -1,17 +1,20 @@ +#include "Object.hpp" + #include +#include + #include "../../AStarPathFinder.hpp" #include "../../Grid.hpp" #include "../../SpatialHashCollisionDetector.hpp" #include "../../Util/util.hpp" #include "../Actions/Action.hpp" -#include "Object.hpp" #include "ObjectGenerator.hpp" namespace griddly { Object::Object(std::string objectName, char mapCharacter, uint32_t playerId, uint32_t zIdx, std::unordered_map> availableVariables, std::shared_ptr objectGenerator, std::weak_ptr grid) - : objectName_(objectName), mapCharacter_(mapCharacter), zIdx_(zIdx), objectGenerator_(objectGenerator), grid_(grid) { + : objectName_(std::move(objectName)), mapCharacter_(mapCharacter), zIdx_(zIdx), objectGenerator_(std::move(objectGenerator)), grid_(std::move(grid)) { availableVariables.insert({"_x", x_}); availableVariables.insert({"_y", y_}); @@ -582,17 +585,16 @@ std::shared_ptr Object::getVariableValue(std::string variableName) { return it->second; } -SingleInputMapping Object::getInputMapping(std::string actionName, uint32_t actionId, bool randomize, InputMapping fallback) { - auto actionInputsDefinitions = objectGenerator_->getActionInputDefinitions(); - auto actionInputsDefinitionIt = actionInputsDefinitions.find(actionName); +SingleInputMapping Object::getInputMapping(const std::string& actionName, uint32_t actionId, bool randomize, InputMapping fallback) { + const auto& actionInputsDefinitions = objectGenerator_->getActionInputDefinitions(); - if (actionInputsDefinitionIt == actionInputsDefinitions.end()) { + if (actionInputsDefinitions.find(actionName) == actionInputsDefinitions.end()) { auto error = fmt::format("Action {0} not found in input definitions.", actionName); throw std::runtime_error(error); } - auto actionInputsDefinition = actionInputsDefinitionIt->second; - auto inputMappings = actionInputsDefinition.inputMappings; + const auto& actionInputsDefinition = actionInputsDefinitions.at(actionName); + const auto& inputMappings = actionInputsDefinition.inputMappings; SingleInputMapping resolvedInputMapping = {actionInputsDefinition.relative, actionInputsDefinition.internal, actionInputsDefinition.mapToGrid}; @@ -649,8 +651,8 @@ std::vector> Object::getInitialActions(std::shared_ptrgetActionInputDefinitions(); - auto actionInputsDefinition = actionInputsDefinitions[actionDefinition.actionName]; + const auto& actionInputsDefinitions = objectGenerator_->getActionInputDefinitions(); + const auto& actionInputsDefinition = actionInputsDefinitions.at(actionDefinition.actionName); auto inputMapping = getInputMapping(actionDefinition.actionName, actionDefinition.actionId, actionDefinition.randomize, fallbackInputMapping); @@ -704,7 +706,7 @@ PathFinderConfig Object::configurePathFinder(YAML::Node searchNode, std::string auto impassableObjectsList = singleOrListNodeToList(searchNode["ImpassableObjects"]); std::set impassableObjectsSet(impassableObjectsList.begin(), impassableObjectsList.end()); - auto actionInputDefinitions = objectGenerator_->getActionInputDefinitions(); + const auto& actionInputDefinitions = objectGenerator_->getActionInputDefinitions(); auto actionInputDefinitionIt = actionInputDefinitions.find(actionName); config.maxSearchDepth = searchNode["MaxDepth"].as(100); diff --git a/src/Griddly/Core/GDY/Objects/Object.hpp b/src/Griddly/Core/GDY/Objects/Object.hpp index 2145cf3fb..070d85e07 100644 --- a/src/Griddly/Core/GDY/Objects/Object.hpp +++ b/src/Griddly/Core/GDY/Objects/Object.hpp @@ -168,7 +168,7 @@ class Object : public std::enable_shared_from_this { virtual void removeObject(); - SingleInputMapping getInputMapping(std::string actionName, uint32_t actionId, bool randomize, InputMapping fallback); + SingleInputMapping getInputMapping(const std::string& actionName, uint32_t actionId, bool randomize, InputMapping fallback); PathFinderConfig configurePathFinder(YAML::Node searchNode, std::string actionName); diff --git a/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp b/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp index 94a6ad26c..330113d40 100644 --- a/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp +++ b/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp @@ -238,20 +238,20 @@ void ObjectGenerator::setActionProbabilities(std::unordered_map ObjectGenerator::getActionInputDefinitions() const { +const std::unordered_map& ObjectGenerator::getActionInputDefinitions() const { return actionInputsDefinitions_; } -std::unordered_map ObjectGenerator::getActionTriggerDefinitions() const { +const std::unordered_map& ObjectGenerator::getActionTriggerDefinitions() const { return actionTriggerDefinitions_; } -std::unordered_map ObjectGenerator::getActionProbabilities() const { +const std::unordered_map& ObjectGenerator::getActionProbabilities() const { return actionProbabilities_; } // The order of object definitions needs to be consistent across levels and maps, so we have to make sure this is ordered here. -std::map> ObjectGenerator::getObjectDefinitions() const { +const std::map>& ObjectGenerator::getObjectDefinitions() const { return objectDefinitions_; } diff --git a/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp b/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp index d27ea6ae9..e2cc3ff34 100644 --- a/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp +++ b/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp @@ -56,11 +56,11 @@ class ObjectGenerator : public std::enable_shared_from_this { virtual void setActionInputDefinitions(std::unordered_map actionInputDefinitions); virtual void setActionTriggerDefinitions(std::unordered_map actionTriggerDefinitions); virtual void setActionProbabilities(std::unordered_map actionProbabilities); - virtual std::unordered_map getActionInputDefinitions() const; - virtual std::unordered_map getActionTriggerDefinitions() const; - virtual std::unordered_map getActionProbabilities() const; + virtual const std::unordered_map& getActionInputDefinitions() const; + virtual const std::unordered_map& getActionTriggerDefinitions() const; + virtual const std::unordered_map& getActionProbabilities() const; - virtual std::map> getObjectDefinitions() const; + virtual const std::map>& getObjectDefinitions() const; private: std::unordered_map objectChars_; diff --git a/src/Griddly/Core/GDY/Objects/ObjectVariable.hpp b/src/Griddly/Core/GDY/Objects/ObjectVariable.hpp index 580fd94ae..fd36de3a6 100644 --- a/src/Griddly/Core/GDY/Objects/ObjectVariable.hpp +++ b/src/Griddly/Core/GDY/Objects/ObjectVariable.hpp @@ -24,8 +24,8 @@ enum class ActionObject { class ObjectVariable { public: ObjectVariable(YAML::Node commandArguments, std::unordered_map>& availableVariables); - int32_t resolve(std::shared_ptr action) const; - std::shared_ptr resolve_ptr(std::shared_ptr action) const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] int32_t resolve(std::shared_ptr action) const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] std::shared_ptr resolve_ptr(std::shared_ptr action) const; private: ObjectVariableType objectVariableType_; diff --git a/src/Griddly/Core/GDY/YAMLUtils.hpp b/src/Griddly/Core/GDY/YAMLUtils.hpp index a4ae9dd21..e0f49fc55 100644 --- a/src/Griddly/Core/GDY/YAMLUtils.hpp +++ b/src/Griddly/Core/GDY/YAMLUtils.hpp @@ -13,8 +13,8 @@ inline std::vector singleOrListNodeToList(YAML::Node singleOrList) { if (singleOrList.IsScalar()) { values.push_back(singleOrList.as()); } else if (singleOrList.IsSequence()) { - for (std::size_t s = 0; s < singleOrList.size(); s++) { - values.push_back(singleOrList[s].as()); + for (auto&& s : singleOrList) { + values.push_back(s.as()); } } diff --git a/src/Griddly/Core/GameProcess.cpp b/src/Griddly/Core/GameProcess.cpp index ff8f7ea97..ae001a804 100644 --- a/src/Griddly/Core/GameProcess.cpp +++ b/src/Griddly/Core/GameProcess.cpp @@ -1,5 +1,7 @@ #include +#include + #include "GDY/Actions/Action.hpp" #include "GameProcess.hpp" #include "Players/Player.hpp" @@ -10,7 +12,7 @@ GameProcess::GameProcess( ObserverType globalObserverType, std::shared_ptr gdyFactory, std::shared_ptr grid) - : grid_(grid), globalObserverType_(globalObserverType), gdyFactory_(gdyFactory) { + : grid_(std::move(std::move(grid))), globalObserverType_(globalObserverType), gdyFactory_(std::move(std::move(gdyFactory))) { } GameProcess::~GameProcess() { @@ -33,11 +35,11 @@ void GameProcess::setLevel(uint32_t levelId) { } void GameProcess::setLevel(std::string levelString) { - levelGenerator_ = gdyFactory_->getLevelGenerator(levelString); + levelGenerator_ = gdyFactory_->getLevelGenerator(std::move(levelString)); } void GameProcess::setLevelGenerator(std::shared_ptr levelGenerator) { - levelGenerator_ = levelGenerator; + levelGenerator_ = std::move(levelGenerator); } std::shared_ptr GameProcess::getLevelGenerator() const { @@ -81,7 +83,7 @@ void GameProcess::init(bool isCloned) { globalObserverConfig.playerId = 0; globalObserverConfig.playerCount = playerCount; globalObserverConfig.highlightPlayers = playerCount > 1; - + observer_->init(globalObserverConfig); auto playerObserverDefinition = gdyFactory_->getPlayerObserverDefinition(); @@ -120,7 +122,7 @@ void GameProcess::init(bool isCloned) { p->init(observerConfig, playerObserverDefinition.trackAvatar, shared_from_this()); - if (playerAvatarObjects.size() > 0) { + if (!playerAvatarObjects.empty()) { auto playerId = p->getId(); if (playerAvatarObjects.find(playerId) != playerAvatarObjects.end()) { p->setAvatar(playerAvatarObjects.at(p->getId())); @@ -202,7 +204,7 @@ void GameProcess::release() { grid_->reset(); } -bool GameProcess::isInitialized() { +bool GameProcess::isInitialized() const { return isInitialized_; } @@ -237,8 +239,8 @@ std::unordered_map> GameProcess::get // TODO: we can cache a lot of this if there are many players so it only needs to be created once. std::unordered_set internalActions; - auto actionInputsDefinitions = gdyFactory_->getActionInputsDefinitions(); - for (auto actionInputDefinition : actionInputsDefinitions) { + const auto& actionInputsDefinitions = gdyFactory_->getActionInputsDefinitions(); + for (const auto& actionInputDefinition : actionInputsDefinitions) { if (actionInputDefinition.second.internal) { internalActions.insert(actionInputDefinition.first); } @@ -246,16 +248,16 @@ std::unordered_map> GameProcess::get // For every object in the grid return the actions that the object can perform // TODO: do not iterate over all the objects if we have avatars. - for (auto object : grid_->getObjects()) { + for (const auto& object : grid_->getObjects()) { if (playerId == object->getPlayerId()) { auto actions = object->getAvailableActionNames(); - for (auto internalActionName : internalActions) { + for (const auto& internalActionName : internalActions) { actions.erase(internalActionName); } auto location = object->getLocation(); - if (actions.size() > 0) { + if (!actions.empty()) { availableActionNames.insert({location, actions}); } } @@ -271,12 +273,12 @@ std::vector GameProcess::getAvailableActionIdsAtLocation(glm::ivec2 lo std::vector availableActionIds{}; if (srcObject) { - auto actionInputDefinitions = gdyFactory_->getActionInputsDefinitions(); - auto actionInputDefinition = actionInputDefinitions[actionName]; + const auto& actionInputDefinitions = gdyFactory_->getActionInputsDefinitions(); + const auto& actionInputDefinition = actionInputDefinitions.at(actionName); auto relativeToSource = actionInputDefinition.relative; - for (auto inputMapping : actionInputDefinition.inputMappings) { + for (const auto& inputMapping : actionInputDefinition.inputMappings) { auto actionId = inputMapping.first; auto mapping = inputMapping.second; @@ -295,12 +297,11 @@ std::vector GameProcess::getAvailableActionIdsAtLocation(glm::ivec2 lo return availableActionIds; } -void GameProcess::generateStateHash(StateInfo& stateInfo) const { +void GameProcess::generateStateHash(StateInfo& stateInfo) { // Hash global variables - for (auto variableIt : stateInfo.globalVariables) { - + for (const auto& variableIt : stateInfo.globalVariables) { // Ignore the internal _steps count - if(variableIt.first != "_steps") { + if (variableIt.first != "_steps") { hash_combine(stateInfo.hash, variableIt.first); for (auto playerVariableIt : variableIt.second) { hash_combine(stateInfo.hash, playerVariableIt.second); @@ -311,14 +312,14 @@ void GameProcess::generateStateHash(StateInfo& stateInfo) const { // Hash ordered object list std::sort(stateInfo.objectInfo.begin(), stateInfo.objectInfo.end(), SortObjectInfo()); - for (auto o : stateInfo.objectInfo) { + for (const auto& o : stateInfo.objectInfo) { hash_combine(stateInfo.hash, o.name); hash_combine(stateInfo.hash, o.location); hash_combine(stateInfo.hash, o.orientation.getUnitVector()); hash_combine(stateInfo.hash, o.playerId); // Hash the object variables - for (auto variableIt : o.variables) { + for (const auto& variableIt : o.variables) { hash_combine(stateInfo.hash, variableIt.first); hash_combine(stateInfo.hash, variableIt.second); } @@ -330,17 +331,17 @@ StateInfo GameProcess::getState() const { stateInfo.gameTicks = *grid_->getTickCount(); - auto& globalVariables = grid_->getGlobalVariables(); + const auto& globalVariables = grid_->getGlobalVariables(); - for (auto& globalVarIt : globalVariables) { + for (const auto& globalVarIt : globalVariables) { auto variableName = globalVarIt.first; auto variableValues = globalVarIt.second; - for (auto variableValue : variableValues) { + for (const auto& variableValue : variableValues) { stateInfo.globalVariables[variableName].insert({variableValue.first, *variableValue.second}); } } - for (auto& object : grid_->getObjects()) { + for (const auto& object : grid_->getObjects()) { ObjectInfo objectInfo; objectInfo.name = object->getObjectName(); @@ -348,7 +349,7 @@ StateInfo GameProcess::getState() const { objectInfo.playerId = object->getPlayerId(); objectInfo.orientation = object->getObjectOrientation(); - for (auto varIt : object->getAvailableVariables()) { + for (const auto& varIt : object->getAvailableVariables()) { if (globalVariables.find(varIt.first) == globalVariables.end()) { objectInfo.variables.insert({varIt.first, *varIt.second}); } diff --git a/src/Griddly/Core/GameProcess.hpp b/src/Griddly/Core/GameProcess.hpp index ba25471d4..ceacc1b33 100644 --- a/src/Griddly/Core/GameProcess.hpp +++ b/src/Griddly/Core/GameProcess.hpp @@ -32,9 +32,8 @@ struct SortObjectInfo { if (loca == locb) { return a.name < b.name; - } else { - return loca < locb; - } + } return loca < locb; + } }; @@ -69,7 +68,7 @@ class GameProcess : public std::enable_shared_from_this { virtual void reset(); - bool isInitialized(); + bool isInitialized() const; virtual int32_t getAccumulatedRewards(uint32_t playerId); @@ -125,7 +124,7 @@ class GameProcess : public std::enable_shared_from_this { std::unordered_map accumulatedRewards_; private: - void generateStateHash(StateInfo& stateInfo) const; + static void generateStateHash(StateInfo& stateInfo) ; void resetObservers(); ObserverConfig getObserverConfig(ObserverType observerType) const; diff --git a/src/Griddly/Core/Grid.cpp b/src/Griddly/Core/Grid.cpp index cd375e59b..6a75ad674 100644 --- a/src/Griddly/Core/Grid.cpp +++ b/src/Griddly/Core/Grid.cpp @@ -29,7 +29,7 @@ Grid::Grid(std::shared_ptr collisionDetectorFactory) : spdlog::set_level(spdlog::level::info); #endif - collisionDetectorFactory_ = collisionDetectorFactory; + collisionDetectorFactory_ = std::move(collisionDetectorFactory); } Grid::~Grid() { @@ -54,9 +54,9 @@ void Grid::resetMap(uint32_t width, uint32_t height) { globalVariables_["_steps"].insert({0, gameTicks_}); - if (updatedLocations_.size() == 0) { + if (updatedLocations_.empty()) { for (auto p = 0; p < playerCount_ + 1; p++) { - updatedLocations_.push_back(std::unordered_set{}); + updatedLocations_.emplace_back(); } } } @@ -73,13 +73,14 @@ void Grid::reset() { collisionObjectActionNames_.clear(); collisionSourceObjectActionNames_.clear(); collisionDetectors_.clear(); + collisionSourceObjects_.clear(); *gameTicks_ = 0; } void Grid::setGlobalVariables(std::unordered_map> globalVariableDefinitions) { globalVariables_.clear(); - for (auto variable : globalVariableDefinitions) { + for (const auto& variable : globalVariableDefinitions) { auto variableName = variable.first; auto playerVariables = variable.second; @@ -105,7 +106,7 @@ void Grid::setGlobalVariables(std::unordered_map globalVariableDefinitions) { globalVariables_.clear(); - for (auto variable : globalVariableDefinitions) { + for (const auto& variable : globalVariableDefinitions) { auto variableName = variable.first; auto variableDefinition = variable.second; @@ -150,7 +151,7 @@ bool Grid::updateLocation(std::shared_ptr object, glm::ivec2 previousLoc invalidateLocation(newLocation); // Update spatial hashes if they exists - if (collisionDetectors_.size() > 0) { + if (!collisionDetectors_.empty()) { auto objectName = object->getObjectName(); auto collisionDetectorActionNamesIt = collisionObjectActionNames_.find(object->getObjectName()); @@ -174,15 +175,14 @@ const std::unordered_set& Grid::getUpdatedLocations(uint32_t playerI return updatedLocations_[playerId]; } -std::unordered_map Grid::executeAndRecord(uint32_t playerId, std::shared_ptr action) { +std::unordered_map Grid::executeAndRecord(uint32_t playerId, const std::shared_ptr& action) { if (recordEvents_) { auto event = buildGridEvent(action, playerId, *gameTicks_); auto reward = executeAction(playerId, action); recordGridEvent(event, reward); return reward; - } else { - return executeAction(playerId, action); } + return executeAction(playerId, action); } std::unordered_map Grid::executeAction(uint32_t playerId, std::shared_ptr action) { @@ -203,7 +203,7 @@ std::unordered_map Grid::executeAction(uint32_t playerId, std spdlog::debug("Executing action {0} with probability {1}", action->getDescription(), executionProbability); if (executionProbability < 1.0) { - auto actionProbability = randomGenerator_->sampleFloat(0,1); + auto actionProbability = randomGenerator_->sampleFloat(0, 1); if (actionProbability > executionProbability) { spdlog::debug("Action aborted due to probability check {0} > {1}", actionProbability, executionProbability); return {}; @@ -255,14 +255,12 @@ std::unordered_map Grid::executeAction(uint32_t playerId, std auto srcBehaviourResult = sourceObject->onActionSrc(originalDestinationObjectName, action); accumulateRewards(rewardAccumulator, srcBehaviourResult.rewards); return rewardAccumulator; - - } else { - spdlog::debug("Cannot perform action={0} on object={1}", action->getActionName(), sourceObject->getObjectName()); - return {}; } + spdlog::debug("Cannot perform action={0} on object={1}", action->getActionName(), sourceObject->getObjectName()); + return {}; } -GridEvent Grid::buildGridEvent(std::shared_ptr action, uint32_t playerId, uint32_t tick) { +GridEvent Grid::buildGridEvent(const std::shared_ptr& action, uint32_t playerId, uint32_t tick) const { auto sourceObject = action->getSourceObject(); auto destObject = action->getDestinationObject(); @@ -298,7 +296,7 @@ GridEvent Grid::buildGridEvent(std::shared_ptr action, uint32_t playerId } void Grid::recordGridEvent(GridEvent event, std::unordered_map rewards) { - event.rewards = rewards; + event.rewards = std::move(rewards); eventHistory_.push_back(event); } @@ -307,7 +305,7 @@ std::unordered_map Grid::performActions(uint32_t playerId, st spdlog::trace("Tick {0}", *gameTicks_); - for (auto action : actions) { + for (const auto& action : actions) { // Check if action is delayed or durative if (action->getDelay() > 0) { delayAction(playerId, action); @@ -333,13 +331,13 @@ std::unordered_map Grid::processDelayedActions() { // Perform any delayed actions std::vector> actionsToExecute; - while (delayedActions_.size() > 0 && delayedActions_.top()->priority <= *(gameTicks_)) { + while (!delayedActions_.empty() && delayedActions_.top()->priority <= *(gameTicks_)) { // Get the top element and remove it actionsToExecute.push_back(delayedActions_.top()); delayedActions_.pop(); } - for (auto delayedAction : actionsToExecute) { + for (const auto& delayedAction : actionsToExecute) { auto action = delayedAction->action; auto playerId = delayedAction->playerId; @@ -355,16 +353,16 @@ std::unordered_map Grid::processDelayedActions() { std::unordered_map Grid::processCollisions() { std::unordered_map collisionRewards; - if (collisionDetectors_.size() == 0) { + if (collisionDetectors_.empty()) { return collisionRewards; } // Check for collisions - for (auto object : objects_) { - auto objectName = object->getObjectName(); + for (const auto& object : collisionSourceObjects_) { + const auto& objectName = object->getObjectName(); auto collisionActionNamesIt = collisionSourceObjectActionNames_.find(objectName); if (collisionActionNamesIt != collisionSourceObjectActionNames_.end()) { - auto collisionActionNames = collisionActionNamesIt->second; + const auto& collisionActionNames = collisionSourceObjectActionNames_.at(objectName); auto location = object->getLocation(); auto playerId = object->getPlayerId(); @@ -376,8 +374,12 @@ std::unordered_map Grid::processCollisions() { auto objectsInCollisionRange = searchResults.objectSet; - for (auto collisionObject : objectsInCollisionRange) { - if (collisionObject == object) continue; + for (const auto& collisionObject : objectsInCollisionRange) { + if (collisionObject == object) { + { + continue; + } + } spdlog::debug("Collision detected for action {0} {1}->{2}", actionName, collisionObject->getObjectName(), objectName); @@ -430,15 +432,14 @@ const TileObjects& Grid::getObjectsAt(glm::ivec2 location) const { auto i = occupiedLocations_.find(location); if (i == occupiedLocations_.end()) { return EMPTY_OBJECTS; - } else { - return i->second; } + return i->second; } std::shared_ptr Grid::getObject(glm::ivec2 location) const { if (occupiedLocations_.count(location) > 0) { - auto& objectsAtLocation = occupiedLocations_.at(location); - if (objectsAtLocation.size() > 0) { + const auto& objectsAtLocation = occupiedLocations_.at(location); + if (!objectsAtLocation.empty()) { // Get the highest index object return objectsAtLocation.rbegin()->second; } @@ -459,7 +460,7 @@ const std::vector Grid::getObjectNames() const { auto namesCount = objectIds_.size(); std::vector orderedNames(namesCount); - for (auto& objectIdIt : objectIds_) { + for (const auto& objectIdIt : objectIds_) { auto name = objectIdIt.first; auto idx = objectIdIt.second; orderedNames[idx] = name; @@ -472,7 +473,7 @@ const std::vector Grid::getAllObjectVariableNames() const { auto namesCount = objectVariableIds_.size(); std::vector orderedNames(namesCount); - for (auto& objectVariableIdIt : objectVariableIds_) { + for (const auto& objectVariableIdIt : objectVariableIds_) { auto name = objectVariableIdIt.first; auto idx = objectVariableIdIt.second; orderedNames[idx] = name; @@ -514,7 +515,7 @@ void Grid::addActionProbability(std::string actionName, float probability) { } void Grid::addCollisionDetector(std::vector objectNames, std::string actionName, std::shared_ptr collisionDetector) { - for (auto objectName : objectNames) { + for (const auto& objectName : objectNames) { collisionObjectActionNames_[objectName].insert(actionName); } @@ -525,13 +526,13 @@ void Grid::addActionTrigger(std::string actionName, ActionTriggerDefinition acti std::shared_ptr collisionDetector = collisionDetectorFactory_->newCollisionDetector(width_, height_, actionTriggerDefinition); std::vector objectNames; - for (auto sourceObjectName : actionTriggerDefinition.sourceObjectNames) { + for (const auto& sourceObjectName : actionTriggerDefinition.sourceObjectNames) { // TODO: I dont think we need to add source names to all object names? // objectNames.push_back(sourceObjectName); collisionSourceObjectActionNames_[sourceObjectName].insert(actionName); } - for (auto destinationObjectName : actionTriggerDefinition.destinationObjectNames) { + for (const auto& destinationObjectName : actionTriggerDefinition.destinationObjectNames) { objectNames.push_back(destinationObjectName); collisionObjectActionNames_[destinationObjectName].insert(actionName); } @@ -555,7 +556,7 @@ std::shared_ptr Grid::getPlayerDefaultObject(uint32_t playerId) const { } void Grid::addObject(glm::ivec2 location, std::shared_ptr object, bool applyInitialActions, std::shared_ptr originatingAction, DiscreteOrientation orientation) { - auto objectName = object->getObjectName(); + const auto& objectName = object->getObjectName(); auto playerId = object->getPlayerId(); if (object->isPlayerAvatar()) { @@ -594,23 +595,28 @@ void Grid::addObject(glm::ivec2 location, std::shared_ptr object, bool a } if (applyInitialActions) { - auto initialActions = object->getInitialActions(originatingAction); - if (initialActions.size() > 0) { + auto initialActions = object->getInitialActions(std::move(originatingAction)); + if (!initialActions.empty()) { spdlog::debug("Performing {0} Initial actions on object {1}.", initialActions.size(), objectName); performActions(0, initialActions); } } - if (collisionDetectors_.size() > 0) { - auto collisionDetectorActionNamesIt = collisionObjectActionNames_.find(objectName); + if (!collisionDetectors_.empty()) { + const auto& collisionDetectorActionNamesIt = collisionObjectActionNames_.find(objectName); if (collisionDetectorActionNamesIt != collisionObjectActionNames_.end()) { - auto collisionDetectorActionNames = collisionDetectorActionNamesIt->second; + const auto& collisionDetectorActionNames = collisionObjectActionNames_.at(objectName); for (const auto& actionName : collisionDetectorActionNames) { auto collisionDetector = collisionDetectors_.at(actionName); spdlog::debug("Adding object {0} to collision detector for action {1}", objectName, actionName); collisionDetector->upsert(object); } } + + auto collisionActionNamesIt = collisionSourceObjectActionNames_.find(objectName); + if (collisionActionNamesIt != collisionSourceObjectActionNames_.end()) { + collisionSourceObjects_.insert(object); + } } } else { @@ -626,7 +632,6 @@ std::shared_ptr Grid::getRandomGenerator() const { return randomGenerator_; } - bool Grid::removeObject(std::shared_ptr object) { auto objectName = object->getObjectName(); auto playerId = object->getPlayerId(); @@ -639,7 +644,7 @@ bool Grid::removeObject(std::shared_ptr object) { invalidateLocation(location); // if we are removing a player's avatar - if (playerAvatars_.size() > 0 && playerId != 0) { + if (!playerAvatars_.empty() && playerId != 0) { auto playerAvatarIt = playerAvatars_.find(playerId); if (playerAvatarIt != playerAvatars_.end() && playerAvatarIt->second == object) { spdlog::debug("Removing player {0} avatar {1}", playerId, objectName); @@ -647,7 +652,7 @@ bool Grid::removeObject(std::shared_ptr object) { } } - if (collisionDetectors_.size() > 0) { + if (!collisionDetectors_.empty()) { auto collisionDetectorActionNamesIt = collisionObjectActionNames_.find(objectName); if (collisionDetectorActionNamesIt != collisionObjectActionNames_.end()) { auto collisionDetectorActionNames = collisionDetectorActionNamesIt->second; @@ -656,6 +661,8 @@ bool Grid::removeObject(std::shared_ptr object) { collisionDetector->remove(object); } } + + collisionSourceObjects_.erase(object); } return true; diff --git a/src/Griddly/Core/Grid.hpp b/src/Griddly/Core/Grid.hpp index e8088e909..d517f6efd 100644 --- a/src/Griddly/Core/Grid.hpp +++ b/src/Griddly/Core/Grid.hpp @@ -63,12 +63,12 @@ struct GlobalVariableDefinition { class Grid : public std::enable_shared_from_this { public: Grid(); - Grid(std::shared_ptr collisionDetectorFactory); + explicit Grid(std::shared_ptr collisionDetectorFactory); virtual ~Grid(); virtual void setPlayerCount(uint32_t playerCount); virtual uint32_t getPlayerCount() const; - virtual void resetMap(uint32_t height, uint32_t width); + virtual void resetMap(uint32_t width, uint32_t height); virtual void resetGlobalVariables(std::unordered_map globalVariableDefinitions); virtual void setGlobalVariables(std::unordered_map> globalVariableDefinitions); @@ -173,15 +173,15 @@ class Grid : public std::enable_shared_from_this { virtual std::shared_ptr getRandomGenerator() const; private: - GridEvent buildGridEvent(std::shared_ptr action, uint32_t playerId, uint32_t tick); + GridEvent buildGridEvent(const std::shared_ptr& action, uint32_t playerId, uint32_t tick) const; void recordGridEvent(GridEvent event, std::unordered_map rewards); const std::vector> getCollisionDetectorsForObject(std::shared_ptr object) const; - std::unordered_map executeAndRecord(uint32_t playerId, std::shared_ptr action); + std::unordered_map executeAndRecord(uint32_t playerId, const std::shared_ptr& action); - uint32_t height_; - uint32_t width_; + uint32_t height_{}; + uint32_t width_{}; const std::shared_ptr gameTicks_; @@ -220,6 +220,9 @@ class Grid : public std::enable_shared_from_this { // Only the source objects that can collide std::unordered_map> collisionSourceObjectActionNames_; + // keep a list of the objects that are named as collision sources, this makes collision processing significantly faster with large maps with many non-colliding objects + std::unordered_set> collisionSourceObjects_; + // Collision detectors are grouped by action name (i.e each trigger) std::shared_ptr collisionDetectorFactory_; std::unordered_map> collisionDetectors_; diff --git a/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp b/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp index b33dbe714..5a6c192a8 100644 --- a/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp +++ b/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp @@ -1,7 +1,6 @@ #include "LevelGenerator.hpp" namespace griddly { -LevelGenerator::~LevelGenerator() { -} +LevelGenerator::~LevelGenerator() = default; } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/LevelGenerators/MapGenerator.cpp b/src/Griddly/Core/LevelGenerators/MapGenerator.cpp index 80ca0d87a..235541086 100644 --- a/src/Griddly/Core/LevelGenerators/MapGenerator.cpp +++ b/src/Griddly/Core/LevelGenerators/MapGenerator.cpp @@ -4,10 +4,11 @@ #include #include +#include namespace griddly { -MapGenerator::MapGenerator(uint32_t playerCount, std::shared_ptr objectGenerator) : playerCount_(playerCount), objectGenerator_(objectGenerator) { +MapGenerator::MapGenerator(uint32_t playerCount, std::shared_ptr objectGenerator) : playerCount_(playerCount), objectGenerator_(std::move(objectGenerator)) { #ifndef NDEBUG spdlog::set_level(spdlog::level::debug); #else @@ -15,7 +16,7 @@ MapGenerator::MapGenerator(uint32_t playerCount, std::shared_ptr grid) { grid->resetMap(width_, height_); diff --git a/src/Griddly/Core/LevelGenerators/MapGenerator.hpp b/src/Griddly/Core/LevelGenerators/MapGenerator.hpp index a6a27db16..e05f5946a 100644 --- a/src/Griddly/Core/LevelGenerators/MapGenerator.hpp +++ b/src/Griddly/Core/LevelGenerators/MapGenerator.hpp @@ -31,7 +31,7 @@ class MapGenerator : public LevelGenerator { void initializeFromFile(std::string filename); - virtual void reset(std::shared_ptr grid) override; + void reset(std::shared_ptr grid) override; private: uint32_t width_ = 0; diff --git a/src/Griddly/Core/Observers/ASCIIObserver.cpp b/src/Griddly/Core/Observers/ASCIIObserver.cpp index e7c6023a3..a6d9ec267 100644 --- a/src/Griddly/Core/Observers/ASCIIObserver.cpp +++ b/src/Griddly/Core/Observers/ASCIIObserver.cpp @@ -8,7 +8,7 @@ namespace griddly { ASCIIObserver::ASCIIObserver(std::shared_ptr grid) : Observer(grid) {} -ASCIIObserver::~ASCIIObserver() {} +ASCIIObserver::~ASCIIObserver() = default; void ASCIIObserver::init(ObserverConfig observerConfig) { Observer::init(observerConfig); diff --git a/src/Griddly/Core/Observers/ASCIIObserver.hpp b/src/Griddly/Core/Observers/ASCIIObserver.hpp index 0a84ed1c5..2d0cb5e24 100644 --- a/src/Griddly/Core/Observers/ASCIIObserver.hpp +++ b/src/Griddly/Core/Observers/ASCIIObserver.hpp @@ -14,8 +14,8 @@ class ASCIIObserver : public Observer { void reset() override; void resetShape() override; - ObserverType getObserverType() const override; - glm::ivec2 getTileSize() const override; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] ObserverType getObserverType() const override; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] glm::ivec2 getTileSize() const override; void print(std::shared_ptr observation) override; diff --git a/src/Griddly/Core/Observers/BlockObserver.cpp b/src/Griddly/Core/Observers/BlockObserver.cpp index a7de56e43..c44740647 100644 --- a/src/Griddly/Core/Observers/BlockObserver.cpp +++ b/src/Griddly/Core/Observers/BlockObserver.cpp @@ -1,7 +1,9 @@ +#include "BlockObserver.hpp" + #include +#include #include "../Grid.hpp" -#include "BlockObserver.hpp" namespace griddly { @@ -14,11 +16,10 @@ const std::unordered_map BlockObserver::blockSpri }; BlockObserver::BlockObserver(std::shared_ptr grid, ResourceConfig resourceConfig, std::unordered_map blockDefinitions, ShaderVariableConfig shaderVariableConfig) - : SpriteObserver(grid, resourceConfig, blockSpriteDefinitions_, shaderVariableConfig), blockDefinitions_(blockDefinitions) { + : SpriteObserver(grid, resourceConfig, blockSpriteDefinitions_, shaderVariableConfig), blockDefinitions_(std::move(blockDefinitions)) { } -BlockObserver::~BlockObserver() { -} +BlockObserver::~BlockObserver() = default; ObserverType BlockObserver::getObserverType() const { return ObserverType::BLOCK_2D; diff --git a/src/Griddly/Core/Observers/BlockObserver.hpp b/src/Griddly/Core/Observers/BlockObserver.hpp index 77d01a034..43be1b874 100644 --- a/src/Griddly/Core/Observers/BlockObserver.hpp +++ b/src/Griddly/Core/Observers/BlockObserver.hpp @@ -17,10 +17,9 @@ struct BlockDefinition { class BlockObserver : public SpriteObserver { public: BlockObserver(std::shared_ptr grid, ResourceConfig resourceConfig, std::unordered_map blockDefinitions, ShaderVariableConfig shaderVariableConfig); - ~BlockObserver(); + ~BlockObserver() override; - - virtual ObserverType getObserverType() const override; + ObserverType getObserverType() const override; void updateObjectSSBOData(PartialObservableGrid& partiallyObservableGrid, glm::mat4& globalModelMatrix, DiscreteOrientation globalOrientation) override; private: diff --git a/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp b/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp index 38a0ce798..acc48f7f5 100644 --- a/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp +++ b/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp @@ -11,8 +11,7 @@ IsometricSpriteObserver::IsometricSpriteObserver(std::shared_ptr grid, Res : SpriteObserver(grid, resourceConfig, spriteDefinitions, shaderVariableConfig) { } -IsometricSpriteObserver::~IsometricSpriteObserver() { -} +IsometricSpriteObserver::~IsometricSpriteObserver() = default; ObserverType IsometricSpriteObserver::getObserverType() const { return ObserverType::ISOMETRIC; diff --git a/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp b/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp index 351f900a2..d5c9a8bad 100644 --- a/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp +++ b/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp @@ -9,13 +9,13 @@ namespace griddly { class IsometricSpriteObserver : public SpriteObserver { public: IsometricSpriteObserver(std::shared_ptr grid, ResourceConfig resourceConfig, std::unordered_map spriteDesciptions, ShaderVariableConfig shaderVariableConfig); - ~IsometricSpriteObserver(); + ~IsometricSpriteObserver() override; - virtual ObserverType getObserverType() const override; + ObserverType getObserverType() const override; protected: - virtual glm::mat4 getViewMatrix() override; - virtual glm::mat4 getGlobalModelMatrix() override; + glm::mat4 getViewMatrix() override; + glm::mat4 getGlobalModelMatrix() override; void resetShape() override; void updateObjectSSBOData(PartialObservableGrid& partiallyObservableGrid, glm::mat4& globalModelMatrix, DiscreteOrientation globalOrientation) override; diff --git a/src/Griddly/Core/Observers/NoneObserver.cpp b/src/Griddly/Core/Observers/NoneObserver.cpp index 70f63ff05..bfb64a066 100644 --- a/src/Griddly/Core/Observers/NoneObserver.cpp +++ b/src/Griddly/Core/Observers/NoneObserver.cpp @@ -1,12 +1,14 @@ #include "NoneObserver.hpp" +#include + namespace griddly { NoneObserver::NoneObserver(std::shared_ptr grid) : Observer(grid) { observationShape_ = {1,1,1}; observationStrides_ = {1,1,1}; - emptyObs_ = std::shared_ptr(new uint8_t[1]{}); + emptyObs_ = std::shared_ptr(new uint8_t[1]{}); //NOLINT } uint8_t* NoneObserver::update() { diff --git a/src/Griddly/Core/Observers/NoneObserver.hpp b/src/Griddly/Core/Observers/NoneObserver.hpp index d67422a43..9587e884b 100644 --- a/src/Griddly/Core/Observers/NoneObserver.hpp +++ b/src/Griddly/Core/Observers/NoneObserver.hpp @@ -11,7 +11,7 @@ class NoneObserver : public Observer { uint8_t* update() override; void resetShape() override; - ObserverType getObserverType() const override; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] ObserverType getObserverType() const override; private: std::shared_ptr emptyObs_; diff --git a/src/Griddly/Core/Observers/Observer.cpp b/src/Griddly/Core/Observers/Observer.cpp index 86d3202a2..14aaf4abd 100644 --- a/src/Griddly/Core/Observers/Observer.cpp +++ b/src/Griddly/Core/Observers/Observer.cpp @@ -2,9 +2,11 @@ #include +#include + namespace griddly { -Observer::Observer(std::shared_ptr grid) : grid_(grid) { +Observer::Observer(std::shared_ptr grid) : grid_(std::move(grid)) { } void Observer::init(ObserverConfig observerConfig) { diff --git a/src/Griddly/Core/Observers/Observer.hpp b/src/Griddly/Core/Observers/Observer.hpp index 2ccd4a8b4..20bced64b 100644 --- a/src/Griddly/Core/Observers/Observer.hpp +++ b/src/Griddly/Core/Observers/Observer.hpp @@ -65,12 +65,12 @@ class Observer { virtual uint8_t* update() = 0; virtual void reset(); - virtual std::vector getShape() const; - virtual std::vector getStrides() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual std::vector getShape() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual std::vector getStrides() const; - virtual glm::ivec2 getTileSize() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual glm::ivec2 getTileSize() const; - virtual PartialObservableGrid getAvatarObservableGrid(glm::ivec2 avatarLocation, Direction avatarOrientation=Direction::NONE) const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual PartialObservableGrid getAvatarObservableGrid(glm::ivec2 avatarLocation, Direction avatarOrientation = Direction::NONE) const; virtual void init(ObserverConfig observerConfig); virtual void setAvatar(std::shared_ptr avatarObject); @@ -79,7 +79,7 @@ class Observer { virtual void release(); - virtual ObserverType getObserverType() const = 0; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual ObserverType getObserverType() const = 0; virtual ~Observer() = 0; diff --git a/src/Griddly/Core/Observers/SpriteObserver.cpp b/src/Griddly/Core/Observers/SpriteObserver.cpp index 726222260..75d0f7348 100644 --- a/src/Griddly/Core/Observers/SpriteObserver.cpp +++ b/src/Griddly/Core/Observers/SpriteObserver.cpp @@ -8,17 +8,17 @@ #include #include +#include #include "../Grid.hpp" #include "Vulkan/VulkanDevice.hpp" namespace griddly { -SpriteObserver::SpriteObserver(std::shared_ptr grid, ResourceConfig resourceConfig, std::unordered_map spriteDefinitions, ShaderVariableConfig shaderVariableConfig) : VulkanGridObserver(grid, resourceConfig, shaderVariableConfig), spriteDefinitions_(spriteDefinitions) { +SpriteObserver::SpriteObserver(std::shared_ptr grid, ResourceConfig resourceConfig, std::unordered_map spriteDefinitions, ShaderVariableConfig shaderVariableConfig) : VulkanGridObserver(grid, resourceConfig, shaderVariableConfig), spriteDefinitions_(std::move(spriteDefinitions)) { } -SpriteObserver::~SpriteObserver() { -} +SpriteObserver::~SpriteObserver() = default; ObserverType SpriteObserver::getObserverType() const { return ObserverType::SPRITE_2D; @@ -39,7 +39,7 @@ vk::SpriteData SpriteObserver::loadImage(std::string imageFilename) { int outputWidth = observerConfig_.tileSize.x; int outputHeight = observerConfig_.tileSize.y; - stbi_uc* resizedPixels = (stbi_uc*)malloc(outputWidth * outputHeight * 4); + auto* resizedPixels = (stbi_uc*)malloc(outputWidth * outputHeight * 4); auto res = stbir_resize_uint8_generic(pixels, width, height, 0, resizedPixels, outputWidth, outputHeight, 0, 4, @@ -166,9 +166,8 @@ std::string SpriteObserver::getSpriteName(const std::string& objectName, const s } void SpriteObserver::updateObjectSSBOData(PartialObservableGrid& observableGrid, glm::mat4& globalModelMatrix, DiscreteOrientation globalOrientation) { - uint32_t backgroundTileIndex = device_->getSpriteArrayLayer("_background_"); - if(backgroundTileIndex != -1) { + if (backgroundTileIndex != -1) { vk::ObjectDataSSBO backgroundTiling; backgroundTiling.modelMatrix = glm::translate(backgroundTiling.modelMatrix, glm::vec3(gridWidth_ / 2.0 - observerConfig_.gridXOffset, gridHeight_ / 2.0 - observerConfig_.gridYOffset, 0.0)); backgroundTiling.modelMatrix = glm::scale(backgroundTiling.modelMatrix, glm::vec3(gridWidth_, gridHeight_, 1.0)); @@ -220,7 +219,7 @@ void SpriteObserver::updateObjectSSBOData(PartialObservableGrid& observableGrid, objectData.modelMatrix = glm::translate(objectData.modelMatrix, glm::vec3(0.5, 0.5, 0.0)); // Offset for the the vertexes as they are between (-0.5, 0.5) and we want them between (0, 1) // Rotate the objects that should be rotated - if(observerConfig_.rotateAvatarImage) { + if (observerConfig_.rotateAvatarImage) { if (!(object == avatarObject_ && observerConfig_.rotateWithAvatar) && !isWallTiles) { auto objectAngleRadians = objectOrientation.getAngleRadians() - globalOrientation.getAngleRadians(); objectData.modelMatrix = glm::rotate(objectData.modelMatrix, objectAngleRadians, glm::vec3(0.0, 0.0, 1.0)); diff --git a/src/Griddly/Core/Observers/SpriteObserver.hpp b/src/Griddly/Core/Observers/SpriteObserver.hpp index 82fbd96cd..2061a2fff 100644 --- a/src/Griddly/Core/Observers/SpriteObserver.hpp +++ b/src/Griddly/Core/Observers/SpriteObserver.hpp @@ -27,9 +27,9 @@ struct SpriteDefinition { class SpriteObserver : public VulkanGridObserver { public: SpriteObserver(std::shared_ptr grid, ResourceConfig resourceConfig, std::unordered_map spriteDesciptions, ShaderVariableConfig shaderVariableConfig); - ~SpriteObserver(); + ~SpriteObserver() override; - virtual ObserverType getObserverType() const override; + ObserverType getObserverType() const override; void updateCommandBuffer() override; protected: diff --git a/src/Griddly/Core/Observers/VectorObserver.cpp b/src/Griddly/Core/Observers/VectorObserver.cpp index 55accaa94..b8b9f3e3d 100644 --- a/src/Griddly/Core/Observers/VectorObserver.cpp +++ b/src/Griddly/Core/Observers/VectorObserver.cpp @@ -4,11 +4,13 @@ #include #include +#include + namespace griddly { VectorObserver::VectorObserver(std::shared_ptr grid) : Observer(grid) {} -VectorObserver::~VectorObserver() {} +VectorObserver::~VectorObserver() = default; void VectorObserver::init(ObserverConfig observerConfig) { Observer::init(observerConfig); @@ -61,7 +63,7 @@ void VectorObserver::resetShape() { observationShape_ = {observationChannels_, gridWidth_, gridHeight_}; observationStrides_ = {1, observationChannels_, observationChannels_ * gridWidth_}; - observation_ = std::shared_ptr(new uint8_t[observationChannels_ * gridWidth_ * gridHeight_]{}); + observation_ = std::shared_ptr(new uint8_t[observationChannels_ * gridWidth_ * gridHeight_]{}); //NOLINT trackAvatar_ = avatarObject_ != nullptr; } diff --git a/src/Griddly/Core/Observers/VectorObserver.hpp b/src/Griddly/Core/Observers/VectorObserver.hpp index 781e17576..dffdc460d 100644 --- a/src/Griddly/Core/Observers/VectorObserver.hpp +++ b/src/Griddly/Core/Observers/VectorObserver.hpp @@ -14,8 +14,8 @@ class VectorObserver : public Observer { void reset() override; void resetShape() override; - ObserverType getObserverType() const override; - glm::ivec2 getTileSize() const override; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] ObserverType getObserverType() const override; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] glm::ivec2 getTileSize() const override; void print(std::shared_ptr observation) override; diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp b/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp index 12be6a115..db99e0fb9 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp @@ -1,10 +1,12 @@ #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE +#include "VulkanDevice.hpp" + #include +#include #include "ShapeBuffer.hpp" -#include "VulkanDevice.hpp" #include "VulkanInitializers.hpp" #include "VulkanInstance.hpp" #include "VulkanPhysicalDeviceInfo.hpp" @@ -14,97 +16,97 @@ namespace vk { VulkanDevice::VulkanDevice(std::shared_ptr vulkanInstance, glm::ivec2 tileSize, std::string shaderPath) - : vulkanInstance_(vulkanInstance), + : vulkanInstance_(std::move(vulkanInstance)), tileSize_(tileSize), - shaderPath_(shaderPath) { + shaderPath_(std::move(shaderPath)) { } VulkanDevice::~VulkanDevice() { if (device_ != VK_NULL_HANDLE) { // Free all the vertex/index buffers - vkDestroyBuffer(device_, shapeBuffer_.vertex.buffer, NULL); - vkFreeMemory(device_, shapeBuffer_.vertex.memory, NULL); - vkDestroyBuffer(device_, shapeBuffer_.index.buffer, NULL); - vkFreeMemory(device_, shapeBuffer_.index.memory, NULL); + vkDestroyBuffer(device_, shapeBuffer_.vertex.buffer, nullptr); + vkFreeMemory(device_, shapeBuffer_.vertex.memory, nullptr); + vkDestroyBuffer(device_, shapeBuffer_.index.buffer, nullptr); + vkFreeMemory(device_, shapeBuffer_.index.memory, nullptr); freeRenderSurfaceMemory(); // Destroy sprite images - vkDestroyImage(device_, spriteImageArrayBuffer_.image, NULL); - vkFreeMemory(device_, spriteImageArrayBuffer_.memory, NULL); - vkDestroyImageView(device_, spriteImageArrayBuffer_.view, NULL); + vkDestroyImage(device_, spriteImageArrayBuffer_.image, nullptr); + vkFreeMemory(device_, spriteImageArrayBuffer_.memory, nullptr); + vkDestroyImageView(device_, spriteImageArrayBuffer_.view, nullptr); // Destroy shader buffers - vkDestroyBuffer(device_, environmentUniformBuffer_.allocated.buffer, NULL); + vkDestroyBuffer(device_, environmentUniformBuffer_.allocated.buffer, nullptr); vkUnmapMemory(device_, environmentUniformBuffer_.allocated.memory); - vkFreeMemory(device_, environmentUniformBuffer_.allocated.memory, NULL); + vkFreeMemory(device_, environmentUniformBuffer_.allocated.memory, nullptr); - vkDestroyBuffer(device_, playerInfoSSBOBuffer_.allocated.buffer, NULL); + vkDestroyBuffer(device_, playerInfoSSBOBuffer_.allocated.buffer, nullptr); vkUnmapMemory(device_, playerInfoSSBOBuffer_.allocated.memory); - vkFreeMemory(device_, playerInfoSSBOBuffer_.allocated.memory, NULL); + vkFreeMemory(device_, playerInfoSSBOBuffer_.allocated.memory, nullptr); - vkDestroyBuffer(device_, objectDataSSBOBuffer_.allocated.buffer, NULL); + vkDestroyBuffer(device_, objectDataSSBOBuffer_.allocated.buffer, nullptr); vkUnmapMemory(device_, objectDataSSBOBuffer_.allocated.memory); - vkFreeMemory(device_, objectDataSSBOBuffer_.allocated.memory, NULL); + vkFreeMemory(device_, objectDataSSBOBuffer_.allocated.memory, nullptr); if (globalVariableSSBOBuffer_.allocatedSize > 0) { - vkDestroyBuffer(device_, globalVariableSSBOBuffer_.allocated.buffer, NULL); + vkDestroyBuffer(device_, globalVariableSSBOBuffer_.allocated.buffer, nullptr); vkUnmapMemory(device_, globalVariableSSBOBuffer_.allocated.memory); - vkFreeMemory(device_, globalVariableSSBOBuffer_.allocated.memory, NULL); + vkFreeMemory(device_, globalVariableSSBOBuffer_.allocated.memory, nullptr); } if (objectVariableSSBOBuffer_.allocatedSize > 0) { - vkDestroyBuffer(device_, objectVariableSSBOBuffer_.allocated.buffer, NULL); + vkDestroyBuffer(device_, objectVariableSSBOBuffer_.allocated.buffer, nullptr); vkUnmapMemory(device_, objectVariableSSBOBuffer_.allocated.memory); - vkFreeMemory(device_, objectVariableSSBOBuffer_.allocated.memory, NULL); + vkFreeMemory(device_, objectVariableSSBOBuffer_.allocated.memory, nullptr); } - vkDestroyCommandPool(device_, commandPool_, NULL); - vkDestroyDevice(device_, NULL); + vkDestroyCommandPool(device_, commandPool_, nullptr); + vkDestroyDevice(device_, nullptr); } } void VulkanDevice::freeRenderSurfaceMemory() { // Remove frame buffers if (colorAttachment_.image != VK_NULL_HANDLE) { - vkDestroyImage(device_, colorAttachment_.image, NULL); - vkFreeMemory(device_, colorAttachment_.memory, NULL); - vkDestroyImageView(device_, colorAttachment_.view, NULL); + vkDestroyImage(device_, colorAttachment_.image, nullptr); + vkFreeMemory(device_, colorAttachment_.memory, nullptr); + vkDestroyImageView(device_, colorAttachment_.view, nullptr); } if (depthAttachment_.image != VK_NULL_HANDLE) { - vkDestroyImage(device_, depthAttachment_.image, NULL); - vkFreeMemory(device_, depthAttachment_.memory, NULL); - vkDestroyImageView(device_, depthAttachment_.view, NULL); + vkDestroyImage(device_, depthAttachment_.image, nullptr); + vkFreeMemory(device_, depthAttachment_.memory, nullptr); + vkDestroyImageView(device_, depthAttachment_.view, nullptr); } if (frameBuffer_ != VK_NULL_HANDLE) { - vkDestroyFramebuffer(device_, frameBuffer_, NULL); + vkDestroyFramebuffer(device_, frameBuffer_, nullptr); } if (renderPass_ != VK_NULL_HANDLE) { - vkDestroyRenderPass(device_, renderPass_, NULL); + vkDestroyRenderPass(device_, renderPass_, nullptr); } // Remove the rendering surface if (renderedImage_ != VK_NULL_HANDLE) { - vkDestroyImage(device_, renderedImage_, NULL); + vkDestroyImage(device_, renderedImage_, nullptr); } if (renderedImageMemory_ != VK_NULL_HANDLE) { - vkFreeMemory(device_, renderedImageMemory_, NULL); + vkFreeMemory(device_, renderedImageMemory_, nullptr); } - vkDestroyPipeline(device_, renderPipeline_.pipeline, NULL); - vkDestroyDescriptorPool(device_, renderPipeline_.descriptorPool, NULL); - vkDestroyPipelineLayout(device_, renderPipeline_.pipelineLayout, NULL); - vkDestroyDescriptorSetLayout(device_, renderPipeline_.descriptorSetLayout, NULL); + vkDestroyPipeline(device_, renderPipeline_.pipeline, nullptr); + vkDestroyDescriptorPool(device_, renderPipeline_.descriptorPool, nullptr); + vkDestroyPipelineLayout(device_, renderPipeline_.pipelineLayout, nullptr); + vkDestroyDescriptorSetLayout(device_, renderPipeline_.descriptorSetLayout, nullptr); for (auto& shader : renderPipeline_.shaderStages) { - vkDestroyShaderModule(device_, shader.module, NULL); + vkDestroyShaderModule(device_, shader.module, nullptr); } - vkDestroySampler(device_, renderPipeline_.sampler, NULL); + vkDestroySampler(device_, renderPipeline_.sampler, nullptr); } // namespace vk @@ -126,12 +128,12 @@ void VulkanDevice::initDevice(bool useGPU) { physicalDevice_ = physicalDeviceInfo->physicalDevice; spdlog::debug("Creating physical device."); - vk_check(vkCreateDevice(physicalDevice_, &deviceCreateInfo, NULL, &device_)); + vk_check(vkCreateDevice(physicalDevice_, &deviceCreateInfo, nullptr, &device_)); vkGetDeviceQueue(device_, computeQueueFamilyIndex, 0, &computeQueue_); spdlog::debug("Creating command pool."); auto commandPoolCreateInfo = vk::initializers::commandPoolCreateInfo(computeQueueFamilyIndex); - vk_check(vkCreateCommandPool(device_, &commandPoolCreateInfo, NULL, &commandPool_)); + vk_check(vkCreateCommandPool(device_, &commandPoolCreateInfo, nullptr, &commandPool_)); } else { spdlog::error("No devices supporting vulkan present for rendering."); @@ -222,7 +224,7 @@ void VulkanDevice::startRecordingCommandBuffer() { scissor.extent.height = height_; vkCmdSetScissor(renderContext_.commandBuffer, 0, 1, &scissor); - vkCmdBindDescriptorSets(renderContext_.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, renderPipeline_.pipelineLayout, 0, 1, &renderPipeline_.descriptorSet, 0, NULL); + vkCmdBindDescriptorSets(renderContext_.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, renderPipeline_.pipelineLayout, 0, 1, &renderPipeline_.descriptorSet, 0, nullptr); vkCmdBindPipeline(renderContext_.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, renderPipeline_.pipeline); } @@ -404,7 +406,7 @@ void VulkanDevice::preloadSprites(std::unordered_map& s spriteImageArrayBuffer_ = createImage(tileSize_.x, tileSize_.y, arrayLayers, colorFormat_, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VkImageViewCreateInfo spriteImageView = vk::initializers::imageViewCreateInfo(colorFormat_, spriteImageArrayBuffer_.image, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_ASPECT_COLOR_BIT, arrayLayers); - vk_check(vkCreateImageView(device_, &spriteImageView, NULL, &spriteImageArrayBuffer_.view)); + vk_check(vkCreateImageView(device_, &spriteImageView, nullptr, &spriteImageArrayBuffer_.view)); int layer = 0; for (auto& spriteToLoad : spritesData) { @@ -586,7 +588,7 @@ VkSampler VulkanDevice::createTextureSampler() { spdlog::debug("Creating texture sampler"); - vk_check(vkCreateSampler(device_, &samplerCreateInfo, NULL, &textureSampler)); + vk_check(vkCreateSampler(device_, &samplerCreateInfo, nullptr, &textureSampler)); return textureSampler; } @@ -664,8 +666,8 @@ void VulkanDevice::stageToDeviceBuffer(VkBuffer& deviceBuffer, void* data, VkDev executeCommandBuffer(commandBuffer); vkFreeCommandBuffers(device_, commandPool_, 1, &commandBuffer); - vkDestroyBuffer(device_, stagingBuffer, NULL); - vkFreeMemory(device_, stagingMemory, NULL); + vkDestroyBuffer(device_, stagingBuffer, nullptr); + vkFreeMemory(device_, stagingMemory, nullptr); spdlog::debug("Done!"); } @@ -685,8 +687,8 @@ void VulkanDevice::stageToDeviceImage(VkImage& deviceImage, void* data, VkDevice copyBufferToImage(stagingBuffer, deviceImage, {{{0, 0}, {(uint32_t)tileSize_.x, (uint32_t)tileSize_.y}}}, arrayLayer); - vkDestroyBuffer(device_, stagingBuffer, NULL); - vkFreeMemory(device_, stagingMemory, NULL); + vkDestroyBuffer(device_, stagingBuffer, nullptr); + vkFreeMemory(device_, stagingMemory, nullptr); spdlog::debug("Done!"); } @@ -695,7 +697,7 @@ void VulkanDevice::createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyF // Create the buffer handle VkBufferCreateInfo bufferCreateInfo = vk::initializers::bufferCreateInfo(usageFlags, size); bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - vk_check(vkCreateBuffer(device_, &bufferCreateInfo, NULL, buffer)); + vk_check(vkCreateBuffer(device_, &bufferCreateInfo, nullptr, buffer)); // Create the memory backing up the buffer handle VkMemoryRequirements memReqs; @@ -703,10 +705,10 @@ void VulkanDevice::createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyF vkGetBufferMemoryRequirements(device_, *buffer, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = findMemoryTypeIndex(memReqs.memoryTypeBits, memoryPropertyFlags); - vk_check(vkAllocateMemory(device_, &memAlloc, NULL, memory)); + vk_check(vkAllocateMemory(device_, &memAlloc, nullptr, memory)); // Initial memory allocation - if (data != NULL) { + if (data != nullptr) { void* mapped; vk_check(vkMapMemory(device_, *memory, 0, size, 0, &mapped)); memcpy(mapped, data, size); @@ -826,7 +828,7 @@ std::vector VulkanDevice::getSupportedPhysicalDevices( std::vector VulkanDevice::getAvailablePhysicalDevices() { uint32_t deviceCount = 0; - vk_check(vkEnumeratePhysicalDevices(vulkanInstance_->getInstance(), &deviceCount, NULL)); + vk_check(vkEnumeratePhysicalDevices(vulkanInstance_->getInstance(), &deviceCount, nullptr)); std::vector physicalDevices(deviceCount); vk_check(vkEnumeratePhysicalDevices(vulkanInstance_->getInstance(), &deviceCount, physicalDevices.data())); @@ -868,7 +870,7 @@ VulkanPhysicalDeviceInfo VulkanDevice::getPhysicalDeviceInfo(VkPhysicalDevice& p bool VulkanDevice::hasQueueFamilySupport(VkPhysicalDevice& device, VulkanQueueFamilyIndices& queueFamilyIndices) { uint32_t queueFamilyCount; - vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, NULL); + vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); std::vector queueFamilyProperties(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilyProperties.data()); @@ -910,7 +912,7 @@ FrameBufferAttachment VulkanDevice::createDepthAttachment() { depthAttachment.memory = imageBuffer.memory; VkImageViewCreateInfo depthStencilView = vk::initializers::imageViewCreateInfo(depthFormat_, depthAttachment.image, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT); - vk_check(vkCreateImageView(device_, &depthStencilView, NULL, &depthAttachment.view)); + vk_check(vkCreateImageView(device_, &depthStencilView, nullptr, &depthAttachment.view)); return depthAttachment; } @@ -931,7 +933,7 @@ FrameBufferAttachment VulkanDevice::createColorAttachment() { colorAttachment.memory = imageBuffer.memory; VkImageViewCreateInfo colorImageView = vk::initializers::imageViewCreateInfo(colorFormat_, colorAttachment.image, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT); - vk_check(vkCreateImageView(device_, &colorImageView, NULL, &colorAttachment.view)); + vk_check(vkCreateImageView(device_, &colorImageView, nullptr, &colorAttachment.view)); return colorAttachment; } @@ -942,7 +944,7 @@ ImageBuffer VulkanDevice::createImage(uint32_t width, uint32_t height, uint32_t VkImageCreateInfo imageInfo = vk::initializers::imageCreateInfo(width, height, arrayLayers, format, tiling, usage); - vk_check(vkCreateImage(device_, &imageInfo, NULL, &image)); + vk_check(vkCreateImage(device_, &imageInfo, nullptr, &image)); VkMemoryRequirements memRequirements; VkMemoryAllocateInfo memAllocInfo(vk::initializers::memoryAllocateInfo()); @@ -951,7 +953,7 @@ ImageBuffer VulkanDevice::createImage(uint32_t width, uint32_t height, uint32_t memAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memAllocInfo.allocationSize = memRequirements.size; memAllocInfo.memoryTypeIndex = findMemoryTypeIndex(memRequirements.memoryTypeBits, properties); - vk_check(vkAllocateMemory(device_, &memAllocInfo, NULL, &memory)); + vk_check(vkAllocateMemory(device_, &memAllocInfo, nullptr, &memory)); vk_check(vkBindImageMemory(device_, image, memory, 0)); return {image, memory}; @@ -1008,7 +1010,7 @@ void VulkanDevice::createRenderPass() { VkRenderPassCreateInfo renderPassInfo = vk::initializers::renderPassCreateInfo(attachmentDescriptions, dependencies, subpassDescription); - vk_check(vkCreateRenderPass(device_, &renderPassInfo, NULL, &renderPass_)); + vk_check(vkCreateRenderPass(device_, &renderPassInfo, nullptr, &renderPass_)); std::vector attachmentViews; attachmentViews.push_back(colorAttachment_.view); @@ -1016,7 +1018,7 @@ void VulkanDevice::createRenderPass() { VkFramebufferCreateInfo framebufferCreateInfo = vk::initializers::framebufferCreateInfo(width_, height_, renderPass_, attachmentViews); - vk_check(vkCreateFramebuffer(device_, &framebufferCreateInfo, NULL, &frameBuffer_)); + vk_check(vkCreateFramebuffer(device_, &framebufferCreateInfo, nullptr, &frameBuffer_)); } VulkanPipeline VulkanDevice::createSpriteRenderPipeline() { @@ -1040,7 +1042,7 @@ VulkanPipeline VulkanDevice::createSpriteRenderPipeline() { vk::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, storageBufferCount), }; VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = vk::initializers::descriptorPoolCreateInfo(descriptorPoolSizes, 1); - vk_check(vkCreateDescriptorPool(device_, &descriptorPoolCreateInfo, NULL, &descriptorPool)); + vk_check(vkCreateDescriptorPool(device_, &descriptorPoolCreateInfo, nullptr, &descriptorPool)); spdlog::debug("Setting up descriptor set layout"); @@ -1068,7 +1070,7 @@ VulkanPipeline VulkanDevice::createSpriteRenderPipeline() { } VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = vk::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); - vk_check(vkCreateDescriptorSetLayout(device_, &descriptorSetLayoutCreateInfo, NULL, &descriptorSetLayout)); + vk_check(vkCreateDescriptorSetLayout(device_, &descriptorSetLayoutCreateInfo, nullptr, &descriptorSetLayout)); spdlog::debug("Allocating descriptor sets"); // Allocate the descriptor set>s @@ -1109,7 +1111,7 @@ VulkanPipeline VulkanDevice::createSpriteRenderPipeline() { } // Write the descriptor to the device - vkUpdateDescriptorSets(device_, descriptorWrites.size(), descriptorWrites.data(), 0, NULL); + vkUpdateDescriptorSets(device_, descriptorWrites.size(), descriptorWrites.data(), 0, nullptr); spdlog::debug("Updating descriptor sets done"); spdlog::debug("Creating pipeline layout"); @@ -1118,7 +1120,7 @@ VulkanPipeline VulkanDevice::createSpriteRenderPipeline() { VkPushConstantRange pushConstantRange = vk::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT, sizeof(ObjectPushConstants), 0); pipelineLayoutCreateInfo.pushConstantRangeCount = 1; pipelineLayoutCreateInfo.pPushConstantRanges = &pushConstantRange; - vk_check(vkCreatePipelineLayout(device_, &pipelineLayoutCreateInfo, NULL, &pipelineLayout)); + vk_check(vkCreatePipelineLayout(device_, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout)); // TODO: not really sure we need a pipeline cache because this is not speed critical // VkPipelineCacheCreateInfo pipelineCacheCreateInfo = vk::initializers::pipelineCacheCreateInfo(); @@ -1178,7 +1180,7 @@ VulkanPipeline VulkanDevice::createSpriteRenderPipeline() { spdlog::debug("Creating graphics pipelines"); - vk_check(vkCreateGraphicsPipelines(device_, NULL, 1, &pipelineCreateInfo, NULL, &pipeline)); + vk_check(vkCreateGraphicsPipelines(device_, nullptr, 1, &pipelineCreateInfo, nullptr, &pipeline)); return {pipeline, pipelineLayout, descriptorPool, descriptorSetLayout, descriptorSet, shaderStages, sampler}; } @@ -1189,10 +1191,10 @@ void VulkanDevice::executeCommandBuffer(VkCommandBuffer commandBuffer) { submitInfo.pCommandBuffers = &commandBuffer; VkFenceCreateInfo fenceInfo = vk::initializers::fenceCreateInfo(); VkFence fence; - vk_check(vkCreateFence(device_, &fenceInfo, NULL, &fence)); + vk_check(vkCreateFence(device_, &fenceInfo, nullptr, &fence)); vk_check(vkQueueSubmit(computeQueue_, 1, &submitInfo, fence)); vk_check(vkWaitForFences(device_, 1, &fence, VK_TRUE, UINT64_MAX)); - vkDestroyFence(device_, fence, NULL); + vkDestroyFence(device_, fence, nullptr); } uint8_t* VulkanDevice::renderFrame() { diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp index 572cc92a9..aa1aa4561 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp @@ -301,7 +301,7 @@ inline VkDescriptorSetLayoutBinding descriptorSetLayoutBinding( setLayoutBinding.stageFlags = stageFlags; setLayoutBinding.binding = binding; setLayoutBinding.descriptorCount = descriptorCount; - setLayoutBinding.pImmutableSamplers = NULL; + setLayoutBinding.pImmutableSamplers = nullptr; return setLayoutBinding; } diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanInstance.cpp b/src/Griddly/Core/Observers/Vulkan/VulkanInstance.cpp index 008a1580a..9380d6e3b 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanInstance.cpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanInstance.cpp @@ -31,14 +31,14 @@ VulkanInstance::VulkanInstance(VulkanConfiguration& config) { #endif // Check if layers are available uint32_t instanceLayerCount; - vk_check(vkEnumerateInstanceLayerProperties(&instanceLayerCount, NULL)); + vk_check(vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr)); std::vector instanceLayers(instanceLayerCount); vk_check(vkEnumerateInstanceLayerProperties(&instanceLayerCount, instanceLayers.data())); uint32_t instanceExtensionCount; - vk_check(vkEnumerateInstanceExtensionProperties(NULL, &instanceExtensionCount, NULL)); + vk_check(vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr)); std::vector instanceExtensions(instanceExtensionCount); - vk_check(vkEnumerateInstanceExtensionProperties(NULL, &instanceExtensionCount, instanceExtensions.data())); + vk_check(vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, instanceExtensions.data())); bool layersAvailable = true; if (layerCount > 0) { @@ -86,7 +86,7 @@ VulkanInstance::VulkanInstance(VulkanConfiguration& config) { spdlog::error("Missing vulkan extensions in driver. Please upgrade your vulkan drivers."); } - vk_check(vkCreateInstance(&instanceCreateInfo, NULL, &instance_)); + vk_check(vkCreateInstance(&instanceCreateInfo, nullptr, &instance_)); } VkInstance VulkanInstance::getInstance() const { @@ -94,7 +94,7 @@ VkInstance VulkanInstance::getInstance() const { } VulkanInstance::~VulkanInstance() { - vkDestroyInstance(instance_, NULL); + vkDestroyInstance(instance_, nullptr); } } // namespace vk \ No newline at end of file diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp index b7cbbd046..1847879a9 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp @@ -11,7 +11,7 @@ class VulkanInstance { ~VulkanInstance(); VulkanInstance(VulkanConfiguration& config); - VkInstance getInstance() const; + [[nodiscard]] VkInstance getInstance() const; private: VkInstance instance_; diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp index abdaca84f..7b38f0bac 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include "VulkanConfiguration.hpp" #include "VulkanDevice.hpp" @@ -14,7 +16,7 @@ namespace griddly { std::shared_ptr VulkanObserver::instance_ = nullptr; -VulkanObserver::VulkanObserver(std::shared_ptr grid, ResourceConfig resourceConfig, ShaderVariableConfig shaderVariableConfig) : Observer(grid), resourceConfig_(resourceConfig), shaderVariableConfig_(shaderVariableConfig) { +VulkanObserver::VulkanObserver(std::shared_ptr grid, ResourceConfig resourceConfig, ShaderVariableConfig shaderVariableConfig) : Observer(grid), resourceConfig_(std::move(resourceConfig)), shaderVariableConfig_(std::move(shaderVariableConfig)) { } VulkanObserver::~VulkanObserver() { @@ -55,7 +57,7 @@ void VulkanObserver::lazyInit() { auto configuration = vk::VulkanConfiguration(); if (instance_ == nullptr) { - instance_ = std::shared_ptr(new vk::VulkanInstance(configuration)); + instance_ = std::make_shared(configuration); } device_ = std::make_shared(vk::VulkanDevice(instance_, observerConfig_.tileSize, shaderPath)); @@ -94,8 +96,7 @@ vk::PersistentSSBOData VulkanObserver::updatePersistentShaderBuffers() { persistentSSBOData.playerInfoSSBOData.push_back(playerInfo); } - - spdlog::debug("Highlighting players {0}", observerConfig_.highlightPlayers ? "true": "false"); + spdlog::debug("Highlighting players {0}", observerConfig_.highlightPlayers ? "true" : "false"); persistentSSBOData.environmentUniform.viewMatrix = getViewMatrix(); persistentSSBOData.environmentUniform.gridDims = glm::vec2{gridWidth_, gridHeight_}; diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp index 01b4f5b8d..195099079 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp @@ -5,7 +5,6 @@ #include "../../Grid.hpp" #include "../Observer.hpp" - #include "VulkanDevice.hpp" // namespace vk { @@ -35,17 +34,16 @@ class VulkanObserver : public Observer { public: VulkanObserver(std::shared_ptr grid, ResourceConfig observerConfig, ShaderVariableConfig shaderVariableConfig); - ~VulkanObserver(); + ~VulkanObserver() override; void print(std::shared_ptr observation) override; - virtual uint8_t* update() override; + uint8_t* update() override; void init(ObserverConfig observerConfig) override; void reset() override; void release() override; protected: - virtual glm::mat4 getViewMatrix() = 0; virtual vk::PersistentSSBOData updatePersistentShaderBuffers(); virtual void updateFrameShaderBuffers() = 0; @@ -73,7 +71,6 @@ class VulkanObserver : public Observer { private: static std::shared_ptr instance_; - }; } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp index 25cae83e6..e45cb480f 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp @@ -33,7 +33,7 @@ inline VkShaderModule loadShader(std::string fileName, VkDevice device) { moduleCreateInfo.codeSize = size; moduleCreateInfo.pCode = (uint32_t*)shaderCode; - vk_check(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule)); + vk_check(vkCreateShaderModule(device, &moduleCreateInfo, nullptr, &shaderModule)); delete[] shaderCode; diff --git a/src/Griddly/Core/Observers/VulkanGridObserver.cpp b/src/Griddly/Core/Observers/VulkanGridObserver.cpp index a8f3b0cfe..5908f370c 100644 --- a/src/Griddly/Core/Observers/VulkanGridObserver.cpp +++ b/src/Griddly/Core/Observers/VulkanGridObserver.cpp @@ -11,8 +11,7 @@ namespace griddly { VulkanGridObserver::VulkanGridObserver(std::shared_ptr grid, ResourceConfig resourceConfig, ShaderVariableConfig shaderVariableConfig) : VulkanObserver(grid, resourceConfig, shaderVariableConfig) { } -VulkanGridObserver::~VulkanGridObserver() { -} +VulkanGridObserver::~VulkanGridObserver() = default; void VulkanGridObserver::resetShape() { spdlog::debug("Resetting grid observer shape."); diff --git a/src/Griddly/Core/Observers/VulkanGridObserver.hpp b/src/Griddly/Core/Observers/VulkanGridObserver.hpp index 078bd0c23..5bd4de53b 100644 --- a/src/Griddly/Core/Observers/VulkanGridObserver.hpp +++ b/src/Griddly/Core/Observers/VulkanGridObserver.hpp @@ -10,14 +10,14 @@ namespace griddly { class VulkanGridObserver : public VulkanObserver { public: VulkanGridObserver(std::shared_ptr grid, ResourceConfig resourceConfig, ShaderVariableConfig shaderVariableConfig); - ~VulkanGridObserver(); + ~VulkanGridObserver() override; protected: - virtual glm::mat4 getViewMatrix() override; + glm::mat4 getViewMatrix() override; virtual std::vector getExposedVariableValues(std::shared_ptr object); virtual PartialObservableGrid getObservableGrid(); virtual glm::mat4 getGlobalModelMatrix(); - virtual void updateFrameShaderBuffers() override; + void updateFrameShaderBuffers() override; virtual void updateObjectSSBOData(PartialObservableGrid& partiallyObservableGrid, glm::mat4& globalModelMatrix, DiscreteOrientation globalOrientation) = 0; diff --git a/src/Griddly/Core/PathFinder.cpp b/src/Griddly/Core/PathFinder.cpp index 059a493f5..069997516 100644 --- a/src/Griddly/Core/PathFinder.cpp +++ b/src/Griddly/Core/PathFinder.cpp @@ -1,10 +1,14 @@ #include "PathFinder.hpp" +#include + +#include + #include "Grid.hpp" namespace griddly { -PathFinder::PathFinder(std::shared_ptr grid, std::set impassableObjects) : grid_(grid), impassableObjects_(impassableObjects) { +PathFinder::PathFinder(std::shared_ptr grid, std::set impassableObjects) : grid_(std::move(std::move(grid))), impassableObjects_(std::move(std::move(impassableObjects))) { } } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/Players/Player.cpp b/src/Griddly/Core/Players/Player.cpp index 6a3db34a5..0819aef2e 100644 --- a/src/Griddly/Core/Players/Player.cpp +++ b/src/Griddly/Core/Players/Player.cpp @@ -1,12 +1,15 @@ +#include "Player.hpp" + #include +#include + #include "../GameProcess.hpp" -#include "Player.hpp" namespace griddly { Player::Player(uint32_t id, std::string name, std::shared_ptr observer) - : id_(id), name_(name), observer_(observer) { + : id_(id), name_(std::move(name)), observer_(std::move(observer)) { score_ = std::make_shared(0); } diff --git a/src/Griddly/Core/Players/Player.hpp b/src/Griddly/Core/Players/Player.hpp index 8dc25168b..6da4219b8 100644 --- a/src/Griddly/Core/Players/Player.hpp +++ b/src/Griddly/Core/Players/Player.hpp @@ -36,15 +36,15 @@ class Player { virtual uint8_t* observe(); - virtual std::string getName() const; - virtual uint32_t getId() const; - virtual std::shared_ptr getScore() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual std::string getName() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual uint32_t getId() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual std::shared_ptr getScore() const; virtual std::shared_ptr getAvatar(); virtual void setAvatar(std::shared_ptr avatarObject); - virtual std::shared_ptr getGameProcess() const; - virtual std::shared_ptr getObserver() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual std::shared_ptr getGameProcess() const; + [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] [[nodiscard]] virtual std::shared_ptr getObserver() const; virtual ~Player(); diff --git a/src/Griddly/Core/SpatialHashCollisionDetector.cpp b/src/Griddly/Core/SpatialHashCollisionDetector.cpp index 91683aaa5..eb812647e 100644 --- a/src/Griddly/Core/SpatialHashCollisionDetector.cpp +++ b/src/Griddly/Core/SpatialHashCollisionDetector.cpp @@ -14,7 +14,7 @@ bool SpatialHashCollisionDetector::upsert(std::shared_ptr object) { return isNewObject; } -void SpatialHashCollisionDetector::insert(std::shared_ptr object) { +void SpatialHashCollisionDetector::insert(const std::shared_ptr& object) { auto location = object->getLocation(); auto hash = calculateHash(location); @@ -54,7 +54,7 @@ SearchResult SpatialHashCollisionDetector::search(glm::ivec2 location) { std::vector hashes; for (uint32_t hashy = bottomLeft.y; hashy <= topRight.y; hashy++) { for (uint32_t hashx = bottomLeft.x; hashx <= topRight.x; hashx++) { - hashes.push_back({hashx, hashy}); + hashes.emplace_back(hashx, hashy); } } @@ -66,7 +66,7 @@ SearchResult SpatialHashCollisionDetector::search(glm::ivec2 location) { switch (triggerType_) { case TriggerType::RANGE_BOX_BOUNDARY: { - for (auto object : objectSet) { + for (const auto& object : objectSet) { auto collisionLocation = object->getLocation(); if (std::abs(location.x - collisionLocation.x) == range_ && std::abs(location.y - collisionLocation.y) <= range_) { spdlog::debug("Range collided object at ({0},{1}), source object at ({2},{3})", collisionLocation.x, collisionLocation.y, location.x, location.y); @@ -79,7 +79,7 @@ SearchResult SpatialHashCollisionDetector::search(glm::ivec2 location) { } } break; case TriggerType::RANGE_BOX_AREA: { - for (auto object : objectSet) { + for (const auto& object : objectSet) { auto collisionLocation = object->getLocation(); if (std::abs(location.y - collisionLocation.y) <= range_ && std::abs(location.x - collisionLocation.x) <= range_) { spdlog::debug("Area collided object at ({0},{1}), source object at ({2},{3})", collisionLocation.x, collisionLocation.y, location.x, location.y); @@ -97,7 +97,7 @@ SearchResult SpatialHashCollisionDetector::search(glm::ivec2 location) { return {collidedObjects, closestObjects}; } -glm::ivec2 SpatialHashCollisionDetector::calculateHash(glm::ivec2 location) { +glm::ivec2 SpatialHashCollisionDetector::calculateHash(glm::ivec2 location) const { auto xHash = location.x / cellSize_; auto yHash = location.y / cellSize_; return {xHash, yHash}; diff --git a/src/Griddly/Core/SpatialHashCollisionDetector.hpp b/src/Griddly/Core/SpatialHashCollisionDetector.hpp index 643472f50..7e4787420 100644 --- a/src/Griddly/Core/SpatialHashCollisionDetector.hpp +++ b/src/Griddly/Core/SpatialHashCollisionDetector.hpp @@ -11,16 +11,16 @@ class SpatialHashCollisionDetector : public CollisionDetector { public: SpatialHashCollisionDetector(uint32_t gridWidth, uint32_t gridHeight, uint32_t cellSize, uint32_t range, TriggerType triggerType); - virtual bool upsert(std::shared_ptr object) override; + bool upsert(std::shared_ptr object) override; - virtual bool remove(std::shared_ptr object) override; + bool remove(std::shared_ptr object) override; - virtual SearchResult search(glm::ivec2 location) override; + SearchResult search(glm::ivec2 location) override; private: - glm::ivec2 calculateHash(glm::ivec2 location); + glm::ivec2 calculateHash(glm::ivec2 location) const; - void insert(std::shared_ptr object); + void insert(const std::shared_ptr& object); std::unordered_map>> buckets_ = {}; diff --git a/src/Griddly/Core/TurnBasedGameProcess.cpp b/src/Griddly/Core/TurnBasedGameProcess.cpp index 3c5fd80ac..14ff505f8 100644 --- a/src/Griddly/Core/TurnBasedGameProcess.cpp +++ b/src/Griddly/Core/TurnBasedGameProcess.cpp @@ -2,6 +2,8 @@ #include +#include + #include "DelayedActionQueueItem.hpp" #include "Util/util.hpp" @@ -13,7 +15,7 @@ TurnBasedGameProcess::TurnBasedGameProcess( ObserverType globalObserverType, std::shared_ptr gdyFactory, std::shared_ptr grid) - : GameProcess(globalObserverType, gdyFactory, grid) { + : GameProcess(globalObserverType, std::move(gdyFactory), std::move(grid)) { } TurnBasedGameProcess::~TurnBasedGameProcess() { @@ -66,7 +68,7 @@ ActionResult TurnBasedGameProcess::performActions(uint32_t playerId, std::vector // This is only used in tests void TurnBasedGameProcess::setTerminationHandler(std::shared_ptr terminationHandler) { - terminationHandler_ = terminationHandler; + terminationHandler_ = std::move(terminationHandler); } std::string TurnBasedGameProcess::getProcessName() const { @@ -88,11 +90,11 @@ std::shared_ptr TurnBasedGameProcess::clone() { // Clone Global Variables spdlog::debug("Cloning global variables..."); std::unordered_map> clonedGlobalVariables; - for (auto globalVariableToCopy : grid_->getGlobalVariables()) { + for (const auto& globalVariableToCopy : grid_->getGlobalVariables()) { auto globalVariableName = globalVariableToCopy.first; auto playerVariableValues = globalVariableToCopy.second; - for (auto playerVariable : playerVariableValues) { + for (const auto& playerVariable : playerVariableValues) { auto playerId = playerVariable.first; auto variableValue = *playerVariable.second; spdlog::debug("Cloning {0}={1} for player {2}", globalVariableName, variableValue, playerId); @@ -103,7 +105,7 @@ std::shared_ptr TurnBasedGameProcess::clone() { // Initialize Object Types spdlog::debug("Cloning objects types..."); - for (auto objectDefinition : objectGenerator->getObjectDefinitions()) { + for (const auto& objectDefinition : objectGenerator->getObjectDefinitions()) { auto objectName = objectDefinition.second->objectName; // do not initialize these objects @@ -111,7 +113,7 @@ std::shared_ptr TurnBasedGameProcess::clone() { continue; } std::vector objectVariableNames; - for (auto variableNameIt : objectDefinition.second->variableDefinitions) { + for (const auto& variableNameIt : objectDefinition.second->variableDefinitions) { objectVariableNames.push_back(variableNameIt.first); } clonedGrid->initObject(objectName, objectVariableNames); @@ -131,7 +133,7 @@ std::shared_ptr TurnBasedGameProcess::clone() { // Clone Objects spdlog::debug("Cloning objects..."); - auto& objectsToCopy = grid_->getObjects(); + const auto & objectsToCopy = grid_->getObjects(); for (const auto& toCopy : objectsToCopy) { auto clonedObject = objectGenerator->cloneInstance(toCopy, clonedGrid); clonedGrid->addObject(toCopy->getLocation(), clonedObject, false, nullptr, toCopy->getObjectOrientation()); @@ -150,7 +152,7 @@ std::shared_ptr TurnBasedGameProcess::clone() { auto delayedActions = grid_->getDelayedActions(); spdlog::debug("Cloning delayed actions..."); - for (auto delayedActionToCopy : delayedActions) { + for (const auto& delayedActionToCopy : delayedActions) { auto remainingTicks = delayedActionToCopy->priority - tickCountToCopy; auto actionToCopy = delayedActionToCopy->action; auto playerId = delayedActionToCopy->playerId; diff --git a/src/Griddly/Core/TurnBasedGameProcess.hpp b/src/Griddly/Core/TurnBasedGameProcess.hpp index 2b7c7161c..741f7a7ce 100644 --- a/src/Griddly/Core/TurnBasedGameProcess.hpp +++ b/src/Griddly/Core/TurnBasedGameProcess.hpp @@ -12,19 +12,18 @@ class GDYFactory; class TurnBasedGameProcess : public GameProcess { public: TurnBasedGameProcess(ObserverType globalObserverType, std::shared_ptr gdyFactory, std::shared_ptr grid); - ~TurnBasedGameProcess(); + ~TurnBasedGameProcess() override; - virtual ActionResult performActions(uint32_t playerId, std::vector> actions, bool updateTicks = true) override; + ActionResult performActions(uint32_t playerId, std::vector> actions, bool updateTicks = true) override; - virtual std::string getProcessName() const override; + std::string getProcessName() const override; void setTerminationHandler(std::shared_ptr terminationHandler); // Clone the Game Process std::shared_ptr clone(); - virtual void seedRandomGenerator(uint32_t seed) override; - + void seedRandomGenerator(uint32_t seed) override; private: static const std::string name_; diff --git a/tests/src/Griddly/Core/AStarPathFinderTest.cpp b/tests/src/Griddly/Core/AStarPathFinderTest.cpp index 5a27a6d26..fe2b95ae5 100644 --- a/tests/src/Griddly/Core/AStarPathFinderTest.cpp +++ b/tests/src/Griddly/Core/AStarPathFinderTest.cpp @@ -54,9 +54,9 @@ ActionInputsDefinition getRotateAndForwardActions() { } TEST(AStarPathFinderTest, searchAllPassable) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto pathFinder = std::shared_ptr( - new AStarPathFinder(mockGridPtr, {}, getUpDownLeftRightActions())); + auto mockGridPtr = std::make_shared(); + auto pathFinder = std::make_shared( + mockGridPtr, std::set{}, getUpDownLeftRightActions()); TileObjects objects = {}; EXPECT_CALL(*mockGridPtr, getObjectsAt).WillRepeatedly(ReturnRef(objects)); @@ -76,8 +76,8 @@ TEST(AStarPathFinderTest, searchAllPassable) { } TEST(AStarPathFinderTest, searchNoPassable) { - auto mockObjectPtr = std::shared_ptr(new MockObject()); - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockObjectPtr = std::make_shared(); + auto mockGridPtr = std::make_shared(); const std::string objectName = "impassable_object"; EXPECT_CALL(*mockObjectPtr, getObjectName).WillRepeatedly(ReturnRef(objectName)); @@ -103,9 +103,9 @@ TEST(AStarPathFinderTest, searchNoPassable) { } TEST(AStarPathFinderTest, searchRotationActionsFacingGoal) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto pathFinder = std::shared_ptr( - new AStarPathFinder(mockGridPtr, {}, getRotateAndForwardActions())); + auto mockGridPtr = std::make_shared(); + auto pathFinder = std::make_shared( + mockGridPtr, std::set{}, getRotateAndForwardActions()); TileObjects objects = {}; EXPECT_CALL(*mockGridPtr, getObjectsAt).WillRepeatedly(ReturnRef(objects)); @@ -125,9 +125,9 @@ TEST(AStarPathFinderTest, searchRotationActionsFacingGoal) { } TEST(AStarPathFinderTest, searchRotationActions) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto pathFinder = std::shared_ptr( - new AStarPathFinder(mockGridPtr, {}, getRotateAndForwardActions())); + auto mockGridPtr = std::make_shared(); + auto pathFinder = std::make_shared( + mockGridPtr, std::set{}, getRotateAndForwardActions()); TileObjects objects = {}; EXPECT_CALL(*mockGridPtr, getObjectsAt).WillRepeatedly(ReturnRef(objects)); diff --git a/tests/src/Griddly/Core/GDY/Actions/ActionTest.cpp b/tests/src/Griddly/Core/GDY/Actions/ActionTest.cpp index d57221b93..c1775040b 100644 --- a/tests/src/Griddly/Core/GDY/Actions/ActionTest.cpp +++ b/tests/src/Griddly/Core/GDY/Actions/ActionTest.cpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/GDY/Actions/Action.hpp" #include "Mocks/Griddly/Core/MockGrid.hpp" #include "gmock/gmock.h" @@ -13,8 +15,8 @@ using ::testing::Return; namespace griddly { TEST(ActionTest, initActionLocations) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - std::shared_ptr action = std::shared_ptr(new Action(mockGridPtr, "testAction", 0, 0)); + auto mockGridPtr = std::make_shared(); + std::shared_ptr action = std::make_shared(mockGridPtr, "testAction", 0, 0); action->init({0, 1}, {3, 4}); diff --git a/tests/src/Griddly/Core/GDY/GDYFactoryTest.cpp b/tests/src/Griddly/Core/GDY/GDYFactoryTest.cpp index 21ae327b4..4de0cd612 100644 --- a/tests/src/Griddly/Core/GDY/GDYFactoryTest.cpp +++ b/tests/src/Griddly/Core/GDY/GDYFactoryTest.cpp @@ -40,8 +40,8 @@ YAML::Node loadFromStringAndGetNode(std::string yamlString, std::string nodeName } TEST(GDYFactoryTest, loadEnvironment) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto environmentNode = loadAndGetNode("tests/resources/loadEnvironment.yaml", "Environment"); @@ -66,8 +66,8 @@ TEST(GDYFactoryTest, loadEnvironment) { } TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_playerId) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -96,8 +96,8 @@ TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_playerId) { } TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_variables) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -126,8 +126,8 @@ TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_variables) { } TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_rotation) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -156,8 +156,8 @@ TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_rotation) { } TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_playerId_rotation_variables) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -188,8 +188,8 @@ TEST(GDYFactoryTest, loadEnvironment_VectorObserverConfig_playerId_rotation_vari } TEST(GDYFactoryTest, loadEnvironment_Observer) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto environmentNode = loadAndGetNode("tests/resources/loadEnvironmentObserver.yaml", "Environment"); @@ -214,8 +214,8 @@ TEST(GDYFactoryTest, loadEnvironment_Observer) { } TEST(GDYFactoryTest, loadEnvironment_BlockObserverConfig) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -246,8 +246,8 @@ TEST(GDYFactoryTest, loadEnvironment_BlockObserverConfig) { } TEST(GDYFactoryTest, loadEnvironment_SpriteObserverConfig) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -283,8 +283,8 @@ TEST(GDYFactoryTest, loadEnvironment_SpriteObserverConfig) { } TEST(GDYFactoryTest, loadEnvironment_IsometricSpriteObserverConfig) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -322,8 +322,8 @@ TEST(GDYFactoryTest, loadEnvironment_IsometricSpriteObserverConfig) { } TEST(GDYFactoryTest, loadEnvironment_ObserverNoAvatar) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto environmentNode = loadAndGetNode("tests/resources/loadEnvironmentObserverNoAvatar.yaml", "Environment"); @@ -346,7 +346,7 @@ TEST(GDYFactoryTest, loadEnvironment_ObserverNoAvatar) { } TEST(GDYFactoryTest, loadEnvironment_PlayerHighlight) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, nullptr, {})); auto yamlString = R"( Environment: @@ -375,7 +375,7 @@ TEST(GDYFactoryTest, loadEnvironment_PlayerHighlight) { } TEST(GDYFactoryTest, loadEnvironment_PlayerNoHighlight) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, nullptr, {})); auto yamlString = R"( Environment: @@ -405,7 +405,7 @@ TEST(GDYFactoryTest, loadEnvironment_PlayerNoHighlight) { } TEST(GDYFactoryTest, loadEnvironment_RotateAvatar) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, nullptr, {})); auto yamlString = R"( Environment: @@ -435,7 +435,7 @@ TEST(GDYFactoryTest, loadEnvironment_RotateAvatar) { } TEST(GDYFactoryTest, loadEnvironment_MultiPlayerNoHighlight) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, nullptr, {})); auto yamlString = R"( Environment: @@ -465,7 +465,7 @@ TEST(GDYFactoryTest, loadEnvironment_MultiPlayerNoHighlight) { } TEST(GDYFactoryTest, loadEnvironment_MultiPlayerHighlight) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, nullptr, {})); auto yamlString = R"( Environment: @@ -495,7 +495,7 @@ TEST(GDYFactoryTest, loadEnvironment_MultiPlayerHighlight) { TEST(GDYFactoryTest, loadEnvironment_termination_v1) { //auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(nullptr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -528,7 +528,7 @@ TEST(GDYFactoryTest, loadEnvironment_termination_v1) { TEST(GDYFactoryTest, loadEnvironment_termination_v2) { //auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(nullptr, mockTerminationGeneratorPtr, {})); auto yamlString = R"( Environment: @@ -582,8 +582,8 @@ TEST(GDYFactoryTest, loadEnvironment_termination_v2) { } TEST(GDYFactoryTest, loadObjects) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto objectsNode = loadAndGetNode("tests/resources/loadObjects.yaml", "Objects"); @@ -637,8 +637,8 @@ TEST(GDYFactoryTest, load_object_initial_actions) { )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto objectsNode = loadFromStringAndGetNode(std::string(yamlString), "Objects"); @@ -675,8 +675,8 @@ void expectOpposingDefinitionNOP(ActionBehaviourType behaviourType, std::string } void testBehaviourDefinition(std::string yamlString, ActionBehaviourDefinition expectedBehaviourDefinition, bool expectNOP) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -948,14 +948,14 @@ std::map> mockObjectDefs(std::vec } TEST(GDYFactoryTest, wallTest) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); - auto mockWall2Object = std::shared_ptr(new MockObject()); - auto mockWall16Object = std::shared_ptr(new MockObject()); - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockWall2Object = std::make_shared(); + auto mockWall16Object = std::make_shared(); + auto mockDefaultObject = std::make_shared(); std::string wall2String = "Wall2"; std::string wall16String = "Wall16"; @@ -969,7 +969,7 @@ TEST(GDYFactoryTest, wallTest) { auto objectDefinitions = mockObjectDefs({wall2String, wall16String}); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectNameFromMapChar(Eq('*'))) .WillRepeatedly(ReturnRef(wall2String)); @@ -999,16 +999,16 @@ TEST(GDYFactoryTest, wallTest) { } TEST(GDYFactoryTest, zIndexTest) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); - auto mockWallObject = std::shared_ptr(new MockObject()); - auto mockFloorObject = std::shared_ptr(new MockObject()); - auto mockGhostObject = std::shared_ptr(new MockObject()); + auto mockWallObject = std::make_shared(); + auto mockFloorObject = std::make_shared(); + auto mockGhostObject = std::make_shared(); - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockDefaultObject = std::make_shared(); std::string wall = "Wall2"; std::string floor = "floor"; @@ -1026,7 +1026,7 @@ TEST(GDYFactoryTest, zIndexTest) { auto objectDefinitions = mockObjectDefs({wall, floor, ghost}); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectNameFromMapChar(Eq('*'))) .WillRepeatedly(ReturnRef(wall)); @@ -1173,8 +1173,8 @@ TEST(GDYFactoryTest, action_input_mapping) { Relative: true )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1211,8 +1211,8 @@ TEST(GDYFactoryTest, action_input_default_values) { Relative: true )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1254,8 +1254,8 @@ TEST(GDYFactoryTest, action_input_meta_data) { Relative: true )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1282,8 +1282,8 @@ TEST(GDYFactoryTest, action_input_map_to_grid) { MapToGrid: true )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1302,8 +1302,8 @@ TEST(GDYFactoryTest, action_input_default_mapping) { - Name: move )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1333,8 +1333,8 @@ TEST(GDYFactoryTest, action_input_internal_mapping) { Internal: true )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1391,8 +1391,8 @@ TEST(GDYFactoryTest, action_range_trigger) { )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1440,8 +1440,8 @@ TEST(GDYFactoryTest, action_range_default_trigger_type) { )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); @@ -1486,8 +1486,8 @@ TEST(GDYFactoryTest, action_no_triggers) { )"; - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockTerminationGeneratorPtr = std::shared_ptr(new MockTerminationGenerator()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockTerminationGeneratorPtr = std::make_shared(); auto gdyFactory = std::shared_ptr(new GDYFactory(mockObjectGeneratorPtr, mockTerminationGeneratorPtr, {})); auto actionsNode = loadFromStringAndGetNode(std::string(yamlString), "Actions"); diff --git a/tests/src/Griddly/Core/GDY/Objects/ObjectGeneratorTest.cpp b/tests/src/Griddly/Core/GDY/Objects/ObjectGeneratorTest.cpp index 17074ccda..fe6e034eb 100644 --- a/tests/src/Griddly/Core/GDY/Objects/ObjectGeneratorTest.cpp +++ b/tests/src/Griddly/Core/GDY/Objects/ObjectGeneratorTest.cpp @@ -1,8 +1,9 @@ +#include #include -#include "Griddly/Core/TestUtils/common.hpp" #include "Griddly/Core/GDY/Objects/Object.hpp" #include "Griddly/Core/GDY/Objects/ObjectGenerator.hpp" +#include "Griddly/Core/TestUtils/common.hpp" #include "Mocks/Griddly/Core/GDY/Actions/MockAction.hpp" #include "Mocks/Griddly/Core/MockGrid.hpp" #include "gmock/gmock.h" @@ -24,7 +25,7 @@ namespace griddly { TEST(ObjectGeneratorTest, cloneInstance) { std::string objectAName = "objectA"; std::string objectBName = "objectB"; - DiscreteOrientation orientation = DiscreteOrientation(Direction::RIGHT); + auto orientation = DiscreteOrientation(Direction::RIGHT); glm::ivec2 location = {4, 5}; char mapCharacter = 'A'; uint32_t zIdx = 1; @@ -45,7 +46,7 @@ TEST(ObjectGeneratorTest, cloneInstance) { EXPECT_CALL(*mockObjectPtr, getRenderTileId).WillOnce(Return(4)); - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); std::map>> globalVariables = { {"globalVariable1", {{0, _V(1)}}}, @@ -54,7 +55,7 @@ TEST(ObjectGeneratorTest, cloneInstance) { EXPECT_CALL(*mockGridPtr, getGlobalVariables()).WillOnce(ReturnRef(globalVariables)); - auto objectGenerator = std::shared_ptr(new ObjectGenerator()); + auto objectGenerator = std::make_shared(); objectGenerator->setAvatarObject(objectAName); objectGenerator->defineNewObject(objectAName, mapCharacter, zIdx, {{"variable1", 0}, {"variable2", 0}}); diff --git a/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp b/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp index 42c044247..0b7179c6f 100644 --- a/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp +++ b/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp @@ -1,3 +1,4 @@ +#include #include #include "Griddly/Core/GDY/Objects/Object.hpp" @@ -24,7 +25,7 @@ using ::testing::UnorderedElementsAre; namespace griddly { std::shared_ptr setupAction(std::string actionName, uint32_t originatingPlayerId, std::shared_ptr sourceObject, std::shared_ptr destObject) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); EXPECT_CALL(*mockActionPtr, getActionName()) .WillRepeatedly(Return(actionName)); @@ -51,7 +52,7 @@ std::shared_ptr setupAction(std::string actionName, uint32_t origina } std::shared_ptr setupAction(std::string actionName, std::shared_ptr sourceObject, std::shared_ptr destObject) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); EXPECT_CALL(*mockActionPtr, getActionName()) .WillRepeatedly(Return(actionName)); @@ -78,7 +79,7 @@ std::shared_ptr setupAction(std::string actionName, std::shared_ptr< } std::shared_ptr setupAction(std::string actionName, std::shared_ptr sourceObject, glm::ivec2 destLocation) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); EXPECT_CALL(*mockActionPtr, getActionName()) .WillRepeatedly(Return(actionName)); @@ -102,7 +103,7 @@ std::shared_ptr setupAction(std::string actionName, std::shared_ptr< } std::shared_ptr setupAction(std::string actionName, std::shared_ptr sourceObject, std::shared_ptr destObject, glm::ivec2 destLocation) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); EXPECT_CALL(*mockActionPtr, getActionName()) .WillRepeatedly(Return(actionName)); @@ -126,7 +127,7 @@ std::shared_ptr setupAction(std::string actionName, std::shared_ptr< } TEST(ObjectTest, getLocation) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto object = std::make_shared(Object("object", 'o', 0, 0, {}, nullptr, mockGridPtr)); object->init({5, 5}); @@ -137,7 +138,7 @@ TEST(ObjectTest, getLocation) { } TEST(ObjectTest, getObjectName) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto object = std::make_shared(Object("object", 'o', 0, 0, {}, nullptr, mockGridPtr)); ASSERT_EQ(object->getObjectName(), "object"); @@ -146,7 +147,7 @@ TEST(ObjectTest, getObjectName) { } TEST(ObjectTest, getDescription) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto object = std::make_shared(Object("object", 'o', 0, 0, {}, nullptr, mockGridPtr)); object->init({9, 6}); @@ -157,7 +158,7 @@ TEST(ObjectTest, getDescription) { } TEST(ObjectTest, getPlayerId) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto object = std::make_shared(Object("object", 'o', 2, 0, {}, nullptr, mockGridPtr)); object->init({5, 5}); @@ -168,7 +169,7 @@ TEST(ObjectTest, getPlayerId) { } TEST(ObjectTest, getVariables) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto object = std::make_shared(Object("object", 'o', 2, 0, {{"test_param", _V(20)}}, nullptr, mockGridPtr)); ASSERT_EQ(*object->getVariableValue("test_param"), 20); @@ -362,7 +363,7 @@ BehaviourResult addCommandsAndExecute(ActionBehaviourType type, std::shared_ptr< } std::shared_ptr mockGrid() { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); EXPECT_CALL(*mockGridPtr, updateLocation) .WillRepeatedly(Return(true)); @@ -697,7 +698,7 @@ TEST(ObjectTest, command_mapped_to_grid) { //* Action: mapped_to_grid //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(2, "srcObject", glm::ivec2(0, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(5, "dstObject", glm::ivec2(1, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); @@ -719,7 +720,7 @@ TEST(ObjectTest, command_mapped_to_grid) { EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()) .Times(2) - .WillRepeatedly(Return(mockInputDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(mockInputDefinitions)); EXPECT_CALL(*mockGridPtr, performActions(Eq(0), SingletonMappedToGridMatcher("mapped_to_grid", srcObjectPtr, gridDimensions))) .Times(1) @@ -756,7 +757,7 @@ TEST(ObjectTest, command_exec_delayed) { //* ActionId: 2 //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(10, "srcObject", glm::ivec2(0, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(2, "dstObject", glm::ivec2(1, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); @@ -774,7 +775,7 @@ TEST(ObjectTest, command_exec_delayed) { EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()) .Times(2) - .WillRepeatedly(Return(mockInputDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(mockInputDefinitions)); EXPECT_CALL(*mockGridPtr, performActions(Eq(0), SingletonDelayedActionVectorMatcher("exec_action", 10, srcObjectPtr, glm::ivec2(0, -1)))) .Times(1) @@ -809,7 +810,7 @@ TEST(ObjectTest, command_exec) { //* ActionId: 2 //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(2, "srcObject", glm::ivec2(0, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(10, "dstObject", glm::ivec2(1, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); @@ -826,7 +827,7 @@ TEST(ObjectTest, command_exec) { EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()) .Times(2) - .WillRepeatedly(Return(mockInputDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(mockInputDefinitions)); auto mockActionPtr = setupAction("do_exec", srcObjectPtr, dstObjectPtr); @@ -865,7 +866,7 @@ TEST(ObjectTest, command_exec_with_action_player_id) { //* Executor: action //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(2, "srcObject", glm::ivec2(0, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(10, "dstObject", glm::ivec2(1, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); @@ -882,7 +883,7 @@ TEST(ObjectTest, command_exec_with_action_player_id) { EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()) .Times(2) - .WillRepeatedly(Return(mockInputDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(mockInputDefinitions)); auto mockActionPtr1 = setupAction("do_exec", 5, srcObjectPtr, dstObjectPtr); auto mockActionPtr2 = setupAction("do_exec", 4, srcObjectPtr, dstObjectPtr); @@ -924,7 +925,7 @@ TEST(ObjectTest, command_exec_with_object_player_id) { //* Executor: object //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(2, "srcObject", glm::ivec2(0, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(10, "dstObject", glm::ivec2(1, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); @@ -941,7 +942,7 @@ TEST(ObjectTest, command_exec_with_object_player_id) { EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()) .Times(2) - .WillRepeatedly(Return(mockInputDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(mockInputDefinitions)); auto mockActionPtr = setupAction("do_exec", srcObjectPtr, dstObjectPtr); @@ -976,7 +977,7 @@ TEST(ObjectTest, command_exec_randomize) { //* Action: exec_action //* Randomize: true //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(1, "srcObject", glm::ivec2(3, 3), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(1, "dstObject", glm::ivec2(6, 6), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); @@ -993,7 +994,7 @@ TEST(ObjectTest, command_exec_randomize) { EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()) .Times(2) - .WillRepeatedly(Return(mockInputDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(mockInputDefinitions)); EXPECT_CALL(*mockGridPtr, performActions(Eq(0), SingletonActionVectorOriginatingPlayerMatcher("exec_action", srcObjectPtr, 1, glm::ivec2(-1, 0)))) .Times(1) @@ -1030,7 +1031,7 @@ TEST(ObjectTest, command_exec_search) { //* Search: //* TargetLocation: [6, 7] //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(1, "srcObject", glm::ivec2(0, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(1, "dstObject", glm::ivec2(5, 6), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); @@ -1066,7 +1067,7 @@ TEST(ObjectTest, command_exec_search) { EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()) .Times(4) - .WillRepeatedly(Return(mockInputDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(mockInputDefinitions)); EXPECT_CALL(*mockGridPtr, performActions(Eq(0), SingletonDelayedActionVectorMatcher("exec_action", 10, srcObjectPtr, glm::ivec2(1, 0)))) .Times(1) @@ -1136,7 +1137,7 @@ TEST(ObjectTest, command_change_to) { //* - change_to: newObject //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(1, "srcObject", glm::ivec2(0, 0), Direction(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(2, "dstObject", glm::ivec2(1, 0), Direction(), {}, mockGridPtr, mockObjectGenerator); @@ -1188,7 +1189,7 @@ TEST(ObjectTest, command_set_tile) { //* - set_tile: 1 //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(1, "srcObject", glm::ivec2(0, 0), Direction(), {}, mockGridPtr, mockObjectGenerator); auto dstObjectPtr = setupObject(2, "dstObject", glm::ivec2(1, 0), Direction(), {}, mockGridPtr, mockObjectGenerator); @@ -1220,7 +1221,7 @@ TEST(ObjectTest, command_spawn) { //* Object: _empty //* - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockObjectGenerator = std::make_shared(); auto mockGridPtr = mockGrid(); auto srcObjectPtr = setupObject(1, "srcObject", glm::ivec2(0, 0), Direction(), {}, mockGridPtr, mockObjectGenerator); auto newObjectPtr = setupObject("newObject", {}); @@ -1552,8 +1553,8 @@ TEST(ObjectTest, isValidActionDestinationLocationOutsideGrid) { } TEST(ObjectTest, getInitialActions) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockObjectGenerator = std::make_shared(); std::string objectName = "objectName"; @@ -1579,7 +1580,7 @@ TEST(ObjectTest, getInitialActions) { {"action2Name", {{{2, {{2, 2}, {2, 2}, "description2"}}}}}}; - EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()).WillRepeatedly(Return(mockActionInputDefinitions)); + EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()).WillRepeatedly(ReturnRefOfCopy(mockActionInputDefinitions)); EXPECT_CALL(*mockGridPtr, getRandomGenerator()).WillRepeatedly(Return(std::mt19937())); auto object = std::make_shared(Object(objectName, 'S', 0, 0, {}, mockObjectGenerator, mockGridPtr)); @@ -1600,13 +1601,13 @@ TEST(ObjectTest, getInitialActions) { } TEST(ObjectTest, getInitialActionsWithOriginatingAction) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockObjectGenerator = std::make_shared(); std::string objectName = "objectName"; std::string originatingActionName = "originatingAction"; - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); EXPECT_CALL(*mockActionPtr, getActionName()) .WillRepeatedly(Return(originatingActionName)); @@ -1645,7 +1646,7 @@ TEST(ObjectTest, getInitialActionsWithOriginatingAction) { {"action2Name", {{{2, {{2, 2}, {2, 2}, "description2"}}}}}}; - EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()).WillRepeatedly(Return(mockActionInputDefinitions)); + EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()).WillRepeatedly(ReturnRefOfCopy(mockActionInputDefinitions)); EXPECT_CALL(*mockGridPtr, getRandomGenerator()).WillRepeatedly(Return(std::mt19937())); auto object = std::make_shared(Object(objectName, 'S', 0, 0, {}, mockObjectGenerator, mockGridPtr)); diff --git a/tests/src/Griddly/Core/GDY/TerminationHandlerTest.cpp b/tests/src/Griddly/Core/GDY/TerminationHandlerTest.cpp index d0037e5d8..04bea2ad4 100644 --- a/tests/src/Griddly/Core/GDY/TerminationHandlerTest.cpp +++ b/tests/src/Griddly/Core/GDY/TerminationHandlerTest.cpp @@ -18,9 +18,9 @@ using ::testing::UnorderedElementsAre; namespace griddly { TEST(TerminationHandlerTest, terminateOnPlayerScore) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); - auto mockPlayer2Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); + auto mockPlayer2Ptr = std::make_shared(); auto player1Score = std::make_shared(10); auto player2Score = std::make_shared(5); @@ -44,7 +44,7 @@ TEST(TerminationHandlerTest, terminateOnPlayerScore) { .Times(1) .WillOnce(ReturnRef(globalVariables)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); TerminationConditionDefinition tcd; tcd.commandName = "eq"; @@ -62,9 +62,9 @@ TEST(TerminationHandlerTest, terminateOnPlayerScore) { } TEST(TerminationHandlerTest, terminateOnPlayerObjects0) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); - auto mockPlayer2Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); + auto mockPlayer2Ptr = std::make_shared(); auto player1Score = std::make_shared(0); auto player2Score = std::make_shared(0); @@ -93,7 +93,7 @@ TEST(TerminationHandlerTest, terminateOnPlayerObjects0) { EXPECT_CALL(*mockPlayer2Ptr, getScore()) .WillRepeatedly(Return(player2Score)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); // Player with 0 bases will end the game and "lose" TerminationConditionDefinition tcd; @@ -112,9 +112,9 @@ TEST(TerminationHandlerTest, terminateOnPlayerObjects0) { } TEST(TerminationHandlerTest, terminateOnGlobalVariable) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); - auto mockPlayer2Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); + auto mockPlayer2Ptr = std::make_shared(); auto player1Score = std::make_shared(0); auto player2Score = std::make_shared(0); @@ -142,7 +142,7 @@ TEST(TerminationHandlerTest, terminateOnGlobalVariable) { EXPECT_CALL(*mockPlayer2Ptr, getScore()) .WillRepeatedly(Return(player2Score)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); TerminationConditionDefinition tcd; tcd.commandName = "eq"; @@ -159,9 +159,9 @@ TEST(TerminationHandlerTest, terminateOnGlobalVariable) { } TEST(TerminationHandlerTest, terminateOnPlayerGlobalVariable) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); - auto mockPlayer2Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); + auto mockPlayer2Ptr = std::make_shared(); auto player1Score = std::make_shared(0); auto player2Score = std::make_shared(0); @@ -193,7 +193,7 @@ TEST(TerminationHandlerTest, terminateOnPlayerGlobalVariable) { EXPECT_CALL(*mockPlayer2Ptr, getScore()) .WillRepeatedly(Return(player2Score)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); // Player with variable_name == 20 will win and the other player will lose TerminationConditionDefinition tcd; @@ -212,9 +212,9 @@ TEST(TerminationHandlerTest, terminateOnPlayerGlobalVariable) { } TEST(TerminationHandlerTest, terminateOnMaxTicks) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); - auto mockPlayer2Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); + auto mockPlayer2Ptr = std::make_shared(); auto player1Score = std::make_shared(0); auto player2Score = std::make_shared(0); @@ -244,7 +244,7 @@ TEST(TerminationHandlerTest, terminateOnMaxTicks) { .Times(1) .WillOnce(ReturnRef(globalVariables)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); TerminationConditionDefinition tcd; tcd.commandName = "eq"; @@ -262,8 +262,8 @@ TEST(TerminationHandlerTest, terminateOnMaxTicks) { } TEST(TerminationHandlerTest, singlePlayer_differentId_win) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); auto players = std::vector>{mockPlayer1Ptr}; @@ -280,7 +280,7 @@ TEST(TerminationHandlerTest, singlePlayer_differentId_win) { .Times(1) .WillOnce(Return(playerObjectCounter)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); TerminationConditionDefinition tcd; tcd.commandName = "eq"; @@ -298,8 +298,8 @@ TEST(TerminationHandlerTest, singlePlayer_differentId_win) { } TEST(TerminationHandlerTest, singlePlayer_differentId_lose) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); auto players = std::vector>{mockPlayer1Ptr}; @@ -316,7 +316,7 @@ TEST(TerminationHandlerTest, singlePlayer_differentId_lose) { .Times(1) .WillOnce(Return(playerObjectCounter)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); TerminationConditionDefinition tcd; tcd.commandName = "eq"; @@ -334,8 +334,8 @@ TEST(TerminationHandlerTest, singlePlayer_differentId_lose) { } TEST(TerminationHandlerTest, singlePlayer_sameId_lose) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); auto players = std::vector>{mockPlayer1Ptr}; @@ -352,7 +352,7 @@ TEST(TerminationHandlerTest, singlePlayer_sameId_lose) { .Times(1) .WillOnce(ReturnRef(globalVariables)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); TerminationConditionDefinition tcd; tcd.commandName = "eq"; @@ -370,8 +370,8 @@ TEST(TerminationHandlerTest, singlePlayer_sameId_lose) { } TEST(TerminationHandlerTest, singlePlayer_sameId_win) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockPlayer1Ptr = std::shared_ptr(new MockPlayer()); + auto mockGridPtr = std::make_shared(); + auto mockPlayer1Ptr = std::make_shared(); auto players = std::vector>{mockPlayer1Ptr}; @@ -388,7 +388,7 @@ TEST(TerminationHandlerTest, singlePlayer_sameId_win) { .Times(1) .WillOnce(ReturnRef(globalVariables)); - auto terminationHandlerPtr = std::shared_ptr(new TerminationHandler(mockGridPtr, players)); + auto terminationHandlerPtr = std::make_shared(mockGridPtr, players); TerminationConditionDefinition tcd; tcd.commandName = "eq"; diff --git a/tests/src/Griddly/Core/GameProcessTest.cpp b/tests/src/Griddly/Core/GameProcessTest.cpp index f470bd433..fcfd81897 100644 --- a/tests/src/Griddly/Core/GameProcessTest.cpp +++ b/tests/src/Griddly/Core/GameProcessTest.cpp @@ -1,4 +1,5 @@ #include +#include #include "Griddly/Core/TurnBasedGameProcess.cpp" #include "Mocks/Griddly/Core/GDY/MockGDYFactory.hpp" @@ -30,13 +31,13 @@ MATCHER_P(ObserverConfigEqMatcher, definition, "") { auto isEqual = definition.gridXOffset == arg.gridXOffset && definition.gridYOffset == arg.gridYOffset && definition.rotateWithAvatar == arg.rotateWithAvatar; - definition.playerId == arg.playerId; - definition.playerCount == arg.playerCount; + // definition.playerId == arg.playerId && + // definition.playerCount == arg.playerCount; return isEqual; } std::shared_ptr mockPlayer(std::string playerName, uint32_t playerId, std::shared_ptr gameProcessPtr, std::shared_ptr mockPlayerAvatarPtr, std::shared_ptr mockPlayerObserverPtr) { - auto mockPlayerPtr = std::shared_ptr(new MockPlayer()); + auto mockPlayerPtr = std::make_shared(); EXPECT_CALL(*mockPlayerPtr, getName) .WillRepeatedly(Return(playerName)); EXPECT_CALL(*mockPlayerPtr, getId) @@ -63,14 +64,14 @@ std::shared_ptr mockPlayer(std::string playerName, uint32_t playerId } TEST(GameProcessTest, init) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockLevelGenerator = std::shared_ptr(new MockLevelGenerator()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockLevelGenerator = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); - auto mockPlayerObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockObserverPtr = std::make_shared(mockGridPtr); + auto mockPlayerObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockGridPtr, resetGlobalVariables) .Times(1); @@ -84,7 +85,7 @@ TEST(GameProcessTest, init) { EXPECT_CALL(*mockGDYFactoryPtr, getGlobalVariableDefinitions()) .WillOnce(Return(std::unordered_map{})); - auto mockPlayerAvatarPtr = std::shared_ptr(new MockObject()); + auto mockPlayerAvatarPtr = std::make_shared(); EXPECT_CALL(*mockLevelGeneratorPtr, reset(Eq(mockGridPtr))) .Times(1); @@ -115,14 +116,14 @@ TEST(GameProcessTest, init) { } TEST(GameProcessTest, initAlreadyInitialized) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockLevelGenerator = std::shared_ptr(new MockLevelGenerator()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockLevelGenerator = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); - auto mockPlayerObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockObserverPtr = std::make_shared(mockGridPtr); + auto mockPlayerObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockGridPtr, resetGlobalVariables) .Times(1); @@ -136,7 +137,7 @@ TEST(GameProcessTest, initAlreadyInitialized) { EXPECT_CALL(*mockGDYFactoryPtr, createObserver(Eq(mockGridPtr), Eq(ObserverType::VECTOR))) .WillOnce(Return(mockObserverPtr)); - auto mockPlayerAvatarPtr = std::shared_ptr(new MockObject()); + auto mockPlayerAvatarPtr = std::make_shared(); EXPECT_CALL(*mockLevelGeneratorPtr, reset(Eq(mockGridPtr))) .Times(1); @@ -177,14 +178,14 @@ TEST(GameProcessTest, initAlreadyInitialized) { } TEST(GameProcessTest, initNoPlayerObserverDefinition) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockLevelGenerator = std::shared_ptr(new MockLevelGenerator()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockLevelGenerator = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); - auto mockPlayerObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockObserverPtr = std::make_shared(mockGridPtr); + auto mockPlayerObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockGridPtr, resetGlobalVariables) .Times(1); @@ -199,7 +200,7 @@ TEST(GameProcessTest, initNoPlayerObserverDefinition) { .Times(1) .WillOnce(Return(mockObserverPtr)); - auto mockPlayerAvatarPtr = std::shared_ptr(new MockObject()); + auto mockPlayerAvatarPtr = std::make_shared(); EXPECT_CALL(*mockLevelGeneratorPtr, reset(Eq(mockGridPtr))) .Times(1); @@ -219,7 +220,7 @@ TEST(GameProcessTest, initNoPlayerObserverDefinition) { EXPECT_CALL(*mockGDYFactoryPtr, getPlayerCount()) .WillRepeatedly(Return(1)); - auto mockPlayerPtr = std::shared_ptr(new MockPlayer()); + auto mockPlayerPtr = std::make_shared(); EXPECT_CALL(*mockPlayerPtr, getName) .WillRepeatedly(Return("Bob")); EXPECT_CALL(*mockPlayerPtr, getId) @@ -254,14 +255,14 @@ TEST(GameProcessTest, initNoPlayerObserverDefinition) { } TEST(GameProcessTest, initWrongNumberOfPlayers) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockLevelGenerator = std::shared_ptr(new MockLevelGenerator()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockLevelGenerator = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); - auto mockPlayerObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockObserverPtr = std::make_shared(mockGridPtr); + auto mockPlayerObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockGridPtr, resetGlobalVariables) .Times(1); @@ -276,7 +277,7 @@ TEST(GameProcessTest, initWrongNumberOfPlayers) { .Times(1) .WillOnce(Return(mockObserverPtr)); - auto mockPlayerAvatarPtr = std::shared_ptr(new MockObject()); + auto mockPlayerAvatarPtr = std::make_shared(); EXPECT_CALL(*mockLevelGeneratorPtr, reset(Eq(mockGridPtr))) .Times(1); @@ -294,7 +295,7 @@ TEST(GameProcessTest, initWrongNumberOfPlayers) { EXPECT_CALL(*mockGDYFactoryPtr, getPlayerCount()) .WillRepeatedly(Return(10)); - auto mockPlayerPtr = std::shared_ptr(new MockPlayer()); + auto mockPlayerPtr = std::make_shared(); EXPECT_CALL(*mockPlayerPtr, getObserver()) .WillRepeatedly(Return(mockObserverPtr)); @@ -312,13 +313,13 @@ TEST(GameProcessTest, initWrongNumberOfPlayers) { } TEST(GameProcessTest, reset) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); - auto mockPlayerObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockObserverPtr = std::make_shared(mockGridPtr); + auto mockPlayerObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockGDYFactoryPtr, getLevelGenerator(Eq(0))) .WillRepeatedly(Return(mockLevelGeneratorPtr)); @@ -330,7 +331,7 @@ TEST(GameProcessTest, reset) { .Times(1) .WillOnce(Return(mockObserverPtr)); - auto mockPlayerAvatarPtr = std::shared_ptr(new MockObject()); + auto mockPlayerAvatarPtr = std::make_shared(); auto observerConfig = ObserverConfig{10, 10, 0, 0, false}; EXPECT_CALL(*mockObserverPtr, init(ObserverConfigEqMatcher(observerConfig))) @@ -367,11 +368,11 @@ TEST(GameProcessTest, reset) { } TEST(GameProcessTest, resetNotInitialized) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockLevelGenerator = std::shared_ptr(new MockLevelGenerator()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockLevelGenerator = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::VECTOR, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); ASSERT_THROW(gameProcessPtr->reset(), std::runtime_error); @@ -380,11 +381,11 @@ TEST(GameProcessTest, resetNotInitialized) { } TEST(GameProcessTest, addPlayer) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockLevelGenerator = std::shared_ptr(new MockLevelGenerator()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockLevelGenerator = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); auto mockPlayerPtr1 = mockPlayer("Bob", 1, nullptr, nullptr, nullptr); auto mockPlayerPtr2 = mockPlayer("Alice", 2, nullptr, nullptr, nullptr); @@ -408,15 +409,15 @@ TEST(GameProcessTest, addPlayer) { } TEST(GameProcessTest, addTooManyPlayers) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockLevelGenerator = std::shared_ptr(new MockLevelGenerator()); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockGridPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockLevelGenerator = std::make_shared(); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); + auto mockLevelGeneratorPtr = std::make_shared(); auto mockPlayerPtr1 = mockPlayer("Bob", 1, nullptr, nullptr, nullptr); auto mockPlayerPtr2 = mockPlayer("Alice", 2, nullptr, nullptr, nullptr); - auto mockPlayerPtr3 = std::shared_ptr(new MockPlayer()); + auto mockPlayerPtr3 = std::make_shared(); EXPECT_CALL(*mockPlayerPtr3, getName) .WillRepeatedly(Return("Obama")); EXPECT_CALL(*mockPlayerPtr3, getId) @@ -438,7 +439,7 @@ TEST(GameProcessTest, addTooManyPlayers) { } TEST(GameProcessTest, performActions) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); uint32_t playerId = 1; @@ -453,10 +454,10 @@ TEST(GameProcessTest, performActions) { EXPECT_CALL(*mockGridPtr, resetGlobalVariables(_)) .Times(2); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); - auto mockTerminationHandlerPtr = std::shared_ptr(new MockTerminationHandler(mockGridPtr)); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockLevelGeneratorPtr = std::make_shared(); + auto mockTerminationHandlerPtr = std::make_shared(mockGridPtr); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockLevelGeneratorPtr, reset(Eq(mockGridPtr))) .Times(2); @@ -474,7 +475,7 @@ TEST(GameProcessTest, performActions) { EXPECT_CALL(*mockGDYFactoryPtr, createObserver(Eq(mockGridPtr), Eq(ObserverType::NONE))) .WillOnce(Return(mockObserverPtr)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); auto mockPlayerPtr = mockPlayer("Bob", 1, gameProcessPtr, nullptr, mockObserverPtr); @@ -483,7 +484,7 @@ TEST(GameProcessTest, performActions) { gameProcessPtr->init(); gameProcessPtr->reset(); - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); auto actionsList = std::vector>{mockActionPtr}; @@ -511,7 +512,7 @@ TEST(GameProcessTest, performActions) { } TEST(GameProcessTest, performActionsMultiAgentRewards) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); uint32_t player1Id = 1; uint32_t player2Id = 2; @@ -528,10 +529,10 @@ TEST(GameProcessTest, performActionsMultiAgentRewards) { EXPECT_CALL(*mockGridPtr, resetGlobalVariables(_)) .Times(2); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); - auto mockTerminationHandlerPtr = std::shared_ptr(new MockTerminationHandler(mockGridPtr)); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockLevelGeneratorPtr = std::make_shared(); + auto mockTerminationHandlerPtr = std::make_shared(mockGridPtr); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockLevelGeneratorPtr, reset(Eq(mockGridPtr))) .Times(2); @@ -549,7 +550,7 @@ TEST(GameProcessTest, performActionsMultiAgentRewards) { EXPECT_CALL(*mockGDYFactoryPtr, createObserver(Eq(mockGridPtr), Eq(ObserverType::NONE))) .WillOnce(Return(mockObserverPtr)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); auto mockPlayerPtr1 = mockPlayer("Bob", 1, gameProcessPtr, nullptr, mockObserverPtr); auto mockPlayerPtr2 = mockPlayer("Spiff", 2, gameProcessPtr, nullptr, mockObserverPtr); @@ -562,7 +563,7 @@ TEST(GameProcessTest, performActionsMultiAgentRewards) { gameProcessPtr->init(); gameProcessPtr->reset(); - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); auto actionsList = std::vector>{mockActionPtr}; @@ -612,7 +613,7 @@ TEST(GameProcessTest, performActionsMultiAgentRewards) { } TEST(GameProcessTest, performActionsDelayedReward) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); std::map>> globalVariables{}; @@ -625,10 +626,10 @@ TEST(GameProcessTest, performActionsDelayedReward) { EXPECT_CALL(*mockGridPtr, resetGlobalVariables(_)) .Times(2); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); - auto mockTerminationHandlerPtr = std::shared_ptr(new MockTerminationHandler(mockGridPtr)); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGridPtr)); + auto mockLevelGeneratorPtr = std::make_shared(); + auto mockTerminationHandlerPtr = std::make_shared(mockGridPtr); + auto mockGDYFactoryPtr = std::make_shared(); + auto mockObserverPtr = std::make_shared(mockGridPtr); EXPECT_CALL(*mockLevelGeneratorPtr, reset(Eq(mockGridPtr))) .Times(2); @@ -646,7 +647,7 @@ TEST(GameProcessTest, performActionsDelayedReward) { EXPECT_CALL(*mockGDYFactoryPtr, createObserver(Eq(mockGridPtr), Eq(ObserverType::NONE))) .WillOnce(Return(mockObserverPtr)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); auto mockPlayerPtr = mockPlayer("Bob", 1, gameProcessPtr, nullptr, mockObserverPtr); @@ -655,7 +656,7 @@ TEST(GameProcessTest, performActionsDelayedReward) { gameProcessPtr->init(); gameProcessPtr->reset(); - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); std::vector> actionList{mockActionPtr}; @@ -685,14 +686,14 @@ TEST(GameProcessTest, performActionsDelayedReward) { } TEST(GameProcessTest, getAvailableActionNames) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto mockObject1 = mockObject("object", 'o', 0, 0, {0, 1}, DiscreteOrientation(), {"move", "internal"}); auto mockObject2 = mockObject("object", 'o', 1, 0, {4, 6}, DiscreteOrientation(), {"move", "fire"}); auto mockObject3 = mockObject("object", 'o', 1, 0, {20, 13}, DiscreteOrientation(), {}); auto objects = std::unordered_set>{mockObject1, mockObject2, mockObject3}; - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); + auto mockGDYFactoryPtr = std::make_shared(); std::unordered_map mockActionInputsDefinitions = { {"move", {{}, false, false}}, {"internal", {{}, false, true}}, @@ -705,7 +706,7 @@ TEST(GameProcessTest, getAvailableActionNames) { EXPECT_CALL(*mockGridPtr, getObjects()) .WillOnce(ReturnRef(objects)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); auto availableActionNames = gameProcessPtr->getAvailableActionNames(1); @@ -714,13 +715,13 @@ TEST(GameProcessTest, getAvailableActionNames) { } // namespace griddly TEST(GameProcessTest, getAvailableActionNames_empty) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto objects = std::unordered_set>{}; EXPECT_CALL(*mockGridPtr, getObjects()) .WillOnce(ReturnRef(objects)); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); + auto mockGDYFactoryPtr = std::make_shared(); std::unordered_map mockActionInputsDefinitions = { {"move", {{}, false, false}}, {"internal", {{}, false, true}}, @@ -730,14 +731,14 @@ TEST(GameProcessTest, getAvailableActionNames_empty) { .Times(1) .WillRepeatedly(Return(mockActionInputsDefinitions)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); auto availableActionNames = gameProcessPtr->getAvailableActionNames(1); ASSERT_EQ(availableActionNames.size(), 0); } std::shared_ptr mockTestAction(std::string actionName, glm::ivec2 vectorToDest) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); EXPECT_CALL(*mockActionPtr, getActionName()) .WillRepeatedly(Return(actionName)); @@ -756,7 +757,7 @@ MATCHER_P2(ActionAndVectorEqMatcher, actionName, vectorToDest, "") { } TEST(GameProcessTest, getAvailableIdsForActionType) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto objectLocation = glm::ivec2{0, 1}; auto mockObject1 = mockObject("object", 'o', 1, 0, objectLocation, DiscreteOrientation(), {"move", "attack"}); @@ -765,7 +766,7 @@ TEST(GameProcessTest, getAvailableIdsForActionType) { .Times(2) .WillRepeatedly(Return(mockObject1)); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); + auto mockGDYFactoryPtr = std::make_shared(); std::unordered_map mockActionInputsDefinitions = { { @@ -801,7 +802,7 @@ TEST(GameProcessTest, getAvailableIdsForActionType) { .Times(2) .WillRepeatedly(Return(mockActionInputsDefinitions)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); auto availableMoveActionIds = gameProcessPtr->getAvailableActionIdsAtLocation(objectLocation, "move"); auto availableAttackActionIds = gameProcessPtr->getAvailableActionIdsAtLocation(objectLocation, "attack"); @@ -815,7 +816,7 @@ TEST(GameProcessTest, getAvailableIdsForActionType) { } TEST(GameProcessTest, getState) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); auto globalVar = _V(5); auto playerVar = _V(6); @@ -839,7 +840,7 @@ TEST(GameProcessTest, getState) { EXPECT_CALL(*mockGridPtr, getGlobalVariables()) .WillRepeatedly(ReturnRef(globalVariables)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, nullptr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, nullptr, mockGridPtr); auto state = gameProcessPtr->getState(); @@ -873,10 +874,10 @@ TEST(GameProcessTest, getState) { } TEST(GameProcessTest, clone) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); + auto mockGridPtr = std::make_shared(); + auto mockLevelGeneratorPtr = std::make_shared(); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockGDYFactoryPtr = std::make_shared(); auto globalVar = _V(5); auto playerVar = _V(6); @@ -915,7 +916,7 @@ TEST(GameProcessTest, clone) { {"object3", std::make_shared(ObjectDefinition{"object3", 'c'})}, }; - EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()).WillRepeatedly(Return(mockObjectDefinitions)); + EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()).WillRepeatedly(ReturnRefOfCopy(mockObjectDefinitions)); EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject1), _)).WillRepeatedly(Return(clonedMockObject1)); EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject2), _)).WillRepeatedly(Return(clonedMockObject2)); EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject3), _)).WillRepeatedly(Return(clonedMockObject3)); @@ -923,11 +924,11 @@ TEST(GameProcessTest, clone) { EXPECT_CALL(*mockGDYFactoryPtr, getObjectGenerator()).WillRepeatedly(Return(mockObjectGeneratorPtr)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::make_shared(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr); for (int i = 0; i < 100; i++) { auto clonedPtr = gameProcessPtr->clone(); } } -} // namespace griddly \ No newline at end of file +} // namespace griddly diff --git a/tests/src/Griddly/Core/GridTest.cpp b/tests/src/Griddly/Core/GridTest.cpp index 12dfdba79..8aca310b8 100644 --- a/tests/src/Griddly/Core/GridTest.cpp +++ b/tests/src/Griddly/Core/GridTest.cpp @@ -1,4 +1,5 @@ +#include #include #include "Griddly/Core/Grid.cpp" @@ -32,7 +33,7 @@ MATCHER_P(ActionEventMatcher, expectedEvent, "") { } TEST(GridTest, getHeightAndWidth) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); ASSERT_EQ(grid->getWidth(), 123); @@ -40,7 +41,7 @@ TEST(GridTest, getHeightAndWidth) { } TEST(GridTest, initializeAvatarObjectDefaultPlayer) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto mockObjectPtr = mockObject("player_1_avatar"); @@ -62,7 +63,7 @@ TEST(GridTest, initializeAvatarObjectDefaultPlayer) { } TEST(GridTest, initializeAvatarObjectSpecificPlayer) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto mockObjectPtr = mockObject("player_1_avatar", '?', 3); @@ -84,7 +85,7 @@ TEST(GridTest, initializeAvatarObjectSpecificPlayer) { } TEST(GridTest, initializeObject) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto mockObjectPtr = mockObject("object_1"); @@ -99,7 +100,7 @@ TEST(GridTest, initializeObject) { } TEST(GridTest, initializeObjectPositionTwice) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto mockObjectPtr = mockObject("object_1"); @@ -120,7 +121,7 @@ TEST(GridTest, initializeObjectPositionTwice) { } TEST(GridTest, initializeObjectPositionTwiceDifferentZ) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto mockObjectPtr = mockObject("object1", '?', 1, 0); @@ -141,7 +142,7 @@ TEST(GridTest, initializeObjectPositionTwiceDifferentZ) { } TEST(GridTest, initializeObjectTwice) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto mockObjectPtr = mockObject("object"); @@ -160,7 +161,7 @@ TEST(GridTest, initializeObjectTwice) { } TEST(GridTest, removeObject) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto playerId = 1; @@ -180,7 +181,7 @@ TEST(GridTest, removeObject) { } TEST(GridTest, removeObjectNotInitialized) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); auto objectLocation = glm::ivec2{4, 4}; @@ -196,7 +197,7 @@ TEST(GridTest, removeObjectNotInitialized) { } TEST(GridTest, performActionDefaultObject) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -230,7 +231,7 @@ TEST(GridTest, performActionDefaultObject) { } TEST(GridTest, performActionOnEmptySpace) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -264,7 +265,7 @@ TEST(GridTest, performActionOnEmptySpace) { } TEST(GridTest, performActionOnObjectWithNeutralPlayerId) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -310,7 +311,7 @@ TEST(GridTest, performActionOnObjectWithNeutralPlayerId) { } TEST(GridTest, performActionOnObjectWithDifferentPlayerId) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); uint32_t playerId = 1; @@ -338,7 +339,7 @@ TEST(GridTest, performActionOnObjectWithDifferentPlayerId) { } TEST(GridTest, performActionDestinationObjectEmpty) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -388,7 +389,7 @@ TEST(GridTest, performActionDestinationObjectEmpty) { } TEST(GridTest, performActionDestinationObjectOutsideGrid) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -438,7 +439,7 @@ TEST(GridTest, performActionDestinationObjectOutsideGrid) { } TEST(GridTest, performActionCannotBePerformedOnDestinationObject) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -496,7 +497,7 @@ TEST(GridTest, performActionCannotBePerformedOnDestinationObject) { } TEST(GridTest, performActionCanBePerformedOnDestinationObject) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -555,7 +556,7 @@ TEST(GridTest, performActionCanBePerformedOnDestinationObject) { } TEST(GridTest, performActionDelayed) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->enableHistory(true); @@ -631,7 +632,7 @@ TEST(GridTest, performActionDelayed) { } TEST(GridTest, objectCounters) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); std::unordered_map>> objects; @@ -640,7 +641,7 @@ TEST(GridTest, objectCounters) { grid->initObject("cat", {}); for (int32_t p = 0; p < 10; p++) { for (int32_t o = 0; o < 5; o++) { - auto mockObject = std::shared_ptr(new MockObject()); + auto mockObject = std::make_shared(); glm::ivec2 location = {p, o}; EXPECT_CALL(*mockObject, init(Eq(location), _)).Times(1); @@ -680,7 +681,7 @@ TEST(GridTest, objectCounters) { } TEST(GridTest, objectCountersEmpty) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->initObject("object", {}); @@ -690,14 +691,14 @@ TEST(GridTest, objectCountersEmpty) { } TEST(GridTest, runInitialActionsForObject) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); grid->initObject("object", {}); auto mockObjectPtr = mockObject("object"); auto mockDefaultObjectPtr = mockObject("defaultObject"); - auto mockActionPtr1 = std::shared_ptr(new MockAction()); - auto mockActionPtr2 = std::shared_ptr(new MockAction()); + auto mockActionPtr1 = std::make_shared(); + auto mockActionPtr2 = std::make_shared(); EXPECT_CALL(*mockActionPtr1, getSourceObject()) .Times(1) @@ -727,7 +728,7 @@ TEST(GridTest, runInitialActionsForObject) { } TEST(GridTest, intializeObjectWithCollisionDetection) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); std::string actionName1 = "trigger_action_1"; @@ -775,15 +776,15 @@ TEST(GridTest, intializeObjectWithCollisionDetection) { } TEST(GridTest, updateLocationWithCollisionDetection) { - auto mockCollisionDetectorFactoryPtr = std::shared_ptr(new MockCollisionDetectorFactory()); - auto mockCollisionDetectorPtr1 = std::shared_ptr(new MockCollisionDetector()); - auto mockCollisionDetectorPtr2 = std::shared_ptr(new MockCollisionDetector()); - auto mockCollisionDetectorPtr3 = std::shared_ptr(new MockCollisionDetector()); + auto mockCollisionDetectorFactoryPtr = std::make_shared(); + auto mockCollisionDetectorPtr1 = std::make_shared(); + auto mockCollisionDetectorPtr2 = std::make_shared(); + auto mockCollisionDetectorPtr3 = std::make_shared(); EXPECT_CALL(*mockCollisionDetectorFactoryPtr, newCollisionDetector) .WillOnce(Return(mockCollisionDetectorPtr1)); - auto grid = std::shared_ptr(new Grid(mockCollisionDetectorFactoryPtr)); + auto grid = std::make_shared(mockCollisionDetectorFactoryPtr); grid->resetMap(123, 456); std::string actionName1 = "collision_trigger_action"; @@ -824,13 +825,13 @@ TEST(GridTest, updateLocationWithCollisionDetection) { } TEST(GridTest, removeObjectWithCollisionDetection) { - auto mockCollisionDetectorFactoryPtr = std::shared_ptr(new MockCollisionDetectorFactory()); - auto mockCollisionDetectorPtr1 = std::shared_ptr(new MockCollisionDetector()); + auto mockCollisionDetectorFactoryPtr = std::make_shared(); + auto mockCollisionDetectorPtr1 = std::make_shared(); EXPECT_CALL(*mockCollisionDetectorFactoryPtr, newCollisionDetector) .WillOnce(Return(mockCollisionDetectorPtr1)); - auto grid = std::shared_ptr(new Grid(mockCollisionDetectorFactoryPtr)); + auto grid = std::make_shared(mockCollisionDetectorFactoryPtr); grid->resetMap(123, 456); std::string actionName1 = "collision_trigger_action"; @@ -871,8 +872,8 @@ TEST(GridTest, removeObjectWithCollisionDetection) { } TEST(GridTest, performActionTriggeredByCollision) { - auto mockCollisionDetectorFactoryPtr = std::shared_ptr(new MockCollisionDetectorFactory()); - auto mockCollisionDetectorPtr1 = std::shared_ptr(new MockCollisionDetector()); + auto mockCollisionDetectorFactoryPtr = std::make_shared(); + auto mockCollisionDetectorPtr1 = std::make_shared(); EXPECT_CALL(*mockCollisionDetectorFactoryPtr, newCollisionDetector) .WillOnce(Return(mockCollisionDetectorPtr1)); @@ -932,7 +933,7 @@ TEST(GridTest, performActionTriggeredByCollision) { } TEST(GridTest, resetTickCounter) { - auto grid = std::shared_ptr(new Grid()); + auto grid = std::make_shared(); grid->resetMap(123, 456); for (int i = 0; i < 100; i++) { diff --git a/tests/src/Griddly/Core/LevelGenerator/MapReaderTest.cpp b/tests/src/Griddly/Core/LevelGenerator/MapReaderTest.cpp index de6b1faad..994c92f53 100644 --- a/tests/src/Griddly/Core/LevelGenerator/MapReaderTest.cpp +++ b/tests/src/Griddly/Core/LevelGenerator/MapReaderTest.cpp @@ -14,6 +14,7 @@ using ::testing::Eq; using ::testing::Mock; using ::testing::Return; using ::testing::ReturnRef; +using ::testing::ReturnRefOfCopy; namespace griddly { @@ -29,11 +30,11 @@ std::map> mockObjectDefinitions(s } TEST(MapGeneratorTest, testLoadStringWithPlayerObjects) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockWallObject = std::shared_ptr(new MockObject()); - auto mockAvatarObject = std::shared_ptr(new MockObject()); - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockGridPtr = std::make_shared(); + auto mockWallObject = std::make_shared(); + auto mockAvatarObject = std::make_shared(); + auto mockDefaultObject = std::make_shared(); std::shared_ptr mapReader(new MapGenerator(1, mockObjectGeneratorPtr)); std::string wallObjectName = "wall"; @@ -42,7 +43,7 @@ TEST(MapGeneratorTest, testLoadStringWithPlayerObjects) { auto objectDefinitions = mockObjectDefinitions({wallObjectName, avatarObjectName}); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockGridPtr, initObject(Eq(wallObjectName), Eq(std::vector{}))) .Times(1); @@ -98,11 +99,11 @@ TEST(MapGeneratorTest, testLoadStringWithPlayerObjects) { } TEST(MapGeneratorTest, testLoadStringWithPlayerObjectsRandomWhitespace) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockWallObject = std::shared_ptr(new MockObject()); - auto mockAvatarObject = std::shared_ptr(new MockObject()); - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockGridPtr = std::make_shared(); + auto mockWallObject = std::make_shared(); + auto mockAvatarObject = std::make_shared(); + auto mockDefaultObject = std::make_shared(); std::shared_ptr mapReader(new MapGenerator(1, mockObjectGeneratorPtr)); std::string wallObjectName = "wall"; @@ -111,7 +112,7 @@ TEST(MapGeneratorTest, testLoadStringWithPlayerObjectsRandomWhitespace) { auto objectDefinitions = mockObjectDefinitions({wallObjectName, avatarObjectName}); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockGridPtr, initObject(Eq(wallObjectName), Eq(std::vector{}))) .Times(1); @@ -167,11 +168,11 @@ TEST(MapGeneratorTest, testLoadStringWithPlayerObjectsRandomWhitespace) { } TEST(MapGeneratorTest, testLoadStringNoSpaces) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockWallObject = std::shared_ptr(new MockObject()); - auto mockAvatarObject = std::shared_ptr(new MockObject()); - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockGridPtr = std::make_shared(); + auto mockWallObject = std::make_shared(); + auto mockAvatarObject = std::make_shared(); + auto mockDefaultObject = std::make_shared(); std::shared_ptr mapReader(new MapGenerator(1, mockObjectGeneratorPtr)); std::string wallObjectName = "wall"; @@ -180,7 +181,7 @@ TEST(MapGeneratorTest, testLoadStringNoSpaces) { auto objectDefinitions = mockObjectDefinitions({wallObjectName, avatarObjectName}); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockGridPtr, initObject(Eq(wallObjectName), Eq(std::vector{}))) .Times(1); @@ -235,11 +236,11 @@ TEST(MapGeneratorTest, testLoadStringNoSpaces) { } TEST(MapGeneratorTest, testLoadStringNoSpacesWithDots) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockWallObject = std::shared_ptr(new MockObject()); - auto mockAvatarObject = std::shared_ptr(new MockObject()); - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockGridPtr = std::make_shared(); + auto mockWallObject = std::make_shared(); + auto mockAvatarObject = std::make_shared(); + auto mockDefaultObject = std::make_shared(); std::shared_ptr mapReader(new MapGenerator(1, mockObjectGeneratorPtr)); std::string wallObjectName = "wall"; @@ -248,7 +249,7 @@ TEST(MapGeneratorTest, testLoadStringNoSpacesWithDots) { auto objectDefinitions = mockObjectDefinitions({wallObjectName, avatarObjectName}); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockGridPtr, initObject(Eq(wallObjectName), Eq(std::vector{}))) .Times(1); @@ -303,12 +304,12 @@ TEST(MapGeneratorTest, testLoadStringNoSpacesWithDots) { } TEST(MapGeneratorTest, testLoadStringMultipleOccupants) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockWallObject = std::shared_ptr(new MockObject()); - auto mockAvatarObject = std::shared_ptr(new MockObject()); - auto mockDefaultObject = std::shared_ptr(new MockObject()); - auto mockFloorObject = std::shared_ptr(new MockObject()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockGridPtr = std::make_shared(); + auto mockWallObject = std::make_shared(); + auto mockAvatarObject = std::make_shared(); + auto mockDefaultObject = std::make_shared(); + auto mockFloorObject = std::make_shared(); std::shared_ptr mapReader(new MapGenerator(1, mockObjectGeneratorPtr)); @@ -321,7 +322,7 @@ TEST(MapGeneratorTest, testLoadStringMultipleOccupants) { objectDefinitions[floorObjectName]->zIdx = -1; EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockGridPtr, initObject(Eq(wallObjectName), Eq(std::vector{}))) .Times(1); @@ -391,11 +392,11 @@ TEST(MapGeneratorTest, testLoadStringMultipleOccupants) { } TEST(MapGeneratorTest, testLoadStringInitialOrientation) { - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockWallObject = std::shared_ptr(new MockObject()); - auto mockAvatarObject = std::shared_ptr(new MockObject()); - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockObjectGeneratorPtr = std::make_shared(); + auto mockGridPtr = std::make_shared(); + auto mockWallObject = std::make_shared(); + auto mockAvatarObject = std::make_shared(); + auto mockDefaultObject = std::make_shared(); std::shared_ptr mapReader(new MapGenerator(1, mockObjectGeneratorPtr)); @@ -405,7 +406,7 @@ TEST(MapGeneratorTest, testLoadStringInitialOrientation) { auto objectDefinitions = mockObjectDefinitions({wallObjectName, avatarObjectName}); EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()) - .WillRepeatedly(Return(objectDefinitions)); + .WillRepeatedly(ReturnRefOfCopy(objectDefinitions)); EXPECT_CALL(*mockGridPtr, initObject(Eq(wallObjectName), Eq(std::vector{}))) .Times(1); diff --git a/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp b/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp index 898731f07..e871baf08 100644 --- a/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/GDY/Objects/Object.hpp" #include "Griddly/Core/Grid.hpp" #include "Griddly/Core/Observers/ASCIIObserver.hpp" @@ -27,7 +29,7 @@ void runASCIIObserverTest(ObserverConfig observerConfig, bool trackAvatar) { ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(avatarDirection), trackAvatar); - std::shared_ptr asciiObserver = std::shared_ptr(new ASCIIObserver(testEnvironment.mockGridPtr)); + std::shared_ptr asciiObserver = std::make_shared(testEnvironment.mockGridPtr); asciiObserver->init(observerConfig); @@ -56,11 +58,11 @@ void runASCIIObserverRTSTest(ObserverConfig observerConfig, std::vector expectedObservationShape, std::vector expectedObservationStride, uint8_t* expectedData) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverRTSTestData testEnvironment = ObserverRTSTestData(observerConfig); - std::shared_ptr asciiObserver = std::shared_ptr(new ASCIIObserver(testEnvironment.mockGridPtr)); + std::shared_ptr asciiObserver = std::make_shared(testEnvironment.mockGridPtr); asciiObserver->init(observerConfig); diff --git a/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp b/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp index 36297a863..6959746dd 100644 --- a/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp @@ -1,4 +1,6 @@ +#include + #include "Griddly/Core/Observers/BlockObserver.hpp" #include "Mocks/Griddly/Core/MockGrid.hpp" #include "ObserverRTSTestData.hpp" @@ -132,7 +134,7 @@ void runBlockObserverTest(ObserverConfig observerConfig, observerConfig.tileSize = glm::ivec2(20, 20); ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(avatarDirection), trackAvatar); - std::shared_ptr blockObserver = std::shared_ptr(new BlockObserver(testEnvironment.mockGridPtr, resourceConfig, getMockBlockDefinitions(), shaderVariableConfig)); + std::shared_ptr blockObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockBlockDefinitions(), shaderVariableConfig); blockObserver->init(observerConfig); blockObserver->reset(); @@ -169,11 +171,11 @@ void runBlockObserverRTSTest(ObserverConfig observerConfig, observerConfig.tileSize = glm::ivec2(20, 20); observerConfig.highlightPlayers = true; - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverRTSTestData testEnvironment = ObserverRTSTestData(observerConfig); - std::shared_ptr blockObserver = std::shared_ptr(new BlockObserver(testEnvironment.mockGridPtr, resourceConfig, getMockRTSBlockDefinitions(), ShaderVariableConfig())); + std::shared_ptr blockObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockRTSBlockDefinitions(), ShaderVariableConfig()); blockObserver->init(observerConfig); blockObserver->reset(); @@ -516,11 +518,11 @@ TEST(BlockObserverTest, reset) { ObserverConfig observerConfig; observerConfig.tileSize = glm::ivec2(20, 20); - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(Direction::NONE), false); - std::shared_ptr blockObserver = std::shared_ptr(new BlockObserver(testEnvironment.mockGridPtr, resourceConfig, getMockBlockDefinitions(), ShaderVariableConfig())); + std::shared_ptr blockObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockBlockDefinitions(), ShaderVariableConfig()); blockObserver->init(observerConfig); diff --git a/tests/src/Griddly/Core/Observers/IsometricSpriteObserverTest.cpp b/tests/src/Griddly/Core/Observers/IsometricSpriteObserverTest.cpp index a5b087571..d87c0adf7 100644 --- a/tests/src/Griddly/Core/Observers/IsometricSpriteObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/IsometricSpriteObserverTest.cpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/Observers/IsometricSpriteObserver.hpp" #include "Mocks/Griddly/Core/MockGrid.hpp" #include "ObserverRTSTestData.hpp" @@ -76,11 +78,11 @@ void runIsometricSpriteObserverRTSTest(ObserverConfig observerConfig, observerConfig.isoTileDepth = 4; observerConfig.highlightPlayers = true; - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverRTSTestData testEnvironment = ObserverRTSTestData(observerConfig); - std::shared_ptr isometricObserver = std::shared_ptr(new IsometricSpriteObserver(testEnvironment.mockGridPtr, resourceConfig, getMockRTSIsometricSpriteDefinitions(), ShaderVariableConfig())); + std::shared_ptr isometricObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockRTSIsometricSpriteDefinitions(), ShaderVariableConfig()); isometricObserver->init(observerConfig); isometricObserver->reset(); @@ -167,7 +169,7 @@ void runIsometricSpriteObserverTest(ObserverConfig observerConfig, ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(avatarDirection), trackAvatar); - std::shared_ptr isometricObserver = std::shared_ptr(new IsometricSpriteObserver(testEnvironment.mockGridPtr, resourceConfig, getMockIsometricSpriteDefinitions(), shaderVariableConfig)); + std::shared_ptr isometricObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockIsometricSpriteDefinitions(), shaderVariableConfig); isometricObserver->init(observerConfig); isometricObserver->reset(); @@ -518,11 +520,11 @@ TEST(IsometricSpriteObserverTest, reset) { observerConfig.isoTileHeight = 16; observerConfig.isoTileDepth = 4; - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(Direction::NONE), false); - std::shared_ptr isometricObserver = std::shared_ptr(new IsometricSpriteObserver(testEnvironment.mockGridPtr, resourceConfig, getMockIsometricSpriteDefinitions(), ShaderVariableConfig())); + std::shared_ptr isometricObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockIsometricSpriteDefinitions(), ShaderVariableConfig()); isometricObserver->init(observerConfig); diff --git a/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp b/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp index 693b2e8f2..c1907887e 100644 --- a/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp +++ b/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/TestUtils/common.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -108,7 +110,7 @@ class ObserverRTSTestData { {{4, 4}, {{0, walls[15]}}}, }; - mockGridPtr = std::shared_ptr(new MockGrid()); + mockGridPtr = std::make_shared(); EXPECT_CALL(*mockGridPtr, getWidth) .WillRepeatedly(Return(5)); EXPECT_CALL(*mockGridPtr, getHeight) diff --git a/tests/src/Griddly/Core/Observers/ObserverTestData.hpp b/tests/src/Griddly/Core/Observers/ObserverTestData.hpp index e680409b4..b3fad5cbf 100644 --- a/tests/src/Griddly/Core/Observers/ObserverTestData.hpp +++ b/tests/src/Griddly/Core/Observers/ObserverTestData.hpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/TestUtils/common.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -88,7 +90,7 @@ class ObserverTestData { {{4, 4}, {{0, walls[15]}}}, }; - mockGridPtr = std::shared_ptr(new MockGrid()); + mockGridPtr = std::make_shared(); EXPECT_CALL(*mockGridPtr, getWidth) .WillRepeatedly(Return(5)); EXPECT_CALL(*mockGridPtr, getHeight) diff --git a/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp b/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp index 78ee93473..33f9e21f4 100644 --- a/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/Observers/SpriteObserver.hpp" #include "Mocks/Griddly/Core/MockGrid.hpp" #include "ObserverRTSTestData.hpp" @@ -87,11 +89,11 @@ void runSpriteObserverRTSTest(ObserverConfig observerConfig, observerConfig.tileSize = glm::ivec2(50, 50); observerConfig.highlightPlayers = true; - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverRTSTestData testEnvironment = ObserverRTSTestData(observerConfig); - std::shared_ptr spriteObserver = std::shared_ptr(new SpriteObserver(testEnvironment.mockGridPtr, resourceConfig, getMockRTSSpriteDefinitions(), ShaderVariableConfig())); + std::shared_ptr spriteObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockRTSSpriteDefinitions(), ShaderVariableConfig()); spriteObserver->init(observerConfig); spriteObserver->reset(); @@ -190,7 +192,7 @@ void runSpriteObserverTest(ObserverConfig observerConfig, ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(avatarDirection), trackAvatar); - std::shared_ptr spriteObserver = std::shared_ptr(new SpriteObserver(testEnvironment.mockGridPtr, resourceConfig, getMockSpriteDefinitions(), shaderVariableConfig)); + std::shared_ptr spriteObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockSpriteDefinitions(), shaderVariableConfig); spriteObserver->init(observerConfig); spriteObserver->reset(); @@ -537,11 +539,11 @@ TEST(SpriteObserverTest, reset) { ObserverConfig observerConfig; observerConfig.tileSize = glm::ivec2(24, 24); - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(Direction::NONE), false); - std::shared_ptr spriteObserver = std::shared_ptr(new SpriteObserver(testEnvironment.mockGridPtr, resourceConfig, getMockSpriteDefinitions(), ShaderVariableConfig())); + std::shared_ptr spriteObserver = std::make_shared(testEnvironment.mockGridPtr, resourceConfig, getMockSpriteDefinitions(), ShaderVariableConfig()); spriteObserver->init(observerConfig); diff --git a/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp b/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp index 0e4e196d6..24626c979 100644 --- a/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/GDY/Objects/Object.hpp" #include "Griddly/Core/Grid.hpp" #include "Griddly/Core/Observers/VectorObserver.hpp" @@ -27,7 +29,7 @@ void runVectorObserverTest(ObserverConfig observerConfig, bool trackAvatar) { ObserverTestData testEnvironment = ObserverTestData(observerConfig, DiscreteOrientation(avatarDirection), trackAvatar); - std::shared_ptr vectorObserver = std::shared_ptr(new VectorObserver(testEnvironment.mockGridPtr)); + std::shared_ptr vectorObserver = std::make_shared(testEnvironment.mockGridPtr); vectorObserver->init(observerConfig); @@ -56,11 +58,11 @@ void runVectorObserverRTSTest(ObserverConfig observerConfig, std::vector expectedObservationShape, std::vector expectedObservationStride, uint8_t* expectedData) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockGridPtr = std::make_shared(); ObserverRTSTestData testEnvironment = ObserverRTSTestData(observerConfig); - std::shared_ptr vectorObserver = std::shared_ptr(new VectorObserver(testEnvironment.mockGridPtr)); + std::shared_ptr vectorObserver = std::make_shared(testEnvironment.mockGridPtr); vectorObserver->init(observerConfig); diff --git a/tests/src/Griddly/Core/Players/PlayerTest.cpp b/tests/src/Griddly/Core/Players/PlayerTest.cpp index 78287fb10..c1dde9153 100644 --- a/tests/src/Griddly/Core/Players/PlayerTest.cpp +++ b/tests/src/Griddly/Core/Players/PlayerTest.cpp @@ -1,3 +1,5 @@ +#include + #include "Griddly/Core/Players/Player.hpp" #include "Mocks/Griddly/Core/GDY/Actions/MockAction.hpp" #include "Mocks/Griddly/Core/MockGameProcess.hpp" @@ -15,7 +17,7 @@ using ::testing::Return; namespace griddly { TEST(PlayerTest, getIdAndName) { - auto mockGameProcessPtr = std::shared_ptr(new MockGameProcess()); + auto mockGameProcessPtr = std::make_shared(); int playerId = 0; std::string name = "PlayerName"; @@ -28,11 +30,11 @@ TEST(PlayerTest, getIdAndName) { TEST(PlayerTest, performActions) { auto mockActionPtr = std::shared_ptr(new MockAction()); - auto mockGameProcessPtr = std::shared_ptr(new MockGameProcess()); + auto mockGameProcessPtr = std::make_shared(); int playerId = 0; std::string name = "PlayerName"; - auto player = std::shared_ptr(new Player(playerId, name, nullptr)); + auto player = std::make_shared(playerId, name, nullptr); ObserverConfig observerConfig{}; @@ -55,11 +57,11 @@ TEST(PlayerTest, performActions) { TEST(PlayerTest, performActions_terminated) { auto mockActionPtr = std::shared_ptr(new MockAction()); - auto mockGameProcessPtr = std::shared_ptr(new MockGameProcess()); + auto mockGameProcessPtr = std::make_shared(); int playerId = 1; std::string name = "PlayerName"; - auto player = std::shared_ptr(new Player(playerId, name, nullptr)); + auto player = std::make_shared(playerId, name, nullptr); ObserverConfig observerConfig{}; @@ -83,13 +85,13 @@ TEST(PlayerTest, performActions_terminated) { } TEST(PlayerTest, observe) { - auto mockGrid = std::shared_ptr(new MockGrid()); - auto mockObserverPtr = std::shared_ptr(new MockObserver(mockGrid)); + auto mockGrid = std::make_shared(); + auto mockObserverPtr = std::make_shared(mockGrid); auto mockObservationBytesPtr = new uint8_t[10 * 10]{}; int playerId = 0; std::string name = "PlayerName"; - auto player = std::shared_ptr(new Player(playerId, name, mockObserverPtr)); + auto player = std::make_shared(playerId, name, mockObserverPtr); EXPECT_CALL(*mockObserverPtr, update()) .Times(1) diff --git a/tests/src/Griddly/Core/TestUtils/common.hpp b/tests/src/Griddly/Core/TestUtils/common.hpp index 761f4cf25..0b3d7d60b 100644 --- a/tests/src/Griddly/Core/TestUtils/common.hpp +++ b/tests/src/Griddly/Core/TestUtils/common.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include "Mocks/Griddly/Core/GDY/Actions/MockAction.hpp" @@ -18,7 +19,7 @@ using ::testing::ReturnRefOfCopy; namespace griddly { std::shared_ptr static mockObject(std::string objectName = "object", char mapCharacter = '?', uint32_t playerId = 1, uint32_t zidx = 0, const glm::ivec2 location = {0, 0}, DiscreteOrientation orientation = DiscreteOrientation(), std::unordered_set availableActionNames = {}, std::unordered_map> availableVariables = {}) { - auto mockObjectPtr = std::shared_ptr(new MockObject()); + auto mockObjectPtr = std::make_shared(); EXPECT_CALL(*mockObjectPtr, getPlayerId()).WillRepeatedly(Return(playerId)); EXPECT_CALL(*mockObjectPtr, getObjectName()).WillRepeatedly(ReturnRefOfCopy(objectName)); @@ -40,7 +41,7 @@ std::shared_ptr static mockObject(std::string objectName = "object", } std::shared_ptr static mockAction(std::string actionName, std::shared_ptr sourceObject, std::shared_ptr destObject) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); EXPECT_CALL(*mockActionPtr, getActionName()).WillRepeatedly(Return(actionName)); EXPECT_CALL(*mockActionPtr, getSourceObject()).WillRepeatedly(Return(sourceObject)); @@ -53,11 +54,11 @@ std::shared_ptr static mockAction(std::string actionName, std::share } std::shared_ptr static mockAction(std::string actionName, glm::ivec2 sourceLocation, glm::ivec2 destLocation) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); const std::string empty = "_empty"; - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockDefaultObject = std::make_shared(); EXPECT_CALL(*mockDefaultObject, getObjectName()).WillRepeatedly(ReturnRefOfCopy(empty)); EXPECT_CALL(*mockActionPtr, getActionName()).WillRepeatedly(Return(actionName)); @@ -71,11 +72,11 @@ std::shared_ptr static mockAction(std::string actionName, glm::ivec2 } std::shared_ptr static mockAction(std::string actionName, std::shared_ptr sourceObject, glm::ivec2 destLocation) { - auto mockActionPtr = std::shared_ptr(new MockAction()); + auto mockActionPtr = std::make_shared(); const std::string empty = "_empty"; - auto mockDefaultObject = std::shared_ptr(new MockObject()); + auto mockDefaultObject = std::make_shared(); EXPECT_CALL(*mockDefaultObject, getObjectName()).WillRepeatedly(ReturnRefOfCopy(empty)); EXPECT_CALL(*mockActionPtr, getActionName()).WillRepeatedly(Return(actionName)); @@ -89,9 +90,9 @@ std::shared_ptr static mockAction(std::string actionName, std::share } bool static commandArgumentsEqual(BehaviourCommandArguments a, BehaviourCommandArguments b) { - for (auto it = a.begin(); it != a.end(); ++it) { - auto key = it->first; - auto node = it->second; + for (auto& it : a) { + auto key = it.first; + auto node = it.second; if (node.Type() != b[key].Type()) { return false; diff --git a/tests/src/Mocks/Griddly/Core/GDY/Objects/MockObjectGenerator.hpp b/tests/src/Mocks/Griddly/Core/GDY/Objects/MockObjectGenerator.hpp index 305b21955..4fc0f33a2 100644 --- a/tests/src/Mocks/Griddly/Core/GDY/Objects/MockObjectGenerator.hpp +++ b/tests/src/Mocks/Griddly/Core/GDY/Objects/MockObjectGenerator.hpp @@ -13,13 +13,13 @@ class MockObjectGenerator : public ObjectGenerator { MOCK_METHOD(void, defineActionBehaviour, (std::string objectName, ActionBehaviourDefinition behaviourDefinition), ()); MOCK_METHOD(void, addInitialAction, (std::string objectName, std::string actionName, uint32_t actionId, uint32_t delay, bool randomize), ()); - MOCK_METHOD((std::unordered_map), getActionInputDefinitions, (), (const)); + MOCK_METHOD((const std::unordered_map&), getActionInputDefinitions, (), (const)); MOCK_METHOD(std::shared_ptr, newInstance, (std::string objectName, uint32_t playerId, std::shared_ptr grid), ()); MOCK_METHOD(std::shared_ptr, cloneInstance, (std::shared_ptr, std::shared_ptr grid), ()); MOCK_METHOD(std::string&, getObjectNameFromMapChar, (char character), ()); - MOCK_METHOD((std::map>), getObjectDefinitions, (), (const)); + MOCK_METHOD((const std::map>&), getObjectDefinitions, (), (const)); MOCK_METHOD(void, setAvatarObject, (std::string objectName), ()); }; diff --git a/tests/src/Mocks/Griddly/Core/MockCollisionDetector.hpp b/tests/src/Mocks/Griddly/Core/MockCollisionDetector.hpp index 92273248c..eb8941d23 100644 --- a/tests/src/Mocks/Griddly/Core/MockCollisionDetector.hpp +++ b/tests/src/Mocks/Griddly/Core/MockCollisionDetector.hpp @@ -5,7 +5,7 @@ namespace griddly { class MockCollisionDetector : public CollisionDetector { public: MockCollisionDetector() : CollisionDetector(10, 10, 1) {} - ~MockCollisionDetector() {} + ~MockCollisionDetector() override = default; MOCK_METHOD(bool, upsert, (std::shared_ptr object), ()); MOCK_METHOD(bool, remove, (std::shared_ptr object), ()); diff --git a/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp b/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp index 468358dd1..60413f75b 100644 --- a/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp +++ b/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp @@ -5,7 +5,7 @@ namespace griddly { class MockCollisionDetectorFactory : public CollisionDetectorFactory { public: MockCollisionDetectorFactory() : CollisionDetectorFactory() {} - ~MockCollisionDetectorFactory() {} + ~MockCollisionDetectorFactory() override = default; MOCK_METHOD(std::shared_ptr, newCollisionDetector, (uint32_t gridHeight, uint32_t gridWidth, ActionTriggerDefinition actionTriggerDefinition), ()); }; diff --git a/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp b/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp index d62c6ac8c..3e5ff69ed 100644 --- a/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp +++ b/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp @@ -8,7 +8,7 @@ namespace griddly { class MockGameProcess : public GameProcess { public: MockGameProcess() : GameProcess(ObserverType::NONE, nullptr, nullptr) {} - ~MockGameProcess() {} + ~MockGameProcess() override = default; MOCK_METHOD(std::shared_ptr, observe, (uint32_t playerId), (const)); MOCK_METHOD(ActionResult, performActions, (uint32_t playerId, std::vector> actions, bool updateTicks), ()); diff --git a/tests/src/Mocks/Griddly/Core/MockGrid.hpp b/tests/src/Mocks/Griddly/Core/MockGrid.hpp index b56058037..e17321269 100644 --- a/tests/src/Mocks/Griddly/Core/MockGrid.hpp +++ b/tests/src/Mocks/Griddly/Core/MockGrid.hpp @@ -34,7 +34,7 @@ class MockGrid : public Grid { MOCK_METHOD((const std::unordered_map&), getObjectIds, (), (const)); MOCK_METHOD((const std::unordered_map&), getObjectVariableIds, (), (const)); - MOCK_METHOD((const std::vector), getObjectVariableNames, (), (const)); + MOCK_METHOD((const std::vector), getAllObjectVariableNames, (), (const)); MOCK_METHOD((const std::vector), getObjectNames, (), (const)); MOCK_METHOD((const std::map>>&), getGlobalVariables, (), (const)); diff --git a/tests/src/Mocks/Griddly/Core/Observers/MockObserver.hpp b/tests/src/Mocks/Griddly/Core/Observers/MockObserver.hpp index 71f29b54e..6c18e86cc 100644 --- a/tests/src/Mocks/Griddly/Core/Observers/MockObserver.hpp +++ b/tests/src/Mocks/Griddly/Core/Observers/MockObserver.hpp @@ -7,7 +7,7 @@ namespace griddly { class MockObserver : public Observer { public: MockObserver(std::shared_ptr grid) : Observer(grid) {} - ~MockObserver() {} + ~MockObserver() override = default; MOCK_METHOD(void, init, (ObserverConfig observerConfig), ()); MOCK_METHOD(uint8_t*, update, (), ());