Search code examples
c++ioexestandardschess

Connect Chess Engine with C++ GUI Program


I want to connect my C++ Program with a Chess Engine in order to have AI for the enemy. In my c++ program-->User will make a move(eg. A2A3)-->I will pass this string to chess engine-->engine will update board-->engine will start A.I for calculating enemy move-->Engine will give enemy's move as string(e.g A7A6) to my C++ program-->etc

I read that in order for my program to interact with a chess engine I have to start the chess_engine.exe file and exchange commands with it via the Standard Input/Output.

Can you tell me how exactly can my Visual Studio program code start a exe file and exchange commands with it?? Any example?

Thank you in advance.


Solution

  • A common misconception is that your engine needs to start separately and connect itself to the GUI. Instead, the GUI itself will open your engine and run it as a child process. The GUI will communicate with your engine using std_in and std_out. In C++, this is as simple as using cin and cout. From your engine, anything that is streamed into cout will be sent to the GUI and any thing streamed from cin will be received from the GUI. In a way, the chess GUI takes the place of your terminal.

    According to the UCI specification the first message the GUI sends to the engine is "uci" telling the engine to switch to uci mode. From your engines perspective your code could look something like this.

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string msg;
        getline(cin, msg);    // Read message from GUI
        
        // Does the GUI want use to switch to UCI mode?
        if (msg == "uci") {
            // Yes, switch to UCI move
            
            // Send some engine info to GUI
            cout << "id name MyEnginesName" << endl
                 << "id author MyName" << endl;  // The endls are very important
            
            // --- GUI will now send some settings to our engine ---
    
            // Read option settings from GUI
            while (getline(cin, msg)) {
                if (msg == "uciok") {
                    break; // Last option has been received
                }
                else {
                    // Parse msg and store option settings
                    // ...
                }      
            }
    
            // Bunch more code here   
        }
        
        cout << "Press any key...";
        cin.get();
        return 0;
    }
    

    A great way to learn the UCI protocol is to practice it yourself on the command line. Download a UCI compatible chess engine like lc0 or stockfish. Open a terminal and cd into the engines directory. Run the engine application on the command line and start typing UCI commands as if you were the GUI.