I have this code which returns the best move using Stockfish Engine. I provide it with a skill level for the engine and the fen string of the position and it should return the best move.
<?php
namespace App;
use SymfonyComponentProcessProcess;
class StockfishService
{
public function getBestMove(int $skillLevel, string $fen): string
{
$output = $this->runCommand("ucinucinewgamenposition startpos moves 10000nsetoption name Skill Level value $skillLevelnposition fen $fenngo movetime 10000n");
$bestMove = $this->extractBestMove($output);
return $bestMove;
}
private function runCommand(string $command): string
{
$process = new Process(['stockfish']);
$process->setInput($command);
$process->start();
$process->wait();
if (!$process->isSuccessful()) {
throw new RuntimeException($process->getErrorOutput());
}
return $process->getIncrementalOutput();
}
private function extractBestMove(string $output): string
{
$lines = explode("n", $output);
foreach ($lines as $line) {
if (strpos($line, 'bestmove') !== false) {
$parts = explode(' ', $line);
return $parts[1]; // Assuming bestmove is the second part
}
}
throw new RuntimeException('Best move not found in engine output');
}
}
But whenever this code gets exectued it returns basically one of the worst moves in the position no matter the skill level. For example for fen position rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQqk e3 1 1(White pawn to e3) it returns a7a6 which is a bad move. I figured out that the problem is that process ends too soon so I added movetime 10000 after the go command but this didn’t solve anything. Any ideas on how can I fix this?
The only thing I tried is to use $process->start()
and $process->wait()
instead of $process->run()