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-2014 Marco Costalba, Joona Kiiski, Tord Romstad
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.
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.
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/>.
35 extern void benchmark(const Position& pos, istream& is);
39 // FEN string of the initial position, normal chess
40 const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
42 // Keep a track of the position keys along the setup moves (from the start position
43 // to the position just before the search starts). This is needed by the repetition
44 // draw detection code.
45 Search::StateStackPtr SetupStates;
48 // position() is called when engine receives the "position" UCI command.
49 // The function sets up the position described in the given FEN string ("fen")
50 // or the starting position ("startpos") and then makes the moves given in the
51 // following move list ("moves").
53 void position(Position& pos, istringstream& is) {
60 if (token == "startpos")
63 is >> token; // Consume "moves" token if any
65 else if (token == "fen")
66 while (is >> token && token != "moves")
71 pos.set(fen, Options["UCI_Chess960"], Threads.main());
72 SetupStates = Search::StateStackPtr(new std::stack<StateInfo>());
74 // Parse move list (if any)
75 while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
77 SetupStates->push(StateInfo());
78 pos.do_move(m, SetupStates->top());
83 // setoption() is called when engine receives the "setoption" UCI command. The
84 // function updates the UCI option ("name") to the given value ("value").
86 void setoption(istringstream& is) {
88 string token, name, value;
90 is >> token; // Consume "name" token
92 // Read option name (can contain spaces)
93 while (is >> token && token != "value")
94 name += string(" ", !name.empty()) + token;
96 // Read option value (can contain spaces)
98 value += string(" ", !value.empty()) + token;
100 if (Options.count(name))
101 Options[name] = value;
103 sync_cout << "No such option: " << name << sync_endl;
107 // go() is called when engine receives the "go" UCI command. The function sets
108 // the thinking time and other parameters from the input string, and starts
111 void go(const Position& pos, istringstream& is) {
113 Search::LimitsType limits;
118 if (token == "searchmoves")
120 limits.searchmoves.push_back(UCI::to_move(pos, token));
122 else if (token == "wtime") is >> limits.time[WHITE];
123 else if (token == "btime") is >> limits.time[BLACK];
124 else if (token == "winc") is >> limits.inc[WHITE];
125 else if (token == "binc") is >> limits.inc[BLACK];
126 else if (token == "movestogo") is >> limits.movestogo;
127 else if (token == "depth") is >> limits.depth;
128 else if (token == "nodes") is >> limits.nodes;
129 else if (token == "movetime") is >> limits.movetime;
130 else if (token == "mate") is >> limits.mate;
131 else if (token == "infinite") limits.infinite = true;
132 else if (token == "ponder") limits.ponder = true;
135 Threads.start_thinking(pos, limits, SetupStates);
141 /// Wait for a command from the user, parse this text string as an UCI command,
142 /// and call the appropriate functions. Also intercepts EOF from stdin to ensure
143 /// that we exit gracefully if the GUI dies unexpectedly. In addition to the UCI
144 /// commands, the function also supports a few debug commands.
146 void UCI::loop(int argc, char* argv[]) {
148 Position pos(StartFEN, false, Threads.main()); // The root position
151 for (int i = 1; i < argc; ++i)
152 cmd += std::string(argv[i]) + " ";
155 if (argc == 1 && !getline(cin, cmd)) // Block here waiting for input
158 istringstream is(cmd);
160 is >> skipws >> token;
162 if (token == "quit" || token == "stop" || token == "ponderhit")
164 // The GUI sends 'ponderhit' to tell us to ponder on the same move the
165 // opponent has played. In case Signals.stopOnPonderhit is set we are
166 // waiting for 'ponderhit' to stop the search (for instance because we
167 // already ran out of time), otherwise we should continue searching but
168 // switch from pondering to normal search.
169 if (token != "ponderhit" || Search::Signals.stopOnPonderhit)
171 Search::Signals.stop = true;
172 Threads.main()->notify_one(); // Could be sleeping
175 Search::Limits.ponder = false;
177 else if (token == "perft")
183 ss << Options["Hash"] << " "
184 << Options["Threads"] << " " << depth << " current " << token;
188 else if (token == "key")
189 sync_cout << hex << uppercase << setfill('0')
190 << "position key: " << setw(16) << pos.key()
191 << "\nmaterial key: " << setw(16) << pos.material_key()
192 << "\npawn key: " << setw(16) << pos.pawn_key()
193 << dec << nouppercase << setfill(' ') << sync_endl;
195 else if (token == "uci")
196 sync_cout << "id name " << engine_info(true)
198 << "\nuciok" << sync_endl;
200 else if (token == "ucinewgame") TT.clear();
201 else if (token == "go") go(pos, is);
202 else if (token == "position") position(pos, is);
203 else if (token == "setoption") setoption(is);
204 else if (token == "flip") pos.flip();
205 else if (token == "bench") benchmark(pos, is);
206 else if (token == "d") sync_cout << pos.pretty() << sync_endl;
207 else if (token == "isready") sync_cout << "readyok" << sync_endl;
208 else if (token == "eval") sync_cout << Eval::trace(pos) << sync_endl;
210 sync_cout << "Unknown command: " << cmd << sync_endl;
212 } while (token != "quit" && argc == 1); // Passed args have one-shot behaviour
214 Threads.wait_for_think_finished(); // Cannot quit whilst the search is running
218 /// format_value() converts a Value to a string suitable for use with the UCI
219 /// protocol specifications:
221 /// cp <x> The score from the engine's point of view in centipawns.
222 /// mate <y> Mate in y moves, not plies. If the engine is getting mated
223 /// use negative values for y.
225 string UCI::format_value(Value v, Value alpha, Value beta) {
229 if (abs(v) < VALUE_MATE_IN_MAX_PLY)
230 ss << "cp " << v * 100 / PawnValueEg;
232 ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
234 ss << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
240 /// format_square() converts a Square to a string (g1, a7, etc.)
242 std::string UCI::format_square(Square s) {
244 char ch[] = { char('a' + file_of(s)),
245 char('1' + rank_of(s)), 0 }; // Zero-terminating
250 /// format_move() converts a Move to a string in coordinate notation
251 /// (g1f3, a7a8q, etc.). The only special case is castling moves, where we print
252 /// in the e1g1 notation in normal chess mode, and in e1h1 notation in chess960
253 /// mode. Internally castling moves are always encoded as "king captures rook".
255 string UCI::format_move(Move m, bool chess960) {
257 Square from = from_sq(m);
258 Square to = to_sq(m);
266 if (type_of(m) == CASTLING && !chess960)
267 to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
269 string move = format_square(from) + format_square(to);
271 if (type_of(m) == PROMOTION)
272 move += " pnbrqk"[promotion_type(m)];
278 /// to_move() takes a position and a string representing a move in
279 /// simple coordinate notation and returns an equivalent legal Move if any.
281 Move UCI::to_move(const Position& pos, string& str) {
283 if (str.length() == 5) // Junior could send promotion piece in uppercase
284 str[4] = char(tolower(str[4]));
286 for (MoveList<LEGAL> it(pos); *it; ++it)
287 if (str == format_move(*it, pos.is_chess960()))