2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
37 //// Local definitions
43 AMBIGUITY_NONE, AMBIGUITY_FILE, AMBIGUITY_RANK, AMBIGUITY_BOTH
46 Ambiguity move_ambiguity(const Position& pos, Move m);
47 const string time_string(int milliseconds);
48 const string score_string(Value v);
56 /// move_to_uci() converts a move to a string in coordinate notation
57 /// (g1f3, a7a8q, etc.). The only special case is castling moves, where we
58 /// print in the e1g1 notation in normal chess mode, and in e1h1 notation in
61 const std::string move_to_uci(Move m, bool chess960) {
64 Square from = move_from(m);
65 Square to = move_to(m);
73 if (move_is_short_castle(m) && !chess960)
74 return from == SQ_E1 ? "e1g1" : "e8g8";
76 if (move_is_long_castle(m) && !chess960)
77 return from == SQ_E1 ? "e1c1" : "e8c8";
79 str = square_to_string(from) + square_to_string(to);
81 if (move_is_promotion(m))
82 str += char(tolower(piece_type_to_char(move_promotion_piece(m))));
87 /// move_from_uci() takes a position and a string as input, and attempts to
88 /// convert the string to a move, using simple coordinate notation (g1f3,
89 /// a7a8q, etc.). This function is not robust, and expects that the input
90 /// move is legal and correctly formatted.
92 Move move_from_uci(const Position& pos, const std::string& str) {
96 Color us = pos.side_to_move();
101 // Read the from and to squares
102 from = make_square(file_from_char(str[0]), rank_from_char(str[1]));
103 to = make_square(file_from_char(str[2]), rank_from_char(str[3]));
105 // Find the moving piece
106 piece = pos.piece_on(from);
108 // If the string has more than 4 characters, try to interpret the 5th
109 // character as a promotion.
110 if (str.length() > 4 && piece == piece_of_color_and_type(us, PAWN))
112 switch (tolower(str[4])) {
114 return make_promotion_move(from, to, KNIGHT);
116 return make_promotion_move(from, to, BISHOP);
118 return make_promotion_move(from, to, ROOK);
120 return make_promotion_move(from, to, QUEEN);
124 // En passant move? We assume that a pawn move is an en passant move
125 // if the destination square is epSquare.
126 if (to == pos.ep_square() && piece == piece_of_color_and_type(us, PAWN))
127 return make_ep_move(from, to);
129 // Is this a castling move? A king move is assumed to be a castling move
130 // if the destination square is occupied by a friendly rook, or if the
131 // distance between the source and destination squares is more than 1.
132 if (piece == piece_of_color_and_type(us, KING))
134 if (pos.piece_on(to) == piece_of_color_and_type(us, ROOK))
135 return make_castle_move(from, to);
137 if (square_distance(from, to) > 1)
139 // This is a castling move, but we have to translate it to the
140 // internal "king captures rook" representation.
141 SquareDelta delta = (to > from ? DELTA_E : DELTA_W);
145 while ( pos.piece_on(s) != piece_of_color_and_type(us, ROOK)
146 && relative_rank(us, s) == RANK_1);
148 return relative_rank(us, s) == RANK_1 ? make_castle_move(from, s) : MOVE_NONE;
152 return make_move(from, to);
156 /// move_to_san() takes a position and a move as input, where it is assumed
157 /// that the move is a legal move from the position. The return value is
158 /// a string containing the move in short algebraic notation.
160 const string move_to_san(Position& pos, Move m) {
163 assert(move_is_ok(m));
166 Square from = move_from(m);
167 Square to = move_to(m);
168 PieceType pt = type_of_piece(pos.piece_on(from));
176 if (move_is_long_castle(m))
178 else if (move_is_short_castle(m))
184 san += piece_type_to_char(pt);
186 switch (move_ambiguity(pos, m)) {
190 san += file_to_char(square_file(from));
193 san += rank_to_char(square_rank(from));
196 san += square_to_string(from);
203 if (pos.move_is_capture(m))
206 san += file_to_char(square_file(from));
210 san += square_to_string(to);
212 if (move_is_promotion(m))
215 san += piece_type_to_char(move_promotion_piece(m));
219 // The move gives check ? We don't use pos.move_is_check() here
220 // because we need to test for mate after the move is done.
224 san += pos.is_mate() ? "#" : "+";
231 /// move_from_san() takes a position and a string as input, and tries to
232 /// interpret the string as a move in short algebraic notation. On success,
233 /// the move is returned. On failure (i.e. if the string is unparsable, or
234 /// if the move is illegal or ambiguous), MOVE_NONE is returned.
236 Move move_from_san(const Position& pos, const string& movestr) {
240 enum { START, TO_FILE, TO_RANK, PROMOTION_OR_CHECK, PROMOTION, CHECK, END };
241 static const string pieceLetters = "KQRBN";
243 MoveStack mlist[MOVES_MAX], *last;
244 PieceType pt = PIECE_TYPE_NONE, promotion = PIECE_TYPE_NONE;
245 File fromFile = FILE_NONE, toFile = FILE_NONE;
246 Rank fromRank = RANK_NONE, toRank = RANK_NONE;
247 Move move = MOVE_NONE;
249 int matches, state = START;
251 // Generate all legal moves for the given position
252 last = generate<MV_LEGAL>(pos, mlist);
255 if (movestr == "O-O-O" || movestr == "O-O-O+")
257 for (MoveStack* cur = mlist; cur != last; cur++)
258 if (move_is_long_castle(cur->move))
263 else if (movestr == "O-O" || movestr == "O-O+")
265 for (MoveStack* cur = mlist; cur != last; cur++)
266 if (move_is_short_castle(cur->move))
272 // Normal moves. We use a simple FSM to parse the san string
273 for (size_t i = 0; i < movestr.length(); i++)
275 char type, c = movestr[i];
277 if (pieceLetters.find(c) != string::npos)
279 else if (c >= 'a' && c <= 'h')
281 else if (c >= '1' && c <= '8')
290 pt = piece_type_from_char(c);
293 else if (state == PROMOTION)
295 promotion = piece_type_from_char(c);
296 state = (i < movestr.length() - 1 ? CHECK : END);
305 fromFile = toFile = file_from_char(c);
308 else if (state == TO_FILE)
310 toFile = file_from_char(c);
313 else if (state == TO_RANK && toFile != FILE_NONE)
315 // Previous file was for disambiguation
317 toFile = file_from_char(c);
323 if (state == TO_RANK)
325 toRank = rank_from_char(c);
326 state = (i < movestr.length() - 1) ? PROMOTION_OR_CHECK : END;
328 else if (state == TO_FILE && fromRank == RANK_NONE)
330 // It's a disambiguation rank instead of a file
331 fromRank = rank_from_char(c);
338 if (state == TO_RANK)
340 // Previous file was for disambiguation, or it's a pawn capture
344 else if (state != TO_FILE)
348 if (state == PROMOTION_OR_CHECK)
355 if (state == PROMOTION_OR_CHECK || state == CHECK)
369 // Look for an unambiguous matching move
370 to = make_square(toFile, toRank);
373 for (MoveStack* cur = mlist; cur != last; cur++)
375 from = move_from(cur->move);
377 if ( pos.type_of_piece_on(from) == pt
378 && move_to(cur->move) == to
379 && move_promotion_piece(cur->move) == promotion
380 && (fromFile == FILE_NONE || fromFile == square_file(from))
381 && (fromRank == RANK_NONE || fromRank == square_rank(from)))
387 return matches == 1 ? move : MOVE_NONE;
391 /// line_to_san() takes a position and a line (an array of moves representing
392 /// a sequence of legal moves from the position) as input, and returns a
393 /// string containing the line in short algebraic notation. If the boolean
394 /// parameter 'breakLines' is true, line breaks are inserted, with a line
395 /// length of 80 characters. After a line break, 'startColumn' spaces are
396 /// inserted at the beginning of the new line.
398 const string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines) {
404 size_t maxLength = 80 - startColumn;
405 Position p(pos, pos.thread());
407 for (Move* m = line; *m != MOVE_NONE; m++)
409 moveStr = move_to_san(p, *m);
410 length += moveStr.length() + 1;
411 if (breakLines && length > maxLength)
413 s << "\n" << std::setw(startColumn) << " ";
414 length = moveStr.length() + 1;
427 /// pretty_pv() creates a human-readable string from a position and a PV.
428 /// It is used to write search information to the log file (which is created
429 /// when the UCI parameter "Use Search Log" is "true").
431 const string pretty_pv(const Position& pos, int time, int depth,
432 Value score, ValueType type, Move pv[]) {
434 const int64_t K = 1000;
435 const int64_t M = 1000000;
440 s << std::setw(2) << depth << " ";
443 s << (type == VALUE_TYPE_LOWER ? ">" : type == VALUE_TYPE_UPPER ? "<" : " ")
444 << std::setw(7) << score_string(score);
447 s << std::setw(8) << time_string(time) << " ";
450 if (pos.nodes_searched() < M)
451 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
452 else if (pos.nodes_searched() < K * M)
453 s << std::setw(7) << pos.nodes_searched() / K << "K ";
455 s << std::setw(7) << pos.nodes_searched() / M << "M ";
458 s << line_to_san(pos, pv, 30, true);
466 Ambiguity move_ambiguity(const Position& pos, Move m) {
468 MoveStack mlist[MOVES_MAX], *last;
470 Square from = move_from(m);
471 Square to = move_to(m);
472 Piece pc = pos.piece_on(from);
473 int matches = 0, f = 0, r = 0;
475 // If there is only one piece 'pc' then move cannot be ambiguous
476 if (pos.piece_count(pos.side_to_move(), type_of_piece(pc)) == 1)
477 return AMBIGUITY_NONE;
479 // Collect all legal moves of piece 'pc' with destination 'to'
480 last = generate<MV_LEGAL>(pos, mlist);
481 for (MoveStack* cur = mlist; cur != last; cur++)
482 if (move_to(cur->move) == to && pos.piece_on(move_from(cur->move)) == pc)
483 candidates[matches++] = cur->move;
486 return AMBIGUITY_NONE;
488 for (int i = 0; i < matches; i++)
490 if (square_file(move_from(candidates[i])) == square_file(from))
493 if (square_rank(move_from(candidates[i])) == square_rank(from))
497 return f == 1 ? AMBIGUITY_FILE : r == 1 ? AMBIGUITY_RANK : AMBIGUITY_BOTH;
501 const string time_string(int millisecs) {
503 const int MSecMinute = 1000 * 60;
504 const int MSecHour = 1000 * 60 * 60;
507 s << std::setfill('0');
509 int hours = millisecs / MSecHour;
510 int minutes = (millisecs - hours * MSecHour) / MSecMinute;
511 int seconds = (millisecs - hours * MSecHour - minutes * MSecMinute) / 1000;
516 s << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
521 const string score_string(Value v) {
525 if (v >= VALUE_MATE - 200)
526 s << "#" << (VALUE_MATE - v + 1) / 2;
527 else if (v <= -VALUE_MATE + 200)
528 s << "-#" << (VALUE_MATE + v) / 2;
531 float floatScore = float(v) / float(PawnValueMidgame);
535 s << std::setprecision(2) << std::fixed << floatScore;