Package: catanatron
CatanatronSettlers of Catan Bot and Bot Simulator. Test out bot strategies at scale (thousands of games per minutes). The goal of this project is to find the strongest Settlers of Catan bot possible.See the motivation of the project here:5 Ways NOT to Build a Catan AI.InstallationClone this repository and install dependencies. This will include the Catanatron bot implementation and thecatanatron-playsimulator.git clone git@github.com:bcollazo/catanatron.git
cd catanatron/Create a virtual environment with Python3.8 or higher. Then:pip install -r dev-requirements.txt
pip install -e catanatron_core
pip install -e catanatron_server
pip install -e catanatron_gym
pip install -e catanatron_experimentalUsageRun simulations and generate datasets via the CLI:catanatron-play --players=R,R,R,W --num=100See more information withcatanatron-play --help.Try Your Own BotsImplement your own bots by creating a file (e.g.myplayers.py) with somePlayerimplementations:fromcatanatronimportPlayerfromcatanatron_experimental.cli.cli_playersimportregister_player@register_player("FOO")classFooPlayer(Player):defdecide(self,game,playable_actions):"""Should return one of the playable_actions.Args:game (Game): complete game state. read-only.playable_actions (Iterable[Action]): options to choose fromReturn:action (Action): Chosen element of playable_actions"""# ===== YOUR CODE HERE =====# As an example we simply return the first action:returnplayable_actions[0]# ===== END YOUR CODE =====Run it by passing the source code tocatanatron-play:catanatron-play --code=myplayers.py --players=R,R,R,FOO --num=10How to Make Catanatron Stronger?The best bot right now is Alpha Beta Search with a hand-crafted value function. One of the most promising ways of improving Catanatron
is to copy the code from (minimax.py) to yourmyplayers.pyand tweak the weights of the value function. You can
also come up with your own innovative features!For more sophisticated approaches, see example player implementations incatanatron_core/catanatron/playersIf you find a bot that consistently beats the best bot right now, please submit a Pull Request! :)Advanced UsageInspecting Games (Browser UI)We provide adocker-compose.ymlwith everything needed to watch games (useful for debugging). It contains all the web-server infrastructure needed to render a game in a browser.To use, ensure you haveDocker Composeinstalled, and run (from this repo's root):docker-compose upYou can now use the--dbflag to make the catanatron-play simulator save
the game in the database for inspection via the web server.catanatron-play --players=W,W,W,W --db --num=1NOTE: A great contribution would be to make the Web UI allow to step forwards and backwards in a game to inspect it (ala chess.com).AccumulatorsTheAccumulatorclass allows you to hook into important events during simulations.For example, write a file likemycode.pyand have:fromcatanatronimportActionTypefromcatanatron_experimentalimportSimulationAccumulator,register_accumulator@register_accumulatorclassPortTradeCounter(SimulationAccumulator):defbefore_all(self):self.num_trades=0defstep(self,game_before_action,action):ifaction.action_type==ActionType.MARITIME_TRADE:self.num_trades+=1defafter_all(self):print(f'There were{self.num_trades}port trades!')Thencatanatron-play --code=mycode.pywill count the number of trades in all simulations.As a Package / LibraryYou can also usecatanatronpackage directly which provides a core
implementation of the Settlers of Catan game logic.fromcatanatronimportGame,RandomPlayer,Color# Play a simple 4v4 gameplayers=[RandomPlayer(Color.RED),RandomPlayer(Color.BLUE),RandomPlayer(Color.WHITE),RandomPlayer(Color.ORANGE),]game=Game(players)print(game.play())# returns winning colorYou can use theopen_linkhelper function to open up the game (useful for debugging):fromcatanatron_server.utilsimportopen_linkopen_link(game)# opens game in browserArchitectureThe code is divided in the following 5 components (folders):catanatron: A pure python implementation of the game logic. Usesnetworkxfor fast graph operations. Is pip-installable (seesetup.py) and can be used as a Python package. See the documentation for the package here:https://catanatron.readthedocs.io/.catanatron_server: Contains a Flask web server in order to serve
game states from a database to a Web UI. The idea of using a database, is to ease watching games played in a different process. It defaults to using an ephemeral in-memory sqlite database. Also pip-installable (not publised in PyPi however).catanatron_gym: OpenAI Gym interface to Catan. Includes a 1v1 environment against a Random Bot and a vector-friendly representations of states and actions. This can be pip-installed independently withpip install catanatron_gym, for more information seecatanatron_gym/README.md.catantron_experimental: A collection of unorganized scripts with contain many failed attempts at finding the best possible bot. Its ok to break these scripts. Its pip-installable. Exposes acatanatron-playcommand-line script that can be used to play games in bulk, create machine learning datasets of games, and more!ui: A React web UI to render games. This is helpful for debugging the core implementation. We decided to use the browser as a randering engine (as opposed to the terminal or a desktop GUI) because of HTML/CSS's ubiquitousness and the ability to use modern animation libraries in the future (https://www.framer.com/motion/orhttps://www.react-spring.io/).AI Bots LeaderboardCatanatron will always be the best bot in this leaderboard.The best bot right now isAlphaBetaPlayerwith n = 2. Here a list of bots strength. Experiments
done by running 1000 (when possible) 1v1 games against previous in list.Player% of wins in 1v1 gamesnum games used for resultAlphaBeta(n=2)80% vs ValueFunction25ValueFunction90% vs GreedyPlayouts(n=25)25GreedyPlayouts(n=25)100% vs MCTS(n=100)25MCTS(n=100)60% vs WeightedRandom15WeightedRandom53% vs WeightedRandom1000VictoryPoint60% vs Random1000Random--Developing for CatanatronTo develop for Catanatron core logic you can use the following test suite:coverage run --source=catanatron -m pytest tests/ && coverage reportOr you can run the suite in watch-mode with:ptw --ignore=tests/integration_tests/ --nobeepMachine LearningGenerate data (several GZIP CSVs of features) by running:catanatron-play --num=100 --outpath=my-data-path/You can then use this data to build a machine learning model, and then
implement aPlayersubclass that implements the corresponding "predict"
step of your model. There are some attempts of these type of
players inreinforcement.py.AppendixRunning Components IndividuallyAs an alternative to running the project with Docker, you can run the following 3 components: a React UI, a Flask Web Server, and a PostgreSQL database in three separate Terminal tabs.React UIcd ui/
npm install
npm startThis can also be run via Docker independetly like (after building):docker build -t bcollazo/catanatron-react-ui:latest ui/
docker run -it -p 3000:3000 bcollazo/catanatron-react-uiFlask Web ServerEnsure you are inside a virtual environment with all dependencies installed and
useflask run.python3.8 -m venv venv
source ./venv/bin/activate
pip install -r requirements.txt
flask runThis can also be run via Docker independetly like (after building):docker build -t bcollazo/catanatron-server:latest . -f Dockerfile.web
docker run -it -p 5000:5000 bcollazo/catanatron-serverPostgreSQL DatabaseMake sure you havedocker-composeinstalled (https://docs.docker.com/compose/install/).docker-compose upOr run any other database deployment (locally or in the cloud).Other Useful CommandsTensorBoardFor watching training progress, usekeras.callbacks.TensorBoardand open TensorBoard:tensorboard --logdir logsDocker GPU TensorFlowdocker run -it tensorflow/tensorflow:latest-gpu-jupyter bash
docker run -it --rm -v $(realpath ./notebooks):/tf/notebooks -p 8888:8888 tensorflow/tensorflow:latest-gpu-jupyterTesting Performancepython -m cProfile -o profile.pstats catanatron_experimental/catanatron_experimental/play.py --num=5
snakeviz profile.pstatspytest --benchmark-compare=0001 --benchmark-compare-fail=mean:10% --benchmark-columns=min,max,mean,stddevHead Large Datasets with PandasIn [1]: import pandas as pd
In [2]: x = pd.read_csv("data/mcts-playouts-labeling-2/labels.csv.gzip", compression="gzip", iterator=True)
In [3]: x.get_chunk(10)Publishing to PyPicatanatron Packagemake build PACKAGE=catanatron_core
make upload PACKAGE=catanatron_core
make upload-production PACKAGE=catanatron_corecatanatron_gym Packagemake build PACKAGE=catanatron_gym
make upload PACKAGE=catanatron_gym
make upload-production PACKAGE=catanatron_gymBuilding Docssphinx-quickstart docs
sphinx-apidoc -o docs/source catanatron
sphinx-build -b html docs/source/ docs/build/htmlContributingI am new to Open Source Development, so open to suggestions on this section. The best contributions would be to make the core bot stronger.Other than that here is also a list of ideas:Improvecatanatronpackage running time performance.Continue refactoring the State to be more and more like a primitivedictorarray.
(Copies are much faster if State is just a native python object).Move RESOURCE to be ints. Pythonenumsturned out to be slow for hashing and using.Move .actions to a Game concept. (to avoid copying when copying State)Remove .current_prompt. It seems its redundant with (is_moving_knight, etc...) and not needed.Improve AlphaBetaPlayer:Explore and improve prunningUse Bayesian Methods or SPSA to tune weights and find better ones.Experiment ideas:DQN Render Method. Use models/mbs=64__1619973412.model. Try to understand it.DQN Two Layer Algo. With Simple Action Space.Simple Alpha GoTry Tensorforce with simple action space.Try simple flat CSV approach but with AlphaBeta-generated games.Visualize tree with graphviz. With colors per maximizing/minimizing.Create simple entry-point notebook for this project. Runnable via Paperspace. (might be hard because catanatron requires Python 3.8 and I haven't seen a GPU-enabled tensorflow+jupyter+pyhon3.8 Docker Image out there).Bugs:Shouldn't be able to use dev card just bought.Features:Continue implementing actions from the UI (not all implemented).Chess.com-like UI for watching game replays (with Play/Pause and Back/Forward).A terminal UI? (for ease of debugging)