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