]> git.sesse.net Git - stockfish/blob - src/san.cpp
8c26ac0078a5bedaf579c4bc1a7197f6afc22275
[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-2009 Marco Costalba
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 "history.h"
32 #include "movepick.h"
33 #include "san.h"
34
35 using std::string;
36
37 ////
38 //// Local definitions
39 ////
40
41 namespace {
42
43   /// Types
44
45   enum Ambiguity {
46     AMBIGUITY_NONE,
47     AMBIGUITY_FILE,
48     AMBIGUITY_RANK,
49     AMBIGUITY_BOTH
50   };
51
52
53   /// Functions
54
55   Ambiguity move_ambiguity(const Position& pos, Move m);
56   const string time_string(int milliseconds);
57   const string score_string(Value v);
58 }
59
60
61 ////
62 //// Functions
63 ////
64
65 /// move_to_san() takes a position and a move as input, where it is assumed
66 /// that the move is a legal move from the position. The return value is
67 /// a string containing the move in short algebraic notation.
68
69 const string move_to_san(const Position& pos, Move m) {
70
71   assert(pos.is_ok());
72   assert(move_is_ok(m));
73
74   Square from, to;
75   PieceType pt;
76
77   from = move_from(m);
78   to = move_to(m);
79   pt = type_of_piece(pos.piece_on(move_from(m)));
80
81   string san = "";
82
83   if (m == MOVE_NONE)
84       return "(none)";
85   else if (m == MOVE_NULL)
86       return "(null)";
87   else if (move_is_long_castle(m) || (int(to - from) == -2 && pt == KING))
88       san = "O-O-O";
89   else if (move_is_short_castle(m) || (int(to - from) == 2 && pt == KING))
90       san = "O-O";
91   else
92   {
93       if (pt != PAWN)
94       {
95           san += piece_type_to_char(pt, true);
96           switch (move_ambiguity(pos, m)) {
97           case AMBIGUITY_NONE:
98             break;
99           case AMBIGUITY_FILE:
100             san += file_to_char(square_file(from));
101             break;
102           case AMBIGUITY_RANK:
103             san += rank_to_char(square_rank(from));
104             break;
105           case AMBIGUITY_BOTH:
106             san += square_to_string(from);
107             break;
108           default:
109             assert(false);
110           }
111       }
112       if (pos.move_is_capture(m))
113       {
114           if (pt == PAWN)
115               san += file_to_char(square_file(move_from(m)));
116           san += "x";
117       }
118       san += square_to_string(move_to(m));
119       if (move_promotion(m))
120       {
121           san += '=';
122           san += piece_type_to_char(move_promotion(m), true);
123       }
124   }
125   // Is the move check?  We don't use pos.move_is_check(m) here, because
126   // Position::move_is_check doesn't detect all checks (not castling moves,
127   // promotions and en passant captures).
128   StateInfo st;
129   Position p(pos);
130   p.do_move(m, st);
131   if (p.is_check())
132       san += p.is_mate()? "#" : "+";
133
134   return san;
135 }
136
137
138 /// move_from_san() takes a position and a string as input, and tries to
139 /// interpret the string as a move in short algebraic notation. On success,
140 /// the move is returned.  On failure (i.e. if the string is unparsable, or
141 /// if the move is illegal or ambiguous), MOVE_NONE is returned.
142
143 Move move_from_san(const Position& pos, const string& movestr) {
144
145   assert(pos.is_ok());
146
147   MovePicker mp = MovePicker(pos, false, MOVE_NONE, OnePly, History());
148
149   // Castling moves
150   if (movestr == "O-O-O" || movestr == "O-O-O+")
151   {
152       Move m;
153       while ((m = mp.get_next_move()) != MOVE_NONE)
154           if (move_is_long_castle(m) && pos.pl_move_is_legal(m))
155               return m;
156
157       return MOVE_NONE;
158   }
159   else if (movestr == "O-O" || movestr == "O-O+")
160   {
161       Move m;
162       while ((m = mp.get_next_move()) != MOVE_NONE)
163           if (move_is_short_castle(m) && pos.pl_move_is_legal(m))
164               return m;
165
166     return MOVE_NONE;
167   }
168
169   // Normal moves. We use a simple FSM to parse the san string.
170   enum { START, TO_FILE, TO_RANK, PROMOTION_OR_CHECK, PROMOTION, CHECK, END };
171   static const string pieceLetters = "KQRBN";
172   PieceType pt = NO_PIECE_TYPE, promotion = NO_PIECE_TYPE;
173   File fromFile = FILE_NONE, toFile = FILE_NONE;
174   Rank fromRank = RANK_NONE, toRank = RANK_NONE;
175   Square to;
176   int state = START;
177
178   for (size_t i = 0; i < movestr.length(); i++)
179   {
180       char type, c = movestr[i];
181       if (pieceLetters.find(c) != string::npos)
182           type = 'P';
183       else if (c >= 'a' && c <= 'h')
184           type = 'F';
185       else if (c >= '1' && c <= '8')
186           type = 'R';
187       else
188           type = c;
189
190       switch (type) {
191       case 'P':
192           if (state == START)
193           {
194               pt = piece_type_from_char(c);
195               state = TO_FILE;
196           }
197           else if (state == PROMOTION)
198           {
199               promotion = piece_type_from_char(c);
200               state = (i < movestr.length() - 1) ? CHECK : END;
201           }
202           else
203               return MOVE_NONE;
204           break;
205       case 'F':
206           if (state == START)
207           {
208               pt = PAWN;
209               fromFile = toFile = file_from_char(c);
210               state = TO_RANK;
211           }
212           else if (state == TO_FILE)
213           {
214               toFile = file_from_char(c);
215               state = TO_RANK;
216           }
217           else if (state == TO_RANK && toFile != FILE_NONE)
218           {
219               // Previous file was for disambiguation
220               fromFile = toFile;
221               toFile = file_from_char(c);
222           }
223           else
224               return MOVE_NONE;
225           break;
226       case 'R':
227           if (state == TO_RANK)
228           {
229               toRank = rank_from_char(c);
230               state = (i < movestr.length() - 1) ? PROMOTION_OR_CHECK : END;
231           }
232           else if (state == TO_FILE && fromRank == RANK_NONE)
233           {
234               // It's a disambiguation rank instead of a file
235               fromRank = rank_from_char(c);
236           }
237           else
238               return MOVE_NONE;
239           break;
240       case 'x': case 'X':
241           if (state == TO_RANK)
242           {
243               // Previous file was for disambiguation, or it's a pawn capture
244               fromFile = toFile;
245               state = TO_FILE;
246           }
247           else if (state != TO_FILE)
248               return MOVE_NONE;
249           break;
250       case '=':
251           if (state == PROMOTION_OR_CHECK)
252               state = PROMOTION;
253           else
254               return MOVE_NONE;
255           break;
256       case '+': case '#':
257           if (state == PROMOTION_OR_CHECK || state == CHECK)
258               state = END;
259           else
260               return MOVE_NONE;
261           break;
262       default:
263           return MOVE_NONE;
264           break;
265       }
266   }
267
268   if (state != END)
269       return MOVE_NONE;
270
271   // Look for a matching move
272   Move m, move = MOVE_NONE;
273   to = make_square(toFile, toRank);
274   int matches = 0;
275
276   while ((m = mp.get_next_move()) != MOVE_NONE)
277       if (   pos.type_of_piece_on(move_from(m)) == pt
278           && move_to(m) == to
279           && move_promotion(m) == promotion
280           && (fromFile == FILE_NONE || fromFile == square_file(move_from(m)))
281           && (fromRank == RANK_NONE || fromRank == square_rank(move_from(m))))
282       {
283           move = m;
284           matches++;
285       }
286   return (matches == 1 ? move : MOVE_NONE);
287 }
288
289
290 /// line_to_san() takes a position and a line (an array of moves representing
291 /// a sequence of legal moves from the position) as input, and returns a
292 /// string containing the line in short algebraic notation.  If the boolean
293 /// parameter 'breakLines' is true, line breaks are inserted, with a line
294 /// length of 80 characters.  After a line break, 'startColumn' spaces are
295 /// inserted at the beginning of the new line.
296
297 const string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines) {
298
299   StateInfo st;
300   std::stringstream s;
301   string moveStr;
302   size_t length = 0;
303   size_t maxLength = 80 - startColumn;
304   Position p(pos);
305
306   for (int i = 0; line[i] != MOVE_NONE; i++)
307   {
308       moveStr = move_to_san(p, line[i]);
309       length += moveStr.length() + 1;
310       if (breakLines && length > maxLength)
311       {
312           s << '\n' << std::setw(startColumn) << ' ';
313           length = moveStr.length() + 1;
314       }
315       s << moveStr << ' ';
316
317       if (line[i] == MOVE_NULL)
318           p.do_null_move(st);
319       else
320           p.do_move(line[i], st);
321   }
322   return s.str();
323 }
324
325
326 /// pretty_pv() creates a human-readable string from a position and a PV.
327 /// It is used to write search information to the log file (which is created
328 /// when the UCI parameter "Use Search Log" is "true").
329
330 const string pretty_pv(const Position& pos, int time, int depth,
331                        uint64_t nodes, Value score, Move pv[]) {
332   std::stringstream s;
333
334   // Depth
335   s << std::setw(2) << depth << "  ";
336
337   // Score
338   s << std::setw(8) << score_string(score);
339
340   // Time
341   s << std::setw(8) << time_string(time) << " ";
342
343   // Nodes
344   if (nodes < 1000000ULL)
345     s << std::setw(8) << nodes << " ";
346   else if (nodes < 1000000000ULL)
347     s << std::setw(7) << nodes/1000ULL << 'k' << " ";
348   else
349     s << std::setw(7) << nodes/1000000ULL << 'M' << " ";
350
351   // PV
352   s << line_to_san(pos, pv, 30, true);
353
354   return s.str();
355 }
356
357
358 namespace {
359
360   Ambiguity move_ambiguity(const Position& pos, Move m) {
361
362     Square from = move_from(m);
363     Square to = move_to(m);
364     Piece pc = pos.piece_on(from);
365
366     // King moves are never ambiguous, because there is never two kings of
367     // the same color.
368     if (type_of_piece(pc) == KING)
369         return AMBIGUITY_NONE;
370
371     MovePicker mp = MovePicker(pos, false, MOVE_NONE, OnePly, History());
372     Move mv, moveList[8];
373
374     int n = 0;
375     while ((mv = mp.get_next_move()) != MOVE_NONE)
376         if (move_to(mv) == to && pos.piece_on(move_from(mv)) == pc && pos.pl_move_is_legal(mv))
377             moveList[n++] = mv;
378
379     if (n == 1)
380         return AMBIGUITY_NONE;
381
382     int f = 0, r = 0;
383     for (int i = 0; i < n; i++)
384     {
385         if (square_file(move_from(moveList[i])) == square_file(from))
386             f++;
387
388         if (square_rank(move_from(moveList[i])) == square_rank(from))
389             r++;
390     }
391     if (f == 1)
392         return AMBIGUITY_FILE;
393
394     if (r == 1)
395         return AMBIGUITY_RANK;
396
397     return AMBIGUITY_BOTH;
398   }
399
400
401   const string time_string(int milliseconds) {
402
403     std::stringstream s;
404     s << std::setfill('0');
405
406     int hours = milliseconds / (1000*60*60);
407     int minutes = (milliseconds - hours*1000*60*60) / (1000*60);
408     int seconds = (milliseconds - hours*1000*60*60 - minutes*1000*60) / 1000;
409
410     if (hours)
411         s << hours << ':';
412
413     s << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
414     return s.str();
415   }
416
417
418   const string score_string(Value v) {
419
420     std::stringstream s;
421
422     if (v >= VALUE_MATE - 200)
423         s << "#" << (VALUE_MATE - v + 1) / 2;
424     else if(v <= -VALUE_MATE + 200)
425         s << "-#" << (VALUE_MATE + v) / 2;
426     else
427     {
428         float floatScore = float(v) / float(PawnValueMidgame);
429         if (v >= 0)
430             s << '+';
431
432         s << std::setprecision(2) << std::fixed << floatScore;
433     }
434     return s.str();
435   }
436 }