├── Includes └── Baba │ ├── Enums │ ├── VerbType.def │ ├── TextType.def │ ├── PropertyType.def │ ├── Action.h │ ├── Game.h │ ├── ObjectType.def │ └── ObjectType.h │ ├── Agent │ ├── Preprocess.h │ ├── Agent.h │ └── RandomAgent.h │ ├── Rules │ ├── Rule.h │ └── Effects.h │ └── Game │ ├── Object.h │ └── Game.h ├── .gitignore ├── Resources └── logo.png ├── Extension ├── pyGUI │ ├── sprite │ │ ├── clear.png │ │ ├── BABA │ │ │ ├── UP.png │ │ │ ├── DOWN.png │ │ │ ├── DOWN0.png │ │ │ ├── DOWN1.png │ │ │ ├── DOWN2.png │ │ │ ├── DOWN3.png │ │ │ ├── LEFT.png │ │ │ ├── LEFT0.png │ │ │ ├── LEFT1.png │ │ │ ├── LEFT2.png │ │ │ ├── LEFT3.png │ │ │ ├── RIGHT.png │ │ │ ├── UP0.png │ │ │ ├── UP1.png │ │ │ ├── UP2.png │ │ │ ├── UP3.png │ │ │ ├── INVALID.png │ │ │ ├── RIGHT0.png │ │ │ ├── RIGHT1.png │ │ │ ├── RIGHT2.png │ │ │ └── RIGHT3.png │ │ ├── FLAG │ │ │ ├── UP.png │ │ │ ├── DOWN.png │ │ │ ├── DOWN0.png │ │ │ ├── DOWN1.png │ │ │ ├── DOWN2.png │ │ │ ├── DOWN3.png │ │ │ ├── LEFT.png │ │ │ ├── LEFT0.png │ │ │ ├── LEFT1.png │ │ │ ├── LEFT2.png │ │ │ ├── LEFT3.png │ │ │ ├── RIGHT.png │ │ │ ├── UP0.png │ │ │ ├── UP1.png │ │ │ ├── UP2.png │ │ │ ├── UP3.png │ │ │ ├── INVALID.png │ │ │ ├── RIGHT0.png │ │ │ ├── RIGHT1.png │ │ │ ├── RIGHT2.png │ │ │ └── RIGHT3.png │ │ ├── WALL │ │ │ ├── UP.png │ │ │ ├── DOWN.png │ │ │ ├── DOWN0.png │ │ │ ├── DOWN1.png │ │ │ ├── DOWN2.png │ │ │ ├── DOWN3.png │ │ │ ├── LEFT.png │ │ │ ├── LEFT0.png │ │ │ ├── LEFT1.png │ │ │ ├── LEFT2.png │ │ │ ├── LEFT3.png │ │ │ ├── RIGHT.png │ │ │ ├── UP0.png │ │ │ ├── UP1.png │ │ │ ├── UP2.png │ │ │ ├── UP3.png │ │ │ ├── INVALID.png │ │ │ ├── RIGHT0.png │ │ │ ├── RIGHT1.png │ │ │ ├── RIGHT2.png │ │ │ └── RIGHT3.png │ │ ├── defeat.png │ │ └── text │ │ │ ├── IS.png │ │ │ ├── BABA.png │ │ │ ├── FLAG.png │ │ │ ├── PUSH.png │ │ │ ├── STOP.png │ │ │ ├── WALL.png │ │ │ ├── WIN.png │ │ │ └── YOU.png │ ├── AI_actions.txt │ ├── gamedata.py │ ├── gamemaker.py │ ├── images.py │ └── GUI.py ├── pyBaba │ ├── Includes │ │ └── pyBaba │ │ │ ├── Agent.h │ │ │ ├── Game.h │ │ │ └── Enums.h │ ├── CMakeLists.txt │ ├── main.cc │ └── Sources │ │ ├── Agent.cc │ │ ├── Game.cc │ │ └── Enums.cc └── BabaAgent │ ├── environment.py │ ├── REINFORCE.py │ └── DQN.py ├── .codacy.yml ├── Scripts ├── travis_build.sh ├── travis_build_docker.sh ├── Dockerfile.cosmic ├── Dockerfile.disco ├── Dockerfile.disco.clang-latest ├── Dockerfile.disco.gcc-latest └── travis_build_codecov.sh ├── UnitTest ├── main.cc ├── CMakeLists.txt ├── Agent │ ├── RandomAgentTests.cc │ └── PreprocessTests.cc ├── Enums │ └── EnumTests.cc ├── Game │ ├── ObjectTests.cc │ └── GameTests.cc └── Rules │ └── EffectTests.cc ├── .lgtm.yml ├── Sources └── Baba │ ├── Agent │ ├── RandomAgent.cc │ └── Preprocess.cc │ ├── CMakeLists.txt │ ├── Rules │ ├── Rule.cc │ └── Effects.cc │ └── Game │ ├── Object.cc │ └── Game.cc ├── .gitmodules ├── codecov.yml ├── Dockerfile ├── CMakeSettings.json ├── appveyor.yml ├── CMakeLists.txt ├── .travis.yml ├── CMake ├── CompileOptions.cmake └── CodeCoverage.cmake ├── .clang-format ├── README.md ├── Documents └── PythonAPI.md └── LICENSE /Includes/Baba/Enums/VerbType.def: -------------------------------------------------------------------------------- 1 | X(IS) 2 | X(HAS) 3 | X(MAKE) 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vs/* 2 | .vscode/* 3 | build/* 4 | **/__pycache__ 5 | **/.idea 6 | *.pyd -------------------------------------------------------------------------------- /Resources/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Resources/logo.png -------------------------------------------------------------------------------- /Includes/Baba/Enums/TextType.def: -------------------------------------------------------------------------------- 1 | X(AND) 2 | X(NOT) 3 | X(ON) 4 | X(LONELY) 5 | X(FACING) 6 | X(NEAR) 7 | -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/clear.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/clear.png -------------------------------------------------------------------------------- /.codacy.yml: -------------------------------------------------------------------------------- 1 | exclude_paths: 2 | - README.md 3 | - Dockerfile 4 | - Libraries/** 5 | - Scripts/** 6 | - Documents/** 7 | -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/UP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/UP.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/UP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/UP.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/UP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/UP.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/defeat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/defeat.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/IS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/IS.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/DOWN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/DOWN.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/DOWN0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/DOWN0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/DOWN1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/DOWN1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/DOWN2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/DOWN2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/DOWN3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/DOWN3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/LEFT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/LEFT.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/LEFT0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/LEFT0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/LEFT1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/LEFT1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/LEFT2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/LEFT2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/LEFT3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/LEFT3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/RIGHT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/RIGHT.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/UP0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/UP0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/UP1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/UP1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/UP2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/UP2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/UP3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/UP3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/DOWN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/DOWN.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/DOWN0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/DOWN0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/DOWN1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/DOWN1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/DOWN2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/DOWN2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/DOWN3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/DOWN3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/LEFT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/LEFT.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/LEFT0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/LEFT0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/LEFT1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/LEFT1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/LEFT2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/LEFT2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/LEFT3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/LEFT3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/RIGHT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/RIGHT.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/UP0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/UP0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/UP1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/UP1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/UP2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/UP2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/UP3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/UP3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/DOWN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/DOWN.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/DOWN0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/DOWN0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/DOWN1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/DOWN1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/DOWN2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/DOWN2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/DOWN3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/DOWN3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/LEFT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/LEFT.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/LEFT0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/LEFT0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/LEFT1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/LEFT1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/LEFT2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/LEFT2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/LEFT3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/LEFT3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/RIGHT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/RIGHT.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/UP0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/UP0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/UP1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/UP1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/UP2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/UP2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/UP3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/UP3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/BABA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/BABA.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/FLAG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/FLAG.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/PUSH.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/PUSH.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/STOP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/STOP.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/WALL.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/WALL.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/WIN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/WIN.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/text/YOU.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/text/YOU.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/INVALID.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/INVALID.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/RIGHT0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/RIGHT0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/RIGHT1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/RIGHT1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/RIGHT2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/RIGHT2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/BABA/RIGHT3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/BABA/RIGHT3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/INVALID.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/INVALID.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/RIGHT0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/RIGHT0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/RIGHT1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/RIGHT1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/RIGHT2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/RIGHT2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/FLAG/RIGHT3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/FLAG/RIGHT3.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/INVALID.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/INVALID.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/RIGHT0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/RIGHT0.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/RIGHT1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/RIGHT1.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/RIGHT2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/RIGHT2.png -------------------------------------------------------------------------------- /Extension/pyGUI/sprite/WALL/RIGHT3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frechele/BabaIsAgent-v0/HEAD/Extension/pyGUI/sprite/WALL/RIGHT3.png -------------------------------------------------------------------------------- /Extension/pyGUI/AI_actions.txt: -------------------------------------------------------------------------------- 1 | Action.RIGHT 2 | Action.RIGHT 3 | Action.RIGHT 4 | Action.RIGHT 5 | Action.RIGHT 6 | Action.RIGHT 7 | Action.RIGHT 8 | Action.DOWN 9 | Action.DOWN -------------------------------------------------------------------------------- /Scripts/travis_build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | export NUM_JOBS=1 6 | 7 | mkdir build 8 | cd build 9 | cmake .. 10 | make 11 | bin/UnitTest 12 | -------------------------------------------------------------------------------- /UnitTest/main.cc: -------------------------------------------------------------------------------- 1 | #include "gtest/gtest.h" 2 | 3 | int main(int argc, char** argv) 4 | { 5 | testing::InitGoogleTest(&argc, argv); 6 | 7 | const int ret = RUN_ALL_TESTS(); 8 | 9 | return ret; 10 | } 11 | -------------------------------------------------------------------------------- /Scripts/travis_build_docker.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | if [ $# -eq 0 ] 6 | then 7 | docker build -t jyp10987/babaisagent . 8 | else 9 | docker build -f $1 -t jyp10987/babaisagent:$2 . 10 | fi 11 | 12 | docker run jyp10987/babaisagent 13 | -------------------------------------------------------------------------------- /Extension/pyBaba/Includes/pyBaba/Agent.h: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #ifndef PYBABA_AGENT_H 4 | #define PYBABA_AGENT_H 5 | 6 | #include 7 | 8 | void buildPreprocess(pybind11::module& m); 9 | void buildAgents(pybind11::module& m); 10 | 11 | #endif // PYBABA_AGENT_H 12 | -------------------------------------------------------------------------------- /Includes/Baba/Enums/PropertyType.def: -------------------------------------------------------------------------------- 1 | X(YOU) 2 | X(STOP) 3 | X(PUSH) 4 | X(PULL) 5 | X(SWAP) 6 | X(TELE) 7 | X(MOVE) 8 | X(FALL) 9 | X(SHIFT) 10 | X(WIN) 11 | X(DEFAT) 12 | X(SINK) 13 | X(HOT) 14 | X(MELT) 15 | X(SHUT) 16 | X(OPEN) 17 | X(WEAK) 18 | X(FLOAT) 19 | X(MORE) 20 | X(UP) 21 | X(DOWN) 22 | X(LEFT) 23 | X(RIGHT) 24 | X(WORD) 25 | -------------------------------------------------------------------------------- /Extension/pyBaba/Includes/pyBaba/Game.h: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #ifndef PYBABA_GAME_H 4 | #define PYBABA_GAME_H 5 | 6 | #include 7 | 8 | void buildObject(pybind11::module& m); 9 | void buildRule(pybind11::module& m); 10 | void buildGame(pybind11::module& m); 11 | 12 | #endif // PYBABA_GAME_H 13 | -------------------------------------------------------------------------------- /Includes/Baba/Enums/Action.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park 2 | 3 | #ifndef BABA_ACTION_H 4 | #define BABA_ACTION_H 5 | 6 | namespace Baba 7 | { 8 | //! 9 | //! \brief Enumerator of action types 10 | //! 11 | enum class Action 12 | { 13 | UP = 0, 14 | DOWN, 15 | LEFT, 16 | RIGHT, 17 | STAY, 18 | COUNT 19 | }; 20 | } // namespace Baba 21 | 22 | #endif // BABA_ACTION_H 23 | -------------------------------------------------------------------------------- /.lgtm.yml: -------------------------------------------------------------------------------- 1 | extraction: 2 | cpp: 3 | configure: 4 | command: 5 | - mkdir _lgtm_build_dir 6 | - cd _lgtm_build_dir 7 | - cmake -DBUILD_GTEST=OFF -DINSTALL_GTEST=OFF .. 8 | index: 9 | build_command: 10 | - cd _lgtm_build_dir 11 | - make 12 | python: 13 | python_setup: 14 | version: 3 15 | 16 | path_classifiers: 17 | library: 18 | - Libraries 19 | -------------------------------------------------------------------------------- /Sources/Baba/Agent/RandomAgent.cc: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park 2 | 3 | #include 4 | 5 | #include 6 | 7 | namespace Baba 8 | { 9 | Action RandomAgent::GetAction([[maybe_unused]]const Game& state) 10 | { 11 | using Random = effolkronium::random_static; 12 | 13 | return static_cast( 14 | Random::get(0, static_cast(Action::COUNT) - 1)); 15 | } 16 | } // namespace Baba 17 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "Libraries/googletest"] 2 | path = Libraries/googletest 3 | url = https://github.com/google/googletest 4 | [submodule "Libraries/spdlog"] 5 | path = Libraries/spdlog 6 | url = https://github.com/gabime/spdlog 7 | [submodule "Libraries/random"] 8 | path = Libraries/random 9 | url = https://github.com/effolkronium/random 10 | [submodule "Libraries/pybind11"] 11 | path = Libraries/pybind11 12 | url = https://github.com/pybind/pybind11 -------------------------------------------------------------------------------- /Extension/pyGUI/gamedata.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import gamemaker 3 | 4 | FPS = 30 5 | BLOCK_SIZE = 24 6 | 7 | # screen 8 | Screen_size = (gamemaker.game.GetWidth() * BLOCK_SIZE, gamemaker.game.GetHeight() * BLOCK_SIZE) 9 | Screen = pygame.display.set_mode((Screen_size[0], Screen_size[1]), pygame.FULLSCREEN) 10 | 11 | # color 12 | COLOR_BLACK = pygame.Color(0, 0, 0) 13 | COLOR_WHITE = pygame.Color(255, 255, 255) 14 | COLOR_BACKGROUND = pygame.Color(177, 216, 216) 15 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | notify: 3 | require_ci_to_pass: yes 4 | 5 | coverage: 6 | precision: 2 7 | round: down 8 | range: 50...100 9 | 10 | status: 11 | project: true 12 | path: true 13 | changes: true 14 | 15 | ignore: 16 | - 'CMake' 17 | - 'Extensions' 18 | - 'Includes' 19 | - 'Libraries' 20 | - 'Scripts' 21 | - 'Resources' 22 | - 'Documents' 23 | 24 | comment: 25 | layout: "header, diff, changes, uncovered" 26 | behavior: default 27 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | LABEL maintainer "JYPark09 " 3 | 4 | RUN apt-get update && apt-get install -y \ 5 | build-essential \ 6 | python3-dev \ 7 | python3-pip \ 8 | python3-venv \ 9 | python3-setuptools \ 10 | cmake \ 11 | --no-install-recommends \ 12 | && rm -rf /var/lib/apt/lists/* 13 | 14 | COPY . /app 15 | 16 | WORKDIR /app/build 17 | RUN cmake .. && \ 18 | make -j "$(nproc)" && \ 19 | make install && \ 20 | bin/UnitTest 21 | 22 | WORKDIR / -------------------------------------------------------------------------------- /UnitTest/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Target name 2 | set(target UnitTest) 3 | 4 | # Sources 5 | file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cc) 6 | 7 | add_executable(${target} ${sources}) 8 | 9 | set_target_properties(${target} 10 | PROPERTIES 11 | ${DEFAULT_PROJECT_OPTIONS} 12 | ) 13 | 14 | target_compile_options(${target} 15 | PRIVATE 16 | ${DEFAULT_COMPILER_OPTIONS} 17 | ) 18 | 19 | target_link_libraries(${target} 20 | PRIVATE 21 | ${DEFAULT_LINKER_OPTIONS} 22 | Baba 23 | gtest 24 | ) -------------------------------------------------------------------------------- /Scripts/Dockerfile.cosmic: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.10 2 | LABEL maintainer "JYPark09 " 3 | 4 | RUN apt-get update && apt-get install -y \ 5 | build-essential \ 6 | python3-dev \ 7 | python3-pip \ 8 | python3-venv \ 9 | python3-setuptools \ 10 | cmake \ 11 | --no-install-recommends \ 12 | && rm -rf /var/lib/apt/lists/* 13 | 14 | COPY . /app 15 | 16 | WORKDIR /app/build 17 | RUN cmake .. && \ 18 | make -j "$(nproc)" && \ 19 | make install && \ 20 | bin/UnitTest 21 | 22 | WORKDIR / -------------------------------------------------------------------------------- /Scripts/Dockerfile.disco: -------------------------------------------------------------------------------- 1 | FROM ubuntu:19.04 2 | LABEL maintainer "JYPark09 " 3 | 4 | RUN apt-get update && apt-get install -y \ 5 | build-essential \ 6 | python3-dev \ 7 | python3-pip \ 8 | python3-venv \ 9 | python3-setuptools \ 10 | cmake \ 11 | --no-install-recommends \ 12 | && rm -rf /var/lib/apt/lists/* 13 | 14 | COPY . /app 15 | 16 | WORKDIR /app/build 17 | RUN cmake .. && \ 18 | make -j "$(nproc)" && \ 19 | make install && \ 20 | bin/UnitTest 21 | 22 | WORKDIR / -------------------------------------------------------------------------------- /Extension/pyBaba/Includes/pyBaba/Enums.h: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #ifndef PYBABA_ENUMS_H 4 | #define PYBABA_ENUMS_H 5 | 6 | #include 7 | 8 | void buildActionEnum(pybind11::module& m); 9 | void buildGameEnum(pybind11::module& m); 10 | void buildObjectTypeEnum(pybind11::module& m); 11 | void buildVerbTypeEnum(pybind11::module& m); 12 | void buildPropertyTypeEnum(pybind11::module& m); 13 | void buildTypeUtilities(pybind11::module& m); 14 | 15 | #endif // PYBABA_ENUMS_H 16 | -------------------------------------------------------------------------------- /Extension/pyBaba/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Target name 2 | set(target pyBaba) 3 | 4 | # Sources 5 | file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cc) 6 | 7 | pybind11_add_module(${target} ${sources}) 8 | 9 | target_include_directories(${target} 10 | PRIVATE 11 | ${CMAKE_CURRENT_SOURCE_DIR}/Includes 12 | ) 13 | 14 | set_target_properties(${target} 15 | PROPERTIES 16 | ${DEFAULT_PROJECT_OPTIONS} 17 | ) 18 | 19 | target_link_libraries(${target} 20 | PRIVATE 21 | Baba 22 | ${DEFAULT_LINKER_OPTIONS} 23 | spdlog::spdlog 24 | ) 25 | -------------------------------------------------------------------------------- /Includes/Baba/Enums/Game.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Hyeonsu Kim 2 | 3 | #ifndef BABA_ENUMS_GAME_H 4 | #define BABA_ENUMS_GAME_H 5 | 6 | namespace Baba 7 | { 8 | //! 9 | //! \brief Enumerator of game results 10 | //! 11 | enum class GameResult 12 | { 13 | INVALID, 14 | WIN, 15 | DEFEAT, 16 | COUNT, 17 | }; 18 | } // namespace Baba 19 | 20 | //! 21 | //! \brief Enumerator of direction 22 | //! 23 | enum class Direction 24 | { 25 | INVALID, 26 | UP, 27 | DOWN, 28 | LEFT, 29 | RIGHT, 30 | }; 31 | 32 | #endif // BABA_ENUMS_GAME_H -------------------------------------------------------------------------------- /Sources/Baba/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Target name 2 | set(target Baba) 3 | 4 | # Sources 5 | file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cc) 6 | 7 | add_library(${target} STATIC ${sources}) 8 | 9 | 10 | target_compile_options(${target} 11 | PRIVATE 12 | 13 | PUBLIC 14 | ${DEFAULT_COMPILE_OPTIONS} 15 | 16 | INTERFACE 17 | ) 18 | 19 | set_target_properties(${target} 20 | PROPERTIES 21 | ${DEFAULT_PROJECT_OPTIONS} 22 | ) 23 | 24 | target_link_libraries(${target} 25 | PRIVATE 26 | 27 | PUBLIC 28 | ${DEFAULT_LINKER_OPTIONS} 29 | 30 | INTERFACE 31 | ) -------------------------------------------------------------------------------- /UnitTest/Agent/RandomAgentTests.cc: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park 2 | 3 | #include "gtest/gtest.h" 4 | 5 | #include 6 | #include 7 | 8 | TEST(RandomAgent, GetAction) 9 | { 10 | using namespace Baba; 11 | 12 | Game game(5, 5); 13 | 14 | RandomAgent agent; 15 | 16 | std::vector actions = { Action::UP, Action::DOWN, Action::LEFT, Action::RIGHT, Action::STAY }; 17 | Action action = agent.GetAction(game); 18 | 19 | EXPECT_NE(std::find(begin(actions), end(actions), action), end(actions)); 20 | } 21 | -------------------------------------------------------------------------------- /Extension/pyGUI/gamemaker.py: -------------------------------------------------------------------------------- 1 | import pyBaba 2 | 3 | game = pyBaba.Game(10, 10) 4 | 5 | def setGame(game_): 6 | game_.Put(2, 1).SetType(pyBaba.ObjectType.BABA).SetText(True) 7 | game_.Put(3, 1).SetType(pyBaba.ObjectType.IS) 8 | game_.Put(4, 1).SetType(pyBaba.ObjectType.YOU) 9 | 10 | game_.Put(1, 4).SetType(pyBaba.ObjectType.BABA) 11 | 12 | game_.Put(7, 5).SetType(pyBaba.ObjectType.FLAG).SetText(True) 13 | game_.Put(7, 6).SetType(pyBaba.ObjectType.IS) 14 | game_.Put(7, 7).SetType(pyBaba.ObjectType.WIN) 15 | 16 | game_.Put(8, 6).SetType(pyBaba.ObjectType.FLAG) 17 | -------------------------------------------------------------------------------- /Extension/pyBaba/main.cc: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | PYBIND11_MODULE(pyBaba, m) 8 | { 9 | m.doc() = R"pbdoc(Baba is you reinforcement learning agent)pbdoc"; 10 | 11 | buildActionEnum(m); 12 | buildGameEnum(m); 13 | buildObjectTypeEnum(m); 14 | buildVerbTypeEnum(m); 15 | buildPropertyTypeEnum(m); 16 | buildTypeUtilities(m); 17 | 18 | buildPreprocess(m); 19 | buildAgents(m); 20 | buildObject(m); 21 | buildRule(m); 22 | buildGame(m); 23 | } 24 | -------------------------------------------------------------------------------- /Scripts/Dockerfile.disco.clang-latest: -------------------------------------------------------------------------------- 1 | FROM ubuntu:19.04 2 | LABEL maintainer "JYPark09 " 3 | 4 | RUN apt-get update && apt-get install -y \ 5 | build-essential \ 6 | python3-dev \ 7 | python3-pip \ 8 | python3-venv \ 9 | python3-setuptools \ 10 | cmake \ 11 | clang-8 \ 12 | --no-install-recommends \ 13 | && rm -rf /var/lib/apt/lists/* 14 | 15 | COPY . /app 16 | 17 | WORKDIR /app/build 18 | RUN cmake .. -DCMAKE_C_COMPILER=clang-8 -DCMAKE_CXX_COMPILER=clang++-8 && \ 19 | make -j "$(nproc)" && \ 20 | make install && \ 21 | bin/UnitTest 22 | 23 | WORKDIR / -------------------------------------------------------------------------------- /Scripts/Dockerfile.disco.gcc-latest: -------------------------------------------------------------------------------- 1 | FROM ubuntu:19.04 2 | LABEL maintainer "JYPark09 " 3 | 4 | RUN apt-get update && apt-get install -y \ 5 | build-essential \ 6 | python3-dev \ 7 | python3-pip \ 8 | python3-venv \ 9 | python3-setuptools \ 10 | cmake \ 11 | gcc-8 \ 12 | g++-8 \ 13 | --no-install-recommends \ 14 | && rm -rf /var/lib/apt/lists/* 15 | 16 | COPY . /app 17 | 18 | WORKDIR /app/build 19 | RUN cmake .. -DCMAKE_C_COMPILER=gcc-8 -DCMAKE_CXX_COMPILER=g++-8 && \ 20 | make -j "$(nproc)" && \ 21 | make install && \ 22 | bin/UnitTest 23 | 24 | WORKDIR / -------------------------------------------------------------------------------- /Includes/Baba/Agent/Preprocess.h: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #ifndef BABA_PREPROCESS_H 4 | #define BABA_PREPROCESS_H 5 | 6 | #include 7 | 8 | #include 9 | 10 | namespace Baba 11 | { 12 | class Preprocess 13 | { 14 | public: 15 | //! Dimension of tensor 16 | static constexpr int TENSOR_DIM = 7; 17 | 18 | //! Convert state to tensor 19 | //! \param game Game state 20 | //! \return Converted tensor 21 | static std::vector StateToTensor(const Game& game); 22 | }; 23 | } // namespace Baba 24 | 25 | #endif // BABA_PREPROCESS_H 26 | -------------------------------------------------------------------------------- /Includes/Baba/Agent/Agent.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park 2 | 3 | #ifndef BABA_AGENT_H 4 | #define BABA_AGENT_H 5 | 6 | #include 7 | #include 8 | 9 | namespace Baba 10 | { 11 | //! 12 | //! \brief Agent interface 13 | //! 14 | class Agent 15 | { 16 | public: 17 | //! Default destructor 18 | virtual ~Agent() = default; 19 | 20 | //! Generate agent's action 21 | //! \param state Current game state 22 | //! \return Generated agent's action 23 | virtual Action GetAction(const Game& state) = 0; 24 | }; 25 | } // namespace Baba 26 | 27 | #endif // BABA_AGENT_H 28 | -------------------------------------------------------------------------------- /Includes/Baba/Agent/RandomAgent.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park 2 | 3 | #ifndef BABA_RANDOM_AGENT_H 4 | #define BABA_RANDOM_AGENT_H 5 | 6 | #include 7 | 8 | namespace Baba 9 | { 10 | //! 11 | //! \brief Agent that plays randomly 12 | //! 13 | class RandomAgent : public Agent 14 | { 15 | public: 16 | //! Default destructor 17 | virtual ~RandomAgent() = default; 18 | 19 | //! Generate agent's action 20 | //! \param state Current game state 21 | //! \return Generated agent's action 22 | Action GetAction(const Game& state) override; 23 | }; 24 | } // namespace Baba 25 | 26 | #endif // BABA_RANDOM_AGENT_H 27 | -------------------------------------------------------------------------------- /Includes/Baba/Enums/ObjectType.def: -------------------------------------------------------------------------------- 1 | X(BABA) 2 | X(KEKE) 3 | X(ME) 4 | 5 | X(ROCK) 6 | X(FLAG) 7 | X(SKULL) 8 | X(JELLY) 9 | X(CRAB) 10 | X(LOVE) 11 | X(PILLAR) 12 | X(KEY) 13 | X(DOOR) 14 | X(ROSE) 15 | X(VIOLET) 16 | X(COG) 17 | X(BELT) 18 | X(BOLT) 19 | X(ROBOT) 20 | X(GHOST) 21 | X(FUNGUS) 22 | X(UFO) 23 | X(ROCKET) 24 | X(HAND) 25 | X(BUG) 26 | X(STAR) 27 | X(MOON) 28 | X(DUST) 29 | X(ANNI) 30 | X(FRUIT) 31 | X(BIRD) 32 | 33 | X(TILE) 34 | X(WALL) 35 | X(GRASS) 36 | X(WATER) 37 | X(LAVA) 38 | X(ICE) 39 | X(ALGAE) 40 | X(HEDGE) 41 | X(PIPE) 42 | X(BOG) 43 | X(FENCE) 44 | X(FOLIAGE) 45 | X(LEAF) 46 | X(TREE) 47 | 48 | X(EMPTY) 49 | X(TEXT) 50 | X(ALL) 51 | X(GROUP) 52 | X(LEVEL) 53 | -------------------------------------------------------------------------------- /UnitTest/Enums/EnumTests.cc: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #include "gtest/gtest.h" 4 | 5 | #include 6 | 7 | TEST(EnumTest, ObjectToProperty) 8 | { 9 | using namespace Baba; 10 | 11 | EXPECT_EQ(ObjectToProperty(ObjectType::BABA), PropertyType::INVALID); 12 | EXPECT_EQ(ObjectToProperty(ObjectType::MELT), PropertyType::MELT); 13 | } 14 | 15 | TEST(EnumTest, PropertyToObject) 16 | { 17 | using namespace Baba; 18 | 19 | EXPECT_EQ(PropertyToObject(PropertyType::MELT), ObjectType::MELT); 20 | EXPECT_EQ(PropertyToObject(PropertyType::HOT), ObjectType::HOT); 21 | 22 | EXPECT_EQ(PropertyToObject(PropertyType::INVALID), ObjectType::INVALID); 23 | } -------------------------------------------------------------------------------- /Extension/pyBaba/Sources/Agent.cc: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #include 4 | 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | namespace py = pybind11; 12 | using namespace Baba; 13 | 14 | void buildPreprocess(py::module& m) 15 | { 16 | py::class_(m, "Preprocess") 17 | .def_static("StateToTensor", &Preprocess::StateToTensor) 18 | .def_readonly_static("TENSOR_DIM", &Preprocess::TENSOR_DIM); 19 | } 20 | 21 | void buildAgents(py::module& m) 22 | { 23 | py::class_ agent(m, "Agent"); 24 | 25 | py::class_(m, "RandomAgent", agent) 26 | .def(py::init<>()) 27 | .def("GetAction", &RandomAgent::GetAction); 28 | } 29 | -------------------------------------------------------------------------------- /CMakeSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "x64-Debug", 5 | "generator": "Ninja", 6 | "configurationType": "Debug", 7 | "inheritEnvironments": [ "msvc_x64_x64" ], 8 | "buildRoot": "${projectDir}\\build\\${name}", 9 | "installRoot": "${projectDir}\\out\\install\\${name}", 10 | "cmakeCommandArgs": "", 11 | "buildCommandArgs": "-v", 12 | "ctestCommandArgs": "", 13 | "variables": [] 14 | }, 15 | { 16 | "name": "x64-Release", 17 | "generator": "Ninja", 18 | "configurationType": "RelWithDebInfo", 19 | "buildRoot": "${projectDir}\\build\\${name}", 20 | "installRoot": "${projectDir}\\out\\install\\${name}", 21 | "cmakeCommandArgs": "", 22 | "buildCommandArgs": "-v", 23 | "ctestCommandArgs": "", 24 | "inheritEnvironments": [ "msvc_x64_x64" ], 25 | "variables": [] 26 | } 27 | ] 28 | } -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 0.4 ({build}) 2 | 3 | skip_branch_with_pr: true 4 | 5 | image: 6 | - Visual Studio 2017 7 | - Visual Studio 2019 8 | 9 | platform: 10 | - x64 11 | 12 | matrix: 13 | fast_finish: true 14 | 15 | configuration: 16 | - Release 17 | 18 | clone_folder: C:\BabaIsAgent 19 | 20 | install: 21 | - git submodule update --init 22 | - ps: | 23 | if ("$env:APPVEYOR_BUILD_WORKER_IMAGE" -eq "Visual Studio 2017") { 24 | $env:CMAKE_GENERATOR = "Visual Studio 15 2017" 25 | } else { 26 | $env:CMAKE_GENERATOR = "Visual Studio 16 2019" 27 | } 28 | $env:PYTHON = "36-x64" 29 | $env:PATH = "C:\Python$env:PYTHON\;C:\Python$env:PYTHON\Scripts;$env:PATH" 30 | 31 | before_build: 32 | - md C:\BabaIsAgent\build 33 | - cd C:\BabaIsAgent\build 34 | - cmake .. -G "%CMAKE_GENERATOR%" -A x64 35 | 36 | build: 37 | project: C:\BabaIsAgent\build\BabaIsAgent.sln 38 | parallel: true 39 | verbosity: normal 40 | 41 | after_build: 42 | - C:\BabaIsAgent\build\bin\Release\UnitTest.exe 43 | -------------------------------------------------------------------------------- /Scripts/travis_build_codecov.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | export TRAVIS_COMPILER=g++-7 6 | export CXX=g++-7 7 | export CXX_FOR_BUILD=g++-7 8 | export CC=gcc-7 9 | export CC_FOR_BUILD=gcc-7 10 | 11 | export NUM_JOBS=1 12 | 13 | sudo apt-get install -yq \ 14 | gcovr \ 15 | ggcov \ 16 | lcov \ 17 | curl \ 18 | 19 | mkdir build 20 | cd build 21 | cmake .. -DCMAKE_BUILD_TYPE=Debug -DBUILD_COVERAGE=ON 22 | make UnitTest 23 | lcov --gcov-tool /usr/bin/gcov-7 -c -i -d UnitTest -o base.info 24 | bin/UnitTest 25 | lcov --gcov-tool /usr/bin/gcov-7 -c -d UnitTest -o test.info 26 | lcov --gcov-tool /usr/bin/gcov-7 -a base.info -a test.info -o coverage.info 27 | lcov --gcov-tool /usr/bin/gcov-7 -r coverage.info '/usr/*' -o coverage.info 28 | lcov --gcov-tool /usr/bin/gcov-7 -r coverage.info '*/Extensions/*' -o coverage.info 29 | lcov --gcov-tool /usr/bin/gcov-7 -r coverage.info '*/Includes/*' -o coverage.info 30 | lcov --gcov-tool /usr/bin/gcov-7 -r coverage.info '*/Libraries/*' -o coverage.info 31 | lcov --gcov-tool /usr/bin/gcov-7 -l coverage.info 32 | 33 | curl -s https://codecov.io/bash > .codecov 34 | chmod +x .codecov 35 | ./.codecov -------------------------------------------------------------------------------- /Includes/Baba/Rules/Rule.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #ifndef BABA_RULE_H 4 | #define BABA_RULE_H 5 | 6 | #include 7 | 8 | namespace Baba 9 | { 10 | //! 11 | //! \brief Rule that conists level 12 | //! 13 | class Rule 14 | { 15 | public: 16 | //! Constructor 17 | Rule(ObjectType target, ObjectType verb, ObjectType effect); 18 | 19 | //! Default destructor 20 | virtual ~Rule() = default; 21 | 22 | //! Returns target object's type 23 | //! \return Target object's type 24 | ObjectType GetTarget() const; 25 | 26 | //! Returns object's verb 27 | //! \return Object's verb 28 | ObjectType GetVerb() const; 29 | 30 | //! Returns effect's type 31 | //! \return Effect's type 32 | ObjectType GetEffect() const; 33 | 34 | //! Returns Rule's id 35 | //! \return Rule's id 36 | std::int64_t GetRuleID() const; 37 | 38 | //! Calculate Rule's id 39 | //! \param target Rule target 40 | //! \param verb Rule verb 41 | //! \param effect Rule effect 42 | //! \return Rule's id 43 | static std::int64_t CalcRuleID(ObjectType target, ObjectType verb, ObjectType effect); 44 | 45 | bool operator<(const Rule& other) const; 46 | 47 | private: 48 | ObjectType target_; 49 | ObjectType verb_; 50 | ObjectType effect_; 51 | }; 52 | } // namespace Baba 53 | 54 | #endif // BABA_RULE_H 55 | -------------------------------------------------------------------------------- /Sources/Baba/Rules/Rule.cc: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #include 4 | #include 5 | 6 | namespace Baba 7 | { 8 | Rule::Rule(ObjectType target, ObjectType verb, ObjectType effect) 9 | : target_(target), verb_(verb), effect_(effect) 10 | { 11 | // Do nothing 12 | } 13 | 14 | ObjectType Rule::GetTarget() const 15 | { 16 | return target_; 17 | } 18 | 19 | ObjectType Rule::GetVerb() const 20 | { 21 | return verb_; 22 | } 23 | 24 | ObjectType Rule::GetEffect() const 25 | { 26 | return effect_; 27 | } 28 | 29 | std::int64_t Rule::GetRuleID() const 30 | { 31 | return Rule::CalcRuleID(target_, verb_, effect_); 32 | } 33 | 34 | std::int64_t Rule::CalcRuleID(ObjectType target, ObjectType verb, 35 | ObjectType effect) 36 | { 37 | std::int64_t ruleID = 0; 38 | 39 | if (IsPropertyType(effect)) 40 | { 41 | ruleID = static_cast( 42 | Effects::GetInstance().GetPriority(ObjectToProperty(effect))); 43 | } 44 | 45 | return (ruleID << 54) | 46 | (static_cast(target) << 36) | 47 | (static_cast(verb) << 18) | 48 | (static_cast(effect) << 0); 49 | } 50 | 51 | bool Rule::operator<(const Rule& other) const 52 | { 53 | return (GetRuleID() < other.GetRuleID()); 54 | } 55 | } // namespace Baba -------------------------------------------------------------------------------- /Sources/Baba/Agent/Preprocess.cc: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #include 4 | 5 | #include 6 | 7 | namespace 8 | { 9 | std::map TensorDimMap = { 10 | { Baba::ObjectType::BABA, 0 }, 11 | { Baba::ObjectType::FLAG, 1 }, 12 | { Baba::ObjectType::IS, 2 }, 13 | { Baba::ObjectType::WIN, 3 }, 14 | { Baba::ObjectType::YOU, 4 } 15 | }; 16 | } 17 | 18 | namespace Baba 19 | { 20 | std::vector Preprocess::StateToTensor(const Game& game) 21 | { 22 | const std::size_t width = game.GetWidth(); 23 | const std::size_t height = game.GetHeight(); 24 | 25 | std::vector tensor(Preprocess::TENSOR_DIM * width * height, 0); 26 | 27 | const auto toIndex = [width, height](std::size_t x, std::size_t y, 28 | std::size_t c) { 29 | return (c * width * height) + (y * width) + x; 30 | }; 31 | 32 | for (std::size_t y = 0; y < height; ++y) 33 | { 34 | for (std::size_t x = 0; x < width; ++x) 35 | { 36 | auto& objs = game.At(x, y); 37 | 38 | if (objs.size() > 0) 39 | { 40 | tensor[toIndex(x, y, TensorDimMap[objs[0]->GetType()])] = 1.f; 41 | tensor[toIndex(x, y, TENSOR_DIM - 2)] = (objs[0]->IsText() ? 1.f : 0.f); 42 | tensor[toIndex(x, y, TENSOR_DIM - 1)] = (game.AtRule(x, y) ? 1.f : 0.f); 43 | } 44 | } 45 | } 46 | 47 | return tensor; 48 | } 49 | } // namespace Baba 50 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # CMake version 2 | cmake_minimum_required(VERSION 3.8.2 FATAL_ERROR) 3 | 4 | # Declare project 5 | project(BabaIsAgent) 6 | 7 | # Set output directories 8 | set(DEFAULT_CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) 9 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin) 10 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) 11 | set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib) 12 | 13 | # External libraries 14 | set(BUILD_GTEST ON CACHE BOOL "" FORCE) 15 | set(BUILD_GMOCK OFF CACHE BOOL "" FORCE) 16 | set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) 17 | add_subdirectory(Libraries/googletest) 18 | 19 | cmake_policy(SET CMP0063 NEW) 20 | set(CMAKE_CXX_VISIBILITY_PRESET hidden) 21 | set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) 22 | 23 | set(BUILD_SHARED_LIBS FALSE) 24 | add_subdirectory(Libraries/spdlog) 25 | add_subdirectory(Libraries/pybind11) 26 | 27 | # Includes 28 | include_directories(Includes) 29 | include_directories(Libraries/pybind11/include) 30 | include_directories(Libraries/random/include) 31 | 32 | # Compile options 33 | include(CMake/CompileOptions.cmake) 34 | 35 | # Project modules 36 | add_subdirectory(Sources/Baba) 37 | add_subdirectory(UnitTest) 38 | 39 | add_subdirectory(Extension/pyBaba) 40 | 41 | # Code coverage 42 | option(BUILD_COVERAGE "Build code coverage" OFF) 43 | if(CMAKE_BUILD_TYPE MATCHES Debug AND CMAKE_COMPILER_IS_GNUCXX AND BUILD_COVERAGE) 44 | include(CMake/CodeCoverage.cmake) 45 | setup_target_for_coverage(${PROJECT_NAME}_coverage UnitTest coverage) 46 | endif() 47 | -------------------------------------------------------------------------------- /UnitTest/Game/ObjectTests.cc: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019 Junyeogn Park 2 | 3 | #include "gtest/gtest.h" 4 | 5 | #include 6 | 7 | TEST(ObjectTest, ID) 8 | { 9 | using namespace Baba; 10 | 11 | Object obj1; 12 | Object obj2; 13 | 14 | EXPECT_EQ(obj2.GetID(), obj1.GetID() + 1); 15 | 16 | EXPECT_EQ(obj1 == obj1, true); 17 | EXPECT_EQ(obj1 != obj2, true); 18 | } 19 | 20 | TEST(ObjectTest, SetType) 21 | { 22 | using namespace Baba; 23 | 24 | Object object; 25 | EXPECT_EQ(object.SetType(ObjectType::BABA).GetType(), ObjectType::BABA); 26 | EXPECT_EQ(object.SetType(ObjectType::KEKE).GetType(), ObjectType::KEKE); 27 | 28 | EXPECT_TRUE(object.SetType(ObjectType::YOU).IsText()); 29 | 30 | EXPECT_ANY_THROW(object.SetType(ObjectType::INVALID)); 31 | } 32 | 33 | TEST(ObjectTest, SetText) 34 | { 35 | using namespace Baba; 36 | 37 | Object object; 38 | object.SetType(ObjectType::BABA); 39 | 40 | EXPECT_FALSE(object.IsText()); 41 | 42 | object.SetText(true); 43 | EXPECT_TRUE(object.IsText()); 44 | 45 | object.SetType(ObjectType::IS); 46 | EXPECT_TRUE(object.IsText()); 47 | 48 | EXPECT_ANY_THROW(object.SetText(false)); 49 | } 50 | 51 | TEST(ObjectTest, Property) 52 | { 53 | using namespace Baba; 54 | 55 | Object object; 56 | object.AddProperty(PropertyType::MELT); 57 | 58 | EXPECT_TRUE(object.HasProperty(PropertyType::MELT)); 59 | 60 | object.RemoveProperty(PropertyType::MELT); 61 | 62 | EXPECT_FALSE(object.HasProperty(PropertyType::MELT)); 63 | } 64 | 65 | TEST(ObjectTest, Destroy) 66 | { 67 | using namespace Baba; 68 | 69 | Object object; 70 | 71 | EXPECT_NO_THROW(object.Destroy()); 72 | EXPECT_EQ(object.IsDestroyed(), true); 73 | EXPECT_ANY_THROW(object.Destroy()); 74 | } 75 | -------------------------------------------------------------------------------- /UnitTest/Agent/PreprocessTests.cc: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #include "gtest/gtest.h" 4 | 5 | #include 6 | 7 | TEST(Preprocess, StateToTensor) 8 | { 9 | using namespace Baba; 10 | 11 | Game game1(10, 10); 12 | 13 | std::vector tensor; 14 | 15 | tensor = Preprocess::StateToTensor(game1); 16 | EXPECT_EQ(tensor.size(), 17 | Preprocess::TENSOR_DIM * game1.GetWidth() * game1.GetHeight()); 18 | 19 | { 20 | Game game2(40, 40); 21 | 22 | tensor = Preprocess::StateToTensor(game2); 23 | EXPECT_EQ(tensor.size(), Preprocess::TENSOR_DIM * game2.GetWidth() * 24 | game2.GetHeight()); 25 | } 26 | 27 | game1.Put(0, 0).SetType(ObjectType::BABA).SetText(true); 28 | game1.Put(1, 0).SetType(ObjectType::IS); 29 | game1.Put(2, 0).SetType(ObjectType::FLAG).SetText(true); 30 | 31 | game1.Put(4, 0).SetType(ObjectType::FLAG); 32 | 33 | const auto toIndex = [](std::size_t x, std::size_t y, 34 | std::size_t c) { 35 | return (c * 100) + (y * 10) + x; 36 | }; 37 | 38 | 39 | game1.Update(); 40 | tensor = Preprocess::StateToTensor(game1); 41 | 42 | EXPECT_FLOAT_EQ(tensor[toIndex(0, 0, 0)], 1.f); 43 | EXPECT_FLOAT_EQ(tensor[toIndex(1, 0, 2)], 1.f); 44 | EXPECT_FLOAT_EQ(tensor[toIndex(2, 0, 1)], 1.f); 45 | 46 | EXPECT_FLOAT_EQ(tensor[toIndex(0, 0, 5)], 1.f); 47 | EXPECT_FLOAT_EQ(tensor[toIndex(1, 0, 5)], 1.f); 48 | EXPECT_FLOAT_EQ(tensor[toIndex(2, 0, 5)], 1.f); 49 | EXPECT_FLOAT_EQ(tensor[toIndex(4, 0, 5)], 0.f); 50 | 51 | EXPECT_FLOAT_EQ(tensor[toIndex(0, 0, 6)], 1.f); 52 | EXPECT_FLOAT_EQ(tensor[toIndex(1, 0, 6)], 1.f); 53 | EXPECT_FLOAT_EQ(tensor[toIndex(2, 0, 6)], 1.f); 54 | EXPECT_FLOAT_EQ(tensor[toIndex(4, 0, 6)], 0.f); 55 | } 56 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | 3 | matrix: 4 | include: 5 | - name: Ubuntu 16.04 + gcc-7 + codecov 6 | os: linux 7 | addons: 8 | apt: 9 | sources: 10 | - ubuntu-toolchain-r-test 11 | packages: 12 | - g++-7 13 | dist: xenial 14 | sudo: required 15 | compiler: gcc 16 | env: 17 | - BUILD_TYPE=Debug 18 | script: 19 | - sh Scripts/travis_build_codecov.sh 20 | 21 | - name: Ubuntu 18.04 + gcc 22 | os: linux 23 | dist: trusty 24 | sudo: required 25 | services: docker 26 | script: 27 | - sh Scripts/travis_build_docker.sh 28 | 29 | - name: Ubuntu 18.10 + gcc 30 | os: linux 31 | dist: trusty 32 | sudo: required 33 | services: docker 34 | script: 35 | - sh Scripts/travis_build_docker.sh Scripts/Dockerfile.cosmic cosmic 36 | 37 | - name: Ubuntu 19.04 + gcc 38 | os: linux 39 | dist: trusty 40 | sudo: required 41 | services: docker 42 | script: 43 | - sh Scripts/travis_build_docker.sh Scripts/Dockerfile.disco disco 44 | 45 | - name: Ubuntu 19.04 + gcc-latest 46 | os: linux 47 | dist: trusty 48 | sudo: required 49 | services: docker 50 | script: 51 | - sh Scripts/travis_build_docker.sh Scripts/Dockerfile.disco.gcc-latest disco-gcc-latest 52 | 53 | - name: Ubuntu 19.04 + clang-latest 54 | os: linux 55 | dist: trusty 56 | services: docker 57 | script: 58 | - sh Scripts/travis_build_docker.sh Scripts/Dockerfile.disco.clang-latest disco-clang-latest 59 | 60 | - name: OS X 10.14 + Xcode 10.2 + clang 61 | os: osx 62 | osx_image: xcode10.2 63 | compiler: clang 64 | script: 65 | - sh Scripts/travis_build.sh 66 | 67 | before_install: 68 | - eval "${MATRIX_EVAL}" -------------------------------------------------------------------------------- /Includes/Baba/Rules/Effects.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #ifndef BABA_EFFECTS_H 4 | #define BABA_EFFECTS_H 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | namespace Baba 15 | { 16 | //! 17 | //! \brief Game effect manager 18 | //! 19 | class Effects 20 | { 21 | private: 22 | //! Constructor 23 | Effects(); 24 | 25 | public: 26 | using EffectFunc = std::function; 27 | 28 | public: 29 | //! Default destructor 30 | ~Effects() = default; 31 | 32 | //! Delete copy constructor 33 | Effects(const Effects&) = delete; 34 | 35 | //! Delete move constructor 36 | Effects(Effects&&) = delete; 37 | 38 | //! Delete copy assignment operator 39 | Effects& operator=(const Effects&) = delete; 40 | 41 | //! Delete move assignment operator 42 | Effects& operator=(Effects&&) = delete; 43 | 44 | static Effects& GetInstance(); 45 | 46 | //! Returns priority of property 47 | //! \param propertyType PropertyType 48 | //! \return priority of propertyType 49 | std::uint8_t GetPriority(PropertyType propertyType) const; 50 | 51 | //! Implement effects of the texts that exist block. 52 | void ImplementBlockEffects(); 53 | 54 | //! Implement effects of the texts that don't exist block. 55 | void ImplementNonBlockEffects(); 56 | 57 | //! Returns map of properties 58 | //! \return Map of properties 59 | const std::map& GetEffects() const; 60 | 61 | private: 62 | void emplace(PropertyType propertyType, EffectFunc func, std::uint8_t priority); 63 | 64 | private: 65 | std::map effects_; 66 | std::map priorities_; 67 | }; 68 | } // namespace Baba 69 | 70 | #endif // BABA_EFFECTS_H 71 | -------------------------------------------------------------------------------- /Extension/pyGUI/images.py: -------------------------------------------------------------------------------- 1 | import pyBaba 2 | import pygame 3 | import gamedata 4 | 5 | BLOCK_SIZE = gamedata.BLOCK_SIZE 6 | screen_size = gamedata.Screen_size 7 | 8 | class ImageLoader: 9 | def __init__(self): 10 | self.obj_images = {pyBaba.ObjectType.BABA: 'BABA', pyBaba.ObjectType.FLAG: 'FLAG', pyBaba.ObjectType.WALL: 'WALL'} 11 | for j in self.obj_images: 12 | temp = [] 13 | for i in pyBaba.Direction.__members__: 14 | temp.append(pygame.transform.scale(pygame.image.load('./sprite/{}/{}.png'.format(self.obj_images[j], i)), 15 | (BLOCK_SIZE, BLOCK_SIZE))) 16 | self.obj_images[j] = temp 17 | 18 | self.text_images = {pyBaba.ObjectType.BABA: 'BABA', pyBaba.ObjectType.FLAG: 'FLAG', pyBaba.ObjectType.IS: 'IS', 19 | pyBaba.ObjectType.YOU: 'YOU', pyBaba.ObjectType.PUSH: 'PUSH', pyBaba.ObjectType.STOP: 'STOP', 20 | pyBaba.ObjectType.WALL: 'WALL', pyBaba.ObjectType.WIN: 'WIN'} 21 | for i in self.text_images: 22 | self.text_images[i] = pygame.transform.scale(pygame.image.load('./sprite/text/{}.png'.format(self.text_images[i])), 23 | (BLOCK_SIZE, BLOCK_SIZE)) 24 | 25 | imageLoader = ImageLoader() 26 | 27 | class clearImage(pygame.sprite.Sprite): 28 | def __init__(self): 29 | pygame.sprite.Sprite.__init__(self) 30 | self.image = pygame.transform.scale(pygame.image.load('./sprite/clear.png'), (screen_size[0]//2, screen_size[1]//4)) 31 | self.rect = self.image.get_rect() 32 | self.rect.center = (screen_size[0]//2, screen_size[1]//2) 33 | def update(self, status): 34 | if status == pyBaba.GameResult.DEFEAT: 35 | self.image = pygame.transform.scale(pygame.image.load('./sprite/defeat.png'), (screen_size[0]//2, screen_size[1]//4)) 36 | 37 | ClearImage = clearImage() 38 | clearImage_Group = pygame.sprite.Group() 39 | clearImage_Group.add(ClearImage) 40 | -------------------------------------------------------------------------------- /Sources/Baba/Game/Object.cc: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | 8 | namespace Baba 9 | { 10 | Object::Object() 11 | { 12 | static int ObjectID = 0; 13 | 14 | objectID_ = ObjectID++; 15 | } 16 | 17 | int Object::GetID() const 18 | { 19 | return objectID_; 20 | } 21 | 22 | bool Object::IsText() const 23 | { 24 | return isText_; 25 | } 26 | 27 | Object& Object::SetText(bool val) 28 | { 29 | if ((IsTextType(type_) || IsVerbType(type_) || IsPropertyType(type_)) && !val) 30 | { 31 | throw std::logic_error("Cannot set to not text"); 32 | } 33 | 34 | isText_ = val; 35 | 36 | return *this; 37 | } 38 | 39 | Object& Object::SetType(ObjectType type) 40 | { 41 | if (type == ObjectType::INVALID) 42 | { 43 | throw std::runtime_error("Invalid object type"); 44 | } 45 | 46 | if (IsTextType(type) || IsVerbType(type) || IsPropertyType(type)) 47 | { 48 | isText_ = true; 49 | } 50 | 51 | type_ = type; 52 | 53 | return *this; 54 | } 55 | 56 | ObjectType Object::GetType() const 57 | { 58 | return type_; 59 | } 60 | 61 | Object& Object::AddProperty(PropertyType type) 62 | { 63 | properties_.emplace(type); 64 | 65 | return *this; 66 | } 67 | 68 | void Object::RemoveProperty(PropertyType type) 69 | { 70 | auto it = std::find(properties_.begin(), properties_.end(), type); 71 | 72 | if (it != properties_.end()) 73 | { 74 | properties_.erase(it); 75 | } 76 | } 77 | 78 | bool Object::HasProperty(PropertyType type) const 79 | { 80 | return std::find(properties_.begin(), properties_.end(), type) != 81 | properties_.end(); 82 | } 83 | 84 | void Object::SetDirection(Direction dir) 85 | { 86 | dir_ = dir; 87 | } 88 | 89 | Direction Object::GetDirection() const 90 | { 91 | return dir_; 92 | } 93 | 94 | void Object::Destroy() 95 | { 96 | if (isDestroyed_) 97 | { 98 | throw std::runtime_error("Already destroyed object"); 99 | } 100 | 101 | isDestroyed_ = true; 102 | } 103 | 104 | bool Object::IsDestroyed() const 105 | { 106 | return isDestroyed_; 107 | } 108 | 109 | bool Object::operator==(const Object& other) const 110 | { 111 | return (objectID_ == other.objectID_); 112 | } 113 | 114 | bool Object::operator!=(const Object& other) const 115 | { 116 | return !(*this == other); 117 | } 118 | } // namespace Baba 119 | -------------------------------------------------------------------------------- /Extension/BabaAgent/environment.py: -------------------------------------------------------------------------------- 1 | import gym 2 | from gym.utils import seeding 3 | from gym.envs.registration import register 4 | import numpy as np 5 | 6 | import pyBaba 7 | 8 | class BabaEnv(gym.Env): 9 | metadata = { 'render.modes' : ['human'] } 10 | 11 | def __init__(self, width, height): 12 | super(BabaEnv, self).__init__() 13 | 14 | self.width = width 15 | self.height = height 16 | 17 | self.action_space = [ 18 | pyBaba.Action.UP, 19 | pyBaba.Action.DOWN, 20 | pyBaba.Action.LEFT, 21 | pyBaba.Action.RIGHT, 22 | pyBaba.Action.STAY 23 | ] 24 | self.action_size = len(self.action_space) 25 | 26 | self.seed() 27 | 28 | def seed(self, seed=None): 29 | self.np_random, seed = seeding.np_random(seed) 30 | 31 | return [seed] 32 | 33 | def reset(self): 34 | self.game = pyBaba.Game(self.width, self.height) 35 | self.done = False 36 | 37 | self.game.Put(2, 1).SetType(pyBaba.ObjectType.BABA).SetText(True) 38 | self.game.Put(3, 1).SetType(pyBaba.ObjectType.IS) 39 | self.game.Put(4, 1).SetType(pyBaba.ObjectType.YOU) 40 | 41 | self.game.Put(1, 4).SetType(pyBaba.ObjectType.BABA) 42 | 43 | self.game.Put(7, 5).SetType(pyBaba.ObjectType.FLAG).SetText(True) 44 | self.game.Put(7, 6).SetType(pyBaba.ObjectType.IS) 45 | self.game.Put(7, 7).SetType(pyBaba.ObjectType.WIN) 46 | 47 | self.game.Put(8, 6).SetType(pyBaba.ObjectType.FLAG) 48 | 49 | return self._get_obs() 50 | 51 | def step(self, action): 52 | self.game.Update(action) 53 | 54 | result = self.game.GetGameResult() 55 | 56 | if result == pyBaba.GameResult.DEFEAT: 57 | self.done = True 58 | reward = -100 59 | elif result == pyBaba.GameResult.WIN: 60 | self.done = True 61 | reward = 200 62 | else: 63 | reward = -0.1 64 | 65 | return self._get_obs(), reward, self.done, {} 66 | 67 | def render(self, mode='human', close=False): 68 | pass 69 | 70 | def _get_obs(self): 71 | return np.array( 72 | pyBaba.Preprocess.StateToTensor(self.game), 73 | dtype=np.float32).reshape(-1, self.height, self.width) 74 | 75 | class BabaEnv10x10(BabaEnv): 76 | def __init__(self): 77 | super(BabaEnv10x10, self).__init__(10, 10) 78 | 79 | register( 80 | id='baba-10x10-v0', 81 | entry_point='environment:BabaEnv10x10', 82 | max_episode_steps=1000, 83 | nondeterministic=True 84 | ) 85 | -------------------------------------------------------------------------------- /Includes/Baba/Game/Object.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #ifndef BABA_OBJECT_H 4 | #define BABA_OBJECT_H 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | namespace Baba 12 | { 13 | //! 14 | //! \brief Object that consists level 15 | //! 16 | class Object 17 | { 18 | public: 19 | //! Pointer vector wrapper 20 | using Arr = std::vector; 21 | 22 | public: 23 | //! Constructor 24 | Object(); 25 | 26 | //! Default destructor 27 | ~Object() = default; 28 | 29 | //! Delete copy constructor 30 | Object(const Object&) = delete; 31 | 32 | //! Delete move constructor 33 | Object(Object&&) = delete; 34 | 35 | //! Delete copy assignment operator 36 | Object& operator=(const Object&) = delete; 37 | 38 | //! Delete move assignment operator 39 | Object& operator=(Object&&) = delete; 40 | 41 | //! Get object id 42 | //! \return ID of object 43 | int GetID() const; 44 | 45 | //! Check object is text 46 | //! \return Whether object is text 47 | bool IsText() const; 48 | //! Set object text status 49 | //! \param value Whether object is text 50 | //! \return This object 51 | Object& SetText(bool value); 52 | 53 | //! Set object type 54 | //! \param type Object type 55 | //! \return This object 56 | Object& SetType(ObjectType type); 57 | //! Get object type 58 | //! \return Object type 59 | ObjectType GetType() const; 60 | 61 | //! Add property to object 62 | //! \param type Property type to add 63 | //! \return This object 64 | Object& AddProperty(PropertyType type); 65 | //! Remove property from object 66 | //! \param type Property type to remove 67 | void RemoveProperty(PropertyType type); 68 | //! Check object has property 69 | //! \param type Property type 70 | //! \return Whether object has property type 71 | bool HasProperty(PropertyType type) const; 72 | 73 | void SetDirection(Direction dir); 74 | Direction GetDirection() const; 75 | 76 | //! Destroy object 77 | void Destroy(); 78 | //! Check object is destroyed 79 | //! \return Whether object is destroyed 80 | bool IsDestroyed() const; 81 | 82 | bool operator==(const Object& other) const; 83 | bool operator!=(const Object& other) const; 84 | 85 | private: 86 | int objectID_; 87 | std::set properties_; 88 | ObjectType type_ = ObjectType::INVALID; 89 | Direction dir_ = Direction::INVALID; 90 | bool isText_ = false; 91 | 92 | bool isDestroyed_ = false; 93 | }; 94 | } // namespace Baba 95 | 96 | #endif // BABA_OBJECT_H 97 | -------------------------------------------------------------------------------- /Extension/pyBaba/Sources/Game.cc: -------------------------------------------------------------------------------- 1 | // Copyrigh(C) 2019 Junyeong Park 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | namespace py = pybind11; 10 | using namespace Baba; 11 | 12 | void buildObject(py::module& m) 13 | { 14 | py::class_(m, "Object") 15 | .def(py::init<>()) 16 | .def("GetID", &Object::GetID) 17 | .def("IsText", &Object::IsText) 18 | .def("SetText", &Object::SetText) 19 | .def("SetType", &Object::SetType) 20 | .def("GetType", &Object::GetType) 21 | .def("AddProperty", &Object::AddProperty) 22 | .def("RemoveProperty", &Object::RemoveProperty) 23 | .def("HasProperty", &Object::HasProperty) 24 | .def("SetDirection", &Object::SetDirection) 25 | .def("GetDirection", &Object::GetDirection) 26 | .def("Destroy", &Object::Destroy) 27 | .def("IsDestroyed", &Object::IsDestroyed); 28 | } 29 | 30 | void buildRule(py::module& m) 31 | { 32 | py::class_(m, "Rule") 33 | .def(py::init()) 34 | .def("GetTarget", &Rule::GetTarget) 35 | .def("GetVerb", &Rule::GetVerb) 36 | .def("GetEffect", &Rule::GetEffect) 37 | .def("GetRuleID", &Rule::GetRuleID) 38 | .def_static("CalculateRuleID", &Rule::CalcRuleID); 39 | } 40 | 41 | void buildGame(py::module& m) 42 | { 43 | py::class_(m, "Game") 44 | .def(py::init()) 45 | .def("GetWidth", &Game::GetWidth) 46 | .def("GetHeight", &Game::GetHeight) 47 | .def("At", &Game::At, py::return_value_policy::reference) 48 | .def("Put", &Game::Put, py::return_value_policy::reference) 49 | .def("DestroyObject", &Game::DestroyObject) 50 | .def("FindObjects", &Game::FindObjects) 51 | .def("FindObjectsByType", &Game::FindObjectsByType) 52 | .def("FindObjectsByProperty", &Game::FindObjectsByProperty) 53 | .def("FindObjectsByPosition", &Game::FindObjectsByPosition) 54 | .def("FilterObjectsByFunction", &Game::FilterObjectByFunction) 55 | .def("GetPositionByObject", &Game::GetPositionByObject) 56 | .def("ValidatePosition", &Game::ValidatePosition) 57 | .def("Update", &Game::Update) 58 | .def("GetGameResult", &Game::GetGameResult) 59 | .def("AddRule", &Game::AddRule) 60 | .def("AddBaseRule", &Game::AddBaseRule) 61 | .def("RemoveRule", &Game::RemoveRule) 62 | .def("TieStuckMoveableObjects", &Game::TieStuckMoveableObjects) 63 | .def("MoveObjects", &Game::MoveObjects) 64 | .def("GetRules", &Game::GetRules) 65 | .def("GetNowAction", &Game::GetNowAction); 66 | } 67 | -------------------------------------------------------------------------------- /Extension/pyBaba/Sources/Enums.cc: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2019 Junyeong Park 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | namespace py = pybind11; 10 | using namespace Baba; 11 | 12 | void buildActionEnum(py::module& m) 13 | { 14 | py::enum_(m, "Action") 15 | .value("UP", Action::UP) 16 | .value("DOWN", Action::DOWN) 17 | .value("LEFT", Action::LEFT) 18 | .value("RIGHT", Action::RIGHT) 19 | .value("STAY", Action::STAY) 20 | .value("COUNT", Action::COUNT) 21 | .export_values(); 22 | } 23 | 24 | void buildGameEnum(py::module& m) 25 | { 26 | py::enum_(m, "GameResult") 27 | .value("INVALID", GameResult::INVALID) 28 | .value("WIN", GameResult::WIN) 29 | .value("DEFEAT", GameResult::DEFEAT) 30 | .value("COUNT", GameResult::COUNT) 31 | .export_values(); 32 | 33 | py::enum_(m, "Direction") 34 | .value("INVALID", Direction::INVALID) 35 | .value("UP", Direction::UP) 36 | .value("DOWN", Direction::DOWN) 37 | .value("LEFT", Direction::LEFT) 38 | .value("RIGHT", Direction::RIGHT) 39 | .export_values(); 40 | } 41 | 42 | void buildObjectTypeEnum(py::module& m) 43 | { 44 | #define X(a) .value(#a, ObjectType::a) 45 | py::enum_(m, "ObjectType") 46 | .value("INVALID", ObjectType::INVALID) 47 | .value("OBJECT_TYPE", ObjectType::OBJECT_TYPE) 48 | #include 49 | .value("VERB_TYPE", ObjectType::VERB_TYPE) 50 | #include 51 | .value("TEXT_TYPE", ObjectType::TEXT_TYPE) 52 | #include 53 | .value("PROP_TYPE", ObjectType::PROP_TYPE) 54 | #include 55 | .value("COUNT", ObjectType::COUNT) 56 | .export_values(); 57 | #undef X 58 | } 59 | 60 | void buildVerbTypeEnum(py::module& m) 61 | { 62 | #define X(a) .value(#a, VerbType::a) 63 | py::enum_(m, "VerbType") 64 | .value("INVALID", VerbType::INVALID) 65 | #include 66 | .value("COUNT", VerbType::COUNT) 67 | .export_values(); 68 | #undef X 69 | } 70 | 71 | void buildPropertyTypeEnum(py::module& m) 72 | { 73 | #define X(a) .value(#a, PropertyType::a) 74 | py::enum_(m, "PropertyType") 75 | .value("INVALID", PropertyType::INVALID) 76 | #include 77 | .value("COUNT", PropertyType::COUNT) 78 | .export_values(); 79 | #undef X 80 | } 81 | 82 | void buildTypeUtilities(py::module& m) 83 | { 84 | m.def("ObjectToProperty", ObjectToProperty); 85 | m.def("PropertyToObject", PropertyToObject); 86 | } 87 | -------------------------------------------------------------------------------- /CMake/CompileOptions.cmake: -------------------------------------------------------------------------------- 1 | # Set warnings as error 2 | option(BABA_WARNINGS_AS_ERRORS "Treat all warnings as error" ON) 3 | if(BABA_WARNINGS_AS_ERRORS) 4 | if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") 5 | set(WARN_AS_ERROR_FLAGS "/WX") 6 | else() 7 | set(WARN_AS_ERROR_FLAGS "-Werror") 8 | endif() 9 | endif() 10 | 11 | # Determine architecture 12 | set(X64 OFF) 13 | if(CMAKE_SIZEOF_VOID_P EQUAL 8) 14 | set(X64 ON) 15 | endif() 16 | 17 | # Project options 18 | set(DEFAULT_PROJECT_OPTIONS 19 | CXX_STANDARD 17 20 | LINKER_LANGUAGE "CXX" 21 | POSITION_INDEPENDENT_CODE ON 22 | ) 23 | 24 | # Compile definitions 25 | set(TOUPPER ${CMAKE_SYSTEM_NAME} SYSTEM_NAME_UPPER) 26 | set(DEFAULT_COMPILE_DEFINITIONS SYSTEM_${SYSTEM_NAME_UPPER}) 27 | 28 | # Compile options 29 | set(DEFAULT_COMPILE_OPTIONS) 30 | 31 | # MSVC compiler options 32 | if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") 33 | set(DEFAULT_COMPILE_DEFINITIONS ${DEFAULT_COMPILE_DEFINITIONS} 34 | _SCL_SECURE_NO_WARNINGS 35 | _CRT_SECURE_NO_WARNINGS 36 | ) 37 | 38 | string(REGEX REPLACE "/W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") 39 | 40 | set(DEFAULT_COMPILE_OPTIONS ${DEFAULT_COMPILE_OPTIONS} 41 | /MP 42 | /W4 43 | ${WARN_AS_ERROR_FLAGS} 44 | 45 | /wd4819 46 | 47 | $<$: 48 | /Gw 49 | /Gs- 50 | /GL 51 | /GF 52 | > 53 | ) 54 | endif() 55 | 56 | # GCC and Clang compiler options 57 | if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") 58 | set(DEFAULT_COMPILE_OPTIONS ${DEFAULT_COMPILE_OPTIONS} 59 | -Wall 60 | -Wno-missing-braces 61 | -Wno-register 62 | -Wno-error=register 63 | 64 | ${WARN_AS_ERROR_FLAGS} 65 | -std=c++1z 66 | ) 67 | endif() 68 | 69 | if(CMAKE_CXX_COMPILER_ID MATCHES "GNU") 70 | set(DEFAULT_COMPILE_OPTIONS ${DEFAULT_COMPILE_OPTIONS} 71 | -Wno-int-in-bool-context 72 | ) 73 | endif() 74 | 75 | if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") 76 | set(DEFAULT_COMPILE_OPTIONS ${DEFAULT_COMPILE_OPTIONS} 77 | -fsized-deallocation 78 | ) 79 | endif() 80 | 81 | # Linker options 82 | set(DEFAULT_LINKER_OPTIONS) 83 | 84 | if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_SYSTEM_NAME MATCHES "Linux") 85 | set(DEFAULT_LINKER_OPTIONS -pthread -lstdc++fs) 86 | endif() 87 | 88 | # Code coverage 89 | if(CMAKE_BUILD_TYPE MATCHES Debug AND (CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")) 90 | set(DEFAULT_COMPILE_OPTIONS ${DEFAULT_COMPILE_OPTIONS} 91 | -g 92 | -O0 93 | -fprofile-arcs 94 | -ftest-coverage 95 | ) 96 | 97 | set(DEFAULT_LINKER_OPTIONS ${DEFAULT_LINKER_OPTIONS} 98 | -fprofile-arcs 99 | -ftest-coverage 100 | ) 101 | endif() -------------------------------------------------------------------------------- /Extension/pyGUI/GUI.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | import pyBaba 4 | import gamemaker 5 | import images 6 | import gamedata 7 | 8 | # testgame 9 | game = gamemaker.game 10 | gamemaker.setGame(game) 11 | 12 | # init 13 | pygame.init() 14 | pygame.font.init() 15 | FPS = gamedata.FPS 16 | BLOCK_SIZE = gamedata.BLOCK_SIZE 17 | 18 | clock = pygame.time.Clock() 19 | 20 | # AI actions 21 | action_dic = {"Action.RIGHT": pyBaba.Action.RIGHT, "Action.LEFT": pyBaba.Action.LEFT, 22 | "Action.UP": pyBaba.Action.UP, "Action.DOWN": pyBaba.Action.DOWN} 23 | f = open("./AI_actions.txt", 'r') 24 | actions = f.read().splitlines() 25 | f.close() 26 | 27 | # screen 28 | Screen_size = gamedata.Screen_size 29 | Screen = gamedata.Screen 30 | 31 | 32 | # color 33 | COLOR_BLACK = gamedata.COLOR_BLACK 34 | COLOR_WHITE = gamedata.COLOR_WHITE 35 | COLOR_BACKGROUND = gamedata.COLOR_BACKGROUND 36 | 37 | 38 | # image 39 | obj_images = images.imageLoader.obj_images 40 | text_images = images.imageLoader.text_images 41 | 42 | 43 | def IsObject(x_position, y_position): 44 | object_list = game.At(x_position, y_position) 45 | for obj in object_list: 46 | if obj.IsText(): 47 | obj_image = text_images[obj.GetType()] 48 | else: 49 | obj_image = obj_images[obj.GetType()][int(obj.GetDirection())] 50 | obj_rect = obj_image.get_rect() 51 | obj_rect.topleft = (game.GetPositionByObject(obj)[0] * BLOCK_SIZE, 52 | game.GetPositionByObject(obj)[1] * BLOCK_SIZE) 53 | Screen.blit(obj_image, obj_rect) 54 | 55 | 56 | def Check(): 57 | for y_position in range(game.GetHeight()): 58 | for x_position in range(game.GetWidth()): 59 | IsObject(x_position, y_position) 60 | 61 | # loop 62 | gameover = False 63 | timer = 0 64 | pygame.time.set_timer(pygame.USEREVENT, 200) 65 | while True: 66 | if gameover: 67 | for event in pygame.event.get(): 68 | if event.type == pygame.KEYDOWN: 69 | if event.key == pygame.K_ESCAPE: 70 | pygame.quit() 71 | sys.exit() 72 | if game.GetGameResult() == pyBaba.GameResult.DEFEAT: 73 | images.clearImage_Group.update(pyBaba.GameResult.DEFEAT) 74 | images.clearImage_Group.draw(Screen) 75 | else: 76 | images.clearImage_Group.draw(Screen) 77 | pygame.display.flip() 78 | continue 79 | 80 | for event in pygame.event.get(): 81 | if event.type == pygame.USEREVENT: 82 | game.Update(action_dic[actions[timer]]) 83 | timer += 1 84 | if event.type == pygame.KEYDOWN: 85 | if event.key == pygame.K_ESCAPE: 86 | pygame.quit() 87 | sys.exit() 88 | 89 | # WIN 90 | if game.GetGameResult() == pyBaba.GameResult.WIN or game.GetGameResult() == pyBaba.GameResult.DEFEAT: 91 | gameover = True 92 | 93 | # draw 94 | Screen.fill(COLOR_BACKGROUND) 95 | Check() 96 | pygame.display.flip() 97 | 98 | clock.tick(FPS) 99 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | # BasedOnStyle: Google 4 | AccessModifierOffset: -3 5 | AlignAfterOpenBracket: Align 6 | AlignConsecutiveAssignments: false 7 | AlignConsecutiveDeclarations: false 8 | AlignEscapedNewlinesLeft: true 9 | AlignOperands: true 10 | AlignTrailingComments: true 11 | AllowAllParametersOfDeclarationOnNextLine: true 12 | AllowShortBlocksOnASingleLine: false 13 | AllowShortCaseLabelsOnASingleLine: false 14 | AllowShortFunctionsOnASingleLine: false 15 | AllowShortIfStatementsOnASingleLine: false 16 | AllowShortLoopsOnASingleLine: false 17 | AlwaysBreakAfterDefinitionReturnType: None 18 | AlwaysBreakAfterReturnType: None 19 | AlwaysBreakBeforeMultilineStrings: true 20 | AlwaysBreakTemplateDeclarations: true 21 | BinPackArguments: true 22 | BinPackParameters: true 23 | BreakBeforeBraces: Custom 24 | BraceWrapping: 25 | AfterClass: true 26 | AfterControlStatement: true 27 | AfterEnum: true 28 | AfterFunction: true 29 | AfterNamespace: true 30 | AfterObjCDeclaration: true 31 | AfterStruct: true 32 | AfterUnion: true 33 | BeforeCatch: true 34 | BeforeElse: true 35 | IndentBraces: false 36 | BreakBeforeBinaryOperators: None 37 | BreakBeforeTernaryOperators: true 38 | BreakConstructorInitializersBeforeComma: false 39 | BreakAfterJavaFieldAnnotations: false 40 | BreakStringLiterals: true 41 | ColumnLimit: 80 42 | CommentPragmas: '^ IWYU pragma:' 43 | ConstructorInitializerAllOnOneLineOrOnePerLine: true 44 | ConstructorInitializerIndentWidth: 4 45 | ContinuationIndentWidth: 4 46 | Cpp11BracedListStyle: false 47 | DerivePointerAlignment: true 48 | DisableFormat: false 49 | ExperimentalAutoDetectBinPacking: false 50 | ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] 51 | IncludeCategories: 52 | - Regex: '^<.*\.h>' 53 | Priority: 1 54 | - Regex: '^<.*' 55 | Priority: 2 56 | - Regex: '.*' 57 | Priority: 3 58 | IncludeIsMainRegex: '([-_](test|unittest))?$' 59 | IndentCaseLabels: true 60 | IndentWidth: 4 61 | IndentWrappedFunctionNames: false 62 | JavaScriptQuotes: Leave 63 | JavaScriptWrapImports: true 64 | KeepEmptyLinesAtTheStartOfBlocks: false 65 | MacroBlockBegin: '' 66 | MacroBlockEnd: '' 67 | MaxEmptyLinesToKeep: 1 68 | NamespaceIndentation: None 69 | ObjCBlockIndentWidth: 2 70 | ObjCSpaceAfterProperty: false 71 | ObjCSpaceBeforeProtocolList: false 72 | PenaltyBreakBeforeFirstCallParameter: 1 73 | PenaltyBreakComment: 300 74 | PenaltyBreakFirstLessLess: 120 75 | PenaltyBreakString: 1000 76 | PenaltyExcessCharacter: 1000000 77 | PenaltyReturnTypeOnItsOwnLine: 200 78 | PointerAlignment: Left 79 | ReflowComments: true 80 | SortIncludes: true 81 | SpaceAfterCStyleCast: false 82 | SpaceBeforeAssignmentOperators: true 83 | SpaceBeforeParens: ControlStatements 84 | SpaceInEmptyParentheses: false 85 | SpacesBeforeTrailingComments: 2 86 | SpacesInAngles: false 87 | SpacesInContainerLiterals: true 88 | SpacesInCStyleCastParentheses: false 89 | SpacesInParentheses: false 90 | SpacesInSquareBrackets: false 91 | Standard: Auto 92 | TabWidth: 4 93 | UseTab: Never -------------------------------------------------------------------------------- /Includes/Baba/Enums/ObjectType.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #ifndef BABA_OBJECT_TYPE_H 4 | #define BABA_OBJECT_TYPE_H 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | namespace Baba 11 | { 12 | //! 13 | //! \brief Enumerator of object types 14 | //! 15 | enum class ObjectType 16 | { 17 | INVALID, 18 | #define X(a) a, 19 | OBJECT_TYPE, 20 | #include "ObjectType.def" 21 | VERB_TYPE, 22 | #include "VerbType.def" 23 | TEXT_TYPE, 24 | #include "TextType.def" 25 | PROP_TYPE, 26 | #include "PropertyType.def" 27 | #undef X 28 | COUNT, 29 | }; 30 | 31 | //! 32 | //! \brief Enumerator of verb types 33 | //! 34 | enum class VerbType 35 | { 36 | INVALID, 37 | #define X(a) a, 38 | #include "VerbType.def" 39 | #undef X 40 | COUNT, 41 | }; 42 | 43 | //! 44 | //! \brief Enumerator of property types 45 | //! 46 | enum class PropertyType 47 | { 48 | INVALID, 49 | #define X(a) a, 50 | #include "PropertyType.def" 51 | #undef X 52 | COUNT, 53 | }; 54 | 55 | //! Check \p type is object type 56 | //! \param type Object type 57 | //! \return Whether type is object type 58 | constexpr bool IsObjectType(ObjectType type) 59 | { 60 | return (type > ObjectType::OBJECT_TYPE && type < ObjectType::VERB_TYPE); 61 | } 62 | 63 | //! Check \p type is verb type 64 | //! \param type Object type 65 | //! \return Whether type is verb type 66 | constexpr bool IsVerbType(ObjectType type) 67 | { 68 | return (type > ObjectType::VERB_TYPE && type < ObjectType::TEXT_TYPE); 69 | } 70 | 71 | //! Check \p type is text type 72 | //! \param type Object type 73 | //! \return Whether type is text type 74 | constexpr bool IsTextType(ObjectType type) 75 | { 76 | return (type > ObjectType::TEXT_TYPE && type < ObjectType::PROP_TYPE); 77 | } 78 | 79 | //! Check \p type is property type 80 | //! \param type Object tyep 81 | //! \return Whether type is property type 82 | constexpr bool IsPropertyType(ObjectType type) 83 | { 84 | return (type > ObjectType::PROP_TYPE && type < ObjectType::COUNT); 85 | } 86 | 87 | //! Convert object type to property type 88 | //! \param type Object type 89 | //! \return Converted type 90 | constexpr PropertyType ObjectToProperty(ObjectType type) 91 | { 92 | if (IsPropertyType(type)) 93 | { 94 | return static_cast( 95 | static_cast(type) - 96 | static_cast(ObjectType::PROP_TYPE)); 97 | } 98 | else 99 | { 100 | return PropertyType::INVALID; 101 | } 102 | } 103 | 104 | //! Convert property type toobject tyep 105 | //! \param type Property type 106 | //! \return Converted type 107 | constexpr ObjectType PropertyToObject(PropertyType type) 108 | { 109 | return (type <= PropertyType::INVALID || type >= PropertyType::COUNT) 110 | ? ObjectType::INVALID 111 | : static_cast( 112 | static_cast(type) + 113 | static_cast(ObjectType::PROP_TYPE)); 114 | } 115 | } // namespace Baba 116 | 117 | #endif // BABA_OBJECT_TYPE_H 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Baba Is Agent 2 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://github.com/JYPark09/BabaIsAgent/blob/master/LICENSE) 3 | [![Build Status](https://travis-ci.com/JYPark09/BabaIsAgent.svg?branch=master)](https://travis-ci.com/JYPark09/BabaIsAgent) 4 | [![Build status](https://ci.appveyor.com/api/projects/status/x3cs2pyati2t6a2s/branch/master?svg=true)](https://ci.appveyor.com/project/JYPark09/babaisyou/branch/master) 5 | [![codecov](https://codecov.io/gh/JYPark09/BabaIsAgent/branch/master/graph/badge.svg)](https://codecov.io/gh/JYPark09/BabaIsAgent) 6 | [![CodeFactor](https://www.codefactor.io/repository/github/jypark09/babaisagent/badge)](https://www.codefactor.io/repository/github/jypark09/babaisagent) 7 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/615531ce885443ec981e7aee0b6388de)](https://www.codacy.com/app/JYPark09/BabaIsAgent?utm_source=github.com&utm_medium=referral&utm_content=JYPark09/BabaIsAgent&utm_campaign=Badge_Grade) 8 | [![Total alerts](https://img.shields.io/lgtm/alerts/g/JYPark09/BabaIsAgent.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/JYPark09/BabaIsAgent/alerts/) 9 | [![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/JYPark09/BabaIsAgent.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/JYPark09/BabaIsAgent/context:cpp) 10 | ![Logo](Resources/logo.png) 11 | Baba Is Agent is [Baba Is You](https://store.steampowered.com/app/736260/Baba_Is_You/) simulation for Reinforcement Learning. 12 | This project is a research project at [OOPArts](https://www.facebook.com/OOPArts-%EC%98%A4%ED%8C%8C%EC%B8%A0-1232318310248618/). 13 | 14 | ## Key Features 15 | - C++17 based Baba Is You library 16 | - GUI simulator program 17 | 18 | ## To-do Features 19 | - [x] Game simulation 20 | - [ ] GUI program 21 | - [ ] Level solver 22 | 23 | ## Quick Start 24 | First, clone the repository: 25 | ``` 26 | git clone --recursive https://github.com/JYPark09/BabaIsAgent 27 | cd BabaIsAgent 28 | ``` 29 | 30 | Second, build project. 31 | 32 | ### Linux, macOS, Windows Subsystem for Linux(WSL) 33 | ``` 34 | mkdir build 35 | cd build 36 | cmake .. 37 | make 38 | ``` 39 | 40 | ### Windows 41 | ``` 42 | mkdir build 43 | cd build 44 | cmake .. -G "Visual Studio 16 2019" -A x64 45 | MSBuild BabaIsAgent.sln /p:Configuration=Release 46 | ``` 47 | 48 | ## Thanks To 49 | - [Chris Ohk](https://github.com/utilForever) 50 | 51 | ## Contact 52 | You can contact us using the following means. 53 | - e-mail: jyp10987 at gmail.com 54 | - [Facebook](https://www.facebook.com/OOPArts-%EC%98%A4%ED%8C%8C%EC%B8%A0-1232318310248618/) 55 | - github issue 56 | 57 | ## License 58 | This project is based on [GNU General Public License version 3](https://opensource.org/licenses/GPL-3.0). 59 | 60 | Copyright(C) 2019 Baba Is Agent Team 61 | - [Junyeong Park](https://github.com/JYPark09) 62 | - [Hyeonsu Kim](https://github.com/git-rla) 63 | - [Taehwan Yu](https://github.com/PhoenixPlanet) 64 | - [Inyeong Park](https://github.com/clwmrndl92) 65 | - [Sooyeon Kim](https://github.com/estela19) 66 | - [Gyeonguk Chae](https://github.com/ShyRoute) 67 | - [Sangyun Chung](https://github.com/starga2er) 68 | - [Seokwon Moon](https://github.com/you4rin) -------------------------------------------------------------------------------- /Extension/BabaAgent/REINFORCE.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn, optim 3 | import torch.nn.functional as F 4 | from torch.distributions import Categorical 5 | 6 | import copy 7 | 8 | from environment import BabaEnv10x10 9 | import pyBaba 10 | 11 | from tensorboardX import SummaryWriter 12 | 13 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 14 | env = BabaEnv10x10() 15 | 16 | class Network(nn.Module): 17 | def __init__(self): 18 | super(Network, self).__init__() 19 | 20 | self.conv1 = nn.Conv2d(pyBaba.Preprocess.TENSOR_DIM, 128, 3, padding=1) 21 | self.conv2 = nn.Conv2d(128, 128, 3, padding=1) 22 | self.conv3 = nn.Conv2d(128, 128, 3, padding=1) 23 | self.conv4 = nn.Conv2d(128, 128, 3, padding=1) 24 | self.conv5 = nn.Conv2d(128, 1, 1, padding=0) 25 | self.fc = nn.Linear(100, 5) 26 | 27 | self.log_probs = [] 28 | self.rewards = [] 29 | 30 | def forward(self, x): 31 | x = F.relu(self.conv1(x)) 32 | x = F.relu(self.conv2(x)) 33 | x = F.relu(self.conv3(x)) 34 | x = F.relu(self.conv4(x)) 35 | x = F.relu(self.conv5(x)) 36 | 37 | x = x.view(x.data.size(0), -1) 38 | x = self.fc(x) 39 | 40 | return F.softmax(x, dim=1) 41 | 42 | net = Network().to(device) 43 | 44 | opt = optim.Adam(net.parameters(), lr=1e-3) 45 | 46 | def get_action(state): 47 | state = torch.tensor(state).to(device) 48 | 49 | policy = net(state) 50 | 51 | m = Categorical(policy) 52 | action = m.sample() 53 | 54 | net.log_probs.append(m.log_prob(action)) 55 | return env.action_space[action.item()] 56 | 57 | def train(): 58 | R = 0 59 | 60 | loss = [] 61 | returns = [] 62 | 63 | for r in net.rewards[::-1]: 64 | R = r + 0.99 * R 65 | returns.insert(0, R) 66 | 67 | returns = torch.tensor(returns) 68 | returns = (returns - returns.mean()) / (returns.std() + 1e-5) 69 | 70 | for prob, R in zip(net.log_probs, returns): 71 | loss.append(-prob * R) 72 | 73 | opt.zero_grad() 74 | 75 | loss = torch.cat(loss).sum() 76 | loss.backward() 77 | 78 | opt.step() 79 | 80 | del net.log_probs[:] 81 | del net.rewards[:] 82 | 83 | if __name__ == '__main__': 84 | writer = SummaryWriter() 85 | 86 | global_step = 0 87 | 88 | for e in range(10000): 89 | score = 0 90 | 91 | state = env.reset().reshape(1, -1, 10, 10) 92 | 93 | step = 0 94 | while step < 3000: 95 | global_step += 1 96 | 97 | action = get_action(state) 98 | next_state, reward, done, _ = env.step(action) 99 | next_state = next_state.reshape(1, -1, 10, 10) 100 | 101 | net.rewards.append(reward) 102 | score += reward 103 | state = copy.deepcopy(next_state) 104 | 105 | step += 1 106 | 107 | if env.done: 108 | break 109 | 110 | train() 111 | 112 | writer.add_scalar('Reward', score, e) 113 | writer.add_scalar('Step', step, e) 114 | 115 | print(f'Episode {e}: score: {score:.3f} time_step: {global_step} step: {step}') 116 | -------------------------------------------------------------------------------- /Sources/Baba/Rules/Effects.cc: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Hyeonsu Kim 2 | 3 | #include 4 | #include 5 | 6 | namespace Baba 7 | { 8 | Effects& Effects::GetInstance() 9 | { 10 | static Effects instance; 11 | return instance; 12 | } 13 | 14 | std::uint8_t Effects::GetPriority(PropertyType propertyType) const 15 | { 16 | return priorities_.at(propertyType); 17 | } 18 | 19 | void Effects::emplace(PropertyType propertyType, EffectFunc func, std::uint8_t priority) 20 | { 21 | effects_.emplace(propertyType, func); 22 | priorities_.emplace(propertyType, priority); 23 | } 24 | 25 | void Effects::ImplementBlockEffects() 26 | { 27 | // ---------------------------------------------------------------------- 28 | // DECLARE 29 | // Change target's type 30 | // ---------------------------------------------------------------------- 31 | /*auto DeclareEffect = [](Game& game, Object& target, const Rule& rule) { 32 | (void)game; 33 | (void)rule; 34 | 35 | target.SetType(rule.GetEffect()); 36 | }; 37 | effects_.emplace(PropertyType::DECLARE, DeclareEffect);*/ 38 | } 39 | 40 | void Effects::ImplementNonBlockEffects() 41 | { 42 | // ---------------------------------------------------------------------- 43 | // YOU 44 | // The player can control this object 45 | // ---------------------------------------------------------------------- 46 | auto YouEffect = [](Game& game, Object& target) { 47 | Direction dir; 48 | 49 | switch (game.GetNowAction()) 50 | { 51 | case Action::UP: 52 | dir = Direction::UP; 53 | break; 54 | case Action::DOWN: 55 | dir = Direction::DOWN; 56 | break; 57 | case Action::LEFT: 58 | dir = Direction::LEFT; 59 | break; 60 | case Action::RIGHT: 61 | dir = Direction::RIGHT; 62 | break; 63 | default: 64 | return; 65 | } 66 | 67 | auto objs = game.TieStuckMoveableObjects(target, dir); 68 | game.MoveObjects(objs, dir); 69 | }; 70 | emplace(PropertyType::YOU, YouEffect, 100); 71 | 72 | // ---------------------------------------------------------------------- 73 | // WIN 74 | // If a YOU object contacts this object, the level is won. 75 | // ---------------------------------------------------------------------- 76 | auto WinEffect = [](Game& game, Object& target) { 77 | (void)game; 78 | (void)target; 79 | }; 80 | emplace(PropertyType::WIN, WinEffect, 101); 81 | 82 | auto WordEffect = [](Game& game, Object& target) { 83 | (void)game; 84 | (void)target; 85 | }; 86 | emplace(PropertyType::WORD, WordEffect, 0); 87 | 88 | // ---------------------------------------------------------------------- 89 | // PUSH 90 | // Make target pushable and make it solid. 91 | // ---------------------------------------------------------------------- 92 | auto PushEffect = [](Game& game, Object& target) { 93 | (void)game; 94 | (void)target; 95 | }; 96 | emplace(PropertyType::PUSH, PushEffect, 10); 97 | 98 | // ---------------------------------------------------------------------- 99 | // STOP 100 | // Make target solid. 101 | // ---------------------------------------------------------------------- 102 | auto StopEffect = [](Game& game, Object& target) { 103 | (void)game; 104 | (void)target; 105 | }; 106 | emplace(PropertyType::STOP, StopEffect, 11); 107 | 108 | // ---------------------------------------------------------------------- 109 | // MELT 110 | // Enchant target with MELT. 111 | // ---------------------------------------------------------------------- 112 | auto MeltEffect = [](Game& game, Object& target) { 113 | (void)game; 114 | (void)target; 115 | }; 116 | emplace(PropertyType::MELT, MeltEffect, 12); 117 | 118 | // ---------------------------------------------------------------------- 119 | // HOT 120 | // Destroy any MELT object that is or intersects with it 121 | // ---------------------------------------------------------------------- 122 | auto HotEffect = [](Game& game, Object& target) { 123 | auto objects = game.FindObjectsByPosition(target); 124 | 125 | for (auto& object : objects) 126 | { 127 | if (!object->IsText() && object->HasProperty(PropertyType::MELT)) 128 | { 129 | game.DestroyObject(*object); 130 | } 131 | } 132 | }; 133 | emplace(PropertyType::HOT, HotEffect, 50); 134 | } 135 | 136 | Effects::Effects() 137 | { 138 | ImplementBlockEffects(); 139 | ImplementNonBlockEffects(); 140 | } 141 | 142 | const std::map& Effects::GetEffects() const 143 | { 144 | return effects_; 145 | } 146 | } // namespace Baba 147 | -------------------------------------------------------------------------------- /Documents/PythonAPI.md: -------------------------------------------------------------------------------- 1 | # Python API 2 | 3 | ## Index 4 | - [Enumerator](#Enumerator) 5 | - [Agent API](#Agent) 6 | - [Object API](#Object) 7 | - [Rule API](#Rule) 8 | - [Game API](#Game) 9 | - [Preprocess API](#Preprocess) 10 | 11 | 12 | ## Enumerator 13 | 14 | ### Action 15 | ```Action을 정의하는 Enumerator입니다.``` 16 | - UP : 위로 이동 17 | - DOWN : 아래로 이동 18 | - LEFT : 왼쪽으로 이동 19 | - RIGHT : 오른쪽으로 이동 20 | - STAY : 가만히 있기 (스페이스) 21 | - COUNT : Action의 개수 22 | 23 | ### GameResult 24 | ```게임의 결과를 정의하는 Enumerator입니다.``` 25 | - INVALID : 게임의 결과가 유효하지 않음 26 | - WIN : 승리함 27 | - DEFEAT : 패배함 28 | - COUNT : GameResult의 개수 29 | 30 | ### Direction 31 | ```오브젝트의 방향을 정의하는 Enumerator입니다.``` 32 | - INVALID : 방향이 유효하지 않음 33 | - UP : 위쪽 34 | - DOWN : 아래쪽 35 | - LEFT : 왼쪽 36 | - RIGHT : 오른쪽 37 | 38 | ### ObjectType 39 | ```오브젝트의 종류를 정의하는 Enumeartor입니다.``` 40 | 자세한 내용은 아래 파일을 참고하세요. 41 | - Includes/Baba/Enums/ObjectType.def 42 | - Includes/Baba/Enums/PropertyType.def 43 | - Includes/Baba/Enums/TextType.def 44 | - Includes/Baba/Enums/VerbType.def 45 | 46 | ### VerbType 47 | ```문장의 종류를 정의하는 Enumerator입니다.``` 48 | 자세한 내용은 아래 파일을 참고하세요. 49 | - Includes/Baba/Enums/VerbType.def 50 | 51 | ### PropertyType 52 | ```속성의 종류를 정의하는 Enumerator입니다.``` 53 | 자세한 내용은 아래 파일을 참고하세요. 54 | - Includes/Baba/Enums/PropertyType.def 55 | 56 | ### 타입 변경 도구 57 | - ObjectToProperty(type) 58 | ```ObjectType의 type를 PropertyType으로 변경합니다.``` 59 | - PropertyToObject(type) 60 | ```PropertyType의 type를 ObjectType으로 변경합니다.``` 61 | 62 | 63 | ## Agent 64 | Agent 클래스를 상속받아 에이전트를 만들 수 있습니다. 만든 Agent 클래스는 `Game`을 입력받으면 `Action`을 반환하는 메소드를 가지고 있어야 합니다. 아래는 Agent의 예시입니다. 65 | 66 | ``` 67 | class MyAgent(pyBaba.Agent): 68 | def GetAction(self, game): 69 | return pyBaba.Action.STAY 70 | ``` 71 | 72 | ## Object 73 | ```게임 내 오브젝트 클래스입니다.``` 74 | ### 메소드 75 | - GetID() -> int 76 | ```오브젝트의 ID를 반환합니다.``` 77 | - IsText() -> bool 78 | ```오브젝트가 Text인지 여부를 반환합니다.``` 79 | - SetText(value:bool) -> Object 80 | ```value가 True이면 오브젝트를 Text로 만듭니다.``` 81 | - SetType(type:ObjectType) -> Object 82 | ```오브젝트의 타입을 변경합니다.``` 83 | - GetType() -> ObjectType 84 | ```오브젝트의 타입을 반환합니다.``` 85 | - AddProperty(type:PropertyType) -> Object 86 | ```오브젝트에 속성을 추가합니다.``` 87 | - RemoveProperty(type:PropertyType) 88 | ```오브젝트의 속성을 제거합니다.``` 89 | - HasProperty(type:PropertyType) -> bool 90 | ```오브젝트가 해당 속성을 가지고 있는지 여부를 반환합니다.``` 91 | - Destroy() 92 | ```오브젝트를 파괴합니다.``` 93 | - IsDestroyed() -> bool 94 | ```오브젝트가 파괴되었는지 여부를 반환합니다.``` 95 | 96 | ## Rule 97 | ```게임의 규칙 클래스입니다.``` 98 | ### 메소드 99 | - GetTarget() -> ObjectType 100 | ```규칙의 목표의 타입을 반환합니다.``` 101 | - GetVerb() -> ObjectType 102 | ```규칙의 동사의 타입을 반환합니다.``` 103 | - GetEffect() -> ObjectType 104 | ```규칙의 효과의 타입을 반환합니다.``` 105 | - GetRuleID() -> int 106 | ```규칙의 ID를 반환합니다.``` 107 | - [static] CalculateRuleID(target:ObjectType, verb:ObjectType, effect:ObjectType) -> int 108 | ```규칙의 ID를 계산합니다.``` 109 | 110 | ## Game 111 | ```게임 클래스입니다.``` 112 | ### 생성자 113 | - (width, height) 114 | ```가로 width, 세로 height 크기의 게임을 생성합니다.``` 115 | 116 | ### 메소드 117 | - GetWidth() -> int 118 | ```게임의 가로 길이를 반환합니다.``` 119 | - GetHeight() -> int 120 | ```게임의 세로 길이를 반환합니다.``` 121 | - At(x:int, y:int) -> list(Object) 122 | ```(x, y)에 있는 오브젝트의 목록을 반환합니다.``` 123 | - Put(x:int, y:int) -> Object 124 | ```(x, y)에 오브젝트를 배치합니다.``` 125 | - DestroyObject(obj:Object) 126 | ```오브젝트를 파괴합니다.``` 127 | - FindObjects(func, excludeText:bool) -> list(Object) 128 | ```func를 만족하는 오브젝트의 목록을 반환합니다. excludeText가 True이면 Text 오브젝트는 배제합니다.``` 129 | - FindObjectsByType(type:ObjectType, excludeText:bool) -> list(Object) 130 | ```특정 type인 오브젝트의 목록을 반환합니다. excludeText가 True이면 Text 오브젝트는 배제합니다.``` 131 | - FindObjectsByProperty(type:PropertyType), excludeText:bool) -> list(Object) 132 | ```특정 Property를 가진 오브젝트의 목록을 반환합니다. excludeText가 True이면 Text 오브젝트는 배제합니다.``` 133 | - FindObjectsByPosition(obj:Object, excludeText:bool) -> list(Object) 134 | ```obj와 같은 위치를 공유하는 오브젝트의 목록을 반환합니다. excludeText가 True이면 Text 오브젝트는 배제합니다.``` 135 | - FilterObjectsByFunction(objs:list(Object), func) -> list(Object) 136 | ```func를 만족하는 오브젝트만 objs에서 추려냅니다.``` 137 | - GetPositionByObject(obj:Object) -> tuple(int, int) 138 | ```obj의 위치를 반환합니다.``` 139 | - ValidatePosition(x:int, y:int) -> bool 140 | ```유효한 위치인지 여부를 반환합니다.``` 141 | - Update(action:Action) 142 | ```게임을 업데이트합니다.``` 143 | - GetGameResult() -> GameResult 144 | ```게임의 결과를 반환합니다.``` 145 | - AddRule(target:ObjectType, verb:ObjectType, effect:ObjectType) -> int 146 | ```게임의 규칙을 추가하고, 추가된 규칙의 ID를 반환합니다.``` 147 | - AddBaseRule(target:ObjectType, verb:ObjectType, effect:ObjectType) -> int 148 | ```게임의 기반 규칙을 추가하고, 추가된 규칙의 ID를 반환합니다. 추가된 규칙은 제거되지 않습니다.``` 149 | - RemoveRule(id:int) 150 | ```게임의 규칙을 제거합니다.``` 151 | - TieStuckMoveableObjects(pusher:Object, dir:Direction) 152 | ```움직임을 발생시키는 물체(YOU)가 움직일 때 영향을 받는 물체(자신 포함)를 모두 묶은 오브젝트의 목록을 반환합니다. 움직이는 게 불가능 할 경우 빈 목록을 반화합니다.``` 153 | - MoveObjects(objs:list(Object), dir:Direction) 154 | ```물체들을 이동합니다.``` 155 | - GetNowAction() -> Action 156 | ```최근 한 행동을 반환합니다.``` 157 | 158 | ## Preprocess 159 | ```게임의 상태를 인공신경망에 넣을 수 있도록 전처리하는 클래스입니다.``` 160 | 161 | ### 필드 162 | - TENSOR_DIM 163 | ```변환된 tensor의 channel 수입니다.``` 164 | 165 | ### 메소드 166 | - StateToTensor(game:Game) -> list(float) 167 | ```game을 tensor로 변환해줍니다.``` -------------------------------------------------------------------------------- /Extension/BabaAgent/DQN.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn, optim 3 | import torch.nn.functional as F 4 | 5 | from collections import namedtuple 6 | import random 7 | import numpy as np 8 | 9 | from environment import BabaEnv10x10 10 | import pyBaba 11 | 12 | from tensorboardX import SummaryWriter 13 | 14 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 15 | env = BabaEnv10x10() 16 | 17 | Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward')) 18 | 19 | class ReplayMemory: 20 | def __init__(self, capacity): 21 | self.capacity = capacity 22 | self.memory = [] 23 | self.position = 0 24 | 25 | def push(self, *args): 26 | if len(self.memory) < self.capacity: 27 | self.memory.append(None) 28 | 29 | self.memory[self.position] = Transition(*args) 30 | self.position = (self.position + 1) % self.capacity 31 | 32 | def sample(self, batch_size): 33 | return random.sample(self.memory, batch_size) 34 | 35 | def __len__(self): 36 | return len(self.memory) 37 | 38 | class Network(nn.Module): 39 | def __init__(self): 40 | super(Network, self).__init__() 41 | 42 | self.conv1 = nn.Conv2d(pyBaba.Preprocess.TENSOR_DIM, 64, 3, padding=1, bias=False) 43 | self.bn1 = nn.BatchNorm2d(64) 44 | self.conv2 = nn.Conv2d(64, 64, 3, padding=1, bias=False) 45 | self.bn2 = nn.BatchNorm2d(64) 46 | self.conv3 = nn.Conv2d(64, 64, 3, padding=1, bias=False) 47 | self.bn3 = nn.BatchNorm2d(64) 48 | self.conv4 = nn.Conv2d(64, 1, 1, padding=0, bias=False) 49 | self.bn4 = nn.BatchNorm2d(1) 50 | 51 | self.fc = nn.Linear(100, 5) 52 | 53 | def forward(self, x): 54 | x = F.relu(self.bn1(self.conv1(x))) 55 | x = F.relu(self.bn2(self.conv2(x))) 56 | x = F.relu(self.bn3(self.conv3(x))) 57 | x = F.relu(self.bn4(self.conv4(x))) 58 | 59 | x = x.view(x.data.size(0), -1) 60 | return self.fc(x) 61 | 62 | BATCH_SIZE = 128 63 | GAMMA = 0.99 64 | EPSILON = 0.9 65 | EPSILON_DECAY = 0.99 66 | MIN_EPSILON = 0.01 67 | TARGET_UPDATE = 10 68 | 69 | net = Network().to(device) 70 | target_net = Network().to(device) 71 | 72 | target_net.load_state_dict(net.state_dict()) 73 | target_net.eval() 74 | 75 | opt = optim.Adam(net.parameters()) 76 | memory = ReplayMemory(10000) 77 | 78 | def get_action(state): 79 | if random.random() > EPSILON: 80 | with torch.no_grad(): 81 | return env.action_space[net(state).max(1)[1].view(1)] 82 | else: 83 | return random.choice(env.action_space) 84 | 85 | def train(): 86 | if len(memory) < BATCH_SIZE: 87 | return 88 | 89 | transitions = memory.sample(BATCH_SIZE) 90 | batch = Transition(*zip(*transitions)) 91 | 92 | actions = tuple((map(lambda a: torch.tensor([[int(a)]]), batch.action))) 93 | rewards = tuple((map(lambda r: torch.tensor([r], dtype=torch.float32), batch.reward))) 94 | 95 | non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), device=device, dtype=torch.uint8) 96 | non_final_next_states = torch.cat([s for s in batch.next_state if s is not None]) 97 | 98 | state_batch = torch.cat(batch.state).to(device) 99 | action_batch = torch.cat(actions).to(device) 100 | reward_batch = torch.cat(rewards).to(device) 101 | 102 | q_values = net(state_batch).gather(1, action_batch) 103 | 104 | next_q_values = torch.zeros(BATCH_SIZE, device=device) 105 | next_q_values[non_final_mask] = target_net(non_final_next_states).max(1)[0].detach() 106 | 107 | expected_state_action_values = (next_q_values * GAMMA) + reward_batch 108 | 109 | loss = F.smooth_l1_loss(q_values, expected_state_action_values.unsqueeze(1)) 110 | 111 | opt.zero_grad() 112 | loss.backward() 113 | 114 | for param in net.parameters(): 115 | param.grad.data.clamp_(-1, 1) 116 | 117 | opt.step() 118 | 119 | if __name__ == '__main__': 120 | writer = SummaryWriter() 121 | 122 | global_step = 0 123 | 124 | scores = [] 125 | for e in range(10000): 126 | score = 0 127 | 128 | state = env.reset().reshape(1, -1, 10, 10) 129 | state = torch.tensor(state).to(device) 130 | 131 | step = 0 132 | while step < 1000: 133 | global_step += 1 134 | 135 | action = get_action(state) 136 | 137 | next_state, reward, done, _ = env.step(action) 138 | next_state = next_state.reshape(1, -1, 10, 10) 139 | next_state = torch.tensor(next_state).to(device) 140 | 141 | memory.push(state, action, next_state, reward) 142 | score += reward 143 | state = next_state 144 | 145 | step += 1 146 | 147 | train() 148 | if env.done: 149 | break 150 | 151 | writer.add_scalar('Reward', score, e) 152 | writer.add_scalar('Step', step, e) 153 | writer.add_scalar('Epsilon', EPSILON, e) 154 | 155 | scores.append(score) 156 | 157 | print(f'Episode {e}: score: {score:.3f} time_step: {global_step} step: {step} epsilon: {EPSILON}') 158 | 159 | if np.mean(scores[-min(50, len(scores)):]) > 180: 160 | print('Solved!') 161 | torch.save(net.state_dict(), 'dqn_agent.bin') 162 | break 163 | 164 | if e % TARGET_UPDATE == 0: 165 | target_net.load_state_dict(net.state_dict()) 166 | 167 | EPSILON *= EPSILON_DECAY 168 | EPSILON = max(EPSILON, MIN_EPSILON) 169 | -------------------------------------------------------------------------------- /UnitTest/Rules/EffectTests.cc: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019 Hyeonsu Kim 2 | 3 | #include "gtest/gtest.h" 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace Baba; 12 | 13 | TEST(EffectTest, BABA) 14 | { 15 | Game game(5, 5); 16 | 17 | Object& obj1 = game.Put(0, 0).SetType(ObjectType::KEKE); 18 | Object& obj2 = game.Put(1, 1).SetType(ObjectType::STAR); 19 | 20 | EXPECT_EQ(*game.FindObjectsByType(ObjectType::KEKE).at(0), obj1); 21 | EXPECT_EQ(*game.FindObjectsByType(ObjectType::STAR).at(0), obj2); 22 | 23 | game.AddBaseRule(ObjectType::KEKE, ObjectType::IS, ObjectType::BABA); 24 | 25 | game.Update(); 26 | 27 | EXPECT_EQ(*game.FindObjectsByType(ObjectType::BABA).at(0), obj1); 28 | EXPECT_EQ(*game.FindObjectsByType(ObjectType::STAR).at(0), obj2); 29 | } 30 | 31 | TEST(EffectTest, YOU) 32 | { 33 | Game game(10, 10); 34 | 35 | game.Put(1, 1).SetType(ObjectType::BABA); 36 | game.Put(5, 5) 37 | .SetType(ObjectType::BABA) 38 | .SetText(true); 39 | game.Put(5, 6).SetType(ObjectType::IS); 40 | game.Put(5, 7).SetType(ObjectType::YOU); 41 | 42 | game.Update(Action::RIGHT); 43 | EXPECT_EQ(game.At(2, 1).size(), 1); 44 | EXPECT_TRUE(game.At(1, 1).empty()); 45 | 46 | game.Update(Action::DOWN); 47 | EXPECT_EQ(game.At(2, 2).size(), 1); 48 | EXPECT_TRUE(game.At(2, 1).empty()); 49 | 50 | game.Update(Action::LEFT); 51 | EXPECT_EQ(game.At(1, 2).size(), 1); 52 | EXPECT_TRUE(game.At(2, 2).empty()); 53 | 54 | game.Update(Action::UP); 55 | EXPECT_EQ(game.At(1, 1).size(), 1); 56 | EXPECT_TRUE(game.At(1, 2).empty()); 57 | } 58 | 59 | TEST(EffectTest, PUSH) 60 | { 61 | Game game(10, 10); 62 | 63 | game.Put(0, 1).SetType(ObjectType::KEY); 64 | game.Put(1, 1).SetType(ObjectType::BABA); 65 | game.Put(1, 1).SetType(ObjectType::KEKE); 66 | game.Put(2, 1).SetType(ObjectType::KEKE); 67 | game.Put(3, 1).SetType(ObjectType::ALGAE); 68 | game.Put(4, 1).SetType(ObjectType::IS); 69 | game.Put(1, 2).SetType(ObjectType::STAR); 70 | 71 | game.AddBaseRule(ObjectType::KEY, ObjectType::IS, ObjectType::PUSH); 72 | game.AddBaseRule(ObjectType::BABA, ObjectType::IS, ObjectType::YOU); 73 | game.AddBaseRule(ObjectType::KEKE, ObjectType::IS, ObjectType::PUSH); 74 | game.AddBaseRule(ObjectType::ALGAE, ObjectType::IS, ObjectType::PUSH); 75 | game.AddBaseRule(ObjectType::STAR, ObjectType::IS, ObjectType::YOU); 76 | 77 | game.Update(Action::RIGHT); 78 | EXPECT_EQ(game.At(0, 1)[0]->GetType(), ObjectType::KEY); 79 | EXPECT_EQ(game.At(1, 1)[0]->GetType(), ObjectType::KEKE); 80 | EXPECT_EQ(game.At(2, 1)[0]->GetType(), ObjectType::BABA); 81 | EXPECT_EQ(game.At(3, 1)[0]->GetType(), ObjectType::KEKE); 82 | EXPECT_EQ(game.At(4, 1)[0]->GetType(), ObjectType::ALGAE); 83 | EXPECT_EQ(game.At(5, 1)[0]->GetType(), ObjectType::IS); 84 | EXPECT_EQ(game.At(2, 2)[0]->GetType(), ObjectType::STAR); 85 | } 86 | 87 | TEST(EffectTest, STOP) 88 | { 89 | Game game(10, 10); 90 | 91 | game.Put(1, 1).SetType(ObjectType::BABA); 92 | game.Put(2, 1).SetType(ObjectType::KEKE); 93 | game.Put(3, 1).SetType(ObjectType::ALGAE); 94 | game.Put(4, 1).SetType(ObjectType::WALL); 95 | 96 | game.AddBaseRule(ObjectType::BABA, ObjectType::IS, ObjectType::YOU); 97 | game.AddBaseRule(ObjectType::KEKE, ObjectType::IS, ObjectType::PUSH); 98 | game.AddBaseRule(ObjectType::ALGAE, ObjectType::IS, ObjectType::PUSH); 99 | game.AddBaseRule(ObjectType::WALL, ObjectType::IS, ObjectType::STOP); 100 | 101 | game.Update(Action::RIGHT); 102 | EXPECT_EQ(game.At(1, 1)[0]->GetType(), ObjectType::BABA); 103 | EXPECT_EQ(game.At(2, 1)[0]->GetType(), ObjectType::KEKE); 104 | EXPECT_EQ(game.At(3, 1)[0]->GetType(), ObjectType::ALGAE); 105 | EXPECT_EQ(game.At(4, 1)[0]->GetType(), ObjectType::WALL); 106 | } 107 | 108 | TEST(EffectTest, WIN) 109 | { 110 | Game game(10, 10); 111 | 112 | game.Put(1, 1).SetType(ObjectType::BABA); 113 | game.Put(1, 1).SetType(ObjectType::FLAG); 114 | game.Put(5, 5) 115 | .SetType(ObjectType::BABA) 116 | .SetText(true); 117 | game.Put(5, 6).SetType(ObjectType::IS); 118 | game.Put(5, 7).SetType(ObjectType::YOU); 119 | game.Put(6, 5) 120 | .SetType(ObjectType::FLAG) 121 | .SetText(true); 122 | game.Put(6, 6).SetType(ObjectType::IS); 123 | game.Put(6, 7).SetType(ObjectType::WIN); 124 | 125 | game.Update(); 126 | 127 | EXPECT_EQ(game.GetGameResult(), GameResult::WIN); 128 | } 129 | 130 | TEST(EffectTest, WIN_YOU) 131 | { 132 | Game game(10, 10); 133 | 134 | game.Put(1, 1).SetType(ObjectType::BABA); 135 | game.Put(1, 2).SetType(ObjectType::FLAG); 136 | 137 | game.AddBaseRule(ObjectType::BABA, ObjectType::IS, ObjectType::YOU); 138 | game.AddBaseRule(ObjectType::FLAG, ObjectType::IS, ObjectType::WIN); 139 | 140 | game.Update(Action::DOWN); 141 | 142 | EXPECT_EQ(game.GetGameResult(), GameResult::WIN); 143 | } 144 | 145 | TEST(EffectTest, MELT) 146 | { 147 | Game game(5, 5); 148 | 149 | Object& obj1 = game.Put(0, 0).SetType(ObjectType::BABA); 150 | 151 | game.AddBaseRule(ObjectType::BABA, ObjectType::IS, ObjectType::MELT); 152 | 153 | game.Update(); 154 | 155 | EXPECT_EQ(*game.FindObjectsByProperty(PropertyType::MELT).at(0), obj1); 156 | } 157 | 158 | TEST(EffectTest, HOT) 159 | { 160 | Game game(5, 5); 161 | 162 | game.Put(0, 0).SetType(ObjectType::BABA); 163 | game.Put(0, 0).SetType(ObjectType::KEKE); 164 | 165 | game.AddBaseRule(ObjectType::BABA, ObjectType::IS, ObjectType::MELT); 166 | game.AddBaseRule(ObjectType::KEKE, ObjectType::IS, ObjectType::HOT); 167 | 168 | game.Update(); 169 | 170 | EXPECT_TRUE(game.FindObjectsByProperty(PropertyType::MELT).empty()); 171 | EXPECT_EQ(game.At(0, 0).size(), 1); 172 | EXPECT_EQ(game.At(0, 0).at(0)->GetType(), ObjectType::KEKE); 173 | } 174 | 175 | TEST(EffectTest, Priority) 176 | { 177 | Game game(5, 5); 178 | 179 | game.AddRule(ObjectType::BABA, ObjectType::IS, ObjectType::MELT); 180 | game.AddRule(ObjectType::BABA, ObjectType::IS, ObjectType::YOU); 181 | game.AddRule(ObjectType::BABA, ObjectType::IS, ObjectType::YOU); 182 | } -------------------------------------------------------------------------------- /Includes/Baba/Game/Game.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park 2 | 3 | #ifndef BABA_GAME_H 4 | #define BABA_GAME_H 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | namespace Baba 16 | { 17 | //! 18 | //! \brief Class that represents game level 19 | //! 20 | class Game final 21 | { 22 | public: 23 | //! Location tuple wrapper 24 | using Point = std::tuple; 25 | 26 | public: 27 | //! Constructor with level shape 28 | Game(std::size_t width, std::size_t height); 29 | 30 | //! Default destructor 31 | ~Game(); 32 | 33 | //! Delete copy constructor 34 | Game(const Game&) = delete; 35 | 36 | //! Delete move constructor 37 | Game(Game&&) = delete; 38 | 39 | //! Delete copy assignment operator 40 | Game& operator=(const Game&) = delete; 41 | 42 | //! Delete move assignment operator 43 | Game& operator=(Game&&) = delete; 44 | 45 | //! Return level's width 46 | //! \return Returned level's width 47 | std::size_t GetWidth() const; 48 | 49 | //! Return level's height 50 | //! \return Returned level's height 51 | std::size_t GetHeight() const; 52 | 53 | //! Get objects in that position 54 | //! \param x x position 55 | //! \param y y position 56 | //! \return Object in that position vector 57 | const Object::Arr& At(std::size_t x, std::size_t y) const; 58 | 59 | //! Returns whether a rule exists in that position. 60 | //! \param x x position 61 | //! \param y y position 62 | //! \return Whether a rule exists in that position. 63 | bool AtRule(std::size_t x, std::size_t y) const; 64 | 65 | //! Put object in that position 66 | //! \param x x position 67 | //! \param y y position 68 | //! \return Created object 69 | Object& Put(std::size_t x, std::size_t y); 70 | 71 | //! Destory object 72 | //! \param object Object will be destroyed 73 | void DestroyObject(Object& object); 74 | 75 | //! Find objects by func 76 | //! \param func function to classify objects 77 | //! \param excludeTest Exclude text option 78 | //! \return Objects that satisfy func 79 | Object::Arr FindObjects(std::function func, bool excludeText = false) const; 80 | 81 | //! Find objects by type 82 | //! \param Object's type 83 | //! \param excludeTest Exclude text option 84 | //! \return Objects having the same \p type 85 | Object::Arr FindObjectsByType(ObjectType type, bool excludeText = false) const; 86 | 87 | //! Find objects by Property 88 | //! \param property Object's property 89 | //! \param excludeTest Exclude text option 90 | //! \return Objects having the same \p property 91 | Object::Arr FindObjectsByProperty(PropertyType property, bool excludeText = false) const; 92 | 93 | //! Find objects by Position of target 94 | //! \param target Object to provide position 95 | //! \param excludeTest Exclude text option 96 | //! \return Objects havaing the same position as target 97 | Object::Arr FindObjectsByPosition(const Object& target, bool excludeText = false) const; 98 | 99 | //! Filter objects by func 100 | //! \param objects objects to be filtered 101 | //! \param func function to classify objects 102 | //! \return filtered objects 103 | Object::Arr FilterObjectByFunction(const Object::Arr& objects, 104 | std::function func) const; 105 | 106 | //! Return target's position 107 | //! \param target target object 108 | //! \return position of target 109 | const Point GetPositionByObject(const Object& target) const; 110 | 111 | //! Check position is valid 112 | //! \param x x position 113 | //! \param y y position 114 | //! \return Whether position is valid 115 | bool ValidatePosition(std::size_t x, std::size_t y) const; 116 | 117 | //! Update game 118 | //! \param action Player's action 119 | void Update(Action action = Action::STAY); 120 | 121 | //! Get game result; 122 | //! \return GameResult 123 | GameResult GetGameResult() const; 124 | 125 | //! Add rule 126 | //! \param target Target of rule 127 | //! \param verb Verb of rule 128 | //! \param effect Effect of rule 129 | //! \return ID of added rule 130 | std::int64_t AddRule(ObjectType target, ObjectType verb, ObjectType effect); 131 | 132 | //! Add base rule 133 | //! \param target Target of rule 134 | //! \param verb Verb of rule 135 | //! \param effect Effect of rule 136 | //! \return ID of added rule 137 | std::int64_t AddBaseRule(ObjectType target, ObjectType verb, ObjectType effect); 138 | 139 | //! Remove rule 140 | //! \param id ID of rule to remove 141 | void RemoveRule(std::int64_t id); 142 | 143 | //! Tie affected objects as the object move 144 | //! \param pusher Object to be center of movement 145 | //! \param dir Direction of movement 146 | //! \return Tied objects 147 | Object::Arr TieStuckMoveableObjects(Object& pusher, Direction dir) const; 148 | 149 | //! Move objects without any condition check. 150 | //! \param objects Objects 151 | //! \param dir Direction of movement 152 | void MoveObjects(const Object::Arr& objects, Direction dir); 153 | 154 | //! Get set of rules 155 | //! \return Set of rules 156 | const std::set& GetRules() const; 157 | 158 | //! Get nowAction_ 159 | //! \return nowAction_ 160 | Action GetNowAction() const; 161 | 162 | private: 163 | void parseRules(); 164 | void applyRules(); 165 | void applyRules(std::set& r, bool doFunc = true); 166 | void determineResult(); 167 | Point dir2Vec(Direction dir) const; 168 | 169 | std::size_t pt2idx(std::size_t x, std::size_t y) const; 170 | 171 | private: 172 | std::size_t width_, height_; 173 | Object::Arr objects_; 174 | std::vector map_; 175 | 176 | std::set rules_; 177 | std::set baseRules_; 178 | std::vector ruleMap_; 179 | 180 | Action nowAction_ = Action::STAY; 181 | GameResult gameResult_ = GameResult::INVALID; 182 | }; 183 | } // namespace Baba 184 | 185 | #endif // BABA_GAME_H 186 | -------------------------------------------------------------------------------- /CMake/CodeCoverage.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # 2012-01-31, Lars Bilke 3 | # - Enable Code Coverage 4 | # 5 | # 2013-09-17, Joakim Söderberg 6 | # - Added support for Clang. 7 | # - Some additional usage instructions. 8 | # 9 | # USAGE: 10 | 11 | # 0. (Mac only) If you use Xcode 5.1 make sure to patch geninfo as described here: 12 | # http://stackoverflow.com/a/22404544/80480 13 | # 14 | # 1. Copy this file into your cmake modules path. 15 | # 16 | # 2. Add the following line to your CMakeLists.txt: 17 | # INCLUDE(CodeCoverage) 18 | # 19 | # 3. Set compiler flags to turn off optimization and enable coverage: 20 | # SET(CMAKE_CXX_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage") 21 | # SET(CMAKE_C_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage") 22 | # 23 | # 3. Use the function SETUP_TARGET_FOR_COVERAGE to create a custom make target 24 | # which runs your test executable and produces a lcov code coverage report: 25 | # Example: 26 | # SETUP_TARGET_FOR_COVERAGE( 27 | # my_coverage_target # Name for custom target. 28 | # test_driver # Name of the test driver executable that runs the tests. 29 | # # NOTE! This should always have a ZERO as exit code 30 | # # otherwise the coverage generation will not complete. 31 | # coverage # Name of output directory. 32 | # ) 33 | # 34 | # 4. Build a Debug build: 35 | # cmake -DCMAKE_BUILD_TYPE=Debug .. 36 | # make 37 | # make my_coverage_target 38 | # 39 | # 40 | 41 | # Check prereqs 42 | FIND_PROGRAM( GCOV_PATH gcov ) 43 | FIND_PROGRAM( LCOV_PATH lcov ) 44 | FIND_PROGRAM( GENHTML_PATH genhtml ) 45 | FIND_PROGRAM( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/tests) 46 | 47 | IF(NOT GCOV_PATH) 48 | MESSAGE(FATAL_ERROR "gcov not found! Aborting...") 49 | ENDIF() # NOT GCOV_PATH 50 | 51 | IF(NOT CMAKE_COMPILER_IS_GNUCXX) 52 | # Clang version 3.0.0 and greater now supports gcov as well. 53 | MESSAGE(WARNING "Compiler is not GNU gcc! Clang Version 3.0.0 and greater supports gcov as well, but older versions don't.") 54 | 55 | IF(NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") 56 | MESSAGE(FATAL_ERROR "Compiler is not GNU gcc! Aborting...") 57 | ENDIF() 58 | ENDIF() # NOT CMAKE_COMPILER_IS_GNUCXX 59 | 60 | SET(CMAKE_CXX_FLAGS_COVERAGE 61 | "-g -O0 --coverage -fprofile-arcs -ftest-coverage" 62 | CACHE STRING "Flags used by the C++ compiler during coverage builds." 63 | FORCE ) 64 | SET(CMAKE_C_FLAGS_COVERAGE 65 | "-g -O0 --coverage -fprofile-arcs -ftest-coverage" 66 | CACHE STRING "Flags used by the C compiler during coverage builds." 67 | FORCE ) 68 | SET(CMAKE_EXE_LINKER_FLAGS_COVERAGE 69 | "" 70 | CACHE STRING "Flags used for linking binaries during coverage builds." 71 | FORCE ) 72 | SET(CMAKE_SHARED_LINKER_FLAGS_COVERAGE 73 | "" 74 | CACHE STRING "Flags used by the shared libraries linker during coverage builds." 75 | FORCE ) 76 | MARK_AS_ADVANCED( 77 | CMAKE_CXX_FLAGS_COVERAGE 78 | CMAKE_C_FLAGS_COVERAGE 79 | CMAKE_EXE_LINKER_FLAGS_COVERAGE 80 | CMAKE_SHARED_LINKER_FLAGS_COVERAGE ) 81 | 82 | IF ( NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR CMAKE_BUILD_TYPE STREQUAL "Coverage")) 83 | MESSAGE( WARNING "Code coverage results with an optimized (non-Debug) build may be misleading" ) 84 | ENDIF() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug" 85 | 86 | 87 | # Param _targetname The name of new the custom make target 88 | # Param _testrunner The name of the target which runs the tests. 89 | # MUST return ZERO always, even on errors. 90 | # If not, no coverage report will be created! 91 | # Param _outputname lcov output is generated as _outputname.info 92 | # HTML report is generated in _outputname/index.html 93 | # Optional fourth parameter is passed as arguments to _testrunner 94 | # Pass them in list form, e.g.: "-j;2" for -j 2 95 | FUNCTION(SETUP_TARGET_FOR_COVERAGE _targetname _testrunner _outputname) 96 | 97 | IF(NOT LCOV_PATH) 98 | MESSAGE(FATAL_ERROR "lcov not found! Aborting...") 99 | ENDIF() # NOT LCOV_PATH 100 | 101 | IF(NOT GENHTML_PATH) 102 | MESSAGE(FATAL_ERROR "genhtml not found! Aborting...") 103 | ENDIF() # NOT GENHTML_PATH 104 | 105 | # Setup target 106 | ADD_CUSTOM_TARGET(${_targetname} 107 | 108 | # Cleanup lcov 109 | ${LCOV_PATH} --directory . --zerocounters 110 | 111 | # Run tests 112 | COMMAND ${_testrunner} ${ARGV3} 113 | 114 | # Capturing lcov counters and generating report 115 | COMMAND ${LCOV_PATH} --directory . --capture --output-file ${_outputname}.info 116 | COMMAND ${LCOV_PATH} --remove ${_outputname}.info 'build/*' 'tests/*' '/usr/*' --output-file ${_outputname}.info.cleaned 117 | COMMAND ${GENHTML_PATH} -o ${_outputname} ${_outputname}.info.cleaned 118 | COMMAND ${CMAKE_COMMAND} -E remove ${_outputname}.info ${_outputname}.info.cleaned 119 | 120 | WORKING_DIRECTORY ${CMAKE_BINARY_DIR} 121 | COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report." 122 | ) 123 | 124 | # Show info where to find the report 125 | ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD 126 | COMMAND ; 127 | COMMENT "Open ./${_outputname}/index.html in your browser to view the coverage report." 128 | ) 129 | 130 | ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE 131 | 132 | # Param _targetname The name of new the custom make target 133 | # Param _testrunner The name of the target which runs the tests 134 | # Param _outputname cobertura output is generated as _outputname.xml 135 | # Optional fourth parameter is passed as arguments to _testrunner 136 | # Pass them in list form, e.g.: "-j;2" for -j 2 137 | FUNCTION(SETUP_TARGET_FOR_COVERAGE_COBERTURA _targetname _testrunner _outputname) 138 | 139 | IF(NOT PYTHON_EXECUTABLE) 140 | MESSAGE(FATAL_ERROR "Python not found! Aborting...") 141 | ENDIF() # NOT PYTHON_EXECUTABLE 142 | 143 | IF(NOT GCOVR_PATH) 144 | MESSAGE(FATAL_ERROR "gcovr not found! Aborting...") 145 | ENDIF() # NOT GCOVR_PATH 146 | 147 | ADD_CUSTOM_TARGET(${_targetname} 148 | 149 | # Run tests 150 | ${_testrunner} ${ARGV3} 151 | 152 | # Running gcovr 153 | COMMAND ${GCOVR_PATH} -x -r ${CMAKE_SOURCE_DIR} -e '${CMAKE_SOURCE_DIR}/tests/' -e '${CMAKE_SOURCE_DIR}/build/' -o ${_outputname}.xml 154 | WORKING_DIRECTORY ${CMAKE_BINARY_DIR} 155 | COMMENT "Running gcovr to produce Cobertura code coverage report." 156 | ) 157 | 158 | # Show info where to find the report 159 | ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD 160 | COMMAND ; 161 | COMMENT "Cobertura code coverage report saved in ${_outputname}.xml." 162 | ) 163 | 164 | ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE_COBERTURA -------------------------------------------------------------------------------- /UnitTest/Game/GameTests.cc: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2019 Hyeonsu Kim 2 | 3 | #include "gtest/gtest.h" 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace Baba; 10 | 11 | TEST(GameTest, GetHeighWidth) 12 | { 13 | Game game(5, 10); 14 | 15 | EXPECT_EQ(game.GetHeight(), 10); 16 | EXPECT_EQ(game.GetWidth(), 5); 17 | } 18 | 19 | TEST(GameTest, Put) 20 | { 21 | Game game(5, 5); 22 | 23 | game.Put(0, 0).SetType(ObjectType::BABA); 24 | game.Put(0, 0).SetType(ObjectType::KEKE); 25 | 26 | EXPECT_EQ(game.At(0, 0).at(0)->GetType(), ObjectType::BABA); 27 | EXPECT_EQ(game.At(0, 0).at(1)->GetType(), ObjectType::KEKE); 28 | } 29 | 30 | TEST(GameTest, FindObjectByType) 31 | { 32 | Game game(5, 5); 33 | 34 | Object& obj1 = game.Put(0, 0).SetType(ObjectType::BABA); 35 | Object& obj2 = game.Put(0, 0).SetType(ObjectType::KEKE); 36 | 37 | EXPECT_EQ(*game.FindObjectsByType(ObjectType::BABA).at(0), obj1); 38 | EXPECT_EQ(*game.FindObjectsByType(ObjectType::KEKE).at(0), obj2); 39 | } 40 | 41 | TEST(GameTest, FindObjectByType_TEXT) 42 | { 43 | Game game(5, 5); 44 | 45 | game.Put(0, 0).SetType(ObjectType::IS); 46 | game.Put(0, 0).SetType(ObjectType::KEKE).SetText(true); 47 | 48 | EXPECT_EQ(game.FindObjectsByType(ObjectType::TEXT).size(), 2); 49 | } 50 | 51 | TEST(GameTest, FindObjectsByProperty) 52 | { 53 | Game game(5, 5); 54 | 55 | game.Put(0, 0).SetType(ObjectType::BABA); 56 | Object& obj2 = game.Put(0, 0) 57 | .SetType(ObjectType::KEKE) 58 | .AddProperty(PropertyType::WORD); 59 | 60 | EXPECT_EQ(*game.FindObjectsByProperty(PropertyType::WORD).at(0), obj2); 61 | } 62 | 63 | TEST(GameTest, FindObjectsByPosition) 64 | { 65 | Game game(5, 5); 66 | 67 | Object& obj1 = game.Put(0, 0).SetType(ObjectType::BABA); 68 | Object& obj2 = game.Put(0, 0).SetType(ObjectType::KEKE); 69 | 70 | EXPECT_EQ(*game.FindObjectsByPosition(obj1).at(0), obj1); 71 | EXPECT_EQ(*game.FindObjectsByPosition(obj1).at(1), obj2); 72 | 73 | game.Put(0, 0).SetType(ObjectType::ME).SetText(true); 74 | 75 | EXPECT_EQ(game.FindObjectsByPosition(obj1, true).size(), 2u); 76 | 77 | Object invalid; 78 | EXPECT_EQ(game.FindObjectsByPosition(invalid).empty(), true); 79 | } 80 | 81 | TEST(GameTest, GetPositionByObject) 82 | { 83 | Game game(5, 5); 84 | 85 | Object& obj1 = game.Put(0, 0).SetType(ObjectType::BABA); 86 | 87 | Object& obj2 = game.Put(4, 4).SetType(ObjectType::BABA); 88 | 89 | auto [x1, y1] = game.GetPositionByObject(obj1); 90 | auto [x2, y2] = game.GetPositionByObject(obj2); 91 | 92 | EXPECT_EQ(x1, 0); 93 | EXPECT_EQ(y1, 0); 94 | EXPECT_EQ(x2, 4); 95 | EXPECT_EQ(y2, 4); 96 | 97 | Object invalid; 98 | EXPECT_ANY_THROW(game.GetPositionByObject(invalid)); 99 | } 100 | 101 | TEST(GameTest, ParseRules_Vertical_Center) 102 | { 103 | Game game(10, 10); 104 | 105 | game.Put(1, 1).SetType(ObjectType::KEKE); 106 | game.Put(5, 5).SetType(ObjectType::KEKE).SetText(true); 107 | game.Put(6, 5).SetType(ObjectType::IS); 108 | game.Put(7, 5).SetType(ObjectType::BABA).SetText(true); 109 | 110 | game.Update(); 111 | 112 | EXPECT_EQ(game.GetRules().size(), 1u); 113 | 114 | EXPECT_TRUE(game.AtRule(5, 5)); 115 | EXPECT_TRUE(game.AtRule(6, 5)); 116 | EXPECT_TRUE(game.AtRule(7, 5)); 117 | EXPECT_FALSE(game.AtRule(8, 5)); 118 | 119 | auto& rule = *game.GetRules().begin(); 120 | 121 | EXPECT_EQ(rule.GetTarget(), ObjectType::KEKE); 122 | EXPECT_EQ(rule.GetVerb(), ObjectType::IS); 123 | EXPECT_EQ(rule.GetEffect(), ObjectType::BABA); 124 | 125 | EXPECT_EQ(game.At(1, 1).at(0)->GetType(), ObjectType::BABA); 126 | } 127 | 128 | TEST(GameTest, ParseRules_Horizontal_Center) 129 | { 130 | Game game(10, 10); 131 | 132 | game.Put(1, 1).SetType(ObjectType::KEKE); 133 | game.Put(5, 5).SetType(ObjectType::KEKE).SetText(true); 134 | game.Put(5, 6).SetType(ObjectType::IS); 135 | game.Put(5, 7).SetType(ObjectType::BABA).SetText(true); 136 | 137 | game.Update(); 138 | 139 | EXPECT_EQ(game.GetRules().size(), 1u); 140 | 141 | EXPECT_TRUE(game.AtRule(5, 5)); 142 | EXPECT_TRUE(game.AtRule(5, 6)); 143 | EXPECT_TRUE(game.AtRule(5, 7)); 144 | EXPECT_FALSE(game.AtRule(8, 5)); 145 | 146 | auto& rule = *game.GetRules().begin(); 147 | 148 | EXPECT_EQ(rule.GetTarget(), ObjectType::KEKE); 149 | EXPECT_EQ(rule.GetVerb(), ObjectType::IS); 150 | EXPECT_EQ(rule.GetEffect(), ObjectType::BABA); 151 | 152 | EXPECT_EQ(game.At(1, 1).at(0)->GetType(), ObjectType::BABA); 153 | } 154 | 155 | TEST(GameTest, ParseRules_Cross) 156 | { 157 | Game game(10, 10); 158 | 159 | game.Put(1, 1).SetType(ObjectType::KEKE); 160 | game.Put(5, 4).SetType(ObjectType::KEKE).SetText(true); 161 | game.Put(5, 5).SetType(ObjectType::IS); 162 | game.Put(5, 6).SetType(ObjectType::HOT); 163 | game.Put(4, 5).SetType(ObjectType::BABA).SetText(true); 164 | game.Put(6, 5).SetType(ObjectType::MELT); 165 | game.Put(1, 1).SetType(ObjectType::BABA); 166 | 167 | game.Update(); 168 | 169 | EXPECT_EQ(game.GetRules().size(), 2u); 170 | 171 | EXPECT_TRUE(game.AtRule(5, 4)); 172 | EXPECT_TRUE(game.AtRule(5, 5)); 173 | EXPECT_TRUE(game.AtRule(5, 6)); 174 | EXPECT_TRUE(game.AtRule(4, 5)); 175 | EXPECT_TRUE(game.AtRule(6, 5)); 176 | EXPECT_FALSE(game.AtRule(8, 5)); 177 | 178 | EXPECT_EQ(game.At(1, 1).at(0)->GetType(), ObjectType::KEKE); 179 | EXPECT_TRUE(game.FindObjectsByType(ObjectType::BABA, true).empty()); 180 | } 181 | 182 | TEST(GameTest, AddOrRemoveRule) 183 | { 184 | Game game(5, 5); 185 | 186 | game.Put(1, 1).SetType(ObjectType::BABA); 187 | 188 | std::int64_t id = 189 | game.AddRule(ObjectType::BABA, ObjectType::IS, ObjectType::YOU); 190 | EXPECT_EQ(game.GetRules().size(), 1u); 191 | 192 | EXPECT_EQ(game.GetRules().begin()->GetRuleID(), id); 193 | 194 | EXPECT_EQ(game.GetRules().begin()->GetTarget(), ObjectType::BABA); 195 | EXPECT_EQ(game.GetRules().begin()->GetVerb(), ObjectType::IS); 196 | EXPECT_EQ(game.GetRules().begin()->GetEffect(), ObjectType::YOU); 197 | 198 | game.RemoveRule(id); 199 | EXPECT_FALSE(game.At(1, 1)[0]->HasProperty(PropertyType::YOU)); 200 | EXPECT_EQ(game.GetRules().size(), 0u); 201 | } 202 | 203 | TEST(GameTest, checkGameOver) 204 | { 205 | Game game(10, 10); 206 | 207 | game.Put(1, 1).SetType(ObjectType::BABA); 208 | 209 | game.AddRule(ObjectType::KEKE, ObjectType::IS, ObjectType::YOU); 210 | 211 | game.Update(); 212 | EXPECT_EQ(game.GetGameResult(), GameResult::DEFEAT); 213 | } 214 | 215 | TEST(GameTest, determineResult_Push) 216 | { 217 | Game game(10, 10); 218 | 219 | game.Put(5, 5).SetType(ObjectType::BABA); 220 | game.Put(4, 6).SetType(ObjectType::BABA).SetText(true); 221 | game.Put(5, 6).SetType(ObjectType::IS); 222 | game.Put(6, 6).SetType(ObjectType::YOU); 223 | 224 | game.Update(Action::STAY); 225 | EXPECT_EQ(game.GetGameResult(), GameResult::INVALID); 226 | 227 | game.Update(Action::DOWN); 228 | EXPECT_EQ(game.GetGameResult(), GameResult::DEFEAT); 229 | } 230 | 231 | TEST(GameTest, determineResult_Priority) 232 | { 233 | Game game(10, 10); 234 | 235 | game.Put(5, 5).SetType(ObjectType::BABA); 236 | game.Put(5, 5).SetType(ObjectType::FLAG); 237 | game.Put(5, 6).SetType(ObjectType::FLAG); 238 | game.Put(4, 6).SetType(ObjectType::BABA).SetText(true); 239 | game.Put(5, 6).SetType(ObjectType::IS); 240 | game.Put(6, 6).SetType(ObjectType::YOU); 241 | 242 | game.AddBaseRule(ObjectType::FLAG, ObjectType::IS, ObjectType::WIN); 243 | 244 | game.Update(Action::STAY); 245 | EXPECT_EQ(game.GetGameResult(), GameResult::WIN); 246 | 247 | game.Update(Action::DOWN); 248 | EXPECT_EQ(game.GetGameResult(), GameResult::DEFEAT); 249 | } 250 | 251 | TEST(GameTest, MoveObject) 252 | { 253 | Game game(10, 10); 254 | 255 | Object& obj = game.Put(5, 5).SetType(ObjectType::BABA); 256 | 257 | game.MoveObjects({ &obj }, Direction::DOWN); 258 | EXPECT_EQ(std::get<0>(game.GetPositionByObject(obj)), 5); 259 | EXPECT_EQ(std::get<1>(game.GetPositionByObject(obj)), 6); 260 | 261 | game.MoveObjects({ &obj }, Direction::LEFT); 262 | EXPECT_EQ(std::get<0>(game.GetPositionByObject(obj)), 4); 263 | EXPECT_EQ(std::get<1>(game.GetPositionByObject(obj)), 6); 264 | 265 | game.MoveObjects({ &obj }, Direction::UP); 266 | EXPECT_EQ(std::get<0>(game.GetPositionByObject(obj)), 4); 267 | EXPECT_EQ(std::get<1>(game.GetPositionByObject(obj)), 5); 268 | 269 | game.MoveObjects({ &obj }, Direction::RIGHT); 270 | EXPECT_EQ(std::get<0>(game.GetPositionByObject(obj)), 5); 271 | EXPECT_EQ(std::get<1>(game.GetPositionByObject(obj)), 5); 272 | EXPECT_EQ(obj.GetDirection(), Direction::RIGHT); 273 | 274 | EXPECT_ANY_THROW(game.MoveObjects({ &obj }, Direction::INVALID)); 275 | } -------------------------------------------------------------------------------- /Sources/Baba/Game/Game.cc: -------------------------------------------------------------------------------- 1 | // Copyright(c) 2019 Junyeong Park, Hyeonsu Kim 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | 10 | namespace Baba 11 | { 12 | Game::Game(std::size_t width, std::size_t height) 13 | : width_(width), height_(height), map_(width * height), ruleMap_(width * height) 14 | { 15 | AddBaseRule(ObjectType::TEXT, ObjectType::IS, ObjectType::PUSH); 16 | AddBaseRule(ObjectType::TEXT, ObjectType::IS, ObjectType::WORD); 17 | } 18 | 19 | Game::~Game() 20 | { 21 | for (auto& obj : objects_) 22 | { 23 | delete obj; 24 | } 25 | objects_.clear(); 26 | } 27 | 28 | std::size_t Game::GetWidth() const 29 | { 30 | return width_; 31 | } 32 | 33 | std::size_t Game::GetHeight() const 34 | { 35 | return height_; 36 | } 37 | 38 | const Object::Arr& Game::At(std::size_t x, std::size_t y) const 39 | { 40 | return map_[pt2idx(x, y)]; 41 | } 42 | 43 | bool Game::AtRule(std::size_t x, std::size_t y) const 44 | { 45 | return ruleMap_[pt2idx(x, y)]; 46 | } 47 | 48 | Object& Game::Put(std::size_t x, std::size_t y) 49 | { 50 | objects_.emplace_back(new Object); 51 | map_[pt2idx(x, y)].emplace_back(objects_.back()); 52 | 53 | return *map_[pt2idx(x, y)].back(); 54 | } 55 | 56 | void Game::DestroyObject(Object& object) 57 | { 58 | for (auto& objs : map_) 59 | { 60 | for (auto obj = objs.begin(); obj != objs.end(); ++obj) 61 | { 62 | if (**obj == object) 63 | { 64 | (*obj)->Destroy(); 65 | objs.erase(obj); 66 | return; 67 | } 68 | } 69 | } 70 | } 71 | 72 | Object::Arr Game::FindObjects(std::function func, 73 | bool excludeText) const 74 | { 75 | Object::Arr result; 76 | 77 | for (auto& objs : map_) 78 | { 79 | for (auto& obj : objs) 80 | { 81 | if (func(*obj)) 82 | { 83 | if (!excludeText || !obj->IsText()) 84 | { 85 | result.emplace_back(obj); 86 | } 87 | } 88 | } 89 | } 90 | 91 | return result; 92 | } 93 | 94 | Object::Arr Game::FindObjectsByType(ObjectType type, bool excludeText) const 95 | { 96 | std::function func; 97 | 98 | if (type == ObjectType::TEXT) 99 | { 100 | func = [](const Object& obj) { return obj.IsText(); }; 101 | excludeText = false; 102 | } 103 | else 104 | { 105 | func = [type](const Object& obj) { return obj.GetType() == type; }; 106 | } 107 | 108 | return FindObjects(func, excludeText); 109 | } 110 | 111 | Object::Arr Game::FindObjectsByProperty(PropertyType property, 112 | bool excludeText) const 113 | { 114 | return FindObjects( 115 | [property](const Object& obj) { return obj.HasProperty(property); }, 116 | excludeText); 117 | } 118 | 119 | Object::Arr Game::FindObjectsByPosition(const Object& target, 120 | bool excludeText) const 121 | { 122 | for (auto& objs : map_) 123 | { 124 | for (auto& obj : objs) 125 | { 126 | if (*obj == target) 127 | { 128 | if (excludeText) 129 | { 130 | Object::Arr arr; 131 | 132 | for (auto& o : objs) 133 | { 134 | if (!o->IsText()) 135 | { 136 | arr.emplace_back(o); 137 | } 138 | } 139 | 140 | return arr; 141 | } 142 | else 143 | { 144 | return objs; 145 | } 146 | } 147 | } 148 | } 149 | 150 | return Object::Arr(); 151 | } 152 | 153 | Object::Arr Game::FilterObjectByFunction( 154 | const Object::Arr& objects, std::function func) const 155 | { 156 | Object::Arr result; 157 | 158 | for (auto& obj : objects) 159 | { 160 | if (func(*obj)) 161 | { 162 | result.emplace_back(obj); 163 | } 164 | } 165 | 166 | return result; 167 | } 168 | 169 | const Game::Point Game::GetPositionByObject(const Object& target) const 170 | { 171 | for (std::size_t y = 0; y < GetHeight(); y++) 172 | { 173 | for (std::size_t x = 0; x < GetWidth(); x++) 174 | { 175 | const auto& objs = map_[pt2idx(x, y)]; 176 | 177 | for (auto& obj : objs) 178 | { 179 | if (*obj == target) 180 | { 181 | return { x, y }; 182 | } 183 | } 184 | } 185 | } 186 | 187 | throw std::runtime_error("Invalid target"); 188 | } 189 | 190 | bool Game::ValidatePosition(std::size_t x, std::size_t y) const 191 | { 192 | return x < width_ && y < height_; 193 | } 194 | 195 | void Game::Update(Action action) 196 | { 197 | gameResult_ = GameResult::INVALID; 198 | nowAction_ = action; 199 | 200 | applyRules(baseRules_); 201 | parseRules(); 202 | applyRules(); 203 | 204 | parseRules(); 205 | applyRules(rules_, false); 206 | 207 | determineResult(); 208 | } 209 | 210 | GameResult Game::GetGameResult() const 211 | { 212 | return gameResult_; 213 | } 214 | 215 | std::int64_t Game::AddRule(ObjectType target, ObjectType verb, 216 | ObjectType effect) 217 | { 218 | rules_.emplace(target, verb, effect); 219 | 220 | return Rule::CalcRuleID(target, verb, effect); 221 | } 222 | 223 | std::int64_t Game::AddBaseRule(ObjectType target, ObjectType verb, 224 | ObjectType effect) 225 | { 226 | baseRules_.emplace(target, verb, effect); 227 | 228 | return Rule::CalcRuleID(target, verb, effect); 229 | } 230 | 231 | void Game::RemoveRule(std::int64_t id) 232 | { 233 | auto it = 234 | std::find_if(rules_.begin(), rules_.end(), 235 | [id](const Rule& rule) { return rule.GetRuleID() == id; }); 236 | 237 | if (it != rules_.end()) 238 | { 239 | auto& rule = *it; 240 | auto targets = FindObjectsByType(rule.GetTarget(), true); 241 | 242 | if (IsPropertyType(rule.GetEffect())) 243 | { 244 | for (auto& target : targets) 245 | { 246 | target->RemoveProperty(ObjectToProperty(rule.GetEffect())); 247 | } 248 | } 249 | it = rules_.erase(it); 250 | } 251 | } 252 | 253 | const std::set& Game::GetRules() const 254 | { 255 | return rules_; 256 | } 257 | 258 | void Game::parseRules() 259 | { 260 | std::fill(ruleMap_.begin(), ruleMap_.end(), false); 261 | 262 | while (!rules_.empty()) 263 | { 264 | RemoveRule(rules_.begin()->GetRuleID()); 265 | } 266 | 267 | auto verbs = FindObjects([](const Object& obj) { 268 | return IsVerbType(obj.GetType()) && obj.HasProperty(PropertyType::WORD); 269 | }); 270 | 271 | for (auto& verb : verbs) 272 | { 273 | auto [x, y] = GetPositionByObject(*verb); 274 | 275 | const auto addRules = [&, x = x, y = y](std::size_t dx, 276 | std::size_t dy) { 277 | if (ValidatePosition(x - dx, y - dy) && 278 | ValidatePosition(x + dx, y + dy)) 279 | { 280 | auto targets = FilterObjectByFunction( 281 | At(x - dx, y - dy), [](const Object& obj) { 282 | return obj.HasProperty(PropertyType::WORD); 283 | }); 284 | auto effects = FilterObjectByFunction( 285 | At(x + dx, y + dy), [](const Object& obj) { 286 | return obj.HasProperty(PropertyType::WORD); 287 | }); 288 | 289 | for (auto& target : targets) 290 | { 291 | for (auto& effect : effects) 292 | { 293 | AddRule(target->GetType(), verb->GetType(), 294 | effect->GetType()); 295 | } 296 | } 297 | 298 | bool hasRule = (targets.size() > 0 && effects.size() > 0); 299 | ruleMap_[pt2idx(x - dx, y - dy)] = 300 | ruleMap_[pt2idx(x - dx, y - dy)] | hasRule; 301 | ruleMap_[pt2idx(x + dx, y + dy)] = 302 | ruleMap_[pt2idx(x + dx, y + dy)] | hasRule; 303 | ruleMap_[pt2idx(x, y)] = ruleMap_[pt2idx(x, y)] | hasRule; 304 | } 305 | }; 306 | 307 | addRules(1, 0); 308 | addRules(0, 1); 309 | } 310 | } 311 | 312 | void Game::applyRules() 313 | { 314 | applyRules(rules_); 315 | } 316 | 317 | void Game::applyRules(std::set& r, bool doFunc) 318 | { 319 | auto& effects = Effects::GetInstance().GetEffects(); 320 | 321 | for (auto& rule : r) 322 | { 323 | if (rule.GetVerb() == ObjectType::IS) 324 | { 325 | auto targets = FindObjectsByType(rule.GetTarget(), true); 326 | 327 | if (IsObjectType(rule.GetEffect())) 328 | { 329 | for (auto& target : targets) 330 | { 331 | target->SetType(rule.GetEffect()); 332 | } 333 | } 334 | else 335 | { 336 | auto func = effects.at(ObjectToProperty(rule.GetEffect())); 337 | 338 | for (auto& target : targets) 339 | { 340 | target->AddProperty(ObjectToProperty(rule.GetEffect())); 341 | if (doFunc) 342 | { 343 | func(*this, *target); 344 | } 345 | } 346 | } 347 | } 348 | // else if (rule.GetVerb() == ObjectType::HAS) 349 | //{ 350 | // // Not implemented yet 351 | //} 352 | // else if (rule.GetVerb() == ObjectType::MAKE) 353 | //{ 354 | // // Not implemented yet 355 | //} 356 | // else 357 | //{ 358 | // // throw 359 | //} 360 | } 361 | } 362 | 363 | void Game::determineResult() 364 | { 365 | auto targets = FindObjectsByProperty(PropertyType::YOU); 366 | 367 | if (targets.empty()) 368 | { 369 | gameResult_ = GameResult::DEFEAT; 370 | return; 371 | } 372 | 373 | for (auto& target : targets) 374 | { 375 | auto objs = FindObjectsByPosition(*target); 376 | 377 | for (auto& obj : objs) 378 | { 379 | if (obj->HasProperty(PropertyType::WIN)) 380 | { 381 | gameResult_ = GameResult::WIN; 382 | return; 383 | } 384 | } 385 | } 386 | 387 | gameResult_ = GameResult::INVALID; 388 | } 389 | 390 | Object::Arr Game::TieStuckMoveableObjects(Object& pusher, Direction dir) const 391 | { 392 | Object::Arr result; 393 | result.push_back(&pusher); 394 | 395 | auto [dx, dy] = dir2Vec(dir); 396 | auto pos = GetPositionByObject(pusher); 397 | std::size_t x = std::get<0>(pos); 398 | std::size_t y = std::get<1>(pos); 399 | 400 | while (ValidatePosition(x += dx, y += dy)) 401 | { 402 | auto objs = At(x, y); 403 | 404 | if (objs.empty()) 405 | { 406 | break; 407 | } 408 | 409 | if (!FilterObjectByFunction(objs, 410 | [](const Object& obj) -> bool { 411 | return obj.HasProperty( 412 | PropertyType::STOP); 413 | }) 414 | .empty()) 415 | { 416 | return Object::Arr(); 417 | } 418 | 419 | auto filtered = 420 | FilterObjectByFunction(objs, [](const Object& obj) -> bool { 421 | return obj.HasProperty(PropertyType::PUSH); 422 | }); 423 | 424 | if (filtered.empty()) 425 | { 426 | break; 427 | } 428 | 429 | result.insert(result.begin(), filtered.begin(), filtered.end()); 430 | } 431 | 432 | return ValidatePosition(x, y) ? result : Object::Arr(); 433 | } 434 | 435 | void Game::MoveObjects(const Object::Arr& objects, Direction dir) 436 | { 437 | for (auto& obj : objects) 438 | { 439 | auto [dx, dy] = dir2Vec(dir); 440 | auto [x, y] = GetPositionByObject(*obj); 441 | auto& box = map_[pt2idx(x, y)]; 442 | 443 | box.erase(std::find(box.begin(), box.end(), obj)); 444 | 445 | map_[pt2idx(x + dx, y + dy)].push_back(obj); 446 | obj->SetDirection(dir); 447 | } 448 | } 449 | 450 | Action Game::GetNowAction() const 451 | { 452 | return nowAction_; 453 | } 454 | 455 | Game::Point Game::dir2Vec(Direction dir) const 456 | { 457 | switch (dir) 458 | { 459 | case Direction::UP: 460 | return Game::Point(0, -1); 461 | case Direction::DOWN: 462 | return Game::Point(0, 1); 463 | case Direction::LEFT: 464 | return Game::Point(-1, 0); 465 | case Direction::RIGHT: 466 | return Game::Point(1, 0); 467 | default: 468 | throw std::runtime_error("Invalid Direction"); 469 | } 470 | } 471 | 472 | std::size_t Game::pt2idx(std::size_t x, std::size_t y) const 473 | { 474 | return x + y * width_; 475 | } 476 | } // namespace Baba 477 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------