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