-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStockfishConnector.cpp
78 lines (70 loc) · 1.96 KB
/
StockfishConnector.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
#include "StockfishConnector.hpp"
#include <iostream>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <array>
#ifdef _WIN32
#include <windows.h>
#endif
namespace {
FILE* stockfishProcess = nullptr;
std::string executeCommand(const std::string& command) {
std::array<char, 128> buffer;
std::string result;
#ifdef _WIN32
if (stockfishProcess) {
fprintf(stockfishProcess, "%s\n", command.c_str());
fflush(stockfishProcess);
while (fgets(buffer.data(), buffer.size(), stockfishProcess) != nullptr) {
result += buffer.data();
if (result.find("bestmove") != std::string::npos) {
break;
}
}
}
#else
// Implementation for Unix-based systems
#endif
return result;
}
}
bool initializeStockfish() {
#ifdef _WIN32
stockfishProcess = _popen("stockfish.exe", "w+");
if (!stockfishProcess) {
std::cerr << "Failed to start Stockfish!" << std::endl;
return false;
}
executeCommand("uci");
return true;
#else
// Implementation for Unix-based systems
#endif
}
std::string getBestMove(const std::string& position) {
if (!stockfishProcess) {
std::cerr << "Stockfish is not initialized!" << std::endl;
return "";
}
executeCommand("position fen " + position);
executeCommand("go depth 10");
std::string output = executeCommand("");
size_t pos = output.find("bestmove");
if (pos != std::string::npos) {
return output.substr(pos + 9, 4); // Extract move in UCI format
}
return "";
}
void closeStockfish() {
if (stockfishProcess) {
#ifdef _WIN32
fprintf(stockfishProcess, "quit\n");
fflush(stockfishProcess);
_pclose(stockfishProcess);
stockfishProcess = nullptr;
#else
// Implementation for Unix-based systems
#endif
}
}