PHP code example of p-chess / api

1. Go to this page and download the library: Download p-chess/api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

p-chess / api example snippets


use PChess\Api\ChessApiClient;

// Create the client with your PSR-18/PSR-17 implementations
$client = new ChessApiClient(
    $httpClient,        // PSR-18 ClientInterface
    $requestFactory,    // PSR-17 RequestFactoryInterface
    $streamFactory,     // PSR-17 StreamFactoryInterface
);

// Get the best move for a position
$fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
$move = $client->getBestMove($fen);
// Returns: 'e4' (or similar)

// Restrict the engine to specific moves
$move = $client->getBestMove($fen, ['e2e4', 'd2d4', 'g1f3']);
// Returns one of the allowed moves

use PChess\Api\ChessApiException;

try {
    $move = $client->getBestMove($fen);
} catch (ChessApiException $e) {
    // Handle the error
    echo $e->getMessage();
}

use Nyholm\Psr7\Factory\Psr17Factory;
use PChess\Api\ChessApiClient;
use Symfony\Component\HttpClient\Psr18Client;

$factory = new Psr17Factory();
$httpClient = new Psr18Client();

$chessClient = new ChessApiClient($httpClient, $factory, $factory);

$fen = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1';
$move = $chessClient->getBestMove($fen);

echo "Best move: $move\n";

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use PChess\Api\ChessApiClient;

$httpClient = new Client();
$factory = new HttpFactory();

$chessClient = new ChessApiClient($httpClient, $factory, $factory);

$fen = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1';
$move = $chessClient->getBestMove($fen);

echo "Best move: $move\n";