Search code examples
c#unity-game-engineartificial-intelligenceuci

Using Stockfish Chess AI in Unity


Good Morning. I am trying to implement Stockfish to a Unity chess game, Ive been told that the best way is using Spawn.Process Does anyone know of existing code I can look at and take as reference?

Are different Gamestates the best way to communicate with AI?

Thanks!


Solution

  • If you can represent your game state in Forsyth-Edwards Notation and read Algebraic Notation to advance your board state, this should work:

    string GetBestMove(string forsythEdwardsNotationString){
        var p = new System.Diagnostics.Process();
        p.StartInfo.FileName = "stockfishExecutable";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.Start();  
        string setupString = "position fen "+forsythEdwardsNotationString;
        p.StandardInput.WriteLine(setupString);
        
        // Process for 5 seconds
        string processString = "go movetime 5000";
        
        // Process 20 deep
        // string processString = "go depth 20";
    
        p.StandardInput.WriteLine(processString);
        
        string bestMoveInAlgebraicNotation = p.StandardOutput.ReadLine();
    
        p.Close();
    
        return bestMoveInAlgebraicNotation;
    }