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