Minimax.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #include "Minimax.h"
  2. #include "ChessGame.h"
  3. #include "Search.h"
  4. #include <iostream>
  5. #include <functional>
  6. #include <limits>
  7. #include <chrono>
  8. using namespace chessy;
  9. size_t chessy::perft(std::ostream& out, ChessGame& chessGame, int depth)
  10. {
  11. size_t result = 0;
  12. std::function<void(const MoveInfo&, ChessGame&, int, bool)> searcher;
  13. std::function<void(ChessGame&, int, bool)> iterate;
  14. // apply a move and search deeper
  15. searcher = [&result, &iterate] (const MoveInfo& mi, ChessGame& cg,
  16. int depth, bool print)
  17. {
  18. if (depth > 1) {
  19. UndoInfo ui = cg.doMove(mi);
  20. size_t interRes = result;
  21. iterate(cg, depth - 1, false);
  22. if (print)
  23. std::cout << mi.move.asString() << ": " <<
  24. (result - interRes) << std::endl;
  25. cg.undoMove(ui);
  26. }
  27. else {
  28. result++;
  29. }
  30. };
  31. // iterate through all positions in the current position
  32. iterate = [&searcher] (ChessGame& cg, int depth, bool print)
  33. {
  34. Search<decltype(searcher)&> search (searcher, cg);
  35. if (cg.getTurn() == WHITE_SIDE)
  36. search.iterateAll<WHITE_SIDE>(cg, depth, print);
  37. else
  38. search.iterateAll<BLACK_SIDE>(cg, depth, print);
  39. };
  40. using namespace std::chrono;
  41. auto begin = high_resolution_clock::now();
  42. iterate(chessGame, depth, true);
  43. auto end = high_resolution_clock::now();
  44. auto millis = duration_cast<milliseconds>(end - begin);
  45. double seconds = millis.count() / 1000.0;
  46. size_t nodesPerSecond = (result * 1000 * 1000 * 1000) /
  47. duration_cast<nanoseconds>(end - begin).count();
  48. out << "Searched " << result << " nodes in " << seconds <<
  49. " seconds. (at " << nodesPerSecond << " nodes per second)" << std::endl;
  50. return result;
  51. }
  52. template MiniMax::BestMove MiniMax::minimax<WHITE_SIDE>(int);
  53. template MiniMax::BestMove MiniMax::minimax<BLACK_SIDE>(int);
  54. Move MiniMax::calculateBest(int depth)
  55. {
  56. if (game.getTurn() == WHITE_SIDE) {
  57. BestMove bm = minimax<WHITE_SIDE>(depth);
  58. return bm.move;
  59. }
  60. else
  61. return minimax<BLACK_SIDE>(depth).move;
  62. }
  63. template<Side side>
  64. float MiniMax::evaluate(void) const
  65. {
  66. int piecePoints = 0;
  67. Board& bd = game.getBoard();
  68. Bitboard p = bd.getPawns<side>();
  69. Bitboard n = bd.getKnights<side>();
  70. Bitboard b = bd.getBishops<side>();
  71. Bitboard r = bd.getRooks<side>();
  72. Bitboard q = bd.getQueens<side>();
  73. Bitboard k = bd.getKing<side>();
  74. piecePoints += 1 * p.popcount();
  75. piecePoints += 3 * n.popcount();
  76. piecePoints += 3 * b.popcount();
  77. piecePoints += 4 * r.popcount();
  78. piecePoints += 6 * q.popcount();
  79. if (k == Bitboard(0ULL))
  80. piecePoints -= 100000;
  81. const Side other = otherSide(side);
  82. p = bd.getPawns<other>();
  83. n = bd.getKnights<other>();
  84. b = bd.getBishops<other>();
  85. r = bd.getRooks<other>();
  86. q = bd.getQueens<other>();
  87. k = bd.getKing<other>();
  88. piecePoints -= 1 * p.popcount();
  89. piecePoints -= 3 * n.popcount();
  90. piecePoints -= 3 * b.popcount();
  91. piecePoints -= 4 * r.popcount();
  92. piecePoints -= 6 * q.popcount();
  93. if (k == Bitboard(0ULL))
  94. piecePoints += 100000;
  95. return piecePoints;
  96. }
  97. template<Side side>
  98. MiniMax::BestMove MiniMax::minimax(int depth)
  99. {
  100. if (depth == 0) {
  101. return { {0, 0}, -evaluate<side>() };
  102. }
  103. BestMove bestMove = { {0, 0}, -std::numeric_limits<float>::infinity() };
  104. Board& board = game.getBoard();
  105. Bitboard friends;
  106. Bitboard enemies;
  107. if (side == WHITE_SIDE) {
  108. friends = board.getWhites();
  109. enemies = board.getBlacks();
  110. }
  111. else {
  112. friends = board.getBlacks();
  113. enemies = board.getWhites();
  114. }
  115. const Board temp = board;
  116. PawnPushGenerator<side> mg{ game };
  117. for (Move push : mg) {
  118. Bitboard& pawns = board.getPawns<side>();
  119. Bitboard pTemp = pawns;
  120. pawns.applyMove(push);
  121. BestMove m = minimax<otherSide(side)>(depth - 1);
  122. m.move = push;
  123. bestMove.overwriteIfBetter(m);
  124. pawns = pTemp;
  125. }
  126. PawnDoublePushGenerator<side> dp{ game };
  127. for (Move push : dp) {
  128. Bitboard& pawns = board.getPawns<side>();
  129. Bitboard pTemp = pawns;
  130. pawns.applyMove(push);
  131. BestMove m = minimax<otherSide(side)>(depth - 1);
  132. m.move = push;
  133. bestMove.overwriteIfBetter(m);
  134. pawns = pTemp;
  135. }
  136. PawnCaptureGenerator<side, LEFT> pl{ game };
  137. for (Move capture : pl) {
  138. Bitboard& pawns = board.getPawns<side>();
  139. board.removeAt(capture.destination);
  140. pawns.applyMove(capture);
  141. BestMove m = minimax<otherSide(side)>(depth - 1);
  142. m.move = capture;
  143. bestMove.overwriteIfBetter(m);
  144. board = temp;
  145. }
  146. PawnCaptureGenerator<side, RIGHT> pr{ game };
  147. for (Move capture : pr) {
  148. Bitboard& pawns = board.getPawns<side>();
  149. board.removeAt(capture.destination);
  150. pawns.applyMove(capture);
  151. BestMove m = minimax<otherSide(side)>(depth - 1);
  152. m.move = capture;
  153. bestMove.overwriteIfBetter(m);
  154. board = temp;
  155. }
  156. PromotionGenerator<side> pg{ game };
  157. for (Move promotion : pg) {
  158. Bitboard& pawns = board.getPawns<side>();
  159. board.removeAt(promotion.destination);
  160. pawns.applyMove(promotion);
  161. BestMove m = minimax<otherSide(side)>(depth - 1);
  162. m.move = promotion;
  163. bestMove.overwriteIfBetter(m);
  164. board = temp;
  165. }
  166. Bitboard& ns = board.getKnights<side>();
  167. PositionSet knights { ns };
  168. for (auto knight : knights) {
  169. for (auto pos : KnightMoveGenerator{ knight, friends }) {
  170. Move move = { knight, pos };
  171. board.removeAt(move.destination);
  172. ns.applyMove(move);
  173. BestMove m = minimax<otherSide(side)>(depth - 1);
  174. m.move = move;
  175. bestMove.overwriteIfBetter(m);
  176. board = temp;
  177. }
  178. }
  179. Bitboard& bs = board.getBishops<side>();
  180. PositionSet bishops { bs };
  181. for (auto bishop : bishops) {
  182. for (auto pos : PrimitiveBishopMoveGenerator{ bishop, enemies, friends }) {
  183. Move move = { bishop, pos };
  184. board.removeAt(move.destination);
  185. bs.applyMove(move);
  186. BestMove m = minimax<otherSide(side)>(depth - 1);
  187. m.move = move;
  188. bestMove.overwriteIfBetter(m);
  189. board = temp;
  190. }
  191. }
  192. Bitboard& rs = board.getRooks<side>();
  193. PositionSet rooks { rs };
  194. for (auto rook : rooks) {
  195. for (auto pos : PrimitiveRookMoveGenerator{ rook, enemies, friends }) {
  196. Move move = { rook, pos };
  197. board.removeAt(move.destination);
  198. rs.applyMove(move);
  199. BestMove m = minimax<otherSide(side)>(depth - 1);
  200. m.move = move;
  201. bestMove.overwriteIfBetter(m);
  202. board = temp;
  203. }
  204. }
  205. Bitboard& qs = board.getQueens<side>();
  206. PositionSet queens { qs };
  207. for (auto queen : queens) {
  208. for (auto pos : PrimitiveQueenMoveGenerator{ queen, enemies, friends }) {
  209. Move move = { queen, pos };
  210. board.removeAt(move.destination);
  211. qs.applyMove(move);
  212. BestMove m = minimax<otherSide(side)>(depth - 1);
  213. m.move = move;
  214. bestMove.overwriteIfBetter(m);
  215. board = temp;
  216. }
  217. }
  218. Bitboard& king = board.getKing<side>();
  219. Index kingIndex = king.getLeastSignificantBit();
  220. for (auto pos : KingMoveGenerator{ king, friends }) {
  221. Move move = { kingIndex, pos };
  222. board.removeAt(pos);
  223. king.applyMove(move);
  224. BestMove m = minimax<otherSide(side)>(depth - 1);
  225. m.move = move;
  226. //if (depth >= 3)
  227. // std::cout << m.move.asString() << " " << bestMove.value << " -> " << m.value << std::endl;
  228. bestMove.overwriteIfBetter(m);
  229. board = temp;
  230. }
  231. if (side == WHITE_SIDE) {
  232. if (game.getCanCastleKingSide(side)) {
  233. if((board.getWhites().bits & 0x6) == 0) {
  234. Move kingMove = {3, 1};
  235. Move rookMove = {0, 2};
  236. king.applyMove(kingMove);
  237. rs.applyMove(rookMove);
  238. board = temp;
  239. }
  240. }
  241. }
  242. for (auto pos : CastlingGenerator<side>{ game }) {
  243. Move move = { kingIndex, pos };
  244. king.applyMove(move);
  245. BestMove m = minimax<otherSide(side)>(depth - 1);
  246. m.move = move;
  247. //if (depth >= 3)
  248. // std::cout << m.move.asString() << " " << bestMove.value << " -> " << m.value << std::endl;
  249. bestMove.overwriteIfBetter(m);
  250. board = temp;
  251. }
  252. float v = evaluate<side>();
  253. bestMove.value *= 0.9f;
  254. bestMove.value += v * 0.2f;
  255. return -bestMove;
  256. }