Minimax.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. #include <iostream>
  53. using namespace std;
  54. std::pair<Move, MoveValue> chessy::miniMax(ChessGame& cg, int depth)
  55. {
  56. std::vector<Move> moves;
  57. moves.reserve(200);
  58. if (cg.getTurn() == WHITE_SIDE)
  59. generateAllMoves<WHITE_SIDE>(cg, moves);
  60. else
  61. generateAllMoves<BLACK_SIDE>(cg, moves);
  62. const Board& b = cg.getBoard();
  63. auto isCheck = [&cg, &b] () {
  64. return cg.getTurn() == BLACK_SIDE ? b.isCheck<WHITE_SIDE>() :
  65. b.isCheck<BLACK_SIDE>();
  66. };
  67. Move bestMove{ 0, 0 };
  68. MoveValue alpha = -1e+30;
  69. MoveValue beta = 1e+30;
  70. for (Move move : moves) {
  71. MoveInfo mi{ move, cg };
  72. UndoInfo ui = cg.doMove(mi);
  73. MoveValue val;
  74. if (isCheck()) {
  75. cg.undoMove(ui);
  76. continue;
  77. }
  78. else {
  79. val = -negamaxImplementation(cg, depth - 1, -beta, -alpha);
  80. }
  81. //cout << move.asString() << ": " << val << ", " << best << ((val > best) ? " good" : " bad") << endl;
  82. //MoveValue val = 0.0;
  83. cg.undoMove(ui);
  84. if(val > alpha) {
  85. alpha = val;
  86. bestMove = move;
  87. }
  88. }
  89. return { bestMove, alpha }; //negamaxImplementation(chessGame, 5);
  90. }
  91. MoveValue chessy::negamaxImplementation(ChessGame& cg, int depth,
  92. chessy::MoveValue alpha, chessy::MoveValue beta)
  93. {
  94. if (depth <= 0) {
  95. if (cg.getTurn() == WHITE_SIDE)
  96. return evaluate<WHITE_SIDE>(cg);
  97. else
  98. return evaluate<BLACK_SIDE>(cg);
  99. }
  100. const Board& b = cg.getBoard();
  101. auto isCheck = [&cg, &b] () {
  102. return cg.getTurn() == BLACK_SIDE ? b.isCheck<WHITE_SIDE>() :
  103. b.isCheck<BLACK_SIDE>();
  104. };
  105. std::vector<Move> moves;
  106. if (cg.getTurn() == WHITE_SIDE)
  107. generateAllMoves<WHITE_SIDE>(cg, moves);
  108. else
  109. generateAllMoves<BLACK_SIDE>(cg, moves);
  110. bool thereIsMove = false;
  111. for (Move move : moves) {
  112. MoveInfo mi{ move, cg };
  113. UndoInfo ui = cg.doMove(mi);
  114. MoveValue val;
  115. if (isCheck())
  116. val = -1e+30;
  117. else {
  118. val = -negamaxImplementation(cg, depth - 1, -beta, -alpha);
  119. thereIsMove = true;
  120. }
  121. cg.undoMove(ui);
  122. if(val >= beta)
  123. return beta;
  124. if(val > alpha)
  125. alpha = val;
  126. }
  127. if (!thereIsMove)
  128. return 0.0;
  129. return alpha;
  130. }
  131. template<Side side>
  132. MoveValue chessy::evaluate(const ChessGame& game)
  133. {
  134. MoveValue piecePoints = 0;
  135. const Board& bd = game.getBoard();
  136. Bitboard p = bd.getPawns<side>();
  137. Bitboard n = bd.getKnights<side>();
  138. Bitboard b = bd.getBishops<side>();
  139. Bitboard r = bd.getRooks<side>();
  140. Bitboard q = bd.getQueens<side>();
  141. Bitboard k = bd.getKing<side>();
  142. for (auto pawn : PositionSet{ p })
  143. piecePoints += 0.5 / 8.0 * pawn.getRow() + 1.0;
  144. piecePoints += 1 * p.popcount();
  145. piecePoints += 3 * n.popcount();
  146. piecePoints += 3 * b.popcount();
  147. piecePoints += 4 * r.popcount();
  148. piecePoints += 6 * q.popcount();
  149. if (k == Bitboard(0ULL))
  150. piecePoints -= 100000;
  151. constexpr Side other = otherSide(side);
  152. p = bd.getPawns<other>();
  153. n = bd.getKnights<other>();
  154. b = bd.getBishops<other>();
  155. r = bd.getRooks<other>();
  156. q = bd.getQueens<other>();
  157. k = bd.getKing<other>();
  158. for (auto pawn : PositionSet{ p })
  159. piecePoints += 0.5 / 8.0 * (7 - pawn.getRow()) + 1.0;
  160. piecePoints -= 1 * p.popcount();
  161. piecePoints -= 3 * n.popcount();
  162. piecePoints -= 3 * b.popcount();
  163. piecePoints -= 4 * r.popcount();
  164. piecePoints -= 6 * q.popcount();
  165. if (k == Bitboard(0ULL))
  166. piecePoints += 100000;
  167. return piecePoints;
  168. }
  169. /*
  170. template MiniMax::BestMove MiniMax::minimax<WHITE_SIDE>(int);
  171. template MiniMax::BestMove MiniMax::minimax<BLACK_SIDE>(int);
  172. Move MiniMax::calculateBest(int depth)
  173. {
  174. if (game.getTurn() == WHITE_SIDE) {
  175. BestMove bm = minimax<WHITE_SIDE>(depth);
  176. return bm.move;
  177. }
  178. else
  179. return minimax<BLACK_SIDE>(depth).move;
  180. }
  181. template<Side side>
  182. float MiniMax::evaluate(void) const
  183. {
  184. int piecePoints = 0;
  185. Board& bd = game.getBoard();
  186. Bitboard p = bd.getPawns<side>();
  187. Bitboard n = bd.getKnights<side>();
  188. Bitboard b = bd.getBishops<side>();
  189. Bitboard r = bd.getRooks<side>();
  190. Bitboard q = bd.getQueens<side>();
  191. Bitboard k = bd.getKing<side>();
  192. piecePoints += 1 * p.popcount();
  193. piecePoints += 3 * n.popcount();
  194. piecePoints += 3 * b.popcount();
  195. piecePoints += 4 * r.popcount();
  196. piecePoints += 6 * q.popcount();
  197. if (k == Bitboard(0ULL))
  198. piecePoints -= 100000;
  199. const Side other = otherSide(side);
  200. p = bd.getPawns<other>();
  201. n = bd.getKnights<other>();
  202. b = bd.getBishops<other>();
  203. r = bd.getRooks<other>();
  204. q = bd.getQueens<other>();
  205. k = bd.getKing<other>();
  206. piecePoints -= 1 * p.popcount();
  207. piecePoints -= 3 * n.popcount();
  208. piecePoints -= 3 * b.popcount();
  209. piecePoints -= 4 * r.popcount();
  210. piecePoints -= 6 * q.popcount();
  211. if (k == Bitboard(0ULL))
  212. piecePoints += 100000;
  213. return piecePoints;
  214. }
  215. template<Side side>
  216. MiniMax::BestMove MiniMax::minimax(int depth)
  217. {
  218. if (depth == 0) {
  219. return { {0, 0}, -evaluate<side>() };
  220. }
  221. BestMove bestMove = { {0, 0}, -std::numeric_limits<float>::infinity() };
  222. Board& board = game.getBoard();
  223. Bitboard friends;
  224. Bitboard enemies;
  225. if (side == WHITE_SIDE) {
  226. friends = board.getWhites();
  227. enemies = board.getBlacks();
  228. }
  229. else {
  230. friends = board.getBlacks();
  231. enemies = board.getWhites();
  232. }
  233. const Board temp = board;
  234. PawnPushGenerator<side> mg{ game };
  235. for (Move push : mg) {
  236. Bitboard& pawns = board.getPawns<side>();
  237. Bitboard pTemp = pawns;
  238. pawns.applyMove(push);
  239. BestMove m = minimax<otherSide(side)>(depth - 1);
  240. m.move = push;
  241. bestMove.overwriteIfBetter(m);
  242. pawns = pTemp;
  243. }
  244. PawnDoublePushGenerator<side> dp{ game };
  245. for (Move push : dp) {
  246. Bitboard& pawns = board.getPawns<side>();
  247. Bitboard pTemp = pawns;
  248. pawns.applyMove(push);
  249. BestMove m = minimax<otherSide(side)>(depth - 1);
  250. m.move = push;
  251. bestMove.overwriteIfBetter(m);
  252. pawns = pTemp;
  253. }
  254. PawnCaptureGenerator<side, LEFT> pl{ game };
  255. for (Move capture : pl) {
  256. Bitboard& pawns = board.getPawns<side>();
  257. board.removeAt(capture.destination);
  258. pawns.applyMove(capture);
  259. BestMove m = minimax<otherSide(side)>(depth - 1);
  260. m.move = capture;
  261. bestMove.overwriteIfBetter(m);
  262. board = temp;
  263. }
  264. PawnCaptureGenerator<side, RIGHT> pr{ game };
  265. for (Move capture : pr) {
  266. Bitboard& pawns = board.getPawns<side>();
  267. board.removeAt(capture.destination);
  268. pawns.applyMove(capture);
  269. BestMove m = minimax<otherSide(side)>(depth - 1);
  270. m.move = capture;
  271. bestMove.overwriteIfBetter(m);
  272. board = temp;
  273. }
  274. PromotionGenerator<side> pg{ game };
  275. for (Move promotion : pg) {
  276. Bitboard& pawns = board.getPawns<side>();
  277. board.removeAt(promotion.destination);
  278. pawns.applyMove(promotion);
  279. BestMove m = minimax<otherSide(side)>(depth - 1);
  280. m.move = promotion;
  281. bestMove.overwriteIfBetter(m);
  282. board = temp;
  283. }
  284. Bitboard& ns = board.getKnights<side>();
  285. PositionSet knights { ns };
  286. for (auto knight : knights) {
  287. for (auto pos : KnightMoveGenerator{ knight, friends }) {
  288. Move move = { knight, pos };
  289. board.removeAt(move.destination);
  290. ns.applyMove(move);
  291. BestMove m = minimax<otherSide(side)>(depth - 1);
  292. m.move = move;
  293. bestMove.overwriteIfBetter(m);
  294. board = temp;
  295. }
  296. }
  297. Bitboard& bs = board.getBishops<side>();
  298. PositionSet bishops { bs };
  299. for (auto bishop : bishops) {
  300. for (auto pos : PrimitiveBishopMoveGenerator{ bishop, enemies, friends }) {
  301. Move move = { bishop, pos };
  302. board.removeAt(move.destination);
  303. bs.applyMove(move);
  304. BestMove m = minimax<otherSide(side)>(depth - 1);
  305. m.move = move;
  306. bestMove.overwriteIfBetter(m);
  307. board = temp;
  308. }
  309. }
  310. Bitboard& rs = board.getRooks<side>();
  311. PositionSet rooks { rs };
  312. for (auto rook : rooks) {
  313. for (auto pos : PrimitiveRookMoveGenerator{ rook, enemies, friends }) {
  314. Move move = { rook, pos };
  315. board.removeAt(move.destination);
  316. rs.applyMove(move);
  317. BestMove m = minimax<otherSide(side)>(depth - 1);
  318. m.move = move;
  319. bestMove.overwriteIfBetter(m);
  320. board = temp;
  321. }
  322. }
  323. Bitboard& qs = board.getQueens<side>();
  324. PositionSet queens { qs };
  325. for (auto queen : queens) {
  326. for (auto pos : PrimitiveQueenMoveGenerator{ queen, enemies, friends }) {
  327. Move move = { queen, pos };
  328. board.removeAt(move.destination);
  329. qs.applyMove(move);
  330. BestMove m = minimax<otherSide(side)>(depth - 1);
  331. m.move = move;
  332. bestMove.overwriteIfBetter(m);
  333. board = temp;
  334. }
  335. }
  336. Bitboard& king = board.getKing<side>();
  337. Index kingIndex = king.getLeastSignificantBit();
  338. for (auto pos : KingMoveGenerator{ king, friends }) {
  339. Move move = { kingIndex, pos };
  340. board.removeAt(pos);
  341. king.applyMove(move);
  342. BestMove m = minimax<otherSide(side)>(depth - 1);
  343. m.move = move;
  344. //if (depth >= 3)
  345. // std::cout << m.move.asString() << " " << bestMove.value << " -> " << m.value << std::endl;
  346. bestMove.overwriteIfBetter(m);
  347. board = temp;
  348. }
  349. if (side == WHITE_SIDE) {
  350. if (game.getCanCastleKingSide(side)) {
  351. if((board.getWhites().bits & 0x6) == 0) {
  352. Move kingMove = {3, 1};
  353. Move rookMove = {0, 2};
  354. king.applyMove(kingMove);
  355. rs.applyMove(rookMove);
  356. board = temp;
  357. }
  358. }
  359. }
  360. for (auto pos : CastlingGenerator<side>{ game }) {
  361. Move move = { kingIndex, pos };
  362. king.applyMove(move);
  363. BestMove m = minimax<otherSide(side)>(depth - 1);
  364. m.move = move;
  365. //if (depth >= 3)
  366. // std::cout << m.move.asString() << " " << bestMove.value << " -> " << m.value << std::endl;
  367. bestMove.overwriteIfBetter(m);
  368. board = temp;
  369. }
  370. float v = evaluate<side>();
  371. bestMove.value *= 0.9f;
  372. bestMove.value += v * 0.2f;
  373. return -bestMove;
  374. }
  375. */