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