├── gui ├── screenshots │ └── 00.png ├── client │ ├── assets │ │ ├── blupig.jpg │ │ ├── yl-v4-main.css │ │ ├── js.cookie.js │ │ └── bootstrap.min.js │ └── index.html └── server │ ├── package.json │ └── index.js ├── docker-start.sh ├── .gitignore ├── docker-nginx.conf ├── .travis.yml ├── Dockerfile ├── tests ├── gtest_main.cc ├── gtest_ai_negamax.cc └── gtest_ai_eval.cc ├── src ├── utils │ └── globals.cc ├── main │ └── main.cc ├── ai │ ├── utils.cc │ ├── ai_controller.cc │ ├── eval.cc │ └── negamax.cc ├── api │ └── renju_api.cc └── protocols │ ├── gomocup.cc │ └── cli.cc ├── include ├── utils │ └── globals.h ├── ai │ ├── ai_controller.h │ ├── utils.h │ ├── negamax.h │ └── eval.h ├── protocols │ ├── gomocup.h │ └── cli.h └── api │ └── renju_api.h ├── README.md ├── CMakeLists.txt └── LICENSE /gui/screenshots/00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yunzhu-li/blupig-gomoku/master/gui/screenshots/00.png -------------------------------------------------------------------------------- /gui/client/assets/blupig.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yunzhu-li/blupig-gomoku/master/gui/client/assets/blupig.jpg -------------------------------------------------------------------------------- /gui/server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "blupig-gomoku-server", 3 | "version": "0.0.4", 4 | "scripts": { 5 | "start": "node ." 6 | }, 7 | "dependencies": { 8 | "cors": "^2.8.5", 9 | "express": "^4.18.2" 10 | }, 11 | "license": "GPL-3.0" 12 | } 13 | -------------------------------------------------------------------------------- /docker-start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -euo pipefail 3 | 4 | # Replace server uri and path 5 | sed -i "s|var api_base_url.*|var api_base_url = '$SERVER_URI';|" /app/gui/client/index.html 6 | 7 | # Start nginx daemon 8 | nginx 9 | 10 | # Start node server 11 | cd /app/gui/server 12 | exec npm start 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | *.smod 19 | 20 | # Compiled Static libraries 21 | *.lai 22 | *.la 23 | *.a 24 | *.lib 25 | 26 | # Executables 27 | *.exe 28 | *.out 29 | *.app 30 | /build/ 31 | 32 | # IDE 33 | /.idea/ 34 | 35 | # Node modules 36 | /gui/server/node_modules/ 37 | 38 | # macOS 39 | .DS_Store 40 | -------------------------------------------------------------------------------- /docker-nginx.conf: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes auto; 3 | pid /run/nginx.pid; 4 | 5 | events { 6 | worker_connections 1024; 7 | } 8 | 9 | http { 10 | include /etc/nginx/mime.types; 11 | default_type application/octet-stream; 12 | 13 | sendfile on; 14 | server_tokens off; 15 | 16 | access_log off; 17 | error_log /dev/stderr; 18 | 19 | server { 20 | listen 8000; 21 | server_name _; 22 | 23 | # HTML client 24 | location / { 25 | root /app/gui/client; 26 | index index.html; 27 | } 28 | 29 | # API 30 | location ~ ^/(status|move)$ { 31 | proxy_pass http://127.0.0.1:8001; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | notifications: 2 | email: false 3 | 4 | os: 5 | - linux 6 | # - osx 7 | 8 | language: cpp 9 | 10 | compiler: 11 | - clang 12 | - gcc 13 | 14 | install: 15 | - if [ "$CXX" = "g++" ] && [ "$TRAVIS_OS_NAME" = "linux" ]; then export CXX="g++-7" CC="gcc-7"; fi 16 | - if [ "$CXX" = "clang++" ] && [ "$TRAVIS_OS_NAME" = "linux" ]; then export CXX="clang++-5.0" CC="clang-5.0"; fi 17 | 18 | addons: 19 | apt: 20 | sources: 21 | - ubuntu-toolchain-r-test 22 | - llvm-toolchain-trusty-5.0 23 | packages: 24 | - gcc-7 25 | - g++-7 26 | - clang-5.0 27 | 28 | script: 29 | - mkdir build 30 | - cd build 31 | - cmake .. -DCMAKE_BUILD_TYPE=Debug -DENABLE_TESTING=YES 32 | - make 33 | - ./gomoku test 34 | - ./gomoku_test 35 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Build container 2 | FROM alpine 3 | 4 | # Copy code 5 | COPY . /app 6 | 7 | # Install packages and build program then remove building toolchain 8 | RUN apk --no-cache add nginx alpine-sdk cmake bash && \ 9 | mkdir /app/build && \ 10 | cd /app/build && \ 11 | cmake .. && \ 12 | make install && \ 13 | apk del --no-cache alpine-sdk cmake 14 | 15 | # Runtime container 16 | FROM node:16-alpine 17 | 18 | # Copy code & configuration 19 | COPY . /app 20 | COPY docker-nginx.conf /etc/nginx/nginx.conf 21 | 22 | # Copy built binary from build container 23 | COPY --from=0 /app/build/gomoku /bin/gomoku 24 | 25 | # Install nginx 26 | RUN apk --no-cache add nginx 27 | 28 | # Install node.js dependencies 29 | RUN cd /app/gui/server && npm install 30 | 31 | # nginx listens on 8000 32 | EXPOSE 8000 33 | 34 | # Set command 35 | CMD ["/app/docker-start.sh"] 36 | -------------------------------------------------------------------------------- /tests/gtest_main.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | 21 | int main(int argc, char** argv) { 22 | testing::InitGoogleTest(&argc, argv); 23 | return RUN_ALL_TESTS(); 24 | } 25 | -------------------------------------------------------------------------------- /src/utils/globals.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | 21 | int g_board_size = 19; 22 | unsigned int g_gs_size = 361; 23 | unsigned int g_node_count = 0; 24 | unsigned int g_eval_count = 0; 25 | unsigned int g_pm_count = 0; 26 | unsigned int g_cc_0 = 0; 27 | unsigned int g_cc_1 = 0; 28 | -------------------------------------------------------------------------------- /include/utils/globals.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_UTILS_GLOBALS_H_ 20 | #define INCLUDE_UTILS_GLOBALS_H_ 21 | 22 | #include 23 | 24 | extern int g_board_size; 25 | extern unsigned int g_gs_size; 26 | extern unsigned int g_node_count; 27 | extern unsigned int g_eval_count; 28 | extern unsigned int g_pm_count; 29 | extern unsigned int g_cc_0; 30 | extern unsigned int g_cc_1; 31 | 32 | #endif // INCLUDE_UTILS_GLOBALS_H_ 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | blupig-gomoku 2 | ------ 3 | 4 | ![blupig](gui/client/assets/blupig.jpg "blupig") 5 | 6 | [![Build Status](https://travis-ci.org/yunzhu-li/blupig-gomoku.svg?branch=master)](https://travis-ci.org/yunzhu-li/blupig-gomoku) 7 | 8 | A Gomoku (五子棋, Five in a Row) AI with a custom `heuristic negamax` algorithm with `alpha-beta pruning` and built-in rules and cut-offs, written in `C++`. 9 | 10 | It provides: 11 | - A REST API (used by the [HTML client](gui)) 12 | - A CLI interface 13 | - The stdin / stdout based [protocol](http://petr.lastovicka.sweb.cz/protocl2en.htm) used in Gomocup 14 | 15 | Currently runs single-threaded, supports only `Gomoku` rules, future plans: 16 | - MCTS with parallelization 17 | - Self-learning 18 | 19 | A live demo is hosted on: https://apps.yunzhu.li/gomoku 20 | 21 | ![Alt text](gui/screenshots/00.png?raw=true "Screenshot") 22 | 23 | Run Your Own Copy 24 | ----- 25 | This application is available as a docker image `yunzhu/blupig-gomoku`. 26 | 27 | - Make sure you have access to `docker`. 28 | 29 | - Run: 30 | ``` 31 | docker run -d --rm -p 8000:8000 -e SERVER_URI="http://:8000" yunzhu/gomoku 32 | ``` 33 | 34 | - Access `http://:8000` in your browser. 35 | 36 | - Play! 37 | -------------------------------------------------------------------------------- /include/ai/ai_controller.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_AI_AI_CONTROLLER_H_ 20 | #define INCLUDE_AI_AI_CONTROLLER_H_ 21 | 22 | class RenjuAIController { 23 | public: 24 | RenjuAIController(); 25 | ~RenjuAIController(); 26 | 27 | static void generateMove(const char *gs, int player, int search_depth, int time_limit, 28 | int *actual_depth, int *move_r, int *move_c, int *winning_player, 29 | unsigned int *node_count, unsigned int *eval_count, unsigned int *pm_count); 30 | }; 31 | 32 | #endif // INCLUDE_AI_AI_CONTROLLER_H_ 33 | -------------------------------------------------------------------------------- /include/protocols/gomocup.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_PROTOCOLS_GOMOCUP_H_ 20 | #define INCLUDE_PROTOCOLS_GOMOCUP_H_ 21 | 22 | #include 23 | 24 | class RenjuProtocolGomocup { 25 | public: 26 | RenjuProtocolGomocup(); 27 | ~RenjuProtocolGomocup(); 28 | 29 | static bool beginSession(int argc, char const *argv[]); 30 | 31 | private: 32 | static void performAndWriteMove(char *gs_string, int time_limit); 33 | static void splitLine(const char *line, int *output); 34 | static void writeStdout(std::string str); 35 | }; 36 | 37 | #endif // INCLUDE_PROTOCOLS_GOMOCUP_H_ 38 | -------------------------------------------------------------------------------- /src/main/main.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | // Exclude main() if building with tests 24 | #ifndef BLUPIG_TEST 25 | 26 | int main(int argc, char const *argv[]) { 27 | if (argc <= 0) return 1; 28 | 29 | // Select Gomocup protocol if "pbrain' found in file name 30 | bool success; 31 | if (strstr(argv[0], "pbrain") != nullptr) { 32 | success = RenjuProtocolGomocup::beginSession(argc, argv); 33 | } else { 34 | success = RenjuProtocolCLI::beginSession(argc, argv); 35 | } 36 | return !success; 37 | } 38 | 39 | #endif // BLUPIG_TEST 40 | -------------------------------------------------------------------------------- /include/api/renju_api.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_API_RENJU_API_H_ 20 | #define INCLUDE_API_RENJU_API_H_ 21 | 22 | #include 23 | 24 | class RenjuAPI { 25 | public: 26 | RenjuAPI(); 27 | ~RenjuAPI(); 28 | 29 | // Generate move based on a given game state 30 | static bool generateMove(const char *gs_string, int ai_player_id, 31 | int search_depth, int time_limit, int num_threads, 32 | int *actual_depth, int *move_r, int *move_c, int *winning_player, 33 | unsigned int *node_count, unsigned int *eval_count, unsigned int *pm_count); 34 | 35 | // Convert a game state string to game state binary array 36 | static void gsFromString(const char *gs_string, char *gs); 37 | 38 | private: 39 | // Render game state into text 40 | static std::string renderGameState(const char *gs); 41 | }; 42 | 43 | #endif // INCLUDE_API_RENJU_API_H_ 44 | -------------------------------------------------------------------------------- /gui/server/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | var express = require('express'); 20 | var cors = require('cors'); 21 | var exec = require('child_process').exec; 22 | 23 | console.log('Start listening...'); 24 | start(); 25 | 26 | function start() { 27 | const corsOptions = { 28 | origin: 'https://apps.yunzhu.li', 29 | } 30 | 31 | var app = express(); 32 | app.use(cors()); 33 | 34 | app.get('/status', function (req, res) { 35 | res.send('ok'); 36 | }); 37 | 38 | // Compute move 39 | app.get('/move', function (req, res) { 40 | // Get query parameters 41 | var state = req.query.s; 42 | var player = req.query.p; 43 | 44 | // Build command 45 | var cmd = 'gomoku'; 46 | if (typeof state !== 'undefined' && state.length > 0) cmd += ' -s ' + state; 47 | if (typeof player !== 'undefined' && player.length > 0) cmd += ' -p ' + player; 48 | 49 | // Execute command 50 | exec(cmd, function(error, stdout, stderr) { 51 | // Write response 52 | res.write(stdout); 53 | res.end(); 54 | }); 55 | }); 56 | app.listen(8001); 57 | } 58 | -------------------------------------------------------------------------------- /include/protocols/cli.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_PROTOCOLS_CLI_H_ 20 | #define INCLUDE_PROTOCOLS_CLI_H_ 21 | 22 | #include 23 | #include 24 | 25 | class RenjuProtocolCLI { 26 | public: 27 | RenjuProtocolCLI(); 28 | ~RenjuProtocolCLI(); 29 | 30 | static bool beginSession(int argc, char const *argv[]); 31 | 32 | // Generate move and responds in json 33 | static std::string generateMove(const char *gs_string, int ai_player_id, int search_depth, 34 | int time_limit, int num_threads); 35 | 36 | private: 37 | // Validates a string and parses into an integer 38 | static bool parseIntegerArgument(const char *str, int max_length, int *result); 39 | 40 | // Validates a string and returns the length. 41 | // If fails validation, -1 is returned. 42 | static int validateString(const char *str, int max_length); 43 | 44 | // Generate json response 45 | static std::string generateResultJson(const std::unordered_map *data, 46 | const std::string &message); 47 | }; 48 | 49 | #endif // INCLUDE_PROTOCOLS_CLI_H_ 50 | -------------------------------------------------------------------------------- /src/ai/utils.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | bool RenjuAIUtils::remoteCell(const char *gs, int r, int c) { 23 | if (gs == nullptr) return false; 24 | for (int i = r - 2; i <= r + 2; ++i) { 25 | if (i < 0 || i >= g_board_size) continue; 26 | for (int j = c - 2; j <= c + 2; ++j) { 27 | if (j < 0 || j >= g_board_size) continue; 28 | if (gs[g_board_size * i + j] > 0) return false; 29 | } 30 | } 31 | return true; 32 | } 33 | 34 | void RenjuAIUtils::zobristInit(int size, uint64_t *z1, uint64_t *z2) { 35 | std::random_device rd; 36 | std::mt19937 gen(rd()); 37 | std::uniform_int_distribution d(0, UINT64_MAX); 38 | 39 | // Generate random values 40 | for (int i = 0; i < size; i++) { 41 | z1[i] = d(gen); 42 | z2[i] = d(gen); 43 | } 44 | } 45 | 46 | uint64_t RenjuAIUtils::zobristHash(const char *gs, int size, uint64_t *z1, uint64_t *z2) { 47 | uint64_t state = 0; 48 | for (int i = 0; i < size; i++) { 49 | if (gs[i] == 1) { 50 | state ^= z1[i]; 51 | } else if (gs[i] == 2) { 52 | state ^= z2[i]; 53 | } 54 | } 55 | return state; 56 | } 57 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # blupig 3 | # Copyright (C) 2016-2017 Yunzhu Li 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # any later version. 9 | 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | # 18 | 19 | cmake_minimum_required(VERSION 2.8) 20 | project(blupig) 21 | 22 | # Enable C++ 11 23 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") 24 | 25 | # Include header directories 26 | include_directories("include") 27 | include_directories("tests") 28 | 29 | # Add source files 30 | file(GLOB_RECURSE SRC "src/*.cc") 31 | file(GLOB_RECURSE SRC_TEST "tests/*.cc") 32 | 33 | # Set default build type to Release 34 | if(NOT CMAKE_BUILD_TYPE) 35 | set(CMAKE_BUILD_TYPE Release) 36 | endif(NOT CMAKE_BUILD_TYPE) 37 | 38 | # Main executable 39 | add_executable(gomoku ${SRC}) 40 | 41 | # Profiling executable 42 | if (ENABLE_PROFILING) 43 | set(CMAKE_BUILD_TYPE Debug) 44 | add_executable(gomoku_prof ${SRC}) 45 | set_target_properties(gomoku_prof PROPERTIES COMPILE_FLAGS "-pg") 46 | set_target_properties(gomoku_prof PROPERTIES LINK_FLAGS "-pg") 47 | endif() 48 | 49 | # Test executable 50 | if (ENABLE_TESTING) 51 | add_executable(gomoku_test ${SRC} ${SRC_TEST}) 52 | set_target_properties(gomoku_test PROPERTIES COMPILE_FLAGS "-D BLUPIG_TEST") 53 | find_package(Threads) 54 | target_link_libraries(gomoku_test ${CMAKE_THREAD_LIBS_INIT}) 55 | endif() 56 | 57 | # Allow installing using 'make install' 58 | install(TARGETS gomoku DESTINATION bin) 59 | -------------------------------------------------------------------------------- /include/ai/utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_AI_UTILS_H_ 20 | #define INCLUDE_AI_UTILS_H_ 21 | 22 | #include 23 | 24 | class RenjuAIUtils { 25 | public: 26 | RenjuAIUtils(); 27 | ~RenjuAIUtils(); 28 | 29 | static inline char getCell(const char *gs, int r, int c) { 30 | if (r < 0 || r >= g_board_size || c < 0 || c >= g_board_size) return -1; 31 | return gs[g_board_size * r + c]; 32 | } 33 | 34 | static inline bool setCell(char *gs, int r, int c, char value) { 35 | if (r < 0 || r >= g_board_size || c < 0 || c >= g_board_size) return false; 36 | gs[g_board_size * r + c] = value; 37 | return true; 38 | } 39 | 40 | static bool remoteCell(const char *gs, int r, int c); 41 | 42 | // Game state hashing 43 | static void zobristInit(int size, uint64_t *z1, uint64_t *z2); 44 | static uint64_t zobristHash(const char *gs, int size, uint64_t *z1, uint64_t *z2); 45 | static inline void zobristToggle(uint64_t *state, uint64_t *z1, uint64_t *z2, 46 | int row_size, int r, int c, int player) { 47 | if (player == 1) { 48 | *state ^= z1[row_size * r + c]; 49 | } else if (player == 2) { 50 | *state ^= z2[row_size * r + c]; 51 | } 52 | } 53 | 54 | }; 55 | 56 | #endif // INCLUDE_AI_UTILS_H_ 57 | -------------------------------------------------------------------------------- /include/ai/negamax.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_AI_NEGAMAX_H_ 20 | #define INCLUDE_AI_NEGAMAX_H_ 21 | 22 | #include 23 | 24 | class RenjuAINegamax { 25 | public: 26 | RenjuAINegamax(); 27 | ~RenjuAINegamax(); 28 | 29 | static void heuristicNegamax(const char *gs, int player, int depth, int time_limit, bool enable_ab_pruning, 30 | int *actual_depth, int *move_r, int *move_c); 31 | 32 | private: 33 | // Preset search breadth 34 | // From root to leaf, each element is for 2 layers 35 | // e.g. {10, 5, 2} -> 10, 10, 5, 5, 2, 2, 2, ... 36 | static int presetSearchBreadth[5]; 37 | 38 | // A move (candidate) 39 | struct Move { 40 | int r; 41 | int c; 42 | int heuristic_val; 43 | int actual_score; 44 | 45 | // Overloads < for sorting 46 | bool operator<(Move other) const { 47 | return heuristic_val > other.heuristic_val; 48 | } 49 | }; 50 | 51 | static int heuristicNegamax(char *gs, int player, int initial_depth, int depth, 52 | bool enable_ab_pruning, int alpha, int beta, 53 | int *move_r, int *move_c); 54 | 55 | // Search possible moves based on a given state, sorted by heuristic values. 56 | static void searchMovesOrdered(const char *gs, int player, std::vector *result); 57 | 58 | // Currently not used 59 | static int negamax(char *gs, int player, int depth, 60 | int *move_r, int *move_c); 61 | }; 62 | 63 | #endif // INCLUDE_AI_NEGAMAX_H_ 64 | -------------------------------------------------------------------------------- /src/api/renju_api.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | bool RenjuAPI::generateMove(const char *gs_string, int ai_player_id, 26 | int search_depth, int time_limit, int num_threads, 27 | int *actual_depth, int *move_r, int *move_c, int *winning_player, 28 | unsigned int *node_count, unsigned int *eval_count, unsigned int *pm_count) { 29 | // Check input data 30 | if (strlen(gs_string) != g_gs_size || 31 | ai_player_id < 1 || ai_player_id > 2 || 32 | search_depth == 0 || search_depth > 10 || 33 | time_limit < 0 || 34 | num_threads < 1) { 35 | return false; 36 | } 37 | 38 | // Copy game state 39 | char *gs = new char[g_gs_size]; 40 | std::memcpy(gs, gs_string, g_gs_size); 41 | 42 | // Convert from string 43 | gsFromString(gs_string, gs); 44 | 45 | // Generate move 46 | RenjuAIController::generateMove(gs, ai_player_id, search_depth, time_limit, actual_depth, 47 | move_r, move_c, winning_player, node_count, eval_count, pm_count); 48 | 49 | // Release memory 50 | delete[] gs; 51 | return true; 52 | } 53 | 54 | void RenjuAPI::gsFromString(const char *gs_string, char *gs) { 55 | if (strlen(gs_string) != g_gs_size) return; 56 | for (int i = 0; i < static_cast(g_gs_size); i++) { 57 | gs[i] = gs_string[i] - '0'; 58 | } 59 | } 60 | 61 | std::string RenjuAPI::renderGameState(const char *gs) { 62 | std::string result = ""; 63 | for (int r = 0; r < g_board_size; r++) { 64 | for (int c = 0; c < g_board_size; c++) { 65 | result.push_back(RenjuAIUtils::getCell(gs, r, c) + '0'); 66 | result.push_back(' '); 67 | } 68 | result.push_back('\n'); 69 | } 70 | return result; 71 | } 72 | -------------------------------------------------------------------------------- /src/ai/ai_controller.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | void RenjuAIController::generateMove(const char *gs, int player, int search_depth, int time_limit, 27 | int *actual_depth, int *move_r, int *move_c, int *winning_player, 28 | unsigned int *node_count, unsigned int *eval_count, unsigned int *pm_count) { 29 | // Check arguments 30 | if (gs == nullptr || 31 | player < 1 || player > 2 || 32 | search_depth == 0 || search_depth > 10 || 33 | time_limit < 0 || 34 | move_r == nullptr || move_c == nullptr) return; 35 | 36 | // Initialize counters 37 | g_eval_count = 0; 38 | g_pm_count = 0; 39 | 40 | // Initialize data 41 | *move_r = -1; 42 | *move_c = -1; 43 | int _winning_player = 0; 44 | if (actual_depth != nullptr) *actual_depth = 0; 45 | 46 | // Check if anyone wins the game 47 | _winning_player = RenjuAIEval::winningPlayer(gs); 48 | if (_winning_player != 0) { 49 | if (winning_player != nullptr) *winning_player = _winning_player; 50 | return; 51 | } 52 | 53 | // Copy game state 54 | char *_gs = new char[g_gs_size]; 55 | std::memcpy(_gs, gs, g_gs_size); 56 | 57 | // Run negamax 58 | RenjuAINegamax::heuristicNegamax(_gs, player, search_depth, time_limit, true, actual_depth, move_r, move_c); 59 | 60 | // Execute the move 61 | std::memcpy(_gs, gs, g_gs_size); 62 | RenjuAIUtils::setCell(_gs, *move_r, *move_c, static_cast(player)); 63 | 64 | // Check if anyone wins the game 65 | _winning_player = RenjuAIEval::winningPlayer(_gs); 66 | 67 | // Write output 68 | if (winning_player != nullptr) *winning_player = _winning_player; 69 | if (node_count != nullptr) *node_count = g_node_count; 70 | if (eval_count != nullptr) *eval_count = g_eval_count; 71 | if (pm_count != nullptr) *pm_count = g_pm_count; 72 | 73 | delete[] _gs; 74 | } 75 | -------------------------------------------------------------------------------- /gui/client/assets/yl-v4-main.css: -------------------------------------------------------------------------------- 1 | /* (C) 2015 Yunzhu Li */ 2 | 3 | html { 4 | position: relative; 5 | min-height: 100%; 6 | } 7 | 8 | body { 9 | margin-bottom: 50px; 10 | font-family: "proxima-nova", "Helvetica Neue", Helvetica, "Hiragino Sans GB","Microsoft YaHei", Arial, sans-serif; 11 | font-weight: 400; 12 | font-size: 15px; 13 | color: #444; 14 | line-height:1.7; 15 | } 16 | 17 | ol, ul { 18 | padding-left: 30px; 19 | } 20 | 21 | .navbar-default { 22 | font-size: 14px; 23 | font-weight: 300; 24 | background-color: #fff; 25 | } 26 | 27 | .navbar-default .navbar-nav>.active>a, 28 | .navbar-default .navbar-nav>.active>a:focus, 29 | .navbar-default .navbar-nav>.active>a:hover { 30 | font-size: 14px; 31 | font-weight: 600; 32 | background-color: #fff; 33 | } 34 | 35 | .navbar-brand { 36 | font-size: 16px; 37 | font-weight: 400; 38 | } 39 | 40 | .panel-default>.panel-heading { 41 | background-color: #f8f8f8; 42 | } 43 | 44 | .panel-title { 45 | font-size: 15px; 46 | line-height: 150%; 47 | color: #555; 48 | } 49 | 50 | .dropdown-menu>li>a { 51 | font-size: 12.5px; 52 | color: #777; 53 | padding: 7px 20px; 54 | } 55 | 56 | .btn-primary { 57 | background-color: #1D98F6; 58 | border-color: #218ADB; 59 | } 60 | 61 | .btn-primary:hover, 62 | .btn-primary:focus { 63 | background-color: #218ADB; 64 | border-color: #0F7ACC; 65 | } 66 | 67 | .progress { 68 | border-radius: 5px; 69 | } 70 | 71 | .progress-bar { 72 | background-color: #1D98F6; 73 | -webkit-transition: none; 74 | -moz-transition: none; 75 | -ms-transition: none; 76 | -o-transition: none; 77 | transition: none; 78 | } 79 | 80 | .footer { 81 | position: absolute; 82 | padding: 14px; 83 | min-height: 50px; 84 | bottom: 0; 85 | width: 100%; 86 | background-color: #fff; 87 | border: solid #e7e7e7; 88 | border-width: 1px; 89 | font-size: 14px; 90 | font-weight: 300; 91 | } 92 | 93 | .footer a { 94 | color: inherit; 95 | } 96 | 97 | .footer a:hover { 98 | color: 333; 99 | } 100 | .container { 101 | max-width: 1100px; 102 | } 103 | 104 | .container-fluid { 105 | max-width: 1100px; 106 | } 107 | 108 | .separator-line { 109 | margin-top: 40px; 110 | width: 100%; 111 | height: 2px; 112 | border-top: 1px solid #e7e7e7; 113 | } 114 | 115 | /* Text styles */ 116 | a { 117 | text-decoration: none; 118 | } 119 | 120 | a:hover { 121 | text-decoration: none; 122 | } 123 | 124 | b { 125 | font-weight: 700; 126 | } 127 | 128 | p { 129 | margin-bottom: 20px; 130 | } 131 | 132 | mark { 133 | background-color: #DADADA; 134 | } 135 | 136 | h4 small { 137 | font-size: 60%; 138 | } 139 | 140 | .h4, h4 { 141 | margin-top: 40px; 142 | margin-bottom: 15px; 143 | color: #333; 144 | font-weight: 400; 145 | font-size: 19px; 146 | } 147 | 148 | .text-muted { 149 | color: #888; 150 | } 151 | 152 | /* Specific */ 153 | .status-indicator { 154 | display:inline-block; 155 | width:11px; 156 | height:11px; 157 | border-radius:3px; 158 | } 159 | -------------------------------------------------------------------------------- /include/ai/eval.h: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #ifndef INCLUDE_AI_EVAL_H_ 20 | #define INCLUDE_AI_EVAL_H_ 21 | 22 | #define kRenjuAiEvalWinningScore 10000 23 | #define kRenjuAiEvalThreateningScore 300 24 | 25 | class RenjuAIEval { 26 | public: 27 | RenjuAIEval(); 28 | ~RenjuAIEval(); 29 | 30 | // Evaluate the entire game state as a player 31 | static int evalState(const char *gs, int player); 32 | 33 | // Evaluate one possible move as a player 34 | static int evalMove(const char *gs, int r, int c, int player); 35 | 36 | // Check if any player is winning based on a given state 37 | static int winningPlayer(const char *gs); 38 | 39 | // Allow testing private members in this class 40 | #ifndef BLUPIG_TEST 41 | private: 42 | #endif 43 | // Result of a single direction measurement 44 | struct DirectionMeasurement { 45 | char length; // Number of pieces in a row 46 | char block_count; // Number of ends blocked by edge or the other player (0-2) 47 | char space_count; // Number of spaces in the middle of pattern 48 | }; 49 | 50 | // A single direction pattern 51 | struct DirectionPattern { 52 | char min_occurrence; // Minimum number of occurrences to match 53 | char length; // Length of pattern (pieces in a row) 54 | char block_count; // Number of ends blocked by edge or the other player (0-2) 55 | char space_count; // Number of spaces in the middle of pattern (-1: Ignore value) 56 | }; 57 | 58 | // An array of preset patterns 59 | static DirectionPattern *preset_patterns; 60 | 61 | // Preset scores of each preset pattern 62 | static int *preset_scores; 63 | 64 | // Loads preset patterns into memory 65 | // preset_patterns_skip is the number of patterns to skip for a maximum 66 | // measured length in an all_direction_measurement (e.g. longest is 3 pieces 67 | // in an ADM, then skip first few patterns that require 4 pieces or more). 68 | static void generatePresetPatterns(DirectionPattern **preset_patterns, 69 | int **preset_scores, 70 | int *preset_patterns_size, 71 | int *preset_patterns_skip); 72 | 73 | // Evaluates an all-direction measurement 74 | static int evalADM(DirectionMeasurement *all_direction_measurement); 75 | 76 | // Tries to match a set of patterns with an all-direction measurement 77 | static int matchPattern(DirectionMeasurement *all_direction_measurement, 78 | DirectionPattern *patterns); 79 | 80 | // Measures all 4 directions 81 | static void measureAllDirections(const char *gs, 82 | int r, 83 | int c, 84 | int player, 85 | bool consecutive, 86 | RenjuAIEval::DirectionMeasurement *adm); 87 | 88 | // Measure a single direction 89 | static void measureDirection(const char *gs, 90 | int r, int c, 91 | int dr, int dc, 92 | int player, 93 | bool consecutive, 94 | RenjuAIEval::DirectionMeasurement *result); 95 | }; 96 | 97 | #endif // INCLUDE_AI_EVAL_H_ 98 | -------------------------------------------------------------------------------- /gui/client/assets/js.cookie.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * JavaScript Cookie v2.1.3 3 | * https://github.com/js-cookie/js-cookie 4 | * 5 | * Copyright 2006, 2015 Klaus Hartl & Fagner Brack 6 | * Released under the MIT license 7 | */ 8 | ;(function (factory) { 9 | var registeredInModuleLoader = false; 10 | if (typeof define === 'function' && define.amd) { 11 | define(factory); 12 | registeredInModuleLoader = true; 13 | } 14 | if (typeof exports === 'object') { 15 | module.exports = factory(); 16 | registeredInModuleLoader = true; 17 | } 18 | if (!registeredInModuleLoader) { 19 | var OldCookies = window.Cookies; 20 | var api = window.Cookies = factory(); 21 | api.noConflict = function () { 22 | window.Cookies = OldCookies; 23 | return api; 24 | }; 25 | } 26 | }(function () { 27 | function extend () { 28 | var i = 0; 29 | var result = {}; 30 | for (; i < arguments.length; i++) { 31 | var attributes = arguments[ i ]; 32 | for (var key in attributes) { 33 | result[key] = attributes[key]; 34 | } 35 | } 36 | return result; 37 | } 38 | 39 | function init (converter) { 40 | function api (key, value, attributes) { 41 | var result; 42 | if (typeof document === 'undefined') { 43 | return; 44 | } 45 | 46 | // Write 47 | 48 | if (arguments.length > 1) { 49 | attributes = extend({ 50 | path: '/' 51 | }, api.defaults, attributes); 52 | 53 | if (typeof attributes.expires === 'number') { 54 | var expires = new Date(); 55 | expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5); 56 | attributes.expires = expires; 57 | } 58 | 59 | try { 60 | result = JSON.stringify(value); 61 | if (/^[\{\[]/.test(result)) { 62 | value = result; 63 | } 64 | } catch (e) {} 65 | 66 | if (!converter.write) { 67 | value = encodeURIComponent(String(value)) 68 | .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent); 69 | } else { 70 | value = converter.write(value, key); 71 | } 72 | 73 | key = encodeURIComponent(String(key)); 74 | key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent); 75 | key = key.replace(/[\(\)]/g, escape); 76 | 77 | return (document.cookie = [ 78 | key, '=', value, 79 | attributes.expires ? '; expires=' + attributes.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE 80 | attributes.path ? '; path=' + attributes.path : '', 81 | attributes.domain ? '; domain=' + attributes.domain : '', 82 | attributes.secure ? '; secure' : '' 83 | ].join('')); 84 | } 85 | 86 | // Read 87 | 88 | if (!key) { 89 | result = {}; 90 | } 91 | 92 | // To prevent the for loop in the first place assign an empty array 93 | // in case there are no cookies at all. Also prevents odd result when 94 | // calling "get()" 95 | var cookies = document.cookie ? document.cookie.split('; ') : []; 96 | var rdecode = /(%[0-9A-Z]{2})+/g; 97 | var i = 0; 98 | 99 | for (; i < cookies.length; i++) { 100 | var parts = cookies[i].split('='); 101 | var cookie = parts.slice(1).join('='); 102 | 103 | if (cookie.charAt(0) === '"') { 104 | cookie = cookie.slice(1, -1); 105 | } 106 | 107 | try { 108 | var name = parts[0].replace(rdecode, decodeURIComponent); 109 | cookie = converter.read ? 110 | converter.read(cookie, name) : converter(cookie, name) || 111 | cookie.replace(rdecode, decodeURIComponent); 112 | 113 | if (this.json) { 114 | try { 115 | cookie = JSON.parse(cookie); 116 | } catch (e) {} 117 | } 118 | 119 | if (key === name) { 120 | result = cookie; 121 | break; 122 | } 123 | 124 | if (!key) { 125 | result[name] = cookie; 126 | } 127 | } catch (e) {} 128 | } 129 | 130 | return result; 131 | } 132 | 133 | api.set = api; 134 | api.get = function (key) { 135 | return api.call(api, key); 136 | }; 137 | api.getJSON = function () { 138 | return api.apply({ 139 | json: true 140 | }, [].slice.call(arguments)); 141 | }; 142 | api.defaults = {}; 143 | 144 | api.remove = function (key, attributes) { 145 | api(key, '', extend(attributes, { 146 | expires: -1 147 | })); 148 | }; 149 | 150 | api.withConverter = init; 151 | 152 | return api; 153 | } 154 | 155 | return init(function () {}); 156 | })); 157 | -------------------------------------------------------------------------------- /src/protocols/gomocup.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | bool RenjuProtocolGomocup::beginSession(int argc, char const *argv[]) { 26 | char line[256]; 27 | char *gs_string = nullptr; 28 | bool errored = false; 29 | int time_limit = 1500; 30 | 31 | while (std::cin.getline(line, 256)) { 32 | // Commands 33 | if (strncmp(line, "START", 5) == 0) { 34 | // START 35 | unsigned int board_size = (unsigned int)atoi(&line[6]); 36 | if (board_size >= 15 && board_size <= 20) { 37 | g_board_size = board_size; 38 | g_gs_size = (unsigned int)g_board_size * g_board_size; 39 | 40 | // Initialize game state 41 | gs_string = new char[g_gs_size + 1]; 42 | memset(gs_string, 0, g_gs_size + 1); 43 | memset(gs_string, '0', g_gs_size); 44 | 45 | // Write output 46 | writeStdout("OK"); 47 | } else { 48 | writeStdout("ERROR"); 49 | errored = true; 50 | break; 51 | } 52 | } else if (strncmp(line, "END", 3) == 0) { 53 | // END 54 | break; 55 | } else if (strncmp(line, "BEGIN", 5) == 0) { 56 | // BEGIN [SIZE] 57 | // Check board status 58 | if (gs_string == nullptr) { 59 | writeStdout("ERROR"); 60 | errored = true; 61 | break; 62 | } 63 | 64 | // Reset board 65 | memset(gs_string, '0', g_gs_size); 66 | 67 | // Put a piece in center 68 | int move_r = g_board_size / 2, move_c = g_board_size / 2; 69 | gs_string[g_board_size * move_r + move_c] = '1'; 70 | 71 | // Write output 72 | std::cout << move_c << "," << move_r << std::endl; 73 | 74 | } else if (strncmp(line, "BOARD", 5) == 0) { 75 | // BOARD 76 | // Check board status 77 | if (gs_string == nullptr) { 78 | writeStdout("ERROR"); 79 | errored = true; 80 | break; 81 | } 82 | 83 | // Reset board 84 | memset(gs_string, '0', g_gs_size); 85 | 86 | while (std::cin.getline(line, 256)) { 87 | // [X],[Y],[field] 88 | if (strncmp(line, "DONE", 4) == 0) { 89 | break; 90 | } else { 91 | // Read piece 92 | int values[3] = {-1, -1, -1}; 93 | splitLine(line, values); 94 | 95 | if (values[2] == -1) { 96 | writeStdout("ERROR"); 97 | errored = true; 98 | break; 99 | } 100 | 101 | // Update board 102 | gs_string[g_board_size * values[1] + values[0]] = '0' + static_cast(values[2]); 103 | } 104 | } 105 | 106 | // Generate, perform a move and write to stdout 107 | performAndWriteMove(gs_string, time_limit); 108 | 109 | } else if (strncmp(line, "TURN", 4) == 0) { 110 | // TURN [X],[Y] 111 | // Check board status 112 | if (gs_string == nullptr) { 113 | writeStdout("ERROR"); 114 | errored = true; 115 | break; 116 | } 117 | 118 | // Read move 119 | int values[2] = {-1, -1}; 120 | int move_r, move_c; 121 | splitLine(&line[5], values); 122 | move_c = values[0]; move_r = values[1]; 123 | 124 | if (move_r == -1 || move_r >= g_board_size || move_c >= g_board_size) { 125 | writeStdout("ERROR"); 126 | errored = true; 127 | break; 128 | } 129 | 130 | // Update board 131 | gs_string[g_board_size * move_r + move_c] = '2'; 132 | 133 | // Generate, perform a move and write to stdout 134 | performAndWriteMove(gs_string, time_limit); 135 | 136 | } else if (strncmp(line, "INFO", 4) == 0) { 137 | // INFO [key] [value] 138 | if (strncmp(line + 5, "timeout_turn", 12) == 0) { 139 | time_limit = atoi(line + 5 + 12 + 1) + 500; 140 | } 141 | } else if (strncmp(line, "ABOUT", 5) == 0) { 142 | std::string build_datetime = __DATE__; 143 | build_datetime = build_datetime + " " + __TIME__; 144 | 145 | writeStdout("name=\"blupig\", version=\"" + build_datetime + "\", author=\"Yunzhu Li\", country=\"China\""); 146 | } else { 147 | writeStdout("UNKNOWN"); 148 | } 149 | } 150 | 151 | // Release memory 152 | if (gs_string != nullptr) delete[] gs_string; 153 | 154 | return !errored; 155 | } 156 | 157 | void RenjuProtocolGomocup::performAndWriteMove(char *gs_string, int time_limit) { 158 | // Generate move 159 | int move_r, move_c, winning_player, actual_depth; 160 | unsigned int node_count, eval_count; 161 | bool success = RenjuAPI::generateMove(gs_string, 1, -1, time_limit, 1, &actual_depth, &move_r, &move_c, 162 | &winning_player, &node_count, &eval_count, nullptr); 163 | 164 | if (success) { 165 | // Write MESSAGE 166 | std::cout << "MESSAGE" << 167 | " d=" << actual_depth << 168 | " node_cnt=" << node_count << 169 | " eval_cnt=" << eval_count << std::endl; 170 | 171 | // Update board 172 | gs_string[g_board_size * move_r + move_c] = '1'; 173 | 174 | // Write output 175 | std::cout << move_c << "," << move_r << std::endl; 176 | } else { 177 | writeStdout("ERROR"); 178 | } 179 | } 180 | 181 | void RenjuProtocolGomocup::splitLine(const char *line, int *output) { 182 | // Copy input 183 | size_t in_length = strlen(line); 184 | char *_line = new char[in_length]; 185 | memcpy(_line, line, in_length); 186 | 187 | int pos = 0, seg_idx = 0, seg_begin = 0; 188 | 189 | while (_line[pos] != 0) { 190 | if (_line[pos] == ',') { 191 | _line[pos] = 0; 192 | output[seg_idx++] = atoi(&_line[seg_begin]); 193 | seg_begin = pos + 1; 194 | } 195 | ++pos; 196 | } 197 | 198 | // Last one 199 | output[seg_idx] = atoi(&line[seg_begin]); 200 | 201 | delete[] _line; 202 | } 203 | 204 | void RenjuProtocolGomocup::writeStdout(std::string str) { 205 | std::cout << str << std::endl; 206 | } 207 | -------------------------------------------------------------------------------- /src/protocols/cli.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | bool RenjuProtocolCLI::beginSession(int argc, char const *argv[]) { 28 | // Print usage if no arguments provided 29 | if (argc < 2) { 30 | std::cerr << "Usage: renju" << std::endl; 31 | std::cerr << " -s The game state (required)" << std::endl; 32 | std::cerr << " [-p ] AI player (1: black, 2: white; default: 1)" << std::endl; 33 | std::cerr << " [-d ] AI Search depth (iterative deepening)" << std::endl; 34 | std::cerr << " [-l ] Execution time limit for iterative deepening (5000)" << std::endl; 35 | std::cerr << " [-t ] Number of threads (1)" << std::endl; 36 | return false; 37 | } 38 | 39 | // Initialize arguments 40 | g_board_size = 19; 41 | g_gs_size = (unsigned int)g_board_size * g_board_size; 42 | char gs_string[362] = {0}; 43 | int ai_player = 1; 44 | int num_threads = 1; 45 | int search_depth = -1; 46 | int time_limit = 5500; 47 | 48 | // Iterate through arguments 49 | for (int i = 0; i < argc; i++) { 50 | const char *arg = argv[i]; 51 | 52 | if (strncmp(arg, "-s", 2) == 0) { 53 | // Check if value exists 54 | if (i >= argc - 1) continue; 55 | 56 | // Validate and copy state 57 | if (validateString(argv[i + 1], 361) == 361) 58 | memcpy(gs_string, argv[i + 1], 361); 59 | 60 | } else if (strncmp(arg, "-p", 2) == 0) { 61 | // AI player ID 62 | if (i >= argc - 1) continue; 63 | parseIntegerArgument(argv[i + 1], 3, &ai_player); 64 | 65 | } else if (strncmp(arg, "-d", 2) == 0) { 66 | // Search depth 67 | if (i >= argc - 1) continue; 68 | parseIntegerArgument(argv[i + 1], 3, &search_depth); 69 | 70 | } else if (strncmp(arg, "-l", 2) == 0) { 71 | // Number of threads 72 | if (i >= argc - 1) continue; 73 | parseIntegerArgument(argv[i + 1], 8, &time_limit); 74 | 75 | } else if (strncmp(arg, "-t", 2) == 0) { 76 | // Number of threads 77 | if (i >= argc - 1) continue; 78 | parseIntegerArgument(argv[i + 1], 3, &num_threads); 79 | 80 | } else if (strncmp(arg, "test", 4) == 0) { 81 | // Build test data 82 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002121000000000000001211112000000000000022122110000000000001211002200000000000002010200000000000000000200000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 83 | search_depth = 8; 84 | ai_player = 2; 85 | } 86 | } 87 | 88 | std::string result = generateMove(gs_string, ai_player, search_depth, time_limit, num_threads); 89 | std::cout << result << std::endl; 90 | 91 | return true; 92 | } 93 | 94 | bool RenjuProtocolCLI::parseIntegerArgument(const char *str, int max_length, int *result) { 95 | if (validateString(str, max_length) < 0) return false; 96 | *result = (int)strtol(str, nullptr, 10); 97 | return true; 98 | } 99 | 100 | int RenjuProtocolCLI::validateString(const char *str, int max_length) { 101 | // Only supports up to 2048 bytes 102 | if (str == nullptr || max_length < 0 || max_length >= 2048) return -1; 103 | 104 | for (int i = 0; i <= max_length; i++) { 105 | if (str[i] == 0) return i; 106 | } 107 | return -1; 108 | } 109 | 110 | std::string RenjuProtocolCLI::generateMove(const char *gs_string, int ai_player_id, int search_depth, 111 | int time_limit, int num_threads) { 112 | // Record start time 113 | std::clock_t clock_begin = std::clock(); 114 | 115 | // Generate move 116 | int move_r, move_c, winning_player, actual_depth; 117 | unsigned int node_count, eval_count, pm_count; 118 | bool success = RenjuAPI::generateMove(gs_string, ai_player_id, search_depth, time_limit, num_threads, &actual_depth, 119 | &move_r, &move_c, &winning_player, &node_count, &eval_count, &pm_count); 120 | 121 | if (!success) return generateResultJson(nullptr, "Invalid input data."); 122 | 123 | // Calculate elapsed CPU time 124 | std::clock_t clock_end = std::clock(); 125 | std::clock_t cpu_time = (clock_end - clock_begin) * 1000 / CLOCKS_PER_SEC; 126 | 127 | // Build date & time 128 | std::string build_datetime = __DATE__; 129 | build_datetime = build_datetime + " " + __TIME__; 130 | 131 | // Generate result map 132 | std::unordered_map data = {{"move_r", std::to_string(move_r)}, 133 | {"move_c", std::to_string(move_c)}, 134 | {"winning_player", std::to_string(winning_player)}, 135 | {"ai_player", std::to_string(ai_player_id)}, 136 | {"search_depth", std::to_string(actual_depth)}, 137 | {"cpu_time", std::to_string(cpu_time)}, 138 | {"num_threads", std::to_string(num_threads)}, 139 | {"node_count", std::to_string(node_count)}, 140 | {"eval_count", std::to_string(eval_count)}, 141 | {"pm_count", std::to_string(pm_count)}, 142 | {"cc_0", std::to_string(g_cc_0)}, 143 | {"cc_1", std::to_string(g_cc_1)}, 144 | {"build", build_datetime}}; 145 | 146 | // Result 147 | return generateResultJson(&data, "ok"); 148 | } 149 | 150 | std::string RenjuProtocolCLI::generateResultJson(const std::unordered_map *data, 151 | const std::string &message) { 152 | nlohmann::json result; 153 | if (data != nullptr) { 154 | // Add all k-v pairs to the result map 155 | for (auto pair : *data) { 156 | result["result"][pair.first] = pair.second; 157 | } 158 | } else { 159 | result["result"] = nullptr; 160 | } 161 | result["message"] = message; 162 | 163 | // Serialize 164 | return result.dump(); 165 | } 166 | -------------------------------------------------------------------------------- /tests/gtest_ai_negamax.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | class RenjuAINegamaxTest : public ::testing::Test { 24 | protected: 25 | char gs[361] = {0}; 26 | char gs_string[362] = {0}; 27 | }; 28 | 29 | TEST_F(RenjuAINegamaxTest, heuristicNegamax0) { 30 | 31 | int move_r0, move_c0, move_r1, move_c1; 32 | 33 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200100000000000000122200000000000000011200000000000000001210000000000000000200200000000000000110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 34 | RenjuAPI::gsFromString(gs_string, gs); 35 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, true, nullptr, &move_r0, &move_c0); 36 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, false, nullptr, &move_r1, &move_c1); 37 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 38 | 39 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200100000000000000122221000000000000011220000000000000001210000000000000001200200000000000011112000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 40 | RenjuAPI::gsFromString(gs_string, gs); 41 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, true, nullptr, &move_r0, &move_c0); 42 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, false, nullptr, &move_r1, &move_c1); 43 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 44 | 45 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000220000000000002111122000000000000001121200000000000000211020000000000000002021000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 46 | RenjuAPI::gsFromString(gs_string, gs); 47 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, true, nullptr, &move_r0, &move_c0); 48 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, false, nullptr, &move_r1, &move_c1); 49 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 50 | 51 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000020000000000000100112100000000000001222210000000000000020122000000000000000101200000000000000000002000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 52 | RenjuAPI::gsFromString(gs_string, gs); 53 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, true, nullptr, &move_r0, &move_c0); 54 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, false, nullptr, &move_r1, &move_c1); 55 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 56 | 57 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000110000000000000000020000000000000000022200000000000000120200010000000000020102120000000000010121210000000000000100211000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 58 | RenjuAPI::gsFromString(gs_string, gs); 59 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, true, nullptr, &move_r0, &move_c0); 60 | RenjuAINegamax::heuristicNegamax(gs, 1, 4, 0, false, nullptr, &move_r1, &move_c1); 61 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 62 | } 63 | 64 | TEST_F(RenjuAINegamaxTest, heuristicNegamax1) { 65 | 66 | int move_r0, move_c0, move_r1, move_c1; 67 | 68 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 69 | RenjuAPI::gsFromString(gs_string, gs); 70 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, true, nullptr, &move_r0, &move_c0); 71 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, false, nullptr, &move_r1, &move_c1); 72 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 73 | 74 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000000000000121111200000000000002020000000000000000022100000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 75 | RenjuAPI::gsFromString(gs_string, gs); 76 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, true, nullptr, &move_r0, &move_c0); 77 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, false, nullptr, &move_r1, &move_c1); 78 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 79 | 80 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001211100000000000000111200000000000000021220000000000000002000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 81 | RenjuAPI::gsFromString(gs_string, gs); 82 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, true, nullptr, &move_r0, &move_c0); 83 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, false, nullptr, &move_r1, &move_c1); 84 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 85 | 86 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001110000000000000000120000000000000000122200000000000000021112000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 87 | RenjuAPI::gsFromString(gs_string, gs); 88 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, true, nullptr, &move_r0, &move_c0); 89 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, false, nullptr, &move_r1, &move_c1); 90 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 91 | 92 | memcpy(gs_string, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001010000000000000000120000000000000002122211000000000001021112000000000000020101000000000000010202000000000000000002000000000000000002210000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 362); 93 | RenjuAPI::gsFromString(gs_string, gs); 94 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, true, nullptr, &move_r0, &move_c0); 95 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, false, nullptr, &move_r1, &move_c1); 96 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 97 | 98 | memcpy(gs_string, "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000020000000000000002120000000000000000220000000000000000010200000000000000000001000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000", 362); 99 | RenjuAPI::gsFromString(gs_string, gs); 100 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, true, nullptr, &move_r0, &move_c0); 101 | RenjuAINegamax::heuristicNegamax(gs, 2, 4, 0, false, nullptr, &move_r1, &move_c1); 102 | EXPECT_EQ(move_r0, move_r1); EXPECT_EQ(move_c0, move_c1); 103 | } 104 | -------------------------------------------------------------------------------- /tests/gtest_ai_eval.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | class RenjuAIEvalTest : public ::testing::Test { 24 | protected: 25 | char gs[361] = {0}; 26 | }; 27 | 28 | TEST_F(RenjuAIEvalTest, winningPlayer) { 29 | EXPECT_EQ(0, RenjuAIEval::winningPlayer(gs)); 30 | 31 | gs[2] = 1; gs[3] = 1; gs[4] = 1; gs[5] = 1; 32 | EXPECT_EQ(0, RenjuAIEval::winningPlayer(gs)); 33 | 34 | gs[6] = 1; 35 | EXPECT_EQ(1, RenjuAIEval::winningPlayer(gs)); 36 | 37 | gs[7] = 1; 38 | EXPECT_EQ(1, RenjuAIEval::winningPlayer(gs)); 39 | 40 | memset(gs, 0, 361); 41 | 42 | gs[2] = 1; gs[3] = 2; gs[4] = 2; gs[5] = 2; gs[6] = 2; gs[7] = 2; 43 | EXPECT_EQ(2, RenjuAIEval::winningPlayer(gs)); 44 | } 45 | 46 | TEST_F(RenjuAIEvalTest, meausreDirection) { 47 | RenjuAIEval::DirectionMeasurement dm; 48 | RenjuAIEval::measureDirection(gs, 0, 0, 1, 1, 1, true, &dm); 49 | EXPECT_EQ(1, dm.length); EXPECT_EQ(1, dm.block_count); EXPECT_EQ(0, dm.space_count); 50 | 51 | // * 0 0 52 | // 0 1 0 53 | // 0 0 0 54 | RenjuAIUtils::setCell(gs, 1, 1, 1); 55 | gs[1 * 15 + 1] = 1; 56 | RenjuAIEval::measureDirection(gs, 0, 0, 1, 1, 1, true, &dm); 57 | EXPECT_EQ(2, dm.length); EXPECT_EQ(1, dm.block_count); EXPECT_EQ(0, dm.space_count); 58 | 59 | // * 0 0 0 60 | // 0 1 0 0 61 | // 0 0 1 0 62 | // 0 0 0 0 63 | RenjuAIUtils::setCell(gs, 2, 2, 1); 64 | RenjuAIEval::measureDirection(gs, 0, 0, 1, 1, 1, true, &dm); 65 | EXPECT_EQ(3, dm.length); EXPECT_EQ(1, dm.block_count); EXPECT_EQ(0, dm.space_count); 66 | 67 | // * 0 0 0 68 | // 0 1 0 0 69 | // 0 0 1 0 70 | // 0 0 0 2 71 | RenjuAIUtils::setCell(gs, 3, 3, 2); 72 | RenjuAIEval::measureDirection(gs, 0, 0, 1, 1, 1, true, &dm); 73 | EXPECT_EQ(3, dm.length); EXPECT_EQ(2, dm.block_count); EXPECT_EQ(0, dm.space_count); 74 | 75 | // * 0 0 0 76 | // 0 1 0 0 77 | // 0 0 0 0 78 | // 0 0 0 1 79 | RenjuAIUtils::setCell(gs, 2, 2, 0); 80 | RenjuAIUtils::setCell(gs, 3, 3, 1); 81 | RenjuAIEval::measureDirection(gs, 0, 0, 1, 1, 1, true, &dm); 82 | EXPECT_EQ(2, dm.length); EXPECT_EQ(1, dm.block_count); EXPECT_EQ(0, dm.space_count); 83 | 84 | RenjuAIEval::measureDirection(gs, 0, 0, 1, 1, 1, false, &dm); 85 | EXPECT_EQ(3, dm.length); EXPECT_EQ(1, dm.block_count); EXPECT_EQ(1, dm.space_count); 86 | 87 | // 0 0 0 0 0 88 | // 0 1 * 1 0 89 | // 0 0 0 0 0 90 | memset(gs, 0, 361); 91 | RenjuAIUtils::setCell(gs, 1, 1, 1); 92 | RenjuAIUtils::setCell(gs, 1, 3, 1); 93 | RenjuAIEval::measureDirection(gs, 1, 2, 0, 1, 1, true, &dm); 94 | EXPECT_EQ(3, dm.length); EXPECT_EQ(0, dm.block_count); EXPECT_EQ(0, dm.space_count); 95 | 96 | RenjuAIEval::measureDirection(gs, 1, 2, 0, 1, 1, false, &dm); 97 | EXPECT_EQ(3, dm.length); EXPECT_EQ(0, dm.block_count); EXPECT_EQ(0, dm.space_count); 98 | 99 | // 0 0 0 0 0 0 100 | // 1 1 * 1 0 0 101 | // 0 0 0 0 0 0 102 | RenjuAIUtils::setCell(gs, 1, 0, 1); 103 | RenjuAIEval::measureDirection(gs, 1, 2, 0, 1, 1, true, &dm); 104 | EXPECT_EQ(4, dm.length); EXPECT_EQ(1, dm.block_count); EXPECT_EQ(0, dm.space_count); 105 | 106 | // 0 0 0 0 0 0 0 107 | // 0 1 * 1 0 1 0 108 | // 0 0 0 0 0 0 0 109 | RenjuAIUtils::setCell(gs, 1, 0, 0); 110 | RenjuAIUtils::setCell(gs, 1, 5, 1); 111 | RenjuAIEval::measureDirection(gs, 1, 2, 0, 1, 1, false, &dm); 112 | EXPECT_EQ(4, dm.length); EXPECT_EQ(0, dm.block_count); EXPECT_EQ(1, dm.space_count); 113 | } 114 | 115 | TEST_F(RenjuAIEvalTest, meausreAllDirections) { 116 | RenjuAIEval::DirectionMeasurement adm[4]; 117 | 118 | // * 0 119 | // 0 0 120 | RenjuAIEval::measureAllDirections(gs, 0, 0, 1, true, adm); 121 | EXPECT_EQ(1, adm[0].length); EXPECT_EQ(1, adm[1].length); EXPECT_EQ(1, adm[2].length); EXPECT_EQ(1, adm[3].length); 122 | EXPECT_EQ(1, adm[0].block_count); EXPECT_EQ(1, adm[1].block_count); EXPECT_EQ(1, adm[2].block_count); EXPECT_EQ(2, adm[3].block_count); 123 | EXPECT_EQ(0, adm[0].space_count); EXPECT_EQ(0, adm[1].space_count); EXPECT_EQ(0, adm[2].space_count); EXPECT_EQ(0, adm[3].space_count); 124 | 125 | // 0 0 0 126 | // * 0 0 127 | // 0 0 0 128 | RenjuAIEval::measureAllDirections(gs, 1, 0, 1, true, adm); 129 | EXPECT_EQ(1, adm[0].length); EXPECT_EQ(1, adm[1].length); EXPECT_EQ(1, adm[2].length); EXPECT_EQ(1, adm[3].length); 130 | EXPECT_EQ(1, adm[0].block_count); EXPECT_EQ(1, adm[1].block_count); EXPECT_EQ(0, adm[2].block_count); EXPECT_EQ(1, adm[3].block_count); 131 | EXPECT_EQ(0, adm[0].space_count); EXPECT_EQ(0, adm[1].space_count); EXPECT_EQ(0, adm[2].space_count); EXPECT_EQ(0, adm[3].space_count); 132 | 133 | // 0 0 0 134 | // * 1 0 135 | // 0 0 0 136 | RenjuAIUtils::setCell(gs, 1, 1, 1); 137 | RenjuAIEval::measureAllDirections(gs, 1, 0, 1, true, adm); 138 | EXPECT_EQ(2, adm[0].length); EXPECT_EQ(1, adm[1].length); EXPECT_EQ(1, adm[2].length); EXPECT_EQ(1, adm[3].length); 139 | EXPECT_EQ(1, adm[0].block_count); EXPECT_EQ(1, adm[1].block_count); EXPECT_EQ(0, adm[2].block_count); EXPECT_EQ(1, adm[3].block_count); 140 | EXPECT_EQ(0, adm[0].space_count); EXPECT_EQ(0, adm[1].space_count); EXPECT_EQ(0, adm[2].space_count); EXPECT_EQ(0, adm[3].space_count); 141 | 142 | // 0 0 0 143 | // 0 2 0 144 | // 0 2 0 145 | // 0 2 0 146 | // 0 * 0 147 | // 0 0 0 148 | RenjuAIUtils::setCell(gs, 1, 1, 2); 149 | RenjuAIUtils::setCell(gs, 2, 1, 2); 150 | RenjuAIUtils::setCell(gs, 3, 1, 2); 151 | RenjuAIEval::measureAllDirections(gs, 4, 1, 2, true, adm); 152 | EXPECT_EQ(1, adm[0].length); EXPECT_EQ(1, adm[1].length); EXPECT_EQ(4, adm[2].length); EXPECT_EQ(1, adm[3].length); 153 | EXPECT_EQ(0, adm[0].block_count); EXPECT_EQ(0, adm[1].block_count); EXPECT_EQ(0, adm[2].block_count); EXPECT_EQ(0, adm[3].block_count); 154 | EXPECT_EQ(0, adm[0].space_count); EXPECT_EQ(0, adm[1].space_count); EXPECT_EQ(0, adm[2].space_count); EXPECT_EQ(0, adm[3].space_count); 155 | } 156 | 157 | TEST_F(RenjuAIEvalTest, matchPattern) { 158 | 159 | RenjuAIEval::DirectionPattern *preset_patterns = nullptr; 160 | int *preset_scores = nullptr; 161 | int preset_patterns_size = 0; 162 | int preset_patterns_skip[6] = {0}; 163 | RenjuAIEval::generatePresetPatterns(&preset_patterns, &preset_scores, &preset_patterns_size, preset_patterns_skip); 164 | 165 | RenjuAIEval::DirectionMeasurement adm[4]; 166 | 167 | // 0 0 0 168 | // 0 2 0 169 | // 0 2 0 170 | // 0 2 0 171 | // 0 * 0 172 | // 0 0 0 173 | memset(gs, 0, 361); 174 | RenjuAIUtils::setCell(gs, 1, 1, 2); 175 | RenjuAIUtils::setCell(gs, 2, 1, 2); 176 | RenjuAIUtils::setCell(gs, 3, 1, 2); 177 | RenjuAIEval::measureAllDirections(gs, 4, 1, 2, true, adm); 178 | EXPECT_EQ(1, RenjuAIEval::matchPattern(adm, &preset_patterns[2])); 179 | 180 | // 0 0 0 0 181 | // 0 * 2 2 182 | // 0 2 0 0 183 | // 0 0 0 0 184 | // 0 2 0 0 185 | // 0 0 0 0 186 | memset(gs, 0, 361); 187 | RenjuAIUtils::setCell(gs, 1, 2, 2); 188 | RenjuAIUtils::setCell(gs, 1, 3, 2); 189 | RenjuAIUtils::setCell(gs, 2, 1, 2); 190 | RenjuAIUtils::setCell(gs, 4, 1, 2); 191 | RenjuAIEval::measureAllDirections(gs, 1, 1, 2, false, adm); 192 | EXPECT_EQ(1, RenjuAIEval::matchPattern(adm, &preset_patterns[14])); 193 | 194 | // 0 0 0 0 0 195 | // 0 * 2 2 0 196 | // 0 0 2 0 0 197 | // 0 0 0 2 0 198 | // 0 0 0 0 0 199 | // 0 0 0 0 0 200 | memset(gs, 0, 361); 201 | RenjuAIUtils::setCell(gs, 1, 2, 2); 202 | RenjuAIUtils::setCell(gs, 1, 3, 2); 203 | RenjuAIUtils::setCell(gs, 2, 2, 2); 204 | RenjuAIUtils::setCell(gs, 3, 3, 2); 205 | RenjuAIEval::measureAllDirections(gs, 1, 1, 2, false, adm); 206 | EXPECT_EQ(1, RenjuAIEval::matchPattern(adm, &preset_patterns[14])); 207 | 208 | // 0 0 0 0 0 0 209 | // 0 * 2 0 2 0 210 | // 0 2 0 0 0 0 211 | // 0 2 0 0 0 0 212 | // 0 2 0 0 0 0 213 | // 0 1 0 0 0 0 214 | memset(gs, 0, 361); 215 | RenjuAIUtils::setCell(gs, 1, 2, 2); 216 | RenjuAIUtils::setCell(gs, 1, 4, 2); 217 | RenjuAIUtils::setCell(gs, 2, 1, 2); 218 | RenjuAIUtils::setCell(gs, 3, 1, 2); 219 | RenjuAIUtils::setCell(gs, 4, 1, 2); 220 | RenjuAIUtils::setCell(gs, 5, 1, 1); 221 | RenjuAIEval::measureAllDirections(gs, 1, 1, 2, false, adm); 222 | EXPECT_EQ(1, RenjuAIEval::matchPattern(adm, &preset_patterns[10])); 223 | } 224 | 225 | TEST_F(RenjuAIEvalTest, evalMove) { 226 | 227 | // 0 0 0 0 0 0 0 228 | // 0 * 1 1 1 1 2 229 | // 0 0 0 0 0 0 0 230 | memset(gs, 0, 361); 231 | RenjuAIUtils::setCell(gs, 1, 2, 1); 232 | RenjuAIUtils::setCell(gs, 1, 3, 1); 233 | RenjuAIUtils::setCell(gs, 1, 4, 1); 234 | RenjuAIUtils::setCell(gs, 1, 5, 1); 235 | RenjuAIUtils::setCell(gs, 1, 6, 2); 236 | EXPECT_EQ(10004, RenjuAIEval::evalMove(gs, 1, 1, 1)); 237 | 238 | // 0 0 0 0 0 0 0 0 239 | // 0 1 1 * 1 1 1 0 240 | // 0 0 0 0 0 0 0 0 241 | memset(gs, 0, 361); 242 | RenjuAIUtils::setCell(gs, 1, 1, 1); 243 | RenjuAIUtils::setCell(gs, 1, 2, 1); 244 | RenjuAIUtils::setCell(gs, 1, 4, 1); 245 | RenjuAIUtils::setCell(gs, 1, 5, 1); 246 | RenjuAIUtils::setCell(gs, 1, 6, 1); 247 | EXPECT_EQ(10004, RenjuAIEval::evalMove(gs, 1, 3, 1)); 248 | 249 | // 0 0 0 0 0 0 250 | // 0 * 1 1 1 0 251 | // 0 0 0 0 0 0 252 | memset(gs, 0, 361); 253 | RenjuAIUtils::setCell(gs, 1, 2, 1); 254 | RenjuAIUtils::setCell(gs, 1, 3, 1); 255 | RenjuAIUtils::setCell(gs, 1, 4, 1); 256 | EXPECT_EQ(703, RenjuAIEval::evalMove(gs, 1, 1, 1)); 257 | 258 | // 0 0 0 0 0 0 259 | // 0 1 * 1 1 0 260 | // 0 0 0 0 0 0 261 | memset(gs, 0, 361); 262 | RenjuAIUtils::setCell(gs, 1, 1, 1); 263 | RenjuAIUtils::setCell(gs, 1, 3, 1); 264 | RenjuAIUtils::setCell(gs, 1, 4, 1); 265 | EXPECT_EQ(703, RenjuAIEval::evalMove(gs, 1, 2, 1)); 266 | } 267 | -------------------------------------------------------------------------------- /src/ai/eval.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | // Initialize global variables 28 | RenjuAIEval::DirectionPattern *RenjuAIEval::preset_patterns = nullptr; 29 | int *RenjuAIEval::preset_scores = nullptr; 30 | int preset_patterns_size = 0; 31 | int preset_patterns_skip[6] = {0}; 32 | 33 | int RenjuAIEval::evalState(const char *gs, int player) { 34 | // Check parameters 35 | if (gs == nullptr || 36 | player < 1 || player > 2) return 0; 37 | 38 | // Evaluate all possible moves 39 | int score = 0; 40 | for (int r = 0; r < g_board_size; ++r) { 41 | for (int c = 0; c < g_board_size; ++c) { 42 | score += evalMove(gs, r, c, player); 43 | } 44 | } 45 | return score; 46 | } 47 | 48 | int RenjuAIEval::evalMove(const char *gs, int r, int c, int player) { 49 | // Check parameters 50 | if (gs == nullptr || 51 | player < 1 || player > 2) return 0; 52 | 53 | // Count evaluations 54 | ++g_eval_count; 55 | 56 | // Generate preset patterns structure in memory 57 | if (preset_patterns == nullptr) { 58 | generatePresetPatterns(&preset_patterns, &preset_scores, &preset_patterns_size, preset_patterns_skip); 59 | } 60 | 61 | // Allocate 4 direction measurements 62 | DirectionMeasurement adm[4]; 63 | 64 | // Measure in consecutive and non-consecutive conditions 65 | int max_score = 0; 66 | for (bool consecutive = false;; consecutive = true) { 67 | // Execute measurement 68 | measureAllDirections(gs, r, c, player, consecutive, adm); 69 | 70 | int score = evalADM(adm); 71 | 72 | // Prefer consecutive 73 | // if (!consecutive) score *= 0.9; 74 | 75 | // Choose the better between consecutive and non-consecutive 76 | max_score = std::max(max_score, score); 77 | 78 | if (consecutive) break; 79 | } 80 | return max_score; 81 | } 82 | 83 | int RenjuAIEval::evalADM(DirectionMeasurement *all_direction_measurement) { 84 | int score = 0; 85 | int size = preset_patterns_size; 86 | 87 | // Add to score by length on each direction 88 | // Find the maximum length in ADM and skip some patterns 89 | int max_measured_len = 0; 90 | for (int i = 0; i < 4; i++) { 91 | int len = all_direction_measurement[i].length; 92 | max_measured_len = len > max_measured_len ? len : max_measured_len; 93 | score += len - 1; 94 | } 95 | int start_pattern = preset_patterns_skip[max_measured_len]; 96 | 97 | // Loop through and try to match all preset patterns 98 | for (int i = start_pattern; i < size; ++i) { 99 | score += matchPattern(all_direction_measurement, &preset_patterns[2 * i]) * preset_scores[i]; 100 | 101 | // Only match one threatening pattern 102 | if (score >= kRenjuAiEvalThreateningScore) break; 103 | } 104 | 105 | return score; 106 | } 107 | 108 | int RenjuAIEval::matchPattern(DirectionMeasurement *all_direction_measurement, 109 | DirectionPattern *patterns) { 110 | // Check arguments 111 | if (all_direction_measurement == nullptr) return -1; 112 | if (patterns == nullptr) return -1; 113 | 114 | // Increment PM count 115 | g_pm_count++; 116 | 117 | // Initialize match_count to INT_MAX since minimum value will be output 118 | int match_count = INT_MAX, single_pattern_match = 0; 119 | 120 | // Currently allows maximum 2 patterns 121 | for (int i = 0; i < 2; ++i) { 122 | auto p = patterns[i]; 123 | if (p.length == 0) break; 124 | 125 | // Initialize counter 126 | single_pattern_match = 0; 127 | 128 | // Loop through 4 directions 129 | for (int j = 0; j < 4; ++j) { 130 | auto dm = all_direction_measurement[j]; 131 | 132 | // Requires exact match 133 | if (dm.length == p.length && 134 | (p.block_count == -1 || dm.block_count == p.block_count) && 135 | (p.space_count == -1 || dm.space_count == p.space_count)) { 136 | single_pattern_match++; 137 | } 138 | } 139 | 140 | // Consider minimum number of occurrences 141 | single_pattern_match /= p.min_occurrence; 142 | 143 | // Take smaller value 144 | match_count = match_count >= single_pattern_match ? single_pattern_match : match_count; 145 | } 146 | return match_count; 147 | } 148 | 149 | void RenjuAIEval::measureAllDirections(const char *gs, 150 | int r, 151 | int c, 152 | int player, 153 | bool consecutive, 154 | RenjuAIEval::DirectionMeasurement *adm) { 155 | // Check arguments 156 | if (gs == nullptr) return; 157 | if (r < 0 || r >= g_board_size || c < 0 || c >= g_board_size) return; 158 | 159 | // Measure 4 directions 160 | measureDirection(gs, r, c, 0, 1, player, consecutive, &adm[0]); 161 | measureDirection(gs, r, c, 1, 1, player, consecutive, &adm[1]); 162 | measureDirection(gs, r, c, 1, 0, player, consecutive, &adm[2]); 163 | measureDirection(gs, r, c, 1, -1, player, consecutive, &adm[3]); 164 | } 165 | 166 | void RenjuAIEval::measureDirection(const char *gs, 167 | int r, int c, 168 | int dr, int dc, 169 | int player, 170 | bool consecutive, 171 | RenjuAIEval::DirectionMeasurement *result) { 172 | // Check arguments 173 | if (gs == nullptr) return; 174 | if (r < 0 || r >= g_board_size || c < 0 || c >= g_board_size) return; 175 | if (dr == 0 && dc == 0) return; 176 | 177 | // Initialization 178 | int cr = r, cc = c; 179 | result->length = 1, result->block_count = 2, result->space_count = 0; 180 | 181 | int space_allowance = 1; 182 | if (consecutive) space_allowance = 0; 183 | 184 | for (bool reversed = false;; reversed = true) { 185 | while (true) { 186 | // Move 187 | cr += dr; cc += dc; 188 | 189 | // Validate position 190 | if (cr < 0 || cr >= g_board_size || cc < 0 || cc >= g_board_size) break; 191 | 192 | // Get cell value 193 | int cell = gs[g_board_size * cr + cc]; 194 | 195 | // Empty cells 196 | if (cell == 0) { 197 | if (space_allowance > 0 && RenjuAIUtils::getCell(gs, cr + dr, cc + dc) == player) { 198 | space_allowance--; result->space_count++; 199 | continue; 200 | } else { 201 | result->block_count--; 202 | break; 203 | } 204 | } 205 | 206 | // Another player 207 | if (cell != player) break; 208 | 209 | // Current player 210 | result->length++; 211 | } 212 | 213 | // Reverse direction and continue (just once) 214 | if (reversed) break; 215 | cr = r; cc = c; 216 | dr = -dr; dc = -dc; 217 | } 218 | 219 | // More than 5 pieces in a row is equivalent to 5 pieces 220 | if (result->length >= 5) { 221 | if (result->space_count == 0) { 222 | result->length = 5; 223 | result->block_count = 0; 224 | } else { 225 | result->length = 4; 226 | result->block_count = 1; 227 | } 228 | } 229 | } 230 | 231 | void RenjuAIEval::generatePresetPatterns(DirectionPattern **preset_patterns, 232 | int **preset_scores, 233 | int *preset_patterns_size, 234 | int *preset_patterns_skip) { 235 | const int _size = 11; 236 | preset_patterns_skip[5] = 0; 237 | preset_patterns_skip[4] = 1; 238 | preset_patterns_skip[3] = 7; 239 | preset_patterns_skip[2] = 10; 240 | 241 | preset_patterns_skip[1] = _size; 242 | preset_patterns_skip[0] = _size; 243 | 244 | DirectionPattern patterns[_size * 2] = { 245 | {1, 5, 0, 0}, {0, 0, 0, 0}, // 10000 246 | {1, 4, 0, 0}, {0, 0, 0, 0}, // 700 247 | {2, 4, 1, 0}, {0, 0, 0, 0}, // 700 248 | {2, 4, -1, 1}, {0, 0, 0, 0}, // 700 249 | {1, 4, 1, 0}, {1, 4, -1, 1}, // 700 250 | {1, 4, 1, 0}, {1, 3, 0, -1}, // 500 251 | {1, 4, -1, 1}, {1, 3, 0, -1}, // 500 252 | {2, 3, 0, -1}, {0, 0, 0, 0}, // 300 253 | // {1, 4, 1, 0}, {0, 0, 0, 0}, // 1 254 | // {1, 4, -1, 1}, {0, 0, 0, 0}, // 1 255 | {3, 2, 0, -1}, {0, 0, 0, 0}, // 50 256 | {1, 3, 0, -1}, {0, 0, 0, 0}, // 20 257 | {1, 2, 0, -1}, {0, 0, 0, 0} // 9 258 | }; 259 | 260 | int scores[_size] = { 261 | 10000, 262 | 700, 263 | 700, 264 | 700, 265 | 700, 266 | 500, 267 | 500, 268 | 300, 269 | // 1, 270 | // 1, 271 | 50, 272 | 20, 273 | 9 274 | }; 275 | 276 | *preset_patterns = new DirectionPattern[_size * 2]; 277 | *preset_scores = new int[_size]; 278 | 279 | memcpy(*preset_patterns, patterns, sizeof(DirectionPattern) * _size * 2); 280 | memcpy(*preset_scores, scores, sizeof(int) * _size); 281 | 282 | *preset_patterns_size = _size; 283 | } 284 | 285 | int RenjuAIEval::winningPlayer(const char *gs) { 286 | if (gs == nullptr) return 0; 287 | for (int r = 0; r < g_board_size; ++r) { 288 | for (int c = 0; c < g_board_size; ++c) { 289 | int cell = gs[g_board_size * r + c]; 290 | if (cell == 0) continue; 291 | for (int dr = -1; dr <= 1; ++dr) { 292 | for (int dc = -1; dc <= 1; ++dc) { 293 | if (dr == 0 && dc <= 0) continue; 294 | DirectionMeasurement dm; 295 | measureDirection(gs, r, c, dr, dc, cell, 1, &dm); 296 | if (dm.length >= 5) return cell; 297 | } 298 | } 299 | } 300 | } 301 | return 0; 302 | } 303 | -------------------------------------------------------------------------------- /src/ai/negamax.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * blupig 3 | * Copyright (C) 2016-2017 Yunzhu Li 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | // kSearchBreadth is used to control branching factor 31 | // Different breadth configurations are possible: 32 | // A lower breadth for a higher depth 33 | // Or vice versa 34 | int RenjuAINegamax::presetSearchBreadth[5] = {17, 7, 5, 3, 3}; 35 | 36 | // Estimated average branching factor for iterative deepening 37 | #define kAvgBranchingFactor 3 38 | 39 | // Maximum depth for iterative deepening 40 | #define kMaximumDepth 16 41 | 42 | // kScoreDecayFactor decays score each layer so the algorithm 43 | // prefers closer advantages 44 | #define kScoreDecayFactor 0.95f 45 | 46 | void RenjuAINegamax::heuristicNegamax(const char *gs, int player, int depth, int time_limit, bool enable_ab_pruning, 47 | int *actual_depth, int *move_r, int *move_c) { 48 | // Check arguments 49 | if (gs == nullptr || 50 | player < 1 || player > 2 || 51 | depth == 0 || depth < -1 || 52 | time_limit < 0) return; 53 | 54 | // Copy game state 55 | char *_gs = new char[g_gs_size]; 56 | memcpy(_gs, gs, g_gs_size); 57 | 58 | // Speedup first move 59 | int _cnt = 0; 60 | for (int i = 0; i < static_cast(g_gs_size); i++) 61 | if (_gs[i] != 0) _cnt++; 62 | 63 | if (_cnt <= 2) depth = 6; 64 | 65 | // Fixed depth or iterative deepening 66 | if (depth > 0) { 67 | if (actual_depth != nullptr) *actual_depth = depth; 68 | heuristicNegamax(_gs, player, depth, depth, enable_ab_pruning, 69 | INT_MIN / 2, INT_MAX / 2, move_r, move_c); 70 | } else { 71 | // Iterative deepening 72 | std::clock_t c_start = std::clock(); 73 | for (int d = 6;; d += 2) { 74 | std::clock_t c_iteration_start = std::clock(); 75 | 76 | // Reset game state 77 | memcpy(_gs, gs, g_gs_size); 78 | 79 | // Execute negamax 80 | heuristicNegamax(_gs, player, d, d, enable_ab_pruning, 81 | INT_MIN / 2, INT_MAX / 2, move_r, move_c); 82 | 83 | // Times 84 | std::clock_t c_iteration = (std::clock() - c_iteration_start) * 1000 / CLOCKS_PER_SEC; 85 | std::clock_t c_elapsed = (std::clock() - c_start) * 1000 / CLOCKS_PER_SEC; 86 | 87 | if (c_elapsed + (c_iteration * kAvgBranchingFactor * kAvgBranchingFactor) > time_limit || 88 | d >= kMaximumDepth) { 89 | if (actual_depth != nullptr) *actual_depth = d; 90 | break; 91 | } 92 | } 93 | } 94 | delete[] _gs; 95 | } 96 | 97 | int RenjuAINegamax::heuristicNegamax(char *gs, int player, int initial_depth, int depth, 98 | bool enable_ab_pruning, int alpha, int beta, 99 | int *move_r, int *move_c) { 100 | // Count node 101 | ++g_node_count; 102 | 103 | int max_score = INT_MIN; 104 | int opponent = player == 1 ? 2 : 1; 105 | 106 | // Search and sort possible moves 107 | std::vector moves_player, moves_opponent, candidate_moves; 108 | searchMovesOrdered(gs, player, &moves_player); 109 | searchMovesOrdered(gs, opponent, &moves_opponent); 110 | 111 | // End if no move could be performed 112 | if (moves_player.size() == 0) return 0; 113 | 114 | // End directly if only one move or a winning move is found 115 | if (moves_player.size() == 1 || moves_player[0].heuristic_val >= kRenjuAiEvalWinningScore) { 116 | auto move = moves_player[0]; 117 | if (move_r != nullptr) *move_r = move.r; 118 | if (move_c != nullptr) *move_c = move.c; 119 | return move.heuristic_val; 120 | } 121 | 122 | // If opponent has threatening moves, consider blocking them first 123 | bool block_opponent = false; 124 | int tmp_size = std::min(static_cast(moves_opponent.size()), 2); 125 | if (moves_opponent[0].heuristic_val >= kRenjuAiEvalThreateningScore) { 126 | block_opponent = true; 127 | for (int i = 0; i < tmp_size; ++i) { 128 | auto move = moves_opponent[i]; 129 | 130 | // Re-evaluate move as current player 131 | move.heuristic_val = RenjuAIEval::evalMove(gs, move.r, move.c, player); 132 | 133 | // Add to candidate list 134 | candidate_moves.push_back(move); 135 | } 136 | } 137 | 138 | // Set breadth 139 | int breadth = (initial_depth >> 1) - ((depth + 1) >> 1); 140 | if (breadth > 4) breadth = presetSearchBreadth[4]; 141 | else breadth = presetSearchBreadth[breadth]; 142 | 143 | // Copy moves for current player 144 | tmp_size = std::min(static_cast(moves_player.size()), breadth); 145 | for (int i = 0; i < tmp_size; ++i) 146 | candidate_moves.push_back(moves_player[i]); 147 | 148 | // Print heuristic values for debugging 149 | // if (depth >= 8) { 150 | // for (int i = 0; i < moves_player.size(); ++i) { 151 | // auto move = moves_player[i]; 152 | // std::cout << depth << " | " << move.r << ", " << move.c << ": " << move.heuristic_val << std::endl; 153 | // } 154 | // } 155 | 156 | // Loop through every move 157 | int size = static_cast(candidate_moves.size()); 158 | for (int i = 0; i < size; ++i) { 159 | auto move = candidate_moves[i]; 160 | 161 | // Execute move 162 | RenjuAIUtils::setCell(gs, move.r, move.c, static_cast(player)); 163 | 164 | // Run negamax recursively 165 | int score = 0; 166 | if (depth > 1) score = heuristicNegamax(gs, // Game state 167 | opponent, // Change player 168 | initial_depth, // Initial depth 169 | depth - 1, // Reduce depth by 1 170 | enable_ab_pruning, // Alpha-Beta 171 | -beta, // 172 | -alpha + move.heuristic_val, 173 | nullptr, // Result move not required 174 | nullptr); 175 | 176 | // Closer moves get more score 177 | if (score >= 2) score = static_cast(score * kScoreDecayFactor); 178 | 179 | // Calculate score difference 180 | move.actual_score = move.heuristic_val - score; 181 | 182 | // Store back to candidate array 183 | candidate_moves[i].actual_score = move.actual_score; 184 | 185 | // Print actual scores for debugging 186 | // if (depth >= 8) 187 | // std::cout << depth << " | " << move.r << ", " << move.c << ": " << move.actual_score << std::endl; 188 | 189 | // Restore 190 | RenjuAIUtils::setCell(gs, move.r, move.c, 0); 191 | 192 | // Update maximum score 193 | if (move.actual_score > max_score) { 194 | max_score = move.actual_score; 195 | if (move_r != nullptr) *move_r = move.r; 196 | if (move_c != nullptr) *move_c = move.c; 197 | } 198 | 199 | // Alpha-beta 200 | int max_score_decayed = max_score; 201 | if (max_score >= 2) max_score_decayed = static_cast(max_score_decayed * kScoreDecayFactor); 202 | if (max_score > alpha) alpha = max_score; 203 | if (enable_ab_pruning && max_score_decayed >= beta) break; 204 | } 205 | 206 | // If no moves that are much better than blocking threatening moves, block them. 207 | // This attempts blocking even winning is impossible if the opponent plays optimally. 208 | if (depth == initial_depth && block_opponent && max_score < 0) { 209 | auto blocking_move = candidate_moves[0]; 210 | int b_score = blocking_move.actual_score; 211 | if (b_score == 0) b_score = 1; 212 | if ((max_score - b_score) / static_cast(std::abs(b_score)) < 0.2) { 213 | if (move_r != nullptr) *move_r = blocking_move.r; 214 | if (move_c != nullptr) *move_c = blocking_move.c; 215 | max_score = blocking_move.actual_score; 216 | } 217 | } 218 | return max_score; 219 | } 220 | 221 | void RenjuAINegamax::searchMovesOrdered(const char *gs, int player, std::vector *result) { 222 | // Clear and previous result 223 | result->clear(); 224 | 225 | // Find an extent to reduce unnecessary calls to RenjuAIUtils::remoteCell 226 | int min_r = INT_MAX, min_c = INT_MAX, max_r = INT_MIN, max_c = INT_MIN; 227 | for (int r = 0; r < g_board_size; ++r) { 228 | for (int c = 0; c < g_board_size; ++c) { 229 | if (gs[g_board_size * r + c] != 0) { 230 | if (r < min_r) min_r = r; 231 | if (c < min_c) min_c = c; 232 | if (r > max_r) max_r = r; 233 | if (c > max_c) max_c = c; 234 | } 235 | } 236 | } 237 | 238 | if (min_r - 2 < 0) min_r = 2; 239 | if (min_c - 2 < 0) min_c = 2; 240 | if (max_r + 2 >= g_board_size) max_r = g_board_size - 3; 241 | if (max_c + 2 >= g_board_size) max_c = g_board_size - 3; 242 | 243 | // Loop through all cells 244 | for (int r = min_r - 2; r <= max_r + 2; ++r) { 245 | for (int c = min_c - 2; c <= max_c + 2; ++c) { 246 | // Consider only empty cells 247 | if (gs[g_board_size * r + c] != 0) continue; 248 | 249 | // Skip remote cells (no pieces within 2 cells) 250 | if (RenjuAIUtils::remoteCell(gs, r, c)) continue; 251 | 252 | Move m; 253 | m.r = r; 254 | m.c = c; 255 | 256 | // Evaluate move 257 | m.heuristic_val = RenjuAIEval::evalMove(gs, r, c, player); 258 | 259 | // Add move 260 | result->push_back(m); 261 | } 262 | } 263 | std::sort(result->begin(), result->end()); 264 | } 265 | 266 | int RenjuAINegamax::negamax(char *gs, int player, int depth, int *move_r, int *move_c) { 267 | // Initialize with a minimum score 268 | int max_score = INT_MIN; 269 | 270 | // Eval game state 271 | if (depth == 0) return RenjuAIEval::evalState(gs, player); 272 | 273 | // Loop through all cells 274 | for (int r = 0; r < g_board_size; ++r) { 275 | for (int c = 0; c < g_board_size; ++c) { 276 | // Consider only empty cells 277 | if (RenjuAIUtils::getCell(gs, r, c) != 0) continue; 278 | 279 | // Skip remote cells (no pieces within 2 cells) 280 | if (RenjuAIUtils::remoteCell(gs, r, c)) continue; 281 | 282 | // Execute move 283 | RenjuAIUtils::setCell(gs, r, c, static_cast(player)); 284 | 285 | // Run negamax recursively 286 | int s = -negamax(gs, // Game state 287 | player == 1 ? 2 : 1, // Change player 288 | depth - 1, // Reduce depth by 1 289 | nullptr, // Result move not required 290 | nullptr); 291 | 292 | // Restore 293 | RenjuAIUtils::setCell(gs, r, c, 0); 294 | 295 | // Update max score 296 | if (s > max_score) { 297 | max_score = s; 298 | if (move_r != nullptr) *move_r = r; 299 | if (move_c != nullptr) *move_c = c; 300 | } 301 | } 302 | } 303 | return max_score; 304 | } 305 | -------------------------------------------------------------------------------- /gui/client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | Gomoku 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 57 | 58 |
59 |
60 | 61 |
62 |
63 |
64 |

65 | Board 66 |
67 |
68 |
69 |
70 |

71 |
72 |
73 |
74 | 75 |
76 |
77 |
78 |
79 |
80 | 81 |
82 |
83 |
84 |

Game Status 85 | 86 | Star

87 |
88 |
89 |
90 | 91 |
92 |

Game Control

93 |
94 |   95 | 96 |
97 |
98 | 99 |
100 |

Statistics

101 |
102 | No data available. 103 |
104 |
105 |
106 |
107 |
108 | 109 | 110 | 498 | 499 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /gui/client/assets/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.3.7 (http://getbootstrap.com) 3 | * Copyright 2011-2016 Twitter, Inc. 4 | * Licensed under the MIT license 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.7",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a("#"===f?[]:f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.7",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c).prop(c,!0)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c).prop(c,!1))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target).closest(".btn");b.call(d,"toggle"),a(c.target).is('input[type="radio"], input[type="checkbox"]')||(c.preventDefault(),d.is("input,button")?d.trigger("focus"):d.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(a>this.$items.length-1||a<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.7",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.7",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);if(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),!c.isInStateTrue())return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null,a.$element=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.7",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.7",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e=a-d&&"bottom"},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); --------------------------------------------------------------------------------