]> git.sesse.net Git - stockfish/blob - src/san.cpp
46ff536ca759e644e0ea91156717438115a22d36
[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 promotion;
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   if (move_is_promotion(m))
80       promotion = char(tolower(piece_type_to_char(move_promotion_piece(m))));
81
82   return square_to_string(from) + square_to_string(to) + promotion;
83 }
84
85
86 /// move_from_uci() takes a position and a string representing a move in
87 /// simple coordinate notation and returns an equivalent Move.
88
89 Move move_from_uci(const Position& pos, const std::string& str) {
90
91   MoveStack mlist[MOVES_MAX];
92   MoveStack* last = generate<MV_LEGAL>(pos, mlist);
93
94   for (MoveStack* cur = mlist; cur != last; cur++)
95       if (str == move_to_uci(cur->move, pos.is_chess960()))
96           return cur->move;
97
98   return MOVE_NONE;
99 }
100
101
102 /// move_to_san() takes a position and a move as input, where it is assumed
103 /// that the move is a legal move from the position. The return value is
104 /// a string containing the move in short algebraic notation.
105
106 const string move_to_san(Position& pos, Move m) {
107
108   assert(pos.is_ok());
109   assert(move_is_ok(m));
110
111   string san;
112   Square from = move_from(m);
113   Square to = move_to(m);
114   PieceType pt = type_of_piece(pos.piece_on(from));
115
116   if (m == MOVE_NONE)
117       return "(none)";
118
119   if (m == MOVE_NULL)
120       return "(null)";
121
122   if (move_is_long_castle(m))
123       san = "O-O-O";
124   else if (move_is_short_castle(m))
125       san = "O-O";
126   else
127   {
128       if (pt != PAWN)
129       {
130           san += piece_type_to_char(pt);
131
132           switch (move_ambiguity(pos, m)) {
133           case AMBIGUITY_NONE:
134             break;
135           case AMBIGUITY_FILE:
136             san += file_to_char(square_file(from));
137             break;
138           case AMBIGUITY_RANK:
139             san += rank_to_char(square_rank(from));
140             break;
141           case AMBIGUITY_BOTH:
142             san += square_to_string(from);
143             break;
144           default:
145             assert(false);
146           }
147       }
148
149       if (pos.move_is_capture(m))
150       {
151           if (pt == PAWN)
152               san += file_to_char(square_file(from));
153
154           san += 'x';
155       }
156       san += square_to_string(to);
157
158       if (move_is_promotion(m))
159       {
160           san += '=';
161           san += piece_type_to_char(move_promotion_piece(m));
162       }
163   }
164
165   // The move gives check ? We don't use pos.move_is_check() here
166   // because we need to test for mate after the move is done.
167   StateInfo st;
168   pos.do_move(m, st);
169   if (pos.is_check())
170       san += pos.is_mate() ? "#" : "+";
171   pos.undo_move(m);
172
173   return san;
174 }
175
176
177 /// move_from_san() takes a position and a string as input, and tries to
178 /// interpret the string as a move in short algebraic notation. On success,
179 /// the move is returned.  On failure (i.e. if the string is unparsable, or
180 /// if the move is illegal or ambiguous), MOVE_NONE is returned.
181
182 Move move_from_san(const Position& pos, const string& movestr) {
183
184   assert(pos.is_ok());
185
186   enum { START, TO_FILE, TO_RANK, PROMOTION_OR_CHECK, PROMOTION, CHECK, END };
187   static const string pieceLetters = "KQRBN";
188
189   MoveStack mlist[MOVES_MAX], *last;
190   PieceType pt = PIECE_TYPE_NONE, promotion = PIECE_TYPE_NONE;
191   File fromFile = FILE_NONE, toFile = FILE_NONE;
192   Rank fromRank = RANK_NONE, toRank = RANK_NONE;
193   Move move = MOVE_NONE;
194   Square from, to;
195   int matches, state = START;
196
197   // Generate all legal moves for the given position
198   last = generate<MV_LEGAL>(pos, mlist);
199
200   // Castling moves
201   if (movestr == "O-O-O" || movestr == "O-O-O+")
202   {
203      for (MoveStack* cur = mlist; cur != last; cur++)
204           if (move_is_long_castle(cur->move))
205               return cur->move;
206
207       return MOVE_NONE;
208   }
209   else if (movestr == "O-O" || movestr == "O-O+")
210   {
211       for (MoveStack* cur = mlist; cur != last; cur++)
212            if (move_is_short_castle(cur->move))
213                return cur->move;
214
215     return MOVE_NONE;
216   }
217
218   // Normal moves. We use a simple FSM to parse the san string
219   for (size_t i = 0; i < movestr.length(); i++)
220   {
221       char type, c = movestr[i];
222
223       if (pieceLetters.find(c) != string::npos)
224           type = 'P';
225       else if (c >= 'a' && c <= 'h')
226           type = 'F';
227       else if (c >= '1' && c <= '8')
228           type = 'R';
229       else
230           type = c;
231
232       switch (type) {
233       case 'P':
234           if (state == START)
235           {
236               pt = piece_type_from_char(c);
237               state = TO_FILE;
238           }
239           else if (state == PROMOTION)
240           {
241               promotion = piece_type_from_char(c);
242               state = (i < movestr.length() - 1 ? CHECK : END);
243           }
244           else
245               return MOVE_NONE;
246           break;
247       case 'F':
248           if (state == START)
249           {
250               pt = PAWN;
251               fromFile = toFile = file_from_char(c);
252               state = TO_RANK;
253           }
254           else if (state == TO_FILE)
255           {
256               toFile = file_from_char(c);
257               state = TO_RANK;
258           }
259           else if (state == TO_RANK && toFile != FILE_NONE)
260           {
261               // Previous file was for disambiguation
262               fromFile = toFile;
263               toFile = file_from_char(c);
264           }
265           else
266               return MOVE_NONE;
267           break;
268       case 'R':
269           if (state == TO_RANK)
270           {
271               toRank = rank_from_char(c);
272               state = (i < movestr.length() - 1) ? PROMOTION_OR_CHECK : END;
273           }
274           else if (state == TO_FILE && fromRank == RANK_NONE)
275           {
276               // It's a disambiguation rank instead of a file
277               fromRank = rank_from_char(c);
278           }
279           else
280               return MOVE_NONE;
281           break;
282       case 'x':
283       case 'X':
284           if (state == TO_RANK)
285           {
286               // Previous file was for disambiguation, or it's a pawn capture
287               fromFile = toFile;
288               state = TO_FILE;
289           }
290           else if (state != TO_FILE)
291               return MOVE_NONE;
292           break;
293       case '=':
294           if (state == PROMOTION_OR_CHECK)
295               state = PROMOTION;
296           else
297               return MOVE_NONE;
298           break;
299       case '+':
300       case '#':
301           if (state == PROMOTION_OR_CHECK || state == CHECK)
302               state = END;
303           else
304               return MOVE_NONE;
305           break;
306       default:
307           return MOVE_NONE;
308           break;
309       }
310   }
311
312   if (state != END)
313       return MOVE_NONE;
314
315   // Look for an unambiguous matching move
316   to = make_square(toFile, toRank);
317   matches = 0;
318
319   for (MoveStack* cur = mlist; cur != last; cur++)
320   {
321       from = move_from(cur->move);
322
323       if (   pos.type_of_piece_on(from) == pt
324           && move_to(cur->move) == to
325           && move_promotion_piece(cur->move) == promotion
326           && (fromFile == FILE_NONE || fromFile == square_file(from))
327           && (fromRank == RANK_NONE || fromRank == square_rank(from)))
328       {
329           move = cur->move;
330           matches++;
331       }
332   }
333   return matches == 1 ? move : MOVE_NONE;
334 }
335
336
337 /// line_to_san() takes a position and a line (an array of moves representing
338 /// a sequence of legal moves from the position) as input, and returns a
339 /// string containing the line in short algebraic notation.  If the boolean
340 /// parameter 'breakLines' is true, line breaks are inserted, with a line
341 /// length of 80 characters.  After a line break, 'startColumn' spaces are
342 /// inserted at the beginning of the new line.
343
344 const string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines) {
345
346   StateInfo st;
347   std::stringstream s;
348   string moveStr;
349   size_t length = 0;
350   size_t maxLength = 80 - startColumn;
351   Position p(pos, pos.thread());
352
353   for (Move* m = line; *m != MOVE_NONE; m++)
354   {
355       moveStr = move_to_san(p, *m);
356       length += moveStr.length() + 1;
357       if (breakLines && length > maxLength)
358       {
359           s << "\n" << std::setw(startColumn) << " ";
360           length = moveStr.length() + 1;
361       }
362       s << moveStr << ' ';
363
364       if (*m == MOVE_NULL)
365           p.do_null_move(st);
366       else
367           p.do_move(*m, st);
368   }
369   return s.str();
370 }
371
372
373 /// pretty_pv() creates a human-readable string from a position and a PV.
374 /// It is used to write search information to the log file (which is created
375 /// when the UCI parameter "Use Search Log" is "true").
376
377 const string pretty_pv(const Position& pos, int time, int depth,
378                        Value score, ValueType type, Move pv[]) {
379
380   const int64_t K = 1000;
381   const int64_t M = 1000000;
382
383   std::stringstream s;
384
385   // Depth
386   s << std::setw(2) << depth << "  ";
387
388   // Score
389   s << (type == VALUE_TYPE_LOWER ? ">" : type == VALUE_TYPE_UPPER ? "<" : " ")
390     << std::setw(7) << score_string(score);
391
392   // Time
393   s << std::setw(8) << time_string(time) << " ";
394
395   // Nodes
396   if (pos.nodes_searched() < M)
397       s << std::setw(8) << pos.nodes_searched() / 1 << " ";
398   else if (pos.nodes_searched() < K * M)
399       s << std::setw(7) << pos.nodes_searched() / K << "K ";
400   else
401       s << std::setw(7) << pos.nodes_searched() / M << "M ";
402
403   // PV
404   s << line_to_san(pos, pv, 30, true);
405
406   return s.str();
407 }
408
409
410 namespace {
411
412   Ambiguity move_ambiguity(const Position& pos, Move m) {
413
414     MoveStack mlist[MOVES_MAX], *last;
415     Move candidates[8];
416     Square from = move_from(m);
417     Square to = move_to(m);
418     Piece pc = pos.piece_on(from);
419     int matches = 0, f = 0, r = 0;
420
421     // If there is only one piece 'pc' then move cannot be ambiguous
422     if (pos.piece_count(pos.side_to_move(), type_of_piece(pc)) == 1)
423         return AMBIGUITY_NONE;
424
425     // Collect all legal moves of piece 'pc' with destination 'to'
426     last = generate<MV_LEGAL>(pos, mlist);
427     for (MoveStack* cur = mlist; cur != last; cur++)
428         if (move_to(cur->move) == to && pos.piece_on(move_from(cur->move)) == pc)
429             candidates[matches++] = cur->move;
430
431     if (matches == 1)
432         return AMBIGUITY_NONE;
433
434     for (int i = 0; i < matches; i++)
435     {
436         if (square_file(move_from(candidates[i])) == square_file(from))
437             f++;
438
439         if (square_rank(move_from(candidates[i])) == square_rank(from))
440             r++;
441     }
442
443     return f == 1 ? AMBIGUITY_FILE : r == 1 ? AMBIGUITY_RANK : AMBIGUITY_BOTH;
444   }
445
446
447   const string time_string(int millisecs) {
448
449     const int MSecMinute = 1000 * 60;
450     const int MSecHour   = 1000 * 60 * 60;
451
452     std::stringstream s;
453     s << std::setfill('0');
454
455     int hours = millisecs / MSecHour;
456     int minutes = (millisecs - hours * MSecHour) / MSecMinute;
457     int seconds = (millisecs - hours * MSecHour - minutes * MSecMinute) / 1000;
458
459     if (hours)
460         s << hours << ':';
461
462     s << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
463     return s.str();
464   }
465
466
467   const string score_string(Value v) {
468
469     std::stringstream s;
470
471     if (v >= VALUE_MATE - 200)
472         s << "#" << (VALUE_MATE - v + 1) / 2;
473     else if (v <= -VALUE_MATE + 200)
474         s << "-#" << (VALUE_MATE + v) / 2;
475     else
476     {
477         float floatScore = float(v) / float(PawnValueMidgame);
478         if (v >= 0)
479             s << '+';
480
481         s << std::setprecision(2) << std::fixed << floatScore;
482     }
483     return s.str();
484   }
485 }