-
Notifications
You must be signed in to change notification settings - Fork 2
/
analyse.cpp
919 lines (854 loc) · 28.4 KB
/
analyse.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
/*
* This file is part of uci-analyser: a UCI-based Chess Game Analyser
* Copyright (C) 2013-2017 David J. Barnes
*
* uci-analyser is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* uci-analyser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with uci-analyser. If not, see <http://www.gnu.org/licenses/>.
*
* David J. Barnes may be contacted as [email protected]
* https://www.cs.kent.ac.uk/people/staff/djb/
*/
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <errno.h>
#include <stdlib.h>
#include "string.h"
#include "engine.h"
#include "evaluation.h"
#include "utils.h"
using namespace std;
/* Starting point for the analyser, and main processing point.
* A UCI-compatible engine is started and configured, then games
* read from the file or stdin source are fed, one by one to it.
* The resulting analysis is wrapped in XML.
*/
static const char *VERSION = "2017.04.07";
// The length of algebraic moves expected by a UCI engine.
#define ALGEBRAIC_MOVELEN 4
void extractInfo(string& info, vector<string> infoTokens, int searchDepth);
bool readGame(istream &movestream, vector<string> &movelist,
string& fenstring, int& bookDepth);
void sendGame(vector<string> &movelist, const string& fenstring, int bookDepth);
void tokenise(string &text, vector<string> &tokens);
void clearEvaluations(void);
void escapeForXML(string& str, const string& pattern, const string& escape_str);
void obtainEvaluations(void);
bool processMovesFile(const string& movesFile);
bool processStdin(void);
bool runEngine(vector<string> files);
void outputTag(const string& tagLine);
void saveEvaluation(Evaluation *ev, const string& info);
bool haveEvaluationForMove(const string &move);
bool showEvaluationsForMove(const string &move, bool white);
bool annotateMove(const string &playedMove);
void showUsage(const char *programName);
bool isResult(const string& move);
bool worse_move(const Evaluation *move, const Evaluation *best);
// Evaluations of the current move.
static vector<Evaluation *> evaluations;
// Defaults that are settable by arguments.
static int defaultBookDepth = 8;
static unsigned numVariations = 5;
static int searchDepth = 20;
// Default analysis engine.
static string engineName = "stockfish";
static map<string, string> engineOptions;
// Which colours we wish to analyse.
static bool analyseWhite = true;
static bool analyseBlack = true;
// A pseudo PGN tag giving the depth, in plies, of
// previous known play at the point this game was played.
// These moves are omitted from the analysis.
static string BOOK_DEPTH_TAG = "BookDepth";
// Games setup from a FEN description can be analysed.
static string FEN_TAG = "FEN";
// Whether to output the game with annotations.
static bool annotate = false;
// Whether the output is XML.
static bool XMLformat = true;
// The evaluation engine.
static Engine *engine;
#ifdef __unix__
int main(int argc, char *argv[]) {
#else
int main(int argc, char *argv[]) {
#endif
bool ok = true;
int argnum = 1;
// Process --arguments.
for (; argnum < argc && strncmp(argv[argnum], "--", 2) == 0;) {
string arg(argv[argnum]);
argnum++;
if (arg == "--annotate") {
annotate = true;
} else if (arg == "--annotatePGN") {
annotate = true;
XMLformat = false;
} else if (arg == "--blackonly") {
if (analyseBlack) {
analyseWhite = false;
analyseBlack = true;
} else {
cerr << arg << " << conflicts with --whiteonly" << endl;
ok = false;
}
} else if (arg == "--bookdepth") {
if (argnum < argc) {
string depth(argv[argnum]);
argnum++;
defaultBookDepth = strToInt(depth);
} else {
cerr << "Missing value argument to " << arg << endl;
ok = false;
}
} else if (arg == "--searchdepth") {
if (argnum < argc) {
string depth(argv[argnum]);
argnum++;
searchDepth = strToInt(depth);
} else {
cerr << "Missing value argument to " << arg << endl;
ok = false;
}
} else if (arg == "--engine") {
if (argnum < argc) {
engineName = argv[argnum];
argnum++;
} else {
cerr << "Missing engine name argument to " << arg << endl;
ok = false;
}
} else if (arg == "--help") {
showUsage(argv[0]);
} else if (arg == "--setoption") {
if (argnum + 1 < argc) {
string name(argv[argnum]);
string value(argv[argnum + 1]);
argnum += 2;
engineOptions[name] = value;
} else {
cerr << "Missing name and/or value argument to " << arg << endl;
ok = false;
}
} else if (arg == "--variations") {
if (argnum < argc) {
string vars(argv[argnum]);
argnum++;
numVariations = strToInt(vars);
} else {
cerr << "Missing value argument to " << arg << endl;
ok = false;
}
} else if (arg == "--version") {
cout << "Version: " << VERSION << endl;
} else if (arg == "--whiteonly") {
if (analyseWhite) {
analyseWhite = true;
analyseBlack = false;
} else {
cerr << arg << " << conflicts with --blackonly" << endl;
ok = false;
}
} else {
cerr << "Unknown argument: " << arg << endl;
ok = false;
}
}
if (ok) {
vector<string> files;
for (; argnum < argc; argnum++) {
files.push_back(argv[argnum]);
}
ok = runEngine(files);
return ok ? 0 : -1;
} else {
showUsage(argv[0]);
return -2;
}
}
void showUsage(const char *programName) {
cerr << "Usage: " << programName << "\n" <<
" [--annotate]\n" <<
" output the games with evaluation annotations\n" <<
" [--annotatePGN]\n" <<
" output the game with evaluation annotations in PGN format\n" <<
" [--blackonly]\n" <<
" only analyse black's moves\n" <<
" [--bookdepth depth]\n" <<
" depth in ply to skip at start of game\n" <<
" [--searchdepth depth]\n" <<
" search depth in ply\n" <<
" [--engine program]\n" <<
" program to use as the UCI engine\n" <<
" [--help]\n" <<
" show this usage message\n" <<
" [--setoption optionName optionValue]\n " <<
" set a UCI option\n" <<
" [--variations vars]\n" <<
" number of variations to analyse per move\n" <<
" [--version]\n" <<
" show the current version\n" <<
" [--whiteonly]\n" <<
" only analyse white's moves\n" <<
" file [...]\n" <<
" file(s) to be analysed." <<
endl;
exit(-2);
}
/*
* Run the engine on the given files.
* Return true if everything was ok.
*/
bool runEngine(vector<string> files) {
bool ok = true;
try {
engine = new Engine(engineName);
if (engine->initEngine(numVariations, searchDepth, engineOptions)) {
if (XMLformat) {
cout << "<gamelist>" << endl;
}
if (files.size() > 0) {
// Process each file of moves.
for (unsigned i = 0; i < files.size(); i++) {
const string& movesFile = files[i];
if (!annotate) {
cout << "<!-- Processing " << movesFile << "-->" << endl;
}
if (!processMovesFile(movesFile)) {
cerr << "Failed to process " << movesFile << endl;
ok = false;
}
clearEvaluations();
}
} else {
if (!processStdin()) {
ok = false;
}
clearEvaluations();
}
} else {
cerr << "Failed to initialise the chess engine." << endl;
ok = false;
}
if (XMLformat) {
cout << "</gamelist>" << endl;
}
engine->quitEngine();
delete engine;
engine = NULL;
} catch (int e) {
cerr << "Failed to start " << engineName << endl;
ok = false;
}
return ok;
}
/*
* Process the long-algebraic moves in movesFile.
*/
bool processMovesFile(const string& movesFile) {
ifstream movestream(movesFile.c_str());
if (movestream.is_open()) {
vector<string> moves;
string fenstring;
int bookDepth;
while (readGame(movestream, moves, fenstring, bookDepth)) {
sendGame(moves, fenstring, bookDepth);
}
movestream.close();
return true;
} else {
cerr << "Unable to open " << movesFile << endl;
return false;
}
}
/*
* Process the long-algebraic moves on stdin
*/
bool processStdin(void) {
vector<string> moves;
string fenstring;
int bookDepth;
while (readGame(cin, moves, fenstring, bookDepth)) {
sendGame(moves, fenstring, bookDepth);
}
return true;
}
/* Extract the string between quotes as the value of a tag. */
static string extractTagValue(const string& line) {
unsigned first_quote = line.find_first_of("\"");
if (first_quote != string::npos) {
unsigned second_quote = line.find_first_of("\"", first_quote + 1);
if (second_quote != string::npos) {
return string(line.substr(first_quote + 1, second_quote - first_quote - 1).c_str());
} else {
cerr << "Missing second quote in " << line << endl;
return "";
}
} else {
cerr << "Missing first quote in " << line << endl;
return "";
}
}
/*
* Read moves for one game from movestream and store them in the moves vector.
* Set any FEN tag value and book depth.
* The end of a game is marked by a zero-length line or the end of file.
* Return true on success; false otherwise.
*/
bool readGame(istream &movestream, vector<string> &movelist,
string& fenstring, int& bookDepth) {
string line;
bool endOfGame = false;
movelist.clear();
fenstring = "";
bookDepth = defaultBookDepth;
// Skip to the tags (if any).
while (movestream.good() && getline(movestream, line) &&
(line.size() == 0 || line[0] != '[')) {
if (line.size() > 0) {
cerr << "Unknown text before game: " << line << endl;
}
}
if (!movestream.good() || line.size() == 0 || line[0] != '[') {
return false;
}
if (XMLformat) {
cout << "<game>" << endl;
cout << "<tags>" << endl;
}
while (line.size() > 0 && line[0] == '[' && !endOfGame) {
if (line.find(BOOK_DEPTH_TAG) != string::npos) {
// Set the bookdepth from this tag.
string tag_value = extractTagValue(line);
if (tag_value.length() > 0) {
int depth = atoi(tag_value.c_str());
// Sanity check.
if (depth >= 0 && depth < 100) {
bookDepth = depth;
} else {
cerr << "Unrealistic book depth: " << depth << endl;
}
}
} else if (line.find(FEN_TAG) != string::npos) {
fenstring = extractTagValue(line);
}
// Output tags.
outputTag(line);
if (!movestream.good() || !getline(movestream, line)) {
endOfGame = true;
}
}
if (XMLformat) {
cout << "</tags>" << endl;
}
if (!annotate) {
cout << "<moves>" << endl;
}
while (movestream.good() && !endOfGame) {
if (!annotate && line.size() > 0) {
cout << line << endl;
}
if (line.size() > 0) {
stringstream moves(line);
string move;
while (moves >> move) {
// Drop any suffixes, such as + and #
// but retain promotions.
if (isResult(move)) {
movelist.push_back(move);
endOfGame = true;
} else {
if (move.length() > ALGEBRAIC_MOVELEN) {
char ch = move[ALGEBRAIC_MOVELEN];
if (ch == '+' || ch == '#') {
move.resize(ALGEBRAIC_MOVELEN);
} else {
// Enforce lowercase.
ch = tolower(ch);
move[ALGEBRAIC_MOVELEN] = ch;
move.resize(ALGEBRAIC_MOVELEN + 1);
}
}
movelist.push_back(move);
}
}
} else {
// Blank line.
}
if (!movestream.good() || !getline(movestream, line)) {
endOfGame = true;
}
}
if (!annotate) {
cout << "</moves>" << endl;
} else {
cout << endl;
}
return movelist.size() > 0;
}
/*
* Send the moves of a game, one by one, to the engine.
*/
void sendGame(vector<string> &movelist, const string& fenstring, int bookDepth) {
// Don't include the result.
int numMoves = movelist.size() - 1;
// The string of moves that is gradually built up.
string moves = "";
// Might be set from the FEN string.
bool white;
// Index into moves from the list.
int moveCount = 0;
int movesToSkip = 0;
// Beware of very short games.
if (bookDepth > numMoves) {
movesToSkip = numMoves;
} else {
movesToSkip = bookDepth;
}
bool okToAnalyse = true;
if (fenstring.length() > 0) {
// bookDepth does not really apply if a non-starting-position
// FEN string has been included.
// NB: Strictly speaking, we should look at the move number of
// the FEN string and adjust book depth appropriately if the
// starting position is still considered to be within book,
// but this is complex to do and would apply in very few cases.
// So be pragmatic.
movesToSkip = 0;
if (fenstring.find(" b ") != string::npos) {
white = false;
} else if (fenstring.find(" w ") != string::npos) {
white = true;
} else {
cerr << "Failed to find who is to move in " << fenstring << endl;
cerr << "Skipping the game." << endl;
okToAnalyse = false;
}
} else {
white = true;
}
if (okToAnalyse) {
if (annotate) {
if (XMLformat) {
cout << "<annotation>" << endl;
}
} else {
cout << "<analysis " <<
"engine = \"" << engine->getIdentity() << "\" " <<
"bookDepth = \"" << bookDepth << "\" " <<
"searchDepth = \"" << searchDepth << "\" " <<
"variations = \"" << numVariations << "\" " <<
">" << endl;
}
engine->startNewGame();
// Skip over the portion considered to be book.
while (moveCount < movesToSkip) {
if (annotate) {
cout << movelist[moveCount] << " ";
}
moves.append(movelist[moveCount]);
moves.append(" ");
moveCount++;
white = !white;
}
for (; moveCount < numMoves; moveCount++) {
const string& playedMove = movelist[moveCount];
// Only analyse a move for a particular colour if required.
if ((white && analyseWhite) || (!white && analyseBlack)) {
// Ask the engine to analyse the current position.
engine->setPosition(moves, fenstring);
engine->go();
// Start with a fresh set of evaluations.
clearEvaluations();
obtainEvaluations();
// Make sure we have an analysis for the played move.
if (!haveEvaluationForMove(playedMove)) {
// The played move wasn't analysed, so force it to be.
engine->setPosition(moves, fenstring);
engine->searchMoves(playedMove);
// Add it to the current ones.
obtainEvaluations();
}
bool playedMoveEvaluated;
if (annotate) {
playedMoveEvaluated = annotateMove(playedMove);
} else {
playedMoveEvaluated = showEvaluationsForMove(playedMove, white);
}
if (!playedMoveEvaluated) {
cerr << "Internal error: " << playedMove <<
" was not evaluated." << endl;
}
}
moves.append(playedMove);
moves.append(" ");
white = !white;
}
if (annotate) {
// Output the result.
cout << movelist[movelist.size() - 1] << endl;
if (XMLformat) {
cout << "</annotation>" << endl;
}
} else {
cout << "</analysis>" << endl;
}
}
if (XMLformat) {
cout << "</game>" << endl;
} else {
cout << endl;
}
}
/*
* Extract the information from an info line returned
* by the engine.
*/
void extractInfo(string &info, vector<string> infoTokens, int searchDepth) {
ASSERT_IS("info", infoTokens[0]);
if (info.find("multipv ") != string::npos) {
int numTokens = infoTokens.size();
int t = 1;
while (t < numTokens && infoTokens[t] != "depth") {
t++;
}
if (t < numTokens) {
int depth = strToInt(infoTokens[t + 1]);
if (depth == searchDepth) {
Evaluation *ev = new Evaluation(infoTokens, info);
saveEvaluation(ev, info);
}
}
}
}
/*
* Do we have an evaluation for the played move?
*/
bool haveEvaluationForMove(const string &move) {
for (vector<Evaluation *>::iterator it = evaluations.begin();
it != evaluations.end(); it++) {
const Evaluation *ev = *it;
if (ev->getFirstMove() == move) {
return true;
}
}
return false;
}
/*
* Show the evaluations for the position before the
* given played move.
* Return whether the played move was evaluated.
*/
bool showEvaluationsForMove(const string &playedMove, bool white) {
cout << "<move player = " <<
'"' << (white ? "white" : "black") << '"' <<
" >" << endl;
cout << "<played";
// cout << " time = " << '"' << evaluations[0]->getTime() << '"' ;
cout << '>';
cout << playedMove << "</played>" << endl;
// Whether the playedMove was one of those evaluated.
bool playedMoveEvaluated = false;
for (vector<Evaluation *>::iterator it = evaluations.begin();
it != evaluations.end(); it++) {
const Evaluation *ev = *it;
string firstMove = ev->getFirstMove();
if (ev != NULL) {
if (!annotate) {
cout << "<evaluation move = " << '"' << firstMove << '"';
cout << " value = " << '"';
if (ev->isForcedMate()) {
cout << "mate " << ev->getNumMateMoves();
} else {
cout << ev->getValue();
if (ev->isLowerBound()) {
cout << " L";
} else if (ev->isUpperBound()) {
cout << " U";
}
}
cout << "\" />";
cout << endl;
}
if (firstMove == playedMove) {
playedMoveEvaluated = true;
}
}
}
cout << "</move>" << endl;
return playedMoveEvaluated;
}
/*
* Show the evaluation for the played move and the best alternative.
* Return whether the played move was evaluated.
*/
bool annotateMove(const string &playedMove) {
vector<Evaluation *>::iterator it = evaluations.begin();
while (it != evaluations.end() && (*it)->getFirstMove() != playedMove) {
it++;
}
if (it != evaluations.end()) {
const Evaluation *ev = *it;
cout << playedMove << " ";
cout << "{ ";
if (ev->isForcedMate()) {
cout << "mate " << ev->getNumMateMoves();
} else {
cout << ev->getValue();
}
cout << " } ";
// Print out the better alternative moves and their evaluations.
it = evaluations.begin();
Evaluation *best = *it;
do {
ev = *it;
if (ev->getFirstMove() != playedMove) {
cout << "( " << ev->getFirstMove() << " { ";
if (ev->isForcedMate()) {
cout << "mate " << ev->getNumMateMoves();
} else {
cout << ev->getValue();
}
cout << " }) ";
}
it++;
} while (it != evaluations.end() && !worse_move(*it, best));
cout << endl;
return true;
} else {
cout << endl;
return false;
}
}
/* return true if move is worse than best */
bool worse_move(const Evaluation *move, const Evaluation *best)
{
if(best->isForcedMate()) {
if(move->isForcedMate()) {
return move->getNumMateMoves() > best->getNumMateMoves();
}
else {
if(best->getNumMateMoves() < 0) {
// Any non-mating move is better.
return false;
}
else {
// Forcing better than non-forcing.
return true;
}
}
}
else if(move->isForcedMate()) {
if(move->getNumMateMoves() < 0) {
// Avoid the forced mate.
return true;
}
else {
// Prefer the forced mate.
return false;
}
}
else {
return move->getValue() < best->getValue();
}
}
/**
* Output the name and value of a tag.
* Ensure that special characters are escaped to fit with
* XML.
*/
void outputTag(const string& tagLine) {
// The tag name.
int first_quote = tagLine.find_first_of("\"");
int last_quote = tagLine.find_last_of("\"");
if (XMLformat) {
cout << "<tag name = \"";
} else {
cout << "[";
}
cout << tagLine.substr(1, first_quote - 2);
if (XMLformat) {
cout << "\"";
}
// The value.
if (XMLformat) {
cout << " value = ";
} else {
cout << " ";
}
string value = tagLine.substr(first_quote + 1, last_quote - first_quote - 1);
escapeForXML(value, "&", "&");
// Escape any quote characters.
string escaped_quote("\\\"");
size_t qindex = value.find_first_of(escaped_quote);
while (qindex != string::npos) {
value.replace(qindex, 2, """);
qindex = value.find_first_of(escaped_quote);
}
cout << "\"" << value << "\"";
if (XMLformat) {
cout << " />" << endl;
} else {
cout << "]" << endl;
}
}
/*
* Escape occurrences of pattern in str with escape_str.
*/
void escapeForXML(string& str, const string& pattern, const string& escape_str) {
size_t pattern_length = pattern.length();
size_t escape_str_length = escape_str.length();
size_t qindex = str.find_first_of(pattern);
while (qindex != string::npos) {
str.replace(qindex, pattern_length, escape_str);
qindex = str.find_first_of(pattern, qindex + escape_str_length);
}
}
/*
* Store the given evaluation in the evaluations array.
*/
void saveEvaluation(Evaluation *ev, const string& info) {
bool inserted = false;
vector<Evaluation *>::iterator it = evaluations.begin();
// Look for an existing occurrence.
const string& move = ev->getFirstMove();
while (it != evaluations.end() && (*it)->getFirstMove() != move) {
it++;
}
if (it != evaluations.end()) {
// Delete the previous one.
evaluations.erase(it);
}
// Insert in decreasing order.
it = evaluations.begin();
while (!inserted && it != evaluations.end()) {
Evaluation *current = *it;
// Mating moves require special treatment.
// Can't just compare scores.
if (ev->isForcedMate() || current->isForcedMate()) {
bool insert_here = false;
if (ev->isForcedMate()) {
if (current->isForcedMate()) {
// Both forced mate.
bool ev_wins = ev->getNumMateMoves() >= 0;
bool current_wins = current->getNumMateMoves() >= 0;
if (ev_wins == current_wins) {
// Both either win or lose.
// Prefer shortest win or slowest loss.
insert_here = ev->getNumMateMoves() <=
current->getNumMateMoves();
} else {
if (ev_wins) {
insert_here = true;
} else {
// Prefer the current win.
}
}
} else {
// ev is forced but current is not.
if (ev->getNumMateMoves() >= 0) {
// Forced win.
insert_here = true;
} else {
// Forced loss.
}
}
} else {
// current is mate but ev is not.
if (current->getNumMateMoves() < 0) {
// current is a forced loss, so prefer ev.
insert_here = true;
} else {
// current is a forced win.
}
}
if (insert_here) {
evaluations.insert(it, ev);
inserted = true;
}
} else if (ev->getValue() > current->getValue()) {
evaluations.insert(it, ev);
inserted = true;
} else {
// No insertion here.
}
if (!inserted) {
it++;
}
}
if (!inserted) {
evaluations.push_back(ev);
}
}
/*
* Obtain the evaluations from the engine.
* Fill out the evaluations array.
*/
void obtainEvaluations(void) {
string reply;
vector<string> tokens;
bool bestMoveFound = false;
bool eof = false;
do {
reply = engine->getResponse(eof);
if (!eof) {
// Break up the reply.
tokens.clear();
tokenise(reply, tokens);
if (tokens.size() > 0) {
string tokenType = tokens[0];
if (tokenType == "info") {
extractInfo(reply, tokens, searchDepth);
} else if (tokenType == "bestmove") {
bestMoveFound = true;
}
}
}
} while (!bestMoveFound && !eof);
}
/*
* Clear the evaluations array.
*/
void clearEvaluations(void) {
for (vector<Evaluation *>::iterator it = evaluations.begin();
it != evaluations.end(); it++) {
Evaluation *eval = *it;
if (eval != NULL) {
delete eval;
}
}
evaluations.clear();
}
/*
* Tokenise text into tokens.
* tokens is not cleared by this function.
*/
void tokenise(string &text, vector<string> &tokens) {
stringstream ss(text);
string token;
while (getline(ss, token, ' ')) {
if (token != "") {
tokens.push_back(token);
}
}
}
bool isResult(const string& move) {
return move == "1-0" ||
move == "0-1" ||
move == "1/2-1/2" ||
move == "*";
}