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