]> git.sesse.net Git - stockfish/blob - src/san.cpp
Unify black and white code in generate_move_if_legal()
[stockfish] / src / san.cpp
1 /*
2   Glaurung, a UCI chess playing engine.
3   Copyright (C) 2004-2008 Tord Romstad
4
5   Glaurung is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Glaurung is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 ////
21 //// Includes
22 ////
23
24 #include <cassert>
25 #include <cstring>
26 #include <iomanip>
27 #include <string>
28 #include <sstream>
29
30 #include "movepick.h"
31 #include "san.h"
32
33
34 ////
35 //// Local definitions
36 ////
37
38 namespace {
39
40   /// Types
41
42   enum Ambiguity {
43     AMBIGUITY_NONE,
44     AMBIGUITY_FILE,
45     AMBIGUITY_RANK,
46     AMBIGUITY_BOTH
47   };
48
49
50   /// Functions
51
52   Ambiguity move_ambiguity(Position &pos, Move m);
53   const std::string time_string(int milliseconds);
54   const std::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 std::string move_to_san(Position &pos, Move m) {
67   std::string str;
68
69   assert(pos.is_ok());
70   assert(move_is_ok(m));
71
72   if(m == MOVE_NONE) {
73     str = "(none)";
74     return str;
75   }
76   else if(m == MOVE_NULL) {
77     str = "(null)";
78     return str;
79   }
80   else if(move_is_long_castle(m))
81     str = "O-O-O";
82   else if(move_is_short_castle(m))
83     str = "O-O";
84   else {
85     Square from, to;
86     Piece pc;
87
88     from = move_from(m);
89     to = move_to(m);
90     pc = pos.piece_on(move_from(m));
91
92     str = "";
93
94     if(type_of_piece(pc) == PAWN) {
95       if(pos.move_is_capture(m))
96         str += file_to_char(square_file(move_from(m)));
97     }
98     else {
99       str += piece_type_to_char(type_of_piece(pc), true);
100
101       Ambiguity amb = move_ambiguity(pos, m);
102       switch(amb) {
103
104       case AMBIGUITY_NONE:
105         break;
106
107       case AMBIGUITY_FILE:
108         str += file_to_char(square_file(from));
109         break;
110
111       case AMBIGUITY_RANK:
112         str += rank_to_char(square_rank(from));
113         break;
114
115       case AMBIGUITY_BOTH:
116         str += square_to_string(from);
117         break;
118
119       default:
120         assert(false);
121       }
122     }
123
124     if(pos.move_is_capture(m))
125       str += "x";
126
127     str += square_to_string(move_to(m));
128
129     if(move_promotion(m)) {
130       str += "=";
131       str += piece_type_to_char(move_promotion(m), true);
132     }
133   }
134
135   // Is the move check?  We don't use pos.move_is_check(m) here, because
136   // Position::move_is_check doesn't detect all checks (not castling moves,
137   // promotions and en passant captures).
138   UndoInfo u;
139   pos.do_move(m, u);
140   if(pos.is_check())
141     str += pos.is_mate()? "#" : "+";
142   pos.undo_move(m, u);
143
144   return str;
145 }
146
147
148 /// move_from_san() takes a position and a string as input, and tries to
149 /// interpret the string as a move in short algebraic notation.  On success,
150 /// the move is returned.  On failure (i.e. if the string is unparsable, or
151 /// if the move is illegal or ambiguous), MOVE_NONE is returned.
152
153 Move move_from_san(Position &pos, const std::string &movestr) {
154   assert(pos.is_ok());
155
156   MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
157                              MOVE_NONE, OnePly);
158
159   // Castling moves
160   if(movestr == "O-O-O") {
161     Move m;
162     while((m = mp.get_next_move()) != MOVE_NONE)
163       if(move_is_long_castle(m) && pos.move_is_legal(m))
164         return m;
165     return MOVE_NONE;
166   }
167   else if(movestr == "O-O") {
168     Move m;
169     while((m = mp.get_next_move()) != MOVE_NONE)
170       if(move_is_short_castle(m) && pos.move_is_legal(m))
171         return m;
172     return MOVE_NONE;
173   }
174
175   // Normal moves
176   const char *cstr = movestr.c_str();
177   const char *c;
178   char *cc;
179   char str[10];
180   int i;
181
182   // Initialize str[] by making a copy of movestr with the characters
183   // 'x', '=', '+' and '#' removed.
184   cc = str;
185   for(i=0, c=cstr; i<10 && *c!='\0' && *c!='\n' && *c!=' '; i++, c++)
186     if(!strchr("x=+#", *c)) {
187       *cc = strchr("nrq", *c)? toupper(*c) : *c;
188       cc++;
189     }
190   *cc = '\0';
191
192   size_t left = 0, right = strlen(str) - 1;
193   PieceType pt = NO_PIECE_TYPE, promotion;
194   Square to;
195   File fromFile = FILE_NONE;
196   Rank fromRank = RANK_NONE;
197
198   // Promotion?
199   if(strchr("BNRQ", str[right])) {
200     promotion = piece_type_from_char(str[right]);
201     right--;
202   }
203   else
204     promotion = NO_PIECE_TYPE;
205
206   // Find the moving piece:
207   if(left < right) {
208     if(strchr("BNRQK", str[left])) {
209       pt = piece_type_from_char(str[left]);
210       left++;
211     }
212     else
213       pt = PAWN;
214   }
215
216   // Find the to square:
217   if(left < right) {
218     if(str[right] < '1' || str[right] > '8' ||
219        str[right-1] < 'a' || str[right-1] > 'h')
220       return MOVE_NONE;
221     to = make_square(file_from_char(str[right-1]), rank_from_char(str[right]));
222     right -= 2;
223   }
224   else
225     return MOVE_NONE;
226
227   // Find the file and/or rank of the from square:
228   if(left <= right) {
229     if(strchr("abcdefgh", str[left])) {
230       fromFile = file_from_char(str[left]);
231       left++;
232     }
233     if(strchr("12345678", str[left]))
234       fromRank = rank_from_char(str[left]);
235   }
236
237   // Look for a matching move:
238   Move m, move = MOVE_NONE;
239   int matches = 0;
240
241   while((m = mp.get_next_move()) != MOVE_NONE) {
242     bool match = true;
243     if(pos.type_of_piece_on(move_from(m)) != pt)
244       match = false;
245     else if(move_to(m) != to)
246       match = false;
247     else if(move_promotion(m) != promotion)
248       match = false;
249     else if(fromFile != FILE_NONE && fromFile != square_file(move_from(m)))
250       match = false;
251     else if(fromRank != RANK_NONE && fromRank != square_rank(move_from(m)))
252       match = false;
253     if(match) {
254       move = m;
255       matches++;
256     }
257   }
258
259   if(matches == 1)
260     return move;
261   else
262     return MOVE_NONE;
263 }
264
265
266 /// line_to_san() takes a position and a line (an array of moves representing
267 /// a sequence of legal moves from the position) as input, and returns a
268 /// string containing the line in short algebraic notation.  If the boolean
269 /// parameter 'breakLines' is true, line breaks are inserted, with a line
270 /// length of 80 characters.  After a line break, 'startColumn' spaces are
271 /// inserted at the beginning of the new line.
272
273 const std::string line_to_san(const Position &pos, Move line[], int startColumn,
274                               bool breakLines) {
275   Position p = Position(pos);
276   UndoInfo u;
277   std::stringstream s;
278   std::string moveStr;
279   size_t length, maxLength;
280
281   length = 0;
282   maxLength = 80 - startColumn;
283
284   for(int i = 0; line[i] != MOVE_NONE; i++) {
285     moveStr = move_to_san(p, line[i]);
286     length += moveStr.length() + 1;
287     if(breakLines && length > maxLength) {
288       s << "\n";
289       for(int j = 0; j < startColumn; j++)
290         s << " ";
291       length = moveStr.length() + 1;
292     }
293     s << moveStr << " ";
294
295     if(line[i] == MOVE_NULL)
296       p.do_null_move(u);
297     else
298       p.do_move(line[i], u);
299   }
300
301   return s.str();
302 }
303
304
305 /// pretty_pv() creates a human-readable string from a position and a PV.
306 /// It is used to write search information to the log file (which is created
307 /// when the UCI parameter "Use Search Log" is "true").
308
309 const std::string pretty_pv(const Position &pos, int time, int depth,
310                             uint64_t nodes, Value score, Move pv[]) {
311   std::stringstream s;
312
313   // Depth
314   s << std::setw(2) << std::setfill(' ') << depth << "  ";
315
316   // Score
317   s << std::setw(8) << score_string(score);
318
319   // Time
320   s << std::setw(8) << std::setfill(' ') << time_string(time) << " ";
321
322   // Nodes
323   if(nodes < 1000000ULL)
324     s << std::setw(8) << std::setfill(' ') << nodes << " ";
325   else if(nodes < 1000000000ULL)
326     s << std::setw(7) << std::setfill(' ') << nodes/1000ULL << 'k' << " ";
327   else
328     s << std::setw(7) << std::setfill(' ') << nodes/1000000ULL << 'M' << " ";
329
330   // PV
331   s << line_to_san(pos, pv, 30, true);
332
333   return s.str();
334 }
335
336
337 namespace {
338
339   Ambiguity move_ambiguity(Position &pos, Move m) {
340     Square from, to;
341     Piece pc;
342
343     from = move_from(m);
344     to = move_to(m);
345     pc = pos.piece_on(from);
346
347     // King moves are never ambiguous, because there is never two kings of
348     // the same color.
349     if(type_of_piece(pc) == KING)
350       return AMBIGUITY_NONE;
351
352     MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
353                                MOVE_NONE, OnePly);
354     Move mv, moveList[8];
355     int i, j, n;
356
357     n = 0;
358     while((mv = mp.get_next_move()) != MOVE_NONE)
359       if(move_to(mv) == to && pos.piece_on(move_from(mv)) == pc
360          && pos.move_is_legal(mv))
361         moveList[n++] = mv;
362     if(n == 1)
363       return AMBIGUITY_NONE;
364
365     j = 0;
366     for(i = 0; i < n; i++)
367       if(square_file(move_from(moveList[i])) == square_file(from))
368         j++;
369     if(j == 1)
370       return AMBIGUITY_FILE;
371
372     j = 0;
373     for(i = 0; i < n; i++)
374       if(square_rank(move_from(moveList[i])) == square_rank(from))
375         j++;
376     if(j == 1)
377       return AMBIGUITY_RANK;
378
379     return AMBIGUITY_BOTH;
380   }
381
382
383   const std::string time_string(int milliseconds) {
384     std::stringstream s;
385
386     int hours = milliseconds / (1000 * 60 * 60);
387     int minutes = (milliseconds - hours*1000*60*60) / (60*1000);
388     int seconds = (milliseconds - hours*1000*60*60 - minutes*60*1000) / 1000;
389
390     if(hours)
391       s << hours << ':';
392     s << std::setw(2) << std::setfill('0') << minutes << ':';
393     s << std::setw(2) << std::setfill('0') << seconds;
394
395     return s.str();
396   }
397
398
399   const std::string score_string(Value v) {
400     std::stringstream s;
401
402     if(abs(v) >= VALUE_MATE - 200) {
403       if(v < 0)
404         s << "-#" << (VALUE_MATE + v) / 2;
405       else
406         s << "#" << (VALUE_MATE - v + 1) / 2;
407     }
408     else {
409       float floatScore = float(v) / float(PawnValueMidgame);
410       if(v >= 0)
411         s << '+';
412       s << std::setprecision(2) << std::fixed << floatScore;
413     }
414     return s.str();
415   }
416
417 }