]> git.sesse.net Git - stockfish/blob - src/san.cpp
Move uci move parsing under san.cpp
[stockfish] / src / san.cpp
1 /*
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
5
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.
10
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.
15
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/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cstring>
27 #include <iomanip>
28 #include <string>
29 #include <sstream>
30
31 #include "movegen.h"
32 #include "san.h"
33
34 using std::string;
35
36 ////
37 //// Local definitions
38 ////
39
40 namespace {
41
42   enum Ambiguity {
43     AMBIGUITY_NONE, AMBIGUITY_FILE, AMBIGUITY_RANK, AMBIGUITY_BOTH
44   };
45
46   Ambiguity move_ambiguity(const Position& pos, Move m);
47   const string time_string(int milliseconds);
48   const string score_string(Value v);
49 }
50
51
52 ////
53 //// Functions
54 ////
55
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
59 /// Chess960 mode.
60
61 const std::string move_to_uci(Move m, bool chess960) {
62
63   std::string str;
64   Square from = move_from(m);
65   Square to = move_to(m);
66
67   if (m == MOVE_NONE)
68       return "(none)";
69
70   if (m == MOVE_NULL)
71       return "0000";
72
73   if (move_is_short_castle(m) && !chess960)
74       return from == SQ_E1 ? "e1g1" : "e8g8";
75
76   if (move_is_long_castle(m) && !chess960)
77       return from == SQ_E1 ? "e1c1" : "e8c8";
78
79   str = square_to_string(from) + square_to_string(to);
80
81   if (move_is_promotion(m))
82       str += char(tolower(piece_type_to_char(move_promotion_piece(m))));
83
84   return str;
85 }
86
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.
91
92 Move move_from_uci(const Position& pos, const std::string& str) {
93
94   Square from, to;
95   Piece piece;
96   Color us = pos.side_to_move();
97
98   if (str.length() < 4)
99       return MOVE_NONE;
100
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]));
104
105   // Find the moving piece
106   piece = pos.piece_on(from);
107
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))
111   {
112       switch (tolower(str[4])) {
113       case 'n':
114           return make_promotion_move(from, to, KNIGHT);
115       case 'b':
116           return make_promotion_move(from, to, BISHOP);
117       case 'r':
118           return make_promotion_move(from, to, ROOK);
119       case 'q':
120           return make_promotion_move(from, to, QUEEN);
121       }
122   }
123
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);
128
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))
133   {
134       if (pos.piece_on(to) == piece_of_color_and_type(us, ROOK))
135           return make_castle_move(from, to);
136
137       if (square_distance(from, to) > 1)
138       {
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);
142           Square s = from;
143
144           do s += delta;
145           while (   pos.piece_on(s) != piece_of_color_and_type(us, ROOK)
146                  && relative_rank(us, s) == RANK_1);
147
148           return relative_rank(us, s) == RANK_1 ? make_castle_move(from, s) : MOVE_NONE;
149       }
150   }
151
152   return make_move(from, to);
153 }
154
155
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.
159
160 const string move_to_san(Position& pos, Move m) {
161
162   assert(pos.is_ok());
163   assert(move_is_ok(m));
164
165   string san;
166   Square from = move_from(m);
167   Square to = move_to(m);
168   PieceType pt = type_of_piece(pos.piece_on(from));
169
170   if (m == MOVE_NONE)
171       return "(none)";
172
173   if (m == MOVE_NULL)
174       return "(null)";
175
176   if (move_is_long_castle(m))
177       san = "O-O-O";
178   else if (move_is_short_castle(m))
179       san = "O-O";
180   else
181   {
182       if (pt != PAWN)
183       {
184           san += piece_type_to_char(pt);
185
186           switch (move_ambiguity(pos, m)) {
187           case AMBIGUITY_NONE:
188             break;
189           case AMBIGUITY_FILE:
190             san += file_to_char(square_file(from));
191             break;
192           case AMBIGUITY_RANK:
193             san += rank_to_char(square_rank(from));
194             break;
195           case AMBIGUITY_BOTH:
196             san += square_to_string(from);
197             break;
198           default:
199             assert(false);
200           }
201       }
202
203       if (pos.move_is_capture(m))
204       {
205           if (pt == PAWN)
206               san += file_to_char(square_file(from));
207
208           san += 'x';
209       }
210       san += square_to_string(to);
211
212       if (move_is_promotion(m))
213       {
214           san += '=';
215           san += piece_type_to_char(move_promotion_piece(m));
216       }
217   }
218
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.
221   StateInfo st;
222   pos.do_move(m, st);
223   if (pos.is_check())
224       san += pos.is_mate() ? "#" : "+";
225   pos.undo_move(m);
226
227   return san;
228 }
229
230
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.
235
236 Move move_from_san(const Position& pos, const string& movestr) {
237
238   assert(pos.is_ok());
239
240   enum { START, TO_FILE, TO_RANK, PROMOTION_OR_CHECK, PROMOTION, CHECK, END };
241   static const string pieceLetters = "KQRBN";
242
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;
248   Square from, to;
249   int matches, state = START;
250
251   // Generate all legal moves for the given position
252   last = generate<MV_LEGAL>(pos, mlist);
253
254   // Castling moves
255   if (movestr == "O-O-O" || movestr == "O-O-O+")
256   {
257      for (MoveStack* cur = mlist; cur != last; cur++)
258           if (move_is_long_castle(cur->move))
259               return cur->move;
260
261       return MOVE_NONE;
262   }
263   else if (movestr == "O-O" || movestr == "O-O+")
264   {
265       for (MoveStack* cur = mlist; cur != last; cur++)
266            if (move_is_short_castle(cur->move))
267                return cur->move;
268
269     return MOVE_NONE;
270   }
271
272   // Normal moves. We use a simple FSM to parse the san string
273   for (size_t i = 0; i < movestr.length(); i++)
274   {
275       char type, c = movestr[i];
276
277       if (pieceLetters.find(c) != string::npos)
278           type = 'P';
279       else if (c >= 'a' && c <= 'h')
280           type = 'F';
281       else if (c >= '1' && c <= '8')
282           type = 'R';
283       else
284           type = c;
285
286       switch (type) {
287       case 'P':
288           if (state == START)
289           {
290               pt = piece_type_from_char(c);
291               state = TO_FILE;
292           }
293           else if (state == PROMOTION)
294           {
295               promotion = piece_type_from_char(c);
296               state = (i < movestr.length() - 1 ? CHECK : END);
297           }
298           else
299               return MOVE_NONE;
300           break;
301       case 'F':
302           if (state == START)
303           {
304               pt = PAWN;
305               fromFile = toFile = file_from_char(c);
306               state = TO_RANK;
307           }
308           else if (state == TO_FILE)
309           {
310               toFile = file_from_char(c);
311               state = TO_RANK;
312           }
313           else if (state == TO_RANK && toFile != FILE_NONE)
314           {
315               // Previous file was for disambiguation
316               fromFile = toFile;
317               toFile = file_from_char(c);
318           }
319           else
320               return MOVE_NONE;
321           break;
322       case 'R':
323           if (state == TO_RANK)
324           {
325               toRank = rank_from_char(c);
326               state = (i < movestr.length() - 1) ? PROMOTION_OR_CHECK : END;
327           }
328           else if (state == TO_FILE && fromRank == RANK_NONE)
329           {
330               // It's a disambiguation rank instead of a file
331               fromRank = rank_from_char(c);
332           }
333           else
334               return MOVE_NONE;
335           break;
336       case 'x':
337       case 'X':
338           if (state == TO_RANK)
339           {
340               // Previous file was for disambiguation, or it's a pawn capture
341               fromFile = toFile;
342               state = TO_FILE;
343           }
344           else if (state != TO_FILE)
345               return MOVE_NONE;
346           break;
347       case '=':
348           if (state == PROMOTION_OR_CHECK)
349               state = PROMOTION;
350           else
351               return MOVE_NONE;
352           break;
353       case '+':
354       case '#':
355           if (state == PROMOTION_OR_CHECK || state == CHECK)
356               state = END;
357           else
358               return MOVE_NONE;
359           break;
360       default:
361           return MOVE_NONE;
362           break;
363       }
364   }
365
366   if (state != END)
367       return MOVE_NONE;
368
369   // Look for an unambiguous matching move
370   to = make_square(toFile, toRank);
371   matches = 0;
372
373   for (MoveStack* cur = mlist; cur != last; cur++)
374   {
375       from = move_from(cur->move);
376
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)))
382       {
383           move = cur->move;
384           matches++;
385       }
386   }
387   return matches == 1 ? move : MOVE_NONE;
388 }
389
390
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.
397
398 const string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines) {
399
400   StateInfo st;
401   std::stringstream s;
402   string moveStr;
403   size_t length = 0;
404   size_t maxLength = 80 - startColumn;
405   Position p(pos, pos.thread());
406
407   for (Move* m = line; *m != MOVE_NONE; m++)
408   {
409       moveStr = move_to_san(p, *m);
410       length += moveStr.length() + 1;
411       if (breakLines && length > maxLength)
412       {
413           s << "\n" << std::setw(startColumn) << " ";
414           length = moveStr.length() + 1;
415       }
416       s << moveStr << ' ';
417
418       if (*m == MOVE_NULL)
419           p.do_null_move(st);
420       else
421           p.do_move(*m, st);
422   }
423   return s.str();
424 }
425
426
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").
430
431 const string pretty_pv(const Position& pos, int time, int depth,
432                        Value score, ValueType type, Move pv[]) {
433
434   const int64_t K = 1000;
435   const int64_t M = 1000000;
436
437   std::stringstream s;
438
439   // Depth
440   s << std::setw(2) << depth << "  ";
441
442   // Score
443   s << (type == VALUE_TYPE_LOWER ? ">" : type == VALUE_TYPE_UPPER ? "<" : " ")
444     << std::setw(7) << score_string(score);
445
446   // Time
447   s << std::setw(8) << time_string(time) << " ";
448
449   // Nodes
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 ";
454   else
455       s << std::setw(7) << pos.nodes_searched() / M << "M ";
456
457   // PV
458   s << line_to_san(pos, pv, 30, true);
459
460   return s.str();
461 }
462
463
464 namespace {
465
466   Ambiguity move_ambiguity(const Position& pos, Move m) {
467
468     MoveStack mlist[MOVES_MAX], *last;
469     Move candidates[8];
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;
474
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;
478
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;
484
485     if (matches == 1)
486         return AMBIGUITY_NONE;
487
488     for (int i = 0; i < matches; i++)
489     {
490         if (square_file(move_from(candidates[i])) == square_file(from))
491             f++;
492
493         if (square_rank(move_from(candidates[i])) == square_rank(from))
494             r++;
495     }
496
497     return f == 1 ? AMBIGUITY_FILE : r == 1 ? AMBIGUITY_RANK : AMBIGUITY_BOTH;
498   }
499
500
501   const string time_string(int millisecs) {
502
503     const int MSecMinute = 1000 * 60;
504     const int MSecHour   = 1000 * 60 * 60;
505
506     std::stringstream s;
507     s << std::setfill('0');
508
509     int hours = millisecs / MSecHour;
510     int minutes = (millisecs - hours * MSecHour) / MSecMinute;
511     int seconds = (millisecs - hours * MSecHour - minutes * MSecMinute) / 1000;
512
513     if (hours)
514         s << hours << ':';
515
516     s << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
517     return s.str();
518   }
519
520
521   const string score_string(Value v) {
522
523     std::stringstream s;
524
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;
529     else
530     {
531         float floatScore = float(v) / float(PawnValueMidgame);
532         if (v >= 0)
533             s << '+';
534
535         s << std::setprecision(2) << std::fixed << floatScore;
536     }
537     return s.str();
538   }
539 }