Minimax.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. if (print)
  29. std::cout << mi.move.asString() << ": " <<
  30. 1 << std::endl;
  31. result++;
  32. }
  33. };
  34. // iterate through all positions in the current position
  35. iterate = [&searcher] (ChessGame& cg, int depth, bool print)
  36. {
  37. Search<decltype(searcher)&> search (searcher, cg);
  38. if (cg.getTurn() == WHITE_SIDE)
  39. search.iterateAll<WHITE_SIDE>(cg, depth, print);
  40. else
  41. search.iterateAll<BLACK_SIDE>(cg, depth, print);
  42. };
  43. using namespace std::chrono;
  44. auto begin = high_resolution_clock::now();
  45. iterate(chessGame, depth, true);
  46. auto end = high_resolution_clock::now();
  47. auto millis = duration_cast<milliseconds>(end - begin);
  48. double seconds = millis.count() / 1000.0;
  49. size_t nodesPerSecond = (result * 1000 * 1000 * 1000) /
  50. duration_cast<nanoseconds>(end - begin).count();
  51. out << "Searched " << result << " nodes in " << seconds <<
  52. " seconds. (at " << nodesPerSecond << " nodes per second)" << std::endl;
  53. return result;
  54. }*/
  55. size_t chessy::perft(std::ostream& out, ChessGame& cg, int depth)
  56. {
  57. std::function<size_t(bool, int)> iterate = [&](bool print, int depth) -> size_t {
  58. if (depth <= 0)
  59. return 1;
  60. std::vector<Move> moves;
  61. moves.reserve(50);
  62. if (cg.getTurn() == WHITE_SIDE)
  63. generateAllMoves<WHITE_SIDE, false>(cg, moves);
  64. else
  65. generateAllMoves<BLACK_SIDE, false>(cg, moves);
  66. size_t sum = 0;
  67. for (Move move : moves) {
  68. MoveInfo mi{ move, cg };
  69. UndoInfo ui = cg.doMove(mi);
  70. size_t v = iterate(false, depth - 1);
  71. if (print)
  72. out << mi.move.asString() << ": " << v << std::endl;
  73. sum += v;
  74. cg.undoMove(ui);
  75. }
  76. return sum;
  77. };
  78. using namespace std::chrono;
  79. auto begin = high_resolution_clock::now();
  80. size_t sum = iterate(true, depth);
  81. auto end = high_resolution_clock::now();
  82. auto millis = duration_cast<milliseconds>(end - begin);
  83. double seconds = millis.count() / 1000.0;
  84. size_t nodesPerSecond = (sum * 1000 * 1000 * 1000) /
  85. duration_cast<nanoseconds>(end - begin).count();
  86. out << "Searched " << sum << " nodes in " << seconds <<
  87. " seconds. (at " << nodesPerSecond << " nodes per second)" << std::endl;
  88. return sum;
  89. }
  90. #include <iostream>
  91. using namespace std;
  92. std::pair<Move, MoveValue> chessy::miniMax(ChessGame& cg, int depth, const TimeCheck& check)
  93. {
  94. std::vector<Move> moves;
  95. moves.reserve(200);
  96. if (cg.getTurn() == WHITE_SIDE) {
  97. generateAllMoves<WHITE_SIDE, false>(cg, moves);
  98. orderMoves<WHITE_SIDE>(cg, moves);
  99. }
  100. else {
  101. generateAllMoves<BLACK_SIDE, false>(cg, moves);
  102. orderMoves<BLACK_SIDE>(cg, moves);
  103. }
  104. const Board& b = cg.getBoard();
  105. auto isCheck = [&cg, &b] () {
  106. return cg.getTurn() == BLACK_SIDE ? b.isCheck<WHITE_SIDE>() :
  107. b.isCheck<BLACK_SIDE>();
  108. };
  109. Move bestMove{ 0, 0 };
  110. MoveValue alpha = -1e+30;
  111. MoveValue beta = 1e+30;
  112. Move lastValidMove = bestMove;
  113. for (Move move : moves) {
  114. MoveInfo mi{ move, cg };
  115. UndoInfo ui = cg.doMove(mi);
  116. MoveValue val;
  117. if (isCheck()) {
  118. cg.undoMove(ui);
  119. continue;
  120. }
  121. else {
  122. lastValidMove = move;
  123. val = -negamaxImplementation(cg, depth - 1, -beta, -alpha, check);
  124. }
  125. //cout << move.asString() << ": " << val << endl;
  126. cg.undoMove(ui);
  127. if(val > alpha) {
  128. alpha = val;
  129. bestMove = move;
  130. }
  131. if (check())
  132. break;
  133. }
  134. if (bestMove.origin == 0 && bestMove.destination == 0) {
  135. bestMove = lastValidMove;
  136. }
  137. return { bestMove, alpha }; //negamaxImplementation(chessGame, 5);
  138. }
  139. MoveValue chessy::negamaxImplementation(ChessGame& cg, int depth,
  140. chessy::MoveValue alpha, chessy::MoveValue beta, const TimeCheck& check)
  141. {
  142. if (depth < 3) {
  143. if (check())
  144. return alpha;
  145. }
  146. if (depth <= 0)
  147. return quiescence(cg, 3, alpha, beta);
  148. //return evaluate(cg);
  149. const Board& b = cg.getBoard();
  150. auto isCheck = [&cg, &b] (Side turn) {
  151. return turn == BLACK_SIDE ? b.isCheck<WHITE_SIDE>() :
  152. b.isCheck<BLACK_SIDE>();
  153. };
  154. std::vector<Move> moves;
  155. moves.reserve(80);
  156. if (cg.getTurn() == WHITE_SIDE) {
  157. generateAllMoves<WHITE_SIDE, false>(cg, moves);
  158. orderMoves<WHITE_SIDE>(cg, moves);
  159. }
  160. else {
  161. generateAllMoves<BLACK_SIDE, false>(cg, moves);
  162. orderMoves<BLACK_SIDE>(cg, moves);
  163. }
  164. bool thereIsMove = false;
  165. for (Move move : moves) {
  166. MoveInfo mi{ move, cg };
  167. UndoInfo ui = cg.doMove(mi);
  168. MoveValue val;
  169. if (isCheck(cg.getTurn()))
  170. val = -1e+30;
  171. else {
  172. val = -negamaxImplementation(cg, depth - 1, -beta, -alpha, check);
  173. thereIsMove = true;
  174. }
  175. cg.undoMove(ui);
  176. if(val >= beta)
  177. return beta;
  178. if(val > alpha)
  179. alpha = val;
  180. }
  181. if (!thereIsMove)
  182. return isCheck(otherSide(cg.getTurn())) ? -1e+30 : 0.0;
  183. return alpha;
  184. }
  185. MoveValue chessy::quiescence(ChessGame& cg, int maxDepth,
  186. MoveValue alpha, MoveValue beta)
  187. {
  188. MoveValue standingPat = evaluate(cg);
  189. if (maxDepth <= 0)
  190. return standingPat;
  191. if (standingPat >= beta)
  192. return beta;
  193. if(standingPat > alpha)
  194. alpha = standingPat;
  195. HashValue hv = cg.getHash();
  196. const auto& history = cg.getHistory();
  197. int equalCount = 0;
  198. /*for (auto i = cg.getHistory().cend() - 1; i >= (history.size() > 100? history.cend()-99 : history.cbegin()); i--) {
  199. if (*i == hv) {
  200. equalCount++;
  201. if (equalCount >= 3)
  202. return 0;
  203. }
  204. }*/
  205. for (auto hash : history) {
  206. if (hash == hv) {
  207. equalCount++;
  208. if (equalCount >= 3)
  209. return 0;
  210. }
  211. }
  212. const Board& b = cg.getBoard();
  213. auto isCheck = [&cg, &b] (Side turn) {
  214. return turn == BLACK_SIDE ? b.isCheck<WHITE_SIDE>() :
  215. b.isCheck<BLACK_SIDE>();
  216. };
  217. std::vector<Move> moves;
  218. moves.reserve(50);
  219. if (cg.getTurn() == WHITE_SIDE) {
  220. generateAllMoves<WHITE_SIDE, true>(cg, moves);
  221. orderMoves<WHITE_SIDE>(cg, moves);
  222. }
  223. else {
  224. generateAllMoves<BLACK_SIDE, true>(cg, moves);
  225. orderMoves<BLACK_SIDE>(cg, moves);
  226. }
  227. bool thereIsMove = false;
  228. for (Move move : moves) {
  229. MoveInfo mi{ move, cg };
  230. UndoInfo ui = cg.doMove(mi);
  231. MoveValue val;
  232. if (isCheck(cg.getTurn()))
  233. val = -1e+30;
  234. else {
  235. val = -quiescence(cg, maxDepth - 1, -beta, -alpha);
  236. thereIsMove = true;
  237. }
  238. cg.undoMove(ui);
  239. if(val >= beta)
  240. return beta;
  241. if(val > alpha)
  242. alpha = val;
  243. }
  244. if (!thereIsMove)
  245. return isCheck(otherSide(cg.getTurn())) ? -1e+30 : 0.0;
  246. return alpha;
  247. }
  248. /*
  249. MoveValue chessy::quiescence(ChessGame& cg, int maxDepth,
  250. MoveValue alpha, MoveValue beta)
  251. {
  252. MoveValue standingPat = evaluate(cg);
  253. if (maxDepth <= 0)
  254. return standingPat;
  255. if (beta <= standingPat)
  256. return beta;
  257. if (alpha < standingPat)
  258. alpha = standingPat;
  259. const Board& b = cg.getBoard();
  260. auto isCheck = [&cg, &b] (Side turn) {
  261. return turn == BLACK_SIDE ? b.isCheck<WHITE_SIDE>() :
  262. b.isCheck<BLACK_SIDE>();
  263. };
  264. std::vector<Move> moves;
  265. moves.reserve(50);
  266. if (cg.getTurn() == WHITE_SIDE) {
  267. generateAllMoves<WHITE_SIDE, true>(cg, moves);
  268. orderMoves<WHITE_SIDE>(cg, moves);
  269. }
  270. else {
  271. generateAllMoves<BLACK_SIDE, true>(cg, moves);
  272. orderMoves<BLACK_SIDE>(cg, moves);
  273. }
  274. bool thereIsMove = false;
  275. for (Move move : moves) {
  276. MoveInfo mi{ move, cg };
  277. UndoInfo ui = cg.doMove(mi);
  278. MoveValue val;
  279. if (isCheck(cg.getTurn()))
  280. val = -1e+30;
  281. else {
  282. val = -quiescence(cg, maxDepth - 1, -beta, -alpha);
  283. if (val == 0.0f)
  284. int s = 23;
  285. thereIsMove = true;
  286. }
  287. cg.undoMove(ui);
  288. if(val >= beta)
  289. return beta;
  290. if(val > alpha)
  291. alpha = val;
  292. }
  293. if (!thereIsMove)
  294. return isCheck(otherSide(cg.getTurn())) ? -1e+30 : 0.0;
  295. return alpha;
  296. }*/
  297. /*
  298. template MiniMax::BestMove MiniMax::minimax<WHITE_SIDE>(int);
  299. template MiniMax::BestMove MiniMax::minimax<BLACK_SIDE>(int);
  300. Move MiniMax::calculateBest(int depth)
  301. {
  302. if (game.getTurn() == WHITE_SIDE) {
  303. BestMove bm = minimax<WHITE_SIDE>(depth);
  304. return bm.move;
  305. }
  306. else
  307. return minimax<BLACK_SIDE>(depth).move;
  308. }
  309. template<Side side>
  310. float MiniMax::evaluate(void) const
  311. {
  312. int piecePoints = 0;
  313. Board& bd = game.getBoard();
  314. Bitboard p = bd.getPawns<side>();
  315. Bitboard n = bd.getKnights<side>();
  316. Bitboard b = bd.getBishops<side>();
  317. Bitboard r = bd.getRooks<side>();
  318. Bitboard q = bd.getQueens<side>();
  319. Bitboard k = bd.getKing<side>();
  320. piecePoints += 1 * p.popcount();
  321. piecePoints += 3 * n.popcount();
  322. piecePoints += 3 * b.popcount();
  323. piecePoints += 4 * r.popcount();
  324. piecePoints += 6 * q.popcount();
  325. if (k == Bitboard(0ULL))
  326. piecePoints -= 100000;
  327. const Side other = otherSide(side);
  328. p = bd.getPawns<other>();
  329. n = bd.getKnights<other>();
  330. b = bd.getBishops<other>();
  331. r = bd.getRooks<other>();
  332. q = bd.getQueens<other>();
  333. k = bd.getKing<other>();
  334. piecePoints -= 1 * p.popcount();
  335. piecePoints -= 3 * n.popcount();
  336. piecePoints -= 3 * b.popcount();
  337. piecePoints -= 4 * r.popcount();
  338. piecePoints -= 6 * q.popcount();
  339. if (k == Bitboard(0ULL))
  340. piecePoints += 100000;
  341. return piecePoints;
  342. }
  343. template<Side side>
  344. MiniMax::BestMove MiniMax::minimax(int depth)
  345. {
  346. if (depth == 0) {
  347. return { {0, 0}, -evaluate<side>() };
  348. }
  349. BestMove bestMove = { {0, 0}, -std::numeric_limits<float>::infinity() };
  350. Board& board = game.getBoard();
  351. Bitboard friends;
  352. Bitboard enemies;
  353. if (side == WHITE_SIDE) {
  354. friends = board.getWhites();
  355. enemies = board.getBlacks();
  356. }
  357. else {
  358. friends = board.getBlacks();
  359. enemies = board.getWhites();
  360. }
  361. const Board temp = board;
  362. PawnPushGenerator<side> mg{ game };
  363. for (Move push : mg) {
  364. Bitboard& pawns = board.getPawns<side>();
  365. Bitboard pTemp = pawns;
  366. pawns.applyMove(push);
  367. BestMove m = minimax<otherSide(side)>(depth - 1);
  368. m.move = push;
  369. bestMove.overwriteIfBetter(m);
  370. pawns = pTemp;
  371. }
  372. PawnDoublePushGenerator<side> dp{ game };
  373. for (Move push : dp) {
  374. Bitboard& pawns = board.getPawns<side>();
  375. Bitboard pTemp = pawns;
  376. pawns.applyMove(push);
  377. BestMove m = minimax<otherSide(side)>(depth - 1);
  378. m.move = push;
  379. bestMove.overwriteIfBetter(m);
  380. pawns = pTemp;
  381. }
  382. PawnCaptureGenerator<side, LEFT> pl{ game };
  383. for (Move capture : pl) {
  384. Bitboard& pawns = board.getPawns<side>();
  385. board.removeAt(capture.destination);
  386. pawns.applyMove(capture);
  387. BestMove m = minimax<otherSide(side)>(depth - 1);
  388. m.move = capture;
  389. bestMove.overwriteIfBetter(m);
  390. board = temp;
  391. }
  392. PawnCaptureGenerator<side, RIGHT> pr{ game };
  393. for (Move capture : pr) {
  394. Bitboard& pawns = board.getPawns<side>();
  395. board.removeAt(capture.destination);
  396. pawns.applyMove(capture);
  397. BestMove m = minimax<otherSide(side)>(depth - 1);
  398. m.move = capture;
  399. bestMove.overwriteIfBetter(m);
  400. board = temp;
  401. }
  402. PromotionGenerator<side> pg{ game };
  403. for (Move promotion : pg) {
  404. Bitboard& pawns = board.getPawns<side>();
  405. board.removeAt(promotion.destination);
  406. pawns.applyMove(promotion);
  407. BestMove m = minimax<otherSide(side)>(depth - 1);
  408. m.move = promotion;
  409. bestMove.overwriteIfBetter(m);
  410. board = temp;
  411. }
  412. Bitboard& ns = board.getKnights<side>();
  413. PositionSet knights { ns };
  414. for (auto knight : knights) {
  415. for (auto pos : KnightMoveGenerator{ knight, friends }) {
  416. Move move = { knight, pos };
  417. board.removeAt(move.destination);
  418. ns.applyMove(move);
  419. BestMove m = minimax<otherSide(side)>(depth - 1);
  420. m.move = move;
  421. bestMove.overwriteIfBetter(m);
  422. board = temp;
  423. }
  424. }
  425. Bitboard& bs = board.getBishops<side>();
  426. PositionSet bishops { bs };
  427. for (auto bishop : bishops) {
  428. for (auto pos : PrimitiveBishopMoveGenerator{ bishop, enemies, friends }) {
  429. Move move = { bishop, pos };
  430. board.removeAt(move.destination);
  431. bs.applyMove(move);
  432. BestMove m = minimax<otherSide(side)>(depth - 1);
  433. m.move = move;
  434. bestMove.overwriteIfBetter(m);
  435. board = temp;
  436. }
  437. }
  438. Bitboard& rs = board.getRooks<side>();
  439. PositionSet rooks { rs };
  440. for (auto rook : rooks) {
  441. for (auto pos : PrimitiveRookMoveGenerator{ rook, enemies, friends }) {
  442. Move move = { rook, pos };
  443. board.removeAt(move.destination);
  444. rs.applyMove(move);
  445. BestMove m = minimax<otherSide(side)>(depth - 1);
  446. m.move = move;
  447. bestMove.overwriteIfBetter(m);
  448. board = temp;
  449. }
  450. }
  451. Bitboard& qs = board.getQueens<side>();
  452. PositionSet queens { qs };
  453. for (auto queen : queens) {
  454. for (auto pos : PrimitiveQueenMoveGenerator{ queen, enemies, friends }) {
  455. Move move = { queen, pos };
  456. board.removeAt(move.destination);
  457. qs.applyMove(move);
  458. BestMove m = minimax<otherSide(side)>(depth - 1);
  459. m.move = move;
  460. bestMove.overwriteIfBetter(m);
  461. board = temp;
  462. }
  463. }
  464. Bitboard& king = board.getKing<side>();
  465. Index kingIndex = king.getLeastSignificantBit();
  466. for (auto pos : KingMoveGenerator{ king, friends }) {
  467. Move move = { kingIndex, pos };
  468. board.removeAt(pos);
  469. king.applyMove(move);
  470. BestMove m = minimax<otherSide(side)>(depth - 1);
  471. m.move = move;
  472. //if (depth >= 3)
  473. // std::cout << m.move.asString() << " " << bestMove.value << " -> " << m.value << std::endl;
  474. bestMove.overwriteIfBetter(m);
  475. board = temp;
  476. }
  477. if (side == WHITE_SIDE) {
  478. if (game.getCanCastleKingSide(side)) {
  479. if((board.getWhites().bits & 0x6) == 0) {
  480. Move kingMove = {3, 1};
  481. Move rookMove = {0, 2};
  482. king.applyMove(kingMove);
  483. rs.applyMove(rookMove);
  484. board = temp;
  485. }
  486. }
  487. }
  488. for (auto pos : CastlingGenerator<side>{ game }) {
  489. Move move = { kingIndex, pos };
  490. king.applyMove(move);
  491. BestMove m = minimax<otherSide(side)>(depth - 1);
  492. m.move = move;
  493. //if (depth >= 3)
  494. // std::cout << m.move.asString() << " " << bestMove.value << " -> " << m.value << std::endl;
  495. bestMove.overwriteIfBetter(m);
  496. board = temp;
  497. }
  498. float v = evaluate<side>();
  499. bestMove.value *= 0.9f;
  500. bestMove.value += v * 0.2f;
  501. return -bestMove;
  502. }
  503. */